From 5196d137636f3db187106d7c4c9ddbe5c61a4435 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 30 Sep 2026 16:47:06 +0800 Subject: [PATCH 01/49] docs: propose memoized nested field offsets and concurrent definition printing RuntimeViewer builds a search corpus by printing every type of an image, and a sample of that build spent 61% of a Swift type's print in the in-process nested field-offset expansion and 9% of it scanning a stripped symbol table for anonymous-context discriminators, neither of them cached. - draft-nested-field-offset-memoization: cache one level of the expansion per metatype (field name, type name, relative offset, child metatype, isLast) and leave the walk itself untouched, so the output stays byte-identical by construction; memoize the discriminator per descriptor address. - draft-concurrent-definition-printing: definitions index lazily behind an unlocked check-then-set and the printer writes their attributes on every print, so two tasks printing the same image race. RuntimeViewer already does that today. Index once behind a lock with synchronous index bodies, and pass the inferred attributes as a local instead of storing them. Both drafts went through two independent review rounds; their decision logs record what each round changed. Neither is accepted yet. --- Documentations/Evolutions/README.md | 2 + .../draft-concurrent-definition-printing.md | 67 ++++++++++++++ .../draft-nested-field-offset-memoization.md | 87 +++++++++++++++++++ Documentations/README.md | 2 + 4 files changed, 158 insertions(+) create mode 100644 Documentations/Evolutions/draft-concurrent-definition-printing.md create mode 100644 Documentations/Evolutions/draft-nested-field-offset-memoization.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index fa5f9959d..afd6cc2fb 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -65,5 +65,7 @@ | [0054](0054-interface-descriptor-only-vtable-members.md) | interface 按 vtable 槽位顺序打印类成员,补上只剩 method descriptor 符号的成员 | Implemented | | [0055](0055-group-sources-by-layer.md) | `Sources/` 按层分组 | Implemented | | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | +| draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | Draft | +| draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | Draft | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/draft-concurrent-definition-printing.md new file mode 100644 index 000000000..951881df2 --- /dev/null +++ b/Documentations/Evolutions/draft-concurrent-definition-printing.md @@ -0,0 +1,67 @@ +# Draft - 定义对象的并发打印安全:索引前置,打印期不再写定义 + +- **状态**: Draft +- **创建日期**: 2026-09-30 +- **最后更新**: 2026-09-30 +- **所属愿景**: 无 +- **关联提案**: [0019-large-stack-executor-and-cross-version-parallelism](0019-large-stack-executor-and-cross-version-parallelism.md)(跨版本并行; + 同版本内并行当时明确不做)、[0002-declaration-model-descriptor-slimming](0002-declaration-model-descriptor-slimming.md)(定义对象的惰性索引形态与物化纪律) +- **实现分支 / PR**: `feature/runtime-viewer/find-navigator` +- **配套文档**: [Internal/Modules/SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)(`isIndexed` 的说明随本提案更新) + +## 摘要 + +`SwiftDeclarationPrinter` 本身是 `Sendable`(可变状态全在 `@Mutex` 后面),但它打印的 `TypeDefinition` / +`ProtocolDefinition` / `ExtensionDefinition` 不是:三者在打印时才惰性 `index(in:)`,守卫是无锁的 check-then-set; +`printIncludedTypeDefinition` 与 diff 渲染的 `printTypeHeader` 每次打印都写 `typeDefinition.attributes`;父类型打印会顺带 +打印嵌套子类型、协议打印默认实现扩展、扩展打印其中的类型与协议。AGENTS.md 因此写明「intra-version parallelism is not safe」。 + +**这个竞争今天已经在发生,不只是并行打印的前提。** RuntimeViewer 的 `RuntimeSwiftSection` 是 actor,显示路径 +`interface(for:)` 与语料路径 `corpusEntry` 都经 `printInterface` `await` 到 printer 的 nonisolated 入口;本库没有启用 +`NonisolatedNonsendingByDefault`,所以打印期间 actor 被释放,两条打印在不同线程上真并行,且共享同一批定义。语料在后台一建 +就是几分钟,期间用户点开同一镜像的类型(或父类型在语料里内联打印嵌套子类型时用户正好点开它),两边同时对同一个定义 +`index(in:)`、同时写数组与 `attributes`——数据竞争,可到堆损坏级别。`next` 上 MCP、导出、多文档共用 `.local` 引擎走的是 +同一条路径,只是时间窗小。本提案把它修掉,并以此解除 `MachOImage`(进程内)读者下同版本内并发打印的限制; +`MachOFile` 共用一个 `FileHandle` 的问题不在本提案。 + +## 方案 + +- **索引一次、并发等待,同步阻塞形态**:三个 `index(in:)` 的函数体今天一个 `await` 都没有,改成**同步函数**(去掉 `async`), + 让「索引体内没有挂起点」由编译器保证;`isIndexed` 改为受锁保护的三态(未索引 / 索引中 / 已索引)加一个带错误通道的 + promise(形态照 `SharedCacheBuildPromise`,含同线程重入的 `precondition`)。锁是**进程级一把**加一张按 `ObjectIdentifier(定义)` + 的 in-flight 表,临界区只翻状态与取 promise,不给每个定义各挂一个 `Mutex`(0002 刚给定义瘦过身,每个定义一次堆分配不值)。 + 首个调用者认领后在自己的线程里跑索引体(它已带大栈执行器偏好),后来者在 promise 上阻塞等待。不死锁的不变量: + 认领 → 索引体 → fulfill 之间没有挂起点(编译器保证),索引体不索引别的定义(今天成立:体内只经 `SharedCache` 取 catalog + 或符号表;用 precondition 守住)。抛错时状态回到未索引、错误广播给全部等待者,下次调用重试(`ExtensionDefinition+Indexing` + 今天就依赖这条重试语义)。不选异步等待(continuation):它不占线程,但要多一套能携带错误的 promise,而同步形态的前提今天全部成立。 +- **打印期不写定义**:`attributes` 按 AGENTS.md 的物化纪律改为**局部变量**——两个打印点各算一次 + `let attributes = TypeAttributeInferrer().infer(for: typeDefinition)` 往下传,删掉存储属性。不做计算属性:纪律明写 + 「Never a per-access computed property」,且 `TypeAttributeInferrer` 在 `SwiftAttributeInference`,该模块依赖 `SwiftDeclaration`, + `TypeDefinition` 自己调不到它。输出不变(今天也是每次打印、在索引之后重算;它读的 `conformingProtocolNames` 由 + `SwiftDeclarationIndexer.prepare()` 填,不受影响)。两处写入点一起改:`SwiftDeclarationPrinter.printIncludedTypeDefinition` + 与 `SwiftDeclarationPrinter+DiffRendering.printTypeHeader`。源码兼容:`public package(set) var attributes` 的读面消失, + 仓库内无其它使用者;下游要的话在 `SwiftAttributeInference` 里留一个转发扩展。`TypeAttributeInferrer` 读 + `typeDefinition.extensions` 的三处是死读(该属性从未被赋值),删掉;顺带记下被它掩盖的缺口:声明在扩展里的 + `buildBlock` 今天识别不到 `@resultBuilder`。 +- **Sendable**:三个定义类标 `@unchecked Sendable`,理由写在类型上:「除索引状态外只在索引期间写、且索引受锁」。本库是 + Swift 6 模式,不标的话调用方在任务组里传不进去。 +- **打印路径的其余共享可变状态**:`Sources/Output` 全量核对,打印路径写定义的只有上述两处;`ParentClassVTableCache` 是 + 每次索引各一份的局部值类型;`SharedCache` 一族本来就线程安全;`SymbolicDemangler.isCacheEnabled` 只读无写入点,**不加锁** + (它在最热的入口上,加 `@Mutex` 等于给 8 路并行加一把全局锁),改 `static let`。打印路径之外的非原子写 + `specialize(...)` 追加 `_specializedChildren`,RuntimeViewer 里写与读都在 section actor 上;「同一 printer 可并发」的承诺不覆盖它, + 文档里写明。 +- **约定更新**:AGENTS.md 的那条改成「`MachOImage` 读者下,同一 printer 实例可被多个任务并发调用,包括同时打印同一个定义、 + 父类型与其嵌套子类型;`MachOFile` 读者仍不可」;`Internal/Modules/SwiftDeclaration.md` 关于 `isIndexed` 的说明同步。 + 不改 `SwiftDeclarationPrinter` 的公开 API,也不提供并行的入口——并行由调用方(RuntimeViewer 的语料 store)用任务组自己组织。 +- **验证**:压力测试用 SymbolTests fixture,覆盖三种情况——全部定义分给 N 个任务、**多个任务同时打印同一个定义**、 + **父类型与它的嵌套子类型同时打印**;**先在改动前跑出 TSan 红**,修后绿,输出与串行逐字节相等;套件按 AGENTS.md 声明 + `ExclusiveImageAccess`,TSan 结论记入决策日志;现有套件全过;渲染 A/B 按 AGENTS.md 必跑。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-09-30 | Created as Draft | 用户在 RuntimeViewer 的 Find 语料构建性能提问轮里选定「跳过嵌套重复 + 并行打印」;并行的前提是本库的定义对象能被并发打印。 | +| 2026-09-30 | 只解除 `MachOImage` 读者的限制 | `MachOFile` 的不安全来自共享 `FileHandle` 的 seek + read,是另一类问题;语料只在进程内构建。 | +| 2026-09-30 | 第一轮审查:「等待同一个 Task」改为首个调用者原地索引 + promise 等待,补抛错回退;补上 diff 渲染那处写入 | 非结构化 `Task {}` 不继承大栈执行器偏好、索引体本来没有 `await`;`SwiftDeclarationPrinter+DiffRendering.swift` 同样写 `attributes`。 | +| 2026-09-30 | 第二轮审查:`attributes` 改局部变量而非计算属性;等待形态定为同步阻塞并把 `index(in:)` 改成同步函数;锁改进程级一把 + in-flight 表;撤掉 `isCacheEnabled` 加锁;动机补上「竞争今天已在发生」、测试先红后绿;定义类标 `@unchecked Sendable` | 计算属性违反 AGENTS.md 物化纪律且依赖方向不通(inferrer 所在模块依赖 `SwiftDeclaration`);`SharedCacheBuildPromise` 是同步阻塞且无错误通道,两种等待形态要二选一并写出不变量;每定义一把 `Mutex` 是每定义一次堆分配;`isCacheEnabled` 无写入点,加锁只添争用;RuntimeViewer 的显示路径与语料路径今天已在 actor 外并行打印同一批定义。 | diff --git a/Documentations/Evolutions/draft-nested-field-offset-memoization.md b/Documentations/Evolutions/draft-nested-field-offset-memoization.md new file mode 100644 index 000000000..b2d9f7b25 --- /dev/null +++ b/Documentations/Evolutions/draft-nested-field-offset-memoization.md @@ -0,0 +1,87 @@ +# Draft - 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 + +- **状态**: Draft +- **创建日期**: 2026-09-30 +- **最后更新**: 2026-09-30 +- **所属愿景**: 无 +- **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(RuntimeViewer 的语料按标记模式打印,所以每个类型都要付 + `printExpandedFieldOffsets` 的全价)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(进程作用域存储的形态) +- **实现分支 / PR**: `feature/runtime-viewer/find-navigator` +- **配套文档**: [Internal/NestedFieldOffsetCycleGuard.md](../Internal/NestedFieldOffsetCycleGuard.md)、 + [Internal/TaskReports/2026-08-06-nested-field-offset-cycle-guard.md](../Internal/TaskReports/2026-08-06-nested-field-offset-cycle-guard.md)、 + [Internal/MachOCaches.md](../Internal/MachOCaches.md)(进程作用域 memo 的清单随本提案更新) + +## 摘要 + +RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印的进程采样:单个 Swift 类型的打印里 61% 落在 +`RuntimeFieldLayoutBackend.storedFieldComments → expandedFieldOffsets → walkNested*FieldOffsets`,其中 9% 落在 +`SymbolicDemangler.buildContextDescriptorMangling → InProcessContext.lookupSymbol(at:)`。前者对每个存储字段从运行时元数据 +重新递归展开嵌套 struct / enum 的布局(深到 16 层),同一个字段类型(`String`、`UInt64`、`Builtin.BridgeObject`……)在每个 +出现处都重算一遍,且故意绕开 demangle memo(`demangleTypeUncached`,每个 struct 字段节点通常 3 次 demangle);后者在共享缓存 +镜像上每查一个匿名上下文地址就逐个重建 dyld 镜像再线性扫镜像自己的 `LC_SYMTAB`(本地符号早已剥离,基本必落空),然后才 +回落到 `AnonymousContextPrivateDiscriminatorIndex`。两处都没有任何缓存。本提案按 metatype 记忆化「一层展开」的结果、 +遍历本身原样不动,给匿名上下文的判别符查询补一层按地址的记忆化。 + +## 方案 + +**1. 按 metatype 缓存单层展开记录,遍历不变。** + +- 不缓存整棵树、不做渲染期剪枝(第二轮审查否掉的形态:节点漏记 `isLast` 会改 `├──` / `└──`,子树是否跨根共享又决定 + 剪枝怎么写,两条路各有陷阱)。缓存的是 `walkNestedStructFieldOffsets` / `walkNestedEnumPayloadFieldOffsets` 对**一个 + metatype** 做的一层工作: + - 类别(struct / enum 或 optional / 其它); + - struct:每条字段 `(fieldName, typeName, relativeOffset, childMetatype?, isLast)`——`isLast` 照今天按 `fieldEntries.count` + 算(名字读失败的字段不出记录但照样计数),`childMetatype` 是 `resolveNestedMetatype` 的结果,nil 表示不下钻; + - enum:每条 payload `(fieldName, typeName, childMetatype, isLast, descends)`——只记解析成功的 payload(今天只给它们打行), + `isLast` 照今天按 `payloadRecords.count` 算,`descends = !isIndirectCase`。 + 遍历的结构、环判断(`enclosingMetatypes`)、深度判断、`#log` 告警全部原封不动,只是把每层的 descriptor / offsets / + records / `nestedTypeName` / `resolveNestedMetatype` 换成查表。字节一致是构造出来的,连告警条数都不变;建一条记录不递归, + 没有 in-flight 问题;内存按唯一 metatype 各一份。 +- 缓存形态照 0053 采纳的方案(不是它否掉的「`SharedCache` 常量键」):`private static let processScopedStorage = Storage()`, + `Storage` 内是 `@Mutex` 字典,键 `ObjectIdentifier(metatype)`——与 `SymbolicDemanglerCache` 的进程作用域 memo 同形。前提是 + 进程不卸载镜像(RuntimeViewer 没有任何 `dlclose`);进程内 metatype 全局唯一,泛型特化的元数据由运行时分配且不回收。 + 它不受按镜像的驱逐管理,大小由进程碰到的唯一 metatype 数决定。记录在锁外建,一次 `withLock` 里 check-and-insert, + 先存者赢(内容确定,浪费上限是并行宽度乘一次构建)。 +- **nil 的固化**:记录里 `childMetatype == nil`(struct 字段解析失败、enum payload 解析失败)会被缓存。定义那个类型的镜像 + 在首次展开之后才加载的话,今天的遍历会开始下钻 / 打出 payload 行,缓存版不会。提供 `removeAll()`,宿主在加载镜像后调一次 + (RuntimeViewer 在 `loadImage` 之后调;宿主自己 `dlopen` 的镜像覆盖不到,但被引用类型所在的镜像通常早已随链接加载, + 近乎理论,写明即可)。`removeAll()` 带代数计数:跨越它的构建只在代数没变时写回,避免把旧结果写回去。 +- `storedFieldComments` 里 `resolveFieldMetatype` 最多被调 3 次(末字段、type layout、展开入口),合并成一个局部变量; + 展开入口的 `?? getTypeByMangledNameInContext(mangledTypeName, in: machO)` 回退保留在入口——另两处没有这个回退,特化失败 + 但裸名能解出的字段不能因合并丢掉展开。这一跳每个顶层字段仍付一次,不在缓存里。 +- `expandedFieldOffsetTransformer` 不受影响:渲染仍逐行经它。RuntimeViewer 从不设置它。 + +**2. 匿名上下文判别符按地址记忆化。** + +- `InProcessContext.privateDiscriminatorIdentifier(forAnonymousContextAt:)` 的结果对已加载镜像是稳定的(来自持有该地址 + 的镜像自己的符号表或 `_symbolic` 索引):加一层进程级 `@Mutex` 字典(同一个 `processScopedStorage`),键是描述符地址, + 值是判别符文本或「无」;命中直接构造 `.identifier` 节点,不再进 `MachOImage.symbol(for:)` 与 `MachOImage.image(for:)`。 + 今天第一条路返回的是 `privateDeclName.children.first`,测试断言它总是 identifier。 +- 只覆盖 `InProcessContext` 这条路;`MachOContext` 走 `Symbol.resolve(from:in:)`,前面已有按镜像的 `demangleContext` memo。 + 进程级的 `nodeReferenceForContextOffset` 只覆盖 `demangleContext(for:)`,不覆盖 `demangleTypeUncached` 经 symbolic + reference 走到的 `buildContextDescriptorMangling`,所以这一刀是必要的。 +- 第 1 条落地后这一条仍有价值:`RuntimeTypeNameDemangling.node(forMetatype:)` 在遍历之外(bound generic 的名字渲染、 + `TypedDumper`)也走这条查找。 +- 不动 MachOKit:fork 政策把性能缓存全放在 MachOKitExtensions(其提案 0001 明确推迟了 `MachOImage` 的 cached view + 与 `closestSymbol` 拷贝),而这里的查找在共享缓存镜像上本来就查不到东西,排序索引救不了它。 + +**3. 验证与文档。** + +- 现有:`RecursiveNestedFieldOffsetExpansionTests`、`NestedFieldOffsetExpansionDepthLimitTests`、`SpecializedDumperFieldTypeTests` + 的运行时用例、`VisibilityRegionProjectionTests.inProcessPrintsProjectToEveryConfiguration`。 +- 新增 fixture 与断言:记忆化路径与「关掉缓存」的路径渲染结果逐字节相等,覆盖**末 payload 解析失败**(特化泛型 enum 里 + `case b([T])` 就能触发)、**末字段名读失败**、间接 payload、环;判别符缓存前后节点相等且为 identifier;`removeAll()` 后重建。 +- 渲染 A/B(`Scripts/run-rendering-ab-verification.py`)按 AGENTS.md 必跑。 +- 文档同批:`Internal/MachOCaches.md` 的进程作用域 memo 清单加上这两个(其中一个有 `removeAll()`); + `Internal/NestedFieldOffsetCycleGuard.md` 补一句「每层从记录里读」。 +- 计时:RuntimeViewer 分支上的 `CorpusBuildTimingProbe`(Release)对 Foundation / SwiftUI / libswiftCore 各跑 + `mcp` 与 `mcp-no-expanded-field-offset` 两个预设,前后对比与 `ru_maxrss` 记入决策日志。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-09-30 | Created as Draft | 用户在 RuntimeViewer 的 Find 语料构建性能提问轮里选定「记忆化 + 符号索引」;用户:「把要改的仓库建一个分支(feature/runtime-viewer/find-navigator),然后开工」。 | +| 2026-09-30 | 符号查找不做排序索引,改为记忆化判别符结果 | 进程内查找先逐个重建 dyld 镜像再线性扫 `LC_SYMTAB`,共享缓存镜像的本地符号已剥离,必落空;MachOKit 上游文件按 fork 政策不改。 | +| 2026-09-30 | 第一轮审查:剪枝改为「保留行、剪子树」;缓存形态改按 0053;写明 enum payload 的 nil 不对称;修 TaskReports 链接 | 原稿把「剪掉节点」写成了字面意思,且引用 0053 的缓存形态与 0053 的决定相反。 | +| 2026-09-30 | 第二轮审查:放弃「结构树 + 渲染期剪枝」,改为按 metatype 缓存单层展开记录、遍历原样不动;缓存形态改成 0053 采纳的 `private static let` + `@Mutex` 字典(第一轮改正时仍写成了 0053 否掉的常量键 `SharedCache`);记录记 `isLast`;展开入口保留 `?? getTypeByMangledNameInContext` 回退;`removeAll()` 带代数;补文档同步清单 | 审查指出树方案漏记 `isLast` 会在「末 payload 解析失败」时改掉 `├──` / `└──` 与祖先列,且子树是否跨根共享没定、两条路各有陷阱;单层记录方案把字节一致变成构造性的,也没有 in-flight 与剪枝问题。 | diff --git a/Documentations/README.md b/Documentations/README.md index 4271d363b..ea4bbe91a 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -155,6 +155,8 @@ selects names using each access's offset and width. | [Evolutions/0054-interface-descriptor-only-vtable-members.md](Evolutions/0054-interface-descriptor-only-vtable-members.md) | **提案 0054(Implemented)**:interface 按 vtable 槽位顺序打印类成员,并补上 descriptor-only member——剥掉 local 符号的镜像(系统 dyld cache 里的 AppKit)里,class 的 public 方法实现没有符号、只剩 `Tj` / `Tq`,interface 过去只从实现符号建成员,于是 AppKit 的 `NSTableViewDiffableDataSource` / `NSCollectionViewDiffableDataSource` 只剩 `init` 和 `deinit`(整个 AppKit 少 53 个成员)。改为从 vtable 槽出发、用 `Tq` 建成员,vtable 成员按槽位顺序打印,没有名字的槽跳过;顺带修掉闭包参数返回 Optional 时 `init` 被误打成 `init?`。ABI snapshot `formatVersion` 5 → 6。 | | [Evolutions/0055-group-sources-by-layer.md](Evolutions/0055-group-sources-by-layer.md) | **提案 0055(Implemented)**:`Sources/` 按层分组——31 个平铺的 target 分进 `Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/` 八个目录,`Package.swift` 逐个声明 `path:`;target / product / 模块名不变,下游无感。连带修正靠 `#filePath` 深度找 fixture 与扫描源码的几处代码,以及 CI 里写死的 `Version.swift` 路径。 | | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | +| [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(Draft)**:进程内嵌套字段偏移展开按 metatype 记忆化为结构树、渲染期再加基址与剪枝;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | +| [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(Draft)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为受锁三态、并发调用等同一个任务;`attributes` 在索引期算好,打印期不再写定义——解除 `MachOImage` 读者下同版本内并行打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [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 的数量与内存实测。 | From 677aae99765b4920f8af3fc11d842e83f0cc2710 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 15:41:10 +0800 Subject: [PATCH 02/49] feat(declaration): let several tasks print the same definitions at once A definition indexed itself on its first print behind an unlocked check-then-set, and the printer wrote TypeDefinition.attributes on every print, so two tasks printing one image raced. RuntimeViewer already does that: its display path and its search corpus both await into the printer's nonisolated entries, which leave the section actor while they print. - index(in:) is synchronous and runs once through DefinitionIndexing: one process-wide lock over a table of passes in flight and each definition's completion flag. Callers arriving during a pass wait on the claimer's promise (SharedCacheBuildPromise with a Result payload) and share its outcome; a failed pass leaves the definition unindexed for a retry. Claiming or waiting from a thread already running a pass traps instead of risking a wait cycle. - Printing writes nothing to a definition: type-level attributes are inferred into a local per print, and TypeDefinition.attributes is removed (RuntimeViewer, REAgent and swift-decompiler never read it). TypeAttributeInferrer drops its three reads of TypeDefinition.extensions, which nothing ever fills, and documents the gap they hid. - TypeDefinition, ProtocolDefinition and ExtensionDefinition are @unchecked Sendable, with the reason on each type; SymbolicDemangler.isCacheEnabled becomes a constant. - ConcurrentDefinitionPrintingTests prints the SymbolTestsCore fixture in process from many tasks, two printers, and a type together with its nested types, comparing every output with a serial print. Before the fix it crashed on a released attributes array and release+TSan reported 28 races; after it, debug, release+TSan (no reports) and a one-thread cooperative pool, with and without the large-stack executor, all pass. CI runs it in the main filter and in the strict-pool step. The full suite passes (2163 tests, exit 0) and the rendering A/B against 4fd4049b is byte-identical over 92 pairs. Proposal draft-concurrent-definition-printing is In Progress; draft-nested-field-offset-memoization is Accepted. --- .github/workflows/macOS.yml | 8 +- AGENTS.md | 2 +- Documentations/Evolutions/README.md | 4 +- .../draft-concurrent-definition-printing.md | 11 +- .../draft-nested-field-offset-memoization.md | 5 +- .../LargeStackTaskExecutorAdoption.md | 2 + .../Internal/Modules/SwiftDeclaration.md | 11 +- .../Internal/ProjectEvolutionLog.md | 10 + Documentations/README.md | 4 +- .../SwiftInspection/SymbolicDemangler.swift | 7 +- .../TypeAttributeInferrer.swift | 37 +-- .../Components/Definitions/Definition.swift | 2 +- .../Definitions/DefinitionIndexing.swift | 100 +++++++ .../ExtensionDefinition+Indexing.swift | 30 ++- .../Definitions/ExtensionDefinition.swift | 23 +- .../ProtocolDefinition+Indexing.swift | 19 +- .../Definitions/ProtocolDefinition.swift | 22 +- .../Definitions/TypeDefinition+Indexing.swift | 20 +- .../Definitions/TypeDefinition.swift | 29 ++- .../MachOCaches/SharedCacheBuildPromise.swift | 4 + ...wiftDeclarationPrinter+DiffRendering.swift | 15 +- .../SwiftDiffableInterfaceBuilder.swift | 6 +- .../SwiftDeclarationPrinter.swift | 26 +- .../SymbolTestsCoreIntegrationTests.swift | 76 +++--- .../WrappedPropertyRecoveryTests.swift | 2 +- .../ObjCMemberRecoveryTests.swift | 5 +- .../PrintFailureEventTests.swift | 10 +- .../VisibilityRegionProjectionTests.swift | 11 +- .../ConcurrentDefinitionPrintingTests.swift | 244 ++++++++++++++++++ 29 files changed, 571 insertions(+), 174 deletions(-) create mode 100644 Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift create mode 100644 Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 38f080e62..9a76e46b4 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|ConcurrentDefinitionPrintingTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is @@ -132,6 +132,10 @@ jobs: # step timeout turns the hang into a failure. The two # `differentKeysParallelVia…` tests are skipped: they prove overlap, # which needs two pool threads by design. + # `ConcurrentDefinitionPrintingTests` is here because a definition's + # first print blocks every other print of it until its one indexing + # pass ends (`DefinitionIndexing`); that pass must never need a pool + # thread to finish. timeout-minutes: 5 env: LIBDISPATCH_COOPERATIVE_POOL_STRICT: 1 @@ -141,5 +145,5 @@ jobs: --skip-build \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests)/' \ + --filter '\.(SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|ConcurrentDefinitionPrintingTests)/' \ --skip 'differentKeysParallelVia' diff --git a/AGENTS.md b/AGENTS.md index 93ef6ff2f..ad0b0eef2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -267,7 +267,7 @@ Library entry points run their body on the demangler's large-stack task executor **Never start an unstructured `Task {}` inside a wrapped entry point**: SE-0417 means it does not inherit the preference (child tasks and default actors do). Nesting is a no-op, and below macOS 15 / iOS 18 the body runs unchanged. [LargeStackTaskExecutorAdoption.md](Documentations/Internal/LargeStackTaskExecutorAdoption.md). -Cross-version work is parallel because versions are different files; **intra-version parallelism is not safe** — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read) and `index(in:)`'s guard is a plain check-then-set. +Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read) — and `specialize(...)` appends to the generic definition unlocked. [draft-concurrent-definition-printing](Documentations/Evolutions/draft-concurrent-definition-printing.md). diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index afd6cc2fb..6ba83decb 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -65,7 +65,7 @@ | [0054](0054-interface-descriptor-only-vtable-members.md) | interface 按 vtable 槽位顺序打印类成员,补上只剩 method descriptor 符号的成员 | Implemented | | [0055](0055-group-sources-by-layer.md) | `Sources/` 按层分组 | Implemented | | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | -| draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | Draft | -| draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | Draft | +| draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | Accepted | +| draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | In Progress | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/draft-concurrent-definition-printing.md index 951881df2..ba47e023f 100644 --- a/Documentations/Evolutions/draft-concurrent-definition-printing.md +++ b/Documentations/Evolutions/draft-concurrent-definition-printing.md @@ -1,8 +1,8 @@ # Draft - 定义对象的并发打印安全:索引前置,打印期不再写定义 -- **状态**: Draft +- **状态**: In Progress - **创建日期**: 2026-09-30 -- **最后更新**: 2026-09-30 +- **最后更新**: 2026-10-01 - **所属愿景**: 无 - **关联提案**: [0019-large-stack-executor-and-cross-version-parallelism](0019-large-stack-executor-and-cross-version-parallelism.md)(跨版本并行; 同版本内并行当时明确不做)、[0002-declaration-model-descriptor-slimming](0002-declaration-model-descriptor-slimming.md)(定义对象的惰性索引形态与物化纪律) @@ -65,3 +65,10 @@ | 2026-09-30 | 只解除 `MachOImage` 读者的限制 | `MachOFile` 的不安全来自共享 `FileHandle` 的 seek + read,是另一类问题;语料只在进程内构建。 | | 2026-09-30 | 第一轮审查:「等待同一个 Task」改为首个调用者原地索引 + promise 等待,补抛错回退;补上 diff 渲染那处写入 | 非结构化 `Task {}` 不继承大栈执行器偏好、索引体本来没有 `await`;`SwiftDeclarationPrinter+DiffRendering.swift` 同样写 `attributes`。 | | 2026-09-30 | 第二轮审查:`attributes` 改局部变量而非计算属性;等待形态定为同步阻塞并把 `index(in:)` 改成同步函数;锁改进程级一把 + in-flight 表;撤掉 `isCacheEnabled` 加锁;动机补上「竞争今天已在发生」、测试先红后绿;定义类标 `@unchecked Sendable` | 计算属性违反 AGENTS.md 物化纪律且依赖方向不通(inferrer 所在模块依赖 `SwiftDeclaration`);`SharedCacheBuildPromise` 是同步阻塞且无错误通道,两种等待形态要二选一并写出不变量;每定义一把 `Mutex` 是每定义一次堆分配;`isCacheEnabled` 无写入点,加锁只添争用;RuntimeViewer 的显示路径与语料路径今天已在 actor 外并行打印同一批定义。 | +| 2026-10-01 | Accepted | 用户在 RuntimeViewer 的 Find navigator 会话里说「开始实现提案,MachOSwiftSection的更改可以和 MachOSwiftSection-FindNavigator 这个agent说」,并在本仓库的会话里直接确认「两份都开工」。 | +| 2026-10-01 | In Progress;开工前定下的实现细节 | 两份里先做本提案:RuntimeViewer 的显示路径与语料路径今天已在并发打印同一批定义。带错误通道的 promise 直接复用 `SharedCacheBuildPromise`(载荷是 `Result`),不另写一个同形的类;`isIndexed` 保持公开只读;`attributes` 直接删除、不留转发扩展——RuntimeViewer、REAgent、swift-decompiler 三个下游都不读它(2026-10-01 逐仓 grep),删除记入 changelog。 | +| 2026-10-01 | 实现:`DefinitionIndexing`(`Components/Definitions/DefinitionIndexing.swift`);认领时检查「当前线程是否正在跑某个索引体」 | 一把 `@Mutex` 守着 in-flight 表与各定义的 `hasCompletedIndexing`;三个定义的旧函数体原样挪进私有的 `runIndexingPass(in:)`,`ExtensionDefinition` 的两处提前返回不再自己置标志。同线程重入与「索引体去索引别的定义」用同一条 `precondition` 拦下:认领或等待时,in-flight 表里只要有一个 promise 的构建线程是当前线程就 trap,不需要另设 task-local。所有 `SharedCache` 都在 `SwiftDeclaration` 下层的模块里,构建闭包按依赖方向够不到定义,「索引体不索引定义」由结构保证。 | +| 2026-10-01 | 压力测试 `ConcurrentDefinitionPrintingTests`(`SwiftPrintingTests`)不声明 `ExclusiveImageAccess` | 它只比较同一进程里两个 indexer 的串行与并发输出,不对进程级状态下断言,不属于 AGENTS.md 要求声明的那类套件;单边声明也排除不了别人。套件加进 CI 的主过滤列表,并因为有意阻塞等待而加进单线程协作池那一步。 | +| 2026-10-01 | TSan 用 release 配置跑 | debug 下 `--sanitize=thread` 在加载 fixture 时就 trap:MachOKit `FileHandle+.swift:194` 用 `load(as:)` 读 `Data` 的内联字节,TSan 改了栈布局,地址落到奇数,标准库的 `_debugPrecondition` 对齐检查触发。这是 MachOKit 的既有问题(应改用 `loadUnaligned`),不在本仓库;release 下该检查被编译掉,TSan 照样检测竞争。 | +| 2026-10-01 | 验证:先红后绿 | 改动前:不开 TSan 跑压力测试,进程直接崩在 `SwiftDeclarationPrinter.swift:237`(`for attribute in typeDefinition.attributes`,另一个任务刚给 `attributes` 重新赋值,旧数组被释放后又被读);release + TSan 报出 28 条数据竞争,全部落在 `TypeDefinition.index` 内部(成员构建、thunk 属性、wrapped property)、打印器写 `attributes` 那段,以及读写成员数组(含 `detachedFromSharedTable()` 新建的 `SymbolTable` 被另一个任务无同步地读),`swift test` 退出码 1。改动后:debug 三个用例全过(约 9 秒);release + TSan 三个用例全过、0 条报告、退出码 0;`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1` 下通过(7.5 秒),再关掉大栈执行器(`MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR=0`)也通过(18 秒),说明阻塞等待不需要额外的池线程。 | +| 2026-10-01 | 全量测试与渲染 A/B | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4):改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B:基线是改动前的 `4fd4049b`,两侧共用一份 `Package.resolved`,35 个依赖完全一致(其中 5 个是本地兄弟依赖),**92 对逐字节一致**——归档 cache 26.6 与 15.5 各 12 对、iOS 15.5–26.5 模拟器 44 对、MachOImage 腿 24 对。脚本写死的 `26.6.2` 归档目录在这台机器上叫 `26.6`,本轮用只改了这个常量的脚本副本跑。iOS 15.5 模拟器的 SwiftUI / WidgetKit 4 对两侧同样以 SIGTRAP 失败,记为 SKIPPED:本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后(上游 `7adae68` 开始校验 LINKEDIT 范围),导出信息为空(offset 0、size 0)的镜像让 `ExportTrie.init` 的强制解包崩溃,由 `ObjCAncestorResolver` 沿依赖闭包查导出表触发;仓库远程 pin 的 `0.52.103 ..< 0.53.0` 不含这个改动,与本提案无关。 | diff --git a/Documentations/Evolutions/draft-nested-field-offset-memoization.md b/Documentations/Evolutions/draft-nested-field-offset-memoization.md index b2d9f7b25..ee119e3c6 100644 --- a/Documentations/Evolutions/draft-nested-field-offset-memoization.md +++ b/Documentations/Evolutions/draft-nested-field-offset-memoization.md @@ -1,8 +1,8 @@ # Draft - 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 -- **状态**: Draft +- **状态**: Accepted - **创建日期**: 2026-09-30 -- **最后更新**: 2026-09-30 +- **最后更新**: 2026-10-01 - **所属愿景**: 无 - **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(RuntimeViewer 的语料按标记模式打印,所以每个类型都要付 `printExpandedFieldOffsets` 的全价)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(进程作用域存储的形态) @@ -85,3 +85,4 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 | 2026-09-30 | 符号查找不做排序索引,改为记忆化判别符结果 | 进程内查找先逐个重建 dyld 镜像再线性扫 `LC_SYMTAB`,共享缓存镜像的本地符号已剥离,必落空;MachOKit 上游文件按 fork 政策不改。 | | 2026-09-30 | 第一轮审查:剪枝改为「保留行、剪子树」;缓存形态改按 0053;写明 enum payload 的 nil 不对称;修 TaskReports 链接 | 原稿把「剪掉节点」写成了字面意思,且引用 0053 的缓存形态与 0053 的决定相反。 | | 2026-09-30 | 第二轮审查:放弃「结构树 + 渲染期剪枝」,改为按 metatype 缓存单层展开记录、遍历原样不动;缓存形态改成 0053 采纳的 `private static let` + `@Mutex` 字典(第一轮改正时仍写成了 0053 否掉的常量键 `SharedCache`);记录记 `isLast`;展开入口保留 `?? getTypeByMangledNameInContext` 回退;`removeAll()` 带代数;补文档同步清单 | 审查指出树方案漏记 `isLast` 会在「末 payload 解析失败」时改掉 `├──` / `└──` 与祖先列,且子树是否跨根共享没定、两条路各有陷阱;单层记录方案把字节一致变成构造性的,也没有 in-flight 与剪枝问题。 | +| 2026-10-01 | Accepted | 与 [draft-concurrent-definition-printing](draft-concurrent-definition-printing.md) 同一次批准:用户在 RuntimeViewer 会话里批准开工,并在本仓库的会话里直接确认「两份都开工」。实现排在并发打印之后。 | diff --git a/Documentations/Internal/LargeStackTaskExecutorAdoption.md b/Documentations/Internal/LargeStackTaskExecutorAdoption.md index 42b302f5a..15a212509 100644 --- a/Documentations/Internal/LargeStackTaskExecutorAdoption.md +++ b/Documentations/Internal/LargeStackTaskExecutorAdoption.md @@ -57,6 +57,8 @@ SE-0417:非结构化 `Task {}` 不继承执行器偏好。核对 `Sources/` MachOKit 自己的读取有上百处 `fileHandle.seek` + `read` 共用一个句柄(`MachOFile.swift`、`DyldCache.swift` 等),两个线程交错就读错位置;`index(in:)` 的 `guard !isIndexed` 是非原子的检查加赋值。前者不在本仓库,需要 MachOKit 改 mmap 读或每个分片独立 `MachOFile` 实例,另起提案。 +后者已由提案 [draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md) 解决:`index(in:)` 改成同步函数,经进程级一把锁只跑一次,打印期不再写定义。所以 `MachOImage` 读者下同一版本内的**打印**可以并发(RuntimeViewer 建语料就这么做);`MachOFile` 读者仍受前者限制,版本内的 `prepare` 并行也仍然不做。 + ### `concurrentMap(maximumConcurrency:)` 的错误语义 窗口化 `withThrowingTaskGroup`:先提交 `window` 个,每完成一个再提交一个,结果按源序落位。首个错误经 `group.next()` 抛出,task group 在作用域退出时取消并等待在飞的子任务(`prepare` 不检查取消,所以在飞的会跑完,结果丢弃),**尚未启动的元素永远不启动**(`theFirstFailureIsRethrownAndPendingElementsNeverStart`)。哪个错误先到是调度决定的——串行时固定是最旧版本的错误,并行时不一定;只影响错误报文,不影响成功路径。 diff --git a/Documentations/Internal/Modules/SwiftDeclaration.md b/Documentations/Internal/Modules/SwiftDeclaration.md index 8dbaaba3b..0d3422fbc 100644 --- a/Documentations/Internal/Modules/SwiftDeclaration.md +++ b/Documentations/Internal/Modules/SwiftDeclaration.md @@ -43,7 +43,16 @@ SwiftDeclaration 是**共享声明模型**:`SwiftIndexing` 往里填,`SwiftP **主干里的顺序是有约束的,不能随手调**:`final` 恢复要在 `applyThunkAttributes` 之后(它要 `@objc` 证据)且在 `orderedMembers` 之前(那一步会把成员值复制走);wrapped property 恢复要在字段回折与成员构建都完成之后。每个步骤方法的 doc comment 各自写明了自己依赖什么。 -三个 Definition 的 `isIndexed` setter 是 `internal` 而非 `private`,**只因为索引扩展在另一个文件里**:包内其它 target 仍然改不动它。 +### 每个定义只索引一次,可以被并发打印 + +三个 Definition 的 `index(in:)` 是**同步**函数,都经 `DefinitionIndexing.swift` 执行(提案 [draft-concurrent-definition-printing](../../Evolutions/draft-concurrent-definition-printing.md))。进程级一把锁守着两样东西:一张「正在索引」的表(按 `ObjectIdentifier(定义)`),和每个定义自己的 `hasCompletedIndexing`。首个调用者认领后在自己的线程上跑完索引体;同时到来的调用者在认领者的 promise(复用 `SharedCacheBuildPromise`,载荷是 `Result`)上阻塞等待,拿到同一个结果。索引体抛错时定义回到未索引、错误交给全部等待者,下次调用重试。`isIndexed` 是只读的计算属性,读的就是锁下的那个标志。 + +阻塞等待不会死锁,靠两条前提,改索引时要守住: + +- **索引体里没有 `await`**。函数签名是同步的,由编译器保证:认领者在认领与交付结果之间不会被挂起。 +- **索引体不去索引别的定义**。它只经 `SharedCache` 一族读镜像,而这些缓存都在 `SwiftDeclaration` 之下的模块里,构建闭包按依赖方向根本够不到定义。认领或等待时如果当前线程正在跑某个索引体,`precondition` 直接 trap,免得等待成环。 + +打印期也不写定义:类型级 attribute 由打印器每次推断成局部变量,不存回 `TypeDefinition`。所以 `MachOImage` 读者下,同一个 printer 实例可以被多个任务同时调用,包括同时打印同一个定义、父类型与它的嵌套子类型(`ConcurrentDefinitionPrintingTests`)。`MachOFile` 读者仍然不行:MachOKit 的文件读取共用一个 `FileHandle`。`specialize(...)` 往泛型定义的 `specializedChildren` 追加时不加锁,也不在这个承诺里。 ## 关键契约 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 400ab3736..4b871bac3 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2134,6 +2134,16 @@ - **关联文档**:[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「规范化偏移的口径」与 STABS 两段、[AGENTS.md](../../AGENTS.md) 符号索引那一节新增的一条、[SystemFrameworkRenderingVerification.md](SystemFrameworkRenderingVerification.md)「跑之前先确认归档目录真的存在」。 - **对应版本**:0.22.0(未发版)。 +## 2026-10-01 定义对象可以并发打印:索引只跑一次,打印期不写定义 + +- **时间段**:2026-09-30(提案)— 2026-10-01(实现)。 +- **动机**:RuntimeViewer 的 Find 语料要并行打印一个镜像的全部定义,而定义对象在打印时才惰性索引,守卫是无锁的「检查再赋值」,打印器每次还要写 `TypeDefinition.attributes`。这个竞争在 RuntimeViewer 里已经在发生:`RuntimeSwiftSection` 是 actor,显示路径和语料路径都 `await` 到打印器的 nonisolated 入口,打印期间 actor 被释放,两条打印真并行地碰同一批定义。 +- **关键决策**:**① 索引改成同步函数,经 `DefinitionIndexing` 只跑一次**:进程级一把 `@Mutex` 守着 in-flight 表和每个定义的 `hasCompletedIndexing`;首个调用者认领后在自己线程上跑完,其余在 promise 上阻塞等待并共享结果(复用 `SharedCacheBuildPromise`,载荷是 `Result`),抛错则回到未索引、下次重试。**② 不死锁靠两条前提**:索引体没有 `await`(编译器保证),索引体不索引别的定义(所有 `SharedCache` 都在下层模块,结构上够不到定义;认领或等待时若当前线程正在跑某个索引体就 `precondition` trap)。**③ 打印期不写定义**:类型级 attribute 改成打印时的局部变量,删掉 `TypeDefinition.attributes`(三个下游都不读它);`TypeAttributeInferrer` 里三处读 `TypeDefinition.extensions` 的死代码删掉,并写明被它掩盖的缺口:声明在扩展里的 `buildBlock` / `subscript(dynamicMember:)` / `dynamicallyCall` 识别不到。**④ 三个定义类标 `@unchecked Sendable`**,理由写在类型上;`SymbolicDemangler.isCacheEnabled` 改成 `static let`。**⑤ 约定**:AGENTS.md 那条「同版本内不能并行」改成「`MachOImage` 读者下打印可以并行,`MachOFile` 读者仍不行,`specialize(...)` 不在承诺内」。 +- **落地模块**:SwiftDeclaration(`DefinitionIndexing`、三个定义类及其 `+Indexing`、`MutableDefinition` 的 requirement)、SwiftAttributeInference(`TypeAttributeInferrer`)、SwiftPrinting / SwiftInterface(打印器与 diff 渲染的两处 attribute、各处 `index(in:)` 调用)、SwiftInspection(`isCacheEnabled`)、MachOCaches(`SharedCacheBuildPromise` 的注释)。测试新增 `ConcurrentDefinitionPrintingTests`(CI 主过滤与单线程协作池两步都加了),其余测试去掉为定义不 `Sendable` 写的 `nonisolated(unsafe)` 绕法。 +- **验证**:改动前压力测试不开 TSan 直接崩(`attributes` 数组被另一个任务重新赋值后又被读),release + TSan 报 28 条数据竞争;改动后 debug、release + TSan(0 条报告)、单线程协作池、单线程协作池且关掉大栈执行器都通过。debug 下用 TSan 会在 MachOKit 读 fixture 时被对齐检查拦下(MachOKit 的既有问题),所以 TSan 一律用 release。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4)改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B 对改动前的 `4fd4049b` 共 92 对逐字节一致(归档 cache 26.6 / 15.5、iOS 15.5–26.5 模拟器、MachOImage 腿);iOS 15.5 模拟器 SwiftUI / WidgetKit 的 4 对两侧同样崩溃,原因是本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后 `ExportTrie.init` 对空导出信息强制解包,与本批无关,细节见提案决策日志。 +- **关联文档**:[draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「版本内并行为什么不做」。 +- **对应版本**:未发版。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/README.md b/Documentations/README.md index ea4bbe91a..21317212b 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -155,8 +155,8 @@ selects names using each access's offset and width. | [Evolutions/0054-interface-descriptor-only-vtable-members.md](Evolutions/0054-interface-descriptor-only-vtable-members.md) | **提案 0054(Implemented)**:interface 按 vtable 槽位顺序打印类成员,并补上 descriptor-only member——剥掉 local 符号的镜像(系统 dyld cache 里的 AppKit)里,class 的 public 方法实现没有符号、只剩 `Tj` / `Tq`,interface 过去只从实现符号建成员,于是 AppKit 的 `NSTableViewDiffableDataSource` / `NSCollectionViewDiffableDataSource` 只剩 `init` 和 `deinit`(整个 AppKit 少 53 个成员)。改为从 vtable 槽出发、用 `Tq` 建成员,vtable 成员按槽位顺序打印,没有名字的槽跳过;顺带修掉闭包参数返回 Optional 时 `init` 被误打成 `init?`。ABI snapshot `formatVersion` 5 → 6。 | | [Evolutions/0055-group-sources-by-layer.md](Evolutions/0055-group-sources-by-layer.md) | **提案 0055(Implemented)**:`Sources/` 按层分组——31 个平铺的 target 分进 `Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/` 八个目录,`Package.swift` 逐个声明 `path:`;target / product / 模块名不变,下游无感。连带修正靠 `#filePath` 深度找 fixture 与扫描源码的几处代码,以及 CI 里写死的 `Version.swift` 路径。 | | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | -| [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(Draft)**:进程内嵌套字段偏移展开按 metatype 记忆化为结构树、渲染期再加基址与剪枝;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | -| [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(Draft)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为受锁三态、并发调用等同一个任务;`attributes` 在索引期算好,打印期不再写定义——解除 `MachOImage` 读者下同版本内并行打印的限制,RuntimeViewer 据此按对象并行建语料。 | +| [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(Accepted)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | +| [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [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/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index e9e498f6c..d14ce72db 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -37,7 +37,12 @@ public enum SymbolicDemangler {} public typealias MetadataReader = SymbolicDemangler extension SymbolicDemangler { - public nonisolated(unsafe) static var isCacheEnabled: Bool = true + /// Whether the demangle memo is consulted. A constant: printing runs + /// from several tasks at once (evolution proposal + /// `concurrent-definition-printing`), and this is read on its hottest + /// entry — a settable flag would need a lock there, and nothing ever set + /// it. + public static let isCacheEnabled: Bool = true public static func demangleSymbol(for symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { return SymbolIndexStore.shared.demangledNode(for: symbol, in: machO) diff --git a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift index 16e2de316..1d09ef6fb 100644 --- a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift +++ b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift @@ -6,12 +6,23 @@ import Demangling /// /// Detectable attributes: /// - `@propertyWrapper`: type has a `wrappedValue` stored field or computed variable -/// - `@resultBuilder`: type has a `static buildBlock` method (also checks extensions) +/// - `@resultBuilder`: type has a `static buildBlock` method /// - `@dynamicMemberLookup`: type has `subscript(dynamicMember:)` /// - `@dynamicCallable`: type has a `dynamicallyCall` method /// - `@objc(Name)` / `@_objcRuntimeName(Name)`: class the source renamed for /// the ObjC runtime, as `index(in:)` read it off the class metadata /// - `@globalActor`: type conforms to `GlobalActor` protocol +/// +/// The member-based checks read the type's own members only. A `buildBlock`, +/// `subscript(dynamicMember:)` or `dynamicallyCall` declared in an extension +/// is not seen — the indexer keeps extensions in its own buckets, not on the +/// definition — so such a type prints without the attribute. (Earlier +/// versions also walked `TypeDefinition.extensions`, which nothing ever +/// fills; evolution proposal `concurrent-definition-printing` removed +/// those reads.) +/// +/// The printer calls `infer(for:)` once per print and keeps the result +/// local; it is never stored on the definition. public struct TypeAttributeInferrer: Sendable { public init() {} @@ -99,42 +110,18 @@ public struct TypeAttributeInferrer: Sendable { private func inferResultBuilder(typeDefinition: TypeDefinition, into attributes: inout [SwiftAttribute]) { if Self.hasBuildBlockMethod(staticFunctions: typeDefinition.staticFunctions) { attributes.append(.resultBuilder) - return - } - // Also check extensions for this type - for extensionDefinition in typeDefinition.extensions { - if Self.hasBuildBlockMethod(staticFunctions: extensionDefinition.staticFunctions) { - attributes.append(.resultBuilder) - return - } } } private func inferDynamicMemberLookup(typeDefinition: TypeDefinition, into attributes: inout [SwiftAttribute]) { if Self.hasDynamicMemberSubscript(subscripts: typeDefinition.subscripts, staticSubscripts: typeDefinition.staticSubscripts) { attributes.append(.dynamicMemberLookup) - return - } - // Also check extensions for this type - for extensionDefinition in typeDefinition.extensions { - if Self.hasDynamicMemberSubscript(subscripts: extensionDefinition.subscripts, staticSubscripts: extensionDefinition.staticSubscripts) { - attributes.append(.dynamicMemberLookup) - return - } } } private func inferDynamicCallable(typeDefinition: TypeDefinition, into attributes: inout [SwiftAttribute]) { if Self.hasDynamicallyCallMethod(functions: typeDefinition.functions, staticFunctions: typeDefinition.staticFunctions) { attributes.append(.dynamicCallable) - return - } - // Also check extensions for this type - for extensionDefinition in typeDefinition.extensions { - if Self.hasDynamicallyCallMethod(functions: extensionDefinition.functions, staticFunctions: extensionDefinition.staticFunctions) { - attributes.append(.dynamicCallable) - return - } } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift index 6b3d9b92b..027c489b8 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift @@ -24,5 +24,5 @@ package protocol MutableDefinition: Definition { var staticFunctions: [FunctionDefinition] { get set } var staticSubscripts: [SubscriptDefinition] { get set } - func index(in machO: some MachOSwiftSectionRepresentableWithCache) async throws + func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift new file mode 100644 index 000000000..eb64c6242 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift @@ -0,0 +1,100 @@ +import Foundation +import FoundationToolbox +@_spi(Internals) import MachOCaches + +/// A definition whose `index(in:)` runs through ``DefinitionIndexing``. +protocol OnceIndexedDefinition: AnyObject { + /// Whether an indexing pass over the definition has completed. + /// ``DefinitionIndexing`` is its only reader and writer, always inside its + /// critical section. + var hasCompletedIndexing: Bool { get set } +} + +/// Runs a definition's indexing pass once, however many tasks ask for it at +/// the same time (evolution proposal `concurrent-definition-printing`). +/// +/// A definition indexes itself on its first print, and a host may print one +/// image's definitions from several tasks at once — RuntimeViewer's display +/// path and its search corpus do, through two printers. The first caller +/// claims the definition and runs the pass on its own thread; a caller that +/// arrives meanwhile blocks on the claim's promise until the pass ends, then +/// shares its outcome: indexed, or the same error. A failed pass leaves the +/// definition unindexed, so the next call tries again. +/// +/// Blocking instead of suspending cannot deadlock as long as two things stay +/// true: +/// - A pass is synchronous, so its claimer is never suspended between the +/// claim and the fulfillment — the compiler holds this one. +/// - A pass never indexes another definition. It reads the image through the +/// `SharedCache` family, and every such cache lives in a module below this +/// one, so no cache build can reach a definition either. Claiming or +/// waiting from a thread that is running a pass traps rather than risk a +/// wait cycle. +/// +/// One process-wide lock covers every definition: it guards the table of +/// passes in flight and each definition's `hasCompletedIndexing`, and is held +/// only to read or flip that state. A lock per definition would cost a heap +/// allocation per definition, which the declaration model was slimmed to +/// avoid (evolution proposal `declaration-model-descriptor-slimming`). +enum DefinitionIndexing { + private typealias Promise = SharedCacheBuildPromise> + + private enum Claim { + case alreadyIndexed + case waitForPass(Promise) + case runPass(Promise) + } + + /// The passes in flight, by definition — and the lock every definition's + /// `hasCompletedIndexing` is read and written under. + @Mutex + private static var promisesByDefinition: [ObjectIdentifier: Promise] = [:] + + static func isIndexed(_ definition: some OnceIndexedDefinition) -> Bool { + _promisesByDefinition.withLockUnchecked { _ in + definition.hasCompletedIndexing + } + } + + /// Runs `pass` over `definition` unless it has completed one already; + /// waits for the pass another caller is running instead of starting a + /// second one. + static func index(_ definition: some OnceIndexedDefinition, runningPass pass: () throws -> Void) throws { + let definitionIdentifier = ObjectIdentifier(definition) + let claim: Claim = _promisesByDefinition.withLockUnchecked { promisesByDefinition in + if definition.hasCompletedIndexing { + return .alreadyIndexed + } + precondition( + !promisesByDefinition.values.contains { $0.isBuilderCurrentThread }, + "DefinitionIndexing: an indexing pass asked to index a definition — waiting here could form a cycle; a pass must read the image, never index" + ) + if let promise = promisesByDefinition[definitionIdentifier] { + return .waitForPass(promise) + } + let promise = Promise() + promisesByDefinition[definitionIdentifier] = promise + return .runPass(promise) + } + + switch claim { + case .alreadyIndexed: + return + case .waitForPass(let promise): + guard let passResult = promise.wait() else { + preconditionFailure("DefinitionIndexing: a pass is fulfilled with its result, never with nil") + } + try passResult.get() + case .runPass(let promise): + let passResult = Result { try pass() } + _promisesByDefinition.withLockUnchecked { promisesByDefinition in + if case .success = passResult { + definition.hasCompletedIndexing = true + } + promisesByDefinition[definitionIdentifier] = nil + } + promise.fulfill(passResult) + try passResult.get() + } + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift index ff3b4e92e..7b935875f 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift @@ -4,24 +4,32 @@ import OrderedCollections @_spi(Internals) import MachOSymbols @_spi(Internals) import SwiftInspection -extension ExtensionDefinition { - package func index(in machO: some MachOSwiftSectionRepresentableWithCache) async throws { - guard !isIndexed else { return } +extension ExtensionDefinition: OnceIndexedDefinition { + /// Resolves a conformance's resilient witnesses to members. Idempotent, + /// and safe to call from several tasks at once: the first runs the pass, + /// the others wait for it (`DefinitionIndexing`). + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + try runIndexingPass(in: machO) + } + } + /// The pass `index(in:)` runs once. Synchronous on purpose, and it must + /// never index another definition: `DefinitionIndexing` blocks the + /// callers that arrive while it runs. + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) throws { // Cheap pre-check on the retained descriptor keeps the typealias-only // majority from materializing at all; the one materialization below // is this operation's single allowed one (proposal 0002). Both early - // returns are COMPLETED indexings ("nothing to index"), so they must - // set `isIndexed` — otherwise every later consumer (the printer's - // three probes plus the diffable builder) re-enters the whole - // materialization per print. A thrown materialization deliberately - // leaves the flag unset so a failed read can be retried. + // returns are COMPLETED passes ("nothing to index"): returning marks + // the definition indexed, so no later consumer (the printer's three + // probes plus the diffable builder) re-enters the materialization per + // print. A thrown materialization leaves it unindexed, so a failed + // read can be retried. guard protocolConformanceDescriptor != nil else { - isIndexed = true return } guard let protocolConformance = try materializedProtocolConformance(in: machO.context), !protocolConformance.resilientWitnesses.isEmpty else { - isIndexed = true return } @@ -85,8 +93,6 @@ extension ExtensionDefinition { } orderedMembers = OrderedMember.offsetOrdered(OrderedMember.allMembers(from: self)) - - isIndexed = true } /// Marks the members whose witness resolved through a protocol diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift index 5b4c1d780..07ce012e0 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift @@ -8,7 +8,13 @@ import SwiftStdlibToolbox @_spi(Internals) import MachOSymbols @_spi(Internals) import SwiftInspection -public final class ExtensionDefinition: Definition, MutableDefinition { +/// An extension block of an image — a conformance, a member extension or a +/// typealias-only block — as the declaration model holds it. +/// +/// `@unchecked Sendable` for the reason `TypeDefinition` gives: written only +/// while the model is built and while `index(in:)` runs once behind +/// `DefinitionIndexing`'s lock; printing writes nothing to it. +public final class ExtensionDefinition: Definition, MutableDefinition, @unchecked Sendable { public let extensionName: ExtensionName public let genericSignature: NodeReference? @@ -96,12 +102,15 @@ public final class ExtensionDefinition: Definition, MutableDefinition { /// from a clang implementation to Swift is not a Swift ABI change. public package(set) var objcImplementation: ObjCImplementationClassFacts? = nil - /// Whether `index(in:)` has completed a pass over this definition. - /// - /// The setter is `internal`, not `private`, only because the indexing - /// pass lives in `ExtensionDefinition+Indexing.swift`: nothing outside this - /// target may flip it, and inside it only that pass does. - public internal(set) var isIndexed: Bool = false + /// Whether `index(in:)` has completed a pass over this definition. Safe + /// to read from any thread. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + /// The flag behind `isIndexed`; `DefinitionIndexing` alone reads and + /// writes it, under its lock. + var hasCompletedIndexing = false public var hasMembers: Bool { !variables.isEmpty || !functions.isEmpty || !staticVariables.isEmpty || !staticFunctions.isEmpty || !allocators.isEmpty || !constructors.isEmpty || !staticSubscripts.isEmpty || !subscripts.isEmpty diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift index 7335532f8..86c75bbaf 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift @@ -5,9 +5,20 @@ import SwiftStdlibToolbox @_spi(Internals) import MachOSymbols @_spi(Internals) import SwiftInspection -extension ProtocolDefinition { - package func index(in machO: some MachOSwiftSectionRepresentableWithCache) async throws { - guard !isIndexed else { return } +extension ProtocolDefinition: OnceIndexedDefinition { + /// Resolves the requirements and their default implementations to + /// members. Idempotent, and safe to call from several tasks at once: the + /// first runs the pass, the others wait for it (`DefinitionIndexing`). + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + try runIndexingPass(in: machO) + } + } + + /// The pass `index(in:)` runs once. Synchronous on purpose, and it must + /// never index another definition: `DefinitionIndexing` blocks the + /// callers that arrive while it runs. + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) throws { let dumpedProtocol = try materializedProtocol(in: machO.context) let name = protocolName.name // Structurally keyed: `demangleSymbolReference` returns references from @@ -72,7 +83,5 @@ extension ProtocolDefinition { defaultImplementationExtensions = [extensionDefinition] } } - - isIndexed = true } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift index 1848221de..94d206bdb 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift @@ -8,7 +8,12 @@ import SwiftStdlibToolbox @_spi(Internals) import MachOSymbols @_spi(Internals) import SwiftInspection -public final class ProtocolDefinition: Definition, MutableDefinition { +/// A protocol of an image, as the declaration model holds it. +/// +/// `@unchecked Sendable` for the reason `TypeDefinition` gives: written only +/// while the model is built and while `index(in:)` runs once behind +/// `DefinitionIndexing`'s lock; printing writes nothing to it. +public final class ProtocolDefinition: Definition, MutableDefinition, @unchecked Sendable { /// The protocol's descriptor reference (evolution proposal 0002). The /// full `MachOSwiftSection.Protocol` — requirement arrays included — is /// rebuilt on demand via `materializedProtocol(in:)` instead of living @@ -57,12 +62,15 @@ public final class ProtocolDefinition: Definition, MutableDefinition { public package(set) var orderedMembers: [OrderedMember] = [] - /// Whether `index(in:)` has completed a pass over this definition. - /// - /// The setter is `internal`, not `private`, only because the indexing - /// pass lives in `ProtocolDefinition+Indexing.swift`: nothing outside this - /// target may flip it, and inside it only that pass does. - public internal(set) var isIndexed: Bool = false + /// Whether `index(in:)` has completed a pass over this definition. Safe + /// to read from any thread. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + /// The flag behind `isIndexed`; `DefinitionIndexing` alone reads and + /// writes it, under its lock. + var hasCompletedIndexing = false /// Whether this protocol's descriptor is in the image's export trie, /// resolved once at construction (see ``ExportStatus``). Available the diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift index 48f857a87..3a306b4f2 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift @@ -7,11 +7,21 @@ import SwiftThunkAnalysis @_spi(Internals) import MachOSymbols @_spi(Internals) import SwiftInspection -extension TypeDefinition { +extension TypeDefinition: OnceIndexedDefinition { /// Fills the definition from the image: fields, members, the facts that /// are only recoverable by cross-referencing several symbol kinds, and /// the member order. Idempotent — a second call on an indexed definition - /// returns immediately. + /// returns immediately — and safe to call from several tasks at once: + /// the first runs the pass, the others wait for it (`DefinitionIndexing`). + package func index(in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try DefinitionIndexing.index(self) { + try runIndexingPass(in: machO) + } + } + + /// The pass `index(in:)` runs once. Synchronous on purpose, and it must + /// never index another definition: `DefinitionIndexing` blocks the + /// callers that arrive while it runs. /// /// The step order below is load-bearing and each step documents what it /// depends on; the two that are easiest to break are `final` recovery @@ -19,9 +29,7 @@ extension TypeDefinition { /// precede `orderedMembers`, which copies the member values) and /// wrapped-property recovery (needs both the folded fields and the member /// variables). - package func index(in machO: some MachOSwiftSectionRepresentableWithCache) async throws { - guard !isIndexed else { return } - + private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) throws { @Dependency(\.symbolIndexStore) var symbolIndexStore @@ -86,8 +94,6 @@ extension TypeDefinition { // Needs the fields and the member variables above: which `_x` is a // wrapper's storage, and whether `x` still has accessors of its own. recoverWrappedProperties(in: machO) - - isIndexed = true } /// The type's stored fields, read from its field descriptor. Carries no diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift index 041268f24..59889a46b 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift @@ -2,7 +2,17 @@ import MachOSwiftSection import SwiftInspection @_spi(Internals) import MachOSymbols -public final class TypeDefinition: Definition { +/// A nominal type of an image, as the declaration model holds it. +/// +/// `@unchecked Sendable`: apart from its indexing state, a definition is +/// written only while the indexer builds the model and while `index(in:)` +/// runs, and `index(in:)` runs at most once, behind a lock that also +/// publishes what it wrote (`DefinitionIndexing`, evolution proposal +/// `concurrent-definition-printing`). Printing writes nothing to it, so one +/// definition may be printed from several tasks at once. The one write +/// outside that promise is `specialize(...)` appending to a generic +/// definition's `specializedChildren`. +public final class TypeDefinition: Definition, @unchecked Sendable { /// The type's context descriptor reference (evolution proposal 0002). /// This is the only Mach-O parse product the definition retains: the /// full `TypeContextWrapper` (trailing objects included) is rebuilt on @@ -125,8 +135,6 @@ public final class TypeDefinition: Definition { public package(set) var conformingProtocolNames: Set = [] - public package(set) var attributes: [SwiftAttribute] = [] - /// The Objective-C runtime name the class's source chose — /// `@objc(NSColorModel)` or `@_objcRuntimeName(Name)` — read off the class /// metadata by `index(in:)` (evolution proposal `objc-custom-class-name`). @@ -134,12 +142,15 @@ public final class TypeDefinition: Definition { /// knows by its `_TtC…` mangling. public package(set) var customObjCClassName: CustomObjCClassName? = nil - /// Whether `index(in:)` has completed a pass over this definition. - /// - /// The setter is `internal`, not `private`, only because the indexing - /// pass lives in `TypeDefinition+Indexing.swift`: nothing outside this - /// target may flip it, and inside it only that pass's tail does. - public internal(set) var isIndexed: Bool = false + /// Whether `index(in:)` has completed a pass over this definition. Safe + /// to read from any thread. + public var isIndexed: Bool { + DefinitionIndexing.isIndexed(self) + } + + /// The flag behind `isIndexed`; `DefinitionIndexing` alone reads and + /// writes it, under its lock. + var hasCompletedIndexing = false /// Specialized metadata bound to this definition. /// diff --git a/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift b/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift index 3a7788d20..ed306be84 100644 --- a/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift +++ b/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift @@ -11,6 +11,10 @@ import Foundation /// `broadcast()` wakes every waiter at once, and `wait()` returns the same /// value to all of them. /// +/// `SwiftDeclaration`'s `DefinitionIndexing` uses it the same way for a +/// definition's one indexing pass, with a `Result` as the value so that +/// waiters share the pass's error too. +/// /// `final class` because the same instance must be referenced from the cache /// dictionary and from every waiter; `NSCondition` also requires a stable /// memory address. `@unchecked Sendable` because the synchronization is diff --git a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift index bce08cc0a..f741bd966 100644 --- a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift +++ b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift @@ -25,16 +25,15 @@ package extension SwiftDeclarationPrinter { /// see `renderLeafName` in `SwiftPrinting` for why. @SemanticStringBuilder func printTypeHeader(_ typeDefinition: TypeDefinition, level: Int, displayParentName: Bool = false) async throws -> SemanticString { - if !typeDefinition.isIndexed { - try await typeDefinition.index(in: machO) - } + try typeDefinition.index(in: machO) - let typeAttributeInferrer = TypeAttributeInferrer() - typeDefinition.attributes = typeAttributeInferrer.infer(for: typeDefinition) + // Inferred for this print and kept local, as `printTypeDefinition` + // does: printing writes nothing to a definition. + let attributes = TypeAttributeInferrer().infer(for: typeDefinition) // Attributes each on their own line; the diff renderer adds indentation // when it marks the lines, so none is emitted here. - for attribute in typeDefinition.attributes { + for attribute in attributes { Keyword(attribute.keyword) if let argument = typeDefinition.attributeArgument(for: attribute) { Standard("(\(argument))") @@ -62,9 +61,7 @@ package extension SwiftDeclarationPrinter { /// `printProtocolDefinition`; keep in sync. @SemanticStringBuilder func printProtocolHeader(_ protocolDefinition: ProtocolDefinition, level: Int, displayParentName: Bool = false) async throws -> SemanticString { - if !protocolDefinition.isIndexed { - try await protocolDefinition.index(in: machO) - } + try protocolDefinition.index(in: machO) // This header-print operation's single wrapper materialization // (proposal 0002). diff --git a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift index b4ebf2e27..4167d3d82 100644 --- a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift @@ -54,10 +54,10 @@ public final class SwiftDiffableInterfaceBuilder: S let printingContext = SwiftIndexEvents.PrintingContext(name: typeDefinition.typeName.name, kind: .type) eventDispatcher.dispatch(.definitionPrintStarted(context: printingContext)) - if !typeDefinition.isIndexed { - try await typeDefinition.index(in: machO) - } + try typeDefinition.index(in: machO) - // Infer type-level attributes - let typeAttributeInferrer = TypeAttributeInferrer() - typeDefinition.attributes = typeAttributeInferrer.infer(for: typeDefinition) + // Type-level attributes, inferred for this print and kept local: + // printing writes nothing to a definition, which is what lets several + // tasks print one at once (evolution proposal + // `concurrent-definition-printing`). + let attributes = TypeAttributeInferrer().infer(for: typeDefinition) // Emit type-level attributes, each on its own line before the declaration - for attribute in typeDefinition.attributes { + for attribute in attributes { Indent(level: level - 1) Keyword(attribute.keyword) // `@objc(NSColorModel)`: the runtime name a renamed class carries @@ -352,9 +352,7 @@ public final class SwiftDeclarationPrinter: S // 0002), threaded into the header and associated-type renderers below. let dumpedProtocol = try protocolDefinition.materializedProtocol(in: machO.context) - if !protocolDefinition.isIndexed { - try await protocolDefinition.index(in: machO) - } + try protocolDefinition.index(in: machO) try await DeclarationBlock(level: level) { try await renderProtocolDeclarationHeader(for: dumpedProtocol, displayParentName: displayParentName) @@ -414,9 +412,7 @@ public final class SwiftDeclarationPrinter: S let printingContext = SwiftIndexEvents.PrintingContext(name: extensionDefinition.extensionName.name, kind: .extension) eventDispatcher.dispatch(.definitionPrintStarted(context: printingContext)) - if !extensionDefinition.isIndexed { - try await extensionDefinition.index(in: machO) - } + try extensionDefinition.index(in: machO) let rendered: SemanticString if isEmptiedByExportFilter(extensionDefinition) { @@ -594,8 +590,8 @@ public final class SwiftDeclarationPrinter: S @SemanticStringBuilder private func printDefinitionContents(_ definition: some Definition, level: Int) async throws -> SemanticString { - if let mutableDefinition = definition as? MutableDefinition, !mutableDefinition.isIndexed { - try await mutableDefinition.index(in: machO) + if let mutableDefinition = definition as? MutableDefinition { + try mutableDefinition.index(in: machO) } let isProtocol = definition is ProtocolDefinition diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index 3244e29c8..f21781626 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -34,16 +34,12 @@ final class STCoreTests: MachOFileTests, @unchecked Sendable { indexer.allProtocolDefinitions.values.first { $0.protocolName.name.hasSuffix(".\(protocolName)") } } - private func indexTypeDefinition(_ typeDefinition: TypeDefinition) async throws { - nonisolated(unsafe) let unsafeTypeDefinition = typeDefinition - let unsafeMachOFile = machOFile - try await unsafeTypeDefinition.index(in: unsafeMachOFile) + private func indexTypeDefinition(_ typeDefinition: TypeDefinition) throws { + try typeDefinition.index(in: machOFile) } - private func indexProtocolDefinition(_ protocolDefinition: ProtocolDefinition) async throws { - nonisolated(unsafe) let unsafeProtocolDefinition = protocolDefinition - let unsafeMachOFile = machOFile - try await unsafeProtocolDefinition.index(in: unsafeMachOFile) + private func indexProtocolDefinition(_ protocolDefinition: ProtocolDefinition) throws { + try protocolDefinition.index(in: machOFile) } } @@ -100,7 +96,7 @@ extension STCoreTests { @Test func storedPropertyFields() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "GenericStructNonRequirement", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) let fieldNames = typeDefinition.fields.map(\.name) #expect(fieldNames == ["field1", "field2", "field3"]) @@ -148,7 +144,7 @@ extension STCoreTests { @Test func classTestNoOverride() async throws { let indexer = try await preparedIndexer() let classTest = try #require(findTypeDefinition(named: "ClassTest", in: indexer)) - try await indexTypeDefinition(classTest) + try indexTypeDefinition(classTest) for function in classTest.functions { #expect(!function.isOverride, "ClassTest.\(function.name) should not be override") @@ -158,7 +154,7 @@ extension STCoreTests { @Test func subclassOverride() async throws { let indexer = try await preparedIndexer() let subclassTest = try #require(findTypeDefinition(named: "SubclassTest", in: indexer)) - try await indexTypeDefinition(subclassTest) + try indexTypeDefinition(subclassTest) let instanceMethod = subclassTest.functions.first { $0.name == "instanceMethod" } #expect(instanceMethod?.isOverride == true) @@ -167,7 +163,7 @@ extension STCoreTests { @Test func finalClassOverride() async throws { let indexer = try await preparedIndexer() let finalClassTest = try #require(findTypeDefinition(named: "FinalClassTest", in: indexer)) - try await indexTypeDefinition(finalClassTest) + try indexTypeDefinition(finalClassTest) let instanceMethod = finalClassTest.functions.first { $0.name == "instanceMethod" } #expect(instanceMethod?.isOverride == true) @@ -243,7 +239,7 @@ extension STCoreTests { @Test func protocolAssociatedType() async throws { let indexer = try await preparedIndexer() let protocolTest = try #require(findProtocolDefinition(named: "ProtocolTest", in: indexer)) - try await indexProtocolDefinition(protocolTest) + try indexProtocolDefinition(protocolTest) #expect(protocolTest.associatedTypes.contains("Body")) } @@ -251,7 +247,7 @@ extension STCoreTests { @Test func offsetSortedProtocolDefaultImplementationExtensionsRetainMembers() async throws { let indexer = try await preparedIndexer() let protocolDefinition = try #require(findProtocolDefinition(named: "ProtocolTest", in: indexer)) - try await indexProtocolDefinition(protocolDefinition) + try indexProtocolDefinition(protocolDefinition) let matchingExtensions = protocolDefinition.defaultImplementationExtensions.filter { extensionDefinition in extensionDefinition.extensionName.name.hasSuffix(".Protocols.ProtocolTest") @@ -284,7 +280,7 @@ extension STCoreTests { @Test func propertyWrapperAttr() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "PropertyWrapperStruct", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) let inferrer = TypeAttributeInferrer() let attributes = inferrer.infer(for: typeDefinition) @@ -295,7 +291,7 @@ extension STCoreTests { @Test func resultBuilderAttr() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "ResultBuilderStruct", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) let inferrer = TypeAttributeInferrer() let attributes = inferrer.infer(for: typeDefinition) @@ -306,7 +302,7 @@ extension STCoreTests { @Test func dynamicMemberLookupAttr() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "DynamicMemberLookupStruct", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) let inferrer = TypeAttributeInferrer() let attributes = inferrer.infer(for: typeDefinition) @@ -317,7 +313,7 @@ extension STCoreTests { @Test func dynamicCallableAttr() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "DynamicCallableStruct", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) let inferrer = TypeAttributeInferrer() let attributes = inferrer.infer(for: typeDefinition) @@ -328,7 +324,7 @@ extension STCoreTests { @Test func structTestNoTypeAttr() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "StructTest", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) let inferrer = TypeAttributeInferrer() let attributes = inferrer.infer(for: typeDefinition) @@ -346,7 +342,7 @@ extension STCoreTests { @Test func dynamicMemberAttr() async throws { let indexer = try await preparedIndexer() let classTest = try #require(findTypeDefinition(named: "ClassTest", in: indexer)) - try await indexTypeDefinition(classTest) + try indexTypeDefinition(classTest) // Verify dynamic members exist let dynamicMethod = classTest.functions.first { $0.name == "dynamicMethod" } @@ -357,7 +353,7 @@ extension STCoreTests { // Check the @objc dynamic case in ObjCAttributeClass where isDynamic IS set let objcClass = try #require(findTypeDefinition(named: "ObjCAttributeClass", in: indexer)) - try await indexTypeDefinition(objcClass) + try indexTypeDefinition(objcClass) let objcDynamicMethod = objcClass.functions.first { $0.name == "objcDynamicMethod" } #expect(objcDynamicMethod != nil, "objcDynamicMethod should exist") @@ -370,7 +366,7 @@ extension STCoreTests { @Test func objcClassMemberAttr() async throws { let indexer = try await preparedIndexer() let objcClass = try #require(findTypeDefinition(named: "ObjCAttributeClass", in: indexer)) - try await indexTypeDefinition(objcClass) + try indexTypeDefinition(objcClass) // @objc is detected via thunk symbols in applyThunkAttributes let objcMethod = objcClass.functions.first { $0.name == "objcMethod" } @@ -388,7 +384,7 @@ extension STCoreTests { @Test func vtableOrdering() async throws { let indexer = try await preparedIndexer() let classTest = try #require(findTypeDefinition(named: "ClassTest", in: indexer)) - try await indexTypeDefinition(classTest) + try indexTypeDefinition(classTest) let orderedMembers = OrderedMember.classOrdered(OrderedMember.allMembers(from: classTest)) let vtableOffsets = orderedMembers.compactMap(\.minVTableOffset) @@ -410,7 +406,7 @@ extension STCoreTests { @Test func overrideMethodsDetected() async throws { let indexer = try await preparedIndexer() let subclassTest = try #require(findTypeDefinition(named: "SubclassTest", in: indexer)) - try await indexTypeDefinition(subclassTest) + try indexTypeDefinition(subclassTest) // Override methods should be detected as overrides let overrideMethods = subclassTest.functions.filter { $0.isOverride } @@ -428,7 +424,7 @@ extension STCoreTests { @Test func pwtOrdering() async throws { let indexer = try await preparedIndexer() let protocolDefinition = try #require(findProtocolDefinition(named: "ProtocolWitnessTableTest", in: indexer)) - try await indexProtocolDefinition(protocolDefinition) + try indexProtocolDefinition(protocolDefinition) let pwtOffsets = protocolDefinition.orderedMembers.compactMap(\.pwtOffset) @@ -487,10 +483,8 @@ extension STCoreTests { extensionName: donorExtensionDefinition.extensionName, genericSignature: nil ) - nonisolated(unsafe) let unsafeExtensionDefinition = descriptorLessExtensionDefinition - let unsafeMachOFile = machOFile - try await unsafeExtensionDefinition.index(in: unsafeMachOFile) - #expect(unsafeExtensionDefinition.isIndexed) + try descriptorLessExtensionDefinition.index(in: machOFile) + #expect(descriptorLessExtensionDefinition.isIndexed) } /// Sweep shape: after one `index(in:)` pass over every extension bucket @@ -499,7 +493,6 @@ extension STCoreTests { /// (no conformance descriptor / conformance without resilient witnesses). @Test func everyIndexedExtensionIsMarkedIndexed() async throws { let indexer = try await preparedIndexer() - let unsafeMachOFile = machOFile for bucket in [ indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, @@ -507,10 +500,9 @@ extension STCoreTests { indexer.conformanceExtensionDefinitions, ] { for extensionDefinition in bucket.values.flatMap({ $0 }) { - nonisolated(unsafe) let unsafeExtensionDefinition = extensionDefinition - try await unsafeExtensionDefinition.index(in: unsafeMachOFile) + try extensionDefinition.index(in: machOFile) #expect( - unsafeExtensionDefinition.isIndexed, + extensionDefinition.isIndexed, "\(extensionDefinition.extensionName.name) completed index(in:) without being marked indexed" ) } @@ -546,10 +538,9 @@ extension STCoreTests { protocolConformanceDescriptor: unreadableDescriptor ) - nonisolated(unsafe) let unsafeExtensionDefinition = unreadableExtensionDefinition - nonisolated(unsafe) let unsafePrinter = SwiftDeclarationPrinter(in: machOFile) + let printer = SwiftDeclarationPrinter(in: machOFile) await #expect(throws: (any Error).self) { - _ = try await unsafePrinter.printExtensionHeader(unsafeExtensionDefinition, level: 1) + _ = try await printer.printExtensionHeader(unreadableExtensionDefinition, level: 1) } } } @@ -583,9 +574,8 @@ extension STCoreTests { ) parentDefinition.typeChildren.append(corruptChildDefinition) - nonisolated(unsafe) let unsafeParentDefinition = parentDefinition - nonisolated(unsafe) let unsafePrinter = SwiftDeclarationPrinter(in: machOFile) - let renderedParent = try await unsafePrinter.printTypeDefinition(unsafeParentDefinition).string + let printer = SwiftDeclarationPrinter(in: machOFile) + let renderedParent = try await printer.printTypeDefinition(parentDefinition).string #expect(renderedParent.contains("StructTest"), "the enclosing type must keep printing") #expect(!renderedParent.contains("FinalClassTest"), "the corrupt child must be dropped, not rendered") @@ -598,7 +588,7 @@ extension STCoreTests { @Test func opaqueReturnTypeTestHasExpectedMembers() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "OpaqueReturnTypeTest", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) // Should have the expected variables and functions #expect(typeDefinition.variables.contains { $0.name == "variable" }) @@ -621,7 +611,7 @@ extension STCoreTests { @Test func opaquePrimaryAssocTypeReturnTestExists() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "OpaquePrimaryAssociatedTypeReturnTypeTest", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) #expect(typeDefinition.variables.contains { $0.name == "body" }) } @@ -629,7 +619,7 @@ extension STCoreTests { @Test func swiftUILikePatternStructTestHasBody() async throws { let indexer = try await preparedIndexer() let typeDefinition = try #require(findTypeDefinition(named: "StructTest", in: indexer)) - try await indexTypeDefinition(typeDefinition) + try indexTypeDefinition(typeDefinition) // StructTest has both instance and static body properties (SwiftUI-like pattern) let instanceBody = typeDefinition.variables.first { $0.name == "body" } @@ -642,7 +632,7 @@ extension STCoreTests { @Test func protocolTestHasBodyRequirement() async throws { let indexer = try await preparedIndexer() let protocolDefinition = try #require(findProtocolDefinition(named: "ProtocolTest", in: indexer)) - try await indexProtocolDefinition(protocolDefinition) + try indexProtocolDefinition(protocolDefinition) // ProtocolTest has associatedtype Body: ProtocolTest #expect(protocolDefinition.associatedTypes.contains("Body")) diff --git a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift index 2a81b6e52..39608cb62 100644 --- a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift @@ -160,7 +160,7 @@ enum WrappedPropertyFixture { let indexer = SwiftDeclarationIndexer(configuration: .init(showCImportedTypes: false, dependencySearchPaths: dependencySearchPaths), eventHandlers: [], in: machO) try await indexer.prepare() let definition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.name.hasSuffix(".\(typeName)") }, "no type named \(typeName)") - try await definition.index(in: machO) + try definition.index(in: machO) return definition } } diff --git a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift index 2ca9691ba..d763aa684 100644 --- a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift @@ -271,10 +271,9 @@ struct ObjCMemberRecoveryTests { ) try await indexer.prepare() let derived = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.name.hasSuffix(".SwiftDerivedWidget") }) - nonisolated(unsafe) let unsafeDerived = derived - try await unsafeDerived.index(in: machOFile) + try derived.index(in: machOFile) - let ping = try #require(unsafeDerived.functions.first { $0.name == "ping" }) + let ping = try #require(derived.functions.first { $0.name == "ping" }) let member = try #require(ping.objcMember, "the index records the name-only tie with nobody asking for it") #expect(member.evidence == .selectorName) #expect(member.isInferredFromSelectorName) diff --git a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift index ec9e21571..27d5152de 100644 --- a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift +++ b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift @@ -113,13 +113,12 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { let protocolDefinition = try #require(indexer.allProtocolDefinitions.values.first) let collector = EventCollector() - nonisolated(unsafe) let unsafeDefinition = protocolDefinition - nonisolated(unsafe) let unsafePrinter = SwiftDeclarationPrinter( + let printer = SwiftDeclarationPrinter( eventHandlers: [collector], in: machOFile ) - _ = try await unsafePrinter.printProtocolDefinition(unsafeDefinition).string + _ = try await printer.printProtocolDefinition(protocolDefinition).string #expect( collector.printStartedNames.contains(protocolDefinition.protocolName.name), @@ -135,13 +134,12 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { hostDefinition.typeChildren.append(unprintableDefinition) let collector = EventCollector() - nonisolated(unsafe) let unsafeHostDefinition = hostDefinition - nonisolated(unsafe) let unsafePrinter = SwiftDeclarationPrinter( + let printer = SwiftDeclarationPrinter( eventHandlers: [collector], in: machOFile ) - _ = try await unsafePrinter.printTypeDefinition(unsafeHostDefinition).string + _ = try await printer.printTypeDefinition(hostDefinition).string #expect( collector.printFailureNames.contains(donorDefinition.typeName.name), diff --git a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift index ebadd090d..647b8042a 100644 --- a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift +++ b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift @@ -85,22 +85,17 @@ final class VisibilityRegionProjectionTests: MachOSwiftSectionFixtureTests, @unc typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString var printings: [(label: String, print: Printing)] = [] - // Definitions are classes the printers index in place; the printings - // run one after another, as the fixture tests always do. for (name, definition) in indexer.rootTypeDefinitions { - nonisolated(unsafe) let unsafeDefinition = definition - printings.append(("type \(name)", { try await $0.printTypeDefinition(unsafeDefinition) })) + printings.append(("type \(name)", { try await $0.printTypeDefinition(definition) })) } for (name, definition) in indexer.rootProtocolDefinitions { - nonisolated(unsafe) let unsafeDefinition = definition - printings.append(("protocol \(name)", { try await $0.printProtocolDefinition(unsafeDefinition) })) + printings.append(("protocol \(name)", { try await $0.printProtocolDefinition(definition) })) } let extensionGroups = [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] for extensionGroup in extensionGroups { for (name, definitions) in extensionGroup { for definition in definitions { - nonisolated(unsafe) let unsafeDefinition = definition - printings.append(("extension \(name)", { try await $0.printExtensionDefinition(unsafeDefinition) })) + printings.append(("extension \(name)", { try await $0.printExtensionDefinition(definition) })) } } } diff --git a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift new file mode 100644 index 000000000..18a65574e --- /dev/null +++ b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift @@ -0,0 +1,244 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +import Semantic +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// Printing the SymbolTestsCore fixture's definitions from several tasks at +/// once reads byte for byte as printing them one after another (evolution +/// proposal `concurrent-definition-printing`). +/// +/// RuntimeViewer prints this way: its search corpus prints an image's +/// definitions from a bounded task group sharing one printer while its +/// display path prints the same definitions through another, both through +/// the in-process reader. A definition indexes itself on its first print, +/// so every test starts from an indexer whose definitions nobody has printed +/// yet and compares against a second indexer printed serially. +/// +/// Under the thread sanitizer (`swift test -c release --sanitize=thread +/// --filter ConcurrentDefinitionPrintingTests`) this suite is the race +/// detector the proposal was verified with. Release, because a debug +/// sanitizer build traps before any test runs: MachOKit's `FileHandle.read` +/// loads the fixture's magic with an aligned load from a buffer the +/// sanitizer's stack layout leaves misaligned. Without the sanitizer, a +/// race still shows up when it corrupts an output or the heap — before +/// the fix it crashed this suite on a released `attributes` array. +@Suite +final class ConcurrentDefinitionPrintingTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + private enum PrintOutcome: Equatable, Sendable { + case printed(FrozenSemanticString) + case threw(String) + + var text: String { + switch self { + case .printed(let printed): + return printed.string + case .threw(let errorDescription): + return "" + } + } + } + + /// One declaration's print. Built per indexer: the definitions of two + /// indexers over one image line up position by position. + private struct PrintJob: Sendable { + let label: String + let print: @Sendable (SwiftDeclarationPrinter) async throws -> SemanticString + + func outcome(using printer: SwiftDeclarationPrinter) async -> PrintOutcome { + do { + return .printed(try await print(printer).frozen()) + } catch { + return .threw(String(describing: error)) + } + } + } + + private struct PrintWork: Sendable { + let jobIndex: Int + let printer: SwiftDeclarationPrinter + } + + /// RuntimeViewer's corpus width. + private static let taskGroupWidth = max(2, ProcessInfo.processInfo.activeProcessorCount / 2) + + /// How many tasks print one definition at the same moment. + private static let simultaneousPrintCount = 4 + + /// The corpus mode RuntimeViewer prints in: every optional comment + /// marked rather than dropped, so every rendering path runs. + private func makePrinter() -> SwiftDeclarationPrinter { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.marksOptionalContent = true + return SwiftDeclarationPrinter(configuration: configuration, in: machOImage) + } + + private func makePreparedIndexer() async throws -> SwiftDeclarationIndexer { + let indexer = SwiftDeclarationIndexer(in: machOImage) + try await indexer.prepare() + return indexer + } + + /// Every type (nested ones included — RuntimeViewer prints those on their + /// own too), protocol and extension the indexer found, in its order. + private static func printJobs(of indexer: SwiftDeclarationIndexer) -> [PrintJob] { + var printJobs: [PrintJob] = [] + for (typeName, typeDefinition) in indexer.allTypeDefinitions { + printJobs.append(PrintJob(label: "type \(typeName.name)") { printer in + try await printer.printTypeDefinition(typeDefinition) + }) + } + for (protocolName, protocolDefinition) in indexer.allProtocolDefinitions { + printJobs.append(PrintJob(label: "protocol \(protocolName.name)") { printer in + try await printer.printProtocolDefinition(protocolDefinition) + }) + } + let extensionGroups = [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] + for extensionGroup in extensionGroups { + for (extensionName, extensionDefinitions) in extensionGroup { + for (extensionIndex, extensionDefinition) in extensionDefinitions.enumerated() { + printJobs.append(PrintJob(label: "extension \(extensionName.name) #\(extensionIndex)") { printer in + try await printer.printExtensionDefinition(extensionDefinition) + }) + } + } + } + return printJobs + } + + /// What every concurrent print must equal: each job of a fresh indexer + /// printed one after another by one printer. + private func serialOutcomes() async throws -> (labels: [String], outcomes: [PrintOutcome]) { + let indexer = try await makePreparedIndexer() + let printJobs = Self.printJobs(of: indexer) + let printer = makePrinter() + var outcomes: [PrintOutcome] = [] + for printJob in printJobs { + outcomes.append(await printJob.outcome(using: printer)) + } + return (printJobs.map(\.label), outcomes) + } + + /// Runs `work` in a task group at most `width` tasks wide and returns the + /// outcomes in `work`'s order. + private static func outcomes(of work: [PrintWork], jobs printJobs: [PrintJob], width: Int) async -> [PrintOutcome] { + await withTaskGroup(of: (workIndex: Int, outcome: PrintOutcome).self) { group in + var outcomes = [PrintOutcome?](repeating: nil, count: work.count) + var nextWorkIndex = 0 + var runningTaskCount = 0 + while nextWorkIndex < work.count || runningTaskCount > 0 { + while runningTaskCount < width, nextWorkIndex < work.count { + let workIndex = nextWorkIndex + let printWork = work[workIndex] + let printJob = printJobs[printWork.jobIndex] + group.addTask { + (workIndex, await printJob.outcome(using: printWork.printer)) + } + nextWorkIndex += 1 + runningTaskCount += 1 + } + if let finished = await group.next() { + outcomes[finished.workIndex] = finished.outcome + runningTaskCount -= 1 + } + } + return outcomes.map { outcome in + guard let outcome else { preconditionFailure("every added task reports back before the group ends") } + return outcome + } + } + } + + /// The jobs whose concurrent outcome differs from the serial one, each + /// described by its first differing line. + private static func mismatches(of work: [PrintWork], outcomes: [PrintOutcome], jobs printJobs: [PrintJob], reference: [PrintOutcome]) -> [String] { + var mismatches: [String] = [] + for (printWork, outcome) in zip(work, outcomes) where outcome != reference[printWork.jobIndex] { + let expectedLines = reference[printWork.jobIndex].text.split(separator: "\n", omittingEmptySubsequences: false) + let actualLines = outcome.text.split(separator: "\n", omittingEmptySubsequences: false) + let commonLineCount = min(expectedLines.count, actualLines.count) + let firstDifferingLine = (0 ..< commonLineCount).first { expectedLines[$0] != actualLines[$0] } ?? commonLineCount + let expectedLine = expectedLines.indices.contains(firstDifferingLine) ? String(expectedLines[firstDifferingLine]) : "" + let actualLine = actualLines.indices.contains(firstDifferingLine) ? String(actualLines[firstDifferingLine]) : "" + mismatches.append("\(printJobs[printWork.jobIndex].label), line \(firstDifferingLine + 1):\n serial: \(expectedLine)\n concurrent: \(actualLine)") + } + return mismatches + } + + @Test func definitionsSpreadOverTasksPrintAsTheyDoSerially() async throws { + let reference = try await serialOutcomes() + let indexer = try await makePreparedIndexer() + let printJobs = Self.printJobs(of: indexer) + try #require(printJobs.map(\.label) == reference.labels) + + // Both printers print every definition, their two prints queued next + // to each other so that they overlap: the corpus and the display path. + let corpusPrinter = makePrinter() + let displayPrinter = makePrinter() + let work = printJobs.indices.flatMap { jobIndex in + [PrintWork(jobIndex: jobIndex, printer: corpusPrinter), PrintWork(jobIndex: jobIndex, printer: displayPrinter)] + } + let outcomes = await Self.outcomes(of: work, jobs: printJobs, width: Self.taskGroupWidth) + + let mismatches = Self.mismatches(of: work, outcomes: outcomes, jobs: printJobs, reference: reference.outcomes) + #expect(printJobs.count > 100) + #expect(mismatches.isEmpty, "\(mismatches.prefix(5).joined(separator: "\n"))") + } + + @Test func oneDefinitionPrintedByManyTasksAtOncePrintsAsItDoesSerially() async throws { + let reference = try await serialOutcomes() + let indexer = try await makePreparedIndexer() + let printJobs = Self.printJobs(of: indexer) + try #require(printJobs.map(\.label) == reference.labels) + + let printers = [makePrinter(), makePrinter()] + var mismatches: [String] = [] + for jobIndex in printJobs.indices { + let work = (0 ..< Self.simultaneousPrintCount).map { printIndex in + PrintWork(jobIndex: jobIndex, printer: printers[printIndex % printers.count]) + } + let outcomes = await Self.outcomes(of: work, jobs: printJobs, width: work.count) + mismatches += Self.mismatches(of: work, outcomes: outcomes, jobs: printJobs, reference: reference.outcomes) + } + #expect(mismatches.isEmpty, "\(mismatches.prefix(5).joined(separator: "\n"))") + } + + @Test func aTypeAndItsNestedTypesPrintedAtOncePrintAsTheyDoSerially() async throws { + let reference = try await serialOutcomes() + let indexer = try await makePreparedIndexer() + let printJobs = Self.printJobs(of: indexer) + try #require(printJobs.map(\.label) == reference.labels) + + // A type's print prints its nested types too, so each subtree printed + // at once has every definition in it reached from several tasks. + var jobIndexByTypeDefinition: [ObjectIdentifier: Int] = [:] + for (jobIndex, typeDefinition) in indexer.allTypeDefinitions.values.enumerated() { + jobIndexByTypeDefinition[ObjectIdentifier(typeDefinition)] = jobIndex + } + let printer = makePrinter() + var printedSubtreeCount = 0 + var mismatches: [String] = [] + for rootTypeDefinition in indexer.rootTypeDefinitions.values where !rootTypeDefinition.typeChildren.isEmpty { + var subtree: [TypeDefinition] = [] + var pending = [rootTypeDefinition] + while let typeDefinition = pending.popLast() { + subtree.append(typeDefinition) + pending += typeDefinition.typeChildren + } + let work = try subtree.map { typeDefinition in + PrintWork(jobIndex: try #require(jobIndexByTypeDefinition[ObjectIdentifier(typeDefinition)]), printer: printer) + } + let outcomes = await Self.outcomes(of: work, jobs: printJobs, width: work.count) + mismatches += Self.mismatches(of: work, outcomes: outcomes, jobs: printJobs, reference: reference.outcomes) + printedSubtreeCount += 1 + } + #expect(printedSubtreeCount > 5) + #expect(mismatches.isEmpty, "\(mismatches.prefix(5).joined(separator: "\n"))") + } +} From 224d0e1c031a3379d95ac43b988afefd40cb18c7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 16:40:43 +0800 Subject: [PATCH 03/49] perf(rendering): memoize the in-process nested field-offset expansion per metatype MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RuntimeViewer's search corpus prints every type of an image in process, and each print expanded every stored field's nested layout from runtime metadata again: the same field type (String, UInt64, …) was re-resolved and re-demangled at every occurrence. Release timing puts the expansion at about a tenth of the print time. - NestedFieldOffsetLevel records what one level of the walk reads about a metatype: each row's field name, type name and relative offset, the metatype one level down, and whether the row draws the closing branch, counted over every field record as before. NestedFieldOffsetLevelMemo keeps one per metatype for the process, built outside its lock with the first store winning. The walk keeps everything positional, so the output is byte-identical by construction. - A level records which types failed to resolve, and an image loaded later can change that, so hosts get RuntimeFieldLayoutMemo.removeAll() (public, SwiftDeclarationRendering) to call after loading an image; a generation count keeps a build that straddles it from being stored. - storedFieldComments resolves a field's metatype at most once, and only when the end offset, the expansion or the type layout will use it. - InProcessContext memoizes the private discriminator of an anonymous context by address; resolving it otherwise rebuilt the owning image and scanned a symbol table that a dyld shared cache image has stripped. NestedFieldOffsetMemoizationTests compares memoized and unmemoized expansions of every stored field in the fixture and pins removeAll() and the generation guard; AnonymousContextPrivateDiscriminatorTests checks the memoized discriminators against AppKit's Objective-C runtime names. The full suite passes (2168 tests), release+TSan reports nothing, and the rendering A/B against 9f5ffa92 is byte-identical over 92 pairs, plus 16 in-process pairs with expanded field offsets on. Proposal draft-nested-field-offset-memoization is In Progress. --- .github/workflows/macOS.yml | 2 +- Documentations/Evolutions/README.md | 2 +- .../draft-nested-field-offset-memoization.md | 13 +- .../Internal/Modules/MachOCaches.md | 5 +- .../Internal/NestedFieldOffsetCycleGuard.md | 4 + .../Internal/ProjectEvolutionLog.md | 10 + Documentations/README.md | 2 +- .../SwiftInspection/SymbolicDemangler.swift | 56 ++++- .../NestedFieldOffsetLevel.swift | 123 +++++++++++ .../RuntimeFieldLayoutBackend.swift | 208 +++++++++++------- .../NestedFieldOffsetMemoizationTests.swift | 138 ++++++++++++ ...mousContextPrivateDiscriminatorTests.swift | 32 +++ 12 files changed, 502 insertions(+), 93 deletions(-) create mode 100644 Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift create mode 100644 Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 9a76e46b4..974c3e0ba 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|ConcurrentDefinitionPrintingTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 6ba83decb..e7cab50dc 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -65,7 +65,7 @@ | [0054](0054-interface-descriptor-only-vtable-members.md) | interface 按 vtable 槽位顺序打印类成员,补上只剩 method descriptor 符号的成员 | Implemented | | [0055](0055-group-sources-by-layer.md) | `Sources/` 按层分组 | Implemented | | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | -| draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | Accepted | +| draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | In Progress | | draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | In Progress | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | diff --git a/Documentations/Evolutions/draft-nested-field-offset-memoization.md b/Documentations/Evolutions/draft-nested-field-offset-memoization.md index ee119e3c6..62aa1aea5 100644 --- a/Documentations/Evolutions/draft-nested-field-offset-memoization.md +++ b/Documentations/Evolutions/draft-nested-field-offset-memoization.md @@ -1,6 +1,6 @@ # Draft - 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-09-30 - **最后更新**: 2026-10-01 - **所属愿景**: 无 @@ -9,7 +9,7 @@ - **实现分支 / PR**: `feature/runtime-viewer/find-navigator` - **配套文档**: [Internal/NestedFieldOffsetCycleGuard.md](../Internal/NestedFieldOffsetCycleGuard.md)、 [Internal/TaskReports/2026-08-06-nested-field-offset-cycle-guard.md](../Internal/TaskReports/2026-08-06-nested-field-offset-cycle-guard.md)、 - [Internal/MachOCaches.md](../Internal/MachOCaches.md)(进程作用域 memo 的清单随本提案更新) + [Internal/Modules/MachOCaches.md](../Internal/Modules/MachOCaches.md)(进程作用域 memo 的清单随本提案更新) ## 摘要 @@ -72,7 +72,7 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 - 新增 fixture 与断言:记忆化路径与「关掉缓存」的路径渲染结果逐字节相等,覆盖**末 payload 解析失败**(特化泛型 enum 里 `case b([T])` 就能触发)、**末字段名读失败**、间接 payload、环;判别符缓存前后节点相等且为 identifier;`removeAll()` 后重建。 - 渲染 A/B(`Scripts/run-rendering-ab-verification.py`)按 AGENTS.md 必跑。 -- 文档同批:`Internal/MachOCaches.md` 的进程作用域 memo 清单加上这两个(其中一个有 `removeAll()`); +- 文档同批:`Internal/Modules/MachOCaches.md` 的进程作用域 memo 清单加上这两个(其中一个有 `removeAll()`); `Internal/NestedFieldOffsetCycleGuard.md` 补一句「每层从记录里读」。 - 计时:RuntimeViewer 分支上的 `CorpusBuildTimingProbe`(Release)对 Foundation / SwiftUI / libswiftCore 各跑 `mcp` 与 `mcp-no-expanded-field-offset` 两个预设,前后对比与 `ru_maxrss` 记入决策日志。 @@ -86,3 +86,10 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 | 2026-09-30 | 第一轮审查:剪枝改为「保留行、剪子树」;缓存形态改按 0053;写明 enum payload 的 nil 不对称;修 TaskReports 链接 | 原稿把「剪掉节点」写成了字面意思,且引用 0053 的缓存形态与 0053 的决定相反。 | | 2026-09-30 | 第二轮审查:放弃「结构树 + 渲染期剪枝」,改为按 metatype 缓存单层展开记录、遍历原样不动;缓存形态改成 0053 采纳的 `private static let` + `@Mutex` 字典(第一轮改正时仍写成了 0053 否掉的常量键 `SharedCache`);记录记 `isLast`;展开入口保留 `?? getTypeByMangledNameInContext` 回退;`removeAll()` 带代数;补文档同步清单 | 审查指出树方案漏记 `isLast` 会在「末 payload 解析失败」时改掉 `├──` / `└──` 与祖先列,且子树是否跨根共享没定、两条路各有陷阱;单层记录方案把字节一致变成构造性的,也没有 in-flight 与剪枝问题。 | | 2026-10-01 | Accepted | 与 [draft-concurrent-definition-printing](draft-concurrent-definition-printing.md) 同一次批准:用户在 RuntimeViewer 会话里批准开工,并在本仓库的会话里直接确认「两份都开工」。实现排在并发打印之后。 | +| 2026-10-01 | In Progress;修正配套文档链接 | 并发打印那份已提交(`9f5ffa92`),本提案接着做。配套文档写成了不存在的 `Internal/MachOCaches.md`,实际在 `Internal/Modules/MachOCaches.md`。 | +| 2026-10-01 | 记下 Release 下的「改前」计时:展开字段偏移约占打印时间一成,不是 Debug 采样的 61% | RuntimeViewer 会话用 `CorpusBuildTimingProbe` 在 JHs-Mac-Studio-Ultra 上量(RuntimeViewer `72913c3d`,Release,MachOSwiftSection `next` 514bb4bd,每个预设一个进程;机器上同时有其他会话,负载 16–55,绝对值偏噪):Foundation(2559 个对象)`mcp` 3.72 s、`mcp-no-expanded-field-offset` 3.33 s,差 0.39 s,约 10.5%;SwiftUI(7378 个)51.95 s 对 47.0 s(两组负载不同,约 10%);libswiftCore(660 个)各预设都在 0.82–0.86 s,差别在噪声内。收益因此比提案动机写的小,但仍按批准的范围实现;「改后」数字等提交后由 RuntimeViewer 会话用同样的预设再量。 | +| 2026-10-01 | 实现:`NestedFieldOffsetLevel` 与 `NestedFieldOffsetLevelMemo`(`SwiftDeclarationRendering/NestedFieldOffsetLevel.swift`);宿主入口是 `RuntimeFieldLayoutMemo.removeAll()` | 记录分 `structFields` / `enumPayloads` / `notExpanded` 三种,构建逻辑从原来的两个遍历函数原样搬出;遍历里只剩基址、祖先列、深度、路径环守卫和日志。memo 是一把 `@Mutex` 守着字典与代数计数,记录在锁外建、先存者赢。宿主入口做成 `public`(不加 SPI):`SwiftDeclarationRendering` 里给宿主的接口都是纯 `public`,RuntimeViewer 已经 import 这个模块。 | +| 2026-10-01 | `storedFieldComments` 只在三个消费方里至少一个要用时才解析字段的 metatype,且只解析一次 | 三个条件(最后一个字段要算结束偏移、要展开、要打 type layout)取并集。直接提到函数开头无条件解析,会让原来一次都不解析的配置(比如只开字段偏移的非末字段)多出一次解析。展开入口的 `?? getTypeByMangledNameInContext` 回退留在展开那段里。运行时展开入口原来的 `machO == nil` 分支没有调用方,随之删掉。 | +| 2026-10-01 | 判别符记忆化:把 `privateDiscriminatorIdentifier` 改成私有协议 `SymbolLookupContext` 的 requirement,只有 `InProcessContext` 换成查表 | 原来它是协议扩展里的方法,经 `as? SymbolLookupContext` 调用时静态派发,`InProcessContext` 覆盖不了。只记 `identifier` 的文本,命中时重建同样的节点,「没有判别符」也记;表放在 `SymbolicDemanglerCache` 的进程级存储里。不提供清除入口:查的是已经在内存里的匿名上下文,答案不会变。 | +| 2026-10-01 | 测试不新建 fixture;加一个只给测试用的 `NestedFieldOffsetLevelMemo.isBypassed`(`package` 级 `@TaskLocal`) | SymbolTestsCore 的 `ValueSpec` 已经同时有:最后一个 payload `pair` 解析不出(前一行 `reference` 因此画 `├──`)、`indirect` payload、`ReferenceSpec` ↔ `ValueSpec` 的环;改 SymbolTestsCore 会牵动全部基线。「末字段名读失败」编译器产不出来,靠构造保证:记录里的 `isLast` 与原来按同一个表达式、对全部字段记录计数。绕过开关是提案「关掉缓存的路径」所需,`@TaskLocal` 只影响当前任务树,不碰并行的其它套件。判别符缓存的测试以 AppKit 私有类的 Objective-C 运行时名字为独立真值,冷热两次都比。 | +| 2026-10-01 | 验证 | 新测试与相关既有套件(嵌套展开、深度上限、特化字段类型、可见性区域投影、两个判别符套件、并发打印)全过。全量 `swift test --skip IntegrationTests` 2168 个测试全过,原始退出码 0,known issue 仍是 `SymbolicManglingIndexTests` 那一条。release + TSan 跑 `ConcurrentDefinitionPrintingTests`(标记模式打印含展开字段偏移,多线程同时查 memo)与 `NestedFieldOffsetMemoizationTests`:0 条报告,退出码 0。渲染 A/B 对 `9f5ffa92`(并发打印那份):92 对逐字节一致,SKIPPED 的仍是 iOS 15.5 模拟器 SwiftUI / WidgetKit 那 4 对(本地 MachOKit `next` 的既有问题)。A/B 的 MachOImage 腿默认不开展开字段偏移,所以另用 `RenderingVerificationTests` 打开全部选项(含 `expandedFieldOffsets`)对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍:16 对逐字节一致,进程内那几份带 17 到约 7800 行展开行。SwiftUI / SwiftUICore 没放进这一轮:该工具记着它们在开展开字段偏移时有既有的栈溢出。`NestedFieldOffsetMemoizationTests` 加进 CI 的主过滤列表。 | diff --git a/Documentations/Internal/Modules/MachOCaches.md b/Documentations/Internal/Modules/MachOCaches.md index 836744a6d..c5689713e 100644 --- a/Documentations/Internal/Modules/MachOCaches.md +++ b/Documentations/Internal/Modules/MachOCaches.md @@ -99,7 +99,10 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { **内存压力**:库不再监听。以前每个 `SharedCache` 实例各挂一个 `MemoryPressureMonitor`,warning 就 `removeAll()`,绕过认领规则,而且清掉的存储被活着的 `NodeReference` 钉着、回收不到内存。现在宿主想清就调 `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()`:清所有出现在任一 cache 里、且没有活持有者的镜像的全部 group。非持有者临时填的镜像也会被清,这是宿主显式调用的后果。 -**不受驱逐的**:两个进程作用域的 memo(`InternedNodeReferenceCache` 与 `SymbolicDemanglerCache` 给没有 Mach-O 句柄的进程内读取路径用的)是 `static let`,不经过按镜像的字典,大小由进程实际碰到的唯一名字数决定。 +**不受驱逐的**:进程作用域的 memo 都是 `static` 存储,不经过按镜像的字典,也不受注册表管: + +- `InternedNodeReferenceCache` 与 `SymbolicDemanglerCache` 给没有 Mach-O 句柄的进程内读取路径用的那两份,大小由进程实际碰到的唯一名字数决定。`SymbolicDemanglerCache` 的这一份里还有一张按地址记的匿名上下文判别符表,`InProcessContext` 查判别符时用(提案 [draft-nested-field-offset-memoization](../../Evolutions/draft-nested-field-offset-memoization.md)):已经在内存里的匿名上下文,答案不会变。 +- `SwiftDeclarationRendering` 的 `NestedFieldOffsetLevelMemo`:进程内嵌套字段偏移展开按 metatype 记下的「一层」(同一提案),大小由进程展开过的唯一 metatype 数决定。它记下了「当时哪些字段类型解析不出」,进程之后加载的镜像可能让它们变得可解析,所以它有清除入口 `RuntimeFieldLayoutMemo.removeAll()`:宿主在进程里加载镜像之后调一次。其余几份没有这个问题,也没有清除入口。 ## 4. 契约与坑 diff --git a/Documentations/Internal/NestedFieldOffsetCycleGuard.md b/Documentations/Internal/NestedFieldOffsetCycleGuard.md index a58a96215..433431171 100644 --- a/Documentations/Internal/NestedFieldOffsetCycleGuard.md +++ b/Documentations/Internal/NestedFieldOffsetCycleGuard.md @@ -94,6 +94,10 @@ struct 持有 `Optional>`,而这个 en **这一点在测试上是诚实的**:本次的 fixture 无法单独触发守卫一(造不出不经 indirect 的值类型环),所以没有为它单独写测试。回归测试端到端地覆盖了两道守卫共同作用下的行为。 +### 每层从记录里读(2026-10-01 起,运行时路径) + +运行时路径每一层要读的东西——描述符、字段偏移、字段记录、每行的类型名、下一层的 metatype——按 metatype 记成一份 `NestedFieldOffsetLevel`,进程内只建一次(提案 [draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md))。遍历本身没动:基址偏移、树的祖先列、深度、路径环守卫和两条日志都还在 `walkNestedExpandedFieldOffsets` 里,所以两道守卫的行为与输出逐字节不变。记录里的 `isLast` 仍按全部字段记录、全部 payload case 计数:解析失败、没有行的那一项照样占位,前一行因此仍画 `├──`(`ValueSpec` 的最后一个 case `pair` 解析不出,`reference` 那行就是这样,`NestedFieldOffsetMemoizationTests` 钉住)。 + ## 影响面 - 输出变化仅限于**此前就是错的**那部分:`indirect` case 底下不再打印它那些并不在该 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 4b871bac3..a9ce2805a 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2144,6 +2144,16 @@ - **关联文档**:[draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「版本内并行为什么不做」。 - **对应版本**:未发版。 +## 2026-10-01 进程内嵌套字段偏移展开按 metatype 记一层;匿名上下文判别符按地址记 + +- **时间段**:2026-09-30(提案)— 2026-10-01(实现)。 +- **动机**:RuntimeViewer 建 Find 语料时打印镜像里的全部类型。Debug 采样里单个类型打印的 61% 落在进程内的嵌套字段偏移展开(同一个字段类型在每个出现处都重新递归、重新 demangle),9% 落在匿名上下文判别符的查找(共享缓存镜像的本地符号已剥离,线性扫符号表基本必落空),两处都没有缓存。Release 下量出来,展开字段偏移约占打印时间一成(Foundation 约 10.5%),收益比 Debug 采样小,按批准的范围照做。 +- **关键决策**:**① 缓存「一层」而不是整棵树**:按 metatype 记下这一层要打印的每行(字段名、类型名、相对偏移、`isLast`)和下一层的 metatype,遍历本身——基址、树的祖先列、深度、路径环守卫、日志——原样留着,所以输出逐字节不变是构造出来的;`isLast` 仍对全部字段记录计数,解析失败、没有行的那项照样占位。**② 进程级存储**:`static` 的 `@Mutex` 字典,键是 `ObjectIdentifier(metatype)`,记录在锁外建、先存者赢;一层记下了「当时哪些类型解析不出」,进程之后加载的镜像可能改变答案,所以给宿主一个 `RuntimeFieldLayoutMemo.removeAll()`,带代数计数防止跨越清除的构建写回。**③ `storedFieldComments` 每个字段最多解析一次 metatype**,且只在有消费方要用时解析。**④ 判别符按地址记忆化**,只在 `InProcessContext` 这条路上,存在 `SymbolicDemanglerCache` 的进程级存储里;查的是已在内存里的匿名上下文,不需要清除入口。 +- **落地模块**:SwiftDeclarationRendering(新文件 `NestedFieldOffsetLevel.swift`:`NestedFieldOffsetLevel`、`NestedFieldOffsetLevelMemo`、公开的 `RuntimeFieldLayoutMemo`;`RuntimeFieldLayoutBackend` 的展开与 `storedFieldComments`)、SwiftInspection(`SymbolicDemangler` 的 `SymbolLookupContext` 与 `SymbolicDemanglerCache`)。测试新增 `NestedFieldOffsetMemoizationTests`,`AnonymousContextPrivateDiscriminatorTests` 加一条冷热两次的判别符对照。 +- **验证**:全量 `swift test --skip IntegrationTests` 2168 个测试全过(原始退出码 0);release + TSan 跑并发打印与记忆化两个套件 0 条报告。渲染 A/B 对并发打印那份(`9f5ffa92`)92 对逐字节一致;因为 A/B 的进程内腿默认不开展开字段偏移,另用 `RenderingVerificationTests` 打开全部选项对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍,16 对逐字节一致(进程内那几份带 17 到约 7800 行展开行)。「改后」计时由 RuntimeViewer 会话补。 +- **关联文档**:[draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md)、[Modules/MachOCaches.md](Modules/MachOCaches.md)「不受驱逐的」、[NestedFieldOffsetCycleGuard.md](NestedFieldOffsetCycleGuard.md)「每层从记录里读」。 +- **对应版本**:未发版。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/README.md b/Documentations/README.md index 21317212b..71e68979d 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -155,7 +155,7 @@ selects names using each access's offset and width. | [Evolutions/0054-interface-descriptor-only-vtable-members.md](Evolutions/0054-interface-descriptor-only-vtable-members.md) | **提案 0054(Implemented)**:interface 按 vtable 槽位顺序打印类成员,并补上 descriptor-only member——剥掉 local 符号的镜像(系统 dyld cache 里的 AppKit)里,class 的 public 方法实现没有符号、只剩 `Tj` / `Tq`,interface 过去只从实现符号建成员,于是 AppKit 的 `NSTableViewDiffableDataSource` / `NSCollectionViewDiffableDataSource` 只剩 `init` 和 `deinit`(整个 AppKit 少 53 个成员)。改为从 vtable 槽出发、用 `Tq` 建成员,vtable 成员按槽位顺序打印,没有名字的槽跳过;顺带修掉闭包参数返回 Optional 时 `init` 被误打成 `init?`。ABI snapshot `formatVersion` 5 → 6。 | | [Evolutions/0055-group-sources-by-layer.md](Evolutions/0055-group-sources-by-layer.md) | **提案 0055(Implemented)**:`Sources/` 按层分组——31 个平铺的 target 分进 `Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/` 八个目录,`Package.swift` 逐个声明 `path:`;target / product / 模块名不变,下游无感。连带修正靠 `#filePath` 深度找 fixture 与扫描源码的几处代码,以及 CI 里写死的 `Version.swift` 路径。 | | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | -| [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(Accepted)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | +| [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [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)。 | diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index d14ce72db..4123a9e99 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -91,15 +91,23 @@ private protocol SymbolLookupContext { /// image's `_symbolic` symbols record it /// (`AnonymousContextPrivateDiscriminatorIndex`). func symbolicReferencePrivateDiscriminator(forAnonymousContextAt offset: Int) -> String? + + /// The discriminator of the private type inside the anonymous context at + /// `offset`, as the identifier a `privateDeclName` takes. A requirement + /// so that a context can memoize it; the default resolves it every time. + func privateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? } extension SymbolLookupContext { - /// The discriminator of the private type inside the anonymous context at - /// `offset`, as the identifier a `privateDeclName` takes: from a symbol on - /// the anonymous descriptor when the image kept one, otherwise from a - /// `_symbolic` symbol naming that type, which an OS framework in the dyld - /// shared cache still carries when the other is gone. func privateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? { + resolvedPrivateDiscriminatorIdentifier(forAnonymousContextAt: offset) + } + + /// From a symbol on the anonymous descriptor when the image kept one, + /// otherwise from a `_symbolic` symbol naming the type inside, which an OS + /// framework in the dyld shared cache still carries when the other is + /// gone. + func resolvedPrivateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? { if let symbol = lookupSymbol(at: offset), let privateDeclName = try? symbol.demangledNode.first(of: Node.Kind.privateDeclName) { return privateDeclName.children.first } @@ -131,6 +139,18 @@ extension InProcessContext: SymbolLookupContext { guard let pointer = UnsafeRawPointer(bitPattern: offset), let machOImage = MachOImage.image(for: pointer) else { return nil } return AnonymousContextPrivateDiscriminatorIndex.shared.privateDiscriminator(forAnonymousContextAt: offset - machOImage.ptr.bitPattern.int, in: machOImage) } + + /// Memoized per address for the process (evolution proposal + /// `nested-field-offset-memoization`). The answer for an anonymous context + /// already in memory never changes, and resolving it rebuilds the owning + /// image and scans its whole symbol table first — which an image in the + /// dyld shared cache has stripped, so that scan almost always comes back + /// empty. + func privateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? { + SymbolicDemanglerCache.shared.privateDiscriminatorIdentifier(forAnonymousContextAt: offset) { + resolvedPrivateDiscriminatorIdentifier(forAnonymousContextAt: offset) + } + } } extension SymbolicDemangler { @@ -821,6 +841,12 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { /// answered "no context mangling" once and is never retried. @Mutex fileprivate var nodeReferenceForSymbolName: [String: NodeReference?] = [:] + + /// The private discriminator of the anonymous context at an in-process + /// address; a stored `nil` records that it has none. Only the + /// process-scoped storage fills it. + @Mutex + fileprivate var privateDiscriminatorForAnonymousContextAddress: [Int: String?] = [:] } /// The memo `context` files entries under, as its cache scope declares: @@ -843,6 +869,26 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { cache.contains(in: machO) } + /// `InProcessContext`'s discriminator lookup, memoized as text. Only an + /// `identifier` — what the lookup returns for every discriminator it + /// finds — is memoized; a hit rebuilds the same node. + fileprivate func privateDiscriminatorIdentifier(forAnonymousContextAt address: Int, resolving resolve: () -> Node?) -> Node? { + let storage = Self.processScopedStorage + if let memoizedDiscriminator = storage.privateDiscriminatorForAnonymousContextAddress[address] { + return memoizedDiscriminator.map { .createTransient(kind: .identifier, text: $0) } + } + let resolvedIdentifier = resolve() + if let resolvedIdentifier { + guard resolvedIdentifier.kind == .identifier, let discriminator = resolvedIdentifier.text else { + return resolvedIdentifier + } + storage.privateDiscriminatorForAnonymousContextAddress.updateValue(discriminator, forKey: address) + } else { + storage.privateDiscriminatorForAnonymousContextAddress.updateValue(nil, forKey: address) + } + return resolvedIdentifier + } + fileprivate func remove(for machO: some MachORepresentableWithCache) { cache.remove(for: machO) } diff --git a/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift b/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift new file mode 100644 index 000000000..1a08bc04d --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift @@ -0,0 +1,123 @@ +import Foundation +import FoundationToolbox + +/// What the in-process nested field-offset walk reads about one metatype: +/// everything it prints for that metatype's rows and everything it needs to +/// go one level down, computed once per metatype (evolution proposal +/// `nested-field-offset-memoization`). +/// +/// A level depends on the metatype alone — its descriptor, field offsets and +/// field records, and the names and metatypes those resolve to — never on +/// where in a tree the metatype is reached, so `String` under two different +/// fields shares one. Everything positional stays with the walk: the base +/// offset, the tree's ancestor column, the depth and the cycle guard. +/// +/// `@unchecked Sendable`: a level is immutable once built, and the metatypes +/// it holds are runtime metadata, which lives as long as the process. +enum NestedFieldOffsetLevel: @unchecked Sendable { + /// A struct's stored fields: one entry per field whose name could be read. + case structFields([StructField]) + /// An enum's (or `Optional`'s) payload cases: one entry per case whose + /// payload type resolved to a metatype. + case enumPayloads([EnumPayload]) + /// A metatype the walk does not expand: neither a struct nor an enum, or + /// one whose metadata could not be read. + case notExpanded + + struct StructField { + let fieldName: String + let typeName: String + let relativeOffset: Int + /// The field's metatype, or `nil` when the walk does not descend. + let childMetatype: Any.Type? + /// Whether the row draws the closing branch. Counted over every field + /// record, including one whose name could not be read and so has no + /// entry — which is how the walk has always drawn it. + let isLast: Bool + } + + struct EnumPayload { + let caseName: String + let typeName: String + let payloadMetatype: Any.Type + /// Counted over every payload case, including one whose payload did + /// not resolve and so has no entry. + let isLast: Bool + /// `false` for an `indirect` case: its payload is boxed, not laid out + /// at the case's offset. + let descends: Bool + } +} + +/// The process-wide memo of ``NestedFieldOffsetLevel``s, keyed by metatype. +/// +/// A `static` store rather than a per-image `SharedCache`: a metatype is +/// unique in the process and outlives every image the host keeps loaded, and +/// one level serves every image that reaches the type. Its size is the +/// number of distinct metatypes the process expanded. A level is built +/// outside the lock and stored by whoever finishes first; two builders of one +/// metatype produce the same level, so the loser only wasted its build. +enum NestedFieldOffsetLevelMemo { + private struct State { + var levelsByMetatype: [ObjectIdentifier: NestedFieldOffsetLevel] = [:] + /// Bumped by `removeAll()`, so a level whose build straddled it is + /// returned to its caller but not stored. + var generation = 0 + } + + @Mutex + private static var state: State = State() + + /// Builds every level afresh and stores none, for the tests that compare + /// the memoized expansion with an unmemoized one. + @TaskLocal + package static var isBypassed = false + + static func level(for metatype: Any.Type, building build: () -> NestedFieldOffsetLevel) -> NestedFieldOffsetLevel { + if isBypassed { + return build() + } + let metatypeIdentifier = ObjectIdentifier(metatype) + let (memoizedLevel, generation) = _state.withLockUnchecked { state in + (state.levelsByMetatype[metatypeIdentifier], state.generation) + } + if let memoizedLevel { + return memoizedLevel + } + let builtLevel = build() + return _state.withLockUnchecked { state in + guard state.generation == generation else { + return builtLevel + } + if let storedLevel = state.levelsByMetatype[metatypeIdentifier] { + return storedLevel + } + state.levelsByMetatype[metatypeIdentifier] = builtLevel + return builtLevel + } + } + + static func removeAll() { + _state.withLockUnchecked { state in + state.levelsByMetatype.removeAll() + state.generation += 1 + } + } +} + +/// The process-wide memo of the in-process (`MachOImage`) field-layout +/// renderer. +public enum RuntimeFieldLayoutMemo { + /// Forgets every memoized level of the nested field-offset expansion. + /// + /// A level records which field and payload types resolved when it was + /// built. A type defined in an image the process had not loaded yet does + /// not resolve, and the level keeps saying so after the image loads: the + /// expansion stops where, rendered again, it would now descend. A host + /// that loads images while it renders — RuntimeViewer, after each image + /// it loads — calls this once after the load. Rendering never needs it + /// otherwise. + public static func removeAll() { + NestedFieldOffsetLevelMemo.removeAll() + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift index 8c6d8491f..542f2fc80 100644 --- a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift @@ -102,12 +102,21 @@ struct RuntimeFieldLayoutBackend { mangledTypeName: MangledName, fieldOffsets: [Int]? ) async throws -> SemanticString { - if let fieldOffsets, let startOffset = fieldOffsets[safe: index] { + let startOffset = fieldOffsets?[safe: index] + let nextFieldOffset = fieldOffsets?[safe: index + 1] + let expandsFieldOffsets = configuration.producesContent(for: .printFieldOffset) && configuration.producesContent(for: .printExpandedFieldOffsets) + // Three consumers below may need the field's metatype — the last + // field's end offset, the expansion and the type layout. Resolved once, + // and only when one of them is going to run. + let needsFieldMetatype = (startOffset != nil && (nextFieldOffset == nil || expandsFieldOffsets)) || configuration.producesContent(for: .printTypeLayout) + let fieldMetatype = needsFieldMetatype ? resolveFieldMetatype(for: mangledTypeName, in: machO) : nil + + if let startOffset { let endOffset: Int? - if let nextFieldOffset = fieldOffsets[safe: index + 1] { + if let nextFieldOffset { endOffset = nextFieldOffset - } else if let metatype = resolveFieldMetatype(for: mangledTypeName, in: machO), - let typeLayout = try? StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout { + } else if let fieldMetatype, + let typeLayout = try? StructMetadata.createInProcess(fieldMetatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout { endOffset = startOffset + Int(typeLayout.size) } else { endOffset = nil @@ -115,16 +124,23 @@ struct RuntimeFieldLayoutBackend { configuration.optionalContent(.printFieldOffset) { configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) // Expanded offsets hang off the field offset: printed only - // when both are on. + // when both are on. A field whose specialized resolution + // failed may still resolve by its bare name, so the expansion + // keeps that second try. configuration.optionalContent(.printExpandedFieldOffsets) { - expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset, baseIndentation: configuration.indentation, ancestors: [], in: machO) + expandedFieldOffsets( + of: fieldMetatype ?? (try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, in: machO)), + baseOffset: startOffset, + baseIndentation: configuration.indentation, + ancestors: [] + ) } } } if configuration.producesContent(for: .printTypeLayout), - let resolvedMetatype = resolveFieldMetatype(for: mangledTypeName, in: machO), - let resolvedMetadata = try? StructMetadata.createInProcess(resolvedMetatype) { + let fieldMetatype, + let resolvedMetadata = try? StructMetadata.createInProcess(fieldMetatype) { try await configuration.optionalContent(.printTypeLayout) { try await resolvedMetadata.asMetadataWrapper(in: .inProcess).dumpTypeLayout(using: configuration) } @@ -192,22 +208,17 @@ struct RuntimeFieldLayoutBackend { // MARK: - Expanded nested field offsets // - // Lifted verbatim from `SwiftDump.TypedDumper`; behaviour-preserving. The - // only changes: `Metadata.createInProcess` → `StructMetadata.createInProcess` - // (the static metadata type is incidental — `asMetadataWrapper(in: .inProcess)` re-dispatches - // on the actual kind), and the top-hop substitution goes through this type's - // `resolveFieldMetatype`. See the original for the extensive rationale on the - // PAC-fault-avoiding static substitution. + // Lifted from `SwiftDump.TypedDumper`. The only changes: + // `Metadata.createInProcess` → `StructMetadata.createInProcess` (the + // static metadata type is incidental — `asMetadataWrapper(in: .inProcess)` + // re-dispatches on the actual kind), the top hop goes through this type's + // `resolveFieldMetatype`, and what each level reads about its metatype is + // memoized (`NestedFieldOffsetLevel`, evolution proposal + // `nested-field-offset-memoization`). See the original for the extensive + // rationale on the PAC-fault-avoiding static substitution. @SemanticStringBuilder - func expandedFieldOffsets(for mangledTypeName: MangledName, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], in machO: MachOImage?) -> SemanticString { - let topMetatype: Any.Type? - if let machO { - topMetatype = resolveFieldMetatype(for: mangledTypeName, in: machO) - ?? (try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, in: machO)) - } else { - topMetatype = try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName) - } + func expandedFieldOffsets(of topMetatype: Any.Type?, baseOffset: Int, baseIndentation: Int, ancestors: [Bool]) -> SemanticString { if let topMetatype { walkNestedExpandedFieldOffsets(of: topMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, enclosingMetatypes: []) } @@ -230,21 +241,36 @@ struct RuntimeFieldLayoutBackend { /// The depth limit stays as the backstop for the acyclic-but-deep case; it /// cannot bound a cycle on its own, because a cycle makes the number of /// paths — not the depth — the thing that explodes. + /// + /// What one level reads about its metatype comes from + /// `nestedFieldOffsetLevel(of:)`, built once per metatype; the walk itself + /// — the rows, their offsets and tree prefixes, the cycle and depth guards + /// and their log lines — is the same either way. @SemanticStringBuilder private func walkNestedExpandedFieldOffsets(of metatype: Any.Type, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int = 0, enclosingMetatypes: Set) -> SemanticString { if enclosingMetatypes.contains(ObjectIdentifier(metatype)) { emitNestedFieldOffsetCycleWarning(for: metatype) } else if depth >= nestedFieldOffsetExpansionDepthLimit { emitNestedFieldOffsetDepthLimitWarning(for: metatype) - } else if let wrapper = try? StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess) { + } else { let nestedEnclosingMetatypes = enclosingMetatypes.union([ObjectIdentifier(metatype)]) - switch wrapper { - case .struct(let metadata): - walkNestedStructFieldOffsets(of: metadata, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, depth: depth, enclosingMetatypes: nestedEnclosingMetatypes) - case .enum(let metadata), - .optional(let metadata): - walkNestedEnumPayloadFieldOffsets(of: metadata, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, depth: depth, enclosingMetatypes: nestedEnclosingMetatypes) - default: + switch nestedFieldOffsetLevel(of: metatype) { + case .structFields(let fields): + for field in fields { + let absoluteOffset = baseOffset + field.relativeOffset + configuration.expandedFieldOffsetComment(fieldName: field.fieldName, typeName: field.typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: field.isLast) + if let childMetatype = field.childMetatype { + walkNestedExpandedFieldOffsets(of: childMetatype, baseOffset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors + [field.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + } + } + case .enumPayloads(let payloads): + for payload in payloads { + configuration.expandedFieldOffsetComment(fieldName: payload.caseName, typeName: payload.typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: payload.isLast) + if payload.descends { + walkNestedExpandedFieldOffsets(of: payload.payloadMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors + [payload.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + } + } + case .notExpanded: SemanticString() } } @@ -267,61 +293,81 @@ struct RuntimeFieldLayoutBackend { #log(.info, "walkNestedExpandedFieldOffsets found \(metatype, privacy: .public) already open on the current path — cutting the cycle") } - @SemanticStringBuilder - private func walkNestedStructFieldOffsets(of metadata: StructMetadata, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int, enclosingMetatypes: Set) -> SemanticString { - if let descriptor = try? metadata.structDescriptor(in: .inProcess), - let nestedFieldOffsets = try? metadata.fieldOffsets(for: descriptor, in: .inProcess), - let nestedFieldRecords = try? descriptor.fieldDescriptor(in: .inProcess).records(in: .inProcess) { - let fieldEntries = Array(zip(nestedFieldRecords, nestedFieldOffsets)) - for (fieldIndex, (nestedFieldRecord, nestedRelativeOffset)) in fieldEntries.enumerated() { - if let fieldName = try? nestedFieldRecord.fieldName(in: .inProcess) { - let absoluteOffset = baseOffset + Int(nestedRelativeOffset) - let isLastField = fieldIndex == fieldEntries.count - 1 - let nestedMangledTypeName = try? nestedFieldRecord.mangledTypeName(in: .inProcess) - let typeName = nestedTypeName(for: nestedMangledTypeName, parentMetadata: metadata) - configuration.expandedFieldOffsetComment(fieldName: fieldName, typeName: typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: isLastField) - - if let nestedMangledTypeName, - let resolvedMetatype = resolveNestedMetatype(for: nestedMangledTypeName, parentMetadata: metadata) { - walkNestedExpandedFieldOffsets(of: resolvedMetatype, baseOffset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors + [isLastField], depth: depth + 1, enclosingMetatypes: enclosingMetatypes) - } - } + /// One level of the walk for `metatype`, built on first use and memoized + /// for the process. Building reads only the metatype's own metadata — the + /// helpers it calls touch no state of this backend — which is what makes + /// the level shareable across every type, image and printer. + private func nestedFieldOffsetLevel(of metatype: Any.Type) -> NestedFieldOffsetLevel { + NestedFieldOffsetLevelMemo.level(for: metatype) { + guard let wrapper = try? StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess) else { + return .notExpanded + } + switch wrapper { + case .struct(let metadata): + return .structFields(nestedStructFields(of: metadata)) + case .enum(let metadata), + .optional(let metadata): + return .enumPayloads(nestedEnumPayloads(of: metadata)) + default: + return .notExpanded } } } - @SemanticStringBuilder - private func walkNestedEnumPayloadFieldOffsets(of metadata: EnumMetadata, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int, enclosingMetatypes: Set) -> SemanticString { - if let descriptor = try? metadata.enumDescriptor(in: .inProcess), - descriptor.hasPayloadCases, - let records = try? descriptor.fieldDescriptor(in: .inProcess).records(in: .inProcess) { - let payloadRecords = Array(records.prefix(descriptor.numberOfPayloadCases)) - for (payloadIndex, payloadRecord) in payloadRecords.enumerated() { - if let mangledTypeName = try? payloadRecord.mangledTypeName(in: .inProcess), - !mangledTypeName.isEmpty, - let resolvedMetatype = resolveNestedMetatype(for: mangledTypeName, parentMetadata: metadata) { - let fieldName = (try? payloadRecord.fieldName(in: .inProcess)) ?? "payload" - let typeName = nestedTypeName(for: mangledTypeName, parentMetadata: metadata) - let isLastPayload = payloadIndex == payloadRecords.count - 1 - configuration.expandedFieldOffsetComment(fieldName: fieldName, typeName: typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: isLastPayload) - // An indirect case stores a `Builtin.NativeObject` box - // reference, not the declared payload laid out inline — so - // the payload's own fields are not at these offsets and - // descending into them would report memory that is not - // there. It is also the only way a value-type field graph - // can be cyclic at all (an inline self-reference would be - // infinitely sized and would not compile), which is what - // made `DVTIconKit`'s icon-spec tree explode here. - // `enumPayloadSize` / `enumPayloadExtraInhabitantCount` - // already treat the flag this way; this walk was the - // outlier. Same call as a class reference: print the case, - // stop at the pointer. - if !payloadRecord.flags.contains(.isIndirectCase) { - walkNestedExpandedFieldOffsets(of: resolvedMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors + [isLastPayload], depth: depth + 1, enclosingMetatypes: enclosingMetatypes) - } - } - } - } + private func nestedStructFields(of metadata: StructMetadata) -> [NestedFieldOffsetLevel.StructField] { + guard let descriptor = try? metadata.structDescriptor(in: .inProcess), + let nestedFieldOffsets = try? metadata.fieldOffsets(for: descriptor, in: .inProcess), + let nestedFieldRecords = try? descriptor.fieldDescriptor(in: .inProcess).records(in: .inProcess) + else { return [] } + let fieldEntries = Array(zip(nestedFieldRecords, nestedFieldOffsets)) + var fields: [NestedFieldOffsetLevel.StructField] = [] + for (fieldIndex, (nestedFieldRecord, nestedRelativeOffset)) in fieldEntries.enumerated() { + guard let fieldName = try? nestedFieldRecord.fieldName(in: .inProcess) else { continue } + let nestedMangledTypeName = try? nestedFieldRecord.mangledTypeName(in: .inProcess) + fields.append(NestedFieldOffsetLevel.StructField( + fieldName: fieldName, + typeName: nestedTypeName(for: nestedMangledTypeName, parentMetadata: metadata), + relativeOffset: Int(nestedRelativeOffset), + childMetatype: nestedMangledTypeName.flatMap { resolveNestedMetatype(for: $0, parentMetadata: metadata) }, + isLast: fieldIndex == fieldEntries.count - 1 + )) + } + return fields + } + + private func nestedEnumPayloads(of metadata: EnumMetadata) -> [NestedFieldOffsetLevel.EnumPayload] { + guard let descriptor = try? metadata.enumDescriptor(in: .inProcess), + descriptor.hasPayloadCases, + let records = try? descriptor.fieldDescriptor(in: .inProcess).records(in: .inProcess) + else { return [] } + let payloadRecords = Array(records.prefix(descriptor.numberOfPayloadCases)) + var payloads: [NestedFieldOffsetLevel.EnumPayload] = [] + for (payloadIndex, payloadRecord) in payloadRecords.enumerated() { + guard let mangledTypeName = try? payloadRecord.mangledTypeName(in: .inProcess), + !mangledTypeName.isEmpty, + let payloadMetatype = resolveNestedMetatype(for: mangledTypeName, parentMetadata: metadata) + else { continue } + payloads.append(NestedFieldOffsetLevel.EnumPayload( + caseName: (try? payloadRecord.fieldName(in: .inProcess)) ?? "payload", + typeName: nestedTypeName(for: mangledTypeName, parentMetadata: metadata), + payloadMetatype: payloadMetatype, + isLast: payloadIndex == payloadRecords.count - 1, + // An indirect case stores a `Builtin.NativeObject` box + // reference, not the declared payload laid out inline — so + // the payload's own fields are not at these offsets and + // descending into them would report memory that is not + // there. It is also the only way a value-type field graph + // can be cyclic at all (an inline self-reference would be + // infinitely sized and would not compile), which is what + // made `DVTIconKit`'s icon-spec tree explode here. + // `enumPayloadSize` / `enumPayloadExtraInhabitantCount` + // already treat the flag this way; this walk was the + // outlier. Same call as a class reference: print the case, + // stop at the pointer. + descends: !payloadRecord.flags.contains(.isIndirectCase) + )) + } + return payloads } private func resolveNestedMetatype(for mangledTypeName: MangledName, parentMetadata: some ValueMetadataProtocol) -> Any.Type? { diff --git a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift new file mode 100644 index 000000000..e77165c0a --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift @@ -0,0 +1,138 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftDeclarationRendering +import Demangling +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// The in-process nested field-offset expansion reads byte for byte the same +/// with its per-metatype memo as without it (evolution proposal +/// `nested-field-offset-memoization`). +/// +/// The memo keeps, per metatype, what one level of the walk reads — each +/// row's field name, type name and relative offset, the metatype one level +/// down, and whether the row draws the closing branch — and the walk keeps +/// everything positional. The fixture's `RecursiveIndirectFieldLayout` carries +/// every shape that could tell the two apart: a cycle, `indirect` payloads, +/// and `ValueSpec`'s last payload case `pair`, whose type does not +/// resolve, so the row before it keeps its `├──` although nothing follows. +@Suite(.serialized) +final class NestedFieldOffsetMemoizationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + private struct FirstProbe {} + + private struct SecondProbe {} + + /// Every stored field of every non-generic struct and class in the + /// fixture, rendered in process with field offsets, expanded field + /// offsets and type layouts on. + private func renderEveryStoredField() async throws -> [(label: String, rendered: String)] { + var configuration = DeclarationRenderConfiguration.demangleOptions(.default) + configuration.printFieldOffset = true + configuration.printExpandedFieldOffsets = true + configuration.printTypeLayout = true + + var renderings: [(label: String, rendered: String)] = [] + for (typeIndex, type) in try machOImage.swift.types.enumerated() { + let fieldDescriptor: FieldDescriptor + switch type { + case .struct(let structType): + guard !structType.descriptor.isGeneric else { continue } + fieldDescriptor = try structType.descriptor.fieldDescriptor(in: imageContext) + case .class(let classType): + guard !classType.descriptor.isGeneric else { continue } + fieldDescriptor = try classType.descriptor.fieldDescriptor(in: imageContext) + case .enum: + continue + } + let renderer = FieldLayoutRenderer(type: type, metadata: nil, machO: machOImage, configuration: configuration) + let fieldOffsets = renderer.fieldOffsets + for (fieldIndex, record) in try fieldDescriptor.records(in: imageContext).enumerated() { + let mangledTypeName = try record.mangledTypeName(in: imageContext) + let rendered = try await renderer.storedFieldComments(forFieldAtIndex: fieldIndex, mangledTypeName: mangledTypeName, fieldOffsets: fieldOffsets) + let fieldName = (try? record.fieldName(in: imageContext)) ?? "#\(fieldIndex)" + renderings.append(("type \(typeIndex) field \(fieldName)", rendered.string)) + } + } + return renderings + } + + private static func mismatches(between expected: [(label: String, rendered: String)], and actual: [(label: String, rendered: String)]) -> [String] { + guard expected.count == actual.count else { + return ["rendered \(actual.count) fields, expected \(expected.count)"] + } + return zip(expected, actual).compactMap { expectedRendering, actualRendering in + expectedRendering.rendered == actualRendering.rendered ? nil : "\(expectedRendering.label):\n\(actualRendering.rendered)\n--- expected ---\n\(expectedRendering.rendered)" + } + } + + @Test func memoizedExpansionReadsAsTheUnmemoizedOne() async throws { + RuntimeFieldLayoutMemo.removeAll() + let unmemoized = try await NestedFieldOffsetLevelMemo.$isBypassed.withValue(true) { + try await renderEveryStoredField() + } + // The first pass builds the levels, the second reads them all back. + let firstMemoized = try await renderEveryStoredField() + let secondMemoized = try await renderEveryStoredField() + + let expandedRowCount = unmemoized.reduce(0) { count, rendering in + count + rendering.rendered.components(separatedBy: "── ").count - 1 + } + #expect(expandedRowCount > 100, "the fixture should expand plenty of nested rows; got \(expandedRowCount)") + let mismatches = Self.mismatches(between: unmemoized, and: firstMemoized) + Self.mismatches(between: unmemoized, and: secondMemoized) + #expect(mismatches.isEmpty, "\(mismatches.prefix(3).joined(separator: "\n\n"))") + } + + /// The row before an unresolved last payload keeps the branch it drew + /// without the memo, read from a cold memo and from a warm one alike. + @Test func aRowBeforeAnUnresolvedLastPayloadKeepsItsOpenBranch() async throws { + RuntimeFieldLayoutMemo.removeAll() + let unmemoized = try await NestedFieldOffsetLevelMemo.$isBypassed.withValue(true) { + try await renderEveryStoredField() + } + let memoized = try await renderEveryStoredField() + let referenceRows = unmemoized.flatMap { rendering in + rendering.rendered.split(separator: "\n").filter { $0.contains("── reference (") } + } + #expect(!referenceRows.isEmpty, "ValueSpec.reference should be expanded somewhere in the fixture") + #expect(referenceRows.allSatisfy { $0.contains("├── reference (") }, "\(referenceRows)") + #expect(Self.mismatches(between: unmemoized, and: memoized).isEmpty) + } + + @Test func aLevelIsBuiltOnceUntilTheMemoIsCleared() { + RuntimeFieldLayoutMemo.removeAll() + var buildCount = 0 + let build: () -> NestedFieldOffsetLevel = { + buildCount += 1 + return .notExpanded + } + _ = NestedFieldOffsetLevelMemo.level(for: FirstProbe.self, building: build) + _ = NestedFieldOffsetLevelMemo.level(for: FirstProbe.self, building: build) + #expect(buildCount == 1) + + RuntimeFieldLayoutMemo.removeAll() + _ = NestedFieldOffsetLevelMemo.level(for: FirstProbe.self, building: build) + #expect(buildCount == 2) + } + + /// A host that loads an image while a level is being built clears the + /// memo in between; the level built from the old state must not land in + /// the cleared memo. + @Test func aLevelBuiltAcrossRemoveAllIsNotStored() { + RuntimeFieldLayoutMemo.removeAll() + var buildCount = 0 + _ = NestedFieldOffsetLevelMemo.level(for: SecondProbe.self) { + buildCount += 1 + RuntimeFieldLayoutMemo.removeAll() + return .notExpanded + } + _ = NestedFieldOffsetLevelMemo.level(for: SecondProbe.self) { + buildCount += 1 + return .notExpanded + } + #expect(buildCount == 2) + } +} diff --git a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift index a00c32bc2..0bea5e352 100644 --- a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift +++ b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift @@ -103,6 +103,38 @@ struct AnonymousContextPrivateDiscriminatorTests { #expect(mismatches.isEmpty, "\(mismatches.count) of \(comparedCount) differ:\n\(mismatches.joined(separator: "\n"))") } + /// The in-process lookup keeps each anonymous context's discriminator by + /// address (evolution proposal `nested-field-offset-memoization`). For + /// every private Swift class AppKit defines directly in an anonymous + /// context, the first answer and the memoized second one must both be the + /// discriminator its Objective-C runtime name spells. + @Test(.enabled(if: runsOnMacOS26OrLater, "the anchor class ships with macOS 26's AppKit")) + func inProcessDiscriminatorsMatchTheObjCRuntimeNameBeforeAndAfterMemoization() throws { + let machOImage = try Self.loadedAppKitImage() + var comparedCount = 0 + var mismatches: [String] = [] + for classObject in machOImage.objcImplementationClassObjects() ?? [] where classObject.isSwiftStable { + guard let readOnlyData = machOImage.instanceReadOnlyData(of: classObject), + let runtimeName = machOImage.className(of: readOnlyData), + runtimeName.hasPrefix("_Tt"), + let expectedDiscriminator = try demangleAsNodeTransient(runtimeName).first(of: .privateDeclName)?.children.first?.text + else { continue } + let metadata: ClassMetadataObjCInterop = try machOImage.readWrapperElement(offset: classObject.offset) + let classDescriptor = try #require(try metadata.descriptor(in: machOImage.context), "\(runtimeName) has no class descriptor") + guard let anonymousContextDescriptor = try classDescriptor.parent(in: machOImage.context)?.resolved?.anonymousContextDescriptor else { continue } + let anonymousContextAddress = machOImage.ptr.advanced(by: anonymousContextDescriptor.offset) + + let firstDiscriminator = SymbolicDemangler.privateDiscriminator(forAnonymousContextAt: anonymousContextAddress) + let memoizedDiscriminator = SymbolicDemangler.privateDiscriminator(forAnonymousContextAt: anonymousContextAddress) + comparedCount += 1 + if firstDiscriminator != expectedDiscriminator || memoizedDiscriminator != expectedDiscriminator { + mismatches.append("\(runtimeName): expected \(expectedDiscriminator), first \(firstDiscriminator ?? "nil"), memoized \(memoizedDiscriminator ?? "nil")") + } + } + #expect(comparedCount > 50, "AppKit on macOS 26 defines dozens of private Swift classes at file scope") + #expect(mismatches.isEmpty, "\(mismatches.count) of \(comparedCount) differ:\n\(mismatches.joined(separator: "\n"))") + } + // MARK: - Helpers /// The nominal's fully qualified name, private discriminators spelled out. From 66f3f6047a0afbcf9a9458de52219b85bf710249 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 16:44:58 +0800 Subject: [PATCH 04/49] docs: propose marking nested definitions in a parent's print RuntimeViewer prints a nested type twice for its search corpus: inline in its parent's print and again as its own object. Its timing probe puts that at about two fifths of the print time on Foundation and SwiftUI, so it wants to cut each child's text out of the parent's print instead. NestedDeclaration flattens a child's atoms into the parent and leaves no boundary to cut at. draft-nested-definition-regions proposes a marksNestedDefinitions switch that wraps every inlined nested definition in a DefinitionRegion keyed by the mangled name of its name node (what RuntimeViewer names the object by), a matching region table and line-wise de-indentation in swift-semantic-string, and a tested promise that a definition printed inline reads byte for byte as printed alone apart from indentation. It first needs a protocol nested in an extension to stop printing its default-implementation extensions inside the enclosing extension's braces. Draft only: four choices are left to the user, and nothing is implemented before it is accepted. --- Documentations/Evolutions/README.md | 1 + .../draft-nested-definition-regions.md | 64 +++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 66 insertions(+) create mode 100644 Documentations/Evolutions/draft-nested-definition-regions.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index e7cab50dc..b692cda6e 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -67,5 +67,6 @@ | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | | draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | In Progress | | draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | In Progress | +| draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | Draft | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | diff --git a/Documentations/Evolutions/draft-nested-definition-regions.md b/Documentations/Evolutions/draft-nested-definition-regions.md new file mode 100644 index 000000000..1a106be80 --- /dev/null +++ b/Documentations/Evolutions/draft-nested-definition-regions.md @@ -0,0 +1,64 @@ +# Draft - 在父定义的打印结果里标出嵌套子定义的边界 + +- **状态**: Draft +- **创建日期**: 2026-10-01 +- **最后更新**: 2026-10-01 +- **所属愿景**: 无 +- **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(同一手法:区域编码在原子的 `identifier` 里,冻结后分离成一张表);RuntimeViewer 的 `draft-find-navigator` §1.1 方案 D(使用方);swift-semantic-string 的设计记录 `docs/VisibilityRegions.md` +- **实现分支 / PR**: 待定(起草于 `feature/runtime-viewer/find-navigator`) +- **配套文档**: 无 + +## 摘要 + +RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的打印里内联了一遍,嵌套类型作为自己的对象又单独打印一遍。它的计时探针量出这部分在 Foundation 和 SwiftUI 上都占打印时间约四成(Foundation 只打顶层 2.23 s、全打 3.72 s;SwiftUI 31.15 s 对 51.95 s),超过它的提案定的 20% 门槛,所以改走方案 D:子对象不再单独打印主体,而是从父对象的打印结果里切出属于自己的那一段,去掉一级缩进后直接用。今天切不出来:`NestedDeclaration` 把子定义的原子摊平进父定义,不留边界。本提案让打印器在一个新开关下,给每个内联打印的嵌套子定义标上边界和身份(手法同可见性区域),并承诺、用测试钉住「同一个定义内联打印和单独打印,除缩进外逐字节相同」。 + +## 方案 + +### 改动位置 + +- **swift-semantic-string**(新功能,另一个仓库):在 `Sources/Semantic/Visibility/VisibilityRegion.swift` 旁边加一个 `DefinitionRegion` 组件,把一个身份字符串编码进内容里每个原子的 `identifier`,用与 `VisibilityTag` 不同的分隔符,两种标记可以叠在同一个原子上;冻结后用一个分离函数(与 `VisibilityRegionTable.swift:59` 的 `separatingVisibilityRegions()` 同形)读回成一张表,记录每个区域的身份、UTF-8 范围和嵌套关系,并还原原子原来的 `identifier`。再加两个通用操作:把冻结字符串连同它的可见性区域表切到某个区域;按行去掉开头 N 级缩进(每级 4 个空格),span 与区域表跟着平移。 +- **MachOSwiftSection**: + - `SwiftDeclarationPrintConfiguration` 加开关 `marksNestedDefinitions`(默认 `false`)。关着时输出与今天逐字节相同。 + - `SwiftDeclarationPrinter.swift:289` 与 `:303`(类型里的嵌套类型、嵌套协议)、`:436` 与 `:450`(extension 里的类型、协议):开关打开时,把每个 `NestedDeclaration` 里那次 `printTypeDefinition` / `printProtocolDefinition` 的结果包进 `DefinitionRegion`。身份用名字节点的 mangled name,即 `mangleAsString(child.typeName.node)` 或 `mangleAsString(child.protocolName.node)`——RuntimeViewer 的 `RuntimeObject.name` 正是这个值,拿到就能对上对象,不需要另建映射。 + - `SwiftDeclarationPrinter.swift:378`:先修一个会破坏下面契约的既有问题。嵌在 extension 里的协议,索引器只给它设 `extensionContext`(`SwiftDeclarationIndexer.swift:651`),`parent` 留空,于是打印时它会在原地、以第 1 级接着打印自己的默认实现扩展,结果落在外层 extension 的大括号里面、顶格(Foundation 的 `extension __C.NSNotificationCenter { protocol AsyncMessage {…} }` 就是这样,生成的 Swift 不合法)。这几行内联时与单独打印时缩进相同,按行去缩进必然对不上。修法见「需要你定的」第 1 条。 +- **不动**:单独打印的输出、开关关着时的全部输出、事件、导出过滤、`displayParentName`。 + +### 契约:内联与单独打印除缩进外逐字节相同 + +对一个嵌套深度为 d 的定义(直接嵌在顶层定义里时 d = 1),它在父定义里的那段区域按行去掉开头 d 级缩进后,必须与单独打印它(同一 printer 配置、`level` 为 1、`displayParentName` 为 `false`)的冻结结果完全相同:文本、span、`identifier`,以及标记模式下的可见性区域表。空行没有缩进,原样保留。 + +需要特别处理的地方: + +- **多行原子**:enum layout 的逐 case 注释是一个原子、多行,每行自带缩进前缀(`DeclarationRenderConfiguration.swift:281` 的 `caseProjection.description(indent:prefix:)`)。去缩进要进到原子内部逐行做,不能只删独立的缩进原子;这正是把去缩进放进 swift-semantic-string 的原因。 +- **transformer**:`EnumLayoutCaseTransformer`、`SpareBitAnalysisTransformer` 等闭包收到 `indentation` 自己决定怎么缩进。契约只覆盖「每行按 `indentation` 加前缀」的 transformer:本库 `OutputTransformer` 的模板都是这样,测试钉住;调用方自己写的任意闭包做不到保证,文档写明。 +- **展开字段偏移**:每行用 `Indent(level: baseIndentation)` 单独成原子(`DeclarationRenderConfiguration.swift:210`),按行去缩进天然成立,测试照样覆盖。 + +### 嵌套与回退 + +区域可以嵌套:孙定义的区域在子定义的区域里,表里记下父子关系,RuntimeViewer 去缩进时按孙定义自己的深度来。子定义打印失败时,`:289` 等循环的逐子 catch 会把它整个丢掉,于是表里没有它的区域;父定义打印失败则整份都没有。两种情况都由 RuntimeViewer 回退到单独打印,本库不做额外处理。 + +### 代价 + +只在开关打开时有:每个内联的嵌套子定义多一次 remangle 和一层原子标记,分离时多扫一遍。RuntimeViewer 换来的是不再单独打印嵌套子定义的主体(约四成打印时间)。 + +### 验证 + +- 契约测试:SymbolTestsCore 里每个有嵌套子定义的类型,逐层取出每个子定义的区域,去缩进后与单独打印比较(文本、span、`identifier`、可见性区域表)。配置覆盖:普通打印;标记模式全开(含 enum layout 与展开字段偏移);`OutputTransformer` 模板全开;进程内与文件两种读取方式。另测区域表的嵌套结构与身份。 +- 嵌在 extension 里的协议:先确认 fixture 里有没有;没有就用现场编译的小 fixture 测,不改 SymbolTestsCore(改它会牵动全部基线)。 +- 开关关着:渲染 A/B 逐字节一致(AGENTS.md 必跑);第 1 条修复会改变「嵌在 extension 里的协议」所在 interface 的输出,A/B 里这类差异要逐处核对并在决策日志里列出。 +- swift-semantic-string:组件、分离、切片、按行去缩进(含多行原子与空行)的单元测试,走它自己的流程。 + +### 需要你定的 + +1. **嵌在 extension 里的协议,默认实现扩展打在哪**(推荐 a): + - a. `extensionContext` 不为空的协议不再在原地打印默认实现扩展;顶层 interface 改在 extensions 区块里打印它们(今天这些扩展被标成 `isAttachedToProtocolDefinition`,在 extensions 区块里跳过)。生成的 Swift 变合法,内联与单独打印也一致;RuntimeViewer 按方案 D 本来就把子对象自己的扩展另外接在后面。 + - b. 保留原地打印,只把缩进改对。Swift 里 extension 不能写在另一个 extension 的大括号里,改缩进也还是不合法,不推荐。 +2. **开关**(推荐单独的 `marksNestedDefinitions`):与 `marksOptionalContent` 互不相干,宿主可以只开一个;RuntimeViewer 两个都开。另一种是并进 `marksOptionalContent`,少一个开关但把两件事绑死。 +3. **身份**(推荐名字节点的 mangled name):与 RuntimeViewer 的对象名一致。另一种是描述符偏移,更便宜,但 RuntimeViewer 的对象不带偏移,得另建映射。 +4. **切片与去缩进放哪**(推荐 swift-semantic-string):它是通用的文本操作,要和可见性区域表一起平移,放在定义那张表的库里最不容易错;放在 RuntimeViewer 也行,但它得自己理解两种标记的编码。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-01 | Created as Draft | RuntimeViewer 的计时探针量出嵌套对象占打印时间约四成(Release,`72913c3d`;Foundation 只打顶层 2.23 s、全打 3.72 s,SwiftUI 31.15 s 对 51.95 s,libswiftCore 15–22%),超过其提案定的 20% 门槛,指向方案 D。用户在 RuntimeViewer 的会话里对「要让 MachOSwiftSection 那边的会话起草这份上游提案吗?」选了「让它起草提案」;只起草,审过置 `Accepted` 之前不写实现。需求三条由 RuntimeViewer 会话转来:子定义原子的边界标记且可嵌套、内联与单独打印除缩进外逐字节相同并用测试钉住(含 enum layout 多行原子、展开字段偏移、transformer 三种情况)、失败由 RuntimeViewer 回退。 | diff --git a/Documentations/README.md b/Documentations/README.md index 71e68979d..b4e42b4c6 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -157,6 +157,7 @@ selects names using each access's offset and width. | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | | [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | +| [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(Draft)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [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 的数量与内存实测。 | From f9724cf258d14f7d4ed3bb886d33ea8c0d6f2628 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 17:15:24 +0800 Subject: [PATCH 05/49] docs: accept the nested-definition regions proposal with every recommended choice --- Documentations/Evolutions/README.md | 2 +- Documentations/Evolutions/draft-nested-definition-regions.md | 3 ++- Documentations/README.md | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index b692cda6e..f1b6f7760 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -67,6 +67,6 @@ | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | | draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | In Progress | | draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | In Progress | -| draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | Draft | +| draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | Accepted | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | diff --git a/Documentations/Evolutions/draft-nested-definition-regions.md b/Documentations/Evolutions/draft-nested-definition-regions.md index 1a106be80..2d97808dc 100644 --- a/Documentations/Evolutions/draft-nested-definition-regions.md +++ b/Documentations/Evolutions/draft-nested-definition-regions.md @@ -1,6 +1,6 @@ # Draft - 在父定义的打印结果里标出嵌套子定义的边界 -- **状态**: Draft +- **状态**: Accepted - **创建日期**: 2026-10-01 - **最后更新**: 2026-10-01 - **所属愿景**: 无 @@ -62,3 +62,4 @@ RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的 | 日期 | 决定 | 理由 | |------|------|------| | 2026-10-01 | Created as Draft | RuntimeViewer 的计时探针量出嵌套对象占打印时间约四成(Release,`72913c3d`;Foundation 只打顶层 2.23 s、全打 3.72 s,SwiftUI 31.15 s 对 51.95 s,libswiftCore 15–22%),超过其提案定的 20% 门槛,指向方案 D。用户在 RuntimeViewer 的会话里对「要让 MachOSwiftSection 那边的会话起草这份上游提案吗?」选了「让它起草提案」;只起草,审过置 `Accepted` 之前不写实现。需求三条由 RuntimeViewer 会话转来:子定义原子的边界标记且可嵌套、内联与单独打印除缩进外逐字节相同并用测试钉住(含 enum layout 多行原子、展开字段偏移、transformer 三种情况)、失败由 RuntimeViewer 回退。 | +| 2026-10-01 | Accepted;四个待定项都按推荐 | 用户在 RuntimeViewer 会话里选定:嵌在 extension 里的协议的默认实现扩展改到顶层 extensions 区块打印;单独开关 `marksNestedDefinitions`;身份用名字节点的 mangled name(RuntimeViewer 核实 `RuntimeSwiftSection.swift:275` 以 `mangleAsString(typeDefinition.typeName.node)` 作 `RuntimeObject.name`,协议在 `:258`、扩展在 `:237`);切片与去缩进放进 swift-semantic-string。随后在本仓库的会话里直接确认「确认,排在遍历修复之后」:先做 swift-demangling 的节点遍历修复(并行打印的引用计数争用),再实现本提案。 | diff --git a/Documentations/README.md b/Documentations/README.md index b4e42b4c6..873e07e26 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -157,7 +157,7 @@ selects names using each access's offset and width. | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | | [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | -| [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(Draft)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | +| [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(Accepted)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [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 的数量与内存实测。 | From 0a0842111ef4d7435cdb05d9290fc329faa648d0 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 17:17:57 +0800 Subject: [PATCH 06/49] docs: record the RuntimeViewer timing of concurrent printing and the memo --- .../Evolutions/draft-concurrent-definition-printing.md | 1 + .../Evolutions/draft-nested-field-offset-memoization.md | 1 + 2 files changed, 2 insertions(+) diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/draft-concurrent-definition-printing.md index ba47e023f..5e78641e8 100644 --- a/Documentations/Evolutions/draft-concurrent-definition-printing.md +++ b/Documentations/Evolutions/draft-concurrent-definition-printing.md @@ -72,3 +72,4 @@ | 2026-10-01 | TSan 用 release 配置跑 | debug 下 `--sanitize=thread` 在加载 fixture 时就 trap:MachOKit `FileHandle+.swift:194` 用 `load(as:)` 读 `Data` 的内联字节,TSan 改了栈布局,地址落到奇数,标准库的 `_debugPrecondition` 对齐检查触发。这是 MachOKit 的既有问题(应改用 `loadUnaligned`),不在本仓库;release 下该检查被编译掉,TSan 照样检测竞争。 | | 2026-10-01 | 验证:先红后绿 | 改动前:不开 TSan 跑压力测试,进程直接崩在 `SwiftDeclarationPrinter.swift:237`(`for attribute in typeDefinition.attributes`,另一个任务刚给 `attributes` 重新赋值,旧数组被释放后又被读);release + TSan 报出 28 条数据竞争,全部落在 `TypeDefinition.index` 内部(成员构建、thunk 属性、wrapped property)、打印器写 `attributes` 那段,以及读写成员数组(含 `detachedFromSharedTable()` 新建的 `SymbolTable` 被另一个任务无同步地读),`swift test` 退出码 1。改动后:debug 三个用例全过(约 9 秒);release + TSan 三个用例全过、0 条报告、退出码 0;`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1` 下通过(7.5 秒),再关掉大栈执行器(`MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR=0`)也通过(18 秒),说明阻塞等待不需要额外的池线程。 | | 2026-10-01 | 全量测试与渲染 A/B | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4):改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B:基线是改动前的 `4fd4049b`,两侧共用一份 `Package.resolved`,35 个依赖完全一致(其中 5 个是本地兄弟依赖),**92 对逐字节一致**——归档 cache 26.6 与 15.5 各 12 对、iOS 15.5–26.5 模拟器 44 对、MachOImage 腿 24 对。脚本写死的 `26.6.2` 归档目录在这台机器上叫 `26.6`,本轮用只改了这个常量的脚本副本跑。iOS 15.5 模拟器的 SwiftUI / WidgetKit 4 对两侧同样以 SIGTRAP 失败,记为 SKIPPED:本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后(上游 `7adae68` 开始校验 LINKEDIT 范围),导出信息为空(offset 0、size 0)的镜像让 `ExportTrie.init` 的强制解包崩溃,由 `ObjCAncestorResolver` 沿依赖闭包查导出表触发;仓库远程 pin 的 `0.52.103 ..< 0.53.0` 不含这个改动,与本提案无关。 | +| 2026-10-01 | 计时:串行下没有额外开销;宽度 14 的并行反而更慢,原因在 swift-demangling | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`):libswiftCore A 1.02/1.03 s、B 1.03/1.02 s;Foundation A 4.15/4.27 s、B 4.19/4.15 s;SwiftUI A 39.93/40.31 s、B 38.75/45.59 s(第二次只用了 0.93 核,按噪声计)——索引加锁在串行下看不出成本。宽度 14(同一来源,改前 = A + 宽度 1,改后 = B + 宽度 14):SwiftUI 串行 42–50 s,并行 61 s / 约 400 s CPU,机器越空越慢(负载约 6 时 204 s / 2599 s CPU)。采样里热点是 `ExtensionDefinition` 索引体里按 conformance 找符号的 `first(of:)`:`NodeReference` 每复制一次都 retain 共享的 `NodeStore`,14 个线程同时给同一个对象加减引用计数。修在 swift-demangling(用户选「上游改遍历」,提案 `draft-unretained-kind-queries`),RuntimeViewer 在修好之前保持宽度 1。 | diff --git a/Documentations/Evolutions/draft-nested-field-offset-memoization.md b/Documentations/Evolutions/draft-nested-field-offset-memoization.md index 62aa1aea5..b2de5a181 100644 --- a/Documentations/Evolutions/draft-nested-field-offset-memoization.md +++ b/Documentations/Evolutions/draft-nested-field-offset-memoization.md @@ -93,3 +93,4 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 | 2026-10-01 | 判别符记忆化:把 `privateDiscriminatorIdentifier` 改成私有协议 `SymbolLookupContext` 的 requirement,只有 `InProcessContext` 换成查表 | 原来它是协议扩展里的方法,经 `as? SymbolLookupContext` 调用时静态派发,`InProcessContext` 覆盖不了。只记 `identifier` 的文本,命中时重建同样的节点,「没有判别符」也记;表放在 `SymbolicDemanglerCache` 的进程级存储里。不提供清除入口:查的是已经在内存里的匿名上下文,答案不会变。 | | 2026-10-01 | 测试不新建 fixture;加一个只给测试用的 `NestedFieldOffsetLevelMemo.isBypassed`(`package` 级 `@TaskLocal`) | SymbolTestsCore 的 `ValueSpec` 已经同时有:最后一个 payload `pair` 解析不出(前一行 `reference` 因此画 `├──`)、`indirect` payload、`ReferenceSpec` ↔ `ValueSpec` 的环;改 SymbolTestsCore 会牵动全部基线。「末字段名读失败」编译器产不出来,靠构造保证:记录里的 `isLast` 与原来按同一个表达式、对全部字段记录计数。绕过开关是提案「关掉缓存的路径」所需,`@TaskLocal` 只影响当前任务树,不碰并行的其它套件。判别符缓存的测试以 AppKit 私有类的 Objective-C 运行时名字为独立真值,冷热两次都比。 | | 2026-10-01 | 验证 | 新测试与相关既有套件(嵌套展开、深度上限、特化字段类型、可见性区域投影、两个判别符套件、并发打印)全过。全量 `swift test --skip IntegrationTests` 2168 个测试全过,原始退出码 0,known issue 仍是 `SymbolicManglingIndexTests` 那一条。release + TSan 跑 `ConcurrentDefinitionPrintingTests`(标记模式打印含展开字段偏移,多线程同时查 memo)与 `NestedFieldOffsetMemoizationTests`:0 条报告,退出码 0。渲染 A/B 对 `9f5ffa92`(并发打印那份):92 对逐字节一致,SKIPPED 的仍是 iOS 15.5 模拟器 SwiftUI / WidgetKit 那 4 对(本地 MachOKit `next` 的既有问题)。A/B 的 MachOImage 腿默认不开展开字段偏移,所以另用 `RenderingVerificationTests` 打开全部选项(含 `expandedFieldOffsets`)对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍:16 对逐字节一致,进程内那几份带 17 到约 7800 行展开行。SwiftUI / SwiftUICore 没放进这一轮:该工具记着它们在开展开字段偏移时有既有的栈溢出。`NestedFieldOffsetMemoizationTests` 加进 CI 的主过滤列表。 | +| 2026-10-01 | 「改后」计时:省 4–10% | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`;用 `nm` 确认只有 C 带 `RuntimeFieldLayoutMemo`):libswiftCore B 1.03/1.02 s → C 0.98/0.99 s(−4%);Foundation B 4.19/4.15 s → C 3.80/3.98 s(CPU 3.80/3.81,约 −9%);SwiftUI B 38.75/45.59 s → C 36.71/37.94 s(CPU 35.85/37.86,约 −7% 到 −10%)。与「展开字段偏移约占打印时间一成」的分项一致。 | From 3953bf471069225f7d0de48dad0af65fdc8c53a4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 18:29:38 +0800 Subject: [PATCH 07/49] docs: record the swift-demangling contention fix and what still contends --- .../Evolutions/draft-concurrent-definition-printing.md | 1 + Documentations/Internal/ProjectEvolutionLog.md | 1 + 2 files changed, 2 insertions(+) diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/draft-concurrent-definition-printing.md index 5e78641e8..63341a1dc 100644 --- a/Documentations/Evolutions/draft-concurrent-definition-printing.md +++ b/Documentations/Evolutions/draft-concurrent-definition-printing.md @@ -73,3 +73,4 @@ | 2026-10-01 | 验证:先红后绿 | 改动前:不开 TSan 跑压力测试,进程直接崩在 `SwiftDeclarationPrinter.swift:237`(`for attribute in typeDefinition.attributes`,另一个任务刚给 `attributes` 重新赋值,旧数组被释放后又被读);release + TSan 报出 28 条数据竞争,全部落在 `TypeDefinition.index` 内部(成员构建、thunk 属性、wrapped property)、打印器写 `attributes` 那段,以及读写成员数组(含 `detachedFromSharedTable()` 新建的 `SymbolTable` 被另一个任务无同步地读),`swift test` 退出码 1。改动后:debug 三个用例全过(约 9 秒);release + TSan 三个用例全过、0 条报告、退出码 0;`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1` 下通过(7.5 秒),再关掉大栈执行器(`MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR=0`)也通过(18 秒),说明阻塞等待不需要额外的池线程。 | | 2026-10-01 | 全量测试与渲染 A/B | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4):改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B:基线是改动前的 `4fd4049b`,两侧共用一份 `Package.resolved`,35 个依赖完全一致(其中 5 个是本地兄弟依赖),**92 对逐字节一致**——归档 cache 26.6 与 15.5 各 12 对、iOS 15.5–26.5 模拟器 44 对、MachOImage 腿 24 对。脚本写死的 `26.6.2` 归档目录在这台机器上叫 `26.6`,本轮用只改了这个常量的脚本副本跑。iOS 15.5 模拟器的 SwiftUI / WidgetKit 4 对两侧同样以 SIGTRAP 失败,记为 SKIPPED:本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后(上游 `7adae68` 开始校验 LINKEDIT 范围),导出信息为空(offset 0、size 0)的镜像让 `ExportTrie.init` 的强制解包崩溃,由 `ObjCAncestorResolver` 沿依赖闭包查导出表触发;仓库远程 pin 的 `0.52.103 ..< 0.53.0` 不含这个改动,与本提案无关。 | | 2026-10-01 | 计时:串行下没有额外开销;宽度 14 的并行反而更慢,原因在 swift-demangling | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`):libswiftCore A 1.02/1.03 s、B 1.03/1.02 s;Foundation A 4.15/4.27 s、B 4.19/4.15 s;SwiftUI A 39.93/40.31 s、B 38.75/45.59 s(第二次只用了 0.93 核,按噪声计)——索引加锁在串行下看不出成本。宽度 14(同一来源,改前 = A + 宽度 1,改后 = B + 宽度 14):SwiftUI 串行 42–50 s,并行 61 s / 约 400 s CPU,机器越空越慢(负载约 6 时 204 s / 2599 s CPU)。采样里热点是 `ExtensionDefinition` 索引体里按 conformance 找符号的 `first(of:)`:`NodeReference` 每复制一次都 retain 共享的 `NodeStore`,14 个线程同时给同一个对象加减引用计数。修在 swift-demangling(用户选「上游改遍历」,提案 `draft-unretained-kind-queries`),RuntimeViewer 在修好之前保持宽度 1。 | +| 2026-10-01 | swift-demangling 修好遍历(它的提案 0016,已快进合入它的 `next`,未推送、未发版);剩下的争用以后再说 | 用临时基准在沙盒里量(本分支的快照,只把 swift-demangling 换成修复分支):进程内打印 SwiftUI 的 17920 个定义,标记模式、一个共享 printer、`.utility` 有界任务组,每个宽度一个新进程,release,JHs-Mac-Studio-Ultra。改前:宽度 1 墙钟 37.74 s / CPU 37.77 s;宽度 14 墙钟 329.50 s / CPU 4446 s。改后:宽度 1 18.02 s / 18.08 s;宽度 4 8.87 s / 26.26 s;宽度 14 15.06–18.87 s / 约 165 s。串行本身也快了一倍:按 conformance 找符号的查询在单线程下同样是热点,省掉的是逐节点的引用计数和以 `NodeReference` 为元素的去重集合。改后在宽度 14 下再采样,剩下的争用在本库:`SymbolIndexStore.demangledNodeReference(for:in:)` 每查一个符号都经 `SharedCache.resolve` 取一次存储(同一把锁,`__ulock_wait2` 约 2750 个样本),以及 `ExtensionDefinition` 索引体里按 conformance 找符号时逐个造 `NodeReference`、retain 同一个 store。用户选择先做 `draft-nested-definition-regions`,这部分以后再说。全量 `swift test --skip IntegrationTests` 用修好的 swift-demangling 跑,2168 个全过(原始退出码 0)。RuntimeViewer 要拿到修复,构建需要解析到 swift-demangling 的 `next`。 | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index a9ce2805a..e3b743144 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2141,6 +2141,7 @@ - **关键决策**:**① 索引改成同步函数,经 `DefinitionIndexing` 只跑一次**:进程级一把 `@Mutex` 守着 in-flight 表和每个定义的 `hasCompletedIndexing`;首个调用者认领后在自己线程上跑完,其余在 promise 上阻塞等待并共享结果(复用 `SharedCacheBuildPromise`,载荷是 `Result`),抛错则回到未索引、下次重试。**② 不死锁靠两条前提**:索引体没有 `await`(编译器保证),索引体不索引别的定义(所有 `SharedCache` 都在下层模块,结构上够不到定义;认领或等待时若当前线程正在跑某个索引体就 `precondition` trap)。**③ 打印期不写定义**:类型级 attribute 改成打印时的局部变量,删掉 `TypeDefinition.attributes`(三个下游都不读它);`TypeAttributeInferrer` 里三处读 `TypeDefinition.extensions` 的死代码删掉,并写明被它掩盖的缺口:声明在扩展里的 `buildBlock` / `subscript(dynamicMember:)` / `dynamicallyCall` 识别不到。**④ 三个定义类标 `@unchecked Sendable`**,理由写在类型上;`SymbolicDemangler.isCacheEnabled` 改成 `static let`。**⑤ 约定**:AGENTS.md 那条「同版本内不能并行」改成「`MachOImage` 读者下打印可以并行,`MachOFile` 读者仍不行,`specialize(...)` 不在承诺内」。 - **落地模块**:SwiftDeclaration(`DefinitionIndexing`、三个定义类及其 `+Indexing`、`MutableDefinition` 的 requirement)、SwiftAttributeInference(`TypeAttributeInferrer`)、SwiftPrinting / SwiftInterface(打印器与 diff 渲染的两处 attribute、各处 `index(in:)` 调用)、SwiftInspection(`isCacheEnabled`)、MachOCaches(`SharedCacheBuildPromise` 的注释)。测试新增 `ConcurrentDefinitionPrintingTests`(CI 主过滤与单线程协作池两步都加了),其余测试去掉为定义不 `Sendable` 写的 `nonisolated(unsafe)` 绕法。 - **验证**:改动前压力测试不开 TSan 直接崩(`attributes` 数组被另一个任务重新赋值后又被读),release + TSan 报 28 条数据竞争;改动后 debug、release + TSan(0 条报告)、单线程协作池、单线程协作池且关掉大栈执行器都通过。debug 下用 TSan 会在 MachOKit 读 fixture 时被对齐检查拦下(MachOKit 的既有问题),所以 TSan 一律用 release。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4)改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B 对改动前的 `4fd4049b` 共 92 对逐字节一致(归档 cache 26.6 / 15.5、iOS 15.5–26.5 模拟器、MachOImage 腿);iOS 15.5 模拟器 SwiftUI / WidgetKit 的 4 对两侧同样崩溃,原因是本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后 `ExportTrie.init` 对空导出信息强制解包,与本批无关,细节见提案决策日志。 +- **后续**:RuntimeViewer 量出宽度 14 的并行打印比串行还慢。根因在 swift-demangling:按种类找节点的查询每访问一个节点都复制一次 `NodeReference`,每次都 retain 镜像共享的 store,14 个线程抢同一个引用计数。修在 swift-demangling(它的提案 0016,合入它的 `next`,未发版)。进程内打印 SwiftUI 全部定义:改前宽度 1 37.7 s、宽度 14 329.5 s;改后宽度 1 18.0 s、宽度 4 8.9 s、宽度 14 15–19 s。宽度 14 下剩下的争用在本库(`SymbolIndexStore` 每查一个符号都经 `SharedCache` 取一次存储,以及按 conformance 找符号时逐个造 `NodeReference`),用户决定以后再说,细节在提案决策日志。 - **关联文档**:[draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「版本内并行为什么不做」。 - **对应版本**:未发版。 From b99fb89d93fe1548eb7d7f8eb4d83ece5ca193cd Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 18:56:38 +0800 Subject: [PATCH 08/49] docs: record RuntimeViewer's timing with the swift-demangling contention fix --- .../Evolutions/draft-concurrent-definition-printing.md | 1 + Documentations/Internal/ProjectEvolutionLog.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/draft-concurrent-definition-printing.md index 63341a1dc..7f183ee52 100644 --- a/Documentations/Evolutions/draft-concurrent-definition-printing.md +++ b/Documentations/Evolutions/draft-concurrent-definition-printing.md @@ -74,3 +74,4 @@ | 2026-10-01 | 全量测试与渲染 A/B | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4):改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B:基线是改动前的 `4fd4049b`,两侧共用一份 `Package.resolved`,35 个依赖完全一致(其中 5 个是本地兄弟依赖),**92 对逐字节一致**——归档 cache 26.6 与 15.5 各 12 对、iOS 15.5–26.5 模拟器 44 对、MachOImage 腿 24 对。脚本写死的 `26.6.2` 归档目录在这台机器上叫 `26.6`,本轮用只改了这个常量的脚本副本跑。iOS 15.5 模拟器的 SwiftUI / WidgetKit 4 对两侧同样以 SIGTRAP 失败,记为 SKIPPED:本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后(上游 `7adae68` 开始校验 LINKEDIT 范围),导出信息为空(offset 0、size 0)的镜像让 `ExportTrie.init` 的强制解包崩溃,由 `ObjCAncestorResolver` 沿依赖闭包查导出表触发;仓库远程 pin 的 `0.52.103 ..< 0.53.0` 不含这个改动,与本提案无关。 | | 2026-10-01 | 计时:串行下没有额外开销;宽度 14 的并行反而更慢,原因在 swift-demangling | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`):libswiftCore A 1.02/1.03 s、B 1.03/1.02 s;Foundation A 4.15/4.27 s、B 4.19/4.15 s;SwiftUI A 39.93/40.31 s、B 38.75/45.59 s(第二次只用了 0.93 核,按噪声计)——索引加锁在串行下看不出成本。宽度 14(同一来源,改前 = A + 宽度 1,改后 = B + 宽度 14):SwiftUI 串行 42–50 s,并行 61 s / 约 400 s CPU,机器越空越慢(负载约 6 时 204 s / 2599 s CPU)。采样里热点是 `ExtensionDefinition` 索引体里按 conformance 找符号的 `first(of:)`:`NodeReference` 每复制一次都 retain 共享的 `NodeStore`,14 个线程同时给同一个对象加减引用计数。修在 swift-demangling(用户选「上游改遍历」,提案 `draft-unretained-kind-queries`),RuntimeViewer 在修好之前保持宽度 1。 | | 2026-10-01 | swift-demangling 修好遍历(它的提案 0016,已快进合入它的 `next`,未推送、未发版);剩下的争用以后再说 | 用临时基准在沙盒里量(本分支的快照,只把 swift-demangling 换成修复分支):进程内打印 SwiftUI 的 17920 个定义,标记模式、一个共享 printer、`.utility` 有界任务组,每个宽度一个新进程,release,JHs-Mac-Studio-Ultra。改前:宽度 1 墙钟 37.74 s / CPU 37.77 s;宽度 14 墙钟 329.50 s / CPU 4446 s。改后:宽度 1 18.02 s / 18.08 s;宽度 4 8.87 s / 26.26 s;宽度 14 15.06–18.87 s / 约 165 s。串行本身也快了一倍:按 conformance 找符号的查询在单线程下同样是热点,省掉的是逐节点的引用计数和以 `NodeReference` 为元素的去重集合。改后在宽度 14 下再采样,剩下的争用在本库:`SymbolIndexStore.demangledNodeReference(for:in:)` 每查一个符号都经 `SharedCache.resolve` 取一次存储(同一把锁,`__ulock_wait2` 约 2750 个样本),以及 `ExtensionDefinition` 索引体里按 conformance 找符号时逐个造 `NodeReference`、retain 同一个 store。用户选择先做 `draft-nested-definition-regions`,这部分以后再说。全量 `swift test --skip IntegrationTests` 用修好的 swift-demangling 跑,2168 个全过(原始退出码 0)。RuntimeViewer 要拿到修复,构建需要解析到 swift-demangling 的 `next`。 | +| 2026-10-01 | RuntimeViewer 用修好的 swift-demangling 复测:宽度 4 在三个镜像上都快约 2.5 倍,宽度 14 在 SwiftUI 上反而比宽度 4 慢 | RuntimeViewer 会话的 `CorpusBuildTimingProbe`(corpus 模式,Release,每次新进程,四档交替各两轮,负载 5–7;本库为 `937172ef` 的 git archive,swift-demangling 为 `e17ae7f`,对照组为 `35d550a`;RuntimeViewer Core 为 `c0ed5fe4`,只改 `defaultPrintingWidth`;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/fix-*`)。libswiftCore(660 个对象):修复前宽度 1 为 0.94 / 0.95 s;修复后宽度 1 为 0.84 / 0.86 s,宽度 4 为 0.34 / 0.34 s(CPU 1.1 s),宽度 14 为 0.36 / 0.35 s(CPU 3.6–3.8 s)。Foundation(2559 个):3.69 / 3.56 s → 3.34 / 3.36 s → 宽度 4 为 1.28 / 1.28 s(CPU 3.5 s)→ 宽度 14 为 0.84 / 0.84 s(CPU 4.6 s)。SwiftUI(7378 个):34.76 / 33.85 s → 17.44 / 16.30 s → 宽度 4 为 6.68 / 6.81 s(CPU 21.9–22.3 s)→ 宽度 14 为 11.95 / 11.58 s(CPU 144–149 s)。与沙盒基准一致:串行减半,宽度 4 收益最好,宽度 14 被本库符号索引里剩下的争用拖住。RuntimeViewer 准备在它的提案里建议宽度取 min(4, 核数 / 2)(下限 1),等它能解析到含 `9f5ffa92` 的本库和含 `d7693c2` 的 swift-demangling 之后再改代码,以免在没有索引锁的版本上并发打印。 | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index e3b743144..9c7294f4b 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2141,7 +2141,7 @@ - **关键决策**:**① 索引改成同步函数,经 `DefinitionIndexing` 只跑一次**:进程级一把 `@Mutex` 守着 in-flight 表和每个定义的 `hasCompletedIndexing`;首个调用者认领后在自己线程上跑完,其余在 promise 上阻塞等待并共享结果(复用 `SharedCacheBuildPromise`,载荷是 `Result`),抛错则回到未索引、下次重试。**② 不死锁靠两条前提**:索引体没有 `await`(编译器保证),索引体不索引别的定义(所有 `SharedCache` 都在下层模块,结构上够不到定义;认领或等待时若当前线程正在跑某个索引体就 `precondition` trap)。**③ 打印期不写定义**:类型级 attribute 改成打印时的局部变量,删掉 `TypeDefinition.attributes`(三个下游都不读它);`TypeAttributeInferrer` 里三处读 `TypeDefinition.extensions` 的死代码删掉,并写明被它掩盖的缺口:声明在扩展里的 `buildBlock` / `subscript(dynamicMember:)` / `dynamicallyCall` 识别不到。**④ 三个定义类标 `@unchecked Sendable`**,理由写在类型上;`SymbolicDemangler.isCacheEnabled` 改成 `static let`。**⑤ 约定**:AGENTS.md 那条「同版本内不能并行」改成「`MachOImage` 读者下打印可以并行,`MachOFile` 读者仍不行,`specialize(...)` 不在承诺内」。 - **落地模块**:SwiftDeclaration(`DefinitionIndexing`、三个定义类及其 `+Indexing`、`MutableDefinition` 的 requirement)、SwiftAttributeInference(`TypeAttributeInferrer`)、SwiftPrinting / SwiftInterface(打印器与 diff 渲染的两处 attribute、各处 `index(in:)` 调用)、SwiftInspection(`isCacheEnabled`)、MachOCaches(`SharedCacheBuildPromise` 的注释)。测试新增 `ConcurrentDefinitionPrintingTests`(CI 主过滤与单线程协作池两步都加了),其余测试去掉为定义不 `Sendable` 写的 `nonisolated(unsafe)` 绕法。 - **验证**:改动前压力测试不开 TSan 直接崩(`attributes` 数组被另一个任务重新赋值后又被读),release + TSan 报 28 条数据竞争;改动后 debug、release + TSan(0 条报告)、单线程协作池、单线程协作池且关掉大栈执行器都通过。debug 下用 TSan 会在 MachOKit 读 fixture 时被对齐检查拦下(MachOKit 的既有问题),所以 TSan 一律用 release。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4)改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B 对改动前的 `4fd4049b` 共 92 对逐字节一致(归档 cache 26.6 / 15.5、iOS 15.5–26.5 模拟器、MachOImage 腿);iOS 15.5 模拟器 SwiftUI / WidgetKit 的 4 对两侧同样崩溃,原因是本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后 `ExportTrie.init` 对空导出信息强制解包,与本批无关,细节见提案决策日志。 -- **后续**:RuntimeViewer 量出宽度 14 的并行打印比串行还慢。根因在 swift-demangling:按种类找节点的查询每访问一个节点都复制一次 `NodeReference`,每次都 retain 镜像共享的 store,14 个线程抢同一个引用计数。修在 swift-demangling(它的提案 0016,合入它的 `next`,未发版)。进程内打印 SwiftUI 全部定义:改前宽度 1 37.7 s、宽度 14 329.5 s;改后宽度 1 18.0 s、宽度 4 8.9 s、宽度 14 15–19 s。宽度 14 下剩下的争用在本库(`SymbolIndexStore` 每查一个符号都经 `SharedCache` 取一次存储,以及按 conformance 找符号时逐个造 `NodeReference`),用户决定以后再说,细节在提案决策日志。 +- **后续**:RuntimeViewer 量出宽度 14 的并行打印比串行还慢。根因在 swift-demangling:按种类找节点的查询每访问一个节点都复制一次 `NodeReference`,每次都 retain 镜像共享的 store,14 个线程抢同一个引用计数。修在 swift-demangling(它的提案 0016,合入它的 `next`,未发版)。进程内打印 SwiftUI 全部定义:改前宽度 1 37.7 s、宽度 14 329.5 s;改后宽度 1 18.0 s、宽度 4 8.9 s、宽度 14 15–19 s。宽度 14 下剩下的争用在本库(`SymbolIndexStore` 每查一个符号都经 `SharedCache` 取一次存储,以及按 conformance 找符号时逐个造 `NodeReference`),用户决定以后再说,细节在提案决策日志。RuntimeViewer 随后复测:宽度 4 在 libswiftCore、Foundation、SwiftUI 上都快约 2.5 倍(SwiftUI 从串行 17 s 降到 6.7 s),宽度 14 在 SwiftUI 上比宽度 4 慢;它准备把宽度取 min(4, 核数 / 2)。 - **关联文档**:[draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「版本内并行为什么不做」。 - **对应版本**:未发版。 From bca9594d17a810e179f84028cacbb559031cd107 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 19:31:44 +0800 Subject: [PATCH 09/49] fix(interface): print a protocol declared in another module's extension without nesting its extensions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A protocol declared in an extension of another module's type keeps an extension context and no parent, so the printer took it for a top-level protocol and printed its default-implementation extensions right after it: inside the enclosing extension's braces, at column 0. Swift cannot nest an extension there; Foundation's interface read extension __C.NSNotificationCenter { protocol AsyncMessage { … } extension __C.NSNotificationCenter.AsyncMessage { … } … } Only a top-level protocol now trails its extensions. The interface prints those of a protocol declared in an extension in its top-level block for nested protocols, beside the ones of protocols nested in a type. A protocol declared in an extension of the module's own type is parented on the type by the compiler and already printed right. ProtocolInExtensionTests compiles a fixture with both kinds and failed before the fix: the interface opened an extension inside another, and the protocol printed on its own carried its extensions. Proposal: draft-nested-definition-regions (the fix it calls for first). --- .../SwiftInterfaceBuilder.swift | 7 +- .../SwiftDeclarationPrinter.swift | 8 +- .../ProtocolInExtensionTests.swift | 167 ++++++++++++++++++ 3 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift index 429560106..7cceb8d69 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift @@ -241,8 +241,11 @@ public final class SwiftInterfaceBuilder: Sen // the top level instead. This loop was dead before evolution // proposal 0007 — it filtered ROOT protocols on `parent != nil`, // which no root ever satisfies, so nested protocols' blocks never - // printed at all. - for protocolDefinition in indexer.allProtocolDefinitions.values where protocolDefinition.parent != nil { + // printed at all. A protocol declared in an extension of another + // module's type is nested too, with an extension context instead + // of a parent; its blocks used to print inside that extension's + // braces (evolution proposal `nested-definition-regions`). + for protocolDefinition in indexer.allProtocolDefinitions.values where protocolDefinition.parent != nil || protocolDefinition.extensionContext != nil { for extensionDefinition in protocolDefinition.defaultImplementationExtensions { await printCatchedThrowing( dispatchingTo: eventDispatcher, diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index bfebc7414..af105cde3 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -375,7 +375,13 @@ public final class SwiftDeclarationPrinter: S } } - if protocolDefinition.parent == nil { + // Only a top-level protocol trails its default-implementation + // extensions. One nested in a type, or declared in an extension of + // another module's type (which leaves it an extension context and no + // parent), prints inside that declaration's braces, where an + // extension cannot go — the interface prints its extensions in the + // top-level extensions block instead (`SwiftInterfaceBuilder`). + if protocolDefinition.parent == nil, protocolDefinition.extensionContext == nil { // Per-extension catch: a default-implementation extension whose // printing throws drops only itself, not the protocol it trails. await BlockList { diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift new file mode 100644 index 000000000..a3ab0287d --- /dev/null +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -0,0 +1,167 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import Semantic +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface + +/// A protocol declared inside an extension (SE-0404) — `extension Host { +/// protocol Delegate {…} }` — has no parent type definition, only an +/// extension context, so the printer took it for a top-level protocol and +/// printed its default-implementation extensions right after it: inside the +/// enclosing extension's braces, at column 0. Swift cannot nest an extension +/// there (Foundation's interface read `extension __C.NSNotificationCenter { +/// protocol AsyncMessage {…} extension …AsyncMessage {…} }`), and a host +/// that takes nested definitions out of their parent's print could not take +/// this protocol out: those trailing lines were not indented by the nesting. +/// They now print in the interface's top-level +/// extensions block, like the extensions of a protocol nested in a type. +@Suite(.serialized) +struct ProtocolInExtensionTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "protocol-in-extension fixture compilation failed:\n\(diagnostics)" } + } + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("ProtocolInExtensionFixture-\(UUID().uuidString)") + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + let sourceURL = workingDirectory.appendingPathComponent("ProtocolsInExtensions.swift") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + let libraryURL = workingDirectory.appendingPathComponent("libProbeProtocolInExtension.dylib") + try run(swiftcArguments: [ + "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ]) + return libraryURL + } + }() + + private static func run(swiftcArguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = ["swiftc"] + swiftcArguments + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + /// + /// Only `Int.Counter` has an extension context. The compiler parents a + /// protocol declared in an extension of this module's own type on the + /// type itself, so `Host.Delegate` is a nested protocol of `Host` — the + /// case that already printed right, kept here as the contrast. + private static let source = """ + public final class FixtureAnchor {} + + public struct Host { + public init() {} + } + + extension Host { + public protocol Delegate { + func handle() + } + } + + extension Host.Delegate { + public func handle() {} + public func delegateHelper() -> Int { 0 } + } + + extension Int { + public protocol Counter { + var count: Int { get } + } + } + + extension Int.Counter { + public var count: Int { 0 } + public func counterHelper() -> Int { 1 } + } + """ + + private func loadFixture() throws -> MachOFile { + let libraryURL = try Self.fixtureCompilationResult.get() + switch try File.loadFromFile(url: libraryURL) { + case .machO(let file): + return file + case .fat(let fatFile): + return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + } + + /// The lines starting an `extension` while inside another declaration's + /// braces. + private static func extensionsOpenedInsideBraces(of interface: String) -> [String] { + var depth = 0 + var nestedExtensionLines: [String] = [] + for line in interface.split(separator: "\n", omittingEmptySubsequences: false) { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if depth > 0, trimmed.hasPrefix("extension ") { + nestedExtensionLines.append(String(line)) + } + depth += line.filter { $0 == "{" }.count - line.filter { $0 == "}" }.count + } + return nestedExtensionLines + } + + @Test("the default implementations of a protocol declared in an extension print in the top-level extensions block") + func defaultImplementationsPrintAtTheTopLevel() async throws { + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: try loadFixture()) + try await builder.prepare() + let interface = try await builder.printRoot().string + + #expect(Self.extensionsOpenedInsideBraces(of: interface).isEmpty, "\(interface)") + let topLevelExtensionLines = interface.split(separator: "\n").filter { $0.hasPrefix("extension ") } + #expect(topLevelExtensionLines.contains { $0.contains("Host.Delegate") }, "\(interface)") + #expect(topLevelExtensionLines.contains { $0.contains("Int.Counter") }, "\(interface)") + // Printed once, not dropped and not repeated. + #expect(interface.components(separatedBy: "func delegateHelper()").count == 2, "\(interface)") + #expect(interface.components(separatedBy: "func counterHelper()").count == 2, "\(interface)") + } + + @Test("a protocol declared in an extension prints on its own without its default-implementation extensions") + func standalonePrintCarriesNoExtension() async throws { + let machOFile = try loadFixture() + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + let printer = SwiftDeclarationPrinter(configuration: .init(), in: machOFile) + + #expect(indexer.allProtocolDefinitions.values.filter { $0.extensionContext != nil }.count == 1) + let nestedProtocols = indexer.allProtocolDefinitions.values.filter { $0.parent != nil || $0.extensionContext != nil } + #expect(nestedProtocols.count == 2) + for protocolDefinition in nestedProtocols { + let printed = try await printer.printProtocolDefinition(protocolDefinition).string + #expect(!printed.contains("extension"), "\(printed)") + } + } +} From b93636c98b0686752cb23b4a7f694d00d11c0033 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 1 Oct 2026 19:32:03 +0800 Subject: [PATCH 10/49] feat(printing): mark nested definitions so a host can take them out of their parent's print MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RuntimeViewer prints every nested type twice for its Find corpus: inline in its parent, and again as its own object — about forty percent of the print time on Foundation and SwiftUI. With the new marksNestedDefinitions, each nested type or protocol printed inside its parent (a type's nested definitions, an extension's) is wrapped in swift-semantic-string's DefinitionRegion, named by its name node's mangled name, the identity RuntimeViewer names its objects by. The host prints the parent once and takes each nested definition out instead of printing it again. The contract, for a parent printed at level 1: a region at depth d, taken out of the frozen print with content(ofDefinitionRegion:) and removingIndentation(levels: d + 1), equals the definition printed on its own by the same printer, in text, spans, identifiers and the tables both separations produce. A child that throws is dropped as before and leaves no region, and a name that does not remangle prints unmarked; the host prints those on their own. Off, the output is unchanged. NestedDefinitionRegionContractTests checks every nested definition of the SymbolTestsCore fixture, in process and from the file, plain, marked, and with every option and the Transformer templates on, and that each parent has one region per nested definition. ProtocolInExtensionTests gains the case the previous fix enabled. The full suite passes (2174 tests) and the rendering A/B is byte-identical over 92 pairs. This needs swift-semantic-string's feature/definition-regions; it cannot land before that is released and the floor raised. Proposal: draft-nested-definition-regions (In Progress). --- .github/workflows/macOS.yml | 2 +- AGENTS.md | 1 + Documentations/Evolutions/README.md | 2 +- .../draft-nested-definition-regions.md | 13 +- Documentations/Glossary.md | 7 + .../Internal/ProjectEvolutionLog.md | 10 + Documentations/README.md | 2 +- .../SwiftDeclarationPrintConfiguration.swift | 28 +++ ...DeclarationPrinter+DefinitionRegions.swift | 39 +++ .../SwiftDeclarationPrinter.swift | 16 +- .../NestedDefinitionRegionContractTests.swift | 222 ++++++++++++++++++ .../ProtocolInExtensionTests.swift | 32 ++- 12 files changed, 360 insertions(+), 14 deletions(-) create mode 100644 Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift create mode 100644 Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 974c3e0ba..10c9e2357 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/AGENTS.md b/AGENTS.md index ad0b0eef2..f2277b99a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -256,6 +256,7 @@ Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` r - **Materialization discipline**: at most one materialization per operation (index it / print it / specialize it), threaded through as a local variable. Never a per-access computed property, and never cached back onto the definition — caching re-accumulates, in browse order, exactly the memory the descriptor slimming reclaimed. - **The printers' error contract inverts by level.** Inside a definition, a failing field fails the whole type. At the top level — `printRoot` and the nested children loops alike — printing catches **per definition**: one type/protocol/extension/nested child that throws drops only itself, never its block. A block-level catch once blanked every type of a legacy binary's interface. - **A name's `kind` takes no part in its equality.** The node identifies the type; `kind` is derived differently per producer and the two disagree for C-imported types. +- **A nested definition's print may depend on its `level` only through indentation.** A host with `marksNestedDefinitions` takes each nested type or protocol out of its parent's print instead of printing it again, removing one indentation level per nesting depth; a hard-coded level, or a line a renderer does not indent, breaks that silently for the host. `NestedDefinitionRegionContractTests` reports it. - The `Name` types are deliberately **not `Codable`**. A mangled symbol already is the tree's serialized form — persist `mangleAsString(node)` and read it back with `demangleAsNode(_:)` rather than reintroducing a node encoding. - [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index f1b6f7760..0ae61ef59 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -67,6 +67,6 @@ | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | | draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | In Progress | | draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | In Progress | -| draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | Accepted | +| draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | In Progress | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | diff --git a/Documentations/Evolutions/draft-nested-definition-regions.md b/Documentations/Evolutions/draft-nested-definition-regions.md index 2d97808dc..d555573ca 100644 --- a/Documentations/Evolutions/draft-nested-definition-regions.md +++ b/Documentations/Evolutions/draft-nested-definition-regions.md @@ -1,12 +1,12 @@ # Draft - 在父定义的打印结果里标出嵌套子定义的边界 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-10-01 - **最后更新**: 2026-10-01 - **所属愿景**: 无 - **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(同一手法:区域编码在原子的 `identifier` 里,冻结后分离成一张表);RuntimeViewer 的 `draft-find-navigator` §1.1 方案 D(使用方);swift-semantic-string 的设计记录 `docs/VisibilityRegions.md` -- **实现分支 / PR**: 待定(起草于 `feature/runtime-viewer/find-navigator`) -- **配套文档**: 无 +- **实现分支 / PR**: 本库 `feature/runtime-viewer/find-navigator`;swift-semantic-string `feature/definition-regions` +- **配套文档**: swift-semantic-string 的设计记录 `docs/DefinitionRegions.md`;[Glossary.md](../Glossary.md)「nested-definition region」 ## 摘要 @@ -16,7 +16,7 @@ RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的 ### 改动位置 -- **swift-semantic-string**(新功能,另一个仓库):在 `Sources/Semantic/Visibility/VisibilityRegion.swift` 旁边加一个 `DefinitionRegion` 组件,把一个身份字符串编码进内容里每个原子的 `identifier`,用与 `VisibilityTag` 不同的分隔符,两种标记可以叠在同一个原子上;冻结后用一个分离函数(与 `VisibilityRegionTable.swift:59` 的 `separatingVisibilityRegions()` 同形)读回成一张表,记录每个区域的身份、UTF-8 范围和嵌套关系,并还原原子原来的 `identifier`。再加两个通用操作:把冻结字符串连同它的可见性区域表切到某个区域;按行去掉开头 N 级缩进(每级 4 个空格),span 与区域表跟着平移。 +- **swift-semantic-string**(新功能,另一个仓库,落在 `Sources/Semantic/DefinitionRegions/` 与 `Frozen/FrozenSemanticString+Indentation.swift`):`DefinitionRegion` 组件把一个身份字符串编码进内容里每个原子的 `identifier`,编码放在可见性标记里面一层,两种标记可以叠在同一个原子上,两种嵌套顺序得到的原子相同;`separatingDefinitionRegions()`(与 `separatingVisibilityRegions()` 同形,两者可按任意顺序调用)读回成 `DefinitionRegionTable`,记录每个区域的身份、UTF-8 范围、深度和直接外层区域,并还原原子原来的 `identifier`。两个操作:`content(ofDefinitionRegion:)` 在**带标记的**冻结串上切出一个区域,去掉该区域及外层区域的身份、按首次使用顺序重建 identifier 表,结果再做两种分离就得到子定义自己的文本与两张表;`removingIndentation(levels:)` 按行去掉开头 N 级缩进(每级 4 个空格),进到多行原子内部,有一行缩进不够就返回 `nil`。 - **MachOSwiftSection**: - `SwiftDeclarationPrintConfiguration` 加开关 `marksNestedDefinitions`(默认 `false`)。关着时输出与今天逐字节相同。 - `SwiftDeclarationPrinter.swift:289` 与 `:303`(类型里的嵌套类型、嵌套协议)、`:436` 与 `:450`(extension 里的类型、协议):开关打开时,把每个 `NestedDeclaration` 里那次 `printTypeDefinition` / `printProtocolDefinition` 的结果包进 `DefinitionRegion`。身份用名字节点的 mangled name,即 `mangleAsString(child.typeName.node)` 或 `mangleAsString(child.protocolName.node)`——RuntimeViewer 的 `RuntimeObject.name` 正是这个值,拿到就能对上对象,不需要另建映射。 @@ -63,3 +63,8 @@ RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的 |------|------|------| | 2026-10-01 | Created as Draft | RuntimeViewer 的计时探针量出嵌套对象占打印时间约四成(Release,`72913c3d`;Foundation 只打顶层 2.23 s、全打 3.72 s,SwiftUI 31.15 s 对 51.95 s,libswiftCore 15–22%),超过其提案定的 20% 门槛,指向方案 D。用户在 RuntimeViewer 的会话里对「要让 MachOSwiftSection 那边的会话起草这份上游提案吗?」选了「让它起草提案」;只起草,审过置 `Accepted` 之前不写实现。需求三条由 RuntimeViewer 会话转来:子定义原子的边界标记且可嵌套、内联与单独打印除缩进外逐字节相同并用测试钉住(含 enum layout 多行原子、展开字段偏移、transformer 三种情况)、失败由 RuntimeViewer 回退。 | | 2026-10-01 | Accepted;四个待定项都按推荐 | 用户在 RuntimeViewer 会话里选定:嵌在 extension 里的协议的默认实现扩展改到顶层 extensions 区块打印;单独开关 `marksNestedDefinitions`;身份用名字节点的 mangled name(RuntimeViewer 核实 `RuntimeSwiftSection.swift:275` 以 `mangleAsString(typeDefinition.typeName.node)` 作 `RuntimeObject.name`,协议在 `:258`、扩展在 `:237`);切片与去缩进放进 swift-semantic-string。随后在本仓库的会话里直接确认「确认,排在遍历修复之后」:先做 swift-demangling 的节点遍历修复(并行打印的引用计数争用),再实现本提案。 | +| 2026-10-01 | In Progress;库接口改为「在带标记的串上切,切完再分离」 | 方案原写「把冻结字符串连同它的可见性区域表切到某个区域」。实现时改成在带标记的冻结串上切(`content(ofDefinitionRegion:)`),可见性区域表由切出的串自己分离得到:`separatingVisibilityRegions()` 按 identifier 表的顺序给条件编号,切表就得重新编号、合并相邻区域、处理跨切点的区域,等于把分离逻辑重写一遍;切串时按首次使用顺序重建 identifier 表,再分离出的表与单独打印的逐项相同(swift-semantic-string 的 `DefinitionRegionTests` 钉住)。定义区域的编码放在可见性标记里面一层:容器与可见性分离都只看第一个字符认标记,放在外层会让容器把带条件的成员当成无条件的。 | +| 2026-10-01 | 「extension 里的协议」只发生在扩展别的模块的类型时;打印器与 interface 生成器各改一处 | 现场编译的 fixture 显示:协议声明在本模块类型的 extension 里时,编译器把它直接挂在类型上(成为该类型的嵌套协议,本来就打印正确);只有扩展别的模块的类型(`extension Int { protocol Counter }`)才留下 extension 上下文、没有 `parent`。修法按「需要你定的」第 1 条 a:`SwiftDeclarationPrinter` 只给 `parent` 与 `extensionContext` 都为空的协议原地打印默认实现扩展;`SwiftInterfaceBuilder` 原本只把 `parent != nil` 的协议的扩展放进顶层区块,现在也包括 `extensionContext != nil` 的。`ProtocolInExtensionTests` 先红后绿:修复前三条全部失败(interface 里 `extension Swift.Int.Counter {` 开在 `extension Swift.Int {` 的大括号里;单独打印带着扩展;从 extension 里取出的协议去不掉缩进),修复后通过。 | +| 2026-10-01 | 实现:`marksNestedDefinitions` 与 `SwiftDeclarationPrinter+DefinitionRegions.swift` | 四处嵌套循环都经 `nestedDefinition(named:printing:)`:先打印子定义,开关打开且结果非空时才算 mangled name(`mangleAsString(name.node)`)并包一层区域;名字 remangle 失败或含控制字符(区域身份不能带)就不标,宿主单独打印它。开关关着时代码路径不变。 | +| 2026-10-01 | 验证:契约测试全部通过 | `NestedDefinitionRegionContractTests`(SwiftInterfaceTests):SymbolTestsCore 里每个有嵌套定义的根类型与 extension(几乎所有类型都嵌在命名空间 enum 里),进程内与文件两种读取方式,各三种配置——只开 `marksNestedDefinitions`;再开 `marksOptionalContent` 并挂 opaque 解析器;全部打印选项打开并装上 `applyTransformers(_:)` 的全部模板。每个区域取出、去缩进后与单独打印比较文本、span、identifier、可见性区域表与内层定义区域表,并核对区域数等于嵌套定义数(防漏标),每种配置都检查了 100 个以上的区域,首次运行即全部通过;另有一条确认开关打开时分离后的文本与不开时逐字节相同。swift-semantic-string 侧全部 432 个测试通过、watchOS `arm64_32` 编译通过。 | +| 2026-10-01 | 全量测试与渲染 A/B 通过;Foundation 上只挪动了两个扩展 | 全量 `swift test --skip IntegrationTests`(沙盒副本,本地兄弟依赖,swift-semantic-string 指向 `feature/definition-regions`)2174 个测试全部通过,原始退出码 0。渲染 A/B:基线是本分支 `ed289fb4` 的 git archive,候选是加上本提案改动的副本,两侧依赖相同、只有 swift-semantic-string 指向不同分支;92 对逐字节一致,iOS 15.5 模拟器的 SwiftUI / WidgetKit 两侧同样崩溃(MachOKit `ExportTrie.init`,见并发打印提案)。A/B 的框架里没有协议声明在别的模块类型的 extension 里,另用两侧 CLI 渲染当前系统 Foundation 的 interface 对比:只有 `NSNotificationCenter.AsyncMessage` 与 `NSNotificationCenter.MainActorMessage` 的两个默认实现扩展,从 `extension __C.NSNotificationCenter { … }` 的大括号里(顶格)挪到了顶层的嵌套协议扩展区块,其余四万多行逐字节相同。 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 26a7d54ed..e70e16839 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -206,6 +206,13 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift` - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) +### nested-definition region(定义区域,`marksNestedDefinitions`) + +`SwiftDeclarationPrintConfiguration.marksNestedDefinitions` 为 `true` 时,父定义打印结果里每个内联打印的嵌套类型或协议被包进 swift-semantic-string 的 `DefinitionRegion`,身份是名字节点的 mangled name,与 RuntimeViewer 的对象名相同。冻结后用 `separatingDefinitionRegions()` 拆出区域表;对深度为 d 的区域,`content(ofDefinitionRegion:)` 再加 `removingIndentation(levels: d + 1)` 得到的值,与该定义单独打印的结果逐项相同(文本、span、identifier,以及两种分离得到的表)。宿主因此只需打印父定义,不必再单独打印每个嵌套定义。与标记模式同时打开时,定义区域的编码放在可见性标记的内层,两者互不影响。 + +- **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift`、`SwiftDeclarationPrintConfiguration.swift` +- **延伸阅读**:[提案 draft-nested-definition-regions](Evolutions/draft-nested-definition-regions.md);swift-semantic-string 的 `docs/DefinitionRegions.md` + ### NodeStore / NodeReference 上游 swift-demangling 的 arena 存储:demangle 结果不再是 class `Node` 树,而是扁平缓冲里的节点(12 字节/节点)加一个 `(store, index)` 引用。本仓库的符号索引、声明模型、各级缓存全部换持 `NodeReference`。注意它的 `Hashable` 是 store 身份语义——见「store-identity vs 结构相等」。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 9c7294f4b..ea29214c9 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2155,6 +2155,16 @@ - **关联文档**:[draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md)、[Modules/MachOCaches.md](Modules/MachOCaches.md)「不受驱逐的」、[NestedFieldOffsetCycleGuard.md](NestedFieldOffsetCycleGuard.md)「每层从记录里读」。 - **对应版本**:未发版。 +## 2026-10-01 嵌套定义在父定义的打印里标出边界(方案 D) + +- **时间段**:2026-10-01(提案、实现)。 +- **动机**:RuntimeViewer 建 Find 语料时,嵌套类型在父类型的打印里内联一遍,又作为自己的对象单独打印一遍,计时探针量出这部分约占打印时间四成(Foundation 只打顶层 2.23 s、全打 3.72 s;SwiftUI 31.15 s 对 51.95 s)。它的方案 D 是只打印父定义、从结果里把嵌套定义切出来;本库要给出边界,并承诺切出来的与单独打印的一样。 +- **关键决策**:**① 新开关 `marksNestedDefinitions`**(默认关,关着时输出逐字节不变),四处嵌套循环把子定义的打印包进 swift-semantic-string 新增的 `DefinitionRegion`,身份是名字节点的 mangled name;名字 remangle 失败或含控制字符就不标,宿主单独打印。**② 库接口在带标记的串上切**:`content(ofDefinitionRegion:)` 去掉外层身份、按首次使用顺序重建 identifier 表,`removingIndentation(levels:)` 按行去缩进,切出的串再分离出的两张表与单独打印的相同;原方案「连同可见性区域表一起切」改掉,因为条件按 identifier 表顺序编号,切表等于重写分离逻辑。定义区域的编码放在可见性标记里面一层,容器与可见性分离都不受影响。**③ 先修一个既有问题**:协议声明在别的模块类型的 extension 里(`extension Int { protocol Counter }`)时,默认实现扩展被打印在外层 extension 的大括号里、顶格,生成的 Swift 不合法;现在只有顶层协议原地带出扩展,这类协议的扩展与嵌在类型里的协议一样放进 interface 的顶层 extensions 区块。声明在本模块类型的 extension 里的协议被编译器直接挂在类型上,本来就打印正确。 +- **落地模块**:SwiftPrinting(`SwiftDeclarationPrintConfiguration.marksNestedDefinitions`、新文件 `SwiftDeclarationPrinter+DefinitionRegions.swift`、四处嵌套循环、协议默认实现扩展的条件)、SwiftInterface(顶层区块收录 extension 里的协议的扩展);swift-semantic-string(`DefinitionRegion`、`DefinitionRegionTable`、`separatingDefinitionRegions()`、`content(ofDefinitionRegion:)`、`removingIndentation(levels:)`)。测试新增 `NestedDefinitionRegionContractTests`、`ProtocolInExtensionTests`,两者加进 CI 主过滤列表。 +- **验证**:`ProtocolInExtensionTests` 先红后绿。契约测试对 SymbolTestsCore 每个有嵌套定义的根类型与 extension,在进程内与文件两种读取方式、三种配置(只标定义区域;加标记模式;全部选项加 Transformer 模板)下逐区域比较,全部通过,区域数与嵌套定义数一致。swift-semantic-string 全部 432 个测试通过,watchOS `arm64_32` 编译通过。全量测试与渲染 A/B 见提案决策日志。 +- **关联文档**:[draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md)、[Glossary.md](../Glossary.md)「nested-definition region」、swift-semantic-string 的 `docs/DefinitionRegions.md`。 +- **对应版本**:未发版。落地前要先发布带 `DefinitionRegion` 的 swift-semantic-string,并抬高本库对它的版本下限。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/README.md b/Documentations/README.md index 873e07e26..d1095ff0e 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -157,7 +157,7 @@ selects names using each access's offset and width. | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | | [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | -| [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(Accepted)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | +| [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [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/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index 0a8e30df0..22d418c63 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -73,6 +73,34 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { /// opaque type resolver as for a normal print. public var marksOptionalContent: Bool = false + /// Wrap every nested type and protocol printed inside its parent — a + /// type's nested definitions and an extension's — in a + /// `DefinitionRegion` named after the definition (evolution proposal + /// `nested-definition-regions`). The identity is the mangled name of the + /// definition's name node: `mangleAsString(typeName.node)`, or + /// `mangleAsString(protocolName.node)` for a protocol. + /// + /// The contract: in the frozen print of a parent printed at the default + /// `level` 1, a region at depth `d`, taken out with + /// `content(ofDefinitionRegion:)` and then + /// `removingIndentation(levels: d + 1)`, equals the frozen print of that + /// definition on its own with the same printer — text, spans, + /// identifiers, and with `marksOptionalContent` the regions its + /// visibility separation finds. So a host that needs every nested + /// definition on its own prints the parent once instead of printing each + /// child again. + /// + /// A child whose print throws is dropped from its parent, as without + /// marking, and leaves no region; a name that does not remangle, or + /// remangles to text a region identity cannot carry, prints unmarked. + /// The host prints such a child on its own. The contract holds for the + /// built-in rendering and for transformers installed by + /// `applyTransformers(_:)`; a hand-written transformer closure must start + /// each line it emits with the indentation it is given. + /// + /// Off by default, and off the output is unchanged byte for byte. + public var marksNestedDefinitions: Bool = false + /// How the static (`MachOFile`) field-layout path resolves cross-module /// types when a layout-bearing flag is on. Defaults to the full transitive /// dependency closure over the system dyld shared cache; set `.singleImage` diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift new file mode 100644 index 000000000..405809f29 --- /dev/null +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift @@ -0,0 +1,39 @@ +import Demangling +import SwiftDeclaration +import Semantic + +// MARK: - Marking Nested Definitions + +/// What `SwiftDeclarationPrintConfiguration.marksNestedDefinitions` changes +/// in the printer (evolution proposal `nested-definition-regions`): the print +/// of each nested type or protocol is wrapped in a `DefinitionRegion` named +/// after it, so a host can take a nested definition out of its parent's print +/// instead of printing it a second time. +extension SwiftDeclarationPrinter { + /// `printNested()` — a nested definition printed at its nesting level — + /// wrapped in a region named after `name` when marking. A child the + /// export filter removed prints nothing and gets no region. + func nestedDefinition(named name: NodeReference, printing printNested: () async throws -> SemanticString) async rethrows -> SemanticString { + let printed = try await printNested() + guard configuration.marksNestedDefinitions, !printed.isEmpty, let identity = await definitionRegionIdentity(of: name) else { + return printed + } + return SemanticString { + DefinitionRegion(identity, content: printed) + } + } + + /// The mangled name of `name`, the identity a host names the definition + /// by — or `nil` when it does not remangle, or carries a control + /// character, which a region identity cannot. Left unmarked, such a child + /// is printed on its own by the host, as without marking. + private func definitionRegionIdentity(of name: NodeReference) async -> String? { + guard let mangledName = try? await mangleAsString(name), + !mangledName.isEmpty, + !mangledName.unicodeScalars.contains(where: { $0.value < 0x20 }) + else { + return nil + } + return mangledName + } +} diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index af105cde3..6daf5fda8 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -292,7 +292,9 @@ public final class SwiftDeclarationPrinter: S context: .init(name: child.typeName.name, kind: .type), { try await NestedDeclaration { - try await printTypeDefinition(child, level: level + 1) + try await nestedDefinition(named: child.typeName.node) { + try await printTypeDefinition(child, level: level + 1) + } } } ) { @@ -306,7 +308,9 @@ public final class SwiftDeclarationPrinter: S context: .init(name: child.protocolName.name, kind: .protocol), { try await NestedDeclaration { - try await printProtocolDefinition(child, level: level + 1) + try await nestedDefinition(named: child.protocolName.node) { + try await printProtocolDefinition(child, level: level + 1) + } } } ) { @@ -445,7 +449,9 @@ public final class SwiftDeclarationPrinter: S context: .init(name: typeDefinition.typeName.name, kind: .type), { try await NestedDeclaration { - try await printTypeDefinition(typeDefinition, level: level + 1) + try await nestedDefinition(named: typeDefinition.typeName.node) { + try await printTypeDefinition(typeDefinition, level: level + 1) + } } } ) { @@ -459,7 +465,9 @@ public final class SwiftDeclarationPrinter: S context: .init(name: protocolDefinition.protocolName.name, kind: .protocol), { try await NestedDeclaration { - try await printProtocolDefinition(protocolDefinition, level: level + 1) + try await nestedDefinition(named: protocolDefinition.protocolName.node) { + try await printProtocolDefinition(protocolDefinition, level: level + 1) + } } } ) { diff --git a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift new file mode 100644 index 000000000..e2316f84e --- /dev/null +++ b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift @@ -0,0 +1,222 @@ +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +import SwiftDeclarationRendering +import OutputTransformer +import SwiftOutputTransformer +import Semantic +import Demangling +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// With `SwiftDeclarationPrintConfiguration.marksNestedDefinitions`, every +/// nested type and protocol taken out of its parent's print — +/// `content(ofDefinitionRegion:)`, then +/// `removingIndentation(levels: depth + 1)` — is exactly the definition +/// printed on its own: text, spans, identifiers, and the tables its +/// visibility and definition separations produce. Checked for every root +/// type and every extension of the SymbolTestsCore fixture that has nested +/// definitions — nearly every type there sits in a namespace enum — in +/// process and from the file, plainly, marked (`marksOptionalContent`), and +/// with every option on and the `Transformer` templates installed. +/// +/// RuntimeViewer builds its Find corpus on this (evolution proposal +/// `nested-definition-regions`): it prints a parent once and takes the nested +/// definitions out of that print instead of printing each again. A nested +/// print that depends on its level other than through indentation — a +/// hard-coded level, a line its renderer does not indent — shows up here as a +/// mismatch, or as a region whose indentation cannot be removed; a lost mark +/// shows up as a parent with fewer regions than nested definitions. +@Suite(.serialized) +final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + enum Variant: CaseIterable, Sendable, CustomStringConvertible { + case plain + case markedOptionalContent + case everyOptionWithTransformers + + var description: String { + switch self { + case .plain: "plain" + case .markedOptionalContent: "marked optional content" + case .everyOptionWithTransformers: "every option with transformers" + } + } + + var configuration: SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.marksNestedDefinitions = true + switch self { + case .plain: + break + case .markedOptionalContent: + configuration.marksOptionalContent = true + case .everyOptionWithTransformers: + configuration.printFieldOffset = true + configuration.printExpandedFieldOffsets = true + configuration.printMemberAddress = true + configuration.printVTableOffset = true + configuration.printPWTOffset = true + configuration.printTypeLayout = true + configuration.printEnumLayout = true + configuration.printExportStatus = true + var transformers = Transformer.SwiftConfiguration() + transformers.swiftFieldOffset.isEnabled = true + transformers.swiftVTableOffset.isEnabled = true + transformers.swiftMemberAddress.isEnabled = true + transformers.swiftTypeLayout.isEnabled = true + transformers.swiftEnumLayout.isEnabled = true + configuration.applyTransformers(transformers) + } + return configuration + } + + var resolvesOpaqueTypes: Bool { + self != .plain + } + } + + private static func nestedDefinitionCount(of typeDefinition: TypeDefinition) -> Int { + typeDefinition.protocolChildren.count + + typeDefinition.typeChildren.reduce(0) { $0 + 1 + nestedDefinitionCount(of: $1) } + } + + private static func nestedDefinitionCount(of extensionDefinition: ExtensionDefinition) -> Int { + extensionDefinition.protocols.count + + extensionDefinition.types.reduce(0) { $0 + 1 + nestedDefinitionCount(of: $1) } + } + + /// Where two prints first differ, for a readable failure. + private static func firstDifference(between takenOut: FrozenSemanticString, and ownPrint: FrozenSemanticString) -> String { + if takenOut.string != ownPrint.string { + let takenOutLines = takenOut.string.split(separator: "\n", omittingEmptySubsequences: false) + let ownPrintLines = ownPrint.string.split(separator: "\n", omittingEmptySubsequences: false) + let lineIndex = (0 ..< max(takenOutLines.count, ownPrintLines.count)).first { index in + index >= takenOutLines.count || index >= ownPrintLines.count || takenOutLines[index] != ownPrintLines[index] + } ?? 0 + let takenOutLine = lineIndex < takenOutLines.count ? String(takenOutLines[lineIndex]) : "" + let ownPrintLine = lineIndex < ownPrintLines.count ? String(ownPrintLines[lineIndex]) : "" + return "text differs at line \(lineIndex + 1):\n taken out: \(takenOutLine)\n own print: \(ownPrintLine)" + } + let takenOutComponents = takenOut.components + let ownPrintComponents = ownPrint.components + let componentIndex = (0 ..< max(takenOutComponents.count, ownPrintComponents.count)).first { index in + index >= takenOutComponents.count || index >= ownPrintComponents.count || takenOutComponents[index] != ownPrintComponents[index] + } ?? 0 + let takenOutComponent = componentIndex < takenOutComponents.count ? "\(takenOutComponents[componentIndex])" : "" + let ownPrintComponent = componentIndex < ownPrintComponents.count ? "\(ownPrintComponents[componentIndex])" : "" + return "same text, span \(componentIndex) differs:\n taken out: \(takenOutComponent)\n own print: \(ownPrintComponent)" + } + + /// Prints every parent with nested definitions, takes each region out, + /// and describes the first few that differ from the definition's own + /// print. + private static func mismatches( + in machO: MachO, + variant: Variant + ) async throws -> (checkedRegionCount: Int, mismatches: [String]) where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + let printer = SwiftDeclarationPrinter(configuration: variant.configuration, in: machO) + if variant.resolvesOpaqueTypes { + printer.addTypeNameResolver(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + } + + typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString + // Every definition a region can name, by the identity the printer + // gives it. + var ownPrintingByIdentity: [String: Printing] = [:] + for typeDefinition in indexer.allTypeDefinitions.values { + ownPrintingByIdentity[try await mangleAsString(typeDefinition.typeName.node)] = { try await $0.printTypeDefinition(typeDefinition) } + } + for protocolDefinition in indexer.allProtocolDefinitions.values { + ownPrintingByIdentity[try await mangleAsString(protocolDefinition.protocolName.node)] = { try await $0.printProtocolDefinition(protocolDefinition) } + } + + var parents: [(label: String, nestedDefinitionCount: Int, print: Printing)] = [] + for (name, typeDefinition) in indexer.rootTypeDefinitions { + let nestedDefinitionCount = nestedDefinitionCount(of: typeDefinition) + guard nestedDefinitionCount > 0 else { continue } + parents.append(("type \(name.name)", nestedDefinitionCount, { try await $0.printTypeDefinition(typeDefinition) })) + } + let extensionGroups = [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] + for extensionGroup in extensionGroups { + for (name, extensionDefinitions) in extensionGroup { + for extensionDefinition in extensionDefinitions { + let nestedDefinitionCount = nestedDefinitionCount(of: extensionDefinition) + guard nestedDefinitionCount > 0 else { continue } + parents.append(("extension \(name.name)", nestedDefinitionCount, { try await $0.printExtensionDefinition(extensionDefinition) })) + } + } + } + + var checkedRegionCount = 0 + var mismatches: [String] = [] + for parent in parents { + let printed = try await parent.print(printer).frozen() + let regions = printed.separatingDefinitionRegions().definitions.regions + if regions.count != parent.nestedDefinitionCount { + mismatches.append("\(parent.label): \(regions.count) regions for \(parent.nestedDefinitionCount) nested definitions") + } + for region in regions { + checkedRegionCount += 1 + let label = "\(parent.label) → \(region.identity) (depth \(region.depth))" + guard let ownPrinting = ownPrintingByIdentity[region.identity] else { + mismatches.append("\(label): no definition has this identity") + continue + } + let ownPrint = try await ownPrinting(printer).frozen() + let regionContent = printed.content(ofDefinitionRegion: region) + guard let takenOut = regionContent.removingIndentation(levels: region.depth + 1) else { + mismatches.append("\(label): the indentation could not be removed\n\(regionContent.string)") + continue + } + if takenOut != ownPrint { + mismatches.append("\(label): \(firstDifference(between: takenOut, and: ownPrint))") + } else if takenOut.separatingVisibilityRegions().regions != ownPrint.separatingVisibilityRegions().regions { + mismatches.append("\(label): the visibility regions differ") + } else if takenOut.separatingDefinitionRegions().definitions != ownPrint.separatingDefinitionRegions().definitions { + mismatches.append("\(label): the nested definition regions differ") + } + } + if mismatches.count >= 5 { break } + } + return (checkedRegionCount, mismatches) + } + + @Test(arguments: Variant.allCases) + func inProcessNestedDefinitionsTakeOutAsTheirOwnPrints(variant: Variant) async throws { + let result = try await Self.mismatches(in: machOImage, variant: variant) + #expect(result.checkedRegionCount > 100) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + + @Test(arguments: Variant.allCases) + func fileNestedDefinitionsTakeOutAsTheirOwnPrints(variant: Variant) async throws { + let result = try await Self.mismatches(in: machOFile, variant: variant) + #expect(result.checkedRegionCount > 100) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + + @Test func unmarkedPrintsAreUnchanged() async throws { + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + var markedConfiguration = SwiftDeclarationPrintConfiguration() + markedConfiguration.marksNestedDefinitions = true + let markedPrinter = SwiftDeclarationPrinter(configuration: markedConfiguration, in: machOFile) + let plainPrinter = SwiftDeclarationPrinter(configuration: .init(), in: machOFile) + var checkedCount = 0 + for typeDefinition in indexer.rootTypeDefinitions.values { + let marked = try await markedPrinter.printTypeDefinition(typeDefinition).frozen() + let plain = try await plainPrinter.printTypeDefinition(typeDefinition).frozen() + #expect(marked.separatingDefinitionRegions().text == plain) + #expect(plain.separatingDefinitionRegions().definitions.isEmpty) + checkedCount += 1 + } + #expect(checkedCount > 50) + } +} diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift index a3ab0287d..691041bda 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import Semantic +import Demangling @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @@ -16,9 +17,9 @@ import Semantic /// enclosing extension's braces, at column 0. Swift cannot nest an extension /// there (Foundation's interface read `extension __C.NSNotificationCenter { /// protocol AsyncMessage {…} extension …AsyncMessage {…} }`), and a host -/// that takes nested definitions out of their parent's print could not take -/// this protocol out: those trailing lines were not indented by the nesting. -/// They now print in the interface's top-level +/// could not take the protocol out of the extension's print (evolution +/// proposal `nested-definition-regions`): those trailing lines were not +/// indented by the nesting. They now print in the interface's top-level /// extensions block, like the extensions of a protocol nested in a type. @Suite(.serialized) struct ProtocolInExtensionTests { @@ -164,4 +165,29 @@ struct ProtocolInExtensionTests { #expect(!printed.contains("extension"), "\(printed)") } } + + @Test("a protocol declared in an extension, taken out of the extension's print, is its own print") + func regionTakenOutOfTheExtensionIsTheProtocolsOwnPrint() async throws { + let machOFile = try loadFixture() + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + var configuration = SwiftDeclarationPrintConfiguration() + configuration.marksNestedDefinitions = true + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + + let extensionsDeclaringProtocols = indexer.typeExtensionDefinitions.values.flatMap { $0 }.filter { !$0.protocols.isEmpty } + #expect(extensionsDeclaringProtocols.count == 1) + for extensionDefinition in extensionsDeclaringProtocols { + let printed = try await printer.printExtensionDefinition(extensionDefinition).frozen() + let regions = printed.separatingDefinitionRegions().definitions.regions + let protocolDefinition = try #require(extensionDefinition.protocols.first) + let region = try #require(regions.first, "\(printed.string)") + let expectedIdentity = try await mangleAsString(protocolDefinition.protocolName.node) + #expect(region.identity == expectedIdentity) + + let takenOut = printed.content(ofDefinitionRegion: region).removingIndentation(levels: region.depth + 1) + let ownPrint = try await printer.printProtocolDefinition(protocolDefinition).frozen() + #expect(takenOut == ownPrint, "\(printed.string)") + } + } } From 0242a1a8836aa57fca3355b9683cfbd24de48c82 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 30 Sep 2026 17:19:50 +0800 Subject: [PATCH 11/49] docs: propose offline generic specialization for RuntimeViewer's offline mode GenericSpecializer.specialize calls the image's metadata accessor, so it only works on a MachOImage loaded in the current process; RuntimeViewer's planned offline mode reads MachOFile and cannot specialize at all. The draft proposes a MachOFile execution path that never touches the runtime: the instantiated type name and the per-depth argument binding built the way the runtime's _buildDemanglingForContext builds them, an offline requirement check that rejects only the violations it can prove, and interface printing of the specialized definition with a bound header, substituted field types and layout comments computed by the static layout engine. It also records two existing problems the work would fix: generic parameter depths miscounted when a non-generic level sits between generic ones, and runtime-specialized nested type names flattened into the innermost level. --- Documentations/Evolutions/README.md | 1 + .../draft-offline-generic-specialization.md | 111 ++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 113 insertions(+) create mode 100644 Documentations/Evolutions/draft-offline-generic-specialization.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 0ae61ef59..b0e2a9b65 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -70,3 +70,4 @@ | draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | In Progress | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | +| draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | Draft | diff --git a/Documentations/Evolutions/draft-offline-generic-specialization.md b/Documentations/Evolutions/draft-offline-generic-specialization.md new file mode 100644 index 000000000..6355222e4 --- /dev/null +++ b/Documentations/Evolutions/draft-offline-generic-specialization.md @@ -0,0 +1,111 @@ +# Draft - 离线泛型特化:不经 runtime 特化泛型类型并完整打印 + +- **状态**: Draft +- **创建日期**: 2026-09-30 +- **最后更新**: 2026-09-30 +- **所属愿景**: 无 +- **关联文档**: [StaticLayoutEngine.md](../Internal/StaticLayoutEngine.md)「后续工作」里的「用户手动特化前端」一条;[SpecializedInterfaceBoundRenderingRestoration.md](../Internal/SpecializedInterfaceBoundRenderingRestoration.md)(运行时特化的打印机制);RuntimeViewer 的 [0003-generic-type-specialization](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/main/Documentations/Evolutions/0003-generic-type-specialization.md)(消费方的 UI 流程) +- **实现分支 / PR**: `feature/offline-generic-specialization`(未开始实现) +- **配套文档**: 待定 + +## 摘要 + +`GenericSpecializer` 的执行步骤 `specialize` 只能在 `MachO == MachOImage` 时调用:它要调用镜像里的 metadata accessor,镜像必须加载在当前进程里。RuntimeViewer 将来的离线模式读的是磁盘上的 `MachOFile`,现在完全不能特化。离线所需的计算其实大半已经在库里了:静态布局引擎能按给定的实参算出 `Box` 的字段偏移与整体布局(`StaticLayoutCalculator.fieldLayout(of:genericArguments:)`,只是一直没有调用方),`__swift5_assocty` 的 witness 投影也已经存在。本提案补上缺的部分,让 RuntimeViewer 离线模式能走和在线模式同样的「request → selection → specialize → 打印」流程。具体是四件事:`GenericSpecializer` 在 `MachOFile` 上的离线执行与离线约束检查;特化后的 `TypeDefinition`;让 interface 打印器离线也能打出绑定后的头部、代换后的字段类型和按实参计算的布局注释;以及静态布局引擎接受任意层数的实参。本库自己不提供入口(没有 CLI 选项)。 + +## 方案 + +### 调用形态(RuntimeViewer 离线模式) + +与在线模式一一对应,只是 `MachO` 换成 `MachOFile`、结果类型换成离线的那一个: + +```swift +let specializer = GenericSpecializer(indexer: indexer) // SwiftDeclarationIndexer +let request = try specializer.makeRequest(for: typeDefinition.typeContextDescriptorWrapper) +// 用户为每个参数选 .candidate / .boundGeneric +let validation = specializer.staticPreflight(selection: selection, for: request) +let result = try specializer.specialize(request, with: selection) // StaticSpecializationResult +let specializedDefinition = try await typeDefinition.specialize( + with: result, + derivingNestedSpecializationsWith: specializer, + in: machOFile +) +let interface = try await printer.printTypeDefinition(specializedDefinition) // SwiftDeclarationPrinter +``` + +`makeRequest` 与 `validate` 本来就对任意 `MachO` 可用,不动。 + +### 改动清单 + +- **SwiftInspection**:新增公开的 `GenericArgumentBinding`,表示「某个泛型签名的参数被绑定到哪些实参」,按 canonical depth 分组(`argumentsByDepth: [[Node]]`),并提供一个只做显示用的代换(`dependentGenericParamType` 按 `(depth, index)` 换成实参,metatype 里面也换)。在 `SymbolicDemangler.swift:460` 的 `buildContextDescriptorMangling` 旁边新增实例化类型名的构造:给定类型描述符和全部实参,产出绑定后的类型节点(`Outer.Inner`)和对应的 `GenericArgumentBinding`。它移植的是运行时 `stdlib/public/runtime/Demangle.cpp` 的 `_buildDemanglingForContext`:沿描述符路径从外到内,某层上下文的累计参数数比已用掉的多,就把多出来的那几个实参挂在这一层;extension 层挂在被扩展的类型上。于是离线得到的名字和在线模式下运行时给出的名字形状一致,名字里的各部分(私有鉴别符、C 导入类型的身份)仍由 `SymbolicDemangler` 生成。 +- **SwiftSpecialization**: + - `GenericSpecializer`(`GenericSpecializer.swift`)新增 `where MachO == MachOFile` 的扩展,放在 `:1320` 运行时执行扩展的旁边:`specialize(_:with:)` 返回 `StaticSpecializationResult`,`staticPreflight(selection:for:)` 是 `runtimePreflight` 的离线对应。 + - 实参取节点:`.candidate` 取候选的 `TypeName` 节点;`.boundGeneric` 用绑定在候选自己镜像上的内层 specializer 递归离线特化,取内层结果的类型节点;`.metatype` / `.metadata` / `.specialized` 用宿主进程的运行时名字(`RuntimeTypeNameDemangling`),不调用目标镜像的任何代码。 + - 没有 key argument 的参数(被同型约束钉死的,例如 `extension Outer where A == Int { struct Inner }` 里的 `A`)由约束的右侧补齐。 + - `StaticSpecializationResult` 携带类型描述符、绑定后的 `TypeName`、`GenericArgumentBinding` 和逐参数的解析结果(参数名、实参节点、`.boundGeneric` 的内层结果)。 + - `TypeDefinition+Specialization.swift` 新增两个 `specialize(with: StaticSpecializationResult, …, in: MachOFile)` 重载,与 `:120` / `:166` 的运行时版本对应(含嵌套派生)。 +- **SwiftDeclaration**:`TypeDefinition`(`TypeDefinition.swift:152` 的 `metadata` 旁)新增 `staticSpecialization: GenericArgumentBinding?`。运行时特化填 `metadata`,离线特化填这个,打印器按哪个非空选路径。 +- **SwiftLayout**: + - `GenericArgumentEnvironment` 能从 `GenericArgumentBinding` 建环境。现在只有 `:147` 的 depth-0 版本,嵌套泛型的内层实参绑不上。 + - `StaticLayoutCalculator` 的 `fieldLayout` / `typeLayout(forDescriptor:)` / `typeLayout(forMangledTypeName:inContextOfDescriptor:)` / `enumCaseLayoutResult`、`nestedFieldOffsetTree` 各加一个接受 `GenericArgumentBinding` 的重载。 + - `EnumLayoutBridge.swift:307` 的 `enumCaseLayoutResult` 目前不接受实参环境,要补上,特化后的泛型枚举才有逐 case 的布局。 +- **SwiftDeclarationRendering**: + - `FieldLayoutRenderState` / `FieldLayoutRenderer`(`FieldLayoutRenderer.swift:38` / `:139`)携带 `GenericArgumentBinding`,`StaticFieldLayoutBackend` 据此向 provider 要特化后的布局。 + - `StaticFieldLayoutProvider`(`StaticFieldLayoutProvider.swift:36`)的新方法带默认实现,已有的外部实现不受影响。 + - 新增离线的字段类型代换:先按 binding 代换,再把 `C.Element` 这类关联类型经 `DependentMemberProjection` 投影成具体类型;投影不了的保留原样。 +- **SwiftPrinting**:`SwiftDeclarationPrinter.swift:275` 与 `SwiftDeclarationPrinter+Headers.swift:37` / `:359` / `:436` 现在只认 `metadata`。改为:头部的绑定节点、字段代换、布局注释三处都在「运行时 metadata」与「离线 binding」之间二选一。 + +明确不动:运行时特化的计算路径(`specialize` / `runtimePreflight` / `resolveAssociatedTypeWitnesses`);SwiftDump 与 dump 输出;CLI;未特化定义的打印。 + +### 离线约束检查 + +检查逐条对应 `runtimePreflight`,但离线能拿到的证据不同,所以分两档: + +- **报错并拒绝**:结构上确定违反的约束。 + - `AnyObject` 参数给了 struct / enum。 + - 父类约束:实参不在索引记录的父类子树里。 + - 具体同型约束与实参对不上。 +- **只给警告、照样特化**:离线证明不了的约束。 + - 协议遵循。候选列表本来就按 indexer 里的遵循记录筛过;`.boundGeneric` 的条件遵循、别的模块补上的遵循、ObjC 协议、marker 协议都查不全。 + - 关联类型约束(`A.Element: Hashable`)投影不出来的情况。 + - 父类约束在 indexer 没有类层级信息时。 + +错误与警告沿用 `SpecializationValidation` 现有的 case,`SpecializerError` 也不加 case:RuntimeViewer 对这几个枚举做了穷尽 `switch`,加 case 会让它编译失败。 + +### 顺带修的两个旧问题 + +两处都在本提案要复用的代码上,不修的话离线结果也会错: + +1. **参数层数可能数错(待测试确认)**:`GenericSpecializer.swift:164` 的 `perLevelNewParameterCounts` 把父链上每个泛型上下文都当成一层。一个本身不声明参数、只因嵌在泛型类型里才算泛型的中间层(`Outer.Middle.Inner` 的 `Middle`),会占掉一个层号。于是 `B` 被命名成 `A2`,而字段记录与约束里写的是 canonical 的 `A1`(τ_1_0),这个参数的约束就收集不到。约束 extension 里声明的泛型类型可能有同样的问题。先用现场编译的 fixture 写出会失败的测试,确认后改为只数真正声明参数的层,和上面的实例化类型名构造共用同一套计数。fixture 里目前没有这两种形状,所以现有测试不会发现。 +2. **运行时特化的类型名被拍平**:`TypeDefinition+Specialization.swift:333` 的 `boundGenericTypeName` 把全部实参放进最内层,`Outer.Inner` 被写成 `Outer.Inner`,`GenericOuter.Inner` 被写成 `GenericOuter.Inner`。打印出来的头部不受影响(它用的是 metadata 的运行时名字),但 `typeName` 是 RuntimeViewer 侧边栏的显示名和标识。改为用上面的实例化类型名构造,在线与离线两种模式的名字才一致。`typeArgumentNodes` 传 `nil` 时仍保持未绑定的名字,这个现有约定不变。 + +### 不做 + +- CLI 入口:用户明确这是给 RuntimeViewer 离线模式用的,本库没有使用它的地方。 +- 实例化普查(自动为二进制里出现过的每个 `Foo` 算布局):另立提案。 +- SwiftDump / dump 路径:RuntimeViewer 只用 `SwiftDeclarationPrinter`。 +- 值泛型与参数包:`makeRequest` 本来就拒绝这两种参数,RuntimeViewer 的 UI 也按不支持展示。 +- 成员签名的代换:运行时特化出的定义只打印头部和存储字段(成员按绑定后的名字查符号查不到),离线保持一致。 + +### 验证 + +- **离线与运行时逐字节对照**:对 fixture 里一组泛型类型与实参组合,分别用运行时(`MachOImage`)和离线(`MachOFile`)特化,打开字段偏移、类型布局、枚举布局、展开偏移几种注释,打印出的 interface 应当逐字节相同。覆盖 struct / class / 单 payload 与多 payload 泛型枚举 / 嵌套泛型 / 非泛型嵌套类型 / 关联类型字段 / `.boundGeneric` 实参。 +- 实例化类型名与运行时 `_mangledTypeName` 给出的名字结构相等;私有类型与约束 extension 里的类型用现场编译的 fixture。 +- 离线约束检查的每一档各有正反例;两个旧问题各有修复前失败、修复后通过的回归测试。 +- 渲染 A/B 验证:本提案不改未特化的打印,但动了打印路径与布局引擎,按项目规定跑一遍。 + +### 未经询问而采用的假设 + +- 公开 API 用 `Static` 前缀表示离线(`StaticSpecializationResult`、`staticPreflight`),与 `StaticLayoutCalculator`、`StaticFieldLayoutBackend` 的命名一致;离线的 `specialize` 与运行时版本同名,靠 `where MachO == …` 区分。 +- 离线执行只对 `MachOFile` 开放。`MachOImage` 的布局注释走运行时 metadata,给它一个没有 metadata 的特化定义只会丢注释。 +- 实参所在镜像必须在被特化类型所在镜像的依赖闭包里,否则布局按字段降级为 `unknown`,关联类型保持未投影。RuntimeViewer 让用户从别的、互不依赖的镜像里挑候选时就会这样,这是如实降级,不是错误。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-09-30 | 创建为 Draft | 用户:「把离线泛型特化实现一下,我记得之前在做静态布局的时候就提到过这个,目前泛型特化只有运行时才能用」 | +| 2026-09-30 | 不提供 CLI 入口 | 用户:这个功能是给 RuntimeViewer 离线运行用的,本库没有应用的地方 | +| 2026-09-30 | 实例化普查不做,另立提案 | 用户选择 | +| 2026-09-30 | 只接 interface 打印路径,不接 SwiftDump | 未询问自定:RuntimeViewer 只用 `SwiftDeclarationPrinter`,dump 路径在本库没有消费方 | +| 2026-09-30 | 值泛型与参数包不支持 | 未询问自定:与运行时特化器的 request 层一致 | +| 2026-09-30 | 约束检查分「确定违反则报错」与「证明不了则警告」两档 | 未询问自定:离线看不到运行时才知道的遵循关系,照运行时的标准一律报错会误拒合法的特化 | diff --git a/Documentations/README.md b/Documentations/README.md index d1095ff0e..d1261cc7c 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -158,6 +158,7 @@ selects names using each access's offset and width. | [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | +| [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(Draft)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数与运行时特化类型名被拍平两个旧问题。本库不提供 CLI 入口。 | | [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 的数量与内存实测。 | From b72638f8cb61739cfa88577cc1a594e4866de070 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 2 Oct 2026 12:34:24 +0800 Subject: [PATCH 12/49] feat(specialization): specialize generic types offline on a MachOFile GenericSpecializer.specialize calls the image's metadata accessor, so only a MachOImage loaded in the current process could be specialized; RuntimeViewer's planned offline mode reads a MachOFile and could not specialize at all. GenericSpecializer now has specialize(_:with:) and staticPreflight(selection:for:), mirroring the in-process steps without touching the runtime: - The selected arguments become type nodes, the parameters a same-type requirement fixes are filled in from it (GenericInstantiation), and the arguments are grouped by depth into a GenericArgumentBinding. The instantiated type name is built the way the runtime's _buildDemanglingForContext builds it (SymbolicDemangler.instantiatedTypeNode). The result is a StaticSpecializationResult. - The requirement check rejects only what it can prove violated: a value type given for AnyObject, a known class outside the required subtree, an associated-type same-type pair resolving to two different types. What it cannot prove offline is a warning. Both reuse the existing SpecializationValidation cases, which RuntimeViewer switches over exhaustively. - TypeDefinition.specialize(with:in:) takes the result. The specialized definition carries the binding in staticSpecialization where an in-process one carries metadata, and the interface printer renders from it the bound header, the substituted field types (associated types projected through their witnesses) and every layout comment, which the static layout engine now computes for a binding of any depth. Fixed on the way: - A generic parameter's depth counts only the contexts that declare parameters (GenericParameterDepthLayout). Five places counted ancestors instead: the specializer, the dump and interface headers, RuntimeMetadataTypeBuilder and AccessorThunkOwnerLayout named B in Outer.Middle.Inner "A2" while every field and requirement read "A1", and GenericArgumentEnvironment's walk of an instantiated type name stopped at an extension node. - An in-process specialization's typeName hangs each argument on its own level: Outer.Inner, not Outer.Inner. - An offline request dropped every requirement on another image's protocol: read from a file, that reference is a bind. - The static expanded field-offset tree projects a concrete type's associated types before naming them and descending into them. - The in-process path gives a specialized generic enum its Enum Layout comment as well, so the two paths compare byte for byte. OfflineSpecializationParityTests compiles a dylib, specializes it once read as a MachOFile and once dlopened as a MachOImage, and prints both with every layout comment on: byte-identical. Each fix above has a test that failed before it; 39 tests are new. The full suite passes on top of feature/runtime-viewer/find-navigator (2224 tests, exit 0). The rendering A/B against the proposal commit, before this branch was rebased onto find-navigator, covers 132 pairs: 90 identical, and the 42 that differ show only the corrected header depths, the projected expanded offsets, and a constrained extension's type substituted with the right argument. Proposal: draft-offline-generic-specialization (In Progress). --- AGENTS.md | 6 +- Documentations/Evolutions/README.md | 2 +- .../draft-offline-generic-specialization.md | 119 ++-- Documentations/Glossary.md | 21 + ...FieldLayoutRendererReaderSpecialization.md | 5 + .../Internal/Modules/SwiftLayout.md | 6 +- .../Internal/OfflineGenericSpecialization.md | 111 ++++ .../Internal/ProjectEvolutionLog.md | 10 + ...lizedInterfaceBoundRenderingRestoration.md | 11 + Documentations/Internal/StaticLayoutEngine.md | 3 +- Documentations/README.md | 5 +- Package.swift | 3 + .../GenericArgumentBinding.swift | 157 +++++ .../GenericParameterDepthLayout.swift | 171 +++++ .../RuntimeMetadataTypeBuilder.swift | 33 +- .../SwiftInspection/SymbolicDemangler.swift | 104 ++- .../SwiftLayout/EnumLayoutBridge.swift | 9 +- .../GenericArgumentEnvironment.swift | 69 +- ...erse+AssociatedTypeWitnessProjection.swift | 63 +- .../SwiftLayout/NestedFieldOffsetTree.swift | 32 +- .../SwiftLayout/StaticLayoutCalculator.swift | 45 ++ .../Resolution/AccessorThunkOwnerLayout.swift | 27 +- .../Definitions/TypeDefinition+Indexing.swift | 6 +- .../Definitions/TypeDefinition.swift | 23 +- .../GenericInstantiation.swift | 180 ++++++ ...ericSpecializer+StaticSpecialization.swift | 601 ++++++++++++++++++ .../GenericSpecializer.swift | 151 ++--- .../StaticSpecializationResult.swift | 77 +++ .../TypeDefinition+Specialization.swift | 172 ++++- .../DependentMemberProjection.swift | 25 +- .../Extensions/GenericContext+Dump.swift | 167 ++--- .../Extensions/Node+OpaqueType.swift | 38 +- .../FieldLayoutRenderer.swift | 24 +- .../RuntimeFieldLayoutBackend.swift | 36 +- .../StaticFieldLayoutBackend.swift | 31 +- .../StaticFieldLayoutProvider.swift | 64 ++ ...StaticSpecializationNodeSubstitution.swift | 25 + .../Output/SwiftDump/Dumper/ClassDumper.swift | 3 +- .../Output/SwiftDump/Dumper/EnumDumper.swift | 3 +- .../SwiftDump/Dumper/StructDumper.swift | 3 +- .../SwiftDump/Protocols/TypedDumper.swift | 6 +- ...wiftDeclarationPrinter+DiffRendering.swift | 2 +- .../SwiftDeclarationPrinter+Headers.swift | 47 +- .../SwiftDeclarationPrinter.swift | 13 +- .../GenericSpecializationFixture.swift | 304 +++++++++ ...GenericSpecializationFixtureIndexers.swift | 48 ++ .../MetadataAccessorTests.swift | 7 +- .../ProtocolGenericContextTests.swift | 3 +- .../GenericParameterDepthDumpTests.swift | 37 ++ .../RuntimeMetadataTypeBuilderTests.swift | 20 + .../GenericParameterDepthNamingTests.swift | 58 ++ .../BoundInstantiationLayoutTests.swift | 97 +++ ...nsionContextInstantiationLayoutTests.swift | 41 ++ .../CanonicalParameterDepthTests.swift | 77 +++ .../GenericSpecializationTests.swift | 1 + .../InstantiatedTypeNameTests.swift | 177 ++++++ .../OfflineSpecializationParityTests.swift | 186 ++++++ .../OfflineSpecializationTests.swift | 257 ++++++++ .../AccessorThunkOwnerLayoutDepthTests.swift | 32 + 59 files changed, 3649 insertions(+), 405 deletions(-) create mode 100644 Documentations/Internal/OfflineGenericSpecialization.md create mode 100644 Sources/Analysis/SwiftInspection/GenericArgumentBinding.swift create mode 100644 Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift create mode 100644 Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift create mode 100644 Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift create mode 100644 Sources/Declaration/SwiftSpecialization/StaticSpecializationResult.swift create mode 100644 Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift create mode 100644 Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift create mode 100644 Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixtureIndexers.swift create mode 100644 Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift create mode 100644 Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift create mode 100644 Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift create mode 100644 Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift create mode 100644 Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift create mode 100644 Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift create mode 100644 Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift create mode 100644 Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift create mode 100644 Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift diff --git a/AGENTS.md b/AGENTS.md index f2277b99a..4f0d49aa6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,14 +43,14 @@ One or two lines each; the linked document is the authority. - **Demangling** (upstream package) — mangled symbol → `Node` AST → printed Swift, plus the remangler. `Node.Kind` covers ~200 mangling node kinds. - **MachOSwiftSection** — the ABI model: the `__swift5_*` sections, every descriptor shape in them, and Swift's position-independent relative pointers. Self-contained — `MachOBase` only, no symbol index, no demangler; a descriptor exposes an implementation's *offset* and `SwiftInspection` attributes the name ([SelfContainedABILayer.md](Documentations/Internal/SelfContainedABILayer.md)). -- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). +- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). - **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). - **SwiftIndexing** — builds the declaration model from an image (`SwiftDeclarationIndexer.prepare()`), unifies extension containers, owns the per-image cache eviction. - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). - **SwiftPrinting** — renders the model as Swift source: keywords the mangling does not carry (`class` vs `static`, `final`), bound rendering of specialized definitions, export-status annotation and `--exported-only` filtering. -- **SwiftSpecialization** — runtime generic specialization (`GenericSpecializer`, `ConformanceProvider`); grafts `specialize(...)` onto `TypeDefinition`. +- **SwiftSpecialization** — generic specialization (`GenericSpecializer`, `ConformanceProvider`): in-process through the metadata accessors on a `MachOImage`, and offline on a `MachOFile` (`StaticSpecializationResult`: the instantiation's name and a `GenericArgumentBinding`, which the printer and the static layout engine render from — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)); grafts `specialize(...)` onto `TypeDefinition`. - **SwiftInterface** — the orchestrator: single-version, two-version diff, and N-version evolution interfaces, all three over one shared structure walk. [Modules/SwiftInterface.md](Documentations/Internal/Modules/SwiftInterface.md). - **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). @@ -300,4 +300,4 @@ Keeping this file's module list and `Documentations/README.md`'s index in sync w ## Work in progress -**GenericSpecializer** (`Sources/Declaration/SwiftSpecialization/`) — interactive runtime specialization of generic types. Core implementation complete with tests. Two-step API: `makeRequest()` returns parameters and candidates, `specialize()` executes with the user's selections. Only protocol requirements need witness tables, passed in requirement order; `baseClass` / `layout` / `sameType` need validation only. Generic parameter names are derived from depth/index (A, B, A1, …) because the binary does not preserve them. +**GenericSpecializer** (`Sources/Declaration/SwiftSpecialization/`) — interactive runtime specialization of generic types. Core implementation complete with tests. Two-step API: `makeRequest()` returns parameters and candidates, `specialize()` executes with the user's selections. Only protocol requirements need witness tables, passed in requirement order; `baseClass` / `layout` / `sameType` need validation only. Generic parameter names are derived from depth/index (A, B, A1, …) because the binary does not preserve them. **A depth counts only the contexts that declare parameters — take it from `GenericParameterDepthLayout`, never from the parent chain or `TargetGenericContext.depth`**: a generic type that declares nothing (`Outer.Middle`) opens no depth, and one extension context can span several (`extension Outer.SecondMiddle where …`). Five readers once counted ancestors and named `B` in `Outer.Middle.Inner` as `A2` while every field and requirement read `A1`. The offline path (`specialize` on a `MachOFile`) is complete too; the specialization's `typeName` hangs each argument on its own level (`Outer.Inner`) on both paths. diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index b0e2a9b65..edfa51f70 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -70,4 +70,4 @@ | draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | In Progress | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | -| draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | Draft | +| draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | diff --git a/Documentations/Evolutions/draft-offline-generic-specialization.md b/Documentations/Evolutions/draft-offline-generic-specialization.md index 6355222e4..78a59d5da 100644 --- a/Documentations/Evolutions/draft-offline-generic-specialization.md +++ b/Documentations/Evolutions/draft-offline-generic-specialization.md @@ -1,12 +1,12 @@ # Draft - 离线泛型特化:不经 runtime 特化泛型类型并完整打印 -- **状态**: Draft +- **状态**: In Progress - **创建日期**: 2026-09-30 -- **最后更新**: 2026-09-30 +- **最后更新**: 2026-10-02 - **所属愿景**: 无 - **关联文档**: [StaticLayoutEngine.md](../Internal/StaticLayoutEngine.md)「后续工作」里的「用户手动特化前端」一条;[SpecializedInterfaceBoundRenderingRestoration.md](../Internal/SpecializedInterfaceBoundRenderingRestoration.md)(运行时特化的打印机制);RuntimeViewer 的 [0003-generic-type-specialization](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/main/Documentations/Evolutions/0003-generic-type-specialization.md)(消费方的 UI 流程) -- **实现分支 / PR**: `feature/offline-generic-specialization`(未开始实现) -- **配套文档**: 待定 +- **实现分支 / PR**: `feature/offline-generic-specialization`,叠在 `feature/runtime-viewer/find-navigator` 之上,须在它之后合入(见决策日志 2026-10-02) +- **配套文档**: [OfflineGenericSpecialization.md](../Internal/OfflineGenericSpecialization.md)(实现说明) ## 摘要 @@ -36,68 +36,102 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) / ### 改动清单 -- **SwiftInspection**:新增公开的 `GenericArgumentBinding`,表示「某个泛型签名的参数被绑定到哪些实参」,按 canonical depth 分组(`argumentsByDepth: [[Node]]`),并提供一个只做显示用的代换(`dependentGenericParamType` 按 `(depth, index)` 换成实参,metatype 里面也换)。在 `SymbolicDemangler.swift:460` 的 `buildContextDescriptorMangling` 旁边新增实例化类型名的构造:给定类型描述符和全部实参,产出绑定后的类型节点(`Outer.Inner`)和对应的 `GenericArgumentBinding`。它移植的是运行时 `stdlib/public/runtime/Demangle.cpp` 的 `_buildDemanglingForContext`:沿描述符路径从外到内,某层上下文的累计参数数比已用掉的多,就把多出来的那几个实参挂在这一层;extension 层挂在被扩展的类型上。于是离线得到的名字和在线模式下运行时给出的名字形状一致,名字里的各部分(私有鉴别符、C 导入类型的身份)仍由 `SymbolicDemangler` 生成。 +按实际落地的形状记录;设计细节见实现说明 [OfflineGenericSpecialization.md](../Internal/OfflineGenericSpecialization.md)。 + +- **SwiftInspection**: + - 新增 `GenericParameterDepthLayout`:一个 generic context 的参数每层几个。层号只数声明了参数的上下文——本身不声明参数的嵌套类型不开层,extension 按被扩展类型拆成几层。见下文「层号错数整类修复」。 + - 新增公开的 `GenericArgumentBinding`:按层分组的实参(`argumentsByDepth: [[Node]]`),只做显示用的代换(metatype 里也换),以及从实例化类型节点读回 binding 的遍历(`argumentListsByLevel(ofInstantiatedTypeNode:)`,会走进 extension 节点的被扩展类型)。 + - `SymbolicDemangler.instantiatedTypeNode(for:binding:in:)`:移植运行时 `_buildDemanglingForContext`,给原有的 `buildContextDescriptorMangling` 加一个可选的 `ContextInstantiation`,名字的其余部分与未绑定的名字同源。extension 层把实参代换进被扩展类型;被扩展类型本身是嵌套泛型时运行时拼出的名字是畸形的(全部实参塞进最内层),离线按层绑定,这是有意的不同。 - **SwiftSpecialization**: - - `GenericSpecializer`(`GenericSpecializer.swift`)新增 `where MachO == MachOFile` 的扩展,放在 `:1320` 运行时执行扩展的旁边:`specialize(_:with:)` 返回 `StaticSpecializationResult`,`staticPreflight(selection:for:)` 是 `runtimePreflight` 的离线对应。 - - 实参取节点:`.candidate` 取候选的 `TypeName` 节点;`.boundGeneric` 用绑定在候选自己镜像上的内层 specializer 递归离线特化,取内层结果的类型节点;`.metatype` / `.metadata` / `.specialized` 用宿主进程的运行时名字(`RuntimeTypeNameDemangling`),不调用目标镜像的任何代码。 - - 没有 key argument 的参数(被同型约束钉死的,例如 `extension Outer where A == Int { struct Inner }` 里的 `A`)由约束的右侧补齐。 - - `StaticSpecializationResult` 携带类型描述符、绑定后的 `TypeName`、`GenericArgumentBinding` 和逐参数的解析结果(参数名、实参节点、`.boundGeneric` 的内层结果)。 - - `TypeDefinition+Specialization.swift` 新增两个 `specialize(with: StaticSpecializationResult, …, in: MachOFile)` 重载,与 `:120` / `:166` 的运行时版本对应(含嵌套派生)。 -- **SwiftDeclaration**:`TypeDefinition`(`TypeDefinition.swift:152` 的 `metadata` 旁)新增 `staticSpecialization: GenericArgumentBinding?`。运行时特化填 `metadata`,离线特化填这个,打印器按哪个非空选路径。 + - `GenericSpecializer+StaticSpecialization.swift`:`where MachO == MachOFile` 扩展的 `specialize(_:with:)`(返回 `StaticSpecializationResult`)与 `staticPreflight(selection:for:)`。实参取节点的方式、约束检查的两档见下文。 + - `GenericInstantiation`:从 key 实参补齐被 same-type 约束钉死的参数(约束右侧代换已知实参、投影关联类型,反复直到没有进展),按层分组,拼实例化类型名。离线结果和在线特化的类型名都用它。 + - `StaticSpecializationResult` 携带类型描述符、实例化类型名、`GenericArgumentBinding`、所用的 `SpecializationSelection`(派生嵌套类型用)和逐参数的解析结果。 + - `TypeDefinition+Specialization.swift` 新增 `specialize(with: StaticSpecializationResult, in:)` 与 `specialize(with:derivingNestedSpecializationsWith:in:)`,后者不需要另传 selection 与节点,都在结果里。 + - `buildRequirement` 认 `.symbol`:读文件时,对别的镜像里协议的引用落在 bind 上,原先整条需求被丢掉(见「顺带修的问题」)。 +- **SwiftDeclaration**:`TypeDefinition.staticSpecialization: GenericArgumentBinding?`,与运行时特化的 `metadata` 互斥。 - **SwiftLayout**: - - `GenericArgumentEnvironment` 能从 `GenericArgumentBinding` 建环境。现在只有 `:147` 的 depth-0 版本,嵌套泛型的内层实参绑不上。 - - `StaticLayoutCalculator` 的 `fieldLayout` / `typeLayout(forDescriptor:)` / `typeLayout(forMangledTypeName:inContextOfDescriptor:)` / `enumCaseLayoutResult`、`nestedFieldOffsetTree` 各加一个接受 `GenericArgumentBinding` 的重载。 - - `EnumLayoutBridge.swift:307` 的 `enumCaseLayoutResult` 目前不接受实参环境,要补上,特化后的泛型枚举才有逐 case 的布局。 + - `GenericArgumentEnvironment.make(forBinding:)`;`make(forInstantiatedTypeNode:)` 改用共享的节点遍历,能穿过 extension 节点。 + - `StaticLayoutCalculator` 新增带 `genericArgumentBinding:` 的 `fieldLayout(of:)`、`typeLayout(forMangledTypeName:inContextOfDescriptor:)`、`enumCaseLayoutResult(forDescriptor:)` 与 `nestedFieldOffsetTree(forMangledTypeName:baseOffset:depthLimit:)`;`EnumLayoutBridge.enumCaseLayoutResult` 接受实参环境。提案原列的 `typeLayout(forDescriptor:)` 没有调用方,未加。 + - `ImageUniverse.projectingConcreteMembers(in:)`:把具体类型的关联类型按 witness 记录投影掉,静态展开偏移树也用它(见「顺带修的问题」)。 - **SwiftDeclarationRendering**: - - `FieldLayoutRenderState` / `FieldLayoutRenderer`(`FieldLayoutRenderer.swift:38` / `:139`)携带 `GenericArgumentBinding`,`StaticFieldLayoutBackend` 据此向 provider 要特化后的布局。 - - `StaticFieldLayoutProvider`(`StaticFieldLayoutProvider.swift:36`)的新方法带默认实现,已有的外部实现不受影响。 - - 新增离线的字段类型代换:先按 binding 代换,再把 `C.Element` 这类关联类型经 `DependentMemberProjection` 投影成具体类型;投影不了的保留原样。 -- **SwiftPrinting**:`SwiftDeclarationPrinter.swift:275` 与 `SwiftDeclarationPrinter+Headers.swift:37` / `:359` / `:436` 现在只认 `metadata`。改为:头部的绑定节点、字段代换、布局注释三处都在「运行时 metadata」与「离线 binding」之间二选一。 + - `StaticFieldLayoutProvider` 新增四个带 binding 的方法,默认实现返回空,库外实现不受影响;`MachOFileStaticFieldLayoutProvider` 实现它们。 + - `FieldLayoutRenderState` / `FieldLayoutRenderer` 携带 `genericArgumentBinding`,`StaticFieldLayoutBackend` 据此要特化后的布局。`FieldLayoutRenderable.precomputedStaticAggregateFieldLayout` 多一个 binding 参数(只有库内的 `MachOFile` / `MachOImage` 遵循)。 + - `StaticSpecializationNodeSubstitution` 与 `DependentMemberProjection.projectingConcreteMembers`:字段类型的离线代换与关联类型投影。 + - `RuntimeFieldLayoutBackend`:带特化 metadata 的泛型 enum 也出 Enum Layout 注释(决策日志 2026-10-01)。 +- **SwiftPrinting**:`boundTypeNode(of:)` 统一给出特化定义头部的绑定名字(运行时取 metadata 的名字,离线取实例化类型名),`renderTypeDeclarationHeader` 改收这个节点;`renderModelFields` 的字段代换与布局注释在 metadata 与 binding 之间二选一。 -明确不动:运行时特化的计算路径(`specialize` / `runtimePreflight` / `resolveAssociatedTypeWitnesses`);SwiftDump 与 dump 输出;CLI;未特化定义的打印。 +明确不动:运行时特化的计算路径(`specialize` / `runtimePreflight` / `resolveAssociatedTypeWitnesses`);SwiftDump 的特化打印;CLI。原列的「未特化定义的打印」因层号整类修复与展开偏移树的投影而改变,见决策日志。 ### 离线约束检查 -检查逐条对应 `runtimePreflight`,但离线能拿到的证据不同,所以分两档: +检查逐条对应 `runtimePreflight`,按离线能拿到的证据分两档: - **报错并拒绝**:结构上确定违反的约束。 - - `AnyObject` 参数给了 struct / enum。 - - 父类约束:实参不在索引记录的父类子树里。 - - 具体同型约束与实参对不上。 + - `AnyObject` 参数给了 struct / enum / tuple;宿主类型按 metadata 的 kind 判断。 + - 父类约束:索引认识、但不在父类子树里的类;宿主类沿它自己完整的父类链按名字比较。 + - 关联类型的 same-type 约束:两侧都解析成具体类型且不相等。被钉死成具体类型的 key 参数不存在(编译器会把它变成非 key),所以实际只有关联类型这一种。 - **只给警告、照样特化**:离线证明不了的约束。 - - 协议遵循。候选列表本来就按 indexer 里的遵循记录筛过;`.boundGeneric` 的条件遵循、别的模块补上的遵循、ObjC 协议、marker 协议都查不全。 - - 关联类型约束(`A.Element: Hashable`)投影不出来的情况。 - - 父类约束在 indexer 没有类层级信息时。 + - 协议遵循:索引记录里查不到(可能是条件遵循、别的模块补上的、运行时合成的),或实参类型不在任何被索引的镜像里。 + - 关联类型投影不出来。 + - 索引没有该父类的类层级信息,或实参类不在任何被索引的镜像里。 + +错误与警告沿用 `SpecializationValidation` 现有的 case,`SpecializerError` 也不加 case:RuntimeViewer 对这几个枚举做了穷尽 `switch`。关联类型的需求按访问路径命名(`A.Element`),与 request 的 `AssociatedTypeRequirement.fullPath` 一致。 + +### 层号错数整类修复 + +原列为「顺带修的旧问题 1」,只涉及特化器。用 0.21.0 的 CLI 跑现场编译的 fixture 证实它是一类问题:未特化的 interface 与 dump 头部同样错(`struct Inner { var innerElement: A1 }`、`struct DeepConstrainedInner where A2: Hashable`)。用户选择整类修复,五处改用 `GenericParameterDepthLayout`: + +| 位置 | 错数的后果 | +|---|---| +| `GenericSpecializer.buildParameters` | 参数名错,按名字收集需求时漏掉,候选不过滤,运行时特化少算 witness table 而失败 | +| `GenericContext+Dump`(dump 与 interface 头部) | 参数子句与字段对不上 | +| `RuntimeMetadataTypeBuilder.bindings` | 进程内节点还原 metadata 时找不到实参 | +| `AccessorThunkOwnerLayout` | thunk 读到的实参被标到不存在的坐标 | +| `GenericArgumentEnvironment.make(forInstantiatedTypeNode:)` | 遍历在 extension 节点停下,约束 extension 里类型的实例化只收到最内层实参,引用它的字段整体降级 | + +`TargetGenericContext.depth` 保留原义(泛型祖先个数,baseline 仍记录它),只是不再拿它命名参数。 -错误与警告沿用 `SpecializationValidation` 现有的 case,`SpecializerError` 也不加 case:RuntimeViewer 对这几个枚举做了穷尽 `switch`,加 case 会让它编译失败。 +### 顺带修的问题 -### 顺带修的两个旧问题 +1. **运行时特化的类型名被拍平**:`TypeDefinition.makeSpecializedDefinition` 改用 `GenericInstantiation`,`Outer.Inner` 不再写成 `Outer.Inner`,派生的 `NestedHost.Plain` 不再写成 `NestedHost.Plain`。实参个数与 key 参数对不上时退回旧形状;`typeArgumentNodes` 传 `nil` 时仍保持未绑定的名字。 +2. **离线 request 丢掉跨镜像协议需求**(实现时发现):读文件时 `B: Hashable` 的协议引用解析成 bind 的符号(`$sSHMp`),`buildRequirement` 只认已解析的 descriptor,整条需求被丢掉——候选不过滤,witness table 不计数。现在按符号名还原协议名;在线路径不受影响。 +3. **静态展开偏移树不投影具体类型的关联类型**(实现时发现):`ElementsHolder<[Int]>.first` 原先显示为 `Swift.Optional.Element>` 并在那里停下,运行时的遍历显示 `Swift.Optional` 并继续展开。现在先投影再命名和展开,未特化类型里出现的实例化字段同样受益。 -两处都在本提案要复用的代码上,不修的话离线结果也会错: +### 不在本次范围(实现时发现,未修) -1. **参数层数可能数错(待测试确认)**:`GenericSpecializer.swift:164` 的 `perLevelNewParameterCounts` 把父链上每个泛型上下文都当成一层。一个本身不声明参数、只因嵌在泛型类型里才算泛型的中间层(`Outer.Middle.Inner` 的 `Middle`),会占掉一个层号。于是 `B` 被命名成 `A2`,而字段记录与约束里写的是 canonical 的 `A1`(τ_1_0),这个参数的约束就收集不到。约束 extension 里声明的泛型类型可能有同样的问题。先用现场编译的 fixture 写出会失败的测试,确认后改为只数真正声明参数的层,和上面的实例化类型名构造共用同一套计数。fixture 里目前没有这两种形状,所以现有测试不会发现。 -2. **运行时特化的类型名被拍平**:`TypeDefinition+Specialization.swift:333` 的 `boundGenericTypeName` 把全部实参放进最内层,`Outer.Inner` 被写成 `Outer.Inner`,`GenericOuter.Inner` 被写成 `GenericOuter.Inner`。打印出来的头部不受影响(它用的是 metadata 的运行时名字),但 `typeName` 是 RuntimeViewer 侧边栏的显示名和标识。改为用上面的实例化类型名构造,在线与离线两种模式的名字才一致。`typeArgumentNodes` 传 `nil` 时仍保持未绑定的名字,这个现有约定不变。 +- 引用「嵌套泛型类型的约束 extension 里声明的类型」的字段(`Outer.SecondMiddle.DeepConstrainedInner`)demangle 失败(`unexpected(at: 11)`),引用它的整个类型从 interface 里消失。 +- 引用约束 extension 里类型的类型,其 memberwise `init` 后面多出一个 `where A == Swift.Int`。 +- class 头部的父类不代换实参(`class Sub: Base`),在线路径也是这样。 +- 在线特化的调用方不传 `typeArgumentNodes` 时,定义保持未绑定的名字,会查到并打印未代换的成员。 ### 不做 - CLI 入口:用户明确这是给 RuntimeViewer 离线模式用的,本库没有使用它的地方。 - 实例化普查(自动为二进制里出现过的每个 `Foo` 算布局):另立提案。 -- SwiftDump / dump 路径:RuntimeViewer 只用 `SwiftDeclarationPrinter`。 +- SwiftDump / dump 路径的离线特化:RuntimeViewer 只用 `SwiftDeclarationPrinter`。 - 值泛型与参数包:`makeRequest` 本来就拒绝这两种参数,RuntimeViewer 的 UI 也按不支持展示。 - 成员签名的代换:运行时特化出的定义只打印头部和存储字段(成员按绑定后的名字查符号查不到),离线保持一致。 ### 验证 -- **离线与运行时逐字节对照**:对 fixture 里一组泛型类型与实参组合,分别用运行时(`MachOImage`)和离线(`MachOFile`)特化,打开字段偏移、类型布局、枚举布局、展开偏移几种注释,打印出的 interface 应当逐字节相同。覆盖 struct / class / 单 payload 与多 payload 泛型枚举 / 嵌套泛型 / 非泛型嵌套类型 / 关联类型字段 / `.boundGeneric` 实参。 -- 实例化类型名与运行时 `_mangledTypeName` 给出的名字结构相等;私有类型与约束 extension 里的类型用现场编译的 fixture。 -- 离线约束检查的每一档各有正反例;两个旧问题各有修复前失败、修复后通过的回归测试。 -- 渲染 A/B 验证:本提案不改未特化的打印,但动了打印路径与布局引擎,按项目规定跑一遍。 +- **离线与在线逐字节对照**(`OfflineSpecializationParityTests`):`GenericSpecializationFixture` 现场编译一个 dylib,同一个文件按 `MachOFile` 读、`dlopen` 后按 `MachOImage` 读,两条路径分别特化,打开字段偏移、类型布局、enum 布局、展开偏移四种注释后打印,逐字节相同。覆盖 struct、final class、泛型父类的 class、单 payload 与多 payload 泛型 enum、关联类型字段、非声明层下的嵌套泛型、派生的嵌套类型、自带参数的嵌套泛型、私有类型、`.boundGeneric` 实参。两条路径按设计不同、未特化类型也一样的三处(payload extra inhabitant 里的空 case、tuple 字段、泛型标准库 struct 的展开遍历深度)不在对照范围,写在实现说明里。 +- **实例化类型名**(`InstantiatedTypeNameTests`):与运行时名字(经 `RuntimeTypeNameDemangling`)结构相等,含私有类型、约束 extension 里的类型(非 key 参数由约束补齐)、跨模块 extension 里的类型;嵌套泛型的约束 extension 单独断言离线的正确形状。 +- **离线执行与约束检查**(`OfflineSpecializationTests`):request 保留跨镜像协议需求;结果的 binding 与类型名;`.candidate` / `.boundGeneric`;泛型候选的类型化错误;每一档约束检查的正反例。 +- **带 binding 的布局**(`BoundInstantiationLayoutTests`):字段偏移与运行时 metadata 的 field offset vector 相同;展开偏移树投影关联类型。 +- **修复前失败的回归测试**:层号五处(`GenericParameterDepthNamingTests`、`GenericParameterDepthDumpTests`、`CanonicalParameterDepthTests`、`AccessorThunkOwnerLayoutDepthTests`、`RuntimeMetadataTypeBuilderTests.nestedGenericBehindNonDeclaringLevelResolvesItsRequirement`、`ExtensionContextInstantiationLayoutTests`),以及运行时类型名拍平、跨镜像协议需求、展开偏移树投影、在线 Enum Layout 四项(把对应修改临时退回旧行为后确认失败)。 +- **全量测试**:`swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra)2210 个测试 / 420 个套件全部通过,原始退出码 0;唯一的 known issue 是早已登记的 `SymbolicManglingIndexTests`。之后把测试 fixture 的单字母泛型参数名改成完整名称,受影响的套件重跑通过(147 个测试)。 +- **rebase 后重跑**(2026-10-02,分支已 rebase 到 find-navigator 的 `86f65341` 之上,带 `USING_LOCAL_DEPENDENCIES=1` 用本地兄弟依赖构建):全量 2224 个测试 / 424 个套件全部通过,原始退出码 0,正好是 rebase 前的 2210 个加上 find-navigator 新增的 14 个;known issue 仍只有 `SymbolicManglingIndexTests`。渲染 A/B 没有重跑。 +- **渲染 A/B**(基线 `b2b7d997`,两侧 release CLI,依赖版本逐个相同):共 132 对,90 对逐字节一致,42 对有差异。每一处差异都核对过,都是本提案预期的改变;两侧各重跑一遍有差异的场景,输出不变,排除了不确定性。 + - 脚本本身的 84 对(15.5 归档 cache;iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器;进程内 `MachOImage` 与当前系统 cache 文件,后两者带布局注释):22 对有差异,全部是头部参数名的修正。Combine 的 `Optional.Publisher.Inner`、`Result.Publisher.Inner` 与 SwiftUICore 的 `TimeDataSource.Resolver.ResolvedOffsetBox` 都嵌在不声明参数的中间层下,头部从 `` 改成 ``,与同一行的 `where` 子句(一直写的是 `A1`)终于一致。 + - 脚本写死的 `26.6.2` 归档目录不存在(卷上现在叫 `26.6`),所以手动补了 26.6 与 27.0 两份 cache 的 24 对:8 对有差异,同样只是上面三个头部。 + - 脚本的 CLI 腿只用默认参数、不出布局注释,于是另跑了打开全部布局注释(含展开偏移)的 24 对(26.6 cache 与 iOS 26.5 模拟器):12 对有差异。除了上面的头部,都是展开偏移树的改进:具体类型的关联类型投影成 witness 后再命名、并继续展开(`Angle.Animatable.AnimatableData` → `Swift.Double`,`BigString._Chunk.RopeElement.Summary` → `BigString.Summary`,`SubviewsCollection.Collection.Index` → `Swift.Int`,`ViewFrame.Animatable.AnimatableData` 展开成 `AnimatablePair<…>` 的各层字段);以及约束 extension 里类型的实参代换修正(`MeasurementView` 的字段 `Measurement.FormatStyle` 展开出的子字段,原先错印成 `Measurement`)。 ### 未经询问而采用的假设 -- 公开 API 用 `Static` 前缀表示离线(`StaticSpecializationResult`、`staticPreflight`),与 `StaticLayoutCalculator`、`StaticFieldLayoutBackend` 的命名一致;离线的 `specialize` 与运行时版本同名,靠 `where MachO == …` 区分。 +- 公开 API 用 `Static` 前缀表示离线(`StaticSpecializationResult`、`staticPreflight`、`staticSpecialization`),与 `StaticLayoutCalculator`、`StaticFieldLayoutBackend` 的命名一致;离线的 `specialize` 与运行时版本同名,靠 `where MachO == …` 区分。 - 离线执行只对 `MachOFile` 开放。`MachOImage` 的布局注释走运行时 metadata,给它一个没有 metadata 的特化定义只会丢注释。 -- 实参所在镜像必须在被特化类型所在镜像的依赖闭包里,否则布局按字段降级为 `unknown`,关联类型保持未投影。RuntimeViewer 让用户从别的、互不依赖的镜像里挑候选时就会这样,这是如实降级,不是错误。 +- 实参所在镜像必须在被特化类型所在镜像的依赖闭包里,否则布局按字段降级为 `unknown`,关联类型保持未投影。这是如实降级,不是错误。 +- 对照测试用现场编译的 dylib 而不是 SymbolTestsCore:同一个文件要能同时按两种方式读。 ## 决策日志 @@ -109,3 +143,12 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) / | 2026-09-30 | 只接 interface 打印路径,不接 SwiftDump | 未询问自定:RuntimeViewer 只用 `SwiftDeclarationPrinter`,dump 路径在本库没有消费方 | | 2026-09-30 | 值泛型与参数包不支持 | 未询问自定:与运行时特化器的 request 层一致 | | 2026-09-30 | 约束检查分「确定违反则报错」与「证明不了则警告」两档 | 未询问自定:离线看不到运行时才知道的遵循关系,照运行时的标准一律报错会误拒合法的特化 | +| 2026-10-01 | Draft → Accepted → In Progress | 用户:「开始实现提案」 | +| 2026-10-01 | 参数层数的错数整类一起修,不只修特化器 | 用 0.21.0 的 CLI 跑现场编译的 fixture 证实:未特化 interface 的头部同样错(`struct Inner { var innerElement: A1 }`),`RuntimeMetadataTypeBuilder` 与 `AccessorThunkOwnerLayout` 用的是同一种数法。用户选择整类修复,接受未特化输出对这类形状的变化 | +| 2026-10-01 | 在线模式也给特化后的泛型枚举出 Enum Layout 注释 | 运行时后端对任何泛型枚举都不出这项注释(`RuntimeFieldLayoutBackend.swift:607`),离线却能算出,逐字节对照因此做不到。用户选择在线也补上 | +| 2026-10-01 | 对照测试用现场编译的 dylib | 未询问自定:同一个文件要能按 `MachOFile` 读、又能 `dlopen` 成 `MachOImage`,SymbolTestsCore 与测试二进制都做不到这一点 | +| 2026-10-01 | 嵌套泛型的约束 extension 里的类型,实例化名字按层绑定,不照搬运行时 | 未询问自定:运行时把全部实参塞进被扩展类型最内层的列表,拼出的名字不对应任何实例化;其余形状与运行时结构相等 | +| 2026-10-01 | `buildRequirement` 认 `.symbol` | 实现时发现:读文件时跨镜像协议的引用解析成 bind 的符号,离线 request 一直丢掉这类需求;修复前确认测试失败 | +| 2026-10-01 | 静态展开偏移树先投影具体类型的关联类型 | 实现时发现:对照测试里 `first` 字段静态显示 `Array.Element` 并停止展开,运行时显示 `Int` 并继续展开;这也改变未特化类型里实例化字段的展开,修复前确认测试失败 | +| 2026-10-01 | 不加 `typeLayout(forDescriptor:genericArgumentBinding:)` | 未询问自定:渲染路径没有调用方 | +| 2026-10-02 | 分支 rebase 到 `feature/runtime-viewer/find-navigator`(`86f65341`)之上,须在它之后合入 | 用户:「rebase一下find-navigator,然后提交」。两边都改过的 11 个文件里,代码文件全部自动合并,文档索引与演进账本两处冲突两边内容都保留。find-navigator 的最后一个提交要用 swift-semantic-string 尚未发版的 `DefinitionRegion`,所以本分支现在要用本地兄弟依赖构建,也要等那个版本发布、本库抬高版本下限之后才能落地 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index e70e16839..f297ebb48 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -80,6 +80,13 @@ - **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`、`Sources/MachO/MachOPointers/`、`Sources/MachO/MachOResolving/Resolvable.swift` - **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) +### depth(泛型参数层号,`GenericParameterDepthLayout`) + +泛型参数 `(depth, index)` 坐标的前一半,mangling 里的 `τ_1_0`、打印出的 `A1`。**层号只数声明了参数的上下文**:本身不声明参数、只因嵌在泛型类型里才算泛型的类型(`Outer.Middle`)不开新层;一个 extension 上下文可能跨好几层(`extension Outer.SecondMiddle where …` 同时覆盖 `Outer` 与 `SecondMiddle` 的层)。generic context descriptor 只记录累计的参数列表,不记录层的边界,从父链数祖先会数错;层号一律从 `GenericParameterDepthLayout` 取。`TargetGenericContext.depth` 是泛型祖先的个数,不是层号。 + +- **主要出现在**:`SwiftInspection.GenericParameterDepthLayout`、`GenericSpecializer` 的参数命名、dump / interface 的泛型参数子句 +- **延伸阅读**:[OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)「参数的层号只数声明了参数的上下文」 + ### dependency closure(依赖闭包) 一个 root 二进制经 `LC_LOAD_DYLIB` 家族 load command 解析出的依赖镜像集合(`MachODependencies.DependencyClosure`)。本项目里的「闭包」默认指**传递**闭包:BFS 递归、按裸镜像名去重、root 排除、解析顺序是契约的一部分(`SwiftLayout.ImageUniverse` 按此顺序惰性索引、命中即停)。同一类型也承载 `.direct` 遍历(只取 root 自己的一层),`SwiftInterfaceBuilderDependencies` 用的是这一种——名字里的「闭包」在那里只是复用同一个结果类型。定位不到的依赖记入 `unresolvedLoadNames`,不算失败。 @@ -153,6 +160,13 @@ linker 把字节相同的函数体合并到同一地址的优化。后果是「 - **主要出现在**:`Descriptor+MethodDescriptorSymbols.swift`、`ClassDumper`、`TypeDefinition.index`、`FinalKeywordICFRegressionTests`、`VTableSlotAttributionTests` - **延伸阅读**:[提案 vtable-slot-attribution](Evolutions/0020-vtable-slot-attribution-via-method-descriptor-symbols.md)、[提案 0006](Evolutions/0006-final-keyword-and-lazy-accessor-type-recovery.md) +### instantiated type name(实例化类型名) + +一个泛型类型某个实例化的名字,实参挂在声明对应参数的那一层:`Outer.Inner`、`Outer.Middle`。这是运行时 `_buildDemanglingForContext` 给实例化起名的形状;`SymbolicDemangler.instantiatedTypeNode(for:binding:in:)` 移植它,离线特化的结果与在线特化的 `TypeDefinition.typeName` 都用它。不要与把全部实参放进最内层的旧形状(`Outer.Inner`)混淆。 + +- **主要出现在**:`SymbolicDemangler.instantiatedTypeNode`、`GenericInstantiation`、`StaticSpecializationResult.typeName` +- **延伸阅读**:[OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)「实例化类型名」 + ### large-stack executor(大栈执行器,`LargeStackTaskExecution`) swift-demangling 0.6.3 起提供的 `TaskExecutor`(`StackSafeExecutor.taskExecutor`,线程栈 16 MB,`@_spi(Internals)`)。demangler 每次 demangle / print / remangle 都按**调用线程的剩余栈**决定要不要跳到它的 8 MB 线程池——协作线程只有 512 KB,探针永远不过,async 打印循环因此每打印一个符号付一次线程往返;task 跑在大栈执行器的线程上时探针每个入口都通过,全程原地执行、零跳转。本库通过 `MachOSymbols.LargeStackTaskExecution.run` 在库入口(索引器 prepare、interface builder、printer 逐定义入口、diff / evolution、dump)自装偏好,宿主零改动;macOS 15 / iOS 18 以下静默回退为原样执行。与「跳转池」(demangler 自己的 8 MB `LargeStackThreadPool`,同步 `withLargeStack` 批次用)是两个池:执行器的 job 是整段 task,会占线程上百秒,不能挤占同步跳转的额度。 @@ -248,6 +262,13 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:`SwiftInspection/ObjCAncestorResolver.swift`、`SwiftInspection/ObjCClassMethodIndex.swift`、`MachODependencies/DependencyPlatforms.swift` - **延伸阅读**:[提案 0049-objc-ancestor-dependency-closure](Evolutions/0049-objc-ancestor-dependency-closure.md)、[ObjCMemberRecovery.md](Internal/ObjCMemberRecovery.md) +### offline specialization(离线特化) + +不经 runtime 特化一个从文件读出的泛型类型:`GenericSpecializer.specialize(_:with:)` 把每个实参变成类型节点,得到实例化类型名与按层分组的实参(`GenericArgumentBinding`),打印器与静态布局引擎据此出绑定头部、代换后的字段类型和布局注释。相对的「运行时特化」(在线)调用镜像里的 metadata accessor,只能用于加载在当前进程里的 `MachOImage`。特化后的定义里,离线的带 `staticSpecialization`,在线的带 `metadata`。 + +- **主要出现在**:`GenericSpecializer+StaticSpecialization.swift`、`StaticSpecializationResult`、`TypeDefinition.staticSpecialization` +- **延伸阅读**:[OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md) + ### permutation 二分(permutation binary search) 不给数据本体排序,而是另存一条「按某序排列的下标数组」(permutation),查询时在这条下标序列上二分。`SymbolTable.rowsSortedByName` 即名字序 permutation:行本体保持插入序不动,名字查找二分这条 `[UInt32]`。替代了被退役的名字键字典 `tableRowByName`。 diff --git a/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md b/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md index 80ae5d334..faeafeac3 100644 --- a/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md +++ b/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md @@ -138,3 +138,8 @@ configuration/isGeneric/staticAggregateFieldLayout,不含 `Self`)传递 rend 相关:[StaticLayoutEngine.md](StaticLayoutEngine.md)、[StaticLayoutDependencyClosure.md](StaticLayoutDependencyClosure.md)、 [FieldMetadataRenderingMigration.md](FieldMetadataRenderingMigration.md)。 + +## 离线特化的实参(2026-10-01) + +离线泛型特化([OfflineGenericSpecialization.md](OfflineGenericSpecialization.md))的定义没有 metadata,只有一份按层分组的实参(`GenericArgumentBinding`)。它沿同一条 reader 特化的路径传下去:`FieldLayoutRenderer` 的 `init` 多一个 `genericArgumentBinding:`,存进 `FieldLayoutRenderState.genericArgumentBinding`;`FieldLayoutRenderable.precomputedStaticAggregateFieldLayout` 多一个同名参数,`MachOFile` 的实现据此向 provider 要这个实例化的字段布局,`MachOImage` 的实现照旧返回 `nil`。`StaticFieldLayoutBackend` 在 binding 非空时调用 `StaticFieldLayoutProvider` 新增的四个带 binding 的方法(字段布局、payload 布局、逐 case 的 enum 布局、展开偏移树),这四个方法的默认实现返回空,库外 provider 不受影响。运行时后端不看 binding:它的实参在 metadata 里。 + diff --git a/Documentations/Internal/Modules/SwiftLayout.md b/Documentations/Internal/Modules/SwiftLayout.md index afffe4fb7..2cd33f97e 100644 --- a/Documentations/Internal/Modules/SwiftLayout.md +++ b/Documentations/Internal/Modules/SwiftLayout.md @@ -28,7 +28,7 @@ SwiftLayout 是**静态聚合布局引擎**:不加载进程、不调用 metada ### 1 / 2:入口与累加 -`StaticLayoutCalculator` 是唯一入口,三个层次的请求共用一条按字段推进的路径(`accumulateFieldLayout`,环境默认 `.empty`):非泛型描述符(`fieldLayout(of:)`)、给定实参的泛型实例化(`fieldLayout(of:genericArguments:)`)、二进制里的 bound generic mangled 引用(`fieldLayout(forInstantiationMangledName:)`)。每个字段独立降级,一个字段解不出来不会毁掉整个类型。 +`StaticLayoutCalculator` 是唯一入口,四个层次的请求共用一条按字段推进的路径(`accumulateFieldLayout`,环境默认 `.empty`):非泛型描述符(`fieldLayout(of:)`)、给定 depth-0 实参的泛型实例化(`fieldLayout(of:genericArguments:)`)、二进制里的 bound generic mangled 引用(`fieldLayout(forInstantiationMangledName:)`),以及按 `GenericArgumentBinding` 绑定了全部层的实例化(`fieldLayout(of:genericArgumentBinding:)`,离线泛型特化用)。最后这一种另有 `typeLayout(forMangledTypeName:inContextOfDescriptor:genericArgumentBinding:)`、`enumCaseLayoutResult(forDescriptor:genericArgumentBinding:)`、`nestedFieldOffsetTree(…genericArgumentBinding:)` 三个配套入口,渲染层据此给特化后的定义出全部布局注释([OfflineGenericSpecialization.md](../OfflineGenericSpecialization.md))。每个字段独立降级,一个字段解不出来不会毁掉整个类型。 `StaticTypeLayoutResolver` 是「mangled name → `StaticTypeLayout`」的递归求解器,按 `Node.Kind` 分派、带记忆化和环路保护;类引用到一个指针为止,不再往下展开。 @@ -56,7 +56,7 @@ SwiftLayout 是**静态聚合布局引擎**:不加载进程、不调用 metada ### 5:没有实参也能算的那部分 -`GenericArgumentEnvironment` 做具体 bound generic 的字段代换,**实参按 nominal parent 链逐层收集**,所以特化父类型的嵌套类型(`Environment.Content` 这种自身没有实参列表的节点)也能绑上父层的实参。代换是手写的自顶向下递归,不是 `Node.Rewriter` 的自底向上——pack expansion 是上下文相关的。 +`GenericArgumentEnvironment` 做具体 bound generic 的字段代换,**实参按 nominal parent 链逐层收集**,所以特化父类型的嵌套类型(`Environment.Content` 这种自身没有实参列表的节点)也能绑上父层的实参。遇到 extension 上下文会走进它的被扩展类型继续收集(约束 extension 里声明的类型,外层实参挂在那里),遍历与 SwiftInspection 的 `GenericArgumentBinding.argumentListsByLevel(ofInstantiatedTypeNode:)` 共用;`make(forBinding:)` 直接从按层分组的实参建环境。代换是手写的自顶向下递归,不是 `Node.Rewriter` 的自底向上——pack expansion 是上下文相关的。 `ClassBoundGenericParameterAnalysis` 是另一条前线:**完全不给实参**时,从 requirement signature 里挖出签名本身就钉死的事实——类约束参数(必是一个对象引用)与具体 same-type 约束(`Value == Date`,来自受约束的 extension)。加上「参数的 metatype 字段恒为 thick」这条,泛型类型在无特化的情况下也能解出可观比例的字段。 @@ -64,7 +64,7 @@ SwiftLayout 是**静态聚合布局引擎**:不加载进程、不调用 metada `ObjCClassIndex` 读 `class_ro_t.instanceSize`(Swift 子类第一个字段的起点),并索引每个静态发出的 Swift 类自己的 `instanceStart`——实际祖先变大时这个值会被 ObjC runtime 滑移(objc4 的 `moveIvars`),dyld cache 里的镜像带的已是滑移后的终值。是否在 classlist 里决定走哪套规则。 -`ImageUniverse` 是五个解析 seam 的统一查找面(类型、协议类约束、ObjC 类实例尺寸、assocty witness、ObjC 协议声明),可以是单镜像,也可以是**依赖闭包**——根镜像急切索引,依赖按解析顺序**惰性**折进来,所以几百个镜像的系统闭包不会被急切 demangle 一遍。闭包本身由 `MachODependencies` 提供,本模块只是薄封装。assocty witness 这个 seam 有一个返回**节点**而非布局的公开入口 `projectedAssociatedTypeWitness(base:associatedTypeReference:)`(2026-09-18,提案 0045-opaque-reference-spelling-and-member-projection):`SwiftDeclarationRendering` 用它把展开后的 opaque archetype 的成员(`IndexingIterator<[Int]>.Element`)投影成 witness 类型,逻辑与 `DependentMemberTypeBridge` 一致,只是不往下算布局。 +`ImageUniverse` 是五个解析 seam 的统一查找面(类型、协议类约束、ObjC 类实例尺寸、assocty witness、ObjC 协议声明),可以是单镜像,也可以是**依赖闭包**——根镜像急切索引,依赖按解析顺序**惰性**折进来,所以几百个镜像的系统闭包不会被急切 demangle 一遍。闭包本身由 `MachODependencies` 提供,本模块只是薄封装。assocty witness 这个 seam 有一个返回**节点**而非布局的公开入口 `projectedAssociatedTypeWitness(base:associatedTypeReference:)`(2026-09-18,提案 0045-opaque-reference-spelling-and-member-projection):`SwiftDeclarationRendering` 用它把展开后的 opaque archetype 的成员(`IndexingIterator<[Int]>.Element`)投影成 witness 类型,逻辑与 `DependentMemberTypeBridge` 一致,只是不往下算布局。`projectingConcreteMembers(in:)`(2026-10-01)在它之上把整棵节点里所有 base 已具体的成员投影掉、投影结果再投影(有跳数上限):展开偏移树用它命名和展开字段(`[Swift.Int].Element` 显示为 `Swift.Int` 并继续展开,与运行时的遍历一致),离线泛型特化用它代换字段类型与约束检查的两侧。 ## 关键契约 diff --git a/Documentations/Internal/OfflineGenericSpecialization.md b/Documentations/Internal/OfflineGenericSpecialization.md new file mode 100644 index 000000000..e67d976f8 --- /dev/null +++ b/Documentations/Internal/OfflineGenericSpecialization.md @@ -0,0 +1,111 @@ +# 离线泛型特化 + +提案 [offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md) 的实现说明:不经 runtime 特化一个从文件读出的泛型类型,并像在线模式一样打印出绑定后的头部、代换后的字段类型和按实参计算的布局注释。给 RuntimeViewer 的离线模式用,本库没有 CLI 入口。 + +## 一句话 + +`GenericSpecializer` 的 `specialize(_:with:)` 把每个实参变成一个类型节点(从不调用目标镜像里的代码),补齐被 same-type 约束钉死的参数,按层分组成 `GenericArgumentBinding`,再按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名,返回 `StaticSpecializationResult`。`TypeDefinition.specialize(with:in:)` 把它变成特化后的定义(`staticSpecialization` 存 binding),`SwiftDeclarationPrinter` 打印时:头部用实例化类型名,字段类型按 binding 代换并把关联类型投影成具体类型,布局注释由静态布局引擎按 binding 计算。 + +```swift +let specializer = GenericSpecializer(indexer: indexer) // SwiftDeclarationIndexer +let request = try specializer.makeRequest(for: typeDefinition.typeContextDescriptorWrapper) +let validation = specializer.staticPreflight(selection: selection, for: request) +let result = try specializer.specialize(request, with: selection) +let specializedDefinition = try await typeDefinition.specialize( + with: result, + derivingNestedSpecializationsWith: specializer, + in: machOFile +) +let interface = try await printer.printTypeDefinition(specializedDefinition) +``` + +## 参数的层号(depth)只数声明了参数的上下文 + +泛型参数在 mangling 里按 `(depth, index)` 引用(`τ_1_0`,打印成 `A1`),demangler、字段记录、需求签名都用这个坐标。层号只数**声明了参数**的上下文,而 generic context descriptor 只记录一份累计的参数列表,不记录层的边界。从父链推层号有两种形状会推错: + +- 本身不声明参数、只因嵌在泛型类型里才算泛型的类型,比如 `Outer.Middle.Inner` 里的 `Middle`。它有 generic context(继承了 `A`),却不开新层:`B` 在第 1 层。 +- extension 本身也不声明参数,但它的 generic context 带着被扩展类型的全部参数,可能跨好几层:`extension Outer.SecondMiddle where A == Int` 一个上下文覆盖 `Outer` 的第 0 层和 `SecondMiddle` 的第 1 层,里面声明的 `DeepConstrainedInner` 的 `B` 在第 2 层。 + +`GenericParameterDepthLayout`(SwiftInspection)给出每层几个参数:类型或 opaque type 上下文增加参数就开一层;extension 增加的参数按被扩展类型(extended context 的 mangling 里每个声明了参数的层各带一个参数列表)拆成几层。拆不开时(读不到、个数对不上)退回「这一级算一层」,不做超出父链的猜测。 + +此前有五处按「每个泛型祖先一层」计数,全部改用它: + +| 位置 | 错数的后果 | +|---|---| +| `GenericSpecializer.buildParameters` | `B` 被命名为 `A2`,按名字收集需求时漏掉 `A1: Hashable`,候选不过滤,运行时特化少算一个 witness table,在 key argument 个数检查处失败 | +| `GenericContext+Dump`(dump 与 interface 的头部) | 未特化的头部打成 `struct Inner { var innerElement: A1 }`,参数子句和字段对不上(0.21.0 的 CLI 就是这样) | +| `RuntimeMetadataTypeBuilder.bindings` | 进程内把节点还原成 metadata 时 `A1` 找不到实参,带需求的嵌套泛型实例化失败 | +| `AccessorThunkOwnerLayout` | thunk 从参数缓冲区读到的第二个字被标成 `(2, 0)`,是没有字段会引用的坐标 | +| `GenericArgumentEnvironment.make(forInstantiatedTypeNode:)`(SwiftLayout) | 节点遍历在 extension 节点处停下,`Outer.ConstrainedInner` 只收到最内层的实参,把 `String` 绑到第 0 层,引用它的字段整体降级 | + +`TargetGenericContext.depth`(ABI 模型)保留原义——泛型祖先的个数,baseline 仍记录它——只是不再拿它命名参数。`AccessorThunkOwnerLayout(genericContext:)` 留作没有 descriptor 时的形式,改为跳过不增加参数的祖先;extension 跨层的情况只有带 `depthLayout` 的新初始化方法能处理,库内调用点全部改用后者。opaque type 的 descriptor 可能在进程内、本镜像或别的镜像里读出,它的父链必须在读它的那个上下文里遍历,所以 `Node+OpaqueType` 在读出 descriptor 的地方就算好 `AccessorThunkOwnerLayout`(`ReadOpaqueType`)。 + +## 实参按层绑定:`GenericArgumentBinding` + +`argumentsByDepth[depth][index]` 是参数 `(depth, index)` 的实参,`.type` 包装的类型节点。它和实例化类型节点可以互相转换:demangler 只给声明了参数的层包 `boundGeneric*` 节点,所以 `argumentListsByLevel(ofInstantiatedTypeNode:)` 从内到外收集每层的 `TypeList` 再反转,恰好就是按层的实参;遇到 extension 节点时走进它的被扩展类型(外层实参挂在那里)。静态布局引擎的 `GenericArgumentEnvironment` 和层号计算都用这一个遍历。 + +`substituting(in:)` 是给显示用的代换:和布局引擎的代换不同,它也代换 metatype 里的参数(`A.Type` 显示成 `Swift.Int.Type`)。布局引擎故意不代换 metatype 的实例,因为 metatype 的存储大小由实例的语法形状决定,与实参无关。 + +## 实例化类型名 + +`SymbolicDemangler.instantiatedTypeNode(for:binding:in:)` 移植运行时的 `_buildDemanglingForContext`:沿描述符路径从外到内,某个类型上下文的累计参数数超过外层已用掉的数量,就把中间那几个实参挂成这一层的 `boundGeneric*`;不声明参数的类型保持普通节点挂在绑定后的父节点下。实现上给原有的 `buildContextDescriptorMangling` 加了一个可选的 `ContextInstantiation`,私有鉴别符、C 导入类型的身份、匿名上下文和 extension 上下文的处理与未绑定的名字完全相同。 + +extension 上下文有一处有意与运行时不同。运行时只给被扩展类型的最外一层(`selfType` 的第一个 `TypeList`)换实参:被扩展类型本身是嵌套泛型时,它把全部实参塞进 `SecondMiddle` 的列表、`Outer` 保持未绑定,拼出的名字不对应任何实例化。离线把 binding 代换进被扩展类型,每层都绑定。和运行时一样,绑定后的 extension 节点不带泛型签名。 + +被 same-type 约束钉死的参数不接受 key argument(`extension Outer where A == Int { struct Inner }` 里的 `A`),request 也不提供它,但它的层照样要绑定、名字里也要写出来。`GenericInstantiation`(SwiftSpecialization)从固定它的约束补上:取约束右侧,代换已知实参,再把具体类型的关联类型投影掉;右侧引用另一个被固定的参数时反复代换直到不再有进展。运行时用 `_gatherWrittenGenericParameters` 做同一件事。 + +运行时特化的类型名也改用这套构造(`TypeDefinition.makeSpecializedDefinition`)。此前 `boundGenericTypeName` 把所有实参放进最内层:`Outer.Inner` 被写成 `Outer.Inner`,派生出的 `NestedHost.Plain` 被写成 `NestedHost.Plain`。打印出来的头部不受影响(它用 metadata 的运行时名字),但 `typeName` 是 RuntimeViewer 侧边栏的显示名和标识。实参个数与 key 参数对不上时仍退回旧形状。 + +## 离线执行与约束检查 + +实参变成类型节点的方式:`.candidate` 取候选的 `TypeName` 节点;`.boundGeneric` 用绑定到候选所在镜像的内层 specializer 递归离线特化,取内层结果的类型名;`.metatype` / `.metadata` / `.specialized` 用本进程运行时给的名字(`RuntimeTypeNameDemangling.node(forMetatype:)`,与在线路径的头部和字段类型同源)。每一层的实参只解析一次,`.boundGeneric` 嵌套的工作量随深度线性增长。 + +`staticPreflight` 对类型泛型签名里的每条需求(根参数有实参的)检查,分两档: + +| 结果 | 情形 | +|---|---| +| 错误 | `AnyObject` 参数给了 struct / enum / tuple(宿主类型按 metadata 的 kind 判断);索引认识、但不在父类子树里的类(宿主类沿它自己完整的父类链按名字比较);关联类型的 same-type 约束两侧都解析成具体类型且不相等 | +| 警告 | 索引记录里查不到的协议遵循(可能是条件遵循、别的模块补上的、运行时合成的);关联类型投影不出来;索引没有该父类的类层级信息;实参类型不在任何被索引的镜像里 | + +错误与警告沿用 `SpecializationValidation` 现有的 case(RuntimeViewer 对它们做了穷尽 `switch`)。`specialize` 与在线路径一样:静态校验或约束检查有错误时抛 `specializationFailed`,泛型 `.candidate` 抛 `candidateRequiresNestedSpecialization`。关联类型的需求用访问路径命名(`A.Element`),与 request 的 `AssociatedTypeRequirement.fullPath` 一致。 + +读文件时,对别的镜像里协议的引用落在 loader 要解析的 bind 上(`Hashable` 是 `$sSHMp`),`resolvedContent` 给出 `.symbol`。`buildRequirement` 原先只认 `.element`,于是离线 request 丢掉了所有跨镜像协议需求:候选不过滤,witness table 也没计数。现在 `.symbol` 按符号名还原协议名。在线路径的 bind 已经解析,不受影响。 + +## 特化后的定义与打印 + +`TypeDefinition.staticSpecialization`(SwiftDeclaration)存离线特化的 binding,与运行时特化的 `metadata` 互斥。打印器的三处都在两者之间二选一: + +- **头部**:`boundTypeNode(of:)` 给出绑定后的名字——运行时特化取 metadata 的运行时名字,离线特化取定义自己的实例化类型名,两者形状相同,都交给 `BoundDumpedTypeNameRenderer`。 +- **字段与 enum payload 的类型**:离线时对字段节点做 binding 代换,再用 `DependentMemberProjection.projectingConcreteMembers` 把具体类型的关联类型投影掉(`Elements.Element?` 在 `Elements == String` 时打成 `Swift.Character?`);投影走被特化类型所在镜像的依赖闭包,投影不了的保留原样。 +- **布局注释**:`FieldLayoutRenderState.genericArgumentBinding` 把 binding 交给 `StaticFieldLayoutBackend`,后者调用 `StaticFieldLayoutProvider` 新增的四个带 binding 的方法(字段布局、payload 布局、逐 case 的 enum 布局、展开的嵌套偏移树)。这四个方法有返回空的默认实现,库外的 provider 不受影响,只是不出注释。 + +为了让两条路径对同一个实例化给出相同的注释,顺带改了两处既有行为: + +- **在线路径给特化后的泛型 enum 出 Enum Layout 注释**。`RuntimeFieldLayoutBackend` 原先对任何泛型 enum 都不算布局;现在定义带着特化 metadata 时,payload 类型经 metadata 代换后解析,enum 自身的 value witness table 从进程内读,仍用它的 size 交叉校验。未特化的泛型 enum 照旧没有这项注释。 +- **静态的展开偏移树投影具体类型的关联类型**。`ElementsHolder<[Int]>` 的 `first` 原先显示为 `Swift.Optional.Element>` 并在那里停下,运行时的遍历显示 `Swift.Optional` 并继续展开;现在静态遍历也先投影(`ImageUniverse.projectingConcreteMembers`)再命名和展开。这对未特化类型里出现的实例化字段同样生效。 + +## 验证 + +`GenericSpecializationFixture`(MachOTestingSupport)现场编译一个 dylib,同一个文件按 `MachOFile` 读(离线)、`dlopen` 后按 `MachOImage` 读(在线)。`OfflineSpecializationParityTests` 对 struct、final class、泛型父类的 class、单 payload 与多 payload 泛型 enum、关联类型字段、非声明层下的嵌套泛型、派生的嵌套类型、自带参数的嵌套泛型、私有类型和 `.boundGeneric` 实参,两条路径分别特化、打开全部布局注释后打印,要求逐字节相同。 + +有三处两条路径按设计就不同,未特化的类型也一样,对照的形状避开了它们: + +- 空 case 存在 payload 的 extra inhabitant 里的单 payload enum:只有运行时能经 value witness 投影出确切字节,静态路径标注 not resolved。 +- tuple 类型的字段:运行时的 Type Layout 注释逐元素展开。 +- `Array` 这类泛型标准库 struct 的字段:运行时的展开遍历在第一个以该 struct 自身参数为类型的嵌套字段处停下(`_buffer: _ArrayBuffer`),静态遍历会继续往下。 + +另有:`InstantiatedTypeNameTests` 把离线的实例化类型名与运行时名字按结构比较(含私有类型、约束 extension 里的类型、跨模块 extension 里的类型),`OfflineSpecializationTests` 覆盖 request、结果与约束检查每一档的正反例,`BoundInstantiationLayoutTests` 把带 binding 的字段偏移与运行时 metadata 的 field offset vector 比较。层号的五处修复各有修复前失败的回归测试(`GenericParameterDepthNamingTests`、`GenericParameterDepthDumpTests`、`CanonicalParameterDepthTests`、`AccessorThunkOwnerLayoutDepthTests`、`RuntimeMetadataTypeBuilderTests.nestedGenericBehindNonDeclaringLevelResolvesItsRequirement`、`ExtensionContextInstantiationLayoutTests`)。 + +真实系统框架上(渲染 A/B,明细在提案的「验证」一节),未特化输出的变化只有三类,都是修正: + +- 嵌在不声明参数的中间层下的泛型类型,头部参数名与它自己的 `where` 子句对上了:Combine 的 `Optional.Publisher.Inner`、`Result.Publisher.Inner`,SwiftUICore 的 `TimeDataSource.Resolver.ResolvedOffsetBox`,原先都打成 ``。macOS 15.5 到 27.0 的 cache、iOS 15.5 到 26.5 的模拟器文件、进程内镜像,三条 reader 路径都一样。 +- 展开偏移树里,具体类型的关联类型投影成它的 witness 再命名,并继续往下展开:`Angle.Animatable.AnimatableData` 显示为 `Swift.Double`,`ViewFrame.Animatable.AnimatableData` 展开成 `AnimatablePair, …>` 的各层字段,`SubviewsCollection.Collection.Index` 显示为 `Swift.Int` 并展开出 `_value`。 +- 约束 extension 里声明的类型,其实例化作字段时实参能代换进去了:`MeasurementView` 的字段 `Measurement.FormatStyle` 展开出的子字段原先印成 `Measurement`(读起来像 `MeasurementView` 的第一个参数),现在是 `Measurement`。 + +## 已知限制与顺带发现 + +- **实参所在镜像要在依赖闭包里**。离线布局与关联类型投影都走被特化类型所在镜像的依赖闭包;RuntimeViewer 让用户从别的、互不依赖的镜像里挑候选时,相关字段降级为 unknown、关联类型保持未投影。这是如实降级。 +- **宿主类型的协议遵循查不到**。`.metatype` 给的宿主类型不在任何被索引的镜像里,它的协议遵循只能报警告。 +- **class 头部的父类不代换**:`class Sub: Base`,在线路径也是这样。 +- **特化后的定义不打印成员**:成员按绑定后的名字查符号查不到,两条路径一致。调用方不传 `typeArgumentNodes` 时,在线路径的定义保持未绑定的名字,会查到并打印未代换的成员(`init(first: A, …)`),这是既有行为。 +- **未修的旧问题**:引用「嵌套泛型类型的约束 extension 里声明的类型」的字段(`Outer.SecondMiddle.DeepConstrainedInner`)demangle 失败(`unexpected(at: 11)`),引用它的整个类型从 interface 里消失;引用约束 extension 里类型的类型,其 memberwise `init` 后面会多出一个 `where A == Swift.Int`。两者都与本提案无关,记录在提案里。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index ea29214c9..c3d6ab065 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2165,6 +2165,16 @@ - **关联文档**:[draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md)、[Glossary.md](../Glossary.md)「nested-definition region」、swift-semantic-string 的 `docs/DefinitionRegions.md`。 - **对应版本**:未发版。落地前要先发布带 `DefinitionRegion` 的 swift-semantic-string,并抬高本库对它的版本下限。 +## 2026-10-01 离线泛型特化,参数层号只数声明了参数的上下文(节号落地时分配) + +- **时间段**:2026-09-30 — 2026-10-02。 +- **动机**:`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在加载进当前进程的 `MachOImage` 上用;RuntimeViewer 将来的离线模式读 `MachOFile`,完全不能特化。用户:「把离线泛型特化实现一下,我记得之前在做静态布局的时候就提到过这个,目前泛型特化只有运行时才能用」。 +- **关键决策**:**① 离线执行与在线一一对应**:`GenericSpecializer` 的 `specialize` / `staticPreflight`,实参变成类型节点(`.metatype` 等宿主类型用本进程运行时的名字),结果是实例化类型名加按层分组的实参(`GenericArgumentBinding`),打印器与静态布局引擎据此出绑定头部、代换并投影关联类型的字段类型、全部布局注释。**② 实例化类型名移植运行时 `_buildDemanglingForContext`**,非 key 参数由 same-type 约束补齐;只有嵌套泛型的约束 extension 一处有意与运行时不同(运行时拼出的名字畸形)。在线特化的 `typeName` 也改用它,不再把实参全放进最内层。**③ 约束检查两档**:确定违反报错,证明不了只警告;沿用现有的 error / warning case,RuntimeViewer 对它们做了穷尽 `switch`。**④ 参数层号整类修复**:用 0.21.0 的 CLI 证实未特化的 interface / dump 头部同样把 `Outer.Middle.Inner` 的 `B` 打成 `A2`;新增 `GenericParameterDepthLayout`(只数声明了参数的上下文,extension 按被扩展类型拆层),五处改用它,用户选择整类一起修。**⑤ 在线模式也给特化后的泛型 enum 出 Enum Layout 注释**,两条路径才能逐字节对照,用户选择。**⑥ 实现时发现并修的两处**:离线 request 丢掉跨镜像协议需求(读文件时协议引用落在 bind 上,`buildRequirement` 只认已解析的 descriptor);静态展开偏移树不投影具体类型的关联类型。 +- **落地模块**:`SwiftInspection`(`GenericParameterDepthLayout`、`GenericArgumentBinding`、`SymbolicDemangler.instantiatedTypeNode`、`RuntimeMetadataTypeBuilder` 的层号)、`SwiftSpecialization`(离线执行、`GenericInstantiation`、`StaticSpecializationResult`、`TypeDefinition` 的离线 `specialize` 重载、在线类型名、`buildRequirement`)、`SwiftDeclaration`(`TypeDefinition.staticSpecialization`)、`SwiftLayout`(带 binding 的四个入口、`make(forBinding:)`、穿过 extension 的实参遍历、`ImageUniverse.projectingConcreteMembers`、展开偏移树的投影)、`SwiftDeclarationRendering`(`StaticFieldLayoutProvider` 的四个新方法、`FieldLayoutRenderState.genericArgumentBinding`、离线字段代换、运行时后端的泛型 enum 布局、`GenericContext+Dump` 的层号、opaque type 的 thunk 实参布局)、`SwiftThunkAnalysis`(`AccessorThunkOwnerLayout` 带层号布局的初始化)、`SwiftDump` / `SwiftPrinting`(头部按层号命名,`boundTypeNode(of:)`)。测试支持新增 `GenericSpecializationFixture`(现场编译的 dylib,同一个文件按两种方式读)与 `GenericSpecializationFixtureIndexers`。 +- **验证**:39 个新测试;层号五处与另外四项修复都先确认修复前失败。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra)2210 个测试 / 420 个套件全部通过,原始退出码 0,known issue 只有早已登记的 `SymbolicManglingIndexTests`。渲染 A/B 以 `b2b7d997` 为基线,共 132 对,90 对逐字节一致;42 对差异全部是预期的改变,两侧重跑确认是确定性的。一是嵌在不声明参数的中间层下的类型头部从 `` 改成 ``(Combine 的 `Optional.Publisher.Inner` / `Result.Publisher.Inner`、SwiftUICore 的 `TimeDataSource.Resolver.ResolvedOffsetBox`,每个版本、每条 reader 路径都有);二是展开偏移树把具体类型的关联类型投影后命名并继续展开(`Angle.AnimatableData` → `Swift.Double` 等);三是约束 extension 里类型的实参代换修正(`MeasurementView` 里原先错印成 `Measurement`)。脚本写死的 `26.6.2` 归档目录不在(卷上叫 `26.6`),26.6 与 27.0 两份 cache 手动补跑;脚本的 CLI 腿不出布局注释,另跑了打开全部布局注释的 24 对。逐项明细在提案的「验证」一节。2026-10-02 分支 rebase 到 find-navigator(`86f65341`)之上,用本地兄弟依赖重跑全量:2224 个测试 / 424 个套件通过,原始退出码 0(rebase 前的 2210 个加上 find-navigator 新增的 14 个);渲染 A/B 未重跑。 +- **关联文档**:[draft-offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md)、[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[StaticLayoutEngine.md](StaticLayoutEngine.md)「后续工作」、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md)、[SpecializedInterfaceBoundRenderingRestoration.md](SpecializedInterfaceBoundRenderingRestoration.md)、[Glossary.md](../Glossary.md)「depth」「instantiated type name」「offline specialization」。 +- **对应版本**:0.22.0(未发版)。叠在 find-navigator 的三份提案之上,须在它们之后合入,也同样要等带 `DefinitionRegion` 的 swift-semantic-string 发版。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/SpecializedInterfaceBoundRenderingRestoration.md b/Documentations/Internal/SpecializedInterfaceBoundRenderingRestoration.md index eaf3fa8c0..d7977e47d 100644 --- a/Documentations/Internal/SpecializedInterfaceBoundRenderingRestoration.md +++ b/Documentations/Internal/SpecializedInterfaceBoundRenderingRestoration.md @@ -149,3 +149,14 @@ interface 打印器不打鉴别符,interface 输出不变;`dump` 与布局 - **第一批,RuntimeViewer 会话**(进程内 RuntimeViewerCore 探针,只换 MachOSwiftSection 的版本):报告的例子变为 `struct AppKit.WindowPortal {`。AppKit 102 个能特化的泛型类型的头部里,开头带点的从 20 处降到 0,16 个 anonymous context 的例子都补全了限定名(如 `enum AppKit.InProcessAnimation.Bridged.Phase {`),4 个 extension context 的例子只去掉了点。打开字段偏移、展开字段偏移、type / enum layout、成员地址全部选项生成的完整 interface 里,含 `(unknown context at $…)` 的文件从 32 个降到 0;74 个文件共 233 行变化,全是一对一替换、没有增删行,其中 226 行只差名字(补限定名、去掉 `(unknown context at $…)`、去掉开头的点),另外 7 行是私有嵌套类型补回父链;偏移、布局数值和地址一个都没变。 - **第二批,本地差分**(基线 `a35daff9` 与候选各编一个 release CLI,共用同一份 `Package.resolved`;输入是当前系统 macOS 26.7 的 dyld shared cache):AppKit 的 `dump` 逐字节相同(dump 不经过这个打印器)。AppKit / SwiftUI / SwiftUICore 的 `interface` 分别变化 255 / 163 / 734 行,行数不变;逐行检查全部是纯插入——每一行都只是在某个名字前面插入了被扩展的类型,没有删改任何别的字符。插入最多的前缀:AppKit 是 `__C.NSEvent.`(83)、`__C.NSView.`(63)、`__C.NSWorkspace.`(40)、`Foundation.AttributeScopes.`(29);SwiftUI 是 `SwiftUI.DisplayList.`(32)、`SwiftUI.AccessibilityAttachment.`(31)、`Foundation.AttributedString.`(22);SwiftUICore 是 `SwiftUI.Material.`(176)、`SwiftUI.Color.`(153)、`SwiftUI.Edge.`(84)。例子:`where B == Invalidations.Tuple` → `where B == __C.NSView.Invalidations.Tuple`,`[_Shadow]` → `[__C.CALayer._Shadow]`,`Layer.SDFLayer` → `SwiftUI.Material.Layer.SDFLayer`。被扩展的类型是泛型时按语法糖打印(SwiftUICore 的 `[A].PublicEncoding`),这种写法编译器接受(`typealias Y = [Int].Foo` 能通过类型检查)。没有用 `Scripts/run-rendering-ab-verification.py`:它写死的归档 cache 目录 `macOS/26.6` 已经不存在(卷上现在是 `26.6.2` 与 `26.7`),脚本会静默地只跑 `15.5` 那一条腿,而且它的框架清单里没有 AppKit。 + +## 离线特化(2026-10-01) + +离线泛型特化([OfflineGenericSpecialization.md](OfflineGenericSpecialization.md))的定义带 `staticSpecialization`(按层分组的实参)而不是 `metadata`,打印器的三处都在两者之间二选一: + +- `renderTypeDeclarationHeader` 的参数从 `specializedMetadata:` 改成 `boundTypeNode:`,由 `boundTypeNode(of:)` 统一给出:运行时特化仍取 metadata 的运行时名字(`SpecializedMetadataNodeSubstitution.boundTypeNode(for:)`),离线特化取定义自己的实例化类型名,两者形状相同。diff 渲染的头部入口同步改。 +- `renderModelFields` 的字段代换:离线时对 `FieldDefinition.typeNode` 做 binding 代换并投影关联类型(`StaticSpecializationNodeSubstitution`),否则照旧走 runtime。 +- 布局注释:`FieldLayoutRenderer` 收到 binding,静态后端按它计算。 + +同一批里运行时特化的 `typeName` 也改成按层挂实参的实例化类型名(此前 `Outer.Inner`),不影响这里的头部——头部一直用 metadata 的名字。 + diff --git a/Documentations/Internal/StaticLayoutEngine.md b/Documentations/Internal/StaticLayoutEngine.md index 869780333..5eb648b0c 100644 --- a/Documentations/Internal/StaticLayoutEngine.md +++ b/Documentations/Internal/StaticLayoutEngine.md @@ -79,7 +79,7 @@ Tests/SwiftLayoutTests/ - **`DependentMemberTypeBridge`(关联类型,阶段 7)**:泛型类型的字段用关联类型(`struct AssociatedTypeStorage { var index: C.Index }`,字段串 `A.Swift.Collection.Index`)时,实例化替换只能把 base 的 `dependentGenericParamType` 换成具体类型,节点仍是 `dependentMemberType(具体base, Protocol.Assoc)`。此桥从节点取出 (base 限定名, 协议限定名, 关联类型名) 三元组,查 `__swift5_assocty` 的 witness——`ImageReference` 新建「`conforming|protocol|assoc` → `AssociatedTypeRecord`」索引,`ImageUniverse` 新增第四个解析 seam `resolveAssociatedTypeWitness`(与前三个共用惰性折入)。取到 witness 的 `substitutedTypeName` 后**在声明该 conformance 的镜像里** demangle(其符号引用相对该镜像),再用 base 自身的 bound-generic 环境二次替换(`Array` 的 `Element` witness 是 `Array` 的参数 (0,0) → `Int16`),最后照常 `layout(forTypeNode:)`。base 仍未替换(裸 `A` / depth>0)则降级。 - **受约束 / 扩展 existential(阶段 7)**:`any Boxed`(带 primary associated type 约束或 same-type 约束的 existential)经 `symbolicExtendedExistentialType` 节点编码——`symbolicExtendedExistentialType → (unique|nonUnique)…ShapeSymbolicReference → constrainedExistential → Type → ProtocolList`。**约束不改变容器大小**(`any Boxed` 与 `any Boxed` 布局相同:opaque buffer + metadata + 每协议 1 witness),故 `extendedExistentialLayout` 取出内层 `ConstrainedExistential` 的 existential 类型节点,路由回既有 `existentialLayout`(自动处理 class-bound / opaque 区分),requirement list 忽略。 - **嵌套于特化泛型父类的类型命名(阶段 7)**:`Outer.Inner` 作字段时,字段节点是 `Enum/Structure(boundGenericStructure(Outer), Identifier('Inner'))`——父上下文是 `boundGeneric*`。原 `NodeTypeNaming.contextQualifiedName` 的 switch 未处理 `boundGeneric*`(落到 `default: node.text` 返回 nil),导致父链被丢、限定名退化成裸 `Inner` 而 miss 索引(实测 SwiftUI `@Environment.Content` 等 279 例)。修复:`contextQualifiedName` 对 `boundGeneric*` 解包到底层 nominal 再递归、对 `.type` 包裹解包。 -- **父链实参环境(阶段 8)**:阶段 7 修好了嵌套类型的**命名**,但字段**使用父参数**的嵌套类型(`Environment` 唯一字段 `content: Content`,`Content` 的 payload 引用 `Value`)仍降级——`Content` 自身不带 `typeList`,实参挂在父链的 `boundGeneric*` 节点上,旧 `make(forBoundGenericNode:)` 只认节点顶层的 `typeList`,建出空环境。修复:`make(forInstantiatedTypeNode:)` 沿 nominal 父链**逐层收集**各 `boundGeneric*` 的 direct `typeList`(demangler 恰好只给声明参数的层套 `boundGeneric*` 壳),最外层 = depth 0——`Environment.Content` 绑定 `{(0,0)→Bool}`,多级 `Outer.Inner` 绑定 `{(0,0)→Int8, (1,0)→Int64}`(顺带修正了旧实现对多级实例化把最内层 typeList 误绑 depth 0 的潜在错位,此前被降级掩盖)。`structureLayout`/`enumLayout` 的 builtin 查表改为**在环境为空时**才做(此前按 `node.kind` 判非泛型;`Enum(BoundGeneric…, Content)` 的 kind 是裸 `.enum`,需以环境判定实例化)。实测这是系统框架剩余 198 例 `genericParameterUnsubstituted` 的全部根因(SwiftUI 的 `Environment<…>` 字段族)。 +- **父链实参环境(阶段 8)**:阶段 7 修好了嵌套类型的**命名**,但字段**使用父参数**的嵌套类型(`Environment` 唯一字段 `content: Content`,`Content` 的 payload 引用 `Value`)仍降级——`Content` 自身不带 `typeList`,实参挂在父链的 `boundGeneric*` 节点上,旧 `make(forBoundGenericNode:)` 只认节点顶层的 `typeList`,建出空环境。修复:`make(forInstantiatedTypeNode:)` 沿 nominal 父链**逐层收集**各 `boundGeneric*` 的 direct `typeList`(demangler 恰好只给声明参数的层套 `boundGeneric*` 壳),最外层 = depth 0——`Environment.Content` 绑定 `{(0,0)→Bool}`,多级 `Outer.Inner` 绑定 `{(0,0)→Int8, (1,0)→Int64}`(顺带修正了旧实现对多级实例化把最内层 typeList 误绑 depth 0 的潜在错位,此前被降级掩盖)。`structureLayout`/`enumLayout` 的 builtin 查表改为**在环境为空时**才做(此前按 `node.kind` 判非泛型;`Enum(BoundGeneric…, Content)` 的 kind 是裸 `.enum`,需以环境判定实例化)。实测这是系统框架剩余 198 例 `genericParameterUnsubstituted` 的全部根因(SwiftUI 的 `Environment<…>` 字段族)。2026-10-01 补上一处遗漏:父链遍历原先在 extension 节点处停下,约束 extension 里声明的类型(`Outer.ConstrainedInner`,外层实参挂在 `Extension(, Outer, )` 的被扩展类型上)只收到最内层实参,把 `String` 绑到 depth 0;现在走进被扩展类型继续收集。遍历本身移到 SwiftInspection 的 `GenericArgumentBinding.argumentListsByLevel(ofInstantiatedTypeNode:)`,与离线泛型特化共用([OfflineGenericSpecialization.md](OfflineGenericSpecialization.md))。 - **class-bound 泛型参数不特化解析(阶段 9)**:阶段 5–8 都在解**具体实例化**(`Foo` 有实参)。阶段 9 转向**未特化**的泛型类型本身:一个 `T: AnyObject` / `T: SomeClass` / `T: SomeClassBoundProtocol` 约束的参数,其存储在运行期**必然是单个对象引用**(8 字节、8 对齐、bitwise-takable、XI = `swift_getHeapObjectExtraInhabitantCount` = 0x7FFF_FFFF(64 位 Darwin 饱和),与具体 class field 完全一致),且**每个 class 实例化布局都相同**——故 `T` 字段本身及其后所有字段无需任何实参即可精确算出。`ClassBoundGenericParameterAnalysis` 读 descriptor 的**累积规范需求签名**(`genericContext.requirements`;需求的 subject 携带绝对 `(depth,index)`,与字段记录同坐标系,嵌套上下文无需额外簿记),demangle 每条需求的**裸参数** subject(约束在依赖成员 `T.Element` 上的不 pin `T`,跳过),再按需求 kind + resolved content 判 class-bound:`layout(.class)`(`T: AnyObject`)、`baseClass`(`T: SomeClass`)、或 class-bound `protocol`(`.objc` 恒真;`.swift` 看 descriptor 的 `classConstraint`;跨镜像 symbol 引用经 `resolveProtocolClassConstraint` + `isObjCProtocolDeclared` seam 按名回收)。结果经 `augmentedWithClassBoundParameterKeys` 注入 `GenericArgumentEnvironment.classBoundParameterKeys`,在每个读字段入口应用(`StaticLayoutCalculator.fieldLayout(ofStruct:/ofClass:)` 与求解器 `computeStructLayout` / `computeClassLayout` 收口点——故泛型超类 `class Sub: Base` 与 ObjC 祖先泛型子类同样受益)。替换阶段:未被具体实参替换、且命中 class-bound 集的 `dependentGenericParamType` 经**同一套 top-down 替换**(故能钻进 `Element?`/`(Element, Int)`/`[Element]`/闭包等复合类型)改写成占位 `.class` 节点,求解器按既有 `.class → .pointerSized` 分派(占位节点名字惰性——class 节点从不被读名/递归)。**具体实参始终优先**于 class-bound 兜底(class-bound 参数的具体实例化用其真实实参);class-bound 泛型 **multi-payload enum**(`ClassBoundContent`)布局固定但 class-bound archetype 不贡献 spare bits(可能装 ObjC tagged pointer,GenEnum.cpp ~7205),其 mpenum 记录 `usesPayloadSpareBits = false`,两条分支算出同样的附加 tag 字节数字。剩余不可静态定:无约束或非 class-bound 参数(`T`、`T: Equatable`、value/pack 参数)——不特化即缺实参,保持逐字段降级。 - **具体 sameType 钉住(阶段 9 补全)**:同一趟需求扫描里,除 class-bound 外还提取 `sameType` 钉住。`extension Foo where Value == Date { struct Bar { var x: Value } }` 这类**约束扩展**里嵌套的类型,其 descriptor 的泛型签名继承了外层 `Value` 参数**加上** `Value == Date` 需求,故字段 `x: Value` 不特化即解析为 `Date`。`ClassBoundGenericParameterAnalysis.layoutFacts` 现返回 `RequirementSignatureLayoutFacts { classBoundParameterKeys, concreteSameTypeSubstitutions }`:对 kind==`.sameType` 且 LHS 为**裸参数**的需求,取 RHS(`resolvedContent` 的 `.type(MangledName)`)demangle、**仅当其完全具体**(不含 `dependentGenericParamType`/`dependentMemberType`——引用别的参数则无法独立替换)时,把 unwrapped RHS 节点作为**真正的 substitution**(不是占位 class)注入 `GenericArgumentEnvironment.substitutions`(`augmented(withRequirementFacts:)`,仅填实例化节点未覆盖的参数——真实例化实参恒优先,且与钉住不矛盾)。钉住到具体类型的参数被编译器从 accessor 的 key 实参里**丢弃**(已被完全确定),故这类嵌套类型的 runtime 布局用**无参** accessor 取得。RHS 可为标量(`Int64`,单镜像即解析)或 bound-generic 具体类型(`Range`,经依赖闭包解析 stdlib descriptor)。实测**收益很小**(5 框架 579 条 sameType 里仅约 23 条是「裸参数 == 具体类型」——75% 是依赖成员 subject 归 assocty bridge、21% 是抽象参数对参数),但它是需求签名能不特化推断的**正确补全**:class-bound + 具体 sameType 合起来 = 需求签名不带实参所能确定的全部。**同值钉住(value generic)同样打通**:`extension ValueGenericBuffer where count == 5` 的需求即 kind==`sameType` 加 `isValueRequirement` 标志(GenMeta.cpp:7460——编译器复用 sameType 而非新增 SameValue kind),RHS mangle 为整数字面量(demangle 出 `.integer` 节点)——`.integer` 天然通过「完全具体」检查、环境按阶段 6 的 value 实参规则绑定,**零代码改动即解析**(fixture `ValuePinnedInner` 的 `InlineArray` 字段 10 字节,双 reader 对 runtime 逐字段相等;值钉住参数同样被丢出 accessor key 实参,无参 accessor 即真值)。顺带修复 SwiftPrinting 接口打印**丢 SE-0452 整数节点**的缺陷(`NodePrintable.printNameInBase` 补 `.integer`/`.negativeInteger`——此前 `ValueGenericBuffer<>`、`InlineArray<, Swift.Bool>`、`where A == ` 渲染为空且已固化进旧接口快照;SwiftDump 路径走 Demangling `NodePrinter` 一直正确)。 - **Swift 声明 `@objc` 协议的 existential(阶段 8)**:`PlatformAccessibilityElementProtocol & NSObject` 形态。Swift 声明的 `@objc` 协议**不 emit Swift protocol descriptor**(不进 `__swift5_protos`),唯一 runtime 痕迹是 ObjC protocol record(`__objc_protolist`,旧式 `_TtP_` 名)。`ExistentialLayoutBridge` 在 class 约束查找 miss 后回退查第五个 seam `isObjCProtocolDeclared`(`ObjCProtocolIndex` 把 `_TtP…_` 解析回限定名建索引;原生 ObjC 协议的裸名不解析——它们 demangle 成 `__C` 引用、在更早的分支处理):命中即视同 imported ObjC 协议——强制 class-bound、不计 witness table。实测这是系统框架剩余 13 例 `typeDescriptorNotFound` 的全部根因。 @@ -198,6 +198,7 @@ Value-generic / pack(阶段 6)由 `ValueGenericAndPackLayoutTests` 验证: - **~~顶层具体泛型实例化的逐字段 offset~~(已完成)**:把阶段 5 的 `GenericArgumentEnvironment` 替换从「字段场景」**对称扩展**到「顶层请求场景」。新增两个公开入口:`StaticLayoutCalculator.fieldLayout(of:genericArguments:)`(descriptor + 具体实参 `Node`,按 depth-0 位置建环境)与 `fieldLayout(forInstantiationMangledName:)`(二进制里的 `Foo` 引用:demangle → 按限定名解析 descriptor → 经 `make(forBoundGenericNode:)` 建环境,故跨模块实例化在其**定义镜像**上展开)。实现上把富信息逐字段路径(`accumulateFieldLayout` → `AggregateFieldLayout`,**带逐字段降级**)线程化 `environment`(默认 `.empty` ⇒ 非泛型行为逐字节不变),并把私有 `fieldLayout(ofStruct:/ofClass:)` 抽出 `in image:` 以支持跨镜像;新增 `GenericArgumentEnvironment.make(forDepthZeroTypeArguments:)` 直接从实参 Node 列表建环境。仅 depth-0 参数;depth>0、裸泛型仍按字段降级。**未**引入对 `SwiftSpecialization` 的依赖——runtime 真值在测试侧用底层 accessor 传具体实参 metatype 取得(无约束泛型无需 PWT)。 - **~~阶段 6 value-generic(SE-0452)与 parameter-pack(SE-0393)实例化~~(已完成)**:环境接受 `.integer`/`.negativeInteger`/扁平 `.pack` 实参;替换改为自定义 top-down 递归,`.tuple`/`.pack` 内的具体 pack expansion 就地展开(逐元素 pattern 实例化、空 pack、单元素坍缩、`Foo` 转发扁平化);求解器新增 `builtinFixedArray` 分派与 `Swift.InlineArray` 特判(`size = stride = element.stride × count`,XI 取首元素);tuple XI 修正为取元素最大值;零大小字段 offset 镜像 IRGen 约定(上报 0)。官方离线 lowering(RemoteInspection `TypeLowering.cpp`)对 pack 直接报错、对裸 `Integer` 不 lower——本阶段以 runtime 替换语义为 ground truth,超越官方离线实现。仍降级:裸 pack/value 参数(无实参)、depth>0、pattern 内嵌套 expansion(见「已知降级」)。 - **~~阶段 9 class-bound 泛型参数不特化解析~~(已完成)**:`ClassBoundGenericParameterAnalysis` 从 descriptor 需求签名提取 class-bound 参数键,经 `GenericArgumentEnvironment.classBoundParameterKeys` + 占位 `.class` 替换,使未特化泛型类型的 class-bound 参数字段(及其后字段)精确解析,见上文「核心算法」。runtime 真值:class-bound 约束大多可经 accessor 传具体类 metatype 取得(`AnyObject` layout 约束 / ObjC 协议 / superclass 约束的签名不需要 witness table);Swift class-bound 协议约束的签名需 witness table,其 fixture 与 `AnyObject` 变体**共享同一字段形状**、经传递性锁定。仍不可静态定:无约束或非 class-bound 参数(`T`、`T: Equatable`、value/pack 参数)——不特化即缺实参。下一步若要继续推进泛型,候选是「扫二进制里出现的 bound-generic 引用逐个实例化枚举」与「用户手动特化前端(镜像 `SwiftSpecialization` 的 request/selection 两步式,执行端已就绪)」。 +- **~~用户手动特化前端~~(2026-10-01 已完成)**:离线泛型特化(提案 [offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md))镜像 `SwiftSpecialization` 的 request/selection 两步式,在 `MachOFile` 上产出 `GenericArgumentBinding`,引擎据此给特化后的定义算字段偏移、payload 布局、逐 case 的 enum 布局与展开偏移树(`StaticLayoutCalculator` 带 `genericArgumentBinding:` 的四个入口)。binding 覆盖全部层,故嵌套在特化父类型里的泛型类型也能整体实例化,不再局限于 depth-0 的 `genericArguments:`。另一条候选「扫二进制里出现的 bound-generic 引用逐个实例化枚举」仍未做。详见 [OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)。 - **multi-payload enum 的 payload 内部偏移(可选,未做)**:当前结构化路径只给整体 size/stride/align(已满足「作为字段」需求,且对全部 fixture multi-payload enum 与 runtime VWT 逐一吻合)。若需逐 case 的 payload 投影/tag 编码细节,`EnumLayoutCalculator.LayoutResult.cases` 已含,可后续暴露。extra inhabitants:三条策略**均已精确**——tagged(依赖实参的泛型实例化)按 runtime 公式(阶段 8),**spare-bits/混合按 IRGen `MultiPayloadEnumImplStrategy::getFixedExtraInhabitantCount` 移植**(精度补漏):`totalTagBits = CommonSpareBits.count() + extra-tag 位按字节向上取整`,`≥ 32 → 0x7FFFFFFF`,否则 `2^totalTagBits − numTags`(capped);`__swift5_mpenum` 序列化 mask 仅裁剪首尾零字节(GenReflection.cpp `calculateSpareBitsMask`),置位数与 `CommonSpareBits.count()` 严格相等,故从 descriptor 重建的 `countSetBits` 可直接作公式输入。XI 统一由 `EnumLayoutCalculator.LayoutResult.extraInhabitantCount` 携带(bridge 不再自算)。注意官方离线实现(RemoteInspection `TypeLowering.cpp:2243`)**从不结构化推导 spare-bits XI**——无 builtin descriptor 时整体退化 tagged 公式(spare-bits 布局连 size 都会算错),有 builtin 时 XI 照抄 descriptor——本引擎在此再次超越官方离线实现(与阶段 6 的 pack 情形同款)。 - **~~预特化泛型 MPE 的 spare-bits 布局~~(2026-08-05 已解决,且定性修正)**:曾记为「预特化 metadata 按编译期 spare-bits 布局,需识别 canonical specialization 记录」的硬骨头,深挖后定性被推翻——真实机制是**布局与实参无关的泛型 MPE 由编译器静态布局**(完整 VWT 烘焙进 metadata pattern,全新参数的实例化也共享它,与预特化无关),且编译器已把裁决写进二进制:只有这类 fixed MPE 才有 builtin/mpenum 记录(`GenReflection.cpp` 门槛 `!needsPayloadSizeInMetadata()`;`!AllowFixedLayoutOptimizations` 时编译器自己也退 tagged 且不发记录,GenEnum.cpp:7192)。修复即放开 `EnumLayoutBridge` 的两道门(builtin 查表的 `environment.isEmpty`、spare-bits 分支的 `!descriptor.isGeneric`)+ `compute()` 补查定义镜像 builtin 索引,`AttributedString.Keys.SetIterator` / `SpatialEventCollection.Iterator` 与 `NSHostingView.AllowAutomationElementsState` / `AnimatedValueState` 一族随之修正,普查整型偏差清零。守卫:`GenericSpareBitsEnumLayoutTests`(fixture `SpareBitsVariantEnum` 24/24/XI 125 修复前红 + OS 迭代器端到端 + 记录存在性判别针)。裁决与全过程见 [TaskReports/2026-08-05-generic-fixed-mpe-spare-bits.md](TaskReports/2026-08-05-generic-fixed-mpe-spare-bits.md)。 - **`@rpath` 完整展开**:`MachOFile` 闭包 MVP 靠 dyld cache bare-name + 显式路径覆盖;完整 `@rpath`/`@loader_path`/`@executable_path` 展开(读 `LC_RPATH` + 相对 root 定位)未做,调用方可预先展开为绝对路径。 diff --git a/Documentations/README.md b/Documentations/README.md index d1261cc7c..3f9e5afe4 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -85,7 +85,8 @@ selects names using each access's offset and width. | [StaticLayoutEngine.md](Internal/StaticLayoutEngine.md) | The shipped `SwiftLayout` module: what was actually built for static field-offset computation (recompute via `performBasicLayout` rather than reading the vector), the file structure, the runtime-accessor-vs-static validation suite, empirical findings that diverged from the research, and the known per-field degradations. Existentials (opaque / class-bound / error / metatype), the default-actor storage builtin, cross-module field/superclass/protocol types (via the dependency closure), ObjC-ancestor classes (Phase 4 — a Swift class deriving from `NSObject` et al. starts its fields at the ObjC ancestor's `instanceSize`, read via `MachOObjCSection`), multi-payload enums + imported C value types (via `__swift5_builtin` whole-type layouts), imported-ObjC-protocol existentials (`any NSCopying`), C-function-pointer / ObjC-block fields, and concrete bound-generic instantiations as fields (Phase 5 — purely syntactic `dependentGenericParamType` substitution via `GenericArgumentEnvironment`, depth-0 type parameters) are resolved; only a top-level generic type's own unsubstituted parameters, value/pack arguments, and depth>0 nested-context parameters remain degraded. | | [StaticLayoutDependencyClosure.md](Internal/StaticLayoutDependencyClosure.md) | Phase-3 (**shipped**): extends `SwiftLayout` from single-image to a dependency closure (`LC_LOAD_DYLIB` + dyld shared cache) so cross-module field/superclass/protocol types resolve, with zero resolver changes. Covers the homogeneous-per-root typing decision, the `ImageUniverse.dependencyClosure` factory, the resilient-class static-computability boundary (and why their runtime field-offset vector is empty), and the validation strategy — plus a "落地实测" section recording where the implementation diverged from the plan (lazy per-image indexing over a 551-image closure, bare-name matching, missing-section tolerance, one-shot cache indexing, literal pinning for resilient classes that emit no `…Wvd` global). ObjC ancestors were resolved by Phase 4 (`ObjCClassIndex` + a third `resolveObjCClassInstanceSize` seam; see StaticLayoutEngine.md). **2026-09-02 起**定位器与遍历已下沉为共享模块 `MachODependencies`(见 [Modules/MachODependencies.md](Internal/Modules/MachODependencies.md)),本文保留为阶段 3 的设计与实测记录。 | | [LeafMigrationPlan.md](Internal/LeafMigrationPlan.md) | Plan for making `SwiftDump` a leaf module. | -| [SpecializedInterfaceBoundRenderingRestoration.md](Internal/SpecializedInterfaceBoundRenderingRestoration.md) | 修复 leaf 迁移引入的回归:interface 路径重新对特化定义做绑定渲染——头部打印 `Box`(跳过泛型签名子句)、字段经特化 metadata 替换;机制经 `SpecializedMetadataNodeSubstitution` + 下移的 `BoundDumpedTypeNameRenderer` 落在 `SwiftDeclarationRendering`,dump 路径零变化。2026-09-23 补一节:运行时名字把私有类型的 anonymous context 写成描述符地址,打出 `struct .WindowPortal<…>`、丢模块与外层类型;五处运行时名字来源统一经 `RuntimeTypeNameDemangling` 去掉它;同日第二批:interface 打印器把 extension context 打印成被扩展的类型(离线同样受益,`Invalidations.Tuple` → `NSView.Invalidations.Tuple`)。 | +| [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md) | 离线泛型特化的实现说明(提案 offline-generic-specialization):`GenericSpecializer` 在 `MachOFile` 上不经 runtime 特化——实参变成类型节点,非 key 参数由 same-type 约束补齐,按层分组成 `GenericArgumentBinding`,按运行时 `_buildDemanglingForContext` 的规则拼实例化类型名;约束检查分「确定违反报错 / 证明不了警告」两档;打印器与静态布局引擎按 binding 出绑定头部、代换并投影关联类型的字段类型、全部布局注释,与在线模式逐字节对照。另记参数层号只数声明了参数的上下文(`GenericParameterDepthLayout`)及其整类修复的五处、在线模式给特化泛型 enum 补 Enum Layout、两条路径按设计不同的三处。 | +| [SpecializedInterfaceBoundRenderingRestoration.md](Internal/SpecializedInterfaceBoundRenderingRestoration.md) | 修复 leaf 迁移引入的回归:interface 路径重新对特化定义做绑定渲染——头部打印 `Box`(跳过泛型签名子句)、字段经特化 metadata 替换;机制经 `SpecializedMetadataNodeSubstitution` + 下移的 `BoundDumpedTypeNameRenderer` 落在 `SwiftDeclarationRendering`,dump 路径零变化。2026-09-23 补一节:运行时名字把私有类型的 anonymous context 写成描述符地址,打出 `struct .WindowPortal<…>`、丢模块与外层类型;五处运行时名字来源统一经 `RuntimeTypeNameDemangling` 去掉它;同日第二批:interface 打印器把 extension context 打印成被扩展的类型(离线同样受益,`Invalidations.Tuple` → `NSView.Invalidations.Tuple`)。2026-10-01 补一节:离线特化的定义带 binding 而不是 metadata,头部改由 `boundTypeNode(of:)` 统一给出。 | | [LeafMigrationRegressionAudit.md](Internal/LeafMigrationRegressionAudit.md) | 对 `aa233bc` leaf 迁移线的全面回归审计:三路逐行比对方法、7 项问题清单(多 payload 枚举容错丢失、深度截断诊断静默 + 测试钉死常量、Void payload case 两路不一致等——已于 2026-07-31 全部修复,见 LeafMigrationRegressionFixes.md)、已修复的历史断裂记录(metadata 注释全丢 / SIGBUS / 绑定渲染回归)与已核对干净的面。 | | [LeafMigrationRegressionFixes.md](Internal/LeafMigrationRegressionFixes.md) | 审计清单 7 项问题的整批修复:`MultiPayloadEnumDescriptorCache` 恢复(per-image 部分 map,dump/interface 共享)、注释/字段渲染全链错误传播恢复(`throws` 化,幽灵空行消失)、Void payload case 括号统一(`printThrowingEnumCase` 按 mangled name 判 payload)、extension conformance 子句 nil-塌缩语义恢复、深度截断 `#log` 恢复、死代码删除。含跨提交差分 harness 方法与收敛数据(edge 语料 0 diff)。 | | [AccessorThunkResolutionExplained.md](Internal/AccessorThunkResolutionExplained.md) | **accessor thunk 解析专题导读**(面向不懂汇编的读者):元数据里为什么会出现「调这个函数」而不是类型名(SE-0360 版本条件 / 旧 runtime 不认识的 mangling)、thunk 长什么样(三段真实样本逐行翻成人话)、离线怎么不执行就读出答案(反汇编 → 给调用目标起名 → 寄存器里装类型表达式做符号求值 → 表达式变回类型名)、进程内那条路、两支怎么进输出与模型、代码地图、oracle 测试为什么最重要、已知降级、术语对照。 | @@ -158,7 +159,7 @@ selects names using each access's offset and width. | [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | -| [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(Draft)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数与运行时特化类型名被拍平两个旧问题。本库不提供 CLI 入口。 | +| [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [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/Package.swift b/Package.swift index 4fcda0189..f6b4d3646 100644 --- a/Package.swift +++ b/Package.swift @@ -667,6 +667,9 @@ extension Target { .target(.MachOSymbols), .target(.MachOSwiftSection), .target(.SwiftInspection), + // The host's runtime names for `.metatype` arguments and the + // member projection the offline specialization substitutes with. + .target(.SwiftDeclarationRendering), .target(.SwiftDeclaration), .target(.SwiftIndexing), ], diff --git a/Sources/Analysis/SwiftInspection/GenericArgumentBinding.swift b/Sources/Analysis/SwiftInspection/GenericArgumentBinding.swift new file mode 100644 index 000000000..8367dba34 --- /dev/null +++ b/Sources/Analysis/SwiftInspection/GenericArgumentBinding.swift @@ -0,0 +1,157 @@ +@_spi(Internals) import Demangling + +/// The arguments one instantiation of a generic type binds its parameters to, +/// one list per depth (evolution proposal `offline-generic-specialization`). +/// +/// A generic parameter is identified by its `(depth, index)` — the pair every +/// mangled reference to it carries (`τ_1_0`, printed `A1`) — and a depth is a +/// context that declares parameters: `Outer.Inner` binds depth 0 +/// to `[Int]` and depth 1 to `[String]`, while `Outer.Middle.Inner` +/// binds the same two depths, because `Middle` declares none. That is exactly +/// how an instantiated type node spells its arguments, one `TypeList` on each +/// level that declares parameters, so the two convert into each other. +/// +/// The arguments are demangled type nodes, never metadata: an offline reader +/// has nothing else, and a node is what a renderer substitutes into a field's +/// type and what the static layout engine lays out. +public struct GenericArgumentBinding: Sendable, Hashable { + /// The arguments of each depth, outermost first, in declaration order — + /// the argument `argumentsByDepth[depth][index]` is what the parameter + /// `(depth, index)` stands for. Every argument is `.type`-wrapped. + public let argumentsByDepth: [[Node]] + + public init(argumentsByDepth: [[Node]]) { + self.argumentsByDepth = argumentsByDepth.map { arguments in + arguments.map(Self.typeWrapped) + } + } + + /// The binding an instantiated type node spells: the argument list of + /// every level that declares parameters, outermost first. `nil` for a + /// node with no instantiated level (a non-generic type, or an unbound + /// generic one). + public init?(instantiatedTypeNode: Node) { + let argumentLists = Self.argumentListsByLevel(ofInstantiatedTypeNode: instantiatedTypeNode) + guard !argumentLists.isEmpty else { return nil } + self.init(argumentsByDepth: argumentLists) + } + + public var isEmpty: Bool { + argumentsByDepth.allSatisfy(\.isEmpty) + } + + /// The argument the parameter `(depth, index)` stands for. + public func argument(depth: Int, index: Int) -> Node? { + guard argumentsByDepth.indices.contains(depth), argumentsByDepth[depth].indices.contains(index) else { return nil } + return argumentsByDepth[depth][index] + } + + /// Every argument in the order of the generic context's cumulative + /// parameter list. + public var flattenedArguments: [Node] { + argumentsByDepth.flatMap { $0 } + } + + /// `node` with every generic parameter this binding binds replaced by its + /// argument, for display: a field's `A?` becomes `Swift.Int?`, and + /// `A.Element` becomes `[Swift.Int].Element` — still a dependent member, + /// which a caller that can read conformance records projects further. A + /// parameter the binding does not cover stays as it is. + /// + /// Unlike the static layout engine's substitution this one reaches into a + /// metatype too: `A.Type` reads `Swift.Int.Type`, which is what it is. The + /// layout engine leaves a metatype's instance alone because the metatype's + /// storage depends on the instance's syntactic kind, not on what it binds + /// to — a concern of layout, not of naming. + public func substituting(in node: Node) -> Node { + guard !isEmpty else { return node } + var rewrittenNodes: [ObjectIdentifier: Node] = [:] + return substitute(node, rewrittenNodes: &rewrittenNodes) + } + + // The tree a demangler hands back is a DAG — every back-reference to a + // substitution is the same instance — so the walk is memoized by identity + // and stays linear in the unique nodes. A subtree with nothing to + // substitute comes back as the same instance. + private func substitute(_ node: Node, rewrittenNodes: inout [ObjectIdentifier: Node]) -> Node { + if let rewrittenNode = rewrittenNodes[ObjectIdentifier(node)] { + return rewrittenNode + } + let rewrittenNode: Node + if node.kind == .dependentGenericParamType, let argument = boundArgument(of: node) { + // The parameter node sits inside a `.type` wrapper already, so the + // argument's own wrapper is dropped to leave exactly one. + rewrittenNode = argument.firstChild ?? argument + } else { + var rewrittenChildren: [Node] = [] + rewrittenChildren.reserveCapacity(node.children.count) + var hasRewrittenChild = false + for child in node.children { + let rewrittenChild = substitute(child, rewrittenNodes: &rewrittenNodes) + hasRewrittenChild = hasRewrittenChild || rewrittenChild !== child + rewrittenChildren.append(rewrittenChild) + } + // A node's children and contents are mutually exclusive, so a node + // rebuilt from its children alone loses nothing. + rewrittenNode = hasRewrittenChild ? Node.createTransient(kind: node.kind, children: rewrittenChildren) : node + } + rewrittenNodes[ObjectIdentifier(node)] = rewrittenNode + return rewrittenNode + } + + private func boundArgument(of parameterNode: Node) -> Node? { + guard parameterNode.children.count == 2, + let depth = parameterNode.children[0].index, + let index = parameterNode.children[1].index + else { return nil } + return argument(depth: Int(depth), index: Int(index)) + } + + private static func typeWrapped(_ node: Node) -> Node { + node.kind == .type ? node : Node.createTransient(kind: .type, child: node) + } +} + +// MARK: - Reading an instantiated type node + +extension GenericArgumentBinding { + /// The argument lists an instantiated type node carries, one per level + /// that declares parameters, outermost first — so the i-th list is depth + /// i's arguments. + /// + /// The demangler wraps exactly the levels that declare parameters in a + /// `boundGeneric*` node; a level that declares none (`Middle` in + /// `Outer.Middle.Inner`) is a plain nominal. A type declared + /// in an extension has the extension as its context, and the outer + /// arguments ride the extension's extended type: `Outer.Inner` + /// for an `Inner` in `extension Outer where …` is `Inner` under + /// `Extension(, Outer, )`. The walk goes through + /// it; a module, a function or any other context ends it, since no + /// instantiated level can sit beyond one. + public static func argumentListsByLevel(ofInstantiatedTypeNode node: Node) -> [[Node]] { + var argumentListsInnermostFirst: [[Node]] = [] + var currentNode: Node? = node + while let cursor = currentNode { + let unwrapped = (cursor.kind == .type ? cursor.firstChild : cursor) ?? cursor + switch unwrapped.kind { + case .boundGenericStructure, .boundGenericEnum, .boundGenericClass, + .boundGenericOtherNominalType, .boundGenericTypeAlias, .boundGenericProtocol: + // The direct `TypeList` child only: a nested generic argument's + // own list must not be picked up. + if let typeList = unwrapped.children.first(where: { $0.kind == .typeList }), !typeList.children.isEmpty { + argumentListsInnermostFirst.append(Array(typeList.children)) + } + currentNode = unwrapped.firstChild + case .structure, .enum, .class, .otherNominalType, .typeAlias, .protocol: + // A nominal's first child is its declaration context. + currentNode = unwrapped.firstChild + case .extension: + // `Extension(, , ?)`. + currentNode = unwrapped.children.count > 1 ? unwrapped.children[1] : nil + default: + currentNode = nil + } + } + return argumentListsInnermostFirst.reversed() + } +} diff --git a/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift b/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift new file mode 100644 index 000000000..9b7cda310 --- /dev/null +++ b/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift @@ -0,0 +1,171 @@ +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Internals) import Demangling + +/// How a generic context's parameters split into depths — the first half of +/// the `(depth, index)` pair every mangled reference to a parameter carries +/// (`τ_1_0`, printed `A1`). +/// +/// A generic context descriptor records its parameters as one cumulative list, +/// outermost first, and records where one depth ends and the next begins +/// nowhere. The parent chain does not say it either, for two reasons: +/// +/// - A type that declares no parameter of its own — `Middle` in +/// `Outer.Middle.Inner` — is generic all the same (it inherits `A`), +/// so it has a generic context, yet it opens no depth: `B` is at depth 1. +/// - An extension declares no parameter either, but its context carries every +/// parameter of the type it extends, and those can span several depths: +/// `extension Outer.SecondMiddle where A == Int` covers `Outer`'s depth 0 and +/// `SecondMiddle`'s depth 1 in one context. +/// +/// So a depth is opened by each type or opaque-type context that adds +/// parameters, and by each level of an extended type that declares them — +/// what the compiler's generic signatures say, and the levels the runtime's +/// `_buildDemanglingForContext` hangs a nested instantiation's arguments on. +/// Counting every generic ancestor as a depth instead named `Inner`'s `B` as +/// `A2` in printed headers and in `GenericSpecializer`'s requests, while every +/// field and requirement read `A1`. +public struct GenericParameterDepthLayout: Sendable, Hashable { + /// The number of parameters at each depth, outermost first. Never holds a + /// zero. + public let parameterCountsByDepth: [Int] + + public init(parameterCountsByDepth: [Int]) { + self.parameterCountsByDepth = parameterCountsByDepth.filter { $0 > 0 } + } + + /// Every parameter of the context — its `numParams`. + public var parameterCount: Int { + parameterCountsByDepth.reduce(0, +) + } + + public var depthCount: Int { + parameterCountsByDepth.count + } + + /// The `(depth, index)` of the parameter at `flatIndex` in the cumulative + /// parameter list, `nil` past its end. + public func position(ofParameterAt flatIndex: Int) -> (depth: Int, index: Int)? { + guard flatIndex >= 0 else { return nil } + var remaining = flatIndex + for (depth, count) in parameterCountsByDepth.enumerated() { + if remaining < count { return (depth, remaining) } + remaining -= count + } + return nil + } + + /// The position in the cumulative parameter list of the parameter + /// `(depth, index)`, `nil` when there is no such parameter. + public func flatIndex(depth: Int, index: Int) -> Int? { + guard parameterCountsByDepth.indices.contains(depth), index >= 0, index < parameterCountsByDepth[depth] else { return nil } + return parameterCountsByDepth[..(_ elements: [Element]) -> [[Element]]? { + guard elements.count == parameterCount else { return nil } + var groups: [[Element]] = [] + groups.reserveCapacity(parameterCountsByDepth.count) + var start = elements.startIndex + for count in parameterCountsByDepth { + groups.append(Array(elements[start ..< start + count])) + start += count + } + return groups + } +} + +// MARK: - Reading a descriptor + +extension GenericParameterDepthLayout { + /// The depth layout of `descriptor`'s generic context, `nil` for a + /// descriptor that is not generic. + public static func make(for descriptor: ContextDescriptorWrapper, in context: some ReadingContext) throws -> GenericParameterDepthLayout? { + guard let genericContext = try descriptor.genericContext(in: context) else { return nil } + return make(for: genericContext, ownedBy: descriptor, in: context) + } + + /// The depth layout of `genericContext`, read from `descriptor` — for a + /// caller that holds the context already. + /// + /// The parent chain is walked the way `TargetGenericContext` walks it to + /// collect `parentParameters` — every type or extension ancestor with a + /// generic context, the first unresolvable parent ending the walk — so the + /// ancestors line up one to one with those cumulative lists. Should they + /// not, or an extension's extended type not split the way its parameter + /// count says, the level counts as one depth: the layout the parent chain + /// alone gives, never a guess past it. + public static func make
( + for genericContext: TargetGenericContext
, + ownedBy descriptor: ContextDescriptorWrapper, + in context: some ReadingContext + ) -> GenericParameterDepthLayout { + make(for: genericContext, ownedBy: descriptor.contextDescriptor, in: context) + } + + /// The depth layout of `genericContext`, read from `descriptor` — the + /// form for a caller holding the descriptor itself rather than a wrapper. + public static func make
( + for genericContext: TargetGenericContext
, + ownedBy descriptor: some ContextDescriptorProtocol, + in context: some ReadingContext + ) -> GenericParameterDepthLayout { + let ancestors = genericAncestorsOutermostFirst(of: descriptor, in: context) + let ancestorExtensions: [ExtensionContextDescriptor?] = ancestors.count == genericContext.parentParameters.count + ? ancestors.map(\.extensionContextDescriptor) + : Array(repeating: nil, count: genericContext.parentParameters.count) + let levelExtensions = ancestorExtensions + [descriptor as? ExtensionContextDescriptor] + let cumulativeCounts = genericContext.parentParameters.map(\.count) + [genericContext.parameters.count] + + var parameterCountsByDepth: [Int] = [] + var previousCumulativeCount = 0 + for (levelExtension, cumulativeCount) in zip(levelExtensions, cumulativeCounts) { + let addedCount = cumulativeCount - previousCumulativeCount + previousCumulativeCount = max(previousCumulativeCount, cumulativeCount) + guard addedCount > 0 else { continue } + if let levelExtension, + let extendedLevelCounts = extendedTypeParameterCountsByLevel(of: levelExtension, in: context), + extendedLevelCounts.reduce(0, +) == addedCount { + parameterCountsByDepth.append(contentsOf: extendedLevelCounts) + } else { + parameterCountsByDepth.append(addedCount) + } + } + return GenericParameterDepthLayout(parameterCountsByDepth: parameterCountsByDepth) + } + + /// The ancestors of `descriptor` whose generic contexts the descriptor's + /// own `parentParameters` record, outermost first. + private static func genericAncestorsOutermostFirst(of descriptor: some ContextDescriptorProtocol, in context: some ReadingContext) -> [ContextDescriptorWrapper] { + var ancestorsInnermostFirst: [ContextDescriptorWrapper] = [] + var parent = (try? descriptor.parent(in: context))?.flatMap(\.resolved) + while let currentParent = parent { + switch currentParent { + case .type, .extension: + if currentParent.contextDescriptor.layout.flags.isGeneric { + ancestorsInnermostFirst.append(currentParent) + } + default: + break + } + parent = (try? currentParent.parent(in: context))?.flatMap(\.resolved) + } + return ancestorsInnermostFirst.reversed() + } + + /// How many parameters each level of an extension's extended type + /// declares, outermost first: the argument lists of its extended-context + /// mangling, which IRGen spells as the self type in the extension's own + /// parameters (`Outer.SecondMiddle`). + private static func extendedTypeParameterCountsByLevel(of extensionDescriptor: ExtensionContextDescriptor, in context: some ReadingContext) -> [Int]? { + guard let extendedContext = try? extensionDescriptor.extendedContext(in: context), + let extendedTypeNode = try? SymbolicDemangler.demangleType(for: extendedContext, in: context) + else { return nil } + let argumentLists = GenericArgumentBinding.argumentListsByLevel(ofInstantiatedTypeNode: extendedTypeNode) + guard !argumentLists.isEmpty else { return nil } + return argumentLists.map(\.count) + } +} diff --git a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift index 7469cfe97..8e7a78ac8 100644 --- a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift +++ b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift @@ -300,7 +300,8 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { var witnessTables: [ProtocolWitnessTable] = [] if let genericContext { - switch keyArguments(of: genericContext, ownArguments: ownArguments, parentType: parentType) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(typeWrapper), in: .inProcess) + switch keyArguments(of: genericContext, depthLayout: depthLayout, ownArguments: ownArguments, parentType: parentType) { case .success(let gathered): keyMetadataTypes = gathered.metadataTypes witnessTables = gathered.witnessTables @@ -340,6 +341,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { private func keyArguments( of genericContext: GenericContext, + depthLayout: GenericParameterDepthLayout, ownArguments: [Any.Type], parentType: Any.Type? ) -> TypeLookupErrorOr { @@ -385,7 +387,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { // whose bindings are the written arguments. var subjectBuilder = self subjectBuilder.genericParameterMetadataTypes = Self.bindings( - of: genericContext, + of: depthLayout, writtenArguments: writtenArguments ) @@ -448,28 +450,19 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { } /// Maps every cumulative generic parameter position to its written - /// argument, using the per-level "newly introduced" counts so `(depth, - /// index)` matches the demangler's coordinates. + /// argument at the `(depth, index)` the demangler names it by — the depth + /// `depthLayout` gives, which counts only the contexts that declare + /// parameters. Counting every generic ancestor bound `Second` in + /// `Outer.NonDeclaringLevel.ConstrainedPair` at depth 2, + /// and its requirement `A1: Hashable` found no argument. private static func bindings( - of genericContext: GenericContext, + of depthLayout: GenericParameterDepthLayout, writtenArguments: [Any.Type] ) -> [GenericParameterPosition: Any.Type] { - var perLevelCounts: [Int] = [] - var previousCumulativeCount = 0 - for parentLevel in genericContext.parentParameters { - perLevelCounts.append(parentLevel.count - previousCumulativeCount) - previousCumulativeCount = parentLevel.count - } - perLevelCounts.append(genericContext.currentParameters.count) - var result: [GenericParameterPosition: Any.Type] = [:] - var flatIndex = 0 - for (depth, count) in perLevelCounts.enumerated() { - for indexInLevel in 0 ..< count { - guard flatIndex < writtenArguments.count else { return result } - result[GenericParameterPosition(depth: depth, index: indexInLevel)] = writtenArguments[flatIndex] - flatIndex += 1 - } + for (flatIndex, writtenArgument) in writtenArguments.enumerated() { + guard let position = depthLayout.position(ofParameterAt: flatIndex) else { break } + result[GenericParameterPosition(depth: position.depth, index: position.index)] = writtenArgument } return result } diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index 4123a9e99..df1477158 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -409,13 +409,13 @@ extension SymbolicDemangler { return top } - private static func buildContextDescriptorMangling(context: SymbolOrElement, recursionLimit: Int, in readingContext: some ReadingContext) throws -> Node? { + private static func buildContextDescriptorMangling(context: SymbolOrElement, recursionLimit: Int, instantiation: ContextInstantiation? = nil, in readingContext: some ReadingContext) throws -> Node? { guard recursionLimit > 0 else { return nil } switch context { case .symbol(let symbol): return try _buildContextManglingForSymbol(symbol, in: readingContext) case .element(let contextDescriptor): - var demangleSymbol = try buildContextDescriptorMangling(context: contextDescriptor, recursionLimit: recursionLimit, in: readingContext) + var demangleSymbol = try buildContextDescriptorMangling(context: contextDescriptor, recursionLimit: recursionLimit, instantiation: instantiation, in: readingContext) if demangleSymbol?.kind == .type { demangleSymbol = demangleSymbol?.children.first @@ -424,7 +424,7 @@ extension SymbolicDemangler { } } - private static func buildContextDescriptorMangling(context: ContextDescriptorWrapper, recursionLimit: Int, in readingContext: some ReadingContext) throws -> Node? { + private static func buildContextDescriptorMangling(context: ContextDescriptorWrapper, recursionLimit: Int, instantiation: ContextInstantiation? = nil, in readingContext: some ReadingContext) throws -> Node? { guard recursionLimit > 0 else { return nil } var parentDescriptorResult = try context.parent(in: readingContext) var demangledParentNode: Node? @@ -432,7 +432,7 @@ extension SymbolicDemangler { var parentDemangling: Node? if let parentDescriptor = parentDescriptorResult { - parentDemangling = try buildContextDescriptorMangling(context: parentDescriptor, recursionLimit: recursionLimit - 1, in: readingContext) + parentDemangling = try buildContextDescriptorMangling(context: parentDescriptor, recursionLimit: recursionLimit - 1, instantiation: instantiation, in: readingContext) if parentDemangling == nil, demangledParentNode == nil { return nil } @@ -478,6 +478,9 @@ extension SymbolicDemangler { guard let parentDemangling else { return nil } guard let extensionContext = context.extensionContextDescriptor else { return nil } guard let extendedContext = try extensionContext.extendedContext(in: readingContext) else { return nil } + if let instantiation, let instantiatedExtension = try instantiation.instantiatedExtension(extensionContext, extendedContext: extendedContext, parentDemangling: parentDemangling, in: readingContext) { + return instantiatedExtension + } guard let demangledExtendedContext = try extendedNominalNode(fromExtendedContext: demangle(for: extendedContext, kind: .type, in: readingContext)) else { return nil } if let requirements = try extensionContext.genericContext(in: readingContext)?.requirements, let signatureNode = try buildGenericSignature(for: requirements, in: readingContext) { return Node.createTransient(kind: .extension, children: [parentDemangling, demangledExtendedContext, signatureNode]) @@ -532,6 +535,9 @@ extension SymbolicDemangler { } let demangling = Node.createTransient(kind: kind, children: [parentDemangling, nameNode]) + if let instantiation, let typeContextDescriptor = context.typeContextDescriptorWrapper { + return try instantiation.instantiatedTypeContext(demangling, of: typeContextDescriptor, in: readingContext) + } return demangling } @@ -664,6 +670,96 @@ extension SymbolicDemangler { } } +// MARK: - Instantiated type names (evolution proposal `offline-generic-specialization`) + +extension SymbolicDemangler { + /// The name of one instantiation of `descriptor`: its context demangling + /// with the arguments of `binding` hung on the levels that declare them — + /// `Outer.Inner`, `Outer.Middle`. + /// + /// A port of the runtime's `_buildDemanglingForContext` + /// (`stdlib/public/runtime/Demangle.cpp`), so an offline specialization's + /// name has the shape the runtime gives the same instantiation: walking + /// the context path outermost first, a type context whose cumulative + /// parameter count exceeds what the levels above it used takes the + /// arguments in between as its own `boundGeneric*` level, and a type that + /// declares none stays a plain nominal under its bound parent. Every other + /// part of the name — private discriminators, C-imported identities, the + /// anonymous and extension contexts — is this demangler's, exactly as for + /// the unbound name. + /// + /// One deliberate difference: an extension context takes its arguments + /// by substituting them into its extended type, which the runtime does + /// only for the outermost level of that type. For a constrained + /// extension of a nested generic type (`extension Outer.SecondMiddle where …`) + /// the runtime puts every argument into `SecondMiddle`'s list and leaves + /// `Outer` unbound, a name of no instantiation; this one binds each + /// level. Like the runtime's, the extension node carries no generic + /// signature: the arguments it constrained are spelled out. + /// + /// - Parameter binding: The arguments of every parameter of the + /// descriptor's generic context, non-key ones (fixed by a same-type + /// requirement) included, grouped by depth. + public static func instantiatedTypeNode(for descriptor: TypeContextDescriptorWrapper, binding: GenericArgumentBinding, in context: some ReadingContext) throws -> Node { + let instantiation = ContextInstantiation(binding: binding) + let demangling = try required(buildContextDescriptorMangling(context: descriptor.asContextDescriptorWrapper, recursionLimit: 50, instantiation: instantiation, in: context)) + return .createTransient(kind: .type, children: [demangling]) + } + + /// The arguments still to be hung on a context path being demangled + /// outermost first, and how many of them the levels above used — + /// `_buildDemanglingForContext`'s `usedDemangledGenerics`. + final class ContextInstantiation { + let binding: GenericArgumentBinding + private let flattenedArguments: [Node] + private var usedArgumentCount = 0 + + init(binding: GenericArgumentBinding) { + self.binding = binding + self.flattenedArguments = binding.flattenedArguments + } + + /// `demangling` — a type context's nominal node — wrapped in a + /// `boundGeneric*` level holding the arguments this context declares, + /// or returned as it is when it declares none. + func instantiatedTypeContext(_ demangling: Node, of descriptor: TypeContextDescriptorWrapper, in readingContext: some ReadingContext) throws -> Node { + guard let parameterCount = try descriptor.genericContext(in: readingContext)?.parameters.count, + parameterCount > usedArgumentCount, + parameterCount <= flattenedArguments.count + else { return demangling } + let arguments = Array(flattenedArguments[usedArgumentCount ..< parameterCount]) + usedArgumentCount = parameterCount + let boundKind: Node.Kind = switch demangling.kind { + case .class: .boundGenericClass + case .structure: .boundGenericStructure + case .enum: .boundGenericEnum + default: .boundGenericOtherNominalType + } + return .createTransient(kind: boundKind, children: [ + .createTransient(kind: .type, children: [demangling]), + .createTransient(kind: .typeList, children: arguments), + ]) + } + + /// The extension context with this instantiation's arguments + /// substituted into its extended type — `Extension(, + /// Outer)` — or `nil` when the extension declares no + /// arguments the levels above have not used, leaving the unbound form. + func instantiatedExtension(_ extensionContext: ExtensionContextDescriptor, extendedContext: MangledName, parentDemangling: Node, in readingContext: some ReadingContext) throws -> Node? { + guard let parameterCount = try extensionContext.genericContext(in: readingContext)?.parameters.count, + parameterCount > usedArgumentCount + else { return nil } + // IRGen spells the extended type in the extension's own + // parameters (`Outer.SecondMiddle`), so substituting the binding + // binds every level of it. + let extendedType = binding.substituting(in: try SymbolicDemangler.demangle(for: extendedContext, kind: .type, in: readingContext)) + usedArgumentCount = parameterCount + let selfType = extendedType.kind == .type ? (extendedType.firstChild ?? extendedType) : extendedType + return .createTransient(kind: .extension, children: [parentDemangling, selfType]) + } + } +} + // MARK: - C-imported type identity (evolution proposal `type-import-info-identity`) extension SymbolicDemangler { diff --git a/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift b/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift index c9025a3a6..c359da890 100644 --- a/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift +++ b/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift @@ -304,11 +304,16 @@ extension StaticTypeLayoutResolver { /// every instantiation, while an argument-dependent one (no record) /// projects the runtime's tagged strategy. Either way an unspecialized /// projection matches every instantiation. + /// + /// `environment` binds an instantiation's arguments — an offline + /// specialization's (evolution proposal `offline-generic-specialization`) + /// — so an enum whose payload depends on them projects too. func enumCaseLayoutResult( of descriptor: EnumDescriptor, - in image: ImageReference + in image: ImageReference, + environment: GenericArgumentEnvironment = .empty ) throws -> EnumLayoutCalculator.LayoutResult? { - let environment = GenericArgumentEnvironment.empty.augmented( + let environment = environment.augmented( withRequirementFacts: ClassBoundGenericParameterAnalysis.layoutFacts(of: descriptor, in: image, imageUniverse: imageUniverse) ) let payloadCaseCount = descriptor.numberOfPayloadCases diff --git a/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift b/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift index 850228495..0f1fac832 100644 --- a/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift +++ b/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift @@ -1,4 +1,5 @@ import Demangling +@_spi(Internals) import SwiftInspection /// A generic parameter's position in a generic signature: its declaration /// `depth` (0 = the type's own parameters, 1+ = an enclosing generic context) @@ -87,12 +88,23 @@ struct GenericArgumentEnvironment { /// Derives the substitution map from an instantiated type node: the node's /// own `boundGeneric*` argument list (if any) plus the argument lists of - /// every bound-generic level along its nominal context chain, bound at - /// their generic-signature depths (outermost level = depth 0). Returns - /// `.empty` for a node with no instantiated level, or one whose arguments - /// cannot all be modelled. + /// every bound-generic level along its context chain — through an + /// extension context into the type it extends — bound at their + /// generic-signature depths (outermost level = depth 0; see + /// `GenericArgumentBinding.argumentListsByLevel(ofInstantiatedTypeNode:)`). + /// Returns `.empty` for a node with no instantiated level, or one whose + /// arguments cannot all be modelled. static func make(forInstantiatedTypeNode node: Node) -> GenericArgumentEnvironment { - let argumentListsByDepth = instantiatedLevelArgumentLists(endingAt: node) + make(forArgumentListsByDepth: GenericArgumentBinding.argumentListsByLevel(ofInstantiatedTypeNode: node)) + } + + /// The substitution map of an instantiation's argument lists, one per + /// depth, outermost first — the shape `GenericArgumentBinding` carries. + static func make(forBinding binding: GenericArgumentBinding) -> GenericArgumentEnvironment { + make(forArgumentListsByDepth: binding.argumentsByDepth) + } + + private static func make(forArgumentListsByDepth argumentListsByDepth: [[Node]]) -> GenericArgumentEnvironment { guard !argumentListsByDepth.isEmpty else { return .empty } var substitutions: [GenericParameterKey: Node] = [:] for (depth, arguments) in argumentListsByDepth.enumerated() { @@ -107,36 +119,6 @@ struct GenericArgumentEnvironment { return GenericArgumentEnvironment(substitutions: substitutions) } - /// Collects one argument list per instantiated level along the nominal - /// context chain of `node`, ordered outermost-first (the generic-signature - /// depth order). Walks from the node outward through `.type` wrappers, - /// `boundGeneric*` shells (collecting each non-empty direct `.typeList`), - /// and nominal contexts; any other context kind (a module, an extension, a - /// function) ends the walk — an instantiated level cannot appear beyond it. - private static func instantiatedLevelArgumentLists(endingAt node: Node) -> [[Node]] { - var argumentListsInnermostFirst: [[Node]] = [] - var currentNode: Node? = node - while let cursor = currentNode { - // Tolerate a leading `.type` wrapper at every step: a freshly - // demangled node is `.type`-wrapped, and so is the underlying - // nominal inside each `boundGeneric*` shell. - let unwrapped = (cursor.kind == .type ? cursor.firstChild : cursor) ?? cursor - if isBoundGenericKind(unwrapped.kind) { - if let typeList = directTypeList(of: unwrapped), !typeList.children.isEmpty { - argumentListsInnermostFirst.append(Array(typeList.children)) - } - currentNode = unwrapped.firstChild - } else if unwrapped.kind == .structure || unwrapped.kind == .enum || unwrapped.kind == .class { - // A nominal's first child is its declaration context — the next - // link outward in the chain. - currentNode = unwrapped.firstChild - } else { - currentNode = nil - } - } - return argumentListsInnermostFirst.reversed() - } - /// Builds the depth-0 substitution map directly from a list of concrete /// arguments (ordered by declaration), as supplied by a caller that holds a /// generic type descriptor and its instantiation arguments rather than a @@ -376,23 +358,6 @@ struct GenericArgumentEnvironment { // MARK: - Node shape helpers - private static func isBoundGenericKind(_ kind: Node.Kind) -> Bool { - switch kind { - case .boundGenericStructure, .boundGenericEnum, .boundGenericClass, - .boundGenericOtherNominalType, .boundGenericTypeAlias, .boundGenericProtocol: - return true - default: - return false - } - } - - /// The direct `.typeList` child of a bound-generic node (its argument list), - /// `nil` if absent. Scans direct children rather than a deep search so a - /// nested generic argument's own `.typeList` is never picked up. - private static func directTypeList(of node: Node) -> Node? { - node.children.first(where: { $0.kind == .typeList }) - } - /// The unwrapped inner node of a `.type`-wrapped argument, or `nil` if the /// argument cannot serve as a positional substitution value. Plain types, /// value arguments (`.integer` / `.negativeInteger`), and *flat* packs are diff --git a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift index 9a913f71e..d839efe4c 100644 --- a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift +++ b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift @@ -1,4 +1,4 @@ -import Demangling +@_spi(Internals) import Demangling import MachOSwiftSection @_spi(Internals) import SwiftInspection @@ -73,3 +73,64 @@ extension ImageUniverse { ) } } + +// MARK: - Projecting every concrete member of a type + +extension ImageUniverse { + /// `node` with every dependent member whose base is concrete replaced by + /// the type its conformance's witness record names — `[Swift.Int].Element` + /// becomes `Swift.Int` (evolution proposal `offline-generic-specialization`). + /// + /// What a substitution leaves behind: a field typed `Elements.Element` + /// reads `[Swift.Int].Element` once `Elements` is `[Swift.Int]`, a member + /// of a concrete type the runtime would have resolved through the + /// conformance. A member whose base still holds a generic parameter, or + /// whose record no image in the universe carries, stays as it is. A + /// witness may itself name a member of the base's arguments + /// (`IndexingIterator`'s `Element` is `Elements.Element`), so a projection + /// is projected again, a bounded number of hops deep. + public func projectingConcreteMembers(in node: Node) -> Node { + var rewrittenNodes: [ObjectIdentifier: Node] = [:] + return projectingConcreteMembers(in: node, remainingHops: Self.maximumProjectionHops, rewrittenNodes: &rewrittenNodes) + } + + /// How many witness records one member may be projected through. A real + /// chain is a handful deep; the bound only keeps a malformed record from + /// looping. + private static var maximumProjectionHops: Int { 8 } + + private func projectingConcreteMembers(in node: Node, remainingHops: Int, rewrittenNodes: inout [ObjectIdentifier: Node]) -> Node { + if let rewrittenNode = rewrittenNodes[ObjectIdentifier(node)] { + return rewrittenNode + } + var rewrittenChildren: [Node] = [] + rewrittenChildren.reserveCapacity(node.children.count) + var hasRewrittenChild = false + for child in node.children { + let rewrittenChild = projectingConcreteMembers(in: child, remainingHops: remainingHops, rewrittenNodes: &rewrittenNodes) + hasRewrittenChild = hasRewrittenChild || rewrittenChild !== child + rewrittenChildren.append(rewrittenChild) + } + // A node's children and contents are mutually exclusive, so a node + // rebuilt from its children alone loses nothing. + var rewrittenNode = hasRewrittenChild ? Node.createTransient(kind: node.kind, children: rewrittenChildren) : node + if rewrittenNode.kind == .dependentMemberType, + remainingHops > 0, + let baseTypeNode = rewrittenNode.children.first, + let associatedTypeReference = rewrittenNode.children.at(1), + !Self.containsGenericParameter(baseTypeNode), + let projection = projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference) { + var nestedRewrittenNodes: [ObjectIdentifier: Node] = [:] + let projectedWitness = projectingConcreteMembers(in: projection.witnessNode, remainingHops: remainingHops - 1, rewrittenNodes: &nestedRewrittenNodes) + // The member sits inside a `.type` wrapper already; the witness's + // own wrapper is dropped to leave exactly one. + rewrittenNode = projectedWitness.kind == .type ? (projectedWitness.firstChild ?? projectedWitness) : projectedWitness + } + rewrittenNodes[ObjectIdentifier(node)] = rewrittenNode + return rewrittenNode + } + + private static func containsGenericParameter(_ node: Node) -> Bool { + node.kind == .dependentGenericParamType || node.children.contains(where: containsGenericParameter) + } +} diff --git a/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift b/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift index 31a57eec4..b5977de1b 100644 --- a/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift +++ b/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift @@ -65,6 +65,32 @@ extension StaticLayoutCalculator { ) } + /// The expanded tree of a field of the instantiation `binding` makes of + /// the type declaring it: the field's type with the binding's arguments + /// substituted, so `let inner: Inner` expands as `Inner` + /// does (evolution proposal `offline-generic-specialization`). + public func nestedFieldOffsetTree( + forMangledTypeName mangledTypeName: MangledName, + baseOffset: Int, + depthLimit: Int, + genericArgumentBinding binding: GenericArgumentBinding + ) -> [NestedFieldOffset] { + guard let node = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: imageUniverse.rootImage.machO.context) else { + return [] + } + let substitutedNode = imageUniverse.projectingConcreteMembers(in: GenericArgumentEnvironment.make(forBinding: binding).substituting(in: node)) + return nestedChildren( + forTypeNode: substitutedNode, + typeDisplayName: substitutedNode.print(using: .default), + in: imageUniverse.rootImage, + baseOffset: baseOffset, + depth: 0, + depthLimit: depthLimit, + enclosingTypeNames: [], + hasUnconditionalStorage: true + ) + } + /// Recurses into a (possibly `.type`-wrapped, possibly bound-generic) type /// node, returning its sub-fields. `image` is the image the node's mangled /// names are read against; recursion switches it to a nested type's defining @@ -231,8 +257,12 @@ extension StaticLayoutCalculator { byteWidth: Int? ) -> NestedFieldOffset { let fieldName = ((try? record.fieldName(in: image.machO.context)).flatMap { $0.isEmpty ? nil : $0 }) ?? fallbackFieldName + // A member of a concrete type the substitution leaves behind + // (`[Swift.Int].Element` in an instantiation over `[Swift.Int]`) is + // named — and expanded — as the type its witness record names, the + // way the runtime's walk names it. let fieldTypeNode: Node? = (try? record.mangledTypeName(in: image.machO.context)).flatMap { mangledTypeName in - (try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO.context)).map { environment.substituting(in: $0) } + (try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO.context)).map { imageUniverse.projectingConcreteMembers(in: environment.substituting(in: $0)) } } let typeName = fieldTypeNode?.print(using: .default) ?? "" let children = descendsIntoFieldType ? (fieldTypeNode.map { diff --git a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift index e0140bef2..a1d905316 100644 --- a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift +++ b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift @@ -144,6 +144,51 @@ public struct StaticLayoutCalculator.Inner`) + /// lays out too, which the depth-0 `genericArguments:` form cannot. An + /// enum reports no fields. + public func fieldLayout( + of typeDescriptor: TypeContextDescriptorWrapper, + genericArgumentBinding binding: GenericArgumentBinding + ) throws -> AggregateFieldLayout { + try fieldLayout(of: typeDescriptor, in: imageUniverse.rootImage, environment: .make(forBinding: binding)) + } + + /// The whole-type layout of a field or payload type, lowered in the + /// context of `contextDescriptor` instantiated by `binding`: the + /// binding's arguments first, then the requirement signature's facts for + /// any parameter it leaves open. + public func typeLayout( + forMangledTypeName mangledTypeName: MangledName, + inContextOfDescriptor contextDescriptor: TypeContextDescriptorWrapper, + genericArgumentBinding binding: GenericArgumentBinding + ) throws -> StaticTypeLayout { + let image = imageUniverse.rootImage + let environment = GenericArgumentEnvironment.make(forBinding: binding).augmented( + withRequirementFacts: ClassBoundGenericParameterAnalysis.layoutFacts( + of: contextDescriptor.typeContextDescriptor, + in: image, + imageUniverse: imageUniverse + ) + ) + return try resolver.layout(forMangledTypeName: mangledTypeName, in: image, environment: environment) + } + + /// The per-case projection layout of the instantiation `binding` makes + /// of an enum descriptor: payloads that depend on the arguments resolve + /// through them. `nil` as for the unbound form. + public func enumCaseLayoutResult( + forDescriptor typeDescriptor: TypeContextDescriptorWrapper, + genericArgumentBinding binding: GenericArgumentBinding + ) -> EnumLayoutCalculator.LayoutResult? { + guard let enumDescriptor = typeDescriptor.enum else { return nil } + return try? resolver.enumCaseLayoutResult(of: enumDescriptor, in: imageUniverse.rootImage, environment: .make(forBinding: binding)) + } + // MARK: - Descriptor dispatch private func fieldLayout( diff --git a/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift index d7f500ea2..2ed8650b5 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift @@ -1,4 +1,5 @@ import MachOSwiftSection +@_spi(Internals) import SwiftInspection /// The generic parameters of the declaration an accessor thunk belongs to — /// an opaque type descriptor, or the type whose field record the thunk @@ -21,8 +22,24 @@ public struct AccessorThunkOwnerLayout: Sendable, Hashable { /// No knowledge of the owner: every argument read is unnameable. public static let unknown = AccessorThunkOwnerLayout(genericParameterKeyFlagsByDepth: []) - /// The layout a descriptor's generic context describes; `nil` — a - /// non-generic owner — yields an empty layout. + /// The layout of an owner's generic context split into depths by + /// `depthLayout` (`GenericParameterDepthLayout.make(for:ownedBy:in:)`); + /// `nil` — a non-generic owner — yields an empty layout. + public init
(genericContext: TargetGenericContext
?, depthLayout: GenericParameterDepthLayout) { + guard let genericContext, let flagsByDepth = depthLayout.grouped(genericContext.parameters.map(\.hasKeyArgument)) else { + self.init(genericContext: genericContext) + return + } + self.init(genericParameterKeyFlagsByDepth: flagsByDepth) + } + + /// The layout a descriptor's generic context describes, read from the + /// context alone; `nil` — a non-generic owner — yields an empty layout. + /// + /// Without the owner's descriptor the depths come from the parent chain, + /// which gets one shape wrong: an extension ancestor that spans several + /// depths (`extension Outer.SecondMiddle where …`) counts as one. Prefer + /// `init(genericContext:depthLayout:)`. public init
(genericContext: TargetGenericContext
?) { guard let genericContext else { self.init(genericParameterKeyFlagsByDepth: []) @@ -30,10 +47,12 @@ public struct AccessorThunkOwnerLayout: Sendable, Hashable { } // `parentParameters` is cumulative per generic ancestor, so each // depth's own parameters are the tail past the previous depth's - // count; the innermost depth is `currentParameters`. + // count; the innermost depth is `currentParameters`. An ancestor + // that adds nothing — a type that is generic only because it is + // nested in one — opens no depth. var flagsByDepth: [[Bool]] = [] var previousCount = 0 - for parentParameters in genericContext.parentParameters { + for parentParameters in genericContext.parentParameters where parentParameters.count > previousCount { flagsByDepth.append(parentParameters.dropFirst(previousCount).map(\.hasKeyArgument)) previousCount = parentParameters.count } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift index 3a306b4f2..49d916584 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift @@ -113,7 +113,11 @@ extension TypeDefinition: OnceIndexedDefinition { // generic, say) is read offline through the same thunk reader the // opaque-type path uses; the thunk's arguments are this type's own // generic arguments. - let accessorThunkOwnerLayout = AccessorThunkOwnerLayout(genericContext: try typeContextDescriptor.genericContext(in: machO.context)) + let ownerGenericContext = try typeContextDescriptor.genericContext(in: machO.context) + let accessorThunkOwnerLayout = AccessorThunkOwnerLayout( + genericContext: ownerGenericContext, + depthLayout: ownerGenericContext.map { GenericParameterDepthLayout.make(for: $0, ownedBy: typeContextDescriptor, in: machO.context) } ?? GenericParameterDepthLayout(parameterCountsByDepth: []) + ) var indexedFields: [FieldDefinition] = [] for record in records { let typeNode = try record.demangledTypeNode(in: machO.context) diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift index 59889a46b..a8ec099cf 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift @@ -28,11 +28,12 @@ public final class TypeDefinition: Definition, @unchecked Sendable { public let typeName: TypeName /// `true` when this definition was produced via `specialize(with:in:)` — - /// i.e. it carries a runtime-resolved `metadata` and a bound-generic - /// `typeName`. `false` for the canonical, unspecialized definitions - /// produced from a MachO image's section data. Always known at - /// construction time, so callers can branch on the type kind without - /// inspecting the optional `metadata` field. + /// i.e. it carries a bound-generic `typeName` and either a + /// runtime-resolved `metadata` or, specialized offline, a + /// `staticSpecialization`. `false` for the canonical, unspecialized + /// definitions produced from a MachO image's section data. Always known + /// at construction time, so callers can branch on the type kind without + /// inspecting the optional fields. public let isSpecialized: Bool /// Whether this type's nominal type descriptor is in the image's export @@ -162,6 +163,18 @@ public final class TypeDefinition: Definition, @unchecked Sendable { /// call the descriptor's metadata accessor. public package(set) var metadata: MetadataWrapper? = nil + /// The arguments an offline specialization bound this definition's + /// generic parameters to, by depth (evolution proposal + /// `offline-generic-specialization`). + /// + /// The offline counterpart of `metadata`: a specialization made from a + /// file has no runtime metadata, so it carries the arguments the + /// metadata would have been instantiated from, and the printer renders + /// the bound header, the substituted field types and the layout comments + /// from them. `nil` for the canonical definition and for a runtime + /// specialization; at most one of the two is ever set. + public package(set) var staticSpecialization: GenericArgumentBinding? = nil + public var hasMembers: Bool { !fields.isEmpty || !variables.isEmpty || !functions.isEmpty || !subscripts.isEmpty || !staticVariables.isEmpty || !staticFunctions.isEmpty || !staticSubscripts.isEmpty || !allocators.isEmpty || !constructors.isEmpty || hasDeallocator diff --git a/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift new file mode 100644 index 000000000..8fde46b1d --- /dev/null +++ b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift @@ -0,0 +1,180 @@ +import Foundation +@_spi(Internals) import Demangling +import MachOKit +import MachOSwiftSection +import SwiftDeclaration +import SwiftDeclarationRendering +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection + +/// The arguments of every parameter of one instantiation of a generic type, +/// grouped by depth, and the instantiation's name (evolution proposal +/// `offline-generic-specialization`). +/// +/// A specialization request offers only the parameters that take a key +/// argument. A parameter a same-type requirement fixes takes none — `A` in +/// `extension Outer where A == Int { struct Inner }` — but the +/// instantiation still binds it, and its name spells it: +/// `Outer.Inner`. The runtime recovers such an +/// argument from the requirement (`_gatherWrittenGenericParameters`); this +/// does the same with nodes: the requirement's right-hand side, with the +/// arguments known so far substituted and any member of a concrete type +/// projected through its conformance. +/// +/// Shared by both specializations: the offline one binds its result with it, +/// and the runtime one names its definition with it, so the two give the +/// same instantiation the same name. +package struct GenericInstantiation { + package let binding: GenericArgumentBinding + + /// The instantiation's name, `.type`-wrapped. + package let typeNode: Node + + /// - Parameter keyArguments: One `.type`-wrapped node per parameter that + /// takes a key argument, in the order of the generic context's + /// cumulative parameter list — `SpecializationRequest.parameters`'s + /// order. + package init( + of descriptor: TypeContextDescriptorWrapper, + keyArguments: [Node], + in machO: MachO + ) throws { + guard let genericContext = try descriptor.genericContext(in: machO.context) else { + throw GenericInstantiationError.notGeneric + } + let parameters = genericContext.parameters + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(descriptor), in: machO.context) + guard depthLayout.parameterCount == parameters.count else { + throw GenericInstantiationError.depthLayoutMismatch(parameterCount: parameters.count, layoutParameterCount: depthLayout.parameterCount) + } + + var argumentsByFlatIndex: [Node?] = Array(repeating: nil, count: parameters.count) + var remainingKeyArguments = keyArguments[...] + for (flatIndex, parameter) in parameters.enumerated() where parameter.hasKeyArgument { + guard let argument = remainingKeyArguments.popFirst() else { + throw GenericInstantiationError.keyArgumentCountMismatch(expected: parameters.filter(\.hasKeyArgument).count, actual: keyArguments.count) + } + argumentsByFlatIndex[flatIndex] = Self.typeWrapped(argument) + } + guard remainingKeyArguments.isEmpty else { + throw GenericInstantiationError.keyArgumentCountMismatch(expected: parameters.filter(\.hasKeyArgument).count, actual: keyArguments.count) + } + + try Self.fillFixedParameters( + &argumentsByFlatIndex, + depthLayout: depthLayout, + requirements: genericContext.requirements, + in: machO + ) + + let arguments = argumentsByFlatIndex.compactMap { $0 } + guard let argumentsByDepth = depthLayout.grouped(arguments) else { + throw GenericInstantiationError.depthLayoutMismatch(parameterCount: arguments.count, layoutParameterCount: depthLayout.parameterCount) + } + self.binding = GenericArgumentBinding(argumentsByDepth: argumentsByDepth) + self.typeNode = try SymbolicDemangler.instantiatedTypeNode(for: descriptor, binding: binding, in: machO.context) + } + + /// Fills every parameter without a key argument from the same-type + /// requirement that fixes it. A right-hand side can name another fixed + /// parameter (`C == B`, `B == Int`), so the requirements are applied until + /// no further one resolves. + private static func fillFixedParameters( + _ argumentsByFlatIndex: inout [Node?], + depthLayout: GenericParameterDepthLayout, + requirements: [GenericRequirementDescriptor], + in machO: MachO + ) throws { + var unresolvedFlatIndices = argumentsByFlatIndex.indices.filter { argumentsByFlatIndex[$0] == nil } + guard !unresolvedFlatIndices.isEmpty else { return } + + // The same-type requirements whose subject is a parameter itself, by + // that parameter's position in the cumulative list. + var fixingRequirementByFlatIndex: [Int: MangledName] = [:] + for requirement in requirements where requirement.layout.flags.kind == .sameType { + guard let subjectNode = try? SymbolicDemangler.demangleType(for: requirement.paramMangledName(in: machO.context), in: machO.context), + let position = genericParameterPosition(of: subjectNode), + let flatIndex = depthLayout.flatIndex(depth: position.depth, index: position.index), + fixingRequirementByFlatIndex[flatIndex] == nil, + let rightHandSide = try? requirement.type(in: machO.context) + else { continue } + fixingRequirementByFlatIndex[flatIndex] = rightHandSide + } + + var didResolveParameter = true + while !unresolvedFlatIndices.isEmpty, didResolveParameter { + didResolveParameter = false + let partialBinding = Self.partialBinding(argumentsByFlatIndex, depthLayout: depthLayout) + for flatIndex in unresolvedFlatIndices { + guard let rightHandSide = fixingRequirementByFlatIndex[flatIndex], + let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context) + else { continue } + let argument = DependentMemberProjection.projectingConcreteMembers(in: partialBinding.substituting(in: rightHandSideNode), in: machO) + guard !containsGenericParameter(argument) else { continue } + argumentsByFlatIndex[flatIndex] = typeWrapped(argument) + didResolveParameter = true + } + unresolvedFlatIndices.removeAll { argumentsByFlatIndex[$0] != nil } + } + + if let unresolvedFlatIndex = unresolvedFlatIndices.first { + let position = depthLayout.position(ofParameterAt: unresolvedFlatIndex) + throw GenericInstantiationError.unresolvedFixedParameter( + name: position.map { genericParameterName(depth: UInt64($0.depth), index: UInt64($0.index)) } ?? "#\(unresolvedFlatIndex)" + ) + } + } + + /// The arguments known so far, every unknown one standing for itself, so + /// a substitution leaves the parameters still to be resolved in place. + private static func partialBinding(_ argumentsByFlatIndex: [Node?], depthLayout: GenericParameterDepthLayout) -> GenericArgumentBinding { + let arguments = argumentsByFlatIndex.enumerated().map { flatIndex, argument in + argument ?? depthLayout.position(ofParameterAt: flatIndex).map { position in + Node.createTransient(kind: .type, child: Node.createTransient(kind: .dependentGenericParamType, children: [ + .createTransient(kind: .index, index: UInt64(position.depth)), + .createTransient(kind: .index, index: UInt64(position.index)), + ])) + } ?? Node.createTransient(kind: .type, child: .createTransient(kind: .errorType)) + } + return GenericArgumentBinding(argumentsByDepth: depthLayout.grouped(arguments) ?? []) + } + + private static func genericParameterPosition(of subjectNode: Node) -> (depth: Int, index: Int)? { + let parameterNode = subjectNode.kind == .type ? subjectNode.firstChild : subjectNode + guard let parameterNode, parameterNode.kind == .dependentGenericParamType, + parameterNode.children.count == 2, + let depth = parameterNode.children[0].index, + let index = parameterNode.children[1].index + else { return nil } + return (Int(depth), Int(index)) + } + + private static func containsGenericParameter(_ node: Node) -> Bool { + node.kind == .dependentGenericParamType || node.children.contains(where: containsGenericParameter) + } + + private static func typeWrapped(_ node: Node) -> Node { + node.kind == .type ? node : Node.createTransient(kind: .type, child: node) + } +} + +/// Why an instantiation's arguments or name could not be built. +package enum GenericInstantiationError: LocalizedError { + case notGeneric + case keyArgumentCountMismatch(expected: Int, actual: Int) + case depthLayoutMismatch(parameterCount: Int, layoutParameterCount: Int) + case unresolvedFixedParameter(name: String) + + package var errorDescription: String? { + switch self { + case .notGeneric: + return "the type is not generic" + case .keyArgumentCountMismatch(let expected, let actual): + return "the type takes \(expected) key argument(s), \(actual) supplied" + case .depthLayoutMismatch(let parameterCount, let layoutParameterCount): + return "the generic context declares \(parameterCount) parameter(s) but its depths cover \(layoutParameterCount)" + case .unresolvedFixedParameter(let name): + return "the argument of \(name), which a same-type requirement fixes, could not be determined from that requirement" + } + } +} diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift new file mode 100644 index 000000000..da0953723 --- /dev/null +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift @@ -0,0 +1,601 @@ +@_spi(Support) import SwiftIndexing +import SwiftDeclaration +import SwiftDeclarationRendering +import Foundation +import MachOSwiftSection +import MachOKit +@_spi(Internals) import Demangling +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection +#if canImport(ObjectiveC) +import ObjectiveC +#endif + +// MARK: - Offline Execution + +/// Specialization without the runtime (evolution proposal +/// `offline-generic-specialization`), for a type read from a file — what +/// RuntimeViewer's offline mode browses. Nothing in the target image runs: an +/// argument is a type node, never metadata, and the result is the +/// instantiation's name and the argument of every parameter, which the +/// interface printer and the static layout engine turn into a bound +/// declaration with its layout. +@_spi(Support) +extension GenericSpecializer where MachO == MachOFile { + /// Specializes the request's type offline. + /// + /// An argument stands for a type node: a `.candidate` for its name, a + /// `.boundGeneric` for the inner type specialized the same way, and a + /// `.metatype` / `.metadata` / `.specialized` for the name this process's + /// runtime gives it — the host's type, read without calling anything in + /// the target image. + /// + /// Throws what the runtime path throws for the same mistakes: the static + /// validation's errors and `staticPreflight`'s as `specializationFailed`, + /// a generic `.candidate` as `candidateRequiresNestedSpecialization`. A + /// requirement offline evidence cannot settle is not an error; ask + /// `staticPreflight` for the warnings. + public func specialize( + _ request: SpecializationRequest, + with selection: SpecializationSelection + ) throws -> StaticSpecializationResult { + try internalStaticSpecialize(request, with: selection, depth: 0) + } + + /// The offline counterpart of `runtimePreflight(selection:for:)`: checks + /// the selection against the type's requirements with the evidence a file + /// carries. + /// + /// Two outcomes per requirement, because offline evidence is incomplete: + /// + /// - **An error** when the requirement is provably violated: an + /// `AnyObject` parameter given a struct or an enum; a class known to + /// the indexer outside the required base class's subtree; a same-type + /// requirement whose two sides resolve to different types. + /// - **A warning** when it cannot be proved either way: a conformance the + /// indexed images do not record (it may be conditional, declared in an + /// image the indexer does not hold, or synthesized by the runtime); a + /// member of an associated type no witness record projects; a base + /// class the indexer knows no hierarchy for. + /// + /// Arguments of `.boundGeneric` are specialized and checked in turn, their + /// diagnostics named by dotted parameter path. + public func staticPreflight( + selection: SpecializationSelection, + for request: SpecializationRequest + ) -> SpecializationValidation { + let builder = SpecializationValidation.builder() + let resolution = resolveStaticArguments(for: request, with: selection, parameterPathPrefix: "", depth: 0) + resolution.errors.forEach { builder.addError($0) } + resolution.warnings.forEach { builder.addWarning($0) } + checkStaticRequirements(of: request, with: resolution, parameterPathPrefix: "", into: builder) + return builder.build() + } +} + +// MARK: - Internals + +extension GenericSpecializer where MachO == MachOFile { + /// What each selected argument stands for, resolved once per + /// specialization: the requirement checks and the result both read it, + /// and a `.boundGeneric` argument is specialized exactly once per level. + struct StaticArgumentResolution { + struct ResolvedArgument { + /// The argument, `.type`-wrapped. + let node: Node + + /// The nominal type the argument instantiates, as the indexer + /// names it — what conformance and subclass lookups key on. + let nominalTypeName: TypeName? + + let innerResult: StaticSpecializationResult? + + /// The type itself when the host process supplied it: its kind + /// and superclass chain are then known exactly. + let hostMetatype: Any.Type? + } + + var arguments: [String: ResolvedArgument] = [:] + var errors: [SpecializationValidation.Error] = [] + var warnings: [SpecializationValidation.Warning] = [] + } + + func internalStaticSpecialize( + _ request: SpecializationRequest, + with selection: SpecializationSelection, + depth: Int + ) throws -> StaticSpecializationResult { + let staticValidation = internalValidate(selection: selection, for: request, parameterPathPrefix: "", depth: depth) + guard staticValidation.isValid else { + throw SpecializerError.specializationFailed(reason: staticValidation.errors.map(\.description).joined(separator: "; ")) + } + + // The runtime path's typed error for a generic candidate, raised + // before anything else as there: it needs `.boundGeneric`. + for parameter in request.parameters { + guard case .candidate(let candidate) = selection[parameter.name] else { continue } + try requireNonGenericCandidate(candidate) + } + + let resolution = resolveStaticArguments(for: request, with: selection, parameterPathPrefix: "", depth: depth) + let builder = SpecializationValidation.builder() + resolution.errors.forEach { builder.addError($0) } + checkStaticRequirements(of: request, with: resolution, parameterPathPrefix: "", into: builder) + let validation = builder.build() + guard validation.isValid else { + throw SpecializerError.specializationFailed(reason: validation.errors.map(\.description).joined(separator: "; ")) + } + + return try staticResult(for: request, with: selection, resolution: resolution) + } + + private func requireNonGenericCandidate(_ candidate: SpecializationRequest.Candidate) throws { + let (descriptor, candidateMachO) = try resolveCandidateDescriptor(candidate) + if let genericContext = try descriptor.typeContextDescriptor.genericContext(in: candidateMachO.context) { + throw SpecializerError.candidateRequiresNestedSpecialization( + candidate: candidate, + parameterCount: Int(genericContext.header.numParams) + ) + } + } + + /// The result for arguments that passed every check: the arguments of + /// every parameter — the fixed ones recovered from their same-type + /// requirements — and the instantiation's name. + private func staticResult( + for request: SpecializationRequest, + with selection: SpecializationSelection, + resolution: StaticArgumentResolution + ) throws -> StaticSpecializationResult { + var keyArguments: [Node] = [] + var resolvedArguments: [StaticSpecializationResult.ResolvedArgument] = [] + for parameter in request.parameters { + guard let argument = resolution.arguments[parameter.name] else { + throw SpecializerError.specializationFailed(reason: "Missing argument for \(parameter.name)") + } + keyArguments.append(argument.node) + resolvedArguments.append(.init(parameterName: parameter.name, argumentNode: argument.node, innerResult: argument.innerResult)) + } + + let instantiation: GenericInstantiation + do { + instantiation = try GenericInstantiation(of: request.typeDescriptor, keyArguments: keyArguments, in: machO) + } catch { + throw SpecializerError.specializationFailed(reason: "could not bind the type's parameters: \((error as? LocalizedError)?.errorDescription ?? "\(error)")") + } + let typeName = TypeName( + node: InternedNodeReferenceCache.shared.reference(interning: instantiation.typeNode, in: machO), + kind: request.typeDescriptor.kind + ) + return StaticSpecializationResult( + typeDescriptor: request.typeDescriptor, + typeName: typeName, + binding: instantiation.binding, + selection: selection, + resolvedArguments: resolvedArguments + ) + } + + // MARK: Argument resolution + + func resolveStaticArguments( + for request: SpecializationRequest, + with selection: SpecializationSelection, + parameterPathPrefix: String, + depth: Int + ) -> StaticArgumentResolution { + var resolution = StaticArgumentResolution() + for parameter in request.parameters { + guard let argument = selection[parameter.name] else { continue } + let parameterPath = Self.joinedPath(parameterPathPrefix, parameter.name) + switch argument { + case .candidate(let candidate): + resolution.arguments[parameter.name] = .init( + node: typeWrappedNode(candidate.typeName.node.materialize()), + nominalTypeName: candidate.typeName, + innerResult: nil, + hostMetatype: nil + ) + case .boundGeneric(let baseCandidate, let innerArguments): + let outcome = staticBoundGenericOutcome( + baseCandidate: baseCandidate, + innerArguments: innerArguments, + parameterPath: parameterPath, + depth: depth + ) + resolution.errors.append(contentsOf: outcome.errors) + resolution.warnings.append(contentsOf: outcome.warnings) + if let innerResult = outcome.result { + resolution.arguments[parameter.name] = .init( + node: innerResult.typeName.node.materialize(), + nominalTypeName: baseCandidate.typeName, + innerResult: innerResult, + hostMetatype: nil + ) + } + case .metatype(let type): + resolveHostArgument(type, parameterName: parameter.name, parameterPath: parameterPath, into: &resolution) + case .metadata(let metadata): + do { + resolveHostArgument(unsafeBitCast(try metadata.asPointer, to: Any.Type.self), parameterName: parameter.name, parameterPath: parameterPath, into: &resolution) + } catch { + resolution.errors.append(.metadataResolutionFailed(parameterName: parameterPath, reason: "\(error)")) + } + case .specialized(let result): + do { + resolveHostArgument(unsafeBitCast(try result.metadata().asPointer, to: Any.Type.self), parameterName: parameter.name, parameterPath: parameterPath, into: &resolution) + } catch { + resolution.errors.append(.metadataResolutionFailed(parameterName: parameterPath, reason: "\(error)")) + } + } + } + return resolution + } + + /// A type the host process supplied, named the way this process's runtime + /// names it — the source the runtime path's own headers and field types + /// are printed from, so both paths spell the argument alike. + private func resolveHostArgument(_ type: Any.Type, parameterName: String, parameterPath: String, into resolution: inout StaticArgumentResolution) { + guard let node = RuntimeTypeNameDemangling.node(forMetatype: type) else { + resolution.errors.append(.metadataResolutionFailed(parameterName: parameterPath, reason: "this process's runtime has no name for \(type)")) + return + } + let argumentNode = typeWrappedNode(node) + resolution.arguments[parameterName] = .init( + node: argumentNode, + nominalTypeName: unboundNominalTypeName(of: argumentNode), + innerResult: nil, + hostMetatype: type + ) + } + + /// Specializes a `.boundGeneric` argument with an inner specializer bound + /// to the candidate's image, collecting the inner diagnostics under the + /// argument's parameter path. Each level resolves its own arguments + /// once, so the work stays linear in the nesting depth. + private func staticBoundGenericOutcome( + baseCandidate: SpecializationRequest.Candidate, + innerArguments: [String: SpecializationSelection.Argument], + parameterPath: String, + depth: Int + ) -> (result: StaticSpecializationResult?, errors: [SpecializationValidation.Error], warnings: [SpecializationValidation.Warning]) { + if depth >= maxBindingDepth { + return (nil, [.metadataResolutionFailed(parameterName: parameterPath, reason: "binding depth exceeded (maxBindingDepth = \(maxBindingDepth))")], []) + } + let inner: (descriptor: TypeContextDescriptorWrapper, specializer: GenericSpecializer) + do { + inner = try makeInnerContext(for: baseCandidate) + } catch { + return (nil, [.metadataResolutionFailed(parameterName: parameterPath, reason: "\(error)")], []) + } + let innerRequest: SpecializationRequest + do { + innerRequest = try inner.specializer.makeRequest(for: inner.descriptor) + } catch { + return (nil, [.metadataResolutionFailed(parameterName: parameterPath, reason: "could not build inner request: \(error)")], []) + } + + let innerSelection = SpecializationSelection(arguments: innerArguments) + let innerValidation = inner.specializer.internalValidate( + selection: innerSelection, + for: innerRequest, + parameterPathPrefix: parameterPath, + depth: depth + 1 + ) + var errors = innerValidation.errors + var warnings = innerValidation.warnings + for innerParameter in innerRequest.parameters { + guard case .candidate(let candidate) = innerSelection[innerParameter.name] else { continue } + do { + try inner.specializer.requireNonGenericCandidate(candidate) + } catch { + errors.append(.metadataResolutionFailed( + parameterName: Self.joinedPath(parameterPath, innerParameter.name), + reason: (error as? LocalizedError)?.errorDescription ?? "\(error)" + )) + } + } + + let innerResolution = inner.specializer.resolveStaticArguments( + for: innerRequest, + with: innerSelection, + parameterPathPrefix: parameterPath, + depth: depth + 1 + ) + errors.append(contentsOf: innerResolution.errors) + warnings.append(contentsOf: innerResolution.warnings) + let checksBuilder = SpecializationValidation.builder() + inner.specializer.checkStaticRequirements(of: innerRequest, with: innerResolution, parameterPathPrefix: parameterPath, into: checksBuilder) + let checks = checksBuilder.build() + errors.append(contentsOf: checks.errors) + warnings.append(contentsOf: checks.warnings) + guard errors.isEmpty else { return (nil, errors, warnings) } + + do { + return (try inner.specializer.staticResult(for: innerRequest, with: innerSelection, resolution: innerResolution), [], warnings) + } catch { + return (nil, [.metadataResolutionFailed(parameterName: parameterPath, reason: (error as? LocalizedError)?.errorDescription ?? "\(error)")], warnings) + } + } + + // MARK: Requirement checks + + /// Checks every requirement of the type's generic signature whose subject + /// is rooted in a selected parameter, against what offline evidence can + /// prove. See `staticPreflight(selection:for:)` for which outcome is an + /// error and which a warning. + func checkStaticRequirements( + of request: SpecializationRequest, + with resolution: StaticArgumentResolution, + parameterPathPrefix: String, + into builder: SpecializationValidation.Builder + ) { + guard let genericContext = (try? request.typeDescriptor.genericContext(in: machO.context)) ?? nil else { return } + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(request.typeDescriptor), in: machO.context) + let binding = partialBinding(of: resolution, depthLayout: depthLayout) + + for requirement in Self.mergedRequirements(from: genericContext) { + let flags = requirement.layout.flags + switch flags.kind { + case .protocol: + // Marker and Objective-C protocols take no witness table and + // are not checked, as on the runtime path. + guard flags.contains(.hasKeyArgument) else { continue } + case .layout, .baseClass, .sameType: + break + default: + continue + } + guard let subjectNode = try? SymbolicDemangler.demangleType(for: requirement.paramMangledName(in: machO.context), in: machO.context), + let rootParameterName = Self.directGenericParamName(of: subjectNode) ?? Self.extractAssociatedPath(of: subjectNode)?.baseParamName, + // A parameter that takes no argument is fixed by the very + // requirement read here; one left unselected is `validate`'s + // error, one that failed to resolve is reported already. + let rootArgument = resolution.arguments[rootParameterName] + else { continue } + + let isDirectParameter = Self.directGenericParamName(of: subjectNode) != nil + // A member is named by its access path, `A.Element` — the + // spelling of `AssociatedTypeRequirement.fullPath`, which is how + // the request lists it. + let memberPath = Self.extractAssociatedPath(of: subjectNode).map { ([$0.baseParamName] + $0.steps.map(\.name)).joined(separator: ".") } + let subject = StaticRequirementSubject( + path: Self.joinedPath(parameterPathPrefix, isDirectParameter ? rootParameterName : (memberPath ?? displayName(of: subjectNode))), + type: DependentMemberProjection.projectingConcreteMembers(in: binding.substituting(in: subjectNode), in: machO), + nominalTypeName: isDirectParameter ? rootArgument.nominalTypeName : nil, + hostMetatype: isDirectParameter ? rootArgument.hostMetatype : nil + ) + + switch flags.kind { + case .protocol: + checkConformance(of: subject, to: requirement, into: builder) + case .layout: + checkClassLayout(of: subject, into: builder) + case .baseClass: + checkBaseClass(of: subject, requirement: requirement, binding: binding, into: builder) + case .sameType: + checkSameType(of: subject, requirement: requirement, binding: binding, into: builder) + default: + break + } + } + } + + /// A requirement's subject with the arguments substituted. + private struct StaticRequirementSubject { + /// The parameter path diagnostics name: the parameter, or the member + /// (`A.Element`). + let path: String + /// The subject's type, its members projected where a record allows. + let type: Node + let nominalTypeName: TypeName? + let hostMetatype: Any.Type? + + var isResolved: Bool { + !containsDependentReference(type) + } + + var display: String { + displayName(of: type) + } + } + + private func checkConformance(of subject: StaticRequirementSubject, to requirement: GenericRequirementDescriptor, into builder: SpecializationValidation.Builder) { + guard let builtRequirement = try? buildRequirement(from: requirement), case .protocol(let info) = builtRequirement else { return } + let protocolName = info.protocolName + guard subject.isResolved, let typeName = subject.nominalTypeName ?? unboundNominalTypeName(of: subject.type) else { + builder.addWarning(.conformanceCheckFailed( + parameterName: subject.path, + protocolName: protocolName.name, + reason: "offline: \(subject.display) is not a nominal type the indexed images could describe" + )) + return + } + guard !conformanceProvider.doesType(typeName, conformTo: protocolName) else { return } + builder.addWarning(.conformanceCheckFailed( + parameterName: subject.path, + protocolName: protocolName.name, + reason: "offline: the indexed images record no conformance of \(subject.display) to \(protocolName.name); a conformance in an image the indexer does not hold, a conditional one, or one the runtime synthesizes cannot be checked without the runtime" + )) + } + + private func checkClassLayout(of subject: StaticRequirementSubject, into builder: SpecializationValidation.Builder) { + if let hostMetatype = subject.hostMetatype { + guard let kind = try? Metadata.createInProcess(hostMetatype).kind else { return } + if !(kind == .class || kind == .objcClassWrapper || kind == .foreignClass) { + builder.addError(.layoutRequirementNotSatisfied(parameterName: subject.path, expectedLayout: .class, actualType: subject.display)) + } + return + } + guard subject.isResolved else { + builder.addWarning(.conformanceCheckFailed( + parameterName: subject.path, + protocolName: "AnyObject", + reason: "offline: \(subject.display) could not be resolved to a concrete type" + )) + return + } + if Self.isValueType(subject.type) { + builder.addError(.layoutRequirementNotSatisfied(parameterName: subject.path, expectedLayout: .class, actualType: subject.display)) + } + } + + private func checkBaseClass(of subject: StaticRequirementSubject, requirement: GenericRequirementDescriptor, binding: GenericArgumentBinding, into builder: SpecializationValidation.Builder) { + guard let expectedNode = try? SymbolicDemangler.demangleType(for: requirement.type(in: machO.context), in: machO.context) else { return } + let expectedType = DependentMemberProjection.projectingConcreteMembers(in: binding.substituting(in: expectedNode), in: machO) + let expectedDisplay = displayName(of: expectedType) + guard let expectedClassName = unboundNominalTypeName(of: expectedType, kind: .class) else { + builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: \(expectedDisplay) is not a class the indexed images could describe")) + return + } + + if let hostMetatype = subject.hostMetatype { + // The host's own class: its superclass chain is complete. + if Self.hostClassChainNames(of: hostMetatype).contains(expectedClassName.name) { return } + builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) + return + } + guard subject.isResolved, let actualTypeName = subject.nominalTypeName ?? unboundNominalTypeName(of: subject.type) else { + builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: \(subject.display) could not be resolved to a concrete type")) + return + } + if Self.isValueType(subject.type) { + builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) + return + } + let subtree = conformanceProvider.subclasses(of: expectedClassName) + guard !subtree.isEmpty else { + builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: the indexed images describe no class hierarchy under \(expectedDisplay)")) + return + } + if subtree.contains(where: { $0.name == actualTypeName.name }) { return } + if conformanceProvider.typeDefinition(for: actualTypeName) != nil { + builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) + } else { + builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: \(subject.display) is in no indexed image, so its superclass chain cannot be read")) + } + } + + private func checkSameType(of subject: StaticRequirementSubject, requirement: GenericRequirementDescriptor, binding: GenericArgumentBinding, into builder: SpecializationValidation.Builder) { + guard let expectedNode = try? SymbolicDemangler.demangleType(for: requirement.type(in: machO.context), in: machO.context) else { return } + let expectedType = DependentMemberProjection.projectingConcreteMembers(in: binding.substituting(in: expectedNode), in: machO) + guard subject.isResolved, !containsDependentReference(expectedType) else { + builder.addWarning(.sameTypeRequirementResolutionSkipped( + parameterName: subject.path, + reason: "offline: \(subject.display) == \(displayName(of: expectedType)) could not be resolved to two concrete types" + )) + return + } + if unwrappedTypeNode(subject.type) != unwrappedTypeNode(expectedType) { + builder.addError(.sameTypeRequirementNotSatisfied(parameterName: subject.path, expectedType: displayName(of: expectedType), actualType: subject.display)) + } + } + + // MARK: Helpers + + /// The arguments resolved so far by `(depth, index)`, every parameter + /// without one standing for itself. + private func partialBinding(of resolution: StaticArgumentResolution, depthLayout: GenericParameterDepthLayout) -> GenericArgumentBinding { + let arguments = (0 ..< depthLayout.parameterCount).map { flatIndex -> Node in + guard let position = depthLayout.position(ofParameterAt: flatIndex) else { + return Node.createTransient(kind: .type, child: .createTransient(kind: .errorType)) + } + let parameterName = genericParameterName(depth: UInt64(position.depth), index: UInt64(position.index)) + if let argument = resolution.arguments[parameterName] { + return argument.node + } + return Node.createTransient(kind: .type, child: Node.createTransient(kind: .dependentGenericParamType, children: [ + .createTransient(kind: .index, index: UInt64(position.depth)), + .createTransient(kind: .index, index: UInt64(position.index)), + ])) + } + return GenericArgumentBinding(argumentsByDepth: depthLayout.grouped(arguments) ?? []) + } + + /// The nominal type a type node instantiates, unbound and named the way + /// the indexer names a definition: `Swift.Array` for `[Swift.Int]`, + /// `Outer.Inner` for `Outer.Inner`. + private func unboundNominalTypeName(of typeNode: Node, kind: TypeKind? = nil) -> TypeName? { + guard let nominal = Self.unboundNominal(of: unwrappedTypeNode(typeNode)) else { return nil } + let nominalKind: TypeKind + switch nominal.kind { + case .structure: nominalKind = .struct + case .enum: nominalKind = .enum + case .class: nominalKind = .class + case .typeAlias, .otherNominalType: nominalKind = kind ?? .struct + default: return nil + } + return TypeName( + node: InternedNodeReferenceCache.shared.reference(interning: Node.createTransient(kind: .type, child: nominal), in: machO), + kind: kind ?? nominalKind + ) + } + + private static func unboundNominal(of node: Node) -> Node? { + switch node.kind { + case .boundGenericStructure, .boundGenericEnum, .boundGenericClass, .boundGenericOtherNominalType, .boundGenericTypeAlias: + guard let unboundType = node.firstChild else { return nil } + return unboundNominal(of: unwrappedTypeNode(unboundType)) + case .structure, .enum, .class, .typeAlias, .otherNominalType: + guard node.children.count >= 2, let context = node.firstChild else { return node } + let unboundContext = unboundNominal(of: context) ?? context + guard unboundContext !== context else { return node } + return Node.createTransient(kind: node.kind, children: [unboundContext] + node.children.dropFirst()) + case .extension: + // `Extension(, , ?)`. + guard node.children.count >= 2, let extendedType = unboundNominal(of: unwrappedTypeNode(node.children[1])) else { return node } + var children = Array(node.children) + children[1] = extendedType + return Node.createTransient(kind: .extension, children: children) + default: + return nil + } + } + + private static func isValueType(_ typeNode: Node) -> Bool { + switch unwrappedTypeNode(typeNode).kind { + case .structure, .boundGenericStructure, .enum, .boundGenericEnum, .tuple: + return true + default: + return false + } + } + + /// The names of the host class and every ancestor, as the indexer names + /// a class. + private static func hostClassChainNames(of type: Any.Type) -> Set { + var names: Set = [] + #if canImport(ObjectiveC) + var currentClass: AnyClass? = type as? AnyClass + while let ancestorClass = currentClass { + if let node = RuntimeTypeNameDemangling.node(forMetatype: ancestorClass), let nominal = unboundNominal(of: unwrappedTypeNode(node)) { + names.insert(Node.createTransient(kind: .type, child: nominal).print(using: .interfaceTypeBuilderOnly)) + } + currentClass = class_getSuperclass(ancestorClass) + } + #endif + return names + } +} + +/// How a diagnostic spells a type: the way the interface prints it. +private func displayName(of typeNode: Node) -> String { + typeNode.print(using: .interface) +} + +private func unwrappedTypeNode(_ node: Node) -> Node { + node.kind == .type ? (node.firstChild ?? node) : node +} + +private func typeWrappedNode(_ node: Node) -> Node { + node.kind == .type ? node : Node.createTransient(kind: .type, child: node) +} + +private func containsDependentReference(_ node: Node) -> Bool { + switch node.kind { + case .dependentGenericParamType, .dependentMemberType: + return true + default: + return node.children.contains(where: containsDependentReference) + } +} diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift index 3d74e6336..738700c98 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift @@ -147,33 +147,13 @@ extension GenericSpecializer { /// `flags.contains(.hasKeyArgument)` guard in /// `resolveAssociatedTypeWitnesses`), so merging conditional records here /// is free of side effects on PWT counts. - private static func mergedRequirements( + static func mergedRequirements( from genericContext: GenericContext ) -> [GenericRequirementDescriptor] { genericContext.requirements + genericContext.conditionalInvertibleProtocolsRequirements } - /// Per-level "newly introduced" parameter counts. - /// - /// `parentParameters[i]` stores the *cumulative* count visible at depth - /// `i` (Swift emits the full canonical parameter list at every nested - /// scope). Differencing successive entries yields the count of - /// parameters added at each depth; `currentParameters` already contains - /// only the new entries at the innermost scope. - private static func perLevelNewParameterCounts( - of genericContext: GenericContext - ) -> [Int] { - var counts: [Int] = [] - var previous = 0 - for parentCumulative in genericContext.parentParameters { - counts.append(parentCumulative.count - previous) - previous = parentCumulative.count - } - counts.append(genericContext.currentParameters.count) - return counts - } - /// Pick out the `~Copyable` / `~Escapable` declaration for the generic /// parameter at the given flat ordinal, unioning if multiple /// `invertedProtocols` requirements target the same parameter. @@ -207,10 +187,11 @@ extension GenericSpecializer { /// Build parameter list from generic context. /// - /// Walks the cumulative `parameters` array level by level using the - /// per-depth "newly introduced" counts, so each parameter receives the - /// `(depth, indexInLevel)` pair that matches the demangler's canonical - /// names (`A`, `B`, `A1`, `B1`, `A2`, …). The flat ordinal of each + /// Walks the cumulative `parameters` array, placing each parameter at the + /// `(depth, index)` its `GenericParameterDepthLayout` gives — the + /// coordinates the demangler names it by (`A`, `B`, `A1`, `B1`, `A2`, …) + /// in the requirements and field records, so the requirements collected + /// by name below are this parameter's. The flat ordinal of each /// parameter — the value Swift writes into `InvertedProtocols.genericParamIndex` /// — equals the offset into the cumulative array. private func buildParameters( @@ -221,67 +202,61 @@ extension GenericSpecializer { var parameters: [SpecializationRequest.Parameter] = [] let cumulativeParameters = genericContext.parameters - let perLevelNewCounts = Self.perLevelNewParameterCounts(of: genericContext) + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(type), in: machO.context) let mergedRequirements = Self.mergedRequirements(from: genericContext) - var paramOffset = 0 - for (depth, newCount) in perLevelNewCounts.enumerated() { - for indexInLevel in 0.. ProtocolName? in - if case .protocol(let info) = requirement { - return info.protocolName - } - return nil + // Find candidate types that satisfy all protocol requirements + let protocolRequirements = requirements.compactMap { requirement -> ProtocolName? in + if case .protocol(let info) = requirement { + return info.protocolName } + return nil + } - // Pull the baseClass requirement (at most one per GP — Swift - // does not allow more than one inheritance constraint) and - // turn its demangled RHS into a `TypeName` so the provider - // can return base-class + subclass list. sameType is - // intentionally *not* converted into a candidate filter: - // its candidate set is genuinely user-determined and can - // span any type, the validate / preflight pass enforces - // consistency. - let baseClassConstraint = Self.baseClassConstraintTypeName(in: requirements) - - let candidates = findCandidates( - satisfying: protocolRequirements, - boundedBy: baseClassConstraint, - options: candidateOptions - ) + // Pull the baseClass requirement (at most one per GP — Swift + // does not allow more than one inheritance constraint) and + // turn its demangled RHS into a `TypeName` so the provider + // can return base-class + subclass list. sameType is + // intentionally *not* converted into a candidate filter: + // its candidate set is genuinely user-determined and can + // span any type, the validate / preflight pass enforces + // consistency. + let baseClassConstraint = Self.baseClassConstraintTypeName(in: requirements) + + let candidates = findCandidates( + satisfying: protocolRequirements, + boundedBy: baseClassConstraint, + options: candidateOptions + ) - let invertibleProtocols = Self.collectInvertibleProtocols( - flatIndex: flatIndex, - in: genericContext - ) + let invertibleProtocols = Self.collectInvertibleProtocols( + flatIndex: flatIndex, + in: genericContext + ) - parameters.append(SpecializationRequest.Parameter( - name: paramName, - index: indexInLevel, - depth: depth, - requirements: requirements, - candidates: candidates, - invertibleProtocols: invertibleProtocols - )) - } - paramOffset += newCount + parameters.append(SpecializationRequest.Parameter( + name: paramName, + index: position.index, + depth: position.depth, + requirements: requirements, + candidates: candidates, + invertibleProtocols: invertibleProtocols + )) } return parameters @@ -404,24 +379,34 @@ extension GenericSpecializer { } /// Build a requirement from a requirement descriptor - private func buildRequirement(from genericRequirement: GenericRequirementDescriptor) throws -> SpecializationRequest.Requirement? { + func buildRequirement(from genericRequirement: GenericRequirementDescriptor) throws -> SpecializationRequest.Requirement? { let flags = genericRequirement.layout.flags switch flags.kind { case .protocol: let resolvedContent = try genericRequirement.resolvedContent(in: machO.context) - guard case .protocol(let protocolRef) = resolvedContent, - let resolved = protocolRef.resolved else { + guard case .protocol(let protocolRef) = resolvedContent else { return nil } // Try to get protocol name let protocolName: ProtocolName - if let swiftProto = resolved.swift { + switch protocolRef { + case .element(let resolved): + guard let swiftProto = resolved.swift else { return nil } let proto = try MachOSwiftSection.`Protocol`(descriptor: swiftProto, in: machO.context) protocolName = try proto.protocolName(in: machO.context) - } else { - return nil + case .symbol(let symbol): + // A protocol another image declares, read from a file: the + // reference lands on the bind that the loader would resolve + // (`$sSHMp` for `Hashable`), which names the protocol. Dropping + // it left an offline request with no requirement at all — every + // type a candidate, no witness table slot accounted for. + guard let protocolNode = try SymbolicDemangler.demangleType(for: symbol, in: machO.context), + protocolNode.kind == .type, + protocolNode.firstChild?.kind == .protocol + else { return nil } + protocolName = ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: protocolNode, in: machO.context)) } return .protocol(SpecializationRequest.ProtocolRequirementInfo( diff --git a/Sources/Declaration/SwiftSpecialization/StaticSpecializationResult.swift b/Sources/Declaration/SwiftSpecialization/StaticSpecializationResult.swift new file mode 100644 index 000000000..4c3c6144c --- /dev/null +++ b/Sources/Declaration/SwiftSpecialization/StaticSpecializationResult.swift @@ -0,0 +1,77 @@ +import Foundation +import Demangling +import MachOSwiftSection +import SwiftDeclaration +@_spi(Internals) import SwiftInspection + +/// The result of specializing a generic type offline — on a `MachOFile`, +/// without the runtime (evolution proposal `offline-generic-specialization`). +/// +/// `SpecializationResult` carries the metadata the type's accessor returned; +/// offline there is none, so this carries what the metadata would have been +/// read for: the instantiation's name and the argument of every generic +/// parameter. `TypeDefinition.specialize(with:in:)` turns it into a +/// specialized definition, which the interface printer renders with a bound +/// header, substituted field types, and layout comments the static layout +/// engine computes for these arguments. +public struct StaticSpecializationResult: Sendable { + /// The generic type that was specialized. + public let typeDescriptor: TypeContextDescriptorWrapper + + /// The instantiation's name, shaped like the runtime's name for the same + /// instantiation: `Outer.Inner`. + public let typeName: TypeName + + /// The argument of every parameter of the type's generic context — the + /// selected ones, and those a same-type requirement fixes — by depth. + public let binding: GenericArgumentBinding + + /// The selection the specialization was made with, so the nested types + /// that only inherit these parameters can be specialized with it too. + public let selection: SpecializationSelection + + /// One entry per parameter of the request, in request order. + public let resolvedArguments: [ResolvedArgument] + + public init( + typeDescriptor: TypeContextDescriptorWrapper, + typeName: TypeName, + binding: GenericArgumentBinding, + selection: SpecializationSelection, + resolvedArguments: [ResolvedArgument] + ) { + self.typeDescriptor = typeDescriptor + self.typeName = typeName + self.binding = binding + self.selection = selection + self.resolvedArguments = resolvedArguments + } + + /// The resolved argument for a parameter. + public func argument(for parameterName: String) -> ResolvedArgument? { + resolvedArguments.first { $0.parameterName == parameterName } + } +} + +// MARK: - ResolvedArgument + +extension StaticSpecializationResult { + /// The type a parameter was bound to. + public struct ResolvedArgument: Sendable { + /// The parameter's name (`A`, `B`, `A1`, …). + public let parameterName: String + + /// The argument as a `.type`-wrapped type node. + public let argumentNode: Node + + /// The inner specialization when the argument was + /// `Argument.boundGeneric`, so a caller can walk the binding tree. + public let innerResult: StaticSpecializationResult? + + public init(parameterName: String, argumentNode: Node, innerResult: StaticSpecializationResult? = nil) { + self.parameterName = parameterName + self.argumentNode = argumentNode + self.innerResult = innerResult + } + } +} diff --git a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift index 01e88ed8e..c7730532d 100644 --- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift @@ -207,18 +207,32 @@ extension TypeDefinition { // Compute the final typeName up-front so it can flow through the // designated init: either the unbound form (`Box`) when no type - // arguments are supplied, or the bound form (`Box`) produced by - // `boundGenericTypeName(...)`. The latter makes the specialized - // definition print as `Box` rather than the placeholder - // `Box`, and gives it a unique mangled name per specialization - // (via `mangleAsString(typeName.node)`). + // arguments are supplied, or the instantiation's name (`Box`). + // The latter makes the specialized definition print as `Box` + // rather than the placeholder `Box`, and gives it a unique mangled + // name per specialization (via `mangleAsString(typeName.node)`). + // + // The instantiation's name hangs each argument on the level that + // declares its parameter — `Outer.Inner`, the runtime's + // shape and the one an offline specialization of the same type gets. + // `boundGenericTypeName` put every argument on the innermost level + // (`Outer.Inner`, and `Outer.Middle` for a nested + // type that declares none); it remains the fallback for arguments + // that do not match the type's key parameters. let unboundTypeName = try materializedTypeContext.typeName(in: machO.context) let finalTypeName: TypeName if let typeArgumentNodes, !typeArgumentNodes.isEmpty { - finalTypeName = Self.boundGenericTypeName( - unboundTypeName: unboundTypeName, - typeArgumentNodes: typeArgumentNodes - ) + if let instantiation = try? GenericInstantiation(of: typeContextDescriptorWrapper, keyArguments: typeArgumentNodes, in: machO) { + finalTypeName = TypeName( + node: InternedNodeReferenceCache.shared.reference(interning: instantiation.typeNode, in: machO), + kind: unboundTypeName.kind + ) + } else { + finalTypeName = Self.boundGenericTypeName( + unboundTypeName: unboundTypeName, + typeArgumentNodes: typeArgumentNodes + ) + } } else { finalTypeName = unboundTypeName } @@ -424,6 +438,146 @@ extension TypeDefinition { } } + // MARK: - Offline specialization (evolution proposal `offline-generic-specialization`) + + /// Append a new specialized `TypeDefinition` for an offline + /// specialization of this definition — the `MachOFile` counterpart of + /// `specialize(with:typeArgumentNodes:in:)`. + /// + /// The result carries no metadata. The new definition takes the + /// instantiation's name from it, and its `staticSpecialization` — the + /// argument of every parameter — is what the printer renders the bound + /// header, the substituted field types and the layout comments from. + /// + /// Throws `SpecializationError.notGenericType` for a non-generic receiver + /// and `.descriptorMismatch` for a result made for another type. Like the + /// runtime overload, this specializes only the receiver; the deriving + /// overload below also derives its nested types. + @discardableResult + public func specialize( + with specializationResult: StaticSpecializationResult, + in machO: MachOFile + ) async throws -> TypeDefinition { + let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) + _specializedChildren.append(specialized) + return specialized + } + + /// Specialize the receiver offline **and** derive specialized nested + /// children for every member of `typeChildren` the result's selection can + /// bind — the offline counterpart of + /// `specialize(with:typeArgumentNodes:derivingNestedSpecializationsWith:selection:typeArgumentNodesByParameter:in:)`, + /// with the same contract: derived children land in the returned + /// definition's `typeChildren` only, a child that declares parameters of + /// its own or fails to specialize is dropped, and the recursion stops at + /// `nestedSpecializationDepthLimit`. The selection travels in the result, + /// and every name comes from the instantiation, so neither is passed. + @_spi(Support) + @discardableResult + public func specialize( + with specializationResult: StaticSpecializationResult, + derivingNestedSpecializationsWith specializer: GenericSpecializer, + in machO: MachOFile + ) async throws -> TypeDefinition { + let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) + specialized.typeChildren = await deriveNestedStaticallySpecializedTypeChildren( + using: specializer, + selection: specializationResult.selection, + in: machO, + depth: 0 + ) + for child in specialized.typeChildren { + child.parent = specialized + } + _specializedChildren.append(specialized) + return specialized + } + + private func makeStaticallySpecializedDefinition( + with specializationResult: StaticSpecializationResult, + in machO: MachOFile + ) throws -> TypeDefinition { + guard typeContextDescriptorWrapper.typeContextDescriptor.layout.flags.isGeneric else { + throw SpecializationError.notGenericType(typeName: typeName.name) + } + // Both descriptors were read from the same file, so their offsets are + // directly comparable. + let expectedDescriptorOffset = typeContextDescriptorWrapper.typeContextDescriptor.offset + let actualDescriptorOffset = specializationResult.typeDescriptor.typeContextDescriptor.offset + guard expectedDescriptorOffset == actualDescriptorOffset else { + throw SpecializationError.descriptorMismatch( + typeName: typeName.name, + expectedOffset: expectedDescriptorOffset, + actualOffset: actualDescriptorOffset + ) + } + + // This specialize operation's single wrapper materialization + // (proposal 0002), released when this function returns. + let materializedTypeContext = try materializedTypeContext(in: machO.context) + let specialized = TypeDefinition( + type: materializedTypeContext, + typeName: specializationResult.typeName, + isSpecialized: true, + exportStatus: exportStatus + ) + specialized.staticSpecialization = specializationResult.binding + return specialized + } + + private func deriveNestedStaticallySpecializedTypeChildren( + using specializer: GenericSpecializer, + selection: SpecializationSelection, + in machO: MachOFile, + depth: Int + ) async -> [TypeDefinition] { + guard depth < Self.nestedSpecializationDepthLimit else { + #log(.info, "deriveNestedStaticallySpecializedTypeChildren reached nested specialization depth limit \(Self.nestedSpecializationDepthLimit, privacy: .public) — truncating subtree at \(self.typeName.name, privacy: .public)") + return [] + } + + var derivedChildren: [TypeDefinition] = [] + for child in typeChildren { + guard child.typeContextDescriptorWrapper.typeContextDescriptor.layout.flags.isGeneric else { + continue + } + // Best-effort, as on the runtime path: a child that fails to + // specialize is dropped and its siblings still arrive. + do { + let request = try specializer.makeRequest(for: child.typeContextDescriptorWrapper) + var childArguments: [String: SpecializationSelection.Argument] = [:] + var hasCompleteBinding = true + for parameter in request.parameters { + guard let argument = selection.arguments[parameter.name] else { + hasCompleteBinding = false + break + } + childArguments[parameter.name] = argument + } + guard hasCompleteBinding else { + continue + } + + let childSelection = SpecializationSelection(arguments: childArguments) + let childResult = try specializer.specialize(request, with: childSelection) + let childSpecialized = try child.makeStaticallySpecializedDefinition(with: childResult, in: machO) + childSpecialized.typeChildren = await child.deriveNestedStaticallySpecializedTypeChildren( + using: specializer, + selection: childSelection, + in: machO, + depth: depth + 1 + ) + for grandchild in childSpecialized.typeChildren { + grandchild.parent = childSpecialized + } + derivedChildren.append(childSpecialized) + } catch { + continue + } + } + return derivedChildren + } + /// Errors raised by `specialize(with:typeArgumentNodes:in:)` when the /// supplied `SpecializationResult` cannot be reconciled with the receiver. public enum SpecializationError: LocalizedError { diff --git a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift index 40fde76a5..0390c8eaf 100644 --- a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift +++ b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift @@ -6,7 +6,7 @@ import MachODependencies import SwiftLayout import SwiftThunkAnalysis @_spi(Internals) import MachOCaches -import Demangling +@_spi(Internals) import Demangling /// The image universes the opaque rewriter projects members through /// (evolution proposal `opaque-reference-spelling-and-member-projection`), @@ -118,3 +118,26 @@ package enum DependentMemberProjection { ) } } + +// MARK: - Projecting every concrete member of a type + +extension DependentMemberProjection { + /// `node` with every dependent member whose base is concrete replaced by + /// the type its conformance's witness record names, through the universe + /// of `machO`'s dependency closure — see + /// ``ImageUniverse/projectingConcreteMembers(in:)``. `node` unchanged when + /// the reader is neither a file nor an in-process image, or the universe + /// cannot be built. + package static func projectingConcreteMembers(in node: Node, in machO: MachO) -> Node { + if let machOFile = machO as? MachOFile { + let registry = fileRegistries.storage(in: machOFile) { FileRegistry(root: $0) } ?? FileRegistry(root: machOFile) + guard let entry = registry.entry(for: searchPaths(for: machOFile)) else { return node } + return entry.withUniverse { $0.projectingConcreteMembers(in: node) } + } + if let machOImage = machO as? MachOImage { + guard let entry = imageEntries.storage(in: machOImage, buildUsing: { (try? ImageUniverse.dependencyClosure(root: $0)).map { Entry(universe: $0) } }) else { return node } + return entry.withUniverse { $0.projectingConcreteMembers(in: node) } + } + return node + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift index ecb1a76f8..b2c751dc2 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift @@ -32,11 +32,15 @@ package func genericValueName(depth: Int, index: Int) throws -> String { } extension TargetGenericContext { + /// - Parameter depthLayout: How this context's parameters split into + /// depths (`GenericParameterDepthLayout.make(for:ownedBy:in:)`), which + /// decides the depth each printed name carries — the one its fields and + /// requirements name it by. @SemanticStringBuilder - package func dumpGenericSignature(resolver: DemangleResolver, in context: some ReadingContext, isDumpCurrentLevelParams: Bool = true, isDumpCurrentLevelRequirements: Bool = true, @SemanticStringBuilder conformancesBuilder: () async throws -> SemanticString = { "" }) async throws -> SemanticString { + package func dumpGenericSignature(resolver: DemangleResolver, depthLayout: GenericParameterDepthLayout, in context: some ReadingContext, isDumpCurrentLevelParams: Bool = true, isDumpCurrentLevelRequirements: Bool = true, @SemanticStringBuilder conformancesBuilder: () async throws -> SemanticString = { "" }) async throws -> SemanticString { if (isDumpCurrentLevelParams ? currentParameters : parameters).count > 0 { Standard("<") - try await dumpGenericParameters(in: context, isDumpCurrentLevel: isDumpCurrentLevelParams) + try await dumpGenericParameters(depthLayout: depthLayout, in: context, isDumpCurrentLevel: isDumpCurrentLevelParams) Standard(">") } @@ -52,134 +56,61 @@ extension TargetGenericContext { } extension TargetGenericContext { + /// Prints the parameter names, `A, B, A1, …`: the context's own + /// parameters, or with `isDumpCurrentLevel` off every parameter in scope. + /// + /// A name spells its parameter's `(depth, index)`, and only + /// `depthLayout` knows the depth. The parent chain does not: a type that + /// declares no parameter is still a generic ancestor, and an extension + /// ancestor can span several depths — counting ancestors printed + /// `struct Inner` over a field the record names `A1`. @SemanticStringBuilder - package func dumpGenericParameters(in context: some ReadingContext, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { - if isDumpCurrentLevel { - var currentValueIndex = 0 - for (offset, parameter) in currentParameters.offsetEnumerated() { - if parameter.kind == .typePack { - Keyword(.each) - Space() - } else if parameter.kind == .value { - Keyword(.let) - Space() - } + package func dumpGenericParameters(depthLayout: GenericParameterDepthLayout, in context: some ReadingContext, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { + // The context's own parameters are the tail of the cumulative list, + // so the positions below are offsets into `parameters` either way. + let firstPrintedOffset = isDumpCurrentLevel ? parameters.count - currentParameters.count : 0 + let printedParameters = parameters[firstPrintedOffset...] + // `values` holds one descriptor per value parameter, in parameter + // order; the printed ones start after those of the skipped parameters. + var valueIndex = parameters[..` with `A` - // duplicated). Walk per-level "newly introduced" slices instead, - // mirroring the depth-aware visit order Swift's - // `forEachParam` produces. - let perLevelCounts = Self.dumpPerLevelNewParameterCounts( - parentParameters: parentParameters, - currentCount: currentParameters.count - ) - let perLevelValueCounts = Self.dumpPerLevelNewValueCounts( - parentValues: parentValues, - currentCount: currentValues.count - ) - var paramOffset = 0 - var valueOffset = 0 - var totalEmitted = 0 - let totalParameters = parameters.count - for (depthIndex, newCount) in perLevelCounts.enumerated() { - let valuesAtThisLevel = perLevelValueCounts[safe: depthIndex] ?? 0 - var currentValueIndexInLevel = 0 - for indexInLevel in 0.. [Int] { - var counts: [Int] = [] - var previous = 0 - for parentCumulative in parentParameters { - counts.append(parentCumulative.count - previous) - previous = parentCumulative.count - } - counts.append(currentCount) - return counts - } - - /// Same idea for value generics. - fileprivate static func dumpPerLevelNewValueCounts( - parentValues: [[GenericValueDescriptor]], - currentCount: Int - ) -> [Int] { - var counts: [Int] = [] - var previous = 0 - for parentCumulative in parentValues { - counts.append(parentCumulative.count - previous) - previous = parentCumulative.count - } - counts.append(currentCount) - return counts - } - @SemanticStringBuilder package func dumpGenericRequirements(resolver: DemangleResolver, in context: some ReadingContext, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { switch resolver { diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift index a5ec321bc..9834fbe38 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift @@ -335,17 +335,17 @@ extension Node { /// the declaration it belongs to (the interface printer's `some` /// expansion uses the same lookup), so a name this image does carry /// resolves here; one it does not is ``foreignOpaqueType(referencedBy:)``'s. - private func opaqueType(referencedBy reference: Node) throws -> OpaqueType? { + private func opaqueType(referencedBy reference: Node) throws -> ReadOpaqueType? { if reference.isKind(of: .opaqueTypeDescriptorSymbolicReference), let offset: Int = reference.index?.cast() { if machO is MachOImage, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { let opaqueTypeDescriptor: OpaqueTypeDescriptor = try absolutePointer.readWrapperElement() - return try OpaqueType(descriptor: opaqueTypeDescriptor, in: .inProcess) + return try ReadOpaqueType(OpaqueType(descriptor: opaqueTypeDescriptor, in: .inProcess), in: .inProcess) } - return try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: offset, in: machO.context), in: machO.context) + return try ReadOpaqueType(OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: offset, in: machO.context), in: machO.context), in: machO.context) } if reference.isKind(of: .opaqueReturnTypeOf), let memberNode = reference.firstChild, let descriptorSymbol = SymbolIndexStore.shared.opaqueTypeDescriptorSymbol(for: memberNode, in: machO) { - return try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: descriptorSymbol.offset, in: machO.context), in: machO.context) + return try ReadOpaqueType(OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: descriptorSymbol.offset, in: machO.context), in: machO.context), in: machO.context) } return nil } @@ -370,7 +370,7 @@ extension Node { /// interface, whose `printOpaqueType` prints only the node's argument /// list, printed the conformer itself as the witness (`typealias Body /// = SidebarListBody.CollectionViewBody`), a real, wrong type. - private func foreignOpaqueType(referencedBy reference: Node) throws -> (image: MachOFile, opaqueType: OpaqueType)? { + private func foreignOpaqueType(referencedBy reference: Node) throws -> (image: MachOFile, opaqueType: ReadOpaqueType)? { guard reference.isKind(of: .opaqueReturnTypeOf), let machOFile = machO as? MachOFile else { return nil } let descriptorSymbolNode = Node.create(kind: .global, children: [Node.create(kind: .opaqueTypeDescriptor, children: [reference.copy()])]) let descriptorSymbolName = try mangleAsString(descriptorSymbolNode) @@ -385,7 +385,7 @@ extension Node { let descriptorOffset = imageAddressSpace.offset(forAddress: descriptorAddress) else { return nil } let opaqueType = try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: descriptorOffset, in: location.image.context), in: location.image.context) - return (image: location.image, opaqueType: opaqueType) + return (image: location.image, opaqueType: ReadOpaqueType(opaqueType, in: location.image.context)) } /// What `node` — an `opaqueType` reference — expands to given the @@ -394,7 +394,8 @@ extension Node { /// the node's generic arguments substituted, nested opaque types /// expanded in turn. `nil` when the underlying type has no shape this /// rewriter substitutes. - fileprivate func expansion(of opaqueType: OpaqueType, forNode node: Node) -> Node? { + fileprivate func expansion(of readOpaqueType: ReadOpaqueType, forNode node: Node) -> Node? { + let opaqueType = readOpaqueType.opaqueType // The ordinal — the opaque type's own position among the // `some` results of the declaration that produced it — is // what indexes the underlying-type array. Measured on a @@ -422,7 +423,7 @@ extension Node { // The thunk's argument buffer is the opaque // descriptor's generic arguments, so its generic // context is what names an argument the thunk reads. - let ownerLayout = AccessorThunkOwnerLayout(genericContext: opaqueType.genericContext) + let ownerLayout = readOpaqueType.ownerLayout guard let underlyingTypeArgumentNode, let resolvedNode = underlyingTypeContent(of: underlyingTypeArgumentNode, ownerLayout: ownerLayout) else { return nil } @@ -677,3 +678,24 @@ extension Node { return OpaqueTypeResolution(node: node, conditionalCandidates: conditionalCandidates, projectedMembers: projectionLedger.projections) } } + +/// An opaque type descriptor read in some context, with the layout +/// of its generic arguments as an accessor thunk inside it reads +/// them. The layout's depths come from the descriptor's parent chain, +/// which must be walked in the context the descriptor was read in — +/// an in-process absolute address and an image offset are not +/// interchangeable — so it is computed where the descriptor is read. +fileprivate struct ReadOpaqueType { + let opaqueType: OpaqueType + let ownerLayout: AccessorThunkOwnerLayout + + init(_ opaqueType: OpaqueType, in context: some ReadingContext) { + self.opaqueType = opaqueType + if let genericContext = opaqueType.genericContext { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .opaqueType(opaqueType.descriptor), in: context) + self.ownerLayout = AccessorThunkOwnerLayout(genericContext: genericContext, depthLayout: depthLayout) + } else { + self.ownerLayout = AccessorThunkOwnerLayout(genericContext: nil as GenericContext?) + } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift b/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift index b7accd704..106c012a7 100644 --- a/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift +++ b/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift @@ -41,6 +41,10 @@ public struct FieldLayoutRenderState { public let configuration: DeclarationRenderConfiguration public let isGeneric: Bool public let staticAggregateFieldLayout: AggregateFieldLayout? + /// The arguments of an offline specialization (evolution proposal + /// `offline-generic-specialization`): the static path computes the + /// comments for this instantiation instead of the unbound type. + public let genericArgumentBinding: GenericArgumentBinding? /// The dumped type as an `Enum`, or `nil` for struct/class. public var enumValue: Enum? { @@ -76,9 +80,10 @@ public protocol FieldLayoutRenderable { static func makeStaticFieldLayoutProvider(machO: Self, resolution: StaticLayoutDependencyResolution) -> (any StaticFieldLayoutProvider)? /// Precompute (once per type, at renderer init) the static aggregate layout - /// the offline path reads field offsets / type layouts from. `nil` for the - /// runtime path or when no static provider was injected. - static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, machO: Self, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? + /// the offline path reads field offsets / type layouts from — of the + /// instantiation `genericArgumentBinding` makes, when one is given. `nil` + /// for the runtime path or when no static provider was injected. + static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, genericArgumentBinding: GenericArgumentBinding?, machO: Self, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? static func renderFieldOffsets(_ state: FieldLayoutRenderState, machO: Self) -> [Int]? @@ -126,6 +131,10 @@ package struct FieldLayoutRenderer { /// when no static provider was injected. package let staticAggregateFieldLayout: AggregateFieldLayout? + /// An offline specialization's arguments; see + /// `FieldLayoutRenderState.genericArgumentBinding`. + package let genericArgumentBinding: GenericArgumentBinding? + /// - Parameters: /// - providedMetadata: a caller-supplied (typically specialized) metadata /// to read field offsets / drive substitution from. @@ -136,10 +145,13 @@ package struct FieldLayoutRenderer { /// the model-driven printer wants. When `false` (the raw-descriptor dump /// path), a `nil` metadata stays `nil` so the bare dumper keeps its "no /// metadata context ⇒ no offsets" contract. - package init(type: TypeContextWrapper, metadata providedMetadata: MetadataWrapper?, machO: MachO, configuration: DeclarationRenderConfiguration, autoResolveAccessorMetadata: Bool = true) { + /// - genericArgumentBinding: an offline specialization's arguments, which + /// the static path computes the comments for. + package init(type: TypeContextWrapper, metadata providedMetadata: MetadataWrapper?, genericArgumentBinding: GenericArgumentBinding? = nil, machO: MachO, configuration: DeclarationRenderConfiguration, autoResolveAccessorMetadata: Bool = true) { self.type = type self.machO = machO self.configuration = configuration + self.genericArgumentBinding = genericArgumentBinding let isGeneric: Bool switch type { @@ -160,7 +172,7 @@ package struct FieldLayoutRenderer { self.metadata = try? FieldLayoutRenderer.resolveAccessorMetadata(for: type, in: machO) } - self.staticAggregateFieldLayout = MachO.precomputedStaticAggregateFieldLayout(for: type, machO: machO, configuration: configuration) + self.staticAggregateFieldLayout = MachO.precomputedStaticAggregateFieldLayout(for: type, genericArgumentBinding: genericArgumentBinding, machO: machO, configuration: configuration) } private static func resolveAccessorMetadata(for type: TypeContextWrapper, in machO: MachO) throws -> MetadataWrapper? { @@ -182,7 +194,7 @@ package struct FieldLayoutRenderer { /// The reader-independent state handed to the rendering witnesses. private var renderState: FieldLayoutRenderState { - FieldLayoutRenderState(type: type, metadata: metadata, configuration: configuration, isGeneric: isGeneric, staticAggregateFieldLayout: staticAggregateFieldLayout) + FieldLayoutRenderState(type: type, metadata: metadata, configuration: configuration, isGeneric: isGeneric, staticAggregateFieldLayout: staticAggregateFieldLayout, genericArgumentBinding: genericArgumentBinding) } // MARK: - Compile-time-dispatched entry points (forward to the reader's backend) diff --git a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift index 542f2fc80..3810f26b2 100644 --- a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift @@ -15,7 +15,7 @@ extension MachOImage: FieldLayoutRenderable { nil } - public static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, machO: MachOImage, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? { + public static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, genericArgumentBinding: GenericArgumentBinding?, machO: MachOImage, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? { // The runtime path reads offsets from materialized metadata, not from a // statically-precomputed aggregate. nil @@ -637,24 +637,40 @@ struct RuntimeFieldLayoutBackend { // MARK: - Enum layout (runtime) - /// The enum's own value-witness type layout. Resolved with the `machO` - /// context (matching the former `EnumDumper.typeLayout`): the enum metadata - /// came from `…resolve(in: machO.context)`, so its value-witness table must be read - /// back through the same reader — the in-process `valueWitnessTable(in: .inProcess)` - /// misinterprets that offset and segfaults. Used by single-payload layout. + /// The enum's own value-witness type layout. A non-generic enum's metadata + /// came from `…resolve(in: machO.context)` (matching the former + /// `EnumDumper.typeLayout`), so its value-witness table must be read back + /// through the same reader — the in-process `valueWitnessTable(in: .inProcess)` + /// misinterprets that offset and segfaults. A specialization's metadata + /// is an in-process address, read through `readingContext` the same way + /// `fieldOffsets` reads it. Used by single-payload layout. private var enumTypeLayout: TypeLayout? { - try? metadata?.valueWitnessTable(in: machO.context).typeLayout + try? metadata?.valueWitnessTable(in: readingContext).typeLayout } + /// A generic enum lays out per instantiation, so only a specialization — + /// a definition that carries the instantiation's metadata — has a + /// layout to show; the payload types then resolve through that metadata + /// (evolution proposal `offline-generic-specialization`, which gives the + /// offline path the same comments). var enumLayout: EnumLayoutCalculator.LayoutResult? { get async { guard configuration.producesContent(for: .printEnumLayout), let enumValue, - !enumValue.descriptor.isGeneric else { return nil } + !enumValue.descriptor.isGeneric || metadata != nil else { return nil } return try? await computeEnumLayout(enumValue, in: machO) } } + /// A payload case's type: substituted through the specialization's + /// metadata for a generic enum, the bare name otherwise. + private func payloadMetatype(for mangledTypeName: MangledName, in machOImage: MachOImage) throws -> Any.Type? { + if isGeneric { + return resolveFieldMetatype(for: mangledTypeName, in: machOImage) + } + return try RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, genericContext: nil, genericArguments: nil, in: machOImage) + } + private func computeEnumLayout(_ enumValue: Enum, in machOImage: MachOImage) async throws -> EnumLayoutCalculator.LayoutResult? { let payloadSize = try enumPayloadSize(enumValue.descriptor, in: machOImage) let numberOfPayloadCases = enumValue.numberOfPayloadCases @@ -809,7 +825,7 @@ struct RuntimeFieldLayoutBackend { } let mangledTypeName = try record.mangledTypeName(in: machOImage.context) guard !mangledTypeName.isEmpty else { continue } - guard let metatype = try RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, genericContext: nil, genericArguments: nil, in: machOImage) else { continue } + guard let metatype = try payloadMetatype(for: mangledTypeName, in: machOImage) else { continue } let typeLayout = try StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout payloadSize = max(payloadSize, typeLayout.size.cast()) } @@ -831,7 +847,7 @@ struct RuntimeFieldLayoutBackend { } let mangledTypeName = try record.mangledTypeName(in: machOImage.context) guard !mangledTypeName.isEmpty else { continue } - guard let metatype = try RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, genericContext: nil, genericArguments: nil, in: machOImage) else { continue } + guard let metatype = try payloadMetatype(for: mangledTypeName, in: machOImage) else { continue } let typeLayout = try StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout return typeLayout.extraInhabitantCount.cast() } diff --git a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift index 67e899882..fe7cae1c5 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift @@ -14,7 +14,7 @@ extension MachOFile: FieldLayoutRenderable { MachOFileStaticFieldLayoutProvider(machOFile: machO, resolution: resolution) } - public static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, machO: MachOFile, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? { + public static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, genericArgumentBinding: GenericArgumentBinding?, machO: MachOFile, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? { // Only when a layout-bearing flag is on and a provider was injected; // enums (no field-offset vector) compute their layout lazily instead. guard configuration.producesContent(for: .printFieldOffset) || configuration.producesContent(for: .printTypeLayout) || configuration.producesContent(for: .printExpandedFieldOffsets), @@ -30,6 +30,9 @@ extension MachOFile: FieldLayoutRenderable { case .enum: return nil } + if let genericArgumentBinding { + return provider.aggregateFieldLayout(forDescriptor: descriptorWrapper, genericArgumentBinding: genericArgumentBinding) + } return provider.aggregateFieldLayout(forDescriptor: descriptorWrapper) } @@ -75,6 +78,7 @@ struct StaticFieldLayoutBackend { private var configuration: DeclarationRenderConfiguration { state.configuration } private var enumValue: Enum? { state.enumValue } private var staticAggregateFieldLayout: AggregateFieldLayout? { state.staticAggregateFieldLayout } + private var genericArgumentBinding: GenericArgumentBinding? { state.genericArgumentBinding } // MARK: - Field offsets (struct / class) @@ -163,11 +167,20 @@ struct StaticFieldLayoutBackend { @SemanticStringBuilder private func expandedFieldOffsets(for mangledTypeName: MangledName, baseOffset: Int) -> SemanticString { if let provider = configuration.staticFieldLayoutProvider { - let tree = provider.nestedFieldOffsetTree( - forMangledTypeName: mangledTypeName, - baseOffset: baseOffset, - depthLimit: nestedFieldOffsetExpansionDepthLimit - ) + let tree = if let genericArgumentBinding { + provider.nestedFieldOffsetTree( + forMangledTypeName: mangledTypeName, + baseOffset: baseOffset, + depthLimit: nestedFieldOffsetExpansionDepthLimit, + genericArgumentBinding: genericArgumentBinding + ) + } else { + provider.nestedFieldOffsetTree( + forMangledTypeName: mangledTypeName, + baseOffset: baseOffset, + depthLimit: nestedFieldOffsetExpansionDepthLimit + ) + } renderNestedFieldOffsetTree(tree, ancestors: []) } } @@ -230,6 +243,9 @@ struct StaticFieldLayoutBackend { guard configuration.producesContent(for: .printEnumLayout), let enumValue, let provider = configuration.staticFieldLayoutProvider else { return nil } + if let genericArgumentBinding { + return provider.enumCaseLayoutResult(forDescriptor: .enum(enumValue.descriptor), genericArgumentBinding: genericArgumentBinding) + } return provider.enumCaseLayoutResult(forDescriptor: .enum(enumValue.descriptor)) } } @@ -238,6 +254,9 @@ struct StaticFieldLayoutBackend { /// context so a generic enum's parameter-typed payloads (`Element` under a /// class-bound constraint) still resolve. private func payloadTypeLayout(for mangledTypeName: MangledName, provider: any StaticFieldLayoutProvider) -> StaticTypeLayout? { + if let enumValue, let genericArgumentBinding { + return provider.typeLayout(forMangledTypeName: mangledTypeName, inContextOfDescriptor: .enum(enumValue.descriptor), genericArgumentBinding: genericArgumentBinding) + } if let enumValue { return provider.typeLayout(forMangledTypeName: mangledTypeName, inContextOfDescriptor: .enum(enumValue.descriptor)) } diff --git a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift index a58adbf80..6ad3b6c08 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift @@ -63,6 +63,46 @@ public protocol StaticFieldLayoutProvider: Sendable { /// The expanded nested-field-offset tree for a field type placed at /// `baseOffset`, descending up to `depthLimit` levels. func nestedFieldOffsetTree(forMangledTypeName mangledTypeName: MangledName, baseOffset: Int, depthLimit: Int) -> [NestedFieldOffset] + + // The same four queries for an instantiation a `GenericArgumentBinding` + // describes — an offline specialization's (evolution proposal + // `offline-generic-specialization`). Each has a default that answers + // nothing, so a provider written before them keeps compiling and + // degrades to no comment rather than to an unspecialized one. + + /// The per-field layout of the instantiation `binding` makes of a + /// struct/class descriptor. + func aggregateFieldLayout(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> AggregateFieldLayout? + + /// The whole-type layout of a payload type, lowered in the context of the + /// instantiation `binding` makes of `contextDescriptor`. + func typeLayout(forMangledTypeName mangledTypeName: MangledName, inContextOfDescriptor contextDescriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> StaticTypeLayout? + + /// The per-case projection layout of the instantiation `binding` makes of + /// an enum descriptor. + func enumCaseLayoutResult(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> EnumLayoutCalculator.LayoutResult? + + /// The expanded nested-field-offset tree for a field type of the + /// instantiation `binding` describes. + func nestedFieldOffsetTree(forMangledTypeName mangledTypeName: MangledName, baseOffset: Int, depthLimit: Int, genericArgumentBinding binding: GenericArgumentBinding) -> [NestedFieldOffset] +} + +extension StaticFieldLayoutProvider { + public func aggregateFieldLayout(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> AggregateFieldLayout? { + nil + } + + public func typeLayout(forMangledTypeName mangledTypeName: MangledName, inContextOfDescriptor contextDescriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> StaticTypeLayout? { + nil + } + + public func enumCaseLayoutResult(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> EnumLayoutCalculator.LayoutResult? { + nil + } + + public func nestedFieldOffsetTree(forMangledTypeName mangledTypeName: MangledName, baseOffset: Int, depthLimit: Int, genericArgumentBinding binding: GenericArgumentBinding) -> [NestedFieldOffset] { + [] + } } /// The MachOFile-backed provider, wrapping a `StaticLayoutCalculator`. @@ -126,4 +166,28 @@ public final class MachOFileStaticFieldLayoutProvider: StaticFieldLayoutProvider defer { lock.unlock() } return calculator.nestedFieldOffsetTree(forMangledTypeName: mangledTypeName, baseOffset: baseOffset, depthLimit: depthLimit) } + + public func aggregateFieldLayout(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> AggregateFieldLayout? { + lock.lock() + defer { lock.unlock() } + return try? calculator.fieldLayout(of: descriptor, genericArgumentBinding: binding) + } + + public func typeLayout(forMangledTypeName mangledTypeName: MangledName, inContextOfDescriptor contextDescriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> StaticTypeLayout? { + lock.lock() + defer { lock.unlock() } + return try? calculator.typeLayout(forMangledTypeName: mangledTypeName, inContextOfDescriptor: contextDescriptor, genericArgumentBinding: binding) + } + + public func enumCaseLayoutResult(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> EnumLayoutCalculator.LayoutResult? { + lock.lock() + defer { lock.unlock() } + return calculator.enumCaseLayoutResult(forDescriptor: descriptor, genericArgumentBinding: binding) + } + + public func nestedFieldOffsetTree(forMangledTypeName mangledTypeName: MangledName, baseOffset: Int, depthLimit: Int, genericArgumentBinding binding: GenericArgumentBinding) -> [NestedFieldOffset] { + lock.lock() + defer { lock.unlock() } + return calculator.nestedFieldOffsetTree(forMangledTypeName: mangledTypeName, baseOffset: baseOffset, depthLimit: depthLimit, genericArgumentBinding: binding) + } } diff --git a/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift b/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift new file mode 100644 index 000000000..483aba8ea --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift @@ -0,0 +1,25 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import SwiftInspection + +/// Binding-driven node substitution for a definition specialized offline +/// (evolution proposal `offline-generic-specialization`) — the counterpart of +/// `SpecializedMetadataNodeSubstitution`, which asks the runtime. +/// +/// Offline there is no metadata to resolve a field's type against, only the +/// arguments: they are substituted for the parameters, and a member of a +/// concrete type that leaves behind (`[Swift.Int].Element`) is projected +/// through the conformance records of the image's dependency closure — the +/// answer the runtime gives, read from the records the runtime reads it +/// from. A member no record answers keeps its spelling. +package enum StaticSpecializationNodeSubstitution { + /// `typeNode` — a field's or an enum payload's declared type — with + /// `binding`'s arguments substituted and concrete members projected. + package static func substitutedTypeNode( + of typeNode: Node, + binding: GenericArgumentBinding, + in machO: MachO + ) -> Node { + DependentMemberProjection.projectingConcreteMembers(in: binding.substituting(in: typeNode), in: machO) + } +} diff --git a/Sources/Output/SwiftDump/Dumper/ClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift index f4c5ae6fa..be06afd95 100644 --- a/Sources/Output/SwiftDump/Dumper/ClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift @@ -73,7 +73,8 @@ package struct ClassDumper: TypedDumper { // segment directly in that case. let isBound = boundDumpedMetatype() != nil if !isBound, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO.context) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(.class(dumped.descriptor)), in: machO.context) + try await genericContext.dumpGenericSignature(resolver: demangleResolver, depthLayout: depthLayout, in: machO.context) { superclass } } else { diff --git a/Sources/Output/SwiftDump/Dumper/EnumDumper.swift b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift index 547bf11be..611f1c200 100644 --- a/Sources/Output/SwiftDump/Dumper/EnumDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift @@ -54,7 +54,8 @@ package struct EnumDumper: TypedDumper { // matching reasoning). let isBound = boundDumpedMetatype() != nil if !isBound, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO.context) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(.enum(dumped.descriptor)), in: machO.context) + try await genericContext.dumpGenericSignature(resolver: demangleResolver, depthLayout: depthLayout, in: machO.context) { if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { invertibleProtocolSet.dumpInvertedProtocolsInheritance } diff --git a/Sources/Output/SwiftDump/Dumper/StructDumper.swift b/Sources/Output/SwiftDump/Dumper/StructDumper.swift index ec305894d..c4159f473 100644 --- a/Sources/Output/SwiftDump/Dumper/StructDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/StructDumper.swift @@ -56,7 +56,8 @@ package struct StructDumper: TypedDumper { // is orthogonal to substitution. let isBound = boundDumpedMetatype() != nil if !isBound, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO.context) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(.struct(dumped.descriptor)), in: machO.context) + try await genericContext.dumpGenericSignature(resolver: demangleResolver, depthLayout: depthLayout, in: machO.context) { if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { invertibleProtocolSet.dumpInvertedProtocolsInheritance } diff --git a/Sources/Output/SwiftDump/Protocols/TypedDumper.swift b/Sources/Output/SwiftDump/Protocols/TypedDumper.swift index 7237e4ca4..213f73c59 100644 --- a/Sources/Output/SwiftDump/Protocols/TypedDumper.swift +++ b/Sources/Output/SwiftDump/Protocols/TypedDumper.swift @@ -202,7 +202,11 @@ extension TypedDumper { // A kind-9 field type: read the thunk offline (the registered // resolver, `MachOFile` only), naming its arguments as this type's // generic parameters — the same leg `TypeDefinition.index` takes. - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try dumped.descriptor.genericContext(in: machO.context)) + let genericContext = try dumped.descriptor.genericContext(in: machO.context) + let ownerLayout = AccessorThunkOwnerLayout( + genericContext: genericContext, + depthLayout: genericContext.map { GenericParameterDepthLayout.make(for: $0, ownedBy: dumped.descriptor, in: machO.context) } ?? GenericParameterDepthLayout(parameterCountsByDepth: []) + ) return typeNode.resolvingAccessorFunctionReferences(in: machO, ownerLayout: ownerLayout) } diff --git a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift index f741bd966..009a09295 100644 --- a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift +++ b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift @@ -52,7 +52,7 @@ package extension SwiftDeclarationPrinter { displayParentName: displayParentName, level: level, leafNameNode: leafNameNode(of: typeDefinition.typeName.node.materialize()), - specializedMetadata: typeDefinition.isSpecialized ? typeDefinition.metadata : nil + boundTypeNode: boundTypeNode(of: typeDefinition) ) } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index c642d8ba7..0e226096e 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -23,9 +23,9 @@ extension SwiftDeclarationPrinter { /// mirroring the matching `StructDumper`/`ClassDumper`/`EnumDumper` /// `declaration` getter. /// - /// With a `specializedMetadata` (a user-driven specialization's - /// runtime-resolved metadata), the header renders the *bound* generic - /// form instead: the name prints with its concrete type arguments + /// With a `boundTypeNode` (a user-driven specialization's bound name, + /// `boundTypeNode(of:)`), the header renders the *bound* generic form + /// instead: the name prints with its concrete type arguments /// (`Box`) via `BoundDumpedTypeNameRenderer`, and the /// generic-signature clause is skipped — emitting it again would produce /// `Box` — while the invertible-protocol marker (and, @@ -34,9 +34,8 @@ extension SwiftDeclarationPrinter { /// getters. Without it (the default), the clean unbound interface form /// renders straight from the descriptor as before. @SemanticStringBuilder - package func renderTypeDeclarationHeader(for type: TypeContextWrapper, displayParentName: Bool, level: Int, leafNameNode: Node? = nil, specializedMetadata: MetadataWrapper? = nil) async throws -> SemanticString { + package func renderTypeDeclarationHeader(for type: TypeContextWrapper, displayParentName: Bool, level: Int, leafNameNode: Node? = nil, boundTypeNode: Node? = nil) async throws -> SemanticString { let resolver = typeDemangleResolver - let boundTypeNode: Node? = specializedMetadata.flatMap { SpecializedMetadataNodeSubstitution.boundTypeNode(for: $0) } switch type { case .struct(let dumped): Keyword(.struct) @@ -46,7 +45,7 @@ extension SwiftDeclarationPrinter { } else { try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } - try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) + try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, ownedBy: .type(.struct(dumped.descriptor)), invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .enum(let dumped): Keyword(.enum) Space() @@ -55,7 +54,7 @@ extension SwiftDeclarationPrinter { } else { try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } - try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) + try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, ownedBy: .type(.enum(dumped.descriptor)), invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .class(let dumped): if dumped.descriptor.isActor { if isDistributedActor(dumped) { @@ -74,7 +73,8 @@ extension SwiftDeclarationPrinter { } let superclass = try await renderClassSuperclass(dumped, resolver: resolver) if boundTypeNode == nil, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: resolver, in: machO.context) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(.class(dumped.descriptor)), in: machO.context) + try await genericContext.dumpGenericSignature(resolver: resolver, depthLayout: depthLayout, in: machO.context) { superclass } } else { @@ -83,10 +83,27 @@ extension SwiftDeclarationPrinter { } } + /// The bound name a specialized definition's header prints — + /// `Box` — or `nil` for an unspecialized one. A runtime + /// specialization's comes from its metadata, as the runtime names it; an + /// offline one's is the instantiation's name it was built with (evolution + /// proposal `offline-generic-specialization`), which has the same shape. + package func boundTypeNode(of typeDefinition: TypeDefinition) -> Node? { + guard typeDefinition.isSpecialized else { return nil } + if let metadata = typeDefinition.metadata { + return SpecializedMetadataNodeSubstitution.boundTypeNode(for: metadata) + } + if typeDefinition.staticSpecialization != nil { + return typeDefinition.typeName.node.materialize() + } + return nil + } + @SemanticStringBuilder - private func renderGenericSignatureWithInvertibles(genericContext: TypeGenericContext?, invertibleProtocolSet: InvertibleProtocolSet?, resolver: DemangleResolver) async throws -> SemanticString { + private func renderGenericSignatureWithInvertibles(genericContext: TypeGenericContext?, ownedBy descriptorWrapper: ContextDescriptorWrapper, invertibleProtocolSet: InvertibleProtocolSet?, resolver: DemangleResolver) async throws -> SemanticString { if let genericContext { - try await genericContext.dumpGenericSignature(resolver: resolver, in: machO.context) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: descriptorWrapper, in: machO.context) + try await genericContext.dumpGenericSignature(resolver: resolver, depthLayout: depthLayout, in: machO.context) { if let invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { invertibleProtocolSet.dumpInvertedProtocolsInheritance } @@ -347,7 +364,12 @@ extension SwiftDeclarationPrinter { staticLayoutDependencyResolution: configuration.staticLayoutDependencyResolution, marksOptionalContent: configuration.marksOptionalContent ) - let fieldLayoutRenderer = FieldLayoutRenderer(type: typeContext, metadata: typeDefinition.metadata, machO: machO, configuration: renderConfiguration) + // An offline specialization carries its arguments instead of + // metadata (evolution proposal `offline-generic-specialization`): the + // static layout path computes the comments for them, and the fields + // substitute them below. + let staticSpecialization: GenericArgumentBinding? = typeDefinition.isSpecialized ? typeDefinition.staticSpecialization : nil + let fieldLayoutRenderer = FieldLayoutRenderer(type: typeContext, metadata: typeDefinition.metadata, genericArgumentBinding: staticSpecialization, machO: machO, configuration: renderConfiguration) let fieldRecords = try typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.fieldDescriptor(in: machO.context).records(in: machO.context) let fieldOffsets = isEnum ? nil : fieldLayoutRenderer.fieldOffsets @@ -433,6 +455,9 @@ extension SwiftDeclarationPrinter { } } let substitutedTypeNode: Node? = { + if let staticSpecialization { + return StaticSpecializationNodeSubstitution.substitutedTypeNode(of: field.typeNode.materialize(), binding: staticSpecialization, in: machO) + } guard let specializedMetadata, let specializedMachOImage, let mangledTypeName else { return nil } return SpecializedMetadataNodeSubstitution.substitutedFieldTypeNode(for: mangledTypeName, metadata: specializedMetadata, in: specializedMachOImage) }() diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 6daf5fda8..ec53274df 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -268,18 +268,19 @@ public final class SwiftDeclarationPrinter: S BreakLine() } - // Specialized definitions carry the runtime-resolved metadata; the - // header renderer uses it to print the bound generic name - // (`Box`, not `Box where …`) — the same substitution the - // dump path performs via `TypedDumper.boundDumpedTypeNode()`. - let specializedMetadata: MetadataWrapper? = typeDefinition.isSpecialized ? typeDefinition.metadata : nil + // Specialized definitions print their bound generic name (`Box`, + // not `Box where …`): from the runtime-resolved metadata — the + // substitution the dump path performs via + // `TypedDumper.boundDumpedTypeNode()` — or, specialized offline, the + // instantiation's name. + let boundTypeNode = boundTypeNode(of: typeDefinition) // This print operation's single wrapper materialization (proposal // 0002), threaded into the header and field renderers below. let materializedTypeContext = try typeDefinition.materializedTypeContext(in: machO.context) try await DeclarationBlock(level: level) { - try await renderTypeDeclarationHeader(for: materializedTypeContext, displayParentName: displayParentName, level: level, specializedMetadata: specializedMetadata) + try await renderTypeDeclarationHeader(for: materializedTypeContext, displayParentName: displayParentName, level: level, boundTypeNode: boundTypeNode) } body: { // Per-CHILD catch: one nested child whose printing throws drops // only itself — the same per-definition contract `printRoot` diff --git a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift new file mode 100644 index 000000000..42795d487 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift @@ -0,0 +1,304 @@ +import Foundation +import MachOKit +import MachOFoundation +import MachOFixtureSupport +import MachOSwiftSection +import Testing + +/// An on-the-fly fixture for generic specialization, compiled once per process +/// and read two ways: as a `MachOFile` (the offline path, evolution proposal +/// `offline-generic-specialization`) and, `dlopen`ed into the test process, as +/// a `MachOImage` (the runtime path). The same binary on both sides is what +/// lets a test hold the two paths' output against each other byte for byte. +/// +/// Three groups of shapes: +/// +/// - **Generic parameter depths.** A depth counts only the contexts that +/// declare parameters: `DepthOuter.Middle.Inner` +/// puts `InnerElement` at depth 1, because `Middle` declares none, and a +/// constrained extension of `DepthOuter.SecondMiddle` spans both of +/// `DepthOuter`'s and `SecondMiddle`'s depths. Every reader that numbered +/// depths by counting generic ancestors got both wrong. +/// - **Offline/runtime parity.** One of every shape the offline specializer +/// prints: struct, class (with a generic superclass), single- and +/// multi-payload enums, an associated-type field, nested types that inherit +/// or add parameters, a private type, a type nested in another module's +/// extension, and a host for `.boundGeneric` arguments. +/// - **Constraint checks.** One type per requirement kind the offline +/// preflight checks, with conforming and non-conforming arguments beside. +package enum GenericSpecializationFixture { + package static let moduleName = "GenericSpecializationFixture" + + package static let source = """ + // Ballast: a struct-only dylib has no `__DATA` segment, and MachOKit before + // 0.52.103 mis-walked such a dylib's chained-fixup pages. + public final class FixtureAnchor {} + + // MARK: - Generic parameter depths + + public struct DepthOuter { + // Generic only because it is nested in `DepthOuter`: it declares no + // parameter, so it opens no depth. + public struct Middle { + public var outerElement: OuterElement + + public struct Inner { + public var outerElement: OuterElement + public var innerElement: InnerElement + } + + // `Inner` without the requirement: its accessor takes no witness + // table, so a test can instantiate it directly. + public struct PlainInner { + public var outerElement: OuterElement + public var innerElement: InnerElement + } + } + + public struct SecondMiddle { + public var middleElement: MiddleElement + } + } + + // `OuterElement` is pinned, so it takes no key argument; `InnerElement` + // is at depth 1. + extension DepthOuter where OuterElement == Int { + public struct ConstrainedInner { + public var outerElement: OuterElement + public var innerElement: InnerElement + } + } + + // The extension's parameters span two depths, `DepthOuter`'s and + // `SecondMiddle`'s, so `InnerElement` is at depth 2. + extension DepthOuter.SecondMiddle where OuterElement == Int { + public struct DeepConstrainedInner { + public var middleElement: MiddleElement + public var innerElement: InnerElement + } + } + + // Fields whose types are instantiations of the shapes above. A field + // naming `DeepConstrainedInner` is left out: its mangled name does not + // demangle (a separate, older problem). + public struct DepthHolder { + public var inner: DepthOuter.Middle.Inner + public var constrained: DepthOuter.ConstrainedInner + public var trailing: Int + } + + // MARK: - Offline/runtime parity + + public struct PairBox { + public var first: First + public var second: Second + public var count: Int + } + + public final class ReferenceBox { + public var element: Element + public var flag: Bool + + public init(element: Element, flag: Bool) { + self.element = element + self.flag = flag + } + } + + open class BaseBox { + public var base: Element + + public init(base: Element) { + self.base = base + } + } + + public final class DerivedBox: BaseBox { + public var extra: Int8 = 0 + } + + public enum SingleChoice { + case value(Payload) + case empty + case other + } + + public enum MultiChoice { + case left(Left) + case right(Right) + case neither + } + + public struct ElementsHolder { + public var elements: Elements + public var first: Elements.Element? + } + + // A non-generic holder of an instantiation whose field is a member of + // the argument: the static walk names it `[Swift.Int].Element` unless it + // projects the member through `Array`'s conformance. + public struct ElementsHolderHolder { + public var holder: ElementsHolder<[Int]> + } + + public struct NestedHost { + public var key: Key + + public struct Plain { + public var key: Key + } + + public struct Pair { + public var key: Key + public var value: Value + } + } + + private struct PrivateBox { + var element: Element + var count: Int + } + + extension Int { + public struct IntExtensionBox { + public var element: Element + } + } + + // MARK: - Constraint checks + + public struct ClassBound { + public var object: Object + } + + open class ConstraintBase { + public init() {} + } + + public final class ConstraintSubclass: ConstraintBase {} + + public final class ConstraintUnrelated { + public init() {} + } + + public struct BaseClassBound { + public var subject: Subject + } + + public protocol FixtureMarker {} + + public struct FixtureMarked: FixtureMarker { + public var value: Int + } + + public struct FixtureUnmarked { + public var value: Int + } + + public struct ProtocolBound { + public var subject: Subject + } + + public struct ElementSameType where Elements.Element == Int { + public var elements: Elements + } + + public struct ElementHashable where Elements.Element: Hashable { + public var elements: Elements + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let diagnostics: String + package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } + } + + private enum WorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in WorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private static let compilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + // The language mode pinned: CI's toolchain and a newer local one + // must compile the same source the same way. `-Onone` keeps the + // private type, which nothing references. + "swiftc", "-swift-version", "5", "-Onone", "-emit-library", + "-module-name", moduleName, + // The absolute output path as the install name, so the + // in-process leg loads with no rpath. + "-Xlinker", "-install_name", "-Xlinker", libraryURL.path, + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + package static func libraryURL() throws -> URL { + try compilationResult.get() + } + + /// The fixture read from disk — what the offline path sees. + package static func machOFile() throws -> MachOFile { + switch try MachOKit.loadFromFile(url: libraryURL()) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + /// The fixture loaded into the test process — what the runtime path sees. + package static func loadedImage() throws -> MachOImage { + let libraryURL = try libraryURL() + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } + + /// The descriptor of the fixture type whose own (unqualified) name is + /// `name`. Every fixture type name is unique, so the bare name is enough. + package static func typeContextDescriptor(named name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeContextDescriptorWrapper { + for descriptor in try machO.swift.typeContextDescriptors where try descriptor.namedContextDescriptor.name(in: machO.context) == name { + return descriptor + } + throw CompilationError(diagnostics: "the fixture declares no type named \(name)") + } + + /// The running system's `libswiftCore`, read from its dyld shared cache: + /// the offline indexer's sub-indexer for the standard library's + /// protocols and conformances. + package static func systemStandardLibraryFile() throws -> MachOFile { + let cache = try DyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + return try #require(cache.machOFile(by: .name("libswiftCore")), "libswiftCore not found in the running system's dyld shared cache") + } +} diff --git a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixtureIndexers.swift b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixtureIndexers.swift new file mode 100644 index 000000000..708769ec2 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixtureIndexers.swift @@ -0,0 +1,48 @@ +@_spi(Support) import SwiftIndexing +import SwiftDeclaration +import Foundation +import Testing +import MachOKit +import MachOSwiftSection + +/// The `GenericSpecializationFixture`'s prepared indexers, one per reading +/// path, each built once per process and shared by every suite: the runtime +/// one over the loaded image plus the process's `libswiftCore`, the offline +/// one over the file plus the running system's `libswiftCore` read from its +/// dyld shared cache. The standard library is there for its protocols and +/// conformances — `Hashable` is declared in it, and so is `String`'s +/// conformance to it. +package actor GenericSpecializationFixtureIndexers { + package static let shared = GenericSpecializationFixtureIndexers() + + private var runtimeIndexer: SwiftDeclarationIndexer? + private var offlineIndexer: SwiftDeclarationIndexer? + + package func runtime() async throws -> SwiftDeclarationIndexer { + if let runtimeIndexer { return runtimeIndexer } + let indexer = SwiftDeclarationIndexer(in: try GenericSpecializationFixture.loadedImage()) + let standardLibrary = try #require(MachOImage(name: "libswiftCore"), "libswiftCore is not loaded in the test process") + indexer.addSubIndexer(SwiftDeclarationIndexer(in: standardLibrary)) + try await indexer.prepare() + runtimeIndexer = indexer + return indexer + } + + /// The fixture's definition whose own name is `name`, from `indexer`'s + /// image — looked up by `declaredNameForTesting`, never `currentName`. + package static func typeDefinition(named name: String, in indexer: SwiftDeclarationIndexer) throws -> TypeDefinition { + try #require( + indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == name }, + "the fixture indexer holds no definition named \(name)" + ) + } + + package func offline() async throws -> SwiftDeclarationIndexer { + if let offlineIndexer { return offlineIndexer } + let indexer = SwiftDeclarationIndexer(in: try GenericSpecializationFixture.machOFile()) + indexer.addSubIndexer(SwiftDeclarationIndexer(in: try GenericSpecializationFixture.systemStandardLibraryFile())) + try await indexer.prepare() + offlineIndexer = indexer + return indexer + } +} diff --git a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift index 5e3742d38..1bbee4eb4 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift @@ -8,6 +8,7 @@ import MachOFixtureSupport @testable import MachOSwiftSection @testable import SwiftDump import SwiftDeclarationRendering +import SwiftInspection #if canImport(SwiftUI) import SwiftUI @@ -159,15 +160,15 @@ final class MetadataAccessorTests: MachOImageTests, @unchecked Sendable { case .enum(let enumDescriptor): guard let genericContext = try enumDescriptor.genericContext(in: machO.context) else { continue } // try mangleAsString(ContextDescriptorWrapper.type(.enum(enumDescriptor)).dumpNameNode(in: machO)).print() - try "\(ContextDescriptorWrapper.type(.enum(enumDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() + try "\(ContextDescriptorWrapper.type(.enum(enumDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), depthLayout: GenericParameterDepthLayout.make(for: genericContext, ownedBy: enumDescriptor, in: machO.context), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() case .struct(let structDescriptor): guard let genericContext = try structDescriptor.genericContext(in: machO.context) else { continue } // try mangleAsString(ContextDescriptorWrapper.type(.struct(structDescriptor)).dumpNameNode(in: machO)).print() - try "\(ContextDescriptorWrapper.type(.struct(structDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() + try "\(ContextDescriptorWrapper.type(.struct(structDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), depthLayout: GenericParameterDepthLayout.make(for: genericContext, ownedBy: structDescriptor, in: machO.context), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() case .class(let classDescriptor): guard let genericContext = try classDescriptor.genericContext(in: machO.context) else { continue } // try mangleAsString(ContextDescriptorWrapper.type(.class(classDescriptor)).dumpNameNode(in: machO)).print() - try "\(ContextDescriptorWrapper.type(.class(classDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() + try "\(ContextDescriptorWrapper.type(.class(classDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), depthLayout: GenericParameterDepthLayout.make(for: genericContext, ownedBy: classDescriptor, in: machO.context), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() } } } diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift index cb517b0d0..fa8605cb5 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift @@ -3,6 +3,7 @@ import Testing @testable import MachOSwiftSection @testable import MachOTestingSupport import MachOFixtureSupport +import SwiftInspection final class ProtocolGenericContextTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @@ -14,7 +15,7 @@ final class ProtocolGenericContextTests: MachOFileTests, @unchecked Sendable { for `protocol` in protocols { if let genericContext = try `protocol`.descriptor.genericContext(in: machO.context) { - try await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context).string.print() + try await genericContext.dumpGenericSignature(resolver: .using(options: .default), depthLayout: GenericParameterDepthLayout.make(for: genericContext, ownedBy: `protocol`.descriptor, in: machO.context), in: machO.context).string.print() } } } diff --git a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift new file mode 100644 index 000000000..68ffff73e --- /dev/null +++ b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift @@ -0,0 +1,37 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftDump +import MachOTestingSupport + +/// The dump path's half of `GenericParameterDepthNamingTests`: the dumpers +/// render a generic declaration's parameter clause through the same +/// `GenericContext` helper the interface printer does, so they numbered +/// depths the same wrong way — `Inner` over a field the record names +/// `A1`. +@Suite +struct GenericParameterDepthDumpTests { + private func dumpedStruct(named name: String) async throws -> String { + let machOFile = try GenericSpecializationFixture.machOFile() + let descriptor = try #require(try GenericSpecializationFixture.typeContextDescriptor(named: name, in: machOFile).struct) + let structType = try Struct(descriptor: descriptor, in: machOFile.context) + return try await structType.dump(using: .demangleOptions(.test), in: machOFile).string + } + + @Test("a parameter behind a level that declares none is named by its canonical depth") + func parameterBehindNonDeclaringLevel() async throws { + let dumped = try await dumpedStruct(named: "Inner") + + #expect(dumped.contains("Inner where A1: Swift.Hashable {"), "\(dumped)") + #expect(!dumped.contains("A2"), "\(dumped)") + } + + @Test("a parameter in a constrained extension of a nested generic type is named by its canonical depth") + func parameterInConstrainedExtensionOfNestedGeneric() async throws { + let dumped = try await dumpedStruct(named: "DeepConstrainedInner") + + #expect(dumped.contains("DeepConstrainedInner where A2: Swift.Hashable {"), "\(dumped)") + } +} diff --git a/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift b/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift index 0ea234b4a..27d8abf61 100644 --- a/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift +++ b/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift @@ -28,6 +28,15 @@ final class OuterGenericFixture { var first: First? var second: Second? } + + /// Declares no parameter of its own, so it opens no depth: `Second` + /// below is at depth 1, and its requirement names it `A1`. + struct NonDeclaringLevel { + struct ConstrainedPair { + var first: First? + var second: Second + } + } } // MARK: - Tests @@ -119,6 +128,8 @@ struct RuntimeMetadataTypeBuilderTests { "OuterGenericFixture": OuterGenericFixture.self, "Inner": OuterGenericFixture.Inner.self, "InnerPair": OuterGenericFixture.InnerPair.self, + "NonDeclaringLevel": OuterGenericFixture.NonDeclaringLevel.self, + "ConstrainedPair": OuterGenericFixture.NonDeclaringLevel.ConstrainedPair.self, ] var declarationName: String? for child in declarationNode.children.reversed() where child.kind == .identifier { @@ -154,6 +165,15 @@ struct RuntimeMetadataTypeBuilderTests { try expectRoundTrip(OuterGenericFixture.InnerPair.self, builder: fixtureBuilder) } + /// The requirement subject `A1` must bind to `Second`. The written + /// arguments used to be bound by counting every generic ancestor as a + /// depth, which put `Second` at depth 2 because `NonDeclaringLevel` is + /// generic without declaring anything, so `A1: Hashable` found no + /// argument and the instantiation failed. + @Test func nestedGenericBehindNonDeclaringLevelResolvesItsRequirement() throws { + try expectRoundTrip(OuterGenericFixture.NonDeclaringLevel.ConstrainedPair.self, builder: fixtureBuilder) + } + @Test func genericArgumentsComposeStructurally() throws { try expectRoundTrip(HashableConstrainedBox<[Int?]>.self, builder: fixtureBuilder) } diff --git a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift new file mode 100644 index 000000000..f9ba16b19 --- /dev/null +++ b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Support) @testable import SwiftInterface +import MachOTestingSupport + +/// A generic parameter's printed name encodes its depth (`A1` is depth 1, +/// index 0), and a depth counts only the contexts that declare parameters. +/// The field records name the parameters that way — the demangler reads the +/// depth straight out of the mangling — so a header has to as well, or its +/// parameter clause and its fields disagree about one parameter. +/// +/// The header used to number depths by counting every generic ancestor. +/// `Middle` in `DepthOuter.Middle.Inner` +/// declares nothing but is generic, so `InnerElement` printed as `A2` while +/// its field read `A1`; a constrained extension of `DepthOuter.SecondMiddle` +/// spans two depths but counted as one, so `DeepConstrainedInner`'s +/// `InnerElement` printed as `A1` while its field read `A2`. +@Suite +struct GenericParameterDepthNamingTests { + private func renderInterface() async throws -> String { + let machOFile = try GenericSpecializationFixture.machOFile() + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) + try await builder.prepare() + return try await builder.printRoot().string + } + + private func headerLine(declaring typeName: String, in interface: String) -> String? { + interface.split(separator: "\n") + .map { $0.trimmingCharacters(in: .whitespaces) } + .first { $0.hasPrefix("struct \(typeName)<") } + } + + @Test("a parameter behind a level that declares none is named by its canonical depth") + func parameterBehindNonDeclaringLevel() async throws { + let interface = try await renderInterface() + + #expect(headerLine(declaring: "Inner", in: interface) == "struct Inner where A1: Swift.Hashable {", "\(interface)") + #expect(interface.contains("var innerElement: A1"), "\(interface)") + } + + @Test("a parameter in a constrained extension of a nested generic type is named by its canonical depth") + func parameterInConstrainedExtensionOfNestedGeneric() async throws { + let interface = try await renderInterface() + + #expect(headerLine(declaring: "DeepConstrainedInner", in: interface) == "struct DeepConstrainedInner where A2: Swift.Hashable {", "\(interface)") + #expect(interface.contains("var innerElement: A2"), "\(interface)") + } + + @Test("a parameter in a constrained extension of a top-level generic type keeps depth 1") + func parameterInConstrainedExtensionOfTopLevelGeneric() async throws { + let interface = try await renderInterface() + + #expect(headerLine(declaring: "ConstrainedInner", in: interface) == "struct ConstrainedInner {", "\(interface)") + } +} diff --git a/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift new file mode 100644 index 000000000..279663866 --- /dev/null +++ b/Tests/SwiftLayoutTests/BoundInstantiationLayoutTests.swift @@ -0,0 +1,97 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout +import MachOTestingSupport +import Demangling + +/// Layouts of instantiations a `GenericArgumentBinding` describes — an +/// offline specialization's (evolution proposal +/// `offline-generic-specialization`) — checked against the runtime's +/// metadata for the same instantiation, and the expanded field-offset tree's +/// naming of a member of a concrete type. +@Suite +struct BoundInstantiationLayoutTests { + private func typeNode(_ type: Any.Type) throws -> Node { + try demangleAsNode(try #require(_mangledTypeName(type)), isType: true) + } + + /// The runtime's field-offset vector of the instantiation the fixture's + /// accessor builds for `arguments` (key arguments only, no witness + /// tables needed by these shapes). + private func runtimeFieldOffsets(ofTypeNamed typeName: String, arguments: [Any.Type]) throws -> [Int] { + let machOImage = try GenericSpecializationFixture.loadedImage() + let descriptor = try GenericSpecializationFixture.typeContextDescriptor(named: typeName, in: machOImage) + let accessor = try #require(try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machOImage.context)) + let response = try accessor(request: .init(), metadatas: arguments.map { try Metadata.createInProcess($0) }, witnessTables: []) + switch try response.value.resolve(in: .inProcess) { + case .struct(let structMetadata): + return try structMetadata.fieldOffsets(in: .inProcess).map { Int($0) } + case .class(let classMetadata): + return try classMetadata.fieldOffsets(in: .inProcess).map { Int($0) } + default: + Issue.record("\(typeName) has no field-offset vector") + return [] + } + } + + private func staticFieldOffsets(ofTypeNamed typeName: String, binding: GenericArgumentBinding) throws -> AggregateFieldLayout { + let machOFile = try GenericSpecializationFixture.machOFile() + let descriptor = try GenericSpecializationFixture.typeContextDescriptor(named: typeName, in: machOFile) + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache])) + return try calculator.fieldLayout(of: descriptor, genericArgumentBinding: binding) + } + + @Test("a nested type behind a level that declares no parameter lays out like the runtime's") + func nestedTypeBehindNonDeclaringLevel() throws { + let binding = GenericArgumentBinding(argumentsByDepth: [[try typeNode(Int.self)], [try typeNode(String.self)]]) + + let aggregate = try staticFieldOffsets(ofTypeNamed: "PlainInner", binding: binding) + + assertFullyComputed(aggregate, equals: try runtimeFieldOffsets(ofTypeNamed: "PlainInner", arguments: [Int.self, String.self]), typeName: "DepthOuter.Middle.PlainInner") + } + + @Test("a class over a generic superclass lays out like the runtime's") + func classOverGenericSuperclass() throws { + let binding = GenericArgumentBinding(argumentsByDepth: [[try typeNode(Int16.self)]]) + + let aggregate = try staticFieldOffsets(ofTypeNamed: "DerivedBox", binding: binding) + + assertFullyComputed(aggregate, equals: try runtimeFieldOffsets(ofTypeNamed: "DerivedBox", arguments: [Int16.self]), typeName: "DerivedBox") + } + + @Test("a fixed parameter's argument lays out the field it types") + func fixedParameter() throws { + // `OuterElement` is pinned to `Int` and takes no key argument; the + // binding still carries it, as `GenericInstantiation` fills it in. + let binding = GenericArgumentBinding(argumentsByDepth: [[try typeNode(Int.self)], [try typeNode(Int8.self)]]) + + let aggregate = try staticFieldOffsets(ofTypeNamed: "ConstrainedInner", binding: binding) + + assertFullyComputed(aggregate, equals: try runtimeFieldOffsets(ofTypeNamed: "ConstrainedInner", arguments: [Int8.self]), typeName: "DepthOuter.ConstrainedInner") + } + + /// The tree used to name the member as the substitution left it, + /// `Swift.Optional.Element>`, and to stop there; + /// the runtime's walk names — and expands — the type it is. + @Test("a member of a concrete type is named and expanded as the type its record names") + func concreteMemberIsProjectedInTheTree() throws { + let machOFile = try GenericSpecializationFixture.machOFile() + let holderDescriptor = try #require(try GenericSpecializationFixture.typeContextDescriptor(named: "ElementsHolderHolder", in: machOFile).struct) + let holderRecord = try #require(try holderDescriptor.fieldDescriptor(in: machOFile.context).records(in: machOFile.context).first) + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache])) + + let tree = calculator.nestedFieldOffsetTree(forMangledTypeName: try holderRecord.mangledTypeName(in: machOFile.context), baseOffset: 0, depthLimit: 8) + + let first = try #require(tree.first { $0.fieldName == "first" }, "\(tree.map(\.fieldName))") + #expect(first.typeName == "Swift.Optional") + // The payload is `Swift.Int` itself, which expands into its + // `_value`, as the runtime's walk does. + let payload = try #require(first.children.first) + #expect(payload.typeName == "Swift.Int") + #expect(payload.children.map(\.fieldName) == ["_value"]) + } +} diff --git a/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift new file mode 100644 index 000000000..9fb196420 --- /dev/null +++ b/Tests/SwiftLayoutTests/ExtensionContextInstantiationLayoutTests.swift @@ -0,0 +1,41 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout +import MachOTestingSupport + +/// An instantiation of a type declared in a constrained extension names its +/// context as an extension: `DepthOuter.ConstrainedInner` +/// demangles to `ConstrainedInner` under `Extension(, +/// DepthOuter, )`, and the outer argument rides the +/// extension's extended type, not a nominal parent. +/// +/// The argument walk stopped at the extension, so it saw only the innermost +/// list and bound `String` to depth 0 — `ConstrainedInner`'s +/// `InnerElement` (depth 1) stayed unsubstituted and the field naming the +/// instantiation, with every field after it, degraded to unknown. +@Suite +struct ExtensionContextInstantiationLayoutTests { + private static let holderQualifiedTypeName = "\(GenericSpecializationFixture.moduleName).DepthHolder" + + @Test("an instantiation under an extension context lays out like the runtime's") + func instantiationUnderExtensionContext() throws { + let machOImage = try GenericSpecializationFixture.loadedImage() + let runtimeOffsets = try #require( + try runtimeFieldOffsets(ofQualifiedTypeName: Self.holderQualifiedTypeName, in: machOImage), + "no runtime field-offset vector for DepthHolder" + ) + + let machOFile = try GenericSpecializationFixture.machOFile() + let aggregate = try fieldLayout( + ofQualifiedTypeName: Self.holderQualifiedTypeName, + with: try StaticLayoutCalculator(machO: machOFile), + in: machOFile + ) + + assertFullyComputed(aggregate, equals: runtimeOffsets, typeName: "DepthHolder") + } +} diff --git a/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift b/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift new file mode 100644 index 000000000..c1c1be81b --- /dev/null +++ b/Tests/SwiftSpecializationTests/CanonicalParameterDepthTests.swift @@ -0,0 +1,77 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Demangling +@testable import MachOSwiftSection +import MachOTestingSupport + +/// `GenericSpecializer` names each parameter by its `(depth, index)` — `A`, +/// `B`, `A1`, … — and collects the parameter's requirements by matching that +/// name against the requirement's subject, which the demangler names from the +/// depth the mangling carries. A depth counts only the contexts that declare +/// parameters. +/// +/// The specializer used to count every generic ancestor as a depth. +/// `InnerElement` in +/// `DepthOuter.Middle.Inner` became `A2` +/// while its requirement reads `A1: Hashable`, so the requirement was never +/// collected: the request offered `InnerElement` every type instead of the +/// Hashable ones, and `specialize` built one witness table too few and failed +/// its key-argument count check. +@Suite(.serialized) +struct CanonicalParameterDepthTests { + private func runtimeRequest(forTypeNamed name: String) async throws -> (specializer: GenericSpecializer, request: SpecializationRequest) { + let indexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let descriptor = try GenericSpecializationFixture.typeContextDescriptor(named: name, in: indexer.machO) + let specializer = GenericSpecializer(indexer: indexer) + return (specializer, try specializer.makeRequest(for: descriptor)) + } + + private func protocolRequirementNames(of parameter: SpecializationRequest.Parameter) -> [String] { + parameter.requirements.compactMap { requirement in + guard case .protocol(let info) = requirement else { return nil } + return info.protocolName.name + } + } + + @Test("a parameter behind a level that declares none takes the next depth") + func parameterBehindNonDeclaringLevel() async throws { + let (_, request) = try await runtimeRequest(forTypeNamed: "Inner") + + #expect(request.parameters.map(\.name) == ["A", "A1"]) + #expect(request.parameters.map(\.depth) == [0, 1]) + let innerParameter = try #require(request.parameters.last) + #expect(protocolRequirementNames(of: innerParameter) == ["Swift.Hashable"]) + } + + @Test("a constrained extension of a nested generic type spans both of its depths") + func constrainedExtensionOfNestedGeneric() async throws { + let (_, request) = try await runtimeRequest(forTypeNamed: "DeepConstrainedInner") + + // `OuterElement` is pinned to `Int`, so it takes no key argument and + // is not offered; `MiddleElement` is `SecondMiddle`'s parameter at + // depth 1, `InnerElement` the type's own at depth 2. + #expect(request.parameters.map(\.name) == ["A1", "A2"]) + let innerParameter = try #require(request.parameters.last) + #expect(protocolRequirementNames(of: innerParameter) == ["Swift.Hashable"]) + } + + @Test("the runtime specializes a type behind a level that declares no parameter") + func runtimeSpecializesTypeBehindNonDeclaringLevel() async throws { + let (specializer, request) = try await runtimeRequest(forTypeNamed: "Inner") + let selection = SpecializationSelection(arguments: Dictionary(uniqueKeysWithValues: zip( + request.parameters.map(\.name), + [SpecializationSelection.Argument.metatype(Int.self), .metatype(String.self)] + ))) + + let result = try specializer.specialize(request, with: selection) + + let metatype = unsafeBitCast(try result.metadata().asPointer, to: Any.Type.self) + let runtimeName = try #require(_mangledTypeName(metatype)) + let printedName = try await demangleAsNode(runtimeName, isType: true).print(using: .default) + #expect(printedName == "GenericSpecializationFixture.DepthOuter.Middle.Inner") + } +} diff --git a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift index 6ddefd89f..69699067a 100644 --- a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift @@ -1215,6 +1215,7 @@ struct GenericSpecializationTests { let genericContext = try #require(try descriptor.genericContext(in: machO.context)) let dumped = try await genericContext.dumpGenericParameters( + depthLayout: GenericParameterDepthLayout.make(for: genericContext, ownedBy: descriptor, in: machO.context), in: machO.context, isDumpCurrentLevel: false ).string diff --git a/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift b/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift new file mode 100644 index 000000000..1028a5e25 --- /dev/null +++ b/Tests/SwiftSpecializationTests/InstantiatedTypeNameTests.swift @@ -0,0 +1,177 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Demangling +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering +import MachOTestingSupport + +/// A specialization's name hangs each argument on the level that declares +/// its parameter — `Outer.Inner`, the shape the +/// runtime gives the instantiation (`_buildDemanglingForContext`) — whether +/// the specialization was made in-process or offline (evolution proposal +/// `offline-generic-specialization`). +/// A host type a test hands over as an argument; a `Sendable` stand-in for +/// the metatype, which a parameterized test's arguments must be. +enum HostTypeArgument: String, Sendable { + case int + case string + case bool + + var type: Any.Type { + switch self { + case .int: Int.self + case .string: String.self + case .bool: Bool.self + } + } +} + +@Suite(.serialized) +struct InstantiatedTypeNameTests { + private static let moduleName = GenericSpecializationFixture.moduleName + + // MARK: - The runtime path's name + + /// The runtime path used to put every argument on the innermost level: + /// `Outer.Middle.Inner`, a name of no type. + /// RuntimeViewer shows `typeName` in its sidebar and keys the + /// specialization on it. + @Test("a runtime specialization's name puts each argument on its own level") + func runtimeSpecializationNameIsNested() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "Inner", in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let result = try specializer.specialize(request, with: ["A": .metatype(Int.self), "A1": .metatype(String.self)]) + + let specialized = try await definition.specialize( + with: result, + typeArgumentNodes: [try await demangleAsNode("Si", isType: true), try await demangleAsNode("SS", isType: true)], + in: indexer.machO + ) + + #expect(specialized.typeName.name(using: .default) == "\(Self.moduleName).DepthOuter.Middle.Inner") + } + + /// A nested type that declares no parameter of its own is derived from + /// its parent's binding; its name used to read `NestedHost.Plain`. + @Test("a derived nested type's name keeps the argument on its parent") + func derivedNestedTypeNameKeepsTheArgumentOnItsParent() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "NestedHost", in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let selection: SpecializationSelection = ["A": .metatype(Int.self)] + let result = try specializer.specialize(request, with: selection) + let intNode = try await demangleAsNode("Si", isType: true) + + let specialized = try await definition.specialize( + with: result, + typeArgumentNodes: [intNode], + derivingNestedSpecializationsWith: specializer, + selection: selection, + typeArgumentNodesByParameter: ["A": intNode], + in: indexer.machO + ) + + #expect(specialized.typeChildren.map { $0.typeName.name(using: .default) } == ["\(Self.moduleName).NestedHost.Plain"]) + } + + // MARK: - The offline name against the runtime's + + /// Specializes the fixture type `typeName` both ways with the same host + /// types, and returns the runtime's name for the instantiation and the + /// offline result's. + private func names( + ofTypeNamed typeName: String, + arguments hostArguments: [String: HostTypeArgument] + ) async throws -> (runtime: Node, offline: Node) { + let arguments = hostArguments.mapValues(\.type) + let runtimeIndexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let runtimeDefinition = try GenericSpecializationFixtureIndexers.typeDefinition(named: typeName, in: runtimeIndexer) + let runtimeSpecializer = GenericSpecializer(indexer: runtimeIndexer) + let runtimeRequest = try runtimeSpecializer.makeRequest(for: runtimeDefinition.typeContextDescriptorWrapper) + let runtimeResult = try runtimeSpecializer.specialize(runtimeRequest, with: SpecializationSelection(arguments: arguments.mapValues { .metatype($0) })) + // The runtime's name as the library reads it: through the one entry + // that rewrites the anonymous context the runtime spells a private + // type's by address. + let runtimeMetatype = unsafeBitCast(try runtimeResult.metadata().asPointer, to: Any.Type.self) + let runtimeName = try #require(RuntimeTypeNameDemangling.node(forMetatype: runtimeMetatype)) + + let offlineIndexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let offlineDefinition = try GenericSpecializationFixtureIndexers.typeDefinition(named: typeName, in: offlineIndexer) + let offlineSpecializer = GenericSpecializer(indexer: offlineIndexer) + let offlineRequest = try offlineSpecializer.makeRequest(for: offlineDefinition.typeContextDescriptorWrapper) + let offlineResult = try offlineSpecializer.specialize(offlineRequest, with: SpecializationSelection(arguments: arguments.mapValues { .metatype($0) })) + + return (runtimeName, offlineResult.typeName.node.materialize()) + } + + @Test( + "an offline instantiation is named like the runtime names it", + arguments: [ + ("PairBox", ["A": .int, "B": .string] as [String: HostTypeArgument]), + ("Inner", ["A": .int, "A1": .string]), + ("Pair", ["A": .int, "A1": .bool]), + ("Plain", ["A": .int]), + ("ReferenceBox", ["A": .int]), + ("MultiChoice", ["A": .int, "B": .string]), + ("PrivateBox", ["A": .int]), + ] + ) + func offlineNameMatchesTheRuntime(typeName: String, arguments: [String: HostTypeArgument]) async throws { + let (runtimeName, offlineName) = try await names(ofTypeNamed: typeName, arguments: arguments) + + let printedOfflineName = await offlineName.print(using: .default) + let printedRuntimeName = await runtimeName.print(using: .default) + #expect(offlineName == runtimeName, "offline \(printedOfflineName) runtime \(printedRuntimeName)") + } + + /// A parameter a same-type requirement fixes takes no argument, yet its + /// level still binds it: `A == Int` in the extension declaring + /// `ConstrainedInner`. The runtime recovers it from the requirement, and + /// so does the offline path. + @Test("a fixed parameter is named by the type its same-type requirement fixes it to") + func fixedParameterIsNamedLikeTheRuntime() async throws { + let (runtimeName, offlineName) = try await names(ofTypeNamed: "ConstrainedInner", arguments: ["A1": .string]) + + let printedOfflineName = await offlineName.print(using: .default) + let printedRuntimeName = await runtimeName.print(using: .default) + #expect(offlineName == runtimeName, "offline \(printedOfflineName) runtime \(printedRuntimeName)") + #expect(printedOfflineName == "(extension in \(Self.moduleName)):\(Self.moduleName).DepthOuter.ConstrainedInner") + } + + /// A type in another module's extension: the extension context stays, + /// carrying the extended type. + @Test("a type nested in another module's extension is named like the runtime names it") + func typeInCrossModuleExtensionIsNamedLikeTheRuntime() async throws { + let (runtimeName, offlineName) = try await names(ofTypeNamed: "IntExtensionBox", arguments: ["A": .string]) + + let printedOfflineName = await offlineName.print(using: .default) + let printedRuntimeName = await runtimeName.print(using: .default) + #expect(offlineName == runtimeName, "offline \(printedOfflineName) runtime \(printedRuntimeName)") + } + + /// For a constrained extension of a nested generic type the runtime puts + /// every extension argument into the innermost list of the extended type + /// and leaves its outer level unbound — + /// `DepthOuter.SecondMiddle`, a name of no type. The offline name binds each level; the difference + /// is deliberate and documented on `SymbolicDemangler.instantiatedTypeNode`. + @Test("a constrained extension of a nested generic type binds each extended level") + func constrainedExtensionOfNestedGenericBindsEachLevel() async throws { + let offlineIndexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "DeepConstrainedInner", in: offlineIndexer) + let specializer = GenericSpecializer(indexer: offlineIndexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + + let result = try specializer.specialize(request, with: ["A1": .metatype(Bool.self), "A2": .metatype(String.self)]) + + #expect(result.typeName.name(using: .default) == "(extension in \(Self.moduleName)):\(Self.moduleName).DepthOuter.SecondMiddle.DeepConstrainedInner") + #expect(result.binding.argumentsByDepth.map { $0.map { $0.print(using: .default) } } == [["Swift.Int"], ["Swift.Bool"], ["Swift.String"]]) + } +} diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift new file mode 100644 index 000000000..09a9abb6b --- /dev/null +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift @@ -0,0 +1,186 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +import Foundation +import Testing +import MachOKit +import Demangling +@testable import MachOSwiftSection +import MachOTestingSupport +import SwiftDeclarationRendering + +/// One instantiation, specialized and printed both ways, must read the same +/// byte for byte (evolution proposal `offline-generic-specialization`): the +/// runtime path from the loaded image and its metadata, the offline path +/// from the same binary read as a file, with every layout comment on. The +/// offline path never asks the runtime, so agreement is the evidence that the +/// instantiation's name, its field types and its layout were all derived +/// right. +/// +/// The shapes avoid three places the two paths differ by design, for +/// unspecialized types too: a single-payload enum whose empty cases ride the +/// payload's extra inhabitants (only the runtime can project their bytes); a +/// tuple-typed field (the runtime breaks its type layout down per element); +/// and a field of a generic standard-library struct such as `Array`, whose +/// expanded offsets the runtime's walk stops at the first nested field typed +/// by the struct's own parameter (`_buffer: _ArrayBuffer`) while the +/// static walk descends through it. +@Suite(.serialized) +struct OfflineSpecializationParityTests { + private static var configuration: SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.printFieldOffset = true + configuration.printTypeLayout = true + configuration.printEnumLayout = true + configuration.printExpandedFieldOffsets = true + return configuration + } + + /// A host-supplied argument, which both paths accept. + enum ParityArgument { + case host(Any.Type) + /// A fixture type bound to arguments of its own: `.boundGeneric`. + case bound(typeName: String, arguments: [String: Any.Type]) + } + + private func selection( + _ arguments: [String: ParityArgument], + for request: SpecializationRequest, + indexer: SwiftDeclarationIndexer + ) throws -> SpecializationSelection { + var selectionArguments: [String: SpecializationSelection.Argument] = [:] + for (parameterName, argument) in arguments { + switch argument { + case .host(let type): + selectionArguments[parameterName] = .metatype(type) + case .bound(let typeName, let innerArguments): + let parameter = try #require(request.parameters.first { $0.name == parameterName }) + let baseCandidate = try #require(parameter.candidates.first { $0.typeName.declaredNameForTesting == typeName }) + selectionArguments[parameterName] = .boundGeneric(baseCandidate: baseCandidate, innerArguments: innerArguments.mapValues { .metatype($0) }) + } + } + return SpecializationSelection(arguments: selectionArguments) + } + + private func runtimeInterface(ofTypeNamed typeName: String, arguments: [String: ParityArgument]) async throws -> String { + let indexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: typeName, in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let selection = try selection(arguments, for: request, indexer: indexer) + let result = try specializer.specialize(request, with: selection) + // What RuntimeViewer hands over: a node per parameter — the + // specialization's name is built from them, and the runtime path + // derives the nested types the binding covers with them. Read here + // from each argument's resolved metadata. + var typeArgumentNodesByParameter: [String: Node] = [:] + for resolvedArgument in result.resolvedArguments { + let argumentType = unsafeBitCast(try resolvedArgument.metadata.asPointer, to: Any.Type.self) + typeArgumentNodesByParameter[resolvedArgument.parameterName] = try #require(RuntimeTypeNameDemangling.node(forMetatype: argumentType)) + } + let typeArgumentNodes = request.parameters.compactMap { typeArgumentNodesByParameter[$0.name] } + let specialized = try await definition.specialize( + with: result, + typeArgumentNodes: typeArgumentNodes, + derivingNestedSpecializationsWith: specializer, + selection: selection, + typeArgumentNodesByParameter: typeArgumentNodesByParameter, + in: indexer.machO + ) + let printer = SwiftDeclarationPrinter(configuration: Self.configuration, in: indexer.machO) + return try await printer.printTypeDefinition(specialized).string + } + + private func offlineInterface(ofTypeNamed typeName: String, arguments: [String: ParityArgument]) async throws -> String { + let indexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: typeName, in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let selection = try selection(arguments, for: request, indexer: indexer) + let result = try specializer.specialize(request, with: selection) + let specialized = try await definition.specialize( + with: result, + derivingNestedSpecializationsWith: specializer, + in: indexer.machO + ) + let printer = SwiftDeclarationPrinter(configuration: Self.configuration, in: indexer.machO) + return try await printer.printTypeDefinition(specialized).string + } + + private func expectParity(ofTypeNamed typeName: String, arguments: [String: ParityArgument], sourceLocation: SourceLocation = #_sourceLocation) async throws { + let runtime = try await runtimeInterface(ofTypeNamed: typeName, arguments: arguments) + let offline = try await offlineInterface(ofTypeNamed: typeName, arguments: arguments) + #expect(offline == runtime, "offline:\n\(offline)\nruntime:\n\(runtime)", sourceLocation: sourceLocation) + // A guard against both sides degrading the same way: the comments + // must be there. + #expect(offline.contains("Type Layout") || offline.contains("Enum Layout"), "no layout comment:\n\(offline)", sourceLocation: sourceLocation) + } + + /// The runtime path printed no `Enum Layout` for any generic enum, a + /// specialization included, although the specialization's metadata says + /// exactly how the instantiation lays out. + @Test("the runtime path lays out a specialized generic enum") + func runtimePathLaysOutASpecializedGenericEnum() async throws { + let runtime = try await runtimeInterface(ofTypeNamed: "MultiChoice", arguments: ["A": .host(Int.self), "B": .host(String.self)]) + + #expect(runtime.contains("Enum Layout"), "\(runtime)") + } + + @Test("a struct with two parameters") + func structWithTwoParameters() async throws { + try await expectParity(ofTypeNamed: "PairBox", arguments: ["A": .host(Int.self), "B": .host(String.self)]) + } + + @Test("a final class") + func finalClass() async throws { + try await expectParity(ofTypeNamed: "ReferenceBox", arguments: ["A": .host(Int.self)]) + } + + @Test("a class whose superclass is generic too") + func classWithGenericSuperclass() async throws { + try await expectParity(ofTypeNamed: "DerivedBox", arguments: ["A": .host(Int.self)]) + } + + @Test("a single-payload enum") + func singlePayloadEnum() async throws { + try await expectParity(ofTypeNamed: "SingleChoice", arguments: ["A": .host(Int.self)]) + } + + @Test("a multi-payload enum") + func multiPayloadEnum() async throws { + try await expectParity(ofTypeNamed: "MultiChoice", arguments: ["A": .host(Int.self), "B": .host(String.self)]) + } + + @Test("a field typed by a member of the argument") + func associatedTypeField() async throws { + // `String`'s `Element` is `Character`: `first` reads `Swift.Character?` + // once the member is projected through the conformance. + try await expectParity(ofTypeNamed: "ElementsHolder", arguments: ["A": .host(String.self)]) + } + + @Test("a nested type behind a level that declares no parameter") + func nestedGenericBehindNonDeclaringLevel() async throws { + try await expectParity(ofTypeNamed: "Inner", arguments: ["A": .host(Int.self), "A1": .host(String.self)]) + } + + @Test("a generic type with a nested type its binding derives") + func derivedNestedType() async throws { + try await expectParity(ofTypeNamed: "NestedHost", arguments: ["A": .host(Int.self)]) + } + + @Test("a nested generic type declaring a parameter of its own") + func nestedGenericDeclaringItsOwnParameter() async throws { + try await expectParity(ofTypeNamed: "Pair", arguments: ["A": .host(Int.self), "A1": .host(Bool.self)]) + } + + @Test("a private type") + func privateType() async throws { + try await expectParity(ofTypeNamed: "PrivateBox", arguments: ["A": .host(Int.self)]) + } + + @Test("a bound-generic argument") + func boundGenericArgument() async throws { + try await expectParity(ofTypeNamed: "PairBox", arguments: ["A": .bound(typeName: "ReferenceBox", arguments: ["A": Int.self]), "B": .host(Int8.self)]) + } +} diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift new file mode 100644 index 000000000..05d991b03 --- /dev/null +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift @@ -0,0 +1,257 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Demangling +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import MachOTestingSupport + +/// A host type with no conformance any indexed image records. +private struct HostUnmarked { + var value: Int +} + +/// A host class outside every fixture hierarchy. +private final class HostUnrelatedClass {} + +/// `GenericSpecializer`'s offline execution on a `MachOFile` (evolution +/// proposal `offline-generic-specialization`): the request, the binding and +/// name a specialization produces, and `staticPreflight`'s two kinds of +/// outcome — an error for a requirement provably violated, a warning for one +/// a file cannot settle. +@Suite(.serialized) +struct OfflineSpecializationTests { + private static let moduleName = GenericSpecializationFixture.moduleName + + private func offlineRequest(forTypeNamed typeName: String) async throws -> (specializer: GenericSpecializer, request: SpecializationRequest) { + let indexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: typeName, in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + return (specializer, try specializer.makeRequest(for: definition.typeContextDescriptorWrapper)) + } + + private func candidate(named typeName: String, in request: SpecializationRequest, parameter parameterName: String) throws -> SpecializationRequest.Candidate { + let parameter = try #require(request.parameters.first { $0.name == parameterName }) + return try #require(parameter.candidates.first { $0.typeName.declaredNameForTesting == typeName }, "\(parameterName) offers no candidate named \(typeName)") + } + + // MARK: - Requests + + /// Read from a file, a requirement on a protocol another image declares + /// lands on the bind the loader would resolve (`$sSHMp`). The request used + /// to drop it: `InnerElement` offered every type, and no witness table + /// was counted. + @Test("an offline request keeps a requirement on another image's protocol") + func offlineRequestKeepsCrossImageProtocolRequirement() async throws { + let (_, request) = try await offlineRequest(forTypeNamed: "Inner") + + let innerParameter = try #require(request.parameters.last) + let protocolNames = innerParameter.requirements.compactMap { requirement -> String? in + guard case .protocol(let info) = requirement else { return nil } + return info.protocolName.name + } + #expect(protocolNames == ["Swift.Hashable"]) + #expect(innerParameter.candidates.contains { $0.typeName.name == "Swift.String" }) + #expect(!innerParameter.candidates.contains { $0.typeName.declaredNameForTesting == "FixtureUnmarked" }) + } + + // MARK: - Results + + @Test("an offline specialization binds every depth and names the instantiation") + func offlineSpecializationBindsEveryDepth() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "Inner") + + let result = try specializer.specialize(request, with: ["A": .metatype(Int.self), "A1": .metatype(String.self)]) + + #expect(result.typeName.name(using: .default) == "\(Self.moduleName).DepthOuter.Middle.Inner") + #expect(result.binding.argumentsByDepth.map { $0.map { $0.print(using: .default) } } == [["Swift.Int"], ["Swift.String"]]) + #expect(result.resolvedArguments.map(\.parameterName) == ["A", "A1"]) + } + + @Test("a candidate argument stands for the candidate's name") + func candidateArgument() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ProtocolBound") + let marked = try candidate(named: "FixtureMarked", in: request, parameter: "A") + + let result = try specializer.specialize(request, with: ["A": .candidate(marked)]) + + #expect(result.typeName.name(using: .default) == "\(Self.moduleName).ProtocolBound<\(Self.moduleName).FixtureMarked>") + } + + @Test("a bound-generic argument is specialized offline in turn") + func boundGenericArgument() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "PairBox") + let referenceBox = try candidate(named: "ReferenceBox", in: request, parameter: "A") + + let result = try specializer.specialize(request, with: [ + "A": .boundGeneric(baseCandidate: referenceBox, innerArguments: ["A": .metatype(Int.self)]), + "B": .metatype(String.self), + ]) + + #expect(result.typeName.name(using: .default) == "\(Self.moduleName).PairBox<\(Self.moduleName).ReferenceBox, Swift.String>") + let innerResult = try #require(result.argument(for: "A")?.innerResult) + #expect(innerResult.typeName.name(using: .default) == "\(Self.moduleName).ReferenceBox") + } + + @Test("a generic candidate throws the runtime path's typed error") + func genericCandidateThrows() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "PairBox") + let referenceBox = try candidate(named: "ReferenceBox", in: request, parameter: "A") + + #expect { + try specializer.specialize(request, with: ["A": .candidate(referenceBox), "B": .metatype(Int.self)]) + } throws: { error in + guard case GenericSpecializer.SpecializerError.candidateRequiresNestedSpecialization = error else { return false } + return true + } + } + + @Test("a missing argument fails the static validation") + func missingArgumentThrows() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "PairBox") + + #expect(throws: GenericSpecializer.SpecializerError.self) { + try specializer.specialize(request, with: ["A": .metatype(Int.self)]) + } + } + + // MARK: - Preflight: errors + + @Test("AnyObject given a value type is an error") + func anyObjectGivenValueTypeIsAnError() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ClassBound") + + let validation = specializer.staticPreflight(selection: ["A": .metatype(Int.self)], for: request) + + #expect(!validation.isValid) + guard case .layoutRequirementNotSatisfied(let parameterName, _, _)? = validation.errors.first else { + Issue.record("expected a layout error, got \(validation.errors)") + return + } + #expect(parameterName == "A") + } + + @Test("AnyObject given a class passes") + func anyObjectGivenClassPasses() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ClassBound") + let subclass = try candidate(named: "ConstraintSubclass", in: request, parameter: "A") + + let validation = specializer.staticPreflight(selection: ["A": .candidate(subclass)], for: request) + + #expect(validation.isValid, "\(validation.errors)") + } + + @Test("a class the indexer knows outside the base class's subtree is an error") + func classOutsideTheSubtreeIsAnError() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "BaseClassBound") + let unrelated = try #require( + try await GenericSpecializationFixtureIndexers.shared.offline().allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == "ConstraintUnrelated" } + ) + + let validation = specializer.staticPreflight( + selection: ["A": .candidate(.init(typeName: unrelated.typeName, source: .image(GenericSpecializationFixture.moduleName)))], + for: request + ) + + #expect(!validation.isValid) + #expect(validation.errors.contains { if case .baseClassRequirementNotSatisfied = $0 { return true } else { return false } }) + } + + @Test("a subclass of the base class passes") + func subclassPasses() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "BaseClassBound") + let subclass = try candidate(named: "ConstraintSubclass", in: request, parameter: "A") + + let validation = specializer.staticPreflight(selection: ["A": .candidate(subclass)], for: request) + + #expect(validation.isValid, "\(validation.errors)") + #expect(validation.warnings.isEmpty, "\(validation.warnings)") + } + + @Test("a host class whose superclass chain misses the base class is an error") + func hostClassOutsideTheSubtreeIsAnError() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "BaseClassBound") + + let validation = specializer.staticPreflight(selection: ["A": .metatype(HostUnrelatedClass.self)], for: request) + + #expect(validation.errors.contains { if case .baseClassRequirementNotSatisfied = $0 { return true } else { return false } }) + } + + @Test("a same-type requirement on a member the argument contradicts is an error") + func contradictedSameTypeIsAnError() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ElementSameType") + + let validation = specializer.staticPreflight(selection: ["A": .metatype([String].self)], for: request) + + #expect(!validation.isValid) + guard case .sameTypeRequirementNotSatisfied(let parameterName, let expectedType, let actualType)? = validation.errors.first else { + Issue.record("expected a same-type error, got \(validation.errors)") + return + } + #expect(parameterName == "A.Element") + #expect(expectedType == "Swift.Int") + #expect(actualType == "Swift.String") + } + + @Test("a same-type requirement on a member the argument satisfies passes") + func satisfiedSameTypePasses() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ElementSameType") + + let validation = specializer.staticPreflight(selection: ["A": .metatype([Int].self)], for: request) + + #expect(validation.isValid, "\(validation.errors)") + #expect(validation.warnings.isEmpty, "\(validation.warnings)") + } + + // MARK: - Preflight: warnings + + @Test("a conformance the indexed images record passes without a warning") + func recordedConformancePasses() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ProtocolBound") + let marked = try candidate(named: "FixtureMarked", in: request, parameter: "A") + + let validation = specializer.staticPreflight(selection: ["A": .candidate(marked)], for: request) + + #expect(validation.isValid) + #expect(validation.warnings.isEmpty, "\(validation.warnings)") + } + + @Test("a conformance no indexed image records is a warning, not an error") + func unrecordedConformanceIsAWarning() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ProtocolBound") + + let validation = specializer.staticPreflight(selection: ["A": .metatype(HostUnmarked.self)], for: request) + + #expect(validation.isValid) + guard case .conformanceCheckFailed(let parameterName, let protocolName, _)? = validation.warnings.first else { + Issue.record("expected a conformance warning, got \(validation.warnings)") + return + } + #expect(parameterName == "A") + #expect(protocolName == "\(Self.moduleName).FixtureMarker") + } + + @Test("a member conformance is checked through the projected member") + func memberConformanceIsCheckedThroughTheProjection() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ElementHashable") + + let satisfied = specializer.staticPreflight(selection: ["A": .metatype([Int].self)], for: request) + let unproven = specializer.staticPreflight(selection: ["A": .metatype([HostUnmarked].self)], for: request) + + #expect(satisfied.isValid && satisfied.warnings.isEmpty, "\(satisfied.warnings)") + #expect(unproven.isValid) + #expect(unproven.warnings.contains { if case .conformanceCheckFailed(let parameterName, _, _) = $0 { return parameterName == "A.Element" } else { return false } }, "\(unproven.warnings)") + } + + @Test("violations stop the specialization") + func violationsStopTheSpecialization() async throws { + let (specializer, request) = try await offlineRequest(forTypeNamed: "ClassBound") + + #expect(throws: GenericSpecializer.SpecializerError.self) { + try specializer.specialize(request, with: ["A": .metatype(Int.self)]) + } + } +} diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift new file mode 100644 index 000000000..ee4bca8f9 --- /dev/null +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkOwnerLayoutDepthTests.swift @@ -0,0 +1,32 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftThunkAnalysis +import MachOTestingSupport + +/// An accessor thunk reads its owner's generic arguments out of one buffer, +/// and `AccessorThunkOwnerLayout` names the k-th word as the parameter it +/// carries — by `(depth, index)`, the coordinates the thunk's type nodes are +/// built with and the field records use. A depth counts only the contexts +/// that declare parameters. +/// +/// The layout used to open a depth for every generic ancestor, so +/// `InnerElement` in `DepthOuter.Middle.Inner` — +/// the second word — read as `(2, 0)`, a +/// parameter no field names, instead of `(1, 0)`. +@Suite +struct AccessorThunkOwnerLayoutDepthTests { + @Test("a word behind a level that declares no parameter names the next depth") + func wordBehindNonDeclaringLevel() throws { + let machOFile = try GenericSpecializationFixture.machOFile() + let descriptor = try GenericSpecializationFixture.typeContextDescriptor(named: "Inner", in: machOFile) + let layout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile.context)) + + let firstPosition = try #require(layout.genericParameterPosition(ofKeyArgumentAt: 0)) + let secondPosition = try #require(layout.genericParameterPosition(ofKeyArgumentAt: 1)) + #expect(firstPosition.depth == 0 && firstPosition.index == 0) + #expect(secondPosition.depth == 1 && secondPosition.index == 0) + } +} From 4661eb426fc4cc033bd6b76c27973d5994d67900 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:50:50 +0800 Subject: [PATCH 13/49] fix: group an opaque type's generic arguments by its descriptor's depths An opaque type reference carries one generic argument list per declaration around the opaque result, outermost first, and the mangler writes a list for every such declaration: an empty one for a level that declares no parameter (ASTMangler::appendBoundGenericArgs). The rewriter took a list's position for its depth, so every list after a non-generic level was read as one level further out. The argument of a generic function in a non-generic type was looked up in the empty list and never substituted - Xcodes' MainToolbarModifier.Body printed SwiftUI.TupleToolbarContent - and an inner level took an outer level's argument, printing a real but wrong type. The runtime's resolveOpaqueType flattens the lists and regroups them by the descriptor's own depths (_gatherGenericParameters). opaqueTypeGenericArgumentsByDepth now does the same with the opaque type descriptor's GenericParameterDepthLayout, which ReadOpaqueType already computes. Without a layout the lists stay keyed by position, which the reference spelling, flattening them anyway, still relies on. OpaqueTypeArgumentDepthTests failed before (ProbeWrapper and ProbePair) and passes now. PR #131 review finding 1; the bug predates the PR. --- .../Extensions/Node+OpaqueType.swift | 43 ++++- .../OpaqueTypeArgumentDepthTests.swift | 182 ++++++++++++++++++ 2 files changed, 219 insertions(+), 6 deletions(-) create mode 100644 Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift index 9834fbe38..a07fa5e3b 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift @@ -38,7 +38,7 @@ package typealias OpaqueTypeDegradationReporter = @Sendable (any Error) -> Void extension Node { /// The generic arguments an `opaqueType` node carries, keyed by the depth - /// each level substitutes. + /// of the parameter each one binds. /// /// Internal rather than private for the same reason the rewriter below is: /// reaching this through `resolveOpaqueType(in:)` needs a binary that @@ -47,10 +47,26 @@ extension Node { /// leaves a parameter unsubstituted (printing `A` / `A1`) or substitutes a /// type belonging to a different parameter, and neither raises. /// - /// The walk mirrors `TypeDecoder.decodeMangledType`'s over the same child, - /// including its stop at the first level that is not a `typeList`. - static func opaqueTypeGenericArgumentsByDepth(of opaqueTypeNode: Node) -> OrderedDictionary { + /// The node spells one argument list per declaration around the opaque + /// result, outermost first, and the mangler writes a list for EVERY such + /// declaration — an empty one for a level that declares no parameter + /// (`ASTMangler::appendBoundGenericArgs`). A list's position is therefore + /// not its depth: the runtime flattens the lists and regroups them by the + /// descriptor's own depths (`resolveOpaqueType` → + /// `_gatherGenericParameters`), and so does this, given the opaque type + /// descriptor's `depthLayout`. Keyed by position instead, the argument of + /// a generic function in a non-generic type was looked up in the type's + /// empty list and never substituted (Xcodes' `MainToolbarModifier.Body` + /// printed `SwiftUI.TupleToolbarContent`). Without a layout the lists + /// stay keyed by position, which is right whenever no level around the + /// result is non-generic. + /// + /// The walk over the lists mirrors `TypeDecoder.decodeMangledType`'s over + /// the same child, including its stop at the first level that is not a + /// `typeList`. + static func opaqueTypeGenericArgumentsByDepth(of opaqueTypeNode: Node, depthLayout: GenericParameterDepthLayout? = nil) -> OrderedDictionary { var argumentsByDepth: OrderedDictionary = [:] + var flattenedArguments: [Node] = [] guard let rootTypeListNode = opaqueTypeNode[safeChild: 2] else { return argumentsByDepth } for (depth, typeListNode) in rootTypeListNode.children.enumerated() { guard typeListNode.isKind(of: .typeList) else { break } @@ -63,8 +79,17 @@ extension Node { // parameter read whatever preorder left at its index: the element // to its left, or a fragment of that element's subtree. argumentsByDepth[depth] = Array(typeListNode.children) + flattenedArguments.append(contentsOf: typeListNode.children) + } + guard let depthLayout else { return argumentsByDepth } + var argumentsByParameterDepth: OrderedDictionary = [:] + for (flatIndex, argument) in flattenedArguments.enumerated() { + // More arguments than the descriptor has parameters: a list this + // walk misread, so the positional reading is the one left. + guard let position = depthLayout.position(ofParameterAt: flatIndex) else { return argumentsByDepth } + argumentsByParameterDepth[position.depth, default: []].append(argument) } - return argumentsByDepth + return argumentsByParameterDepth } /// Substitutes an opaque type's generic parameters with the concrete @@ -412,7 +437,7 @@ extension Node { // carries ordinal 0, so this is correctness for a shape // those two do not have and a client binary may. let ordinal: Int = node[safeChild: 1]?.index?.cast() ?? 0 - let allTypeList = Node.opaqueTypeGenericArgumentsByDepth(of: node) + let allTypeList = Node.opaqueTypeGenericArgumentsByDepth(of: node, depthLayout: readOpaqueType.depthLayout) guard let underlyingTypeArgumentMangledName = opaqueType.underlyingTypeArgumentMangledNames[safe: ordinal] else { return nil } let underlyingTypeArgumentNode: Node? if machO is MachOImage { @@ -688,14 +713,20 @@ extension Node { fileprivate struct ReadOpaqueType { let opaqueType: OpaqueType let ownerLayout: AccessorThunkOwnerLayout + /// How the descriptor's parameters split into depths: what regroups the + /// argument lists of a reference to it (`opaqueTypeGenericArgumentsByDepth`). + /// `nil` for a descriptor with no generic context. + let depthLayout: GenericParameterDepthLayout? init(_ opaqueType: OpaqueType, in context: some ReadingContext) { self.opaqueType = opaqueType if let genericContext = opaqueType.genericContext { let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .opaqueType(opaqueType.descriptor), in: context) self.ownerLayout = AccessorThunkOwnerLayout(genericContext: genericContext, depthLayout: depthLayout) + self.depthLayout = depthLayout } else { self.ownerLayout = AccessorThunkOwnerLayout(genericContext: nil as GenericContext?) + self.depthLayout = nil } } } diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift new file mode 100644 index 000000000..7061c1db4 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift @@ -0,0 +1,182 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftDeclarationRendering +import Demangling +@_spi(Internals) import SwiftInspection +@_spi(Internals) import MachOSymbols + +/// An opaque type reference spells its generic arguments as one list per +/// declaration around the opaque result, outermost first, and the mangler +/// writes a list for EVERY such declaration — an empty one for a level that +/// declares no parameter (`ASTMangler::appendBoundGenericArgs`). A parameter's +/// depth counts only the levels that declare parameters, so a list's position +/// is not its depth: the runtime flattens the lists and regroups them by the +/// descriptor's own depths (`resolveOpaqueType` → `_gatherGenericParameters`). +/// +/// Taking the position for the depth left the parameter of a generic function +/// in a non-generic type unsubstituted — Xcodes' `MainToolbarModifier.Body` +/// printed `SwiftUI.TupleToolbarContent` inside a type that has no +/// parameters — and, with a generic type nested in a non-generic one, read the +/// type's argument as the function's: a real, wrong type. +/// +/// Driven through `resolveOpaqueType(in:)` on a hand-built node, as +/// `OpaqueTypeOrdinalTests` does: the compiler substitutes an opaque type it +/// can see through into the module's own reflection records, so a fixture +/// cannot produce a record that still references the descriptor. The node +/// carries the argument lists the mangler writes for these declarations. +@Suite +struct OpaqueTypeArgumentDepthTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "opaque-type-argument-depth fixture compilation failed:\n\(diagnostics)" } + } + + private static let moduleName = "OpaqueTypeArgumentDepthFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + /// + /// `ProbeNamespace` declares no parameter, so the mangler writes an empty + /// list for it in front of every list below it: `makeWrapper`'s lists are + /// `[[], [Element]]`, and `Box.makePair`'s are `[[], [Boxed], [Extra]]`. + private static let fixtureSource = """ + public final class FixtureAnchor {} + + public protocol ProbeShape {} + + public struct ProbeWrapper: ProbeShape { + public var wrapped: Wrapped + public init(wrapped: Wrapped) { self.wrapped = wrapped } + } + + public struct ProbePair: ProbeShape { + public var first: First + public var second: Second + public init(first: First, second: Second) { + self.first = first + self.second = second + } + } + + public enum ProbeNamespace { + public static func makeWrapper(_ element: Element) -> some ProbeShape { + ProbeWrapper(wrapped: element) + } + + public struct Box { + public var boxed: Boxed + public init(boxed: Boxed) { self.boxed = boxed } + + public func makePair(_ extra: Extra) -> some ProbeShape { + ProbePair(first: boxed, second: extra) + } + } + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private func loadFixtureMachOFile() throws -> MachOFile { + let libraryURL = try Self.fixtureCompilationResult.get() + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + /// The offset of the opaque type descriptor of the declaration named + /// `declarationName`, found by its demangled symbol. + private func opaqueTypeDescriptorOffset(ofDeclarationNamed declarationName: String, in machOFile: MachOFile) throws -> Int { + let symbols = SymbolIndexStore.shared.symbols(of: .opaqueTypeDescriptor, in: machOFile) + let symbol = symbols.first { $0.demangledNode.materialize().print(using: .default).contains(declarationName) } + return try #require(symbol, "no opaque type descriptor names \(declarationName): \(symbols.map { $0.demangledNode.materialize().print(using: .default) })").offset + } + + /// The underlying type of `declarationName`'s opaque result, resolved for + /// a reference carrying `argumentListsByLevel` — one list per declaration + /// around the result, as the mangler writes them. + private func resolvedUnderlyingType(ofDeclarationNamed declarationName: String, argumentListsByLevel: [[Node]]) async throws -> String { + let machOFile = try loadFixtureMachOFile() + let descriptorOffset = try opaqueTypeDescriptorOffset(ofDeclarationNamed: declarationName, in: machOFile) + let opaqueTypeNode = Node.create( + kind: .type, + children: [ + Node.create( + kind: .opaqueType, + children: [ + Node.create(kind: .opaqueTypeDescriptorSymbolicReference, index: UInt64(descriptorOffset)), + Node.create(kind: .index, index: 0), + Node.create(kind: .typeList, children: argumentListsByLevel.map { Node.create(kind: .typeList, children: $0) }), + ] + ), + ] + ) + return await (try opaqueTypeNode.resolveOpaqueType(in: machOFile)).print(using: DemangleOptions.default) + } + + @Test("a generic function's argument is substituted when its type declares no parameter") + func argumentOfAGenericFunctionInANonGenericTypeIsSubstituted() async throws { + let integerType = try await demangleAsNode("Si", isType: true) + + let resolved = try await resolvedUnderlyingType(ofDeclarationNamed: "makeWrapper", argumentListsByLevel: [[], [integerType]]) + + #expect(resolved == "\(Self.moduleName).ProbeWrapper") + } + + @Test("each argument substitutes its own parameter when a level declaring none comes first") + func eachArgumentSubstitutesItsOwnParameter() async throws { + let integerType = try await demangleAsNode("Si", isType: true) + let stringType = try await demangleAsNode("SS", isType: true) + + let resolved = try await resolvedUnderlyingType(ofDeclarationNamed: "makePair", argumentListsByLevel: [[], [integerType], [stringType]]) + + #expect(resolved == "\(Self.moduleName).ProbePair") + } +} From c8cf653d69227be129f4c6ff5fedcc5e98ab6ed7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:50:50 +0800 Subject: [PATCH 14/49] fix: count an opaque parameter's depth from its type or extension MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The opaque type provider counted the depths around an opaque result as the parent levels that grow the parameter count. An extension of a nested generic type brings several depths at once - `extension Outer.SecondMiddle where A: Hashable` brings Outer's A and SecondMiddle's C - and was counted as one, so a constraint on τ_2_0 lay beyond the computed depth: a debug build trapped in the provider, and a release build printed a bare `some`. Take the depth count of the nearest type or extension up the descriptor's parent chain from GenericParameterDepthLayout, which splits an extension by the type it extends, as the runtime's _gatherGenericParameterCounts does. An anonymous context in between is where a generic declaration's own signature lives and is passed over: its depth is the one declaresOwnGenericParameters adds. OpaqueParameterInMultiDepthExtensionTests trapped before and passes now. PR #131 review finding 8; the bug predates the PR. --- ...ftInterfaceBuilderOpaqueTypeProvider.swift | 45 +++++-- ...eParameterInMultiDepthExtensionTests.swift | 127 ++++++++++++++++++ 2 files changed, 159 insertions(+), 13 deletions(-) create mode 100644 Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift index 3378a1ae8..a61ae216d 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift @@ -208,12 +208,17 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider inheritedParameterCount { - enclosingDepthCount += 1 - inheritedParameterCount = parameters.count - } - let opaqueParameterDepth = enclosingDepthCount + (Self.declaresOwnGenericParameters(node) ? 1 : 0) + let opaqueParameterDepth = enclosingDepthCount(of: opaqueType) + (Self.declaresOwnGenericParameters(node) ? 1 : 0) var constraintsByParameter: [GenericParameterCoordinate: OpaqueParameterConstraints] = [:] for requirement in requirements { @@ -269,6 +268,26 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider Int { + var parent = (try? opaqueType.descriptor.parent(in: machO.context))?.flatMap(\.resolved) + while let currentParent = parent { + switch currentParent { + case .type, .extension: + return (try? GenericParameterDepthLayout.make(for: currentParent, in: machO.context))?.depthCount ?? 0 + default: + parent = (try? currentParent.parent(in: machO.context))?.flatMap(\.resolved) + } + } + return 0 + } + /// Whether the declaration introduces generic parameters of its own: its /// type is wrapped in a `dependentGenericType`. The entity is unwrapped /// first so a `static` or accessor wrapper does not hide it; a constrained diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift new file mode 100644 index 000000000..a495e47cb --- /dev/null +++ b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift @@ -0,0 +1,127 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Support) @testable import SwiftInterface + +/// `SwiftInterfaceBuilderOpaqueTypeProvider` finds an opaque result's +/// constraint at the depth of the opaque parameters, which it counts from the +/// descriptor's parent chain: one depth per ancestor whose generic context +/// adds parameters. An extension of a nested generic type adds two depths at +/// once — `extension Outer.SecondMiddle where A: Hashable` carries `Outer`'s +/// `A` and `SecondMiddle`'s `C` — so the count came out one short, and the +/// constraint on `τ_2_0` lay beyond it. A debug build trapped on the +/// `assertionFailure` that guards that impossible depth; a release build +/// printed a bare `some`. The runtime counts depths through the extended +/// type for exactly this reason (`_gatherGenericParameterCounts`). +/// +/// An exit test, because the defect traps. +@Suite(.serialized) +struct OpaqueParameterInMultiDepthExtensionTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Error, CustomStringConvertible { + let diagnostics: String + var description: String { "opaque-parameter extension-depth fixture compilation failed:\n\(diagnostics)" } + } + + private struct MissingConstraint: Error, CustomStringConvertible { + let interface: String + var description: String { "the opaque result did not print its constraint:\n\(interface)" } + } + + /// The class is ballast: a struct-only fixture dylib has no `__DATA` + /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. + private static let source = """ + public final class FixtureAnchor {} + + public struct Outer { + public struct SecondMiddle { + public init() {} + } + } + + extension Outer.SecondMiddle where A: Hashable { + public var body: some Sequence { [1] } + + // A generic declaration's signature lives in an anonymous context + // between the descriptor and the extension: one depth more. + public func elements(_ element: Element) -> some Sequence { [element] } + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("OpaqueParameterExtensionDepthFixture-\(UUID().uuidString)") + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + let sourceURL = workingDirectory.appendingPathComponent("OpaqueParameterExtensionDepth.swift") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueExtensionDepth.dylib") + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeOpaqueExtensionDepth", + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + /// The fixture's interface with the opaque type provider attached, as + /// `interface --parse-opaque-return-type` and RuntimeViewer print it; it + /// throws unless the opaque result names its constraint. + static func printInterfaceNamingTheOpaqueConstraint() async throws { + let libraryURL = try fixtureCompilationResult.get() + let machOFile: MachOFile + switch try File.loadFromFile(url: libraryURL) { + case .machO(let file): + machOFile = file + case .fat(let fatFile): + machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + try await builder.prepare() + let interface = try await builder.printRoot().string + guard interface.contains("var body: some Swift.Sequence {"), interface.contains("func elements(_: A2) -> some Swift.Sequence") else { + throw MissingConstraint(interface: interface) + } + } + + @Test("opaque results in an extension spanning two depths name their constraints") + func opaqueResultsInAnExtensionSpanningTwoDepthsNameTheirConstraints() async { + await #expect(processExitsWith: .success) { + do { + try await OpaqueParameterInMultiDepthExtensionTests.printInterfaceNamingTheOpaqueConstraint() + } catch { + // An error thrown out of an exit test ends the child on a + // trap too; exiting keeps a missing constraint apart from the + // provider's own trap. + exit(EXIT_FAILURE) + } + } + } +} From 7d7ffd41ca442dc2d0e3d0d6a97651605de9ce86 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:50:50 +0800 Subject: [PATCH 15/49] fix: name a thunk's type declared in a generic extension ThunkTypeNodeBuilder bound the arguments a kind-9 accessor thunk passes by walking the type contexts and counting each level's own key parameters. An extension context is no type level of that walk, so the accessor of `extension Outer where A: Hashable { struct Inner }`, which takes A and B, counted one parameter, the counts did not match, and the field printed as `accessor function at ...`. When every parameter of the type's whole generic context takes a key argument, the arguments are one per parameter: group them with GenericParameterDepthLayout and name the instantiation the way the runtime does (SymbolicDemangler.instantiatedTypeNode). Otherwise keep the walk. It is what names a type in a same-type-constrained extension, which receives its own parameters' arguments alone; replacing the walk outright turned that field into `accessor function at ...` as well, so a guard test pins the shape. AccessorThunkTypeInGenericExtensionTests: the first test failed before and passes now; the guard test passes before and after, and failed on the replacement. PR #131 review finding 13; the bug predates the PR. --- .../Resolution/ThunkTypeNodeBuilder.swift | 40 ++++- ...ssorThunkTypeInGenericExtensionTests.swift | 155 ++++++++++++++++++ 2 files changed, 190 insertions(+), 5 deletions(-) create mode 100644 Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift diff --git a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift index 370137c2c..a88cd0030 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift @@ -19,9 +19,12 @@ fileprivate protocol ThunkTypeNodeBuildingLogging {} /// the existing substitution rewrites it into the concrete argument. A /// mangled name is demangled. A specialized accessor's symbol is demangled /// and the type it is the accessor *for* taken. And an accessor applied to -/// arguments becomes the accessor's nominal type with a `boundGeneric*` -/// wrapper per generic level of its declaration chain, the way the demangler -/// itself spells `Outer.Inner`. +/// arguments becomes the accessor's type bound to them: named the way the +/// runtime names the instantiation when they are one per parameter of the +/// type's whole context — `Outer.Inner`, an extension context +/// and the type it extends included — and otherwise wrapped in a +/// `boundGeneric*` node per generic level of its declaration chain, the way +/// the demangler itself spells it. package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { package let machO: MachOFile package let environment: MachOThunkEnvironment @@ -91,17 +94,44 @@ package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { } } + /// The accessor's type bound to the arguments the thunk passed it. + /// + /// When every parameter of the type's whole generic context takes a key + /// argument, the arguments are one per parameter: grouped by + /// `GenericParameterDepthLayout`, they name the instantiation the way the + /// runtime does (`SymbolicDemangler.instantiatedTypeNode`). Both count + /// what the walk of the type contexts below misses — the parameters an + /// extension context brings (`extension Outer where A: Hashable { struct + /// Inner }` takes `A` and `B`), which left such a type unnamed, its + /// field `accessor function at …`. + /// + /// Otherwise the walk of the type contexts binds each level's own key + /// parameters. It is what names a type in a same-type-constrained + /// extension — `extension Outer where A == Int { struct Inner }` + /// receives the argument of `B` alone and reads + /// `Outer< where A == Swift.Int>.Inner<…>` — since an extension's + /// parameters are no type level of the walk. private func boundTypeNode(accessorAddress: UInt64, typeArguments: [ThunkTypeExpression]) -> Node? { guard let origin = environment.accessorOriginsByAddress[accessorAddress] else { return nil } do { let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: origin.descriptorOffset, in: origin.machO.context) - let unboundNode = try SymbolicDemangler.demangleContext(for: descriptor, in: origin.machO.context) - guard let keyParameterCountsByLevel = try keyParameterCountsByNominalLevel(of: descriptor, in: origin.machO) else { return nil } var argumentNodes: [Node] = [] for typeArgument in typeArguments { guard let argumentNode = typeNode(for: typeArgument) else { return nil } argumentNodes.append(argumentNode) } + if let typeDescriptor = descriptor.typeContextDescriptorWrapper, + let genericContext = try typeDescriptor.genericContext(in: origin.machO.context), + genericContext.parameters.allSatisfy(\.hasKeyArgument) { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: descriptor, in: origin.machO.context) + guard let argumentsByDepth = depthLayout.grouped(argumentNodes) else { + #log(.info, "accessor at 0x\(String(accessorAddress, radix: 16), privacy: .public) takes \(depthLayout.parameterCount, privacy: .public) type arguments, \(argumentNodes.count, privacy: .public) were named") + return nil + } + return enveloped(try SymbolicDemangler.instantiatedTypeNode(for: typeDescriptor, binding: GenericArgumentBinding(argumentsByDepth: argumentsByDepth), in: origin.machO.context)) + } + let unboundNode = try SymbolicDemangler.demangleContext(for: descriptor, in: origin.machO.context) + guard let keyParameterCountsByLevel = try keyParameterCountsByNominalLevel(of: descriptor, in: origin.machO) else { return nil } guard keyParameterCountsByLevel.reduce(0, +) == argumentNodes.count else { #log(.info, "accessor at 0x\(String(accessorAddress, radix: 16), privacy: .public) takes \(keyParameterCountsByLevel.reduce(0, +), privacy: .public) type arguments, \(argumentNodes.count, privacy: .public) were named") return nil diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift new file mode 100644 index 000000000..10865c71f --- /dev/null +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift @@ -0,0 +1,155 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import Demangling +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering +@testable import SwiftThunkAnalysis + +/// A kind-9 accessor thunk names the type it instantiates by the accessor it +/// calls: the type's descriptor, and one key argument per generic parameter +/// of the type's whole context. The node builder counted the parameters of the +/// type contexts on the declaration chain only and stopped at any other parent +/// — an extension — so a generic type declared in a generic extension +/// (`extension Outer where A: Hashable { struct Inner }`) counted one key +/// parameter where its accessor takes two, `Outer`'s `A` and its own `B`. The +/// field read `accessor function at …` in dump and interface. The extension +/// walk `GenericArgumentEnvironment` gained in evolution proposal +/// `offline-generic-specialization` is the reading side of the same shape. +@Suite(.serialized) +struct AccessorThunkTypeInGenericExtensionTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Error, CustomStringConvertible { + let diagnostics: String + var description: String { "accessor-thunk generic-extension fixture compilation failed:\n\(diagnostics)" } + } + + /// `Inner` is `~Copyable`, so a field of it is instantiated by a thunk + /// that first asks whether the runtime supports noncopyable types — a + /// kind-9 accessor function reference in the field record. The class is + /// ballast: a struct-only fixture dylib has no `__DATA` segment, which + /// older MachOKit releases mis-walked. + private static let fixtureSource = """ + public final class FixtureAnchor {} + + public struct Outer {} + + extension Outer where A: Hashable { + public struct Inner: ~Copyable { + public var value: Int + } + } + + public struct Holder: ~Copyable { + public var inner: Outer.Inner + } + + public struct SameTypeOuter {} + + extension SameTypeOuter where A == Int { + public struct Inner: ~Copyable { + public var value: Int + } + } + + public struct SameTypeHolder: ~Copyable { + public var inner: SameTypeOuter.Inner + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("AccessorThunkGenericExtensionFixture-\(UUID().uuidString)") + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + let sourceURL = workingDirectory.appendingPathComponent("AccessorThunkGenericExtension.swift") + let libraryURL = workingDirectory.appendingPathComponent("libProbeThunkExtension.dylib") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + // Optimized so the thunk takes the shape a shipping binary carries. + process.arguments = [ + "swiftc", "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeThunkExtension", + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private func loadFixture() throws -> MachOFile { + let libraryURL = try Self.fixtureCompilationResult.get() + switch try File.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + } + + /// The `inner` field's type of the holder named `holderName`, read + /// through the entry the indexer uses for a kind-9 field: the thunk's + /// arguments named as the holder's parameters. + private func resolvedInnerFieldType(ofHolderNamed holderName: String) throws -> String { + let machOFile = try loadFixture() + let holder = try #require( + try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == holderName } + ) + let genericContext = try #require(try holder.typeContextDescriptor.genericContext(in: machOFile.context)) + let ownerLayout = AccessorThunkOwnerLayout( + genericContext: genericContext, + depthLayout: GenericParameterDepthLayout.make(for: genericContext, ownedBy: holder.asContextDescriptorWrapper, in: machOFile.context) + ) + let record = try #require( + try holder.typeContextDescriptor.fieldDescriptor(in: machOFile.context).records(in: machOFile.context).first { try $0.fieldName(in: machOFile.context) == "inner" } + ) + let typeNode = try SymbolicDemangler.demangleType(for: try record.mangledTypeName(in: machOFile.context), in: machOFile.context) + try #require(typeNode.contains(.accessorFunctionReference), "the field must be read through a thunk for this test to mean anything: \(typeNode.print(using: .default))") + return typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout).print(using: .default) + } + + @Test("a thunk instantiating a generic type declared in a generic extension is named") + func thunkInstantiatingATypeInAGenericExtensionIsNamed() throws { + let fieldType = try resolvedInnerFieldType(ofHolderNamed: "Holder") + + #expect(!fieldType.contains("accessor function"), "\(fieldType)") + #expect(fieldType.contains("Outer") && fieldType.contains("Inner"), "\(fieldType)") + } + + /// A type in a same-type-constrained extension receives the arguments of + /// its own parameters alone — the parameter the extension fixes takes no + /// key argument — and the walk of the type contexts names it. Naming the + /// instantiation from the whole context cannot, so it must not take over + /// there: doing so turned this field into `accessor function at …`. + @Test("a thunk instantiating a generic type declared in a same-type-constrained extension stays named") + func thunkInstantiatingATypeInASameTypeConstrainedExtensionStaysNamed() throws { + let fieldType = try resolvedInnerFieldType(ofHolderNamed: "SameTypeHolder") + + #expect(!fieldType.contains("accessor function"), "\(fieldType)") + #expect(fieldType.contains("SameTypeOuter< where A == Swift.Int>.Inner"), "\(fieldType)") + } +} From ad4f33b33a1b050c45481f89e0c94972ea9ef679 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:50:50 +0800 Subject: [PATCH 16/49] fix: walk the superclass chain in the offline base-class check The offline check took ConformanceProvider.subclasses(of:) for proof. That class hierarchy links only indexed Swift classes, so a Swift class below an Objective-C class - FixtureOperation: Operation for - fell out of the subtree, and as the class itself was indexed, the check reported a definite violation: staticPreflight failed and specialize threw, where the runtime accepts the selection. Walk up the superclass chain the indexed images describe instead, comparing unbound class names. Reaching the base proves the requirement, a root class reached without it proves the violation, and a link no indexed image describes - an Objective-C class, or a class of an image the indexer does not hold - only warns. ConformanceProvider gains superclassLink(of:), defaulting to .unknown, and the public SuperclassLink enum; the warning branch no input reached goes. OfflineObjectiveCBaseClassTests failed before and passes now. PR #131 review finding 2. --- .../ConformanceProvider.swift | 63 ++++++++- ...ericSpecializer+StaticSpecialization.swift | 36 +++-- .../OfflineObjectiveCBaseClassTests.swift | 129 ++++++++++++++++++ 3 files changed, 211 insertions(+), 17 deletions(-) create mode 100644 Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift diff --git a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift index 79efaa8d3..56a4584ae 100644 --- a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift +++ b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift @@ -49,6 +49,23 @@ public protocol ConformanceProvider: Sendable { /// no class-hierarchy knowledge degrade to "show every candidate" /// without breaking the contract. func subclasses(of baseClassName: TypeName) -> [TypeName] + + /// What the provider knows of the class `className` inherits from + /// directly — the link the offline base-class check walks up (evolution + /// proposal `offline-generic-specialization`). Default `.unknown`: a + /// provider without class-hierarchy knowledge proves nothing either way. + func superclassLink(of className: TypeName) -> SuperclassLink +} + +/// A class's direct superclass, as a `ConformanceProvider` knows it. +public enum SuperclassLink: Sendable, Equatable { + /// The provider describes the class, and it inherits from this class. + case inherits(from: TypeName) + /// The provider describes the class, and it has no superclass. + case root + /// The provider holds no description of the class: an Objective-C + /// class, or a class of an image it does not index. + case unknown } // MARK: - Default Implementations @@ -78,6 +95,10 @@ extension ConformanceProvider { public func subclasses(of baseClassName: TypeName) -> [TypeName] { [] } + + public func superclassLink(of className: TypeName) -> SuperclassLink { + .unknown + } } // MARK: - IndexerConformanceProvider @@ -111,6 +132,9 @@ public final class IndexerConformanceProvider SuperclassLink { + guard className.kind == .class else { return .unknown } + return classHierarchy().superclassLinkByClassName[className.name] ?? .unknown + } + /// Build (or fetch from cache) the parent-name → direct-subclasses - /// map by walking every indexed `.class` definition's + /// map, and the class-name → superclass map that reads the same links + /// the other way, by walking every indexed `.class` definition's /// `superclassType` link. Lock-protected so concurrent first-callers /// don't both pay the O(n) build cost. - private func directChildrenMap() -> [String: [TypeName]] { + private func classHierarchy() -> (directChildrenByParentName: [String: [TypeName]], superclassLinkByClassName: [String: SuperclassLink]) { subclassCache.lock.lock() defer { subclassCache.lock.unlock() } - if let cached = subclassCache.directChildrenByParentName { return cached } + if let cachedChildren = subclassCache.directChildrenByParentName, let cachedLinks = subclassCache.superclassLinkByClassName { + return (cachedChildren, cachedLinks) + } var map: [String: [TypeName]] = [:] + var links: [String: SuperclassLink] = [:] for (childTypeName, entry) in indexer.allAllTypeDefinitions { guard childTypeName.kind == .class else { continue } guard case .class(let classDescriptor) = entry.value.typeContextDescriptorWrapper else { continue } @@ -212,14 +245,18 @@ extension IndexerConformanceProvider: ConformanceProvider { } // A missing / unreadable superclass link is the ordinary "this class - // has no usable parent" case and stays silent. + // has no usable parent" case and stays silent. Missing is a root + // class; unreadable stays unknown, proving nothing. var superNode: Node? do { superNode = try classWrapper.superclassNode(in: entry.machO.context) } catch { continue } - guard let superNode else { continue } + guard let superNode else { + links[childTypeName.name] = .root + continue + } // `SymbolicDemangler.demangleType` may wrap the result in a // `.type` node or return a deeper tree depending on the @@ -240,10 +277,12 @@ extension IndexerConformanceProvider: ConformanceProvider { } let superTypeName = TypeName(node: InternedNodeReferenceCache.shared.reference(interning: superNode, in: entry.machO), kind: .class) map[superTypeName.name, default: []].append(childTypeName) + links[childTypeName.name] = .inherits(from: superTypeName) } subclassCache.directChildrenByParentName = map - return map + subclassCache.superclassLinkByClassName = links + return (map, links) } } @@ -333,6 +372,16 @@ public struct CompositeConformanceProvider: ConformanceProvider { } return result } + + /// The first provider that describes the class answers: a class lives in + /// one image, so at most one sub-indexer knows its superclass link. + public func superclassLink(of className: TypeName) -> SuperclassLink { + for provider in providers { + let link = provider.superclassLink(of: className) + if link != .unknown { return link } + } + return .unknown + } } // MARK: - EmptyConformanceProvider diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift index da0953723..fad33706f 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift @@ -463,17 +463,33 @@ extension GenericSpecializer where MachO == MachOFile { builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) return } - let subtree = conformanceProvider.subclasses(of: expectedClassName) - guard !subtree.isEmpty else { - builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: the indexed images describe no class hierarchy under \(expectedDisplay)")) - return - } - if subtree.contains(where: { $0.name == actualTypeName.name }) { return } - if conformanceProvider.typeDefinition(for: actualTypeName) != nil { - builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) - } else { - builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: \(subject.display) is in no indexed image, so its superclass chain cannot be read")) + // Up the superclass chain the indexed images describe, class names + // compared unbound. Reaching the base proves the requirement; a root + // class reached without it proves the violation. A link no indexed + // image describes proves nothing either way: an Objective-C class — + // `NSOperation` between a Swift class and an `NSObject` bound — or a + // class of an image the indexer does not hold. Taking that for a + // violation rejected every Swift class below a Cocoa class, which the + // runtime accepts. + var currentClassName = actualTypeName + var visitedClassNames: Set = [] + while visitedClassNames.insert(currentClassName.name).inserted { + if currentClassName.name == expectedClassName.name { return } + switch conformanceProvider.superclassLink(of: currentClassName) { + case .inherits(let superclassName): + currentClassName = unboundNominalTypeName(of: superclassName.node.materialize(), kind: .class) ?? superclassName + case .root: + builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) + return + case .unknown: + let reason = currentClassName.name == actualTypeName.name + ? "offline: \(subject.display) is in no indexed image, so its superclass chain cannot be read" + : "offline: the superclass chain of \(subject.display) leaves the indexed images at \(currentClassName.name), so whether it reaches \(expectedDisplay) cannot be read" + builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: reason)) + return + } } + builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: the superclass chain of \(subject.display) loops back on itself")) } private func checkSameType(of subject: StaticRequirementSubject, requirement: GenericRequirementDescriptor, binding: GenericArgumentBinding, into builder: SpecializationValidation.Builder) { diff --git a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift new file mode 100644 index 000000000..b26bdce21 --- /dev/null +++ b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift @@ -0,0 +1,129 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +import MachOTestingSupport + +/// A base-class requirement on an Objective-C class, checked offline +/// (evolution proposal `offline-generic-specialization`). +/// +/// The offline check reads class hierarchies from the indexed images, and +/// those hold Swift classes only: a Swift class whose superclass is an +/// Objective-C class other than the base — `FixtureOperation: Operation` +/// under an `NSObject` bound — has no indexed link up to the base. The check +/// took that for proof of a violation and rejected the selection, while the +/// runtime accepts it. A chain that leaves the indexed classes is evidence the +/// file does not carry; `staticPreflight` promises a warning for that, never +/// an error. Cocoa bounds — `NSObject`, `NSView`, `UIViewController` — are +/// the most common base-class bounds there are. +@Suite(.serialized) +struct OfflineObjectiveCBaseClassTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "Objective-C base-class fixture compilation failed:\n\(diagnostics)" } + } + + private static let moduleName = "ObjectiveCBaseClassFixture" + + private static let fixtureSource = """ + import Foundation + + public final class FixtureOperation: Operation {} + + public final class FixtureObject: NSObject {} + + public struct ObjectBound { + public var subject: Subject + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private func loadFixtureMachOFile() throws -> MachOFile { + let libraryURL = try Self.fixtureCompilationResult.get() + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + /// The offline specializer over the fixture file, the request for + /// `ObjectBound`, and the candidate for the fixture class `className`. + /// The candidate is built from the indexer's definition rather than taken + /// from the request: the request's list is narrowed by the same indexed + /// hierarchy, so a class below an Objective-C intermediate is not on it. + private func offlineSelection(ofClassNamed className: String) async throws -> (specializer: GenericSpecializer, request: SpecializationRequest, candidate: SpecializationRequest.Candidate) { + let indexer = SwiftDeclarationIndexer(in: try loadFixtureMachOFile()) + try await indexer.prepare() + let boundDefinition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == "ObjectBound" }) + let classDefinition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == className }) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: boundDefinition.typeContextDescriptorWrapper) + return (specializer, request, .init(typeName: classDefinition.typeName, source: .image(Self.moduleName))) + } + + @Test("a Swift class below an Objective-C intermediate is not a base-class violation") + func swiftClassBelowAnObjectiveCIntermediateIsNotAViolation() async throws { + let (specializer, request, operation) = try await offlineSelection(ofClassNamed: "FixtureOperation") + + let validation = specializer.staticPreflight(selection: ["A": .candidate(operation)], for: request) + + #expect(validation.isValid, "\(validation.errors)") + } + + @Test("a Swift class below an Objective-C intermediate specializes offline") + func swiftClassBelowAnObjectiveCIntermediateSpecializes() async throws { + let (specializer, request, operation) = try await offlineSelection(ofClassNamed: "FixtureOperation") + + let result = try specializer.specialize(request, with: ["A": .candidate(operation)]) + + #expect(result.typeName.name(using: .default) == "\(Self.moduleName).ObjectBound<\(Self.moduleName).FixtureOperation>") + } +} From 6c35e8c4b3337335f054a102caa352375349790a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 17/49] fix: bind a parameter tied to another by a same-type requirement When a same-type requirement ties two parameters (`First == Second`), the compiler writes the one that keeps its key argument on the left, and the runtime's _gatherWrittenGenericParameters copies its argument to the right-hand one. fillFixedParameters read the requirement from the left only, so Second was never bound: the offline specialization threw unresolvedFixedParameter, and the runtime one fell back to a flat name, TiedParameterPair, while its header printed the runtime's TiedParameterPair. Read such a requirement both ways. And when naming a runtime specialization still fails, log why before falling back to the flat name, which names no instantiation. GenericSpecializationFixture gains TiedParameterPair. Both TiedParameterInstantiationTests failed before and pass now. PR #131 review findings 3 and 10. --- .../GenericInstantiation.swift | 42 ++++++++++--- .../TypeDefinition+Specialization.swift | 10 ++- .../GenericSpecializationFixture.swift | 9 +++ .../TiedParameterInstantiationTests.swift | 62 +++++++++++++++++++ 4 files changed, 111 insertions(+), 12 deletions(-) create mode 100644 Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift diff --git a/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift index 8fde46b1d..7fee4ffd6 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift @@ -79,6 +79,11 @@ package struct GenericInstantiation { /// requirement that fixes it. A right-hand side can name another fixed /// parameter (`C == B`, `B == Int`), so the requirements are applied until /// no further one resolves. + /// + /// A requirement between two parameters (`First == Second`) is read both + /// ways, as the runtime's `_gatherWrittenGenericParameters` reads it: the + /// compiler writes the parameter that keeps its key argument on the LEFT, + /// so it is the right-hand parameter that takes the left one's argument. private static func fillFixedParameters( _ argumentsByFlatIndex: inout [Node?], depthLayout: GenericParameterDepthLayout, @@ -89,16 +94,26 @@ package struct GenericInstantiation { guard !unresolvedFlatIndices.isEmpty else { return } // The same-type requirements whose subject is a parameter itself, by - // that parameter's position in the cumulative list. + // that parameter's position in the cumulative list; and, for those + // whose right-hand side is a parameter too, the left-hand parameter + // by the right-hand one's position. var fixingRequirementByFlatIndex: [Int: MangledName] = [:] + var leftHandFlatIndexByRightHandFlatIndex: [Int: Int] = [:] for requirement in requirements where requirement.layout.flags.kind == .sameType { guard let subjectNode = try? SymbolicDemangler.demangleType(for: requirement.paramMangledName(in: machO.context), in: machO.context), let position = genericParameterPosition(of: subjectNode), let flatIndex = depthLayout.flatIndex(depth: position.depth, index: position.index), - fixingRequirementByFlatIndex[flatIndex] == nil, let rightHandSide = try? requirement.type(in: machO.context) else { continue } - fixingRequirementByFlatIndex[flatIndex] = rightHandSide + if fixingRequirementByFlatIndex[flatIndex] == nil { + fixingRequirementByFlatIndex[flatIndex] = rightHandSide + } + if let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context), + let rightHandPosition = genericParameterPosition(of: rightHandSideNode), + let rightHandFlatIndex = depthLayout.flatIndex(depth: rightHandPosition.depth, index: rightHandPosition.index), + leftHandFlatIndexByRightHandFlatIndex[rightHandFlatIndex] == nil { + leftHandFlatIndexByRightHandFlatIndex[rightHandFlatIndex] = flatIndex + } } var didResolveParameter = true @@ -106,13 +121,20 @@ package struct GenericInstantiation { didResolveParameter = false let partialBinding = Self.partialBinding(argumentsByFlatIndex, depthLayout: depthLayout) for flatIndex in unresolvedFlatIndices { - guard let rightHandSide = fixingRequirementByFlatIndex[flatIndex], - let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context) - else { continue } - let argument = DependentMemberProjection.projectingConcreteMembers(in: partialBinding.substituting(in: rightHandSideNode), in: machO) - guard !containsGenericParameter(argument) else { continue } - argumentsByFlatIndex[flatIndex] = typeWrapped(argument) - didResolveParameter = true + if let rightHandSide = fixingRequirementByFlatIndex[flatIndex], + let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context) { + let argument = DependentMemberProjection.projectingConcreteMembers(in: partialBinding.substituting(in: rightHandSideNode), in: machO) + if !containsGenericParameter(argument) { + argumentsByFlatIndex[flatIndex] = typeWrapped(argument) + didResolveParameter = true + continue + } + } + if let leftHandFlatIndex = leftHandFlatIndexByRightHandFlatIndex[flatIndex], + let leftHandArgument = argumentsByFlatIndex[leftHandFlatIndex] { + argumentsByFlatIndex[flatIndex] = leftHandArgument + didResolveParameter = true + } } unresolvedFlatIndices.removeAll { argumentsByFlatIndex[$0] != nil } } diff --git a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift index c7730532d..b80577713 100644 --- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift @@ -222,12 +222,18 @@ extension TypeDefinition { let unboundTypeName = try materializedTypeContext.typeName(in: machO.context) let finalTypeName: TypeName if let typeArgumentNodes, !typeArgumentNodes.isEmpty { - if let instantiation = try? GenericInstantiation(of: typeContextDescriptorWrapper, keyArguments: typeArgumentNodes, in: machO) { + do { + let instantiation = try GenericInstantiation(of: typeContextDescriptorWrapper, keyArguments: typeArgumentNodes, in: machO) finalTypeName = TypeName( node: InternedNodeReferenceCache.shared.reference(interning: instantiation.typeNode, in: machO), kind: unboundTypeName.kind ) - } else { + } catch { + // The flat name is the name of no instantiation, so falling + // back to it is a degradation worth a trace: the header still + // prints the runtime's name, and the two now disagree. + let reason = (error as? LocalizedError)?.errorDescription ?? "\(error)" + #log(.error, "could not name the instantiation of \(unboundTypeName.name, privacy: .public) (\(reason, privacy: .public)); naming it with every argument on its innermost level") finalTypeName = Self.boundGenericTypeName( unboundTypeName: unboundTypeName, typeArgumentNodes: typeArgumentNodes diff --git a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift index 42795d487..452d5d822 100644 --- a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift +++ b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift @@ -69,6 +69,15 @@ package enum GenericSpecializationFixture { } } + // `Second` is tied to `First`, so it takes no key argument: the compiler + // writes the requirement as `First == Second`, the parameter that keeps + // its key argument on the left, and the instantiation binds `Second` to + // `First`'s argument. A warning in the fixture's Swift 5 mode. + public struct TiedParameterPair where First == Second { + public var first: First + public var second: Second + } + // The extension's parameters span two depths, `DepthOuter`'s and // `SecondMiddle`'s, so `InnerElement` is at depth 2. extension DepthOuter.SecondMiddle where OuterElement == Int { diff --git a/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift b/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift new file mode 100644 index 000000000..47578d39d --- /dev/null +++ b/Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift @@ -0,0 +1,62 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Demangling +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering +import MachOTestingSupport + +/// A same-type requirement between two parameters — `TiedParameterPair where First == Second` — leaves the second without a key argument: +/// the request offers `A` alone, and the instantiation binds `B` to the same +/// type. The compiler writes the requirement with the parameter that keeps +/// its key argument on the LEFT, so the argument has to be copied from left +/// to right, as the runtime's `_gatherWrittenGenericParameters` does when the +/// left-hand parameter is already filled in. +/// +/// `GenericInstantiation` read such a requirement only right to left (a +/// parameter fixed by the type on the right): the offline specialization +/// threw `unresolvedFixedParameter`, and the runtime path's `typeName` fell +/// back, silently, to `TiedParameterPair` while its header reads +/// the runtime's `TiedParameterPair`. +@Suite(.serialized) +struct TiedParameterInstantiationTests { + private static let moduleName = GenericSpecializationFixture.moduleName + + @Test("an offline specialization binds a parameter tied to another by a same-type requirement") + func offlineSpecializationBindsTheTiedParameter() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "TiedParameterPair", in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + + let result = try specializer.specialize(request, with: ["A": .metatype(Int.self)]) + + #expect(result.typeName.name(using: .default) == "\(Self.moduleName).TiedParameterPair") + } + + @Test("a runtime specialization's name binds a parameter tied to another as the runtime does") + func runtimeSpecializationNameBindsTheTiedParameter() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "TiedParameterPair", in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let result = try specializer.specialize(request, with: ["A": .metatype(Int.self)]) + let runtimeMetatype = unsafeBitCast(try result.metadata().asPointer, to: Any.Type.self) + let runtimeName = try #require(RuntimeTypeNameDemangling.node(forMetatype: runtimeMetatype)) + + let specialized = try await definition.specialize( + with: result, + typeArgumentNodes: [try await demangleAsNode("Si", isType: true)], + in: indexer.machO + ) + + let printedName = await specialized.typeName.node.materialize().print(using: .default) + let printedRuntimeName = await runtimeName.print(using: .default) + #expect(specialized.typeName.node.materialize() == runtimeName, "specialized \(printedName) runtime \(printedRuntimeName)") + } +} From d1a47dfbfcd07fecc72a408da01eee4a69f20d80 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 18/49] fix: print the defaults synthesized for a protocol in an extension A protocol declared in an extension of another module's type prints, and is indexed, only in the interface's extensions block, while its default-implementation extensions print in the nested-protocol block before it. Under library evolution a default that comes from a parent protocol's extension is a witness named after the requirement itself; prepare()'s symbol scan misses it, and the protocol's own index pass synthesizes its extension. The block read the list before that pass, so the extension printed nowhere, and a second print of the same builder showed it. Index the protocol before reading the list: index(in:) is synchronous, idempotent and runs once. ProtocolInExtensionDefaultWitnessTests failed before and passes now. PR #131 review finding 4. --- .../SwiftInterfaceBuilder.swift | 16 ++- ...otocolInExtensionDefaultWitnessTests.swift | 127 ++++++++++++++++++ 2 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift index 7cceb8d69..f76252285 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift @@ -246,7 +246,7 @@ public final class SwiftInterfaceBuilder: Sen // of a parent; its blocks used to print inside that extension's // braces (evolution proposal `nested-definition-regions`). for protocolDefinition in indexer.allProtocolDefinitions.values where protocolDefinition.parent != nil || protocolDefinition.extensionContext != nil { - for extensionDefinition in protocolDefinition.defaultImplementationExtensions { + for extensionDefinition in indexedDefaultImplementationExtensions(of: protocolDefinition) { await printCatchedThrowing( dispatchingTo: eventDispatcher, context: .init(name: extensionDefinition.extensionName.name, kind: .extension) @@ -269,6 +269,20 @@ public final class SwiftInterfaceBuilder: Sen } } + /// `protocolDefinition`'s default-implementation extensions, read once + /// it is indexed. The list is complete only then: the protocol's own pass + /// synthesizes the extension of a default the module indexer's symbol scan + /// misses — under library evolution, a default witness named after the + /// requirement itself. A protocol nested in a type is indexed by the time + /// the nested protocols' block prints, its type printed before it; one + /// declared in an extension prints, and indexes, only in the extensions + /// block after it, so its synthesized extension printed nowhere. A pass + /// that fails is reported when the protocol prints. + private func indexedDefaultImplementationExtensions(of protocolDefinition: ProtocolDefinition) -> [ExtensionDefinition] { + try? protocolDefinition.index(in: machO) + return protocolDefinition.defaultImplementationExtensions + } + private func collectModules() async throws { eventDispatcher.dispatch(.moduleCollectionStarted) @Dependency(\.symbolIndexStore) diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift new file mode 100644 index 000000000..771e1d855 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift @@ -0,0 +1,127 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Support) @testable import SwiftInterface + +/// A protocol declared in an extension of another module's type prints its +/// default-implementation extensions in the interface's top-level block for +/// nested protocols (evolution proposal `nested-definition-regions`). That +/// block reads the protocol's `defaultImplementationExtensions` before the +/// protocol itself is printed: it is printed — and indexed — inside the +/// extension declaring it, in the last block. +/// +/// An extension the module indexer attaches during `prepare()` is there by +/// then; one the protocol's own index pass synthesizes is not. Under library +/// evolution a requirement whose default comes from a parent protocol's +/// extension — `Labeled.describe()`, from `extension Base` — is implemented by +/// a default witness named after the requirement itself, which no +/// protocol-extension block holds, so only the index pass finds it. That +/// extension printed nowhere: not after the protocol, which no longer trails +/// its extensions, and not in the top-level block, which ran first. +@Suite(.serialized) +struct ProtocolInExtensionDefaultWitnessTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "protocol-in-extension default-witness fixture compilation failed:\n\(diagnostics)" } + } + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + private static let source = """ + public final class FixtureAnchor {} + + public protocol Base {} + + extension Base { + public func describe() -> String { "base" } + } + + extension Int { + public protocol Labeled: Base { + func describe() -> String + } + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("ProtocolInExtensionDefaultWitnessFixture-\(UUID().uuidString)") + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + let sourceURL = workingDirectory.appendingPathComponent("ProtocolInExtensionDefaultWitness.swift") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + let libraryURL = workingDirectory.appendingPathComponent("libProbeDefaultWitness.dylib") + // Library evolution makes `Labeled` resilient, which is what + // gives its requirement a default witness of its own. + try run(swiftcArguments: [ + "-swift-version", "5", "-O", "-emit-library", "-enable-library-evolution", + "-module-name", "ProbeDefaultWitness", + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ]) + return libraryURL + } + }() + + private static func run(swiftcArguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = ["swiftc"] + swiftcArguments + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + private func makeBuilder() async throws -> SwiftInterfaceBuilder { + let libraryURL = try Self.fixtureCompilationResult.get() + let machOFile: MachOFile + switch try File.loadFromFile(url: libraryURL) { + case .machO(let file): + machOFile = file + case .fat(let fatFile): + machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) + try await builder.prepare() + return builder + } + + @Test("a default implementation only the protocol's own index finds prints in the interface") + func defaultImplementationFoundByTheIndexPassPrints() async throws { + let interface = try await makeBuilder().printRoot().string + + let topLevelExtensionLines = interface.split(separator: "\n").filter { $0.hasPrefix("extension ") } + #expect(topLevelExtensionLines.contains { $0.contains("Int.Labeled") }, "\(interface)") + } + + @Test("printing the same builder twice gives the same interface") + func printingTwiceGivesTheSameInterface() async throws { + let builder = try await makeBuilder() + + let firstInterface = try await builder.printRoot().string + let secondInterface = try await builder.printRoot().string + + #expect(firstInterface == secondInterface) + } +} From d2f8d586b42abdaba317e919884fead26f7bf39e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 19/49] fix: warn on a conditional conformance in the offline check The indexer records a conformance under the type's unbound name and drops its conditions, so the offline check took Array's Hashable record for proof that [FixtureUnmarked] is Hashable: no warning, and specialize built an instantiation that cannot exist, which the runtime path rejects. When the recorded conformance is conditional - its descriptor counts conditional requirements - warn instead. Checking the conditions against the binding is left for later. ConformanceProvider gains isConditionalConformance(of:to:), defaulting to false. OfflineConditionalConformanceTests failed before and passes now. PR #131 review finding 5. --- .../ConformanceProvider.swift | 27 ++++++++++ ...ericSpecializer+StaticSpecialization.swift | 15 +++++- .../OfflineConditionalConformanceTests.swift | 54 +++++++++++++++++++ 3 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift diff --git a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift index 56a4584ae..dcbd3da4d 100644 --- a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift +++ b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift @@ -55,6 +55,15 @@ public protocol ConformanceProvider: Sendable { /// proposal `offline-generic-specialization`). Default `.unknown`: a /// provider without class-hierarchy knowledge proves nothing either way. func superclassLink(of className: TypeName) -> SuperclassLink + + /// Whether the conformance of `typeName` to `protocolName` that the + /// provider records holds only under conditions — `Array: Hashable where + /// Element: Hashable`. Such a record, kept under the type's unbound name, + /// proves nothing for one instantiation, so the offline check does not + /// take it for proof (evolution proposal `offline-generic-specialization`). + /// Default `false`: the record stands for the conformance, as + /// `doesType(_:conformTo:)` has always read it. + func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool } /// A class's direct superclass, as a `ConformanceProvider` knows it. @@ -99,6 +108,10 @@ extension ConformanceProvider { public func superclassLink(of className: TypeName) -> SuperclassLink { .unknown } + + public func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { + false + } } // MARK: - IndexerConformanceProvider @@ -202,6 +215,16 @@ extension IndexerConformanceProvider: ConformanceProvider { return classHierarchy().superclassLinkByClassName[className.name] ?? .unknown } + /// Read off the conformance's own descriptor, which the conformance + /// extension the indexer built for it keeps: its conditional requirements + /// are counted in the flags. + public func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { + (indexer.allConformanceExtensionDefinitions[typeName.extensionName] ?? []).contains { entry in + entry.value.conformingProtocolName == protocolName + && (entry.value.protocolConformanceDescriptor?.flags.numConditionalRequirements ?? 0) > 0 + } + } + /// Build (or fetch from cache) the parent-name → direct-subclasses /// map, and the class-name → superclass map that reads the same links /// the other way, by walking every indexed `.class` definition's @@ -382,6 +405,10 @@ public struct CompositeConformanceProvider: ConformanceProvider { } return .unknown } + + public func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { + providers.contains { $0.isConditionalConformance(of: typeName, to: protocolName) } + } } // MARK: - EmptyConformanceProvider diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift index fad33706f..3b0155f79 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift @@ -411,11 +411,22 @@ extension GenericSpecializer where MachO == MachOFile { )) return } - guard !conformanceProvider.doesType(typeName, conformTo: protocolName) else { return } + guard conformanceProvider.doesType(typeName, conformTo: protocolName) else { + builder.addWarning(.conformanceCheckFailed( + parameterName: subject.path, + protocolName: protocolName.name, + reason: "offline: the indexed images record no conformance of \(subject.display) to \(protocolName.name); a conformance in an image the indexer does not hold, a conditional one, or one the runtime synthesizes cannot be checked without the runtime" + )) + return + } + // The record is kept under the type's unbound name, so a conditional + // one says nothing about this instantiation: `[FixtureUnmarked]` + // passed `Hashable` on `Array`'s record, conditions and all. + guard conformanceProvider.isConditionalConformance(of: typeName, to: protocolName) else { return } builder.addWarning(.conformanceCheckFailed( parameterName: subject.path, protocolName: protocolName.name, - reason: "offline: the indexed images record no conformance of \(subject.display) to \(protocolName.name); a conformance in an image the indexer does not hold, a conditional one, or one the runtime synthesizes cannot be checked without the runtime" + reason: "offline: \(typeName.name) conforms to \(protocolName.name) only under conditions, which \(subject.display) may not meet; they cannot be checked without the runtime" )) } diff --git a/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift b/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift new file mode 100644 index 000000000..8831bae91 --- /dev/null +++ b/Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift @@ -0,0 +1,54 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +import MachOTestingSupport + +/// A conformance the indexed images record under a generic type's unbound +/// name may hold only under conditions — `Array: Hashable where Element: +/// Hashable` — and the offline check (evolution proposal +/// `offline-generic-specialization`) took the record for proof whatever the +/// arguments: an `Array` of a type that is not `Hashable` passed a `Hashable` +/// requirement with no warning, and `specialize` named an instantiation that +/// cannot exist. The runtime path rejects the same selection. +/// `staticPreflight` promises a warning for a conformance offline evidence +/// cannot settle, and a conditional one is such a conformance. +@Suite(.serialized) +struct OfflineConditionalConformanceTests { + @Test("a conditional conformance is not taken for proof whatever the arguments") + func conditionalConformanceIsNotTakenForProof() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "Inner", in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let hashableParameter = try #require(request.parameters.first { $0.name == "A1" }) + let array = try #require( + hashableParameter.candidates.first { $0.typeName.declaredNameForTesting == "Array" }, + "A1 offers no Array candidate" + ) + let unconstrainedParameter = try #require(request.parameters.first { $0.name == "A" }) + let unmarked = try #require( + unconstrainedParameter.candidates.first { $0.typeName.declaredNameForTesting == "FixtureUnmarked" }, + "A offers no FixtureUnmarked candidate" + ) + + let validation = specializer.staticPreflight( + selection: [ + "A": .metatype(Int.self), + "A1": .boundGeneric(baseCandidate: array, innerArguments: ["A": .candidate(unmarked)]), + ], + for: request + ) + + #expect( + validation.warnings.contains { + guard case .conformanceCheckFailed(let parameterName, let protocolName, _) = $0 else { return false } + return parameterName == "A1" && protocolName == "Swift.Hashable" + } || !validation.isValid, + "errors \(validation.errors) warnings \(validation.warnings)" + ) + } +} From 2d58a451a3b842cae418e694c9c9e79d7cf7dd28 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 20/49] fix: keep the member name when a projected witness is opaque The static expanded field-offset tree projects a concrete type's associated type through its witness record. A record keeps an opaque type reference for the result of a `dynamic` declaration or of an availability-conditional `some`, and the projection spliced it into the row: `() -> opaque type symbolic reference 0x1A60.0`, where 0.21.0 printed the member, `DynamicConcrete.Shape.Body`. Do not project a witness holding an opaque type or a kind-9 accessor reference; the member name stays. NestedFieldOffsetOpaqueWitnessTests failed before for both shapes and passes now. PR #131 review finding 6. --- ...erse+AssociatedTypeWitnessProjection.swift | 19 ++- .../NestedFieldOffsetOpaqueWitnessTests.swift | 141 ++++++++++++++++++ 2 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift diff --git a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift index d839efe4c..c82693cad 100644 --- a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift +++ b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift @@ -119,7 +119,8 @@ extension ImageUniverse { let baseTypeNode = rewrittenNode.children.first, let associatedTypeReference = rewrittenNode.children.at(1), !Self.containsGenericParameter(baseTypeNode), - let projection = projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference) { + let projection = projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference), + !Self.containsUnspellableReference(projection.witnessNode) { var nestedRewrittenNodes: [ObjectIdentifier: Node] = [:] let projectedWitness = projectingConcreteMembers(in: projection.witnessNode, remainingHops: remainingHops - 1, rewrittenNodes: &nestedRewrittenNodes) // The member sits inside a `.type` wrapper already; the witness's @@ -133,4 +134,20 @@ extension ImageUniverse { private static func containsGenericParameter(_ node: Node) -> Bool { node.kind == .dependentGenericParamType || node.children.contains(where: containsGenericParameter) } + + /// Whether `node` holds a reference that prints as a placeholder rather + /// than a type: an opaque type — the record keeps one for the result of a + /// `dynamic` declaration, an availability-conditional `some` (SE-0360) and + /// a non-inlinable `some` of another resilient module, whose underlying + /// type it cannot fix — or a kind-9 accessor function. Spliced into a + /// field's type it read `opaque type symbolic reference 0x….0`; the member + /// it would replace, `Concrete.Body`, names the type better. + private static func containsUnspellableReference(_ node: Node) -> Bool { + switch node.kind { + case .opaqueType, .opaqueReturnType, .opaqueReturnTypeOf, .opaqueTypeDescriptorSymbolicReference, .accessorFunctionReference: + return true + default: + return node.children.contains(where: containsUnspellableReference) + } + } } diff --git a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift new file mode 100644 index 000000000..3fe47be72 --- /dev/null +++ b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift @@ -0,0 +1,141 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout +import Demangling + +/// The static expanded field-offset tree names a member of a concrete type by +/// the type its conformance's witness record names (evolution proposal +/// `offline-generic-specialization`): `[Swift.Int].Element` reads `Swift.Int`. +/// A witness record can name an opaque type, though. The compiler writes the +/// underlying type into the record whenever it knows it, but not for a +/// `dynamic` naming declaration, whose result can be replaced, nor for an +/// availability-conditional one (SE-0360), whose underlying type depends on +/// the OS the code runs on — and not for a non-inlinable `some` of another +/// resilient module. The projection spliced that reference into the row as it +/// was, and the row printed the demangler's placeholder, +/// `() -> opaque type symbolic reference 0x….0`, where it used to print the +/// member, `DynamicConcrete.Body`. +@Suite +struct NestedFieldOffsetOpaqueWitnessTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "nested-field-offset opaque-witness fixture compilation failed:\n\(diagnostics)" } + } + + private static let moduleName = "NestedFieldOffsetOpaqueWitnessFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + private static let fixtureSource = """ + public final class FixtureAnchor {} + + public protocol Shape { + associatedtype Body + var body: Body { get } + } + + public struct DynamicConcrete: Shape { + public init() {} + public dynamic var body: some Equatable { 1 } + } + + public struct ConditionalConcrete: Shape { + public init() {} + public var body: some Equatable { + if #available(macOS 26, *) { + return 1 + } else { + return "one" + } + } + } + + public struct Wrapper { + public var make: () -> Value.Body + } + + public struct DynamicHolder { + public var wrapper: Wrapper + } + + public struct ConditionalHolder { + public var wrapper: Wrapper + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-swift-version", "5", "-O", "-emit-library", + "-module-name", moduleName, + "-target", "arm64-apple-macosx15.0", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private func loadFixtureMachOFile() throws -> MachOFile { + let libraryURL = try Self.fixtureCompilationResult.get() + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + @Test("a member whose witness is an opaque type is not named by a placeholder", arguments: ["DynamicHolder", "ConditionalHolder"]) + func memberWithAnOpaqueWitnessIsNotNamedByAPlaceholder(holderName: String) throws { + let machOFile = try loadFixtureMachOFile() + let holderDescriptor = try #require( + try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == holderName }?.struct + ) + let wrapperRecord = try #require(try holderDescriptor.fieldDescriptor(in: machOFile.context).records(in: machOFile.context).first) + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.dependencyClosure(root: machOFile, searchPaths: [.systemDyldSharedCache])) + + let tree = calculator.nestedFieldOffsetTree(forMangledTypeName: try wrapperRecord.mangledTypeName(in: machOFile.context), baseOffset: 0, depthLimit: 8) + + let make = try #require(tree.first { $0.fieldName == "make" }, "\(tree.map(\.fieldName))") + // The demangler's two placeholders for an opaque reference it cannot + // spell: one resolved from a file, one from a symbol. + #expect(!make.typeName.contains("opaque type symbolic reference") && !make.typeName.contains("opaque return type"), "\(make.typeName)") + } +} From f5266e3052a6fd45ae25bb9435b1bc5e7ed1c2df Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 21/49] fix: lock a definition's specialized children specializedChildren lives in a non-atomic associated object that specialize(...) reads, appends to and writes back. TypeDefinition is @unchecked Sendable, and RuntimeViewer awaits specialize(...) from its section actor: a nonisolated async method, which runs off the actor while the actor goes on reading the list. Two specializations at once lost one, and a read overlapping a write could retain an array the write had just released. Read and append under one process-wide lock. The storage stays an associated object: moving it into TypeDefinition would change the instance size DeclarationModelInstanceSizeTests pins. AGENTS.md and TypeDefinition's documentation no longer call the append unlocked. ConcurrentSpecializationTests specializes one definition from 512 tasks in a child process: 445 to 467 were kept before, all 512 now. PR #131 review finding 7. --- AGENTS.md | 2 +- .../Definitions/TypeDefinition.swift | 5 +- .../TypeDefinition+Specialization.swift | 33 ++++++-- .../ConcurrentSpecializationTests.swift | 77 +++++++++++++++++++ 4 files changed, 108 insertions(+), 9 deletions(-) create mode 100644 Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift diff --git a/AGENTS.md b/AGENTS.md index 9308ca0d3..a7da25770 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -271,7 +271,7 @@ Library entry points run their body on the demangler's large-stack task executor **Never start an unstructured `Task {}` inside a wrapped entry point**: SE-0417 means it does not inherit the preference (child tasks and default actors do). Nesting is a no-op, and below macOS 15 / iOS 18 the body runs unchanged. [LargeStackTaskExecutorAdoption.md](Documentations/Internal/LargeStackTaskExecutorAdoption.md). -Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read) — and `specialize(...)` appends to the generic definition unlocked. [draft-concurrent-definition-printing](Documentations/Evolutions/draft-concurrent-definition-printing.md). +Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [draft-concurrent-definition-printing](Documentations/Evolutions/draft-concurrent-definition-printing.md). diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift index a8ec099cf..56d05188e 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift @@ -10,8 +10,9 @@ import SwiftInspection /// publishes what it wrote (`DefinitionIndexing`, evolution proposal /// `concurrent-definition-printing`). Printing writes nothing to it, so one /// definition may be printed from several tasks at once. The one write -/// outside that promise is `specialize(...)` appending to a generic -/// definition's `specializedChildren`. +/// outside that promise, `specialize(...)` appending to a generic +/// definition's `specializedChildren`, holds a lock of its own +/// (`SwiftSpecialization`). public final class TypeDefinition: Definition, @unchecked Sendable { /// The type's context descriptor reference (evolution proposal 0002). /// This is the only Mach-O parse product the definition retains: the diff --git a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift index b80577713..f04463ea0 100644 --- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift @@ -20,10 +20,29 @@ import AssociatedObject /// instance properties to a type it does not own. extension TypeDefinition { /// Associated-object backing for `specializedChildren`. Mutated only - /// within this file (the `specialize(...)` family appends to it). + /// within this file (the `specialize(...)` family appends to it), and + /// read and written only under `specializedChildrenAccess`. @AssociatedObject(.retain(.nonatomic)) private var _specializedChildren: [TypeDefinition] = [] + /// The lock every read and write of `_specializedChildren` holds — one + /// for all definitions, as a specialization is rare and its append quick. + /// A host reads the list while it specializes from another task: + /// RuntimeViewer's section actor awaits `specialize(...)`, a nonisolated + /// async method that runs off the actor while the actor goes on reading. + /// Unlocked, two appends at once lost one of them, and a read overlapping + /// a write could retain the array the write had just released (the + /// associated object is retained non-atomically, and its getter even + /// writes on a first read). + @Mutex + private static var specializedChildrenAccess: Void = () + + private func appendSpecializedChild(_ specialized: TypeDefinition) { + Self._specializedChildrenAccess.withLockUnchecked { _ in + _specializedChildren.append(specialized) + } + } + /// Specialized children produced by **directly** calling /// `specialize(with:in:)` (or the `derivingNestedSpecializationsWith` /// overload) on this generic definition. Each entry is a sibling-shaped @@ -67,7 +86,9 @@ extension TypeDefinition { /// independent subtrees in `outerSpecialized.typeChildren`). Equality /// of `metadata` does not imply identity of the wrapping /// `TypeDefinition`. - public var specializedChildren: [TypeDefinition] { _specializedChildren } + public var specializedChildren: [TypeDefinition] { + Self._specializedChildrenAccess.withLockUnchecked { _ in _specializedChildren } + } /// Maximum recursion depth that `deriveNestedSpecializedTypeChildren` /// will descend before bailing out. Swift's source-level nesting rarely @@ -127,7 +148,7 @@ extension TypeDefinition { typeArgumentNodes: typeArgumentNodes, in: machO ) - _specializedChildren.append(specialized) + appendSpecializedChild(specialized) return specialized } @@ -187,7 +208,7 @@ extension TypeDefinition { for child in specialized.typeChildren { child.parent = specialized } - _specializedChildren.append(specialized) + appendSpecializedChild(specialized) return specialized } @@ -465,7 +486,7 @@ extension TypeDefinition { in machO: MachOFile ) async throws -> TypeDefinition { let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) - _specializedChildren.append(specialized) + appendSpecializedChild(specialized) return specialized } @@ -495,7 +516,7 @@ extension TypeDefinition { for child in specialized.typeChildren { child.parent = specialized } - _specializedChildren.append(specialized) + appendSpecializedChild(specialized) return specialized } diff --git a/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift b/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift new file mode 100644 index 000000000..1a464cac6 --- /dev/null +++ b/Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift @@ -0,0 +1,77 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Demangling +@testable import MachOSwiftSection +import MachOTestingSupport + +/// `specialize(...)` appends the new definition to the generic definition's +/// `specializedChildren`: an associated object, retained non-atomically, read, +/// appended to and written back with no lock. `TypeDefinition` is declared +/// `@unchecked Sendable`, and RuntimeViewer calls `specialize` from its section +/// actor into a nonisolated async method — which runs off the actor while the +/// actor goes on reading the same array. Two specializations at once lose one +/// of them, and a read that overlaps a write can retain an array the write has +/// just released. +/// +/// Measured before the fix: 445 to 467 of 512 specializations kept, every run. +/// An exit test all the same: the overlap that loses an entry can also free +/// an array still being read, which would take the whole process down. +@Suite(.serialized) +struct ConcurrentSpecializationTests { + /// Specializes one definition from many tasks at once, each reading the + /// list meanwhile, and fails unless every specialization was kept. + static func specializeOneDefinitionFromManyTasks() async throws { + let machOImage = try GenericSpecializationFixture.loadedImage() + // An indexer of its own: the appends must not reach the definitions + // the other suites share. + let indexer = SwiftDeclarationIndexer(in: machOImage) + try await indexer.prepare() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "PairBox", in: indexer) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let result = try specializer.specialize(request, with: ["A": .metatype(Int.self), "B": .metatype(String.self)]) + let typeArgumentNodes = [try await demangleAsNode("Si", isType: true), try await demangleAsNode("SS", isType: true)] + let specializationCount = 512 + + try await withThrowingTaskGroup(of: Void.self) { group in + for _ in 0 ..< specializationCount { + group.addTask { + try await definition.specialize(with: result, typeArgumentNodes: typeArgumentNodes, in: machOImage) + // What RuntimeViewer's actor does while a specialization + // runs off it. + _ = definition.specializedChildren.count + } + } + try await group.waitForAll() + } + + let keptCount = definition.specializedChildren.count + guard keptCount == specializationCount else { + throw LostSpecializations(keptCount: keptCount, expectedCount: specializationCount) + } + } + + private struct LostSpecializations: Swift.Error, CustomStringConvertible { + let keptCount: Int + let expectedCount: Int + var description: String { "kept \(keptCount) of \(expectedCount) specializations" } + } + + @Test("specializations made from many tasks at once are all kept") + func specializationsFromManyTasksAreAllKept() async { + await #expect(processExitsWith: .success) { + do { + try await ConcurrentSpecializationTests.specializeOneDefinitionFromManyTasks() + } catch { + // An error thrown out of an exit test ends the child on a + // trap, which reads like a crash; a lost specialization is a + // plain failure. + exit(EXIT_FAILURE) + } + } + } +} From 5308fa1ae262954a4479396254ef11ec6c3777a8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 22/49] fix: project a specialized field's type through the print's own images Printing an offline specialization projected its fields' associated types through search paths taken from the thunk resolver, or inferred from where the binary sits plus the host's cache, never from the print's staticLayoutDependencyResolution. The host's macOS images are no candidates for an iOS binary, so with an iOS simulator cache configured the layout comment was computed for Int? while the field still read [Int].Element?. When the print has a static field-layout provider, project through it. StaticFieldLayoutProvider gains projectingConcreteMembers(in:), defaulting to nil, which the MachOFile provider answers over the images its layouts are computed from, through StaticLayoutCalculator's new public method of the same name. staticPreflight has no print configuration and keeps the default path. OfflineProjectionDependencyResolutionTests runs only where /Volumes/DyldSharedCaches/iOS-Simulator/27.0 exists; there it failed before and passes now. PR #131 review finding 11. --- .../SwiftLayout/StaticLayoutCalculator.swift | 8 ++ .../StaticFieldLayoutProvider.swift | 19 +++ ...StaticSpecializationNodeSubstitution.swift | 15 ++- .../SwiftDeclarationPrinter+Headers.swift | 7 +- ...eProjectionDependencyResolutionTests.swift | 122 ++++++++++++++++++ 5 files changed, 168 insertions(+), 3 deletions(-) create mode 100644 Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift diff --git a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift index 9dad8252b..859e4f255 100644 --- a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift +++ b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift @@ -146,6 +146,14 @@ public struct StaticLayoutCalculator Node { + imageUniverse.projectingConcreteMembers(in: node) + } + /// The per-field layout of the instantiation `binding` makes of /// `typeDescriptor` — every depth of its generic signature bound, so a /// nested type of a specialized parent (`Outer.Inner`) diff --git a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift index 6ad3b6c08..6d7477dd7 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift @@ -4,6 +4,7 @@ import MachODependencies import MachOSwiftSection import MachOFoundation import SwiftLayout +import Demangling @_spi(Internals) import SwiftInspection /// How the static (MachOFile) field-layout path resolves field / superclass / @@ -85,9 +86,21 @@ public protocol StaticFieldLayoutProvider: Sendable { /// The expanded nested-field-offset tree for a field type of the /// instantiation `binding` describes. func nestedFieldOffsetTree(forMangledTypeName mangledTypeName: MangledName, baseOffset: Int, depthLimit: Int, genericArgumentBinding binding: GenericArgumentBinding) -> [NestedFieldOffset] + + /// `node` with every member of a concrete type projected through the + /// witness records of the images the layouts above are computed over — + /// `[Swift.Int].Element` read as `Swift.Int` — so a field's printed type + /// and the layout printed beside it come from the same images. `nil` + /// when the provider has no images of its own: the caller projects + /// through its own. + func projectingConcreteMembers(in node: Node) -> Node? } extension StaticFieldLayoutProvider { + public func projectingConcreteMembers(in node: Node) -> Node? { + nil + } + public func aggregateFieldLayout(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> AggregateFieldLayout? { nil } @@ -190,4 +203,10 @@ public final class MachOFileStaticFieldLayoutProvider: StaticFieldLayoutProvider defer { lock.unlock() } return calculator.nestedFieldOffsetTree(forMangledTypeName: mangledTypeName, baseOffset: baseOffset, depthLimit: depthLimit, genericArgumentBinding: binding) } + + public func projectingConcreteMembers(in node: Node) -> Node? { + lock.lock() + defer { lock.unlock() } + return calculator.projectingConcreteMembers(in: node) + } } diff --git a/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift b/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift index 483aba8ea..7096d837d 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift @@ -14,12 +14,23 @@ import MachOSwiftSection /// from. A member no record answers keeps its spelling. package enum StaticSpecializationNodeSubstitution { /// `typeNode` — a field's or an enum payload's declared type — with - /// `binding`'s arguments substituted and concrete members projected. + /// `binding`'s arguments substituted and concrete members projected: + /// through the images `staticFieldLayoutProvider` computes the layout + /// comments over, when the print has one, so the type and its layout agree + /// — an iOS binary printed against an iOS cache used to have its layout + /// computed while its field kept `[Swift.Int].Element?`, the host's macOS + /// images being no candidates for an iOS root. Without a provider (no + /// layout comment printed) through the images the opaque rewriter uses. package static func substitutedTypeNode( of typeNode: Node, binding: GenericArgumentBinding, + staticFieldLayoutProvider: (any StaticFieldLayoutProvider)?, in machO: MachO ) -> Node { - DependentMemberProjection.projectingConcreteMembers(in: binding.substituting(in: typeNode), in: machO) + let substitutedNode = binding.substituting(in: typeNode) + if let projectedNode = staticFieldLayoutProvider?.projectingConcreteMembers(in: substitutedNode) { + return projectedNode + } + return DependentMemberProjection.projectingConcreteMembers(in: substitutedNode, in: machO) } } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 0e226096e..2b29018bc 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -456,7 +456,12 @@ extension SwiftDeclarationPrinter { } let substitutedTypeNode: Node? = { if let staticSpecialization { - return StaticSpecializationNodeSubstitution.substitutedTypeNode(of: field.typeNode.materialize(), binding: staticSpecialization, in: machO) + return StaticSpecializationNodeSubstitution.substitutedTypeNode( + of: field.typeNode.materialize(), + binding: staticSpecialization, + staticFieldLayoutProvider: renderConfiguration.staticFieldLayoutProvider, + in: machO + ) } guard let specializedMetadata, let specializedMachOImage, let mangledTypeName else { return nil } return SpecializedMetadataNodeSubstitution.substitutedFieldTypeNode(for: mangledTypeName, metadata: specializedMetadata, in: specializedMachOImage) diff --git a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift new file mode 100644 index 000000000..d59e3ea3c --- /dev/null +++ b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift @@ -0,0 +1,122 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Support) @testable import SwiftPrinting +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +import MachOTestingSupport +import SwiftDeclarationRendering + +/// An archived iOS simulator cache: the dependency closure an iOS simulator +/// binary is printed against here. Machine-specific, hence the suite's +/// condition. +private let iOSSimulatorCachePath = "/Volumes/DyldSharedCaches/iOS-Simulator/27.0/dyld_sim_shared_cache_arm64" + +/// A field of an offline specialization (evolution proposal +/// `offline-generic-specialization`) names a member of a concrete type by the +/// type its witness record names — `[Swift.Int].Element` reads `Swift.Int` — +/// and the layout comments beside it are computed over the dependency closure +/// the print configuration names (`staticLayoutDependencyResolution`). The +/// projection built a closure of its own, from the thunk resolver's search +/// paths or the ones inferred from the file's location plus the running +/// system's cache, so the field's name and its layout were read from two +/// different sets of images. An iOS binary stored outside any runtime tree and +/// printed against an iOS cache has its layout computed and its field left +/// as `[Swift.Int].Element?`: the host's macOS images are never candidates for +/// an iOS root. +@Suite(.serialized, .enabled(if: FileManager.default.fileExists(atPath: iOSSimulatorCachePath))) +struct OfflineProjectionDependencyResolutionTests { + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "iOS simulator projection fixture compilation failed:\n\(diagnostics)" } + } + + private static let moduleName = "SimulatorProjectionFixture" + + private static let fixtureSource = """ + public final class FixtureAnchor {} + + public struct ElementsHolder { + public var elements: Elements + public var first: Elements.Element? + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "--sdk", "iphonesimulator", + "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, + "-target", "arm64-apple-ios17.0-simulator", + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain before waiting, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private func loadFixtureMachOFile() throws -> MachOFile { + let libraryURL = try Self.fixtureCompilationResult.get() + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + @Test("a field's projected member and its layout are read from the same images") + func projectedMemberAndLayoutAreReadFromTheSameImages() async throws { + let machOFile = try loadFixtureMachOFile() + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + let definition = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == "ElementsHolder" }) + let specializer = GenericSpecializer(indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let result = try specializer.specialize(request, with: ["A": .metatype([Int].self)]) + let specialized = try await definition.specialize(with: result, in: machOFile) + var configuration = SwiftDeclarationPrintConfiguration() + configuration.printTypeLayout = true + configuration.staticLayoutDependencyResolution = .dependencyClosure(searchPaths: [.dyldSharedCache(path: iOSSimulatorCachePath)]) + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machOFile) + + let printed = try await printer.printTypeDefinition(specialized).string + + let firstFieldLine = try #require(printed.split(separator: "\n").first { $0.contains("var first:") }, "\(printed)") + #expect(firstFieldLine.contains("Swift.Int") && !firstFieldLine.contains("Element"), "\(printed)") + } +} From de14e727f0589192a6ad6deecb486ef7d1e875fb Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 23/49] perf: return a node without members from the projection as it is Both associated-type projection entries did their work for every node. The rendering one inferred search paths (listing directories), took two locks and, on its first call, built a whole dependency closure even for a plain Swift.Int; the image universe one rebuilt every node on the way. Return a node holding no dependentMemberType untouched. PR #131 review finding 14. --- .../ImageUniverse+AssociatedTypeWitnessProjection.swift | 3 +++ .../SwiftDeclarationRendering/DependentMemberProjection.swift | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift index c82693cad..bcf05b604 100644 --- a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift +++ b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift @@ -90,6 +90,9 @@ extension ImageUniverse { /// (`IndexingIterator`'s `Element` is `Elements.Element`), so a projection /// is projected again, a bounded number of hops deep. public func projectingConcreteMembers(in node: Node) -> Node { + // Most nodes name no member at all; they come back as they are, + // without a rebuilt copy of every node on the way. + guard node.contains(.dependentMemberType) else { return node } var rewrittenNodes: [ObjectIdentifier: Node] = [:] return projectingConcreteMembers(in: node, remainingHops: Self.maximumProjectionHops, rewrittenNodes: &rewrittenNodes) } diff --git a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift index 0390c8eaf..ede6dbbac 100644 --- a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift +++ b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift @@ -129,6 +129,10 @@ extension DependentMemberProjection { /// the reader is neither a file nor an in-process image, or the universe /// cannot be built. package static func projectingConcreteMembers(in node: Node, in machO: MachO) -> Node { + // Nothing to project, so nothing to look up: no search-path inference + // (it lists directories), no lock, no dependency closure built — the + // first call used to build one even for a plain `Swift.Int`. + guard node.contains(.dependentMemberType) else { return node } if let machOFile = machO as? MachOFile { let registry = fileRegistries.storage(in: machOFile) { FileRegistry(root: $0) } ?? FileRegistry(root: machOFile) guard let entry = registry.entry(for: searchPaths(for: machOFile)) else { return node } From 4e8f4a7fd5dd68f6d1b2444f9535f83ce8190803 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 24/49] refactor: spell out the abbreviated names in the specializer's new lines Rename param, paramName, protocolRef, swiftProto, proto and info in the lines the offline specialization rewrote, and compile ProtocolInExtensionTests' fixture in an explicit Swift 5 mode. Both were cut from the PR #131 review by its findings cap. --- ...ericSpecializer+StaticSpecialization.swift | 4 ++-- .../GenericSpecializer.swift | 24 +++++++++---------- .../ProtocolInExtensionTests.swift | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift index 3b0155f79..b1edc0274 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift @@ -401,8 +401,8 @@ extension GenericSpecializer where MachO == MachOFile { } private func checkConformance(of subject: StaticRequirementSubject, to requirement: GenericRequirementDescriptor, into builder: SpecializationValidation.Builder) { - guard let builtRequirement = try? buildRequirement(from: requirement), case .protocol(let info) = builtRequirement else { return } - let protocolName = info.protocolName + guard let builtRequirement = try? buildRequirement(from: requirement), case .protocol(let protocolRequirement) = builtRequirement else { return } + let protocolName = protocolRequirement.protocolName guard subject.isResolved, let typeName = subject.nominalTypeName ?? unboundNominalTypeName(of: subject.type) else { builder.addWarning(.conformanceCheckFailed( parameterName: subject.path, diff --git a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift index 738700c98..434644872 100644 --- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift +++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift @@ -205,25 +205,25 @@ extension GenericSpecializer { let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(type), in: machO.context) let mergedRequirements = Self.mergedRequirements(from: genericContext) - for (flatIndex, param) in cumulativeParameters.enumerated() { + for (flatIndex, parameter) in cumulativeParameters.enumerated() { // Skip non-key parameters (type packs, values, etc.) - guard param.hasKeyArgument, param.kind == .type else { continue } + guard parameter.hasKeyArgument, parameter.kind == .type else { continue } guard let position = depthLayout.position(ofParameterAt: flatIndex) else { continue } // Get parameter name based on depth and per-level index // (e.g., A, B, A1, B1, A2...). - let paramName = genericParameterName(depth: position.depth.cast(), index: position.index.cast()) + let parameterName = genericParameterName(depth: position.depth.cast(), index: position.index.cast()) // Collect requirements for this parameter (ordered for PWT passing) let requirements = try collectRequirements( - for: paramName, + for: parameterName, from: mergedRequirements ) // Find candidate types that satisfy all protocol requirements let protocolRequirements = requirements.compactMap { requirement -> ProtocolName? in - if case .protocol(let info) = requirement { - return info.protocolName + if case .protocol(let protocolRequirement) = requirement { + return protocolRequirement.protocolName } return nil } @@ -250,7 +250,7 @@ extension GenericSpecializer { ) parameters.append(SpecializationRequest.Parameter( - name: paramName, + name: parameterName, index: position.index, depth: position.depth, requirements: requirements, @@ -385,17 +385,17 @@ extension GenericSpecializer { switch flags.kind { case .protocol: let resolvedContent = try genericRequirement.resolvedContent(in: machO.context) - guard case .protocol(let protocolRef) = resolvedContent else { + guard case .protocol(let protocolReference) = resolvedContent else { return nil } // Try to get protocol name let protocolName: ProtocolName - switch protocolRef { + switch protocolReference { case .element(let resolved): - guard let swiftProto = resolved.swift else { return nil } - let proto = try MachOSwiftSection.`Protocol`(descriptor: swiftProto, in: machO.context) - protocolName = try proto.protocolName(in: machO.context) + guard let swiftProtocolDescriptor = resolved.swift else { return nil } + let protocolWrapper = try MachOSwiftSection.`Protocol`(descriptor: swiftProtocolDescriptor, in: machO.context) + protocolName = try protocolWrapper.protocolName(in: machO.context) case .symbol(let symbol): // A protocol another image declares, read from a file: the // reference lands on the bind that the loader would resolve diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift index 691041bda..66e9f681a 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -50,7 +50,7 @@ struct ProtocolInExtensionTests { try source.write(to: sourceURL, atomically: true, encoding: .utf8) let libraryURL = workingDirectory.appendingPathComponent("libProbeProtocolInExtension.dylib") try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", + "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", "-target", "arm64-apple-macosx15.0", sourceURL.path, "-o", libraryURL.path, ]) From 07993a5f7749a566bf6f4de92b7d22b0d2bc8bd5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 25/49] fix: create a file's mapping and handle once under concurrent first reads MachOFile's and DyldCache's file mappings and handles are created on their first read and stored in non-atomic associated objects, with no lock. One DyldCache is read by many readers at once: a FullDyldCache hands the same sub-cache instances to every image read from it, and FullDyldCache.cachedHost is opened once per process, so diff and evolution, preparing their inputs concurrently, make a sub-cache's first read from several roots together. Each racing reader mapped the file again and stored its mapping over the others', and one holding a replaced mapping unretained could read through a file already unmapped. Create each under a lock and store it once; every later read still takes it without the lock. Found in the cross-check of PR #131 review finding 7: the same unlocked write to a non-atomic associated object. ConcurrentFileMappingTests races 32 threads on a fresh instance's first read, 20 rounds per accessor. Before, 12 to 19 of the rounds handed the readers 2 to 7 distinct objects, for each of the four accessors; now every round hands out one. --- .../MachOReading/Extensions/DyldCache+.swift | 27 +++- .../MachOReading/Extensions/MachOFile+.swift | 23 +++- .../ConcurrentFileMappingTests.swift | 130 ++++++++++++++++++ 3 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift diff --git a/Sources/MachO/MachOReading/Extensions/DyldCache+.swift b/Sources/MachO/MachOReading/Extensions/DyldCache+.swift index 0fe1a89a9..ce9b7e327 100644 --- a/Sources/MachO/MachOReading/Extensions/DyldCache+.swift +++ b/Sources/MachO/MachOReading/Extensions/DyldCache+.swift @@ -2,15 +2,34 @@ import Foundation import MachOKit import FileIO import AssociatedObject +import FoundationToolbox extension DyldCache { + /// The lock a cache file's handle and mapping are created under. One + /// `DyldCache` is read by many readers at once: a `FullDyldCache` hands + /// the same sub-cache instances to every image read from it, and the + /// host's cache (`FullDyldCache.cachedHost`) is opened once per process — + /// so `diff` and `evolution`, preparing their inputs concurrently, make + /// the first read of a sub-cache from several roots together. Created + /// unlocked, each racing reader mapped the file again and stored its own + /// mapping over the others', and a reader holding a replaced one + /// unretained (the association is non-atomic) could read through a file + /// already unmapped. Created under this lock, each is stored once and + /// never replaced, so every later read takes it without the lock. + @Mutex + private static var fileAccessCreation: Void = () + @AssociatedObject(.retain(.nonatomic)) private var _fileHandle: FileHandle? var fileHandle: FileHandle { if let _fileHandle { return _fileHandle - } else { + } + return Self._fileAccessCreation.withLockUnchecked { _ in + if let _fileHandle { + return _fileHandle + } let fileHandle = try! FileHandle(forReadingFrom: url) _fileHandle = fileHandle return fileHandle @@ -23,7 +42,11 @@ extension DyldCache { var fileIO: MemoryMappedFile { if let _fileIO { return _fileIO - } else { + } + return Self._fileAccessCreation.withLockUnchecked { _ in + if let _fileIO { + return _fileIO + } let fileIO = try! MemoryMappedFile.open(url: url, isWritable: false) _fileIO = fileIO return fileIO diff --git a/Sources/MachO/MachOReading/Extensions/MachOFile+.swift b/Sources/MachO/MachOReading/Extensions/MachOFile+.swift index 29a31cc7b..c1f1539fe 100644 --- a/Sources/MachO/MachOReading/Extensions/MachOFile+.swift +++ b/Sources/MachO/MachOReading/Extensions/MachOFile+.swift @@ -3,15 +3,30 @@ import MachOKit import MachOKitExtensions import FileIO import AssociatedObject +import FoundationToolbox extension MachOFile { + /// The lock a file's handle and mapping are created under, the way + /// `DyldCache`'s are. Created unlocked, readers racing to make a file's + /// first read each opened it again and stored their own over the others', + /// and a reader holding a replaced one unretained (the association is + /// non-atomic) could read through a file already unmapped. Created under + /// it, each is stored once and never replaced, so every later read takes + /// it without the lock. + @Mutex + private static var fileAccessCreation: Void = () + @AssociatedObject(.retain(.nonatomic)) private var _fileHandle: FileHandle? var fileHandle: FileHandle { if let _fileHandle { return _fileHandle - } else { + } + return Self._fileAccessCreation.withLockUnchecked { _ in + if let _fileHandle { + return _fileHandle + } let fileHandle = try! FileHandle(forReadingFrom: url) _fileHandle = fileHandle return fileHandle @@ -24,7 +39,11 @@ extension MachOFile { var fileIO: MemoryMappedFile { if let _fileIO { return _fileIO - } else { + } + return Self._fileAccessCreation.withLockUnchecked { _ in + if let _fileIO { + return _fileIO + } let fileIO = try! MemoryMappedFile.open(url: url, isWritable: false) _fileIO = fileIO return fileIO diff --git a/Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift b/Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift new file mode 100644 index 000000000..95a10caa3 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/ConcurrentFileMappingTests.swift @@ -0,0 +1,130 @@ +import Foundation +import Testing +import MachOKit +@testable import MachOReading +import MachOFixtureSupport + +/// A file's mapping and handle are created on its first read and shared by +/// every read after it. Several readers can make that first read at once: +/// `diff` and `evolution` prepare their inputs concurrently, and each input's +/// dependency lookup reads the host's dyld cache through sub-cache instances +/// every reader shares — a `FullDyldCache` hands the same ones to all its +/// images, and `FullDyldCache.cachedHost` is opened once per process. Every +/// accessor must hand all of them one object. Created unlocked, each racing +/// reader opened the file again and stored its own over the others'. +@Suite +struct ConcurrentFileMappingTests { + /// How many readers make the first read of one instance together. + private static let readerCount = 32 + + /// How many fresh instances each test races on: one round can miss the + /// overlap, which a wrong accessor shows in nearly every round. + private static let roundCount = 20 + + private static var isHostDyldCacheAvailable: Bool { + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + } + + @Test func concurrentFirstReadsOfAFileShareOneMapping() throws { + for _ in 0 ..< Self.roundCount { + let machOFile = try Self.freshFixtureFile() + let distinctCount = Self.distinctObjectCount { machOFile.fileIO } + #expect(distinctCount == 1, "\(distinctCount) mappings of one file") + } + } + + @Test func concurrentFirstReadsOfAFileShareOneHandle() throws { + for _ in 0 ..< Self.roundCount { + let machOFile = try Self.freshFixtureFile() + let distinctCount = Self.distinctObjectCount { machOFile.fileHandle } + #expect(distinctCount == 1, "\(distinctCount) handles of one file") + } + } + + @Test(.enabled(if: isHostDyldCacheAvailable)) + func concurrentFirstReadsOfADyldCacheShareOneMapping() throws { + for _ in 0 ..< Self.roundCount { + let dyldCache = try DyldCache(path: .current) + let distinctCount = Self.distinctObjectCount { dyldCache.fileIO } + #expect(distinctCount == 1, "\(distinctCount) mappings of one cache file") + } + } + + @Test(.enabled(if: isHostDyldCacheAvailable)) + func concurrentFirstReadsOfADyldCacheShareOneHandle() throws { + for _ in 0 ..< Self.roundCount { + let dyldCache = try DyldCache(path: .current) + let distinctCount = Self.distinctObjectCount { dyldCache.fileHandle } + #expect(distinctCount == 1, "\(distinctCount) handles of one cache file") + } + } + + /// A new instance each time: the accessor under test must not have run on + /// it yet. + private static func freshFixtureFile() throws -> MachOFile { + switch try loadFromFile(named: .SymbolTestsCore) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + } + + /// How many distinct objects `read` hands `readerCount` readers released + /// together. + /// + /// The readers are threads of the test's own, not the global dispatch + /// queue: this body blocks a cooperative thread until they finish (the + /// same arrangement as `SharedCacheResolveTests`). Each one is parked on + /// the start signal before any is let go, so the first reads overlap as + /// closely as threads allow. + private static func distinctObjectCount(returnedBy read: @escaping () -> AnyObject) -> Int { + let reader = UncheckedReader(read: read) + let handedObjects = HandedObjects() + let readersReady = DispatchGroup() + let readersFinished = DispatchGroup() + let startSignal = DispatchSemaphore(value: 0) + for _ in 0 ..< readerCount { + readersReady.enter() + readersFinished.enter() + Thread { + readersReady.leave() + startSignal.wait() + handedObjects.append(reader.read()) + readersFinished.leave() + }.start() + } + readersReady.wait() + for _ in 0 ..< readerCount { + startSignal.signal() + } + readersFinished.wait() + return handedObjects.distinctCount + } +} + +/// Carries a read of a non-`Sendable` file onto the reader threads. Racing on +/// that file is what the test does, so the box only quiets the checker. +private struct UncheckedReader: @unchecked Sendable { + let read: () -> AnyObject +} + +/// The objects the readers were handed, kept alive until they are counted: +/// a mapping replaced and freed mid-round could have its address reused by +/// the next one, and two mappings would count as one. +private final class HandedObjects: @unchecked Sendable { + private let lock = NSLock() + private var objects: [AnyObject] = [] + + func append(_ object: AnyObject) { + lock.lock() + defer { lock.unlock() } + objects.append(object) + } + + var distinctCount: Int { + lock.lock() + defer { lock.unlock() } + return Set(objects.map(ObjectIdentifier.init)).count + } +} From f108d5e6818709d553bc4c2dc9883004135f33d8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 11:51:32 +0800 Subject: [PATCH 26/49] ci: run the suites PR #131 and its review added The main filter now includes the offline specialization and depth suites, the review's repro suites and ConcurrentFileMappingTests - all but OfflineProjectionDependencyResolutionTests, which needs an archived iOS simulator cache. And the one-thread cooperative pool step could not catch an index pass waiting on a pool thread: on the runner every print runs on the demangler's large-stack executor, whose threads the strict pool does not shrink. A new step runs ConcurrentDefinitionPrintingTests there with the executor off, the way prints run below macOS 15. PR #131 review finding 15. These suites have not run on the CI's Xcode 26.6 yet; locally they pass under its Swift 6.3.3. --- .github/workflows/macOS.yml | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index fed712124..236ab532a 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is @@ -147,3 +147,22 @@ jobs: --build-path .build-test-${{ matrix.configuration }} \ --filter '\.(SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|ConcurrentDefinitionPrintingTests)/' \ --skip 'differentKeysParallelVia' + + - name: Run the concurrent printing suite on a one-thread pool without the large-stack executor (${{ matrix.configuration }}) + # The step above cannot catch an indexing pass that needs a pool + # thread: on this runner every print runs inside + # `LargeStackTaskExecution.run`, on the demangler's own threads, which + # the strict pool does not shrink. With the executor off, prints run + # on the cooperative pool itself — as they do below macOS 15 / iOS 18 + # — and a pass that waited on pool work would hang here. + timeout-minutes: 5 + env: + LIBDISPATCH_COOPERATIVE_POOL_STRICT: 1 + MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR: 0 + run: | + swift test \ + -c ${{ matrix.configuration }} \ + --skip-build \ + --enable-experimental-prebuilts \ + --build-path .build-test-${{ matrix.configuration }} \ + --filter '\.ConcurrentDefinitionPrintingTests/' From 0269828284dbd55933e34b4289c086dbae8f3e65 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 12:46:27 +0800 Subject: [PATCH 27/49] docs: record the PR #131 review and how each finding was settled - Roadmaps/2026-10-08-pr131-review-findings.md: the 15 findings, each with the four questions, its repro test, the fix and before and after examples, and the landing record: the commits, the verification on this machine and the rendering A/B. - ReviewAdjudications A53-A59: findings 9 and 12, the intended name difference in finding 10, three minor items the findings cap cut, and the four candidates the review's verifiers refuted. - The decision logs of the four proposals the fixes touch; the offline specialization note (the superclass walk, conditional conformances, tied parameters, projection through the print's images); the opaque return type note (argument lists regrouped by depth, the provider's depth count); the SwiftThunkAnalysis and MachODependencies module notes. - AGENTS.md: eight readers, not five, once counted depths wrongly. - ProjectEvolutionLog: a section for this batch, numbered at landing. Verified on JHs-Mac-Studio with Xcode 26.6 (Swift 6.3.3): the full suite runs 2358 tests in 448 suites and fails only the two MultiPayloadEnumDescriptorCacheTests tests that fail the same way on beae202d here, besides the registered known issue. The rendering A/B against beae202d is byte-identical over 90 pairs. --- AGENTS.md | 2 +- .../draft-concurrent-definition-printing.md | 8 +- .../draft-nested-definition-regions.md | 1 + .../draft-nested-field-offset-memoization.md | 1 + .../draft-offline-generic-specialization.md | 14 +- .../Internal/Modules/MachODependencies.md | 2 +- .../Internal/Modules/SwiftThunkAnalysis.md | 9 + .../Internal/OfflineGenericSpecialization.md | 16 +- .../Internal/OpaqueReturnTypeResolution.md | 10 +- .../Internal/ProjectEvolutionLog.md | 21 + .../Internal/ReviewAdjudications.md | 85 + Roadmaps/2026-10-08-pr131-review-findings.md | 1758 +++++++++++++++++ 12 files changed, 1912 insertions(+), 15 deletions(-) create mode 100644 Roadmaps/2026-10-08-pr131-review-findings.md diff --git a/AGENTS.md b/AGENTS.md index a7da25770..ea560282c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -305,4 +305,4 @@ Keeping this file's module list and `Documentations/README.md`'s index in sync w ## Work in progress -**GenericSpecializer** (`Sources/Declaration/SwiftSpecialization/`) — interactive runtime specialization of generic types. Core implementation complete with tests. Two-step API: `makeRequest()` returns parameters and candidates, `specialize()` executes with the user's selections. Only protocol requirements need witness tables, passed in requirement order; `baseClass` / `layout` / `sameType` need validation only. Generic parameter names are derived from depth/index (A, B, A1, …) because the binary does not preserve them. **A depth counts only the contexts that declare parameters — take it from `GenericParameterDepthLayout`, never from the parent chain or `TargetGenericContext.depth`**: a generic type that declares nothing (`Outer.Middle`) opens no depth, and one extension context can span several (`extension Outer.SecondMiddle where …`). Five readers once counted ancestors and named `B` in `Outer.Middle.Inner` as `A2` while every field and requirement read `A1`. The offline path (`specialize` on a `MachOFile`) is complete too; the specialization's `typeName` hangs each argument on its own level (`Outer.Inner`) on both paths. +**GenericSpecializer** (`Sources/Declaration/SwiftSpecialization/`) — interactive runtime specialization of generic types. Core implementation complete with tests. Two-step API: `makeRequest()` returns parameters and candidates, `specialize()` executes with the user's selections. Only protocol requirements need witness tables, passed in requirement order; `baseClass` / `layout` / `sameType` need validation only. Generic parameter names are derived from depth/index (A, B, A1, …) because the binary does not preserve them. **A depth counts only the contexts that declare parameters — take it from `GenericParameterDepthLayout`, never from the parent chain or `TargetGenericContext.depth`**: a generic type that declares nothing (`Outer.Middle`) opens no depth, and one extension context can span several (`extension Outer.SecondMiddle where …`). Eight readers once counted ancestors or list positions instead: five named `B` in `Outer.Middle.Inner` as `A2` while every field and requirement read `A1`, and three in the opaque-type and thunk paths substituted an opaque type's arguments from the wrong level, trapped on an extension spanning two depths, or left a type declared in a generic extension unnamed. The offline path (`specialize` on a `MachOFile`) is complete too; the specialization's `typeName` hangs each argument on its own level (`Outer.Inner`) on both paths. diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/draft-concurrent-definition-printing.md index 7f183ee52..bcc045152 100644 --- a/Documentations/Evolutions/draft-concurrent-definition-printing.md +++ b/Documentations/Evolutions/draft-concurrent-definition-printing.md @@ -47,9 +47,8 @@ Swift 6 模式,不标的话调用方在任务组里传不进去。 - **打印路径的其余共享可变状态**:`Sources/Output` 全量核对,打印路径写定义的只有上述两处;`ParentClassVTableCache` 是 每次索引各一份的局部值类型;`SharedCache` 一族本来就线程安全;`SymbolicDemangler.isCacheEnabled` 只读无写入点,**不加锁** - (它在最热的入口上,加 `@Mutex` 等于给 8 路并行加一把全局锁),改 `static let`。打印路径之外的非原子写 - `specialize(...)` 追加 `_specializedChildren`,RuntimeViewer 里写与读都在 section actor 上;「同一 printer 可并发」的承诺不覆盖它, - 文档里写明。 + (它在最热的入口上,加 `@Mutex` 等于给 8 路并行加一把全局锁),改 `static let`。打印路径之外的写是 + `specialize(...)` 追加 `_specializedChildren`。原写「RuntimeViewer 里写与读都在 section actor 上,承诺不覆盖它」;PR #131 的 review 查明这个前提不成立(`specialize` 是 nonisolated async,离开 actor 执行,actor 同时在读),改为读写都经一把专用的锁,见决策日志 2026-10-08。 - **约定更新**:AGENTS.md 的那条改成「`MachOImage` 读者下,同一 printer 实例可被多个任务并发调用,包括同时打印同一个定义、 父类型与其嵌套子类型;`MachOFile` 读者仍不可」;`Internal/Modules/SwiftDeclaration.md` 关于 `isIndexed` 的说明同步。 不改 `SwiftDeclarationPrinter` 的公开 API,也不提供并行的入口——并行由调用方(RuntimeViewer 的语料 store)用任务组自己组织。 @@ -75,3 +74,6 @@ | 2026-10-01 | 计时:串行下没有额外开销;宽度 14 的并行反而更慢,原因在 swift-demangling | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`):libswiftCore A 1.02/1.03 s、B 1.03/1.02 s;Foundation A 4.15/4.27 s、B 4.19/4.15 s;SwiftUI A 39.93/40.31 s、B 38.75/45.59 s(第二次只用了 0.93 核,按噪声计)——索引加锁在串行下看不出成本。宽度 14(同一来源,改前 = A + 宽度 1,改后 = B + 宽度 14):SwiftUI 串行 42–50 s,并行 61 s / 约 400 s CPU,机器越空越慢(负载约 6 时 204 s / 2599 s CPU)。采样里热点是 `ExtensionDefinition` 索引体里按 conformance 找符号的 `first(of:)`:`NodeReference` 每复制一次都 retain 共享的 `NodeStore`,14 个线程同时给同一个对象加减引用计数。修在 swift-demangling(用户选「上游改遍历」,提案 `draft-unretained-kind-queries`),RuntimeViewer 在修好之前保持宽度 1。 | | 2026-10-01 | swift-demangling 修好遍历(它的提案 0016,已快进合入它的 `next`,未推送、未发版);剩下的争用以后再说 | 用临时基准在沙盒里量(本分支的快照,只把 swift-demangling 换成修复分支):进程内打印 SwiftUI 的 17920 个定义,标记模式、一个共享 printer、`.utility` 有界任务组,每个宽度一个新进程,release,JHs-Mac-Studio-Ultra。改前:宽度 1 墙钟 37.74 s / CPU 37.77 s;宽度 14 墙钟 329.50 s / CPU 4446 s。改后:宽度 1 18.02 s / 18.08 s;宽度 4 8.87 s / 26.26 s;宽度 14 15.06–18.87 s / 约 165 s。串行本身也快了一倍:按 conformance 找符号的查询在单线程下同样是热点,省掉的是逐节点的引用计数和以 `NodeReference` 为元素的去重集合。改后在宽度 14 下再采样,剩下的争用在本库:`SymbolIndexStore.demangledNodeReference(for:in:)` 每查一个符号都经 `SharedCache.resolve` 取一次存储(同一把锁,`__ulock_wait2` 约 2750 个样本),以及 `ExtensionDefinition` 索引体里按 conformance 找符号时逐个造 `NodeReference`、retain 同一个 store。用户选择先做 `draft-nested-definition-regions`,这部分以后再说。全量 `swift test --skip IntegrationTests` 用修好的 swift-demangling 跑,2168 个全过(原始退出码 0)。RuntimeViewer 要拿到修复,构建需要解析到 swift-demangling 的 `next`。 | | 2026-10-01 | RuntimeViewer 用修好的 swift-demangling 复测:宽度 4 在三个镜像上都快约 2.5 倍,宽度 14 在 SwiftUI 上反而比宽度 4 慢 | RuntimeViewer 会话的 `CorpusBuildTimingProbe`(corpus 模式,Release,每次新进程,四档交替各两轮,负载 5–7;本库为 `937172ef` 的 git archive,swift-demangling 为 `e17ae7f`,对照组为 `35d550a`;RuntimeViewer Core 为 `c0ed5fe4`,只改 `defaultPrintingWidth`;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/fix-*`)。libswiftCore(660 个对象):修复前宽度 1 为 0.94 / 0.95 s;修复后宽度 1 为 0.84 / 0.86 s,宽度 4 为 0.34 / 0.34 s(CPU 1.1 s),宽度 14 为 0.36 / 0.35 s(CPU 3.6–3.8 s)。Foundation(2559 个):3.69 / 3.56 s → 3.34 / 3.36 s → 宽度 4 为 1.28 / 1.28 s(CPU 3.5 s)→ 宽度 14 为 0.84 / 0.84 s(CPU 4.6 s)。SwiftUI(7378 个):34.76 / 33.85 s → 17.44 / 16.30 s → 宽度 4 为 6.68 / 6.81 s(CPU 21.9–22.3 s)→ 宽度 14 为 11.95 / 11.58 s(CPU 144–149 s)。与沙盒基准一致:串行减半,宽度 4 收益最好,宽度 14 被本库符号索引里剩下的争用拖住。RuntimeViewer 准备在它的提案里建议宽度取 min(4, 核数 / 2)(下限 1),等它能解析到含 `9f5ffa92` 的本库和含 `d7693c2` 的 swift-demangling 之后再改代码,以免在没有索引锁的版本上并发打印。 | +| 2026-10-08 | PR #131 review 第 7 条:`specializedChildren` 的读和四处追加都经一把进程级的锁(`TypeDefinition+Specialization.swift` 的 `@Mutex specializedChildrenAccess`);更正「RuntimeViewer 里写与读都在 section actor 上」 | 那个前提不成立:RuntimeViewer 的 `actor RuntimeSwiftSection` 在 `await baseTypeDefinition.specialize(...)`,这个方法是 nonisolated async,本库没开 `NonisolatedNonsendingByDefault`,所以它离开 actor 执行,而 actor 同时可能在读这个数组。复现测试 `ConcurrentSpecializationTests`(子进程里跑):512 个任务同时特化同一个定义,改前每次只留下 445 到 467 个,改后 512 个全在。关联对象保留,没有把存储挪进 `TypeDefinition`:那会改变它的实例大小,`DeclarationModelInstanceSizeTests` 钉着这个大小。AGENTS.md 那句「`specialize(...)` 无锁追加」同步改写。 | +| 2026-10-08 | 第 7 条的横向排查:`MachOFile` 与 `DyldCache` 懒创建文件映射和句柄的四个 getter(`MachOReading/Extensions/MachOFile+.swift`、`DyldCache+.swift`)改为在一把锁下创建、只存一次 | 同一类写法(无锁地写一个 nonatomic 关联对象)。`FullDyldCache` 把同一批子 cache 实例交给它的所有镜像,`FullDyldCache.cachedHost` 又是进程级单例,`diff` 与 `evolution` 并行准备几个输入、各自经依赖查找读宿主 cache 时,会同时第一次读同一个子 cache:各自映射一次文件、互相覆盖,没被 retain 的读者还可能读到已经 unmap 的映射。新测试 `ConcurrentFileMappingTests`(`MachOSwiftSectionTests`)让 32 个线程同时做第一次读取、重复 20 轮:改前四个 getter 都失败(每个 getter 的 20 轮里有 12 到 19 轮,32 个读者拿到 2 到 7 个不同的对象),改后全部通过。热路径不变:第一次之后的读取仍然不拿锁。 | +| 2026-10-08 | PR #131 review 第 9 条(等待别的线程跑完索引时不借出优先级)不修,登记 | 见 [ReviewAdjudications.md](../Internal/ReviewAdjudications.md) A53:没观察到延迟,修法要在 `SharedCacheBuildPromise` 里记下构建线程并处理它提前退出的情况;RuntimeViewer 出现能感觉到的等待时再做。 | diff --git a/Documentations/Evolutions/draft-nested-definition-regions.md b/Documentations/Evolutions/draft-nested-definition-regions.md index d555573ca..2b56c7f21 100644 --- a/Documentations/Evolutions/draft-nested-definition-regions.md +++ b/Documentations/Evolutions/draft-nested-definition-regions.md @@ -68,3 +68,4 @@ RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的 | 2026-10-01 | 实现:`marksNestedDefinitions` 与 `SwiftDeclarationPrinter+DefinitionRegions.swift` | 四处嵌套循环都经 `nestedDefinition(named:printing:)`:先打印子定义,开关打开且结果非空时才算 mangled name(`mangleAsString(name.node)`)并包一层区域;名字 remangle 失败或含控制字符(区域身份不能带)就不标,宿主单独打印它。开关关着时代码路径不变。 | | 2026-10-01 | 验证:契约测试全部通过 | `NestedDefinitionRegionContractTests`(SwiftInterfaceTests):SymbolTestsCore 里每个有嵌套定义的根类型与 extension(几乎所有类型都嵌在命名空间 enum 里),进程内与文件两种读取方式,各三种配置——只开 `marksNestedDefinitions`;再开 `marksOptionalContent` 并挂 opaque 解析器;全部打印选项打开并装上 `applyTransformers(_:)` 的全部模板。每个区域取出、去缩进后与单独打印比较文本、span、identifier、可见性区域表与内层定义区域表,并核对区域数等于嵌套定义数(防漏标),每种配置都检查了 100 个以上的区域,首次运行即全部通过;另有一条确认开关打开时分离后的文本与不开时逐字节相同。swift-semantic-string 侧全部 432 个测试通过、watchOS `arm64_32` 编译通过。 | | 2026-10-01 | 全量测试与渲染 A/B 通过;Foundation 上只挪动了两个扩展 | 全量 `swift test --skip IntegrationTests`(沙盒副本,本地兄弟依赖,swift-semantic-string 指向 `feature/definition-regions`)2174 个测试全部通过,原始退出码 0。渲染 A/B:基线是本分支 `ed289fb4` 的 git archive,候选是加上本提案改动的副本,两侧依赖相同、只有 swift-semantic-string 指向不同分支;92 对逐字节一致,iOS 15.5 模拟器的 SwiftUI / WidgetKit 两侧同样崩溃(MachOKit `ExportTrie.init`,见并发打印提案)。A/B 的框架里没有协议声明在别的模块类型的 extension 里,另用两侧 CLI 渲染当前系统 Foundation 的 interface 对比:只有 `NSNotificationCenter.AsyncMessage` 与 `NSNotificationCenter.MainActorMessage` 的两个默认实现扩展,从 `extension __C.NSNotificationCenter { … }` 的大括号里(顶格)挪到了顶层的嵌套协议扩展区块,其余四万多行逐字节相同。 | +| 2026-10-08 | PR #131 review 第 4 条:interface 的嵌套协议默认实现区块读列表之前,先对协议调用 `index(in:)` | 声明在 extension 里的协议,要到后面的 extensions 区块才被打印、被索引;而它的默认实现列表只有在协议自己的索引过程里才完整——library evolution 下,默认实现来自父协议 extension 时,编译器生成一个挂在需求名下的默认 witness,`prepare()` 的符号扫描认不出它,由协议的索引过程兜底补出这个 extension。区块读列表时协议还没索引,列表是空的,打印器又不再在协议后面接它(本提案的改动),于是这个 extension 哪里都不打印;同一个 builder 打印两次,第二次才出现。改前它被打印在外层 extension 的大括号里(位置不合法,但打印了),所以这是本提案引入的回退,只出现在这个窄形状上。索引同步、可重复调用、只跑一次(`DefinitionIndexing`),区块顺序不动。复现测试 `ProtocolInExtensionDefaultWitnessTests`(library evolution 编的 fixture)先红后绿。RuntimeViewer 的 `defaultImplementationExtensionsLeftToPrint(of:)` 也是直接读这个列表,要同样先索引协议(那边改)。根因的另一种修法——让 `prepare()` 认出挂在需求名下的默认 witness——改动大得多,没做 | diff --git a/Documentations/Evolutions/draft-nested-field-offset-memoization.md b/Documentations/Evolutions/draft-nested-field-offset-memoization.md index b2de5a181..a0085785d 100644 --- a/Documentations/Evolutions/draft-nested-field-offset-memoization.md +++ b/Documentations/Evolutions/draft-nested-field-offset-memoization.md @@ -94,3 +94,4 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 | 2026-10-01 | 测试不新建 fixture;加一个只给测试用的 `NestedFieldOffsetLevelMemo.isBypassed`(`package` 级 `@TaskLocal`) | SymbolTestsCore 的 `ValueSpec` 已经同时有:最后一个 payload `pair` 解析不出(前一行 `reference` 因此画 `├──`)、`indirect` payload、`ReferenceSpec` ↔ `ValueSpec` 的环;改 SymbolTestsCore 会牵动全部基线。「末字段名读失败」编译器产不出来,靠构造保证:记录里的 `isLast` 与原来按同一个表达式、对全部字段记录计数。绕过开关是提案「关掉缓存的路径」所需,`@TaskLocal` 只影响当前任务树,不碰并行的其它套件。判别符缓存的测试以 AppKit 私有类的 Objective-C 运行时名字为独立真值,冷热两次都比。 | | 2026-10-01 | 验证 | 新测试与相关既有套件(嵌套展开、深度上限、特化字段类型、可见性区域投影、两个判别符套件、并发打印)全过。全量 `swift test --skip IntegrationTests` 2168 个测试全过,原始退出码 0,known issue 仍是 `SymbolicManglingIndexTests` 那一条。release + TSan 跑 `ConcurrentDefinitionPrintingTests`(标记模式打印含展开字段偏移,多线程同时查 memo)与 `NestedFieldOffsetMemoizationTests`:0 条报告,退出码 0。渲染 A/B 对 `9f5ffa92`(并发打印那份):92 对逐字节一致,SKIPPED 的仍是 iOS 15.5 模拟器 SwiftUI / WidgetKit 那 4 对(本地 MachOKit `next` 的既有问题)。A/B 的 MachOImage 腿默认不开展开字段偏移,所以另用 `RenderingVerificationTests` 打开全部选项(含 `expandedFieldOffsets`)对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍:16 对逐字节一致,进程内那几份带 17 到约 7800 行展开行。SwiftUI / SwiftUICore 没放进这一轮:该工具记着它们在开展开字段偏移时有既有的栈溢出。`NestedFieldOffsetMemoizationTests` 加进 CI 的主过滤列表。 | | 2026-10-01 | 「改后」计时:省 4–10% | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`;用 `nm` 确认只有 C 带 `RuntimeFieldLayoutMemo`):libswiftCore B 1.03/1.02 s → C 0.98/0.99 s(−4%);Foundation B 4.19/4.15 s → C 3.80/3.98 s(CPU 3.80/3.81,约 −9%);SwiftUI B 38.75/45.59 s → C 36.71/37.94 s(CPU 35.85/37.86,约 −7% 到 −10%)。与「展开字段偏移约占打印时间一成」的分项一致。 | +| 2026-10-08 | PR #131 review 第 12 条(缓存会记住「这个字段类型解析不出」)本库不修,登记为 [ReviewAdjudications.md](../Internal/ReviewAdjudications.md) A54;转 RuntimeViewer | 这是方案里写明的取舍,清除入口 `RuntimeFieldLayoutMemo.removeAll()` 交给宿主在加载镜像后调用。review 查到 RuntimeViewer 的 find-navigator 分支只在它自己 `dlopen` 之后调用,被检查的进程自己加载的镜像不会触发;`DyldUtilities.observeDyldRegisterEvents()` 写好了 dyld 加载镜像的回调但从没被调用,那边要注册它并在回调里调用 `removeAll()`。 | diff --git a/Documentations/Evolutions/draft-offline-generic-specialization.md b/Documentations/Evolutions/draft-offline-generic-specialization.md index 78a59d5da..668524ee4 100644 --- a/Documentations/Evolutions/draft-offline-generic-specialization.md +++ b/Documentations/Evolutions/draft-offline-generic-specialization.md @@ -68,12 +68,12 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) / - **报错并拒绝**:结构上确定违反的约束。 - `AnyObject` 参数给了 struct / enum / tuple;宿主类型按 metadata 的 kind 判断。 - - 父类约束:索引认识、但不在父类子树里的类;宿主类沿它自己完整的父类链按名字比较。 + - 父类约束:沿索引记录的父类链往上走(类名去掉实参再比较),走到根类也没碰到基类;宿主类沿它自己完整的父类链按名字比较。 - 关联类型的 same-type 约束:两侧都解析成具体类型且不相等。被钉死成具体类型的 key 参数不存在(编译器会把它变成非 key),所以实际只有关联类型这一种。 - **只给警告、照样特化**:离线证明不了的约束。 - - 协议遵循:索引记录里查不到(可能是条件遵循、别的模块补上的、运行时合成的),或实参类型不在任何被索引的镜像里。 + - 协议遵循:索引记录里查不到(可能是别的模块补上的、运行时合成的),或实参类型不在任何被索引的镜像里;记录在案、但遵循带条件(`Array: Hashable where Element: Hashable`)时同样只警告,条件不逐条检查。 - 关联类型投影不出来。 - - 索引没有该父类的类层级信息,或实参类不在任何被索引的镜像里。 + - 父类链走出了被索引的镜像(中间隔着一个 ObjC 类,比如 `FixtureOperation → NSOperation → NSObject` 的 `NSOperation`),或实参类不在任何被索引的镜像里。 错误与警告沿用 `SpecializationValidation` 现有的 case,`SpecializerError` 也不加 case:RuntimeViewer 对这几个枚举做了穷尽 `switch`。关联类型的需求按访问路径命名(`A.Element`),与 request 的 `AssociatedTypeRequirement.fullPath` 一致。 @@ -93,7 +93,7 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) / ### 顺带修的问题 -1. **运行时特化的类型名被拍平**:`TypeDefinition.makeSpecializedDefinition` 改用 `GenericInstantiation`,`Outer.Inner` 不再写成 `Outer.Inner`,派生的 `NestedHost.Plain` 不再写成 `NestedHost.Plain`。实参个数与 key 参数对不上时退回旧形状;`typeArgumentNodes` 传 `nil` 时仍保持未绑定的名字。 +1. **运行时特化的类型名被拍平**:`TypeDefinition.makeSpecializedDefinition` 改用 `GenericInstantiation`,`Outer.Inner` 不再写成 `Outer.Inner`,派生的 `NestedHost.Plain` 不再写成 `NestedHost.Plain`。实参个数与 key 参数对不上时退回旧形状,并记一条错误日志(这个名字不对应任何实例化,类型头又印着运行时的名字,两者会不一致);`typeArgumentNodes` 传 `nil` 时仍保持未绑定的名字。 2. **离线 request 丢掉跨镜像协议需求**(实现时发现):读文件时 `B: Hashable` 的协议引用解析成 bind 的符号(`$sSHMp`),`buildRequirement` 只认已解析的 descriptor,整条需求被丢掉——候选不过滤,witness table 不计数。现在按符号名还原协议名;在线路径不受影响。 3. **静态展开偏移树不投影具体类型的关联类型**(实现时发现):`ElementsHolder<[Int]>.first` 原先显示为 `Swift.Optional.Element>` 并在那里停下,运行时的遍历显示 `Swift.Optional` 并继续展开。现在先投影再命名和展开,未特化类型里出现的实例化字段同样受益。 @@ -152,3 +152,9 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) / | 2026-10-01 | 静态展开偏移树先投影具体类型的关联类型 | 实现时发现:对照测试里 `first` 字段静态显示 `Array.Element` 并停止展开,运行时显示 `Int` 并继续展开;这也改变未特化类型里实例化字段的展开,修复前确认测试失败 | | 2026-10-01 | 不加 `typeLayout(forDescriptor:genericArgumentBinding:)` | 未询问自定:渲染路径没有调用方 | | 2026-10-02 | 分支 rebase 到 `feature/runtime-viewer/find-navigator`(`86f65341`)之上,须在它之后合入 | 用户:「rebase一下find-navigator,然后提交」。两边都改过的 11 个文件里,代码文件全部自动合并,文档索引与演进账本两处冲突两边内容都保留。find-navigator 的最后一个提交要用 swift-semantic-string 尚未发版的 `DefinitionRegion`,所以本分支现在要用本地兄弟依赖构建,也要等那个版本发布、本库抬高版本下限之后才能落地 | +| 2026-10-08 | PR #131 review 第 2 条:离线父类检查沿父类链往上走,链走出被索引的镜像只给警告;`ConformanceProvider` 加带默认实现的 `superclassLink(of:)` 与公开枚举 `SuperclassLink` | 原写法拿 `subclasses(of:)` 的子树当证据,而那张类层级图只连得起被索引的 Swift 类:`FixtureOperation: Operation` 配 `` 时链断在 `NSOperation`,`FixtureOperation` 又「已被索引」,就被判成确定违反,`specialize` 抛错,运行时却接受同样的选择——违背本提案「证明不了只警告」的原则。`subclasses(of:)` 的结果总以基类自己开头,「索引里没有类层级」那条警告分支一直走不到,随之删掉。复现测试 `OfflineObjectiveCBaseClassTests` 先红后绿。仍有的局限:比的是去掉实参的类名(`>` 选 `DerivedBox` 会放行),候选列表同样被那张图缩小、不列出 ObjC 父类下的 Swift 类,两者在线路径也一样,留作以后 | +| 2026-10-08 | PR #131 review 第 3 条:same-type 约束两边都是参数(`First == Second`)时,右边的参数抄左边的实参 | 编译器把仍带 key argument 的参数写在左边,`fillFixedParameters` 只按左边记约束,`Second` 永远补不上:离线特化抛 `unresolvedFixedParameter`,在线特化静默退回扁平名 ``。这是运行时 `_gatherWrittenGenericParameters` 里的另一个分支,移植时漏了。这种写法放在类型声明上,Swift 6 模式报错、Swift 5 只警告;放在 extension 上一直合法。共享 fixture 加了 `TiedParameterPair`,复现测试 `TiedParameterInstantiationTests` 离线、在线各一条,先红后绿,在线名与运行时名结构相等 | +| 2026-10-08 | PR #131 review 第 5 条:记录在案、但带条件的协议遵循只给警告;`ConformanceProvider` 加带默认实现的 `isConditionalConformance(of:to:)` | 索引器按未绑定的类型名记遵循,条件被丢掉:`Inner` 的 `A1` 选「元素是 `FixtureUnmarked` 的 `Array`」时一个警告都没有,`specialize` 拼出一个不可能存在的实例化,运行时会拒绝同样的选择。条件个数从遵循描述符的 flags(`numConditionalRequirements`)读,不加新存储。用 binding 逐条检查条件留作以后。复现测试 `OfflineConditionalConformanceTests` 先红后绿 | +| 2026-10-08 | PR #131 review 第 10 条:在线特化算实例化名字失败、退回扁平名时记一条错误日志 | 原来是 `try?`,没有日志也没有事件,类型头印着运行时的名字,同一个定义就有两个名字。修完第 3 条后基本走不到。另一处名字不一致(嵌套泛型类型的约束 extension 里,`typeName` 按层绑定而类型头是运行时的名字)是本提案 2026-10-01 定下的有意差异,登记为 [ReviewAdjudications.md](../Internal/ReviewAdjudications.md) A55 | +| 2026-10-08 | PR #131 review 第 11 条:打印离线特化定义的字段时,关联类型投影走打印配置建好的依赖闭包;`StaticFieldLayoutProvider` 加带默认实现的 `projectingConcreteMembers(in:)`,`StaticLayoutCalculator` 开同名的公开方法 | 投影原先用的搜索路径来自 thunk 解析器或「文件所在位置推断 + 宿主 cache」,不看打印配置的 `staticLayoutDependencyResolution`,宿主的 macOS 镜像对 iOS 二进制又从来不是候选:iOS 模拟器二进制配 iOS 模拟器 cache 打印时,布局注释按 `Int?` 算(`size: 9`),字段类型却还是 `[Int].Element?`。现在字段类型与旁边的布局注释读同一批镜像。没打开布局注释(没有 provider)时退回原路径;`staticPreflight` 没有打印配置,仍走默认路径,写进实现说明。复现测试 `OfflineProjectionDependencyResolutionTests` 只在有 `/Volumes/DyldSharedCaches/iOS-Simulator/27.0` 的机器上跑 | +| 2026-10-08 | 本轮修复的验证 | 修后全量与复现测试见演进账本「PR #131 review 的修复」一节;改动连同各自的复现测试分条提交 | diff --git a/Documentations/Internal/Modules/MachODependencies.md b/Documentations/Internal/Modules/MachODependencies.md index 3a45b4d99..5ef713b43 100644 --- a/Documentations/Internal/Modules/MachODependencies.md +++ b/Documentations/Internal/Modules/MachODependencies.md @@ -28,7 +28,7 @@ MachODependencies 回答一个问题:**一个二进制链接了哪些镜像, 打不开的搜索路径**不抛错**,记进 `DependencySearchPathLoadFailure`(附原始 error;系统 cache 不可用时是 `systemDyldSharedCacheUnavailable`)。理由有二:一条坏路径不该让整个解析失败;本模块在事件层(`SwiftIndexEvents`)之下,无法派发事件,只能把失败当数据回传,由上层决定落点——`SwiftInterfaceBuilderDependencies` 把它们派发为 `renderingDegraded(.dependencyLoad)` 事件,CLI 经 `ConsoleEventHandler` 落到 stderr。 -`.systemDyldSharedCache` 取 MachOKitExtensions 的 `FullDyldCache.cachedHost`:本机 cache 在进程内只打开一次,所有定位器共用。不要直接读 `FullDyldCache.host`:它每读一次就重新打开、映射本机 cache 的全部文件(macOS 27 是 82 个),而定位器是按根构建的,51 个版本的 evolution 因此曾同时开着 4,182 个文件([ProjectEvolutionLog](../ProjectEvolutionLog.md) 第 82 节)。`FileDependencyLocatorTests.locatorsShareOneOpeningOfTheSystemCache` 钉住了共用。 +`.systemDyldSharedCache` 取 MachOKitExtensions 的 `FullDyldCache.cachedHost`:本机 cache 在进程内只打开一次,所有定位器共用。不要直接读 `FullDyldCache.host`:它每读一次就重新打开、映射本机 cache 的全部文件(macOS 27 是 82 个),而定位器是按根构建的,51 个版本的 evolution 因此曾同时开着 4,182 个文件([ProjectEvolutionLog](../ProjectEvolutionLog.md) 第 82 节)。`FileDependencyLocatorTests.locatorsShareOneOpeningOfTheSystemCache` 钉住了共用。共用的后果是几个根会同时第一次读同一个子 cache(`diff` 与 `evolution` 并行准备各个输入):`DyldCache` 与 `MachOFile` 的文件映射和句柄由 MachOReading 懒创建,创建时持锁、只存一次,之后的读取不拿锁;曾经无锁创建,每个抢到的读者各映射一次、互相覆盖(`ConcurrentFileMappingTests`,PR #131 review 第 7 条的横向排查)。 ## 2. load name 归一(`DependencyLoadName.bareImageName(of:)`) diff --git a/Documentations/Internal/Modules/SwiftThunkAnalysis.md b/Documentations/Internal/Modules/SwiftThunkAnalysis.md index 9d9c7eb29..1de4c2fff 100644 --- a/Documentations/Internal/Modules/SwiftThunkAnalysis.md +++ b/Documentations/Internal/Modules/SwiftThunkAnalysis.md @@ -68,6 +68,15 @@ v6 不再提供通用 `writeBack` 属性:后索引用 `isPostIndex`,前索 可用性检查自身的调用**永远不跟进**——它的结果必须保持未知,后面那个 `cbz` 才会被两支都跑。 +### accessor 带着实参时,类型名的两条拼法 + +`ThunkTypeNodeBuilder.boundTypeNode` 把「调用了某个类型的 accessor、传了这些实参」拼回类型名,按 accessor 收的实参分两条路: + +- **类型的整个泛型上下文里每个参数都带 key argument**:thunk 传进来的实参正好一个参数一个。按 `GenericParameterDepthLayout` 分层,再交给 `SymbolicDemangler.instantiatedTypeNode` 照运行时的规则拼名字,extension 上下文和被扩展的类型都能处理。`extension Outer where A: Hashable { struct Inner: ~Copyable }` 的 accessor 收 `A` 和 `B` 两个实参,走这条路,得到 `Outer.Inner`。 +- **否则**(有参数被 same-type 约束固定,运行时自己推出来而不是接收):沿类型上下文逐层绑定各层自己的 key 参数。extension 的参数不算这条遍历的一层,所以 `extension Outer where A == Int { struct Inner }` 只收 `B` 的实参也对得上,拼出 `Outer< where A == Swift.Int>.Inner`。 + +只有第二条的时候,第一种形状对不上个数(遍历只数到 `Inner` 的 1 个参数),整个放弃,字段印成 `accessor function at …`(PR #131 review 第 13 条,回归测试 `AccessorThunkTypeInGenericExtensionTests`)。第一版修法把第二条整个换掉,复现测试和全量都是绿的,却让 same-type 约束 extension 里的类型也退化成 `accessor function at …`——那是第二条本来能处理、第一条会放弃的输入;同一个测试文件里的守护测试钉着这个形状。替换一段旧逻辑时,要专门拿旧逻辑能处理的输入去比,不能只看测试。「extension 固定了一部分参数、另一部分仍要接收」的混合形状两条路都对不上,照旧放弃。 + ### 偏移口径:一个混用就静默出错的地方 对 dyld shared cache 里的镜像,`MachOSwiftSection` 全线使用的偏移是 `unslidVirtualAddress - sharedRegionStart`,**不是文件偏移**。同一个镜像上还并存着另外三套记账,彼此差值固定但都不等价: diff --git a/Documentations/Internal/OfflineGenericSpecialization.md b/Documentations/Internal/OfflineGenericSpecialization.md index e67d976f8..f0f038e9a 100644 --- a/Documentations/Internal/OfflineGenericSpecialization.md +++ b/Documentations/Internal/OfflineGenericSpecialization.md @@ -52,9 +52,9 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) extension 上下文有一处有意与运行时不同。运行时只给被扩展类型的最外一层(`selfType` 的第一个 `TypeList`)换实参:被扩展类型本身是嵌套泛型时,它把全部实参塞进 `SecondMiddle` 的列表、`Outer` 保持未绑定,拼出的名字不对应任何实例化。离线把 binding 代换进被扩展类型,每层都绑定。和运行时一样,绑定后的 extension 节点不带泛型签名。 -被 same-type 约束钉死的参数不接受 key argument(`extension Outer where A == Int { struct Inner }` 里的 `A`),request 也不提供它,但它的层照样要绑定、名字里也要写出来。`GenericInstantiation`(SwiftSpecialization)从固定它的约束补上:取约束右侧,代换已知实参,再把具体类型的关联类型投影掉;右侧引用另一个被固定的参数时反复代换直到不再有进展。运行时用 `_gatherWrittenGenericParameters` 做同一件事。 +被 same-type 约束钉死的参数不接受 key argument(`extension Outer where A == Int { struct Inner }` 里的 `A`),request 也不提供它,但它的层照样要绑定、名字里也要写出来。`GenericInstantiation`(SwiftSpecialization)从固定它的约束补上:取约束右侧,代换已知实参,再把具体类型的关联类型投影掉;右侧引用另一个被固定的参数时反复代换直到不再有进展。约束两边都是参数时(`struct TiedParameterPair where First == Second`)反过来读:编译器把仍带 key argument 的参数写在左边,所以是右边的 `Second` 抄左边 `First` 的实参。运行时用 `_gatherWrittenGenericParameters` 做同一件事,两个方向都有;只按左边记约束时 `Second` 永远补不上,离线特化抛错、在线退回扁平名(PR #131 review 第 3 条)。 -运行时特化的类型名也改用这套构造(`TypeDefinition.makeSpecializedDefinition`)。此前 `boundGenericTypeName` 把所有实参放进最内层:`Outer.Inner` 被写成 `Outer.Inner`,派生出的 `NestedHost.Plain` 被写成 `NestedHost.Plain`。打印出来的头部不受影响(它用 metadata 的运行时名字),但 `typeName` 是 RuntimeViewer 侧边栏的显示名和标识。实参个数与 key 参数对不上时仍退回旧形状。 +运行时特化的类型名也改用这套构造(`TypeDefinition.makeSpecializedDefinition`)。此前 `boundGenericTypeName` 把所有实参放进最内层:`Outer.Inner` 被写成 `Outer.Inner`,派生出的 `NestedHost.Plain` 被写成 `NestedHost.Plain`。打印出来的头部不受影响(它用 metadata 的运行时名字),但 `typeName` 是 RuntimeViewer 侧边栏的显示名和标识。实参个数与 key 参数对不上时仍退回旧形状,并经 `NestedSpecializationLogging` 记一条错误日志:这个名字不对应任何实例化,类型头又印着运行时的名字,两者不一致。 ## 离线执行与约束检查 @@ -64,8 +64,12 @@ extension 上下文有一处有意与运行时不同。运行时只给被扩展 | 结果 | 情形 | |---|---| -| 错误 | `AnyObject` 参数给了 struct / enum / tuple(宿主类型按 metadata 的 kind 判断);索引认识、但不在父类子树里的类(宿主类沿它自己完整的父类链按名字比较);关联类型的 same-type 约束两侧都解析成具体类型且不相等 | -| 警告 | 索引记录里查不到的协议遵循(可能是条件遵循、别的模块补上的、运行时合成的);关联类型投影不出来;索引没有该父类的类层级信息;实参类型不在任何被索引的镜像里 | +| 错误 | `AnyObject` 参数给了 struct / enum / tuple(宿主类型按 metadata 的 kind 判断);沿索引记录的父类链往上走到根类也没碰到基类(宿主类沿它自己完整的父类链按名字比较);关联类型的 same-type 约束两侧都解析成具体类型且不相等 | +| 警告 | 索引记录里查不到的协议遵循(可能是别的模块补上的、运行时合成的);记录在案、但带条件的协议遵循;关联类型投影不出来;父类链走出了被索引的镜像;实参类型不在任何被索引的镜像里 | + +父类检查沿 `ConformanceProvider.superclassLink(of:)` 一步一步往上走,类名去掉实参后比较(否则 `BaseBox` 和 `BaseBox` 对不上):走到基类就通过;走到根类(`.root`)还没碰到才报错;某一步的类没有任何被索引的镜像描述(`.unknown`)就只给警告。这一步通常是 ObjC 类——`FixtureOperation → NSOperation → NSObject` 里的 `NSOperation`——索引器的类层级只连得起 Swift 类。曾经拿 `subclasses(of:)` 的子树当证据,把每个 Cocoa 类下面的 Swift 类都判成违反,运行时却接受(PR #131 review 第 2 条)。 + +协议遵循的记录按未绑定的类型名存,遵循的条件被丢掉了:`Array: Hashable` 的记录对 `[FixtureUnmarked]` 什么也证明不了。所以记录在案的遵循若带条件(遵循描述符 flags 里的 `numConditionalRequirements` 不为 0,经 `ConformanceProvider.isConditionalConformance(of:to:)` 查),检查给警告,不逐条核对条件(PR #131 review 第 5 条)。 错误与警告沿用 `SpecializationValidation` 现有的 case(RuntimeViewer 对它们做了穷尽 `switch`)。`specialize` 与在线路径一样:静态校验或约束检查有错误时抛 `specializationFailed`,泛型 `.candidate` 抛 `candidateRequiresNestedSpecialization`。关联类型的需求用访问路径命名(`A.Element`),与 request 的 `AssociatedTypeRequirement.fullPath` 一致。 @@ -76,7 +80,7 @@ extension 上下文有一处有意与运行时不同。运行时只给被扩展 `TypeDefinition.staticSpecialization`(SwiftDeclaration)存离线特化的 binding,与运行时特化的 `metadata` 互斥。打印器的三处都在两者之间二选一: - **头部**:`boundTypeNode(of:)` 给出绑定后的名字——运行时特化取 metadata 的运行时名字,离线特化取定义自己的实例化类型名,两者形状相同,都交给 `BoundDumpedTypeNameRenderer`。 -- **字段与 enum payload 的类型**:离线时对字段节点做 binding 代换,再用 `DependentMemberProjection.projectingConcreteMembers` 把具体类型的关联类型投影掉(`Elements.Element?` 在 `Elements == String` 时打成 `Swift.Character?`);投影走被特化类型所在镜像的依赖闭包,投影不了的保留原样。 +- **字段与 enum payload 的类型**:离线时对字段节点做 binding 代换,再把具体类型的关联类型投影掉(`Elements.Element?` 在 `Elements == String` 时打成 `Swift.Character?`),投影不了的保留原样。打印配置带着 `staticFieldLayoutProvider`(打开了布局注释)时,投影经 `StaticFieldLayoutProvider.projectingConcreteMembers(in:)` 走它按打印配置(`staticLayoutDependencyResolution`)建好的依赖闭包,字段类型和旁边的布局注释读的是同一批镜像;没有 provider 时退回 `DependentMemberProjection.projectingConcreteMembers`,它的搜索路径来自 thunk 解析器或「文件所在位置推断 + 宿主 cache」。曾经一律走后者:iOS 模拟器二进制配 iOS 模拟器 cache 打印时,布局按 `Int?` 算,字段却还是 `[Int].Element?`,因为宿主的 macOS 镜像对 iOS 二进制从来不是候选(PR #131 review 第 11 条)。`staticPreflight` 没有打印配置,约束检查里的投影仍走默认路径。 - **布局注释**:`FieldLayoutRenderState.genericArgumentBinding` 把 binding 交给 `StaticFieldLayoutBackend`,后者调用 `StaticFieldLayoutProvider` 新增的四个带 binding 的方法(字段布局、payload 布局、逐 case 的 enum 布局、展开的嵌套偏移树)。这四个方法有返回空的默认实现,库外的 provider 不受影响,只是不出注释。 为了让两条路径对同一个实例化给出相同的注释,顺带改了两处既有行为: @@ -106,6 +110,8 @@ extension 上下文有一处有意与运行时不同。运行时只给被扩展 - **实参所在镜像要在依赖闭包里**。离线布局与关联类型投影都走被特化类型所在镜像的依赖闭包;RuntimeViewer 让用户从别的、互不依赖的镜像里挑候选时,相关字段降级为 unknown、关联类型保持未投影。这是如实降级。 - **宿主类型的协议遵循查不到**。`.metatype` 给的宿主类型不在任何被索引的镜像里,它的协议遵循只能报警告。 +- **父类检查比的是去掉实参的类名**:`>` 选 `DerivedBox` 会放行;要比到实参,得沿父类链做实参代换。候选列表也由只连得起 Swift 类的类层级缩小,ObjC 父类下面的 Swift 类不在列表里(RuntimeViewer 的 UI 选不到它),在线路径一样。 +- **带条件的协议遵循不逐条核对**:只给警告。用 binding 检查每个条件留作以后。 - **class 头部的父类不代换**:`class Sub: Base`,在线路径也是这样。 - **特化后的定义不打印成员**:成员按绑定后的名字查符号查不到,两条路径一致。调用方不传 `typeArgumentNodes` 时,在线路径的定义保持未绑定的名字,会查到并打印未代换的成员(`init(first: A, …)`),这是既有行为。 - **未修的旧问题**:引用「嵌套泛型类型的约束 extension 里声明的类型」的字段(`Outer.SecondMiddle.DeepConstrainedInner`)demangle 失败(`unexpected(at: 11)`),引用它的整个类型从 interface 里消失;引用约束 extension 里类型的类型,其 memberwise `init` 后面会多出一个 `where A == Swift.Int`。两者都与本提案无关,记录在提案里。 diff --git a/Documentations/Internal/OpaqueReturnTypeResolution.md b/Documentations/Internal/OpaqueReturnTypeResolution.md index cafa315b4..3add4ef5b 100644 --- a/Documentations/Internal/OpaqueReturnTypeResolution.md +++ b/Documentations/Internal/OpaqueReturnTypeResolution.md @@ -106,7 +106,7 @@ descriptor(或其 GOT 槽)。本模块协议(ProtocolTest)走 `\x02 `some Sendable` 在 descriptor 里只剩下参数本身:marker protocol(Sendable、Copyable、Escapable、BitwiseCopyable)从不进 generic requirements(`swift/lib/IRGen/GenMeta.cpp` 里 "Marker protocols do not record generic requirements at all"),`some Any` 本来就没有约束,`some AnyObject` 只有一条 layout 约束(kind `0x1F`),`SwiftInterfaceBuilderOpaqueTypeProvider` 不读 layout。这三种形状里 `numRequirements` 与父级相同,全部是继承来的。 -因此 provider 定位参数**只能按坐标,不能按位置**:opaque 自己的参数全在同一深度,下标就是它在声明里的序号(`Qr` 是 0,`QR` 是 n + 1,见 `ASTMangler::appendOpaqueTypeArchetype`)。深度从 descriptor 算:父级每让参数总数增长一次算一层(非泛型嵌套类型不占层,与运行时 `_gatherGenericParameterCounts` 一致),声明自己泛型再加一层(type 节点套着 `dependentGenericType`)。**不要**从声明的 mangled 签名数层——`swift-demangle -expand` 看 `Outer.generic() -> some Equatable` 的 `QOMQ` 符号,签名里只有一个 `DependentGenericParamCount`,外层类型那一层被 `appendGenericSignatureParts` 省掉了;也不要用 `GenericContext.depth`,它对每个带泛型上下文的父级都加一。 +因此 provider 定位参数**只能按坐标,不能按位置**:opaque 自己的参数全在同一深度,下标就是它在声明里的序号(`Qr` 是 0,`QR` 是 n + 1,见 `ASTMangler::appendOpaqueTypeArchetype`)。深度从 descriptor 算:沿父链找到最近的类型或 extension,取它的 `GenericParameterDepthLayout` 层数(非泛型嵌套类型不占层;extension 按被扩展的类型拆层,一个 extension 可以带来好几层,与运行时 `_gatherGenericParameterCounts` 换成被扩展类型来数一致),声明自己泛型再加一层(type 节点套着 `dependentGenericType`)。中间的匿名上下文是泛型声明自己签名所在的地方,它那一层由「声明自己泛型」那一项算,所以跳过;直接拿 descriptor 的父上下文来算,会把 `Outer.generic() -> some Equatable` 的方法那层数两次。曾经按「父级每让参数总数增长一次算一层」来数:`extension Outer.SecondMiddle where A: Hashable` 一次带来 `Outer` 的 `A` 和 `SecondMiddle` 的 `C` 两层,被数成一层,约束落在 `τ_2_0` 上、超出算出的层号,debug 构建在 provider 里 trap,release 打出裸 `some`(PR #131 review 第 8 条,回归测试 `OpaqueParameterInMultiDepthExtensionTests`)。**不要**从声明的 mangled 签名数层——`swift-demangle -expand` 看 `Outer.generic() -> some Equatable` 的 `QOMQ` 符号,签名里只有一个 `DependentGenericParamCount`,外层类型那一层被 `appendGenericSignatureParts` 省掉了;也不要用 `GenericContext.depth`,它对每个带泛型上下文的父级都加一。 查不到就返回 nil,printer 打出裸 `some`。这是有意的:`some Any` 会把 `some Sendable` 写成一个不对的类型,裸 `some` 至少不撒谎,而且与 `swift-section interface` 不带 `--parse-opaque-return-type`(默认)时的输出形态一致。回归测试是 `Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift`(2026-09-18,RuntimeViewer 批量导出 PhotosUIFoundation 在 `PhotosGroupingItemListManager.GroupItem.value` 上崩溃的复现)。 @@ -124,6 +124,14 @@ witness 或签名里引用**别的声明**的 opaque 类型(`Qo` 节点:owne 一个容易误判的点:编译器自己的 `.swiftinterface` 写的不一定是同一个引用。fixture 里 `Outer.body: some Equatable { helper() }` 的 witness `B`,编译器写 `@_opaqueReturnTypeOf("$s11ProbeClient5OuterV4bodyQrvp", 0) __`——`body` 自己声明的 opaque;二进制的 witness 记录已经被 IRGen 代入一层(同模块可见),指向 `helper()` 的。拼法相同,层级差一。`CrossImageOpaqueReferenceTests` 因此用显式期望串,`ProjectedOpaqueMemberWitnessTests` 的 client 自己没有 opaque,才能和编译器的 interface 逐字比。 +### 1.6 引用带的实参表:每层外围声明一张,空层也有一张 + +`Qo` 节点带着命名声明的泛型实参,每层外围声明一张表,从外到内。编译器给**每一层**都写一张(`ASTMangler::appendBoundGenericArgs`),不声明参数的层写空表,所以表的位置不是层号。运行时 `resolveOpaqueType` 先把所有表拍平,再按描述符自己的层结构重新分组(`_gatherGenericParameters`),从不把位置当层号。`Node.opaqueTypeGenericArgumentsByDepth`(`Node+OpaqueType.swift`)照做:重写器把 opaque 描述符的 `GenericParameterDepthLayout`(`ReadOpaqueType` 里算好的那份)传进来,拍平后重新分组;不传时仍按位置分组,只用来拍平的 `OpaqueReferenceSpelling` 不受影响。 + +曾经直接按位置当层号(PR #131 review 第 1 条,回归测试 `OpaqueTypeArgumentDepthTests`)。外围只要有一层不声明参数,它后面的每张表都被当成外一层的:非泛型类型里的泛型函数,实参去空表里找,留下裸 `A`——Xcodes 的 `MainToolbarModifier.Body` 印出 `SwiftUI.TupleToolbarContent`;再往里的层拿到外一层的实参,印出真实但错误的类型(`ProbeNamespace.Box.makePair` 的 `Extra` 拿到了 `Boxed` 的实参)。 + +命名声明本身是泛型时,描述符的自有层会把它的参数和 opaque 参数并成一层,看起来层数不对;但实参表只覆盖命名声明的签名,opaque 参数总在最后、不在表里,所以按扁平下标取位置仍然正确:`Box.makePair` 的 `[Boxed, Extra]` 落到 `(0,0)`、`(1,0)`。 + --- ## 2. 协议、关联类型、约束与 opaque 的关系 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index e8ca7854c..05576f2cc 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2316,6 +2316,27 @@ - **关联文档**:[draft-offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md)、[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[StaticLayoutEngine.md](StaticLayoutEngine.md)「后续工作」、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md)、[SpecializedInterfaceBoundRenderingRestoration.md](SpecializedInterfaceBoundRenderingRestoration.md)、[Glossary.md](../Glossary.md)「depth」「instantiated type name」「offline specialization」。 - **对应版本**:0.22.0(未发版)。叠在 find-navigator 的三份提案之上,须在它们之后合入,也同样要等带 `DefinitionRegion` 的 swift-semantic-string 发版。 +## 2026-10-08 PR #131 review 的修复:13 条修掉,第 9、12 条登记不修(节号落地时分配) + +- **时间段**:2026-10-07(review、复现测试)— 2026-10-08(修复落地)。 +- **动机**:`/code-review max` 对 PR #131(find-navigator 配套的三份提案加离线泛型特化)给出 15 条发现,逐条按四问裁决、写好复现测试与修法,记在 [Roadmaps/2026-10-08-pr131-review-findings.md](../../Roadmaps/2026-10-08-pr131-review-findings.md)。用户审完后说「把发现的问题修一下吧」。 +- **关键决策**: + - 有修法的 13 条全部落地,包括原本建议「离线模式接入前再修」的第 5、11 条(修法已写好、已验证)。每条修复连同它的复现测试一个 commit。 + - 第 1、8、13 条与 PR 已整类修掉的「泛型参数层号数错」同属一类,这次补齐:opaque 引用的实参表按位置当层号、opaque provider 按父链数层、thunk 类型构造器只数类型层。按全库扫描,除这八处外没有别的地方用父链或位置数层号。 + - 第 13 条保留旧逻辑作为第二条路:整个替换的第一版让 same-type 约束 extension 里的类型退化成 `accessor function at …`,加守护测试钉住那个形状。 + - 第 7 条(`specializedChildren` 无锁追加)的横向排查查出 MachOReading 里 `MachOFile` / `DyldCache` 懒创建文件映射和句柄的四个 getter 是同一类写法。`FullDyldCache` 把同一批子 cache 实例交给所有镜像、`cachedHost` 又是进程级单例,`diff` / `evolution` 并行准备输入时会同时第一次读同一个子 cache,所以按「同类一并修」改为持锁创建、只存一次(review 记录原把它列为「另开一项」)。 + - 登记不修:第 9 条(等待索引时不借出优先级)、第 12 条(嵌套偏移缓存记住解析失败,转 RuntimeViewer)、第 10 条里有意的名字差异、review 被条数上限砍掉的三个顺带项,以及核验时驳回的四条候选,见 [ReviewAdjudications.md](ReviewAdjudications.md) A53–A59。 + - 顺带:PR 重写过的几行缩写改成完整名称;`ProtocolInExtensionTests` 编 fixture 补 `-swift-version 5`;CI 主过滤列表补上离线特化、层号与这批新加的套件(依赖本机 cache 的 `OfflineProjectionDependencyResolutionTests` 除外),单线程协作池那一步之后另加一步,关掉大栈执行器再跑并发打印测试——原来那一步测不出它要防的问题,因为打印跑在 swift-demangling 自己的线程上,严格池缩不到它们。 +- **公开 API 与行为变化**(写进 0.22.0 发版说明):新增 `ConformanceProvider.superclassLink(of:)`、`ConformanceProvider.isConditionalConformance(of:to:)`(都有默认实现)与公开枚举 `SuperclassLink`,`StaticFieldLayoutProvider.projectingConcreteMembers(in:)`(有默认实现),`StaticLayoutCalculator.projectingConcreteMembers(in:)`。行为:opaque 类型的实参按描述符的层结构分组;离线父类检查遇到 ObjC 中间类只给警告;带条件的协议遵循给警告;extension 里协议兜底补出的默认实现重新打印出来;静态展开偏移不再把 opaque 实际类型印成占位符。 +- **落地模块**:SwiftDeclarationRendering(`Node+OpaqueType`、`DependentMemberProjection`、`StaticFieldLayoutProvider`、`StaticSpecializationNodeSubstitution`)、SwiftInterface(`SwiftInterfaceBuilder`、`SwiftInterfaceBuilderOpaqueTypeProvider`)、SwiftPrinting(`SwiftDeclarationPrinter+Headers`)、SwiftThunkAnalysis(`ThunkTypeNodeBuilder`)、SwiftSpecialization(`ConformanceProvider`、`GenericInstantiation`、`GenericSpecializer`、`GenericSpecializer+StaticSpecialization`、`TypeDefinition+Specialization`)、SwiftDeclaration(`TypeDefinition` 的说明)、SwiftLayout(`ImageUniverse+AssociatedTypeWitnessProjection`、`StaticLayoutCalculator`)、MachOReading(`MachOFile+`、`DyldCache+`);测试支持 `GenericSpecializationFixture` 加 `TiedParameterPair`;CI。 +- **验证**: + - JHs-Mac-Studio-Ultra(Swift 6.4)上 review 时验证过修法:复现测试在 PR 头上全红、修后全绿,全量 2354 个测试全部通过。 + - 落地时在 JHs-Mac-Studio 上重新验证,用的是 CI 的工具链(Xcode 26.6、Swift 6.3.3),依赖钉到与 Ultra 相同的版本(MachOKit 0.54.101、MachOKitExtensions 1.1.2、MachOObjCSection 0.8.109、swift-demangling 0.7.1,只有 swift-semantic-string 链本地的 `next`)。11 个复现套件(含新的 `ConcurrentFileMappingTests`)在 PR 头的源码上全部失败、修后全部通过。`OfflineProjectionDependencyResolutionTests` 写死的归档 cache 本机没有,在沙盒副本里临时改指本机装的 iOS 27.0 模拟器 runtime 里的 cache,同样是 PR 头上失败、修后通过。 + - 全量 `swift test --skip IntegrationTests`:2358 个测试、448 个套件(Ultra 上的 2354 / 447 加上新的 `ConcurrentFileMappingTests`),原始退出码 1。失败的只有 `MultiPayloadEnumDescriptorCacheTests` 的两条(`everyFixtureMultiPayloadEnumRendersALayout`、`noncopyableMultiPayloadEnumLaysOutFromItsResolvedPayloads`):换回 PR 头的源码,在同一环境里同样两条、同样位置失败,是这台机器上早就有的环境问题(进程内 enum 布局,这批改动不碰;`next` 上也是这样)。另有早已登记的 known issue(`SymbolicManglingIndexTests`)。 + - 渲染 A/B(基线 `beae202d`,候选是这批代码提交的末尾 `f108d5e6`;两侧 release,共用同一份 `Package.resolved`,经构建队列预构建后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 27.0 模拟器的框架在 cache 里、不是文件,那条腿按设计跳过。会改变输出的几条在这些框架与选项组合里都没有触发:第 1 条要外层有一层不声明参数的 opaque 引用,系统框架的 witness 记录里多半已被编译器代换成具体类型;第 6 条只在打开展开字段偏移时出现,A/B 的 CLI 腿不出布局注释、MachOImage 腿不开展开偏移。第 1 条在真实 app 上的效果另用两侧 CLI 对本机的 `/Applications/Xcodes.app` 复核:11599 行的 interface 只有两行不同,都是 `typealias Body` 里的 `TupleToolbarContent` 补上了实参;补出来的类型里露出 5 处本来就解不出的 kind-9 占位符,修前藏在 `A` 后面。 +- **关联文档**:review 记录;[ReviewAdjudications.md](ReviewAdjudications.md) A53–A59;四份提案的决策日志([并发打印](../Evolutions/draft-concurrent-definition-printing.md)、[离线特化](../Evolutions/draft-offline-generic-specialization.md)、[嵌套定义区域](../Evolutions/draft-nested-definition-regions.md)、[嵌套偏移记忆化](../Evolutions/draft-nested-field-offset-memoization.md));[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md)、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、[Modules/MachODependencies.md](Modules/MachODependencies.md)。 +- **对应版本**:0.22.0(未发版),随 PR #131 合入。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 517d6aecb..dd9b03751 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -602,3 +602,88 @@ - dump/interface 打印的声明里如果出现函数局部类型,`currentName` 会把它显示成外层函数签名的尾巴。库代码里目前没有调用它,影响待查。 - 上游 swift-demangling 的 `Node.identifier` 同样不认 `.localDeclName`。 - `MemberKey` 这个候选的镜像路径是空字符串,原因没查。 + +--- + +## A53 — 等另一个线程跑完某个定义的索引时,不把自己的优先级借给它(PR #131 review 发现 9) + +- **裁决**:不修(2026-10-08)。 +- **发现**:`DefinitionIndexing`(`Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift`)让第二个要索引同一个定义的调用者在 `SharedCacheBuildPromise.wait()` 上阻塞,底层是 `NSCondition`,不会把等待者的 QoS 借给正在跑索引的线程。RuntimeViewer 在 `.utility` 上建 Find 语料,用户恰好点开语料正在索引的那个类型时,前台的打印要等后台线程跑完。 +- **复现 / 是否误报**:机制属实,读码确认。没有实测延迟;单个定义的索引通常是毫秒级。 +- **与 main 基线对比**:PR 新引入。改前每个调用者各自索引同一个定义,那是数据竞争,也正是 PR 要修的问题。`SharedCache` 的并发构建用的是同一个 promise,一直是同样的取舍。 +- **为什么不修**:代价没观察到,修法却不小:要在 promise 里记下构建线程,等待前用 `pthread_override_qos_class_start_np` 借出优先级、等完调 `_end_np`,还要处理构建线程在等待开始前已经退出(`pthread_t` 失效)的情况。 +- **既往修复**:无。 +- **复审条件**:RuntimeViewer 出现能感觉到的「点开一个类型要等」。到时在 `SharedCacheBuildPromise` 里做,`SharedCache` 一起受益。 + +--- + +## A54 — 嵌套字段偏移的进程级缓存会记住「这个字段类型解析不出」(PR #131 review 发现 12,**有意设计**) + +- **裁决**:本库不修(2026-10-08),转 RuntimeViewer。 +- **发现**:`NestedFieldOffsetLevelMemo`(`Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift`)按 metatype 记下展开树的每一层,「当时哪些字段类型解析不出」也一起记住。宿主之后加载了定义那个类型的镜像,缓存仍说解析不出,展开树在那里停下。 +- **复现 / 是否误报**:属实,是设计本身的取舍,提案 [draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md) 已写明,并判断为近乎理论。review 没有在 AppKit、SwiftUI、WebKit、Xcode IDE 框架里找到实例。 +- **与 main 基线对比**:PR 新引入(记忆化本身是这个 PR 的一部分)。 +- **为什么不修**:库不知道宿主进程什么时候加载了新镜像(库不注册 dyld 回调),所以清除入口 `RuntimeFieldLayoutMemo.removeAll()` 交给宿主,在加载镜像之后调用。 +- **转 RuntimeViewer**:它的 find-navigator 分支只在自己 `dlopen` 之后(`DyldUtilities.loadImage(at:)`)调用 `removeAll()`,被检查的进程自己加载的镜像不会触发。`DyldUtilities.observeDyldRegisterEvents()` 写了 dyld 加载镜像的回调,但从没被调用;那边要注册这个回调,在回调里调用 `removeAll()`。 +- **既往修复**:无。 +- **复审条件**:真实框架里出现「宿主后加载的镜像让一棵展开树变短」的实例,或者 RuntimeViewer 注册回调之后仍有残留。 + +--- + +## A55 — 嵌套泛型类型的约束 extension 里的类型,在线特化的 `typeName` 与类型头不是同一个名字(PR #131 review 发现 10 的一部分,**有意设计**) + +- **裁决**:不修(2026-10-08)。发现 10 的另一部分(算类型名失败时静默退回扁平名)已修,见 [Roadmaps/2026-10-08-pr131-review-findings.md](../../Roadmaps/2026-10-08-pr131-review-findings.md) 第 10 条。 +- **发现**:`extension Outer.SecondMiddle where … { struct DeepConstrainedInner }` 这类类型在线特化之后,`typeName` 按层绑定实参,类型头印的却是运行时 metadata 的名字。运行时只给被扩展类型最内层的列表换实参,把全部实参塞进 `SecondMiddle` 的列表、`Outer` 保持未绑定。 +- **复现 / 是否误报**:属实;提案 [draft-offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md) 的决策日志(2026-10-01「嵌套泛型的约束 extension 里的类型,实例化名字按层绑定,不照搬运行时」)写明这是有意的差异,[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)「实例化类型名」一节也有说明。 +- **与 main 基线对比**:PR 新引入(在线特化的 `typeName` 是这个 PR 改成按层绑定的)。 +- **为什么不修**:运行时拼出的名字不对应任何实例化。`typeName` 是 RuntimeViewer 侧边栏的显示名和标识,按层绑定的才是对的;类型头取 metadata 的名字是两条路径共有的做法,离线路径的类型头因此与在线逐字节相同。 +- **既往修复**:无。 +- **复审条件**:RuntimeViewer 需要两者一致,比如拿类型头的文字去匹配 `typeName`。 + +--- + +## A56 — 嵌套 `.boundGeneric` 实参链的请求构建次数随深度平方增长(PR #131 review 顺带项) + +- **裁决**:不修(2026-10-08)。 +- **发现**:离线特化每遇到一层 `.boundGeneric` 实参,`staticBoundGenericOutcome`(`GenericSpecializer+StaticSpecialization.swift`)为这一层建一次内层请求(`makeInnerContext` + `makeRequest`),再让内层 specializer 的 `internalValidate` 校验,而 `internalValidate` 又把更深各层的请求重建一遍。深度为 d 的实参链因此要建约 d(d+3)/2 次请求(review 的计数)。`staticBoundGenericOutcome` 注释里的「随深度线性增长」说的是实参解析,不含校验。 +- **复现 / 是否误报**:属实,读码确认。 +- **与 main 基线对比**:离线路径是 PR 新增的;在线路径的 `internalValidate` 递归建请求是既有写法。 +- **为什么不修**:实际的嵌套很浅(RuntimeViewer 的 UI 里用户一层一层手选,`[[Int]]` 这种已经少见),`maxBindingDepth` 也给了上限。要省掉重复,得让校验与解析共用同一份内层请求,改动两条路径的结构。 +- **既往修复**:无。 +- **复审条件**:出现需要深层嵌套实参的调用方,或者 profiling 显示特化耗时主要花在重建请求上。 + +--- + +## A57 — 测试支持里共享的 fixture 索引器在并行套件下会被重复构建(`GenericSpecializationFixtureIndexers`,PR #131 review 顺带项) + +- **裁决**:不修(2026-10-08)。 +- **发现**:`GenericSpecializationFixtureIndexers`(`Sources/TestSupport/MachOTestingSupport/`)是一个 actor,`runtime()` / `offline()` 先查缓存,没有就新建索引器、`await indexer.prepare()`,之后才存进属性。actor 在 `await` 处可重入,几个套件同时第一次调用时各建一份。 +- **复现 / 是否误报**:属实,读码确认(actor reentrancy)。 +- **与 main 基线对比**:PR 新增的测试支持代码。 +- **为什么不修**:只多花测试时间和内存,每一份都是完整的索引,结果正确,不影响任何断言。 +- **既往修复**:无。 +- **复审条件**:测试变慢或内存占用成为问题时,改成存一个 `Task`,让后到的调用者等它。 + +--- + +## A58 — 离线 `specialize(with:in:)` 只按描述符偏移核对特化结果属于哪个类型(PR #131 review 顺带项) + +- **裁决**:不修(2026-10-08)。 +- **发现**:`TypeDefinition` 的离线 `specialize(with:in:)` 经 `makeStaticallySpecializedDefinition`(`Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift`)只比较定义自己的描述符偏移和 `StaticSpecializationResult.typeDescriptor` 的偏移,注释假定两者来自同一个文件。把另一个文件里偏移恰好相同的类型的特化结果传进来,也会被接受,特化出的定义带着别的类型的名字和 binding。 +- **复现 / 是否误报**:属实,读码确认;只有把一个文件的特化结果交给另一个文件的定义,也就是误用 API,才会碰到。 +- **与 main 基线对比**:PR 新增。在线路径按 metadata 的描述符核对,metadata 来自本进程,没有跨文件的问题。 +- **为什么不修**:正确的用法(同一个 specializer、同一个文件)不会触发。要彻底防住误用,得让结果带上镜像身份(文件 URL 加 UUID,或 `SharedCacheKey`),改的是公开的结果类型。 +- **既往修复**:无。 +- **复审条件**:RuntimeViewer 的离线模式里出现多个文件的特化结果混用的路径,或者以后给 `StaticSpecializationResult` 加镜像身份时一起做。 + +--- + +## A59 — PR #131 review 中被核验驳回的四条候选(**误报**) + +- **裁决**:误报(2026-10-08,review 时各有一个核验 agent 读码与编译器源码后驳回)。登记在这里,下次 review 对照跳过。 +- **一、打印器改了「extension 里的协议」的默认实现扩展的打印位置,会让 RuntimeViewer 或库内的使用方丢掉这些扩展**:不成立。`SwiftDeclarationPrinter.swift` 只在 `parent` 与 `extensionContext` 都为空时把默认实现扩展接在协议后面,这是提案 [draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md) 有意改的契约;库里唯一调用 `printProtocolDefinition` 的 `SwiftInterfaceBuilder` 在顶层区块按同一条件补上(diff / evolution 只打印协议头,扩展整桶另印,从不依赖打印器接在后面;dump 不走这个打印器)。RuntimeViewer 那边被点名的分支在跳过之后紧接着又把同一桶扩展无条件追加了一次,所以不丢;与本 PR 配套的是它的 `feature/find-navigator`,用的条件与这里相同。(本轮另修的第 4 条是另一回事:协议在第五块才被索引,第四块读到的列表是空的。) +- **二、离线特化把 `.metadata` 实参当指针用,文件里读出的 `Metadata` 会成野指针**:不成立。离线 `specialize` 的文档(`GenericSpecializer+StaticSpecialization.swift` 开头)与 [OfflineGenericSpecialization.md](OfflineGenericSpecialization.md) 都写明 `.metatype` / `.metadata` / `.specialized` 是宿主进程自己的类型;`.specialized` 的 `metadata()` 先从内存读 kind,只可能是已经解引用过的进程内地址。在线路径对 `.metadata` 一直有同样的前提,误用时同样会崩,不是本 PR 引入的新风险。 +- **三、特化后的泛型 enum 跳过解析不出的 payload,会算出错误的 Enum Layout**:不成立。`RuntimeFieldLayoutBackend` 在打印布局前用 value witness table 的 size 交叉校验(`impliedTotalSize` 与 `typeLayout.size` 不等就不出注释),这条校验是 `12232bee` 专门为这类缺口加的,对特化的泛型 enum 同样生效;跳过 payload 只会让注释消失,不会印出错的布局。非泛型 enum 在基线上就这样跳过。 +- **四、`GenericParameterDepthLayout` 跳过匿名上下文,让泛型方法的 opaque 描述符层号算错、thunk 名字跟着错**:不成立。层结构确实把方法的参数与 opaque 参数并成一层,但 kind-9 thunk 的实参缓冲只按命名声明的签名绑定(编译器 `AbstractMetadataAccessor::emit` 取 `O->getGenericSignature()`),不含 opaque 参数;两种层结构只在第三个字及以后不同,那里放的是 witness table,从不被命名。基线用 `AccessorThunkOwnerLayout(genericContext:)` 算出的是同一个结构,PR 只是把计算挪了位置。 +- **既往修复**:无。 +- **复审条件**:上面任何一条的前提被改动——打印器或 RuntimeViewer 改了追加扩展的条件;离线特化开始接受文件里读出的 `Metadata`;enum 布局的 size 交叉校验被拿掉;thunk 的实参缓冲开始带 opaque 参数。 diff --git a/Roadmaps/2026-10-08-pr131-review-findings.md b/Roadmaps/2026-10-08-pr131-review-findings.md new file mode 100644 index 000000000..82392c5d8 --- /dev/null +++ b/Roadmaps/2026-10-08-pr131-review-findings.md @@ -0,0 +1,1758 @@ +# PR #131 review findings(RuntimeViewer Find 配套 + 离线泛型特化,2026-10-08) + +`/code-review max` 对 PR #131(`feature/runtime-viewer/find-navigator` → `next`,13 个 commit、90 个文件、+5540/−625)给出 15 条发现。这份记录逐条按四问(能否复现 / 基线有没有 / 值不值得修 / 以前修过没有)裁决,并为每条附上复现测试、修法 diff 和修前修后的示例。 + +**当前状态:已落地(2026-10-08)。** 用户审完这份记录后说「把发现的问题修一下吧」。有修法的 13 条(第 1–8、10、11、13–15 条,含原本建议「离线模式接入前修」的第 5、11 条)全部修掉,每条连同它的复现测试一个 commit;第 9、12 条登记不修。第 7 条横向排查查出的四处同类写法(落地清单第 6 项)也在这一批修掉,配新测试。登记项见 [ReviewAdjudications.md](../Documentations/Internal/ReviewAdjudications.md) A53–A59,其中包括 review 时被核验驳回的四条候选。提交与本机验证见文末「六、落地记录」。 + +下面几条是记录写成时(2026-10-08 凌晨,那时只落记录、代码未改)的状态: + +- **复现测试**:10 个测试文件,另在共享 fixture `GenericSpecializationFixture` 里加了一个类型,写在 JHs-Mac-Studio-Ultra 的 `.worktrees/MachOSwiftSection-FindNavigator` 里,未提交。在 PR 头 `beae202d` 上 14 个测试全部失败(第 6 条带两组参数,共 15 个用例),失败原因与发现描述一致。 +- **修法**:只在沙盒副本里改过、验证过。修后 14 个复现测试和第 13 条的 1 个守护测试全部通过;全量 2354 个测试、447 个套件全部通过(退出码 0,唯一一条 known issue 是 `next` 上本来就有的 `SymbolicManglingIndexTests`)。 +- **第 13 条的修法改过一次**:第一版整个替换了旧逻辑,测试全绿,但实测把一个本来能用的形状弄坏了,现在的版本保留旧逻辑作为另一条路径。经过写在第 13 条里。 +- **diff 怎么读**:下文每条的 diff 都摘自沙盒与 worktree 的逐文件比较。同一个文件里属于不同条目的改动,拆到了各自的条目下(比如 `ConformanceProvider.swift` 分在第 2、5 条),所以个别 hunk 头的行数是整个 hunk 的,与条目下显示的行数不一致。能直接打上的完整补丁是 `…/Logs/ReviewFixes/all-fixes.diff`(20 个文件,+449/−90),已用 `git apply --check` 确认能干净打到 worktree 上。只挑一部分修时,我再按条目切出对应的补丁。 +- 对比基线:`git diff next...feature/runtime-viewer/find-navigator`(PR 头 `beae202d`)。已裁决清单([ReviewAdjudications.md](../Documentations/Internal/ReviewAdjudications.md) A1–A52)里没有覆盖这 15 条的条目。 + +## 总表 + +| # | 问题 | 严重度 | 从哪来 | 复现测试 | 建议 | +|---|---|---|---|---|---| +| 1 | opaque 类型的实参按「第几张表」当层号 | 中 | 基线就有(2025-12 起) | `OpaqueTypeArgumentDepthTests` | 合并前修 | +| 2 | 离线检查把 Cocoa 子类判成违反基类约束 | 中 | PR 引入 | `OfflineObjectiveCBaseClassTests` | 合并前修 | +| 3 | 「参数 == 参数」的 same-type 约束补不出参数 | 低到中 | PR 引入 | `TiedParameterInstantiationTests` | 合并前修 | +| 4 | extension 里协议兜底补出的默认实现无处打印 | 低 | PR 引入 | `ProtocolInExtensionDefaultWitnessTests` | 合并前修 | +| 5 | 带条件的协议遵循被当成成立 | 低 | PR 引入 | `OfflineConditionalConformanceTests` | 离线模式接入前修 | +| 6 | 静态展开偏移把 opaque 类型印成占位符 | 低 | PR 引入 | `NestedFieldOffsetOpaqueWitnessTests` | 合并前修 | +| 7 | `specializedChildren` 无锁追加 | 低到中 | 机制旧,PR 扩大 | `ConcurrentSpecializationTests` | 合并前修 | +| 8 | opaque provider 少数一层 | 低到中 | 基线就有(2026-09-18 起) | `OpaqueParameterInMultiDepthExtensionTests` | 合并前修 | +| 9 | 等待索引时的优先级反转 | 低 | PR 引入 | 无(没有可测的行为) | 不修,登记 | +| 10 | 在线特化算类型名失败时静默退回 | 低 | PR 引入 | 由第 3 条的在线测试覆盖 | 合并前修(补日志) | +| 11 | 字段类型与布局注释读的是两套镜像 | 低 | 机制旧,PR 扩大 | `OfflineProjectionDependencyResolutionTests`(只在本机跑) | 离线模式接入前修 | +| 12 | 嵌套偏移缓存会记住「解析失败」 | 低 | PR 有意如此 | 无 | 本库不修,登记;转 RuntimeViewer | +| 13 | thunk 类型构造器认不出泛型 extension 里的泛型类型 | 低 | 基线就有(2026-09-12 起) | `AccessorThunkTypeInGenericExtensionTests` | 合并前修 | +| 14 | 关联类型投影没有提前返回 | 低(性能) | PR 引入 | 无 | 合并前修 | +| 15 | CI 覆盖 | 低 | PR 引入 | 无 | 合并前修 | + +第 1、8、13 条与 PR 声称已整类修掉的「泛型参数层号数错」同属一类(PR 修了五处,漏了这三处)。按全库扫描,除这八处外没有别的地方用父链数层号。 + +## 验证环境 + +- **修后沙盒**:`/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorMerge/MachOSwiftSection`,是 `beae202d` 的副本加复现测试加全部修法。它只链了 swift-semantic-string 一个本地依赖(`DefinitionRegion` 只在它的 `next` 上),其余依赖按 `next` 要求的发布版解析(MachOKit 0.54.101、MachOKitExtensions 1.1.2、MachOObjCSection 0.8.109、swift-demangling 0.7.1、FrameworkToolbox 0.15.0)。构建目录 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-FindNavigatorSandbox`。 +- **基线沙盒**:`/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorReviewBaseline/MachOSwiftSection`,PR 头加复现测试,不带修法,用来确认复现测试失败。两个沙盒共用同一份 `Package.resolved`。 +- 命令:在沙盒目录里 `USING_LOCAL_DEPENDENCIES=1 queued-build swift test --scratch-path <构建目录> --filter …`;工具链 Swift 6.4(Xcode 27),机器 JHs-Mac-Studio-Ultra。 +- 日志(`…` = `/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorMerge`): + - 修前:`…/Logs/ReviewRepro/`(最初的复现与诊断),`…/Logs/ReviewBaselineFinal/repro-suites.log`(最终版测试在 PR 头上的结果)。 + - 修后:`…/Logs/ReviewFixes/`,其中 `full-suite-2.log` 是最终的全量,`examples-after.log` 是 10 个复现套件,`all-fixes.diff` 与 `PerFile/` 是补丁。带 `first-version` 字样的文件和 `full-suite.log` 对应第 13 条第一版修法,留作记录。 + - 第 13 条守护测试的对照:`…/Logs/ReviewBaselineFinal/guard-test-pr-head.log`、`guard-test-first-fix.log`。 + - CLI 示例:`…/Logs/ReviewFixes/Examples/`,同一个输入分别用三个 CLI 跑: + - `release-0.21.0`:本机装的 0.21.0 release CLI,代表 `next` 的行为(这些代码路径上两者相同); + - `pr-head`:基线沙盒编出的 debug CLI; + - `fixed`:修后沙盒编出的 debug CLI。 + - 实验二进制与源码:`/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorReviewRepro/experiments/`,与对应复现测试的 fixture 源码相同,只是单独编出来给 CLI 用,所以 opaque 描述符的偏移和测试里的不一样。 + +## 一、建议合并前修 + +### 1. opaque 类型的实参按「第几张表」当层号(中,基线就有) + +`Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift:52`(`opaqueTypeGenericArgumentsByDepth`),调用点 `:415`。 + +opaque 类型(`some View` 这类不透明返回类型)的引用会带上泛型实参:每一层外围声明一张实参表。重写器解析它的底层类型时,把「第几张表」直接当成参数的层号用。 + +- **能复现吗**:能。 + - 真实二进制:0.21.0 对 `/Applications/Xcodes.app` 的 `interface -a arm64` 在非泛型的 `MainToolbarModifier` 里印出 `SwiftUI.TupleToolbarContent`,共两处。 + - 原因已对照 Swift 6.4 源码确认。编译器 `ASTMangler::appendBoundGenericArgs` 给每一层外围声明都写一张表,不声明参数的层写空表。运行时 `resolveOpaqueType` 则先把所有表拍平,再按描述符自己的层结构重新分组(`_gatherGenericParameters`),从不把位置当层号。 + - 后果:外围只要有一层不声明参数(写了空表),它后面的每张表都被错当成往外一层的。最外的泛型层去空表里找实参,落空、留下裸 `A`;再往里的层拿到的是外一层的实参,印出「真实但错误」的类型(测试里 `makePair` 的 `Extra` 拿到了 `Boxed` 的 `Int`)。 +- **基线有没有**:`next` 与 0.21.0 都有,这段代码从 2025-12-16 的 `5e7373fa` 起就按位置取层号。PR 在同一个文件里新加了 `ReadOpaqueType`,已经算出正确的层结构,但这个函数没用上。 +- **值不值得修**:值得。普通 SwiftUI app 的 dump、interface 和 RuntimeViewer 都会走到(进程内路径用的是同一张表)。改动小。 +- **以前修过吗**:没有。2026-09-11 的 `a85b172d` 修过同一个函数的另一个 bug(`for type in typeListNode` 按 preorder 遍历,取到了 typeList 节点本身)。那次验收只统计「depth ≥ 1 的裸参数残留」(178 → 10),层号 0 上因空表留下的裸 `A` 不在统计范围内。 + +**复现测试** `Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift`(2 个测试)。fixture 里 `ProbeNamespace` 是不声明参数的 `enum`,按编译器的写法,`makeWrapper` 的实参表是 `[[], [Element]]`,`Box.makePair` 的是 `[[], [Boxed], [Extra]]`。测试照这个形状手工拼出 opaque 节点(做法同 `OpaqueTypeOrdinalTests`;编译器会把能看透的 opaque 类型直接代换进本模块的反射记录,fixture 造不出仍引用描述符的记录),再交给 `resolveOpaqueType(in:)`: + +```swift +public enum ProbeNamespace { + public static func makeWrapper(_ element: Element) -> some ProbeShape { ProbeWrapper(wrapped: element) } + public struct Box { + public func makePair(_ extra: Extra) -> some ProbeShape { ProbePair(first: boxed, second: extra) } + } +} +// 实参表 [[], [Int]] → 期望 ProbeWrapper +// 实参表 [[], [Int], [String]] → 期望 ProbePair +``` + +修前: + +``` +resolved → "OpaqueTypeArgumentDepthFixture.ProbeWrapper" +resolved → "OpaqueTypeArgumentDepthFixture.ProbePair" ← Extra 的位置拿到了 Boxed 的实参 +``` + +**修法**:先把各层实参表按顺序拍平,再用 opaque 描述符的 `GenericParameterDepthLayout` 重新分组,这正是运行时的做法。`ReadOpaqueType` 已经算出了这个层结构,多存一份传进去即可。新参数默认 `nil`:不传时仍按位置分组,`OpaqueReferenceSpelling.swift:137`(只拍平使用)和现有单测不受影响。重写器本身、ordinal 的处理不动。 + +```diff +--- a/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift ++++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift +@@ -38,7 +38,7 @@ + + extension Node { + /// The generic arguments an `opaqueType` node carries, keyed by the depth +- /// each level substitutes. ++ /// of the parameter each one binds. + /// + /// Internal rather than private for the same reason the rewriter below is: + /// reaching this through `resolveOpaqueType(in:)` needs a binary that +@@ -47,10 +47,26 @@ + /// leaves a parameter unsubstituted (printing `A` / `A1`) or substitutes a + /// type belonging to a different parameter, and neither raises. + /// +- /// The walk mirrors `TypeDecoder.decodeMangledType`'s over the same child, +- /// including its stop at the first level that is not a `typeList`. +- static func opaqueTypeGenericArgumentsByDepth(of opaqueTypeNode: Node) -> OrderedDictionary { ++ /// The node spells one argument list per declaration around the opaque ++ /// result, outermost first, and the mangler writes a list for EVERY such ++ /// declaration — an empty one for a level that declares no parameter ++ /// (`ASTMangler::appendBoundGenericArgs`). A list's position is therefore ++ /// not its depth: the runtime flattens the lists and regroups them by the ++ /// descriptor's own depths (`resolveOpaqueType` → ++ /// `_gatherGenericParameters`), and so does this, given the opaque type ++ /// descriptor's `depthLayout`. Keyed by position instead, the argument of ++ /// a generic function in a non-generic type was looked up in the type's ++ /// empty list and never substituted (Xcodes' `MainToolbarModifier.Body` ++ /// printed `SwiftUI.TupleToolbarContent`). Without a layout the lists ++ /// stay keyed by position, which is right whenever no level around the ++ /// result is non-generic. ++ /// ++ /// The walk over the lists mirrors `TypeDecoder.decodeMangledType`'s over ++ /// the same child, including its stop at the first level that is not a ++ /// `typeList`. ++ static func opaqueTypeGenericArgumentsByDepth(of opaqueTypeNode: Node, depthLayout: GenericParameterDepthLayout? = nil) -> OrderedDictionary { + var argumentsByDepth: OrderedDictionary = [:] ++ var flattenedArguments: [Node] = [] + guard let rootTypeListNode = opaqueTypeNode[safeChild: 2] else { return argumentsByDepth } + for (depth, typeListNode) in rootTypeListNode.children.enumerated() { + guard typeListNode.isKind(of: .typeList) else { break } +@@ -63,8 +79,17 @@ + // parameter read whatever preorder left at its index: the element + // to its left, or a fragment of that element's subtree. + argumentsByDepth[depth] = Array(typeListNode.children) ++ flattenedArguments.append(contentsOf: typeListNode.children) + } +- return argumentsByDepth ++ guard let depthLayout else { return argumentsByDepth } ++ var argumentsByParameterDepth: OrderedDictionary = [:] ++ for (flatIndex, argument) in flattenedArguments.enumerated() { ++ // More arguments than the descriptor has parameters: a list this ++ // walk misread, so the positional reading is the one left. ++ guard let position = depthLayout.position(ofParameterAt: flatIndex) else { return argumentsByDepth } ++ argumentsByParameterDepth[position.depth, default: []].append(argument) ++ } ++ return argumentsByParameterDepth + } + + /// Substitutes an opaque type's generic parameters with the concrete +@@ -412,7 +437,7 @@ + // carries ordinal 0, so this is correctness for a shape + // those two do not have and a client binary may. + let ordinal: Int = node[safeChild: 1]?.index?.cast() ?? 0 +- let allTypeList = Node.opaqueTypeGenericArgumentsByDepth(of: node) ++ let allTypeList = Node.opaqueTypeGenericArgumentsByDepth(of: node, depthLayout: readOpaqueType.depthLayout) + guard let underlyingTypeArgumentMangledName = opaqueType.underlyingTypeArgumentMangledNames[safe: ordinal] else { return nil } + let underlyingTypeArgumentNode: Node? + if machO is MachOImage { +@@ -688,14 +713,20 @@ + fileprivate struct ReadOpaqueType { + let opaqueType: OpaqueType + let ownerLayout: AccessorThunkOwnerLayout ++ /// How the descriptor's parameters split into depths: what regroups the ++ /// argument lists of a reference to it (`opaqueTypeGenericArgumentsByDepth`). ++ /// `nil` for a descriptor with no generic context. ++ let depthLayout: GenericParameterDepthLayout? + + init(_ opaqueType: OpaqueType, in context: some ReadingContext) { + self.opaqueType = opaqueType + if let genericContext = opaqueType.genericContext { + let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .opaqueType(opaqueType.descriptor), in: context) + self.ownerLayout = AccessorThunkOwnerLayout(genericContext: genericContext, depthLayout: depthLayout) ++ self.depthLayout = depthLayout + } else { + self.ownerLayout = AccessorThunkOwnerLayout(genericContext: nil as GenericContext?) ++ self.depthLayout = nil + } + } + } +``` + +一个容易担心的点:命名声明本身是泛型时,opaque 描述符的「自有」层会把函数参数和 opaque 参数并成一层,看起来像是层数算错了。但实参表只覆盖命名声明的签名,opaque 参数总在最后、不在表里,所以按扁平下标取位置仍然正确:`Box.makePair` 的 `[Boxed, Extra]` 落到 `(0,0)`、`(1,0)`。 + +**修后**:两个测试通过;`OpaqueTypeGenericParameterSubstitutionTests`、`OpaqueTypeOrdinalTests` 等现有 opaque 套件不变。 + +``` +resolved → "OpaqueTypeArgumentDepthFixture.ProbeWrapper" +resolved → "OpaqueTypeArgumentDepthFixture.ProbePair" +``` + +真实二进制:`interface -a arm64 /Applications/Xcodes.app/Contents/MacOS/Xcodes`,第 4311 行。0.21.0 与 PR 头相同: + +```swift +extension Xcodes.MainToolbarModifier: SwiftUI.ViewModifier { + typealias Body = SwiftUI.ModifiedContent, SwiftUI.ToolbarModifier<(), SwiftUI.TupleToolbarContent>> +``` + +修后(原文是一整行,这里按层级拆开,`…` 是省略的部分): + +```swift +typealias Body = SwiftUI.ModifiedContent< + SwiftUI._ViewModifier_Content, + SwiftUI.ToolbarModifier<(), SwiftUI.TupleToolbarContent< + SwiftUI.ToolbarItemGroup>…>, + SwiftUI.Spacer, + SwiftUI.ModifiedContent<…SwiftUI.Menu, …>…> + )>> + >> +> +``` + +整份 interface(11603 行)修后只变了两行:第 4311 行和第 4898 行,修前都含 `TupleToolbarContent`。0.21.0 与 PR 头的输出完全相同。 + +解开后的类型里有 `accessor function at 8328`。这是另一个既有的限制:同一份输出里,修前就已有 6 行、13 处这个占位符(kind-9 accessor thunk 没解出来),以前这一处藏在 `A` 后面看不到。与本条无关,不在这次修。 + +**落地时**:这条会改变普通 SwiftUI app 的 interface 输出,渲染 A/B 必跑。`Internal/OpaqueReturnTypeResolution.md` 补一句「实参表按描述符的层结构重新分组」。 + +### 2. 离线检查把 Cocoa 子类判成违反基类约束(中,PR 引入) + +`Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift:443`(`checkBaseClass`)。 + +- **能复现吗**:能。`` 选 `FixtureOperation: Operation` 时,离线 `staticPreflight` 报错,`specialize` 抛错,在线(运行时)路径却接受同样的选择。原因有两层: + - `ConformanceProvider.subclasses(of:)` 的类层级图只连得起**已索引的 Swift 类**。`FixtureOperation → NSOperation → NSObject` 断在中间的 ObjC 类上,于是 `FixtureOperation` 不在 `NSObject` 的子树里。检查又因为它「已被索引」,就判成确定违反。 + - `subclasses(of:)` 的结果总以基类自己开头,所以「索引里没有这个类层级」那条警告分支永远走不到。 +- **基线有没有**:离线检查是 PR 新代码;在线路径由运行时判断,不受影响。 +- **值不值得修**:值得。``、``、`` 是最常见的基类约束,离线模式一接上宿主就会误拒合法特化,违背 PR 自己定的「证明不了只给警告」原则。 +- **以前修过吗**:没有。`subclasses(of:)` 是 2026-05-10 的 `a209e2b3` 为缩小候选列表写的,空结果的含义是「不缩小」,以前从没被当成证据用过。 + +**复现测试** `Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift`(2 个测试,自带一个 `import Foundation` 的小 fixture): + +```swift +public final class FixtureOperation: Operation {} +public final class FixtureObject: NSObject {} +public struct ObjectBound { public var subject: Subject } +``` + +候选是从索引器的定义手工构造的:请求里的候选列表同样被那张类层级图缩小过,所以 `FixtureOperation` 根本不在列表里。这个「候选列表缺类」是基线既有的问题,在线路径也一样,这里不修。修前: + +``` +staticPreflight → isValid == false +specialize → specializationFailed("Type 'ObjectiveCBaseClassFixture.FixtureOperation' for parameter 'A' does not inherit from required base class 'NSObject'") +``` + +**修法**:沿实际类的父类链往上走。走到基类就通过;走到根类还没碰到基类才报错;链走出已索引的类(ObjC 类,或索引器没收录的镜像里的类)就给警告。为此给 `ConformanceProvider` 加一个带默认实现的 `superclassLink(of:)`,库外的遵循者不用改。`IndexerConformanceProvider` 在建子类图的同一遍循环里顺手记下反向链接,名字一律去掉实参后再比较,否则 `BaseBox` 和 `BaseBox` 对不上。死分支随之删掉。 + +```diff +--- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift ++++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +@@ -463,17 +474,33 @@ + builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) + return + } +- let subtree = conformanceProvider.subclasses(of: expectedClassName) +- guard !subtree.isEmpty else { +- builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: the indexed images describe no class hierarchy under \(expectedDisplay)")) +- return ++ // Up the superclass chain the indexed images describe, class names ++ // compared unbound. Reaching the base proves the requirement; a root ++ // class reached without it proves the violation. A link no indexed ++ // image describes proves nothing either way: an Objective-C class — ++ // `NSOperation` between a Swift class and an `NSObject` bound — or a ++ // class of an image the indexer does not hold. Taking that for a ++ // violation rejected every Swift class below a Cocoa class, which the ++ // runtime accepts. ++ var currentClassName = actualTypeName ++ var visitedClassNames: Set = [] ++ while visitedClassNames.insert(currentClassName.name).inserted { ++ if currentClassName.name == expectedClassName.name { return } ++ switch conformanceProvider.superclassLink(of: currentClassName) { ++ case .inherits(let superclassName): ++ currentClassName = unboundNominalTypeName(of: superclassName.node.materialize(), kind: .class) ?? superclassName ++ case .root: ++ builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) ++ return ++ case .unknown: ++ let reason = currentClassName.name == actualTypeName.name ++ ? "offline: \(subject.display) is in no indexed image, so its superclass chain cannot be read" ++ : "offline: the superclass chain of \(subject.display) leaves the indexed images at \(currentClassName.name), so whether it reaches \(expectedDisplay) cannot be read" ++ builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: reason)) ++ return ++ } + } +- if subtree.contains(where: { $0.name == actualTypeName.name }) { return } +- if conformanceProvider.typeDefinition(for: actualTypeName) != nil { +- builder.addError(.baseClassRequirementNotSatisfied(parameterName: subject.path, expectedBaseClass: expectedDisplay, actualType: subject.display)) +- } else { +- builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: \(subject.display) is in no indexed image, so its superclass chain cannot be read")) +- } ++ builder.addWarning(.baseClassRequirementResolutionFailed(parameterName: subject.path, reason: "offline: the superclass chain of \(subject.display) loops back on itself")) + } +``` + +`ConformanceProvider.swift` 里的配套改动(与第 5 条的 `isConditionalConformance` 写在同一处,第 5 条另列): + +```diff +--- a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift ++++ b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift +@@ -49,8 +49,34 @@ + /// no class-hierarchy knowledge degrade to "show every candidate" + /// without breaking the contract. + func subclasses(of baseClassName: TypeName) -> [TypeName] ++ ++ /// What the provider knows of the class `className` inherits from ++ /// directly — the link the offline base-class check walks up (evolution ++ /// proposal `offline-generic-specialization`). Default `.unknown`: a ++ /// provider without class-hierarchy knowledge proves nothing either way. ++ func superclassLink(of className: TypeName) -> SuperclassLink + } + ++/// A class's direct superclass, as a `ConformanceProvider` knows it. ++public enum SuperclassLink: Sendable, Equatable { ++ /// The provider describes the class, and it inherits from this class. ++ case inherits(from: TypeName) ++ /// The provider describes the class, and it has no superclass. ++ case root ++ /// The provider holds no description of the class: an Objective-C ++ /// class, or a class of an image it does not index. ++ case unknown ++} ++ + // MARK: - Default Implementations + + extension ConformanceProvider { +@@ -78,6 +104,14 @@ + public func subclasses(of baseClassName: TypeName) -> [TypeName] { + [] + } ++ ++ public func superclassLink(of className: TypeName) -> SuperclassLink { ++ .unknown ++ } + } + + // MARK: - IndexerConformanceProvider +@@ -111,6 +145,9 @@ + /// (`TypeName.name`, "Module.Type") is stable across both paths. + private final class SubclassCache: @unchecked Sendable { + var directChildrenByParentName: [String: [TypeName]]? ++ /// Every indexed class's direct superclass by the class's name: the ++ /// same links, read the other way, built in the same walk. ++ var superclassLinkByClassName: [String: SuperclassLink]? + let lock = NSLock() + } + +@@ -152,7 +189,7 @@ + // return empty so callers can fall back to "do not narrow". + guard baseClassName.kind == .class else { return [] } + +- let directChildren = directChildrenMap() ++ let directChildren = classHierarchy().directChildrenByParentName + + // BFS over the parent → direct-subclasses graph, keyed by + // canonical name string. Result list still uses `TypeName`s +@@ -171,18 +208,37 @@ + } + } + return result ++ } ++ ++ public func superclassLink(of className: TypeName) -> SuperclassLink { ++ guard className.kind == .class else { return .unknown } ++ return classHierarchy().superclassLinkByClassName[className.name] ?? .unknown + } + + /// Build (or fetch from cache) the parent-name → direct-subclasses +- /// map by walking every indexed `.class` definition's ++ /// map, and the class-name → superclass map that reads the same links ++ /// the other way, by walking every indexed `.class` definition's + /// `superclassType` link. Lock-protected so concurrent first-callers + /// don't both pay the O(n) build cost. +- private func directChildrenMap() -> [String: [TypeName]] { ++ private func classHierarchy() -> (directChildrenByParentName: [String: [TypeName]], superclassLinkByClassName: [String: SuperclassLink]) { + subclassCache.lock.lock() + defer { subclassCache.lock.unlock() } +- if let cached = subclassCache.directChildrenByParentName { return cached } ++ if let cachedChildren = subclassCache.directChildrenByParentName, let cachedLinks = subclassCache.superclassLinkByClassName { ++ return (cachedChildren, cachedLinks) ++ } + + var map: [String: [TypeName]] = [:] ++ var links: [String: SuperclassLink] = [:] + for (childTypeName, entry) in indexer.allAllTypeDefinitions { + guard childTypeName.kind == .class else { continue } + guard case .class(let classDescriptor) = entry.value.typeContextDescriptorWrapper else { continue } +@@ -212,14 +268,18 @@ + } + + // A missing / unreadable superclass link is the ordinary "this class +- // has no usable parent" case and stays silent. ++ // has no usable parent" case and stays silent. Missing is a root ++ // class; unreadable stays unknown, proving nothing. + var superNode: Node? + do { + superNode = try classWrapper.superclassNode(in: entry.machO.context) + } catch { + continue + } +- guard let superNode else { continue } ++ guard let superNode else { ++ links[childTypeName.name] = .root ++ continue ++ } + + // `SymbolicDemangler.demangleType` may wrap the result in a + // `.type` node or return a deeper tree depending on the +@@ -240,10 +300,12 @@ + } + let superTypeName = TypeName(node: InternedNodeReferenceCache.shared.reference(interning: superNode, in: entry.machO), kind: .class) + map[superTypeName.name, default: []].append(childTypeName) ++ links[childTypeName.name] = .inherits(from: superTypeName) + } + + subclassCache.directChildrenByParentName = map +- return map ++ subclassCache.superclassLinkByClassName = links ++ return (map, links) + } + } + +@@ -333,6 +395,20 @@ + } + return result + } ++ ++ /// The first provider that describes the class answers: a class lives in ++ /// one image, so at most one sub-indexer knows its superclass link. ++ public func superclassLink(of className: TypeName) -> SuperclassLink { ++ for provider in providers { ++ let link = provider.superclassLink(of: className) ++ if link != .unknown { return link } ++ } ++ return .unknown ++ } + } +``` + +仍有的局限(基线就有,不在这次修):比较的是**去掉实参的类名**,`>` 选 `DerivedBox` 时会被放行。要比到实参,得沿父类链做实参代换,留作以后。可选增强:用现成的 `ObjCAncestorResolver` 顺着依赖闭包把 ObjC 祖先也读出来,这样 `NSOperation → NSObject` 能直接证明,连警告都不用给。 + +**修后**:2 个测试通过,`OfflineSpecializationTests` 里原有的三条基类测试(不相关的类报错、子类通过、宿主类报错)不变。同一个选择现在是零个错误、一条警告: + +``` +Could not resolve required base class for parameter 'A'; preflight skipped the inheritance check: offline: the superclass chain of ObjectiveCBaseClassFixture.FixtureOperation leaves the indexed images at __C.NSOperation, so whether it reaches NSObject cannot be read +``` + +**落地时**:`ConformanceProvider` 多了一个带默认实现的 requirement 和一个公开枚举 `SuperclassLink`,进 0.22.0 发版说明;`Internal/OfflineGenericSpecialization.md` 的「离线约束检查」一节改写基类那一条。 + +### 3. 「参数 == 参数」的 same-type 约束补不出参数(低到中,PR 引入;含第 10 条可测的一侧) + +`Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift:82`(`fillFixedParameters`)。 + +- **能复现吗**:能,SymbolTestsCore 里现成的 `SameTypeRequirementTest where First == Second` 就是这个形状。编译器把仍带 key argument 的参数写在约束**左边**(`First == Second`),不带 key argument 的 `Second` 在右边。`fillFixedParameters` 只按左边记约束,于是 `Second` 永远补不上。 + - 离线:`GenericInstantiation` 抛 `unresolvedFixedParameter`,`specialize` 把它包成 `specializationFailed` 抛出。 + - 在线:`try?` 静默退回扁平名 ``(见第 10 条),而类型头印的是运行时的 ``。 + - 运行时 `_gatherWrittenGenericParameters`(Swift 6.4 源码 `stdlib/public/runtime/MetadataLookup.cpp`,函数从 3575 行起)在 3686 行前后有「左边已有实参、右边也是参数,就抄给右边」的分支,PR 移植时漏了。 +- **基线有没有**:`GenericInstantiation` 是 PR 新代码;在线类型名的形状也是 PR 改的。 +- **值不值得修**:值得。用户无法绕开。这个写法放在类型声明上,Swift 6 语言模式会报错(Swift 5 只是警告);但放在 extension 上一直合法(`extension Pair where First == Second { struct Nested }`,已用 `-swift-version 6` 编过),所以新代码里同样会出现。extension 这个形状走的是同一段补参数的逻辑,没有单独测。改动小。 +- **以前修过吗**:没有。 + +**复现测试** `Tests/SwiftSpecializationTests/TiedParameterInstantiationTests.swift`(2 个测试)。为了离线、在线两条路都能测,并能拿运行时的名字作对照,形状加在共享 fixture `GenericSpecializationFixture` 里(它用 Swift 5 模式编译,这个写法只是警告): + +```diff +--- a/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift ++++ b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationFixture.swift +@@ ++ // `Second` is tied to `First`, so it takes no key argument: the compiler ++ // writes the requirement as `First == Second`, the parameter that keeps ++ // its key argument on the left, and the instantiation binds `Second` to ++ // `First`'s argument. A warning in the fixture's Swift 5 mode. ++ public struct TiedParameterPair where First == Second { ++ public var first: First ++ public var second: Second ++ } +``` + +用到这个共享 fixture 的 9 个现有套件(`OfflineSpecializationTests`、`OfflineSpecializationParityTests`、`InstantiatedTypeNameTests`、`CanonicalParameterDepthTests`、`BoundInstantiationLayoutTests`、`ExtensionContextInstantiationLayoutTests`、`AccessorThunkOwnerLayoutDepthTests`、`GenericParameterDepthNamingTests`、`GenericParameterDepthDumpTests`)加了这个类型后全部仍然通过。修前: + +``` +离线:specializationFailed(reason: "could not bind the type's parameters: the argument of B, which a same-type requirement fixes, could not be determined from that requirement") +在线:specialized GenericSpecializationFixture.TiedParameterPair runtime GenericSpecializationFixture.TiedParameterPair +``` + +**修法**:收集 same-type 约束时,右边也是参数的另记一份;补参数时先按原逻辑用右边的类型补,补不上就看自己是不是某条约束的右边、左边已有实参,有就抄过来。迭代到不动点的逻辑不变。 + +```diff +--- a/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift ++++ b/Sources/Declaration/SwiftSpecialization/GenericInstantiation.swift +@@ -79,6 +79,11 @@ + /// requirement that fixes it. A right-hand side can name another fixed + /// parameter (`C == B`, `B == Int`), so the requirements are applied until + /// no further one resolves. ++ /// ++ /// A requirement between two parameters (`First == Second`) is read both ++ /// ways, as the runtime's `_gatherWrittenGenericParameters` reads it: the ++ /// compiler writes the parameter that keeps its key argument on the LEFT, ++ /// so it is the right-hand parameter that takes the left one's argument. + private static func fillFixedParameters( + _ argumentsByFlatIndex: inout [Node?], + depthLayout: GenericParameterDepthLayout, +@@ -89,16 +94,26 @@ + guard !unresolvedFlatIndices.isEmpty else { return } + + // The same-type requirements whose subject is a parameter itself, by +- // that parameter's position in the cumulative list. ++ // that parameter's position in the cumulative list; and, for those ++ // whose right-hand side is a parameter too, the left-hand parameter ++ // by the right-hand one's position. + var fixingRequirementByFlatIndex: [Int: MangledName] = [:] ++ var leftHandFlatIndexByRightHandFlatIndex: [Int: Int] = [:] + for requirement in requirements where requirement.layout.flags.kind == .sameType { + guard let subjectNode = try? SymbolicDemangler.demangleType(for: requirement.paramMangledName(in: machO.context), in: machO.context), + let position = genericParameterPosition(of: subjectNode), + let flatIndex = depthLayout.flatIndex(depth: position.depth, index: position.index), +- fixingRequirementByFlatIndex[flatIndex] == nil, + let rightHandSide = try? requirement.type(in: machO.context) + else { continue } +- fixingRequirementByFlatIndex[flatIndex] = rightHandSide ++ if fixingRequirementByFlatIndex[flatIndex] == nil { ++ fixingRequirementByFlatIndex[flatIndex] = rightHandSide ++ } ++ if let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context), ++ let rightHandPosition = genericParameterPosition(of: rightHandSideNode), ++ let rightHandFlatIndex = depthLayout.flatIndex(depth: rightHandPosition.depth, index: rightHandPosition.index), ++ leftHandFlatIndexByRightHandFlatIndex[rightHandFlatIndex] == nil { ++ leftHandFlatIndexByRightHandFlatIndex[rightHandFlatIndex] = flatIndex ++ } + } + + var didResolveParameter = true +@@ -106,13 +121,20 @@ + didResolveParameter = false + let partialBinding = Self.partialBinding(argumentsByFlatIndex, depthLayout: depthLayout) + for flatIndex in unresolvedFlatIndices { +- guard let rightHandSide = fixingRequirementByFlatIndex[flatIndex], +- let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context) +- else { continue } +- let argument = DependentMemberProjection.projectingConcreteMembers(in: partialBinding.substituting(in: rightHandSideNode), in: machO) +- guard !containsGenericParameter(argument) else { continue } +- argumentsByFlatIndex[flatIndex] = typeWrapped(argument) +- didResolveParameter = true ++ if let rightHandSide = fixingRequirementByFlatIndex[flatIndex], ++ let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSide, in: machO.context) { ++ let argument = DependentMemberProjection.projectingConcreteMembers(in: partialBinding.substituting(in: rightHandSideNode), in: machO) ++ if !containsGenericParameter(argument) { ++ argumentsByFlatIndex[flatIndex] = typeWrapped(argument) ++ didResolveParameter = true ++ continue ++ } ++ } ++ if let leftHandFlatIndex = leftHandFlatIndexByRightHandFlatIndex[flatIndex], ++ let leftHandArgument = argumentsByFlatIndex[leftHandFlatIndex] { ++ argumentsByFlatIndex[flatIndex] = leftHandArgument ++ didResolveParameter = true ++ } + } + unresolvedFlatIndices.removeAll { argumentsByFlatIndex[$0] != nil } + } +``` + +**修后**:2 个测试通过,在线名与运行时名结构相等。 + +``` +离线:GenericSpecializationFixture.TiedParameterPair (绑定 [["Swift.Int", "Swift.Int"]]) +在线:specialized GenericSpecializationFixture.TiedParameterPair runtime GenericSpecializationFixture.TiedParameterPair +``` + +### 4. extension 里协议兜底补出的默认实现无处打印(低,PR 引入) + +`Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift:248`。 + +interface 的打印顺序是:顶层类型 → 特化子类型 → 顶层协议 → 嵌套协议的默认实现 extension → 所有 extension。PR 的 `bca9594d` 把「声明在 extension 里的协议」的默认实现挪到了第四块;而这类协议自己要到第五块才被打印、被索引。 + +- **能复现吗**:能,已造出触发条件。library evolution 下,若协议需求的默认实现来自**父协议**的 extension(`Labeled: Base`,`describe()` 的默认实现写在 `extension Base` 里),编译器会生成一个挂在 `Labeled` 需求名下的默认 witness。模块索引器 `prepare()` 只扫协议 extension 块的符号,扫不到它;要等协议自己的索引过程兜底补出这个 extension。第四块读列表时协议还没索引,列表是空的;而打印器又不再在协议后面打印它,于是哪里都不打印。 +- **基线有没有**:改前打印在 `extension Swift.Int { … }` 的大括号里(位置不合法,但打印了): + + ```swift + extension Swift.Int { + protocol Labeled: ProbeDefaultWitness.Base { + func describe() -> Swift.String + } + extension Swift.Int.Labeled { + func describe() -> Swift.String + } + } + ``` + + PR 的修复把它挪走之后,这种情况就彻底消失了。属于 PR 引入的回退,只在这个窄形状上出现。 +- **值不值得修**:值得,改动小。 +- **以前修过吗**:没有。兜底逻辑来自 2026-08-22 的 `85b88b43`(提案 0007,统一 extension 容器),本意是「没有模块索引器时」才用;第四块的条件是 0007 修活的,PR 扩大了条件,但没考虑索引时机。 + +**复现测试** `Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift`(2 个测试,fixture 用 `-enable-library-evolution` 编): + +```swift +public protocol Base {} +extension Base { public func describe() -> String { "base" } } +extension Int { + public protocol Labeled: Base { func describe() -> String } +} +``` + +修前:顶层没有 `extension Swift.Int.Labeled`;同一个 builder 打印两次,结果不一样。第一次打印到第五块时协议才被索引,第二次打印时列表已经完整,第四块就把它印出来了。 + +**修法**:第四块读列表之前,先对协议调用 `index(in:)`(PR 已经让它同步、可重复调用、只跑一次),区块顺序不动。`printRootContents` 整个函数体是 `@SemanticStringBuilder`,直接写 `try? …` 会被当成要拼进输出的组件,所以包成一个小辅助函数。 + +```diff +--- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift ++++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift +@@ -246,7 +246,7 @@ + // of a parent; its blocks used to print inside that extension's + // braces (evolution proposal `nested-definition-regions`). + for protocolDefinition in indexer.allProtocolDefinitions.values where protocolDefinition.parent != nil || protocolDefinition.extensionContext != nil { +- for extensionDefinition in protocolDefinition.defaultImplementationExtensions { ++ for extensionDefinition in indexedDefaultImplementationExtensions(of: protocolDefinition) { + await printCatchedThrowing( + dispatchingTo: eventDispatcher, + context: .init(name: extensionDefinition.extensionName.name, kind: .extension) +@@ -267,6 +267,20 @@ + } + } + } ++ } ++ ++ /// `protocolDefinition`'s default-implementation extensions, read once ++ /// it is indexed. The list is complete only then: the protocol's own pass ++ /// synthesizes the extension of a default the module indexer's symbol scan ++ /// misses — under library evolution, a default witness named after the ++ /// requirement itself. A protocol nested in a type is indexed by the time ++ /// the nested protocols' block prints, its type printed before it; one ++ /// declared in an extension prints, and indexes, only in the extensions ++ /// block after it, so its synthesized extension printed nowhere. A pass ++ /// that fails is reported when the protocol prints. ++ private func indexedDefaultImplementationExtensions(of protocolDefinition: ProtocolDefinition) -> [ExtensionDefinition] { ++ try? protocolDefinition.index(in: machO) ++ return protocolDefinition.defaultImplementationExtensions + } + + private func collectModules() async throws { +``` + +横向排查:库里读 `defaultImplementationExtensions` 的只有这里和打印器(`SwiftDeclarationPrinter.swift:393`,读之前已经 `index(in:)`),没有别的遗漏。**RuntimeViewer 有同样的顺序问题**:`RuntimeSwiftSection.defaultImplementationExtensionsLeftToPrint(of:)` 也是直接读这个列表,需要在读之前确保协议已索引(那边改)。 + +**修后**:2 个测试通过;`ProtocolInExtensionTests` 不变。 + +CLI 对同一个 fixture 的 `interface`(只摘最后一段)。PR 头: + +```swift +extension Swift.Int { + protocol Labeled: ProbeDefaultWitness.Base { + func describe() -> Swift.String + } +} +``` + +修后: + +```swift +extension Swift.Int.Labeled { + func describe() -> Swift.String +} + +extension Swift.Int { + protocol Labeled: ProbeDefaultWitness.Base { + func describe() -> Swift.String + } +} +``` + +默认实现块出现在协议声明之前,这是 PR 定下的区块顺序(嵌套协议的默认实现 extension 块在所有 extension 之前),不是这次修法带来的。 + +**根因的另一种修法(未做)**:让 `prepare()` 的符号扫描也认出「挂在需求名下的默认 witness」,列表在 `prepare()` 之后就完整。改动大得多,眼下这处读取顺序的修法已经够用。 + +### 6. 静态展开偏移把 opaque 类型印成占位符(低,PR 引入) + +`Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift:102`(`projectingConcreteMembers`)。 + +PR 让静态展开偏移树的每一行都经过「关联类型投影」:`[Swift.Int].Element` 按 `Array` 遵循 `Collection` 时记录的实际类型(witness)读成 `Swift.Int`。但实际类型记录里可能是一个 opaque 类型引用,投影把它原样拼进了这一行。 + +- **能复现吗**:能,但要用对写法。编译器只要知道 opaque 结果的底层类型,就会把它直接写进本模块的记录,**开了 library evolution 也一样**(普通写法实测得到 `() -> Swift.Int`,测试通过)。会留下 opaque 引用的写法有三种:`dynamic` 的命名声明、按系统版本返回不同类型(SE-0360,`if #available`),以及另一个 resilient 模块里不可内联的 `some`。前两种已实测复现,第三种未实测。 +- **基线有没有**:改前(0.21.0)这一行印的是成员名: + + ``` + // └── make (() -> NestedFieldOffsetOpaqueWitnessFixture.DynamicConcrete.NestedFieldOffsetOpaqueWitnessFixture.Shape.Body): 0x0 + ``` + + PR 头变成占位符,属于 PR 引入的回退。 +- **值不值得修**:值得,改动小。只影响读文件(`MachOFile`)并打开展开字段偏移、而且关联类型的实际类型是 opaque 的字段。离线特化代换字段类型走的是同一个函数,一并受益。 +- **以前修过吗**:没有,新代码。 + +**复现测试** `Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift`(1 个测试 × 2 组参数): + +```swift +public struct DynamicConcrete: Shape { public dynamic var body: some Equatable { 1 } } +public struct ConditionalConcrete: Shape { + public var body: some Equatable { if #available(macOS 26, *) { return 1 } else { return "one" } } +} +public struct Wrapper { public var make: () -> Value.Body } +public struct DynamicHolder { public var wrapper: Wrapper } +public struct ConditionalHolder { public var wrapper: Wrapper } +``` + +修前: + +``` +make.typeName → "() -> opaque type symbolic reference 0x1A38.0" (DynamicHolder) +make.typeName → "() -> opaque type symbolic reference 0x1A60.0" (ConditionalHolder) +``` + +**修法**:投影出来的实际类型里含 opaque 引用(或 kind-9 accessor 引用)时不替换,保留成员名,也就是改前的输出。`[Int].Element → Int` 这类能正常投影的不受影响。另一种做法是走 opaque 重写器把它解开,但重写器在 `SwiftDeclarationRendering` 里,`SwiftLayout` 够不到;而且条件可用的 opaque 没有唯一的底层类型。 + +```diff +--- a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift ++++ b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift +@@ -119,7 +122,8 @@ + let baseTypeNode = rewrittenNode.children.first, + let associatedTypeReference = rewrittenNode.children.at(1), + !Self.containsGenericParameter(baseTypeNode), +- let projection = projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference) { ++ let projection = projectedAssociatedTypeWitness(base: baseTypeNode, associatedTypeReference: associatedTypeReference), ++ !Self.containsUnspellableReference(projection.witnessNode) { + var nestedRewrittenNodes: [ObjectIdentifier: Node] = [:] + let projectedWitness = projectingConcreteMembers(in: projection.witnessNode, remainingHops: remainingHops - 1, rewrittenNodes: &nestedRewrittenNodes) + // The member sits inside a `.type` wrapper already; the witness's +@@ -133,4 +137,20 @@ + private static func containsGenericParameter(_ node: Node) -> Bool { + node.kind == .dependentGenericParamType || node.children.contains(where: containsGenericParameter) + } ++ ++ /// Whether `node` holds a reference that prints as a placeholder rather ++ /// than a type: an opaque type — the record keeps one for the result of a ++ /// `dynamic` declaration, an availability-conditional `some` (SE-0360) and ++ /// a non-inlinable `some` of another resilient module, whose underlying ++ /// type it cannot fix — or a kind-9 accessor function. Spliced into a ++ /// field's type it read `opaque type symbolic reference 0x….0`; the member ++ /// it would replace, `Concrete.Body`, names the type better. ++ private static func containsUnspellableReference(_ node: Node) -> Bool { ++ switch node.kind { ++ case .opaqueType, .opaqueReturnType, .opaqueReturnTypeOf, .opaqueTypeDescriptorSymbolicReference, .accessorFunctionReference: ++ return true ++ default: ++ return node.children.contains(where: containsUnspellableReference) ++ } ++ } + } +``` + +(同一文件开头那处 `guard node.contains(.dependentMemberType)` 属于第 14 条。) + +**修后**:两组参数都通过;`SwiftLayoutTests` 全部 33 个套件不变。 + +``` +make.typeName → "() -> NestedFieldOffsetOpaqueWitnessFixture.DynamicConcrete.NestedFieldOffsetOpaqueWitnessFixture.Shape.Body" +make.typeName → "() -> NestedFieldOffsetOpaqueWitnessFixture.ConditionalConcrete.NestedFieldOffsetOpaqueWitnessFixture.Shape.Body" +``` + +CLI `dump --emit-expanded-field-offsets`,`DynamicHolder` 的展开行(`ConditionalHolder` 同理): + +``` +0.21.0:// └── make (() -> NestedFieldOffsetOpaqueWitnessFixture.DynamicConcrete.NestedFieldOffsetOpaqueWitnessFixture.Shape.Body): 0x0 +PR 头: // └── make (() -> opaque type symbolic reference 0x1A28.0): 0x0 +修后: // └── make (() -> NestedFieldOffsetOpaqueWitnessFixture.DynamicConcrete.NestedFieldOffsetOpaqueWitnessFixture.Shape.Body): 0x0 +``` + +### 7. `specializedChildren` 无锁追加(低到中,机制旧,PR 扩大) + +`Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift:24`(关联对象),追加点 `:130`、`:190`、`:462`、`:492`。 + +`specializedChildren` 存在一个 nonatomic 的关联对象里(ObjC 运行时挂在对象上的附加存储;`TypeDefinition` 在另一个模块,跨模块的 extension 加不了存储属性)。追加是「读出数组 → 追加 → 写回」三步,没有锁。 + +- **能复现吗**:能,而且是确定性的:512 个任务同时特化同一个定义,每次只留下 445 到 467 个(直接跑 5 次、挂 lldb 跑 6 次,11 次全部丢)。RuntimeViewer 侧也核实了(它的 find-navigator 工作树 `942524f4`,`RuntimeViewerCore/Sources/RuntimeViewerCore/Core/RuntimeSwiftSection.swift`):`actor RuntimeSwiftSection` 在第 905 行 `await baseTypeDefinition.specialize(...)`,这个方法是 nonisolated async,本库没开 `NonisolatedNonsendingByDefault`,所以它离开 actor 执行;与此同时 actor 可能在第 295/393/630 行读这个数组。最坏情况是读到写入方刚释放的数组(use-after-free),这个没实际跑出来。 +- **基线有没有**:机制是 2026-06-15 拆模块(`47b5961f`)时引入的。PR 又加了两处追加,还把 `TypeDefinition` 标成 `@unchecked Sendable`,并发打印提案里「RuntimeViewer 的读写都在 section actor 上」这个前提不成立。 +- **值不值得修**:值得,改动小。 +- **以前修过吗**:没有。 + +**复现测试** `Tests/SwiftSpecializationTests/ConcurrentSpecializationTests.swift`(1 个测试,在子进程里跑:丢更新的那种重叠,也可能释放一个仍在被读的数组,那会把整个测试进程带走)。用自己的索引器,不污染共享定义: + +```swift +try await withThrowingTaskGroup(of: Void.self) { group in + for _ in 0 ..< 512 { + group.addTask { + try await definition.specialize(with: result, typeArgumentNodes: typeArgumentNodes, in: machOImage) + _ = definition.specializedChildren.count // RuntimeViewer 的 actor 同时在读 + } + } + try await group.waitForAll() +} +// 留下的个数 != 512 → 子进程以 EXIT_FAILURE 退出 +``` + +修前:`expected exit status ".success", but ".exitCode(EXIT_FAILURE)" was reported`。 + +注意:exit test 的测试体一旦抛错,子进程是以 SIGTRAP 结束的,看起来像崩溃。所以测试体里自己 catch 后 `exit(EXIT_FAILURE)`,让 SIGTRAP 只剩「被测代码 trap」这一种含义。 + +**修法**:关联对象保留,读和四处追加都经过同一把所有定义共用的锁(库里 `@Mutex` 宏的惯用写法,同 `DefinitionIndexing`)。特化很少、追加很快,一把锁足够。没有把存储挪进 `TypeDefinition`:那会改变它的实例大小,而 `DeclarationModelInstanceSizeTests` 专门钉住了这个大小。 + +```diff +--- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift ++++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +@@ -20,10 +20,29 @@ + /// instance properties to a type it does not own. + extension TypeDefinition { + /// Associated-object backing for `specializedChildren`. Mutated only +- /// within this file (the `specialize(...)` family appends to it). ++ /// within this file (the `specialize(...)` family appends to it), and ++ /// read and written only under `specializedChildrenAccess`. + @AssociatedObject(.retain(.nonatomic)) + private var _specializedChildren: [TypeDefinition] = [] + ++ /// The lock every read and write of `_specializedChildren` holds — one ++ /// for all definitions, as a specialization is rare and its append quick. ++ /// A host reads the list while it specializes from another task: ++ /// RuntimeViewer's section actor awaits `specialize(...)`, a nonisolated ++ /// async method that runs off the actor while the actor goes on reading. ++ /// Unlocked, two appends at once lost one of them, and a read overlapping ++ /// a write could retain the array the write had just released (the ++ /// associated object is retained non-atomically, and its getter even ++ /// writes on a first read). ++ @Mutex ++ private static var specializedChildrenAccess: Void = () ++ ++ private func appendSpecializedChild(_ specialized: TypeDefinition) { ++ Self._specializedChildrenAccess.withLockUnchecked { _ in ++ _specializedChildren.append(specialized) ++ } ++ } ++ + /// Specialized children produced by **directly** calling + /// `specialize(with:in:)` (or the `derivingNestedSpecializationsWith` + /// overload) on this generic definition. Each entry is a sibling-shaped +@@ -67,7 +86,9 @@ + /// independent subtrees in `outerSpecialized.typeChildren`). Equality + /// of `metadata` does not imply identity of the wrapping + /// `TypeDefinition`. +- public var specializedChildren: [TypeDefinition] { _specializedChildren } ++ public var specializedChildren: [TypeDefinition] { ++ Self._specializedChildrenAccess.withLockUnchecked { _ in _specializedChildren } ++ } + + /// Maximum recursion depth that `deriveNestedSpecializedTypeChildren` + /// will descend before bailing out. Swift's source-level nesting rarely +@@ -127,7 +148,7 @@ + typeArgumentNodes: typeArgumentNodes, + in: machO + ) +- _specializedChildren.append(specialized) ++ appendSpecializedChild(specialized) + return specialized + } + +@@ -187,7 +208,7 @@ + for child in specialized.typeChildren { + child.parent = specialized + } +- _specializedChildren.append(specialized) ++ appendSpecializedChild(specialized) + return specialized + } + +@@ -459,7 +486,7 @@ + in machO: MachOFile + ) async throws -> TypeDefinition { + let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) +- _specializedChildren.append(specialized) ++ appendSpecializedChild(specialized) + return specialized + } + +@@ -489,7 +516,7 @@ + for child in specialized.typeChildren { + child.parent = specialized + } +- _specializedChildren.append(specialized) ++ appendSpecializedChild(specialized) + return specialized + } +``` + +两处说明随之改写: + +```diff +--- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift ++++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift +@@ -10,8 +10,9 @@ + /// publishes what it wrote (`DefinitionIndexing`, evolution proposal + /// `concurrent-definition-printing`). Printing writes nothing to it, so one + /// definition may be printed from several tasks at once. The one write +-/// outside that promise is `specialize(...)` appending to a generic +-/// definition's `specializedChildren`. ++/// outside that promise, `specialize(...)` appending to a generic ++/// definition's `specializedChildren`, holds a lock of its own ++/// (`SwiftSpecialization`). + public final class TypeDefinition: Definition, @unchecked Sendable { +--- a/AGENTS.md ++++ b/AGENTS.md +@@ -271,7 +271,7 @@ +-… The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read) — and `specialize(...)` appends to the generic definition unlocked. [draft-concurrent-definition-printing](…). ++… The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [draft-concurrent-definition-printing](…). +``` + +**修后**:测试通过(512 个全部留下)。 + +**横向排查**:库里另有四处同样「懒创建、无锁、nonatomic」的关联对象:`MachOFile` 与 `DyldCache` 的 `_fileHandle`、`_fileIO`(`Sources/MachO/MachOReading/Extensions/MachOFile+.swift`、`DyldCache+.swift`)。`MachOFile` 本来就声明不支持同一版本内并发;但宿主的 dyld cache 对象会被多个版本共享(`FullDyldCache.cachedHost`),跨版本并行时这四处会不会真被并发首次访问,还没查。它们不在本 PR 范围内,建议另开一项。 + +**落地时**:`draft-concurrent-definition-printing` 的决策日志补一条(前提更正 + 加锁)。 + +### 8. opaque provider 少数一层(低到中,基线就有) + +`Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift:230`。 + +provider 负责给 `some P` 印出约束(`interface --parse-opaque-return-type` 和 RuntimeViewer 都会挂它)。它按父链里「参数个数增长的层」来数 opaque 参数所在的层号。 + +- **能复现吗**:能。 + - `extension Outer.SecondMiddle where A: Hashable { var body: some Sequence }` 这个 extension 一次带来两层(`Outer` 的 `A` 和 `SecondMiddle` 的 `C`),被数成一层。约束落在 `τ_2_0` 上,超出了算出的层号 1。 + - debug 构建(`swift test`、debug CLI、debug RuntimeViewer)在这里崩溃,崩溃信息:`SwiftInterfaceBuilderOpaqueTypeProvider.swift:253: Fatal error: opaque type descriptor of (extension in ProbeOpaqueExtensionDepth):ProbeOpaqueExtensionDepth.Outer.SecondMiddle< where A: Swift.Hashable>.body : some constrains parameter τ_2_0, beyond the opaque parameters' depth 1`。 + - release(0.21.0)没有断言,打印出裸 `var body: some`,同一个 extension 里的泛型方法也是裸 `some`。 + - Swift 运行时 `_gatherGenericParameterCounts` 遇到 extension 会改用被扩展的类型来数层,所以不会少数。 +- **基线有没有**:有。这段是 2026-09-18 的 `044f69dc` 修 PhotosUIFoundation 崩溃时写的;PR 修那五处同类错误时漏了这里。 +- **值不值得修**:值得。合法但不常见的形状,会让 debug 构建崩溃。 +- **以前修过吗**:没有。`044f69dc` 当时有意按「父层是否增加参数」来数,没考虑跨层的 extension。 + +**复现测试** `Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift`(1 个测试,在子进程里跑,因为修前会崩)。除了属性,还加了一个同在这个 extension 里的泛型方法,覆盖下面说的匿名上下文那条路径: + +```swift +extension Outer.SecondMiddle where A: Hashable { + public var body: some Sequence { [1] } + public func elements(_ element: Element) -> some Sequence { [element] } +} +// 期望:var body: some Swift.Sequence { 以及 func elements(_: A2) -> some Swift.Sequence +``` + +修前:`expected exit status ".success", but ".signal(SIGTRAP)" was reported`。测试体里自己的检查失败会以 `EXIT_FAILURE` 退出,所以这里的 SIGTRAP 就是 provider 自己崩溃。PR 头的 debug CLI 对同一个 fixture 跑 `interface --parse-opaque-return-type` 也以 133(SIGTRAP)退出,stderr 就是上面那条崩溃信息。 + +**修法**:改用 opaque 描述符所在的类型或 extension 的 `GenericParameterDepthLayout` 层数,再加上声明自己是否泛型的那一层(`declaresOwnGenericParameters` 保留不变)。 + +一个踩过的坑:第一版直接拿描述符的**直接**父上下文来算,结果 `OpaqueParameterWithoutProtocolRequirementTests` 里 `Outer.generic() -> some Equatable` 退化成裸 `some`。原因是泛型方法的 opaque 描述符,父上下文是一个带着方法自己签名的**匿名上下文**,旧代码(`validParentGenericContextDescriptor` 只认类型和 extension)会跳过它,直接拿它算就把方法那一层数了两次。所以要沿父链找到最近的类型或 extension。 + +```diff +--- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift ++++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift +@@ -208,12 +208,17 @@ + /// The depth comes from the descriptor, not from the declaration's mangled + /// signature: a member's signature spells only the depths it adds + /// (`ASTMangler::appendGenericSignatureParts` skips the context's). It is +- /// the number of enclosing depths — one per parent level that grows the +- /// parameter count, as the runtime's `_gatherGenericParameterCounts` +- /// counts them, so a non-generic nested type adds none — plus one when the +- /// declaration is generic itself, which its type node says (a +- /// `dependentGenericType` wrapper; a constrained extension's signature +- /// sits in the context and does not count). ++ /// the number of enclosing depths — the depths of the context the ++ /// declaration sits in, the descriptor's parent, as ++ /// `GenericParameterDepthLayout` counts them: a non-generic nested type ++ /// adds none, and an extension of a nested generic type adds every level ++ /// of the type it extends, which the runtime's ++ /// `_gatherGenericParameterCounts` reaches by switching to the extended ++ /// type — plus one when the declaration is generic itself, which its type ++ /// node says (a `dependentGenericType` wrapper; a constrained extension's ++ /// signature sits in the context and does not count). Counting the parent ++ /// chain's growing levels instead took `extension Outer.SecondMiddle ++ /// where A: Hashable` for one depth and trapped below on its `τ_2_0`. + /// + /// A requirement on a parameter beyond that depth cannot exist for a + /// well-formed image: that is reported as a fault and asserted in debug +@@ -227,13 +232,7 @@ + return nil + } + +- var enclosingDepthCount = 0 +- var inheritedParameterCount = 0 +- for parameters in genericContext.parentParameters where parameters.count > inheritedParameterCount { +- enclosingDepthCount += 1 +- inheritedParameterCount = parameters.count +- } +- let opaqueParameterDepth = enclosingDepthCount + (Self.declaresOwnGenericParameters(node) ? 1 : 0) ++ let opaqueParameterDepth = enclosingDepthCount(of: opaqueType) + (Self.declaresOwnGenericParameters(node) ? 1 : 0) + + var constraintsByParameter: [GenericParameterCoordinate: OpaqueParameterConstraints] = [:] + for requirement in requirements { +@@ -269,6 +268,26 @@ + return parameterConstraints + } + ++ /// The depths of the type or extension the declaration naming `opaqueType` ++ /// sits in, as `GenericParameterDepthLayout` counts them — the nearest one ++ /// up the descriptor's parent chain. An anonymous context in between is ++ /// where a generic declaration's own signature lives; its depth is the one ++ /// `declaresOwnGenericParameters` adds, so it is passed over here, as the ++ /// parent chain's own `parentParameters` passes over it. No type or ++ /// extension above (a top-level declaration) is no enclosing depth. ++ private func enclosingDepthCount(of opaqueType: OpaqueType) -> Int { ++ var parent = (try? opaqueType.descriptor.parent(in: machO.context))?.flatMap(\.resolved) ++ while let currentParent = parent { ++ switch currentParent { ++ case .type, .extension: ++ return (try? GenericParameterDepthLayout.make(for: currentParent, in: machO.context))?.depthCount ?? 0 ++ default: ++ parent = (try? currentParent.parent(in: machO.context))?.flatMap(\.resolved) ++ } ++ } ++ return 0 ++ } ++ + /// Whether the declaration introduces generic parameters of its own: its + /// type is wrapped in a `dependentGenericType`. The entity is unwrapped + /// first so a `static` or accessor wrapper does not hide it; a constrained +``` + +**修后**:测试通过;`OpaqueParameterWithoutProtocolRequirementTests`、`OpaqueConstraintRenderingTests`、`ProjectedOpaqueMemberWitnessTests`、`CrossImageOpaqueReferenceTests` 不变。 + +CLI `interface --parse-opaque-return-type`。0.21.0(release,没有断言): + +```swift +extension ProbeOpaqueExtensionDepth.Outer.SecondMiddle where A: Swift.Hashable { + var body: some { +… +extension ProbeOpaqueExtensionDepth.Outer.SecondMiddle { + func elements(_: A2) -> some where A: Swift.Hashable +``` + +PR 头(debug):崩溃,没有输出。修后: + +```swift +extension ProbeOpaqueExtensionDepth.Outer.SecondMiddle where A: Swift.Hashable { + var body: some Swift.Sequence { +… +extension ProbeOpaqueExtensionDepth.Outer.SecondMiddle { + func elements(_: A2) -> some Swift.Sequence where A: Swift.Hashable +``` + +(泛型方法单独印在一个不带 `where` 的 extension 里、把约束挂在方法上,是打印器原本就有的写法,与本条无关。) + +**落地时**:`Internal/OpaqueReturnTypeResolution.md` 里描述层号算法的那段同步改写。 + +### 10. 在线特化算类型名失败时静默退回(低,PR 引入) + +`Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift:225`。 + +- **能复现吗**:能,主要落点就是第 3 条的形状。`try?` 失败后退回旧的扁平名,没有日志也没有事件;类型头仍印运行时的名字,于是同一个定义有两个名字。另一处名字不一致(嵌套泛型类型的约束 extension 里,`DeepConstrainedInner` 的 `typeName` 按层绑定,而类型头是运行时那种把实参全塞进最内层的名字)是提案写明的**有意差异**,不改。 +- **基线有没有**:PR 新代码。 +- **值不值得修**:值得,补一条日志即可;修完第 3 条后基本走不到。 +- **以前修过吗**:没有。 + +**复现测试**:可测的症状已由第 3 条的在线测试覆盖(修前在线名 ``,运行时 ``)。日志本身没有可断言的行为。 + +**修法**:`try?` 换成 `do/catch`,退回之前先打一条 `#log(.error, …)`。文件里已有 `NestedSpecializationLogging` 这个日志通道,subsystem 与 category 不变。 + +```diff +--- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift ++++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +@@ -222,12 +243,18 @@ + let unboundTypeName = try materializedTypeContext.typeName(in: machO.context) + let finalTypeName: TypeName + if let typeArgumentNodes, !typeArgumentNodes.isEmpty { +- if let instantiation = try? GenericInstantiation(of: typeContextDescriptorWrapper, keyArguments: typeArgumentNodes, in: machO) { ++ do { ++ let instantiation = try GenericInstantiation(of: typeContextDescriptorWrapper, keyArguments: typeArgumentNodes, in: machO) + finalTypeName = TypeName( + node: InternedNodeReferenceCache.shared.reference(interning: instantiation.typeNode, in: machO), + kind: unboundTypeName.kind + ) +- } else { ++ } catch { ++ // The flat name is the name of no instantiation, so falling ++ // back to it is a degradation worth a trace: the header still ++ // prints the runtime's name, and the two now disagree. ++ let reason = (error as? LocalizedError)?.errorDescription ?? "\(error)" ++ #log(.error, "could not name the instantiation of \(unboundTypeName.name, privacy: .public) (\(reason, privacy: .public)); naming it with every argument on its innermost level") + finalTypeName = Self.boundGenericTypeName( + unboundTypeName: unboundTypeName, + typeArgumentNodes: typeArgumentNodes +``` + +### 13. thunk 类型构造器认不出泛型 extension 里的泛型类型(低,基线就有) + +`Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift:94`(`boundTypeNode`,以及它用的 `keyParameterCountsByNominalLevel`、`bound`)。 + +kind-9 accessor thunk 是编译器为某些字段生成的「取类型的小函数」,比如 `~Copyable` 的泛型类型,在不确定运行时支持的系统上就要先查询再实例化。本库会对它做符号执行,读出它调用了哪个类型的 accessor、传了哪些实参,再拼回类型名。 + +- **能复现吗**:能。`extension Outer where A: Hashable { struct Inner: ~Copyable }` 的 accessor 收 `A` 和 `B` 两个实参,而构造器只数父链上的「类型层」各自声明了几个参数。extension 描述符的父上下文是模块,不是被扩展的 `Outer`,所以这条链上只有 `Inner` 一层、只数出 1 个,对不上就放弃。dump 打印 `var inner: accessor function at 2488`(0.21.0 实测,测试里是 `accessor function at 2608`)。没在真实框架里找到实例。 +- **基线有没有**:有,2026-09-12 的 `1b1b60aa` 首版就是这样。它是 PR 在 `GenericArgumentEnvironment` 修掉的那个「extension 走不过去」在构造一侧的对应。 +- **值不值得修**:值得。PR 新加的 `GenericParameterDepthLayout` 和 `SymbolicDemangler.instantiatedTypeNode` 正好能拼这种名字。但**不能整个替换掉旧逻辑**,见下面的修法。 +- **以前修过吗**:没有。 + +**复现测试** `Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift`(1 个测试),走的是索引器解析 kind-9 字段时用的同一个入口: + +```swift +public struct Outer {} +extension Outer where A: Hashable { + public struct Inner: ~Copyable { public var value: Int } +} +public struct Holder: ~Copyable { + public var inner: Outer.Inner +} +``` + +修前:`fieldType → "accessor function at 2608"`。 + +**修法**:分两条路。 + +- 类型的**整个**泛型上下文里每个参数都带 key argument 时,thunk 传进来的实参正好一个参数一个:用 `GenericParameterDepthLayout` 分层,再用 `SymbolicDemangler.instantiatedTypeNode` 照运行时的规则拼名字,extension 上下文和被扩展的类型都能处理好。第 13 条的形状走这条路。 +- 否则(有参数被 same-type 约束固定、运行时自己推出来而不是接收)照旧走原来的逻辑,一行不改。 + +**为什么不能整个替换**:这一版之前,我先试过直接删掉旧逻辑、遇到不带 key argument 的参数就放弃。复现测试和全量都过了,但实测发现它把一个本来能用的形状弄坏了:same-type 约束的 extension 里的类型(`extension SameTypeOuter where A == Int { struct Inner }`)。thunk 只传 `B` 的实参;旧逻辑因为 extension 不算一层,正好对上个数,拼出的名字信息是完整的。三个 CLI 对同一个 fixture(`experiments/finding13b`)的 dump: + +``` +0.21.0: var inner: (extension in ProbeThunkSameType):ProbeThunkSameType.Outer< where A == Swift.Int>.Inner +PR 头: var inner: (extension in ProbeThunkSameType):ProbeThunkSameType.Outer< where A == Swift.Int>.Inner +整个替换的那一版: var inner: accessor function at 2592 +``` + +所以现在的修法只在新路径确实能处理时才用它,其余情况与 PR 头逐字相同;另加一条守护测试钉住这个形状(见下面的测试 diff)。旧逻辑在「extension 固定了一部分参数、另一部分仍要接收」的混合形状上本来就对不上个数、会放弃,这一点不变。 + +```diff +--- a/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift ++++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift +@@ -19,9 +19,12 @@ + /// the existing substitution rewrites it into the concrete argument. A + /// mangled name is demangled. A specialized accessor's symbol is demangled + /// and the type it is the accessor *for* taken. And an accessor applied to +-/// arguments becomes the accessor's nominal type with a `boundGeneric*` +-/// wrapper per generic level of its declaration chain, the way the demangler +-/// itself spells `Outer.Inner`. ++/// arguments becomes the accessor's type bound to them: named the way the ++/// runtime names the instantiation when they are one per parameter of the ++/// type's whole context — `Outer.Inner`, an extension context ++/// and the type it extends included — and otherwise wrapped in a ++/// `boundGeneric*` node per generic level of its declaration chain, the way ++/// the demangler itself spells it. + package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { + package let machO: MachOFile + package let environment: MachOThunkEnvironment +@@ -91,17 +94,44 @@ + } + } + ++ /// The accessor's type bound to the arguments the thunk passed it. ++ /// ++ /// When every parameter of the type's whole generic context takes a key ++ /// argument, the arguments are one per parameter: grouped by ++ /// `GenericParameterDepthLayout`, they name the instantiation the way the ++ /// runtime does (`SymbolicDemangler.instantiatedTypeNode`). Both count ++ /// what the walk of the type contexts below misses — the parameters an ++ /// extension context brings (`extension Outer where A: Hashable { struct ++ /// Inner }` takes `A` and `B`), which left such a type unnamed, its ++ /// field `accessor function at …`. ++ /// ++ /// Otherwise the walk of the type contexts binds each level's own key ++ /// parameters. It is what names a type in a same-type-constrained ++ /// extension — `extension Outer where A == Int { struct Inner }` ++ /// receives the argument of `B` alone and reads ++ /// `Outer< where A == Swift.Int>.Inner<…>` — since an extension's ++ /// parameters are no type level of the walk. + private func boundTypeNode(accessorAddress: UInt64, typeArguments: [ThunkTypeExpression]) -> Node? { + guard let origin = environment.accessorOriginsByAddress[accessorAddress] else { return nil } + do { + let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: origin.descriptorOffset, in: origin.machO.context) +- let unboundNode = try SymbolicDemangler.demangleContext(for: descriptor, in: origin.machO.context) +- guard let keyParameterCountsByLevel = try keyParameterCountsByNominalLevel(of: descriptor, in: origin.machO) else { return nil } + var argumentNodes: [Node] = [] + for typeArgument in typeArguments { + guard let argumentNode = typeNode(for: typeArgument) else { return nil } + argumentNodes.append(argumentNode) + } ++ if let typeDescriptor = descriptor.typeContextDescriptorWrapper, ++ let genericContext = try typeDescriptor.genericContext(in: origin.machO.context), ++ genericContext.parameters.allSatisfy(\.hasKeyArgument) { ++ let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: descriptor, in: origin.machO.context) ++ guard let argumentsByDepth = depthLayout.grouped(argumentNodes) else { ++ #log(.info, "accessor at 0x\(String(accessorAddress, radix: 16), privacy: .public) takes \(depthLayout.parameterCount, privacy: .public) type arguments, \(argumentNodes.count, privacy: .public) were named") ++ return nil ++ } ++ return enveloped(try SymbolicDemangler.instantiatedTypeNode(for: typeDescriptor, binding: GenericArgumentBinding(argumentsByDepth: argumentsByDepth), in: origin.machO.context)) ++ } ++ let unboundNode = try SymbolicDemangler.demangleContext(for: descriptor, in: origin.machO.context) ++ guard let keyParameterCountsByLevel = try keyParameterCountsByNominalLevel(of: descriptor, in: origin.machO) else { return nil } + guard keyParameterCountsByLevel.reduce(0, +) == argumentNodes.count else { + #log(.info, "accessor at 0x\(String(accessorAddress, radix: 16), privacy: .public) takes \(keyParameterCountsByLevel.reduce(0, +), privacy: .public) type arguments, \(argumentNodes.count, privacy: .public) were named") + return nil +``` + +守护测试(加在同一个复现测试文件里,属于修法的一部分,所以只在沙盒里、不在 worktree 的复现测试里): + +```diff +--- a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift ++++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift +@@ -55,6 +55,18 @@ + public struct Holder: ~Copyable { + public var inner: Outer.Inner + } ++ ++ public struct SameTypeOuter {} ++ ++ extension SameTypeOuter where A == Int { ++ public struct Inner: ~Copyable { ++ public var value: Int ++ } ++ } ++ ++ public struct SameTypeHolder: ~Copyable { ++ public var inner: SameTypeOuter.Inner ++ } + """ + + private static let fixtureCompilationResult: Result = { +@@ -99,12 +111,13 @@ + } + } + +- /// `Holder.inner`'s type, read through the entry the indexer uses for a +- /// kind-9 field: the thunk's arguments named as `Holder`'s parameters. +- private func resolvedInnerFieldType() throws -> String { ++ /// The `inner` field's type of the holder named `holderName`, read ++ /// through the entry the indexer uses for a kind-9 field: the thunk's ++ /// arguments named as the holder's parameters. ++ private func resolvedInnerFieldType(ofHolderNamed holderName: String) throws -> String { + let machOFile = try loadFixture() + let holder = try #require( +- try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == "Holder" } ++ try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == holderName } + ) + let genericContext = try #require(try holder.typeContextDescriptor.genericContext(in: machOFile.context)) + let ownerLayout = AccessorThunkOwnerLayout( +@@ -121,9 +134,22 @@ + + @Test("a thunk instantiating a generic type declared in a generic extension is named") + func thunkInstantiatingATypeInAGenericExtensionIsNamed() throws { +- let fieldType = try resolvedInnerFieldType() ++ let fieldType = try resolvedInnerFieldType(ofHolderNamed: "Holder") + + #expect(!fieldType.contains("accessor function"), "\(fieldType)") + #expect(fieldType.contains("Outer") && fieldType.contains("Inner"), "\(fieldType)") + } ++ ++ /// A type in a same-type-constrained extension receives the arguments of ++ /// its own parameters alone — the parameter the extension fixes takes no ++ /// key argument — and the walk of the type contexts names it. Naming the ++ /// instantiation from the whole context cannot, so it must not take over ++ /// there: doing so turned this field into `accessor function at …`. ++ @Test("a thunk instantiating a generic type declared in a same-type-constrained extension stays named") ++ func thunkInstantiatingATypeInASameTypeConstrainedExtensionStaysNamed() throws { ++ let fieldType = try resolvedInnerFieldType(ofHolderNamed: "SameTypeHolder") ++ ++ #expect(!fieldType.contains("accessor function"), "\(fieldType)") ++ #expect(fieldType.contains("SameTypeOuter< where A == Swift.Int>.Inner"), "\(fieldType)") ++ } + } +``` + +两条测试在三个版本上的结果(证明守护测试确实能挡住那种改法,而不是怎么改都过): + +| 代码版本 | 第 13 条的复现测试 | 守护测试 | +|---|---|---| +| PR 头 | 失败(`accessor function at …`) | 通过 | +| 整个替换的那一版 | 通过 | 失败(`fieldType → "accessor function at 2712"`) | +| 现在的修法 | 通过 | 通过 | + +**修后**:两条都通过: + +``` +fieldType → "(extension in ProbeThunkExtension):ProbeThunkExtension.Outer.Inner" +fieldType → "(extension in ProbeThunkExtension):ProbeThunkExtension.SameTypeOuter< where A == Swift.Int>.Inner" +``` + +换成现在这版修法后重跑了全量(2354 个测试全过,见开头);Xcodes 的 interface 与整个替换那一版逐字相同。 + +CLI dump,第 13 条的 fixture(`experiments/finding13`): + +``` +0.21.0: var inner: accessor function at 2488 +PR 头: var inner: accessor function at 2488 +修后: var inner: (extension in ProbeThunkExtension):ProbeThunkExtension.Outer.Inner +``` + +same-type 那个 fixture(`experiments/finding13b`)修后与 0.21.0、PR 头逐字相同: + +``` +var inner: (extension in ProbeThunkSameType):ProbeThunkSameType.Outer< where A == Swift.Int>.Inner +``` + +**这一条给的教训**:整个替换的那一版,复现测试和全量(2353 个测试)都是绿的,回退是用 CLI 拿旧逻辑本来能处理的形状做对比才发现的。替换一段旧逻辑时,要专门找旧逻辑能处理、新逻辑放弃的输入去比,不能只看测试。 + +**落地时**:会改变 thunk 字段的输出,渲染 A/B 必跑。`Internal/Modules/SwiftThunkAnalysis.md` 里讲类型名拼法的地方同步。 + +### 14. 关联类型投影没有提前返回(低,性能,PR 引入) + +`Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift:131`,`Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift:92`。 + +- **能复现吗**:属实(读码)。每次调用都重新推断搜索路径(要列目录)、拿两把锁;第一次调用还要建整个依赖闭包,哪怕节点里根本没有关联类型成员。PR 无条件调用它:离线特化的每个字段、离线检查的每条约束、在线特化补固定参数时各一到三次。旧的 opaque 重写器调用前有 `isConcreteNominal` 前置检查,这里没有。 +- **基线有没有**:PR 新代码。 +- **值不值得修**:值得,一行。纯性能,没有可断言的行为,没写测试。 +- **以前修过吗**:没有。 + +**修法**:两个入口开头各加一行,节点里没有 `dependentMemberType` 就原样返回(`contains(_:)` 是按种类做的整树搜索,正是这里要的语义)。 + +```diff +--- a/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift ++++ b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift +@@ -129,6 +129,10 @@ + /// the reader is neither a file nor an in-process image, or the universe + /// cannot be built. + package static func projectingConcreteMembers(in node: Node, in machO: MachO) -> Node { ++ // Nothing to project, so nothing to look up: no search-path inference ++ // (it lists directories), no lock, no dependency closure built — the ++ // first call used to build one even for a plain `Swift.Int`. ++ guard node.contains(.dependentMemberType) else { return node } + if let machOFile = machO as? MachOFile { + let registry = fileRegistries.storage(in: machOFile) { FileRegistry(root: $0) } ?? FileRegistry(root: machOFile) + guard let entry = registry.entry(for: searchPaths(for: machOFile)) else { return node } +--- a/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift ++++ b/Sources/Analysis/SwiftLayout/ImageUniverse+AssociatedTypeWitnessProjection.swift +@@ -90,6 +90,9 @@ + /// (`IndexingIterator`'s `Element` is `Elements.Element`), so a projection + /// is projected again, a bounded number of hops deep. + public func projectingConcreteMembers(in node: Node) -> Node { ++ // Most nodes name no member at all; they come back as they are, ++ // without a rebuilt copy of every node on the way. ++ guard node.contains(.dependentMemberType) else { return node } + var rewrittenNodes: [ObjectIdentifier: Node] = [:] + return projectingConcreteMembers(in: node, remainingHops: Self.maximumProjectionHops, rewrittenNodes: &rewrittenNodes) + } +``` + +### 15. CI 覆盖(低,PR 引入) + +`.github/workflows/macOS.yml:123`(主过滤列表)与 `:135`–`:149`(单线程协作线程池那一步,PR 加的说明从 `:135` 开始)。 + +- **属实**: + - PR 把 `ConcurrentDefinitionPrintingTests` 加进「只给一个线程的协作线程池」那一步,想证明索引过程从不需要池线程。但 CI 上每次打印都跑在 `LargeStackTaskExecution.run` 里、用的是 swift-demangling 自己的线程,`LIBDISPATCH_COOPERATIVE_POOL_STRICT` 缩不到它们,所以这一步测不出它要防的问题。提案本地验证时关了执行器(`MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR=0`),CI 没有。 + - 离线特化和层号相关的新套件一个都没进 CI 的过滤列表。 +- **值不值得修**:值得。注意:这些套件**从没在 CI(Xcode 26.6)上跑过**,加进去可能暴露只在 CI 上出现的问题,那正是加的意义。 +- **以前修过吗**:没有。仓库的 CI 一直只跑子集(有意为之),新套件通常会补进列表。 + +**修法**:主过滤列表补上 PR 和这批新加的套件(第 11 条那个依赖本机 cache 的除外);另加一步,在单线程池且关掉大栈执行器的条件下单独跑并发打印测试。`ContinuousIntegrationTestFilterTests` 只要求列表里的名字都是真实存在的套件,满足。 + +```diff +--- a/.github/workflows/macOS.yml ++++ b/.github/workflows/macOS.yml +@@ -120,7 +120,7 @@ +- --filter '\.(…|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests)(/|$)' ++ --filter '\.(…|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests)(/|$)' +@@ -147,3 +147,22 @@ + --build-path .build-test-${{ matrix.configuration }} \ + --filter '\.(SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|ConcurrentDefinitionPrintingTests)/' \ + --skip 'differentKeysParallelVia' ++ ++ - name: Run the concurrent printing suite on a one-thread pool without the large-stack executor (${{ matrix.configuration }}) ++ # The step above cannot catch an indexing pass that needs a pool ++ # thread: on this runner every print runs inside ++ # `LargeStackTaskExecution.run`, on the demangler's own threads, which ++ # the strict pool does not shrink. With the executor off, prints run ++ # on the cooperative pool itself — as they do below macOS 15 / iOS 18 ++ # — and a pass that waited on pool work would hang here. ++ timeout-minutes: 5 ++ env: ++ LIBDISPATCH_COOPERATIVE_POOL_STRICT: 1 ++ MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR: 0 ++ run: | ++ swift test \ ++ -c ${{ matrix.configuration }} \ ++ --skip-build \ ++ --enable-experimental-prebuilts \ ++ --build-path .build-test-${{ matrix.configuration }} \ ++ --filter '\.ConcurrentDefinitionPrintingTests/' +``` + +(过滤列表前半段没变,用 `…` 省略。)本地按新加这一步的条件(`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`、`MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR=0`)在修后沙盒里跑 `ConcurrentDefinitionPrintingTests`:3 个测试全部通过,用时约 13 秒(日志 `…/Logs/ReviewFixes/ci-step-strict-pool.log`)。CI 用的 Xcode 26.6 上没跑过。 + +## 二、建议离线模式接入前修 + +这两条只有离线特化才会走到,而 RuntimeViewer 目前还没有调用离线特化。修法已写好、已验证,可以和上一组一起合,也可以等离线模式接入时再合。 + +### 5. 带条件的协议遵循被当成成立(低,PR 引入) + +`Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift:403`(`checkConformance`)。 + +- **能复现吗**:能。`doesType(_:conformTo:)` 只查按未绑定类型名记录的遵循表,条件被丢掉了。于是 `Inner` 的 `A1` 选「元素是 `FixtureUnmarked` 的 `Array`」时,`Hashable` 约束一个警告都没有,`specialize` 会拼出一个不可能存在的实例化;运行时路径会拒绝同样的选择。`staticPreflight` 的文档承诺这种情况给警告。 +- **基线有没有**:丢条件是 2026-01-26 的 `25d3a8bb`(`ConformanceProvider` 第一版)以来的既有语义,在线的候选列表也因此会列出 `Array`;但在线最后由运行时核验,不会放行。离线检查把这条记录当成了证明,是 PR 引入的。 +- **值不值得修**:值得,不急。 +- **以前修过吗**:没有。 + +**复现测试** `Tests/SwiftSpecializationTests/OfflineConditionalConformanceTests.swift`(1 个测试,用 PR 的共享 fixture,不用改)。断言只要求「这个选择被标记出来」,给警告或报错都算,不预先限定修法。修前:零个警告、零个错误。 + +**修法**:索引器给每个协议遵循建的 conformance extension 都留着遵循描述符,`flags.numConditionalRequirements` 就是条件约束的个数,不用加新存储。给 `ConformanceProvider` 加一个默认返回 `false` 的 `isConditionalConformance(of:to:)`;离线检查遇到记录在案、但带条件的遵循时给警告。用绑定逐条检查这些条件,留作以后的增强。候选列表不动(它只是提示)。 + +`ConformanceProvider.swift` 的这几处改动与第 2 条落在同几个 hunk 里,这里只摘第 5 条的行;`@@` 后面括号里写的是它们在文件里的位置,真正的 hunk 头见第 2 条。 + +```diff +--- a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift ++++ b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift +@@ (协议 requirement,接在第 2 条的 superclassLink(of:) 之后) ++ ++ /// Whether the conformance of `typeName` to `protocolName` that the ++ /// provider records holds only under conditions — `Array: Hashable where ++ /// Element: Hashable`. Such a record, kept under the type's unbound name, ++ /// proves nothing for one instantiation, so the offline check does not ++ /// take it for proof (evolution proposal `offline-generic-specialization`). ++ /// Default `false`: the record stands for the conformance, as ++ /// `doesType(_:conformTo:)` has always read it. ++ func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool + } +@@ (默认实现) ++ ++ public func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { ++ false ++ } + } +@@ (IndexerConformanceProvider) ++ ++ /// Read off the conformance's own descriptor, which the conformance ++ /// extension the indexer built for it keeps: its conditional requirements ++ /// are counted in the flags. ++ public func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { ++ (indexer.allConformanceExtensionDefinitions[typeName.extensionName] ?? []).contains { entry in ++ entry.value.conformingProtocolName == protocolName ++ && (entry.value.protocolConformanceDescriptor?.flags.numConditionalRequirements ?? 0) > 0 ++ } ++ } +@@ (CompositeConformanceProvider) ++ ++ public func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { ++ providers.contains { $0.isConditionalConformance(of: typeName, to: protocolName) } ++ } + } +--- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift ++++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +@@ -411,11 +411,22 @@ + )) + return + } +- guard !conformanceProvider.doesType(typeName, conformTo: protocolName) else { return } ++ guard conformanceProvider.doesType(typeName, conformTo: protocolName) else { ++ builder.addWarning(.conformanceCheckFailed( ++ parameterName: subject.path, ++ protocolName: protocolName.name, ++ reason: "offline: the indexed images record no conformance of \(subject.display) to \(protocolName.name); a conformance in an image the indexer does not hold, a conditional one, or one the runtime synthesizes cannot be checked without the runtime" ++ )) ++ return ++ } ++ // The record is kept under the type's unbound name, so a conditional ++ // one says nothing about this instantiation: `[FixtureUnmarked]` ++ // passed `Hashable` on `Array`'s record, conditions and all. ++ guard conformanceProvider.isConditionalConformance(of: typeName, to: protocolName) else { return } + builder.addWarning(.conformanceCheckFailed( + parameterName: subject.path, + protocolName: protocolName.name, +- reason: "offline: the indexed images record no conformance of \(subject.display) to \(protocolName.name); a conformance in an image the indexer does not hold, a conditional one, or one the runtime synthesizes cannot be checked without the runtime" ++ reason: "offline: \(typeName.name) conforms to \(protocolName.name) only under conditions, which \(subject.display) may not meet; they cannot be checked without the runtime" + )) + } +``` + +**修后**:测试通过;`OfflineSpecializationTests` 里「记录在案的遵循不给警告」「投影后的成员遵循」等测试不变(`Array: Sequence`、`Int: Hashable` 都不带条件)。 + +同一个选择现在给一条警告: + +``` +Conformance check for parameter 'A1' against protocol 'Swift.Hashable' failed to run: offline: Swift.Array conforms to Swift.Hashable only under conditions, which [GenericSpecializationFixture.FixtureUnmarked] may not meet; they cannot be checked without the runtime +``` + +### 11. 字段类型与布局注释读的是两套镜像(低,机制旧,PR 扩大) + +`Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift`、`DependentMemberProjection.swift:75`(`searchPaths(for:)`)、`SwiftDeclarationPrinter+Headers.swift:459`。 + +- **能复现吗**:能,只在有归档 iOS 模拟器 cache 的机器上。离线特化一个 iOS 模拟器二进制、打印时配置 iOS 模拟器 cache: + + ``` + // Type Layout: (size: 9, stride: 16, alignment: 8, extraInhabitantCount: 0) + var first: [Int].Element? + ``` + + 布局注释是按 `Int?` 算的(`size: 9`),字段类型却还是 `[Int].Element?`。原因是关联类型投影用的搜索路径来自 thunk 解析器或「文件所在位置推断 + 宿主 cache」,不看打印配置的 `staticLayoutDependencyResolution`;而宿主的 macOS 镜像对 iOS 二进制从来不是候选。离线约束检查也用同一套路径,所以一条被违反的 `where A.Element == B` 会被降成警告。 +- **基线有没有**:这套路径是 2026-09-18 的 `72b5c5f6` 给 opaque 成员投影写的;PR 把它用到了字段类型和约束检查上。 +- **值不值得修**:值得,不急,只影响跨平台的离线特化。 +- **以前修过吗**:没有。 + +**复现测试** `Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift`(1 个测试):编一个 `-target arm64-apple-ios17.0-simulator` 的 fixture(`ElementsHolder`),离线特化成 `ElementsHolder<[Int]>`,打印时 `staticLayoutDependencyResolution = .dependencyClosure(searchPaths: [.dyldSharedCache(path: "/Volumes/DyldSharedCaches/iOS-Simulator/27.0/dyld_sim_shared_cache_arm64")])`。套件带 `.enabled(if:)`,没有这个 cache 的机器(包括 CI)会跳过。 + +**修法**:给 `StaticFieldLayoutProvider` 加一个默认返回 `nil` 的投影方法;`MachOFileStaticFieldLayoutProvider` 用自己那份按打印配置建好的依赖闭包来投影(为此 `StaticLayoutCalculator` 开一个公开的 `projectingConcreteMembers(in:)`,它的镜像集合原本是模块内可见)。打印字段时优先用它,没有 provider(没开布局注释)才退回原来的路径。特化器的 `staticPreflight` 没有打印配置,保持现状,写进文档。 + +```diff +--- a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift ++++ b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift +@@ -145,6 +145,14 @@ + } + + // MARK: - Instantiations bound by a binding (evolution proposal `offline-generic-specialization`) ++ ++ /// `node` with every member of a concrete type projected through the ++ /// witness records of this calculator's images — the images its layouts ++ /// are computed over, so a field type projected here and the layout ++ /// printed beside it read the same records. ++ public func projectingConcreteMembers(in node: Node) -> Node { ++ imageUniverse.projectingConcreteMembers(in: node) ++ } + + /// The per-field layout of the instantiation `binding` makes of + /// `typeDescriptor` — every depth of its generic signature bound, so a +--- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift ++++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift +@@ -4,6 +4,7 @@ + import MachOSwiftSection + import MachOFoundation + import SwiftLayout ++import Demangling + @_spi(Internals) import SwiftInspection + + /// How the static (MachOFile) field-layout path resolves field / superclass / +@@ -85,9 +86,21 @@ + /// The expanded nested-field-offset tree for a field type of the + /// instantiation `binding` describes. + func nestedFieldOffsetTree(forMangledTypeName mangledTypeName: MangledName, baseOffset: Int, depthLimit: Int, genericArgumentBinding binding: GenericArgumentBinding) -> [NestedFieldOffset] ++ ++ /// `node` with every member of a concrete type projected through the ++ /// witness records of the images the layouts above are computed over — ++ /// `[Swift.Int].Element` read as `Swift.Int` — so a field's printed type ++ /// and the layout printed beside it come from the same images. `nil` ++ /// when the provider has no images of its own: the caller projects ++ /// through its own. ++ func projectingConcreteMembers(in node: Node) -> Node? + } + + extension StaticFieldLayoutProvider { ++ public func projectingConcreteMembers(in node: Node) -> Node? { ++ nil ++ } ++ + public func aggregateFieldLayout(forDescriptor descriptor: TypeContextDescriptorWrapper, genericArgumentBinding binding: GenericArgumentBinding) -> AggregateFieldLayout? { + nil + } +@@ -190,4 +203,10 @@ + defer { lock.unlock() } + return calculator.nestedFieldOffsetTree(forMangledTypeName: mangledTypeName, baseOffset: baseOffset, depthLimit: depthLimit, genericArgumentBinding: binding) + } ++ ++ public func projectingConcreteMembers(in node: Node) -> Node? { ++ lock.lock() ++ defer { lock.unlock() } ++ return calculator.projectingConcreteMembers(in: node) ++ } + } +--- a/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift ++++ b/Sources/Output/SwiftDeclarationRendering/StaticSpecializationNodeSubstitution.swift +@@ -14,12 +14,23 @@ + /// from. A member no record answers keeps its spelling. + package enum StaticSpecializationNodeSubstitution { + /// `typeNode` — a field's or an enum payload's declared type — with +- /// `binding`'s arguments substituted and concrete members projected. ++ /// `binding`'s arguments substituted and concrete members projected: ++ /// through the images `staticFieldLayoutProvider` computes the layout ++ /// comments over, when the print has one, so the type and its layout agree ++ /// — an iOS binary printed against an iOS cache used to have its layout ++ /// computed while its field kept `[Swift.Int].Element?`, the host's macOS ++ /// images being no candidates for an iOS root. Without a provider (no ++ /// layout comment printed) through the images the opaque rewriter uses. + package static func substitutedTypeNode( + of typeNode: Node, + binding: GenericArgumentBinding, ++ staticFieldLayoutProvider: (any StaticFieldLayoutProvider)?, + in machO: MachO + ) -> Node { +- DependentMemberProjection.projectingConcreteMembers(in: binding.substituting(in: typeNode), in: machO) ++ let substitutedNode = binding.substituting(in: typeNode) ++ if let projectedNode = staticFieldLayoutProvider?.projectingConcreteMembers(in: substitutedNode) { ++ return projectedNode ++ } ++ return DependentMemberProjection.projectingConcreteMembers(in: substitutedNode, in: machO) + } + } +--- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift ++++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +@@ -456,7 +456,12 @@ + } + let substitutedTypeNode: Node? = { + if let staticSpecialization { +- return StaticSpecializationNodeSubstitution.substitutedTypeNode(of: field.typeNode.materialize(), binding: staticSpecialization, in: machO) ++ return StaticSpecializationNodeSubstitution.substitutedTypeNode( ++ of: field.typeNode.materialize(), ++ binding: staticSpecialization, ++ staticFieldLayoutProvider: renderConfiguration.staticFieldLayoutProvider, ++ in: machO ++ ) + } + guard let specializedMetadata, let specializedMachOImage, let mangledTypeName else { return nil } + return SpecializedMetadataNodeSubstitution.substitutedFieldTypeNode(for: mangledTypeName, metadata: specializedMetadata, in: specializedMachOImage) +``` + +**修后**:测试通过。字段类型与布局注释现在出自同一套镜像: + +```swift +struct SimulatorProjectionFixture.ElementsHolder<[Swift.Int]> { + // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 2147483647) + var elements: [Swift.Int] + // Type Layout: (size: 9, stride: 16, alignment: 8, extraInhabitantCount: 0) + var first: Swift.Int? +} +``` + +**落地时**:`StaticFieldLayoutProvider` 多了一个带默认实现的 requirement,`StaticLayoutCalculator` 多了一个公开方法,进发版说明;`Internal/OfflineGenericSpecialization.md` 写明「打印时投影走打印配置的依赖闭包,`staticPreflight` 仍走默认路径」。 + +## 三、不修,登记 + +拟写入 [ReviewAdjudications.md](../Documentations/Internal/ReviewAdjudications.md)(从 A53 起编号),落地批次一起写。 + +### 9. 等待索引时的优先级反转(低) + +`Sources/Declaration/SwiftDeclaration/Components/Definitions/DefinitionIndexing.swift:84`。 + +- **属实**(机制):等待用的是 `SharedCacheBuildPromise.wait()`,底层是 NSCondition;前台打印等后台 utility 线程跑完某个定义的索引时,不会把自己的 QoS(线程调度优先级)借给它。RuntimeViewer 的语料在 `.utility` 优先级上建,用户恰好点开语料正在索引的类型时就会等。通常只差毫秒级,没实测。 +- **基线**:PR 新引入(以前各自索引各自的,但那是数据竞争)。`SharedCache` 的并发构建用的是同一个 promise,一直是同样的取舍。 +- **裁决**:不修。复审条件:RuntimeViewer 出现能感觉到的点开延迟。 +- **真要修**:在 `SharedCacheBuildPromise` 里记下构建线程,等待前用 `pthread_override_qos_class_start_np` 把等待者的优先级借给它,等完 `_end_np`。要处理构建线程在等待开始前已经结束的情况(`pthread_t` 失效),这是没现在就做的另一个原因。`SharedCache` 会一起受益。没写 diff。 + +### 12. 嵌套偏移缓存会记住「解析失败」(低,PR 有意如此) + +- **属实**(设计如此):进程级的嵌套偏移缓存按 metatype 记录每一层,「这个字段类型解析不出」也会被记住;宿主之后加载了定义那个类型的镜像,缓存仍说解析不出。提案里已写明「近乎理论」,review 也没在 AppKit、SwiftUI、WebKit、Xcode IDE 框架里找到实例。本库提供了 `RuntimeFieldLayoutMemo.removeAll()`,由宿主在加载镜像后调用。 +- **裁决**:本库不修。 +- **转 RuntimeViewer**:它的 find-navigator 分支只在自己 `dlopen` 之后(`DyldUtilities.loadImage(at:)`)调用 `removeAll()`;被检查的进程自己加载的镜像不会触发。`DyldUtilities.observeDyldRegisterEvents()` 写了 dyld 加载镜像的回调,但从没被调用。那边要注册这个回调,并在回调里调用 `removeAll()`。 + +## 四、顺带项(review 因条数上限砍掉的) + +| 项 | 结论 | 处置 | +|---|---|---| +| swift-semantic-string 构建阻塞 | `DefinitionRegion` 只在它的 `next` 上,`Package.swift` 下限仍是 `from: "0.4.0"`;`next` 分支没有 CI 门禁,现在合并不会被拦,但合完后按远程版本解析的 `next` 编不过 | PR 描述里已列为合并前的阻碍:先给 swift-semantic-string 发版、再抬下限 | +| 缩写命名 | PR 重写过的几行里有 `param`、`paramName`、`protocolRef`、`swiftProto`、`proto`,新文件里有 `info`;大多是旧代码挪行带过来的 | 只改这几行,diff 见下;`GenericSpecializer.swift` 其余旧代码里的缩写(含公开错误类型的关联值标签)不在本次范围 | +| `ProtocolInExtensionTests` 编 fixture 没写语言模式 | 它不输出 module interface,Swift 6.4 不会报错,只是稳健性 | 补 `-swift-version 5`,diff 见下 | +| 嵌套 `.boundGeneric` 实参链的请求次数随深度平方增长 | 属实,深度 d 时约 d(d+3)/2 次;实际嵌套很浅 | 不修,登记 | +| 测试 fixture 的共享索引器在并行套件下会重复构建 | 只影响测试耗时 | 不修,登记 | +| 离线 `specialize(with:in:)` 只比较描述符偏移 | 拿另一个文件里偏移恰好相同的结果也会被接受;只有误用 API 才会碰到 | 不修,登记;以后可让结果带上镜像身份 | + +缩写改名的 diff(只动 PR 重写过的行): + +```diff +--- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift ++++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift +@@ -205,25 +205,25 @@ +- for (flatIndex, param) in cumulativeParameters.enumerated() { ++ for (flatIndex, parameter) in cumulativeParameters.enumerated() { + // Skip non-key parameters (type packs, values, etc.) +- guard param.hasKeyArgument, param.kind == .type else { continue } ++ guard parameter.hasKeyArgument, parameter.kind == .type else { continue } + guard let position = depthLayout.position(ofParameterAt: flatIndex) else { continue } + + // Get parameter name based on depth and per-level index + // (e.g., A, B, A1, B1, A2...). +- let paramName = genericParameterName(depth: position.depth.cast(), index: position.index.cast()) ++ let parameterName = genericParameterName(depth: position.depth.cast(), index: position.index.cast()) + + // Collect requirements for this parameter (ordered for PWT passing) + let requirements = try collectRequirements( +- for: paramName, ++ for: parameterName, + from: mergedRequirements + ) + + // Find candidate types that satisfy all protocol requirements + let protocolRequirements = requirements.compactMap { requirement -> ProtocolName? in +- if case .protocol(let info) = requirement { +- return info.protocolName ++ if case .protocol(let protocolRequirement) = requirement { ++ return protocolRequirement.protocolName + } + return nil + } +@@ -250,7 +250,7 @@ + parameters.append(SpecializationRequest.Parameter( +- name: paramName, ++ name: parameterName, + index: position.index, +@@ -385,17 +385,17 @@ +- guard case .protocol(let protocolRef) = resolvedContent else { ++ guard case .protocol(let protocolReference) = resolvedContent else { + return nil + } + + // Try to get protocol name + let protocolName: ProtocolName +- switch protocolRef { ++ switch protocolReference { + case .element(let resolved): +- guard let swiftProto = resolved.swift else { return nil } +- let proto = try MachOSwiftSection.`Protocol`(descriptor: swiftProto, in: machO.context) +- protocolName = try proto.protocolName(in: machO.context) ++ guard let swiftProtocolDescriptor = resolved.swift else { return nil } ++ let protocolWrapper = try MachOSwiftSection.`Protocol`(descriptor: swiftProtocolDescriptor, in: machO.context) ++ protocolName = try protocolWrapper.protocolName(in: machO.context) +--- a/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift ++++ b/Sources/Declaration/SwiftSpecialization/GenericSpecializer+StaticSpecialization.swift +@@ -401,8 +401,8 @@ + private func checkConformance(of subject: StaticRequirementSubject, to requirement: GenericRequirementDescriptor, into builder: SpecializationValidation.Builder) { +- guard let builtRequirement = try? buildRequirement(from: requirement), case .protocol(let info) = builtRequirement else { return } +- let protocolName = info.protocolName ++ guard let builtRequirement = try? buildRequirement(from: requirement), case .protocol(let protocolRequirement) = builtRequirement else { return } ++ let protocolName = protocolRequirement.protocolName +--- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift ++++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +@@ -50,7 +50,7 @@ + try run(swiftcArguments: [ +- "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", ++ "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", +``` + +## 五、落地清单 + +决定修哪几条之后: + +1. **每条修复连同它的复现测试同一批提交**;不修的条目把对应测试删掉(或留作 `withKnownIssue`,由用户定),并写进已裁决清单。第 3 条的测试依赖共享 fixture 里新加的 `TiedParameterPair`,两者一起进或一起退。第 13 条的守护测试是修法的一部分,随修法一起进。 +2. **渲染 A/B 必跑**(AGENTS.md 对动到打印和索引的改动的要求)。会改变既有输出的是第 1 条(普通 SwiftUI app 的 opaque 类型实参)、第 4 条(extension 里协议的默认实现块)、第 6 条(静态展开偏移里 opaque 实际类型那一行)、第 8 条(带 provider 的 interface)、第 13 条(kind-9 字段名)。PR 本身在 rebase 和合并 `next` 后也还没重跑 A/B。 +3. **文档同批**: + - 演进账本补一节。 + - `draft-concurrent-definition-printing` 决策日志:第 7 条(前提更正、加锁)、第 9 条(登记)。 + - `draft-offline-generic-specialization` 决策日志与 `Internal/OfflineGenericSpecialization.md`:第 2、3、5、10、11 条。 + - `draft-nested-definition-regions` 决策日志:第 4 条。 + - `Internal/OpaqueReturnTypeResolution.md`:第 1、8 条。 + - `Internal/Modules/SwiftThunkAnalysis.md`:第 13 条。 + - AGENTS.md 的 `specialize(...)` 那句(diff 见第 7 条)。 + - AGENTS.md「Work in progress」那段的「Five readers once counted ancestors」改成八处。 +4. **发版说明(0.22.0)**: + - 新增:`ConformanceProvider` 的两个带默认实现的 requirement(`superclassLink(of:)`、`isConditionalConformance(of:to:)`)和公开枚举 `SuperclassLink`;`StaticFieldLayoutProvider.projectingConcreteMembers(in:)`;`StaticLayoutCalculator.projectingConcreteMembers(in:)`。 + - 行为变化:opaque 类型实参按描述符的层结构分组;离线基类检查对 ObjC 中间类给警告;带条件的遵循给警告。 +5. **转告 RuntimeViewer**:第 4 条(读默认实现列表前先索引协议)、第 7 条(库修后,`specialize` 可以照常在 actor 外跑)、第 12 条(加载镜像后清缓存)。 +6. **另开一项**:`MachOFile` 与 `DyldCache` 懒创建文件句柄的那四处无锁关联对象(见第 7 条的横向排查)。 + +## 六、落地记录(2026-10-08) + +落地在 JHs-Mac-Studio 上做:复现测试、review 记录和完整补丁都只在 Ultra 上、没有推送,经 ssh 只读地取回,在同一个基线 `beae202d` 上打上补丁(`git apply --check` 干净)。 + +**提交**(每条修复连同它的复现测试一个 commit,按顺序): + +| commit | 条目 | +|---|---| +| `4661eb42` | 第 1 条:opaque 类型的实参按描述符的层结构分组 | +| `c8cf653d` | 第 8 条:opaque provider 从所在类型或 extension 取层数 | +| `7d7ffd41` | 第 13 条:泛型 extension 里的类型由 thunk 拼出名字(含守护测试) | +| `ad4f33b3` | 第 2 条:离线父类检查沿父类链往上走 | +| `6c35e8c4` | 第 3、10 条:「参数 == 参数」的约束补参数;退回扁平名时记日志 | +| `d1a47dfb` | 第 4 条:读默认实现列表前先索引协议 | +| `d2f8d586` | 第 5 条:带条件的遵循给警告 | +| `2d58a451` | 第 6 条:投影出的实际类型是 opaque 时保留成员名 | +| `f5266e30` | 第 7 条:`specializedChildren` 加锁 | +| `5308fa1a` | 第 11 条:字段类型经打印配置的依赖闭包投影 | +| `de14e727` | 第 14 条:没有关联类型成员的节点不做投影 | +| `4e8f4a7f` | 第四节的两个顺带项:缩写改名、`ProtocolInExtensionTests` 补 `-swift-version 5` | +| `07993a5f` | 落地清单第 6 项:`MachOFile` / `DyldCache` 的文件映射和句柄持锁创建、只存一次 | +| `f108d5e6` | 第 15 条:CI 过滤列表与单线程池、关大栈执行器的一步 | + +文档(本记录、已裁决清单 A53–A59、四份提案的决策日志、实现说明、演进账本)在随后的文档提交里。 + +**落地清单第 6 项改为本批就修**:全局规则要求确认为真的问题连同类一起修。查到它可达——`FullDyldCache` 把同一批子 cache 实例交给所有镜像,`FullDyldCache.cachedHost` 是进程级单例,`diff` 与 `evolution` 并行准备几个输入、各自经依赖查找读宿主 cache 时,会同时第一次读同一个子 cache。新测试 `ConcurrentFileMappingTests`(`MachOSwiftSectionTests`)每轮新建一个实例,让 32 个线程同时做第一次读取,每个 getter 跑 20 轮:修前四个 getter 都失败,20 轮里有 12 到 19 轮,32 个读者拿到 2 到 7 个不同的对象;修后每轮都只有一个。`MachOFile` 那两处只在同一个文件被并发读时才会撞上(`MachOFile` 读者本来就不承诺并发),修法一样、热路径不变,一并改了。 + +**本机验证**(Xcode 26.6、Swift 6.3.3,也就是 CI 的工具链;Ultra 上用的是 Swift 6.4)。沙盒 `/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorReviewFixes/MachOSwiftSection` 只链 swift-semantic-string,其余依赖钉到与 Ultra 相同的版本(MachOKit 0.54.101、MachOKitExtensions 1.1.2、MachOObjCSection 0.8.109、swift-demangling 0.7.1);fixture 按 CI 的做法 ad-hoc 签名重编。日志在 `/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorReviewFixes/Logs/`。 + +- 修前(PR 头的源码 + 全部测试):10 个复现套件(含 `ConcurrentFileMappingTests`)全部失败,`OfflineProjectionDependencyResolutionTests` 跳过(见下),原始退出码 1;第 13 条的守护测试照常通过。`repro-suites-baseline.log`。 +- 修后:同样这些套件的 19 个测试里 18 个通过、第 11 条那个跳过,原始退出码 0。`repro-suites-final.log`。 +- `OfflineProjectionDependencyResolutionTests` 在上面两轮里都跳过:本机没有 `/Volumes/DyldSharedCaches/iOS-Simulator/27.0`。另在沙盒副本里把它的路径临时改指本机装的 iOS 27.0 模拟器 runtime(`/Library/Developer/CoreSimulator/Volumes/iOS_24A434/…/dyld_sim_shared_cache_arm64`),PR 头上失败(字段仍是 `[Int].Element?`)、修后通过。`environment-check-baseline.log`、`environment-check-final.log`。 +- 全量 `swift test --skip IntegrationTests`:2358 个测试、448 个套件(Ultra 上的 2354 / 447 加上新的 `ConcurrentFileMappingTests`),原始退出码 1。失败的只有 `MultiPayloadEnumDescriptorCacheTests` 的 `everyFixtureMultiPayloadEnumRendersALayout` 与 `noncopyableMultiPayloadEnumLaysOutFromItsResolvedPayloads`:换回 PR 头的源码,在同一个沙盒、同一份 fixture 上同样两条在同样位置(`:101`、`:130`)失败,是这台机器上早就有的环境问题,`next` 上也是这样(进程内 enum 布局,这批改动不碰)。另有早已登记的 known issue(`SymbolicManglingIndexTests`)。`full-suite-final.log`。 +- 渲染 A/B:基线 `beae202d`,候选 `f108d5e6`(这批代码提交的末尾),两侧都是 `git archive` 出来的沙盒、只链 swift-semantic-string、共用同一份 `Package.resolved`,经构建队列预构建 release 后带 `--skip-build --no-baseline-cache --jobs 3` 跑。**90 对全部逐字节一致**:归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 27.0 模拟器的框架在 cache 里、不是文件,按设计跳过。输出在 `/Volumes/DerivedData/Agents.noindex/claude/Sandboxes/FindNavigatorReviewAB/Output/`,日志 `…/FindNavigatorReviewAB/Logs/ab-run.log`。落地清单第 2 项列出的会改变输出的几条,在这些框架与选项组合里都没有触发;第 1 条另用两侧 CLI 对本机 `/Applications/Xcodes.app` 复核:11599 行的 interface 只有两行不同(第 4308、4895 行),都是 `TupleToolbarContent` 补上了实参,与第 1 条「修后」一节在 Ultra 上看到的一致(那边是 11603 行,宿主不同);补出来的类型里露出的 5 处 `accessor function at` 就是那一节说的既有限制。 + +**还没做的**:RuntimeViewer 那边的三件事(落地清单第 5 项)还没转告;PR #131 的描述里的发版说明还没按上面第 4 项更新;推送等用户确认。另外 PR 现在与 `next` 冲突:`next` 在 `433f1421` 之后合进了两个修复,并要求 MachOObjCSection 0.8.110,要再把 `next` 合进分支一次。 From 52460a79c3574f6c53a6f9e70f99d2438114782f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 8 Oct 2026 20:38:48 +0800 Subject: [PATCH 28/49] feat(declaration): say which protocols the printer trails with their default implementations RuntimeViewer's Find corpus and content pane print a protocol's default-implementation extensions themselves whenever the printer does not trail the declaration with them, so they need the printer's rule. It was private, so RuntimeViewer copied it; when bca9594d added `extensionContext == nil` to it, the copy was wrong until RuntimeViewer followed in a commit of its own (74c349c7). This package held two copies as well: the printer's condition, and its negation in SwiftInterfaceBuilder's block for nested protocols. ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration now states the rule once: true only for a protocol declared at the top level, neither nested in a type nor declared in an extension of another module's type. Three places change: - ProtocolDefinition gains the public property. Its documentation gives the rule, why a nested protocol and one declared in another module's extension print their extensions at the top level instead, and that the printer, the interface builder and hosts all read it. - SwiftDeclarationPrinter.printProtocolDefinition trails the declaration with the extensions when the property is true. - SwiftInterfaceBuilder prints, in its block for nested protocols, the extensions of every protocol for which it is false. Behavior is unchanged. On JHs-Mac-Studio with Xcode 27.0 and the local sibling dependencies, SwiftInterfaceTests, SwiftSectionKitTests and SwiftPrintingTests (without EnumCaseRenderingParityTests) give the same per-test results before and after: 289 -> 290, 64 and 42 tests, all passing, raw exit code 0. The added one is the new test; the whole-module SymbolTestsCore interface snapshot is among the rest. EnumCaseRenderingParityTests crashes (SIGSEGV) in its first test in this environment, before and after alike. ProtocolInExtensionTests' fixture gains a top-level protocol, and a new test pins the property true / false / false for a protocol declared at the top level, in a type, and in an extension of Int. With the property set back to `parent == nil` alone, the rule before bca9594d, that test fails along with the suite's three existing ones, so the printer and the interface builder both go through the property. Docs: the decision log of draft-nested-definition-regions, a note in the evolution log's section for it, and ExtensionContainerUnification's description of the trailing path. RuntimeViewer PR #121 review finding PR121.27. --- .../draft-nested-definition-regions.md | 3 +- .../Internal/ExtensionContainerUnification.md | 2 +- .../Internal/ProjectEvolutionLog.md | 1 + .../Definitions/ProtocolDefinition.swift | 20 ++++++++++ .../SwiftInterfaceBuilder.swift | 7 +++- .../SwiftDeclarationPrinter.swift | 12 +++--- .../ProtocolInExtensionTests.swift | 39 +++++++++++++++++-- 7 files changed, 69 insertions(+), 15 deletions(-) diff --git a/Documentations/Evolutions/draft-nested-definition-regions.md b/Documentations/Evolutions/draft-nested-definition-regions.md index 2b56c7f21..12085ff99 100644 --- a/Documentations/Evolutions/draft-nested-definition-regions.md +++ b/Documentations/Evolutions/draft-nested-definition-regions.md @@ -2,7 +2,7 @@ - **状态**: In Progress - **创建日期**: 2026-10-01 -- **最后更新**: 2026-10-01 +- **最后更新**: 2026-10-08 - **所属愿景**: 无 - **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(同一手法:区域编码在原子的 `identifier` 里,冻结后分离成一张表);RuntimeViewer 的 `draft-find-navigator` §1.1 方案 D(使用方);swift-semantic-string 的设计记录 `docs/VisibilityRegions.md` - **实现分支 / PR**: 本库 `feature/runtime-viewer/find-navigator`;swift-semantic-string `feature/definition-regions` @@ -69,3 +69,4 @@ RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的 | 2026-10-01 | 验证:契约测试全部通过 | `NestedDefinitionRegionContractTests`(SwiftInterfaceTests):SymbolTestsCore 里每个有嵌套定义的根类型与 extension(几乎所有类型都嵌在命名空间 enum 里),进程内与文件两种读取方式,各三种配置——只开 `marksNestedDefinitions`;再开 `marksOptionalContent` 并挂 opaque 解析器;全部打印选项打开并装上 `applyTransformers(_:)` 的全部模板。每个区域取出、去缩进后与单独打印比较文本、span、identifier、可见性区域表与内层定义区域表,并核对区域数等于嵌套定义数(防漏标),每种配置都检查了 100 个以上的区域,首次运行即全部通过;另有一条确认开关打开时分离后的文本与不开时逐字节相同。swift-semantic-string 侧全部 432 个测试通过、watchOS `arm64_32` 编译通过。 | | 2026-10-01 | 全量测试与渲染 A/B 通过;Foundation 上只挪动了两个扩展 | 全量 `swift test --skip IntegrationTests`(沙盒副本,本地兄弟依赖,swift-semantic-string 指向 `feature/definition-regions`)2174 个测试全部通过,原始退出码 0。渲染 A/B:基线是本分支 `ed289fb4` 的 git archive,候选是加上本提案改动的副本,两侧依赖相同、只有 swift-semantic-string 指向不同分支;92 对逐字节一致,iOS 15.5 模拟器的 SwiftUI / WidgetKit 两侧同样崩溃(MachOKit `ExportTrie.init`,见并发打印提案)。A/B 的框架里没有协议声明在别的模块类型的 extension 里,另用两侧 CLI 渲染当前系统 Foundation 的 interface 对比:只有 `NSNotificationCenter.AsyncMessage` 与 `NSNotificationCenter.MainActorMessage` 的两个默认实现扩展,从 `extension __C.NSNotificationCenter { … }` 的大括号里(顶格)挪到了顶层的嵌套协议扩展区块,其余四万多行逐字节相同。 | | 2026-10-08 | PR #131 review 第 4 条:interface 的嵌套协议默认实现区块读列表之前,先对协议调用 `index(in:)` | 声明在 extension 里的协议,要到后面的 extensions 区块才被打印、被索引;而它的默认实现列表只有在协议自己的索引过程里才完整——library evolution 下,默认实现来自父协议 extension 时,编译器生成一个挂在需求名下的默认 witness,`prepare()` 的符号扫描认不出它,由协议的索引过程兜底补出这个 extension。区块读列表时协议还没索引,列表是空的,打印器又不再在协议后面接它(本提案的改动),于是这个 extension 哪里都不打印;同一个 builder 打印两次,第二次才出现。改前它被打印在外层 extension 的大括号里(位置不合法,但打印了),所以这是本提案引入的回退,只出现在这个窄形状上。索引同步、可重复调用、只跑一次(`DefinitionIndexing`),区块顺序不动。复现测试 `ProtocolInExtensionDefaultWitnessTests`(library evolution 编的 fixture)先红后绿。RuntimeViewer 的 `defaultImplementationExtensionsLeftToPrint(of:)` 也是直接读这个列表,要同样先索引协议(那边改)。根因的另一种修法——让 `prepare()` 认出挂在需求名下的默认 witness——改动大得多,没做 | +| 2026-10-08 | 「哪些协议在声明后面接着打印默认实现扩展」公开为 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration`,打印器与 `SwiftInterfaceBuilder` 都改读它 | RuntimeViewer PR #121 审查的第 PR121.27 条:它的 Find 语料与内容区要自己补印打印器不接在协议后面的默认实现扩展,此前只能照抄本提案定下的条件;本提案 2026-10-01 给条件加上 `extensionContext == nil` 时,它那份拷贝就错了,直到它的 74c349c7 跟上。库里也写了两份:打印器一份,`SwiftInterfaceBuilder` 的嵌套协议区块取反一份。现在规则只写在这个属性里(`parent == nil && extensionContext == nil`):打印器读它,区块读它的反面,宿主也读它;文档注释写明为什么嵌在类型里与声明在别的模块类型的 extension 里的协议不在其列。行为不变:JHs-Mac-Studio、Xcode 27.0、本地兄弟依赖,改动前后 SwiftInterfaceTests、SwiftSectionKitTests 与 SwiftPrintingTests(不含 `EnumCaseRenderingParityTests`)的逐条结果相同,289→290、64、42 个测试全部通过,原始退出码 0,多出的一条是新测试;整模块 interface 快照 `SymbolTestsCoreInterfaceSnapshotTests` 也在其中。`EnumCaseRenderingParityTests` 在这个环境里改动前后都在第一个测试崩溃(SIGSEGV),两侧单独跑结果相同,与本改动无关。`ProtocolInExtensionTests` 的 fixture 加了顶层协议 `Greeter`,新测试断言三种位置的协议这个属性分别为 true / false / false;把属性临时改回只看 `parent == nil`(本提案之前的规则)时,新测试与该套件原有的三条一起失败,说明打印器与区块都只经这个属性。渲染 A/B 没做:只是把已有条件抽成属性,不算 AGENTS.md 说的大型重构 | diff --git a/Documentations/Internal/ExtensionContainerUnification.md b/Documentations/Internal/ExtensionContainerUnification.md index 4301397aa..6463b1928 100644 --- a/Documentations/Internal/ExtensionContainerUnification.md +++ b/Documentations/Internal/ExtensionContainerUnification.md @@ -19,7 +19,7 @@ **`updateConfiguration` 的 re-prepare 原为静默 no-op。** `prepare()` 的 `isPrepared` 门从无人复位,配置变更后的重建从未发生过。顺带修复(复位后重跑),它同时成为桶重置(`index()` 入口清空四桶)的确定性验证入口——修复前 re-run 会把所有 append 产线的块成倍复制。 -**嵌套协议的扩展块经由原死循环的修复版打印。** `printRoot` 里那个循环原来在 root 协议上过滤 `parent != nil`(恒空);修复为遍历 `allProtocolDefinitions` 的嵌套协议。fixture 的协议全部嵌套在 enum 命名空间里,所以快照中四个协议扩展块整体从 extensions 区迁到 protocols 区之后——纯迁移,零内容变化。顶层协议走 `printThrowingProtocol` 的尾随路径(`parent == nil` 门)。 +**嵌套协议的扩展块经由原死循环的修复版打印。** `printRoot` 里那个循环原来在 root 协议上过滤 `parent != nil`(恒空);修复为遍历 `allProtocolDefinitions` 的嵌套协议。fixture 的协议全部嵌套在 enum 命名空间里,所以快照中四个协议扩展块整体从 extensions 区迁到 protocols 区之后——纯迁移,零内容变化。顶层协议走 `printProtocolDefinition` 的尾随路径。哪些协议尾随由 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration` 一处回答(既没有 `parent` 也没有 `extensionContext`),这个循环取它的反面,所以声明在别的模块类型的 extension 里的协议也走这个循环(见 [draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md));宿主自己补印默认实现扩展时读的也是这个属性。 **`protocol-extension default` 标注落在 conformance 兜底分支。** `ExtensionDefinition.index()` 经 `element.defaultImplementationSymbols` 解析成功的 witness,其成员打 `isProtocolExtensionDefault`,interface(`renderMember`)与 dump(`ProtocolConformanceDumper`)在 `printMemberAddress` 开启时渲染标注。**SourceEditor 上未触发**:折叠地址上 `resilientWitness.implementationSymbols` 的首选分支总能命中(protocol witness 符号在场),兜底分支需要「witness 实现符号缺失而默认实现符号可解析」的组合——已落地待真实触发场景(fixture 非 resilient,`resilientWitnesses` 为空,同样够不到)。issue 点名的 `SourceEditorView.elide` 三兄弟经 `nm` 证实是**真类成员**被 ICF 折叠(提案 0006 的 `Tq` 门处理),并非误归属的协议默认实现。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 05576f2cc..11c1e5044 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2303,6 +2303,7 @@ - **关键决策**:**① 新开关 `marksNestedDefinitions`**(默认关,关着时输出逐字节不变),四处嵌套循环把子定义的打印包进 swift-semantic-string 新增的 `DefinitionRegion`,身份是名字节点的 mangled name;名字 remangle 失败或含控制字符就不标,宿主单独打印。**② 库接口在带标记的串上切**:`content(ofDefinitionRegion:)` 去掉外层身份、按首次使用顺序重建 identifier 表,`removingIndentation(levels:)` 按行去缩进,切出的串再分离出的两张表与单独打印的相同;原方案「连同可见性区域表一起切」改掉,因为条件按 identifier 表顺序编号,切表等于重写分离逻辑。定义区域的编码放在可见性标记里面一层,容器与可见性分离都不受影响。**③ 先修一个既有问题**:协议声明在别的模块类型的 extension 里(`extension Int { protocol Counter }`)时,默认实现扩展被打印在外层 extension 的大括号里、顶格,生成的 Swift 不合法;现在只有顶层协议原地带出扩展,这类协议的扩展与嵌在类型里的协议一样放进 interface 的顶层 extensions 区块。声明在本模块类型的 extension 里的协议被编译器直接挂在类型上,本来就打印正确。 - **落地模块**:SwiftPrinting(`SwiftDeclarationPrintConfiguration.marksNestedDefinitions`、新文件 `SwiftDeclarationPrinter+DefinitionRegions.swift`、四处嵌套循环、协议默认实现扩展的条件)、SwiftInterface(顶层区块收录 extension 里的协议的扩展);swift-semantic-string(`DefinitionRegion`、`DefinitionRegionTable`、`separatingDefinitionRegions()`、`content(ofDefinitionRegion:)`、`removingIndentation(levels:)`)。测试新增 `NestedDefinitionRegionContractTests`、`ProtocolInExtensionTests`,两者加进 CI 主过滤列表。 - **验证**:`ProtocolInExtensionTests` 先红后绿。契约测试对 SymbolTestsCore 每个有嵌套定义的根类型与 extension,在进程内与文件两种读取方式、三种配置(只标定义区域;加标记模式;全部选项加 Transformer 模板)下逐区域比较,全部通过,区域数与嵌套定义数一致。swift-semantic-string 全部 432 个测试通过,watchOS `arm64_32` 编译通过。全量测试与渲染 A/B 见提案决策日志。 +- **补记(2026-10-08)**:③ 定下的规则公开为 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration`(新增公开 API,写进 0.22.0 发版说明)。此前库里写了两份(打印器一份,`SwiftInterfaceBuilder` 的嵌套协议区块取反一份);RuntimeViewer 要知道哪些协议的默认实现得自己补印,只能再照抄一份,③ 改规则时它就跟着错过一次(RuntimeViewer PR #121 审查的第 PR121.27 条)。现在打印器、interface 生成器与宿主都读这个属性。行为不变,证据见提案决策日志。 - **关联文档**:[draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md)、[Glossary.md](../Glossary.md)「nested-definition region」、swift-semantic-string 的 `docs/DefinitionRegions.md`。 - **对应版本**:未发版。落地前要先发布带 `DefinitionRegion` 的 swift-semantic-string,并抬高本库对它的版本下限。 diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift index 94d206bdb..d0d1c4de7 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift @@ -29,6 +29,26 @@ public final class ProtocolDefinition: Definition, MutableDefinition, @unchecked public package(set) var defaultImplementationExtensions: [ExtensionDefinition] = [] + /// Whether `SwiftDeclarationPrinter.printProtocolDefinition` prints + /// ``defaultImplementationExtensions`` right after the protocol's + /// declaration: true only for a protocol declared at the top level. + /// + /// A protocol nested in a type, or declared in an extension of another + /// module's type (which leaves it an ``extensionContext`` and no + /// ``parent``), prints inside that declaration's braces, where Swift + /// cannot put an extension. Its default-implementation extensions belong + /// at the top level instead: the interface prints them in its block for + /// nested protocols, and a host that prints such a protocol by itself + /// appends them after it. A protocol declared in an extension of its own + /// module's type is the nested kind: the compiler parents it on the type. + /// + /// The printer, the interface builder (`SwiftInterfaceBuilder`) and hosts + /// all read this one rule rather than restating it, so they cannot + /// disagree on where those extensions print. + public var printsDefaultImplementationExtensionsAfterDeclaration: Bool { + parent == nil && extensionContext == nil + } + public package(set) var associatedTypes: [String] = [] public package(set) var allocators: [FunctionDefinition] = [] diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift index f76252285..f3151ef8f 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift @@ -238,14 +238,17 @@ public final class SwiftInterfaceBuilder: Sen // blocks: the per-protocol printer emits them trailing TOP-LEVEL // protocol declarations only (extension blocks cannot nest inside // a parent's body), so nested protocols' blocks surface here at - // the top level instead. This loop was dead before evolution + // the top level instead. The loop takes exactly the protocols + // `printsDefaultImplementationExtensionsAfterDeclaration` rules + // out — the printer reads the same property — so each block + // prints once. This loop was dead before evolution // proposal 0007 — it filtered ROOT protocols on `parent != nil`, // which no root ever satisfies, so nested protocols' blocks never // printed at all. A protocol declared in an extension of another // module's type is nested too, with an extension context instead // of a parent; its blocks used to print inside that extension's // braces (evolution proposal `nested-definition-regions`). - for protocolDefinition in indexer.allProtocolDefinitions.values where protocolDefinition.parent != nil || protocolDefinition.extensionContext != nil { + for protocolDefinition in indexer.allProtocolDefinitions.values where !protocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration { for extensionDefinition in indexedDefaultImplementationExtensions(of: protocolDefinition) { await printCatchedThrowing( dispatchingTo: eventDispatcher, diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index ec53274df..a518149be 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -380,13 +380,11 @@ public final class SwiftDeclarationPrinter: S } } - // Only a top-level protocol trails its default-implementation - // extensions. One nested in a type, or declared in an extension of - // another module's type (which leaves it an extension context and no - // parent), prints inside that declaration's braces, where an - // extension cannot go — the interface prints its extensions in the - // top-level extensions block instead (`SwiftInterfaceBuilder`). - if protocolDefinition.parent == nil, protocolDefinition.extensionContext == nil { + // Which protocols trail their default-implementation extensions is + // `printsDefaultImplementationExtensionsAfterDeclaration`'s to say: a + // top-level one only. The interface prints the others' extensions in + // its top-level block for nested protocols (`SwiftInterfaceBuilder`). + if protocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration { // Per-extension catch: a default-implementation extension whose // printing throws drops only itself, not the protocol it trails. await BlockList { diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift index 66e9f681a..117413a07 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -76,13 +76,25 @@ struct ProtocolInExtensionTests { /// `FixtureAnchor` is ballast: a fixture dylib with no class has no /// `__DATA` segment, which older MachOKit releases mis-walked. /// - /// Only `Int.Counter` has an extension context. The compiler parents a - /// protocol declared in an extension of this module's own type on the - /// type itself, so `Host.Delegate` is a nested protocol of `Host` — the - /// case that already printed right, kept here as the contrast. + /// A protocol in each place one can be declared: `Greeter` at the top + /// level, `Host.Delegate` in a type, `Int.Counter` in an extension of + /// another module's type. Only `Int.Counter` has an extension context. + /// The compiler parents a protocol declared in an extension of this + /// module's own type on the type itself, so `Host.Delegate` is a nested + /// protocol of `Host` — the case that already printed right, kept here as + /// the contrast. private static let source = """ public final class FixtureAnchor {} + public protocol Greeter { + func greet() + } + + extension Greeter { + public func greet() {} + public func greeterHelper() -> Int { 2 } + } + public struct Host { public init() {} } @@ -166,6 +178,25 @@ struct ProtocolInExtensionTests { } } + /// `printsDefaultImplementationExtensionsAfterDeclaration` is the one + /// statement of the rule the printer, the interface builder and hosts + /// read: a host appends a protocol's default-implementation extensions + /// itself exactly when it is false. + @Test("only a protocol declared at the top level is printed with its default implementations after it") + func onlyATopLevelProtocolTrailsItsDefaultImplementations() async throws { + let indexer = SwiftDeclarationIndexer(in: try loadFixture()) + try await indexer.prepare() + + let verdictByProtocolName = Dictionary(uniqueKeysWithValues: indexer.allProtocolDefinitions.values.map { + ($0.protocolName.name, $0.printsDefaultImplementationExtensionsAfterDeclaration) + }) + #expect(verdictByProtocolName == [ + "ProbeProtocolInExtension.Greeter": true, + "ProbeProtocolInExtension.Host.Delegate": false, + "Swift.Int.Counter": false, + ]) + } + @Test("a protocol declared in an extension, taken out of the extension's print, is its own print") func regionTakenOutOfTheExtensionIsTheProtocolsOwnPrint() async throws { let machOFile = try loadFixture() From c9e82cc71c9f363c8086f258e690ad84f2cda747 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 9 Oct 2026 15:17:47 +0800 Subject: [PATCH 29/49] docs: track external ObjC changes, starting with direct methods LLVM 23 gives objc_direct methods a stable `-[Class sel]D` symbol and Swift is pitching `@objcDirect` on top of it. Such methods have no method list entry, so the ObjC member recovery would silently miss them. Record the upstream status, the binary shape and the constraints a future reader must respect, in a new section for ObjC-side changes. --- .../Internal/ObjCChanges/ObjCDirectMethods.md | 96 +++++++++++++++++++ Documentations/Internal/ObjCChanges/README.md | 23 +++++ Documentations/Internal/ObjCMemberRecovery.md | 1 + Documentations/README.md | 1 + 4 files changed, 121 insertions(+) create mode 100644 Documentations/Internal/ObjCChanges/ObjCDirectMethods.md create mode 100644 Documentations/Internal/ObjCChanges/README.md diff --git a/Documentations/Internal/ObjCChanges/ObjCDirectMethods.md b/Documentations/Internal/ObjCChanges/ObjCDirectMethods.md new file mode 100644 index 000000000..a5de2f821 --- /dev/null +++ b/Documentations/Internal/ObjCChanges/ObjCDirectMethods.md @@ -0,0 +1,96 @@ +# direct method 的新 ABI 与 Swift `@objcDirect` + +- **上游链接**:Swift 提案 [swift-evolution#3501](https://github.com/swiftlang/swift-evolution/pull/3501)(第二次 pitch,[论坛帖](https://forums.swift.org/t/pitch-2-objcdirect-direct-dispatch-for-objective-c-exposed-methods/89708))、实现 [swiftlang/swift#91894](https://github.com/swiftlang/swift/pull/91894);clang 侧 [LLVM RFC](https://discourse.llvm.org/t/rfc-optimizing-code-size-of-objc-direct-by-exposing-function-symbols-and-moving-nil-checks-to-thunks/88866)、[llvm-project#170616](https://github.com/llvm/llvm-project/pull/170616)、[llvm-project#170618](https://github.com/llvm/llvm-project/pull/170618) +- **上游状态**:clang 侧已合入,随 LLVM 23 发布;Swift 侧是 pitch,提案状态 "Awaiting review",实现 PR 未合,且只能在实验开关 `-enable-experimental-feature ObjCDirect` 下使用 +- **最后核对**:2026-10-09 +- **我们的动作**:观望,未立提案 + +## 一句话 + +direct method 是不走 `objc_msgSend` 的 ObjC 方法:调用方把它当普通 C 函数直接调用,它没有 selector,也不进类的 method list(ObjC runtime 用来按 selector 查找实现的那张表)。clang 从 2019 年起就支持 `__attribute__((objc_direct))`,LLVM 23 给它换了一套跨编译器可用的 ABI;Swift 提案在这套 ABI 之上新增 `@objcDirect`,让 Swift 方法也能以 direct method 的形式暴露给 ObjC。对我们来说,这类方法在 ObjC metadata 里不留痕迹,**ObjC 成员恢复会静默漏掉它们**;不会崩,也不会读错。 + +## 上游变了什么 + +### clang 侧:两代 ABI + +| | 2019 设计(clang 10 起) | LLVM 23 的新 ABI(`-fobjc-direct-precondition-thunk`) | +|---|---|---| +| 符号名 | `\01-[Class sel]`,强制 hidden | `-[Class sel]D`,不再强制 hidden | +| receiver 为 `nil` 的检查 | 在被调用方里,每次都做 | 在调用方生成的 `-[Class sel]D_thunk` 里,只在调用方证明不了 receiver 非 `nil` 时才调用这个 thunk | +| class method 的类初始化(realization) | 被调用方里先发一次 `[self self]` | 在同一个 thunk 里,只在类可能尚未初始化时做 | +| `_cmd` 参数 | 留在签名里,调用方不赋值 | 不在签名里 | + +`-[Class sel]D_thunk` 是 `linkonce_odr` 加 hidden:每个调用方的编译单元各自生成一份,链接时折叠,定义 direct method 的镜像里不一定有它。编译开关在 clang 22 就有,但只改符号名、不生成 thunk,真正可用的下限是 clang 23。 + +这套新 ABI **不依赖 Swift 提案是否通过**:用 clang 23 加这个开关编译的纯 ObjC 二进制,本身就会带 `-[Class sel]D` 符号。 + +### Swift 侧:`@objcDirect` + +提案把编译器原本为每个 `@objc` 成员生成的桥接函数(符号以 `To` 结尾的 `@objc` thunk)原样复用,只改两处:符号名换成 `-[Class sel]D`,签名去掉 `_cmd`。Swift 原生入口 `$s…F`、vtable、method descriptor 都不变,提案明确说这个属性不改变 Swift ABI。 + +能写在哪里(编译器在这些位置之外都会报错): + +- 非泛型类的方法与 initializer,且必须是静态派发:不能是 `override`、`dynamic`(含 `@NSManaged`)、`required init`、`@IBAction`,也不能有子类覆写它。非 `final` 的方法只要没有子类覆写就可以写。 +- 不能是 `private` / `fileprivate`,不能是协议 requirement,不能是 `async`。 +- 不支持 property、accessor、subscript、`deinit`(提案把它们列为 future direction)。 +- 可以写在 `@objc @implementation` extension 里,但必须与头文件里的 `objc_direct` 声明一致。SE-0436 原本把 `objc_direct` 列为 `@implementation` 表达不了的东西,这个提案补上了。 + +普及的门槛:import 生成头文件的**每一个** ObjC 编译单元都必须开同一个 clang 开关,否则链接时找不到符号。所以这是整个构建系统的设置,不是单个 target 能决定的。 + +## 二进制里会变成什么样 + +以一个 `@objc` 方法改成 `@objcDirect` 为例: + +| 二进制里的事实 | 普通 `@objc` 方法 | `@objcDirect` 方法 | +|---|---|---| +| 类的 method list 条目(selector、type encoding、IMP) | 有 | 没有 | +| selector 字符串 | 有 | 没有(除非别处也用到同名 selector) | +| `@objc` thunk 的符号 | `$s…FTo`,local | 没有 `To` 符号,同一个函数改名为 `-[Class sel]D` | +| thunk 的参数 | `self, _cmd, 实参…` | `self, 实参…` | +| thunk 符号的可见性 | 永远 local | 方法的有效访问级别是 `public` 时导出,否则 hidden | +| Swift 原生入口、vtable、method descriptor | 有 | 不变 | +| `.swiftinterface` | `@objc` | `@objcDirect`,且 `swift-module-flags` 里记下 `-enable-experimental-feature ObjCDirect` | + +符号里的类名是**生成头文件里的 `@interface` 名**:有 `@objc(Name)` 就是 `Name`,否则是 Swift 类的简单名(如 `Cache`),**不是** ObjC runtime 名(`_TtC3Mod5Cache`)。class method 用 `+[Class sel]D`,`throws` 方法在末尾多一个 `NSError **` 参数,`@objc(renamedSelector)` 改的是符号里的 selector 段。 + +## 对我们的影响 + +### 不受影响 + +- ABI 读取层(`MachOSwiftSection`)、demangler、`SwiftLayout`:Swift metadata 和 mangling 都没变。`-[Class sel]D` 不是 Swift 符号,符号索引对它的处理和对今天已有的 `-[Class sel]` 一样。 +- Swift 侧 ABI diff(`SwiftDiffing`):它本来就不比较 `@objc`,与提案「不改变 Swift ABI」一致。 + +### 静默漏信息 + +1. **ObjC 成员恢复看不到 direct method**。`ObjCMembers.table(...)`(`Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift`)从类的 method list 出发,三档证据都要先有一个 IMP:第一档看 IMP 处的 `To` 符号,第二档反汇编 IMP 处的 thunk,第三档按 selector 名字匹配 method list 条目。direct method 不在 method list 里,三档都轮不到它。结果是 interface 和 dump 把它印成普通 Swift 方法,不带 `@objc`,也不带 `@objcDirect`。 + - 写了 `final` 的 direct method 没有 method descriptor,也没有 `@objc` 证据,`recoverFinalMembers`(`TypeDefinition+FinalRecovery.swift:64`)会给它补上 `final`,与源码一致。 + - 没写 `final` 的(提案允许,只要没有子类覆写)有没有 vtable 条目,提案没说,要等工具链可用后用 fixture 实测。 +2. **`@objc @implementation` 类的 ObjC 段不再完整**。[ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md) 的前提之一是「ObjC 方法表永远完整」,direct 成员打破了它:dump 的 ObjC 段会少掉这些方法。Swift 侧还能不能从符号里看到这些成员,要等工具链实测。 +3. **`swift-section objc` 把「改成 direct」报成「删除」**。`objc diff` 看到的是 method list 少了一个条目,而这个方法其实变成了一个导出符号,我们没有读。纯 ObjC 的 direct method 在 2019 设计下本来就看不见,这不是新问题;新 ABI 让 `public` 的 direct method 有了可读的导出符号,才变成「能读而没读」。 + +## 将来支持时的要点 + +这里只记约束,方案到时候写进提案。 + +- **证据来源是符号名**:`-[Class sel]D` / `+[Class sel]D`,非 `public` 的在 local 符号表里(只在未 strip 的二进制里有),`public` 的在 export trie 里。从名字能读出类名、selector、实例方法还是 class method;读不到 type encoding,因为它没有 method list 条目。 +- **系统 cache 里只剩 `public` 的**:hidden 符号会和 `To` thunk 一样被 strip 掉(AppKit 的 cache 镜像就是这样)。 +- **联结到 Swift 成员可以复用第二档的 thunk 解码**:`-[Class sel]D` 的函数体就是原来的 `@objc` thunk,同样会调用 Swift 实现。区别是少了 `_cmd`,实参寄存器整体前移一位(第一个实参在 `x1`,不在 `x2`);解码器只找调用目标时不受影响,读实参时要注意。 +- **类名要按头文件名查**:没有 `@objc(Name)` 的类,符号里是 Swift 简单名,现有按 runtime 名查找的入口(`ObjCClassMethodIndex.runtimeNames(forSwiftClassQualifiedName:)`、`SwiftClassObjectIndex`)都对不上,需要新增一个按头文件名查找的入口。 +- **不要把 direct method 记成 `.objc`**,要单独加一个属性 case。今天有两处把 `.objc` 读成「经 ObjC runtime 派发」: + - `recoverFinalMembers` 把「有 `.objc` 且无 descriptor」当作 `@objc dynamic`、不补 `final`,而 direct method 恰恰是静态派发。 + - `--exported-only` 过滤(`SwiftDeclarationPrinter+ExportFilter.swift` 的 `isExcludedByExportFilter`)保留所有 `@objc` 成员,理由是镜像外能经 runtime 调到它们;hidden 的 direct method 在镜像外调不到,应当被过滤掉。 +- **调用方镜像里的 `-[Class sel]D_thunk` 不是定义**:它是调用方为自己生成的前置检查函数,不能当作「这个镜像里有这个方法」的证据。反过来,调用方镜像里对 `-[Class sel]D` 的未定义引用能说明它跨镜像调用了哪些 direct method。 +- **显式 selector 的判定照旧**:`@objc(renamedSelector) @objcDirect` 的符号里是改过的 selector,`ObjCMemberShape` 用编译器的推导规则比对的做法不需要改。 +- **ObjC ABI diff 要把导出的 `-[Class sel]D` 当作链接期 ABI**:删掉一个 `public` direct method,旧客户端在 dyld 加载时就报找不到符号,而不是运行时报 unrecognized selector。 + +## 什么时候该动手 + +满足任意一条就立提案: + +- 提案进入审查并被接受。 +- Swift 的正式工具链里能用这个功能(不再需要实验开关)。 +- 在真实二进制里见到第一个 direct 符号。检查方法:`nm | grep -E '[-+]\[[^ ]+ [^]]+\]D$'`,加 `(_thunk)?` 可以同时看调用方的 thunk。 + +## 核对记录 + +- 2026-10-09:swift-evolution#3501 open(第二次 pitch,"Awaiting review");swiftlang/swift#91894 open;llvm-project#170616 于 2026-01-05 合入,llvm-project#170618 于 2026-03-30 合入。尚未普查已有的系统二进制里有没有 `-[Class sel]D` 符号。 diff --git a/Documentations/Internal/ObjCChanges/README.md b/Documentations/Internal/ObjCChanges/README.md new file mode 100644 index 000000000..b2b470cde --- /dev/null +++ b/Documentations/Internal/ObjCChanges/README.md @@ -0,0 +1,23 @@ +# ObjC 侧的外部变化(ObjCChanges/) + +本目录跟踪**本仓库之外**发生、会改变二进制里 ObjC 相关事实的变化:Swift Evolution 提案、clang / LLVM 的 ABI 改动、objc4 runtime 的变化、Apple SDK 与系统二进制的新形态。每一篇回答三件事:上游变了什么、编出来的二进制因此长成什么样、我们的读取器(ObjC 成员恢复、`@objc @implementation` 识别、`swift-section objc`)会不会因此崩、读错或漏读。 + +它和相邻目录的分工: + +- `Evolutions/` 记录**我们自己**的改动决策。这里的某条变化要动手支持时,另立一份提案,并从这里链过去。 +- `References/` 是外部资料的译文,讲的是已经稳定的编码规则。这里记录的是还在变动中的东西,状态会随上游推进而更新。 +- `ObjCMemberRecovery.md`、`ObjCImplementationClassRecognition.md` 等实现说明描述我们今天怎么读。这里描述的是「明天可能出现、今天还读不到」的形态。 + +## 写作约定 + +- **一个话题一篇**,PascalCase 文件名。同一件事的 clang 侧和 Swift 侧(例如 direct method 的新 ABI 与 `@objcDirect` 提案)放在同一篇,因为二进制里的痕迹是同一套。 +- **头部固定四个字段**:上游链接、上游状态、最后核对日期、我们的动作(观望 / 已立提案 / 已支持)。上游状态变化时原地更新,并在文末「核对记录」追加一行,不另起新文件。 +- **影响要分级写清**:不受影响、静默漏信息、会读错、会崩。静默漏信息最危险,因为输出看起来完整。 +- **「将来支持时的要点」只写约束,不写方案**。方案属于提案;这里只记下现在就知道、到时候容易忘的坑。 +- 每新增一篇,同批更新下表与 [`Documentations/README.md`](../../README.md) 索引。 + +## 状态总表 + +| 话题 | 上游状态(核对日期) | 对我们的影响 | 我们的动作 | +|---|---|---|---| +| [ObjCDirectMethods.md](ObjCDirectMethods.md):direct method 的新 ABI 与 Swift `@objcDirect` | clang 侧已合入 LLVM 23;Swift 侧是第二次 pitch,未进入审查,实现 PR 未合(2026-10-09) | 静默漏信息:这类方法不在 method list 里,ObjC 成员恢复看不到它们;不崩、不读错 | 观望,未立提案 | diff --git a/Documentations/Internal/ObjCMemberRecovery.md b/Documentations/Internal/ObjCMemberRecovery.md index 4a7ea47f4..39c368b4b 100644 --- a/Documentations/Internal/ObjCMemberRecovery.md +++ b/Documentations/Internal/ObjCMemberRecovery.md @@ -62,6 +62,7 @@ - **模拟器运行时文件里读不全的类(2026-10-08 已修复)**:UIKitCore / Foundation 的 `__objc_classlist` 曾有约三分之一读不出(UIKitCore 5017 项里 791 个 `class_ro_t` 读不到、624 个被误读为元类),`UIView` / `UIResponder` / `UIDocument` 都在其中,链在那里断并标 `(bound; chain not resolvable offline)`,静态布局也排不出它们的 Swift 子类的字段。原因是这些框架用 `-interposable` 链接,导出的类在 classlist、`isa`、`superclass` 里都以「绑定到自己」的 bind 引用(UIKitCore 有 1,586 个这样的 classlist 条目,iOS 16.4 到 26.5 的模拟器都有),而 MachOObjCSection 只解 rebase。修复在 MachOObjCSection 与 MachOKitExtensions(`resolveSelfBind(fileOffset:)`),本库的 `SimulatorRuntimeObjCAncestorLayoutTests` 钉住 iOS 18.5 SwiftUI 的 `PlatformDocument` 排在 `UIDocument` 之后的 `0xc8`。 - **磁盘上的独立二进制**:父类在别的镜像时是 bind,`superclassLocation` 返回 `.unresolvable(name)`;2026-09-21 起这个名字交给镜像的祖先解析器在依赖闭包里找(见下一节),找不到——依赖镜像不在宿主上、iOS 二进制在 macOS 宿主上没给 `--dependency-search-path`、`.unresolvable(nil)`(Swift 类的槽位为零又没有 bind 名)——链才在那里断;祖先的 category 若在闭包够不到的镜像里(闭包报为未解析的依赖),那个 category 的方法看不见,覆写它的成员会被判成显式 selector(fixture 的 `categoryInAnUnreachableImageIsInvisible` 钉住这条边界)。根本没被链接、只在运行时加载的框架也属此列:iOS 模拟器 runtime 的 SwiftUI 不链接私有框架 UIAccessibility,它给 `NSObject` 加的 `UIAccessibilityElementTraversal` 等 category 离线看不见,SwiftUI 里 6 个 `_accessibility…` 成员(如 `_accessibilityIsFirstSibling(for:)` ↔ `_accessibilityIsFirstSiblingForType:`)因此被判成 `@objc(…)`;离线分不出源码是显式写了 selector 还是覆写了头文件里的声明(2026-10-08 祖先链在模拟器腿上走通后才露出来);断了的话同镜像祖先照常判,显式 selector 一律不判。旧的 `LC_DYLD_INFO` bind 格式(部署目标低于 macOS 12 / iOS 16——iOS 15.5 模拟器运行时的全部框架)把 bind 槽位留成 0,MachOObjCSection 曾把它读成「没有父类」,链会被误判为走完、每个 UIKit 覆写都成了显式 selector(第一轮 A/B 的模拟器腿就是这样);本库当时在读取器里补了一道 MachOKitExtensions 的 `resolveBind(fileOffset:)` 取 bind 符号名。2026-10-08 起 MachOObjCSection 自己就按两种格式给名,那道补丁随之删掉;「Swift 类不可能是 ObjC 根类」这道兜底仍在。同一天起,父类在**同一个文件**里、却以 bind 引用自己导出的类时(`-interposable` 链接的文件,iOS 26 及更早模拟器 runtime 的框架都是),MachOObjCSection 直接跟到那个类,返回 `.resolved`;之前它见 bind 就放弃,链在这里退成按名字查([MachOObjCSection 的说明](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/main/Documentations/Internal/SelfBindPointerSlots.md))。fixture 的 `.legacyBinds` 变体固定两种结果:空解析器下断在 `NSObject`,默认解析器下经宿主 cache 走完。 - **strip 后的显式 selector**:只有第一档能给;第二档的 importer 拼法守卫天然拒绝它(见上),第三档只管覆写。 +- **direct method 不在表里**:`objc_direct` 方法没有 method list 条目,三档都轮不到它,包括尚在 pitch 阶段的 Swift `@objcDirect`。上游状态、二进制里的痕迹(`-[Class sel]D` 符号)与将来支持时的约束见 [ObjCChanges/ObjCDirectMethods.md](ObjCChanges/ObjCDirectMethods.md)。 - **仅 ARM64**:第二档的解码器与模块其余部分一样只认 ARM64,x86_64 镜像只有第一、三档。 - **`required` 不还原**:`init?(coder:)` 打成 `override init?(coder:)`,库本来就不还原 `required`。 - **`init` 与 `.cxx_destruct` 也在表里**:编译器给每个 ObjC 派生的 Swift 类合成的 `init` 与指向 ivar destroyer 的 `-.cxx_destruct` 都是方法表条目;前者联结到 allocator 定义(`@objc init()`,默认 selector `init` 不算显式),后者没有对应的成员定义,只在 dump 的符号行上留一条注释。 diff --git a/Documentations/README.md b/Documentations/README.md index 668d4d470..d15f38f28 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -170,5 +170,6 @@ selects names using each access's offset and width. | [EventBasedDegradationReporting.md](Internal/EventBasedDegradationReporting.md) | **降级上报走事件**(提案 0005 的实现说明):库代码不写进程流,落点由宿主装的 `Handler` 决定(GUI → os_log,CLI → stderr);`Dispatcher` 零 handler 时的 os_log 地板与它为何在 dispatcher 而非调用点、`unhandledFailureDescription` 为何是白名单式穷举 switch;四条走不通的近路(`@Loggable` 的 product 与部署下限双重限制 + 泛型类型不可用、`SwiftDeclarationRendering` 因依赖方向够不到事件类型、`Handler` 非 `Sendable` 导致改注入 `Dispatcher`、fd 重定向测试会挂死整轮 `swift test` 故改源码扫描);顺带修掉的 `ConsoleEventHandler` 写 stdout 与 diff 单侧 header 失败删两侧;以及 `FileHandle.write(_:)` 为何会 abort 宿主。 | | [PrivateTypeMemberAttribution.md](Internal/PrivateTypeMemberAttribution.md) | 同名私有类型的成员归属(issue #115 修复说明):成员索引的打印名 key 剥掉了私有判别符、不是单射,「解析单个类型的成员/信息/属性」必须走带 `node:` 的重载;当时踩坑的全部位置(dump 三个 dumper、deinit/destructor、thunk 属性、`typeInfoByName`)、刻意不改 key 格式的理由、fixture 的防优化手段与回归防线。 | | [References/](Internal/References/README.md) | **外部权威资料的中译**(与 `Internal/` 其余文档相反:不描述本库,而是本库赖以成立的外部事实)。目前是 Slava Pestov《Compiling Swift Generics》**全书 24 章中译**,译自 `swift-6.4.0-RELEASE` 的 `docs/Generics/`(Apache License 2.0 with Runtime Library Exception,每篇标明出处/原作者/许可/commit)。书讲「源码怎么编成二进制」,本库做反方向的事,故书里的编码规则即本库的解码依据:generic signature 与 requirement 的 canonical 顺序(Generic Signatures / Building Generic Signatures)、`⊗` 替换代数(Substitution Maps)、conformance 三形态与 witness table(Conformances / Conformance Paths)、existential 容器布局(Existential Types)、`some P` 的完整机制(Opaque Result Types)。译文正文忠于原著,仅在确有对应处以「译注」标出本库落点;该目录 README 是分部索引与阅读约定(术语、两套记法、图的降级、原书笔误的处理)。 | +| [ObjCChanges/](Internal/ObjCChanges/README.md) | **ObjC 侧的外部变化跟踪**:本仓库之外(Swift Evolution、clang / LLVM、objc4、Apple 系统二进制)会改变二进制里 ObjC 事实的变化,每篇记上游状态与核对日期、二进制里的新形态、对 ObjC 成员恢复 / `@implementation` 识别 / `swift-section objc` 的影响分级,以及将来支持时的约束;该目录 README 是状态总表。目前一篇:direct method 的新 ABI(LLVM 23 已合入)与 Swift `@objcDirect`(pitch 阶段),这类方法不在 method list 里,成员恢复会静默漏掉。 | | [TaskReports/](Internal/TaskReports/) | Dated per-task fix / investigation reports. | | [Reviews/](Internal/Reviews/) | Dated code-review records — one file per review event: findings, measurements taken at the time, and the resulting to-do list. Distinct from the topic-organised issue ledgers (e.g. `NodeStoreMigrationOpenIssues.md`), which they cross-reference. | From 643dc019ceca7f3d597d98b3ed980d36778a36d3 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 07:44:04 +0800 Subject: [PATCH 30/49] fix: name function-local types after the function that declares them A type declared in a function or closure sits under a chain of anonymous contexts, which have no name of their own. SymbolicDemangler dropped the chain, so the type read as a member of its outer type and same-named ones merged: SwiftUI's TableDataSource declares seven Visitors, and its interface printed one of them six times. In a private function's body the type borrowed the function's private discriminator and became a private type that does not exist. Its members, whose symbols spell the real name, then matched nothing and were lost. Debug builds went wrong too. - SymbolicDemangler names an anonymous context from the descriptor's own mangled name, the `$sMXX` symbol on the descriptor, or a `_symbolic` symbol naming the type it wraps, in that order. AnonymousContextNameIndex (was AnonymousContextPrivateDiscriminatorIndex) collects the last. A local type's function and closures replace the chain; a private discriminator is read from the wrapped type's own name only. - With none of the three, a local type is named after its anonymous context's address, `Holder.(Visitor in $1a2b3c)`, as the runtime and Remote Mirror do. The new public LocalTypeNaming tells the compiler's name from such a placeholder, whose shape is a private type's. - RuntimeTypeNameDemangling and NodeTypeNaming give runtime names and qualified names the same function context. - The interface prints a local type's short name where a type is referenced, a comment naming its function above its declaration, and the compiler's full name in a conformance's extension header. - ABISnapshotDocument's formatVersion goes from 6 to 7: every local type is keyed by a new name, so an older baseline is rejected rather than reporting each one removed. With the names matching, five whole-tree searches over member nodes found the local type's enclosing declaration first, since a member node's first child is its context: conformance members were bucketed by it and lost to deduplication, a synthesized hash(into:) printed twice in the body, @dynamicMemberLookup went uninferred, unlabeled parameters took their `_:` count from the enclosing function, and a static stored property of a type declared in a getter printed as computed. These now read the member's own node (memberSubtree, accessorKind). LocalTypeFixture compiles local types in five variants, each keeping a different name source, beside twins declared outside any function body. The four new suites and each of the five member fixes failed before the change and pass after it. The full suite passes (2383 tests); see ProjectEvolutionLog section 87 for the system-framework A/B. --- .github/workflows/macOS.yml | 2 +- ....swift => AnonymousContextNameIndex.swift} | 120 +++-- .../SwiftInspection/LocalTypeNaming.swift | 77 +++ .../SwiftInspection/NodeTypeNaming.swift | 21 + ...edCacheEvictionGroup+SwiftInspection.swift | 2 +- .../SwiftInspection/SymbolicDemangler.swift | 262 ++++++++-- .../TypeAttributeInferrer.swift | 15 +- .../Building/DefinitionBuilder.swift | 18 +- .../Building/MemberSymbolBucketing.swift | 2 +- .../TypeDefinition+SynthesizedMembers.swift | 19 +- .../DemanglingNode+AccessorKind.swift | 12 +- .../DemanglingNode+MemberSubtree.swift | 32 ++ .../RuntimeTypeNameDemangling.swift | 77 ++- .../SwiftDiffing/ABISnapshotDocument.swift | 10 +- .../FunctionTypeNodePrintable.swift | 9 +- .../NodePrintables/TypeNodePrintable.swift | 20 +- .../SwiftDeclarationPrinter+Headers.swift | 74 +++ .../SwiftDeclarationPrinter.swift | 12 +- .../LocalTypeFixture.swift | 492 ++++++++++++++++++ .../RuntimeTypeNameLocalTypeTests.swift | 57 ++ ...imeTypeNamePrivateDiscriminatorTests.swift | 2 +- Tests/SwiftDumpTests/LocalTypeDumpTests.swift | 37 ++ .../nestedFunctionsSnapshot.1.txt | 5 +- .../LocalTypeContextNameTests.swift | 183 +++++++ .../SymbolicManglingIndexTests.swift | 28 +- .../LocalTypeInterfaceTests.swift | 275 ++++++++++ .../interfaceSnapshot.1.txt | 3 + 27 files changed, 1729 insertions(+), 137 deletions(-) rename Sources/Analysis/SwiftInspection/{AnonymousContextPrivateDiscriminatorIndex.swift => AnonymousContextNameIndex.swift} (52%) create mode 100644 Sources/Analysis/SwiftInspection/LocalTypeNaming.swift create mode 100644 Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+MemberSubtree.swift create mode 100644 Sources/TestSupport/MachOTestingSupport/LocalTypeFixture.swift create mode 100644 Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift create mode 100644 Tests/SwiftDumpTests/LocalTypeDumpTests.swift create mode 100644 Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift create mode 100644 Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 236ab532a..bf8bc0b52 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift b/Sources/Analysis/SwiftInspection/AnonymousContextNameIndex.swift similarity index 52% rename from Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift rename to Sources/Analysis/SwiftInspection/AnonymousContextNameIndex.swift index ead37925a..eaa12ddf4 100644 --- a/Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift +++ b/Sources/Analysis/SwiftInspection/AnonymousContextNameIndex.swift @@ -5,28 +5,34 @@ import MachOFoundation import MachOSwiftSection @_spi(Internals) import MachOCaches -/// Per-image index of the private discriminators of anonymous contexts, -/// recovered from the image's `_symbolic` symbols. +/// Per-image index of what the image's `_symbolic` symbols record about the +/// types that sit directly in an anonymous context: the private +/// discriminator of an outermost `private` / `fileprivate` type, and the full +/// name of a type declared in a function or closure body. /// -/// The compiler parents every outermost `private` / `fileprivate` type on an -/// anonymous context, and the discriminator the type's name needs is recorded -/// in two places `SymbolicDemangler` reads first: the anonymous context's own -/// mangled name, which the compiler writes only under -/// `-enable-anonymous-context-mangled-names` (a debugger flag, off by -/// default), and a symbol on the anonymous descriptor. An OS framework in the +/// The compiler parents both on an anonymous context of their own — the +/// private type for its unstable identity, the local type for the function or +/// closure, which no descriptor can name — and the name the type needs is +/// recorded in two places `SymbolicDemangler` reads first: the anonymous +/// context's own mangled name, which the compiler writes only under +/// `-enable-anonymous-context-mangled-names` (added to `-g -Onone` builds +/// alone), and a symbol on the anonymous descriptor. An OS framework in the /// dyld shared cache has neither, so its private types demangled as if they /// were internal — `AppKit.FontPanelBIUSPopUpButton` where the Objective-C -/// runtime name says `_TtC6AppKitP33_05EA0EB8E781FFE22747790FC22932B124…`. +/// runtime name says `_TtC6AppKitP33_05EA0EB8E781FFE22747790FC22932B124…` — +/// and its local types as members of the enclosing type +/// (`AppKit.NSWMDeferrableWMWindowTransaction.DeferralState`, declared in +/// `deferCompletionUntil()`; evolution proposal `local-type-context-names`). /// /// What such an image does keep is the symbol the compiler gives every mangled /// name it emits with symbolic references in it /// (`IRGenMangler::mangleSymbolNameForSymbolicMangling`), which spells out the -/// full context mangling of each referent, discriminator included — -/// `SymbolicManglingIndex` pairs those referents with the references they -/// stand for. A type with a field descriptor always has one, since the -/// descriptor's own type name references the type. So for a direct reference -/// to a type descriptor whose parent is an anonymous context, the -/// discriminator of the referent is that anonymous context's. +/// full context mangling of each referent, discriminator and enclosing +/// function included — `SymbolicManglingIndex` pairs those referents with the +/// references they stand for. A type with a field descriptor always has one, +/// since the descriptor's own type name references the type. So for a direct +/// reference to a type descriptor whose parent is an anonymous context, the +/// referent is the name that anonymous context gives the type. /// /// The symbol sits on the mangled name in `__swift5_typeref`, never on either /// descriptor, which is why an offset lookup at the anonymous context cannot @@ -36,9 +42,11 @@ import MachOSwiftSection /// context with neither a mangled name nor a symbol asks for it — and evicted /// with the demangle memo (`SymbolicDemangler.removeCache(for:)`). It keeps /// nothing of `SymbolicManglingIndex`, whose storage goes with the symbol -/// store instead. -package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendable { - package static let shared = AnonymousContextPrivateDiscriminatorIndex() +/// store instead: a private type keeps its discriminator as text, a local +/// type its name as a type mangling, demangled again when asked for — an +/// image has few local types, and each is asked for once per demangling. +package final class AnonymousContextNameIndex: @unchecked Sendable { + package static let shared = AnonymousContextNameIndex() private let cache = SharedCache(evictionGroup: .demangleMemo) @@ -49,8 +57,14 @@ package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendab /// the type it wraps (`_05EA0EB8E781FFE22747790FC22932B1`). let privateDiscriminatorsByAnonymousContextOffset: [Int: String] - init(privateDiscriminatorsByAnonymousContextOffset: [Int: String]) { + /// Anonymous context descriptor offset → the full name of the local + /// type it wraps, as a type mangling with no `$s` prefix + /// (`6AppKit33NSWMDeferrableWMWindowTransactionC20deferCompletionUntilyycyF13DeferralStateL_V`). + let localTypeManglingsByAnonymousContextOffset: [Int: String] + + init(privateDiscriminatorsByAnonymousContextOffset: [Int: String], localTypeManglingsByAnonymousContextOffset: [Int: String]) { self.privateDiscriminatorsByAnonymousContextOffset = privateDiscriminatorsByAnonymousContextOffset + self.localTypeManglingsByAnonymousContextOffset = localTypeManglingsByAnonymousContextOffset } } @@ -74,11 +88,23 @@ package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendab // MARK: - Queries /// The private discriminator of the anonymous context at `offset`, or - /// `nil` when no `_symbolic` symbol references a type directly inside it. + /// `nil` when no `_symbolic` symbol references a private type directly + /// inside it. package func privateDiscriminator(forAnonymousContextAt offset: Int, in machO: some MachORepresentableWithCache) -> String? { storage(in: machO)?.privateDiscriminatorsByAnonymousContextOffset[offset] } + /// The compiler's name of the local type the anonymous context at `offset` + /// wraps — the nominal, `Structure(Function(…), LocalDeclName(…))` — or + /// `nil` when no `_symbolic` symbol references a local type directly + /// inside it. + package func localTypeName(forAnonymousContextAt offset: Int, in machO: some MachORepresentableWithCache) -> Node? { + guard let mangling = storage(in: machO)?.localTypeManglingsByAnonymousContextOffset[offset], + let typeNode = try? demangleAsNodeTransient(mangling, isType: true) + else { return nil } + return Self.nominal(of: typeNode) + } + // MARK: - Build /// A referenced descriptor that sits directly in an anonymous context. @@ -87,11 +113,18 @@ package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendab let name: String } + /// What a referent records for the anonymous context its type sits in. + private enum RecordedName { + case privateDiscriminator(String) + case localTypeMangling(String) + } + /// Only direct references: the indirect form (`0x02`) goes through a /// pointer into another image, whose anonymous contexts are that image's to /// name. private static func build(in machO: some MachOSwiftSectionRepresentableWithCache) -> Storage { var privateDiscriminatorsByAnonymousContextOffset: [Int: String] = [:] + var localTypeManglingsByAnonymousContextOffset: [Int: String] = [:] // Each referenced descriptor is read once. Its referent is not settled // with it: when one reference's referent fails to demangle, the next // reference to the same descriptor is still tried. @@ -109,12 +142,18 @@ package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendab } guard let anonymousContextMember, privateDiscriminatorsByAnonymousContextOffset[anonymousContextMember.anonymousContextOffset] == nil, + localTypeManglingsByAnonymousContextOffset[anonymousContextMember.anonymousContextOffset] == nil, let referentNode = SymbolicManglingIndex.shared.referentNode(of: reference, in: machO), - let privateDiscriminator = privateDiscriminator(ofReferentNode: referentNode, named: anonymousContextMember.name) + let recordedName = recordedName(ofReferentNode: referentNode, named: anonymousContextMember.name) else { continue } - privateDiscriminatorsByAnonymousContextOffset[anonymousContextMember.anonymousContextOffset] = privateDiscriminator + switch recordedName { + case .privateDiscriminator(let privateDiscriminator): + privateDiscriminatorsByAnonymousContextOffset[anonymousContextMember.anonymousContextOffset] = privateDiscriminator + case .localTypeMangling(let localTypeMangling): + localTypeManglingsByAnonymousContextOffset[anonymousContextMember.anonymousContextOffset] = localTypeMangling + } } - return Storage(privateDiscriminatorsByAnonymousContextOffset: privateDiscriminatorsByAnonymousContextOffset) + return Storage(privateDiscriminatorsByAnonymousContextOffset: privateDiscriminatorsByAnonymousContextOffset, localTypeManglingsByAnonymousContextOffset: localTypeManglingsByAnonymousContextOffset) } private static func anonymousContextMember(at offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) -> AnonymousContextMember? { @@ -125,20 +164,31 @@ package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendab return AnonymousContextMember(anonymousContextOffset: anonymousContext.offset, name: name) } - /// The discriminator on the referent's own name, provided that name is the - /// referenced descriptor's — a referent that demangles to anything else is - /// not trusted with the anonymous context. - private static func privateDiscriminator(ofReferentNode referentNode: Node, named expectedName: String) -> String? { - var nominal = referentNode + /// The private discriminator or the local type name on the referent's own + /// name, provided that name is the referenced descriptor's — a referent + /// that demangles to anything else is not trusted with the anonymous + /// context. + private static func recordedName(ofReferentNode referentNode: Node, named expectedName: String) -> RecordedName? { + let nominal = nominal(of: referentNode) + guard nominal.children.count >= 2 else { return nil } + let nameNode = nominal.children[1] + guard nameNode.children.count >= 2, nameNode.children[1].text == expectedName else { return nil } + switch nameNode.kind { + case .privateDeclName: + return nameNode.children[0].text.map { .privateDiscriminator($0) } + case .localDeclName: + let typeNode = Node.createTransient(kind: .type, children: [nominal]) + return (try? mangleAsString(typeNode)).map { .localTypeMangling($0) } + default: + return nil + } + } + + private static func nominal(of node: Node) -> Node { + var nominal = node while nominal.kind == .global || nominal.kind == .type, let child = nominal.children.first { nominal = child } - guard nominal.children.count >= 2 else { return nil } - let nameNode = nominal.children[1] - guard nameNode.kind == .privateDeclName, - nameNode.children.count >= 2, - nameNode.children[1].text == expectedName - else { return nil } - return nameNode.children[0].text + return nominal } } diff --git a/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift b/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift new file mode 100644 index 000000000..51409f164 --- /dev/null +++ b/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift @@ -0,0 +1,77 @@ +@_spi(Internals) import Demangling + +/// How the name of a type declared in a function or closure body says so +/// (evolution proposal `local-type-context-names`). +/// +/// `SymbolicDemangler` gives such a type the compiler's own name when the +/// image keeps a source of it, and a position-based one when it keeps none. +/// A printer reads this to print the type's declared name alone where a type +/// is referenced, since nothing outside the body can spell it; a host reads it +/// to tell a local type from a private one, whose name has the same shape as +/// a position-based one. +public enum LocalTypeNaming: Sendable, Equatable { + /// The compiler's name, `Visitor #1 in Holder.countValues()`: a + /// `localDeclName` under the function or closure that declares the type. + case compilerSpelled + + /// No source the image keeps names the function or closure, so the type + /// is called after the address of the anonymous context wrapping it, + /// under the nearest context the descriptors name: + /// `Holder.(Visitor in $1a2b3c)`. The name has a `privateDeclName`'s + /// shape, but the type is not private and `$1a2b3c` is no discriminator — + /// a compiler-written discriminator never starts with `$`. + case positionBased +} + +extension Node { + /// How this nominal's name marks a local type, or `nil` when it does not + /// name one. A type nested in a local type is not one itself: its own + /// name is a plain identifier under the local type. + public var localTypeNaming: LocalTypeNaming? { + var nominal = self + while wrapsANominal(nominal.kind), let wrapped = nominal.children.first { + nominal = wrapped + } + guard nominal.kind.isAnyGeneric, let declarationName = nominal.children.at(1) else { return nil } + switch declarationName.kind { + case .localDeclName: + return .compilerSpelled + case .privateDeclName: + return declarationName.children.first?.text?.hasPrefix("$") == true ? .positionBased : nil + default: + return nil + } + } +} + +extension NodeReference { + /// ``Node/localTypeNaming``, read from the store without materializing + /// the tree. + public var localTypeNaming: LocalTypeNaming? { + var nominal = self + while wrapsANominal(nominal.kind), let wrapped = nominal.children.first { + nominal = wrapped + } + guard nominal.kind.isAnyGeneric, nominal.children.count >= 2 else { return nil } + let declarationName = nominal.children[1] + switch declarationName.kind { + case .localDeclName: + return .compilerSpelled + case .privateDeclName: + return declarationName.children.first?.text?.hasPrefix("$") == true ? .positionBased : nil + default: + return nil + } + } +} + +/// The kinds a nominal's name sits under: the demangling's root, a type, and +/// a bound generic type, whose first child is the unbound one. +private func wrapsANominal(_ kind: Node.Kind) -> Bool { + switch kind { + case .global, .type, .boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericOtherNominalType: + return true + default: + return false + } +} diff --git a/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift index 902da5409..3725e9e7d 100644 --- a/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift +++ b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift @@ -142,6 +142,14 @@ package enum NodeTypeNaming { private static func qualifiedName(ofNominal node: Node) -> String? { guard let identifier = declaredName(of: node) else { return nil } guard let context = node.firstChild else { return identifier } + if node.children.at(1)?.kind == .localDeclName { + // A type declared in a function or closure body, keyed under that + // function or closure as the compiler spells it — nothing else + // shares it. Under its bare name, which is all the context rules + // below make of it, two methods' same-named types shared one key + // (evolution proposal `local-type-context-names`). + return context.print(using: .interfaceTypeBuilderOnly) + "." + identifier + } if let contextName = contextQualifiedName(of: context) { return contextName + "." + identifier } @@ -159,6 +167,19 @@ package enum NodeTypeNaming { guard let entityTag = nameNode.children.first?.text, let entityName = nameNode.children.at(1)?.text else { return nil } return "related decl '\(entityTag)' for \(entityName)" } + if let nameNode = node.children.at(1), nameNode.kind == .localDeclName { + // `Visitor #1`: two same-named types of one body differ by the + // ordinal alone. + guard let localName = nameNode.children.at(1)?.text, let ordinal = nameNode.children.first?.index else { return nil } + return "\(localName) #\(ordinal + 1)" + } + if let nameNode = node.children.at(1), nameNode.kind == .privateDeclName, + let discriminator = nameNode.children.first?.text, discriminator.hasPrefix("$"), + let localName = nameNode.children.at(1)?.text { + // A local type no source names (`LocalTypeNaming.positionBased`): + // its address is what keeps it apart from the others of its name. + return "(\(localName) in \(discriminator))" + } return node.identifier } diff --git a/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift b/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift index 60cbfdd86..e7142c4fc 100644 --- a/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift +++ b/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift @@ -21,7 +21,7 @@ extension SharedCacheEvictionGroup { /// it has resolved them; same lifetime, follows `symbolStore`. package static let objcAncestorResolver = SharedCacheEvictionGroup("objcAncestorResolver") - /// `SymbolicDemanglerCache` and `AnonymousContextPrivateDiscriminatorIndex`: + /// `SymbolicDemanglerCache` and `AnonymousContextNameIndex`: /// the memo's values are references into the interned arena, so the /// group follows `internedNames`. package static let demangleMemo = SharedCacheEvictionGroup("demangleMemo") diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index df1477158..a2c7bd3a6 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -64,7 +64,7 @@ extension SymbolicDemangler { /// would keep the dropped store's buffers alive. public static func removeCache(for machO: some MachOSwiftSectionRepresentableWithCache) { // The memo and the per-image state the same demanglings read - // (`AnonymousContextPrivateDiscriminatorIndex`) share the group. + // (`AnonymousContextNameIndex`) share the group. SharedCacheRegistry.shared.evict(groups: [.demangleMemo], for: SharedCacheKey(machO)) } @@ -84,32 +84,76 @@ extension SymbolicDemangler { // MARK: - Symbol Lookup Protocol +/// The lookups that name an anonymous context beyond what its descriptor +/// says (evolution proposal `local-type-context-names`). +/// +/// An anonymous context stands for something the descriptors cannot name: a +/// function, a closure, or the type a function body or a `private` / +/// `fileprivate` declaration wraps in one of its own. Its name — the +/// compiler's mangling of that thing (`IRGenMangler::mangleAnonymousDescriptorName`) +/// — is written into the descriptor only under +/// `-enable-anonymous-context-mangled-names`, which the driver adds to +/// `-g -Onone` builds alone; these are the places a release build still +/// keeps it. private protocol SymbolLookupContext { func lookupSymbol(at offset: Int) -> Symbol? - /// The private discriminator of the anonymous context at `offset`, as the - /// image's `_symbolic` symbols record it - /// (`AnonymousContextPrivateDiscriminatorIndex`). + /// The private discriminator of the type the anonymous context at + /// `offset` wraps, as the image's `_symbolic` symbols record it + /// (`AnonymousContextNameIndex`). func symbolicReferencePrivateDiscriminator(forAnonymousContextAt offset: Int) -> String? + /// The compiler's full name of the local type the anonymous context at + /// `offset` wraps, as the image's `_symbolic` symbols record it + /// (`AnonymousContextNameIndex`). + func symbolicReferenceLocalTypeName(forAnonymousContextAt offset: Int) -> Node? + + /// The compiler's name for what the anonymous context at `offset` stands + /// for, short of the descriptor's own name. A requirement so that a + /// context can memoize it; the default resolves it every time. + func anonymousContextName(forAnonymousContextAt offset: Int) -> Node? + /// The discriminator of the private type inside the anonymous context at /// `offset`, as the identifier a `privateDeclName` takes. A requirement /// so that a context can memoize it; the default resolves it every time. func privateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? + + /// `$
`: the anonymous context at `offset` spelled by its address + /// in the image's own address space — what a local type whose context no + /// symbol names is called after (`SymbolicDemangler.positionNameOfUnnamedLocalType`). + func positionName(forAnonymousContextAt offset: Int) -> String? } extension SymbolLookupContext { + func anonymousContextName(forAnonymousContextAt offset: Int) -> Node? { + resolvedAnonymousContextName(forAnonymousContextAt: offset) + } + func privateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? { resolvedPrivateDiscriminatorIdentifier(forAnonymousContextAt: offset) } - /// From a symbol on the anonymous descriptor when the image kept one, - /// otherwise from a `_symbolic` symbol naming the type inside, which an OS - /// framework in the dyld shared cache still carries when the other is - /// gone. + /// From the descriptor's `$sMXX` symbol when the image kept its + /// local symbols (`IRGenMangler::mangleAnonymousDescriptor`); otherwise, + /// for the context a local type hangs off, from a `_symbolic` symbol + /// naming that type, which an OS framework in the dyld shared cache still + /// carries when the other is gone. + func resolvedAnonymousContextName(forAnonymousContextAt offset: Int) -> Node? { + if let symbol = lookupSymbol(at: offset), let name = SymbolicDemangler.anonymousContextName(ofDescriptorSymbolNamed: symbol.name) { + return name + } + return symbolicReferenceLocalTypeName(forAnonymousContextAt: offset) + } + + /// The discriminator on the name of the private type the context wraps, + /// and on nothing else. The first `privateDeclName` anywhere in the + /// context's name, which this used to take, is an enclosing private + /// function's whenever the context stands for that function, a closure in + /// it, or a type declared in its body: hung on the context and then on the + /// type, it faked a private type that does not exist. func resolvedPrivateDiscriminatorIdentifier(forAnonymousContextAt offset: Int) -> Node? { - if let symbol = lookupSymbol(at: offset), let privateDeclName = try? symbol.demangledNode.first(of: Node.Kind.privateDeclName) { - return privateDeclName.children.first + if let name = anonymousContextName(forAnonymousContextAt: offset), let discriminator = SymbolicDemangler.privateDiscriminatorIdentifier(ofPrivateTypeNamed: name) { + return discriminator } guard let privateDiscriminator = symbolicReferencePrivateDiscriminator(forAnonymousContextAt: offset) else { return nil } return .createTransient(kind: .identifier, text: privateDiscriminator) @@ -122,7 +166,18 @@ extension MachOContext: SymbolLookupContext { } func symbolicReferencePrivateDiscriminator(forAnonymousContextAt offset: Int) -> String? { - AnonymousContextPrivateDiscriminatorIndex.shared.privateDiscriminator(forAnonymousContextAt: offset, in: machO) + AnonymousContextNameIndex.shared.privateDiscriminator(forAnonymousContextAt: offset, in: machO) + } + + func symbolicReferenceLocalTypeName(forAnonymousContextAt offset: Int) -> Node? { + AnonymousContextNameIndex.shared.localTypeName(forAnonymousContextAt: offset, in: machO) + } + + /// The address the dump's member address comments print too: unslid for + /// an image in a dyld shared cache, the file's own otherwise — so a file + /// and the same image loaded in-process agree. + func positionName(forAnonymousContextAt offset: Int) -> String? { + SymbolicDemangler.positionName(ofAddress: machO.address(forOffset: offset)) } } @@ -137,7 +192,21 @@ extension InProcessContext: SymbolLookupContext { /// per image and keyed from the image's header. func symbolicReferencePrivateDiscriminator(forAnonymousContextAt offset: Int) -> String? { guard let pointer = UnsafeRawPointer(bitPattern: offset), let machOImage = MachOImage.image(for: pointer) else { return nil } - return AnonymousContextPrivateDiscriminatorIndex.shared.privateDiscriminator(forAnonymousContextAt: offset - machOImage.ptr.bitPattern.int, in: machOImage) + return AnonymousContextNameIndex.shared.privateDiscriminator(forAnonymousContextAt: offset - machOImage.ptr.bitPattern.int, in: machOImage) + } + + func symbolicReferenceLocalTypeName(forAnonymousContextAt offset: Int) -> Node? { + guard let pointer = UnsafeRawPointer(bitPattern: offset), let machOImage = MachOImage.image(for: pointer) else { return nil } + return AnonymousContextNameIndex.shared.localTypeName(forAnonymousContextAt: offset - machOImage.ptr.bitPattern.int, in: machOImage) + } + + /// Memoized per address for the process, like the discriminator below: + /// the runtime spells every anonymous context of a name by its address, + /// and resolving one scans the owning image's symbol table. + func anonymousContextName(forAnonymousContextAt offset: Int) -> Node? { + SymbolicDemanglerCache.shared.anonymousContextName(forAnonymousContextAt: offset, in: self) { + resolvedAnonymousContextName(forAnonymousContextAt: offset) + } } /// Memoized per address for the process (evolution proposal @@ -151,6 +220,13 @@ extension InProcessContext: SymbolLookupContext { resolvedPrivateDiscriminatorIdentifier(forAnonymousContextAt: offset) } } + + /// The image-relative address `MachOContext` spells for the same + /// descriptor read from the image or its file. + func positionName(forAnonymousContextAt offset: Int) -> String? { + guard let pointer = UnsafeRawPointer(bitPattern: offset), let machOImage = MachOImage.image(for: pointer) else { return nil } + return SymbolicDemangler.positionName(ofAddress: machOImage.address(forOffset: offset - machOImage.ptr.bitPattern.int)) + } } extension SymbolicDemangler { @@ -162,6 +238,54 @@ extension SymbolicDemangler { package static func privateDiscriminator(forAnonymousContextAt address: UnsafeRawPointer) -> String? { InProcessContext.shared.privateDiscriminatorIdentifier(forAnonymousContextAt: address.bitPattern.int)?.text } + + /// The compiler's name for what the anonymous context at `address` in + /// this process stands for — the function, the closure, or the type it + /// wraps (`Visitor #1 in Holder.countValues()`): from the descriptor's own + /// name when it carries one, else as `anonymousContextName(of:in:)` finds + /// it. `RuntimeTypeNameDemangling` names a runtime name's anonymous + /// contexts through this. + package static func anonymousContextName(forAnonymousContextAt address: UnsafeRawPointer) -> Node? { + guard let descriptor = try? ContextDescriptorWrapper.resolve(at: address, in: InProcessContext.shared), + case .anonymous(let anonymousContext) = descriptor + else { return nil } + return try? anonymousContextName(of: anonymousContext, in: InProcessContext.shared) + } + + /// `$
` for the anonymous context at `address` in this process — + /// the same text a descriptor-built name spells for it. + package static func positionName(forAnonymousContextAt address: UnsafeRawPointer) -> String? { + InProcessContext.shared.positionName(forAnonymousContextAt: address.bitPattern.int) + } + + /// `$`, the spelling the runtime gives an anonymous + /// context it knows nothing about (`_buildDemanglingForContext`, + /// `stdlib/public/runtime/Demangle.cpp`). + static func positionName(ofAddress address: UInt64) -> String { + "$" + String(address, radix: 16) + } + + /// What `$sMXX` names: the anonymous descriptor's context, the + /// tree its own mangled name would demangle to. `nil` for a symbol that + /// names no anonymous descriptor — a lookup by address may come back with + /// whatever else sits there. + static func anonymousContextName(ofDescriptorSymbolNamed symbolName: String) -> Node? { + guard symbolName.hasSuffix("MXX"), let symbolNode = try? demangleAsNodeTransient(symbolName) else { return nil } + let anonymousDescriptor = symbolNode.kind == .global ? symbolNode.children.first : symbolNode + guard let anonymousDescriptor, anonymousDescriptor.kind == .anonymousDescriptor else { return nil } + return anonymousDescriptor.children.first + } + + /// The discriminator of a private type, read from its own name + /// (`Structure(, PrivateDeclName(, ))`); + /// `nil` for any other name, a function's included. + static func privateDiscriminatorIdentifier(ofPrivateTypeNamed name: Node) -> Node? { + guard name.kind.isAnyGeneric, + let declarationName = name.children.at(1), declarationName.kind == .privateDeclName, + let discriminator = declarationName.children.first, discriminator.kind == .identifier + else { return nil } + return discriminator + } } // MARK: - ReadingContext Support @@ -431,7 +555,15 @@ extension SymbolicDemangler { var nameNode = try adoptAnonymousContextName(context: context, parentContextRef: &parentDescriptorResult, outSymbol: &demangledParentNode, in: readingContext) var parentDemangling: Node? - if let parentDescriptor = parentDescriptorResult { + if let demangledParentNode, isAnonymousContext(parentDescriptorResult) { + // A local type: the adopted name's context — the closure, the + // function — stands for the whole chain of anonymous contexts + // above, which no descriptor names (evolution proposal + // `local-type-context-names`). Building that chain instead lost + // the function whenever it was not private: an anonymous context + // with no discriminator demangles as its own parent. + parentDemangling = demangledParentNode + } else if let parentDescriptor = parentDescriptorResult { parentDemangling = try buildContextDescriptorMangling(context: parentDescriptor, recursionLimit: recursionLimit - 1, instantiation: instantiation, in: readingContext) if parentDemangling == nil, demangledParentNode == nil { return nil @@ -488,8 +620,11 @@ extension SymbolicDemangler { return Node.createTransient(kind: .extension, children: [parentDemangling, demangledExtendedContext]) } case .anonymous: - // With no discriminator on record the context is skipped, and the - // type inside demangles as if it were internal. + // Reached when nothing below took the context's name: a context + // standing for a function or a closure, or one no source names. + // It contributes a discriminator only when it wraps a private + // type; otherwise it is skipped, and a type inside demangles as if + // it were internal. if let lookupContext = readingContext as? SymbolLookupContext, let privateDeclNameIdentifier = lookupContext.privateDiscriminatorIdentifier(forAnonymousContextAt: context.contextDescriptor.offset) { if let parentDemangling { @@ -507,14 +642,17 @@ extension SymbolicDemangler { return try .createTransient(kind: .module, text: moduleContext.name(in: readingContext)) case .opaqueType: guard let parentDescriptorResult else { return nil } - if parentDemangling?.kind == .anonymousContext { - guard var mangledNode = try demangleAnonymousContextName(context: parentDescriptorResult, in: readingContext) else { + if case .element(.anonymous(let anonymousContext)) = parentDescriptorResult { + // A generic function's opaque result type hangs off the + // function's anonymous context, whose name is the function. + // Decided from the descriptor, not from the parent's + // demangling: an anonymous context with no discriminator + // demangles as its own parent, which left every function that + // is not private without its opaque type's name. + guard let functionNode = try anonymousContextName(of: anonymousContext, in: readingContext) else { return nil } - if mangledNode.kind == .global { - mangledNode = mangledNode.children[0] - } - let opaqueNode = Node.createTransient(kind: .opaqueReturnTypeOf, children: [mangledNode]) + let opaqueNode = Node.createTransient(kind: .opaqueReturnTypeOf, children: [functionNode]) return opaqueNode } else if let parentDemangling, parentDemangling.kind == .module { let opaqueNode = Node.createTransient(kind: .opaqueReturnTypeOf, children: [parentDemangling]) @@ -532,6 +670,14 @@ extension SymbolicDemangler { } nameNode = Node.createTransient(kind: .privateDeclName, children: [parentDemangling.children[0], nameNode]) parentDemangling = parentDemangling.children[1] + } else if demangledParentNode == nil, nameNode.kind == .identifier, let positionName = try positionNameOfUnnamedLocalType(inside: parentDescriptorResult, in: readingContext) { + // A local type no source names: spelled by the address of the + // anonymous context wrapping it, under the nearest context the + // descriptors name (the anonymous contexts between demangled as + // their parents) — the runtime's and Remote Mirror's convention + // (`MetadataReader::buildContextDescriptorMangling`). Two methods' + // same-named local types would otherwise share one name. + nameNode = Node.createTransient(kind: .privateDeclName, children: [.createTransient(kind: .identifier, text: positionName), nameNode]) } let demangling = Node.createTransient(kind: kind, children: [parentDemangling, nameNode]) @@ -541,16 +687,19 @@ extension SymbolicDemangler { return demangling } + /// The name the anonymous context `parentContextRef` gives the type or + /// protocol `context` it wraps — a `localDeclName` for a type declared in + /// a function or closure body, a `privateDeclName` for an outermost + /// private one — the remote mirror's `adoptAnonymousContextName` + /// (`include/swift/Remote/MetadataReader.h`). On success + /// `parentContextRef` moves past the anonymous context and `outSymbol` + /// holds the name's own context: the enclosing function or closure, or + /// the module, type or extension a private type sits in. private static func adoptAnonymousContextName(context: ContextDescriptorWrapper, parentContextRef: inout SymbolOrElement?, outSymbol: inout Node?, in readingContext: some ReadingContext) throws -> Node? { outSymbol = nil - guard let parentContextLocalRef = parentContextRef else { return nil } - guard case .element(let parentContext) = parentContextRef else { return nil } guard context.isType || context.isProtocol else { return nil } - guard var mangledNode = try demangleAnonymousContextName(context: parentContextLocalRef, in: readingContext) else { return nil } - if mangledNode.kind == .global { - mangledNode = mangledNode.children[0] - } - guard mangledNode.children.count >= 2 else { return nil } + guard case .element(.anonymous(let anonymousContext))? = parentContextRef else { return nil } + guard let mangledNode = try anonymousContextName(of: anonymousContext, in: readingContext), mangledNode.children.count >= 2 else { return nil } let nameChild = mangledNode.children[1] @@ -563,16 +712,45 @@ extension SymbolicDemangler { guard let namedContext = context.namedContextDescriptor else { return nil } guard try namedContext.name(in: readingContext) == identifierNode.text else { return nil } - parentContextRef = try parentContext.parent(in: readingContext) + parentContextRef = try anonymousContext.parent(in: readingContext) outSymbol = mangledNode.children[0] return nameChild } - private static func demangleAnonymousContextName(context: SymbolOrElement, in readingContext: some ReadingContext) throws -> Node? { - guard case .element(.anonymous(let context)) = context, let mangledName = try context.mangledName(in: readingContext) else { return nil } - return try demangle(for: mangledName, kind: .symbol, in: readingContext) + /// The compiler's name for what `anonymousContext` stands for — a + /// function, a closure, the type it wraps — from, in order: the + /// descriptor's own mangled name, which the compiler writes only under + /// `-enable-anonymous-context-mangled-names` (the driver adds it to + /// `-g -Onone` builds alone), then what the image keeps elsewhere + /// (`SymbolLookupContext.anonymousContextName(forAnonymousContextAt:)`). + private static func anonymousContextName(of anonymousContext: AnonymousContextDescriptor, in readingContext: some ReadingContext) throws -> Node? { + if let mangledName = try anonymousContext.mangledName(in: readingContext) { + let symbolNode = try demangle(for: mangledName, kind: .symbol, in: readingContext) + return symbolNode.kind == .global ? symbolNode.children.first : symbolNode + } + guard let lookupContext = readingContext as? SymbolLookupContext else { return nil } + return lookupContext.anonymousContextName(forAnonymousContextAt: anonymousContext.offset) + } + + private static func isAnonymousContext(_ context: SymbolOrElement?) -> Bool { + if case .element(.anonymous)? = context { + return true + } + return false + } + + /// `$
` of the anonymous context `parent` when it wraps a local + /// type — when its own parent is an anonymous context too, a function's + /// or a closure's; an outermost private type's wrapper sits directly in a + /// module, a type or an extension. + private static func positionNameOfUnnamedLocalType(inside parent: SymbolOrElement?, in readingContext: some ReadingContext) throws -> String? { + guard case .element(.anonymous(let anonymousContext))? = parent, + isAnonymousContext(try anonymousContext.parent(in: readingContext)), + let lookupContext = readingContext as? SymbolLookupContext + else { return nil } + return lookupContext.positionName(forAnonymousContextAt: anonymousContext.offset) } private static func readProtocol(offset: Int, pointer: RelativeProtocolDescriptorPointer, in context: some ReadingContext) throws -> Node? { @@ -943,6 +1121,12 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { /// process-scoped storage fills it. @Mutex fileprivate var privateDiscriminatorForAnonymousContextAddress: [Int: String?] = [:] + + /// The compiler's name for what the anonymous context at an in-process + /// address stands for; a stored `nil` records that nothing names it. + /// Only the process-scoped storage fills it. + @Mutex + fileprivate var anonymousContextNameForAnonymousContextAddress: [Int: NodeReference?] = [:] } /// The memo `context` files entries under, as its cache scope declares: @@ -985,6 +1169,20 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { return resolvedIdentifier } + /// `InProcessContext`'s anonymous context name lookup, memoized as an + /// interned reference; a hit materializes a fresh tree. + fileprivate func anonymousContextName(forAnonymousContextAt address: Int, in context: InProcessContext, resolving resolve: () -> Node?) -> Node? { + let storage = Self.processScopedStorage + if let memoizedName = storage.anonymousContextNameForAnonymousContextAddress[address] { + return memoizedName?.materialize() + } + let resolvedName = resolve() + // `updateValue`: a plain subscript assignment of a nil verdict would + // remove the key instead of recording "nothing names it". + storage.anonymousContextNameForAnonymousContextAddress.updateValue(resolvedName.map { InternedNodeReferenceCache.shared.reference(interning: $0, in: context) }, forKey: address) + return resolvedName + } + fileprivate func remove(for machO: some MachORepresentableWithCache) { cache.remove(for: machO) } diff --git a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift index 1d09ef6fb..39488eea1 100644 --- a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift +++ b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift @@ -66,16 +66,19 @@ public struct TypeAttributeInferrer: Sendable { /// Checks whether the type has a `subscript(dynamicMember:)`, /// which is the characteristic subscript of a `@dynamicMemberLookup` type. /// - /// Detection performs a recursive preorder search of the subscript's demangled node tree - /// for a `.labelList` node whose first child has `.text == "dynamicMember"`. - /// The node tree is `global → getter → subscript → [context, labelList, type]`, - /// so a recursive search is needed since `.labelList` is not a direct child of the root. + /// Detection looks for a subscript whose own `.labelList` has a first child with + /// `.text == "dynamicMember"`. The node tree is + /// `global → getter → subscript → [context, labelList, type]`: a preorder search finds + /// the subscript node ahead of its context, and the label list is its direct child. + /// Searching the whole tree for the label list reached the context first — a local + /// type's context is the function declaring it, whose labels then stood in for the + /// subscript's (evolution proposal `local-type-context-names`). static func hasDynamicMemberSubscript(subscripts: [SubscriptDefinition], staticSubscripts: [SubscriptDefinition]) -> Bool { let allSubscripts = subscripts + staticSubscripts return allSubscripts.contains { subscriptDefinition in - // Use Node's preorder traversal (recursive) instead of .children (direct only) subscriptDefinition.node - .first(of: .labelList)? + .first(of: .subscript)? + .children.first(of: .labelList)? .children.first?.text == "dynamicMember" } } diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift index 8d912cc6e..381450b79 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift @@ -40,9 +40,10 @@ package enum DefinitionBuilder { var variables: [VariableDefinition] = [] var accessorsByName: [String: [Accessor]] = [:] for memberSymbol in memberSymbols { - guard let variableNode = memberSymbol.demangledNode.first(of: .variable) else { continue } + let memberSubtree = memberSymbol.demangledNode.memberSubtree + guard let variableNode = memberSubtree.first(of: .variable) else { continue } guard let name = variableNode.identifier else { continue } - let kind = memberSymbol.accessorKind + let kind = memberSubtree.accessorKind let node = memberSymbol.demangledNode let symbolOffset = memberSymbol.offset let (descriptor, vtableOffset) = dispatchLookups.dispatch(forMemberNode: node, implementationOffset: symbolOffset) @@ -56,7 +57,7 @@ package enum DefinitionBuilder { continue } let nodes = accessors.map(\.symbol.demangledNode) - guard let node = nodes.first(where: { $0.contains(.getter) || !$0.hasAccessor }) else { continue } + guard let node = nodes.first(where: { $0.memberSubtree.contains(.getter) || !$0.memberSubtree.hasAccessor }) else { continue } var variableDefinition = VariableDefinition(node: node, name: name, accessors: accessors, isGlobalOrStatic: isGlobalOrStatic) if accessors.contains(where: { $0.methodDescriptor?.method?.layout.flags.isDynamic ?? false }) { variableDefinition.attributes.append(.dynamic) @@ -87,8 +88,9 @@ package enum DefinitionBuilder { // the `contains(.getter)` test below and the accessor disappears. var accessorsByNode: OrderedDictionary = [:] for memberSymbol in memberSymbols { - guard let subscriptNode = memberSymbol.demangledNode.first(of: .subscript).map(StructuralNodeReferenceKey.init) else { continue } - let kind = memberSymbol.accessorKind + let memberSubtree = memberSymbol.demangledNode.memberSubtree + guard let subscriptNode = memberSubtree.first(of: .subscript).map(StructuralNodeReferenceKey.init) else { continue } + let kind = memberSubtree.accessorKind let node = memberSymbol.demangledNode let symbolOffset = memberSymbol.offset let (descriptor, vtableOffset) = dispatchLookups.dispatch(forMemberNode: node, implementationOffset: symbolOffset) @@ -97,7 +99,7 @@ package enum DefinitionBuilder { for (_, accessors) in accessorsByNode { let nodes = accessors.map(\.symbol.demangledNode) - guard let node = nodes.first(where: { $0.contains(.getter) }) else { continue } + guard let node = nodes.first(where: { $0.memberSubtree.contains(.getter) }) else { continue } var subscriptDefinition = SubscriptDefinition(node: node, accessors: accessors, isStatic: isStatic) if accessors.contains(where: { $0.methodDescriptor?.method?.layout.flags.isDynamic ?? false }) { subscriptDefinition.attributes.append(.dynamic) @@ -122,7 +124,7 @@ package enum DefinitionBuilder { var pendingMergedByAllocatorNode: OrderedDictionary = [:] var allocators: [FunctionDefinition] = [] for memberSymbol in memberSymbols { - guard let allocatorNode = memberSymbol.demangledNode.first(of: .allocator).map(StructuralNodeReferenceKey.init) else { continue } + guard let allocatorNode = memberSymbol.demangledNode.memberSubtree.first(of: .allocator).map(StructuralNodeReferenceKey.init) else { continue } let isMergedThunk = memberSymbol.demangledNode.children.first?.kind == .mergedFunction if isMergedThunk { if canonicalIndexByAllocatorNode[allocatorNode] == nil, pendingMergedByAllocatorNode[allocatorNode] == nil { @@ -172,7 +174,7 @@ package enum DefinitionBuilder { var pendingMergedByFunctionNode: OrderedDictionary = [:] var functions: [FunctionDefinition] = [] for memberSymbol in memberSymbols { - guard let functionNode = memberSymbol.demangledNode.first(of: .function).map(StructuralNodeReferenceKey.init), let name = functionNode.reference.identifier else { continue } + guard let functionNode = memberSymbol.demangledNode.memberSubtree.first(of: .function).map(StructuralNodeReferenceKey.init), let name = functionNode.reference.identifier else { continue } let isMergedThunk = memberSymbol.demangledNode.children.first?.kind == .mergedFunction if isMergedThunk { if canonicalIndexByFunctionNode[functionNode] == nil, pendingMergedByFunctionNode[functionNode] == nil { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift index 0e3eb7685..fc9e0d86c 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift @@ -3,7 +3,7 @@ import OrderedCollections extension Definition { func addSymbol(_ symbol: MemberSymbol, memberSymbolsByKind: inout OrderedDictionary, inExtension: Bool) { - let node = symbol.demangledNode + let node = symbol.demangledNode.memberSubtree if node.contains(.variable) { if node.contains(.static) { if node.isStoredVariable { diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift index b7ddef4d9..b6321eda0 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift @@ -35,12 +35,21 @@ extension TypeDefinition { // Returns the argument label list of a member as an array of strings, // with "_" for unnamed parameters. Works on function / constructor / - // allocator / getter nodes; returns an empty array if no labelList - // node exists (which means the function either takes no parameters - // or takes exclusively unnamed parameters — the demangler does not - // always emit an explicit labelList for the all-unnamed case). + // allocator nodes; returns an empty array if no labelList node exists + // (which means the function either takes no parameters or takes + // exclusively unnamed parameters — the demangler does not always emit + // an explicit labelList for the all-unnamed case). + // + // The member's OWN label list, a child of its declaration: the + // declaration's first child is its context, which a whole-tree search + // reached first. A local type's context is the function declaring it, + // so `encode(to:)`'s labels stood in for its `Key`'s `hash(into:)`, + // and the synthesized member stayed in the body (evolution proposal + // `local-type-context-names`). func labels(of node: NodeReference) -> [String] { - guard let list = node.first(of: .labelList) else { return [] } + guard let declarationNode = node.first(of: .function, .allocator, .constructor), + let list = declarationNode.children.first(of: .labelList) + else { return [] } return list.children.map { child in if child.kind == .firstElementMarker { return "_" } return child.text ?? "_" diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift index 3c84cb72b..3ec37a4db 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift @@ -1,7 +1,17 @@ import Demangling extension DemanglingNode where Self: Sequence { + /// The accessor this member symbol is; `.none` for a property's storage, + /// or for anything else that is no accessor. + /// + /// The search stops at the first accessor OR declaration in preorder: a + /// member's own accessor comes before its `variable` / `subscript`, and + /// the declaration's context comes after it. A local type's context can + /// hold an accessor of its own — the getter declaring the type — which a + /// search for accessors alone found for a static stored property's + /// storage symbol, and the property printed as a computed one (evolution + /// proposal `local-type-context-names`). package var accessorKind: AccessorKind { - guard let node = first(of: .getter, .setter, .modifyAccessor, .readAccessor) else { return .none } + guard let node = first(of: .getter, .setter, .modifyAccessor, .readAccessor, .variable, .subscript) else { return .none } switch node.kind { case .getter: return .getter case .setter: return .setter diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+MemberSubtree.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+MemberSubtree.swift new file mode 100644 index 000000000..33349bf3d --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+MemberSubtree.swift @@ -0,0 +1,32 @@ +import Demangling + +extension DemanglingNode { + /// The part of a member symbol's tree the member builders read the member + /// from: a protocol witness's requirement, without the conformance the + /// witness is filed under; the whole tree for any other symbol. + /// + /// A witness names its conformance first (`protocol witness for + /// Swift.Hashable.hash(into:) in conformance Key #1 in + /// Holder.keyFromGetter.getter : Any`), so a kind-scoped search of the + /// whole tree — `contains(_:)`, `first(of:)` — reaches the conforming + /// type before the requirement. A local type's name carries its enclosing + /// declaration: a getter's variable, a method's `static`, the function + /// itself. Searched whole, every witness of a type declared in a getter + /// read as a property named after the getter, a type declared in a + /// `static` method lent its witnesses `static`, and the method witnesses + /// of one conformance all keyed as the enclosing function, which kept one + /// of them (evolution proposal `local-type-context-names`). + package var memberSubtree: Self { + guard let protocolWitness, let requirement = protocolWitness.children.at(1) else { return self } + return requirement + } + + /// The protocol witness this tree is, or the one under its `global` root. + private var protocolWitness: Self? { + if kind == .protocolWitness { + return self + } + guard kind == .global else { return nil } + return children.first { $0.kind == .protocolWitness } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift index df066eabd..0e86931c7 100644 --- a/Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift +++ b/Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift @@ -10,9 +10,11 @@ /// `AnonymousContext("$
", , TypeList())`, "an unstable /// mangling ... by its pointer identity" (`stdlib/public/runtime/Demangle.cpp`, /// `_buildDemanglingForContext`). The compiler parents every outermost -/// `private` / `fileprivate` type on such a context, so every private type -/// reaches us that way: as the specialized definition itself, as one of its -/// type arguments, or anywhere inside a field's type. +/// `private` / `fileprivate` type on such a context, and every type declared +/// in a function or closure body on a chain of them (the type's own, one per +/// closure, the function's), so every private and local type reaches us that +/// way: as the specialized definition itself, as one of its type arguments, +/// or anywhere inside a field's type. /// /// That address names nothing a reader can use. The interface printer has no /// spelling for it and printed nothing — the separator after it dangled in @@ -20,12 +22,15 @@ /// private type lost its module and every enclosing type — while the stock /// printer rendered it as `(unknown context at $…)`. So each anonymous context /// is rewritten into what the name built from the descriptors carries -/// (`SymbolicDemangler.buildContextDescriptorMangling`): the private type -/// inside gets a `privateDeclName` when the image records the discriminator — -/// a symbol on the anonymous descriptor, or a `_symbolic` symbol naming the -/// type, which is what survives in the dyld shared cache -/// (`AnonymousContextPrivateDiscriminatorIndex`) — and the context is replaced -/// by its parent when it records nothing. +/// (`SymbolicDemangler.buildContextDescriptorMangling`), from the same sources +/// (evolution proposal `local-type-context-names`): the compiler's own name +/// for the type inside, which carries a local type's function and closure and +/// a private type's discriminator; a discriminator alone, which is all an OS +/// framework in the dyld shared cache records for a private type +/// (`AnonymousContextNameIndex`); and, for a local type nothing names, the +/// position-based name `(Name in $
)`. A private type the image +/// records nothing for loses the context, and demangles as if it were +/// internal. package enum RuntimeTypeNameDemangling { /// The runtime's name for `metatype`, with every anonymous context /// rewritten as described on the type. `nil` on runtimes that predate @@ -56,8 +61,8 @@ package enum RuntimeTypeNameDemangling { // `AnonymousContext` children: the address identifier, the parent // context, and an always-empty generic argument list — the runtime // gives an anonymous context no arguments of its own. - if let privateTypeNode = privateTypeNode(renaming: node, rewrittenNodes: &rewrittenNodes) { - rewrittenNode = privateTypeNode + if let namedTypeNode = typeNode(renaming: node, rewrittenNodes: &rewrittenNodes) { + rewrittenNode = namedTypeNode } else if node.kind == .anonymousContext, let parent = node.children.at(1) { rewrittenNode = rewritingAnonymousContexts(in: parent, rewrittenNodes: &rewrittenNodes) } else { @@ -79,11 +84,18 @@ package enum RuntimeTypeNameDemangling { } /// `Type(AnonymousContext("$
", parent, …), Identifier(name), …)` - /// → `Type(parent, PrivateDeclName(Identifier(discriminator), Identifier(name)), …)` - /// when this process's image records the discriminator of the anonymous - /// context at that address; `nil` otherwise, leaving the node to the - /// parent-only rewrite. - private static func privateTypeNode(renaming node: Node, rewrittenNodes: inout [ObjectIdentifier: Node]) -> Node? { + /// renamed the way the descriptors name the type, or `nil` when nothing + /// names it, leaving the node to the parent-only rewrite: + /// + /// - the compiler's name for the type: a local type's + /// (`Visitor #1 in Holder.countValues()`), whose function or closure + /// stands in for every anonymous context above, or a private type's, put + /// under the runtime's own parent, which carries the arguments of a bound + /// enclosing type; + /// - a private discriminator alone; + /// - for a local type — an anonymous context whose parent is one too — + /// `(name in $
)` under the nearest context the runtime names. + private static func typeNode(renaming node: Node, rewrittenNodes: inout [ObjectIdentifier: Node]) -> Node? { guard node.children.count >= 2, let anonymousContext = node.children.first, anonymousContext.kind == .anonymousContext, @@ -93,13 +105,34 @@ package enum RuntimeTypeNameDemangling { let address = UInt(addressText.dropFirst(), radix: 16), let anonymousContextAddress = UnsafeRawPointer(bitPattern: address), node.children[1].kind == .identifier, - let privateDiscriminator = SymbolicDemangler.privateDiscriminator(forAnonymousContextAt: anonymousContextAddress) + let name = node.children[1].text else { return nil } - let privateDeclName = Node.createTransient(kind: .privateDeclName, children: [ - .createTransient(kind: .identifier, text: privateDiscriminator), - node.children[1], - ]) - var rewrittenChildren = [rewritingAnonymousContexts(in: parent, rewrittenNodes: &rewrittenNodes), privateDeclName] + + let context: Node + let declarationName: Node + if let compilerSpelledName = SymbolicDemangler.anonymousContextName(forAnonymousContextAt: anonymousContextAddress), + let compilerSpelledContext = compilerSpelledName.children.first, + let compilerSpelledDeclarationName = compilerSpelledName.children.at(1), + compilerSpelledDeclarationName.kind == .localDeclName || compilerSpelledDeclarationName.kind == .privateDeclName, + compilerSpelledDeclarationName.children.at(1)?.text == name { + context = compilerSpelledDeclarationName.kind == .localDeclName ? compilerSpelledContext : rewritingAnonymousContexts(in: parent, rewrittenNodes: &rewrittenNodes) + declarationName = compilerSpelledDeclarationName + } else if let privateDiscriminator = SymbolicDemangler.privateDiscriminator(forAnonymousContextAt: anonymousContextAddress) { + context = rewritingAnonymousContexts(in: parent, rewrittenNodes: &rewrittenNodes) + declarationName = Node.createTransient(kind: .privateDeclName, children: [ + .createTransient(kind: .identifier, text: privateDiscriminator), + node.children[1], + ]) + } else if parent.kind == .anonymousContext, let positionName = SymbolicDemangler.positionName(forAnonymousContextAt: anonymousContextAddress) { + context = rewritingAnonymousContexts(in: parent, rewrittenNodes: &rewrittenNodes) + declarationName = Node.createTransient(kind: .privateDeclName, children: [ + .createTransient(kind: .identifier, text: positionName), + node.children[1], + ]) + } else { + return nil + } + var rewrittenChildren = [context, declarationName] for remainingChild in node.children.dropFirst(2) { rewrittenChildren.append(rewritingAnonymousContexts(in: remainingChild, rewrittenNodes: &rewrittenNodes)) } diff --git a/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift b/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift index e68667186..ccce5ce56 100644 --- a/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift +++ b/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift @@ -16,6 +16,14 @@ public struct ABISnapshotDocument: Sendable, Codable, Equatable { /// `ABIDiffer.extensionBucketKey(for:)`). /// /// History: + /// - 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 + /// (evolution proposal `local-type-context-names`) — no longer as a + /// member of the enclosing type, under which two methods' same-named + /// types shared one key. Key scheme unchanged; an older baseline would + /// misreport every local type, its members and its conformances as + /// removed and added, and a removed type is a breaking change. /// - 6: a class container of a stripped image carries the vtable members /// whose only symbol is their method descriptor's `Tq` (evolution /// proposal `interface-descriptor-only-vtable-members`) — the public @@ -41,7 +49,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 = 6 + public static let currentFormatVersion = 7 public let formatVersion: Int public var provenance: ABIProvenance? diff --git a/Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift index 3fd2f7e8f..433fbee63 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift @@ -394,7 +394,14 @@ extension FunctionTypeNodePrintable where Self: DependentGenericNodePrintable { mutating func printLabelList(name: Node, type: Node, genericFunctionTypeList: Node?) async { var labelList = name.children.first(of: .labelList) - if let argumentTuple = name.first(of: .argumentTuple), let tuple = argumentTuple.first(of: .tuple) { + // The declaration's OWN argument tuple, from its own function type. + // `name`'s first child is its context, which a whole-tree search + // reached first: a local type's context is the function declaring + // it, whose parameter count then decided how many unnamed labels a + // member of the type printed (evolution proposal + // `local-type-context-names`). + let ownFunctionType = type.kind == .dependentGenericType ? type.children.at(1)?.children.first : type + if let argumentTuple = ownFunctionType?.children.first(of: .argumentTuple), let tuple = argumentTuple.first(of: .tuple) { if !tuple.children.isEmpty, labelList == nil || labelList!.children.isEmpty { labelList = Node.create(kind: .labelList, children: (0 ..< tuple.children.count).map { _ in NodeFactory.firstElementMarker }) } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index 0181b0b1d..d3348b95c 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -1,5 +1,6 @@ import SwiftDeclaration import SwiftDeclarationRendering +import SwiftInspection import Demangling import Semantic @@ -155,8 +156,16 @@ extension TypeNodePrintable { } guard let contextNode = name.children.first else { return } + // A type declared in a function or closure body: nothing outside the + // body can spell it, so a reference prints its declared name alone — + // the name its declaration prints under, a comment above which names + // the function (evolution proposal `local-type-context-names`). This + // printer spells no function, closure or local name, and printed + // such a reference as nothing at all (`__derived_struct_equals(_: , _: )`). + let isLocalType = name.localTypeNaming != nil + var resolvedCImportedModule = false - if shouldPrintContext() { + if shouldPrintContext(), !isLocalType { let writtenUnitCountBeforeContext = target.writtenUnitCount if contextNode.kind == .module { let siblingIdentifier = name.children.at(1)?.text @@ -183,7 +192,14 @@ extension TypeNodePrintable { } if let declarationName = name.children.at(1) { - if declarationName.kind != .privateDeclName { + if declarationName.kind == .localDeclName { + // `Visitor #1`'s identifier: the ordinal tells same-named + // types of one body apart, which the comment above each + // declaration does here. + if let identifier = declarationName.children.at(1) { + await printIdentifier(identifier, parentKind: name.kind) + } + } else if declarationName.kind != .privateDeclName { if declarationName.kind == .identifier { // A resolved C-imported module may pair with an identifier // whose C spelling differs from its Swift one — `__C`'s diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 2b29018bc..8ca97ebd0 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -488,4 +488,78 @@ extension SwiftDeclarationPrinter { } } } + + // MARK: - Local types (evolution proposal `local-type-context-names`) + + /// The comment above the declaration of a type declared in a function or + /// closure body: the compiler's name for it, modules left out + /// (`Visitor #1 in Holder.countValues()`), or — when no source the image + /// keeps names the function or closure — a sentence saying so. `nil` for + /// any other type. + package func localTypeDeclarationComment(for typeName: SwiftDeclaration.TypeName) -> String? { + switch typeName.node.localTypeNaming { + case .compilerSpelled: + typeName.name(using: .localTypeDeclarationComment) + case .positionBased: + "Local type in a function or closure the binary does not name" + case nil: + nil + } + } + + /// An extension header's extended type. A local type whose function no + /// source names — or a type nested in one — keeps its position-based name + /// in full, `Holder.(Visitor in $1a2b3c)`: printed like any other name it + /// would read `Holder.Visitor`, a member type the source never declared, + /// and alike for every unnamed `Visitor` of `Holder`. + @SemanticStringBuilder + package func renderExtendedTypeName(_ extensionName: ExtensionName) -> SemanticString { + if spellsPositionNamedLocalType(extensionName.node) { + TypeDeclaration(kind: extensionName.kind.semanticTypeKind, extensionName.name(using: DemangleOptions.interfaceTypeBuilderOnly.union(.showPrivateDiscriminators))) + } else { + extensionName.print() + } + } + + /// Whether `name` or a type it is nested in is a position-based local + /// type. + private func spellsPositionNamedLocalType(_ name: NodeReference) -> Bool { + var current = name + while true { + if current.localTypeNaming == .positionBased { + return true + } + while [.type, .boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericOtherNominalType].contains(current.kind), let wrapped = current.children.first { + current = wrapped + } + guard current.kind.isAnyGeneric, let context = current.children.first else { + return false + } + current = context + } + } +} + +extension DemangleOptions { + /// A local type's compiler-spelled name the way a reader would say it: + /// no modules, no parameter types, the `#1` ordinal kept. + fileprivate static let localTypeDeclarationComment = DemangleOptions.simplified.union(.displayLocalNameContexts) +} + +extension ExtensionKind { + /// The kind `ExtensionName.print()` declares the extended type as. + fileprivate var semanticTypeKind: SemanticType.TypeKind { + switch self { + case .type(.enum): + .enum + case .type(.struct): + .struct + case .type(.class): + .class + case .protocol: + .protocol + case .typeAlias: + .other + } + } } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index a518149be..3f0e57c40 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -227,6 +227,16 @@ public final class SwiftDeclarationPrinter: S try typeDefinition.index(in: machO) + // A local type's declaration says which function or closure declares + // it: the name the declaration prints under is the bare declared one, + // which two methods' local types can share (evolution proposal + // `local-type-context-names`). + if let localTypeComment = localTypeDeclarationComment(for: typeDefinition.typeName) { + Indent(level: level - 1) + Comment(localTypeComment) + BreakLine() + } + // Type-level attributes, inferred for this print and kept local: // printing writes nothing to a definition, which is what lets several // tasks print one at once (evolution proposal @@ -510,7 +520,7 @@ public final class SwiftDeclarationPrinter: S } Keyword(.extension) Space() - extensionDefinition.extensionName.print() + renderExtendedTypeName(extensionDefinition.extensionName) // This print operation's single conformance materialization // (proposal 0002). Propagates on failure: a public entry must not diff --git a/Sources/TestSupport/MachOTestingSupport/LocalTypeFixture.swift b/Sources/TestSupport/MachOTestingSupport/LocalTypeFixture.swift new file mode 100644 index 000000000..bc11675a2 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/LocalTypeFixture.swift @@ -0,0 +1,492 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import Testing + +/// An on-the-fly fixture for types declared inside function and closure +/// bodies (evolution proposal `local-type-context-names`). +/// +/// A local type hangs off a chain of anonymous contexts — one for the type +/// itself, one per enclosing closure, one for the function — none of which +/// carries a name unless the compiler ran with +/// `-enable-anonymous-context-mangled-names`, which the driver adds only to +/// `-g -Onone` builds. The full name a reader needs comes from one of three +/// places; each of the first three variants keeps exactly one of them: +/// +/// - `.debugNames`: compiled with that flag, then `strip -x` — only the +/// anonymous context descriptors' own names. +/// - `.anonymousDescriptorSymbols`: the exported and imported symbols plus +/// the anonymous descriptors' `$sMXX` symbols. +/// - `.symbolicReferences`: the exported and imported symbols plus the +/// `_symbolic` ones — the shape of AppKit in the dyld shared cache, where +/// only the symbol on a field descriptor's type name spells a local type. +/// - `.unstripped`: every symbol — the shape of an unstripped release build +/// (SwiftUI in the dyld shared cache), and the one variant whose member +/// symbols survive, so members are attributed in it. +/// - `.stripped` (`strip -x`): none of them — a stripped app. +/// +/// No strip option removes chosen local symbols (`strip -R` handles global +/// ones only), so the two variants that keep some are cut with +/// `strip -s ` — which accepts a local symbol only when +/// it was a private external before linking, as the `MXX` and `_symbolic` +/// ones are and the member symbols are not. Stripping invalidates the +/// linker's ad-hoc signature, which `dlopen` then refuses; every variant is +/// re-signed. Each variant has a module name of its own, so all of them can +/// be loaded into the test process at once. +package enum LocalTypeFixture { + /// The `ExclusiveImageAccess` key every suite touching these images + /// declares: one for all four, since a suite reads several of them. + package static let exclusiveAccessName = "LocalTypeFixture" + + package enum Variant: String, CaseIterable, Sendable, CustomTestStringConvertible { + case debugNames + case anonymousDescriptorSymbols + case symbolicReferences + case unstripped + case stripped + + /// The variants that keep a source of every local type's name. + package static let named: [Variant] = [.debugNames, .anonymousDescriptorSymbols, .symbolicReferences, .unstripped] + + package var moduleName: String { + "LocalTypeFixture" + rawValue.prefix(1).uppercased() + rawValue.dropFirst() + } + + package var testDescription: String { rawValue } + } + + /// One shape per way a local type's context can look. Compiled `-Onone` + /// so nothing is dead-stripped; without `-g` the driver adds no + /// anonymous context names, which is what a release build leaves too. + package static let swiftSource = """ + public protocol LocalTypeFixtureVisitor { + mutating func visit(_ value: Int) + } + + public protocol LocalTypeFixtureEntryVisitor: ~Copyable { + mutating func visit(entry: Int) -> Bool + } + + public struct Holder { + public init() {} + + // Two methods each declaring a `Visitor`: SwiftUI's `TableDataSource` + // shape, where every one of them used to demangle as `Holder.Visitor`. + // The first is `Equatable`, so a local type also appears in the + // parameter list of a member (`__derived_struct_equals`). + public func countValues() -> Any { + struct Visitor: LocalTypeFixtureVisitor, Equatable { + var count: Int + mutating func visit(_ value: Int) { + count += 1 + } + } + return Visitor(count: 0) + } + + public func sumValues() -> Any { + struct Visitor: LocalTypeFixtureVisitor { + var sum: Int + mutating func visit(_ value: Int) { + sum += value + } + } + return Visitor(sum: 0) + } + + // A private method: its private discriminator names the method, never + // the type declared in it. + private func hiddenValues() -> Any { + struct Hidden { + var value: Int + } + return Hidden(value: 0) + } + + public func revealHiddenValues() -> Any { + hiddenValues() + } + + // A closure between the method and the type: one more anonymous context. + public func valuesFromClosure() -> Any { + let make = { () -> Any in + struct InClosure { + var value: Int + } + return InClosure(value: 0) + } + return make() + } + + // Two same-named types in one method: `Twin #1` and `Twin #2`. + public func twins(_ flag: Bool) -> Any { + if flag { + struct Twin { + var first: Int + } + return Twin(first: 0) + } else { + struct Twin { + var second: Int + } + return Twin(second: 0) + } + } + + // An enum and a class: every nominal kind. + public func mode(_ flag: Bool) -> Any { + enum Mode { + case on + case off + } + return flag ? Mode.on : Mode.off + } + + public func box() -> AnyObject { + final class Box { + var value = 0 + } + return Box() + } + + // A type nested in a local type, referenced by a field of it. + public func nested() -> Any { + struct Generator { + struct Element { + var value: Int + } + var element: Element + } + return Generator(element: Generator.Element(value: 0)) + } + + // SwiftUI's `IndexWrappingVisitor` shape: a `~Copyable` generic + // parameter makes the compiler name the type's members as if they + // were declared in an extension carrying the inverse requirement + // (`…Ri_zrlE…`). + public func wrapping() -> Bool { + struct WrappingGenerator { + struct IndexWrappingVisitor: LocalTypeFixtureEntryVisitor, ~Copyable { + var index: Int + var base: Base + mutating func visit(entry: Int) -> Bool { + index += 1 + return base.visit(entry: entry) + } + } + struct Counter: LocalTypeFixtureEntryVisitor { + var count: Int + mutating func visit(entry: Int) -> Bool { + count += 1 + return true + } + } + } + var visitor = WrappingGenerator.IndexWrappingVisitor(index: 0, base: WrappingGenerator.Counter(count: 0)) + return visitor.visit(entry: 0) + } + + // A generic method's opaque result type hangs off the method's own + // anonymous context, whatever the build. + public func opaqueValue(_ value: Value) -> some Equatable { + 0 + } + + // Conformances to standard-library protocols, whose witnesses are + // symbols filed under the conformance — under the local type's full + // name, its enclosing declaration included. A getter, a `static` + // method and a throwing method each put a node of their own kind + // into that name. `KeyTwin` and `PayloadTwin` declare the same types + // outside any body. The getter's `Key` also has a static stored + // property, whose storage symbol is no accessor while its name holds + // one. + public var keyFromGetter: Any { + struct Key: Hashable { + static var shared = 0 + var value: Int + } + Key.shared += 1 + return Key(value: Key.shared) + } + + public static func keyFromStaticMethod() -> Any { + struct Key: Hashable { + var value: Int + } + return Key(value: 0) + } + + // The synthesized `CodingKeys` brings initializers and properties + // to the conformances: every member kind. + public func payload() throws -> Any { + struct Payload: Codable { + var value: Int + } + return Payload(value: 0) + } + + // A method with argument labels and parameters: its label list and + // argument tuple sit in every member's name, ahead of the member's + // own. `LookupTwin` declares the same type outside any body. + public func lookup(named name: String, at index: Int) -> Any { + @dynamicMemberLookup + struct Lookup: Hashable { + var value: Int + subscript(dynamicMember member: String) -> Int { value } + func combine(_ first: Int, _ second: Int, _ third: Int) -> Int { first + second + third } + } + return Lookup(value: index + name.count) + } + } + + public struct KeyTwin: Hashable { + static var shared = 0 + var value: Int + } + + public struct PayloadTwin: Codable { + var value: Int + } + + @dynamicMemberLookup + public struct LookupTwin: Hashable { + var value: Int + public subscript(dynamicMember member: String) -> Int { value } + func combine(_ first: Int, _ second: Int, _ third: Int) -> Int { first + second + third } + } + + // A method of another module's type: an extension above the anonymous + // contexts. + extension String { + public func localTypeFixtureWrapped() -> Any { + struct Wrapper { + var value: String + } + return Wrapper(value: self) + } + } + + // A top-level function: nothing but the module above the anonymous contexts. + public func localTypeFixtureTopLevel() -> Any { + struct TopLevel { + var value: Int + } + return TopLevel(value: 0) + } + """ + + /// The compiler's spelling of every type the source declares in a body, + /// nested types of local types included, as the stock demangler prints + /// the type descriptors' `Mn` symbols of an unstripped build + /// (`swift-demangle -compact`) — the ground truth a name built from the + /// descriptors is held to. `Hidden` is not listed: its method is private, + /// and the discriminator hashes the source file's name (see + /// `isCompilerSpelledHiddenName(_:of:)`). + package static func compilerSpelledNames(of variant: Variant) -> [String] { + let moduleName = variant.moduleName + return [ + "TopLevel #1 in \(moduleName).localTypeFixtureTopLevel() -> Any", + "Visitor #1 in \(moduleName).Holder.countValues() -> Any", + "Visitor #1 in \(moduleName).Holder.sumValues() -> Any", + "InClosure #1 in closure #1 () -> Any in \(moduleName).Holder.valuesFromClosure() -> Any", + "Box #1 in \(moduleName).Holder.box() -> Swift.AnyObject", + "Mode #1 in \(moduleName).Holder.mode(Swift.Bool) -> Any", + "Twin #1 in \(moduleName).Holder.twins(Swift.Bool) -> Any", + "Twin #2 in \(moduleName).Holder.twins(Swift.Bool) -> Any", + "Generator #1 in \(moduleName).Holder.nested() -> Any", + "Element in Generator #1 in \(moduleName).Holder.nested() -> Any", + "WrappingGenerator #1 in \(moduleName).Holder.wrapping() -> Swift.Bool", + "IndexWrappingVisitor in WrappingGenerator #1 in \(moduleName).Holder.wrapping() -> Swift.Bool", + "Counter in WrappingGenerator #1 in \(moduleName).Holder.wrapping() -> Swift.Bool", + "Wrapper #1 in (extension in \(moduleName)):Swift.String.localTypeFixtureWrapped() -> Any", + "Key #1 in \(moduleName).Holder.keyFromGetter.getter : Any", + "Key #1 in static \(moduleName).Holder.keyFromStaticMethod() -> Any", + "Payload #1 in \(moduleName).Holder.payload() throws -> Any", + "CodingKeys in Payload #1 in \(moduleName).Holder.payload() throws -> Any", + "Lookup #1 in \(moduleName).Holder.lookup(named: Swift.String, at: Swift.Int) -> Any", + ] + } + + /// Whether the fixture declares the type in a body — a local type, or a + /// type nested in one — as opposed to `Holder` and the twins. + /// + /// Read off the descriptors alone, so a test can pick the local types + /// without trusting the names it checks: a local type's own anonymous + /// context sits under its function's or closure's, while a private + /// type's sits under a type, an extension or the module. + package static func isDeclaredInABody(_ descriptor: ContextDescriptorWrapper, in context: some ReadingContext) throws -> Bool { + var parent = try descriptor.parent(in: context)?.resolved + while let currentParent = parent { + let grandparent = try currentParent.parent(in: context)?.resolved + if case .anonymous = currentParent, case .anonymous? = grandparent { + return true + } + parent = grandparent + } + return false + } + + /// `Hidden #1 in .Holder.(hiddenValues in _)() -> Any`: + /// the discriminator belongs to the private method, and the type's own + /// name is a local one. + package static func isCompilerSpelledHiddenName(_ name: String, of variant: Variant) -> Bool { + name.hasPrefix("Hidden #1 in \(variant.moduleName).Holder.(hiddenValues in _") && name.hasSuffix(")() -> Any") + } + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "LocalTypeFixture \(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; every variant shares one working directory. + private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("LocalTypeFixture-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let swiftSourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + try swiftSource.write(to: swiftSourceURL, atomically: true, encoding: .utf8) + + var libraries: [Variant: URL] = [:] + for variant in Variant.allCases { + let libraryURL = workingDirectory.appendingPathComponent("lib\(variant.moduleName).dylib") + // Install names are the absolute output paths, so the + // in-process leg loads each variant with no rpath. + var arguments = [ + // The language mode pinned: CI's toolchain and a newer + // local one must compile the same source the same way. + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", variant.moduleName, + "-Xlinker", "-install_name", "-Xlinker", libraryURL.path, + swiftSourceURL.path, "-o", libraryURL.path, + ] + if variant == .debugNames { + arguments += ["-Xfrontend", "-enable-anonymous-context-mangled-names"] + } + _ = try run(step: "swiftc (\(variant.rawValue))", arguments) + + switch variant { + case .debugNames, + .stripped: + _ = try run(step: "strip (\(variant.rawValue))", ["strip", "-x", libraryURL.path]) + case .anonymousDescriptorSymbols: + try strip(libraryURL, keepingLocalSymbolsWhere: { $0.hasSuffix("MXX") }, in: workingDirectory, variant: variant) + case .symbolicReferences: + try strip(libraryURL, keepingLocalSymbolsWhere: { $0.hasPrefix("_symbolic") }, in: workingDirectory, variant: variant) + case .unstripped: + break + } + _ = try run(step: "codesign (\(variant.rawValue))", ["codesign", "--force", "--sign", "-", libraryURL.path]) + libraries[variant] = libraryURL + } + return libraries + } + }() + + private static func symbolNames(of libraryURL: URL, globalOnly: Bool, step: String) throws -> [String] { + let output = try run(step: step, ["nm", globalOnly ? "-gj" : "-j", libraryURL.path]) + return output.split(separator: "\n").map(String.init).filter { !$0.isEmpty } + } + + /// Strips every local symbol but those `isKept` selects. The global ones + /// stay: `-g` lists the imported symbols too, which the indirect symbol + /// table refers to and `strip -s` refuses to drop. + private static func strip(_ libraryURL: URL, keepingLocalSymbolsWhere isKept: (String) -> Bool, in workingDirectory: URL, variant: Variant) throws { + let globalSymbolNames = try symbolNames(of: libraryURL, globalOnly: true, step: "nm -g (\(variant.rawValue))") + let keptLocalSymbolNames = try symbolNames(of: libraryURL, globalOnly: false, step: "nm (\(variant.rawValue))").filter(isKept) + let keepListURL = workingDirectory.appendingPathComponent("keep-\(variant.rawValue).txt") + try ((globalSymbolNames + keptLocalSymbolNames).joined(separator: "\n") + "\n").write(to: keepListURL, atomically: true, encoding: .utf8) + _ = try run(step: "strip -s (\(variant.rawValue))", ["strip", "-s", keepListURL.path, libraryURL.path]) + } + + /// Runs `xcrun ` and returns its standard output. + @discardableResult + private static func run(step: String, _ arguments: [String]) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + let standardOutputPipe = Pipe() + let standardErrorPipe = Pipe() + process.standardOutput = standardOutputPipe + process.standardError = standardErrorPipe + try process.run() + // Drain both pipes BEFORE waitUntilExit, or a long output deadlocks + // both sides; standard error on a thread of its own so neither pipe + // can fill while the other is read. + let standardErrorReader = PipeReader(pipe: standardErrorPipe) + let outputData = standardOutputPipe.fileHandleForReading.readDataToEndOfFile() + let diagnosticsData = standardErrorReader.waitForData() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw CompilationError(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return String(decoding: outputData, as: UTF8.self) + } + + /// Reads a pipe to its end on a thread of its own. + private final class PipeReader: @unchecked Sendable { + private let condition = NSCondition() + private var data: Data? + + init(pipe: Pipe) { + Thread { + let readData = pipe.fileHandleForReading.readDataToEndOfFile() + self.condition.lock() + self.data = readData + self.condition.signal() + self.condition.unlock() + }.start() + } + + func waitForData() -> Data { + condition.lock() + defer { condition.unlock() } + while data == nil { + condition.wait() + } + return data ?? Data() + } + } + + package static func libraryURL(_ variant: Variant) throws -> URL { + let libraries = try compilationResult.get() + guard let libraryURL = libraries[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + package static func machOFile(_ variant: Variant) throws -> MachOFile { + let libraryURL = try libraryURL(variant) + switch try MachOKit.loadFromFile(url: libraryURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } + + /// The variant loaded into the test process. + package static func loadedImage(_ variant: Variant) throws -> MachOImage { + let libraryURL = try libraryURL(variant) + let handle = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + try #require(handle != nil, "the \(variant.rawValue) fixture did not load: \(dlerror().map { String(cString: $0) } ?? "no dlerror")") + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the \(variant.rawValue) fixture dylib did not load in-process") + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift new file mode 100644 index 000000000..a5d476541 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNameLocalTypeTests.swift @@ -0,0 +1,57 @@ +import Foundation +import Testing +import MachOKit +@testable import Demangling +@testable import MachOSwiftSection +@testable import MachOTestingSupport +@testable @_spi(Internals) import SwiftInspection +@testable import SwiftDeclarationRendering + +/// The runtime names a local type through its anonymous contexts' addresses +/// (`AnonymousContext("$
", …)` for the type's own, each closure's +/// and the function's). A name that comes from the runtime has to read like +/// the one built from the descriptors (evolution proposal +/// `local-type-context-names`): the compiler's spelling where the image +/// records it, the same position-based name where it does not. Dropping +/// every anonymous context instead, as `RuntimeTypeNameDemangling` did, read +/// both of `Holder`'s `Visitor`s as `Holder.Visitor`. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct RuntimeTypeNameLocalTypeTests { + @Test(arguments: LocalTypeFixture.Variant.allCases) + func runtimeNameOfALocalTypeIsItsDescriptorBuiltName(variant: LocalTypeFixture.Variant) throws { + let machOImage = try LocalTypeFixture.loadedImage(variant) + var runtimeNames: [String] = [] + for descriptor in try machOImage.swift.typeContextDescriptors { + let contextDescriptor = descriptor.asContextDescriptorWrapper + // A generic type's accessor wants its arguments. + guard try LocalTypeFixture.isDeclaredInABody(contextDescriptor, in: machOImage.context), + !descriptor.contextDescriptor.layout.flags.isGeneric, + let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machOImage.context) + else { continue } + let metatype = unsafeBitCast(UInt(try accessor(request: .init()).value.address), to: Any.Type.self) + let descriptorBuiltNode = try SymbolicDemangler.demangleContext(for: contextDescriptor, in: machOImage.context) + + let runtimeNode = try #require(RuntimeTypeNameDemangling.node(forMetatype: metatype)) + + let runtimeName = Self.printedName(of: runtimeNode) + #expect(runtimeName == Self.printedName(of: descriptorBuiltNode)) + #expect(runtimeNode.first(of: .anonymousContext) == nil, "\(runtimeName)") + runtimeNames.append(runtimeName) + } + // Every local type but the generic `IndexWrappingVisitor`, no two alike. + #expect(runtimeNames.count == 19) + #expect(Set(runtimeNames).count == runtimeNames.count, "\(runtimeNames.sorted())") + if variant != .stripped { + let expectedNames = LocalTypeFixture.compilerSpelledNames(of: variant).filter { !$0.hasPrefix("IndexWrappingVisitor ") } + #expect(runtimeNames.filter { !LocalTypeFixture.isCompilerSpelledHiddenName($0, of: variant) }.sorted() == expectedNames.sorted()) + } + } + + private static func printedName(of node: Node) -> String { + var nominal = node + while nominal.kind == .global || nominal.kind == .type || nominal.kind == .typeMangling, let child = nominal.children.first { + nominal = child + } + return nominal.print(using: .default) + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift index 94c59408e..3016458ff 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift @@ -11,7 +11,7 @@ import MachOKit /// type's anonymous context by the descriptor's address. It has to come out /// carrying the discriminator the name built from the descriptors carries — /// which, for an OS framework in the dyld shared cache, only a `_symbolic` -/// symbol records (`AnonymousContextPrivateDiscriminatorIndex`). Dropping the +/// symbol records (`AnonymousContextNameIndex`). Dropping the /// anonymous context instead, as `RuntimeTypeNameDemangling` used to, left the /// two names disagreeing about the same type. /// diff --git a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift new file mode 100644 index 000000000..e0a9efe5f --- /dev/null +++ b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift @@ -0,0 +1,37 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftDump +@testable import MachOTestingSupport + +/// The dump declares a local type under the compiler's full name and lists +/// the members its symbols attribute to it (evolution proposal +/// `local-type-context-names`). Both of `Holder`'s `Visitor`s used to be +/// declared as `Holder.Visitor`, and since the member symbols spell the real +/// name, neither listed a member. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct LocalTypeDumpTests { + @Test func eachVisitorIsDeclaredUnderItsMethodWithItsOwnMembers() async throws { + let variant = LocalTypeFixture.Variant.unstripped + let machOFile = try LocalTypeFixture.machOFile(variant) + var dumps: [String] = [] + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + guard case .struct(let structDescriptor) = typeContextDescriptor, + try structDescriptor.name(in: machOFile.context) == "Visitor" + else { continue } + let structType = try Struct(descriptor: structDescriptor, in: machOFile.context) + dumps.append(try await structType.dump(using: .demangleOptions(.test), in: machOFile).string) + } + let moduleName = variant.moduleName + let countingVisitor = try #require(dumps.first { $0.hasPrefix("struct Visitor #1 in \(moduleName).Holder.countValues() -> Any {") }, "\(dumps)") + let summingVisitor = try #require(dumps.first { $0.hasPrefix("struct Visitor #1 in \(moduleName).Holder.sumValues() -> Any {") }, "\(dumps)") + + #expect(countingVisitor.contains("var count: Swift.Int"), "\(countingVisitor)") + #expect(!countingVisitor.contains("var sum: Swift.Int"), "\(countingVisitor)") + #expect(countingVisitor.contains("visit(Swift.Int) -> ()"), "\(countingVisitor)") + #expect(summingVisitor.contains("var sum: Swift.Int"), "\(summingVisitor)") + #expect(summingVisitor.contains("visit(Swift.Int) -> ()"), "\(summingVisitor)") + } +} diff --git a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/nestedFunctionsSnapshot.1.txt b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/nestedFunctionsSnapshot.1.txt index c74c72758..10f97993f 100644 --- a/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/nestedFunctionsSnapshot.1.txt +++ b/Tests/SwiftDumpTests/Snapshots/__Snapshots__/SymbolTestsCoreDumpSnapshotTests/nestedFunctionsSnapshot.1.txt @@ -5,7 +5,7 @@ struct SymbolTestsCore.NestedFunctions.NestedFunctionHolderTest { /* Function */ SymbolTestsCore.NestedFunctions.NestedFunctionHolderTest.outerWithLocalClass() -> Swift.String } -class SymbolTestsCore.NestedFunctions.NestedFunctionHolderTest.LocalClass { +class LocalClass #1 in SymbolTestsCore.NestedFunctions.NestedFunctionHolderTest.outerWithLocalClass() -> Swift.String { var label: Swift.String // No implementation in this image (deleted method — slot retained for ABI) @@ -16,4 +16,7 @@ class SymbolTestsCore.NestedFunctions.NestedFunctionHolderTest.LocalClass { /* [Modify] */ // No implementation in this image (deleted method — slot retained for ABI) /* [ Init ] */ + + /* Deallocator */ + __deallocating_deinit in LocalClass #1 in SymbolTestsCore.NestedFunctions.NestedFunctionHolderTest.outerWithLocalClass() -> Swift.String } \ No newline at end of file diff --git a/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift b/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift new file mode 100644 index 000000000..0b8e1b009 --- /dev/null +++ b/Tests/SwiftInspectionTests/LocalTypeContextNameTests.swift @@ -0,0 +1,183 @@ +import Foundation +import Testing +import MachOKit +@testable import Demangling +@testable import MachOSwiftSection +@testable import MachOTestingSupport +@testable @_spi(Internals) import SwiftInspection + +/// A type declared in a function or closure body hangs off a chain of +/// anonymous contexts — the type's own, one per closure, the function's — +/// none of which carries a name in a release build (evolution proposal +/// `local-type-context-names`). `SymbolicDemangler` used to drop the chain, +/// so two methods' `Visitor`s both read as `Holder.Visitor`, or to borrow the +/// private discriminator of an enclosing private method, faking a private +/// type. Each `LocalTypeFixture` variant keeps one source of the full name +/// (`debugNames`, `anonymousDescriptorSymbols`, `symbolicReferences`), all of +/// them (`unstripped`) or none (`stripped`); every reader path must come back +/// with the compiler's own spelling where a source exists, and with distinct +/// position-based names where none does. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct LocalTypeContextNameTests { + // MARK: - The compiler's spelling, from each source + + @Test(arguments: LocalTypeFixture.Variant.named) + func fileNamesEveryLocalTypeTheWayTheCompilerDoes(variant: LocalTypeFixture.Variant) throws { + let machOFile = try LocalTypeFixture.machOFile(variant) + let names = try Self.localTypeNames(in: machOFile, context: machOFile.context) + try Self.expectCompilerSpelling(names, variant: variant) + } + + @Test(arguments: LocalTypeFixture.Variant.named) + func imageNamesEveryLocalTypeTheWayTheCompilerDoes(variant: LocalTypeFixture.Variant) throws { + let machOImage = try LocalTypeFixture.loadedImage(variant) + let names = try Self.localTypeNames(in: machOImage, context: machOImage.context) + try Self.expectCompilerSpelling(names, variant: variant) + } + + /// The runtime-metadata paths reach a descriptor by address and demangle + /// it through `InProcessContext`. + @Test(arguments: LocalTypeFixture.Variant.named) + func inProcessDescriptorsNameEveryLocalTypeTheWayTheCompilerDoes(variant: LocalTypeFixture.Variant) throws { + let machOImage = try LocalTypeFixture.loadedImage(variant) + var names: [String] = [] + for descriptor in try Self.localTypeDescriptors(in: machOImage) { + let inProcessDescriptor: ContextDescriptorWrapper = try .resolve(at: machOImage.ptr.advanced(by: descriptor.contextDescriptor.offset), in: .inProcess) + names.append(Self.printedName(of: try SymbolicDemangler.demangleContext(for: inProcessDescriptor, in: .inProcess))) + } + try Self.expectCompilerSpelling(names, variant: variant) + } + + /// A private method's discriminator stays on the method. Taking the first + /// `privateDeclName` anywhere in the anonymous context's symbol used to + /// hang it on every anonymous context and then on the type, reading + /// `Holder.(unknown context at _…).(Hidden in _…)` — a private type that + /// does not exist. + @Test(arguments: LocalTypeFixture.Variant.named) + func privateMethodLendsNoDiscriminatorToItsLocalType(variant: LocalTypeFixture.Variant) throws { + let machOFile = try LocalTypeFixture.machOFile(variant) + let hidden = try #require(try Self.localTypeDescriptors(in: machOFile).first { try $0.namedContextDescriptor?.name(in: machOFile.context) == "Hidden" }) + let nominal = Self.nominal(of: try SymbolicDemangler.demangleContext(for: hidden, in: machOFile.context)) + + #expect(nominal.children.at(1)?.kind == .localDeclName) + #expect(nominal.first(of: .anonymousContext) == nil) + #expect(nominal.children.first?.kind == .function) + #expect(nominal.children.first?.children.at(1)?.kind == .privateDeclName) + } + + // MARK: - No source: position-based names + + /// With every name source stripped, a local type is spelled by the + /// address of the anonymous context wrapping it — the runtime's and + /// Remote Mirror's convention — under the nearest context the + /// descriptors can name. Two methods' `Visitor`s must not merge. + @Test func strippedLocalTypesGetDistinctPositionBasedNames() throws { + let machOFile = try LocalTypeFixture.machOFile(.stripped) + let moduleName = LocalTypeFixture.Variant.stripped.moduleName + var names: [String: String] = [:] + for descriptor in try Self.localTypeDescriptors(in: machOFile) { + let name = try #require(try descriptor.namedContextDescriptor?.name(in: machOFile.context)) + let printedName = Self.printedName(of: try SymbolicDemangler.demangleContext(for: descriptor, in: machOFile.context)) + #expect(names.updateValue(name, forKey: printedName) == nil, "two local types share the name \(printedName)") + guard case .element(.anonymous(let anonymousContext))? = try descriptor.parent(in: machOFile.context) else { continue } + let address = String(machOFile.address(forOffset: anonymousContext.offset), radix: 16) + #expect(printedName.hasSuffix("(\(name) in $\(address))"), "\(printedName) does not name the anonymous context at \(address)") + } + #expect(names.values.filter { $0 == "Visitor" }.count == 2) + #expect(names.values.filter { $0 == "Twin" }.count == 2) + #expect(names.values.filter { $0 == "Key" }.count == 2) + // The nearest named context stays: the type, the extended type, the module. + #expect(names.keys.contains { $0.hasPrefix("\(moduleName).Holder.(Visitor in $") }) + #expect(names.keys.contains { $0.hasPrefix("(extension in \(moduleName)):Swift.String.(Wrapper in $") }) + #expect(names.keys.contains { $0.hasPrefix("\(moduleName).(TopLevel in $") }) + // A type nested in a local one keeps its own name under it. + #expect(names.keys.contains { $0.hasPrefix("\(moduleName).Holder.(Generator in $") && $0.hasSuffix(").Element") }) + } + + /// The position comes from the image's own address space, so the file + /// and the loaded image agree on it. + @Test func strippedLocalTypesAreNamedAlikeInTheFileAndInProcess() throws { + let machOFile = try LocalTypeFixture.machOFile(.stripped) + let machOImage = try LocalTypeFixture.loadedImage(.stripped) + let fileNames = try Self.localTypeNames(in: machOFile, context: machOFile.context).sorted() + let imageNames = try Self.localTypeNames(in: machOImage, context: machOImage.context).sorted() + var inProcessNames: [String] = [] + for descriptor in try Self.localTypeDescriptors(in: machOImage) { + let inProcessDescriptor: ContextDescriptorWrapper = try .resolve(at: machOImage.ptr.advanced(by: descriptor.contextDescriptor.offset), in: .inProcess) + inProcessNames.append(Self.printedName(of: try SymbolicDemangler.demangleContext(for: inProcessDescriptor, in: .inProcess))) + } + #expect(fileNames == imageNames) + #expect(fileNames == inProcessNames.sorted()) + } + + // MARK: - Qualified names + + /// The static layout engine and the ObjC-side lookups key a type by + /// `NodeTypeNaming`'s qualified name, both for its descriptor and for a + /// field typed as it. A local type's key has to tell its function apart: + /// keyed by its bare name, two methods' `Visitor`s share one key, and a + /// field typed as one resolves to the other. + @Test(arguments: LocalTypeFixture.Variant.allCases) + func qualifiedNamesOfLocalTypesAreDistinct(variant: LocalTypeFixture.Variant) throws { + let machOFile = try LocalTypeFixture.machOFile(variant) + var qualifiedNames: [String] = [] + for descriptor in try Self.localTypeDescriptors(in: machOFile) { + let node = try SymbolicDemangler.demangleContext(for: descriptor, in: machOFile.context) + qualifiedNames.append(try #require(NodeTypeNaming.nominalQualifiedName(of: node), "\(Self.printedName(of: node)) has no qualified name")) + } + #expect(qualifiedNames.count == 20) + #expect(Set(qualifiedNames).count == qualifiedNames.count, "\(qualifiedNames.sorted())") + } + + // MARK: - Opaque result types + + /// A generic method's opaque result type hangs off the method's anonymous + /// context. Its name is the method's: from the descriptor's own name in a + /// debug build, from the `MXX` symbol in an unstripped one. Both used to + /// fail for a method that is not private — the anonymous context was + /// dropped before the opaque type could ask it for its name. + @Test(arguments: [LocalTypeFixture.Variant.debugNames, .anonymousDescriptorSymbols, .unstripped]) + func opaqueResultTypeOfAGenericMethodIsNamedAfterTheMethod(variant: LocalTypeFixture.Variant) throws { + let machOFile = try LocalTypeFixture.machOFile(variant) + // Exported, so it survives every strip; a dylib's `__TEXT` sits at 0, + // so the symbol's value is the descriptor's offset. + let symbol = try #require(machOFile.symbols.first { $0.name.hasSuffix("6HolderV11opaqueValueyQrxlFQOMQ") }, "the fixture exports no opaque type descriptor for opaqueValue") + let descriptor = try OpaqueTypeDescriptor.resolve(at: symbol.offset, in: machOFile.context) + // The compiler's spelling: the descriptor symbol names the opaque type. + let compilerSpelled = try #require(try demangleAsNodeTransient(symbol.name).first(of: .opaqueReturnTypeOf)) + + let descriptorBuilt = try SymbolicDemangler.demangleContext(for: .opaqueType(descriptor), in: machOFile.context) + + #expect(descriptorBuilt.print(using: .default) == compilerSpelled.print(using: .default)) + } + + // MARK: - Helpers + + /// Every type context the fixture declares in a body, nested types of + /// local types included. + private static func localTypeDescriptors(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [ContextDescriptorWrapper] { + try machO.swift.typeContextDescriptors.map(\.asContextDescriptorWrapper).filter { try LocalTypeFixture.isDeclaredInABody($0, in: machO.context) } + } + + private static func localTypeNames(in machO: some MachOSwiftSectionRepresentableWithCache, context: some ReadingContext) throws -> [String] { + try localTypeDescriptors(in: machO).map { printedName(of: try SymbolicDemangler.demangleContext(for: $0, in: context)) } + } + + private static func expectCompilerSpelling(_ names: [String], variant: LocalTypeFixture.Variant, sourceLocation: SourceLocation = #_sourceLocation) throws { + let hiddenNames = names.filter { LocalTypeFixture.isCompilerSpelledHiddenName($0, of: variant) } + #expect(hiddenNames.count == 1, "\(names)", sourceLocation: sourceLocation) + #expect(names.filter { !LocalTypeFixture.isCompilerSpelledHiddenName($0, of: variant) }.sorted() == LocalTypeFixture.compilerSpelledNames(of: variant).sorted(), sourceLocation: sourceLocation) + } + + private static func nominal(of node: Node) -> Node { + var nominal = node + while nominal.kind == .global || nominal.kind == .type || nominal.kind == .typeMangling, let child = nominal.children.first { + nominal = child + } + return nominal + } + + private static func printedName(of node: Node) -> String { + nominal(of: node).print(using: .default) + } +} diff --git a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift index 336b07f29..4b2fb519a 100644 --- a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift @@ -114,21 +114,17 @@ struct SymbolicManglingIndexTests { /// Every `_symbolic` symbol is an answer the compiler wrote down in /// advance: the referent of a direct reference to a type or protocol /// descriptor is that descriptor's full name. `SymbolicDemangler` builds - /// the same name from the descriptors themselves, so the two must agree. - /// - /// Except, for now, for a type declared inside a function body: it sits in - /// an anonymous context standing for that function, which the compiler - /// spells (`DeferralState #1 in …deferCompletionUntil() -> () -> ()`) and - /// `SymbolicDemangler` drops, as it dropped a private type's discriminator - /// before the symbolic-mangling index. Recorded in the proposal's decision - /// log as a known difference, not fixed there. + /// the same name from the descriptors themselves, so the two must agree — + /// a type declared in a function body too (`DeferralState #1 in + /// …deferCompletionUntil()`), whose function the descriptors spell only as + /// an anonymous context (evolution proposal `local-type-context-names`). @Test(.enabled(if: runsOnMacOS26OrLater, "the anchor symbols ship with macOS 26's AppKit")) func descriptorBuiltNamesAgreeWithTheCompilersSpelling() throws { let machOFile = try Self.appKitFileInSystemCache() var visitedReferencedOffsets: Set = [] var comparedCount = 0 + var localTypeCount = 0 var mismatches: [String] = [] - var localTypeMismatches: [String] = [] for reference in SymbolicManglingIndex.shared.references(in: machOFile) where reference.kind == .directContextDescriptor { guard visitedReferencedOffsets.insert(reference.referencedOffset).inserted else { continue } let context: ContextDescriptorWrapper = try .resolve(at: reference.referencedOffset, in: machOFile.context) @@ -145,20 +141,16 @@ struct SymbolicManglingIndexTests { let compilerSpelledName = Self.printedName(of: referentNode) let descriptorBuiltName = try Self.printedName(of: SymbolicDemangler.demangleContext(for: context, in: machOFile.context)) comparedCount += 1 + if referentNode.first(of: .localDeclName) != nil { + localTypeCount += 1 + } if descriptorBuiltName != compilerSpelledName { - let mismatch = "descriptor \(descriptorBuiltName), compiler \(compilerSpelledName)" - if referentNode.first(of: .localDeclName) != nil { - localTypeMismatches.append(mismatch) - } else { - mismatches.append(mismatch) - } + mismatches.append("descriptor \(descriptorBuiltName), compiler \(compilerSpelledName)") } } #expect(comparedCount > 500, "AppKit on macOS 26 references hundreds of its own types and protocols directly") + #expect(localTypeCount > 0, "AppKit references a local type directly (DeferralState); without one the local leg is unproven") #expect(mismatches.isEmpty, "\(mismatches.count) of \(comparedCount) differ:\n\(mismatches.prefix(40).joined(separator: "\n"))") - withKnownIssue("SymbolicDemangler drops the function context of a type declared in a function body") { - #expect(localTypeMismatches.isEmpty, "\(localTypeMismatches.count) local types differ:\n\(localTypeMismatches.joined(separator: "\n"))") - } } // MARK: - Anchor symbols diff --git a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift new file mode 100644 index 000000000..b37cc3226 --- /dev/null +++ b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift @@ -0,0 +1,275 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDeclaration +@_spi(Support) import SwiftIndexing +@_spi(Support) import SwiftInterface +@testable import MachOTestingSupport + +/// Local types on the indexing and interface paths (evolution proposal +/// `local-type-context-names`). Named after their method, two methods' +/// `Visitor`s are two definitions: the indexer used to key both under +/// `Holder.Visitor`, keep the last one and file it twice under `Holder`. +/// In the interface a local type stays nested in its enclosing type, its +/// method named in a comment above it, and a reference to it in a type +/// position prints its declared name — the upstream-free printer used to +/// print nothing there. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct LocalTypeInterfaceTests { + private func fileBuilder(of variant: LocalTypeFixture.Variant) async throws -> SwiftInterfaceBuilder { + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: try LocalTypeFixture.machOFile(variant)) + try await builder.prepare() + return builder + } + + private func interface(of variant: LocalTypeFixture.Variant) async throws -> String { + try await fileBuilder(of: variant).printRoot().string + } + + private func inProcessInterface(of variant: LocalTypeFixture.Variant) async throws -> String { + let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: try LocalTypeFixture.loadedImage(variant)) + try await builder.prepare() + return try await builder.printRoot().string + } + + /// The block whose header line STARTS with `prefix`, through its closing + /// brace at the same indentation. + private func block(startingWith prefix: String, in interface: String) -> String? { + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0.hasPrefix(prefix) }) else { return nil } + let indentation = lines[start].prefix { $0 == " " } + guard let end = lines[start...].firstIndex(where: { $0 == "\(indentation)}" }) else { return nil } + return lines[start...end].joined(separator: "\n") + } + + // MARK: - Indexing + + /// Every local type is one definition, filed once under its enclosing + /// type. The two `Visitor`s used to collapse into one definition that + /// `Holder` listed twice. + @Test func everyLocalTypeIsIndexedOnceUnderItsEnclosingType() async throws { + let indexer = try await fileBuilder(of: .unstripped).indexer + let holder = try #require(indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == "Holder" }) + let childNames = holder.typeChildren.map(\.typeName.declaredNameForTesting) + + #expect(childNames.sorted() == ["Box", "Generator", "Hidden", "InClosure", "Key", "Key", "Lookup", "Mode", "Payload", "Twin", "Twin", "Visitor", "Visitor", "WrappingGenerator"]) + #expect(Set(holder.typeChildren.map { ObjectIdentifier($0) }).count == holder.typeChildren.count, "a definition is listed twice") + // Holder, its fourteen local types, the four types nested in them, the + // two local types outside `Holder`, and the twins `KeyTwin`, + // `PayloadTwin` with its `CodingKeys`, and `LookupTwin`. + #expect(indexer.allTypeDefinitions.count == 25) + } + + /// A `~Copyable` generic parameter makes the compiler name a type's + /// members as if they sat in an extension with the inverse requirement; + /// that extension must extend the very name the type is indexed under, + /// or a host looking the type up by the extension's name (RuntimeViewer + /// does) lists it as a stray extension. + @Test func inverseExtensionOfANestedLocalTypeExtendsTheIndexedName() async throws { + let indexer = try await fileBuilder(of: .unstripped).indexer + let visitor = try #require(indexer.allTypeDefinitions.keys.first { $0.declaredNameForTesting == "IndexWrappingVisitor" }) + + #expect(indexer.typeExtensionDefinitions.keys.contains { $0.name == visitor.name }, "no extension extends \(visitor.name)") + #expect(visitor.name.hasPrefix("IndexWrappingVisitor in WrappingGenerator #1 in ")) + } + + // MARK: - Conformance members + + /// A local type of the fixture, its twin declared outside any body, and + /// the standard-library protocols both conform to — each type by the name + /// its conformance extensions are filed and printed under. + private struct TwinConformances { + let localTypeName: String + let twinName: String + let protocolNames: [String] + } + + private static func twinConformances(moduleName: String) -> [TwinConformances] { + let hashableProtocolNames = ["Swift.Hashable", "Swift.Equatable"] + return [ + TwinConformances(localTypeName: "Key #1 in \(moduleName).Holder.keyFromGetter.getter : Any", twinName: "\(moduleName).KeyTwin", protocolNames: hashableProtocolNames), + TwinConformances(localTypeName: "Key #1 in static \(moduleName).Holder.keyFromStaticMethod() -> Any", twinName: "\(moduleName).KeyTwin", protocolNames: hashableProtocolNames), + TwinConformances(localTypeName: "Payload #1 in \(moduleName).Holder.payload() throws -> Any", twinName: "\(moduleName).PayloadTwin", protocolNames: ["Swift.Encodable", "Swift.Decodable"]), + TwinConformances( + localTypeName: "CodingKeys in Payload #1 in \(moduleName).Holder.payload() throws -> Any", + twinName: "\(moduleName).PayloadTwin.CodingKeys", + protocolNames: hashableProtocolNames + ["Swift.CodingKey", "Swift.CustomStringConvertible", "Swift.CustomDebugStringConvertible"] + ), + TwinConformances( + localTypeName: "Lookup #1 in \(moduleName).Holder.lookup(named: Swift.String, at: Swift.Int) -> Any", + twinName: "\(moduleName).LookupTwin", + protocolNames: hashableProtocolNames + ), + ] + } + + /// The member lines of `extension : `, trimmed + /// and sorted; `nil` when the interface prints no such extension. + private func members(ofExtensionOf typeName: String, conformingTo protocolName: String, in interface: String) -> [String]? { + let header = "extension \(typeName): \(protocolName) {" + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false) + guard let start = lines.firstIndex(where: { $0 == header || $0 == header + "}" }) else { return nil } + guard lines[start] == header, let end = lines[start...].firstIndex(of: "}") else { return [] } + return lines[(start + 1).. [String] { + block.split(separator: "\n").dropFirst().dropLast().map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }.sorted() + } + + /// A local type's context comes first in each of its members' names. The + /// method declaring `Lookup`, `lookup(named:at:)`, put its label list and + /// argument tuple there, and the getter declaring `Key` its accessor. Read + /// as the member's own, they kept the synthesized `hash(into:)` in + /// `Lookup`'s body (its labels read `named:at:`), lost + /// `@dynamicMemberLookup` (the subscript's first label read `named`), gave + /// `combine(_:_:_:)` one unnamed label per parameter of the method — two + /// for three — and printed `Key`'s `static var shared` as a computed + /// property, its storage symbol read as a getter. Each twin prints the + /// same members, its own name in them read as the local type's. + private func expectLocalTypeBodiesMatchTheirTwins(in interface: String, moduleName: String) throws { + for twinBody in Self.twinBodies { + let afterComment = try #require(interface.components(separatedBy: "\n // \(twinBody.comment)\n").dropFirst().first, "no \(twinBody.comment) in\n\(interface)") + let localTypeBlock = try #require(block(startingWith: " struct \(twinBody.localTypeName) {", in: afterComment), "\(afterComment)") + let twinBlock = try #require(block(startingWith: "struct \(twinBody.twinName) {", in: interface), "\(interface)") + + #expect(memberLines(of: localTypeBlock) == memberLines(of: twinBlock).map { $0.replacingOccurrences(of: "\(moduleName).\(twinBody.twinName)", with: twinBody.localTypeName) }, "\(localTypeBlock)\n\(twinBlock)") + } + #expect(interface.contains("\n // Lookup #1 in Holder.lookup(named:at:)\n @dynamicMemberLookup\n struct Lookup {\n"), "\(interface)") + #expect(interface.contains("\n@dynamicMemberLookup\nstruct LookupTwin {\n"), "\(interface)") + } + + @Test func localTypeBodiesPrintLikeTheirTwinsOffline() async throws { + try expectLocalTypeBodiesMatchTheirTwins(in: try await interface(of: .unstripped), moduleName: LocalTypeFixture.Variant.unstripped.moduleName) + } + + @Test func localTypeBodiesPrintLikeTheirTwinsInProcess() async throws { + try expectLocalTypeBodiesMatchTheirTwins(in: try await inProcessInterface(of: .unstripped), moduleName: LocalTypeFixture.Variant.unstripped.moduleName) + } + + // MARK: - The interface + + private func expectNamedLocalTypes(in interface: String) throws { + let holder = try #require(block(startingWith: "struct Holder {", in: interface), "\(interface)") + // Both `Visitor`s, each under the comment naming its method, with its + // own fields and members. + #expect(holder.contains("\n // Visitor #1 in Holder.countValues()\n struct Visitor {\n var count: Swift.Int\n"), "\(holder)") + #expect(holder.contains("\n // Visitor #1 in Holder.sumValues()\n struct Visitor {\n var sum: Swift.Int\n"), "\(holder)") + #expect(holder.components(separatedBy: "struct Visitor {").count - 1 == 2, "\(holder)") + #expect(holder.components(separatedBy: "func visit(_: Swift.Int)").count - 1 == 2, "\(holder)") + #expect(holder.contains("\n // Twin #1 in Holder.twins(_:)\n struct Twin"), "\(holder)") + #expect(holder.contains("\n // Twin #2 in Holder.twins(_:)\n struct Twin"), "\(holder)") + #expect(holder.contains("\n // Hidden #1 in Holder.hiddenValues()\n struct Hidden"), "\(holder)") + #expect(holder.contains("\n // InClosure #1 in closure #1 in Holder.valuesFromClosure()\n struct InClosure"), "\(holder)") + // In a type position, a local type is its declared name; a type + // nested in it is reached through that name. + #expect(holder.contains("var element: Generator.Element"), "\(holder)") + #expect(holder.contains("static func __derived_struct_equals(_: Visitor, _: Visitor) -> Swift.Bool"), "\(holder)") + // Outside any type: under the module, and in an extension of the + // type whose method declares it. + #expect(interface.contains("\n// TopLevel #1 in localTypeFixtureTopLevel()\nstruct TopLevel {"), "\(interface)") + let stringExtension = try #require(block(startingWith: "extension Swift.String {", in: interface), "\(interface)") + #expect(stringExtension.contains("\n // Wrapper #1 in String.localTypeFixtureWrapped()\n struct Wrapper"), "\(stringExtension)") + } + + @Test func interfaceNamesEachLocalTypesMethodOffline() async throws { + try expectNamedLocalTypes(in: try await interface(of: .unstripped)) + } + + @Test func interfaceNamesEachLocalTypesMethodInProcess() async throws { + try expectNamedLocalTypes(in: try await inProcessInterface(of: .unstripped)) + } + + /// With every name source stripped, the comment says the method is not + /// recorded instead of naming a wrong one, and the two `Visitor`s stay + /// two declarations. + @Test func strippedInterfaceSaysTheMethodIsNotRecorded() async throws { + let interface = try await interface(of: .stripped) + let holder = try #require(block(startingWith: "struct Holder {", in: interface), "\(interface)") + + #expect(holder.contains("\n // Local type in a function or closure the binary does not name\n struct Visitor {\n var count: Swift.Int\n"), "\(holder)") + #expect(holder.contains("\n // Local type in a function or closure the binary does not name\n struct Visitor {\n var sum: Swift.Int\n"), "\(holder)") + #expect(holder.components(separatedBy: "struct Visitor {").count - 1 == 2, "\(holder)") + #expect(!holder.contains(" in $"), "a position-based name leaked into a type position:\n\(holder)") + // An extension of such a type, or of one nested in it, keeps the + // position-based name: `Holder.WrappingGenerator.Counter` would name + // a member type the source never declared. + let moduleName = LocalTypeFixture.Variant.stripped.moduleName + #expect(interface.contains("\nextension \(moduleName).Holder.(Visitor in $"), "\(interface)") + #expect(interface.contains("\nextension \(moduleName).Holder.(WrappingGenerator in $"), "\(interface)") + #expect(!interface.contains("\nextension \(moduleName).Holder.WrappingGenerator."), "\(interface)") + } +} diff --git a/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt b/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt index 4876e20f4..78d069367 100644 --- a/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt +++ b/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt @@ -2264,10 +2264,13 @@ enum MetatypeUsage { } enum NestedFunctions { struct NestedFunctionHolderTest { + // LocalClass #1 in NestedFunctions.NestedFunctionHolderTest.outerWithLocalClass() class LocalClass { // Field offset: 0x10 // Type Layout: (size: 16, stride: 16, alignment: 8, extraInhabitantCount: 2147483647) var label: Swift.String + + deinit } func outerWithLocalClass() -> Swift.String } From 2cdbbdc9107d4dd219da2288979dc3b351a5345d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 07:44:10 +0800 Subject: [PATCH 31/49] docs: document local type names and propose local-type-context-names - The proposal, with the three choices the user made: local types stay nested in their outer type, the interface prints their short name with a comment naming the function, and a local type no source names gets a position-based name. - SymbolicManglingSymbols: `_symbolic` symbols are one of three sources of a local type's name, and the AppKit known issue is gone. - Glossary: position-based name. - AGENTS.md: an anonymous context's name is the compiler's whole mangling, and a whole-tree search over a member node meets its context first (memberSubtree, accessorKind). - ReviewAdjudications A60: three searches of that shape left as they are. - swift-section agent skill: how dump and interface spell local types, and why snapshot format 7 rejects format-6 baselines. - FixtureTestingAndContinuousIntegration: re-record a snapshot by deleting its file; the suites' `.snapshots(record: .missing)` overrides SNAPSHOT_TESTING_RECORD. - The 2026-09-24 roadmap entry, the evolution log and MachOCaches follow. --- AGENTS.md | 5 +- .../skills/swift-section-cli/SKILL.md | 14 +- Documentations/Evolutions/README.md | 1 + .../draft-local-type-context-names.md | 123 ++++++++++++++++++ Documentations/Glossary.md | 7 + .../FixtureTestingAndContinuousIntegration.md | 6 +- .../Internal/Modules/MachOCaches.md | 2 +- .../Internal/ProjectEvolutionLog.md | 25 ++++ .../Internal/ReviewAdjudications.md | 21 +++ .../Internal/SymbolicManglingSymbols.md | 11 +- Documentations/README.md | 1 + .../2026-09-24-local-type-context-names.md | 12 +- 12 files changed, 214 insertions(+), 14 deletions(-) create mode 100644 Documentations/Evolutions/draft-local-type-context-names.md diff --git a/AGENTS.md b/AGENTS.md index 22153f4f6..3a3e87ff3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,7 +44,7 @@ One or two lines each; the linked document is the authority. - **Demangling** (upstream package) — mangled symbol → `Node` AST → printed Swift, plus the remangler. `Node.Kind` covers ~200 mangling node kinds. - **MachOSwiftSection** — the ABI model: the `__swift5_*` sections, every descriptor shape in them, and Swift's position-independent relative pointers. Self-contained — `MachOBase` only, no symbol index, no demangler; a descriptor exposes an implementation's *offset* and `SwiftInspection` attributes the name ([SelfContainedABILayer.md](Documentations/Internal/SelfContainedABILayer.md)). -- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). +- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors, a local or private type's anonymous contexts named by `AnonymousContextNameIndex` and the descriptors' own symbols, and `LocalTypeNaming` telling a local type's name apart), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). - **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). @@ -181,11 +181,12 @@ A type with genuinely nothing to test goes on the sentinel allowlist with a type Each of these fails **silently**, and several produce a real, fully-qualified, *wrong* type rather than an error. -- **`Node` conforms to `Sequence`, and its iterator is `preorder()`, which yields the node itself first.** `for child in node` is the whole subtree, not the children — read as "the children", position 0 holds the parent and every later position holds the element to its left or a fragment of its subtree. Iterating where positions matter goes through `.children`; the kind-scoped helpers (`first(of:)` / `all(of:)` / `contains(_:)` / `filter(of:)`) are whole-tree searches by design and are right when that IS the intent. +- **`Node` conforms to `Sequence`, and its iterator is `preorder()`, which yields the node itself first.** `for child in node` is the whole subtree, not the children — read as "the children", position 0 holds the parent and every later position holds the element to its left or a fragment of its subtree. Iterating where positions matter goes through `.children`; the kind-scoped helpers (`first(of:)` / `all(of:)` / `contains(_:)` / `filter(of:)`) are whole-tree searches by design and are right when that IS the intent. **On a member's tree it rarely is**: a declaration's first child is its context, and a protocol witness names its conformance before the requirement, so a search reaches the context first — and a local type's context is the function, closure or getter declaring it. Searched whole, a local type's witnesses were filed as properties named after the getter or as `static`, their methods deduplicated down to one, the enclosing method's labels stood in for a member's, and a static stored property's storage read as a getter. Read a witness through `memberSubtree`, a declaration's labels or argument tuple from its own direct children, and an accessor as whichever comes first in preorder, an accessor or the member's own `variable` / `subscript` (`accessorKind`). - **A `DemangledSymbol` stored into the declaration model must be detached first** (`detachedFromSharedTable()`). One stored survivor pins the whole shared `SymbolTable`, defeating the per-image reclamation `removeSubIndexer(_:)` exists for. Do NOT detach on the query path. `SymbolTableRetentionTests` catches a forgotten seventh storing site. - **Any `Dictionary`/`Set` keyed on a `NodeReference` whose keys and lookups can come from different stores must key on `StructuralNodeReferenceKey`, never a bare `NodeReference`** — its intrinsic `Hashable` is store-identity based. Different stores are the norm within one image. Bare keys are safe only for grouping within a single `memberSymbols` batch. Symptoms of getting it wrong differ per site: a dropped `override` keyword, a discarded setter, a doubled `func`, a twice-claimed witness. - **Do NOT reintroduce `demangleAsNode` / `Node.create` on unbounded inputs.** Sources carries zero cached call sites; a tree that is consumed and dropped stays transient (`demangleAsNodeTransient` / `Node.createTransient`). - **A runtime metatype becomes a node only through `RuntimeTypeNameDemangling.node(forMetatype:)`, never bare `_mangledTypeName` + demangle.** The runtime spells a private type's anonymous context by its descriptor address, which the printers render as nothing or as `(unknown context at $…)` — a specialized header read `struct .WindowPortal<…>`, and a private type argument lost its module and every enclosing type. +- **An anonymous context's name is the compiler's whole mangling of what it stands for — a function, a closure, or the private or local type it wraps — never a fragment of it.** It comes from the descriptor's own name (debug builds only), the `$sMXX` symbol on the descriptor, or a `_symbolic` referent (`AnonymousContextNameIndex`); a private discriminator is read off the wrapped type's own `privateDeclName` and nothing else. Taking `first(of: .privateDeclName)` from the context's name borrowed an enclosing private function's discriminator and faked private types, and dropping the context lost every local type's function, so two methods' `Visitor`s merged into one definition. A local type no source names is position-named `Holder.(Visitor in $
)` — tell it from a private type with `localTypeNaming`, never by string ([draft-local-type-context-names](Documentations/Evolutions/draft-local-type-context-names.md)). - **Do NOT call bare `NodeReference(interning:)` on a batch path** — route through `InternedNodeReferenceCache`. - **A `_symbolic` symbol's referents are one mangling, not several.** The compiler appends them with one mangler, so a later referent reuses substitutions and words of the earlier ones (`7SwiftUI19_ConditionalContentV AA08ModifiedD0V`); demangled alone it fails or names something else. Take referents from `SymbolicManglingIndex.referentNode(of:in:)`, which demangles them together — and for the same reason never splice referents into the mangled name as text. - **Resolving one type's members/info/attributes must use the node-taking overloads** (`memberSymbols(of:for:node:in:)` and friends). The name-only forms flatten every sub-bucket on purpose: the name key is printed with `.interfaceTypeBuilderOnly`, which strips private discriminators, so same-named private types share a bucket (issue #115). diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index fc18c43fc..81c5fb7fa 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -241,7 +241,10 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 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 of its local symbols the newer tool also records the class members that only their method - descriptor names (see §9), which an old baseline would report as added wholesale. + descriptor names (see §9), which an old baseline would report as added wholesale. Format 7 + 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. ## 8. `--resolve-c-module-names` (interface, macOS only) @@ -284,6 +287,15 @@ Attribution against a non-macOS binary is limited (it warns and degrades rather and `-[Class selector]` comments use. **`@_objcRuntimeName(Name)`** is the same fact on a class with no Objective-C ancestor, where `@objc` would not be legal Swift (mostly the standard library) — not a typo. +- **A declaration under a comment like `// Visitor #1 in Holder.countValues()`** is a type + declared in a function or closure body. `interface` keeps it nested in the enclosing type + and prints its bare name wherever it is referenced (nothing outside the body can spell it), + so two methods' `Visitor`s are two declarations that only the comment tells apart; their + conformance extensions carry the compiler's full name + (`extension Visitor #1 in M.Holder.countValues() -> Any: P`), and `dump` declares the type + under that full name. **`(Visitor in $1a2b3c)`** is such a type in a binary stripped of every + record of its function: the `$` number is the address of the anonymous context descriptor + that wraps it — the runtime's own spelling — not a private discriminator. ## 10. Where the details live diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index d76297d39..2a4fee7f3 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -75,3 +75,4 @@ | [0060](0060-evolution-interface-available-annotations.md) | evolution 联合接口的 @available 生命周期标注(真属性 + 位图注释保留) | Implemented | | [0061](0061-dyld-shared-cache-path-versions.md) | 测试用的 dyld shared cache 路径按版本取 | Implemented | | draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | +| draft | [局部类型的名字:找回函数与闭包上下文](draft-local-type-context-names.md) | In Progress | diff --git a/Documentations/Evolutions/draft-local-type-context-names.md b/Documentations/Evolutions/draft-local-type-context-names.md new file mode 100644 index 000000000..6ebbf8aad --- /dev/null +++ b/Documentations/Evolutions/draft-local-type-context-names.md @@ -0,0 +1,123 @@ +# Draft - 局部类型的名字:找回函数与闭包上下文 + +- **状态**: In Progress +- **创建日期**: 2026-10-10 +- **最后更新**: 2026-10-11 +- **所属愿景**: 无 +- **关联提案**: [0050-symbolic-mangling-symbol-index](0050-symbolic-mangling-symbol-index.md)(对照测试发现并登记了这个问题,`_symbolic` 符号是这里的来源之一) +- **实现分支 / PR**: `feature/local-type-context-names` +- **起因**: RuntimeViewer 会话在 macOS 27.2 的 SwiftUI 上复现并查清根因后转交;早先的记录在 [Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md) + +## 摘要 + +函数、闭包里声明的类型(local type)挂在一串 anonymous context 下面:类型本身、闭包、函数各一层(`lib/IRGen/GenDecl.cpp` 的 `getAddrOfContextDescriptorForParent`)。release 构建不给这些 anonymous context descriptor 写名字,所有系统框架和测试 fixture 都是 release 构建。`SymbolicDemangler` 于是只能二选一: + +- 把整串丢掉。局部类型变成了外层类型的成员,同一类型里不同函数的同名局部类型撞成一个名字。SwiftUI 的 `TableDataSource` 有 7 个 `Visitor`,其中 6 个都解成 `SwiftUI.TableDataSource.Visitor`,索引器按名字存定义,只留下最后一个,嵌套遍历又把它追加了 6 次。结果 interface 里 5 个类型丢失、1 个重复 6 遍。 +- 用 `first(of: .privateDeclName)` 从外围的 private 函数借来 private discriminator,把局部类型伪造成 private 类型,比如 `AccessibilityRotorInfo.(unknown context at _0306…).(IndexingWrappingGenerator in _0306…)`。 + +名字一错,用真名记录的成员符号就对不上,成员静默丢失。带扩展上下文的成员(`~Copyable` 泛型参数让成员落在一个 inverse 约束扩展里)会单独建一个 extension,RuntimeViewer 在顶层找不到同名类型,就把它列成一个孤立的 Ex。 + +debug 构建名字是有的(`-g -Onone` 时 driver 自动加 `-enable-anonymous-context-mangled-names`),但结果也会错。2025-05 的 `be2f186e` 把 anonymous context 从「保留成节点」改成了「直接丢掉」。`adoptAnonymousContextName` 后面那个判断要求父级是 anonymous context 节点才覆盖,此后只在外围函数恰好是 private、借到了 discriminator 时才成立。debug 版 swift-section 自己 dump 自己,`PendingRebuild #1 in getUnspecialized(_:)` 印成了 `PendingRebuild #1 in Demangling`,两个不同闭包里的 `VisitedPair` 撞成同一个名字。 + +本提案让 `SymbolicDemangler` 从三个来源找回局部类型的完整名字,三处都没有时按位置起一个不撞名的占位名;runtime 名字那条路同样处理;interface 打印器补上局部类型的写法。 + +## 方案 + +### 改动位置 + +- `Sources/Analysis/SwiftInspection/SymbolicDemangler.swift` + - `adoptAnonymousContextName`(`:544`)与 `demangleAnonymousContextName`(`:573`):anonymous context 的名字按三个来源依次取,见下一节。 + - `buildContextDescriptorMangling`(`:427`):采用了名字、而 anonymous context 上面还是 anonymous context(即局部类型)时,名字里的上下文(闭包、函数)整体代替那串 anonymous context,不再逐层构建它们;覆盖条件按描述符判断,不再看节点的 kind。三处都没有名字的局部类型,名字写成 `PrivateDeclName("$<地址>", 名字)`。 + - `resolvedPrivateDiscriminatorIdentifier`(`:110`)与 `.anonymous` 分支(`:490`):private discriminator 只取被包着的类型自己的 private 名字,不再从外围函数借。 + - `.opaqueType` 分支(`:508`):同一个「看节点 kind」的判断改成按描述符判断,名字同样走三个来源。不改的话,debug 构建里 private 泛型函数的 opaque type 会因为上一条而丢名字。 +- `Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift`:被引用者的名字是 `localDeclName` 时,把编译器写下的完整名字也记下来(`:131` 以前一律放弃)。类改名为 `AnonymousContextNameIndex`,它记的已经不只是 discriminator。 +- `Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift`(`:59`–`:107`):runtime 用 `$地址` 表示的 anonymous context 走同一套来源;局部类型的整串 anonymous context 由名字里的上下文代替;找不到名字的局部类型用同样的占位名。 +- `Sources/Analysis/SwiftInspection/LocalTypeNaming.swift`(新增,公开):`Node.localTypeNaming` / `NodeReference.localTypeNaming` 判断一个名字是不是局部类型、名字是编译器给的(`.compilerSpelled`)还是按位置起的(`.positionBased`)。打印器用它,RuntimeViewer 做 Local 标签、从 Private 标签里排除占位名也用它,不必自己按 `$` 猜。 +- `Sources/Analysis/SwiftInspection/NodeTypeNaming.swift`(`qualifiedName(ofNominal:)`、`declaredName(of:)`):静态布局引擎和 ObjC 那边按这个限定名给类型建索引、按名字查字段类型。局部类型的限定名以前只算得出光秃秃的 `Visitor`(函数上下文没有前缀),不同函数里的同名局部类型撞键;改成带上声明它的函数和 `#序号`,按位置命名的带上 `$` 地址。 +- `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift`(`printType`,`:156`):类型位置上的局部类型印短名。现在函数、闭包这类上下文和 `localDeclName` 都印成空,debug 版 interface 里已经有 `__derived_struct_equals(_: , _: )`。 +- `Sources/Output/SwiftDiffing/ABISnapshotDocument.swift`:`currentFormatVersion` 6 → 7,理由见决策日志。 +- `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift`(`printIncludedTypeDefinition`)与 `SwiftDeclarationPrinter+Headers.swift`:局部类型的声明前加一行注释,写出它在哪个函数里;按位置命名的局部类型(以及嵌在它里面的类型)的 extension 头印带 `$` 的全名,否则会读成 `Holder.Visitor` 这种源码里没有的成员类型路径。diff / evolution 渲染器自己拼声明头,这批不加注释。 +- 名字对上之后才暴露的五处整树搜索。成员节点的第一个子节点是上下文,witness 还把 conformance 排在 requirement 前面,前序搜索于是先碰到局部类型的外层声明。以前局部类型的名字对不上,这些符号从来匹配不到,问题一直藏着: + - `Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+MemberSubtree.swift`(新增)、`MemberSymbolBucketing.swift`(`addSymbol`)、`DefinitionBuilder.swift`:conformance 成员只按 witness 的 requirement 分类、去重。否则声明在 getter 里的类型,witness 全被当成以 getter 命名的属性丢掉;`static` 方法里的类型,witness 全进 `static` 桶;方法类 witness 都按外层函数去重,只剩一个(SwiftUI 的 `CodingKeys`、`HostKeys` 少了 `_rawHashValue`、`init?(intValue:)`、`_updateDefault` 等)。 + - `TypeDefinition+SynthesizedMembers.swift`(`labels(of:)`):取成员自己声明节点上的标签。否则外层函数的标签顶替成员的,合成的 `hash(into:)`、`encode(to:)` 去不掉,在主体里重复出现。 + - `Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift`(`hasDynamicMemberSubscript`):取下标节点自己的标签,否则推断不出 `@dynamicMemberLookup`。 + - `Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift`(`printLabelList`):参数全是匿名时,`_` 标签的个数按成员自己的参数元组定,不再按外层函数的。 + - `Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift`(`accessorKind`):前序遍历里先碰到访问器还是先碰到成员自己的 `variable` / `subscript`,以先碰到的为准。否则声明在 getter 里的类型,它的 `static` 存储属性的存储符号被读成 getter,打印成 `{ get set }` 的计算属性。 + +### 明确不动 + +ABI 层(`MachOSwiftSection`)、符号索引(`MachOSymbols`)、索引器的嵌套遍历(`SwiftDeclarationIndexer.swift:525`,局部类型照旧挂在外层类型下,见决策日志)、RuntimeViewer 仓库。同类整树搜索里还有三处不改:`final` 恢复的 `Tq` 兜底、上游的 `DemanglingNode.identifier`、`DefinitionBuilder` 挑变量代表节点的那一步,理由见 [ReviewAdjudications A60](../Internal/ReviewAdjudications.md)。 + +### 名字从哪来 + +一个 anonymous context 的名字,就是编译器给它的 mangling(`IRGenMangler.h` 的 `mangleAnonymousDescriptorName`)。包着类型的那一层,名字就是类型自己的完整名字,比如 `Visitor #1 in TableDataSource.performDrop(to:)`。三个来源依次试: + +1. **描述符自带的名字**:只有 `-enable-anonymous-context-mangled-names` 时才写,也就是 debug 构建。 +2. **anonymous descriptor 上的符号**:`$s<上下文>MXX`(`mangleAnonymousDescriptor`),解出来是 `AnonymousDescriptor(<上下文>)`,剥掉这一层就和第 1 条相同。没剥本地符号的镜像都有:缓存里的 SwiftUI、SwiftUICore,测试 fixture。缓存里的 AppKit 一个都没有。 +3. **`_symbolic` 符号**:有字段描述符的类型,编译器都会给它的类型名记一个 `_symbolic` 符号,里面是完整名字。剥了本地符号的系统框架照样留着它(AppKit 就靠它)。它按类型描述符记,所以只覆盖直接包着类型的那一层。 + +都没有时(主要是 strip 过的第三方 App),按 runtime 和 Remote Mirror 的做法用位置起名:`TableDataSource.(Visitor in $1a2b3c)`。数字是包着类型的那个 anonymous context 的地址,口径与 dump 的成员地址注释相同(`address(forOffset:)`:缓存镜像取未滑动的虚拟地址,独立文件取 vmaddr),所以 `MachOFile` 与进程内两条路径的名字一样。这个名字不撞名、不丢类型,只是看不出在哪个函数里。它借用 `privateDeclName` 的形状,是因为这个形状每个下游都已经会处理;`$` 开头的 discriminator 不是真的,RuntimeViewer 的 Private 标签要用 `localTypeNaming == .positionBased` 把它排除。 + +匿名上下文的名字以后只整体使用:采用名字时,类型自己的名字(`localDeclName` 或 `privateDeclName`)连同名字里的上下文一起用;private discriminator 只从「被包着的类型自己的 `privateDeclName`」取,函数、闭包的名字里有 `privateDeclName` 也不取。进程内按地址查名字要扫整张符号表,所以和 discriminator 一样按地址记忆。 + +### 输出 + +dump 的声明头打印完整名字,debug 构建今天就是这样: + +```swift +struct Visitor #1 in SwiftUI.TableDataSource.performDrop(to: SwiftUI.DropCoordinator) -> () { +``` + +interface 里局部类型照旧嵌在外层类型里,声明前加一行注释写出所在函数,参数、字段这些类型位置印短名 `Visitor`,conformance 的 extension 头保留编译器全名。下面是 `TableDataSource` 的头两个 `Visitor`,字段从略: + +```swift +struct TableDataSource { + // Visitor #1 in TableDataSource.performDrop(to:) + struct Visitor: ~Swift.Copyable { + … + } + // Visitor #1 in TableDataSource.itemProvider(at:) + struct Visitor: ~Swift.Copyable { + … + } +} +``` + +### 测试 + +- 仿照 `RenamedObjCClassFixture` 在测试里现场编一个局部类型 fixture(`LocalTypeFixture`)。五个变体各用自己的模块名,可以同时加载进测试进程;前三个各只留一个名字来源: + - `debugNames`:`-Xfrontend -enable-anonymous-context-mangled-names` 编译后 `strip -x`,只有描述符自带的名字; + - `anonymousDescriptorSymbols`:只保留导出符号、导入符号和 `MXX`; + - `symbolicReferences`:只保留导出符号、导入符号和 `_symbolic`,AppKit 就是这个形状; + - `unstripped`:一个符号都不剥,SwiftUI 在 cache 里就是这个形状,也是唯一留着成员符号的变体,用来验证成员能挂回类型; + - `stripped`:`strip -x`,三处都没有。 + + `strip -R` 只能删全局符号,删不掉 `MXX` 这种本地符号,所以只留一部分本地符号的两个变体用 `strip -s <保留清单>`;它只留得住原本是 private extern 的本地符号(`MXX`、`_symbolic` 是,成员实现符号不是)。strip 会让签名失效,每个变体都用 `codesign --force --sign -` 重签,才能 `dlopen`。形状覆盖 private 与非 private 的外围函数、闭包、同一类型里不同函数的同名局部类型、同一函数里的 `#1` 与 `#2`、局部类型里的嵌套类型、`~Copyable` 泛型参数让成员落在扩展上下文里、另一个模块的类型的 extension 里的局部类型、顶层函数里的局部类型、泛型函数的 opaque type。`MachOFile` 与进程内两条路径都跑,runtime 名字那条路也跑。 +- 成员的测试拿局部类型和声明在任何函数体之外的「孪生」类型对照(`KeyTwin`、`PayloadTwin`、`LookupTwin`):声明在 getter、`static` 方法、`throws` 方法、带标签的方法里的局部类型,每个 conformance 列出的成员、成员所在的数组(实例 / `static`、函数 / 属性 / 初始化器)、主体里的成员(含 `static` 存储属性)和 `@dynamicMemberLookup` 都要与孪生类型相同。期望值来自孪生类型,不来自被测代码对局部类型的输出。 +- `SymbolicManglingIndexTests.descriptorBuiltNamesAgreeWithTheCompilersSpelling` 去掉 `withKnownIssue`:AppKit 里被直接引用的局部类型,从描述符还原的名字要与编译器写的一致。 +- SymbolTestsCore 里本来就有一个局部类型(`outerWithLocalClass()` 里的 `LocalClass`),它的 dump 与 interface 快照重新生成。 +- 系统框架 dump / interface 的 A/B 对比:差异只能是局部类型的名字、interface 里局部类型的写法,以及因此挂回来的成员。结果是 96 对里 30 对有差异,全在 SwiftUI / SwiftUICore,逐对核对都来自局部类型,没有一对少了成员;当前系统的 AppKit 只有 3 个局部类型变化。明细见 [ProjectEvolutionLog](../Internal/ProjectEvolutionLog.md) 本批一节。 + +### 已知限制 + +- 占位名看不出在哪个函数里。strip 过的 App 里,局部 class 的 ObjC 运行时名(`_TtCF…`,旧 mangling)其实带着函数上下文,可以作为第四个来源,本提案不做。 +- 局部类型不会出现在泛型上下文里(编译器报 `type '…' cannot be nested in generic function`),所以离线特化不会遇到「局部类型外面的函数带实参」这种名字;局部类型里面可以有泛型类型(SwiftUI 的 `IndexWrappingVisitor`),它的参数是自己的,按普通嵌套类型处理。 +- dump 的声明头先印名字、再接泛型参数,泛型局部类型于是读成 `IndexWrappingVisitor in WrappingGenerator #1 in M.Holder.wrapping() -> Swift.Bool`,`` 像是挂在 `Bool` 上。debug 构建早就是这样,属于 dump 拼声明头的既有写法,这批不改。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-10 | 创建为 Draft,用户批准后直接置为 In Progress | RuntimeViewer 会话转交的调查结果,用户要求接手修复。 | +| 2026-10-10 | 局部类型照旧挂在外层类型下,不提到顶层 | 用户选择。与 debug 构建今天的行为一致,索引器不用改;RuntimeViewer 侧边栏默认也挂在外层类型下,那边再加 Local 标签。 | +| 2026-10-10 | interface 里类型位置印短名,声明前加注释写出所在函数,extension 头保留编译器全名 | 用户选择。编译器全名太长,也不是合法 Swift;只印短名又分不清同名的几个,注释补上这一点。 | +| 2026-10-10 | 三个来源都没有时按位置起占位名,不维持现状 | 用户选择。现状会让同名局部类型互相覆盖,丢类型;占位名照 runtime 和 Remote Mirror 的做法,不撞名,代价是 RuntimeViewer 的 Private 标签要排除 `$` 开头的 discriminator。 | +| 2026-10-10 | `AnonymousContextPrivateDiscriminatorIndex` 改名为 `AnonymousContextNameIndex` | 它要记局部类型的完整名字,不只是 discriminator;`package` 级,不影响公开 API。 | +| 2026-10-10 | 删掉「泛型函数里的局部类型做离线特化」这条已知限制 | 试编 fixture 时编译器报 `type '…' cannot be nested in generic function`:局部类型根本不会出现在泛型上下文里。 | +| 2026-10-10 | fixture 加第五个变体 `unstripped` | `strip -s` 只留得住原本是 private extern 的本地符号(`MXX`、`_symbolic`),成员实现符号留不住,「只有 `MXX`」的变体里成员就没了;成员归属的测试改用不剥的变体。 | +| 2026-10-11 | 新增公开的 `LocalTypeNaming` | 打印器要分辨局部类型;RuntimeViewer 的 Local / Private 标签也要分辨,给一个受支持的接口,免得下游按 `$` 前缀猜。 | +| 2026-10-11 | `NodeTypeNaming` 的限定名一并改为带函数上下文 | 横向排查同类问题时发现:静态布局引擎按限定名建索引、按名字查字段类型,局部类型的限定名退化成光秃秃的 `Visitor`,同名的撞键。修复前同样撞(当时是 `M.Holder.Visitor`),属于同一类。 | +| 2026-10-11 | ABI snapshot `formatVersion` 6 → 7 | snapshot 记录全部类型,容器键是类型名的 mangling;局部类型改名后,旧基线对比新工具会把每个局部类型连同成员、conformance 报成删掉再加上,删掉类型算破坏性变更,`--fail-on-breaking` 的 CI 会误报失败。照 v6 的先例(记录方式变了、键格式没变也提升)提升,让旧基线以明确的错误被拒。 | +| 2026-10-11 | 成员分类、去重、三处标签读取和访问器种类改为只看成员自己的节点 | 系统框架 A/B 里 iOS 26.5 模拟器那条腿的 SwiftUICore 少了 conformance 成员(`_rawHashValue`、`_updateDefault`、`CodingKeys` 的初始化器)。基线里名字对不上,witness 符号匹配不到,退回按 requirement 打印,反而完整;名字对上以后拿到真正的 witness 符号,整树搜索就先碰到了外层声明。横向排查又找到四处同类,都用 fixture 复现、先红后绿。 | +| 2026-10-11 | `final` 恢复的 `Tq` 兜底、上游 `DemanglingNode.identifier`、变量的代表节点不修,登记 ReviewAdjudications A60 | 第一处被按节点的 descriptor 连接挡在前面,第三处因为符号表里 getter 总在最前,都造不出会变红的测试;第二处在上游包里,要局部类型声明在运算符函数里才触发。 | +| 2026-10-11 | 测试里 `__derived_struct_equals(Visitor, Visitor)` 的期望改为 `(_: Visitor, _: Visitor)` | 当时把无标签的输出当成打印器的既有写法;其实是 `printLabelList` 按外层函数 `countValues()` 的空参数元组算标签,与孪生类型对照后确认是错的。 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 4cb6873c1..39da9d33c 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -276,6 +276,13 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift`(`row(forName:)`) - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) +### position-based name(按位置起的名字) + +函数或闭包里声明的局部类型,在二进制里找不回所在函数时用的名字:`Holder.(Visitor in $1a2b3c)`。局部类型的函数名有三个来源——描述符自带的名字(只有 debug 构建写)、匿名描述符的 `$s<上下文>MXX` 符号、`_symbolic` 符号——三处都没有(典型是 strip 过的 App)时,`SymbolicDemangler` 照运行时和 Remote Mirror 的做法,用包着该类型的那个匿名上下文的地址起名,挂在最近一个能叫出名字的上下文下面。地址的口径与 dump 的成员地址注释相同,所以同一个镜像从文件读和在进程内读得到同一个名字。它借用 `privateDeclName` 的形状,但类型不是 private,`$` 开头的部分也不是鉴别符;判断用 `LocalTypeNaming.positionBased`,不要按字符串猜。 + +- **主要出现在**:`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`(`positionNameOfUnnamedLocalType`)、`Sources/Analysis/SwiftInspection/LocalTypeNaming.swift`、`Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift` +- **延伸阅读**:[提案 local-type-context-names](Evolutions/draft-local-type-context-names.md) + ### renamed class(改名类,`@objc(Name)` / `@_objcRuntimeName(Name)`) 源码给 ObjC 运行时另起了名字的 Swift 类:类对象的 `class_ro_t` 名是源码写的名字(`NSScrollPocket`),而不是 `_TtC6AppKit14NSScrollPocket` 这样的 mangling。二进制里只剩类元数据 flag 字里的 `HasCustomObjCName` 与名字本身,`SwiftClassObjectIndex` 顺着类元数据自带的描述符指针把它们配到 Swift 类上(父类在另一个 resilience domain、不进 classlist 的类读 metadata pattern)。本仓库凡是「demangle 运行时名找 Swift 类」的地方都要为它回退,否则一律配不上——成员恢复与布局引擎以前就是这样漏掉它们的。interface 与 dump 打印 `@objc(Name)`,原生 Swift 对象模型的类打印 `@_objcRuntimeName(Name)`。 diff --git a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md index abe763f30..798226fc6 100644 --- a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md +++ b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md @@ -159,8 +159,10 @@ allowlist 并填 reason」,实施时被偷换成永远通过的 sentinel 测 | 远端依赖 pin 版本缺新 API | 升 `Package.swift` pin | | runner 上 fixture 产物路径与本地布局不同 | "Normalize SymbolTestsCore fixture path" 符号链接步骤 | -- **无自动重录 workflow**:快照漂移永远由开发者本地 `SNAPSHOT_TESTING_RECORD=all` 重录、 - 人工 review 后与触发变更同 PR 提交。CI 的 `xcode-version` 永远显式 pin,不用 `latest-stable`—— +- **无自动重录 workflow**:快照漂移永远由开发者本地重录、人工 review 后与触发变更同 PR 提交。 + 重录要删掉旧的快照文件再跑,让 `record: .missing` 补写:两个快照套件都带 suite trait + `.snapshots(record: .missing)`,它盖过 `SNAPSHOT_TESTING_RECORD=all` 环境变量,设了也不重录 + ([TaskReports/2026-08-22](TaskReports/2026-08-22-final-keyword-and-lazy-accessor-recovery.md) 的勘误)。CI 的 `xcode-version` 永远显式 pin,不用 `latest-stable`—— 任何 bump 都应是有意的、可 review 的变更(工具链升级可能合法地改变发出的元数据与 section 顺序, 后者由 linker 决定,同工具链内稳定)。 diff --git a/Documentations/Internal/Modules/MachOCaches.md b/Documentations/Internal/Modules/MachOCaches.md index ec03a3cff..d88a17fb8 100644 --- a/Documentations/Internal/Modules/MachOCaches.md +++ b/Documentations/Internal/Modules/MachOCaches.md @@ -82,7 +82,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { | `objcImplementationClasses`(SwiftInspection) | `ObjCImplementationClassIndex`(持有指向符号表 arena 的 `NodeReference`) | `symbolStore` | | `objcHierarchy`(SwiftInspection) | `ObjCClassMethodIndex`、`SwiftClassObjectIndex`、`ObjCClassHierarchyProviderStore`(宿主的弱引用注册,手工遵循 `SharedCacheEvicting`) | `symbolStore` | | `objcAncestorResolver`(SwiftInspection) | `ObjCAncestorResolverStore` | `symbolStore` | -| `demangleMemo`(SwiftInspection) | `SymbolicDemanglerCache`、`AnonymousContextPrivateDiscriminatorIndex` | `internedNames` | +| `demangleMemo`(SwiftInspection) | `SymbolicDemanglerCache`、`AnonymousContextNameIndex` | `internedNames` | | `propertyWrapperCatalog`(SwiftDeclarationRendering) | `PropertyWrapperTypeCatalogStore` | — | | `multiPayloadEnumDescriptors`(SwiftDeclarationRendering) | `MultiPayloadEnumDescriptorCache` | — | | `dependentMemberProjection`(SwiftDeclarationRendering) | `DependentMemberProjection` 的两个实例 | — | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 98d45f401..d3db190e5 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2370,6 +2370,31 @@ - **关联文档**:review 记录;[ReviewAdjudications.md](ReviewAdjudications.md) A53–A59;四份提案的决策日志([并发打印](../Evolutions/draft-concurrent-definition-printing.md)、[离线特化](../Evolutions/draft-offline-generic-specialization.md)、[嵌套定义区域](../Evolutions/draft-nested-definition-regions.md)、[嵌套偏移记忆化](../Evolutions/draft-nested-field-offset-memoization.md));[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md)、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、[Modules/MachODependencies.md](Modules/MachODependencies.md)。 - **对应版本**:0.22.0(未发版),随 PR #131 合入。 +## 2026-10-10 局部类型的名字:找回函数与闭包上下文(节号落地时分配) + +- **时间段**:2026-10-10 — 2026-10-11。 +- **动机**:RuntimeViewer 会话在 macOS 27.2 的 SwiftUI 侧边栏里看到一行孤立的 Ex(`IndexWrappingVisitor in IndexingWrappingGenerator #1 in closure #1 … in AccessibilityRotorInfo.readEntryList(…)`),追下去是函数、闭包里声明的局部类型名字全错:`TableDataSource` 的 7 个 `Visitor` 在 interface 里只剩 1 个、重复 6 遍;private 函数里的局部类型被伪造成 private 类型;成员符号用真名记录,对不上错的名字,成员静默丢失。会话把调查结果转交过来,用户让这边接手修。这个问题 2026-09-24 已经记在 roadmap `2026-09-24-local-type-context-names` 里,当时只登记、没修。 +- **关键决策**: + - 匿名上下文的名字有三个来源,依次试:描述符自带的名字(只有 debug 构建写)、匿名描述符的 `$s<上下文>MXX` 符号(没剥本地符号的镜像,例如 cache 里的 SwiftUI)、`_symbolic` 符号(剥了本地符号的 AppKit 也还留着)。局部类型取到名字后,名字里的函数、闭包整体代替那串匿名上下文。 + - private discriminator 只从被包着的类型自己的名字取,不再用 `first(of: .privateDeclName)` 从外围函数借。 + - 三处都没有时,照 runtime 和 Remote Mirror 的做法用匿名上下文的地址起名:`Holder.(Visitor in $1a2b3c)`(用户选择)。地址口径与 dump 的成员地址相同,所以文件和进程内读出同一个名字。 + - 局部类型照旧挂在外层类型下(用户选择)。interface 里声明前加一行注释写出所在函数,参数、字段这些类型位置印短名,conformance 的 extension 头印编译器全名(用户选择)。 + - debug 构建也修了:`be2f186e`(2025-05)把匿名上下文改成直接丢掉之后,采用名字只在外围函数恰好是 private 时才接得上函数。`.opaqueType` 分支是同一个原因,一起改成按描述符判断。 + - 横向排查:`NodeTypeNaming` 的限定名(静态布局引擎、ObjC 那边按它建索引)对局部类型退化成光秃秃的短名,光改解名器的话 `Holder` 里十个局部类型的键全是 `"Holder"`,比修复前还糟,一起改成带上声明它的函数和 `#序号`。 + - ABI snapshot `formatVersion` 6 → 7:snapshot 记录全部类型、按名字的 mangling 作键,旧基线会把每个局部类型报成删掉再加上,删掉类型算破坏性变更。 + - 名字对上之后暴露出五处整树搜索,一起修掉:成员节点的第一个子节点是上下文,witness 还把 conformance 排在 requirement 前面,前序搜索先碰到局部类型的外层声明。A/B 的 iOS 26.5 模拟器腿里,SwiftUICore 的局部类型 conformance 少了 `_rawHashValue`、`_updateDefault`、`CodingKeys` 的初始化器:基线名字对不上,witness 符号匹配不到,反而退回按 requirement 打印出了全部成员。conformance 成员改按 witness 的 requirement(`memberSubtree`)分类、去重;主体里合成成员的去重、`@dynamicMemberLookup` 推断、匿名参数的 `_` 标签、访问器种类(getter 里的局部类型,`static` 存储属性被印成计算属性)改读成员自己的节点。`final` 恢复的 `Tq` 兜底、上游 `DemanglingNode.identifier`、变量的代表节点是同类但不修,登记 [ReviewAdjudications A60](ReviewAdjudications.md)。 +- **公开 API 与行为变化**(写进下个版本的发版说明):新增 `LocalTypeNaming` 与 `Node.localTypeNaming` / `NodeReference.localTypeNaming`。行为:局部类型的名字从 `Holder.Visitor` 变成 `Visitor #1 in Holder.countValues()`,没有来源时是 `Holder.(Visitor in $1a2b3c)`;dump、interface、`TypeName` 都跟着变;同一类型里同名的局部类型不再合并;它们的成员挂回来了;ABI snapshot 格式升到 7,旧基线要重新生成。 +- **落地模块**:SwiftInspection(`SymbolicDemangler`、`AnonymousContextNameIndex`(原 `AnonymousContextPrivateDiscriminatorIndex`)、`LocalTypeNaming`、`NodeTypeNaming`)、SwiftDeclaration(`DemanglingNode+MemberSubtree`、`DemanglingNode+AccessorKind`、`MemberSymbolBucketing`、`DefinitionBuilder`、`TypeDefinition+SynthesizedMembers`)、SwiftAttributeInference(`TypeAttributeInferrer`)、SwiftDeclarationRendering(`RuntimeTypeNameDemangling`)、SwiftPrinting(`TypeNodePrintable`、`FunctionTypeNodePrintable`、`SwiftDeclarationPrinter`、`SwiftDeclarationPrinter+Headers`)、SwiftDiffing(`ABISnapshotDocument`)、TestSupport(`LocalTypeFixture`)。 +- **验证**: + - 新增 `LocalTypeFixture`:测试里现场编译一份局部类型源码,五个变体各留一个名字来源(只有描述符名字、只有 `MXX`、只有 `_symbolic`、全不剥、全剥光)。四个新套件(`LocalTypeContextNameTests`、`LocalTypeInterfaceTests`、`LocalTypeDumpTests`、`RuntimeTypeNameLocalTypeTests`)先在未修改的代码上确认失败,修后全绿;`NodeTypeNaming` 的那条单独做了一次红绿。`SymbolicManglingIndexTests.descriptorBuiltNamesAgreeWithTheCompilersSpelling` 去掉 `withKnownIssue` 后在 macOS 27.2 的 AppKit 上通过(`DeferralState` 只能靠 `_symbolic` 找回)。四个新套件加进了 CI 的过滤清单。 + - 成员的对照测试:fixture 加了声明在 getter、`static` 方法、`throws` 方法、带标签的方法里的局部类型,各配一个声明在函数体之外的孪生类型,断言 conformance 成员(interface 文本与模型里的数组)、主体成员和 `@dynamicMemberLookup` 与孪生类型相同。五处整树搜索的修复各自先红后绿:修复前分别读出以 getter / 外层函数命名的成员、错进 `static` 桶、主体里多一份 `hash(into:)`、缺属性、`combine(_: Int, _: Int, Int)`、`static var shared: Int { get set }`。 + - SymbolTestsCore 的 dump 与 interface 快照只变了 `LocalClass` 一处:名字换成编译器全名,interface 加注释,以前丢掉的 `deinit` / deallocator 挂回来了。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,五个兄弟依赖都链本地):2383 个测试、455 个套件全部通过,原始退出码 0。 + - 系统框架 A/B(`Scripts/run-rendering-ab-verification.py`;基线是 next cd248de9 的 `git archive` 沙盒,两侧 release 预构建,共用同一份 `Package.resolved`):96 对里 30 对有差异,全部在 SwiftUI / SwiftUICore,逐对核对都来自局部类型——名字换成编译器全名,interface 加注释、conformance 的 extension 头印全名,以前丢掉的成员、字段和布局注释挂回来(`TableDataSource` 的 7 个 `Visitor` 各有自己的字段,基线是一份 `var result: SwiftUI.DeleteInteraction?` 印 6 遍)。按典型 witness 成员(`_rawHashValue`、`hash(into:)`、`_updateDefault`、`CodingKeys` 的初始化器等)计数,没有一对比基线少;缓存镜像的 SwiftUICore 还多出基线印成 `{}` 的 conformance 成员。第一轮 A/B 里 iOS 26.5 模拟器腿的成员丢失就是上面的整树搜索问题,修后第二轮消失;两轮的 96 份基线渲染逐字节相同。 + - macOS 27.2 当前系统 cache 的 AppKit(剥光本地符号,只靠 `_symbolic`)手工对比 dump 与 interface:只有 3 个局部类型变化(`NSWMDeferrableWMWindowTransaction.deferCompletionUntil()` 里的 `DeferralState`、`_NSLocalizedIndexedCollation.sortedArray(from:collationStringSelector:)` 里的 `ObjectWrapper`、`NSView._HitTestMap.differencePairs(to:differences:)` 里的 `Pair`)。 +- **关联文档**:[draft-local-type-context-names](../Evolutions/draft-local-type-context-names.md)、[Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md)、[SymbolicManglingSymbols.md](SymbolicManglingSymbols.md)「边界」、[Glossary.md](../Glossary.md)「position-based name」、`swift-section` agent skill 第 9 节。 +- **对应版本**:下一个版本(未发版)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index dd9b03751..0d4330d97 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -687,3 +687,24 @@ - **四、`GenericParameterDepthLayout` 跳过匿名上下文,让泛型方法的 opaque 描述符层号算错、thunk 名字跟着错**:不成立。层结构确实把方法的参数与 opaque 参数并成一层,但 kind-9 thunk 的实参缓冲只按命名声明的签名绑定(编译器 `AbstractMetadataAccessor::emit` 取 `O->getGenericSignature()`),不含 opaque 参数;两种层结构只在第三个字及以后不同,那里放的是 witness table,从不被命名。基线用 `AccessorThunkOwnerLayout(genericContext:)` 算出的是同一个结构,PR 只是把计算挪了位置。 - **既往修复**:无。 - **复审条件**:上面任何一条的前提被改动——打印器或 RuntimeViewer 改了追加扩展的条件;离线特化开始接受文件里读出的 `Metadata`;enum 布局的 size 交叉校验被拿掉;thunk 的实参缓冲开始带 opaque 参数。 + +--- + +## A60 — 局部类型的上下文让三处整树搜索可能读错成员:`final` 恢复的 `Tq` 兜底、上游 `identifier`、变量的代表节点(局部类型名字提案横向排查发现) + +- **裁决**:三处都不修(2026-10-11)。 +- **背景**:局部类型的名字里带着声明它的函数、闭包或访问器(提案 [draft-local-type-context-names](../Evolutions/draft-local-type-context-names.md))。成员符号的节点以上下文为第一个子节点,前序遍历的整树搜索因此会先进入上下文,拿到外层声明的节点。同一批里能变红的五处已经修掉(conformance 成员的分类与去重、主体里合成成员的去重、`@dynamicMemberLookup` 推断、匿名参数的标签、`static` 存储属性的存储符号被读成 getter),下面三处判为不修。 +- **一、`final` 恢复的第四道门**:`TypeDefinition.recoverFinalMembers`(`TypeDefinition+FinalRecovery.swift`,`Tq` 符号那段)把每个 method descriptor 符号读成成员名时,先对整棵树做 `first(of: .function)`,找不到才找 `.variable`、`.subscript`。局部 class 的属性访问器 descriptor(`method descriptor for sides.getter … in Shape #1 in Holder.shape(_:)`)会被读成外层函数名 `shape`,而不是 `sides`。 + - **复现 / 是否误报**:机制属实。`-Onone` 编出的局部 class 带着 `Tq` 局部符号,`nm` 可见。但输出层面复现不出来:这道门只在成员与 descriptor 连不上时起作用,而局部 class 的成员靠同一批 `Tq` 符号按节点连接(`ClassDispatchLookups.methodDescriptorLookup`),不受 ICF 影响,总是先连上;`-O` 构建会把局部 class 的属性去虚化,连 `Tq` 符号都不生成。 + - **与 main 基线对比**:代码是基线既有的。基线里局部 class 的名字是错的,descriptor 按节点匹配不到,这处走不到;本分支让名字对上之后才可达,但仍被节点连接挡在前面。 + - **为什么不修**:造不出修复前会失败的测试。修法是现成的:按查询的成员种类分别取 `.function` / `.variable` / `.subscript`,对普通 class 结果不变。 + - **既往修复**:无。第四道门来自提案 0006 的 ICF 回归(issue #106,`FinalKeywordICFRegressionTests`),当时只考虑了普通 class。 +- **二、上游 swift-demangling 的 `DemanglingNode.identifier`**:第二个子节点不是标识符时(运算符函数、下标),它在整棵树里找,任意位置的运算符优先。局部类型声明在一个运算符函数里时,类型自己的运算符成员会读成外层运算符的名字。 + - **复现 / 是否误报**:读码确认,没有构造样本。外层声明只要不是运算符函数就不会触发:外层是普通函数时,标识符的优先级低于运算符,仍然返回成员自己的运算符。 + - **与 main 基线对比**:基线既有;同样是局部类型名字对上之后才可达。 + - **为什么不修**:根在上游包,触发条件极少见,本仓库所有调用点都按名字比较,读错只影响这一种写法。 +- **三、`DefinitionBuilder.variablesProduct` 挑变量的代表节点**:从一个属性的访问器符号里挑「是 getter、或不是访问器」的第一个,判断仍用整树的 `contains(.getter)`。局部类型声明在 getter 里时,每个访问器都含上下文的 getter,于是挑的是第一个符号,不论它是什么。 + - **复现 / 是否误报**:机制属实,输出层面复现不出来。符号表里 getter 总排在 setter、modify 和存储符号前面,挑出来的就是 getter;代表节点只用来打印声明,getter、setter、存储符号打出来的声明也一样。 + - **与 main 基线对比**:代码是基线既有的,同样是局部类型名字对上之后才可达。 + - **为什么不修**:造不出会变红的测试。同一处的访问器种类(`accessorKind`)已经修掉,那个读错会把 `static` 存储属性印成计算属性。 +- **复审条件**:节点连接不再先于第四道门(`methodDescriptorLookup` 的建键方式改了);出现了局部 class 被误标 `final`、运算符函数里的局部类型成员名字读错的实例;或者局部类型的属性以 setter 之类的节点出现在声明、ABI 键里。 diff --git a/Documentations/Internal/SymbolicManglingSymbols.md b/Documentations/Internal/SymbolicManglingSymbols.md index 2bd0af48f..0821a559b 100644 --- a/Documentations/Internal/SymbolicManglingSymbols.md +++ b/Documentations/Internal/SymbolicManglingSymbols.md @@ -9,7 +9,7 @@ mangled name 里的 symbolic reference 只是 5 个字节(控制字节 + 相 编译器另给每条带引用的 mangled name 生成一个供链接器去重的符号,名字里按引用顺序写出每个被引用者的完整 mangling, 模块、外层类型、private 鉴别符一个不缺,而 dyld shared cache 保留着它们。`SymbolIndexStore` 在已有的符号表扫描里把这类 符号收进一张独立的表;SwiftInspection 的 `SymbolicManglingIndex` 把每个引用和它的被引用者配对,按被引用的位置建索引。 -私有鉴别符的还原(`AnonymousContextPrivateDiscriminatorIndex`)是第一个消费者,`SymbolicDemangler` 的对照测试是第二个。 +匿名上下文里的类型取名(`AnonymousContextNameIndex`:private 类型的鉴别符,函数体里声明的局部类型的完整名字)是第一个消费者,`SymbolicDemangler` 的对照测试是第二个。 ## 这些符号长什么样 @@ -51,7 +51,7 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference | MachOSymbols | `SymbolicManglingSymbols.swift` | `SymbolicManglingSymbols`:按行、零拷贝的集合(`MachOImage` 的名字留在映射的字符串表里);`SymbolicManglingSymbolName`:拆出角色、带占位的 mangled name、被引用者;字节级前缀判断 `nameBytesHaveSymbolicManglingSymbolPrefix` | | MachOSymbols | `SymbolIndexStore.swift` | 两条采集腿各多一个前缀分支,收进 `Storage.symbolicManglingSymbolTable`(沿用 `SymbolTable`);查询 `symbolicManglingSymbols(in:)` | | SwiftInspection | `SymbolicManglingIndex.swift` | `SymbolicManglingReference`(种类、引用位置、被引用位置、符号位置、第几个被引用者,24 字节);按镜像的 `SharedCache`:读每个符号标的 mangled name、按顺序配对、按被引用位置排一份下标;查询 `references(in:)` / `references(to:in:)` / `referentNode(of:in:)` / `referentNode(forContextDescriptorAt:in:)` / `referentNodes(ofSymbolAt:in:)` / `unpairedSymbolCount(in:)` | -| SwiftInspection | `AnonymousContextPrivateDiscriminatorIndex.swift` | 不再自己扫符号表:遍历 `0x01` 引用,每个描述符只读一次父级,父级是匿名上下文就从解好的被引用者节点里取鉴别符;某个引用解不出来就接着试下一个指向同一描述符的引用 | +| SwiftInspection | `AnonymousContextNameIndex.swift` | 不再自己扫符号表:遍历 `0x01` 引用,每个描述符只读一次父级,父级是匿名上下文就从解好的被引用者节点里取名字——private 类型取鉴别符,局部类型(名字是 `localDeclName`)把整个名字存成 type mangling,用时再解;某个引用解不出来就接着试下一个指向同一描述符的引用。原名 `AnonymousContextPrivateDiscriminatorIndex`,提案 [local-type-context-names](../Evolutions/draft-local-type-context-names.md) 改名 | | SwiftIndexing | `SwiftDeclarationIndexer.deinit` | 符号库那一支(`claims.symbolStore`)一起驱逐 `SymbolicManglingIndex` | ## 为什么这样落 @@ -62,7 +62,7 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference `MangledName.resolve(from:in:)`,`MachOSymbols` 的依赖够不到 ABI 模型;提案 0018 也已把符号归属放在 SwiftInspection。 - **不驻留 `String` / `Node`**:引用只记位置与下标,被引用者在查询时连同前面的被引用者一起 transient demangle。 - **驱逐**:索引的存储握着符号库那张表,符号库被回收时它若留着,就钉住那张表,所以放在 `claims.symbolStore` 那一支。 - 私有鉴别符索引只存 `[Int: String]`,不握任何表,仍跟着 demangle memo 走。 + 匿名上下文名字索引只存字符串(鉴别符、局部类型的 mangling),不握任何表,仍跟着 demangle memo 走。 - **代价**:离线路径(`MachOContext`)找符号本来就经 `SymbolIndexStore`,收集在同一趟扫描里,不多扫一遍。进程内路径 (`InProcessContext`)找符号走 MachOKit,不建符号库;私有鉴别符改为经本索引之后,进程内第一次遇到没有名字的匿名上下文, 要先为该镜像建 `SymbolIndexStore`(原先只扫一遍符号表)。RuntimeViewer 这类宿主通常早已为正在看的镜像建好;这笔一次性 @@ -75,10 +75,7 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference SwiftUICore 实测为 0。没有被引用者的符号(如 `_symbolic Si`)不读字节。 - 间接引用(`0x02`)只给出指针槽的位置,不解它指向哪个镜像的哪个描述符。 - 不提供被引用者的原始文本:单独拿去 demangle 就会踩上面那个坑。 -- 函数体里声明的局部类型:编译器写 `DeferralState #1 in AppKit.NSWMDeferrableWMWindowTransaction.deferCompletionUntil() -> () -> ()`, - `SymbolicDemangler` 从描述符还原时丢掉函数那一层——和私有鉴别符是同一类问题(匿名上下文没有名字)。对照测试把它登记为 - 已知问题(`withKnownIssue`),本提案不修;待办记在 - [Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md)。 +- 函数体里声明的局部类型:编译器写 `DeferralState #1 in AppKit.NSWMDeferrableWMWindowTransaction.deferCompletionUntil() -> () -> ()`,`SymbolicDemangler` 从描述符还原时曾丢掉函数那一层——和私有鉴别符是同一类问题(匿名上下文没有名字)。本提案当时把它登记为已知问题(`withKnownIssue`);提案 [local-type-context-names](../Evolutions/draft-local-type-context-names.md) 修掉了它,`_symbolic` 符号是局部类型名字的三个来源之一(另两个是描述符自带的名字和匿名描述符的 `MXX` 符号),对照测试的已知问题随之去掉。只有字段描述符的类型才有这个符号,所以一个被剥光本地符号、又没有字段描述符的局部类型仍然找不回函数,按位置起名。 ## 实测(macOS 26.7 系统 dyld shared cache) diff --git a/Documentations/README.md b/Documentations/README.md index 05bafe1d5..5171f341a 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -165,6 +165,7 @@ selects names using each access's offset and width. | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | +| [Evolutions/draft-local-type-context-names.md](Evolutions/draft-local-type-context-names.md) | **提案 draft(In Progress)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;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/Roadmaps/2026-09-24-local-type-context-names.md b/Roadmaps/2026-09-24-local-type-context-names.md index 58798632c..022166e9d 100644 --- a/Roadmaps/2026-09-24-local-type-context-names.md +++ b/Roadmaps/2026-09-24-local-type-context-names.md @@ -3,7 +3,7 @@ 提案 [0050-symbolic-mangling-symbol-index](../Documentations/Evolutions/0050-symbolic-mangling-symbol-index.md) 的对照测试发现的问题: `SymbolicDemangler` 从描述符还原函数体里声明的类型时,丢掉了函数那一层。 -**当前状态:只落记录,代码未改。** 用户裁定先记下来(「第二个先记下来」),修复批次另起。 +**当前状态(2026-10-11):已修,见提案 [local-type-context-names](../Documentations/Evolutions/draft-local-type-context-names.md)。** 下面是 2026-09-24 的原始记录,保持原貌;它的推断有几处被后来的调查更正,列在文末「更正(2026-10-10)」。 ## 现象 @@ -50,3 +50,13 @@ - 提案决策日志:「函数体里的局部类型:对照测试登记为已知问题,本提案不修」。 - [Internal/SymbolicManglingSymbols.md](../Documentations/Internal/SymbolicManglingSymbols.md)「边界」。 - [Internal/ProjectEvolutionLog.md](../Documentations/Internal/ProjectEvolutionLog.md) 2026-09-24 两节。 + +## 更正(2026-10-10) + +RuntimeViewer 会话在 macOS 27.2 的 SwiftUI 上复现了这个问题并查清根因,转交过来修。对上面记录的更正: + +- 「dyld shared cache 里它上面也查不到符号」只对 AppKit 成立。SwiftUI、SwiftUICore 在 cache 里保留了本地符号,匿名描述符的 `$s<上下文>MXX` 符号都在,进程内也读得到。当时的代码没有用它取名,只用 `first(of: .privateDeclName)` 从里面取鉴别符,取到的是外围 private 函数的,于是局部类型被伪造成 private 类型(`AccessibilityRotorInfo.(unknown context at _0306…).(IndexingWrappingGenerator in _0306…)`)。 +- 「父级是 anonymous context,再上一层是外层类型」:父链确实是一串匿名上下文,而且是多层——类型自己一层、每个闭包一层、函数一层(`lib/IRGen/GenDecl.cpp` 的 `getAddrOfContextDescriptorForParent`)。 +- 除了撞名,还有两个症状没记:上面那个伪造的 private 类型;以及成员符号用真名记录,跟错的名字永远对不上,成员静默丢失,带扩展上下文的成员(`~Copyable` 泛型参数让成员落在一个 inverse 约束扩展里)在 RuntimeViewer 里成了孤立的顶层 Ex。 +- debug 构建也错:driver 只在 `-g -Onone` 时加 `-enable-anonymous-context-mangled-names`,描述符这时带着名字,但 2025-05 的 `be2f186e` 把匿名上下文改成「直接丢掉」之后,采用名字的那段逻辑只在外围函数恰好是 private 时才把函数接上。 +- 修复方向里「键得是类型描述符,不能是匿名上下文」不必要:类型自己那一层匿名上下文是每个类型各有一个的(`getAddrOfAnonymousContextDescriptor(ofChild)`),按它做键就是按类型做键。 From 2ab00e967cc16442c5c3fc2bda5d46c5ac7094ab Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 07:45:35 +0800 Subject: [PATCH 32/49] docs: land proposal 0062 (local-type-context-names) as Implemented Numbers the proposal against the shared branches (origin/next and origin/main at 0061), marks it Implemented with the closing judgements, updates every link to the draft, and records the batch as section 87 of the evolution ledger. --- AGENTS.md | 2 +- ...context-names.md => 0062-local-type-context-names.md} | 9 ++++++--- Documentations/Evolutions/README.md | 2 +- Documentations/Glossary.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 4 ++-- Documentations/Internal/ReviewAdjudications.md | 2 +- Documentations/Internal/SymbolicManglingSymbols.md | 4 ++-- Documentations/README.md | 2 +- Roadmaps/2026-09-24-local-type-context-names.md | 2 +- 9 files changed, 16 insertions(+), 13 deletions(-) rename Documentations/Evolutions/{draft-local-type-context-names.md => 0062-local-type-context-names.md} (92%) diff --git a/AGENTS.md b/AGENTS.md index 3a3e87ff3..ac6765b6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -186,7 +186,7 @@ Each of these fails **silently**, and several produce a real, fully-qualified, * - **Any `Dictionary`/`Set` keyed on a `NodeReference` whose keys and lookups can come from different stores must key on `StructuralNodeReferenceKey`, never a bare `NodeReference`** — its intrinsic `Hashable` is store-identity based. Different stores are the norm within one image. Bare keys are safe only for grouping within a single `memberSymbols` batch. Symptoms of getting it wrong differ per site: a dropped `override` keyword, a discarded setter, a doubled `func`, a twice-claimed witness. - **Do NOT reintroduce `demangleAsNode` / `Node.create` on unbounded inputs.** Sources carries zero cached call sites; a tree that is consumed and dropped stays transient (`demangleAsNodeTransient` / `Node.createTransient`). - **A runtime metatype becomes a node only through `RuntimeTypeNameDemangling.node(forMetatype:)`, never bare `_mangledTypeName` + demangle.** The runtime spells a private type's anonymous context by its descriptor address, which the printers render as nothing or as `(unknown context at $…)` — a specialized header read `struct .WindowPortal<…>`, and a private type argument lost its module and every enclosing type. -- **An anonymous context's name is the compiler's whole mangling of what it stands for — a function, a closure, or the private or local type it wraps — never a fragment of it.** It comes from the descriptor's own name (debug builds only), the `$sMXX` symbol on the descriptor, or a `_symbolic` referent (`AnonymousContextNameIndex`); a private discriminator is read off the wrapped type's own `privateDeclName` and nothing else. Taking `first(of: .privateDeclName)` from the context's name borrowed an enclosing private function's discriminator and faked private types, and dropping the context lost every local type's function, so two methods' `Visitor`s merged into one definition. A local type no source names is position-named `Holder.(Visitor in $
)` — tell it from a private type with `localTypeNaming`, never by string ([draft-local-type-context-names](Documentations/Evolutions/draft-local-type-context-names.md)). +- **An anonymous context's name is the compiler's whole mangling of what it stands for — a function, a closure, or the private or local type it wraps — never a fragment of it.** It comes from the descriptor's own name (debug builds only), the `$sMXX` symbol on the descriptor, or a `_symbolic` referent (`AnonymousContextNameIndex`); a private discriminator is read off the wrapped type's own `privateDeclName` and nothing else. Taking `first(of: .privateDeclName)` from the context's name borrowed an enclosing private function's discriminator and faked private types, and dropping the context lost every local type's function, so two methods' `Visitor`s merged into one definition. A local type no source names is position-named `Holder.(Visitor in $
)` — tell it from a private type with `localTypeNaming`, never by string ([0062-local-type-context-names](Documentations/Evolutions/0062-local-type-context-names.md)). - **Do NOT call bare `NodeReference(interning:)` on a batch path** — route through `InternedNodeReferenceCache`. - **A `_symbolic` symbol's referents are one mangling, not several.** The compiler appends them with one mangler, so a later referent reuses substitutions and words of the earlier ones (`7SwiftUI19_ConditionalContentV AA08ModifiedD0V`); demangled alone it fails or names something else. Take referents from `SymbolicManglingIndex.referentNode(of:in:)`, which demangles them together — and for the same reason never splice referents into the mangled name as text. - **Resolving one type's members/info/attributes must use the node-taking overloads** (`memberSymbols(of:for:node:in:)` and friends). The name-only forms flatten every sub-bucket on purpose: the name key is printed with `.interfaceTypeBuilderOnly`, which strips private discriminators, so same-named private types share a bucket (issue #115). diff --git a/Documentations/Evolutions/draft-local-type-context-names.md b/Documentations/Evolutions/0062-local-type-context-names.md similarity index 92% rename from Documentations/Evolutions/draft-local-type-context-names.md rename to Documentations/Evolutions/0062-local-type-context-names.md index 6ebbf8aad..9095058fc 100644 --- a/Documentations/Evolutions/draft-local-type-context-names.md +++ b/Documentations/Evolutions/0062-local-type-context-names.md @@ -1,11 +1,12 @@ -# Draft - 局部类型的名字:找回函数与闭包上下文 +# 0062 - 局部类型的名字:找回函数与闭包上下文 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-10-10 - **最后更新**: 2026-10-11 - **所属愿景**: 无 - **关联提案**: [0050-symbolic-mangling-symbol-index](0050-symbolic-mangling-symbol-index.md)(对照测试发现并登记了这个问题,`_symbolic` 符号是这里的来源之一) -- **实现分支 / PR**: `feature/local-type-context-names` +- **实现分支 / PR**: `feature/local-type-context-names`(worktree `.worktrees/MachOSwiftSection-LocalTypeContextNames`,基于 `next`),按本仓库惯例在本地合并进 `next` +- **配套文档**: 名字的三个来源与找不回函数的情况见 [SymbolicManglingSymbols.md](../Internal/SymbolicManglingSymbols.md)「边界」;CLI 用户在 dump / interface 里看到的写法见 `swift-section` agent skill 第 9 节(`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`);同类但不修的三处见 [ReviewAdjudications A60](../Internal/ReviewAdjudications.md) - **起因**: RuntimeViewer 会话在 macOS 27.2 的 SwiftUI 上复现并查清根因后转交;早先的记录在 [Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md) ## 摘要 @@ -121,3 +122,5 @@ struct TableDataSource { | 2026-10-11 | 成员分类、去重、三处标签读取和访问器种类改为只看成员自己的节点 | 系统框架 A/B 里 iOS 26.5 模拟器那条腿的 SwiftUICore 少了 conformance 成员(`_rawHashValue`、`_updateDefault`、`CodingKeys` 的初始化器)。基线里名字对不上,witness 符号匹配不到,退回按 requirement 打印,反而完整;名字对上以后拿到真正的 witness 符号,整树搜索就先碰到了外层声明。横向排查又找到四处同类,都用 fixture 复现、先红后绿。 | | 2026-10-11 | `final` 恢复的 `Tq` 兜底、上游 `DemanglingNode.identifier`、变量的代表节点不修,登记 ReviewAdjudications A60 | 第一处被按节点的 descriptor 连接挡在前面,第三处因为符号表里 getter 总在最前,都造不出会变红的测试;第二处在上游包里,要局部类型声明在运算符函数里才触发。 | | 2026-10-11 | 测试里 `__derived_struct_equals(Visitor, Visitor)` 的期望改为 `(_: Visitor, _: Visitor)` | 当时把无标签的输出当成打印器的既有写法;其实是 `printLabelList` 按外层函数 `countValues()` 的空参数元组算标签,与孪生类型对照后确认是错的。 | +| 2026-10-11 | In Progress → Implemented,编号 0062 | 用户确认合入。按共享分支编号(origin/next 与 origin/main 最大都是 0061),开工后 `next` 没有新提交,不用 rebase;本地合并进 `next`;演进账本第 87 节 | +| 2026-10-11 | 收尾判断:不另写专题文档;新术语已登记 | 名字的三个来源与找不回的情况写在 SymbolicManglingSymbols.md「边界」,CLI 用户看到的写法写在 agent skill 第 9 节,整树搜索的陷阱写进 AGENTS.md,不修的三处在 A60,都已登记在头部;其余实现决策都在本提案与演进账本里,没有再值得单列的。「position-based name」(按位置起的名字)是本提案新造的说法,已登记术语表;`LocalTypeNaming` 是标识符,不登记 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 2a4fee7f3..a264782b7 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -75,4 +75,4 @@ | [0060](0060-evolution-interface-available-annotations.md) | evolution 联合接口的 @available 生命周期标注(真属性 + 位图注释保留) | Implemented | | [0061](0061-dyld-shared-cache-path-versions.md) | 测试用的 dyld shared cache 路径按版本取 | Implemented | | draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | -| draft | [局部类型的名字:找回函数与闭包上下文](draft-local-type-context-names.md) | In Progress | +| [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 39da9d33c..c6d8c5e54 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -281,7 +281,7 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 函数或闭包里声明的局部类型,在二进制里找不回所在函数时用的名字:`Holder.(Visitor in $1a2b3c)`。局部类型的函数名有三个来源——描述符自带的名字(只有 debug 构建写)、匿名描述符的 `$s<上下文>MXX` 符号、`_symbolic` 符号——三处都没有(典型是 strip 过的 App)时,`SymbolicDemangler` 照运行时和 Remote Mirror 的做法,用包着该类型的那个匿名上下文的地址起名,挂在最近一个能叫出名字的上下文下面。地址的口径与 dump 的成员地址注释相同,所以同一个镜像从文件读和在进程内读得到同一个名字。它借用 `privateDeclName` 的形状,但类型不是 private,`$` 开头的部分也不是鉴别符;判断用 `LocalTypeNaming.positionBased`,不要按字符串猜。 - **主要出现在**:`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`(`positionNameOfUnnamedLocalType`)、`Sources/Analysis/SwiftInspection/LocalTypeNaming.swift`、`Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift` -- **延伸阅读**:[提案 local-type-context-names](Evolutions/draft-local-type-context-names.md) +- **延伸阅读**:[提案 0062](Evolutions/0062-local-type-context-names.md) ### renamed class(改名类,`@objc(Name)` / `@_objcRuntimeName(Name)`) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index d3db190e5..ec2f7898f 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2370,7 +2370,7 @@ - **关联文档**:review 记录;[ReviewAdjudications.md](ReviewAdjudications.md) A53–A59;四份提案的决策日志([并发打印](../Evolutions/draft-concurrent-definition-printing.md)、[离线特化](../Evolutions/draft-offline-generic-specialization.md)、[嵌套定义区域](../Evolutions/draft-nested-definition-regions.md)、[嵌套偏移记忆化](../Evolutions/draft-nested-field-offset-memoization.md));[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md)、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、[Modules/MachODependencies.md](Modules/MachODependencies.md)。 - **对应版本**:0.22.0(未发版),随 PR #131 合入。 -## 2026-10-10 局部类型的名字:找回函数与闭包上下文(节号落地时分配) +## 87. 局部类型的名字:找回函数与闭包上下文 - **时间段**:2026-10-10 — 2026-10-11。 - **动机**:RuntimeViewer 会话在 macOS 27.2 的 SwiftUI 侧边栏里看到一行孤立的 Ex(`IndexWrappingVisitor in IndexingWrappingGenerator #1 in closure #1 … in AccessibilityRotorInfo.readEntryList(…)`),追下去是函数、闭包里声明的局部类型名字全错:`TableDataSource` 的 7 个 `Visitor` 在 interface 里只剩 1 个、重复 6 遍;private 函数里的局部类型被伪造成 private 类型;成员符号用真名记录,对不上错的名字,成员静默丢失。会话把调查结果转交过来,用户让这边接手修。这个问题 2026-09-24 已经记在 roadmap `2026-09-24-local-type-context-names` 里,当时只登记、没修。 @@ -2392,7 +2392,7 @@ - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,五个兄弟依赖都链本地):2383 个测试、455 个套件全部通过,原始退出码 0。 - 系统框架 A/B(`Scripts/run-rendering-ab-verification.py`;基线是 next cd248de9 的 `git archive` 沙盒,两侧 release 预构建,共用同一份 `Package.resolved`):96 对里 30 对有差异,全部在 SwiftUI / SwiftUICore,逐对核对都来自局部类型——名字换成编译器全名,interface 加注释、conformance 的 extension 头印全名,以前丢掉的成员、字段和布局注释挂回来(`TableDataSource` 的 7 个 `Visitor` 各有自己的字段,基线是一份 `var result: SwiftUI.DeleteInteraction?` 印 6 遍)。按典型 witness 成员(`_rawHashValue`、`hash(into:)`、`_updateDefault`、`CodingKeys` 的初始化器等)计数,没有一对比基线少;缓存镜像的 SwiftUICore 还多出基线印成 `{}` 的 conformance 成员。第一轮 A/B 里 iOS 26.5 模拟器腿的成员丢失就是上面的整树搜索问题,修后第二轮消失;两轮的 96 份基线渲染逐字节相同。 - macOS 27.2 当前系统 cache 的 AppKit(剥光本地符号,只靠 `_symbolic`)手工对比 dump 与 interface:只有 3 个局部类型变化(`NSWMDeferrableWMWindowTransaction.deferCompletionUntil()` 里的 `DeferralState`、`_NSLocalizedIndexedCollation.sortedArray(from:collationStringSelector:)` 里的 `ObjectWrapper`、`NSView._HitTestMap.differencePairs(to:differences:)` 里的 `Pair`)。 -- **关联文档**:[draft-local-type-context-names](../Evolutions/draft-local-type-context-names.md)、[Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md)、[SymbolicManglingSymbols.md](SymbolicManglingSymbols.md)「边界」、[Glossary.md](../Glossary.md)「position-based name」、`swift-section` agent skill 第 9 节。 +- **关联文档**:[0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md)、[Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md)、[SymbolicManglingSymbols.md](SymbolicManglingSymbols.md)「边界」、[Glossary.md](../Glossary.md)「position-based name」、`swift-section` agent skill 第 9 节。 - **对应版本**:下一个版本(未发版)。 ## 维护约定 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 0d4330d97..d96bd9a5e 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -693,7 +693,7 @@ ## A60 — 局部类型的上下文让三处整树搜索可能读错成员:`final` 恢复的 `Tq` 兜底、上游 `identifier`、变量的代表节点(局部类型名字提案横向排查发现) - **裁决**:三处都不修(2026-10-11)。 -- **背景**:局部类型的名字里带着声明它的函数、闭包或访问器(提案 [draft-local-type-context-names](../Evolutions/draft-local-type-context-names.md))。成员符号的节点以上下文为第一个子节点,前序遍历的整树搜索因此会先进入上下文,拿到外层声明的节点。同一批里能变红的五处已经修掉(conformance 成员的分类与去重、主体里合成成员的去重、`@dynamicMemberLookup` 推断、匿名参数的标签、`static` 存储属性的存储符号被读成 getter),下面三处判为不修。 +- **背景**:局部类型的名字里带着声明它的函数、闭包或访问器(提案 [0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md))。成员符号的节点以上下文为第一个子节点,前序遍历的整树搜索因此会先进入上下文,拿到外层声明的节点。同一批里能变红的五处已经修掉(conformance 成员的分类与去重、主体里合成成员的去重、`@dynamicMemberLookup` 推断、匿名参数的标签、`static` 存储属性的存储符号被读成 getter),下面三处判为不修。 - **一、`final` 恢复的第四道门**:`TypeDefinition.recoverFinalMembers`(`TypeDefinition+FinalRecovery.swift`,`Tq` 符号那段)把每个 method descriptor 符号读成成员名时,先对整棵树做 `first(of: .function)`,找不到才找 `.variable`、`.subscript`。局部 class 的属性访问器 descriptor(`method descriptor for sides.getter … in Shape #1 in Holder.shape(_:)`)会被读成外层函数名 `shape`,而不是 `sides`。 - **复现 / 是否误报**:机制属实。`-Onone` 编出的局部 class 带着 `Tq` 局部符号,`nm` 可见。但输出层面复现不出来:这道门只在成员与 descriptor 连不上时起作用,而局部 class 的成员靠同一批 `Tq` 符号按节点连接(`ClassDispatchLookups.methodDescriptorLookup`),不受 ICF 影响,总是先连上;`-O` 构建会把局部 class 的属性去虚化,连 `Tq` 符号都不生成。 - **与 main 基线对比**:代码是基线既有的。基线里局部 class 的名字是错的,descriptor 按节点匹配不到,这处走不到;本分支让名字对上之后才可达,但仍被节点连接挡在前面。 diff --git a/Documentations/Internal/SymbolicManglingSymbols.md b/Documentations/Internal/SymbolicManglingSymbols.md index 0821a559b..bdd884feb 100644 --- a/Documentations/Internal/SymbolicManglingSymbols.md +++ b/Documentations/Internal/SymbolicManglingSymbols.md @@ -51,7 +51,7 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference | MachOSymbols | `SymbolicManglingSymbols.swift` | `SymbolicManglingSymbols`:按行、零拷贝的集合(`MachOImage` 的名字留在映射的字符串表里);`SymbolicManglingSymbolName`:拆出角色、带占位的 mangled name、被引用者;字节级前缀判断 `nameBytesHaveSymbolicManglingSymbolPrefix` | | MachOSymbols | `SymbolIndexStore.swift` | 两条采集腿各多一个前缀分支,收进 `Storage.symbolicManglingSymbolTable`(沿用 `SymbolTable`);查询 `symbolicManglingSymbols(in:)` | | SwiftInspection | `SymbolicManglingIndex.swift` | `SymbolicManglingReference`(种类、引用位置、被引用位置、符号位置、第几个被引用者,24 字节);按镜像的 `SharedCache`:读每个符号标的 mangled name、按顺序配对、按被引用位置排一份下标;查询 `references(in:)` / `references(to:in:)` / `referentNode(of:in:)` / `referentNode(forContextDescriptorAt:in:)` / `referentNodes(ofSymbolAt:in:)` / `unpairedSymbolCount(in:)` | -| SwiftInspection | `AnonymousContextNameIndex.swift` | 不再自己扫符号表:遍历 `0x01` 引用,每个描述符只读一次父级,父级是匿名上下文就从解好的被引用者节点里取名字——private 类型取鉴别符,局部类型(名字是 `localDeclName`)把整个名字存成 type mangling,用时再解;某个引用解不出来就接着试下一个指向同一描述符的引用。原名 `AnonymousContextPrivateDiscriminatorIndex`,提案 [local-type-context-names](../Evolutions/draft-local-type-context-names.md) 改名 | +| SwiftInspection | `AnonymousContextNameIndex.swift` | 不再自己扫符号表:遍历 `0x01` 引用,每个描述符只读一次父级,父级是匿名上下文就从解好的被引用者节点里取名字——private 类型取鉴别符,局部类型(名字是 `localDeclName`)把整个名字存成 type mangling,用时再解;某个引用解不出来就接着试下一个指向同一描述符的引用。原名 `AnonymousContextPrivateDiscriminatorIndex`,提案 [0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md) 改名 | | SwiftIndexing | `SwiftDeclarationIndexer.deinit` | 符号库那一支(`claims.symbolStore`)一起驱逐 `SymbolicManglingIndex` | ## 为什么这样落 @@ -75,7 +75,7 @@ name」这种东西:typeref 本体里的 substitution 把 symbolic reference SwiftUICore 实测为 0。没有被引用者的符号(如 `_symbolic Si`)不读字节。 - 间接引用(`0x02`)只给出指针槽的位置,不解它指向哪个镜像的哪个描述符。 - 不提供被引用者的原始文本:单独拿去 demangle 就会踩上面那个坑。 -- 函数体里声明的局部类型:编译器写 `DeferralState #1 in AppKit.NSWMDeferrableWMWindowTransaction.deferCompletionUntil() -> () -> ()`,`SymbolicDemangler` 从描述符还原时曾丢掉函数那一层——和私有鉴别符是同一类问题(匿名上下文没有名字)。本提案当时把它登记为已知问题(`withKnownIssue`);提案 [local-type-context-names](../Evolutions/draft-local-type-context-names.md) 修掉了它,`_symbolic` 符号是局部类型名字的三个来源之一(另两个是描述符自带的名字和匿名描述符的 `MXX` 符号),对照测试的已知问题随之去掉。只有字段描述符的类型才有这个符号,所以一个被剥光本地符号、又没有字段描述符的局部类型仍然找不回函数,按位置起名。 +- 函数体里声明的局部类型:编译器写 `DeferralState #1 in AppKit.NSWMDeferrableWMWindowTransaction.deferCompletionUntil() -> () -> ()`,`SymbolicDemangler` 从描述符还原时曾丢掉函数那一层——和私有鉴别符是同一类问题(匿名上下文没有名字)。本提案当时把它登记为已知问题(`withKnownIssue`);提案 [0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md) 修掉了它,`_symbolic` 符号是局部类型名字的三个来源之一(另两个是描述符自带的名字和匿名描述符的 `MXX` 符号),对照测试的已知问题随之去掉。只有字段描述符的类型才有这个符号,所以一个被剥光本地符号、又没有字段描述符的局部类型仍然找不回函数,按位置起名。 ## 实测(macOS 26.7 系统 dyld shared cache) diff --git a/Documentations/README.md b/Documentations/README.md index 5171f341a..190c58f46 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -165,7 +165,7 @@ selects names using each access's offset and width. | [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | | [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | -| [Evolutions/draft-local-type-context-names.md](Evolutions/draft-local-type-context-names.md) | **提案 draft(In Progress)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | +| [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;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/Roadmaps/2026-09-24-local-type-context-names.md b/Roadmaps/2026-09-24-local-type-context-names.md index 022166e9d..5b4c8b392 100644 --- a/Roadmaps/2026-09-24-local-type-context-names.md +++ b/Roadmaps/2026-09-24-local-type-context-names.md @@ -3,7 +3,7 @@ 提案 [0050-symbolic-mangling-symbol-index](../Documentations/Evolutions/0050-symbolic-mangling-symbol-index.md) 的对照测试发现的问题: `SymbolicDemangler` 从描述符还原函数体里声明的类型时,丢掉了函数那一层。 -**当前状态(2026-10-11):已修,见提案 [local-type-context-names](../Documentations/Evolutions/draft-local-type-context-names.md)。** 下面是 2026-09-24 的原始记录,保持原貌;它的推断有几处被后来的调查更正,列在文末「更正(2026-10-10)」。 +**当前状态(2026-10-11):已修,见提案 [0062-local-type-context-names](../Documentations/Evolutions/0062-local-type-context-names.md)。** 下面是 2026-09-24 的原始记录,保持原貌;它的推断有几处被后来的调查更正,列在文末「更正(2026-10-10)」。 ## 现象 From 1292cda2975f5fcd34a82c3d95f470a424189955 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 23:01:04 +0800 Subject: [PATCH 33/49] feat: read a name's private declarations and recover their source files RuntimeViewer tags a private type in its sidebar and lists the private discriminators its name carries, with the source file each one was derived from. Both computations lived in RuntimeViewer; they move here so that the host only presents them. - SwiftInspection: `Node.privateDeclarations` and `NodeReference.privateDeclarations` return the `PrivateDeclaration`s (name and discriminator) a name reads, in reading order. The search covers the whole tree but skips the signature of a function or closure context and the `$` address of a position-based name: RuntimeViewer's search took that address for a discriminator and counted the private types in a local type's function signature. A nameless private initializer or subscript reads as `init` / `subscript`. - SwiftDeclaration: `DefinitionName.localTypeDisplayName`, a local type's name without modules or parameter types (`Visitor #1 in TableDataSource.performDrop(to:)`). The interface's comment above a local type's declaration now takes it from there. - New target and product SwiftPrivateDiscriminators. A discriminator is MD5(module name + file name), so candidate file names are hashed until one matches. `PrivateDiscriminatorSourceFiles` is that search, moved from RuntimeViewer unchanged, with its generated list of known file names and the script generating it. `PrivateDiscriminatorSourceFileIndex` takes one image's candidates from a prepared indexer, reads them once, outside its lock and in one large-stack hop, then lets the indexer go, and remembers every answer, recovered or not. - Tests: the shapes a private declaration takes, on both readers of a compiled fixture; a whole-tree oracle over the fixture's and SymbolTestsCore's names; the display name; the search; and the per-image index (stack size, overlapping first requests, letting the indexer go). The two system-image cases, whose discriminators were taken on macOS 27.2, stay out of CI; the other new suites join its filter. --- .github/workflows/macOS.yml | 2 +- Package.swift | 34 + Scripts/GenerateKnownSwiftSourceFileNames.sh | 79 + .../SwiftInspection/LocalTypeNaming.swift | 4 +- .../SwiftInspection/PrivateDeclarations.swift | 109 + .../DefinitionName+LocalTypeDisplayName.swift | 85 + .../PrivateDiscriminatorSourceFileIndex.swift | 205 ++ ...criminatorSourceFiles+KnownFileNames.swift | 2027 +++++++++++++++++ .../PrivateDiscriminatorSourceFiles.swift | 549 +++++ .../SwiftDeclarationPrinter+Headers.swift | 16 +- .../LocalTypeDisplayNameTests.swift | 77 + .../PrivateDeclarationsWholeTreeTests.swift | 143 ++ .../PrivateDeclarationsTests.swift | 167 ++ ...ateDiscriminatorSourceFileIndexTests.swift | 272 +++ ...criminatorSourceFileSystemImageTests.swift | 50 + ...PrivateDiscriminatorSourceFilesTests.swift | 213 ++ 16 files changed, 4018 insertions(+), 14 deletions(-) create mode 100755 Scripts/GenerateKnownSwiftSourceFileNames.sh create mode 100644 Sources/Analysis/SwiftInspection/PrivateDeclarations.swift create mode 100644 Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName+LocalTypeDisplayName.swift create mode 100644 Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift create mode 100644 Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift create mode 100644 Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles.swift create mode 100644 Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift create mode 100644 Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift create mode 100644 Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift create mode 100644 Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift create mode 100644 Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift create mode 100644 Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFilesTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index bf8bc0b52..0eb574a03 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests|PrivateDeclarationsTests|PrivateDeclarationsWholeTreeTests|LocalTypeDisplayNameTests|PrivateDiscriminatorSourceFilesTests|PrivateDiscriminatorSourceFileIndexTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/Package.swift b/Package.swift index f0c5f60fb..44fd3853a 100644 --- a/Package.swift +++ b/Package.swift @@ -617,6 +617,24 @@ extension Target { path: "Sources/Declaration/SwiftIndexing", ) + /// Recovers the source files private discriminators were derived from: + /// MD5 over candidate file names, drawn from an indexed image's names and + /// a generated list of known file names (evolution proposal + /// `private-declarations`). + static let SwiftPrivateDiscriminators = Target.target( + name: "SwiftPrivateDiscriminators", + dependencies: [ + .product(.MachOKit), + .product(.MachOObjCSection), + .product(.Demangling), + .target(.MachOSwiftSection), + .target(.SwiftInspection), + .target(.SwiftDeclaration), + .target(.SwiftIndexing), + ], + path: "Sources/Declaration/SwiftPrivateDiscriminators", + ) + /// Infers source-level Swift attributes (`@propertyWrapper`, /// `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …) from the /// `SwiftDeclaration` model. A low-level peer over the model so the @@ -1142,6 +1160,19 @@ extension Target { swiftSettings: testSettings, ) + static let SwiftPrivateDiscriminatorsTests = Target.testTarget( + name: "SwiftPrivateDiscriminatorsTests", + dependencies: [ + .target(.SwiftPrivateDiscriminators), + .target(.SwiftInspection), + .target(.SwiftDeclaration), + .target(.SwiftIndexing), + .target(.MachOFixtureSupport), + .target(.MachOTestingSupport), + ], + swiftSettings: testSettings, + ) + static let SwiftIndexingTests = Target.testTarget( name: "SwiftIndexingTests", dependencies: [ @@ -1239,6 +1270,7 @@ let package = Package( .library(.SwiftAttributeInference), .library(.SwiftDiffing), .library(.SwiftIndexing), + .library(.SwiftPrivateDiscriminators), .library(.SwiftPrinting), .library(.SwiftSpecialization), .library(.SwiftInterface), @@ -1270,6 +1302,7 @@ let package = Package( .SwiftAttributeInference, .SwiftDiffing, .SwiftIndexing, + .SwiftPrivateDiscriminators, .SwiftPrinting, .SwiftSpecialization, .SwiftInterface, @@ -1305,6 +1338,7 @@ let package = Package( .SwiftSectionCommandTests, .SwiftSectionKitTests, .SwiftIndexingTests, + .SwiftPrivateDiscriminatorsTests, .SwiftSpecializationTests, .SwiftInterfaceTests, .MachOTestingSupportTests, diff --git a/Scripts/GenerateKnownSwiftSourceFileNames.sh b/Scripts/GenerateKnownSwiftSourceFileNames.sh new file mode 100755 index 000000000..125a965a6 --- /dev/null +++ b/Scripts/GenerateKnownSwiftSourceFileNames.sh @@ -0,0 +1,79 @@ +#!/bin/zsh +# Regenerates PrivateDiscriminatorSourceFiles+KnownFileNames.swift: the names +# of the Swift source files in public repositories whose code ships in Apple's +# frameworks. PrivateDiscriminatorSourceFiles tries them before it derives +# any name from an image's own names; a name only counts once its MD5 matches a +# discriminator, so a name that is not in the image costs a hash and nothing else. +# +# Scripts/GenerateKnownSwiftSourceFileNames.sh +# +# Needs a signed-in `gh`. Reads from GitHub only; writes nothing but the Swift file. +# Each source is pinned to the commit it resolved to, which the file's header lists. + +set -euo pipefail + +outputFile="${0:A:h}/../Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift" + +# repository|ref|directory|what it covers. A ref ending in ^ is that commit's parent. +sources=( + "OpenSwiftUIProject/OpenSwiftUI|main||SwiftUI and SwiftUICore, whose file names OpenSwiftUI recovered (MIT)" + "swiftlang/swift-foundation|main||Foundation (Apache 2.0)" + "swiftlang/swift|main|stdlib/public/|the standard library (Apache 2.0)" + "swiftlang/swift|da242bd2d4bfbbc1db1742ba58e66f1c168e6f22^|stdlib/public/Darwin/|the Darwin overlays before most moved into the SDK (Apache 2.0)" + "swiftlang/swift|23c3b15f5f2676dd2cfeaabdaf62ae9b49d6faf1^|stdlib/public/Darwin/|the last Darwin overlays, Foundation's among them (Apache 2.0)" +) + +namesFile=$(mktemp) +trap 'rm -f "$namesFile"' EXIT +sourceLines=() + +for source in "${sources[@]}"; do + IFS='|' read -r repository ref directory description <<< "$source" + if [[ $ref == *^ ]]; then + commit=$(gh api "repos/$repository/commits/${ref%^}" --jq '.parents[0].sha') + else + commit=$(gh api "repos/$repository/commits/$ref" --jq '.sha') + fi + if [[ $(gh api "repos/$repository/git/trees/$commit?recursive=1" --jq '.truncated') != false ]]; then + print -u2 "The tree of $repository at $commit is truncated; list it another way." + exit 1 + fi + gh api "repos/$repository/git/trees/$commit?recursive=1" --jq " + .tree[] + | select(.type == \"blob\") + | .path + | select(startswith(\"$directory\")) + | select(endswith(\".swift\") or endswith(\".swift.gyb\")) + | select(test(\"(^|/)(Tests|Benchmarks|Examples?)/\") | not) + " | sed -e 's#.*/##' -e 's#\.gyb$##' >> "$namesFile" + sourceLines+=("// - $repository @ $commit${directory:+, $directory}: $description") + print "$repository @ $commit: $(wc -l < "$namesFile" | tr -d ' ') names so far" +done + +names=$(LC_ALL=C sort -u "$namesFile") +if print -r -- "$names" | /usr/bin/grep -q '[\\"]'; then + print -u2 'A file name contains a backslash or a quotation mark, which the string literal cannot hold as is.' + exit 1 +fi + +{ + print -r -- '// Generated by Scripts/GenerateKnownSwiftSourceFileNames.sh. Do not edit.' + print -r -- '//' + print -r -- '// The names of the Swift source files, tests and benchmarks aside, in:' + print -rl -- "${sourceLines[@]}" + print -r -- '//' + print -r -- '// File names only: nothing else from these repositories is included.' + print -r -- '' + print -r -- 'extension PrivateDiscriminatorSourceFiles {' + print -r -- " /// Swift source file names known from public repositories whose code ships in Apple's" + print -r -- " /// frameworks, OpenSwiftUI's reconstruction of SwiftUI among them. They are tried first," + print -r -- " /// before any name is derived from an image's own names." + print -r -- ' public static let knownFileNames: [String] = knownFileNamesText.split(separator: "\n").map(String.init)' + print -r -- '' + print -r -- ' private static let knownFileNamesText = """' + print -r -- "$names" | sed 's/^/ /' + print -r -- ' """' + print -r -- '}' +} > "$outputFile" + +print "Wrote $(print -r -- "$names" | wc -l | tr -d ' ') names to ${outputFile:A}" diff --git a/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift b/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift index 51409f164..b30b0d65f 100644 --- a/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift +++ b/Sources/Analysis/SwiftInspection/LocalTypeNaming.swift @@ -37,7 +37,7 @@ extension Node { case .localDeclName: return .compilerSpelled case .privateDeclName: - return declarationName.children.first?.text?.hasPrefix("$") == true ? .positionBased : nil + return declarationName.isPositionBasedPrivateName ? .positionBased : nil default: return nil } @@ -58,7 +58,7 @@ extension NodeReference { case .localDeclName: return .compilerSpelled case .privateDeclName: - return declarationName.children.first?.text?.hasPrefix("$") == true ? .positionBased : nil + return declarationName.isPositionBasedPrivateName ? .positionBased : nil default: return nil } diff --git a/Sources/Analysis/SwiftInspection/PrivateDeclarations.swift b/Sources/Analysis/SwiftInspection/PrivateDeclarations.swift new file mode 100644 index 000000000..cd94cedbd --- /dev/null +++ b/Sources/Analysis/SwiftInspection/PrivateDeclarations.swift @@ -0,0 +1,109 @@ +@_spi(Internals) import Demangling + +/// A private or fileprivate declaration a name reads (evolution proposal +/// `private-declarations`): the declaration's name, and the private +/// discriminator the compiler gave the file declaring it. +public struct PrivateDeclaration: Hashable, Sendable { + /// The declaration's name: `EnabledKey`, `readEntryList`. A private + /// initializer's or subscript's mangled name carries none of its own + /// (`Holder.(in _C017…).init(argument:)`), so theirs reads `init` or + /// `subscript`. `nil` only for a name of a shape nothing here expects. + public let name: String? + + /// `_` followed by the 32 uppercase hexadecimal digits of + /// `MD5(module name + source file name)`, the compiler's + /// `SourceFile::getPrivateDiscriminator`. + public let discriminator: String + + public init(name: String?, discriminator: String) { + self.name = name + self.discriminator = discriminator + } +} + +extension DemanglingNode { + /// The private declarations this name reads, in the order it reads them, + /// each once. + /// + /// A name printed for a reader leaves its discriminators out; this is + /// where they are kept. The whole tree is read — the declaration's own + /// name, every enclosing context, an extension's extended type and + /// requirements, a specialized type's generic arguments — except for two + /// parts: + /// + /// - The signature of a function, closure, variable, subscript or + /// initializer the name runs through: its argument labels, parameter + /// types and result type. A local type's name runs through the + /// function declaring it, + /// `InPrivateSignature #1 in M.Holder.(takes in _C017…)(M.(PrivateArgument in _C017…)) -> Any`, + /// and the name a reader is shown of it + /// (`DefinitionName.localTypeDisplayName`) leaves the signature out: + /// the method is read, `PrivateArgument` is not. + /// - A position-based local type's address + /// (`LocalTypeNaming.positionBased`): `$1a2b3c` has a private name's + /// shape, but is no discriminator. + public var privateDeclarations: [PrivateDeclaration] { + var privateDeclarations: [PrivateDeclaration] = [] + // Walked with an explicit stack, in preorder: a name's tree has no + // depth limit a recursion could rely on. + var pendingNodes: [(node: Self, parentKind: Node.Kind?)] = [(self, nil)] + while let (node, parentKind) = pendingNodes.popLast() { + if node.kind == .privateDeclName { + if let privateDeclaration = node.privateDeclaration(declaredBy: parentKind), !privateDeclarations.contains(privateDeclaration) { + privateDeclarations.append(privateDeclaration) + } + continue + } + let readsSignature = !node.kind.declaresSignature + for child in node.children.reversed() where readsSignature || !child.kind.isSignaturePart { + pendingNodes.append((child, node.kind)) + } + } + return privateDeclarations + } + + /// Whether this is a position-based local type's private name: the + /// address of the anonymous context wrapping the type, which a + /// compiler-written discriminator never starts with. + package var isPositionBasedPrivateName: Bool { + kind == .privateDeclName && children.first?.text?.hasPrefix("$") == true + } + + /// The declaration this `privateDeclName` names, under a parent of + /// `parentKind`; `nil` for a position-based local type's. + private func privateDeclaration(declaredBy parentKind: Node.Kind?) -> PrivateDeclaration? { + guard !isPositionBasedPrivateName, let discriminator = children.first?.text else { return nil } + if let name = children.at(1)?.text { + return PrivateDeclaration(name: name, discriminator: discriminator) + } + switch parentKind { + case .allocator?, .constructor?: + return PrivateDeclaration(name: "init", discriminator: discriminator) + case .subscript?: + return PrivateDeclaration(name: "subscript", discriminator: discriminator) + default: + return PrivateDeclaration(name: nil, discriminator: discriminator) + } + } +} + +extension Node.Kind { + /// The declarations whose children include a signature: argument labels + /// and a function type, or a variable's type. The children are laid out + /// by the demangler's `demanglePlainFunction`, `demangleEntity`, + /// `demangleFunctionEntity` and `demangleSubscript`; a private + /// subscript's or initializer's `privateDeclName` is a child of its own, + /// not part of the signature. + fileprivate var declaresSignature: Bool { + switch self { + case .function, .variable, .subscript, .allocator, .constructor, .explicitClosure, .implicitClosure, .macro: + return true + default: + return false + } + } + + fileprivate var isSignaturePart: Bool { + self == .type || self == .labelList + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName+LocalTypeDisplayName.swift b/Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName+LocalTypeDisplayName.swift new file mode 100644 index 000000000..37effc605 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName+LocalTypeDisplayName.swift @@ -0,0 +1,85 @@ +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftInspection + +extension DefinitionName { + /// The name a reader is shown of a type declared in a function or + /// closure body, or of a type nested in one; `nil` for any other type + /// (evolution proposal `private-declarations`). + /// + /// The compiler's name of such a type carries the declaring function's + /// whole signature, `Visitor #1 in M.Holder.countValues() -> Any`. Shown + /// to a reader it leaves the modules and the parameter and result types + /// out and keeps the ordinal: `Visitor #1 in Holder.countValues()` — + /// short enough to list, and still telling apart the `Visitor`s two + /// methods of one type declare. A type nested in one reads + /// `Element in Generator #1 in Holder.nested()`. + /// + /// A position-based local type (`LocalTypeNaming.positionBased`) has no + /// function to name, and keeps the address of the anonymous context + /// wrapping it, `Holder.(Visitor in $1a2b3c)`: it is the one thing that + /// tells the unnamed `Visitor`s of `Holder` apart. Real private + /// discriminators are left out either way. + public var localTypeDisplayName: String? { + switch node.nearestLocalTypeNaming { + case .compilerSpelled?: + return node.print(using: .localTypeDisplayName) + case .positionBased?: + let readableNode = PrivateDiscriminatorRemover().rewrite(node.materialize()) + return readableNode.print(using: DemangleOptions.localTypeDisplayName.union(.showPrivateDiscriminators)) + case nil: + return nil + } + } +} + +extension DemangleOptions { + /// A local type's compiler-spelled name the way a reader says it: no + /// modules, no parameter or result types, the `#1` ordinal kept. + fileprivate static let localTypeDisplayName = DemangleOptions.simplified.union(.displayLocalNameContexts) +} + +extension NodeReference { + /// How the nearest local type this name runs through is named — the + /// type itself, or a type it is nested in — or `nil` when it runs + /// through none. + fileprivate var nearestLocalTypeNaming: LocalTypeNaming? { + var current = self + while true { + if let localTypeNaming = current.localTypeNaming { + return localTypeNaming + } + while current.kind.wrapsANominal, let wrapped = current.children.first { + current = wrapped + } + guard current.kind.isAnyGeneric, let context = current.children.first else { + return nil + } + current = context + } + } +} + +extension Node.Kind { + /// The kinds a nominal's name sits under: the demangling's root, a type, + /// and a bound generic type, whose first child is the unbound one. + fileprivate var wrapsANominal: Bool { + switch self { + case .global, .type, .boundGenericStructure, .boundGenericClass, .boundGenericEnum, .boundGenericOtherNominalType: + return true + default: + return false + } + } +} + +/// Replaces every compiler-written `privateDeclName` with the name it +/// declares, keeping position-based ones, so that a tree printed with +/// `showPrivateDiscriminators` shows the `$` addresses alone. +private final class PrivateDiscriminatorRemover: Node.Rewriter { + override func visit(_ node: Node) -> Node { + guard node.kind == .privateDeclName, !node.isPositionBasedPrivateName, let name = node.children.at(1) else { + return node + } + return name + } +} diff --git a/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift new file mode 100644 index 000000000..cb9fe0a95 --- /dev/null +++ b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift @@ -0,0 +1,205 @@ +import Foundation +import MachOKit +import MachOSwiftSection +@_spi(Core) import MachOObjCSection +@_spi(Internals) import Demangling +import SwiftDeclaration +@_spi(Support) import SwiftIndexing +import SwiftInspection + +/// The source files of an image's private discriminators, recovered on +/// demand and remembered (evolution proposal `private-declarations`). +/// +/// The candidates come from the image itself: the names of every Swift type, +/// protocol and extension its indexer holds, with the private declarations +/// each reads, and the names of its Objective-C classes and protocols. They +/// are read on the first request, and every answer is kept — a discriminator +/// nothing recovers too, which is the slowest one to search for — so asking +/// again costs a lookup. A host keeps one per image and drops it with the +/// image. +/// +/// `@unchecked Sendable`: the candidates and answers are only read and +/// written under `lock`. The image's names are read outside it, on a large +/// stack: reading them prints every name the image declares, and nothing +/// demangles under a lock. Two first requests that overlap therefore both +/// read them, and the one that comes back second drops what it read. The +/// search runs under the lock, so two requests for one image still search +/// once. Once the candidates are built, the names closure is let go of, and +/// with it what it captured — an indexer, and through it the image's caches. +public final class PrivateDiscriminatorSourceFileIndex: @unchecked Sendable { + private enum Answer { + case recovered(PrivateDiscriminatorSourceFiles.SourceFile) + case unrecovered + } + + private let imagePath: String + + private let knownFileNames: [String] + + private let lock = NSLock() + + /// Reads the image's names; `nil` once the candidates are built. + private var imageNames: (@Sendable () -> [PrivateDiscriminatorSourceFiles.ImageName])? + + private var candidates: PrivateDiscriminatorSourceFiles.Candidates? + + private var answerByDiscriminator: [String: Answer] = [:] + + private var numberOfSearches = 0 + + /// How many searches have run: one for each request that brought a + /// discriminator not asked for before. Read by the tests. + var searchCount: Int { + lock.lock() + defer { lock.unlock() } + return numberOfSearches + } + + /// - Parameters: + /// - imagePath: The image the names come from. Its file name is the + /// first module name tried. + /// - knownFileNames: File names to try before any is derived from the + /// image's names. + /// - imageNames: Every name the image declares. Called on the first + /// request — by each of two first requests that overlap — on a large + /// stack and outside the index's lock, and let go of once the + /// candidates are built. + public init( + imagePath: String, + knownFileNames: [String] = PrivateDiscriminatorSourceFiles.knownFileNames, + imageNames: @escaping @Sendable () -> [PrivateDiscriminatorSourceFiles.ImageName] + ) { + self.imagePath = imagePath + self.knownFileNames = knownFileNames + self.imageNames = imageNames + } + + /// The image of a prepared indexer, loaded into this process. The index + /// holds the indexer until it has read the names. + @_spi(Support) + public convenience init(indexer: SwiftDeclarationIndexer, knownFileNames: [String] = PrivateDiscriminatorSourceFiles.knownFileNames) { + self.init(imagePath: indexer.machO.imagePath, knownFileNames: knownFileNames) { + Self.swiftNames(in: indexer) + Self.objectiveCNames(in: indexer.machO) + } + } + + /// The image of a prepared indexer, read from a file or a dyld shared + /// cache. The index holds the indexer until it has read the names. + @_spi(Support) + public convenience init(indexer: SwiftDeclarationIndexer, knownFileNames: [String] = PrivateDiscriminatorSourceFiles.knownFileNames) { + self.init(imagePath: indexer.machO.imagePath, knownFileNames: knownFileNames) { + Self.swiftNames(in: indexer) + Self.objectiveCNames(in: indexer.machO) + } + } + + /// The source file of each of `discriminators` that a candidate + /// produces; a discriminator none does is left out. + /// + /// Only the discriminators not asked for before are searched for. A + /// search costs one hash per candidate and module name, and one for a + /// discriminator nothing recovers runs through every candidate: in a + /// debug build that is seconds for SwiftUI. Ask for the ones shown. + public func sourceFiles(forDiscriminators discriminators: some Sequence) -> [String: PrivateDiscriminatorSourceFiles.SourceFile] { + let requestedDiscriminators = Set(discriminators) + // Read outside the lock and on a large stack: reading the names + // prints every one of them, and the request may come from a + // cooperative thread's 512 KB stack. One hop for the whole batch; + // a thread that already has the stack reads them where it is. + let readCandidates = imageNamesToRead(forDiscriminators: requestedDiscriminators).map { imageNames in + PrivateDiscriminatorSourceFiles.Candidates(imagePath: imagePath, imageNames: StackSafeExecutor.withLargeStack { imageNames() }) + } + lock.lock() + defer { lock.unlock() } + // Another first request may have built them meanwhile: those stay, + // and these are dropped. + if candidates == nil, let readCandidates { + candidates = readCandidates + imageNames = nil + } + let unansweredDiscriminators = requestedDiscriminators.filter { answerByDiscriminator[$0] == nil } + if !unansweredDiscriminators.isEmpty, let candidates { + numberOfSearches += 1 + let search = PrivateDiscriminatorSourceFiles(recovering: unansweredDiscriminators, candidates: candidates, knownFileNames: knownFileNames) + // A search also finds the file a synthesized one was made for. + for (discriminator, sourceFile) in search.sourceFileByDiscriminator { + answerByDiscriminator[discriminator] = .recovered(sourceFile) + } + for discriminator in unansweredDiscriminators where answerByDiscriminator[discriminator] == nil { + answerByDiscriminator[discriminator] = .unrecovered + } + } + var sourceFileByDiscriminator: [String: PrivateDiscriminatorSourceFiles.SourceFile] = [:] + for discriminator in requestedDiscriminators { + if case .recovered(let sourceFile) = answerByDiscriminator[discriminator] { + sourceFileByDiscriminator[discriminator] = sourceFile + } + } + return sourceFileByDiscriminator + } + + /// What reads the image's names, when a request for `discriminators` + /// brings one not answered before and the candidates are not built yet. + private func imageNamesToRead(forDiscriminators discriminators: Set) -> (@Sendable () -> [PrivateDiscriminatorSourceFiles.ImageName])? { + lock.lock() + defer { lock.unlock() } + guard candidates == nil, discriminators.contains(where: { answerByDiscriminator[$0] == nil }) else { return nil } + return imageNames + } + + // MARK: - Names of the Image + + /// The names of every Swift type, protocol and extension `indexer` + /// holds, as a reader is shown them, each with the private declarations + /// it reads. + private static func swiftNames(in indexer: SwiftDeclarationIndexer) -> [PrivateDiscriminatorSourceFiles.ImageName] { + var imageNames: [PrivateDiscriminatorSourceFiles.ImageName] = [] + func append(_ definitionName: some DefinitionName) { + imageNames.append(.init(printedName: definitionName.name, discriminators: definitionName.node.privateDeclarations.map(\.discriminator))) + } + indexer.allTypeDefinitions.keys.forEach(append) + indexer.allProtocolDefinitions.keys.forEach(append) + for extensionDefinitions in [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] { + extensionDefinitions.keys.forEach(append) + } + return imageNames + } + + /// The names of the Objective-C classes and protocols an in-process image + /// declares. A class dyld has realized keeps its read-only data behind + /// its read-write data. + private static func objectiveCNames(in machO: MachOImage) -> [PrivateDiscriminatorSourceFiles.ImageName] { + var names: [String] = [] + for objectiveCClass in machO.objc.classes64 ?? [] { + let readOnlyData = objectiveCClass.classROData(in: machO) + ?? objectiveCClass.classRWData(in: machO).flatMap { $0.classROData(in: machO) ?? $0.ext(in: machO)?.classROData(in: machO) } + if let name = readOnlyData?.name(in: machO) { + names.append(name) + } + } + for objectiveCProtocol in machO.objc.protocols64 ?? [] { + names.append(objectiveCProtocol.mangledName(in: machO)) + } + return objectiveCImageNames(names) + } + + /// The names of the Objective-C classes and protocols an image read from + /// a file or a dyld shared cache declares. + private static func objectiveCNames(in machO: MachOFile) -> [PrivateDiscriminatorSourceFiles.ImageName] { + var names: [String] = [] + for objectiveCClass in machO.objc.classes64 ?? [] { + if let name = objectiveCClass.classROData(in: machO)?.name(in: machO) { + names.append(name) + } + } + for objectiveCProtocol in machO.objc.protocols64 ?? [] { + names.append(objectiveCProtocol.mangledName(in: machO)) + } + return objectiveCImageNames(names) + } + + /// A Swift class or protocol is listed under its mangled runtime name, + /// `_TtC7SwiftUI…`; the Swift names cover it already. + private static func objectiveCImageNames(_ names: [String]) -> [PrivateDiscriminatorSourceFiles.ImageName] { + names.filter { !$0.isEmpty && !$0.hasPrefix("_Tt") }.map { .init(printedName: $0) } + } +} diff --git a/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift new file mode 100644 index 000000000..29e3b6a1c --- /dev/null +++ b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift @@ -0,0 +1,2027 @@ +// Generated by Scripts/GenerateKnownSwiftSourceFileNames.sh. Do not edit. +// +// The names of the Swift source files, tests and benchmarks aside, in: +// - OpenSwiftUIProject/OpenSwiftUI @ aefa4e6edc9c37a992a0cf9c6cf317fb670ed305: SwiftUI and SwiftUICore, whose file names OpenSwiftUI recovered (MIT) +// - swiftlang/swift-foundation @ aadd9259be076a86a7e7918b938751d69dfe1198: Foundation (Apache 2.0) +// - swiftlang/swift @ 488fdfe4523bb35326ca384fda4c00e1e5581301, stdlib/public/: the standard library (Apache 2.0) +// - swiftlang/swift @ 272c466e47507c4c6359f30ab8c9ceea5e7c216d, stdlib/public/Darwin/: the Darwin overlays before most moved into the SDK (Apache 2.0) +// - swiftlang/swift @ 9b963b7c464d06a1bf5aef3aca78c910c0945744, stdlib/public/Darwin/: the last Darwin overlays, Foundation's among them (Apache 2.0) +// +// File names only: nothing else from these repositories is included. + +extension PrivateDiscriminatorSourceFiles { + /// Swift source file names known from public repositories whose code ships in Apple's + /// frameworks, OpenSwiftUI's reconstruction of SwiftUI among them. They are tried first, + /// before any name is derived from an image's own names. + public static let knownFileNames: [String] = knownFileNamesText.split(separator: "\n").map(String.init) + + private static let knownFileNamesText = """ + ALAssetsLibrary.swift + ARKit.swift + ASCII.swift + AVCaptureDevice.swift + AVCapturePhotoOutput.swift + AVCaptureSynchronizedDataCollection.swift + AVCaptureVideoDataOutput.swift + AVError.swift + AVMetadataObject.swift + AbsoluteEdge.swift + Accelerate.swift + AccelerateBuffer.swift + AccentColor.swift + AccessibilityAction.swift + AccessibilityActionCategory.swift + AccessibilityActionKind.swift + AccessibilityActivationPoint.swift + AccessibilityAdditions.swift + AccessibilityAnnouncementPriority.swift + AccessibilityAppIntentAction.swift + AccessibilityAttachmentModifier.swift + AccessibilityChartDescriptor.swift + AccessibilityChildBehavior.swift + AccessibilityChildBehaviorKind.swift + AccessibilityCombinable.swift + AccessibilityConfiguration.swift + AccessibilityContainerModifier.swift + AccessibilityCore.swift + AccessibilityCoreUserSettings.swift + AccessibilityCustomAttributes.swift + AccessibilityCustomContent.swift + AccessibilityDataSeries.swift + AccessibilityDeferredAttachment.swift + AccessibilityDirectTouch.swift + AccessibilityEnvironment.swift + AccessibilityEnvironmentAdditions.swift + AccessibilityFocus.swift + AccessibilityFocusState.swift + AccessibilityFocusStore.swift + AccessibilityGeometry.swift + AccessibilityHeadingLevel.swift + AccessibilityIdentifierStorage.swift + AccessibilityLabel.swift + AccessibilityLabelStorage.swift + AccessibilityLabeledContent.swift + AccessibilityLargeContentView.swift + AccessibilityNode.swift + AccessibilityNodeAttachment.swift + AccessibilityNodeList.swift + AccessibilityNodeProxy.swift + AccessibilityNullableOptionSet.swift + AccessibilityNumeric.swift + AccessibilityProperties+Keys.swift + AccessibilityProperties.swift + AccessibilityQuickAction.swift + AccessibilityRelation.swift + AccessibilityRepresentation.swift + AccessibilityRole.swift + AccessibilityRotor.swift + AccessibilityRotorEntry.swift + AccessibilityRotorEntryBuilder.swift + AccessibilityRotorEntryRange.swift + AccessibilityScrolling.swift + AccessibilityShims.swift + AccessibilityTable.swift + AccessibilityTechnologies.swift + AccessibilityTextContentType.swift + AccessibilityTextLayoutProperties.swift + AccessibilityTraits.swift + AccessibilityTraitsAdditions.swift + AccessibilityValue.swift + AccessibilityViewModifier.swift + AccessibilityVisibility.swift + Actor.swift + ActorQueueManager.swift + AdditiveArithmeticDifferentiation.swift + Address.swift + AffineTransform.swift + Aggregate.swift + AggregatingSymbolSource.swift + Algorithm.swift + AlignedTimelineSchedule.swift + AlignmentGuide.swift + AlignmentLayout.swift + AlignmentWritingModifier.swift + AllowsWindowActivationEventsResponder.swift + AlwaysOn.swift + AlwaysOnBridge.swift + Anchor+Point.swift + Anchor.swift + AnchorShapeStyle.swift + Android.swift + Angle.swift + Animatable.swift + AnimatableArray.swift + AnimatableAttribute.swift + AnimatableModifier.swift + AnimatablePair.swift + AnimatableView.swift + Animation.swift + AnimationCompletion.swift + AnimationContext.swift + AnimationListener.swift + AnimationModifier.swift + AnimationState.swift + AnimationTimelineSchedule.swift + AnsiColor.swift + AnyAnimatableData.swift + AnyCodable.swift + AnyDifferentiable.swift + AnyDragResponder.swift + AnyGesture.swift + AnyHashable.swift + AnyHashable2.swift + AnyLayout.swift + AnyPlatformViewHost.swift + AnyShapeStyle.swift + AnySliderStyle.swift + AnyStyleContext.swift + AnyTransition.swift + AnyUIHostingView.swift + AnyView.swift + App.swift + AppGraph.swift + AppIntentAction.swift + AppKit.swift + AppKitAccessibility.swift + AppKitApp.swift + AppKitAppDelegate.swift + AppKitAppearanceConversions.swift + AppKitColorConversions.swift + AppKitConversions.swift + AppKitDisplayList.swift + AppKitEventBindingBridge.swift + AppKitFeedbackImplementation.swift + AppKitGestureRecognizer.swift + AppKitKeyEventConversions.swift + AppKitProgressView.swift + AppKit_FoundationExtensions.swift + AppWindowsController.swift + Appearance.swift + AppearanceActionModifier.swift + AppearanceActionSceneModifier.swift + AppearsActive.swift + ArchivableProgressView.swift + ArchivableView.swift + ArchivableViewModifier.swift + ArchivedView.swift + ArchivedViewCore.swift + ArchivedViewHost.swift + ArchivedViewInput.swift + ArchivedViewState.swift + Arithmetic.swift + Array.swift + ArrayBody.swift + ArrayBuffer.swift + ArrayBufferProtocol.swift + ArrayCast.swift + ArrayDifferentiation.swift + ArrayShared.swift + ArraySlice.swift + ArrayType.swift + AspectRatioLayout.swift + Assert.swift + AssertCommon.swift + AsymmetricTransition.swift + AsyncCompactMapSequence.swift + AsyncDropFirstSequence.swift + AsyncDropWhileSequence.swift + AsyncFilterSequence.swift + AsyncFlatMapSequence.swift + AsyncImage.swift + AsyncIteratorProtocol.swift + AsyncLet.swift + AsyncMapSequence.swift + AsyncMessage+AsyncSequence.swift + AsyncMessage.swift + AsyncNewDocumentProvider.swift + AsyncPrefixSequence.swift + AsyncPrefixWhileSequence.swift + AsyncSequence.swift + AsyncStream.swift + AsyncStreamBuffer.swift + AsyncThrowingCompactMapSequence.swift + AsyncThrowingDropWhileSequence.swift + AsyncThrowingFilterSequence.swift + AsyncThrowingFlatMapSequence.swift + AsyncThrowingMapSequence.swift + AsyncThrowingPrefixWhileSequence.swift + AsyncThrowingStream.swift + Atomic.swift + AtomicBool.swift + AtomicFloats.swift + AtomicInt.swift + AtomicIntegers.swift + AtomicLazyReference.swift + AtomicMemoryOrderings.swift + AtomicOptional.swift + AtomicPointers.swift + AtomicRepresentable.swift + AtomicStorage.swift + AttributeContainer.swift + AttributeCountInfoKey.swift + AttributeCountTestInfo.swift + AttributeGraphAdditions.swift + AttributeInvalidatingSubscriber.swift + AttributeScope.swift + AttributedString+AttributeTransformation.swift + AttributedString+CharacterView.swift + AttributedString+Guts.swift + AttributedString+IndexTracking.swift + AttributedString+IndexValidity.swift + AttributedString+Runs+AttributeSlices.swift + AttributedString+Runs+Run.swift + AttributedString+Runs.swift + AttributedString+UTF16View.swift + AttributedString+UTF8View.swift + AttributedString+UnicodeScalarView.swift + AttributedString+_InternalRun.swift + AttributedString+_InternalRuns.swift + AttributedString+_InternalRunsSlice.swift + AttributedString.swift + AttributedStringAttribute.swift + AttributedStringAttributeConstrainingBehavior.swift + AttributedStringAttributeStorage.swift + AttributedStringCodable.swift + AttributedStringKey+Extension.swift + AttributedStringProtocol.swift + AttributedSubstring.swift + AutomaticLabeledContentStyle.swift + Availability.swift + Axis.swift + BNNS.swift + BPlistDecodingDocument.swift + BPlistDecodingFormat.swift + BPlistEncodingFormat.swift + BPlistLegacyDecodingFormat.swift + BPlistPrimitive+Scope.swift + BPlistPrimitive.swift + BPlistPrimitiveSource.swift + BPlistScanner.swift + BackdropEffect.swift + BackgroundModifier.swift + BackgroundStyle.swift + Backtrace+Codable.swift + Backtrace.swift + BacktraceFormatter.swift + BacktraceJSONFormatter.swift + BacktracerThreadLocals.swift + Base64.swift + Benchmark.swift + BezierAnimation.swift + BidiClass+ICU.swift + BidirectionalCollection.swift + BinaryFloatingPoint+FormatStyle.swift + BinaryFloatingPoint.swift + BinaryInteger+FormatStyle.swift + BinaryInteger+NumericStringRepresentation.swift + Bindable.swift + Binding+ObjectLocation.swift + Binding.swift + BindingOperations.swift + BitVector.swift + BitVector64.swift + Bitset.swift + BlendMode.swift + BlendModeEffect.swift + Block.swift + BloomFilter.swift + BlurEffect.swift + BlurStyle.swift + BlurTransition.swift + BodyLabelGroupStyle.swift + Bool.swift + BorderlessButtonStyle.swift + BorrowingSequence.swift + Box.swift + Boxing.swift + BridgeObjectiveC.swift + BridgeStorage.swift + Bridgeable.swift + BridgingBuffer.swift + BufferView.swift + BufferViewCompatibility.swift + BufferViewIndex.swift + BufferViewIterator.swift + BuiltInUnicodeScalarSet.swift + Builtin.swift + BuiltinMath.swift + Bundle+Stub.swift + BundleMacro.swift + Button.swift + ButtonBorderShape.swift + ButtonDefaultRenderingModeModifier.swift + ButtonRole.swift + ButtonStyle.swift + ButtonStyleConfiguration.swift + ButtonStyleConvertible.swift + ByteCountFormatStyle.swift + ByteOrder.swift + ByteSwapping.swift + CAHostingLayer.swift + CAHostingLayerEvent.swift + CAHostingLayerPlatformDefinition.swift + CALayerView.swift + CFExecutor.swift + CGAffineTransform+Extension.swift + CGColorConversions.swift + CGFloat.swift + CGImageConversions.swift + CGPoint+Extension.swift + CGPoint+Math.swift + CGRect+Extension.swift + CGSize+Extension.swift + CGSize+Math.swift + CKError.swift + CKFetchRecordZoneChangesOperation.swift + CKRecord.swift + CKRecordValue.swift + CKRecordZone_ID.swift + CKRecord_ID.swift + CKRecord_Reference.swift + CKShare.swift + CKShare_Participant.swift + CKSubscription_NotificationInfo.swift + CLError.swift + CMTime.swift + CMTimeRange.swift + CNError.swift + CString.swift + CTypes.swift + CXProviderConfiguration.swift + CachedEnvironment.swift + CachingMemoryReader.swift + Calendar.swift + CalendarConstants.swift + CalendarDependentFormatStyle.swift + CalendarEra.swift + CalendarUtility.swift + Calendar_Astronomy.swift + Calendar_Autoupdating.swift + Calendar_Bridge.swift + Calendar_Cache.swift + Calendar_Chinese.swift + Calendar_Enumerate.swift + Calendar_Gregorian.swift + Calendar_Hebrew.swift + Calendar_ICU.swift + Calendar_ObjC.swift + Calendar_Protocol.swift + Calendar_Recurrence.swift + CallbacksGesture.swift + CancellableGesture.swift + CapitalizationContextDependentFormatStyle.swift + CatalogAppearance.swift + CatalogLookup.swift + CategoryGesture.swift + Cell.swift + ChangedBodyProperty.swift + Character.swift + CharacterProperties.swift + CharacterSet.swift + CheckClass.swift + CheckedContinuation.swift + Chrono.swift + CircularProgressViewStyle.swift + ClipEffect.swift + Clock.swift + ClosedRange.swift + CocoaArray.swift + CocoaError+FilePath.swift + CocoaError.swift + Codable.swift + CodableAnimation.swift + CodableAttributedString.swift + CodableEffectAnimation.swift + CodableHelpers.swift + CodableUtilities.swift + CodableWithConfiguration.swift + Collection Stdlib Defaults.swift + Collection+Extension.swift + Collection.swift + CollectionAlgorithms.swift + CollectionDifference.swift + CollectionOfOne.swift + Collections+DataProtocol.swift + Color+ShapeStyle.swift + Color.swift + ColorMatrix.swift + ColorNonDarwinShims.swift + ColorScheme.swift + ColorView.swift + CombineTypealiases.swift + CombiningTransition.swift + CommandFlag.swift + CommandGroup.swift + CommandLine.swift + CommandOperation.swift + Commands.swift + CommandsInputs.swift + CommandsList.swift + CompactBacktrace.swift + CompactImageMap.swift + Comparable+Extension.swift + Comparable.swift + Comparison.swift + ComparisonResult.swift + Compatibility.swift + CompilerProtocols.swift + CompositingGroupEffect.swift + Compression.swift + ConcatenatedCollection.swift + Conditional.swift + ConditionalCommands.swift + ConditionalContent.swift + ConditionalGraphicsView.swift + ConditionalMetadata.swift + ConditionallyArchivableView.swift + ConfigurationBasedResolvableStringAttribute.swift + Conjunction.swift + ConstCell.swift + ConstantColor.swift + ContainerShape.swift + ContainerValueKey.swift + ContainerValueWritingModifier.swift + ContainerValues.swift + ContentPathObserver.swift + ContentShapeKindModifier.swift + ContentShapeKinds.swift + ContentShapeModifier.swift + ContentSizeCategory.swift + ContentStyle.swift + ContentTransition.swift + ContentTransitionProvidingFormatStyle.swift + Context.swift + ContiguousArray.swift + ContiguousArrayBuffer.swift + ContiguousBytes.swift + ContiguouslyStored.swift + Continuation.swift + ContinuousClock.swift + ContinuousObservation.swift + ControlSize.swift + Conversion.swift + CooperativeExecutor.swift + CoordinateSpace.swift + CoordinateSpaceGesture.swift + CoordinateSpaceModifier.swift + CoordinateSpaceProtocol.swift + CoreAudio.swift + CoreColor.swift + CoreFont.swift + CoreFoundation.swift + CoreFoundationNonDarwinShims.swift + CoreGlue.swift + CoreGraphics.swift + CoreImage.swift + CorePlatformImage.swift + CoreSymbolication.swift + CoreSystemUtils.swift + CoreTesting.swift + CoreText+Private.swift + CoreTextUtil.swift + CoreUIDefaultSystemColorDefinition.swift + CoreUIShims.swift + CoreUISystemCatalogColorName.swift + CrashLog.swift + CrashLogCapture.swift + CurrentEventProvider.swift + CustomAnimation.swift + CustomAnimationModifier.swift + CustomEventTrace.swift + CustomFont.swift + CustomRecursiveStringConvertible.swift + CustomView.swift + CustomViewCountCache.swift + CustomViewModifier.swift + CxxConvertibleToBool.swift + CxxConvertibleToCollection.swift + CxxDictionary.swift + CxxIterable.swift + CxxOptional.swift + CxxPair.swift + CxxRandomAccessCollection.swift + CxxSequence.swift + CxxSet.swift + CxxSpan.swift + CxxVector.swift + CycleDetector.swift + DarwinImpl.swift + Data+Base64.swift + Data+Bridging.swift + Data+Deprecated.swift + Data+Error.swift + Data+Inline.swift + Data+InlineSlice.swift + Data+Iterator.swift + Data+LargeSlice.swift + Data+LegacyRepresentation.swift + Data+Reading.swift + Data+Representation.swift + Data+Searching+BoyerMoore.swift + Data+Searching.swift + Data+Writing.swift + Data+WritingOptions.swift + Data.swift + DataProtocol.swift + DataStorage.swift + Date+AnchoredRelativeFormatStyle.swift + Date+ComponentsFormatStyle+Stub.swift + Date+FormatStyle.swift + Date+HTTPFormatStyle.swift + Date+ICU.swift + Date+ISO8601FormatStyle.swift + Date+IntervalFormatStyle.swift + Date+Locale.swift + Date+RelativeFormatStyle.swift + Date+VerbatimFormatStyle.swift + Date.swift + DateComponents+ISO8601FormatStyle.swift + DateComponents.swift + DateFieldSymbol.swift + DateFormatString.swift + DateFormatStyle.swift + DateInterval.swift + DateParseStrategy.swift + DebugReplaceableView.swift + Debugger.swift + DebuggerSupport.swift + Decimal+Compatibility.swift + Decimal+Conformances.swift + Decimal+FormatStyle.swift + Decimal+Math.swift + Decimal+ParseStrategy.swift + Decimal.swift + DefaultAnimation.swift + DefaultCombiningAnimation.swift + DefaultDescriptionAttribute.swift + DefaultDividerStyle.swift + DefaultFocus.swift + DefaultFocusEvaluationPriority.swift + DefaultLabelStyle.swift + DefaultLayoutViewResponder.swift + DefaultPadding.swift + DefaultParameters.swift + DefaultProgressViewStyle.swift + DefaultStyle.swift + DefaultSymbolLocator.swift + DelayAnimation.swift + DelayedGesture.swift + Deque+Codable.swift + Deque+Collection.swift + Deque+CustomDebugStringConvertible.swift + Deque+CustomReflectable.swift + Deque+CustomStringConvertible.swift + Deque+Equatable.swift + Deque+ExpressibleByArrayLiteral.swift + Deque+Extras.swift + Deque+Hashable.swift + Deque+Storage.swift + Deque+Testing.swift + Deque+UnsafeHandle.swift + Deque.swift + DerivedLayoutEngine.swift + Dictionary.swift + DictionaryBridging.swift + DictionaryBuilder.swift + DictionaryCasting.swift + DictionaryStorage.swift + DictionaryVariant.swift + Differentiable.swift + DifferentialOperators.swift + DifferentiationUtilities.swift + Diffing.swift + Direction.swift + DiscardingTaskGroup.swift + Disconnected.swift + DiscontiguousAttributedSubstring.swift + DiscontiguousSlice.swift + DiscreteFormatStyle.swift + Disjunction.swift + Dispatch.swift + DispatchData+DataProtocol.swift + DispatchExecutor.swift + DisplayList.GraphicsRenderer.swift + DisplayList.swift + DisplayListAnimations.swift + DisplayListAsyncLayer.swift + DisplayListPlatformEffect.swift + DisplayListPrinter.swift + DisplayListStdoutRenderer.swift + DisplayListTransforms.swift + DisplayListUtil.swift + DisplayListViewCache.swift + DisplayListViewDrawing.swift + DisplayListViewModel.swift + DisplayListViewPlatform.swift + DisplayListViewRenderer.swift + DisplayListViewUpdater.swift + DisplayList_StableIdentity.swift + DistanceGesture.swift + DistributedActor.swift + DistributedActorSystem.swift + DistributedAssertions.swift + DistributedDefaultExecutor.swift + DistributedMacros.swift + DistributedMetadata.swift + Divider.swift + DividerStyle.swift + Division.swift + DocumentBaseBox.swift + DocumentBrowserViewController.swift + DocumentCreationStrategy.swift + DocumentKey.swift + Double+Extension.swift + Double.swift + DropWhile.swift + Dump.swift + Duration+Formatting.swift + Duration+TimeFormatStyle.swift + Duration+UnitsFormatStyle.swift + Duration+Utils.swift + Duration.swift + DurationGesture.swift + DurationProtocol.swift + Dwarf.swift + DynamicContainer.swift + DynamicContainerAdaptor.swift + DynamicContainerItem.swift + DynamicLayoutMap.swift + DynamicLayoutView.swift + DynamicProperty.swift + DynamicPropertyBuffer.swift + DynamicTypeSize.swift + DynamicView.swift + DynamicViewContent.swift + DynamicViewListItem.swift + Edge.swift + EdgeInsets.swift + EdgeInsetsConversions.swift + EditMode.swift + EffectiveLabelStyle.swift + EightByteBuffer.swift + EitherSequence.swift + Elf.swift + ElfImageCache.swift + EmbeddedCasting.swift + EmbeddedImpl.swift + EmbeddedPlatformPOSIX.swift + EmbeddedPlatformSingleThreaded.swift + EmbeddedPrint.swift + EmbeddedRuntime.swift + EmbeddedStubs.swift + EmptyCollection.swift + EmptyGesture.swift + EmptyScene.swift + EmptyView.swift + EmscriptenLibc.swift + Enabled.swift + EncodingContainers+PredicateExpression.swift + EntryDefaultValueMacro.swift + EntryMacro.swift + EnumeratedSequence.swift + Environment+Objects.swift + Environment+Observation.swift + Environment+UITraitKey.swift + Environment.swift + EnvironmentAdditions.swift + EnvironmentConfigurableFormatter.swift + EnvironmentHelper.swift + EnvironmentKey+Test.swift + EnvironmentKey.swift + EnvironmentKeyTransformModifier.swift + EnvironmentKeyWritingModifier.swift + EnvironmentObject.swift + EnvironmentParagraphStyle.swift + EnvironmentSceneModifier.swift + EnvironmentValues.swift + EnvironmentWritingModifier.swift + EnvironmentalModifier.swift + EnvironmentalView.swift + Equality.swift + Equatable.swift + EquatableView.swift + ErrorCodes+POSIX.swift + ErrorCodes+Win32.swift + ErrorCodes.swift + ErrorType.swift + Errors.swift + EvaluateDefaultFocusAction.swift + Event.swift + EventBinding.swift + EventBindingBridge.swift + EventBindingManager.swift + EventBindingSource.swift + EventDebug.swift + EventFilter.swift + EventGraphHost.swift + EventID.swift + EventListener.swift + EventModifiers.swift + EventPhase.swift + EventSourceType.swift + EventType.swift + ExampleApp.swift + ExclusiveGesture.swift + Exclusivity.swift + Executor.swift + ExecutorAssertions.swift + ExecutorBridge.swift + ExecutorImpl.swift + ExistentialCollection.swift + Export.swift + Expression.swift + ExpressionEvaluation.swift + FallbackDelegateBox.swift + FallbackLabelStyle.swift + Feature.swift + FeatureFlagsShims.swift + FileManager+Basics.swift + FileManager+Bridge.swift + FileManager+DarwinSearchPaths.swift + FileManager+Directories.swift + FileManager+Files.swift + FileManager+SearchPaths.swift + FileManager+SymbolicLinks.swift + FileManager+Utilities.swift + FileManager+WindowsSearchPaths.swift + FileManager+XDGSearchPaths.swift + FileManager.swift + FileOperations+Enumeration.swift + FileOperations.swift + FileSystemRepresentable.swift + FillStyle.swift + Filter.swift + FilteredTransition.swift + FixedSizeLayout.swift + FlatMap.swift + Flatten.swift + Float.swift + Float16.swift + Float80.swift + FloatingPoint+Extension.swift + FloatingPoint.swift + FloatingPointDifferentiation.swift + FloatingPointFormatStyle.swift + FloatingPointFromString.swift + FloatingPointParseStrategy.swift + FloatingPointParsing.swift + FloatingPointRandom.swift + FloatingPointToString.swift + FluidSpringAnimation.swift + FocusBridge.swift + FocusEffectDelegate.swift + FocusEffectView.swift + FocusEventProxy.swift + FocusGroup.swift + FocusItem.swift + FocusNavigator.swift + FocusResponder.swift + FocusRingHelper.swift + FocusState.swift + FocusStore.swift + FocusStoreList.swift + FocusViewGraph.swift + Focusable.swift + FocusedValue.swift + Font.swift + FontDefinition.swift + FontNonDarwinShims.swift + ForEach.swift + ForegroundColor.swift + ForegroundLayerEffect.swift + ForegroundStyle.swift + FormatParsingUtilities.swift + FormatStyle.swift + FormatterCache.swift + Foundation+ProtobufMessage.swift + Foundation.swift + FoundationAdditions.swift + FoundationAttributes.swift + FoundationEssentials.swift + FoundationMacros.swift + FoundationShims.swift + FrameLayout.swift + FramePointerUnwinder.swift + FreeBSDImpl.swift + FullyInhabited.swift + FunctionInfo.swift + GLKMath.swift + GameplayKit.swift + GeometryActionModifier.swift + GeometryEffect.swift + GeometryReader.swift + Gesture.swift + GestureCategory.swift + GestureContainerFactory.swift + GestureDebug.swift + GestureDependency.swift + GestureDescriptor.swift + GestureFeature.swift + GestureGraph.swift + GestureInputs.swift + GestureLabelModifier.swift + GestureMask.swift + GestureModifier.swift + GestureOutputs.swift + GesturePhase.swift + GestureState.swift + GestureViewModifier.swift + Glibc.swift + GlobalActor.swift + GlobalConcurrentExecutor.swift + GlobalCoordinateSpace.swift + GradientColorSpace.swift + Graph.swift + GraphHost.swift + GraphInputs.swift + GraphReuse.swift + GraphValue.swift + GraphicsContext.swift + GraphicsConversions.swift + GraphicsFilter.swift + GraphicsImage.swift + Group.swift + GroupedFormLabeledContentStyle.swift + HStack.swift + HVStack.swift + HashTable.swift + Hashable.swift + Hasher.swift + Hashes.swift + Hashing.swift + HiddenModifier.swift + HitTestBindingModifier.swift + HitTestableEvent.swift + HitTestingDebug.swift + HitTestingSupport.swift + HomeKit.swift + HostingControllerUtilities.swift + HostingViewRegistry.swift + HostingViewTransparentBackgroundReason.swift + HoverEvent.swift + IANACharsetNames.swift + ICU+CaseMap.swift + ICU+Enumeration.swift + ICU+Enums.swift + ICU+FieldPositer.swift + ICU+Foundation.swift + ICU+ResourceBundle.swift + ICU+StringConverter.swift + ICUDateFormatter.swift + ICUDateIntervalFormatter.swift + ICULegacyNumberFormatter.swift + ICUListFormatter.swift + ICUNumberFormatter.swift + ICUPatternGenerator.swift + ICURelativeDateFormatter.swift + IDView.swift + INBooleanResolutionResult.swift + INCallRecord.swift + INDoubleResolutionResult.swift + INGetCarLockStatusIntentResponse.swift + INGetCarPowerLevelStatusIntentResponse.swift + INIntegerResolutionResult.swift + INIntent.swift + INNotebookItemTypeResolutionResult.swift + INParameter.swift + INPlayMediaIntent.swift + INRequestRideIntent.swift + INRideOption.swift + INSaveProfileInCarIntent.swift + INSearchCallHistoryIntent.swift + INSearchForPhotosIntentResponse.swift + INSetCarLockStatusIntent.swift + INSetClimateSettingsInCarIntent.swift + INSetDefrosterSettingsInCarIntent.swift + INSetProfileInCarIntent.swift + INSetRadioStationIntent.swift + INSetSeatSettingsInCarIntent.swift + INShortcut.swift + INStartPhotoPlaybackIntentResponse.swift + INStartWorkoutIntent.swift + IO.swift + IOReturn.swift + ISO8859-1.swift + IconOnlyLabelStyle.swift + Identifiable.swift + IdentifiedModifier.swift + IdentifiedPreference.swift + IdentifiedViewProxy.swift + IdentifiedViewTree.swift + IdentifiedViewsKey.swift + IdentityLink.swift + IgnoredByLayoutEffect.swift + Image+Accessibility.swift + Image+PlatformRepresentation.swift + Image.swift + ImageDynamicRange.swift + ImageLayer.swift + ImageMap+Darwin.swift + ImageMap+Linux.swift + ImageMap+Win32.swift + ImageMap.swift + ImageOrientation.swift + ImageRenderingMode.swift + ImageResizing.swift + ImageSource.swift + ImageStyle.swift + ImplicitShapeStyle.swift + IncludesStyledText.swift + IndexPath.swift + IndexSet.swift + Indices.swift + Inequality.swift + InitialSceneSizeState.swift + InlineArray.swift + InputStream.swift + InsetViewModifier.swift + InsettableShape.swift + Instant.swift + Int128.swift + IntegerFormatStyle.swift + IntegerParseStrategy.swift + IntegerParsing.swift + IntegerTypes.swift + Integers.swift + InterfaceIdiom.swift + InterfaceIdiomDependentFormatStyle.swift + InterfaceIdiomPredicate.swift + InterpolatableContent.swift + InterpolatedShapeStyle.swift + IsInHostingConfiguration.swift + IsVisionEnabled.swift + IterativeParsingDriver.swift + IterativeParsingSupport.swift + JSON.swift + JSON5Scanner.swift + JSONDecoder.swift + JSONDecoderImpl.swift + JSONEncoder.swift + JSONMap.swift + JSONMapBuildingSink.swift + JSONPrimitive+Scope.swift + JSONPrimitive.swift + JSONPrimitiveSource.swift + JSONScanner.swift + JSONScannerEventSource.swift + JSONWriter.swift + JindoTripleVStack.swift + Join.swift + KeyEvent.swift + KeyPath+Inspection.swift + KeyPath.swift + KeyPathComparator.swift + KeyPressModifier.swift + KeyValuePairs.swift + KeyboardShortcut.swift + KeyboardShortcutPickerOptionTraitKey.swift + KitAccentColorProvider.swift + KitCoreUINamedColorProvider.swift + Label.swift + LabelGroup.swift + LabelGroupStyle.swift + LabelStyle.swift + LabelVisibility.swift + LabeledContent.swift + LabeledContentStyleConfiguration.swift + LabeledView.swift + LabelsHiddenModifier.swift + LaunchTestSupport.swift + Layout.swift + LayoutComputer.swift + LayoutDirection.swift + LayoutDirectionBehavior.swift + LayoutGesture.swift + LayoutPriority.swift + LayoutProxy.swift + LayoutTrace.swift + LayoutTraits.swift + LayoutView.swift + LazyCollection.swift + LazyContainer.swift + LazyLayout.swift + LazySequence.swift + LazyState.swift + LazyView.swift + LeadingTrailingLabeledContentStyle.swift + LeafViewResponder.swift + LegacyABI.swift + LegacyApp.swift + Libc.swift + LifetimeManager.swift + LimitSequence.swift + LimitedAvailabilityCommandContent.swift + LimitedAvailabilityScene.swift + LineLimits.swift + LinearProgressViewStyle.swift + Link.swift + LinuxImpl.swift + ListFormatData.swift + ListFormatLookup.swift + ListFormatStyle.swift + ListFormatterImpl.swift + ListLabelStyle.swift + ListStyle.swift + LocalCoordinateSpace.swift + LocalTestingDistributedActorSystem.swift + Locale+Components.swift + Locale+Components_ICU.swift + Locale+Language.swift + Locale.swift + Locale_Autoupdating.swift + Locale_Bridge.swift + Locale_Cache.swift + Locale_ICU.swift + Locale_Notifications.swift + Locale_ObjC.swift + Locale_Preferences.swift + Locale_Protocol.swift + Locale_Unlocalized.swift + LocalizedString.swift + Location.swift + Locking.swift + Logging.swift + LogicalCompletionAnimation.swift + LuminanceReduced.swift + MPMusicPlayerPlayParameters.swift + Macros.swift + MagnifyEvent.swift + MainActor.swift + MainActorMessage.swift + MainActorUtils.swift + MainMenuItem.swift + ManagedBuffer.swift + Mangling.swift + Map.swift + Map2Gesture.swift + MapGesture.swift + MaskLayer.swift + MatchedGeometryEffect.swift + Material.swift + Math.swift + Measurement+FormatStyle+Stub.swift + Measurement.swift + MemoryLayout.swift + MemoryReader.swift + Metal.swift + MetalKit.swift + MigrationSupport.swift + Mirror.swift + Mirrors.swift + Misc.swift + ModelIO.swift + ModifiedColor.swift + ModifiedFont.swift + ModifierKeySource.swift + ModifierKeysChanged.swift + ModifierTransition.swift + Module.swift + MouseEvent.swift + MoveTransition.swift + MultiStreamFile.swift + MultiViewResponder.swift + MultimodalListStyle.swift + Musl.swift + MutableCollection+Extension.swift + MutableCollection.swift + MutableRawSpan.swift + MutableRef.swift + MutableSpan.swift + Mutex+ExtendedLifetime.swift + Mutex.swift + MutexUnavailable.swift + NFC.swift + NFD.swift + NLLanguageRecognizer.swift + NLTagger.swift + NLTokenizer.swift + NSApplicationDelegateAdaptor.swift + NSArray.swift + NSAttributedString+Accessibility.swift + NSAttributedString+Extension.swift + NSCoder.swift + NSData+DataProtocol.swift + NSDate.swift + NSDictionary.swift + NSError.swift + NSEvent.swift + NSExpression.swift + NSFastEnumeration.swift + NSGeometry.swift + NSGraphics.swift + NSHostingController.swift + NSHostingSceneBridgingOptions.swift + NSHostingSizingOptions.swift + NSHostingView.swift + NSImageConversions.swift + NSIndexSet.swift + NSItemProvider.swift + NSManagedObjectContext.swift + NSNumber.swift + NSObject.swift + NSOpenGL.swift + NSOrderedCollectionDifference.swift + NSPredicate.swift + NSPredicateConversion.swift + NSRange.swift + NSSet.swift + NSSortDescriptor.swift + NSString.swift + NSStringAPI.swift + NSStringEncodings.swift + NSStringIntents.swift + NSTextCheckingResult.swift + NSURL.swift + NSUndoManager.swift + NSValue.swift + NSViewControllerRepresentable.swift + NSViewRepresentable.swift + NSViewResponder.swift + NWConnection.swift + NWEndpoint.swift + NWError.swift + NWListener.swift + NWParameters.swift + NWPath.swift + NWProtocol.swift + NWProtocolIP.swift + NWProtocolTCP.swift + NWProtocolTLS.swift + NWProtocolUDP.swift + NameTableNI.swift + NamedColor.swift + NamedCoordinateSpace.swift + NamedImage.swift + Namespace.swift + NativeDictionary.swift + NativeSet.swift + NavigationAuthority.swift + NavigationPreferenceKey.swift + Negation.swift + NestedNames.swift + Network.swift + Never+View.swift + NewtypeWrapper.swift + NonGestureEventType.swift + Notification.swift + NotificationCenter.swift + NotificationCenterMessage.swift + NumberAttributedFormat.swift + NumberFormatStyleConfiguration.swift + NumericDifferentiation.swift + OSReleaseScanner.swift + ObjectCache.swift + ObjectIdentifier+DebugDescription.swift + ObjectIdentifier.swift + ObjectiveC.swift + Observable.swift + ObservableObjectDescriptor.swift + ObservationRegistrar.swift + ObservationTracking.swift + ObservationUtils.swift + Observations.swift + ObservedObject.swift + OffsetEffect.swift + OffsetShapeStyle.swift + OpacityEffect.swift + OpenBSDImpl.swift + OpenCL.swift + OpenStepPlist.swift + OpenSwiftUIGlue.swift + OpenSwiftUIMacrosPlugin.swift + OpenURLAction.swift + OptionSet+Extension.swift + OptionSet.swift + Optional.swift + OptionalDifferentiation.swift + OptionalGesture.swift + OptionalView.swift + OutputRawSpan.swift + OutputSpan.swift + OutputStream.swift + OverlayModifier.swift + PDBCache.swift + PDBFile+SymbolSource.swift + PDBFile.swift + PHChange.swift + PHProjectChangeRequest.swift + POSIXError.swift + Package.swift + PaddingLayout.swift + Paint.swift + PanEvent.swift + ParagraphTypesetting.swift + ParseEventVocabularies.swift + ParseStrategy.swift + ParseableFormatStyle.swift + PartialAsyncTask.swift + Path.swift + PathData.swift + PeCoff.swift + PeImageCache.swift + PerformanceTest.swift + PersonNameComponents.swift + PhysicalButtonEvent.swift + PhysicalButtonPressGesture.swift + Placement.swift + PlacementContext.swift + PlainButtonStyle.swift + PlainDividerStyle.swift + Platform.swift + PlatformAlias.swift + PlatformDrawable.swift + PlatformEnvironment.swift + PlatformExecutorCooperative.swift + PlatformExecutorDarwin.swift + PlatformExecutorFreeBSD.swift + PlatformExecutorLinux.swift + PlatformExecutorNone.swift + PlatformExecutorOpenBSD.swift + PlatformExecutorWindows.swift + PlatformFocusViewProvider.swift + PlatformGestureInputs.swift + PlatformHostingControllerHelper.swift + PlatformImage.swift + PlatformItemList.swift + PlatformItemListFlag.swift + PlatformItemListGenerator.swift + PlatformItems.swift + PlatformItemsStrategy.swift + PlatformListCell.swift + PlatformSceneCache.swift + PlatformUnaryViewResponder.swift + PlatformView+SafeArea.swift + PlatformViewCoordinator.swift + PlatformViewFactory.swift + PlatformViewHost.swift + PlatformViewRepresentable.swift + PlatformViewRepresentableContext.swift + PlatformViewRepresentableLayoutOptions.swift + PlatformViewResponderBase.swift + PlaygroundDisplay.swift + PlistDecoder.swift + PlistDecoderGeneric.swift + PlistDictionaryDecoder.swift + PlistDictionaryEncoder.swift + PlistEncoder.swift + PlistEncoderGeneric.swift + Pointer.swift + Pointers+DataProtocol.swift + Policy.swift + PositionLayout.swift + Predicate+Codable.swift + Predicate+Description.swift + Predicate.swift + PredicateBindings.swift + PredicateCodableConfiguration.swift + PredicateEvaluation.swift + PredicateExpression.swift + PredicateExpressionConstruction.swift + PredicateMacro.swift + PreferenceActionModifier.swift + PreferenceBridge.swift + PreferenceCombiner.swift + PreferenceKey.swift + PreferenceList.swift + PreferenceSceneModifier.swift + PreferenceTransformModifier.swift + PreferenceWritingModifier.swift + PreferencesInputs.swift + PreferencesOutputs.swift + PreferredColorScheme.swift + PrefixWhile.swift + PresentedSceneValueInputModifier.swift + Prespecialize.swift + PreviewColorSchemeTrait.swift + PreviewMacro.swift + PreviewShims.swift + PrimitiveButtonStyle.swift + PrimitiveButtonStyleConfiguration.swift + Print.swift + PriorityQueue.swift + PrivacyRedaction.swift + Private.swift + ProcMapsScanner.swift + ProcessInfo+API.swift + ProcessInfo+ObjC.swift + ProcessInfo.swift + Progress+Stub.swift + Progress.swift + ProgressFraction.swift + ProgressManager+Interop.swift + ProgressManager+Properties+Accessors.swift + ProgressManager+Properties+Definitions.swift + ProgressManager+Properties+Helpers.swift + ProgressManager+State.swift + ProgressManager.swift + ProgressReporter.swift + ProgressView+Date.swift + ProgressView+Foundation.swift + ProgressView.swift + ProgressViewStyle.swift + Project.swift + Projection.swift + ProjectionTransform.swift + ProjectionTransformHelper.swift + PropertyList.swift + PropertyListKey+Test.swift + ProposedSize.swift + ProtobufDecoder.swift + ProtobufEncoder.swift + ProtobufMessage.swift + ProtobufTestHelper.swift + ProviderBackedResolvableStringAttribute.swift + PtrAuth.swift + Publishers+KeyValueObserving.swift + Publishers+Locking.swift + Publishers+NotificationCenter.swift + Publishers+Timer.swift + Publishers+URLSession.swift + PushTransition.swift + Quadrature.swift + QuartzCoreShims.swift + Quaternion.swift + Queue.swift + REPL.swift + RGBColorSpace.swift + Random.swift + RandomAccessCollection.swift + Range.swift + RangeExpression.swift + RangeReplaceableCollection.swift + RangeSet.swift + RangeSetRanges.swift + RasterizationOptions.swift + RawSpan.swift + RecurrenceRule.swift + RedactionReasons.swift + ReducedTimelineSchedule.swift + Ref.swift + ReferenceConvertible.swift + ReflectionMirror.swift + Regex.swift + RegexPatternCache.swift + Registers.swift + RenderBoxView.swift + RendererConfiguration.swift + RendererEffect.swift + RendererLeafView.swift + Repeat.swift + RepeatAnimation.swift + RepeatGesture.swift + RequiredTapCount.swift + ResettableGestureRule.swift + ResolvableAbsoluteDate.swift + ResolvableCurrentDate.swift + ResolvableDateInterval.swift + ResolvableProgress.swift + ResolvableStringAttribute.swift + ResolvableTextSegmentAttribute.swift + ResolvableTimer.swift + ResolvedGradient.swift + ResolvedImage.swift + ResolvedMulticolorStyle.swift + ResolvedText.swift + ResponderBasedHitTesting.swift + ResponderNode.swift + ResponderViewModifier.swift + Result+AsyncInit.swift + Result.swift + ReuseTrace.swift + Reverse.swift + RichFrame.swift + RigidArray+Append.swift + RigidArray+Container.swift + RigidArray+Descriptions.swift + RigidArray+Equatable.swift + RigidArray+Hashable.swift + RigidArray+Initializers.swift + RigidArray+Insertions.swift + RigidArray+Removals.swift + RigidArray+Replacements.swift + RigidArray.swift + RootViewForSimplifiedApplicationProvider.swift + RotateEvent.swift + Rotation3DEffect.swift + Rotation3DEffectHelper.swift + RotationEffect.swift + Round+Extension.swift + RoundedCornerStyle.swift + RunLoopUtils.swift + Runtime.swift + RuntimeFunctionCounters.swift + RuntimeIssueHandlingTrait.swift + SExpPrinter.swift + SFSymbolsShims.swift + SIMDDifferentiation.swift + SIMDFloatConcreteOperations.swift + SIMDIntegerConcreteOperations.swift + SIMDMaskConcreteOperations.swift + SIMDVector.swift + SIMDVectorTypes.swift + SafariServices.swift + SafeAreaIgnoringLayout.swift + SafeAreaInsets.swift + SafelySerializableDiscreteFormatStyle.swift + ScaleEffect.swift + ScaledMetric.swift + Scanner.swift + Scene+Environment.swift + Scene.swift + SceneActivationConditions.swift + SceneBridge.swift + SceneBuilder.swift + SceneID.swift + SceneInputs.swift + SceneKit.swift + SceneList.swift + SceneModifier.swift + SceneOutputs.swift + ScenePhase.swift + SceneStorage.swift + Schedulers+Date.swift + Schedulers+DispatchQueue.swift + Schedulers+OperationQueue.swift + Schedulers+RunLoop.swift + ScrapeableContent.swift + ScrollCoordinateSpace.swift + ScrollEventConverter.swift + ScrollGeometry.swift + ScrollPosition+Modifiers.swift + ScrollPosition.swift + ScrollStateRequest.swift + ScrollTarget.swift + ScrollTransactionAdditions.swift + Scrollable.swift + SearchFieldState.swift + SectionInfo.swift + SemanticFeature.swift + Semantics.swift + Sendable.swift + SensoryFeedback.swift + SensoryFeedbackGenerator.swift + SeparatorShapeStyle.swift + Sequence.swift + SequenceAlgorithms.swift + Set.swift + SetAlgebra.swift + SetAnyHashableExtensions.swift + SetBridging.swift + SetBuilder.swift + SetCasting.swift + SetStorage.swift + SetVariant.swift + Shader.swift + ShadowEffect.swift + ShadowProtocols.swift + ShadowStyle.swift + Shape.swift + ShapeLayer.swift + ShapeStyle.swift + ShapeStyleName.swift + ShapeStylePack.swift + ShapeStylePair.swift + ShapeStyleRendering.swift + ShapeStyleResolver.swift + ShapeStyleShape.swift + ShapeStyledLeafView.swift + ShapeView.swift + Shapes.swift + Shims.swift + SidebarLabelStyle.swift + Signposts.swift + SimultaneousGesture.swift + SipHash.swift + SizeAdaptiveFormatStyle.swift + SizeGesture.swift + Slice.swift + SliceBuffer.swift + SlideTransition.swift + Slider.swift + SliderStyleKey.swift + SmallString.swift + Sort.swift + SortComparator.swift + SortDescriptor.swift + Source.swift + SourceCompatibilityShims.swift + Spacer.swift + Spacing.swift + SpacingLayout.swift + Span+Path.swift + Span+Utils.swift + Span.swift + SpatialEvent.swift + SpatialTapGesture.swift + SpeedAnimation.swift + SpinLoopHint.swift + Spring+DurationBounce.swift + Spring+MassStiffnessDamping.swift + Spring+ResponseDampingRatio.swift + Spring+SettlingDurationDampingRatio.swift + Spring+VectorArithmetic.swift + Spring.swift + SpringAnimation.swift + SpringLoadingBehavior.swift + SpriteKit.swift + SpriteKitQuickLooks.swift + Stack.swift + StackLayout.swift + StandardLibraryAdditions.swift + State.swift + StateContainerGesture.swift + StateObject.swift + StaticBigInt.swift + StaticIf.swift + StaticPrint.swift + StaticString.swift + StdoutApp.swift + StdoutRendererHost.swift + StoredLocation.swift + Stride.swift + String+Bridging.swift + String+Comparison.swift + String+Comparison_ICU.swift + String+EncodeAs.swift + String+Encoding+Names.swift + String+Encoding.swift + String+EndianAdaptorSequence.swift + String+Essentials.swift + String+Extension.swift + String+IO.swift + String+Internals.swift + String+Locale.swift + String+Path.swift + String+SortComparator.swift + String.Index+ABI.swift + String.swift + StringBlocks.swift + StringBreadcrumbs.swift + StringBridge.swift + StringCharacterView.swift + StringComparable.swift + StringComparison.swift + StringCreate.swift + StringEncodingMappingData.swift + StringGraphemeBreaking.swift + StringGuts.swift + StringGutsRangeReplaceable.swift + StringGutsSlice.swift + StringHashable.swift + StringIndex.swift + StringIndexConversions.swift + StringIndexValidation.swift + StringInterpolation.swift + StringLegacy.swift + StringNormalization.swift + StringObject.swift + StringProtocol+Essentials.swift + StringProtocol+Locale.swift + StringProtocol+Stub.swift + StringProtocol.swift + StringRangeReplaceableCollection.swift + StringStorage.swift + StringStorageBridge.swift + StringSwitch.swift + StringTesting.swift + StringUTF16View.swift + StringUTF8Validation.swift + StringUTF8View.swift + StringUnicodeScalarView.swift + StringWordBreaking.swift + StrokeStyle.swift + StrokedShape.swift + StrongHash.swift + StyleContext.swift + StyledFormatStyle.swift + StyledTextResponder.swift + Subprogress.swift + SubscriptionLifetime.swift + SubscriptionView.swift + Substring.swift + SuspendingClock.swift + SwiftFileManager.swift + SwiftFileManagerDelegate.swift + SwiftNativeNSArray.swift + SwiftOnoneSupport.swift + SwiftUI.Color.swift + SwiftUI.EnvironmentValues.swift + SwiftifyImport.swift + SwitchToggleStyle.swift + SymbolEffect.swift + SymbolLocator.swift + SymbolRenderingMode.swift + SymbolVariants.swift + SymbolicatedBacktrace.swift + SystemColors.swift + SystemFont.swift + SystemFormatStyle+DateOffset.swift + SystemFormatStyle+DateReference.swift + SystemFormatStyle+Timer.swift + SystemSliderStyle.swift + TKSmartCard.swift + Tag.swift + TagAddition.swift + TapGesture.swift + TappableEvent.swift + TappablePadding.swift + TargetLinux.swift + TargetMacOS.swift + TargetWindows.swift + Task+Deadline.swift + Task+PriorityEscalation.swift + Task+TaskExecutor.swift + Task+immediate.swift + Task+init.swift + Task.swift + TaskCancellation.swift + TaskCancellationScope.swift + TaskGroup+addTask.swift + TaskGroup.swift + TaskLocal.swift + TaskModifier.swift + TaskSleep.swift + TaskSleepDuration.swift + TemporaryAllocation.swift + Test.swift + TestApp+Test.swift + TestApp.swift + TestHost.swift + TestIDView.swift + TestingAppDelegate.swift + TestingSceneDelegate.swift + Text+Accessibility.swift + Text+AlwaysOn.swift + Text+AttributedString.swift + Text+CLKTextProvider.swift + Text+Concatenation.swift + Text+Date.swift + Text+DiscreteFormatStyle.swift + Text+Encapsulation.swift + Text+Formatter.swift + Text+Image.swift + Text+Justification.swift + Text+LayoutShape.swift + Text+LineHeight.swift + Text+Localized.swift + Text+LocalizedStringResource.swift + Text+NSAttributedString.swift + Text+OpenSwiftUI.swift + Text+PlatformRepresentation.swift + Text+Renderer.swift + Text+Scale.swift + Text+Selection.swift + Text+SizeFitting.swift + Text+Sizing.swift + Text+Spacing.swift + Text+StringDrawingContext.swift + Text+Suffix.swift + Text+Superscript.swift + Text+View.swift + Text.swift + TextAlignment.swift + TextAlignmentDependentFormatStyle.swift + TextAnimationsProvider.swift + TextLineStyle.swift + TextLineStyleConversions.swift + TextNonDarwinShims.swift + TextStyle.swift + TgmathDerivatives.swift + Themes.swift + ThreadLocal.swift + ThreadUtils.swift + Time.swift + TimeDataFormatting+Configuration.swift + TimeDataFormatting+Schedule.swift + TimeDataFormatting.swift + TimeInterval+Utils.swift + TimeZone.swift + TimeZoneDependentFormatStyle.swift + TimeZone_Autoupdating.swift + TimeZone_Bridge.swift + TimeZone_Cache.swift + TimeZone_GMT.swift + TimeZone_GMTICU.swift + TimeZone_ICU.swift + TimeZone_ICUResource.swift + TimeZone_ObjC.swift + TimeZone_Protocol.swift + TimeZone_SingleDSTRule.swift + TimelineSchedule.swift + TimelineView.swift + TimerTimelineSchedule.swift + TimerUtils.swift + Timing.swift + Tint.swift + TiocConstants.swift + TitleAndIconLabelStyle.swift + TitleOnlyLabelStyle.swift + Toggle.swift + ToggleState.swift + ToggleStyle.swift + ToolbarItemBridging.swift + ToolbarItemLabelStyle.swift + ToolbarSafeAreaInset.swift + ToolbarTitleDisplayMode.swift + TouchEvent.swift + TouchType.swift + Tracing.swift + TraitValues.swift + Transaction.swift + TransactionAnimation.swift + TransactionID.swift + TransactionModifier.swift + TransformEvent.swift + Transition.swift + TransitionTraitKey.swift + TrimmedShape.swift + Tuist.swift + Tuple.swift + TupleCommandContent.swift + TupleScene.swift + TupleTypeDescription.swift + TupleView.swift + TypeConformance.swift + TypealiasStrings.swift + Types.swift + TypesettingConfiguration.swift + TypesettingLanguage.swift + TypesettingLanguageAwareLineHeightRatio.swift + UIApplicationDelegateAdaptor.swift + UIHostingController.swift + UIHostingControllerSizingOptions.swift + UIHostingView+Extension.swift + UIHostingView.swift + UIHostingViewBase.swift + UIHostingViewDebugLayer.swift + UIHostingViewable.swift + UIImageConversions.swift + UIKit.swift + UIKitAccessibility.swift + UIKitApp.swift + UIKitAppDelegate.swift + UIKitConversions.swift + UIKitDisplayList.swift + UIKitEnvironment.swift + UIKitEventBindingBridge.swift + UIKitFeedbackImplementation.swift + UIKitGestureContainer.swift + UIKitGestureRecognizer.swift + UIKitGestureUtilities.swift + UIKitHostContainerFocusItemInput.swift + UIKitHoverGestureRecognizer.swift + UIKitKeyEventConversions.swift + UIKitKeyPressResponder.swift + UIKitMainMenuController.swift + UIKitNavigationBridge.swift + UIKitProgressView.swift + UIKitRelationshipGestureRecognizer.swift + UIKitResponderEventBindingBridge.swift + UIKitResponderGestureRecognizer.swift + UIKitSceneConnectionOption.swift + UIKitSensoryFeedbackCache.swift + UIKitUpdateCycle.swift + UIKit_FoundationExtensions.swift + UIViewControllerProvider.swift + UIViewControllerRepresentable.swift + UIViewRepresentable.swift + UIViewResponder.swift + UInt128.swift + UIntBuffer.swift + URL+UnicodeLookalikeTable.swift + URL.swift + URLCache.swift + URLComponents.swift + URLComponents_ObjC.swift + URLEncoder.swift + URLFormatStyle.swift + URLParseStrategy.swift + URLParser+ICU.swift + URLParser.swift + URLRequest.swift + URLSession.swift + URLTemplate.swift + URLTemplate_Expression.swift + URLTemplate_PercentEncoding.swift + URLTemplate_Substitution.swift + URLTemplate_Value.swift + URLTemplate_VariableName.swift + URL_Bridge.swift + URL_C+Encoding.swift + URL_C+File.swift + URL_C+Parsing.swift + URL_C+Resolution.swift + URL_C+Spans.swift + URL_File.swift + URL_Impl.swift + URL_Info.swift + URL_Parsing.swift + URL_Protocol.swift + URL_Resolution.swift + URL_Swift.swift + URL_Validation.swift + UTF16.swift + UTF32.swift + UTF8.swift + UTF8EncodingError.swift + UTF8Span.swift + UTF8SpanBits.swift + UTF8SpanComparisons.swift + UTF8SpanFundamentals.swift + UTF8SpanInternalHelpers.swift + UTF8SpanIterators.swift + UTFEncoding.swift + UUID.swift + UUID_Wrappers.swift + UnaryLayoutView.swift + UnaryMinus.swift + UnavailableStringAPIs.swift + UncheckedSendable.swift + UnfoldSequence.swift + Unicode.swift + UnicodeBreakProperty.swift + UnicodeData.swift + UnicodeEncoding.swift + UnicodeHelpers.swift + UnicodeParser.swift + UnicodeSPI.swift + UnicodeScalar.swift + UnicodeScalarProperties.swift + UnimplementedExecutor.swift + UniqueArray+Append.swift + UniqueArray+Container.swift + UniqueArray+Descriptions.swift + UniqueArray+Equatable.swift + UniqueArray+Hashable.swift + UniqueArray+Initializers.swift + UniqueArray+Insertions.swift + UniqueArray+Removals.swift + UniqueArray+Replacements.swift + UniqueArray.swift + UniqueBox.swift + UniqueID.swift + UniqueSeedGenerator.swift + UnitCurve.swift + UnitPoint.swift + UnitRect.swift + Unmanaged+Extension.swift + Unmanaged.swift + UnmanagedOpaqueString.swift + UnmanagedString.swift + UnsafeBufferPointer.swift + UnsafeBufferPointerSlice.swift + UnsafeCxxIterators.swift + UnsafeHeterogeneousBuffer.swift + UnsafeMutableBufferPointer+Utilities.swift + UnsafePointer+Extension.swift + UnsafePointer.swift + UnsafeRawBufferPointer.swift + UnsafeRawPointer.swift + Update.swift + UpdateFrequencyDependentFormatStyle.swift + UserDefaultsAdditions.swift + Utils.swift + VStack.swift + ValidUTF8Buffer.swift + ValueActionModifier.swift + ValueActionSceneModifier.swift + VarArgs.swift + VariableBlurEffect.swift + VariableBlurStyle.swift + VariablePrecisionDiscreteFormatStyle.swift + VariadicView.swift + VariadicViewChildren.swift + VectorArithmetic.swift + VectorImageLayer.swift + VectorMath.swift + Velocity.swift + VelocitySampler.swift + VelocityTrackingAnimation.swift + VersionSeed.swift + VersionSeedTracker.swift + VibrantColorStyle.swift + View+Animatable.swift + View.swift + ViewAlias.swift + ViewBuilder.swift + ViewDebug.swift + ViewDimensions.swift + ViewFrame.swift + ViewGeometry.swift + ViewGraph.swift + ViewGraphDelegate.swift + ViewGraphFeature.swift + ViewGraphGeometryObservers.swift + ViewGraphRender.swift + ViewInputPredicate+View.swift + ViewInputPredicate.swift + ViewInputs.swift + ViewList.swift + ViewListContent.swift + ViewModifier+Animatable.swift + ViewModifier.swift + ViewOutputs.swift + ViewPlatformOutputs.swift + ViewRendererHost.swift + ViewRendererHostProperties.swift + ViewRendererVendor.swift + ViewRenderingPhase.swift + ViewResponder.swift + ViewSize.swift + ViewStyle.swift + ViewTest.swift + ViewThatFits.swift + ViewTrait.swift + ViewTransform.swift + View_Indirect.swift + Visibility.swift + Vision.swift + Volatile.swift + WASILibc+Extensions.swift + WASILibc.swift + WKInterfaceController.swift + WasmImpl.swift + WatchEnvironment.swift + WatchKitFeedbackImplementation.swift + WhitespaceRemovingFormatStyle.swift + WidgetAuxiliaryViewMetadata.swift + WidgetCore.swift + Win32Unwinder.swift + WinSDK+Extensions.swift + WinSDK.swift + WindowEnvironment.swift + WindowGroup.swift + WindowSceneConfiguration.swift + Windows1252.swift + WindowsImpl.swift + WordPair.swift + WrappingLabelStyle.swift + WriteBackMutableSlice.swift + WritingMode.swift + XCTest.swift + XMLPlistDecodingDocument.swift + XMLPlistDecodingFormat.swift + XMLPlistEncodingFormat.swift + XMLPlistLegacyDecodingFormat.swift + XMLPlistMap.swift + XMLPlistMapBuildingSink.swift + XMLPlistPrimitive+Scope.swift + XMLPlistPrimitive.swift + XMLPlistPrimitiveSource.swift + XMLPlistScanner.swift + XMLPlistScannerEventSource.swift + XPC.swift + ZIndex.swift + ZStack.swift + Zip.swift + _DequeBuffer.swift + _DequeBufferHeader.swift + _DequeSlot.swift + _InlineArray.swift + _RemoveGlobalActor.swift + _ThreadLocal.swift + _UnsafeWrappedBuffer.swift + build-list-format-data-impl.swift + float.swift + list-format-data-schema.swift + main.swift + os_log.swift + os_signpost.swift + simd.swift + std.swift + tgmath.swift + ucrt.swift + update-iana-charset-names-impl.swift + update-list-format-data-impl.swift + vDSP_Arithmetic.swift + vDSP_Biquad.swift + vDSP_ClippingLimitThreshold.swift + vDSP_ComplexConversion.swift + vDSP_ComplexOperations.swift + vDSP_Conversion.swift + vDSP_Convolution.swift + vDSP_DCT.swift + vDSP_DFT.swift + vDSP_DecibelConversion.swift + vDSP_FFT.swift + vDSP_FFT_DFT_Common.swift + vDSP_FIR.swift + vDSP_FillClearGenerate.swift + vDSP_Geometry.swift + vDSP_Integration.swift + vDSP_Interpolation.swift + vDSP_PolarRectangularConversion.swift + vDSP_PolynomialEvaluation.swift + vDSP_RecursiveFilters.swift + vDSP_Reduction.swift + vDSP_SingleVectorOperations.swift + vDSP_SlidingWindow.swift + vForce_Operations.swift + vImage_Buffer.swift + vImage_CGImageFormat.swift + vImage_CVImageFormat.swift + vImage_Converter.swift + vImage_Error.swift + vImage_Options.swift + """ +} diff --git a/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles.swift b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles.swift new file mode 100644 index 000000000..22ddd5907 --- /dev/null +++ b/Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles.swift @@ -0,0 +1,549 @@ +import Foundation +import CryptoKit + +/// The source files that private discriminators were derived from, recovered +/// by hashing candidate file names (evolution proposal +/// `private-declarations`). +/// +/// A discriminator is the MD5 of a module's name followed by a source file's +/// name (see `PrivateDeclaration`), so it cannot be decoded — but a file name +/// can be guessed and checked, and a 128-bit digest that matches is a certain +/// identification: a recovered name is never a guess, and the candidates only +/// decide how many are found. They are tried in rising order of cost, and the +/// search stops once every discriminator asked for is found: +/// +/// 1. `knownFileNames`, the Swift file names of public repositories whose code +/// ships in Apple's frameworks — OpenSwiftUI's reconstruction of SwiftUI +/// among them. +/// 2. Every identifier in the image's names, as it is, without its leading +/// underscores, and every run of its camel-case words: +/// `DefaultLayoutViewResponder` yields `Default`, `LayoutView`, +/// `ViewResponder`, … — each with `.swift` appended. +/// 3. `Type+Category.swift` from the words of the names declared with the same +/// discriminator, which usually carry both: `DateTextStorage` is declared in +/// `Text+Date.swift`. +/// 4. The runs of step 2 followed by a word that often ends a file name +/// (`Additions`, `Utils`, …), or by a plural `s`. +/// 5. `Type+Category.swift` with any type name of the image before a word of +/// step 3: `ObjectLocation` is declared in `Binding+ObjectLocation.swift`. +/// +/// On macOS 26.7 this recovers 408 of SwiftUICore's 439 discriminators, 576 of +/// SwiftUI's 709 and 84 of Foundation's 86 — without the known file names, +/// 382, 561 and 64. `PrivateDiscriminatorSourceFileIndex` runs it over an +/// indexed image and remembers the answers. +public struct PrivateDiscriminatorSourceFiles: Sendable { + public struct SourceFile: Hashable, Sendable { + /// The file's name, `Enabled.swift`. + public let fileName: String + + /// The module name that went into the digest: a framework's own name + /// (`SwiftUICore`), which is not always the module its types are + /// printed under (`SwiftUI`). + public let moduleName: String + + /// Whether the discriminator belongs to the file the compiler + /// synthesizes for `fileName`, whose discriminator is the MD5 of that + /// file's own followed by `SYNTHESIZED FILE` + /// (`SynthesizedFileUnit::getDiscriminatorForPrivateDecl`). + public let isSynthesized: Bool + + public init(fileName: String, moduleName: String, isSynthesized: Bool) { + self.fileName = fileName + self.moduleName = moduleName + self.isSynthesized = isSynthesized + } + } + + /// A name an image declares, as a reader is shown it — `SwiftUI.EnabledKey`, + /// without its discriminators — and the discriminators of the private + /// declarations it reads (`DemanglingNode.privateDeclarations`). + public struct ImageName: Hashable, Sendable { + public let printedName: String + + public let discriminators: [String] + + public init(printedName: String, discriminators: [String] = []) { + self.printedName = printedName + self.discriminators = discriminators + } + } + + /// Words that often end a file name, tried after every run of words + /// (step 4). Each was the last word of a SwiftUICore file name nothing else + /// recovered. + private static let fileNameSuffixes = ["Additions", "Conversions", "Utils", "Helpers", "Modifier", "Style", "View", "Environment", "Core", "s"] + + /// The source file of every discriminator found: those asked for, and + /// the files the compiler synthesized one of them for found on the way. + let sourceFileByDiscriminator: [String: SourceFile] + + /// Recovers the source files of `discriminators`. + /// + /// - Parameters: + /// - discriminators: The discriminators to recover. Every candidate costs + /// one hash per module name, and a discriminator nothing recovers is + /// hashed against all of them: in a debug build that takes three to + /// four seconds for SwiftUICore, and a whole image's take minutes. Ask + /// for the ones shown. + /// - imagePath: The image the names come from. Its file name is the + /// first module name tried. + /// - imageNames: Every name the image declares. They make the candidates, + /// and their discriminators say which names were declared in the same + /// file. + /// - knownFileNames: File names to try before any is derived from the + /// image's names. + public init( + recovering discriminators: some Sequence, + imagePath: String, + imageNames: some Sequence, + knownFileNames: [String] = PrivateDiscriminatorSourceFiles.knownFileNames + ) { + self.init(recovering: discriminators, candidates: Candidates(imagePath: imagePath, imageNames: imageNames), knownFileNames: knownFileNames) + } + + init(recovering discriminators: some Sequence, candidates: Candidates, knownFileNames: [String]) { + var search = Search( + moduleNames: candidates.moduleNames, + requestedDiscriminators: Set(discriminators), + imageDiscriminators: Set(candidates.identifiersByDiscriminator.keys) + ) + Self.recover(into: &search, knownFileNames: knownFileNames, identifiers: candidates.identifiers, identifiersByDiscriminator: candidates.identifiersByDiscriminator) + self.sourceFileByDiscriminator = search.sourceFileByDiscriminator + } + + /// The source file `discriminator` was derived from, or `nil` when it was + /// not asked for or no candidate produced it. + public func sourceFile(forDiscriminator discriminator: String) -> SourceFile? { + sourceFileByDiscriminator[discriminator] + } + + /// Tries the candidates of each step in turn, and returns as soon as every + /// discriminator asked for is found — before building the next step's + /// candidates, which cost more than the hashing of the steps before. + private static func recover(into search: inout Search, knownFileNames: [String], identifiers: Set, identifiersByDiscriminator: [String: Set]) { + // 1. Known file names. + for knownFileName in knownFileNames { + guard !search.isComplete else { return } + search.check(NamePart(knownFileName)) + } + + // 2. Identifiers and their runs of words. + guard !search.isComplete else { return } + var stemTexts: Set = [] + for identifier in identifiers { + stemTexts.formUnion(fileNameStems(for: identifier)) + } + let stems = stemTexts.map(NamePart.init) + for stem in stems { + guard !search.isComplete else { return } + search.check(stem, NamePart.swiftFileExtension) + } + + // 3. Two words declared with the same discriminator. + var categoriesByDiscriminator: [String: [NamePart]] = [:] + func categories(for discriminator: String) -> [NamePart] { + if let categories = categoriesByDiscriminator[discriminator] { + return categories + } + var categoryTexts: Set = [] + for identifier in identifiersByDiscriminator[discriminator] ?? [] { + categoryTexts.formUnion(fileNameStems(for: identifier).filter { $0.utf8.first.map(isUppercaseLetter) ?? false }) + } + let categories = categoryTexts.sorted().map(NamePart.init) + categoriesByDiscriminator[discriminator] = categories + return categories + } + for discriminator in search.pendingDiscriminators { + let categories = categories(for: discriminator) + for type in categories { + for category in categories where category.text != type.text { + guard search.isPending(discriminator) else { break } + search.check(type, NamePart.plusSign, category, NamePart.swiftFileExtension) + } + } + } + + // 4. Runs of words followed by a common last word. + for suffix in fileNameSuffixes { + let suffixWithExtension = NamePart(suffix + ".swift") + for stem in stems { + guard !search.isComplete else { return } + search.check(stem, suffixWithExtension) + } + } + + // 5. Any type name before a word declared with the discriminator. + let typeNames = identifiers.filter { $0.utf8.first.map(isUppercaseLetter) ?? false }.sorted().map(NamePart.init) + for discriminator in search.pendingDiscriminators { + let categories = categories(for: discriminator) + for type in typeNames { + guard search.isPending(discriminator) else { break } + for category in categories where category.text != type.text { + search.check(type, NamePart.plusSign, category, NamePart.swiftFileExtension) + } + } + } + } + + // MARK: - Module Names + + /// The module names an image's own file name suggests, most likely first: + /// the name itself (`SwiftUICore`), what Xcode makes of it as a module name + /// (`My App` → `My_App`), and the name left after a library prefix + /// (`libswiftAppKit.dylib` → `AppKit`). + fileprivate static func moduleNames(forImagePath imagePath: String) -> [String] { + let fileName = ((imagePath as NSString).lastPathComponent as NSString).deletingPathExtension + var moduleNames: [String] = [] + func append(_ moduleName: String) { + guard !moduleName.isEmpty, !moduleNames.contains(moduleName) else { return } + moduleNames.append(moduleName) + } + append(fileName) + append(identifierSpelling(of: fileName)) + for libraryPrefix in ["libswift", "lib"] where fileName.hasPrefix(libraryPrefix) { + append(String(fileName.dropFirst(libraryPrefix.count))) + break + } + return moduleNames + } + + /// `name` with every character that cannot appear in an identifier + /// replaced by `_`, and a `_` in front of a leading digit — the spelling + /// Xcode gives a product's module name. + private static func identifierSpelling(of name: String) -> String { + var bytes = name.utf8.map { isIdentifierByte($0) && $0 < 0x80 ? $0 : UInt8(ascii: "_") } + if let firstByte = bytes.first, isDigit(firstByte) { + bytes.insert(UInt8(ascii: "_"), at: 0) + } + return String(decoding: bytes, as: UTF8.self) + } + + /// The module part of a Swift name, `SwiftUI` in `SwiftUI.EnabledKey`. + /// `nil` when what comes before the first dot is no identifier — a local + /// type's name starts with the type, `Visitor #1 in SwiftUI.…`. + fileprivate static func leadingModuleName(of printedName: String) -> String? { + guard let dotIndex = printedName.firstIndex(of: ".") else { return nil } + let moduleName = printedName[..) { + let bytes = Array(printedName.utf8) + var index = 0 + while index < bytes.count { + guard isIdentifierByte(bytes[index]) else { + index += 1 + continue + } + let identifierStartIndex = index + while index < bytes.count, isIdentifierByte(bytes[index]) { + index += 1 + } + identifiers.insert(String(decoding: bytes[identifierStartIndex ..< index], as: UTF8.self)) + } + } + + /// The file names, without their extension, that `identifier` suggests: + /// the identifier as it is and without its leading underscores, and every + /// run of its camel-case words. + private static func fileNameStems(for identifier: String) -> Set { + var stems: Set = [identifier] + let strippedBytes = Array(identifier.utf8.drop { $0 == UInt8(ascii: "_") }) + guard !strippedBytes.isEmpty else { return stems } + stems.insert(String(decoding: strippedBytes, as: UTF8.self)) + guard strippedBytes.allSatisfy({ $0 < 0x80 }) else { return stems } + let wordRanges = camelCaseWordRanges(in: strippedBytes) + for firstWordIndex in wordRanges.indices { + for endWordIndex in firstWordIndex + 1 ... wordRanges.count { + stems.insert(String(decoding: wordRanges[firstWordIndex ..< endWordIndex].flatMap { strippedBytes[$0] }, as: UTF8.self)) + } + } + return stems + } + + /// The ranges of `bytes`' camel-case words: `URL`, `Session` in + /// `URLSession`; `UI`, `2` in `UI2`. Underscores separate words and belong + /// to none. + private static func camelCaseWordRanges(in bytes: [UInt8]) -> [Range] { + var wordRanges: [Range] = [] + var index = 0 + func lowercaseOrDigitRunEnd(from startIndex: Int) -> Int { + var endIndex = startIndex + while endIndex < bytes.count, isLowercaseLetter(bytes[endIndex]) || isDigit(bytes[endIndex]) { + endIndex += 1 + } + return endIndex + } + while index < bytes.count { + let byte = bytes[index] + if isUppercaseLetter(byte) { + var uppercaseRunEndIndex = index + while uppercaseRunEndIndex < bytes.count, isUppercaseLetter(bytes[uppercaseRunEndIndex]) { + uppercaseRunEndIndex += 1 + } + let isFollowedByLowercase = uppercaseRunEndIndex < bytes.count && isLowercaseLetter(bytes[uppercaseRunEndIndex]) + if !isFollowedByLowercase { + // An acronym that ends the name or comes before a digit: `UI`. + wordRanges.append(index ..< uppercaseRunEndIndex) + index = uppercaseRunEndIndex + } else if uppercaseRunEndIndex - index > 1 { + // An acronym before a capitalized word: `URL` in `URLSession`. + wordRanges.append(index ..< uppercaseRunEndIndex - 1) + index = uppercaseRunEndIndex - 1 + } else { + // A capitalized word: `Session`. + let wordEndIndex = lowercaseOrDigitRunEnd(from: uppercaseRunEndIndex) + wordRanges.append(index ..< wordEndIndex) + index = wordEndIndex + } + } else if isLowercaseLetter(byte) || isDigit(byte) { + let wordEndIndex = lowercaseOrDigitRunEnd(from: index) + wordRanges.append(index ..< wordEndIndex) + index = wordEndIndex + } else { + index += 1 + } + } + return wordRanges + } + + // MARK: - Bytes + + private static func isIdentifierByte(_ byte: UInt8) -> Bool { + isUppercaseLetter(byte) || isLowercaseLetter(byte) || isDigit(byte) || byte == UInt8(ascii: "_") || byte >= 0x80 + } + + private static func isUppercaseLetter(_ byte: UInt8) -> Bool { + (UInt8(ascii: "A") ... UInt8(ascii: "Z")).contains(byte) + } + + private static func isLowercaseLetter(_ byte: UInt8) -> Bool { + (UInt8(ascii: "a") ... UInt8(ascii: "z")).contains(byte) + } + + private static func isDigit(_ byte: UInt8) -> Bool { + (UInt8(ascii: "0") ... UInt8(ascii: "9")).contains(byte) + } +} + +// MARK: - Candidates + +extension PrivateDiscriminatorSourceFiles { + /// What a search draws its candidates from, read once out of an image's + /// names: the module names to hash under, every identifier, and the + /// identifiers of the names read with each discriminator. + struct Candidates: Sendable { + let moduleNames: [String] + + let identifiers: Set + + let identifiersByDiscriminator: [String: Set] + + init(imagePath: String, imageNames: some Sequence) { + var moduleNames = PrivateDiscriminatorSourceFiles.moduleNames(forImagePath: imagePath) + var knownModuleNames = Set(moduleNames) + var identifiers: Set = [] + var identifiersByDiscriminator: [String: Set] = [:] + for imageName in imageNames { + var nameIdentifiers: Set = [] + PrivateDiscriminatorSourceFiles.collectIdentifiers(in: imageName.printedName, into: &nameIdentifiers) + identifiers.formUnion(nameIdentifiers) + guard !imageName.discriminators.isEmpty else { continue } + // Only a name with a private declaration names a module the + // digests were made in; an Objective-C class has no module + // part, and every name taken here multiplies the work. + if let moduleName = PrivateDiscriminatorSourceFiles.leadingModuleName(of: imageName.printedName), knownModuleNames.insert(moduleName).inserted { + moduleNames.append(moduleName) + } + for discriminator in imageName.discriminators { + identifiersByDiscriminator[discriminator, default: []].formUnion(nameIdentifiers) + } + } + self.moduleNames = moduleNames + self.identifiers = identifiers + self.identifiersByDiscriminator = identifiersByDiscriminator + } + } +} + +// MARK: - Search + +extension PrivateDiscriminatorSourceFiles { + /// A piece of a candidate file name, kept with its bytes so a candidate is + /// hashed without being assembled. + fileprivate struct NamePart { + static let swiftFileExtension = NamePart(".swift") + + static let plusSign = NamePart("+") + + let text: String + + let bytes: [UInt8] + + init(_ text: String) { + self.text = text + self.bytes = Array(text.utf8) + } + } + + /// The discriminators still looked for, and the source files found so far. + fileprivate struct Search { + private static let synthesizedFileSuffix = Array("SYNTHESIZED FILE".utf8) + + private let moduleNames: [NamePart] + + /// Every discriminator still looked for, by digest: those asked for, + /// and those of the files the compiler synthesized one of them for. + private var pendingDiscriminatorByDigest: [Digest128: String] = [:] + + /// The discriminator of the file the compiler synthesized for each of + /// the image's discriminators, where it is one of those asked for. + private let synthesizedDiscriminatorByOwnerDiscriminator: [String: String] + + private var remainingRequestedDiscriminators: Set + + private(set) var sourceFileByDiscriminator: [String: SourceFile] = [:] + + init(moduleNames: [String], requestedDiscriminators: Set, imageDiscriminators: Set) { + self.moduleNames = moduleNames.map(NamePart.init) + var requestedDiscriminatorByDigest: [Digest128: String] = [:] + for requestedDiscriminator in requestedDiscriminators { + if let digest = Digest128(discriminator: requestedDiscriminator) { + requestedDiscriminatorByDigest[digest] = requestedDiscriminator + } + } + self.remainingRequestedDiscriminators = Set(requestedDiscriminatorByDigest.values) + self.pendingDiscriminatorByDigest = requestedDiscriminatorByDigest + // A synthesized file has no name of its own to hash: its owner is + // looked for instead, among the discriminators the image declares + // something with. + var synthesizedDiscriminatorByOwnerDiscriminator: [String: String] = [:] + for ownerDiscriminator in imageDiscriminators { + var hashFunction = Insecure.MD5() + hashFunction.update(data: Array(ownerDiscriminator.utf8)) + hashFunction.update(data: Self.synthesizedFileSuffix) + guard let synthesizedDiscriminator = requestedDiscriminatorByDigest[Digest128(hashFunction.finalize())], + let ownerDigest = Digest128(discriminator: ownerDiscriminator) + else { continue } + synthesizedDiscriminatorByOwnerDiscriminator[ownerDiscriminator] = synthesizedDiscriminator + pendingDiscriminatorByDigest[ownerDigest] = ownerDiscriminator + } + self.synthesizedDiscriminatorByOwnerDiscriminator = synthesizedDiscriminatorByOwnerDiscriminator + } + + /// Whether every discriminator asked for has been found. + var isComplete: Bool { + remainingRequestedDiscriminators.isEmpty + } + + /// The discriminators still looked for, sorted so that a search runs + /// the same every time. + var pendingDiscriminators: [String] { + pendingDiscriminatorByDigest.values.sorted() + } + + func isPending(_ discriminator: String) -> Bool { + sourceFileByDiscriminator[discriminator] == nil && !isComplete + } + + /// Hashes the file name `parts` spell, under every module name. + mutating func check(_ parts: NamePart...) { + for moduleName in moduleNames { + var hashFunction = Insecure.MD5() + moduleName.bytes.withUnsafeBytes { hashFunction.update(bufferPointer: $0) } + for part in parts { + part.bytes.withUnsafeBytes { hashFunction.update(bufferPointer: $0) } + } + let digest = Digest128(hashFunction.finalize()) + guard let discriminator = pendingDiscriminatorByDigest[digest] else { continue } + record(sourceFile(hashedAs: moduleName, followedBy: parts), for: discriminator, digest: digest) + return + } + } + + /// The source file `moduleName` followed by `parts` names — read under + /// the first module name the same bytes start with. When one module + /// name starts another, one digest has two readings: + /// `SwiftUICoreGlue.swift` is `Glue.swift` in SwiftUICore and + /// `CoreGlue.swift` in SwiftUI. The module names come most likely + /// first, so the reading does not depend on which candidate happened + /// to be tried first. + private func sourceFile(hashedAs moduleName: NamePart, followedBy parts: [NamePart]) -> SourceFile { + let hashedBytes = moduleName.bytes + parts.flatMap(\.bytes) + for earlierModuleName in moduleNames.prefix(while: { $0.text != moduleName.text }) where hashedBytes.starts(with: earlierModuleName.bytes) { + let fileNameBytes = hashedBytes.dropFirst(earlierModuleName.bytes.count) + guard let firstByte = fileNameBytes.first, firstByte != UInt8(ascii: ".") else { continue } + return SourceFile(fileName: String(decoding: fileNameBytes, as: UTF8.self), moduleName: earlierModuleName.text, isSynthesized: false) + } + return SourceFile(fileName: parts.map(\.text).joined(), moduleName: moduleName.text, isSynthesized: false) + } + + private mutating func record(_ sourceFile: SourceFile, for discriminator: String, digest: Digest128) { + pendingDiscriminatorByDigest[digest] = nil + sourceFileByDiscriminator[discriminator] = sourceFile + remainingRequestedDiscriminators.remove(discriminator) + guard let synthesizedDiscriminator = synthesizedDiscriminatorByOwnerDiscriminator[discriminator], + sourceFileByDiscriminator[synthesizedDiscriminator] == nil, + let synthesizedDigest = Digest128(discriminator: synthesizedDiscriminator) + else { return } + pendingDiscriminatorByDigest[synthesizedDigest] = nil + sourceFileByDiscriminator[synthesizedDiscriminator] = SourceFile(fileName: sourceFile.fileName, moduleName: sourceFile.moduleName, isSynthesized: true) + remainingRequestedDiscriminators.remove(synthesizedDiscriminator) + } + } +} + +// MARK: - Digest128 + +/// An MD5 digest as two words, so a candidate's digest is looked up without +/// building its hexadecimal spelling. +private struct Digest128: Hashable { + let leadingBits: UInt64 + let trailingBits: UInt64 + + /// Reads the digest in place: every candidate makes one, so it allocates + /// nothing. + init(_ digest: Insecure.MD5Digest) { + let bits = digest.withUnsafeBytes { buffer in + (leading: UInt64(bigEndian: buffer.loadUnaligned(fromByteOffset: 0, as: UInt64.self)), + trailing: UInt64(bigEndian: buffer.loadUnaligned(fromByteOffset: 8, as: UInt64.self))) + } + self.leadingBits = bits.leading + self.trailingBits = bits.trailing + } + + /// Reads a discriminator: `_` followed by 32 uppercase hexadecimal digits. + init?(discriminator: String) { + let digits = Array(discriminator.utf8.dropFirst()) + guard discriminator.utf8.first == UInt8(ascii: "_"), digits.count == 32 else { return nil } + var bytes = [UInt8](repeating: 0, count: 16) + for byteIndex in 0 ..< 16 { + guard let highNibble = Self.nibble(digits[byteIndex * 2]), let lowNibble = Self.nibble(digits[byteIndex * 2 + 1]) else { return nil } + bytes[byteIndex] = highNibble << 4 | lowNibble + } + self.init(bytes: bytes) + } + + private init(bytes: [UInt8]) { + var leadingBits: UInt64 = 0 + var trailingBits: UInt64 = 0 + for index in 0 ..< 8 { + leadingBits = leadingBits << 8 | UInt64(bytes[index]) + trailingBits = trailingBits << 8 | UInt64(bytes[index + 8]) + } + self.leadingBits = leadingBits + self.trailingBits = trailingBits + } + + private static func nibble(_ digit: UInt8) -> UInt8? { + switch digit { + case UInt8(ascii: "0") ... UInt8(ascii: "9"): digit - UInt8(ascii: "0") + case UInt8(ascii: "A") ... UInt8(ascii: "F"): digit - UInt8(ascii: "A") + 10 + default: nil + } + } +} diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 8ca97ebd0..3c31e3454 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -492,14 +492,14 @@ extension SwiftDeclarationPrinter { // MARK: - Local types (evolution proposal `local-type-context-names`) /// The comment above the declaration of a type declared in a function or - /// closure body: the compiler's name for it, modules left out - /// (`Visitor #1 in Holder.countValues()`), or — when no source the image - /// keeps names the function or closure — a sentence saying so. `nil` for - /// any other type. + /// closure body: the name a reader is shown of it + /// (`DefinitionName.localTypeDisplayName`, `Visitor #1 in + /// Holder.countValues()`), or — when no source the image keeps names the + /// function or closure — a sentence saying so. `nil` for any other type. package func localTypeDeclarationComment(for typeName: SwiftDeclaration.TypeName) -> String? { switch typeName.node.localTypeNaming { case .compilerSpelled: - typeName.name(using: .localTypeDeclarationComment) + typeName.localTypeDisplayName case .positionBased: "Local type in a function or closure the binary does not name" case nil: @@ -540,12 +540,6 @@ extension SwiftDeclarationPrinter { } } -extension DemangleOptions { - /// A local type's compiler-spelled name the way a reader would say it: - /// no modules, no parameter types, the `#1` ordinal kept. - fileprivate static let localTypeDeclarationComment = DemangleOptions.simplified.union(.displayLocalNameContexts) -} - extension ExtensionKind { /// The kind `ExtensionName.print()` declares the extended type as. fileprivate var semanticTypeKind: SemanticType.TypeKind { diff --git a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift new file mode 100644 index 000000000..69b47060f --- /dev/null +++ b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift @@ -0,0 +1,77 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +@testable import MachOTestingSupport +import SwiftDeclaration +@_spi(Support) import SwiftIndexing +import SwiftInspection + +/// The name a reader is shown of a type declared in a function or closure +/// body, or of a type nested in one (evolution proposal +/// `private-declarations`): no modules, no parameter or result types, the +/// ordinal kept; a position-based one keeps its `$` address. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct LocalTypeDisplayNameTests { + /// Every type of `variant` the fixture declares in a body, with the name a + /// reader is shown of it, and every other type's. + private static func displayNames(of variant: LocalTypeFixture.Variant) async throws -> (inBodies: [String], elsewhere: [String?]) { + let machOFile = try LocalTypeFixture.machOFile(variant) + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: machOFile) + try await indexer.prepare() + var inBodies: [String] = [] + var elsewhere: [String?] = [] + for (typeName, typeDefinition) in indexer.allTypeDefinitions { + if try LocalTypeFixture.isDeclaredInABody(typeDefinition.typeContextDescriptorWrapper.asContextDescriptorWrapper, in: machOFile.context) { + inBodies.append(try #require(typeName.localTypeDisplayName, "\(typeName.name)")) + } else { + elsewhere.append(typeName.localTypeDisplayName) + } + } + return (inBodies, elsewhere) + } + + @Test func compilerSpelledNamesLeaveModulesAndSignaturesOut() async throws { + let (inBodies, elsewhere) = try await Self.displayNames(of: .unstripped) + + #expect(inBodies.sorted() == [ + "Box #1 in Holder.box()", + "CodingKeys in Payload #1 in Holder.payload()", + "Counter in WrappingGenerator #1 in Holder.wrapping()", + "Element in Generator #1 in Holder.nested()", + "Generator #1 in Holder.nested()", + "Hidden #1 in Holder.hiddenValues()", + "InClosure #1 in closure #1 in Holder.valuesFromClosure()", + "IndexWrappingVisitor in WrappingGenerator #1 in Holder.wrapping()", + "Key #1 in Holder.keyFromGetter.getter", + "Key #1 in static Holder.keyFromStaticMethod()", + "Lookup #1 in Holder.lookup(named:at:)", + "Mode #1 in Holder.mode(_:)", + "Payload #1 in Holder.payload()", + "TopLevel #1 in localTypeFixtureTopLevel()", + "Twin #1 in Holder.twins(_:)", + "Twin #2 in Holder.twins(_:)", + "Visitor #1 in Holder.countValues()", + "Visitor #1 in Holder.sumValues()", + "Wrapper #1 in String.localTypeFixtureWrapped()", + "WrappingGenerator #1 in Holder.wrapping()", + ]) + #expect(!elsewhere.isEmpty) + #expect(elsewhere.allSatisfy { $0 == nil }, "\(elsewhere)") + } + + /// With every name source stripped, a local type is named by the address + /// of its anonymous context: the address stays, so `Holder`'s two + /// `Visitor`s stay apart, and no real discriminator is printed. + @Test func positionBasedNamesKeepTheirAddress() async throws { + let (inBodies, elsewhere) = try await Self.displayNames(of: .stripped) + + #expect(inBodies.count == 20) + #expect(Set(inBodies).count == inBodies.count, "\(inBodies.sorted())") + #expect(inBodies.allSatisfy { $0.contains(" in $") }, "\(inBodies.sorted())") + #expect(!inBodies.contains { $0.contains(" in _") }, "\(inBodies.sorted())") + #expect(inBodies.filter { $0.hasPrefix("Holder.(Visitor in $") && $0.hasSuffix(")") }.count == 2, "\(inBodies.sorted())") + #expect(inBodies.contains { $0.hasPrefix("Holder.(Generator in $") && $0.hasSuffix(").Element") }, "\(inBodies.sorted())") + #expect(elsewhere.allSatisfy { $0 == nil }, "\(elsewhere)") + } +} diff --git a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift new file mode 100644 index 000000000..f2f94edb8 --- /dev/null +++ b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift @@ -0,0 +1,143 @@ +import Foundation +import Testing +import MachOKit +import MachOFixtureSupport +@testable import MachOTestingSupport +import Demangling +import SwiftDeclaration +@_spi(Support) import SwiftIndexing +import SwiftInspection + +/// `privateDeclarations` reads a name's whole tree but for two parts: the +/// signature of a function, closure, variable, subscript, initializer or +/// macro the name runs through, and a position-based local type's `$` +/// address (evolution proposal `private-declarations`). A name that runs +/// through neither reads exactly what a whole-tree search reads — the search +/// RuntimeViewer ran before this one moved here. Every definition name of the +/// fixtures below that runs through neither is checked against such a +/// search, written apart from the library's walk. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct PrivateDeclarationsWholeTreeTests { + /// What the comparison covered: the names compared, and how many of them + /// read a private declaration. + private struct Coverage { + var comparedNames = 0 + var namesReadingAPrivateDeclaration = 0 + } + + /// Every `privateDeclName` in the tree, in preorder, each once — the + /// search RuntimeViewer ran (`node.all(of: .privateDeclName)`). + private static func wholeTreePrivateDeclarations(of node: Node) -> [PrivateDeclaration] { + var privateDeclarations: [PrivateDeclaration] = [] + func visit(_ node: Node) { + if node.kind == .privateDeclName, let discriminator = node.children.first?.text { + let privateDeclaration = PrivateDeclaration(name: node.children.at(1)?.text, discriminator: discriminator) + if !privateDeclarations.contains(privateDeclaration) { + privateDeclarations.append(privateDeclaration) + } + } + for child in node.children { + visit(child) + } + } + visit(node) + return privateDeclarations + } + + /// The declarations whose children carry a signature. + private static let declarationsWithASignature: Set = [ + .function, .explicitClosure, .implicitClosure, .allocator, .constructor, .subscript, .variable, .macro, + ] + + /// Whether the name runs through a declaration with a signature, or names + /// a type by the address of its anonymous context. + private static func runsThroughASignatureOrAnAddress(_ node: Node) -> Bool { + if declarationsWithASignature.contains(node.kind) { + return true + } + if node.kind == .privateDeclName, node.children.first?.text?.hasPrefix("$") == true { + return true + } + return node.children.contains(where: runsThroughASignatureOrAnAddress) + } + + private static func definitionNames(of indexer: SwiftDeclarationIndexer) -> [any DefinitionName] { + var definitionNames: [any DefinitionName] = [] + definitionNames += indexer.allTypeDefinitions.keys.map { $0 as any DefinitionName } + definitionNames += indexer.allProtocolDefinitions.keys.map { $0 as any DefinitionName } + for extensionDefinitions in [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] { + definitionNames += extensionDefinitions.keys.map { $0 as any DefinitionName } + } + return definitionNames + } + + private static func compare(definitionNamesOf indexer: SwiftDeclarationIndexer) -> Coverage { + var coverage = Coverage() + for definitionName in definitionNames(of: indexer) { + let node = definitionName.node.materialize() + guard !runsThroughASignatureOrAnAddress(node) else { continue } + let expectedPrivateDeclarations = wholeTreePrivateDeclarations(of: node) + #expect(definitionName.node.privateDeclarations == expectedPrivateDeclarations, "\(definitionName.name)") + #expect(node.privateDeclarations == expectedPrivateDeclarations, "\(definitionName.name)") + coverage.comparedNames += 1 + if !expectedPrivateDeclarations.isEmpty { + coverage.namesReadingAPrivateDeclaration += 1 + } + } + return coverage + } + + @Test func localTypeFixtureReadFromItsFile() async throws { + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: try LocalTypeFixture.machOFile(.unstripped)) + try await indexer.prepare() + + let coverage = Self.compare(definitionNamesOf: indexer) + #expect(coverage.comparedNames > 0) + } + + @Test func localTypeFixtureLoadedIntoTheProcess() async throws { + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: try LocalTypeFixture.loadedImage(.unstripped)) + try await indexer.prepare() + + let coverage = Self.compare(definitionNamesOf: indexer) + #expect(coverage.comparedNames > 0) + } + + /// SymbolTestsCore declares private types (`PrivateDoppelgangers.swift`, + /// `Structs.swift`), so here the names compared do read some. + @Test func symbolTestsCore() async throws { + let machOFile: MachOFile + switch try loadFromFile(named: .SymbolTestsCore) { + case .machO(let thinMachOFile): + machOFile = thinMachOFile + case .fat(let fatFile): + machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: machOFile) + try await indexer.prepare() + + let coverage = Self.compare(definitionNamesOf: indexer) + #expect(coverage.comparedNames > 0) + #expect(coverage.namesReadingAPrivateDeclaration > 0) + } + + /// The names of `PrivateDeclarationsTests` (SwiftInspectionTests) that run + /// through no signature, compiled from a sample module `Shapes`: a + /// private type; a type in a constrained extension of a private generic + /// type, which no fixture above has; and specialized types whose + /// arguments are private. + @Test(arguments: [ + "$s6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVMn", + "$s6Shapes14PrivateGeneric33_C01776A4525D5700C9CAB18498B5F7E5LLVAASiRszlE22InConstrainedExtensionVMn", + "$sSay6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVGD", + "$sSDy6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVAA13PrivateHolder33_C01776A4525D5700C9CAB18498B5F7E5LLVGD", + ]) + func sampleNamesReadingPrivateDeclarations(mangledName: String) throws { + let node = try demangleAsNodeTransient(mangledName) + try #require(!Self.runsThroughASignatureOrAnAddress(node)) + + let expectedPrivateDeclarations = Self.wholeTreePrivateDeclarations(of: node) + #expect(!expectedPrivateDeclarations.isEmpty) + #expect(node.privateDeclarations == expectedPrivateDeclarations) + } +} diff --git a/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift b/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift new file mode 100644 index 000000000..acbb70d39 --- /dev/null +++ b/Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift @@ -0,0 +1,167 @@ +import Foundation +import Testing +import MachOKit +@testable import Demangling +@testable import MachOSwiftSection +@testable import MachOTestingSupport +@testable @_spi(Internals) import SwiftInspection + +/// The private declarations a name reads (evolution proposal +/// `private-declarations`): the whole tree but a declaring function's or +/// closure's signature and a position-based local type's address. +/// +/// The manglings are real. The `SwiftUI` ones are type descriptor symbols of +/// macOS 27.2's SwiftUI. The `Shapes` ones come from compiling, with +/// `swiftc -c -Onone -parse-as-library -module-name Shapes`, a file that +/// declares — among the shapes named in each test — `private struct +/// PrivateArgument {}`, `private struct PrivateGeneric {}` and +/// `private struct PrivateHolder`; its private discriminator is +/// `_C01776A4525D5700C9CAB18498B5F7E5`. +@Suite(ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct PrivateDeclarationsTests { + private static let shapesDiscriminator = "_C01776A4525D5700C9CAB18498B5F7E5" + + private static func privateDeclarations(of mangledName: String) throws -> [PrivateDeclaration] { + try demangleAsNodeTransient(mangledName).privateDeclarations + } + + // MARK: - Declarations and their contexts + + @Test func privateTypeReadsItself() throws { + #expect(try Self.privateDeclarations(of: "$s6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVMn") == [ + PrivateDeclaration(name: "PrivateArgument", discriminator: Self.shapesDiscriminator), + ]) + } + + /// `private func hidden()` of a private type carries no discriminator of + /// its own: the type's is the one read. + @Test func typeInAMethodOfAPrivateTypeReadsTheType() throws { + // InPrivateMethodOfPrivateType #1 in Shapes.(PrivateHolder in _C017…).hidden() -> Any + #expect(try Self.privateDeclarations(of: "$s6Shapes13PrivateHolder33_C01776A4525D5700C9CAB18498B5F7E5LLV6hiddenypyF02Inb8MethodOfB4TypeL_VMn") == [ + PrivateDeclaration(name: "PrivateHolder", discriminator: Self.shapesDiscriminator), + ]) + } + + /// A type declared in a constrained extension of a private type sits + /// under an `extension` node, whose parent is its second child: the + /// extended type is read. + @Test func typeInAConstrainedExtensionReadsTheExtendedType() throws { + // (extension in Shapes):Shapes.(PrivateGeneric in _C017…).InConstrainedExtension + #expect(try Self.privateDeclarations(of: "$s6Shapes14PrivateGeneric33_C01776A4525D5700C9CAB18498B5F7E5LLVAASiRszlE22InConstrainedExtensionVMn") == [ + PrivateDeclaration(name: "PrivateGeneric", discriminator: Self.shapesDiscriminator), + ]) + } + + @Test func specializedTypeReadsItsGenericArguments() throws { + // [Shapes.(PrivateArgument in _C017…)] + #expect(try Self.privateDeclarations(of: "$sSay6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVGD") == [ + PrivateDeclaration(name: "PrivateArgument", discriminator: Self.shapesDiscriminator), + ]) + } + + @Test func declarationsAreReadInOrderAndOnce() throws { + // [Shapes.(PrivateArgument in _C017…) : Shapes.(PrivateHolder in _C017…)] + #expect(try Self.privateDeclarations(of: "$sSDy6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVAA13PrivateHolder33_C01776A4525D5700C9CAB18498B5F7E5LLVGD") == [ + PrivateDeclaration(name: "PrivateArgument", discriminator: Self.shapesDiscriminator), + PrivateDeclaration(name: "PrivateHolder", discriminator: Self.shapesDiscriminator), + ]) + // [Shapes.(PrivateArgument in _C017…) : Shapes.(PrivateArgument in _C017…)] + #expect(try Self.privateDeclarations(of: "$sSDy6Shapes15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVADGD") == [ + PrivateDeclaration(name: "PrivateArgument", discriminator: Self.shapesDiscriminator), + ]) + } + + // MARK: - Local types + + /// A local type whose function is not private reads nothing, though the + /// function's signature names a type of the module. + @Test func localTypeOfANonPrivateMethodReadsNothing() throws { + // Visitor #1 in SwiftUI.TableDataSource.performDrop(to: SwiftUI.DropCoordinator) -> () + #expect(try Self.privateDeclarations(of: "$s7SwiftUI15TableDataSourceV11performDrop2toyAA0G11CoordinatorVy10Foundation9IndexPathVG_tF7VisitorL_VMn").isEmpty) + } + + /// The method a local type is declared in is read when it is private — + /// the method's discriminator, under the method's name, not the type's. + @Test func localTypeOfAPrivateMethodReadsTheMethod() throws { + // IndexingWrappingGenerator #1 in closure #1 () -> () in SwiftUI.AccessibilityRotorInfo.(readEntryList in _030667BF…)((SwiftUI.AccessibilityRotorEntryList) -> ()) -> () + #expect(try Self.privateDeclarations(of: "$s7SwiftUI22AccessibilityRotorInfoV13readEntryList33_030667BFE09FD674B7612731735E240ELLyyyAA0cdgH0VXEFyyXEfU_25IndexingWrappingGeneratorL_VMn") == [ + PrivateDeclaration(name: "readEntryList", discriminator: "_030667BFE09FD674B7612731735E240E"), + ]) + } + + /// The private type in a private method's signature is not read; the + /// method is. + @Test func privateTypeInAMethodSignatureIsNotRead() throws { + // InPrivateSignature #1 in Shapes.Holder.(takes in _C017…)(Shapes.(PrivateArgument in _C017…)) -> Any + #expect(try Self.privateDeclarations(of: "$s6Shapes6HolderV5takes33_C01776A4525D5700C9CAB18498B5F7E5LLyypAA15PrivateArgumentAELLVF02InL9SignatureL_VMn") == [ + PrivateDeclaration(name: "takes", discriminator: Self.shapesDiscriminator), + ]) + } + + @Test func privateTypeInAClosureSignatureIsNotRead() throws { + // InClosureSignature #1 in closure #1 (Shapes.(PrivateArgument in _C017…)) -> Any in Shapes.Holder.closure() -> Any + #expect(try Self.privateDeclarations(of: "$s6Shapes6HolderV7closureypyFypAA15PrivateArgument33_C01776A4525D5700C9CAB18498B5F7E5LLVcfU_18InClosureSignatureL_VMn").isEmpty) + } + + /// A private initializer's or subscript's mangled private name carries a + /// discriminator and no name; the declaration's kind stands in for one. + @Test func privateInitializerAndSubscriptAreNamedByTheirKind() throws { + // InPrivateInitializer #1 in Shapes.Holder.(in _C017…).init(argument: Swift.Int) -> Shapes.Holder + #expect(try Self.privateDeclarations(of: "$s6Shapes6HolderV8argumentACSi_tc33_C01776A4525D5700C9CAB18498B5F7E5Llfc20InPrivateInitializerL_VMn") == [ + PrivateDeclaration(name: "init", discriminator: Self.shapesDiscriminator), + ]) + // InPrivateSubscript #1 in Shapes.Holder.subscript.getter : (Swift.Int) -> Any + #expect(try Self.privateDeclarations(of: "$s6Shapes6HolderVyypSic33_C01776A4525D5700C9CAB18498B5F7E5Llig18InPrivateSubscriptL_VMn") == [ + PrivateDeclaration(name: "subscript", discriminator: Self.shapesDiscriminator), + ]) + } + + /// `Holder.(Visitor in $1a2b3c)`: the shape of a private name, the + /// address of the anonymous context wrapping the type. + @Test func positionBasedAddressIsNoDiscriminator() { + let holder = Node.create(kind: .structure, children: [ + Node.create(kind: .module, text: "M"), + Node.create(kind: .identifier, text: "Holder"), + ]) + let visitor = Node.create(kind: .type, child: Node.create(kind: .structure, children: [ + holder, + Node.create(kind: .privateDeclName, children: [ + Node.create(kind: .identifier, text: "$1a2b3c"), + Node.create(kind: .identifier, text: "Visitor"), + ]), + ])) + + #expect(visitor.localTypeNaming == .positionBased) + #expect(visitor.privateDeclarations.isEmpty) + #expect(NodeReference(interning: visitor).privateDeclarations.isEmpty) + } + + // MARK: - Names built from descriptors + + /// What `SymbolicDemangler` names each local type of the fixture: only + /// `Hidden`, declared in the private `hiddenValues()`, reads a private + /// declaration, and where nothing names the functions every name is + /// position-based and reads none. + @Test(arguments: [LocalTypeFixture.Variant.unstripped, .stripped]) + func localTypesBuiltFromDescriptorsReadOnlyTheirPrivateMethod(variant: LocalTypeFixture.Variant) throws { + let machOFile = try LocalTypeFixture.machOFile(variant) + var privateDeclarationsByTypeName: [String: [PrivateDeclaration]] = [:] + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + let descriptor = typeContextDescriptor.asContextDescriptorWrapper + guard try LocalTypeFixture.isDeclaredInABody(descriptor, in: machOFile.context) else { continue } + let typeName = try #require(try descriptor.namedContextDescriptor?.name(in: machOFile.context)) + let node = try SymbolicDemangler.demangleContext(for: descriptor, in: machOFile.context) + privateDeclarationsByTypeName[typeName, default: []] += node.privateDeclarations + } + + #expect(privateDeclarationsByTypeName.count > 10) + for (typeName, privateDeclarations) in privateDeclarationsByTypeName where !(typeName == "Hidden" && variant == .unstripped) { + #expect(privateDeclarations.isEmpty, "\(typeName) reads \(privateDeclarations)") + } + if variant == .unstripped { + let hidden = try #require(privateDeclarationsByTypeName["Hidden"]) + #expect(hidden.map(\.name) == ["hiddenValues"]) + #expect(hidden.allSatisfy { $0.discriminator.hasPrefix("_") && $0.discriminator.count == 33 }) + } + } +} diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift new file mode 100644 index 000000000..12f90b98c --- /dev/null +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift @@ -0,0 +1,272 @@ +import Foundation +import Testing +import MachOKit +import MachOFixtureSupport +@testable import MachOTestingSupport +@_spi(Support) import SwiftIndexing +import SwiftInspection +@testable @_spi(Support) import SwiftPrivateDiscriminators + +/// An image's private discriminators, recovered from candidates the image's +/// own names make (evolution proposal `private-declarations`). +/// +/// Nothing here depends on the system the tests run on; the suite reading the +/// running system's images is `PrivateDiscriminatorSourceFileSystemImageTests`. +@Suite(.serialized, ExclusiveImageAccess(LocalTypeFixture.exclusiveAccessName)) +struct PrivateDiscriminatorSourceFileIndexTests { + /// The fixture is compiled from `Fixture.swift`, and its names spell + /// `Fixture` (`LocalTypeFixtureVisitor`). `md5 -s + /// 'LocalTypeFixtureUnstrippedFixture.swift'`, computed outside this code + /// base, is `2ea5a000e301e8e89be43d5fb26a4d0e`. + private static let unstrippedFixtureDiscriminator = "_2EA5A000E301E8E89BE43D5FB26A4D0E" + + private static let swiftUICorePath = "/System/Library/Frameworks/SwiftUICore.framework/Versions/A/SwiftUICore" + + /// `md5 -s 'SwiftUICoreEnabled.swift'`. + private static let enabledDiscriminator = "_09CE35833F3876FE3A3A46977D61FC64" + + /// No candidate the names below make produces it. + private static let unrecoverableDiscriminator = "_70EED0686586E4A728468B96DBF4A6DF" + + private static let enabledSourceFile = PrivateDiscriminatorSourceFiles.SourceFile(fileName: "Enabled.swift", moduleName: "SwiftUICore", isSynthesized: false) + + /// Two names of SwiftUICore's, as its indexer prints them: under the ABI + /// module name `SwiftUI`. + private static let swiftUICoreNames: [PrivateDiscriminatorSourceFiles.ImageName] = [ + .init(printedName: "SwiftUI.EnabledKey", discriminators: [enabledDiscriminator]), + .init(printedName: "SwiftUI.NearestScrollableAxesEnvironmentKey", discriminators: [unrecoverableDiscriminator]), + ] + + /// The size of a large-stack worker's stack, which reading the names + /// needs: `StackSafeExecutor.largeStackThreadSize`. + private static let largeStackSize = 8 * 1024 * 1024 + + /// The discriminator of the private `hiddenValues()`, which declares the + /// local type `Hidden`, read off the indexed name of that type. + private static func hiddenValuesDiscriminator(in indexer: SwiftDeclarationIndexer) throws -> String { + let hidden = try #require(indexer.allTypeDefinitions.keys.first { $0.node.localTypeNaming != nil && $0.name.hasPrefix("Hidden #1 in ") }) + return try #require(hidden.node.privateDeclarations.first).discriminator + } + + @Test func fileImageRecoversTheFixtureSourceFile() async throws { + let machOFile = try LocalTypeFixture.machOFile(.unstripped) + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: machOFile) + try await indexer.prepare() + let discriminator = try Self.hiddenValuesDiscriminator(in: indexer) + + #expect(discriminator == Self.unstrippedFixtureDiscriminator) + let sourceFiles = PrivateDiscriminatorSourceFileIndex(indexer: indexer, knownFileNames: []).sourceFiles(forDiscriminators: [discriminator]) + #expect(sourceFiles == [discriminator: .init(fileName: "Fixture.swift", moduleName: "LocalTypeFixtureUnstripped", isSynthesized: false)]) + } + + @Test func loadedImageRecoversTheFixtureSourceFile() async throws { + let machOImage = try LocalTypeFixture.loadedImage(.unstripped) + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: machOImage) + try await indexer.prepare() + let discriminator = try Self.hiddenValuesDiscriminator(in: indexer) + + let sourceFiles = PrivateDiscriminatorSourceFileIndex(indexer: indexer, knownFileNames: []).sourceFiles(forDiscriminators: [discriminator]) + #expect(sourceFiles == [discriminator: .init(fileName: "Fixture.swift", moduleName: "LocalTypeFixtureUnstripped", isSynthesized: false)]) + } + + /// The image's names are read on the first request, and only then; a + /// discriminator nothing produces is left out of every answer, and is + /// not searched for again. + @Test func namesAreReadOnceAndAnswersKept() { + let readCount = ReadCount() + let index = PrivateDiscriminatorSourceFileIndex(imagePath: Self.swiftUICorePath, knownFileNames: []) { + readCount.increment() + return Self.swiftUICoreNames + } + #expect(readCount.value == 0) + + #expect(index.sourceFiles(forDiscriminators: [Self.enabledDiscriminator, Self.unrecoverableDiscriminator]) == [Self.enabledDiscriminator: Self.enabledSourceFile]) + #expect(index.searchCount == 1) + #expect(index.sourceFiles(forDiscriminators: [Self.unrecoverableDiscriminator]).isEmpty) + #expect(index.sourceFiles(forDiscriminators: [Self.enabledDiscriminator]) == [Self.enabledDiscriminator: Self.enabledSourceFile]) + #expect(readCount.value == 1) + #expect(index.searchCount == 1) + } + + /// Reading the names prints every name the image declares, and a request + /// comes from wherever the host is — a cooperative thread's 512 KB stack + /// here. The names are read on a large stack all the same. + @Test func namesAreReadOnALargeStack() async throws { + let requestingStackSize = pthread_get_stacksize_np(pthread_self()) + try #require(requestingStackSize < Self.largeStackSize, "the premise: the request comes from a small stack, not \(requestingStackSize) bytes") + let readingStackSizes = ReadingStackSizes() + let index = PrivateDiscriminatorSourceFileIndex(imagePath: Self.swiftUICorePath, knownFileNames: []) { + readingStackSizes.append(pthread_get_stacksize_np(pthread_self())) + return Self.swiftUICoreNames + } + + #expect(index.sourceFiles(forDiscriminators: [Self.enabledDiscriminator]) == [Self.enabledDiscriminator: Self.enabledSourceFile]) + let stackSizes = readingStackSizes.values + #expect(stackSizes.count == 1) + #expect(stackSizes.allSatisfy { $0 >= Self.largeStackSize }, "the names were read on stacks of \(stackSizes) bytes") + } + + /// The names are read outside the index's lock: two first requests that + /// overlap both read them — each waits in the names closure until the + /// other is there too — agree, and search once. + @Test func overlappingFirstRequestsBothReadAndSearchOnce() async throws { + let readCount = ReadCount() + let rendezvous = Rendezvous(expectedArrivals: 2) + let index = PrivateDiscriminatorSourceFileIndex(imagePath: Self.swiftUICorePath, knownFileNames: []) { + readCount.increment() + // Times out instead of hanging when the other request cannot get + // here — which is what a lock held across the read does. + _ = rendezvous.arriveAndWait(timeout: 10) + return Self.swiftUICoreNames + } + + let answers = await Self.onThreadsOfTheirOwn(2) { + index.sourceFiles(forDiscriminators: [Self.enabledDiscriminator, Self.unrecoverableDiscriminator]) + } + #expect(answers == Array(repeating: [Self.enabledDiscriminator: Self.enabledSourceFile], count: 2)) + #expect(readCount.value == 2) + #expect(index.searchCount == 1) + } + + /// The indexer's deinit is what releases the image's caches + /// (`SharedCacheRegistry`), and a host keeps the index as long as the + /// image: once the names are read, the index lets go of the indexer. + @Test func indexLetsGoOfItsIndexerOnceTheNamesAreRead() async throws { + let (index, indexer) = try await Self.indexHoldingTheOnlyReferenceToItsIndexer() + #expect(indexer.object != nil, "the premise: until the first request, the index holds the indexer") + + #expect(index.sourceFiles(forDiscriminators: [Self.unstrippedFixtureDiscriminator]) == [ + Self.unstrippedFixtureDiscriminator: .init(fileName: "Fixture.swift", moduleName: "LocalTypeFixtureUnstripped", isSynthesized: false), + ]) + #expect(try await indexer.isReleased(within: 2), "the index still holds its indexer") + } + + private static func indexHoldingTheOnlyReferenceToItsIndexer() async throws -> (PrivateDiscriminatorSourceFileIndex, WeakReference>) { + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: try LocalTypeFixture.machOFile(.unstripped)) + try await indexer.prepare() + return (PrivateDiscriminatorSourceFileIndex(indexer: indexer, knownFileNames: []), WeakReference(indexer)) + } + + /// Runs `body` on `count` threads started for it, all at once, and + /// returns what each returned. Threads of their own, not tasks: two + /// tasks are not sure to run at once on a busy cooperative pool. + private static func onThreadsOfTheirOwn(_ count: Int, _ body: @escaping @Sendable () -> Result) async -> [Result] { + await withCheckedContinuation { continuation in + let results = ResultCollector(expectedCount: count) { continuation.resume(returning: $0) } + for _ in 0 ..< count { + Thread { results.append(body()) }.start() + } + } + } +} + +private final class ReadCount: @unchecked Sendable { + private let lock = NSLock() + + private var count = 0 + + var value: Int { + lock.lock() + defer { lock.unlock() } + return count + } + + func increment() { + lock.lock() + defer { lock.unlock() } + count += 1 + } +} + +private final class ReadingStackSizes: @unchecked Sendable { + private let lock = NSLock() + + private var stackSizes: [Int] = [] + + var values: [Int] { + lock.lock() + defer { lock.unlock() } + return stackSizes + } + + func append(_ stackSize: Int) { + lock.lock() + defer { lock.unlock() } + stackSizes.append(stackSize) + } +} + +/// Holds every caller until `expectedArrivals` have arrived. +private final class Rendezvous: @unchecked Sendable { + private let condition = NSCondition() + + private let expectedArrivals: Int + + private var arrivals = 0 + + init(expectedArrivals: Int) { + self.expectedArrivals = expectedArrivals + } + + /// Whether every expected caller arrived within `timeout` seconds. + func arriveAndWait(timeout: TimeInterval) -> Bool { + condition.lock() + defer { condition.unlock() } + arrivals += 1 + condition.broadcast() + let deadline = Date(timeIntervalSinceNow: timeout) + while arrivals < expectedArrivals { + if !condition.wait(until: deadline) { + return arrivals >= expectedArrivals + } + } + return true + } +} + +/// Collects the results of `expectedCount` threads and hands them over once +/// the last is in. +private final class ResultCollector: @unchecked Sendable { + private let lock = NSLock() + + private let expectedCount: Int + + private let completion: @Sendable ([Result]) -> Void + + private var results: [Result] = [] + + init(expectedCount: Int, completion: @escaping @Sendable ([Result]) -> Void) { + self.expectedCount = expectedCount + self.completion = completion + } + + func append(_ result: Result) { + lock.lock() + results.append(result) + let completedResults = results.count == expectedCount ? results : nil + lock.unlock() + if let completedResults { + completion(completedResults) + } + } +} + +private final class WeakReference: @unchecked Sendable { + private(set) weak var object: Object? + + init(_ object: Object) { + self.object = object + } + + /// Whether the object is gone within `timeout` seconds. The last + /// reference to a closure run on a large stack can sit with the worker + /// that ran it for a moment after the call that submitted it returns. + func isReleased(within timeout: TimeInterval) async throws -> Bool { + let deadline = Date(timeIntervalSinceNow: timeout) + while object != nil { + guard Date() < deadline else { return false } + try await Task.sleep(nanoseconds: 10_000_000) + } + return true + } +} diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift new file mode 100644 index 000000000..a7fefa5bd --- /dev/null +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift @@ -0,0 +1,50 @@ +import Foundation +import Testing +import MachOKit +import MachOFixtureSupport +@_spi(Support) import SwiftIndexing +import SwiftInspection +@_spi(Support) import SwiftPrivateDiscriminators + +/// Private discriminators of the running system's own images, read out of its +/// dyld shared cache (evolution proposal `private-declarations`). +/// +/// The discriminators and the files they are recovered to are those of +/// macOS 27.2, where they were taken; another release can move a type to +/// another file or drop it. So this suite stays out of the CI workflow's +/// filter, whose runner runs another release. +@Suite(.serialized) +struct PrivateDiscriminatorSourceFileSystemImageTests { + /// A private class's discriminator, found through the class's own name. + @Test func systemFoundationRecoversJSONEncoder() async throws { + let cache = try DyldCache(path: .current) + let foundation = try #require(cache.machOFile(named: .Foundation)) + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: foundation) + try await indexer.prepare() + let encoder = try #require(indexer.allTypeDefinitions.keys.first { $0.name == "Foundation.__JSONEncoder" }) + let discriminator = try #require(encoder.node.privateDeclarations.first).discriminator + + // `md5 -s 'FoundationJSONEncoder.swift'`. + #expect(discriminator == "_12768CA107A31EF2DCE034FD75B541C9") + #expect(PrivateDiscriminatorSourceFileIndex(indexer: indexer).sourceFiles(forDiscriminators: [discriminator])[discriminator]?.fileName == "JSONEncoder.swift") + } + + /// SwiftUICore's types print under its ABI module name, `SwiftUI`, but the + /// compiler hashed the module's own name: only the module name taken + /// from the image's file name recovers them. No known file names, so the + /// file name too comes from the image's names (`EnabledKey`). + @Test func systemSwiftUICoreHashesItsOwnModuleName() async throws { + let cache = try DyldCache(path: .current) + let swiftUICore = try #require(cache.machOFile(named: .SwiftUICore)) + let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: swiftUICore) + try await indexer.prepare() + let enabledKey = try #require(indexer.allTypeDefinitions.keys.first { $0.name == "SwiftUI.EnabledKey" }) + let discriminator = try #require(enabledKey.node.privateDeclarations.first).discriminator + + // `md5 -s 'SwiftUICoreEnabled.swift'`. + #expect(discriminator == "_09CE35833F3876FE3A3A46977D61FC64") + #expect(PrivateDiscriminatorSourceFileIndex(indexer: indexer, knownFileNames: []).sourceFiles(forDiscriminators: [discriminator]) == [ + discriminator: .init(fileName: "Enabled.swift", moduleName: "SwiftUICore", isSynthesized: false), + ]) + } +} diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFilesTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFilesTests.swift new file mode 100644 index 000000000..71f4160d8 --- /dev/null +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFilesTests.swift @@ -0,0 +1,213 @@ +import Testing +@testable import SwiftPrivateDiscriminators + +/// Recovering the source file a private discriminator was derived from. Every +/// expected value was computed with `md5 -s` outside this code base — +/// `md5 -s 'SwiftUICoreEnabled.swift'` is `09ce35833f3876fe3a3a46977d61fc64` — +/// and the discriminators, with the private types declared under them, are the +/// ones SwiftUICore and Foundation actually carry (macOS 26.7). +/// +/// Each rule is tested with no known file names, so that only the image's own +/// names can produce the file name. Moved from RuntimeViewer with the search +/// itself (evolution proposal `private-declarations`). +@Suite +struct PrivateDiscriminatorSourceFilesTests { + private static let swiftUICorePath = "/System/Library/Frameworks/SwiftUICore.framework/Versions/A/SwiftUICore" + private static let foundationPath = "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation" + + /// A name as a reader is shown it — without discriminators — and the + /// discriminators of the private declarations it reads. + private static func name(_ printedName: String, discriminators: [String] = []) -> PrivateDiscriminatorSourceFiles.ImageName { + PrivateDiscriminatorSourceFiles.ImageName(printedName: printedName, discriminators: discriminators) + } + + private static func sourceFile(of discriminator: String, in imagePath: String = swiftUICorePath, among imageNames: [PrivateDiscriminatorSourceFiles.ImageName], knownFileNames: [String] = []) -> PrivateDiscriminatorSourceFiles.SourceFile? { + PrivateDiscriminatorSourceFiles(recovering: [discriminator], imagePath: imagePath, imageNames: imageNames, knownFileNames: knownFileNames) + .sourceFile(forDiscriminator: discriminator) + } + + // MARK: - Names of the Image + + @Test("a framework's discriminator is recovered under the framework's own name, not the module its types print under") + func frameworkDiscriminatorUsesFrameworkName() { + let sourceFile = Self.sourceFile( + of: "_09CE35833F3876FE3A3A46977D61FC64", + among: [Self.name("SwiftUI.EnabledKey", discriminators: ["_09CE35833F3876FE3A3A46977D61FC64"])] + ) + #expect(sourceFile == .init(fileName: "Enabled.swift", moduleName: "SwiftUICore", isSynthesized: false)) + } + + @Test("a file named after another type in the image is found through that type's name") + func fileNamedAfterAnotherType() { + let privateType = Self.name("SwiftUI.ResetDeltaModifier", discriminators: ["_C38EF38637B6130AEFD462CBD5EAC727"]) + + #expect(Self.sourceFile(of: "_C38EF38637B6130AEFD462CBD5EAC727", among: [privateType]) == nil) + #expect(Self.sourceFile(of: "_C38EF38637B6130AEFD462CBD5EAC727", among: [privateType, Self.name("SwiftUI._ViewInputs")])?.fileName == "ViewInputs.swift") + } + + @Test("a private type nested in another type is recovered too") + func nestedPrivateTypeIsRecovered() { + let sourceFile = Self.sourceFile( + of: "_09CE35833F3876FE3A3A46977D61FC64", + among: [ + Self.name("SwiftUI.Outer"), + Self.name("SwiftUI.Outer.EnabledKey", discriminators: ["_09CE35833F3876FE3A3A46977D61FC64"]), + ] + ) + #expect(sourceFile?.fileName == "Enabled.swift") + } + + @Test("an acronym ends a word, so JSONEncoder suggests JSONEncoder.swift") + func acronymEndsAWord() { + let sourceFile = Self.sourceFile( + of: "_12768CA107A31EF2DCE034FD75B541C9", + in: Self.foundationPath, + among: [Self.name("Foundation.__JSONEncoder", discriminators: ["_12768CA107A31EF2DCE034FD75B541C9"])] + ) + #expect(sourceFile == .init(fileName: "JSONEncoder.swift", moduleName: "Foundation", isSynthesized: false)) + } + + @Test("a run of words from the middle of a name is a file name too") + func middleRunOfWords() { + let sourceFile = Self.sourceFile( + of: "_25C7EE19F64B0E53EE4CB01B5E3710EB", + among: [ + Self.name("SwiftUI.DisplayList.InterpolatorLayer.Contents", discriminators: ["_25C7EE19F64B0E53EE4CB01B5E3710EB"]), + Self.name("__C.RBDisplayListInterpolatorOptionKey"), + ] + ) + #expect(sourceFile?.fileName == "DisplayListInterpolator.swift") + } + + @Test("a word that often ends a file name is tried after a run of words") + func commonLastWord() { + let sourceFile = Self.sourceFile( + of: "_82B2D47816BC992595021D60C278AFF0", + among: [ + Self.name("SwiftUI.AtomicBuffer", discriminators: ["_82B2D47816BC992595021D60C278AFF0"]), + Self.name("SwiftUI.MainThreadFlags"), + ] + ) + #expect(sourceFile?.fileName == "ThreadUtils.swift") + } + + @Test("a name is tried in the plural") + func pluralName() { + let sourceFile = Self.sourceFile( + of: "_59349949219F590F26B6A55CEC9D59A2", + among: [Self.name("SwiftUI.Signpost.Level", discriminators: ["_59349949219F590F26B6A55CEC9D59A2"])] + ) + #expect(sourceFile?.fileName == "Signposts.swift") + } + + @Test("an extension's file name comes from two words of the names declared in it") + func extensionFileFromItsOwnNames() { + let sourceFile = Self.sourceFile( + of: "_AEE0E21EC7C6B2D1204F94F94CBF7389", + among: [Self.name("SwiftUI.DateTextStorage", discriminators: ["_AEE0E21EC7C6B2D1204F94F94CBF7389"])] + ) + #expect(sourceFile?.fileName == "Text+Date.swift") + } + + @Test("an extension's file name can start with any type of the image") + func extensionFileOfAnotherType() { + let privateType = Self.name("SwiftUI.ObjectLocation", discriminators: ["_7719FABF28E05207C06C2817640AD611"]) + + #expect(Self.sourceFile(of: "_7719FABF28E05207C06C2817640AD611", among: [privateType]) == nil) + #expect(Self.sourceFile(of: "_7719FABF28E05207C06C2817640AD611", among: [privateType, Self.name("SwiftUI.Binding")])?.fileName == "Binding+ObjectLocation.swift") + } + + @Test("the file the compiler synthesizes for a file of the image is recovered through that file") + func synthesizedFileIsRecovered() { + let sourceFile = Self.sourceFile( + of: "_7851CE71456138B12D1FE5F34D2E09D2", + in: Self.foundationPath, + among: [ + Self.name("Foundation.__JSONEncoder", discriminators: ["_12768CA107A31EF2DCE034FD75B541C9"]), + Self.name("Foundation.SynthesizedConformance", discriminators: ["_7851CE71456138B12D1FE5F34D2E09D2"]), + ] + ) + #expect(sourceFile == .init(fileName: "JSONEncoder.swift", moduleName: "Foundation", isSynthesized: true)) + } + + @Test("the module a private type prints under is tried when the image's file name is not the module") + func moduleFromPrintedNameIsTried() { + let imagePath = "/Applications/My App.app/Contents/Frameworks/Shared.framework/Shared" + let sourceFile = Self.sourceFile( + of: "_49589088029ECC1F743D97737F6C44F6", + in: imagePath, + among: [ + Self.name("My_App.Row", discriminators: ["_49589088029ECC1F743D97737F6C44F6"]), + Self.name("My_App.ContentView"), + ] + ) + #expect(sourceFile?.moduleName == "My_App") + } + + /// A local type's name starts with the type, not a module: what comes + /// before its first dot is no module name to hash under. + @Test("a local type's name lends no module name") + func localTypeNameLendsNoModuleName() { + let imagePath = "/Applications/My App.app/Contents/Frameworks/Shared.framework/Shared" + let sourceFiles = PrivateDiscriminatorSourceFiles.Candidates( + imagePath: imagePath, + imageNames: [Self.name("Visitor #1 in My_App.Holder.(rows in _49589088029ECC1F743D97737F6C44F6)() -> Any", discriminators: ["_49589088029ECC1F743D97737F6C44F6"])] + ) + #expect(sourceFiles.moduleNames == ["Shared"]) + } + + /// The discriminator is made up — `md5 -s 'SwiftUICoreGlue.swift'` — since + /// the point is that those bytes read two ways: `CoreGlue.swift`, the known + /// name, hashed under `SwiftUI`, is `Glue.swift` under `SwiftUICore`. + @Test("a digest two module names read alike is read under the module name tried first") + func digestIsReadUnderTheFirstModuleName() { + let sourceFile = Self.sourceFile( + of: "_CE8713EF1F659E3933681417E097F9F6", + among: [Self.name("SwiftUI.Foo", discriminators: ["_CE8713EF1F659E3933681417E097F9F6"])], + knownFileNames: ["CoreGlue.swift"] + ) + #expect(sourceFile == .init(fileName: "Glue.swift", moduleName: "SwiftUICore", isSynthesized: false)) + } + + @Test("only the discriminators asked for are looked for") + func onlyRequestedDiscriminators() { + let sourceFiles = PrivateDiscriminatorSourceFiles( + recovering: ["_09CE35833F3876FE3A3A46977D61FC64"], + imagePath: Self.swiftUICorePath, + imageNames: [ + Self.name("SwiftUI.EnabledKey", discriminators: ["_09CE35833F3876FE3A3A46977D61FC64"]), + Self.name("SwiftUI.ResetDeltaModifier", discriminators: ["_C38EF38637B6130AEFD462CBD5EAC727"]), + Self.name("SwiftUI._ViewInputs"), + ], + knownFileNames: [] + ) + #expect(sourceFiles.sourceFile(forDiscriminator: "_09CE35833F3876FE3A3A46977D61FC64")?.fileName == "Enabled.swift") + #expect(sourceFiles.sourceFile(forDiscriminator: "_C38EF38637B6130AEFD462CBD5EAC727") == nil) + } + + @Test("a discriminator no candidate produces is left unrecovered") + func unproducedDiscriminatorIsUnrecovered() { + let sourceFile = Self.sourceFile( + of: "_70EED0686586E4A728468B96DBF4A6DF", + among: [Self.name("SwiftUI.NearestScrollableAxesEnvironmentKey", discriminators: ["_70EED0686586E4A728468B96DBF4A6DF"])] + ) + #expect(sourceFile == nil) + } + + // MARK: - Known File Names + + @Test("a known file name recovers a discriminator the image's names do not produce") + func knownFileNameIsTried() { + let privateType = Self.name("SwiftUI.ResetDeltaModifier", discriminators: ["_C38EF38637B6130AEFD462CBD5EAC727"]) + + #expect(Self.sourceFile(of: "_C38EF38637B6130AEFD462CBD5EAC727", among: [privateType], knownFileNames: ["ViewInputs.swift"])?.fileName == "ViewInputs.swift") + } + + @Test("the bundled file names include OpenSwiftUI's, and are what is tried by default") + func bundledFileNamesAreTriedByDefault() { + let privateType = Self.name("SwiftUI.ResetDeltaModifier", discriminators: ["_C38EF38637B6130AEFD462CBD5EAC727"]) + let sourceFiles = PrivateDiscriminatorSourceFiles(recovering: ["_C38EF38637B6130AEFD462CBD5EAC727"], imagePath: Self.swiftUICorePath, imageNames: [privateType]) + + #expect(sourceFiles.sourceFile(forDiscriminator: "_C38EF38637B6130AEFD462CBD5EAC727")?.fileName == "ViewInputs.swift") + } +} From 295d8d8f2c6d63fad1bb76958675bcf61567f678 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 23:01:09 +0800 Subject: [PATCH 34/49] docs: document SwiftPrivateDiscriminators and propose private-declarations - The proposal, with the choices the user made: RuntimeViewer calls the recovery in its engine process, while the library takes the candidates from the image and keeps the answers per image; a local type's display name leaves out modules and parameter types; a private function's discriminator counts for the local types it declares. The six review findings and their fixes are in its decision log. - Modules/SwiftPrivateDiscriminators: the search, the known file names and the per-image index, and how the index's candidates differ from RuntimeViewer's sidebar list. - AGENTS.md: the new module, and `privateDeclarations` in SwiftInspection. - Documentations/README, the module index and the proposal index. --- AGENTS.md | 5 +- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-private-declarations.md | 152 ++++++++++++++++++ Documentations/Internal/Modules/README.md | 1 + .../Modules/SwiftPrivateDiscriminators.md | 59 +++++++ Documentations/README.md | 2 + 6 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 Documentations/Evolutions/draft-private-declarations.md create mode 100644 Documentations/Internal/Modules/SwiftPrivateDiscriminators.md diff --git a/AGENTS.md b/AGENTS.md index ac6765b6e..af77af459 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,7 +32,7 @@ SwiftInspection and everything above it also import └── MachOCaches, MachOBase ``` -`SwiftLayout` is a peer of that spine: it depends on `SwiftInspection` + `MachOSwiftSection` (+ `MachOObjCSection` for ObjC-ancestor instance sizes) and is consumed by `SwiftDeclarationRendering`. `TypeIndexing`, `SwiftDiffing` and `OutputTransformer` hang off the same level as the modules that use them. +`SwiftLayout` is a peer of that spine: it depends on `SwiftInspection` + `MachOSwiftSection` (+ `MachOObjCSection` for ObjC-ancestor instance sizes) and is consumed by `SwiftDeclarationRendering`. `TypeIndexing`, `SwiftDiffing`, `SwiftPrivateDiscriminators` and `OutputTransformer` hang off the same level as the modules that use them. **`Sources/` is grouped by layer, not flat**: `Support/`, `MachO/`, `ABI/`, `Analysis/`, `Declaration/`, `Output/`, `Commands/`, `Executables/`, `TestSupport/`, each holding the targets of that layer. SwiftPM's default `Sources/` therefore never applies — a new target goes into a group directory and declares `path: "Sources//"` in `Package.swift`. Code that locates a source file from `#filePath` assumes this depth: the fixture paths in `MachOFileName` / `MachOImageName` climb three levels to the package root, and the source scans in the tests take the module name from two levels below `Sources`. [0055-group-sources-by-layer](Documentations/Evolutions/0055-group-sources-by-layer.md). @@ -44,11 +44,12 @@ One or two lines each; the linked document is the authority. - **Demangling** (upstream package) — mangled symbol → `Node` AST → printed Swift, plus the remangler. `Node.Kind` covers ~200 mangling node kinds. - **MachOSwiftSection** — the ABI model: the `__swift5_*` sections, every descriptor shape in them, and Swift's position-independent relative pointers. Self-contained — `MachOBase` only, no symbol index, no demangler; a descriptor exposes an implementation's *offset* and `SwiftInspection` attributes the name ([SelfContainedABILayer.md](Documentations/Internal/SelfContainedABILayer.md)). -- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors, a local or private type's anonymous contexts named by `AnonymousContextNameIndex` and the descriptors' own symbols, and `LocalTypeNaming` telling a local type's name apart), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). +- **SwiftInspection** — runtime metadata analysis, and where ABI-layer symbol attribution lives: `SymbolicDemangler` (names carrying symbolic references; also demanglings built straight from descriptors, a local or private type's anonymous contexts named by `AnonymousContextNameIndex` and the descriptors' own symbols, and `LocalTypeNaming` telling a local type's name apart, `privateDeclarations` (a `[PrivateDeclaration]`) the private declarations a name reads — not a declaring function's signature, not a position-based `$` address), `SymbolicManglingIndex` (each symbolic reference in the mangled names the image's `_symbolic` symbols name, paired with the referent the compiler spelled for it — where a system image's private discriminators come from; [SymbolicManglingSymbols.md](Documentations/Internal/SymbolicManglingSymbols.md)), `RuntimeMetadataTypeBuilder` (node → live metadata), `GenericParameterDepthLayout` + `GenericArgumentBinding` (how a generic context's parameters split into depths, and one instantiation's arguments by depth — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)), `EnumLayoutCalculator` + `RuntimeEnumCaseProjector`, `ClassHierarchyDumper`, `ObjCImplementationClassIndex` (SE-0436 `@objc @implementation` classes, recognized from `__objc_classlist` joined with the symbol table — [ObjCImplementationClassRecognition.md](Documentations/Internal/ObjCImplementationClassRecognition.md)), `SwiftClassObjectIndex` (the Swift classes a source renamed for the ObjC runtime — `@objc(NSScrollPocket)` — joined to their descriptor through the class metadata, since their runtime name demangles to nothing; every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss — [CustomObjCClassNames.md](Documentations/Internal/CustomObjCClassNames.md)), `ObjCClassHierarchy` + `ObjCClassHierarchyProviding` / `ObjCClassHierarchyProviderStore` (the per-image seam through which a host hands over the ObjC class hierarchies it already indexed — RuntimeViewer's indexer, or `SwiftIndexing`'s adapter over `ObjCIndexing.ObjCInterfaceIndexer`) with `ObjCClassMethodIndex` as the library's own lazy reader behind it (class, metaclass and same-image category method lists, the ancestor chain, the adopted protocols' selectors) and `ObjCAncestorResolver` / `ObjCAncestorResolverStore` following a standalone file's bound superclass or category target by name into its dependency closure (export trie first, then the class list; the indexer and `dump` register one per image over the configured search paths, an unregistered file defaults to the system cache, an in-process image needs none — so a file's chain reaches libobjc's `NSObject` like a cache image's does), `ObjCMember` / `ObjCMemberTable` (the per-class ObjC member table: every method-table entry tied to its Swift member — the `@objc`, `override` and explicit-selector facts in one place) and `ObjCMemberShape` (a member's selector shape: the importer's naming rules applied as a forward CHECK, and the compiler's own selector derivation ported for the explicit-selector verdict) — [ObjCMemberRecovery.md](Documentations/Internal/ObjCMemberRecovery.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). - **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). - **SwiftIndexing** — builds the declaration model from an image (`SwiftDeclarationIndexer.prepare()`), unifies extension containers, owns the per-image cache eviction. +- **SwiftPrivateDiscriminators** — recovers the source file a private discriminator was derived from (`MD5(module name + file name)`): candidate file names hashed until one matches — a generated list of known ones, then names the image itself declares. `PrivateDiscriminatorSourceFileIndex` holds one image's candidates and remembers every answer. [Modules/SwiftPrivateDiscriminators.md](Documentations/Internal/Modules/SwiftPrivateDiscriminators.md). - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). - **SwiftPrinting** — renders the model as Swift source: keywords the mangling does not carry (`class` vs `static`, `final`), bound rendering of specialized definitions, export-status annotation and `--exported-only` filtering. - **SwiftSpecialization** — generic specialization (`GenericSpecializer`, `ConformanceProvider`): in-process through the metadata accessors on a `MachOImage`, and offline on a `MachOFile` (`StaticSpecializationResult`: the instantiation's name and a `GenericArgumentBinding`, which the printer and the static layout engine render from — [OfflineGenericSpecialization.md](Documentations/Internal/OfflineGenericSpecialization.md)); grafts `specialize(...)` onto `TypeDefinition`. diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index a264782b7..e2e002527 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -76,3 +76,4 @@ | [0061](0061-dyld-shared-cache-path-versions.md) | 测试用的 dyld shared cache 路径按版本取 | Implemented | | draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | +| draft | [私有声明:从名字取 discriminator,按镜像反推源文件](draft-private-declarations.md) | In Progress | diff --git a/Documentations/Evolutions/draft-private-declarations.md b/Documentations/Evolutions/draft-private-declarations.md new file mode 100644 index 000000000..05ceba743 --- /dev/null +++ b/Documentations/Evolutions/draft-private-declarations.md @@ -0,0 +1,152 @@ +# Draft - 私有声明:从名字取 discriminator,按镜像反推源文件 + +- **状态**: In Progress +- **创建日期**: 2026-10-11 +- **最后更新**: 2026-10-11 +- **关联提案**: [0062-local-type-context-names](0062-local-type-context-names.md)(占位名与 `LocalTypeNaming`);展示一侧是 RuntimeViewer 的 [draft-private-discriminator-tag](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/feature/private-discriminator-tag/Documentations/Evolutions/draft-private-discriminator-tag.md) +- **实现分支**: `feature/private-declarations`(worktree `.worktrees/MachOSwiftSection-PrivateDeclarations`),基于本地 `next` 100da85c,要用 0062 的 `LocalTypeNaming` + +## 摘要 + +RuntimeViewer 的侧栏给私有类型挂一个 `Private` 标签,点开列出 private discriminator,以及 discriminator 来自哪个源文件。这背后的两件事现在都由 RuntimeViewer 自己做: + +- 从名字的 demangle 树里收集 `privateDeclName` 节点。 +- 拿候选文件名算 MD5 去撞 discriminator,反推源文件。discriminator 就是 `MD5(模块名 + 源文件名)`。 + +用户要求这两件逻辑下沉到本库,RuntimeViewer 只管展示。0062 之后,RuntimeViewer 的第一件有两处错,都出在整树搜索上: + +- 它把占位名 `(Visitor in $1a2b3c)` 里的 `$` 地址当成了 discriminator。 +- 局部类型的编译器全名带着所在函数的签名,参数、返回值里的 private 类型也会被收进来。 + +本提案在本库提供三样东西: + +1. 名字经过的私有声明。 +2. 局部类型给读者看的名字。 +3. 按镜像反推源文件。 + +## 方案 + +### 名字经过的私有声明 + +- 接口:`Node.privateDeclarations` 和 `NodeReference.privateDeclarations`,公开,放在 `SwiftInspection`,挨着 `LocalTypeNaming`。返回 `[PrivateDeclaration]`,每项有 `name` 和 `discriminator`,按阅读顺序排列并去重。 +- 语义:显示名里读得到的私有声明。RuntimeViewer 打印显示名时不打印 discriminator,discriminator 就靠这份列表保留下来。`Private` 标签和源文件反推共用这一份,不拆成两个接口。 +- 取法:整棵树前序搜索 `privateDeclName`,只有两处不进: + - 函数、闭包这类上下文节点的签名部分,即参数标签、参数类型和返回类型的子节点。局部类型给读者看的名字(下一节)不打印它们。 + - 按位置命名的占位名(`localTypeNaming == .positionBased`)里 `$` 开头的那一段,它不是 discriminator。 +- 结果: + - 不带函数上下文的名字,结果和今天 RuntimeViewer 的整树搜索相同,特化类型的泛型实参、扩展的约束照旧算。 + - 局部类型所在的函数本身是 private 时,函数的 discriminator 算进去,`name` 是函数名,如 `readEntryList`。 +- 不改成「沿上下文链每层取第一个子节点」:`.extension` 的子节点是 `[module, 被扩展的类型, 泛型签名?]`,`.anonymousContext` 是 `[name, parent, types]`(swift-demangling `Demangler.swift` 的 `demangleExtensionContext` 与 `Z` 分支)。两者的父级都不在第一个子节点,只取第一个会从扩展直接跳到模块,漏掉被扩展的类型。 + +### 局部类型给读者看的名字 + +- 接口:`DefinitionName.localTypeDisplayName`(暂名)。 +- 对局部类型和嵌在局部类型里的类型返回: + - 编译器命名的:不带模块名和参数类型,保留 `#1` 序号,如 `Visitor #1 in TableDataSource.performDrop(to:)`。和 interface 里局部类型声明前那行注释是同一种写法,两处改用同一个实现。 + - 这套写法今天在 `SwiftPrinting` 的 `SwiftDeclarationPrinter+Headers.swift` 里:`localTypeDeclarationComment` 是 package 级,它用的 `DemangleOptions.localTypeDeclarationComment` 是同一文件里 fileprivate 的。 + - 命名挪到 `SwiftDeclaration` 的 `DefinitionName`,打印器往下调它,依赖方向不变。 + - 按位置命名时注释里那句说明是注释的事,留在打印器里。 + - 按位置命名的:`TableDataSource.(Visitor in $1a2b3c)`。同一类型下的几个无名局部类型只靠这个 `$` 地址区分,所以保留它。 + - 两种写法都不打印真正的 private discriminator。 +- 其余类型返回 `nil`。 + +### 按镜像反推源文件 + +- **位置**:新开一个 target(暂名 `SwiftPrivateDiscriminators`,放在 `Sources/Declaration/` 下,公开 product)。代码从 RuntimeViewer 的 `RuntimePrivateDiscriminatorSourceFiles` 搬过来。 +- **算法不变**: + - 候选按代价从低到高分五步: + 1. 已知文件名。 + 2. 镜像名字里的标识符和其中的驼峰片段。 + 3. 同一 discriminator 下的名字两两拼成 `类型+分类`。 + 4. 第 2 步的候选接常见结尾词或复数 `s`。 + 5. 镜像里任一类型名接第 3 步的分类词。 + - 要的 discriminator 全部找到就停。 + - 128 位摘要对上才算数,所以结果只会还原不出,不会还原错。 + - 合成文件的 discriminator 是 `MD5(所属文件的 discriminator + "SYNTHESIZED FILE")`,顺带一起解出。 +- **两层接口**: + - **纯函数**:输入要还原的 discriminator、模块名候选、名字(每个名字带上它经过的 discriminator)和已知文件名。RuntimeViewer 现有的测试原样搬到这一层。 + - **镜像一层**:用一个已经 `prepare()` 过的 `SwiftDeclarationIndexer` 来建。 + - 名字候选:索引器里 Swift 类型、协议、扩展的名字,加上镜像里 ObjC 类与协议的名字。 + - 和 RuntimeViewer 原来用的侧栏对象表不是同一批。这里多了侧栏并进类型那一行的扩展,即被扩展的类型或协议就在本镜像里的那些,它们的名字多半和类型名重复。 + - 这里也少了侧栏列出的 C struct / union 名、ObjC 分类名,以及 Swift 类在 ObjC 运行时里的 `_Tt…` 名;`_Tt…` 名对应的 Swift 名字已经在里面。 + - RuntimeViewer 提案里的还原率是 macOS 26.7 上用侧栏那批候选量的,本 index 没有重新量。 + - 模块名候选:镜像文件名(`SwiftUICore`,不是 ABI 名 `SwiftUI`),加上带私有声明的名字里的模块名。 + - 候选在第一次请求时建好。每个 discriminator 的结果都记下来,还原不出也记,同一个对象再问就不再算。 + - 线程安全: + - 状态在一把锁下,名字却在锁外读。读名字要打印镜像里的每个名字,不能持锁 demangle。 + - 请求可能来自 512 KB 栈的协作线程,所以整批名字放在大栈上读。 + - 搜索在锁内,同一镜像的两次请求只搜一次。 + - 名字读完就放掉读名字的闭包,连同它握着的索引器。 + - 调用方按镜像持有它,镜像卸载时一起释放。 +- **已知文件名清单**:2007 个文件名,是生成出来的 Swift 源文件。它和生成脚本 `GenerateKnownSwiftSourceFileNames.sh` 一起搬过来,照旧不手改。 +- **MD5**:用 CryptoKit 的 `Insecure.MD5`。本库只支持 Apple 平台,最低系统版本与 CryptoKit 的要求一致。 + +### 没有询问就采用的假设 + +- 这次不给 `swift-section` 加子命令,要的话以后另提。 +- 镜像一层的候选不扩大到符号表里的全部标识符。RuntimeViewer 量过,这样只多还原 3 个百分点,候选却多一个数量级,还原不出的那些会更慢。那次是在 macOS 26.7 上量的,用的是侧栏那批候选和最初的规则。 +- 反推算法不改,还原率不提高。 + +### 测试 + +- **私有声明**:用 0062 的 `LocalTypeFixture`,`MachOFile` 与进程内两条路径都跑。覆盖这些形状: + - private 类型; + - 嵌在 private 类型里的类型; + - private 函数里的局部类型,算上函数的 discriminator; + - 非 private 函数里的局部类型,什么都不算; + - 按位置命名的局部类型,`$` 那一段不算; + - 函数签名里出现 private 类型,不算; + - 特化类型的泛型实参里有 private 类型,算; + - 嵌在受约束扩展里的类型,被扩展类型的 private 名字算; + - 不带函数上下文的名字,结果与整树搜索逐个相同(`PrivateDeclarationsWholeTreeTests`): + - 名字取自 fixture 的两条读取路径和 SymbolTestsCore 的全部定义名,再加几条编译样本的名字。 + - 只取既不经过签名、也不是按位置命名的那些。 + - 对照的是一份另外写的整树前序搜索。 +- **显示名**:编译器命名的、按位置命名的、嵌在局部类型里的类型,以及非局部类型(应返回 `nil`)。 +- **反推**: + - 纯函数一层:RuntimeViewer 的 `RuntimePrivateDiscriminatorSourceFilesTests` 搬过来,期望值照旧是在代码之外用 `md5 -s` 算的。 + - 镜像一层(`PrivateDiscriminatorSourceFileIndexTests`): + - fixture 的 `Fixture.swift`,两条读取路径; + - 名字只读一次,还原不出的也不再搜; + - 名字在大栈上读; + - 两个并发的首次请求都读名字,只搜一次; + - 名字读完,index 放掉索引器。 + - 系统镜像(`PrivateDiscriminatorSourceFileSystemImageTests`,不进 CI): + - Foundation:`__JSONEncoder` → `JSONEncoder.swift`。 + - SwiftUICore:`EnabledKey` → SwiftUICore 的 `Enabled.swift`,钉住「模块名取镜像文件名,不是 ABI 名」。 + - 这两个 discriminator 是 macOS 27.2 上取的。 + +### 文档 + +同一批更新: + +- 新 target 的 module 文档; +- AGENTS.md 的模块列表; +- `Documentations/README.md` 的索引; +- 演进账本; +- 术语表:「私有声明」要不要登记,落地时判断。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-11 | Created as Draft:「你这边把私有鉴别器的逻辑下沉到MachOSwiftSection,RV这边只负责展示的逻辑」 | 用户的原始描述。RuntimeViewer 那份提案原本就定了以后下沉到本库,拆法与接法当时未定 | +| 2026-10-11 | 反推由 RuntimeViewer 在引擎进程里调用,新增一条引擎命令;候选由本库从镜像取,结果按镜像缓存 | 用户选择。推荐的是在 App 进程里拿侧栏对象表现算,不加引擎命令,未采纳 | +| 2026-10-11 | 局部类型给读者看的名字不带模块名和参数类型 | 用户选择:侧栏里同名的几个局部类型要能分开,过滤时也不该被函数签名里的类型命中 | +| 2026-10-11 | 局部类型所在函数是 private 时,函数的 discriminator 算进私有声明 | 用户选择,与「名字经过的私有声明都算」一致 | +| 2026-10-11 | 实现分支基于本地 `next`(100da85c,未推送) | 要用 0062 的 `LocalTypeNaming`。`next` 推不推由用户定 | +| 2026-10-11 | 私有声明的取法由「沿上下文链取」改为「整树搜索,跳过函数与闭包的签名和占位名的 `$` 段」;标签与反推共用一份 | MSS 会话指出两点。一是 `.extension`、`.anonymousContext` 的父级在第二个子节点,已在 swift-demangling 源码核实,只取第一个子节点会漏掉被扩展的类型。二是 RuntimeViewer 现有语义有意收进泛型实参。按「显示名读得到的」来定,局部类型的显示名本来就不印签名,两种用途在局部类型上一致,不必拆成两个接口 | +| 2026-10-11 | Accepted,随即转 In Progress | 用户批准:「开工」 | +| 2026-10-11 | private 构造器与下标的 `PrivateDeclaration.name` 取 `init` / `subscript` | 实现时发现:编译样本里 private 构造器的私有名只有 discriminator,印成 `Holder.(in _C017…).init(argument:)`,下标同理;不补名字的话弹窗里只剩一个空名 | +| 2026-10-11 | 用索引器建 index 的两个初始化方法标 `@_spi(Support)` | `SwiftDeclarationIndexer` 本身是 `@_spi(Support)`,公开接口不能出现它;直接给名字闭包的初始化方法保持公开 | +| 2026-10-11 | ObjC 名字跳过 `_Tt` 开头的 | 那是 Swift 类型在 ObjC 运行时的 mangled 名,Swift 名字已经覆盖,留着只多出无用的候选 | +| 2026-10-11 | index 的状态用一把 `NSLock`,一次请求从头持有到尾,不用 `@Mutex` 属性 | `@Mutex` 只保护单次读写;整个请求加锁,同一镜像的两次并发请求才只搜一次。最低部署版本 10.15,用不上 `Synchronization.Mutex` | +| 2026-10-11 | 测试的名字取真实 mangling:macOS 27.2 SwiftUI 的类型描述符符号,加一个现编的小样本(`swiftc -c -Onone -module-name Shapes`),discriminator 写在测试文档里 | 签名里带 private 类型、private 构造器与下标、受约束扩展这几种形状 SwiftUI 里找不到现成的;手写 mangling 只用于两参数字典,并先用 `swift-demangle` 核对 | +| 2026-10-11 | 先红后绿:把取法临时改回整树读取(读签名、收 `$`),`PrivateDeclarationsTests` 里针对这两点的 4 个用例全红,其余 8 个照绿;改回后全绿 | 证明测试抓得住 RuntimeViewer 原来那两处错 | +| 2026-10-11 | MSS 会话审查了本分支,列出六条,用户要求全部修、不留「不修」项;以下各行是这六条的落实 | — | +| 2026-10-11 | 名字改在锁外读,取代上面「一次请求从头持有到尾」那一行。新的流程:
1. 锁内只看有没有没答过的 discriminator、候选建没建,并取出读名字的闭包。
2. 锁外把整批名字放进 `StackSafeExecutor.withLargeStack` 里读。
3. 再上锁,候选还没建才装进去,后到的丢掉自己读的那份。
搜索仍在锁内,两次请求仍只搜一次 | 审查指出两点。一是持锁读名字违反 AGENTS.md 的「Do not hold a lock across a demangle」,先例是 NodeStoreMigrationOpenIssues #9。二是 RuntimeViewer 从 `nonisolated async` 方法里调用,跑在 512 KB 栈的协作线程上,每打印一个名字都要切一次线程。先红后绿:读名字时的栈从 536,576 字节变为 8 MB;两个并发的首次请求,原来只有一个读到名字,现在两个都读到 | +| 2026-10-11 | 候选建好后放掉读名字的闭包 | 审查指出:闭包握着索引器,而镜像的缓存要等最后一个索引器释放才回收(`SwiftDeclarationIndexer` 的 deinit),index 活多久,缓存就留多久。先红后绿:只剩 index 握着索引器时,请求之后索引器原来还在,现在会释放 | +| 2026-10-11 | 补齐「测试」一节答应过的测试:
- 不带函数上下文的名字逐个对照另写的整树搜索(`PrivateDeclarationsWholeTreeTests`)。
- index 加一个 internal 的搜索次数,测还原不出的 discriminator 第二次问不再搜。
- 系统镜像补上 SwiftUICore,与 Foundation 一起挪进单独的 `PrivateDiscriminatorSourceFileSystemImageTests`。
另外 `PrivateDeclarationsTests` 补上 `ExclusiveImageAccess` 声明;除系统镜像那个套件外,新套件都加进 CI 的 `--filter` | 审查指出「测试」一节有三处没兑现,还有一个套件漏了 fixture 互斥声明。临时改坏三处验证测试会红:
- 删掉记录「还原不出」的几行:两个用例变红。
- 扩展只读第一个子节点:对照套件里受约束扩展的样本名字变红。fixture 的定义名里没有落在扩展节点下的 private 名字,那部分不红。
- struct 自己的 private 名字不读:SymbolTestsCore 有 6 个名字变红。
系统镜像那个套件不进 CI:它的 discriminator 是 macOS 27.2 上取的,CI runner 跑的是别的系统版本 | +| 2026-10-11 | 术语统一写 private discriminator / discriminator,标题一并改;用户原话照录 | 仓库其余文档和术语表写「鉴别符」,0062 写英文。按文档风格要求,术语保留英文,不用中文自造词 | +| 2026-10-11 | 更正「候选与 RuntimeViewer 侧栏对象表是同一批,还原率不变」 | 两边不是同一批:本库多收了侧栏并进类型的扩展名字,少了侧栏列出的 C struct / union 名、ObjC 分类名和 `_Tt…` 名。还原率是 RuntimeViewer 在 macOS 26.7 上用旧候选量的,本 index 没有重新量。搜索本身没有上限,候选多出来只会让还原出的变多,少掉的那几类能不能还原出东西没有量过 | +| 2026-10-11 | 更正:`next` 已推到 origin(100da85c) | 「实现分支基于本地 `next`(100da85c,未推送)」那一行写的时候是这样,之后已经推送 | diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index 207fcb661..b15703217 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -17,6 +17,7 @@ | SwiftSectionKit | [SwiftSectionKit.md](SwiftSectionKit.md) | ✅ 已写(调用方指南:[SwiftSectionKit.md](../../SwiftSectionKit.md)) | | swift-section (CLI) | [SwiftSectionKit.md](SwiftSectionKit.md) | ✅ 已写(与 SwiftSectionKit 同篇:包装层只剩 flag 映射、错误翻译、流路由与退出码) | | SwiftIndexing | — | 待写 | +| SwiftPrivateDiscriminators | [SwiftPrivateDiscriminators.md](SwiftPrivateDiscriminators.md) | ✅ 已写(提案 [draft-private-declarations](../../Evolutions/draft-private-declarations.md)) | | SwiftPrinting | — | 待写 | | SwiftSpecialization | — | 待写 | | SwiftThunkAnalysis | [SwiftThunkAnalysis.md](SwiftThunkAnalysis.md) | ✅ 已写(入门:[AccessorThunkResolutionExplained.md](../AccessorThunkResolutionExplained.md)) | diff --git a/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md b/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md new file mode 100644 index 000000000..63b7aa0f8 --- /dev/null +++ b/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md @@ -0,0 +1,59 @@ +# SwiftPrivateDiscriminators 模块 + +> 模块参考文档(module reference),随代码维护。读者:维护者。 +> 来历与取舍见提案 [draft-private-declarations](../../Evolutions/draft-private-declarations.md);本文负责全貌与分工。 + +## 模块定位 + +private discriminator 是编译器给 private / fileprivate 声明的名字加的一段 `_` 加 32 位大写十六进制,值是 `MD5(模块名 + 源文件名)`(Swift `lib/AST/Module.cpp` 的 `SourceFile::getPrivateDiscriminator`)。它解不回去,但可以猜:拿候选文件名算一遍 MD5,128 位摘要对上就是确认。本模块做的就是这件事:给出一个镜像里的 discriminator,反推它们来自哪个源文件。 + +它只管反推。名字里读得到哪些私有声明,由 `SwiftInspection` 的 `DemanglingNode.privateDeclarations` 回答,那是所有名字都要用的轻量接口;本模块带着 2007 个已知文件名的清单,只有要反推的宿主才依赖它。 + +宿主目前是 RuntimeViewer:侧栏的 `Private` 标签弹窗里显示 discriminator 与反推出的文件名,引擎进程按镜像持有一个 `PrivateDiscriminatorSourceFileIndex`。 + +## 文件 → 子系统对照 + +| 子系统 | 文件 | +|---|---| +| 1. 搜索本身(纯函数) | `PrivateDiscriminatorSourceFiles.swift`:五步候选、`Search`(摘要比对、合成文件、一段字节两种读法)、`Candidates`(从名字里读出的模块名与标识符)、`Digest128` | +| 2. 已知文件名 | `PrivateDiscriminatorSourceFiles+KnownFileNames.swift`,由 `Scripts/GenerateKnownSwiftSourceFileNames.sh` 生成,不手改 | +| 3. 按镜像取候选、记答案 | `PrivateDiscriminatorSourceFileIndex.swift` | + +## 关键契约 + +- **结果只会「还原不出」,不会「还原错」。** 候选只决定找到多少;对上的摘要就是确认。所以按文本切词、拼文件名这些做法再粗糙,也只影响还原率。 +- **候选由五步组成,按代价从低到高,要的 discriminator 全部找到就停:** 已知文件名;名字里的标识符与驼峰片段;同一 discriminator 下名字的词两两拼 `类型+分类`;片段接常见结尾词或复数;镜像里任一类型名接分类。还原不出的 discriminator 要把五步全部算完,所以最慢:Debug 构建里 SwiftUICore 一个要三四秒。 +- **模块名候选:镜像文件名在前。** 哈希用的是框架自己的名字(`SwiftUICore`),不是类型打印出来的 ABI 名(`SwiftUI`);后者从带私有声明的名字前缀里补上。局部类型的名字以类型开头(`Visitor #1 in SwiftUI.…`),第一个点之前不是标识符,不会被当成模块名。 +- **一个模块名是另一个的前缀时,同一段哈希输入有两种读法**(`SwiftUICoreGlue.swift` 既是 SwiftUICore 的 `Glue.swift`,也是 SwiftUI 的 `CoreGlue.swift`):一律按模块名的先后取前一种,结果不随候选的尝试顺序变。 +- **镜像一层的候选**:索引器里 Swift 类型、协议、扩展的名字(`.interfaceTypeBuilderOnly`,不带 discriminator),加上 ObjC 类与协议名。以 `_Tt` 开头的 ObjC 名是 Swift 类型的运行时 mangled 名,Swift 名字已经覆盖,跳过。 + - 和 RuntimeViewer 原来用的侧栏对象表不是同一批。这里多了侧栏并进类型那一行的扩展(被扩展的类型或协议就在本镜像里),这些名字多半和类型名重复;少了侧栏列出的 C struct / union 名、ObjC 分类名和 `_Tt…` 名。 + - RuntimeViewer 提案里的还原率是 macOS 26.7 上用侧栏那批候选量的,本 index 没有重新量。搜索本身没有上限,所以候选多出来只会让还原出的变多。 + - 不扩大到符号表的全部标识符:RuntimeViewer 当时量过,只多三个百分点,候选却多一个数量级。 +- **名字在第一次请求时才读,每个答案都记住**,还原不出也记。宿主按镜像持有,随镜像释放。 +- **名字在锁外读,搜索在锁内。** `PrivateDiscriminatorSourceFileIndex` 的状态全在一把 `NSLock` 下。 + - 读名字要打印镜像里的每个名字,而 AGENTS.md 规定不能持锁 demangle。 + - 请求可能来自 512 KB 栈的协作线程,所以整批名字放进 `StackSafeExecutor.withLargeStack` 里读,一批只切一次线程;栈够大的线程就地读。 + - 两个并发的首次请求各读一遍,后到的丢掉自己那份。搜索仍在锁内,所以同一镜像的两次请求只搜一次。 +- **名字读完就放掉读名字的闭包。** 按索引器建的 index 不再握着索引器:镜像缓存要等最后一个索引器释放才回收(`SharedCacheRegistry`),index 却随镜像活着。 +- **`SwiftDeclarationIndexer` 是 `@_spi(Support)`**,所以按索引器建 index 的两个初始化方法也是 `@_spi(Support)`;不用索引器的初始化方法(直接给名字的闭包)是公开的。 + +## 测试锚点 + +- `Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFilesTests.swift`:每条规则各一个用例,都不带已知文件名,期望值是在代码之外用 `md5 -s` 算的(从 RuntimeViewer 搬来)。 +- `Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift`,与运行的系统无关,在 CI 里跑: + - 局部类型 fixture 的 `Fixture.swift`(`MachOFile` 与进程内两条路径); + - 名字只读一次,还原不出的不再搜(`searchCount`); + - 名字在大栈上读; + - 两个并发的首次请求都读名字、只搜一次; + - 名字读完放掉索引器。 +- `Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift`,读运行中系统的 dyld shared cache,不进 CI,因为它的 discriminator 是 macOS 27.2 上取的: + - Foundation 的 `__JSONEncoder` → `JSONEncoder.swift`; + - SwiftUICore 的 `EnabledKey` → SwiftUICore 的 `Enabled.swift`,钉住模块名取镜像文件名。 +- 名字经过的私有声明: + - `Tests/SwiftInspectionTests/PrivateDeclarationsTests.swift`:逐个形状。 + - `Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift`:不经过签名、也不是按位置命名的定义名,与另写的整树搜索逐个相同。 + +## 相关文档 + +- 提案:[draft-private-declarations](../../Evolutions/draft-private-declarations.md) +- 局部类型与占位名:[0062-local-type-context-names](../../Evolutions/0062-local-type-context-names.md) diff --git a/Documentations/README.md b/Documentations/README.md index 190c58f46..8e5a869d4 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -76,6 +76,7 @@ selects names using each access's offset and width. | [Modules/SwiftDeclaration.md](Internal/Modules/SwiftDeclaration.md) | SwiftDeclaration 模块参考:共享声明模型的定位与七个子系统,四条关键契约(持描述符引用而非胖 wrapper 的 materialization 纪律、名字按结构相等且 `kind` 不参与、四态 `ExportStatus` 的两种「无结论」作用域、库代码不写进程流与事件兜底)。 | | [Modules/MachOSymbols.md](Internal/Modules/MachOSymbols.md) | MachOSymbols 模块参考:符号索引层的定位与四个子系统(索引本体与非单射的名字键、查询出口与 detach 规则、跨 store 对账为什么必须用 `StructuralNodeReferenceKey`、大栈执行器),以及改结构布局要先 clean 等契约。 | | [Modules/SwiftLayout.md](Internal/Modules/SwiftLayout.md) | SwiftLayout 模块参考:静态布局引擎的能力边界与八个子系统(入口与递归求解、基础累加、已知布局表与 builtin 交叉校验、三个桥接、无实参也能算的那部分、ObjC 互操作、镜像查找面),四条关键契约(降级是产品的一部分、实参永远赢过推断、官方离线实现不是标准答案、跨模块偏移按具体部署算)。 | +| [Modules/SwiftPrivateDiscriminators.md](Internal/Modules/SwiftPrivateDiscriminators.md) | SwiftPrivateDiscriminators 模块参考:从 private discriminator 反推源文件的三个子系统(纯函数的五步候选搜索、生成的已知文件名清单、按镜像取候选并记住答案的 index),关键契约(只会还原不出、不会还原错;模块名候选的先后;候选与 RuntimeViewer 侧栏对象表的差别;名字首次请求才读,在锁外、在大栈上读,读完放掉索引器)与测试锚点。 | | [Modules/SwiftThunkAnalysis.md](Internal/Modules/SwiftThunkAnalysis.md) | SwiftThunkAnalysis 模块参考:kind-9 accessor thunk 符号求值的模块视角索引——五个子系统、按输入形态列的当前能力表(含 macOS 27 cache 打不开这个已知缺口)、三条故意的拒绝、dyld cache 偏移口径与 `ExportedSymbol.offset` 两个静默出错点、测试如何 scope 一个读不出来的 resolver。 | | [ProjectEvolutionLog.md](Internal/ProjectEvolutionLog.md) | 编年演进账本:逐工作弧(Foundation 解析 → demangler → 模块化 → SwiftLayout → SwiftDiffing/ABI evolution …)的时间段/动机/关键决策/落地文档/版本对应,含每批次必须追加的维护约定。 | | [ReviewAdjudications.md](Internal/ReviewAdjudications.md) | Review 已裁决清单:判定为「不修 / 误报」的发现及结论、理由、复审条件;每轮 code review 先对照此表,已裁决且理由仍成立的直接跳过。 | @@ -166,6 +167,7 @@ selects names using each access's offset and width. | [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | +| [Evolutions/draft-private-declarations.md](Evolutions/draft-private-declarations.md) | **提案 draft(In Progress)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | | [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 的数量与内存实测。 | From eb5b9b317db81c2754bc0c437369da6e84608904 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 23:02:54 +0800 Subject: [PATCH 35/49] docs: land proposal 0063 (private-declarations) as Implemented Numbers the proposal against the shared branches (origin/next at 0062, origin/main at 0061), marks it Implemented with the closing judgements and the user's choice not to re-measure the recovery rate, updates every link to the draft, registers "private declaration" in the glossary, and records the batch as section 88 of the evolution ledger. --- ...ations.md => 0063-private-declarations.md} | 10 +++++--- Documentations/Evolutions/README.md | 2 +- Documentations/Glossary.md | 7 ++++++ Documentations/Internal/Modules/README.md | 2 +- .../Modules/SwiftPrivateDiscriminators.md | 4 ++-- .../Internal/ProjectEvolutionLog.md | 23 +++++++++++++++++++ Documentations/README.md | 2 +- 7 files changed, 42 insertions(+), 8 deletions(-) rename Documentations/Evolutions/{draft-private-declarations.md => 0063-private-declarations.md} (90%) diff --git a/Documentations/Evolutions/draft-private-declarations.md b/Documentations/Evolutions/0063-private-declarations.md similarity index 90% rename from Documentations/Evolutions/draft-private-declarations.md rename to Documentations/Evolutions/0063-private-declarations.md index 05ceba743..c71910a12 100644 --- a/Documentations/Evolutions/draft-private-declarations.md +++ b/Documentations/Evolutions/0063-private-declarations.md @@ -1,10 +1,11 @@ -# Draft - 私有声明:从名字取 discriminator,按镜像反推源文件 +# 0063 - 私有声明:从名字取 discriminator,按镜像反推源文件 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-10-11 - **最后更新**: 2026-10-11 - **关联提案**: [0062-local-type-context-names](0062-local-type-context-names.md)(占位名与 `LocalTypeNaming`);展示一侧是 RuntimeViewer 的 [draft-private-discriminator-tag](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/feature/private-discriminator-tag/Documentations/Evolutions/draft-private-discriminator-tag.md) -- **实现分支**: `feature/private-declarations`(worktree `.worktrees/MachOSwiftSection-PrivateDeclarations`),基于本地 `next` 100da85c,要用 0062 的 `LocalTypeNaming` +- **实现分支**: `feature/private-declarations`(worktree `.worktrees/MachOSwiftSection-PrivateDeclarations`),基于本地 `next` 100da85c,要用 0062 的 `LocalTypeNaming`;按本仓库惯例在本地合并进 `next` +- **配套文档**: 模块全貌、三个子系统、候选与 RuntimeViewer 侧栏对象表的差别见 [Modules/SwiftPrivateDiscriminators.md](../Internal/Modules/SwiftPrivateDiscriminators.md);术语见 [Glossary.md](../Glossary.md)「private declaration」 ## 摘要 @@ -150,3 +151,6 @@ RuntimeViewer 的侧栏给私有类型挂一个 `Private` 标签,点开列出 | 2026-10-11 | 术语统一写 private discriminator / discriminator,标题一并改;用户原话照录 | 仓库其余文档和术语表写「鉴别符」,0062 写英文。按文档风格要求,术语保留英文,不用中文自造词 | | 2026-10-11 | 更正「候选与 RuntimeViewer 侧栏对象表是同一批,还原率不变」 | 两边不是同一批:本库多收了侧栏并进类型的扩展名字,少了侧栏列出的 C struct / union 名、ObjC 分类名和 `_Tt…` 名。还原率是 RuntimeViewer 在 macOS 26.7 上用旧候选量的,本 index 没有重新量。搜索本身没有上限,候选多出来只会让还原出的变多,少掉的那几类能不能还原出东西没有量过 | | 2026-10-11 | 更正:`next` 已推到 origin(100da85c) | 「实现分支基于本地 `next`(100da85c,未推送)」那一行写的时候是这样,之后已经推送 | +| 2026-10-11 | 还原率不重新量 | 用户选择。文档里已注明那组还原率是 RuntimeViewer 在 macOS 26.7 上用旧候选量的 | +| 2026-10-11 | In Progress → Implemented,编号 0063 | 用户确认合入。MSS 会话复审了六条修复,在本 worktree 跑相关的 13 组 129 个测试,原始退出码 0。按共享分支编号(origin/next 最大 0062,origin/main 最大 0061);开工后 `next` 没有新提交,不用 rebase;本地合并进 `next`;演进账本第 88 节 | +| 2026-10-11 | 收尾判断:不另写实现说明;登记术语「private declaration」 | 模块全貌、三个子系统和候选的来源写在 [Modules/SwiftPrivateDiscriminators.md](../Internal/Modules/SwiftPrivateDiscriminators.md),已登记在头部;取法与线程安全的决策都在本提案和演进账本里,没有再值得单列的。「private declaration」(私有声明)在本库有特定含义:显示名读得到的私有声明,不含函数签名里的,也不含按位置起名的 `$` 段,已登记术语表。`PrivateDeclaration`、`localTypeDisplayName` 是标识符,不登记;private discriminator 是编译器的说法,不是本项目造的,也不登记 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index e2e002527..2130e6bfb 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -76,4 +76,4 @@ | [0061](0061-dyld-shared-cache-path-versions.md) | 测试用的 dyld shared cache 路径按版本取 | Implemented | | draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | -| draft | [私有声明:从名字取 discriminator,按镜像反推源文件](draft-private-declarations.md) | In Progress | +| [0063](0063-private-declarations.md) | 私有声明:从名字取 discriminator,按镜像反推源文件 | Implemented | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index c6d8c5e54..c566f3e03 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -283,6 +283,13 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`(`positionNameOfUnnamedLocalType`)、`Sources/Analysis/SwiftInspection/LocalTypeNaming.swift`、`Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift` - **延伸阅读**:[提案 0062](Evolutions/0062-local-type-context-names.md) +### private declaration(私有声明,`privateDeclarations`) + +一个名字的显示名里读得到的 `private` / `fileprivate` 声明,每个连同它的 private discriminator:`Node.privateDeclarations` / `NodeReference.privateDeclarations` 返回的 `[PrivateDeclaration]`,按阅读顺序排列、去重。取法是整树搜索 `privateDeclName`,有两处不算:函数、闭包这类上下文的签名部分(参数和返回值里的 private 类型),以及 position-based name 里 `$` 开头的那一段(那是地址,不是 discriminator)。特化类型的泛型实参、受约束扩展里被扩展的类型都算;局部类型所在的函数是 private 时,函数也算,`name` 是函数名。RuntimeViewer 的 `Private` 标签和源文件反推(`SwiftPrivateDiscriminators`)读的都是这一份。 + +- **主要出现在**:`Sources/Analysis/SwiftInspection/PrivateDeclarations.swift`、`Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFileIndex.swift` +- **延伸阅读**:[提案 0063](Evolutions/0063-private-declarations.md)、[Modules/SwiftPrivateDiscriminators.md](Internal/Modules/SwiftPrivateDiscriminators.md) + ### renamed class(改名类,`@objc(Name)` / `@_objcRuntimeName(Name)`) 源码给 ObjC 运行时另起了名字的 Swift 类:类对象的 `class_ro_t` 名是源码写的名字(`NSScrollPocket`),而不是 `_TtC6AppKit14NSScrollPocket` 这样的 mangling。二进制里只剩类元数据 flag 字里的 `HasCustomObjCName` 与名字本身,`SwiftClassObjectIndex` 顺着类元数据自带的描述符指针把它们配到 Swift 类上(父类在另一个 resilience domain、不进 classlist 的类读 metadata pattern)。本仓库凡是「demangle 运行时名找 Swift 类」的地方都要为它回退,否则一律配不上——成员恢复与布局引擎以前就是这样漏掉它们的。interface 与 dump 打印 `@objc(Name)`,原生 Swift 对象模型的类打印 `@_objcRuntimeName(Name)`。 diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index b15703217..b2d261e4a 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -17,7 +17,7 @@ | SwiftSectionKit | [SwiftSectionKit.md](SwiftSectionKit.md) | ✅ 已写(调用方指南:[SwiftSectionKit.md](../../SwiftSectionKit.md)) | | swift-section (CLI) | [SwiftSectionKit.md](SwiftSectionKit.md) | ✅ 已写(与 SwiftSectionKit 同篇:包装层只剩 flag 映射、错误翻译、流路由与退出码) | | SwiftIndexing | — | 待写 | -| SwiftPrivateDiscriminators | [SwiftPrivateDiscriminators.md](SwiftPrivateDiscriminators.md) | ✅ 已写(提案 [draft-private-declarations](../../Evolutions/draft-private-declarations.md)) | +| SwiftPrivateDiscriminators | [SwiftPrivateDiscriminators.md](SwiftPrivateDiscriminators.md) | ✅ 已写(提案 [0063-private-declarations](../../Evolutions/0063-private-declarations.md)) | | SwiftPrinting | — | 待写 | | SwiftSpecialization | — | 待写 | | SwiftThunkAnalysis | [SwiftThunkAnalysis.md](SwiftThunkAnalysis.md) | ✅ 已写(入门:[AccessorThunkResolutionExplained.md](../AccessorThunkResolutionExplained.md)) | diff --git a/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md b/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md index 63b7aa0f8..3fc37c8ee 100644 --- a/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md +++ b/Documentations/Internal/Modules/SwiftPrivateDiscriminators.md @@ -1,7 +1,7 @@ # SwiftPrivateDiscriminators 模块 > 模块参考文档(module reference),随代码维护。读者:维护者。 -> 来历与取舍见提案 [draft-private-declarations](../../Evolutions/draft-private-declarations.md);本文负责全貌与分工。 +> 来历与取舍见提案 [0063-private-declarations](../../Evolutions/0063-private-declarations.md);本文负责全貌与分工。 ## 模块定位 @@ -55,5 +55,5 @@ private discriminator 是编译器给 private / fileprivate 声明的名字加 ## 相关文档 -- 提案:[draft-private-declarations](../../Evolutions/draft-private-declarations.md) +- 提案:[0063-private-declarations](../../Evolutions/0063-private-declarations.md) - 局部类型与占位名:[0062-local-type-context-names](../../Evolutions/0062-local-type-context-names.md) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index ec2f7898f..1a2876baa 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2395,6 +2395,29 @@ - **关联文档**:[0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md)、[Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md)、[SymbolicManglingSymbols.md](SymbolicManglingSymbols.md)「边界」、[Glossary.md](../Glossary.md)「position-based name」、`swift-section` agent skill 第 9 节。 - **对应版本**:下一个版本(未发版)。 +## 88. 私有声明:从名字取 discriminator,按镜像反推源文件 + +- **时间段**:2026-10-11。 +- **动机**:RuntimeViewer 的侧栏给私有类型挂一个 `Private` 标签,点开列出 private discriminator 和它来自哪个源文件。这两件计算原来都在 RuntimeViewer 里做,用户要求下沉到本库,RuntimeViewer 只管展示。0062 之后,RuntimeViewer 原来的整树搜索多了两处错:把 position-based name 里 `$` 开头的地址当成 discriminator,把局部类型所在函数签名里的 private 类型也收了进来。实现由 RuntimeViewer 会话在本仓库的 `feature/private-declarations` 分支上完成,本会话审查。 +- **关键决策**: + - 私有声明的取法:整树前序搜索 `privateDeclName`,只跳过函数、闭包这类上下文的签名部分和 position-based name 的 `$` 段;`Private` 标签与源文件反推共用这一份。原定的「沿上下文链每层取第一个子节点」没有采用:`.extension` 和 `.anonymousContext` 的父级在第二个子节点,只取第一个会漏掉被扩展的类型;RuntimeViewer 现有的语义也有意收进泛型实参里的 private 类型。 + - 局部类型所在函数是 private 时,函数的 discriminator 也算(用户选择)。private 构造器、下标的私有名字里只有 discriminator,`name` 取 `init` / `subscript`。 + - 局部类型给读者看的名字不带模块名和参数类型(用户选择),interface 里局部类型声明前那行注释改用同一个实现。 + - 源文件反推单开一个 target `SwiftPrivateDiscriminators`(公开 product),算法、2007 个已知文件名和生成脚本从 RuntimeViewer 原样搬来。RuntimeViewer 在引擎进程里调用,新增一条引擎命令;候选由本库从镜像取,结果按镜像记住(用户选择)。模块名候选取镜像文件名(`SwiftUICore`),不是 ABI 名(`SwiftUI`)。 + - 按镜像的 index:名字在锁外读,整批放在大栈上;搜索在锁内,同一镜像只搜一次;名字读完就放掉索引器。这几条有两条是审查后改的:原来持锁读名字,违反 AGENTS.md 的「Do not hold a lock across a demangle」,而且在 512 KB 栈的协作线程上逐个打印名字要逐个切线程;原来 index 一直握着索引器,镜像的缓存要等 index 释放才回收。 + - 还原率没有重新量(用户选择)。这里的候选与 RuntimeViewer 侧栏对象表互有多少,RuntimeViewer 提案里的数字是在 macOS 26.7 上用旧候选量的。 +- **审查**:本会话列出六条,用户要求全部修、不留「不修」项。除了上面线程安全的两条,还有:提案「测试」一节有三处没兑现(与另写的整树搜索逐个对照、还原不出的不再重搜、SwiftUICore 的模块名);文档索引写的还是旧取法;`PrivateDeclarationsTests` 漏了 `ExclusiveImageAccess`;术语混写、「候选与侧栏是同一批」说错、没记 `next` 已推送、CI 没加新套件。审查顺带在全库排查了「持锁时 demangle」,找到的五处老代码和一处疑似另行处理。 +- **公开 API 与行为变化**(写进下个版本的发版说明):新增 `PrivateDeclaration` 与 `Node.privateDeclarations` / `NodeReference.privateDeclarations`(SwiftInspection)、`DefinitionName.localTypeDisplayName`(SwiftDeclaration),以及新 product `SwiftPrivateDiscriminators`(`PrivateDiscriminatorSourceFiles`、`PrivateDiscriminatorSourceFileIndex`;用索引器建 index 的两个初始化方法是 `@_spi(Support)`,与 `SwiftDeclarationIndexer` 一致)。dump 与 interface 的输出不变。 +- **落地模块**:SwiftInspection(`PrivateDeclarations`、`LocalTypeNaming`)、SwiftDeclaration(`DefinitionName+LocalTypeDisplayName`)、SwiftPrinting(`SwiftDeclarationPrinter+Headers`)、新 target SwiftPrivateDiscriminators(`PrivateDiscriminatorSourceFiles`、`PrivateDiscriminatorSourceFiles+KnownFileNames`、`PrivateDiscriminatorSourceFileIndex`)、`Scripts/GenerateKnownSwiftSourceFileNames.sh`。 +- **验证**: + - 先红后绿:取法临时改回 RuntimeViewer 的整树读取(读签名、收 `$`),`PrivateDeclarationsTests` 里针对这两点的 4 个用例变红。审查后补的测试各自在修复前变红:读名字时的栈是 536,576 字节;两个并发的首次请求只有一个读到名字;只剩 index 握着索引器时索引器不释放;删掉记录「还原不出」的几行后,同一个 discriminator 被重复搜索;扩展只读第一个子节点时,受约束扩展的样本变红;struct 自己的 private 名字不读时,SymbolTestsCore 有 6 个名字变红。 + - 新套件 `PrivateDeclarationsTests`、`PrivateDeclarationsWholeTreeTests`、`LocalTypeDisplayNameTests`、`PrivateDiscriminatorSourceFilesTests`、`PrivateDiscriminatorSourceFileIndexTests` 加进了 CI 的过滤清单。`PrivateDiscriminatorSourceFileSystemImageTests`(Foundation 的 `JSONEncoder.swift`、SwiftUICore 的 `Enabled.swift`)不进 CI:它的 discriminator 是在 macOS 27.2 上取的。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,带 `USING_LOCAL_DEPENDENCIES=1`,RuntimeViewer 会话跑):2426 个测试、461 个套件全部通过,原始退出码 0。复审时本会话在同一 worktree 跑相关的 13 组 129 个测试,原始退出码 0,新增和改动的文件没有编译警告。 + - RuntimeViewer Core 用 SwiftPM 的 edit 模式指向本分支编译,私有声明相关的 3 个套件、14 个测试通过,其中包括经引擎命令反推出 `JSONEncoder.swift` 的那个。 + - 没跑系统框架 A/B:打印只是把局部类型注释的写法挪进 `DefinitionName`,打印选项没变,SymbolTestsCore 的 interface 快照照旧通过。 +- **关联文档**:[0063-private-declarations](../Evolutions/0063-private-declarations.md)、[Modules/SwiftPrivateDiscriminators.md](Modules/SwiftPrivateDiscriminators.md)、[Glossary.md](../Glossary.md)「private declaration」;展示一侧是 RuntimeViewer 的 `draft-private-discriminator-tag`。 +- **对应版本**:下一个版本(未发版)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/README.md b/Documentations/README.md index 8e5a869d4..8abaf62bb 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -167,7 +167,7 @@ selects names using each access's offset and width. | [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | | [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | -| [Evolutions/draft-private-declarations.md](Evolutions/draft-private-declarations.md) | **提案 draft(In Progress)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | +| [Evolutions/0063-private-declarations.md](Evolutions/0063-private-declarations.md) | **提案 0063(Implemented)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | | [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 的数量与内存实测。 | From f490d9c4b2cf2b46a53a7863e991d06b4abebd7b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 23:38:05 +0800 Subject: [PATCH 36/49] fix: keep the specializer's demangling off small stacks under its locks On a 512 KB thread every demangle and print hops to a large-stack worker and blocks on it, so a lock held across one makes every waiter wait behind the hop. RuntimeViewer reaches two such locks from an actor: - IndexerConformanceProvider.classHierarchy() built its class maps under the cache's lock, demangling each class's superclass and printing two names per class, each a hop of its own. A miss now moves to a large stack first, in one hop, and takes the lock there, so the walk runs inline and nothing hops while the lock is held. A hit never hops. Both maps still come from one walk and are stored together. - The four async TypeDefinition.specialize overloads are library entry points but never ran on the large-stack task executor. RuntimeViewer calls the deriving one from an actor, and through GenericInstantiation it takes DependentMemberProjection's per-image lock and hops per demangle under it. They now run through LargeStackTaskExecution.run like the other async entry points. Tests, both red before the fix on a 536,576-byte stack: the class-map build reports an injected unreadable class from inside the walk, and a forwarding conformance provider is asked for candidates while a nested type is derived; each records the stack it runs on. Both suites join CI's filter. --- .github/workflows/macOS.yml | 2 +- .../ConformanceProvider.swift | 51 ++++-- .../TypeDefinition+Specialization.swift | 97 ++++++----- .../ClassHierarchyBuildStackTests.swift | 101 ++++++++++++ ...pecializationEntryPointExecutorTests.swift | 156 ++++++++++++++++++ 5 files changed, 357 insertions(+), 50 deletions(-) create mode 100644 Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift create mode 100644 Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 0eb574a03..2463f8e90 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests|PrivateDeclarationsTests|PrivateDeclarationsWholeTreeTests|LocalTypeDisplayNameTests|PrivateDiscriminatorSourceFilesTests|PrivateDiscriminatorSourceFileIndexTests)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|ClassHierarchyBuildStackTests|SpecializationEntryPointExecutorTests|MultiPayloadEnumTests|SymbolicDemanglerDemanglingTests|MalformedSymbolValueTests|ContinuousIntegrationTestFilterTests|MachOImageCacheMembershipTests|SharedCacheResolveTests|SharedCacheResolveSwiftConcurrencyTests|SharedCacheKeyTests|SharedCacheRegistryTests|DependencyLoadNameTests|DependencyClosureTests|FileDependencyLocatorTests|SwiftInterfaceBuilderDependenciesTests|ManglingPrefixTests|MethodDescriptorTests|MethodOverrideDescriptorTests|MethodDefaultOverrideDescriptorTests|ProtocolRequirementTests|ResilientWitnessTests|LargeStackTaskExecutionTests|BoundedConcurrentMapTests|SwiftEvolutionInterfaceBuilderTests|EvolutionCommandValidationTests|DiffCommandValidationTests|ObjCSectionCommandTests|ObjCAPICommandParsingTests|ObjCDumpDiagnosticsTests|MachOSourceTests|InterfaceAnnotationStyleTests|TransformerRequestTests|ABIRequestTests|DumpAndInterfaceRequestTests|ObjCRequestTests|CommandRequestMappingTests|CommandLineErrorTranslationTests|StandardStreamOutputTests|CommandLineStreamWriteScanTests|ConcurrentDefinitionPrintingTests|NestedFieldOffsetMemoizationTests|NestedDefinitionRegionContractTests|ProtocolInExtensionTests|OfflineSpecializationTests|OfflineSpecializationParityTests|InstantiatedTypeNameTests|CanonicalParameterDepthTests|GenericParameterDepthNamingTests|GenericParameterDepthDumpTests|BoundInstantiationLayoutTests|ExtensionContextInstantiationLayoutTests|AccessorThunkOwnerLayoutDepthTests|OpaqueTypeArgumentDepthTests|OfflineObjectiveCBaseClassTests|TiedParameterInstantiationTests|ProtocolInExtensionDefaultWitnessTests|OfflineConditionalConformanceTests|NestedFieldOffsetOpaqueWitnessTests|ConcurrentSpecializationTests|OpaqueParameterInMultiDepthExtensionTests|AccessorThunkTypeInGenericExtensionTests|ConcurrentFileMappingTests|LocalTypeContextNameTests|LocalTypeInterfaceTests|LocalTypeDumpTests|RuntimeTypeNameLocalTypeTests|PrivateDeclarationsTests|PrivateDeclarationsWholeTreeTests|LocalTypeDisplayNameTests|PrivateDiscriminatorSourceFilesTests|PrivateDiscriminatorSourceFileIndexTests)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift index dcbd3da4d..28be72719 100644 --- a/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift +++ b/Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift @@ -3,7 +3,7 @@ import SwiftDeclaration import Foundation import MachOSwiftSection import OrderedCollections -import Demangling +@_spi(Internals) import Demangling @_spi(Internals) import MachOSymbols @_spi(Internals) import SwiftInspection @@ -148,9 +148,23 @@ public final class IndexerConformanceProvider(_ body: (SubclassCache) -> Value) -> Value { + lock.lock() + defer { lock.unlock() } + return body(self) + } } + private typealias ClassHierarchy = (directChildrenByParentName: [String: [TypeName]], superclassLinkByClassName: [String: SuperclassLink]) + private let subclassCache = SubclassCache() public init(indexer: SwiftDeclarationIndexer) { @@ -230,13 +244,33 @@ extension IndexerConformanceProvider: ConformanceProvider { /// the other way, by walking every indexed `.class` definition's /// `superclassType` link. Lock-protected so concurrent first-callers /// don't both pay the O(n) build cost. - private func classHierarchy() -> (directChildrenByParentName: [String: [TypeName]], superclassLinkByClassName: [String: SuperclassLink]) { - subclassCache.lock.lock() - defer { subclassCache.lock.unlock() } - if let cachedChildren = subclassCache.directChildrenByParentName, let cachedLinks = subclassCache.superclassLinkByClassName { - return (cachedChildren, cachedLinks) + /// + /// The walk demangles every class's superclass and prints two names per + /// class, and a host calls the specializer synchronously — RuntimeViewer + /// from an actor, on a 512 KB cooperative thread, where each of those calls + /// would hop to a large-stack worker on its own with the lock held. So a + /// miss moves to a large stack first, in one hop, and takes the lock + /// there: the walk runs inline under it and nothing hops while it is held. + /// A hit takes the lock briefly and never hops. + private func classHierarchy() -> ClassHierarchy { + if let cachedHierarchy = subclassCache.withLock({ $0.builtHierarchy }) { + return cachedHierarchy } + return StackSafeExecutor.withLargeStack { + self.subclassCache.withLock { cache in + if let builtHierarchy = cache.builtHierarchy { + return builtHierarchy + } + let builtHierarchy = self.buildClassHierarchy() + cache.directChildrenByParentName = builtHierarchy.directChildrenByParentName + cache.superclassLinkByClassName = builtHierarchy.superclassLinkByClassName + return builtHierarchy + } + } + } + /// One walk over the indexed classes, building both maps. + private func buildClassHierarchy() -> ClassHierarchy { var map: [String: [TypeName]] = [:] var links: [String: SuperclassLink] = [:] for (childTypeName, entry) in indexer.allAllTypeDefinitions { @@ -302,9 +336,6 @@ extension IndexerConformanceProvider: ConformanceProvider { map[superTypeName.name, default: []].append(childTypeName) links[childTypeName.name] = .inherits(from: superTypeName) } - - subclassCache.directChildrenByParentName = map - subclassCache.superclassLinkByClassName = links return (map, links) } } diff --git a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift index f04463ea0..c99535154 100644 --- a/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift +++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift @@ -137,19 +137,25 @@ extension TypeDefinition { /// `specialize(with:typeArgumentNodes:derivingNestedSpecializationsWith:selection:typeArgumentNodesByParameter:in:)`, /// which auto-derives nested specialized children from the same outer /// binding. + /// + /// Like the library's other async entry points, the body runs on the + /// large-stack task executor (`LargeStackTaskExecution.run`), so a caller + /// on a 512 KB cooperative thread does not hop per demangle. @discardableResult public func specialize( with specializationResult: SpecializationResult, typeArgumentNodes: [Node]? = nil, in machO: MachOImage, ) async throws -> TypeDefinition { - let specialized = try makeSpecializedDefinition( - with: specializationResult, - typeArgumentNodes: typeArgumentNodes, - in: machO - ) - appendSpecializedChild(specialized) - return specialized + try await LargeStackTaskExecution.run { + let specialized = try makeSpecializedDefinition( + with: specializationResult, + typeArgumentNodes: typeArgumentNodes, + in: machO + ) + appendSpecializedChild(specialized) + return specialized + } } /// Specialize the receiver **and** derive specialized nested children @@ -182,6 +188,12 @@ extension TypeDefinition { /// `nestedSpecializationDepthLimit`; hitting it logs an `os_log` /// warning under the `com.machoswiftsection.swift-interface` subsystem /// and truncates the subtree. + /// + /// The body runs on the large-stack task executor + /// (`LargeStackTaskExecution.run`). RuntimeViewer calls this overload + /// from an actor; without the executor its body ran on a 512 KB + /// cooperative thread and hopped per demangle, some of them under + /// `DependentMemberProjection`'s per-image lock. @_spi(Support) @discardableResult public func specialize( @@ -192,24 +204,26 @@ extension TypeDefinition { typeArgumentNodesByParameter: [String: Node], in machO: MachOImage ) async throws -> TypeDefinition { - let specialized = try makeSpecializedDefinition( - with: specializationResult, - typeArgumentNodes: typeArgumentNodes, - in: machO - ) - specialized.typeChildren = await deriveNestedSpecializedTypeChildren( - using: specializer, - selection: selection, - typeArgumentNodesByParameter: typeArgumentNodesByParameter, - inheritedTypeArgumentNodes: typeArgumentNodes ?? [], - in: machO, - depth: 0 - ) - for child in specialized.typeChildren { - child.parent = specialized + try await LargeStackTaskExecution.run { + let specialized = try makeSpecializedDefinition( + with: specializationResult, + typeArgumentNodes: typeArgumentNodes, + in: machO + ) + specialized.typeChildren = await deriveNestedSpecializedTypeChildren( + using: specializer, + selection: selection, + typeArgumentNodesByParameter: typeArgumentNodesByParameter, + inheritedTypeArgumentNodes: typeArgumentNodes ?? [], + in: machO, + depth: 0 + ) + for child in specialized.typeChildren { + child.parent = specialized + } + appendSpecializedChild(specialized) + return specialized } - appendSpecializedChild(specialized) - return specialized } private func makeSpecializedDefinition( @@ -479,15 +493,18 @@ extension TypeDefinition { /// Throws `SpecializationError.notGenericType` for a non-generic receiver /// and `.descriptorMismatch` for a result made for another type. Like the /// runtime overload, this specializes only the receiver; the deriving - /// overload below also derives its nested types. + /// overload below also derives its nested types. Both run their body on + /// the large-stack task executor, as the runtime overloads do. @discardableResult public func specialize( with specializationResult: StaticSpecializationResult, in machO: MachOFile ) async throws -> TypeDefinition { - let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) - appendSpecializedChild(specialized) - return specialized + try await LargeStackTaskExecution.run { + let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) + appendSpecializedChild(specialized) + return specialized + } } /// Specialize the receiver offline **and** derive specialized nested @@ -506,18 +523,20 @@ extension TypeDefinition { derivingNestedSpecializationsWith specializer: GenericSpecializer, in machO: MachOFile ) async throws -> TypeDefinition { - let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) - specialized.typeChildren = await deriveNestedStaticallySpecializedTypeChildren( - using: specializer, - selection: specializationResult.selection, - in: machO, - depth: 0 - ) - for child in specialized.typeChildren { - child.parent = specialized + try await LargeStackTaskExecution.run { + let specialized = try makeStaticallySpecializedDefinition(with: specializationResult, in: machO) + specialized.typeChildren = await deriveNestedStaticallySpecializedTypeChildren( + using: specializer, + selection: specializationResult.selection, + in: machO, + depth: 0 + ) + for child in specialized.typeChildren { + child.parent = specialized + } + appendSpecializedChild(specialized) + return specialized } - appendSpecializedChild(specialized) - return specialized } private func makeStaticallySpecializedDefinition( diff --git a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift new file mode 100644 index 000000000..b40395baa --- /dev/null +++ b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift @@ -0,0 +1,101 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Dependencies +@_spi(Internals) import MachOSymbols +@testable import MachOSwiftSection +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// `IndexerConformanceProvider` builds its class hierarchy on a large stack. +/// +/// The build demangles every indexed class's superclass and prints two names +/// per class. A host calls the specializer synchronously — RuntimeViewer from +/// an actor, on a 512 KB cooperative thread — and on such a thread each of +/// those calls hopped to a large-stack worker on its own, with the provider's +/// lock held throughout. The build has to move to a large stack in one hop +/// instead, before it takes the lock. +/// +/// The one piece of code a test can run inside the build is an event handler: +/// a class whose wrapper cannot be materialized is reported from the walk +/// itself (`SubclassMapMaterializationFailureTests` injects the same unreadable +/// class). The handler records the stack of the thread it is called on. +@Suite +final class ClassHierarchyBuildStackTests: MachOFileTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + private static let largeStackSize = 8 * 1024 * 1024 + + private func typeName(named leafName: String, in indexer: SwiftDeclarationIndexer) throws -> TypeName { + try #require(indexer.allTypeDefinitions.keys.first { $0.declaredNameForTesting == leafName }) + } + + @Test func classHierarchyIsBuiltOnALargeStack() async throws { + let recorder = SubclassMapReportStackRecorder() + let unsafeMachOFile = machOFile + let indexer = SwiftDeclarationIndexer(eventHandlers: [recorder], in: unsafeMachOFile) + try await indexer.prepare() + + let baseClassName = try typeName(named: "ClassTest", in: indexer) + let donorTypeName = try typeName(named: "FinalClassTest", in: indexer) + let donorDefinition = try #require(indexer.allTypeDefinitions[donorTypeName]) + guard case .class(let realClassDescriptor) = donorDefinition.typeContextDescriptorWrapper else { + Issue.record("FinalClassTest is expected to be a class") + return + } + // A real class descriptor's layout re-wrapped far past the fixture's + // end of file, so materializing its wrapper throws inside the build. + indexer.currentStorage.allTypeDefinitions[donorTypeName] = TypeDefinition( + typeContextDescriptorWrapper: .class(ClassDescriptor(layout: realClassDescriptor.layout, offset: 0x0FFF_FFF0)), + typeName: donorTypeName, + isSpecialized: false + ) + indexer.allStorageCache = .init() + + // The caller gets a cooperative thread's stack explicitly, so the test + // does not depend on which thread Swift Testing runs its body on. The + // body suspends instead of blocking while the thread works. + let provider = IndexerConformanceProvider(indexer: indexer) + let callerStackSize = await withCheckedContinuation { continuation in + let callerThread = Thread { + let callerStackSize = pthread_get_stacksize_np(pthread_self()) + _ = provider.subclasses(of: baseClassName) + continuation.resume(returning: callerStackSize) + } + callerThread.stackSize = 512 * 1024 + callerThread.start() + } + try #require(callerStackSize < Self.largeStackSize, "the caller must have a small stack for the test to mean anything; it has \(callerStackSize) bytes") + + let reportingStackSizes = recorder.stackSizes + try #require(!reportingStackSizes.isEmpty, "the unreadable class must be reported from inside the build") + #expect( + reportingStackSizes.allSatisfy { $0 >= Self.largeStackSize }, + "the build ran on stacks of \(reportingStackSizes) bytes; called from a \(callerStackSize)-byte stack it must move to a large one" + ) + } +} + +/// Records the stack size of every thread that reports a subclass-map +/// degradation. Event handlers run on the dispatching thread. +private final class SubclassMapReportStackRecorder: SwiftIndexEvents.Handler, @unchecked Sendable { + private let lock = NSLock() + private var recordedStackSizes: [Int] = [] + + func handle(event: SwiftIndexEvents.Payload) { + guard case .renderingDegraded(let context, _) = event, case .subclassMap = context.source else { return } + let stackSize = pthread_get_stacksize_np(pthread_self()) + lock.lock() + defer { lock.unlock() } + recordedStackSizes.append(stackSize) + } + + var stackSizes: [Int] { + lock.lock() + defer { lock.unlock() } + return recordedStackSizes + } +} diff --git a/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift b/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift new file mode 100644 index 000000000..955f4a964 --- /dev/null +++ b/Tests/SwiftSpecializationTests/SpecializationEntryPointExecutorTests.swift @@ -0,0 +1,156 @@ +@_spi(Support) @testable import SwiftSpecialization +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +import Foundation +import Testing +import MachOKit +import Demangling +@_spi(Internals) import MachOSymbols +@testable import MachOSwiftSection +import MachOTestingSupport + +/// The async `TypeDefinition.specialize` overloads are library entry points, +/// so their bodies run on the large-stack task executor like every other +/// async entry point's (`LargeStackTaskExecution.run`). Without it, a body +/// called from a cooperative thread — RuntimeViewer calls the deriving +/// overload from an actor — runs on that thread's 512 KB stack, where every +/// demangle and print hops to a large-stack worker on its own, among them the +/// ones `DependentMemberProjection` makes under its per-image lock. +/// +/// The conformance provider is the code a test can run inside the body: +/// deriving a nested type asks the specializer for the nested type's request, +/// and the request asks the provider for candidates. A stand-in provider +/// records the stack of every thread it is asked on. +@Suite +struct SpecializationEntryPointExecutorTests { + private static let largeStackSize = 8 * 1024 * 1024 + + @Test(.enabled(if: LargeStackTaskExecution.isEnabled && LargeStackTaskExecution.isSupported)) + func runtimeDerivingSpecializationRunsOnTheLargeStackExecutor() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.runtime() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "NestedHost", in: indexer) + let recordingProvider = StackRecordingConformanceProvider(wrapping: IndexerConformanceProvider(indexer: indexer)) + let specializer = GenericSpecializer(machO: indexer.machO, conformanceProvider: recordingProvider, indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let selection: SpecializationSelection = ["A": .metatype(Int.self)] + let result = try specializer.specialize(request, with: selection) + let intNode = try await demangleAsNode("Si", isType: true) + recordingProvider.removeRecordedStackSizes() + + let specialized = try await definition.specialize( + with: result, + typeArgumentNodes: [intNode], + derivingNestedSpecializationsWith: specializer, + selection: selection, + typeArgumentNodesByParameter: ["A": intNode], + in: indexer.machO + ) + + try #require(!specialized.typeChildren.isEmpty, "the fixture's nested type must be derived, or the provider is never asked") + try expectOnlyLargeStacks(recordingProvider.recordedStackSizes) + } + + @Test(.enabled(if: LargeStackTaskExecution.isEnabled && LargeStackTaskExecution.isSupported)) + func offlineDerivingSpecializationRunsOnTheLargeStackExecutor() async throws { + let indexer = try await GenericSpecializationFixtureIndexers.shared.offline() + let definition = try GenericSpecializationFixtureIndexers.typeDefinition(named: "NestedHost", in: indexer) + let recordingProvider = StackRecordingConformanceProvider(wrapping: IndexerConformanceProvider(indexer: indexer)) + let specializer = GenericSpecializer(machO: indexer.machO, conformanceProvider: recordingProvider, indexer: indexer) + let request = try specializer.makeRequest(for: definition.typeContextDescriptorWrapper) + let result = try specializer.specialize(request, with: ["A": .metatype(Int.self)]) + recordingProvider.removeRecordedStackSizes() + + let specialized = try await definition.specialize( + with: result, + derivingNestedSpecializationsWith: specializer, + in: indexer.machO + ) + + try #require(!specialized.typeChildren.isEmpty, "the fixture's nested type must be derived, or the provider is never asked") + try expectOnlyLargeStacks(recordingProvider.recordedStackSizes) + } + + private func expectOnlyLargeStacks(_ stackSizes: [Int]) throws { + try #require(!stackSizes.isEmpty, "deriving the nested type must ask the provider for candidates") + #expect( + stackSizes.allSatisfy { $0 >= Self.largeStackSize }, + "the provider was asked on stacks of \(Set(stackSizes).sorted()) bytes; the specialization's body must run on the large-stack executor" + ) + } +} + +/// Forwards every question to a real provider and records the stack size of +/// the thread each one was asked on. +private final class StackRecordingConformanceProvider: ConformanceProvider, @unchecked Sendable { + private let wrappedProvider: any ConformanceProvider + private let lock = NSLock() + private var stackSizes: [Int] = [] + + init(wrapping wrappedProvider: any ConformanceProvider) { + self.wrappedProvider = wrappedProvider + } + + var recordedStackSizes: [Int] { + lock.lock() + defer { lock.unlock() } + return stackSizes + } + + func removeRecordedStackSizes() { + lock.lock() + defer { lock.unlock() } + stackSizes.removeAll() + } + + private func recordCurrentThreadStackSize() { + let stackSize = pthread_get_stacksize_np(pthread_self()) + lock.lock() + defer { lock.unlock() } + stackSizes.append(stackSize) + } + + func types(conformingTo protocolName: ProtocolName) -> [TypeName] { + recordCurrentThreadStackSize() + return wrappedProvider.types(conformingTo: protocolName) + } + + func doesType(_ typeName: TypeName, conformTo protocolName: ProtocolName) -> Bool { + recordCurrentThreadStackSize() + return wrappedProvider.doesType(typeName, conformTo: protocolName) + } + + func conformances(of typeName: TypeName) -> [ProtocolName] { + recordCurrentThreadStackSize() + return wrappedProvider.conformances(of: typeName) + } + + var allTypeNames: [TypeName] { + recordCurrentThreadStackSize() + return wrappedProvider.allTypeNames + } + + func typeDefinition(for typeName: TypeName) -> TypeDefinition? { + recordCurrentThreadStackSize() + return wrappedProvider.typeDefinition(for: typeName) + } + + func imagePath(for typeName: TypeName) -> String? { + recordCurrentThreadStackSize() + return wrappedProvider.imagePath(for: typeName) + } + + func subclasses(of baseClassName: TypeName) -> [TypeName] { + recordCurrentThreadStackSize() + return wrappedProvider.subclasses(of: baseClassName) + } + + func superclassLink(of className: TypeName) -> SuperclassLink { + recordCurrentThreadStackSize() + return wrappedProvider.superclassLink(of: className) + } + + func isConditionalConformance(of typeName: TypeName, to protocolName: ProtocolName) -> Bool { + recordCurrentThreadStackSize() + return wrappedProvider.isConditionalConformance(of: typeName, to: protocolName) + } +} From 3ebf529a908d19b0c3471222adcb9917416f34c6 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Oct 2026 23:38:05 +0800 Subject: [PATCH 37/49] docs: narrow the lock rule and adjudicate the remaining sites - AGENTS.md: "Do not hold a lock across a demangle" becomes "never let a demangle or print hop while you hold a lock": be on a large stack already (an executor-wrapped entry point, or one withLargeStack taken before locking), or demangle outside the lock and insert-if-absent. - ReviewAdjudications A61: the five other locks the sweep found (the printer's one-time builds, the static field layout provider, the dependent member projection, the property wrapper catalog, the ObjC ancestor resolver) stay as they are; every caller in the library and in RuntimeViewer reaches them through an executor-wrapped entry point. - LargeStackTaskExecutorAdoption: the specialize overloads join the table of wrapped entry points. - Evolution ledger section 89. --- AGENTS.md | 2 +- .../LargeStackTaskExecutorAdoption.md | 1 + .../Internal/ProjectEvolutionLog.md | 23 +++++++++++++++++++ .../Internal/ReviewAdjudications.md | 22 ++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index af77af459..1c589f7a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ Each of these fails **silently**, and several produce a real, fully-qualified, * - **Do NOT call bare `NodeReference(interning:)` on a batch path** — route through `InternedNodeReferenceCache`. - **A `_symbolic` symbol's referents are one mangling, not several.** The compiler appends them with one mangler, so a later referent reuses substitutions and words of the earlier ones (`7SwiftUI19_ConditionalContentV AA08ModifiedD0V`); demangled alone it fails or names something else. Take referents from `SymbolicManglingIndex.referentNode(of:in:)`, which demangles them together — and for the same reason never splice referents into the mangled name as text. - **Resolving one type's members/info/attributes must use the node-taking overloads** (`memberSymbols(of:for:node:in:)` and friends). The name-only forms flatten every sub-bucket on purpose: the name key is printed with `.interfaceTypeBuilderOnly`, which strips private discriminators, so same-named private types share a bucket (issue #115). -- **Do not hold a lock across a demangle** — the large-stack hop can block. +- **Never let a demangle or print hop while you hold a lock.** On a 512 KB thread each call hops to a large-stack worker and blocks on it, so every thread waiting on the lock waits behind the hop — without bound once the pool saturates (`SymbolIndexStore.lateDemangledNode`, 2026-08-03). Under a lock, either be on a large stack already — inside a `LargeStackTaskExecution.run` entry point, or past one `StackSafeExecutor.withLargeStack` taken *before* locking (`IndexerConformanceProvider.classHierarchy()`) — or demangle outside the lock and insert-if-absent under it. A synchronous API runs on whatever thread its host calls it from. The sites that rely on their entry point's executor: [ReviewAdjudications A61](Documentations/Internal/ReviewAdjudications.md). - **A `MachOFile` symbol's `offset` is its raw `n_value` — an address, not the file offset MachOKit's doc comment claims.** Into the index it goes through `SymbolValueOffsetConverter`; as an address it is used as is (`ThunkAddressSpace.address(forSymbolValue:)`). A dylib's `__TEXT` at 0 makes the two look interchangeable; a main executable's at 0x100000000 does not. **A STABS entry (`nlist.isDebuggingEntry`) never supplies an offset or an address**: an `N_GSYM` carries the value 0 under the very name of the symbol it describes. The index lets one only reserve its name's row (`SymbolTableBuilder.reserveRow`), which keeps members in source order — dropping the entries outright reorders 42 SymbolTestsCore snapshots. `ExecutableImageSymbolOffsetTests` pins the offsets. - **Changing a struct layout in `MachOSymbols` needs `swift package clean`.** Incremental builds have been observed linking stale downstream objects (runtime SIGSEGV in `outlined destroy`). Moving a public type across modules or flipping a dependency edge does the same. Clean first, diagnose second. diff --git a/Documentations/Internal/LargeStackTaskExecutorAdoption.md b/Documentations/Internal/LargeStackTaskExecutorAdoption.md index 15a212509..6077568e0 100644 --- a/Documentations/Internal/LargeStackTaskExecutorAdoption.md +++ b/Documentations/Internal/LargeStackTaskExecutorAdoption.md @@ -32,6 +32,7 @@ | `SwiftInterface` | `SwiftInterfaceBuilder.prepare()` / `printRoot()`;`SwiftDiffableInterfaceBuilder.prepare()`;`AnySwiftEvolutionInterfaceBuilder.prepare(maximumConcurrentPreparations:)` / `printAnnotatedInterface()` / `annotatedBlocks()`(pack façade 委托);`SwiftDiffableInterfaceRenderer.printAnnotatedInterface(format:)` / `annotatedDiffBlocks()` | | `SwiftPrinting` | `SwiftDeclarationPrinter.printTypeDefinition` / `printProtocolDefinition` / `printExtensionDefinition` / `printDefinition`(RuntimeViewer 逐类型导出绕过 `printRoot` 的路径) | | `SwiftDump` | 六个 `Dumpable.dump(using:in:)` 遵循者(`Struct` / `Class` / `Enum` / `Protocol` / `ProtocolConformance` / `AssociatedType`) | +| `SwiftSpecialization` | `TypeDefinition.specialize(...)` 的四个 async 重载(运行时两个、离线两个)。2026-10-11 才补上,此前漏包,见 [ReviewAdjudications A61](ReviewAdjudications.md) 第三处。`GenericSpecializer` 的入口是同步的,跑在宿主调用它的线程上;其中类继承表的建表由 `IndexerConformanceProvider` 自己先切一次大栈再做 | **嵌套免费**:`printRoot` 里再进 `printTypeDefinition`、父类型的嵌套子类型循环再进 `printTypeDefinition`,都是「已在执行器上再包一层」。SE-0417 的 `withTaskExecutorPreference` 在当前执行器就是目标执行器时不切换,`nestedRunsStayOnTheSameThread` 钉住线程不变。CLI 的 `dump` 循环按类型逐个调 `dump`,每个类型进出执行器各一跳,SwiftUICore 五千余类型约一万跳、总计零点几秒,远小于原来每个符号一跳,故 CLI 侧没有再包一层。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 1a2876baa..529221dfb 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2418,6 +2418,29 @@ - **关联文档**:[0063-private-declarations](../Evolutions/0063-private-declarations.md)、[Modules/SwiftPrivateDiscriminators.md](Modules/SwiftPrivateDiscriminators.md)、[Glossary.md](../Glossary.md)「private declaration」;展示一侧是 RuntimeViewer 的 `draft-private-discriminator-tag`。 - **对应版本**:下一个版本(未发版)。 +## 89. 持锁时 demangle 不切线程:类继承表改在大栈上建,`TypeDefinition.specialize` 补上执行器 + +- **时间段**:2026-10-11。 +- **动机**:审查第 88 节的分支时,它的 index 持锁读名字,违反 AGENTS.md 的「Do not hold a lock across a demangle」。按规矩在全库横向排查同一写法,又找到六处老代码。其中 RuntimeViewer 真会从 512 KB 栈的线程走进来的有两处: + - 在 actor 里同步调用 `GenericSpecializer.makeRequest`。带父类约束的参数第一次找候选时,`IndexerConformanceProvider.classHierarchy()` 在锁内给每个类 demangle 一次父类、打印两次名字,每次都单独切一趟线程。 + - 在 actor 里调用 `TypeDefinition.specialize(...)` 的 deriving 重载。它没有包执行器,条件满足时会在 `DependentMemberProjection` 的锁内逐次切线程。 +- **关键决策**(用户选择:只修真会从小栈调进来的,其余登记不修,并把规则写准确): + - `classHierarchy()`:缓存没命中时先一次切到大栈(`StackSafeExecutor.withLargeStack`),再在大栈上取锁、复查、建表,持锁期间不再切线程;命中缓存的调用不切线程。没有改成「锁外建表、锁内插入」:并发的首次调用本来就要等这张表,锁外建会让它们各建一遍。两张表(父类 → 子类、子类 → 父类)仍在同一次遍历里建出、在同一把锁下一起存,`subclasses(of:)` 和离线父类检查用的 `superclassLink(of:)` 读到的是同一份。 + - `TypeDefinition.specialize(...)` 的四个 async 重载包上 `LargeStackTaskExecution.run`,和库里其它 async 入口一致。执行器接入时(`4c6bdd4d`,2026-09-03)漏了它们。 + - 其余五处的锁不改,登记 [ReviewAdjudications A61](ReviewAdjudications.md):调用都经包过执行器的入口进来,macOS 15 起持锁期间不切线程。 + - AGENTS.md 的规则改写成「Never let a demangle or print hop while you hold a lock」:要么已经在大栈上(执行器包过的入口里,或者取锁前先 `withLargeStack`),要么锁外 demangle、锁内 insert-if-absent;同步 API 跑在宿主调用它的线程上。 + - 测试的观察点:库外看不到这些代码跑在哪个线程上。用户同意为此加一个只给测试用的钩子,动手时找到了现成的观察点,就没有加。两边都在回调里记下当前线程的栈大小: + - `classHierarchy()`:沿用 `SubclassMapMaterializationFailureTests` 的办法,注入一个读不出来的类描述符。建表时发出的降级事件,在建表线程上同步交给处理器。 + - `specialize`:用一个转发型的 `ConformanceProvider`。派生嵌套类型时,特化器会在 `specialize` 的函数体里问它要候选。 + - RuntimeViewer 那边每次请求都新建 provider,section 那份表建好后也不再刷新。这两个问题转给 RuntimeViewer 会话修。 +- **落地模块**:SwiftSpecialization(`ConformanceProvider.swift`、`TypeDefinition+Specialization.swift`)。 +- **验证**: + - `ClassHierarchyBuildStackTests`:在 512 KB 栈的线程上调用 `subclasses(of:)`。修复前建表跑在调用方 536,576 字节的栈上,测试失败;修复后跑在 8 MB 的栈上,测试通过。 + - `SpecializationEntryPointExecutorTests`:运行时、离线两个 deriving 重载各一条。修复前 provider 在 536,576 字节的栈上被调用,测试失败;修复后在执行器的大栈线程上,测试通过。两个新套件加进了 CI 的过滤清单。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,带 `USING_LOCAL_DEPENDENCIES=1`)在 `classHierarchy()` 修好之后跑过一次:2427 个测试、462 个套件全部通过,原始退出码 0。`specialize` 包上执行器之后,重跑了它在库内唯一的调用方 `SwiftSpecializationTests`(154 个测试、27 个套件),以及 `ContinuousIntegrationTestFilterTests`,全部通过,原始退出码 0。 +- **关联文档**:AGENTS.md「Never let a demangle or print hop while you hold a lock」、[ReviewAdjudications A61](ReviewAdjudications.md)、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「包了哪些入口」、[NodeStoreMigrationOpenIssues 第 9 条](NodeStoreMigrationOpenIssues.md)(规则的来历)。 +- **对应版本**:下一个版本(未发版)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index d96bd9a5e..e361d7640 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -708,3 +708,25 @@ - **与 main 基线对比**:代码是基线既有的,同样是局部类型名字对上之后才可达。 - **为什么不修**:造不出会变红的测试。同一处的访问器种类(`accessorKind`)已经修掉,那个读错会把 `static` 存储属性印成计算属性。 - **复审条件**:节点连接不再先于第四道门(`methodDescriptorLookup` 的建键方式改了);出现了局部 class 被误标 `final`、运算符函数里的局部类型成员名字读错的实例;或者局部类型的属性以 setter 之类的节点出现在声明、ABI 键里。 + +--- + +## A61 — 持锁时 demangle 的五处:打印器的一次性建表、静态布局 provider、关联类型成员投影、property wrapper 目录、ObjC 祖先解析(「持锁时 demangle」横向排查) + +- **裁决**:五处的锁都不改(2026-10-11)。排查中发现的入口漏包已修,见第三处。 +- **背景**:审查提案 [0063-private-declarations](../Evolutions/0063-private-declarations.md) 时,它的 index 持锁读名字,违反 AGENTS.md 当时的「Do not hold a lock across a demangle」。这条规则来自 [NodeStoreMigrationOpenIssues 第 9 条](NodeStoreMigrationOpenIssues.md):在 512 KB 栈的线程上,每次 demangle、打印都要切到大栈线程、用信号量等结果;持锁时这样一等,所有等这把锁的线程都排在后面。危害要两个条件同时成立:调用方在小栈上,并且有别的线程在等同一把锁。横向排查找到下面五处同样的写法,外加 `IndexerConformanceProvider.classHierarchy()` 一处。后者 RuntimeViewer 从 actor 里同步调用,已修:缓存没命中时先切一次大栈,再在大栈上取锁建表(`ClassHierarchyBuildStackTests`)。规则因此改写成「持锁时 demangle 不许切线程」:要么已经在大栈上(`LargeStackTaskExecution.run` 包过的入口里,或者取锁前先 `StackSafeExecutor.withLargeStack`),要么锁外 demangle、锁内 insert-if-absent。下面五处靠的是入口的执行器:库内和 RuntimeViewer 的调用都经包过执行器的 async 入口进来,macOS 15 起在 16 MB 栈上执行,持锁期间不切线程。 +- **一、`SwiftDeclarationPrinter` 的两次建表**(`SwiftDeclarationPrinter.swift:93` 的 `@_rawLayout` 存储表、`:118` 的静态布局 provider):都是 printer 实例上的 `@Mutex`,第一次用到时在锁内建表,命中也拿同一把锁。`:93` 对每个 `__swift5_builtin` 描述符做一次 `demangleType`;`:118` 对 `MachOFile` 建依赖闭包,要把根镜像的全部描述符 demangle 一遍(`MachOImage` 直接返回 nil)。唯一入口 `printTypeDefinition` 已包执行器。 +- **二、`MachOFileStaticFieldLayoutProvider`**(`StaticFieldLayoutProvider.swift:129` 的锁,11 个查询方法每次都拿):底层计算器的 memo 不是线程安全的(`:124-126` 的注释),所以每次查询都在锁内算;懒加载依赖镜像时,会在锁内把整个依赖镜像 demangle 一遍。只服务 `MachOFile`。异步入口(打印、dump)已包执行器。同步的 public 入口有 provider 自己的方法、`MachOFile.precomputedStaticAggregateFieldLayout` 和 `MachOFile.renderFieldOffsets`,库内和 RuntimeViewer 都没有从小栈调用。 +- **三、`DependentMemberProjection`**(`:44` 每个镜像一份 entry 的锁,`:61` 按文件登记的锁):每次关联类型成员投影都拿 entry 锁,锁内做 `demangleType`,懒加载依赖镜像时要把整个镜像 demangle 一遍;文件那把锁在没命中时建依赖闭包。异步入口有 opaque 类型改写(经 `printTypeDefinition`)、`AssociatedType.dump` 和 `SwiftDeclarationIndexer.prepare()`,都已包执行器。 + - **排查中发现的入口漏包(已修)**:`TypeDefinition.specialize(...)` 的四个 async 重载(运行时两个、离线两个)没有包执行器。RuntimeViewer 在 actor 里调用其中一个(`RuntimeSwiftSection.swift:935`)。当某个 fixed 参数的 same-type 右侧代换后带 `dependentMemberType` 时,这条路会经 `GenericInstantiation` 在 512 KB 栈上拿这把锁,并逐次切线程。本批把四个重载都包上了 `LargeStackTaskExecution.run`(`SpecializationEntryPointExecutorTests`),和其它 async 入口一致。 + - 同步的 `GenericSpecializer.specialize(_:with:)` / `staticPreflight` 也会走到这里,只服务 `MachOFile`。 +- **四、`PropertyWrapperTypeCatalog`**(`:140`,每个镜像一个 catalog):每次查询都拿锁。没命中时在锁内 demangle 导出符号名(`:173`),第一次没命中还要建依赖闭包。入口是 `TypeDefinition.index(in:)`,调用方都在已包的入口里,包括打印、索引,以及 diff 和 evolution 渲染。同步 public 入口 `evidence(forWrapperCandidate:)` 没有人从小栈调用。 +- **五、`ObjCAncestorResolver`**(`:92`、`:133`,每个镜像一个 resolver):原先列为疑似,核实属实,但有条件。依赖镜像的 `ObjCClassMethodIndex` 存储(进程级、按镜像共享)第一次建的时候,会在锁内给每个 Swift 类 demangle 一次限定名(`ObjCClassMethodIndex.swift:444` → `NodeTypeNaming`)。入口经 `index(in:)`、`prepare()` 和 `Class.dump`,都已包执行器。同步 public 入口是 `ObjCMembers.table(forSwiftClassQualifiedName:in:)`。 +- **复现 / 是否误报**:五处的机制都属实。输出层面复现不出:结果不会错,只会在「小栈调用 + 有人等锁」时多等。第三处的漏包修掉之后,库内和 RuntimeViewer 的调用路径都不满足第一个条件。 +- **与 main 基线对比**:五处的锁在 main(0.22.0)上都有。第二处按 binding 查询的四个方法和 `projectingConcreteMembers` 来自离线特化(`b72638f8`、`5308fa1a`),main 上没有。第三处的漏包入口里,运行时的两个重载 main 上就有;从它们走到这把锁的那一步(`GenericInstantiation`,`6c35e8c4`,2026-10-08)main 上没有。 +- **为什么不修**: + 1. 第一个条件不成立:调用都经包了执行器的入口进来,macOS 15 起持锁期间不切线程。macOS 15 以下没有执行器,这些路径上每次 demangle 不管有没有锁都要切线程,锁不是额外的代价。 + 2. 第二、三处的同步入口只服务 `MachOFile`。同一个 `MachOFile` 本来就不支持并发读(MachOKit 的读取共享一个 `FileHandle`),所以没有并发等锁的线程。 + 3. 第二、三处的锁保护的是不线程安全的计算器 memo。要把 demangle 挪出锁,得把计算器改成线程安全的,代价大,而收益只在上面两个条件同时成立时才有。 +- **既往修复**:无。规则来自第 9 条(`lateDemangledNode`,2026-08-03 修)。第一处 `:118` 的锁(`7ebed7d3`,2026-06-24)是专门为防止并发重复建表加的;第二处的锁随读取器特化引入(`1af4ea24`,2026-06-22)。其余几处(`268159bd`、`72b5c5f6`、`01fe2f82`、`758314ff`)都写在规则进 AGENTS.md(2026-09-14)之后,从写法看,当时把规则理解成了「所有查询都要拿的锁」。 +- **复审条件**:有宿主在协作线程或 libdispatch 线程上并发调用上面列出的同步入口;又出现没包执行器、能走到这几把锁的 async 入口(像这次的 `TypeDefinition.specialize`);`MachOFile` 改成支持并发读;或者有宿主在 macOS 15 以下的实测里卡在这些锁上。 From afdf9c78028c40087f401923558fbe1d8380a110 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 10 Oct 2026 18:29:22 +0800 Subject: [PATCH 38/49] feat(SwiftPrinting): print SE-0491 module selectors in interface and dump Swift 6.4 writes a .swiftinterface with module selectors (Swift::Int), and the Xcode 27 SDK interfaces are spelled that way. Add an opt-in to match: SwiftDeclarationPrintConfiguration.usesModuleSelectors and 'interface --module-selectors' for the interface, swift-demangling's DemangleOptions.useModuleSelectors and 'dump --enable-module-selectors' for the dump. Both are off by default, and off the output is unchanged. The interface printer follows the compiler's rules, as swift-demangling now does: every nested type carries the module that declared it, so a type another module adds in an extension keeps its origin (Swift::Duration.Foundation::TimeFormatStyle), and a C type imported as a member is qualified level by level; local types and the associated types of type parameters carry none. Names the printers used to write as text now go through the type printer: ~Swift.Copyable / ~Swift.Escapable print long-lived protocol nodes through the caller's resolver, and the extension header no longer shows the dotted lookup key ExtensionName.name, which a sweep test over a compiled fixture caught. OpaqueTypeResolving.opaqueType takes the flag, so the opaque constraint text follows it while the names it matches protocol facts by stay dotted. Evolution proposal: module-selectors. Needs swift-demangling's feature/module-selectors (unreleased). --- AGENTS.md | 1 + .../skills/swift-section-cli/SKILL.md | 11 +- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-module-selectors.md | 43 +++++ .../Internal/Modules/SwiftInterface.md | 2 +- .../Internal/ProjectEvolutionLog.md | 19 ++ Documentations/README.md | 1 + .../Swift/InterfaceRequest.swift | 6 + .../Components/Names/ExtensionName.swift | 16 +- .../Commands/InterfaceCommand.swift | 4 + .../Models/DemangleOptionGroup.swift | 5 + .../Extensions/GenericContext+Dump.swift | 45 ++++- .../Output/SwiftDump/Dumper/ClassDumper.swift | 6 +- .../Output/SwiftDump/Dumper/EnumDumper.swift | 4 +- .../SwiftDump/Dumper/StructDumper.swift | 4 +- ...ftInterfaceBuilderOpaqueTypeProvider.swift | 21 ++- .../DependentGenericNodePrintable.swift | 11 +- .../InterfaceNodePrintable.swift | 2 + .../NodePrintables/NodePrintable.swift | 23 ++- .../NodePrintableDelegate.swift | 6 +- .../NodePrintables/TypeNameResolving.swift | 5 +- .../NodePrintables/TypeNodePrintable.swift | 123 ++++++++++-- .../NodePrinter/FunctionNodePrinter.swift | 1 + .../NodePrinter/SubscriptNodePrinter.swift | 1 + .../NodePrinter/TypeNodePrinter.swift | 1 + .../NodePrinter/VariableNodePrinter.swift | 1 + .../SwiftDeclarationPrintConfiguration.swift | 12 ++ .../SwiftDeclarationPrinter+Headers.swift | 18 +- .../SwiftDeclarationPrinter.swift | 10 +- .../ModuleSelectorFixture.swift | 176 ++++++++++++++++++ .../ModuleSelectorDumpTests.swift | 72 +++++++ .../ModuleSelectorInterfaceTests.swift | 120 ++++++++++++ .../CommandRequestMappingTests.swift | 17 +- 33 files changed, 724 insertions(+), 64 deletions(-) create mode 100644 Documentations/Evolutions/draft-module-selectors.md create mode 100644 Sources/TestSupport/MachOTestingSupport/ModuleSelectorFixture.swift create mode 100644 Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift create mode 100644 Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift diff --git a/AGENTS.md b/AGENTS.md index 1c589f7a9..e3a7d1072 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -263,6 +263,7 @@ Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` r - **The printers' error contract inverts by level.** Inside a definition, a failing field fails the whole type. At the top level — `printRoot` and the nested children loops alike — printing catches **per definition**: one type/protocol/extension/nested child that throws drops only itself, never its block. A block-level catch once blanked every type of a legacy binary's interface. - **A name's `kind` takes no part in its equality.** The node identifies the type; `kind` is derived differently per producer and the two disagree for C-imported types. - **A nested definition's print may depend on its `level` only through indentation.** A host with `marksNestedDefinitions` takes each nested type or protocol out of its parent's print instead of printing it again, removing one indentation level per nesting depth; a hard-coded level, or a line a renderer does not indent, breaks that silently for the host. `NestedDefinitionRegionContractTests` reports it. +- **Never write a module-qualified name into output as text** (`"Swift.Copyable"`, `module + "." + name`). Print it as a node through the type printer or the caller's `DemangleResolver`, so SE-0491 module selectors (`usesModuleSelectors` / `DemangleOptions.useModuleSelectors`, `Swift::Copyable`) reach it; `ModuleSelectorInterfaceTests.noNameKeepsItsDottedQualification` sweeps a fixture's interface for leftovers. A node handed to the interface printer must outlive the print — it memoizes fragments by node identity. Lookup keys are the exception: they stay dotted, printed with fixed presets that never carry the option. [draft-module-selectors](Documentations/Evolutions/draft-module-selectors.md). - The `Name` types are deliberately **not `Codable`**. A mangled symbol already is the tree's serialized form — persist `mangleAsString(node)` and read it back with `demangleAsNode(_:)` rather than reintroducing a node encoding. - [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index 81c5fb7fa..d6d45621f 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -42,8 +42,9 @@ swift-section interface --help | grep -- --exported-only # empty ⇒ this bui Flags added comparatively late, and therefore worth checking: `--emit-header`, `--emit-export-status`, `--exported-only`, `--jobs`, `evolution --interface`, `--supplementary-apinotes`, from 0.20.0 `--dependency-search-path`, -`--infer-objc-overrides` and the whole `objc` subcommand group, and from 0.22.0 -`evolution --emit-available` / `--platform`. When one is missing, say so +`--infer-objc-overrides` and the whole `objc` subcommand group, from 0.22.0 +`evolution --emit-available` / `--platform`, and after 0.22.0 `interface --module-selectors` +/ `dump --enable-module-selectors`. When one is missing, say so rather than silently producing a weaker answer — the alternative is usually "upgrade (`brew upgrade swift-section`), or do without that annotation". @@ -144,6 +145,12 @@ Spelled the same on both: `--emit-type-layout`, `--emit-enum-layout`, `--emit-me `--emit-header`, `--emit-export-status`, `--color-scheme`, `--output-path`, `--dependency-search-path` (§2). +SE-0491 module selectors — `Swift::Int` instead of `Swift.Int`, the spelling a Swift 6.4 +`.swiftinterface` uses, with every nested level naming the module that declared it +(`Swift::Duration.Foundation::TimeFormatStyle`) — are off by default and spelled differently +too: `interface --module-selectors`, `dump --enable-module-selectors` (one of the demangler +switches below). + Only `dump` has: `--sections`, `--preferred-binary-order`, and the demangler option group (`--demangle-options default|simplified|interface` plus ~22 `--enable-…` / `--disable-…` switches). diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 2130e6bfb..8500b4c54 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -77,3 +77,4 @@ | draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | | [0063](0063-private-declarations.md) | 私有声明:从名字取 discriminator,按镜像反推源文件 | Implemented | +| draft | [适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名](draft-module-selectors.md) | In Progress | diff --git a/Documentations/Evolutions/draft-module-selectors.md b/Documentations/Evolutions/draft-module-selectors.md new file mode 100644 index 000000000..46f40ad1d --- /dev/null +++ b/Documentations/Evolutions/draft-module-selectors.md @@ -0,0 +1,43 @@ +# Draft - 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 + +- **状态**: In Progress +- **创建日期**: 2026-10-10 +- **最后更新**: 2026-10-10 +- **关联提案**: swift-demangling 提案 `draft-module-selectors`(`DemangleOptions.useModuleSelectors`,本提案的 dump 一侧与 interface 的委托打印都建在它上面) + +## 摘要 + +[SE-0491](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0491-module-selectors.md)(Swift 6.3 实现)给源码加了 `Module::Name` 写法:名字前带上它来自的模块,查找只认这个模块,不会被同名的类型、成员或局部变量挡住——典型的坑是模块里有个与模块同名的类型(`XCTest` 模块里的 `XCTest` 类),这时 `XCTest.XCTestCase` 会被当成去 `XCTest` 类里找嵌套类型。提案不改 ABI,二进制里没有任何新东西要读,影响只在「名字怎么写」。 + +Swift 6.4 编译器生成 `.swiftinterface` 时默认就用这种写法:Xcode 27 SDK 里 Swift、Foundation、AppKit、_Concurrency 的接口全是 `Swift::Int`、`Foundation::Date.Foundation::FormatStyle`、`~Swift::Copyable`(SwiftUI 关掉了)。本库一直写 `Swift.Int`。本提案加一个默认关闭的开关,打开后 interface 和 dump 按编译器写接口文件的同一套规则输出。 + +## 方案 + +**规则**(与编译器 `TypePrinter::shouldPrintModuleSelector` / `printQualifiedType` 一致,swift-demangling 与本库的 interface 打印器各实现一份,算法相同): + +- 模块与它限定的名字之间写 `::`。 +- 嵌套类型的每一层都带上**声明它的模块**:最近一层 extension 的模块,没有 extension 就是上下文链根上的模块。于是本模块在 `Swift.Duration` 的 extension 里声明的类型写成 `Swift::Duration.ModuleSelectorFixture::LocalFormat`——这个出处在点号写法里整个丢失。 +- 不加:局部类型(上下文链经过函数、闭包、匿名上下文);类型参数的关联类型 `A.Element`(SE-0491 明文禁止)。 +- 由 C 导入成别的类型成员的类型(`NSAttributedString.Key`,TypeIndexing 给出的 Swift 写法带点号)每一层都带解析出的模块:`Foundation::NSAttributedString.Foundation::Key`,与 SDK 接口相同;`__C` 解析不出真实模块时嵌套层不加选择器。 +- 手写的限定名一起改:`Builtin.`、`Swift.AnyObject`、`~Swift.Copyable` / `~Swift.Escapable`。 + +**开关与接线**: + +- interface:`SwiftDeclarationPrintConfiguration.usesModuleSelectors`(默认关)。节点打印器在创建时从委托读一次,存在打印上下文里,所以同一个打印器的记忆化片段不会混两种写法。CLI `interface --module-selectors`,SwiftSectionKit `InterfaceRequest.usesModuleSelectors`。 +- dump:`DemangleOptions.useModuleSelectors`(swift-demangling 新选项)。CLI `dump --enable-module-selectors`,经 `DemangleOptionGroup` 进 `DumpRequest.demangleOptions`。 +- 不透明类型约束(`some Swift::Collection`)由 provider 拼成文字交回,`OpaqueTypeResolving.opaqueType(forNode:index:)` 因此加了 `usesModuleSelectors` 参数;provider 用来匹配协议事实的名字仍是 `opaqueTypeBuilderOnly` 的点号写法,只有交回的文字换写法。 +- extension 的声明头(`extension Swift::Duration {`)原先直接拿 `ExtensionName.name` 显示——那是按固定预设印出、兼作查找 key 的点号写法。`ExtensionName.print` 加了 `usesModuleSelectors` 参数(默认关),打印头部时按配置传入,`name` 本身不变。这一处是扫漏测试在实现中途抓出来的。 +- `~Swift.Copyable` / `~Swift.Escapable` 不再是写死的文字,而是两个常驻的协议类型节点,交给当前的类型打印器 / resolver 去印,于是自动跟随任何拼写选项,富文本里也成了真正的协议引用。节点必须常驻:interface 打印器按节点地址记忆化片段,临时节点释放后地址复用会串缓存。 + +**不动**:dump 注释里的 ObjC 运行时名字(`-[Swift.__StringStorage characterAtIndex:]`、`ObjC ancestor chain: Swift.__SwiftNativeNSDictionary → …`)——那是运行时给 Swift 类起的类名字符串,原样照抄,不是 Swift 源码里的限定名;查找 key(`Swift.Int` 之类的内部字符串,用固定预设打印,从不带这个选项);ABI diff / snapshot;TypeIndexing(它读 SourceKit 生成的接口,编译器只在写 `.swiftinterface` 时才用模块选择器);RuntimeViewer(选项默认关,加设置项另议)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-10 | Created as Draft:适配 SE-0491,swift-demangling 加一个使用 module selector 的选项 | 用户要求「适配一下这个提案,顺便改一下 swift-demangling,加一个 options 使用 module-selector」 | +| 2026-10-10 | 嵌套类型每一层都带模块(照编译器),不只在最外层 | 用户选定。与 Xcode 27 SDK 接口一致,并保留嵌套类型由哪个模块的 extension 声明的信息 | +| 2026-10-10 | 默认关闭;interface 与 dump 都接 | 打开即改变每一份输出与快照;dump 已有逐个 demangle 选项的 `--enable-/--disable-` 开关,新选项照样接,成本几乎为零 | +| 2026-10-10 | `~Swift.Copyable` 改由类型打印器 / resolver 印协议节点,不在原处按开关二选一 | 拼写从此只有一个来源。代价:开关关闭时,凡显示标准库模块的选项组合文字不变;不显示的(如 `--demangle-options simplified`)从 `~Swift.Copyable` 变成 `~Copyable`,与它对其余标准库名字的写法一致;富文本里它从一个「其他类型名」变成模块 + 协议两段 | +| 2026-10-10 | `OpaqueTypeResolving.opaqueType` 加 `usesModuleSelectors` 参数,不给默认实现 | 解析器角色协议按约定不带默认实现,签名漂移要在编译期暴露;已知实现方只有本库的 provider(RuntimeViewer 只构造它)。若改成让 provider 在构造时自带开关,配置与 provider 会各说各话 | +| 2026-10-10 | 验证 | 新测试 27 个全过,interface 扫漏测试在修 extension 头之前失败;全量 2370 个测试 / 453 个套件只剩本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`;macOS 27 的 libswiftCore / Observation / Synchronization 打开开关后 interface 零残留,dump 只剩注释里的 ObjC 运行时类名;libswiftCore 与 SDK 接口共有的 107 条嵌套类型路径逐层模块一致。渲染 A/B 另记 | diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index cef2f03a5..d7839dd6a 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -52,7 +52,7 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 把 `some P` 的占位还原成带 primary associated type 实参的完整拼写(`some Collection & Sendable`)。领域细节已有两篇专文——[OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md)(descriptor 编码、anchor/塌缩机制、字节级调试)与 [OpaquePrimaryAssociatedTypeAttribution.md](../OpaquePrimaryAssociatedTypeAttribution.md)(提案 0011 的实现说明)——本节只给文件分工: -- **`SwiftInterfaceBuilderOpaqueTypeProvider`**:入口,也是一个 `ExtraDataProvider`(挂到 builder 上,printer 打印 `some` 返回类型时经 `opaqueType(forNode:index:)` 回查)。从符号表定位 opaque type descriptor,把 generic requirements 拆成 superclass 项、协议项与 same-type 项(`some Base & P` 的父类排在组合最前,与编译器 `.swiftinterface` 同形;2026-09-18 之前 superclass 项被 `OpaqueType.requirements(in:)` 与 provider 双双丢弃,`some Base` 打成裸 `some`),逐协议调用归属判定(anchor 直接命中 → refine 闭包 → 名字兜底,兜底四条件缺一不可——宁可少一个实参也不捏造一个)。参数按坐标(深度 + 序号)定位而不是按位置:没有运行时可见约束的参数(`some Sendable` / `some Any` / `some AnyObject`)返回 nil、渲染为裸 `some`,走不到的状态 `#log(.fault)` 加 debug 断言,读取失败 `#log(.error)`(见 [OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md) §1.3、§1.4)。实参与父类这类**完整类型**用去掉 `removeBoundGeneric` 的选项打印,并先剥掉关联类型的协议限定(`Node.strippingAssociatedTypeProtocolQualifiers()`,在 `SwiftDeclarationRendering`)——上游 `NodePrinter` 的 `*BuilderOnly` 选项是给类型名用的,直接拿来打类型会丢泛型实参、多出 `A.Probe.N.A` 这样的限定(同文 §2.3、§4.7)。 +- **`SwiftInterfaceBuilderOpaqueTypeProvider`**:入口,也是一个 `ExtraDataProvider`(挂到 builder 上,printer 打印 `some` 返回类型时经 `opaqueType(forNode:index:usesModuleSelectors:)` 回查;最后一个参数来自打印配置的 `usesModuleSelectors`,为真时交回的文字写成 `some Swift::Collection`,而用来匹配协议事实的名字始终是 `opaqueTypeBuilderOnly` 的点号写法——见提案 [draft-module-selectors](../../Evolutions/draft-module-selectors.md))。从符号表定位 opaque type descriptor,把 generic requirements 拆成 superclass 项、协议项与 same-type 项(`some Base & P` 的父类排在组合最前,与编译器 `.swiftinterface` 同形;2026-09-18 之前 superclass 项被 `OpaqueType.requirements(in:)` 与 provider 双双丢弃,`some Base` 打成裸 `some`),逐协议调用归属判定(anchor 直接命中 → refine 闭包 → 名字兜底,兜底四条件缺一不可——宁可少一个实参也不捏造一个)。参数按坐标(深度 + 序号)定位而不是按位置:没有运行时可见约束的参数(`some Sendable` / `some Any` / `some AnyObject`)返回 nil、渲染为裸 `some`,走不到的状态 `#log(.fault)` 加 debug 断言,读取失败 `#log(.error)`(见 [OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md) §1.3、§1.4)。实参与父类这类**完整类型**用去掉 `removeBoundGeneric` 的选项打印,并先剥掉关联类型的协议限定(`Node.strippingAssociatedTypeProtocolQualifiers()`,在 `SwiftDeclarationRendering`)——上游 `NodePrinter` 的 `*BuilderOnly` 选项是给类型名用的,直接拿来打类型会丢泛型实参、多出 `A.Probe.N.A` 这样的限定(同文 §2.3、§4.7)。 - **`OpaqueSameTypeConstraint`** / **`OpaqueDependentMemberProjection`**:从 requirement 节点里挖出来的单条 same-type 约束(区分正向 pin `τ.Name == X` 与反向 pin `outer == τ.Name`,后者渲染期经 `SubstitutionMap` 回溯)及其解析器。 - **`ProtocolFactsResolver`**:按「可达 descriptor 优先、内置表兜底」的链条解析协议事实(自声明的 associated type 名、refine 闭包),`refineClosureContainsAnchor` 对不完整闭包返回三态(命中 / 完整排除 / `nil` 不可证)。 - **`BuiltinStandardLibraryProtocolFacts`**:冻结的 stdlib 协议表——**primary associated type 名单与顺序的唯一来源**(SE-0346 不留运行时痕迹),也是离线 bind-only 外部协议的兜底。无 associated type 的协议也登记空条目,让归属能说「确定不附着」而非降级。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 529221dfb..85cfc24d9 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2441,6 +2441,25 @@ - **关联文档**:AGENTS.md「Never let a demangle or print hop while you hold a lock」、[ReviewAdjudications A61](ReviewAdjudications.md)、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「包了哪些入口」、[NodeStoreMigrationOpenIssues 第 9 条](NodeStoreMigrationOpenIssues.md)(规则的来历)。 - **对应版本**:下一个版本(未发版)。 +## 2026-10-10 适配 SE-0491:模块选择器写法(节号落地时分配) + +- **时间段**:2026-10-10。 +- **动机**:SE-0491(Swift 6.3)加了 `Module::Name` 写法;Swift 6.4 编译器写 `.swiftinterface` 默认就用它,Xcode 27 SDK 里 Swift、Foundation、AppKit、_Concurrency 的接口全是 `Swift::Int`、`Foundation::Date.Foundation::FormatStyle`。二进制里没有新东西,影响只在名字怎么写。用户:「适配一下这个提案,顺便改一下 swift-demangling,加一个 options 使用 module-selector」。 +- **关键决策**: + - 两边各加一个默认关闭的开关:swift-demangling 的 `DemangleOptions.useModuleSelectors`(不进任何预设),本库 interface 的 `SwiftDeclarationPrintConfiguration.usesModuleSelectors`;CLI `interface --module-selectors`、`dump --enable-module-selectors`。 + - 规则照编译器:嵌套类型每一层都带声明它的模块(最近的 extension 的模块,否则上下文链根上的模块),局部类型与 `A.Element` 不加;用户选了「每层都带」而不是「只在最外层」。由 C 导入成成员的类型同样逐层带解析出的模块。 + - `~Swift.Copyable` / `~Swift.Escapable` 改由类型打印器 / resolver 印常驻的协议节点,不再写死文字。开关关闭时,显示标准库模块的选项组合文字不变;`simplified` 这类不显示的变成 `~Copyable`。 + - `OpaqueTypeResolving.opaqueType` 加 `usesModuleSelectors` 参数(不给默认实现,按角色协议的约定);provider 匹配协议事实的名字仍是点号写法。 + - 扫漏测试在实现中途抓出 extension 声明头直接显示查找 key(`ExtensionName.name`);`ExtensionName.print` 加参数修掉。dump 注释里 ObjC 运行时给 Swift 类起的名字(`-[Swift.__StringStorage …]`)是运行时字符串,原样保留。 +- **落地模块**:swift-demangling(`DemangleOptions`、`NodePrinter`);SwiftPrinting(配置、委托、四个节点打印器的上下文、`TypeNodePrintable`、`DependentGenericNodePrintable`、extension 头);SwiftDeclarationRendering(`InvertibleProtocolSet` 的协议节点与 resolver 版本的打印);SwiftDeclaration(`ExtensionName.print`);SwiftDump(三个 dumper 的调用点);SwiftInterface(opaque provider);SwiftSectionKit(`InterfaceRequest.usesModuleSelectors`);swift-section(两个开关)。测试支持新增 `ModuleSelectorFixture`(现场编译,任何 Swift 6.2+ 工具链都能编,CI 不跳过)。 +- **验证**: + - swift-demangling:新测试在只加选项声明时 26 处失败、实现后全过;全量 624 个测试通过,原始退出码 0(含逐字节对照官方 demangler 的语料测试)。 + - 本库:新增 `ModuleSelectorInterfaceTests`、`ModuleSelectorDumpTests` 与两条 CLI 映射测试,27 个测试全过;interface 的扫漏测试在修 extension 头之前失败。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,依赖为远端发布版,只有 swift-demangling 指本分支、swift-semantic-string 指本地 `next`):2370 个测试 / 453 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`,另有登记过的 known issue。 + - 真实系统库(macOS 27,当前系统 cache):libswiftCore、libswiftObservation、libswiftSynchronization 的 interface 与 dump 打开开关后扫漏,interface 零残留;dump 只剩注释里的 ObjC 运行时类名。libswiftCore 与 SDK `Swift.swiftinterface` 共有的 107 条嵌套类型路径,逐层模块全部一致。 + - 渲染 A/B:见下方补记。 +- **关联文档**:[draft-module-selectors](../Evolutions/draft-module-selectors.md)、swift-demangling 提案 `draft-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 +- **对应版本**:0.22.0 之后(未发版);依赖 swift-demangling 发版(新选项)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/README.md b/Documentations/README.md index 8abaf62bb..5dde3d50b 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -168,6 +168,7 @@ selects names using each access's offset and width. | [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | | [Evolutions/0063-private-declarations.md](Evolutions/0063-private-declarations.md) | **提案 0063(Implemented)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | +| [Evolutions/draft-module-selectors.md](Evolutions/draft-module-selectors.md) | **提案 draft(In Progress)**:适配 SE-0491 模块选择器——默认关闭的开关(interface 的 `usesModuleSelectors` / `--module-selectors`,dump 的 swift-demangling 新选项 `useModuleSelectors` / `--enable-module-selectors`),打开后照 Swift 6.4 编译器写 `.swiftinterface` 的规则输出 `Swift::Int`,嵌套类型每层带声明它的模块(`Swift::Duration.Foundation::TimeFormatStyle`),局部类型与 `A.Element` 不加。`~Swift.Copyable` 改由类型打印器印协议节点;`OpaqueTypeResolving.opaqueType` 加参数。 | | [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/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index cfdd53164..af63329c8 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -57,6 +57,9 @@ public struct InterfaceRequest: Sendable, Equatable { /// alone (no symbol behind it) prints as `override`. The tie is recorded /// either way. public var infersObjCOverridesFromSelectorNames: Bool + /// Names qualified with SE-0491 module selectors (`Swift::Int`), as a + /// Swift 6.4 `.swiftinterface` spells them. + public var usesModuleSelectors: Bool /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool @@ -78,6 +81,7 @@ public struct InterfaceRequest: Sendable, Equatable { printsExportedDeclarationsOnly: Bool = false, memberSortOrder: SwiftDeclarationMemberSortOrder = .byCategory, infersObjCOverridesFromSelectorNames: Bool = false, + usesModuleSelectors: Bool = false, emitsHeader: Bool = false, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output @@ -96,6 +100,7 @@ public struct InterfaceRequest: Sendable, Equatable { self.printsExportedDeclarationsOnly = printsExportedDeclarationsOnly self.memberSortOrder = memberSortOrder self.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames + self.usesModuleSelectors = usesModuleSelectors self.emitsHeader = emitsHeader self.commentTransformers = commentTransformers self.destination = destination @@ -131,6 +136,7 @@ public struct InterfaceRequest: Sendable, Equatable { // The index records the name-only ObjC tie either way; this decides // whether it prints as `@objc override`. printConfiguration.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames + printConfiguration.usesModuleSelectors = usesModuleSelectors var configuration = SwiftInterfaceBuilderConfiguration( indexConfiguration: .init( diff --git a/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift b/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift index 449d7a4c5..9dc4d1765 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift @@ -8,19 +8,23 @@ public struct ExtensionName: DefinitionName, Hashable, Sendable { public let kind: ExtensionKind + /// The extended type's name as an extension header spells it — with + /// SE-0491 module selectors (`Swift::Duration`) when `usesModuleSelectors` + /// is set. `name` itself stays dotted: it is also a lookup key. @SemanticStringBuilder - public func print() -> SemanticString { + public func print(usesModuleSelectors: Bool = false) -> SemanticString { + let printedName = usesModuleSelectors ? name(using: DemangleOptions.interfaceTypeBuilderOnly.union(.useModuleSelectors)) : name switch kind { case .type(.enum): - TypeDeclaration(kind: .enum, name) + TypeDeclaration(kind: .enum, printedName) case .type(.struct): - TypeDeclaration(kind: .struct, name) + TypeDeclaration(kind: .struct, printedName) case .type(.class): - TypeDeclaration(kind: .class, name) + TypeDeclaration(kind: .class, printedName) case .protocol: - TypeDeclaration(kind: .protocol, name) + TypeDeclaration(kind: .protocol, printedName) case .typeAlias: - TypeDeclaration(kind: .other, name) + TypeDeclaration(kind: .other, printedName) } } } diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 7d9c0c0e6..942018a69 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -62,6 +62,9 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(name: .customLong("exported-only"), help: "Print only the declarations the image exports: types and protocols whose descriptor symbol has an export-trie entry, extensions targeting them, and members with at least one exported symbol (dispatch-thunk and other derived forms included). `override` / `@objc` members and anything without export evidence are kept.") var exportedOnly: Bool = false + @Flag(name: .customLong("module-selectors"), help: "Qualify names with SE-0491 module selectors (Swift::Int instead of Swift.Int), the way the Swift 6.4 compiler writes a .swiftinterface. Every type level carries the module that declared it (Swift::Duration.Foundation::TimeFormatStyle).") + var moduleSelectors: Bool = false + @Option(name: .shortAndLong, help: "The color scheme for the output.") var colorScheme: SemanticColorScheme = .none @@ -82,6 +85,7 @@ struct InterfaceCommand: AsyncParsableCommand { printsExportedDeclarationsOnly: exportedOnly, memberSortOrder: sortMembersByOffset ? .byOffset : .byCategory, infersObjCOverridesFromSelectorNames: objcMemberOptions.infersOverridesFromSelectorNames, + usesModuleSelectors: moduleSelectors, emitsHeader: emitHeader, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output diff --git a/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift b/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift index fa9ea78e3..694201a63 100644 --- a/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift +++ b/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift @@ -66,6 +66,8 @@ struct DemangleOptionGroup: ParsableArguments, Sendable { var showClosureSignature: Bool? @Flag(inversion: .prefixedEnableDisable) var showModuleInDependentMemberType: Bool? + @Flag(inversion: .prefixedEnableDisable, help: "Qualify names with SE-0491 module selectors (Swift::Int instead of Swift.Int); every type level carries the module that declared it.") + var moduleSelectors: Bool? func buildSwiftDumpDemangleOptions() -> SwiftDump.DemangleOptions { var options = demangleOptions.options @@ -135,6 +137,9 @@ struct DemangleOptionGroup: ParsableArguments, Sendable { if let showModuleInDependentMemberType { options = options.update(.showModuleInDependentMemberType, enabled: showModuleInDependentMemberType) } + if let moduleSelectors { + options = options.update(.useModuleSelectors, enabled: moduleSelectors) + } return options } } diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift index b2c751dc2..375e8c72d 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift @@ -259,7 +259,7 @@ extension GenericRequirementDescriptor { case .conformance /* (let protocolConformanceDescriptor) */: Error("SwiftDumpConformance") case .invertedProtocols(let invertedProtocols): - invertedProtocols.protocols.dumpInvertedProtocolNames + try await invertedProtocols.protocols.dumpInvertedProtocolNames(builder: builder) } } } @@ -362,7 +362,7 @@ extension GenericRequirementDescriptor { case .conformance /* (let protocolConformanceDescriptor) */: Standard("SwiftDumpConformance") case .invertedProtocols(let invertedProtocols): - invertedProtocols.protocols.dumpInvertedProtocolNames + try await invertedProtocols.protocols.dumpInvertedProtocolNames(builder: builder) } } } @@ -381,30 +381,55 @@ extension InvertibleProtocolSet { hasCopyable || hasEscapable } - /// Dump the inverted protocol names (e.g., `~Swift.Copyable`, `~Swift.Escapable`). + /// `Swift.Copyable` and `Swift.Escapable` as the type nodes a suppressed + /// conformance names. They print through the caller's resolver like any + /// other protocol reference, so they are spelled the way the names around + /// them are — `Swift::Copyable` under module selectors (evolution proposal + /// `module-selectors`) — rather than as text fixed here. + /// + /// One long-lived instance each: the interface printer memoizes a printed + /// fragment by node identity, and a node freed after one print would hand + /// its fragment to whatever is allocated at its address next. + package static let copyableProtocolTypeNode = invertibleProtocolTypeNode(named: "Copyable") + package static let escapableProtocolTypeNode = invertibleProtocolTypeNode(named: "Escapable") + + private static func invertibleProtocolTypeNode(named name: String) -> Node { + Node.create(kind: .type, child: Node.create(kind: .protocol, children: [ + Node.create(kind: .module, text: stdlibName), + Node.create(kind: .identifier, text: name), + ])) + } + + /// Dump the inverted protocol names (e.g., `~Swift.Copyable`, `~Swift.Escapable`), + /// each protocol spelled by `builder`. @SemanticStringBuilder - package var dumpInvertedProtocolNames: SemanticString { + package func dumpInvertedProtocolNames(@SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { if hasCopyable && hasEscapable { Standard("~") - TypeName(kind: .other, "Swift.Copyable") + try await builder(Self.copyableProtocolTypeNode) Standard(" & ~") - TypeName(kind: .other, "Swift.Escapable") + try await builder(Self.escapableProtocolTypeNode) } else if hasCopyable { Standard("~") - TypeName(kind: .other, "Swift.Copyable") + try await builder(Self.copyableProtocolTypeNode) } else if hasEscapable { Standard("~") - TypeName(kind: .other, "Swift.Escapable") + try await builder(Self.escapableProtocolTypeNode) } } + /// Dump the inverted protocol names, each protocol spelled by `resolver`. + package func dumpInvertedProtocolNames(resolver: DemangleResolver) async throws -> SemanticString { + try await dumpInvertedProtocolNames { try await resolver.resolve(for: $0) } + } + /// Dump the inverted protocols as an inheritance clause with colon prefix (e.g., `: ~Swift.Copyable`). @SemanticStringBuilder - package var dumpInvertedProtocolsInheritance: SemanticString { + package func dumpInvertedProtocolsInheritance(resolver: DemangleResolver) async throws -> SemanticString { if hasInvertedProtocols { Standard(":") Space() - dumpInvertedProtocolNames + try await dumpInvertedProtocolNames(resolver: resolver) } } } diff --git a/Sources/Output/SwiftDump/Dumper/ClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift index be06afd95..60c18fe44 100644 --- a/Sources/Output/SwiftDump/Dumper/ClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift @@ -127,7 +127,7 @@ package struct ClassDumper: TypedDumper { if hasInvertedProtocols { Standard(",") Space() - dumped.invertibleProtocolSet!.dumpInvertedProtocolNames + try await dumped.invertibleProtocolSet!.dumpInvertedProtocolNames(resolver: demangleResolver) } } else if let resilientSuperclass = dumped.resilientSuperclass, let kind = dumped.descriptor.resilientSuperclassReferenceKind, let superclass = try await resilientSuperclass.dumpSuperclass(resolver: demangleResolver, for: kind, in: machO.context) { Standard(":") @@ -136,10 +136,10 @@ package struct ClassDumper: TypedDumper { if hasInvertedProtocols { Standard(",") Space() - dumped.invertibleProtocolSet!.dumpInvertedProtocolNames + try await dumped.invertibleProtocolSet!.dumpInvertedProtocolNames(resolver: demangleResolver) } } else if hasInvertedProtocols { - dumped.invertibleProtocolSet!.dumpInvertedProtocolsInheritance + try await dumped.invertibleProtocolSet!.dumpInvertedProtocolsInheritance(resolver: demangleResolver) } } } diff --git a/Sources/Output/SwiftDump/Dumper/EnumDumper.swift b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift index 611f1c200..a54047563 100644 --- a/Sources/Output/SwiftDump/Dumper/EnumDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift @@ -57,11 +57,11 @@ package struct EnumDumper: TypedDumper { let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(.enum(dumped.descriptor)), in: machO.context) try await genericContext.dumpGenericSignature(resolver: demangleResolver, depthLayout: depthLayout, in: machO.context) { if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { - invertibleProtocolSet.dumpInvertedProtocolsInheritance + try await invertibleProtocolSet.dumpInvertedProtocolsInheritance(resolver: demangleResolver) } } } else if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { - invertibleProtocolSet.dumpInvertedProtocolsInheritance + try await invertibleProtocolSet.dumpInvertedProtocolsInheritance(resolver: demangleResolver) } } } diff --git a/Sources/Output/SwiftDump/Dumper/StructDumper.swift b/Sources/Output/SwiftDump/Dumper/StructDumper.swift index c4159f473..35d0bf843 100644 --- a/Sources/Output/SwiftDump/Dumper/StructDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/StructDumper.swift @@ -59,11 +59,11 @@ package struct StructDumper: TypedDumper { let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: .type(.struct(dumped.descriptor)), in: machO.context) try await genericContext.dumpGenericSignature(resolver: demangleResolver, depthLayout: depthLayout, in: machO.context) { if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { - invertibleProtocolSet.dumpInvertedProtocolsInheritance + try await invertibleProtocolSet.dumpInvertedProtocolsInheritance(resolver: demangleResolver) } } } else if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { - invertibleProtocolSet.dumpInvertedProtocolsInheritance + try await invertibleProtocolSet.dumpInvertedProtocolsInheritance(resolver: demangleResolver) } } } diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift index a61ae216d..a74fbf59a 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift @@ -77,11 +77,18 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider DemangleOptions { + usesModuleSelectors ? options.union(.useModuleSelectors) : options + } + public init(machO: MachO) { self.machO = machO } - public func opaqueType(forNode node: Node, index: Int?) async -> String? { + public func opaqueType(forNode node: Node, index: Int?, usesModuleSelectors: Bool) async -> String? { do { @Dependency(\.symbolIndexStore) var symbolIndexStore @@ -133,13 +140,17 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider`, // the generics book's own example) is what lands // here; its mangling qualifies every step with its // declaring protocol, and the upstream printer // would spell that out as `A.Probe.N.A.Probe.N.A`. - await primaryAssociatedTypes.append(substitutionMap.rootOriginal(for: substitutionNode).strippingAssociatedTypeProtocolQualifiers().print(using: Self.typeSpellingOptions)) + await primaryAssociatedTypes.append(substitutionMap.rootOriginal(for: substitutionNode).strippingAssociatedTypeProtocolQualifiers().print(using: Self.outputOptions(Self.typeSpellingOptions, usesModuleSelectors: usesModuleSelectors))) } } result.write("<") diff --git a/Sources/Output/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift index 5e1df2e0a..ac7e2d792 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift @@ -1,4 +1,6 @@ import SwiftDeclaration +import SwiftDeclarationRendering +import MachOSwiftSection import Demangling /// The slice of printer state the dependent-generic layer reads and writes. @@ -320,10 +322,13 @@ extension DependentGenericNodePrintable { mutating func printDependentGenericInverseConformanceRequirement(_ name: Node) async { await printFirstChild(name, suffix: ": ~") + // Printed as protocol references, so they take this printer's + // qualification like any other name (`~Swift::Copyable` under module + // selectors) and reach a rich target as the protocols they are. switch name.children.at(1)?.index { - case 0: target.write("Swift.Copyable", context: .context(state: .printType)) - case 1: target.write("Swift.Escapable", context: .context(state: .printType)) - default: target.write("Swift.") + case 0: await printName(InvertibleProtocolSet.copyableProtocolTypeNode) + case 1: await printName(InvertibleProtocolSet.escapableProtocolTypeNode) + default: target.write("Swift\(context.usesModuleSelectors ? "::" : ".")") } } } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift index 26f7d531f..49c11c3b1 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift @@ -40,6 +40,8 @@ protocol InterfaceNodePrintable: NodePrintable, BoundGenericNodePrintable, TypeN struct InterfaceNodePrinterContext: InterfaceNodePrintableContext, MemberDeclarationNodePrintableContext { var dependentMemberTypeDepth = 0 + var usesModuleSelectors = false + /// How many `repeat` patterns enclose the node being printed. `each` is /// only ever written inside one. var packExpansionDepth = 0 diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift index 624a49c26..533ca1da5 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift @@ -20,6 +20,11 @@ protocol NodePrintableContext { /// context (`A.Element`, not `A.Swift.Sequence.Element`); see /// `shouldPrintContext()`. var dependentMemberTypeDepth: Int { get } + + /// Qualify names with SE-0491 module selectors (`Swift::Int`). Fixed for + /// a printer's lifetime — it is read from the delegate when the printer + /// is created — so a memoized fragment never mixes the two spellings. + var usesModuleSelectors: Bool { get } } /// Per-call hints for one `printName`. @@ -159,17 +164,23 @@ extension NodePrintable { /// the sibling identifier may be rewritten to its Swift spelling too. @discardableResult mutating func printModule(_ node: Node, siblingIdentifier: String? = nil) async -> Bool { - var moduleName = node.text ?? "" - var resolvedCImportedModule = false + let moduleName = await resolvedModuleName(of: node, siblingIdentifier: siblingIdentifier) + target.write(moduleName.text, context: .context(for: node, state: .printModule)) + return moduleName.isResolvedCImportedModule + } + + /// The module a `module` node names, with a C-imported module spelling + /// (`__C` / `__ObjC`) resolved to its real module through the delegate + /// when the sibling identifier finds one. + func resolvedModuleName(of node: Node, siblingIdentifier: String?) async -> (text: String, isResolvedCImportedModule: Bool) { + let moduleName = node.text ?? "" if moduleName == objcModule || moduleName == cModule, let identifier = siblingIdentifier, let delegate, let updatedModuleName = await or(await delegate.moduleName(forTypeName: identifier), await delegate.moduleName(forTypeName: identifier.strippedRefSuffix)) { - moduleName = updatedModuleName - resolvedCImportedModule = true + return (updatedModuleName, true) } - target.write(moduleName, context: .context(for: node, state: .printModule)) - return resolvedCImportedModule + return (moduleName, false) } mutating func printIdentifier(_ node: Node, parentKind: Node.Kind? = nil) async { diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift index dca3c771a..6e448b2dc 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift @@ -9,9 +9,13 @@ import Demangling protocol NodePrintableDelegate: AnyObject, Sendable { func moduleName(forTypeName typeName: String) async -> String? func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? - func opaqueType(forNode node: Node, index: Int?) async -> String? + func opaqueType(forNode node: Node, index: Int?, usesModuleSelectors: Bool) async -> String? /// Whether what `opaqueType(forNode:index:)` supplies is to be marked as /// visible only with opaque type resolution on (see /// `SwiftDeclarationPrintConfiguration.marksOptionalContent`). var marksOptionalContent: Bool { get } + /// Whether names are qualified with SE-0491 module selectors (see + /// `SwiftDeclarationPrintConfiguration.usesModuleSelectors`). A printer + /// reads it once, when it is created. + var usesModuleSelectors: Bool { get } } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift index ffaa82997..b47edae34 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift @@ -47,5 +47,8 @@ public protocol CImportedNameResolving: TypeNameResolving { /// Expands an opaque return type (`some P`) from its descriptor's generic /// requirements. public protocol OpaqueTypeResolving: TypeNameResolving { - func opaqueType(forNode node: Node, index: Int?) async -> String? + /// The constraint text after `some`, its names qualified with SE-0491 + /// module selectors (`Swift::Collection`) when + /// `usesModuleSelectors` is set, as the rest of the print is. + func opaqueType(forNode node: Node, index: Int?, usesModuleSelectors: Bool) async -> String? } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index d3348b95c..722a620fd 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -25,9 +25,9 @@ extension TypeNodePrintable { .unmanaged: await printFirstChild(name) case .builtinTypeName: - target.write(name.text ?? "", context: .context(for: name, state: .printType)) + target.write(builtinTypeNameSpelling(name.text ?? ""), context: .context(for: name, state: .printType)) case .builtinTupleType: - target.write("Builtin.TheTupleType", context: .context(for: name, state: .printType)) + target.write(builtinTypeNameSpelling("Builtin.TheTupleType"), context: .context(for: name, state: .printType)) case .enum, .structure, .class, @@ -78,7 +78,7 @@ extension TypeNodePrintable { // a type printer does not handle — so delegate whole, exactly as // `printOpaqueType` does, instead of printing children into an // empty `<>`. - target.write(await name.print(using: .default), context: .context(for: name, state: .printType)) + target.write(await name.print(using: delegatedPrintOptions), context: .context(for: name, state: .printType)) case .opaqueType: await printOpaqueType(name) case .symbolicExtendedExistentialType: @@ -91,7 +91,7 @@ extension TypeNodePrintable { mutating func printOpaqueReturnType(_ node: Node) async { target.write("some", context: .context(for: node, state: .printKeyword)) - if let targetNode = context.targetNode, let opaqueType = await delegate?.opaqueType(forNode: targetNode, index: node.first(of: .opaqueReturnTypeIndex)?.index?.int) { + if let targetNode = context.targetNode, let opaqueType = await delegate?.opaqueType(forNode: targetNode, index: node.first(of: .opaqueReturnTypeIndex)?.index?.int, usesModuleSelectors: context.usesModuleSelectors) { let constraintStart = target.writtenUnitCount target.writeSpace() target.write(opaqueType) @@ -146,7 +146,23 @@ extension TypeNodePrintable { target.write(text, context: .context(for: name, state: .printType)) return } - target.write(await name.print(using: .default), context: .context(for: name, state: .printType)) + target.write(await name.print(using: delegatedPrintOptions), context: .context(for: name, state: .printType)) + } + + /// The options a node handed whole to the upstream `NodePrinter` prints + /// with — `.default`, plus module selectors when this printer uses them. + var delegatedPrintOptions: DemangleOptions { + context.usesModuleSelectors ? DemangleOptions.default.union(.useModuleSelectors) : .default + } + + /// A builtin type's name, which the demangler builds whole + /// (`Builtin.RawPointer`), with its qualifier spelled as a module selector + /// (`Builtin::RawPointer`) when this printer uses them — the compiler's + /// own spelling in a `.swiftinterface`. + func builtinTypeNameSpelling(_ text: String) -> String { + let dottedQualifier = "Builtin." + guard context.usesModuleSelectors, text.hasPrefix(dottedQualifier) else { return text } + return "Builtin::" + text.dropFirst(dottedQualifier.count) } mutating func printType(_ name: Node) async { @@ -165,16 +181,22 @@ extension TypeNodePrintable { let isLocalType = name.localTypeNaming != nil var resolvedCImportedModule = false + var resolvedCImportedModuleName: String? if shouldPrintContext(), !isLocalType { let writtenUnitCountBeforeContext = target.writtenUnitCount if contextNode.kind == .module { let siblingIdentifier = name.children.at(1)?.text - resolvedCImportedModule = await printModule(contextNode, siblingIdentifier: siblingIdentifier) - // The module→type dot stays inside this leaf's scope so a - // fully-qualified top-level name (`AppKit.MenuItem`) selects - // as one span. + let moduleName = await resolvedModuleName(of: contextNode, siblingIdentifier: siblingIdentifier) + resolvedCImportedModule = moduleName.isResolvedCImportedModule + if resolvedCImportedModule { + resolvedCImportedModuleName = moduleName.text + } + target.write(moduleName.text, context: .context(for: contextNode, state: .printModule)) + // The module→type separator stays inside this leaf's scope so + // a fully-qualified top-level name (`AppKit.MenuItem`) + // selects as one span. if target.writtenUnitCount != writtenUnitCountBeforeContext { - target.write(".") + target.write(context.usesModuleSelectors ? "::" : ".") } } else { await printName(contextNode, options: NodePrintOptions(asPrefixContext: true)) @@ -187,6 +209,7 @@ extension TypeNodePrintable { target.pushTypeReferenceScope(nil) target.write(".") target.popTypeReferenceScope() + await printModuleSelector(ofNestedType: name) } } } @@ -213,7 +236,22 @@ extension TypeNodePrintable { let identifierText = declarationName.text, let delegate, let swiftSpelling = await delegate.swiftName(forCName: identifierText, category: CImportedTypeNameCategory(nodeKind: name.kind)) { - target.write(swiftSpelling, context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) + if context.usesModuleSelectors, let resolvedCImportedModuleName, swiftSpelling.contains(".") { + // Imported as a member (`NSAttributedString.Key`): + // every level carries the module, as the compiler + // writes it (`Foundation::NSAttributedString.Foundation::Key`). + let components = swiftSpelling.split(separator: ".", omittingEmptySubsequences: false) + for (componentIndex, component) in components.enumerated() { + if componentIndex > 0 { + target.write(".") + target.write(resolvedCImportedModuleName, context: .context(for: contextNode, state: .printModule)) + target.write("::") + } + target.write(String(component), context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) + } + } else { + target.write(swiftSpelling, context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) + } } else { await printIdentifier(declarationName, parentKind: name.kind) } @@ -227,6 +265,27 @@ extension TypeNodePrintable { } } + /// Writes the module selector a nested type's own name carries — the + /// `Foundation::` of `Swift::Duration.Foundation::TimeFormatStyle` — when + /// this printer uses module selectors. The compiler writes one on every + /// type it qualifies, parent printed or not + /// (`TypePrinter::printQualifiedType`), since an extension in another + /// module can declare a nested type its parent's module knows nothing + /// about. + /// + /// Written inside the nested type's own reference scope, after the + /// separator dot, the way a top-level type's module is. Nothing is written + /// for a type inside a function or closure (a module selector skips local + /// scopes, so the compiler writes none either), nor for a C-imported + /// module spelling that does not resolve to a real module. + mutating func printModuleSelector(ofNestedType name: Node) async { + guard context.usesModuleSelectors, let module = name.declaringModuleForModuleSelector else { return } + let moduleName = await resolvedModuleName(of: module, siblingIdentifier: name.children.at(1)?.text) + guard !moduleName.text.isEmpty, moduleName.text != objcModule, moduleName.text != cModule else { return } + target.write(moduleName.text, context: .context(for: module, state: .printModule)) + target.write("::") + } + mutating func printTypeList(_ name: Node) async { await printChildren(name) } @@ -315,7 +374,7 @@ extension TypeNodePrintable { await printChildren(protocolsTypeList, suffix: " & ", separator: " & ") } target.write("Swift", context: .context(for: name, state: .printModule)) - target.write(".") + target.write(context.usesModuleSelectors ? "::" : ".") target.write("AnyObject", context: .context(for: name, parentKind: .protocol, state: .printIdentifier)) } @@ -352,3 +411,43 @@ extension TypeNodePrintable { } } } + +extension Node { + /// The `module` node naming the module that declared this nested type + /// declaration: the module of the nearest enclosing extension, else the + /// module at the root of its context chain — `nil` once the chain leaves + /// types and extensions (a function, closure or anonymous context), and + /// for anything but a type declaration, which carries no module selector + /// of its own. The same rule as the `useModuleSelectors` option of + /// swift-demangling's `NodePrinter`. + /// + /// Iterative: the chain is as long as the nesting, and this walk sits + /// outside the depth-checked `printName` recursion. + fileprivate var declaringModuleForModuleSelector: Node? { + switch kind { + case .class, .structure, .enum, .protocol, .otherNominalType, .typeAlias: + break + default: + return nil + } + var context = children.first + while let current = context { + switch current.kind { + case .module: + return current + case .extension: + guard let extensionModule = current.children.first, extensionModule.kind == .module else { return nil } + return extensionModule + case .type, + .class, .structure, .enum, .protocol, .otherNominalType, .typeAlias, + .boundGenericClass, .boundGenericStructure, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias: + // A type's first child is the type it wraps; a nominal's is its + // own context; a bound generic's is its unbound type. + context = current.children.first + default: + return nil + } + } + return nil + } +} diff --git a/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift index 9b04c5123..9c73d507d 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift @@ -33,6 +33,7 @@ struct FunctionNodePrinter: MemberDeclarationNodePrin self.isClassMember = isClassMember self.isFinal = isFinal self.delegate = delegate + context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false } mutating func printDeclaration(_ node: Node) async throws { diff --git a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift index f4f6960f7..ef1afe9c3 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift @@ -39,6 +39,7 @@ struct SubscriptNodePrinter: MemberDeclarationNodePri self.hasSetter = hasSetter self.indentation = indentation self.delegate = delegate + context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false } mutating func printDeclaration(_ node: Node) async throws { diff --git a/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift index 5650aee52..511af4da7 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift @@ -16,6 +16,7 @@ struct TypeNodePrinter: InterfaceNodePrintable { init(delegate: (any NodePrintableDelegate)? = nil, isProtocol: Bool = false) { self.delegate = delegate + context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.isProtocol = isProtocol } diff --git a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift index 32146f0c5..4a22f34a5 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift @@ -42,6 +42,7 @@ struct VariableNodePrinter: MemberDeclarationNodePrin self.hasSetter = hasSetter self.indentation = indentation self.delegate = delegate + context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false } mutating func printDeclaration(_ node: Node) async throws { diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index 22d418c63..c0c454a5e 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -56,6 +56,18 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { /// ever supplies an override — a method no ancestor implements is left /// alone, so this can never invent an `@objc(name)`. public var infersObjCOverridesFromSelectorNames: Bool = false + + /// Qualify names with SE-0491 module selectors — `Swift::Int` instead of + /// `Swift.Int` — as the Swift 6.4 compiler does when it writes a + /// `.swiftinterface` (evolution proposal `module-selectors`). Every type + /// level carries the module that declared it, so a type another module + /// adds in an extension says where it comes from + /// (`Swift::Duration.Foundation::TimeFormatStyle`); a local type and the + /// associated type of a type parameter (`A.Element`) carry none. + /// + /// Off by default, and off the output is unchanged byte for byte. + public var usesModuleSelectors: Bool = false + public var memberSortOrder: SwiftDeclarationMemberSortOrder = .byCategory public var printTypeLayout: Bool = false public var printEnumLayout: Bool = false diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 3c31e3454..f75937841 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -105,11 +105,11 @@ extension SwiftDeclarationPrinter { let depthLayout = GenericParameterDepthLayout.make(for: genericContext, ownedBy: descriptorWrapper, in: machO.context) try await genericContext.dumpGenericSignature(resolver: resolver, depthLayout: depthLayout, in: machO.context) { if let invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { - invertibleProtocolSet.dumpInvertedProtocolsInheritance + try await invertibleProtocolSet.dumpInvertedProtocolsInheritance(resolver: resolver) } } } else if let invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { - invertibleProtocolSet.dumpInvertedProtocolsInheritance + try await invertibleProtocolSet.dumpInvertedProtocolsInheritance(resolver: resolver) } } @@ -151,7 +151,7 @@ extension SwiftDeclarationPrinter { if hasInvertedProtocols { Standard(",") Space() - dumped.invertibleProtocolSet!.dumpInvertedProtocolNames + try await dumped.invertibleProtocolSet!.dumpInvertedProtocolNames(resolver: resolver) } } else if let resilientSuperclass = dumped.resilientSuperclass, let kind = dumped.descriptor.resilientSuperclassReferenceKind, let superclass = try await resilientSuperclass.dumpSuperclass(resolver: resolver, for: kind, in: machO.context) { Standard(":") @@ -160,10 +160,10 @@ extension SwiftDeclarationPrinter { if hasInvertedProtocols { Standard(",") Space() - dumped.invertibleProtocolSet!.dumpInvertedProtocolNames + try await dumped.invertibleProtocolSet!.dumpInvertedProtocolNames(resolver: resolver) } } else if hasInvertedProtocols { - dumped.invertibleProtocolSet!.dumpInvertedProtocolsInheritance + try await dumped.invertibleProtocolSet!.dumpInvertedProtocolsInheritance(resolver: resolver) } } @@ -511,13 +511,15 @@ extension SwiftDeclarationPrinter { /// source names — or a type nested in one — keeps its position-based name /// in full, `Holder.(Visitor in $1a2b3c)`: printed like any other name it /// would read `Holder.Visitor`, a member type the source never declared, - /// and alike for every unnamed `Visitor` of `Holder`. + /// and alike for every unnamed `Visitor` of `Holder`. Both spellings carry + /// module selectors when the configuration asks for them. @SemanticStringBuilder package func renderExtendedTypeName(_ extensionName: ExtensionName) -> SemanticString { if spellsPositionNamedLocalType(extensionName.node) { - TypeDeclaration(kind: extensionName.kind.semanticTypeKind, extensionName.name(using: DemangleOptions.interfaceTypeBuilderOnly.union(.showPrivateDiscriminators))) + let positionBasedNameOptions = DemangleOptions.interfaceTypeBuilderOnly.union(.showPrivateDiscriminators) + TypeDeclaration(kind: extensionName.kind.semanticTypeKind, extensionName.name(using: configuration.usesModuleSelectors ? positionBasedNameOptions.union(.useModuleSelectors) : positionBasedNameOptions)) } else { - extensionName.print() + extensionName.print(usesModuleSelectors: configuration.usesModuleSelectors) } } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 3f0e57c40..a42868630 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -1020,10 +1020,18 @@ extension SwiftDeclarationPrinter: NodePrintableDelegate { } public func opaqueType(forNode node: Node, index: Int?) async -> String? { - await typeNameResolverRegistry.opaqueTypeResolvers.asyncFirstNonNil { await $0.opaqueType(forNode: node, index: index) } + await opaqueType(forNode: node, index: index, usesModuleSelectors: configuration.usesModuleSelectors) + } + + public func opaqueType(forNode node: Node, index: Int?, usesModuleSelectors: Bool) async -> String? { + await typeNameResolverRegistry.opaqueTypeResolvers.asyncFirstNonNil { await $0.opaqueType(forNode: node, index: index, usesModuleSelectors: usesModuleSelectors) } } var marksOptionalContent: Bool { configuration.marksOptionalContent } + + var usesModuleSelectors: Bool { + configuration.usesModuleSelectors + } } diff --git a/Sources/TestSupport/MachOTestingSupport/ModuleSelectorFixture.swift b/Sources/TestSupport/MachOTestingSupport/ModuleSelectorFixture.swift new file mode 100644 index 000000000..5102fd3a9 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/ModuleSelectorFixture.swift @@ -0,0 +1,176 @@ +import Foundation +import MachOKit +import MachOFoundation +import Testing + +/// An on-the-fly fixture for the SE-0491 module-selector spelling (evolution +/// proposal `module-selectors`): one reference of every shape the selector +/// rules treat differently. +/// +/// - `Outer.Inner`, a type nested in a type of this module: every level +/// carries `ModuleSelectorFixture::`. +/// - `Duration.LocalFormat`, a type this module declares in an extension of +/// the standard library's `Duration`: the parent is `Swift::`, the nested +/// type names the module whose extension declared it — the case where the +/// two levels differ and the dotted spelling loses where the type is from. +/// - `Dictionary.Index` and `Box.Slot`, types nested in a +/// bound generic type. +/// - `any Marker & AnyObject`, whose `AnyObject` the printer spells itself. +/// - `some Collection`, the opaque type constraint the opaque type +/// provider spells. +/// - `Unique: ~Copyable` and `T: ~Copyable`, the suppressed conformances a +/// type header and a `where` clause spell. +/// - `[S.Element]`, an associated type of a type parameter, which no module +/// selector may qualify. +/// +/// Nothing here needs a recent toolchain, so the fixture compiles with the +/// selected one — CI's included. +package enum ModuleSelectorFixture { + package static let moduleName = "ModuleSelectorFixture" + + /// The `Anchor` class is ballast for the reader: a struct-only module + /// compiles to a dylib with no `__DATA` segment (see + /// `ExportedOnlyLibraryEvolutionFixtureTests`). + package static let source = """ + public struct Outer { + public struct Inner { + public init() {} + } + public init() {} + } + + public struct Box { + public struct Slot { + public init() {} + } + public var element: Element + } + + extension Duration { + public struct LocalFormat { + public init() {} + } + } + + public struct Unique: ~Copyable { + public var value: Int + } + + public protocol Marker {} + + public struct Shapes { + public var nested: Outer.Inner + public var foreignNested: Duration.LocalFormat + public var standardLibraryNested: Dictionary.Index + public var genericNested: Box.Slot + public var composition: any Marker & AnyObject + + public func opaqueCollection() -> some Collection { [1] } + + public func borrowAnything(_ value: borrowing Value) {} + + public func elements(of sequence: Elements) -> [Elements.Element] { Array(sequence) } + } + + extension Outer: Hashable {} + + extension Marker { + public func describe() -> String { "" } + } + + public protocol Container { + associatedtype Item: Marker + var item: Item { get } + } + + public struct Conformer: Marker, Container { + public var item: Conformer { self } + } + + public class Anchor { + public func run() {} + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let diagnostics: String + package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } + } + + private enum WorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in WorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + /// Compiled once per process. + private static let compilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + "swiftc", "-swift-version", "5", "-emit-library", "-enable-library-evolution", + "-module-name", moduleName, + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + /// Every name in `output` still qualified the dotted way by a module that + /// `output` spells with a selector somewhere — what a print path writing a + /// qualified name by hand, instead of through the type printer, leaves + /// behind. Each entry is the qualified name and the line it is on. + @available(macOS 13.0, *) + package static func dottedQualifications(in output: String) -> [(qualifiedName: String, line: String)] { + let selectedModuleNames = Set(output.matches(of: /([A-Za-z_][A-Za-z0-9_]*)::/).map { String($0.output.1) }) + var dottedQualifications: [(qualifiedName: String, line: String)] = [] + for line in output.split(separator: "\n") { + // A whole qualified name at a time (`Swift::Duration.Foundation::LocalFormat`): + // every `.`-separated level but the last must not be a bare module name. + for qualifiedName in line.matches(of: /[A-Za-z_][A-Za-z0-9_]*(?:(?:\.|::)[A-Za-z_][A-Za-z0-9_]*)*/) { + let levels = qualifiedName.output.split(separator: ".") + if levels.dropLast().contains(where: { !$0.contains("::") && selectedModuleNames.contains(String($0)) }) { + dottedQualifications.append((String(qualifiedName.output), String(line))) + } + } + } + return dottedQualifications + } + + package static func machOFile() throws -> MachOFile { + switch try MachOKit.loadFromFile(url: try compilationResult.get()) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } + return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + } + } +} diff --git a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift new file mode 100644 index 000000000..97d489217 --- /dev/null +++ b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift @@ -0,0 +1,72 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +@testable import MachOTestingSupport + +/// `dump` with `DemangleOptions.useModuleSelectors` (evolution proposal +/// `module-selectors`): the names swift-demangling prints follow the option, +/// and so do the suppressed conformances the dumper spells itself. +@Suite +struct ModuleSelectorDumpTests { + private func structDump(named name: String, options: DemangleOptions) async throws -> String { + let machOFile = try ModuleSelectorFixture.machOFile() + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + guard case .struct(let structDescriptor) = typeContextDescriptor, try structDescriptor.name(in: machOFile.context) == name else { continue } + return try await Struct(descriptor: structDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string + } + Issue.record("struct \(name) not found") + return "" + } + + @Test(arguments: [ + ("ModuleSelectorFixture.Outer.Inner", "ModuleSelectorFixture::Outer.ModuleSelectorFixture::Inner"), + ("Swift.Duration.LocalFormat", "Swift::Duration.ModuleSelectorFixture::LocalFormat"), + ("ModuleSelectorFixture.Marker & Swift.AnyObject", "ModuleSelectorFixture::Marker & Swift::AnyObject"), + ]) + func fieldTypesFollowTheOption(spellingWithoutSelectors: String, spellingWithSelectors: String) async throws { + let dumpWithoutSelectors = try await structDump(named: "Shapes", options: .interface) + #expect(dumpWithoutSelectors.contains(spellingWithoutSelectors), "\(dumpWithoutSelectors)") + let dumpWithSelectors = try await structDump(named: "Shapes", options: DemangleOptions.interface.union(.useModuleSelectors)) + #expect(dumpWithSelectors.contains(spellingWithSelectors), "\(dumpWithSelectors)") + } + + @Test func suppressedConformanceFollowsTheOption() async throws { + let dumpWithoutSelectors = try await structDump(named: "Unique", options: .interface) + #expect(dumpWithoutSelectors.contains("struct ModuleSelectorFixture.Unique: ~Swift.Copyable"), "\(dumpWithoutSelectors)") + let dumpWithSelectors = try await structDump(named: "Unique", options: DemangleOptions.interface.union(.useModuleSelectors)) + #expect(dumpWithSelectors.contains("struct ModuleSelectorFixture::Unique: ~Swift::Copyable"), "\(dumpWithSelectors)") + } + + /// The sweep over every type, protocol and conformance the fixture + /// dumps: no name left qualified the dotted way by a module the dump + /// spells with a selector somewhere. + @Test func noNameKeepsItsDottedQualification() async throws { + let machOFile = try ModuleSelectorFixture.machOFile() + let options = DemangleOptions.interface.union(.useModuleSelectors) + var dumps: [String] = [] + for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { + switch typeContextDescriptor { + case .struct(let structDescriptor): + try await dumps.append(Struct(descriptor: structDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string) + case .enum(let enumDescriptor): + try await dumps.append(Enum(descriptor: enumDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string) + case .class(let classDescriptor): + try await dumps.append(Class(descriptor: classDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string) + } + } + for protocolDescriptor in try machOFile.swift.protocolDescriptors { + try await dumps.append(MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string) + } + for protocolConformanceDescriptor in try machOFile.swift.protocolConformanceDescriptors { + try await dumps.append(ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machOFile.context).dump(using: .demangleOptions(options), in: machOFile).string) + } + let dump = dumps.joined(separator: "\n") + #expect(dump.contains("Swift::") && dump.contains("\(ModuleSelectorFixture.moduleName)::"), "\(dump)") + for dottedQualification in ModuleSelectorFixture.dottedQualifications(in: dump) { + Issue.record("dotted qualification `\(dottedQualification.qualifiedName)` left in: \(dottedQualification.line)") + } + } +} diff --git a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift new file mode 100644 index 000000000..2d51fe26f --- /dev/null +++ b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift @@ -0,0 +1,120 @@ +import Foundation +import Testing +import MachOKit +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@testable import MachOTestingSupport + +/// `SwiftDeclarationPrintConfiguration.usesModuleSelectors` qualifies the +/// interface's names with SE-0491 module selectors, by the rules the Swift +/// 6.4 compiler applies when it writes a `.swiftinterface` (evolution +/// proposal `module-selectors`): every type level carries the module that +/// declared it, while a type parameter's associated type carries none. +/// +/// The expected spellings follow those rules, not this printer's output: +/// each is the compiler's spelling of the same shape in the Xcode 27 SDK +/// interfaces (`Swift::Duration.Foundation::TimeFormatStyle`, +/// `~Swift::Copyable`, `Swift::AnyObject`) with this fixture's names. +@Suite(.serialized) +struct ModuleSelectorInterfaceTests { + private func printedInterface(usesModuleSelectors: Bool) async throws -> String { + let machOFile = try ModuleSelectorFixture.machOFile() + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.usesModuleSelectors = usesModuleSelectors + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: printConfiguration), eventHandlers: [], in: machOFile) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + try await builder.prepare() + return try await builder.printRoot().string + } + + struct SpellingCase: Sendable, CustomTestStringConvertible { + let summary: String + let spellingWithoutSelectors: String + let spellingWithSelectors: String + + var testDescription: String { summary } + } + + static let spellingCases: [SpellingCase] = [ + SpellingCase( + summary: "a type nested in a type of the same module", + spellingWithoutSelectors: "var nested: ModuleSelectorFixture.Outer.Inner", + spellingWithSelectors: "var nested: ModuleSelectorFixture::Outer.ModuleSelectorFixture::Inner" + ), + SpellingCase( + summary: "a type this module declares in an extension of a standard library type", + spellingWithoutSelectors: "var foreignNested: Swift.Duration.LocalFormat", + spellingWithSelectors: "var foreignNested: Swift::Duration.ModuleSelectorFixture::LocalFormat" + ), + SpellingCase( + summary: "a type nested in a bound generic standard library type", + spellingWithoutSelectors: "var standardLibraryNested: [Swift.String : Swift.Int].Index", + spellingWithSelectors: "var standardLibraryNested: [Swift::String : Swift::Int].Swift::Index" + ), + SpellingCase( + summary: "a type nested in a bound generic type of the same module", + spellingWithoutSelectors: "var genericNested: ModuleSelectorFixture.Box.Slot", + spellingWithSelectors: "var genericNested: ModuleSelectorFixture::Box.ModuleSelectorFixture::Slot" + ), + SpellingCase( + summary: "AnyObject in a composition", + spellingWithoutSelectors: "var composition: ModuleSelectorFixture.Marker & Swift.AnyObject", + spellingWithSelectors: "var composition: ModuleSelectorFixture::Marker & Swift::AnyObject" + ), + SpellingCase( + summary: "the header of an extension of another module's type", + spellingWithoutSelectors: "extension Swift.Duration {", + spellingWithSelectors: "extension Swift::Duration {" + ), + SpellingCase( + summary: "the header of a conformance extension", + spellingWithoutSelectors: "extension ModuleSelectorFixture.Outer: Swift.Hashable {", + spellingWithSelectors: "extension ModuleSelectorFixture::Outer: Swift::Hashable {" + ), + SpellingCase( + summary: "the header of a protocol extension", + spellingWithoutSelectors: "extension ModuleSelectorFixture.Marker {", + spellingWithSelectors: "extension ModuleSelectorFixture::Marker {" + ), + SpellingCase( + summary: "an opaque type's constraint", + spellingWithoutSelectors: "func opaqueCollection() -> some Swift.Collection", + spellingWithSelectors: "func opaqueCollection() -> some Swift::Collection" + ), + SpellingCase( + summary: "a suppressed conformance in a type header", + spellingWithoutSelectors: "struct Unique: ~Swift.Copyable", + spellingWithSelectors: "struct Unique: ~Swift::Copyable" + ), + SpellingCase( + summary: "a suppressed conformance in a where clause", + spellingWithoutSelectors: "A: ~Swift.Copyable", + spellingWithSelectors: "A: ~Swift::Copyable" + ), + SpellingCase( + summary: "an associated type of a type parameter keeps no selector", + spellingWithoutSelectors: "-> [A.Element] where A: Swift.Sequence", + spellingWithSelectors: "-> [A.Element] where A: Swift::Sequence" + ), + ] + + @Test(arguments: spellingCases) + func interfaceSpellsNamesWithModuleSelectors(_ spellingCase: SpellingCase) async throws { + let interfaceWithoutSelectors = try await printedInterface(usesModuleSelectors: false) + #expect(interfaceWithoutSelectors.contains(spellingCase.spellingWithoutSelectors), "\(interfaceWithoutSelectors)") + let interfaceWithSelectors = try await printedInterface(usesModuleSelectors: true) + #expect(interfaceWithSelectors.contains(spellingCase.spellingWithSelectors), "\(interfaceWithSelectors)") + } + + /// The sweep: once a module is spelled with a selector anywhere, no name + /// may still be qualified with it the old way. Catches a print path that + /// writes a qualified name by hand instead of through the type printer — + /// the extension header was one when the option was added. + @Test func noNameKeepsItsDottedQualification() async throws { + let interface = try await printedInterface(usesModuleSelectors: true) + #expect(interface.contains("Swift::") && interface.contains("\(ModuleSelectorFixture.moduleName)::"), "\(interface)") + for dottedQualification in ModuleSelectorFixture.dottedQualifications(in: interface) { + Issue.record("dotted qualification `\(dottedQualification.qualifiedName)` left in: \(dottedQualification.line)") + } + } +} diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index d62696bfa..f50327791 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -85,6 +85,15 @@ struct CommandRequestMappingTests { #expect(request.destination == .file(path: "out.txt")) } + @Test("--enable-module-selectors reaches the demangle options, off by default") + func dumpModuleSelectors() throws { + var expectedOptions = try DumpCommand.parse(["/tmp/Sample"]).makeRequest().demangleOptions + #expect(expectedOptions.contains(.useModuleSelectors) == false) + expectedOptions.insert(.useModuleSelectors) + let request = try DumpCommand.parse(["/tmp/Sample", "--enable-module-selectors"]).makeRequest() + #expect(request.demangleOptions == expectedOptions) + } + @Test("--emit-field-offsets alone is the flat form") func dumpFlatFieldOffsets() throws { #expect(try DumpCommand.parse(["/tmp/Sample", "--emit-field-offsets"]).makeRequest().fieldOffsetComments == .flat) @@ -106,7 +115,7 @@ struct CommandRequestMappingTests { "--show-c-imported-types", "--parse-opaque-return-type", "--resolve-c-module-names", "--supplementary-apinotes", "/tmp/Extra.apinotes", "--emit-offset-comments", "--sort-members-by-offset", "--exported-only", - "--infer-objc-overrides", "--emit-header", + "--infer-objc-overrides", "--module-selectors", "--emit-header", ]).makeRequest() #expect(request.showsCImportedTypes) #expect(request.parsesOpaqueReturnTypes) @@ -115,9 +124,15 @@ struct CommandRequestMappingTests { #expect(request.memberSortOrder == .byOffset) #expect(request.printsExportedDeclarationsOnly) #expect(request.infersObjCOverridesFromSelectorNames) + #expect(request.usesModuleSelectors) #expect(request.emitsHeader) } + @Test("interface prints without module selectors unless asked") + func interfaceModuleSelectorsDefaultOff() throws { + #expect(try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest().usesModuleSelectors == false) + } + @Test("--emit-expanded-field-offsets implies the offset comments") func interfaceExpandedFieldOffsets() throws { #expect(try InterfaceCommand.parse(["/tmp/Sample", "--emit-expanded-field-offsets"]).makeRequest().fieldOffsetComments == .expanded) From e697e5fc96ee7d93c5fe7a585b2e0dc97cfa0122 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 10 Oct 2026 19:10:32 +0800 Subject: [PATCH 39/49] docs: record the rendering A/B for the module-selector option 90 pairs byte-identical across the archived caches, the simulator runtimes and the in-process reader, so the output with the option off is unchanged. --- Documentations/Evolutions/draft-module-selectors.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-module-selectors.md b/Documentations/Evolutions/draft-module-selectors.md index 46f40ad1d..3d4ea2a11 100644 --- a/Documentations/Evolutions/draft-module-selectors.md +++ b/Documentations/Evolutions/draft-module-selectors.md @@ -40,4 +40,4 @@ Swift 6.4 编译器生成 `.swiftinterface` 时默认就用这种写法:Xcode | 2026-10-10 | 默认关闭;interface 与 dump 都接 | 打开即改变每一份输出与快照;dump 已有逐个 demangle 选项的 `--enable-/--disable-` 开关,新选项照样接,成本几乎为零 | | 2026-10-10 | `~Swift.Copyable` 改由类型打印器 / resolver 印协议节点,不在原处按开关二选一 | 拼写从此只有一个来源。代价:开关关闭时,凡显示标准库模块的选项组合文字不变;不显示的(如 `--demangle-options simplified`)从 `~Swift.Copyable` 变成 `~Copyable`,与它对其余标准库名字的写法一致;富文本里它从一个「其他类型名」变成模块 + 协议两段 | | 2026-10-10 | `OpaqueTypeResolving.opaqueType` 加 `usesModuleSelectors` 参数,不给默认实现 | 解析器角色协议按约定不带默认实现,签名漂移要在编译期暴露;已知实现方只有本库的 provider(RuntimeViewer 只构造它)。若改成让 provider 在构造时自带开关,配置与 provider 会各说各话 | -| 2026-10-10 | 验证 | 新测试 27 个全过,interface 扫漏测试在修 extension 头之前失败;全量 2370 个测试 / 453 个套件只剩本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`;macOS 27 的 libswiftCore / Observation / Synchronization 打开开关后 interface 零残留,dump 只剩注释里的 ObjC 运行时类名;libswiftCore 与 SDK 接口共有的 107 条嵌套类型路径逐层模块一致。渲染 A/B 另记 | +| 2026-10-10 | 验证 | 新测试 27 个全过,interface 扫漏测试在修 extension 头之前失败;全量 2370 个测试 / 453 个套件只剩本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`;macOS 27 的 libswiftCore / Observation / Synchronization 打开开关后 interface 零残留,dump 只剩注释里的 ObjC 运行时类名;libswiftCore 与 SDK 接口共有的 107 条嵌套类型路径逐层模块一致。渲染 A/B(基线 next `cd248de9` + swift-demangling `next` `e17ae7f`,候选 `52fb45f9` + swift-demangling `8419460`;两侧 swift-semantic-string 都是本地 `next`,共用同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 26.6.2 与 15.5 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 模拟器缺的三个框架与 iOS 27.0 模拟器(框架在 cache 里)按设计跳过。开关关闭时输出不变 | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 85cfc24d9..0dbab897d 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2456,7 +2456,7 @@ - swift-demangling:新测试在只加选项声明时 26 处失败、实现后全过;全量 624 个测试通过,原始退出码 0(含逐字节对照官方 demangler 的语料测试)。 - 本库:新增 `ModuleSelectorInterfaceTests`、`ModuleSelectorDumpTests` 与两条 CLI 映射测试,27 个测试全过;interface 的扫漏测试在修 extension 头之前失败。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,依赖为远端发布版,只有 swift-demangling 指本分支、swift-semantic-string 指本地 `next`):2370 个测试 / 453 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`,另有登记过的 known issue。 - 真实系统库(macOS 27,当前系统 cache):libswiftCore、libswiftObservation、libswiftSynchronization 的 interface 与 dump 打开开关后扫漏,interface 零残留;dump 只剩注释里的 ObjC 运行时类名。libswiftCore 与 SDK `Swift.swiftinterface` 共有的 107 条嵌套类型路径,逐层模块全部一致。 - - 渲染 A/B:见下方补记。 + - 渲染 A/B(基线 next `cd248de9` + swift-demangling `next` `e17ae7f`,候选 `52fb45f9` + swift-demangling `8419460`;两侧 swift-semantic-string 都是本地 `next`,共用同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 26.6.2 与 15.5 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 模拟器缺的三个框架与 iOS 27.0 模拟器(框架在 cache 里)按设计跳过。开关关闭时输出不变。 - **关联文档**:[draft-module-selectors](../Evolutions/draft-module-selectors.md)、swift-demangling 提案 `draft-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 - **对应版本**:0.22.0 之后(未发版);依赖 swift-demangling 发版(新选项)。 From 0a8cda8b19ef3de84ec9fb6e3f895a57ba5b99ea Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 12 Oct 2026 16:47:04 +0800 Subject: [PATCH 40/49] test: pin module selectors on a position-based extension header Rebasing the module-selector option onto next met proposal 0062's renderExtendedTypeName, which spells a local type no source names by its position (Holder.(Visitor in $1a2b3c)). That spelling now follows the option too; left dotted, it was the one old-style qualification in an interface spelled Module::Name. The new test fails without it on all three expectations and passes with it. --- ...-selectors.md => 0064-module-selectors.md} | 0 .../LocalTypeInterfaceTests.swift | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+) rename Documentations/Evolutions/{draft-module-selectors.md => 0064-module-selectors.md} (100%) diff --git a/Documentations/Evolutions/draft-module-selectors.md b/Documentations/Evolutions/0064-module-selectors.md similarity index 100% rename from Documentations/Evolutions/draft-module-selectors.md rename to Documentations/Evolutions/0064-module-selectors.md diff --git a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift index b37cc3226..e7d4eb33c 100644 --- a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection import SwiftDeclaration @_spi(Support) import SwiftIndexing +import SwiftPrinting @_spi(Support) import SwiftInterface @testable import MachOTestingSupport @@ -272,4 +273,22 @@ struct LocalTypeInterfaceTests { #expect(interface.contains("\nextension \(moduleName).Holder.(WrappingGenerator in $"), "\(interface)") #expect(!interface.contains("\nextension \(moduleName).Holder.WrappingGenerator."), "\(interface)") } + + /// With module selectors on (evolution proposal `module-selectors`), a + /// position-based extension header carries them like every other name + /// and keeps its position-based level: a header left dotted would be the + /// one old-style qualification in an interface spelled `Module::Name`. + @Test func strippedInterfaceSpellsPositionBasedExtensionsWithModuleSelectors() async throws { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.usesModuleSelectors = true + let builder = try SwiftInterfaceBuilder(configuration: .init(printConfiguration: printConfiguration), eventHandlers: [], in: try LocalTypeFixture.machOFile(.stripped)) + try await builder.prepare() + let interface = try await builder.printRoot().string + + let moduleName = LocalTypeFixture.Variant.stripped.moduleName + let holderExtensionHeaders = interface.split(separator: "\n").filter { $0.hasPrefix("extension \(moduleName)::Holder.") } + #expect(holderExtensionHeaders.contains { $0.contains("Visitor in $") }, "\(interface)") + #expect(holderExtensionHeaders.contains { $0.contains("WrappingGenerator in $") }, "\(interface)") + #expect(!interface.contains("\nextension \(moduleName).Holder."), "\(interface)") + } } From aaac3aebf57a3b51077440258dbf04229c08fec5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 12 Oct 2026 16:47:04 +0800 Subject: [PATCH 41/49] docs: land proposal 0064 (module-selectors) as Implemented Number the proposal 0064 and section 90 of the evolution log, point every reference at the numbered file and at swift-demangling's proposal 0017, and record the rebase onto next: the two conflicts with proposal 0062, the position-based extension header test, and the full suite (2436 tests, only the two MultiPayloadEnumDescriptorCacheTests failures this machine always has). --- AGENTS.md | 2 +- Documentations/Evolutions/0064-module-selectors.md | 9 +++++---- Documentations/Evolutions/README.md | 2 +- Documentations/Internal/Modules/SwiftInterface.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 7 ++++--- Documentations/README.md | 2 +- 6 files changed, 13 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e3a7d1072..cb36d9471 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -263,7 +263,7 @@ Use `resolveRebase(fileOffset:)`. Note `ValueMetadataProtocol.descriptor(in:)` r - **The printers' error contract inverts by level.** Inside a definition, a failing field fails the whole type. At the top level — `printRoot` and the nested children loops alike — printing catches **per definition**: one type/protocol/extension/nested child that throws drops only itself, never its block. A block-level catch once blanked every type of a legacy binary's interface. - **A name's `kind` takes no part in its equality.** The node identifies the type; `kind` is derived differently per producer and the two disagree for C-imported types. - **A nested definition's print may depend on its `level` only through indentation.** A host with `marksNestedDefinitions` takes each nested type or protocol out of its parent's print instead of printing it again, removing one indentation level per nesting depth; a hard-coded level, or a line a renderer does not indent, breaks that silently for the host. `NestedDefinitionRegionContractTests` reports it. -- **Never write a module-qualified name into output as text** (`"Swift.Copyable"`, `module + "." + name`). Print it as a node through the type printer or the caller's `DemangleResolver`, so SE-0491 module selectors (`usesModuleSelectors` / `DemangleOptions.useModuleSelectors`, `Swift::Copyable`) reach it; `ModuleSelectorInterfaceTests.noNameKeepsItsDottedQualification` sweeps a fixture's interface for leftovers. A node handed to the interface printer must outlive the print — it memoizes fragments by node identity. Lookup keys are the exception: they stay dotted, printed with fixed presets that never carry the option. [draft-module-selectors](Documentations/Evolutions/draft-module-selectors.md). +- **Never write a module-qualified name into output as text** (`"Swift.Copyable"`, `module + "." + name`). Print it as a node through the type printer or the caller's `DemangleResolver`, so SE-0491 module selectors (`usesModuleSelectors` / `DemangleOptions.useModuleSelectors`, `Swift::Copyable`) reach it; `ModuleSelectorInterfaceTests.noNameKeepsItsDottedQualification` sweeps a fixture's interface for leftovers. A node handed to the interface printer must outlive the print — it memoizes fragments by node identity. Lookup keys are the exception: they stay dotted, printed with fixed presets that never carry the option. [0064-module-selectors](Documentations/Evolutions/0064-module-selectors.md). - The `Name` types are deliberately **not `Codable`**. A mangled symbol already is the tree's serialized form — persist `mangleAsString(node)` and read it back with `demangleAsNode(_:)` rather than reintroducing a node encoding. - [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). diff --git a/Documentations/Evolutions/0064-module-selectors.md b/Documentations/Evolutions/0064-module-selectors.md index 3d4ea2a11..883bd6428 100644 --- a/Documentations/Evolutions/0064-module-selectors.md +++ b/Documentations/Evolutions/0064-module-selectors.md @@ -1,9 +1,9 @@ -# Draft - 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 +# 0064 - 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-10-10 -- **最后更新**: 2026-10-10 -- **关联提案**: swift-demangling 提案 `draft-module-selectors`(`DemangleOptions.useModuleSelectors`,本提案的 dump 一侧与 interface 的委托打印都建在它上面) +- **最后更新**: 2026-10-12 +- **关联提案**: swift-demangling 提案 `0017-module-selectors`(`DemangleOptions.useModuleSelectors`,本提案的 dump 一侧与 interface 的委托打印都建在它上面) ## 摘要 @@ -41,3 +41,4 @@ Swift 6.4 编译器生成 `.swiftinterface` 时默认就用这种写法:Xcode | 2026-10-10 | `~Swift.Copyable` 改由类型打印器 / resolver 印协议节点,不在原处按开关二选一 | 拼写从此只有一个来源。代价:开关关闭时,凡显示标准库模块的选项组合文字不变;不显示的(如 `--demangle-options simplified`)从 `~Swift.Copyable` 变成 `~Copyable`,与它对其余标准库名字的写法一致;富文本里它从一个「其他类型名」变成模块 + 协议两段 | | 2026-10-10 | `OpaqueTypeResolving.opaqueType` 加 `usesModuleSelectors` 参数,不给默认实现 | 解析器角色协议按约定不带默认实现,签名漂移要在编译期暴露;已知实现方只有本库的 provider(RuntimeViewer 只构造它)。若改成让 provider 在构造时自带开关,配置与 provider 会各说各话 | | 2026-10-10 | 验证 | 新测试 27 个全过,interface 扫漏测试在修 extension 头之前失败;全量 2370 个测试 / 453 个套件只剩本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`;macOS 27 的 libswiftCore / Observation / Synchronization 打开开关后 interface 零残留,dump 只剩注释里的 ObjC 运行时类名;libswiftCore 与 SDK 接口共有的 107 条嵌套类型路径逐层模块一致。渲染 A/B(基线 next `cd248de9` + swift-demangling `next` `e17ae7f`,候选 `52fb45f9` + swift-demangling `8419460`;两侧 swift-semantic-string 都是本地 `next`,共用同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 26.6.2 与 15.5 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 模拟器缺的三个框架与 iOS 27.0 模拟器(框架在 cache 里)按设计跳过。开关关闭时输出不变 | +| 2026-10-12 | In Progress → Implemented,编号 0064 | 用户要求合并。分支 rebase 到 `next` `b8db48bf`,与其间合入的 0062(局部类型的名字)在两处冲突,两边都保留:`TypeNodePrintable.printType` 里局部类型照旧不印上下文,C 导入模块名照旧记下;extension 头改走 0062 的 `renderExtendedTypeName`,它的两种写法(普通名字,以及按位置命名的局部类型 `Holder.(Visitor in $…)`)都随开关带模块选择器——后者留成点号,就是开关打开的 interface 里唯一一处旧写法。新增 `LocalTypeInterfaceTests.strippedInterfaceSpellsPositionBasedExtensionsWithModuleSelectors` 钉住这个组合:extension 头不带选择器时它的 3 条断言全部失败(印成 `LocalTypeFixtureStripped.Holder.(Key in $5e3c): Swift::Equatable`,一行里混着两种写法),带上后与相关的 7 个套件共 60 个测试一起通过,原始退出码 0。rebase 后全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,依赖为远端发布版,swift-demangling 指本分支、swift-semantic-string 指本地 `next`):2436 个测试 / 465 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`。冲突只在两处小的合并点,没有重跑渲染 A/B。按共享分支编号(origin/next 最大 0063,origin/main 最大 0061);本地合并进 `next`;演进账本第 90 节;swift-demangling 一侧编号 0017,快进合入它的 `next` | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 8500b4c54..69cf620a0 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -77,4 +77,4 @@ | draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | | [0063](0063-private-declarations.md) | 私有声明:从名字取 discriminator,按镜像反推源文件 | Implemented | -| draft | [适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名](draft-module-selectors.md) | In Progress | +| [0064](0064-module-selectors.md) | 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 | Implemented | diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index d7839dd6a..389ec7357 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -52,7 +52,7 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 把 `some P` 的占位还原成带 primary associated type 实参的完整拼写(`some Collection & Sendable`)。领域细节已有两篇专文——[OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md)(descriptor 编码、anchor/塌缩机制、字节级调试)与 [OpaquePrimaryAssociatedTypeAttribution.md](../OpaquePrimaryAssociatedTypeAttribution.md)(提案 0011 的实现说明)——本节只给文件分工: -- **`SwiftInterfaceBuilderOpaqueTypeProvider`**:入口,也是一个 `ExtraDataProvider`(挂到 builder 上,printer 打印 `some` 返回类型时经 `opaqueType(forNode:index:usesModuleSelectors:)` 回查;最后一个参数来自打印配置的 `usesModuleSelectors`,为真时交回的文字写成 `some Swift::Collection`,而用来匹配协议事实的名字始终是 `opaqueTypeBuilderOnly` 的点号写法——见提案 [draft-module-selectors](../../Evolutions/draft-module-selectors.md))。从符号表定位 opaque type descriptor,把 generic requirements 拆成 superclass 项、协议项与 same-type 项(`some Base & P` 的父类排在组合最前,与编译器 `.swiftinterface` 同形;2026-09-18 之前 superclass 项被 `OpaqueType.requirements(in:)` 与 provider 双双丢弃,`some Base` 打成裸 `some`),逐协议调用归属判定(anchor 直接命中 → refine 闭包 → 名字兜底,兜底四条件缺一不可——宁可少一个实参也不捏造一个)。参数按坐标(深度 + 序号)定位而不是按位置:没有运行时可见约束的参数(`some Sendable` / `some Any` / `some AnyObject`)返回 nil、渲染为裸 `some`,走不到的状态 `#log(.fault)` 加 debug 断言,读取失败 `#log(.error)`(见 [OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md) §1.3、§1.4)。实参与父类这类**完整类型**用去掉 `removeBoundGeneric` 的选项打印,并先剥掉关联类型的协议限定(`Node.strippingAssociatedTypeProtocolQualifiers()`,在 `SwiftDeclarationRendering`)——上游 `NodePrinter` 的 `*BuilderOnly` 选项是给类型名用的,直接拿来打类型会丢泛型实参、多出 `A.Probe.N.A` 这样的限定(同文 §2.3、§4.7)。 +- **`SwiftInterfaceBuilderOpaqueTypeProvider`**:入口,也是一个 `ExtraDataProvider`(挂到 builder 上,printer 打印 `some` 返回类型时经 `opaqueType(forNode:index:usesModuleSelectors:)` 回查;最后一个参数来自打印配置的 `usesModuleSelectors`,为真时交回的文字写成 `some Swift::Collection`,而用来匹配协议事实的名字始终是 `opaqueTypeBuilderOnly` 的点号写法——见提案 [0064-module-selectors](../../Evolutions/0064-module-selectors.md))。从符号表定位 opaque type descriptor,把 generic requirements 拆成 superclass 项、协议项与 same-type 项(`some Base & P` 的父类排在组合最前,与编译器 `.swiftinterface` 同形;2026-09-18 之前 superclass 项被 `OpaqueType.requirements(in:)` 与 provider 双双丢弃,`some Base` 打成裸 `some`),逐协议调用归属判定(anchor 直接命中 → refine 闭包 → 名字兜底,兜底四条件缺一不可——宁可少一个实参也不捏造一个)。参数按坐标(深度 + 序号)定位而不是按位置:没有运行时可见约束的参数(`some Sendable` / `some Any` / `some AnyObject`)返回 nil、渲染为裸 `some`,走不到的状态 `#log(.fault)` 加 debug 断言,读取失败 `#log(.error)`(见 [OpaqueReturnTypeResolution.md](../OpaqueReturnTypeResolution.md) §1.3、§1.4)。实参与父类这类**完整类型**用去掉 `removeBoundGeneric` 的选项打印,并先剥掉关联类型的协议限定(`Node.strippingAssociatedTypeProtocolQualifiers()`,在 `SwiftDeclarationRendering`)——上游 `NodePrinter` 的 `*BuilderOnly` 选项是给类型名用的,直接拿来打类型会丢泛型实参、多出 `A.Probe.N.A` 这样的限定(同文 §2.3、§4.7)。 - **`OpaqueSameTypeConstraint`** / **`OpaqueDependentMemberProjection`**:从 requirement 节点里挖出来的单条 same-type 约束(区分正向 pin `τ.Name == X` 与反向 pin `outer == τ.Name`,后者渲染期经 `SubstitutionMap` 回溯)及其解析器。 - **`ProtocolFactsResolver`**:按「可达 descriptor 优先、内置表兜底」的链条解析协议事实(自声明的 associated type 名、refine 闭包),`refineClosureContainsAnchor` 对不完整闭包返回三态(命中 / 完整排除 / `nil` 不可证)。 - **`BuiltinStandardLibraryProtocolFacts`**:冻结的 stdlib 协议表——**primary associated type 名单与顺序的唯一来源**(SE-0346 不留运行时痕迹),也是离线 bind-only 外部协议的兜底。无 associated type 的协议也登记空条目,让归属能说「确定不附着」而非降级。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 0dbab897d..022709f61 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2441,7 +2441,7 @@ - **关联文档**:AGENTS.md「Never let a demangle or print hop while you hold a lock」、[ReviewAdjudications A61](ReviewAdjudications.md)、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「包了哪些入口」、[NodeStoreMigrationOpenIssues 第 9 条](NodeStoreMigrationOpenIssues.md)(规则的来历)。 - **对应版本**:下一个版本(未发版)。 -## 2026-10-10 适配 SE-0491:模块选择器写法(节号落地时分配) +## 90. 适配 SE-0491:模块选择器写法 - **时间段**:2026-10-10。 - **动机**:SE-0491(Swift 6.3)加了 `Module::Name` 写法;Swift 6.4 编译器写 `.swiftinterface` 默认就用它,Xcode 27 SDK 里 Swift、Foundation、AppKit、_Concurrency 的接口全是 `Swift::Int`、`Foundation::Date.Foundation::FormatStyle`。二进制里没有新东西,影响只在名字怎么写。用户:「适配一下这个提案,顺便改一下 swift-demangling,加一个 options 使用 module-selector」。 @@ -2457,8 +2457,9 @@ - 本库:新增 `ModuleSelectorInterfaceTests`、`ModuleSelectorDumpTests` 与两条 CLI 映射测试,27 个测试全过;interface 的扫漏测试在修 extension 头之前失败。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,依赖为远端发布版,只有 swift-demangling 指本分支、swift-semantic-string 指本地 `next`):2370 个测试 / 453 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`,另有登记过的 known issue。 - 真实系统库(macOS 27,当前系统 cache):libswiftCore、libswiftObservation、libswiftSynchronization 的 interface 与 dump 打开开关后扫漏,interface 零残留;dump 只剩注释里的 ObjC 运行时类名。libswiftCore 与 SDK `Swift.swiftinterface` 共有的 107 条嵌套类型路径,逐层模块全部一致。 - 渲染 A/B(基线 next `cd248de9` + swift-demangling `next` `e17ae7f`,候选 `52fb45f9` + swift-demangling `8419460`;两侧 swift-semantic-string 都是本地 `next`,共用同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 26.6.2 与 15.5 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 模拟器缺的三个框架与 iOS 27.0 模拟器(框架在 cache 里)按设计跳过。开关关闭时输出不变。 -- **关联文档**:[draft-module-selectors](../Evolutions/draft-module-selectors.md)、swift-demangling 提案 `draft-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 -- **对应版本**:0.22.0 之后(未发版);依赖 swift-demangling 发版(新选项)。 + - 落地(2026-10-12):rebase 到 `next` `b8db48bf`,与 0062(局部类型的名字)在 `TypeNodePrintable.printType` 和 extension 头上冲突,两边都保留;extension 头走 0062 的 `renderExtendedTypeName`,按位置命名的局部类型(`Holder.(Visitor in $…)`)也随开关带模块选择器,由新测试 `LocalTypeInterfaceTests.strippedInterfaceSpellsPositionBasedExtensionsWithModuleSelectors` 钉住:extension 头不带选择器时它的 3 条断言全部失败(印成 `LocalTypeFixtureStripped.Holder.(Key in $5e3c): Swift::Equatable`,一行里混着两种写法),带上后与相关的 7 个套件共 60 个测试一起通过,原始退出码 0。全量 `swift test --skip IntegrationTests`(同上的依赖配置):2436 个测试 / 465 个套件,原始退出码 1,失败的仍只有那两条 `MultiPayloadEnumDescriptorCacheTests`。冲突点小,没有重跑渲染 A/B。 +- **关联文档**:[0064-module-selectors](../Evolutions/0064-module-selectors.md)、swift-demangling 提案 `0017-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 +- **对应版本**:下一个版本(未发版);发版前 swift-demangling 要先发版(新选项 `useModuleSelectors`),再抬本库的版本范围。 ## 维护约定 diff --git a/Documentations/README.md b/Documentations/README.md index 5dde3d50b..469ed62cf 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -168,7 +168,7 @@ selects names using each access's offset and width. | [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | | [Evolutions/0063-private-declarations.md](Evolutions/0063-private-declarations.md) | **提案 0063(Implemented)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | -| [Evolutions/draft-module-selectors.md](Evolutions/draft-module-selectors.md) | **提案 draft(In Progress)**:适配 SE-0491 模块选择器——默认关闭的开关(interface 的 `usesModuleSelectors` / `--module-selectors`,dump 的 swift-demangling 新选项 `useModuleSelectors` / `--enable-module-selectors`),打开后照 Swift 6.4 编译器写 `.swiftinterface` 的规则输出 `Swift::Int`,嵌套类型每层带声明它的模块(`Swift::Duration.Foundation::TimeFormatStyle`),局部类型与 `A.Element` 不加。`~Swift.Copyable` 改由类型打印器印协议节点;`OpaqueTypeResolving.opaqueType` 加参数。 | +| [Evolutions/0064-module-selectors.md](Evolutions/0064-module-selectors.md) | **提案 0064(Implemented)**:适配 SE-0491 模块选择器——默认关闭的开关(interface 的 `usesModuleSelectors` / `--module-selectors`,dump 的 swift-demangling 新选项 `useModuleSelectors` / `--enable-module-selectors`),打开后照 Swift 6.4 编译器写 `.swiftinterface` 的规则输出 `Swift::Int`,嵌套类型每层带声明它的模块(`Swift::Duration.Foundation::TimeFormatStyle`),局部类型与 `A.Element` 不加。`~Swift.Copyable` 改由类型打印器印协议节点;`OpaqueTypeResolving.opaqueType` 加参数。 | | [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 的数量与内存实测。 | From c6fd74d083e728522b35eda34e277099127bb17d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 13 Oct 2026 12:35:58 +0800 Subject: [PATCH 42/49] perf(symbols): attribute folded symbols from a per-address grouping Identical code folding piles the witnesses of many conformances onto one address: a single SwiftUI `_destroySelf` or value witness implementation carries well over a thousand names. Extension and protocol indexing, and both protocol dumpers, picked the symbol belonging to a conformance or a protocol by demangling, searching and printing every name at the address in turn, once per conformance asking. That is quadratic in the group's size: printing SwiftUI made 15,047 such calls, 451 candidates each on average, 3.65 million checks over only 17,852 distinct names, and it took half the time RuntimeViewer spends building an image's Find corpus. `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` answers the question from a grouping of the address's rows by owner -- the type the first protocol conformance names, or the first protocol -- built once per address, owner rule and print preset on the image's storage, outside its lock, first finisher kept. The rule, the presets, the candidate order and the queried offset stamped on each value are the ones the four call sites used, which now only filter out what an earlier witness claimed. Verified by `SymbolOwnerGroupingSwiftUITests`: every multi-name address of SwiftUI in process, both rules under both presets, answers exactly as a one-by-one reference implementation kept in the test; eight tasks asking an address first at once agree. Proposal: draft-faster-lazy-definition-indexing. --- AGENTS.md | 1 + Documentations/Evolutions/README.md | 1 + .../draft-faster-lazy-definition-indexing.md | 59 ++++++++ .../Internal/Modules/MachOSymbols.md | 2 + .../Internal/ProjectEvolutionLog.md | 19 +++ Documentations/README.md | 1 + .../ExtensionDefinition+Indexing.swift | 19 ++- .../ProtocolDefinition+Indexing.swift | 12 +- .../MachO/MachOSymbols/SymbolIndexStore.swift | 114 +++++++++++++++ .../Dumper/ProtocolConformanceDumper.swift | 11 +- .../SwiftDump/Dumper/ProtocolDumper.swift | 10 +- .../SymbolOwnerGroupingTests.swift | 135 ++++++++++++++++++ 12 files changed, 368 insertions(+), 16 deletions(-) create mode 100644 Documentations/Evolutions/draft-faster-lazy-definition-indexing.md create mode 100644 Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift diff --git a/AGENTS.md b/AGENTS.md index cb36d9471..1510d55d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -189,6 +189,7 @@ Each of these fails **silently**, and several produce a real, fully-qualified, * - **A runtime metatype becomes a node only through `RuntimeTypeNameDemangling.node(forMetatype:)`, never bare `_mangledTypeName` + demangle.** The runtime spells a private type's anonymous context by its descriptor address, which the printers render as nothing or as `(unknown context at $…)` — a specialized header read `struct .WindowPortal<…>`, and a private type argument lost its module and every enclosing type. - **An anonymous context's name is the compiler's whole mangling of what it stands for — a function, a closure, or the private or local type it wraps — never a fragment of it.** It comes from the descriptor's own name (debug builds only), the `$sMXX` symbol on the descriptor, or a `_symbolic` referent (`AnonymousContextNameIndex`); a private discriminator is read off the wrapped type's own `privateDeclName` and nothing else. Taking `first(of: .privateDeclName)` from the context's name borrowed an enclosing private function's discriminator and faked private types, and dropping the context lost every local type's function, so two methods' `Visitor`s merged into one definition. A local type no source names is position-named `Holder.(Visitor in $
)` — tell it from a private type with `localTypeNaming`, never by string ([0062-local-type-context-names](Documentations/Evolutions/0062-local-type-context-names.md)). - **Do NOT call bare `NodeReference(interning:)` on a batch path** — route through `InternedNodeReferenceCache`. +- **Picking the symbol that belongs to a given conformance or protocol out of an address's `Symbols` goes through `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)`, never a loop that demangles, searches and prints each symbol.** Identical code folding puts over a thousand names on one SwiftUI witness address and every conformance asks that address again: four such loops (extension and protocol indexing, both protocol dumpers) made the attribution quadratic — half the time of printing a whole image. The query groups an address once and answers from the grouping ([draft-faster-lazy-definition-indexing](Documentations/Evolutions/draft-faster-lazy-definition-indexing.md)). - **A `_symbolic` symbol's referents are one mangling, not several.** The compiler appends them with one mangler, so a later referent reuses substitutions and words of the earlier ones (`7SwiftUI19_ConditionalContentV AA08ModifiedD0V`); demangled alone it fails or names something else. Take referents from `SymbolicManglingIndex.referentNode(of:in:)`, which demangles them together — and for the same reason never splice referents into the mangled name as text. - **Resolving one type's members/info/attributes must use the node-taking overloads** (`memberSymbols(of:for:node:in:)` and friends). The name-only forms flatten every sub-bucket on purpose: the name key is printed with `.interfaceTypeBuilderOnly`, which strips private discriminators, so same-named private types share a bucket (issue #115). - **Never let a demangle or print hop while you hold a lock.** On a 512 KB thread each call hops to a large-stack worker and blocks on it, so every thread waiting on the lock waits behind the hop — without bound once the pool saturates (`SymbolIndexStore.lateDemangledNode`, 2026-08-03). Under a lock, either be on a large stack already — inside a `LargeStackTaskExecution.run` entry point, or past one `StackSafeExecutor.withLargeStack` taken *before* locking (`IndexerConformanceProvider.classHierarchy()`) — or demangle outside the lock and insert-if-absent under it. A synchronous API runs on whatever thread its host calls it from. The sites that rely on their entry point's executor: [ReviewAdjudications A61](Documentations/Internal/ReviewAdjudications.md). diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 69cf620a0..91be05ac0 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -78,3 +78,4 @@ | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | | [0063](0063-private-declarations.md) | 私有声明:从名字取 discriminator,按镜像反推源文件 | Implemented | | [0064](0064-module-selectors.md) | 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 | Implemented | +| draft | [并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找](draft-faster-lazy-definition-indexing.md) | In Progress | diff --git a/Documentations/Evolutions/draft-faster-lazy-definition-indexing.md b/Documentations/Evolutions/draft-faster-lazy-definition-indexing.md new file mode 100644 index 000000000..161cd0f67 --- /dev/null +++ b/Documentations/Evolutions/draft-faster-lazy-definition-indexing.md @@ -0,0 +1,59 @@ +# Draft - 并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找 + +- **状态**: In Progress +- **创建日期**: 2026-10-13 +- **最后更新**: 2026-10-13 +- **关联提案**: [draft-concurrent-definition-printing](draft-concurrent-definition-printing.md)(同版本内并行打印的前提)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(`SharedCache` 的现行形态) +- **实现分支**: `feature/faster-lazy-definition-indexing` + +## 摘要 + +RuntimeViewer 的 Find 语料要把一个镜像的全部定义打印一遍(进程内 `MachOImage`,每镜像 4 路并行),打印触发的惰性索引才是大头,真正渲染文本只占约两成。2026-10-13 在 M1 Max 上用 RuntimeViewer 的计时探针测 AppKit、SwiftUI、SwiftUICore、libswiftCore、Foundation 五个镜像:语料合计 Release 约 20 s、Debug 约 104 s。整轮采样(占语料时间): + +- `ExtensionDefinition.runIndexingPass` 给 resilient witness 找实现符号的 `_symbol(for:typeName:visitedNodes:)` 占 **50–53%**(Release、Debug 一致); +- Release 下 `SharedCache.resolve` 的 `os_unfair_lock` 慢路径占 **25%**,其中约四分之三来自上一条里逐个候选的 `demangledNodeReference`; +- `TypeDefinition` 索引 13–20%,其中 `PropertyWrapperTypeCatalog.evidence` 拿着 `NSLock` 搜依赖镜像的导出表,锁等待约 **8%**。 + +修完:Release 约 20 s → 8.4 s,Debug 约 104 s → 53 s。输出逐字节不变。 + +## 方案 + +**1. 同一地址的符号按归属查表(主因)。** 临时计数(SwiftUI,Debug):`_symbol` 调用 15,047 次,平均每次 451 个候选、平均第 242 个才命中;共检查 365 万次,涉及的不重复符号只有 17,852 个,每个平均被检查 204 次。原因是 identical code folding:许多类型内容相同的 witness 实现(`_destroySelf`、`Owup` 一类)被合并到同一地址,一个地址挂着成百上千个别名,每个 conformance 都要从头把这串别名逐个 demangle、`first(of: .protocolConformance)` 全树搜索、打印类型名再比较——对别名组大小是平方级。 + +`SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` 回答「这个地址上、归属打印为 T 的符号,按 `symbols(for:in:)` 的顺序」。归属两种(`SymbolOwnerKind`):`.conformingType` 是符号树里第一个 `protocolConformance` 的第一个子节点,`.protocol` 是第一个 `protocol` 节点;打印预设由调用方给。每个「地址 + 规则 + 预设」第一次被问到时把该地址的全部行分组一次(锁外计算,锁内插入,先到者胜),之后每次查询是两次字典查找。分组表挂在该镜像的 `Storage` 上,随它一起淘汰。同一写法的四处都改用它,各自只剩已认领节点(`visitedNodes`)的过滤: + +| 调用点 | 规则 | 预设 | +|---|---|---| +| `ExtensionDefinition` 索引 | `.conformingType` | `.interfaceTypeBuilderOnly` | +| `ProtocolDefinition` 索引 | `.protocol` | `.interfaceTypeBuilderOnly` | +| `ProtocolConformanceDumper.demangledSymbol` | `.conformingType` | `.interfaceType` | +| `ProtocolDumper.validNode` | `.protocol` | `.interfaceType` | + +规则与原实现逐条相同:同一个打印预设、同一个「树里第一个节点」、同一个候选顺序、返回值同样是带查询偏移的独立 `DemangledSymbol`、demangler 拒绝的行同样跳过。 + +**2. 属性包装器目录锁外查找。** `PropertyWrapperTypeCatalog.evidence(forWrapperCandidate:)` 锁内只读写按前缀的结论缓存;导出表搜索与其中的 demangle 放到锁外,并发的首次查询各算各的、先写入者胜(结论是导出表的纯函数,谁写都一样);依赖闭包的查找表用另一把锁只建一次。 + +锁去掉之后剩下的开销是建依赖闭包本身:`InProcessDependencyLocator` 每找一个依赖都调 `MachOImage(name:)`,后者把进程里全部已映射镜像的路径逐个拆一遍,一个几百个依赖的闭包、上千个映射镜像就是几十万次拆分,其余打印线程都在等它。定位器改为构造时遍历一遍已映射镜像建「bare name → 镜像」表,同名取第一个,与 `MachOImage(name:)` 的选择逐个一致;代价是构造之后才映射的镜像它看不到(`DependencyClosure(root: MachOImage)` 每次新建定位器)。MachOKit 的 `MachOImage(name:)` 按 fork 政策不动。 + +**3. `SharedCache` 读路径:不改。** 第 1 条修完重测,锁的慢路径只剩语料时间的 0.7%–1.7%,`SharedCache.resolve` 在语料打印内部只占 2%(其余是加载阶段建符号索引)。见决策日志。 + +**验证。** + +- `SymbolOwnerGroupingSwiftUITests`(MachOSymbolsTests):进程内 SwiftUI 的每个多名字地址,两种规则 × 两种预设,新查询与旧的逐个符号规则(测试里的参照实现:按名字 demangle、取归属、打印、比较)给出同样的名字、偏移与节点;另在一份不进缓存的新建索引上让 8 个任务同时首次查询同一地址,答案全部一致。 +- `PropertyWrapperTypeCatalogLockTests`(SwiftDeclarationRenderingTests):一个前缀的搜索被卡住时,另一个已有结论的前缀必须立刻返回;旧写法下 10 秒超时失败,新写法通过。没有结论的前缀也被记住、不再搜索。 +- `InProcessDependencyLocatorTests`(MachODependenciesTests):进程里每个已映射镜像的路径(加几个不存在的拼写),定位器与 `MachOImage(name:)` 指向同一个镜像。 +- 现有测试套件;AGENTS.md 规定的渲染 A/B(三种 reader 路径,逐字节一致);RuntimeViewer 探针前后对照。 + +**未询问即采用的假设**:分组表只按需建、不在符号索引构建时预算(多数镜像的大多数地址永远不会被问到);不改变 `first(of:)` 在符号树上的语义(AGENTS.md 指出它对成员树往往不对,但改它会改输出,不在本提案内)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-13 | 创建并置为 Accepted:三处都做,Debug 构建下未优化泛型的固有开销(约 28%)先不处理 | 用户在 RuntimeViewer 会话中报「Find 构建语料还是太慢」,看过上面的测量与采样后选定「三处都做」「Debug 专项先不管」。 | +| 2026-10-13 | 查表做成两种归属规则 × 任意打印预设,同一写法的四处一起改;`ClassDumper.validNode` 与 `OverrideSymbolMatcher` 不改 | 横向排查找到 `ProtocolDefinition` 索引与两个 dumper 用的是同一种「在别名里逐个比较」的写法(采样里 `ProtocolDefinition` 约占语料时间 1%,dumper 不在 RuntimeViewer 的路径上,但 `dump` 同样平方级)。后两处按声明上下文**结构相等**认领,规则不同,实测各占 0.4%–0.5%。 | +| 2026-10-13 | 第 2 条扩大到依赖定位:`InProcessDependencyLocator` 改为构造时建表 | 目录的锁去掉后重采样(负载约 40):`TypeDefinition` 索引占 39%,其中目录 25%,几乎全是 `resolvedDependencyLookups()`——一个线程建闭包,其余线程等它;建闭包的时间又几乎都在 `MachOImage.init(name:)`。改后 libswiftCore 的语料 1.2 s → 0.4 s。 | +| 2026-10-13 | 第 3 条不改 `SharedCache` | 第 1 条修完后,低负载采样里全部锁慢路径占语料时间 1.7%(`SharedCache.resolve` 自己 0.7% 以下);`SharedCache.resolve` 的包含时间在语料打印内部只占 2%,其余 28% 是加载阶段在后台队列上建符号索引,不在语料构建里。 | +| 2026-10-13 | ReviewAdjudications A61 第四处(`PropertyWrapperTypeCatalog`)改判为修 | A61 只考虑了「小栈调用方持锁切线程」,没考虑长临界区本身:并行打印的调用方都在大栈上、不切线程,照样排在别人的导出表搜索后面。 | +| 2026-10-13 | 验证通过 | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,`USING_LOCAL_DEPENDENCIES=1`):2442 个测试 / 468 个套件,原始退出码 1,失败的只有两条 `MultiPayloadEnumDescriptorCacheTests`,在基线 next `5dca3331` 的 release 测试包上同样两条、同样失败点。渲染 A/B(基线为钉在 `5dca3331` 的 detached worktree,两侧共用本地兄弟依赖与同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build`):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 缺的三个框架与 iOS 27.0 / 27.1 模拟器(框架在 cache 里)按设计跳过。 | +| 2026-10-13 | 实测(RuntimeViewer 探针,进程内,每镜像 4 路,M1 Max,基线与候选交替两轮,负载 6–13):Release 合计 20.3 s → 8.4 s(SwiftUI 8.8 → 2.7,SwiftUICore 6.0 → 1.9,AppKit 2.9 → 2.4,Foundation 1.4 → 1.0,libswiftCore 1.2 → 0.4),CPU 64.5 s → 30 s;Debug 合计 103.7 s → 52.6 s(SwiftUI 47.0 → 18.1,SwiftUICore 32.2 → 12.3) | 同一份 RuntimeViewerCore(next `4fc214ad`)与锁文件,只把 MachOSwiftSection 用 SwiftPM edit 模式换成本分支。修后采样:`ExtensionDefinition` 索引从 53% 降到 7%,锁慢路径合计 1.7%;剩下的大头是 ObjC 打印(约四分之一)、`TypeDefinition` 索引(约五分之一)和字段布局(约 8%)。 | diff --git a/Documentations/Internal/Modules/MachOSymbols.md b/Documentations/Internal/Modules/MachOSymbols.md index 40df4b7eb..795b7034b 100644 --- a/Documentations/Internal/Modules/MachOSymbols.md +++ b/Documentations/Internal/Modules/MachOSymbols.md @@ -35,6 +35,8 @@ MachOSymbols 是**符号索引**层:把一个镜像的符号表和 export trie > 解析**某一个**类型的成员 / 信息 / 属性,必须用带 node 的重载(`memberSymbols(of:for:node:in:)`、`methodDescriptorMemberSymbols(of:for:node:in:)`、`typeInfo(for:node:in:)`、`thunkAttributeMembers(of:for:node:in:)`)。只带名字的那几个重载会故意把所有子桶摊平,只用于「所有打印成这个名字的类型」这种聚合查询。 +**同一地址上的符号按归属分组**(演进提案 `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` = 这个镜像没有导出信息,**此时绝不标注**)。 ## 子系统 2:查询出口与 detach diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 022709f61..9829e992e 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2461,6 +2461,25 @@ - **关联文档**:[0064-module-selectors](../Evolutions/0064-module-selectors.md)、swift-demangling 提案 `0017-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 - **对应版本**:下一个版本(未发版);发版前 swift-demangling 要先发版(新选项 `useModuleSelectors`),再抬本库的版本范围。 +## 2026-10-13 并行打印下的惰性索引提速(节号落地时分配) + +- **时间段**:2026-10-13。 +- **动机**:RuntimeViewer 用户报「Find 构建可搜索的语料还是太慢」。RuntimeViewer 的计时探针在 M1 Max 上测 AppKit、SwiftUI、SwiftUICore、libswiftCore、Foundation 的语料:Release 约 20 s,用户日常用的 Debug 约 104 s。整轮采样显示时间不在 RuntimeViewer,而在本库打印时触发的惰性索引:给 resilient witness 找实现符号占 50–53%,Release 下 `SharedCache` 的锁慢路径 25%,属性包装器目录持锁搜导出表 8%。 +- **关键决策**: + - 根因是 identical code folding 下的平方级认领:SwiftUI 一个 `_destroySelf` 或值 witness 的实现地址挂着上千个名字,每个 conformance 都把这串名字逐个 demangle、整树搜索、打印比较(15,047 次调用、365 万次检查,只涉及 17,852 个不同名字)。改为 `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)`:每个「地址 + 归属规则 + 打印预设」第一次被问到时在 `Storage` 上分组一次,之后查表。规则(第一个 `protocolConformance` 的第一个子节点 / 第一个 `protocol` 节点)、预设、候选顺序、查询偏移都与原实现相同。 + - 同一写法的四处一起改:`ExtensionDefinition` 与 `ProtocolDefinition` 的索引、`ProtocolConformanceDumper` 与 `ProtocolDumper`。按声明上下文结构相等认领的 `ClassDumper.validNode`、`OverrideSymbolMatcher` 规则不同、开销可忽略,不改。AGENTS.md 加了一条:在别名里找归属走这个查询,不再写逐个比较的循环。 + - `PropertyWrapperTypeCatalog` 锁内只读写结论缓存,搜索与 demangle 在锁外;依赖闭包用另一把锁只建一次。ReviewAdjudications A61 第四处据此改判。锁去掉后剩下的开销是建依赖闭包:`InProcessDependencyLocator` 改为构造时遍历一遍已映射镜像建表,代替每个依赖一次的 `MachOImage(name:)` 全量扫描,选择结果逐个一致。 + - `SharedCache` 不改:第 1 条修完后锁慢路径只剩语料时间的 1.7% 以下,`resolve` 在语料打印内部只占 2%。 + - 用户定 Debug 构建下未优化泛型的固有开销(约 28%,Swift 运行时的泛型元数据查找)这次不处理。 +- **落地模块**:MachOSymbols(`SymbolIndexStore.SymbolOwnerKind`、`Storage` 上的分组表、新查询)、MachODependencies(`InProcessDependencyLocator`)、SwiftDeclaration(`ExtensionDefinition` / `ProtocolDefinition` 索引)、SwiftDeclarationRendering(`PropertyWrapperTypeCatalog`)、SwiftDump(两个协议 dumper)。 +- **验证**: + - 新测试:`SymbolOwnerGroupingSwiftUITests`(进程内 SwiftUI 每个多名字地址、两种规则 × 两种预设,与测试里保留的逐个比较参照实现逐项相同;8 个任务同时首次查询结果一致)、`PropertyWrapperTypeCatalogLockTests`(旧写法 10 秒超时失败、新写法通过)、`InProcessDependencyLocatorTests`(与 `MachOImage(name:)` 逐个一致)。 + - RuntimeViewer 探针(同一份 RuntimeViewerCore 与锁文件,只把本库用 SwiftPM edit 模式换成本分支,基线与候选交替两轮,负载 6–13):Release 20.3 s → 8.4 s、CPU 64.5 s → 30 s;Debug 103.7 s → 52.6 s。 + - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,`USING_LOCAL_DEPENDENCIES=1`):2442 个测试 / 468 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`(基线 next `5dca3331` 上同样失败)。 + - 渲染 A/B(基线 next `5dca3331` 的 detached worktree,两侧共用本地兄弟依赖与同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build`):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对。 +- **关联文档**:[draft-faster-lazy-definition-indexing](../Evolutions/draft-faster-lazy-definition-indexing.md)、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「同一地址上的符号按归属分组」、[Modules/MachODependencies.md](Modules/MachODependencies.md)「定位器」、[ReviewAdjudications A61](ReviewAdjudications.md)。 +- **对应版本**:下一个版本(未发版)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/README.md b/Documentations/README.md index 469ed62cf..b1b28f16a 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -169,6 +169,7 @@ selects names using each access's offset and width. | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | | [Evolutions/0063-private-declarations.md](Evolutions/0063-private-declarations.md) | **提案 0063(Implemented)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | | [Evolutions/0064-module-selectors.md](Evolutions/0064-module-selectors.md) | **提案 0064(Implemented)**:适配 SE-0491 模块选择器——默认关闭的开关(interface 的 `usesModuleSelectors` / `--module-selectors`,dump 的 swift-demangling 新选项 `useModuleSelectors` / `--enable-module-selectors`),打开后照 Swift 6.4 编译器写 `.swiftinterface` 的规则输出 `Swift::Int`,嵌套类型每层带声明它的模块(`Swift::Duration.Foundation::TimeFormatStyle`),局部类型与 `A.Element` 不加。`~Swift.Copyable` 改由类型打印器印协议节点;`OpaqueTypeResolving.opaqueType` 加参数。 | +| [Evolutions/draft-faster-lazy-definition-indexing.md](Evolutions/draft-faster-lazy-definition-indexing.md) | **提案 draft(In Progress)**:RuntimeViewer 的 Find 语料(进程内并行打印整个镜像)一半时间耗在给 resilient witness 找实现符号上——identical code folding 让一个地址挂成百上千个别名,每个 conformance 都从头逐个 demangle、搜索、打印比较,平方级。改为 `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` 按地址把别名按归属(被遵循类型 / 协议)分组一次、之后查表,`ExtensionDefinition`、`ProtocolDefinition` 与两个协议 dumper 都改用它;`PropertyWrapperTypeCatalog` 锁外搜导出表,`InProcessDependencyLocator` 一次建表代替逐个 `MachOImage(name:)`;`SharedCache` 重测后不改。M1 Max 五个系统框架:Release 20 s → 8.4 s,Debug 104 s → 53 s,输出逐字节不变。 | | [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/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift index 7b935875f..7732af49b 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift @@ -33,13 +33,20 @@ extension ExtensionDefinition: OnceIndexedDefinition { return } - // Structurally keyed: `demangleSymbolReference` returns references from - // different stores, and store-identity equality would let the same - // implementation symbol be claimed by two witnesses. + // The first of `symbols` whose conformance names this extension's + // type and that no earlier witness claimed. The index answers the + // first half from a grouping it builds once per address (evolution + // proposal `faster-lazy-definition-indexing`): identical code folding + // leaves a thousand names on one address, and checking them one by + // one for every conformance was quadratic. `symbols` is what the index + // listed at its offset, so the offset stands for it. Structurally + // keyed: references can come from different stores, and + // store-identity equality would let the same implementation symbol be + // claimed by two witnesses. func _symbol(for symbols: Symbols, typeName: String, visitedNodes: borrowing OrderedSet = []) throws -> DemangledSymbol? { - for symbol in symbols { - if let node = SymbolicDemangler.demangleSymbolReference(for: symbol, in: machO), let protocolConformanceNode = node.first(of: .protocolConformance), let symbolTypeName = protocolConformanceNode.children.first?.print(using: .interfaceTypeBuilderOnly), symbolTypeName == typeName, !visitedNodes.contains(StructuralNodeReferenceKey(node)) { - return .init(symbol: symbol, demangledNode: node) + for candidate in SymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: typeName, ownerKind: .conformingType, printedWith: .interfaceTypeBuilderOnly, in: machO) { + if !visitedNodes.contains(StructuralNodeReferenceKey(candidate.demangledNode)) { + return candidate } } return nil diff --git a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift index 86c75bbaf..dec5ebd92 100644 --- a/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift @@ -21,13 +21,17 @@ extension ProtocolDefinition: OnceIndexedDefinition { private func runIndexingPass(in machO: some MachOSwiftSectionRepresentableWithCache) throws { let dumpedProtocol = try materializedProtocol(in: machO.context) let name = protocolName.name - // Structurally keyed: `demangleSymbolReference` returns references from + // The first of `symbols` whose first protocol is this one and that no + // earlier requirement claimed — answered from the index's grouping of + // the address by protocol, built once per address (evolution proposal + // `faster-lazy-definition-indexing`); `symbols` is what the index + // listed at its offset. Structurally keyed: references can come from // different stores, and store-identity equality would let the same // implementation symbol be claimed by two requirements. func _symbol(for symbols: Symbols, visitedNodes: borrowing OrderedSet = []) throws -> DemangledSymbol? { - for symbol in symbols { - if let node = SymbolicDemangler.demangleSymbolReference(for: symbol, in: machO), let protocolNode = node.first(of: .protocol), protocolNode.print(using: .interfaceTypeBuilderOnly) == name, !visitedNodes.contains(StructuralNodeReferenceKey(node)) { - return .init(symbol: symbol, demangledNode: node) + for candidate in SymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: name, ownerKind: .protocol, printedWith: .interfaceTypeBuilderOnly, in: machO) { + if !visitedNodes.contains(StructuralNodeReferenceKey(candidate.demangledNode)) { + return candidate } } return nil diff --git a/Sources/MachO/MachOSymbols/SymbolIndexStore.swift b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift index 7d5a4f384..3e13805bf 100644 --- a/Sources/MachO/MachOSymbols/SymbolIndexStore.swift +++ b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift @@ -130,6 +130,18 @@ public final class SymbolIndexStore: @unchecked Sendable { } } + /// What a symbol at an address it shares with others belongs to — how + /// the one a caller is after is told apart from the names identical + /// code folding put beside it. + public enum SymbolOwnerKind: Hashable, Sendable { + /// The type its first protocol conformance names: a protocol + /// witness's conforming type. + case conformingType + /// Its first protocol: a protocol requirement's, or a default + /// implementation's. + case `protocol` + } + public final class Storage: @unchecked Sendable { typealias MemberSymbolRows = OrderedDictionary> @@ -362,6 +374,88 @@ public final class SymbolIndexStore: @unchecked Sendable { _lateDemangledNodeByName.withLockUnchecked { $0[name] } } + // MARK: Symbols grouped by owner + + /// One grouping of an offset's rows: the offset, the rule naming each + /// row's owner, and the options the owner is printed with. + struct OwnerGroupingKey: Hashable { + let offset: Int + let ownerKind: SymbolOwnerKind + let printOptionsRawValue: Int + } + + /// Per queried offset, owner rule and print options, the rows there + /// grouped by the name of their owner, each group in the offset's row + /// order — built the first time the offset is asked about that way + /// (evolution proposal `faster-lazy-definition-indexing`). + /// + /// Identical code folding piles the witnesses of many conformances + /// onto one address: in SwiftUI a single `_destroySelf` or value + /// witness implementation carries well over a thousand names. Every + /// conformance asks the address for its own witness, and answering + /// that by demangling, searching and printing each name in turn was + /// quadratic in the group's size — 3.65 million checks over 17,852 + /// distinct names for SwiftUI alone. Grouping once makes each later + /// question two dictionary probes. + @Mutex + private var rowsByOwnerNameByGroupingKey: [OwnerGroupingKey: [String: [UInt32]]] = [:] + + /// The rows at `offset` whose owner, named by `ownerKind` and printed + /// with `options`, prints as `ownerName`, in the order + /// `symbolRowsByOffset` lists them. + /// + /// The grouping runs outside the lock — it demangles nothing, but it + /// walks and prints trees, which may hop to a large-stack thread — + /// and two threads grouping the same offset at once both do the work; + /// the first to finish is kept, and both answer from the same rows, + /// since the grouping is a pure function of the frozen table. + func rows(at offset: Int, ownedBy ownerName: String, ownerKind: SymbolOwnerKind, options: DemangleOptions) -> [UInt32] { + let groupingKey = OwnerGroupingKey(offset: offset, ownerKind: ownerKind, printOptionsRawValue: options.rawValue) + if let rowsByOwnerName = _rowsByOwnerNameByGroupingKey.withLockUnchecked({ $0[groupingKey] }) { + return rowsByOwnerName[ownerName] ?? [] + } + let rowsByOwnerName = groupRowsByOwnerName(at: offset, ownerKind: ownerKind, options: options) + return _rowsByOwnerNameByGroupingKey.withLockUnchecked { groupings in + if let winner = groupings[groupingKey] { + return winner[ownerName] ?? [] + } + groupings[groupingKey] = rowsByOwnerName + return rowsByOwnerName[ownerName] ?? [] + } + } + + /// The grouping itself, by the rules the attributing code matched + /// one symbol at a time before: the conformance is the first + /// `protocolConformance` node of the symbol's tree in deduped + /// preorder and its owner the conformance's first child; a protocol + /// owner is the first `protocol` node. A row the demangler rejected, + /// or whose tree has no owner, joins no group — it matched nothing + /// before either. + private func groupRowsByOwnerName(at offset: Int, ownerKind: SymbolOwnerKind, options: DemangleOptions) -> [String: [UInt32]] { + guard let rows = symbolRowsByOffset[offset] else { return [:] } + var rowsByOwnerName: [String: [UInt32]] = [:] + for row in rows { + guard let rootNodeIndex = rootNodeIndexByTableRow[Int(row)] else { continue } + let rootNode = nodeStore.reference(at: rootNodeIndex) + let ownerNode: NodeReference? = switch ownerKind { + case .conformingType: + rootNode.first(of: .protocolConformance)?.children.first + case .protocol: + rootNode.first(of: .protocol) + } + guard let ownerNode else { continue } + rowsByOwnerName[ownerNode.print(using: options), default: []].append(row) + } + return rowsByOwnerName + } + + /// Test-only visibility into a grouping: `nil` until the offset has + /// been asked about with that owner rule and those options. + func rowsByOwnerNameForTesting(at offset: Int, ownerKind: SymbolOwnerKind, options: DemangleOptions) -> [String: [UInt32]]? { + let groupingKey = OwnerGroupingKey(offset: offset, ownerKind: ownerKind, printOptionsRawValue: options.rawValue) + return _rowsByOwnerNameByGroupingKey.withLockUnchecked { $0[groupingKey] } + } + // MARK: Row materialization /// Rebuilds the `Symbol` for an offset-table row using the queried @@ -1289,6 +1383,26 @@ public final class SymbolIndexStore: @unchecked Sendable { return .init(offset: offset, symbols: rows.map { storage.symbol(atRow: $0, offset: offset) }) } + /// Of the symbols `symbols(for:in:)` lists at `offset`, the ones whose + /// owner — named by `ownerKind`, printed with `options` — prints as + /// `ownerName`, in that query's order, each paired with its demangled + /// tree: what a conformance asks an implementation address for when it + /// attributes a witness, and a protocol a requirement's or default + /// implementation's address. Each value is standalone and stamped with + /// the queried offset, as a value built from that query's `Symbol` + /// would be. + /// + /// One grouping per offset, owner rule and options, kept with the + /// image's index, answers every later question about it; see + /// `Storage.rows(at:ownedBy:ownerKind:options:)`. + package func symbols(for offset: Int, ownedBy ownerName: String, ownerKind: SymbolOwnerKind, printedWith options: DemangleOptions, in machO: some MachORepresentableWithCache) -> [DemangledSymbol] { + guard let storage = storage(in: machO) else { return [] } + return storage.rows(at: offset, ownedBy: ownerName, ownerKind: ownerKind, options: options).compactMap { row in + guard let rootNodeIndex = storage.rootNodeIndexByTableRow[Int(row)] else { return nil } + return DemangledSymbol(symbol: storage.symbol(atRow: row, offset: offset), demangledNode: storage.nodeStore.reference(at: rootNodeIndex)) + } + } + /// The image's symbolic-mangling symbols — `_symbolic ` and /// `_default assoc type ` — as the build sweep collected them (evolution /// proposal `symbolic-mangling-symbol-index`), building the index on diff --git a/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift b/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift index eac0e1680..694a7fa41 100644 --- a/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift @@ -190,10 +190,15 @@ package struct ProtocolConformanceDumper: Con return nil } + /// The first of `symbols` whose conformance names `typeName` and that no + /// earlier witness claimed, answered from the index's grouping of the + /// address by conforming type (evolution proposal + /// `faster-lazy-definition-indexing`). `symbols` is what the index + /// listed at its offset. package static func demangledSymbol(for symbols: Symbols, typeName: String, visitedNodes: borrowing OrderedSet = [], in machO: MachO) -> DemangledSymbol? { - for symbol in symbols { - if let node = SymbolicDemangler.demangleSymbolReference(for: symbol, in: machO), let targetNode = node.first(of: .protocolConformance), let symbolTypeName = targetNode.children.at(0)?.print(using: .interfaceType), symbolTypeName == typeName, !visitedNodes.contains(StructuralNodeReferenceKey(node)) { - return .init(symbol: symbol, demangledNode: node) + for candidate in SymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: typeName, ownerKind: .conformingType, printedWith: .interfaceType, in: machO) { + if !visitedNodes.contains(StructuralNodeReferenceKey(candidate.demangledNode)) { + return candidate } } return nil diff --git a/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift b/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift index 67b5cfa1a..b3a480ce9 100644 --- a/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift @@ -153,11 +153,15 @@ package struct ProtocolDumper: NamedDumper { /// degraded to `[Stripped Symbol]`). Protocol-side attribution needs its /// own evidence model and is out of scope for the vtable-attribution /// proposal — the folding ambiguity documented there applies here too. + /// + /// Answered from the index's grouping of the address by protocol, built + /// once per address (evolution proposal `faster-lazy-definition-indexing`); + /// `symbols` is what the index listed at its offset. private func validNode(for symbols: Symbols, visitedNode: borrowing OrderedSet = []) async throws -> NodeReference? { let currentInterfaceName = try await _name(using: .options(.interfaceType)).string - for symbol in symbols { - if let node = SymbolicDemangler.demangleSymbolReference(for: symbol, in: machO), let protocolNode = node.first(of: .protocol), await protocolNode.print(using: .interfaceType) == currentInterfaceName, !visitedNode.contains(StructuralNodeReferenceKey(node)) { - return node + for candidate in SymbolIndexStore.shared.symbols(for: symbols.offset, ownedBy: currentInterfaceName, ownerKind: .protocol, printedWith: .interfaceType, in: machO) { + if !visitedNode.contains(StructuralNodeReferenceKey(candidate.demangledNode)) { + return candidate.demangledNode } } return nil diff --git a/Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift b/Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift new file mode 100644 index 000000000..a82adee24 --- /dev/null +++ b/Tests/MachOSymbolsTests/SymbolOwnerGroupingTests.swift @@ -0,0 +1,135 @@ +import Foundation +import Testing +import MachOKit +import MachOResolving +@_spi(Internals) import Demangling +@_spi(Internals) @testable import MachOSymbols +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// Pins `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` — +/// the per-address grouping that tells which of the names identical code +/// folding put on one address belongs to a given conformance or protocol +/// (evolution proposal `faster-lazy-definition-indexing`) — to the +/// one-symbol-at-a-time rule it replaced in `ExtensionDefinition`, +/// `ProtocolDefinition`, `ProtocolConformanceDumper` and `ProtocolDumper`: +/// list the address's symbols, demangle each by its name, take the owner +/// node, print it, compare. +/// +/// SwiftUI in-process, because that is where the folding is heavy: single +/// addresses there carry over a thousand names, so a grouping that dropped a +/// name, kept a rejected one, reordered a group or stamped the wrong offset +/// would show. Every address with more than one name is compared, under both +/// owner rules and both print presets the callers use. +final class SymbolOwnerGroupingSwiftUITests: MachOImageTests, @unchecked Sendable { + override class var imageName: MachOImageName { .SwiftUI } + + @Test(arguments: [ + (SymbolIndexStore.SymbolOwnerKind.conformingType, DemangleOptions.interfaceTypeBuilderOnly), + (SymbolIndexStore.SymbolOwnerKind.conformingType, DemangleOptions.interfaceType), + (SymbolIndexStore.SymbolOwnerKind.protocol, DemangleOptions.interfaceTypeBuilderOnly), + (SymbolIndexStore.SymbolOwnerKind.protocol, DemangleOptions.interfaceType), + ]) + func groupingAnswersLikeTheOneByOneRule(ownerKind: SymbolIndexStore.SymbolOwnerKind, options: DemangleOptions) throws { + let storage = try #require(SymbolIndexStore.shared.storage(in: machOImage)) + let sharedOffsets = storage.symbolRowsByOffset.filter { $0.value.count > 1 }.keys.sorted() + // Not vacuous: the image really folds, at the scale that made the + // one-by-one rule quadratic. + #expect(sharedOffsets.count > 100) + #expect((storage.symbolRowsByOffset.values.map(\.count).max() ?? 0) > 100) + + var comparedOwnerCount = 0 + var mismatchCount = 0 + for offset in sharedOffsets { + let expectedMatchesByOwnerName = OneByOneOwnerRule.matchesByOwnerName(at: offset, ownerKind: ownerKind, options: options, in: machOImage) + for (ownerName, expectedMatches) in expectedMatchesByOwnerName { + let answer = SymbolIndexStore.shared.symbols(for: offset, ownedBy: ownerName, ownerKind: ownerKind, printedWith: options, in: machOImage).map(OneByOneOwnerRule.Match.init) + comparedOwnerCount += 1 + if answer != expectedMatches { + mismatchCount += 1 + if mismatchCount <= 3 { + Issue.record("offset \(offset), owner \(ownerName): grouping answered \(answer.map(\.name)), one by one \(expectedMatches.map(\.name))") + } + } + } + // A name no symbol there is owned by gets nothing. + if !SymbolIndexStore.shared.symbols(for: offset, ownedBy: "No.Such.Owner", ownerKind: ownerKind, printedWith: options, in: machOImage).isEmpty { + mismatchCount += 1 + Issue.record("offset \(offset) answered symbols for an owner none of them has") + } + } + #expect(comparedOwnerCount > 0) + #expect(mismatchCount == 0) + } + + /// Several tasks asking about one address for the first time all build + /// the grouping outside the lock; one is kept, and every task answers + /// with exactly the rows the one-by-one rule finds. Run on a storage + /// built for this test alone, so no other test has grouped the address + /// yet. + @Test func concurrentFirstQuestionsAgree() async throws { + let storage = try #require(SymbolIndexStore.shared.buildStorage(for: machOImage)) + let (offset, rows) = try #require(storage.symbolRowsByOffset.max { $0.value.count < $1.value.count }) + let expectedMatchesByOwnerName = OneByOneOwnerRule.matchesByOwnerName(at: offset, ownerKind: .conformingType, options: .interfaceTypeBuilderOnly, in: machOImage) + let ownerName = try #require(expectedMatchesByOwnerName.max { $0.value.count < $1.value.count }?.key) + let expectedNames = try #require(expectedMatchesByOwnerName[ownerName]).map(\.name) + #expect(storage.rowsByOwnerNameForTesting(at: offset, ownerKind: .conformingType, options: .interfaceTypeBuilderOnly) == nil) + #expect(rows.count > 1) + + let answers = await withTaskGroup(of: [String].self) { group in + for _ in 0 ..< 8 { + group.addTask { + storage.rows(at: offset, ownedBy: ownerName, ownerKind: .conformingType, options: .interfaceTypeBuilderOnly) + .map { storage.symbolTable.materializedName(atRow: $0) } + } + } + var answers: [[String]] = [] + for await answer in group { + answers.append(answer) + } + return answers + } + #expect(answers.count == 8) + #expect(answers.allSatisfy { $0 == expectedNames }) + #expect(storage.rowsByOwnerNameForTesting(at: offset, ownerKind: .conformingType, options: .interfaceTypeBuilderOnly)?[ownerName]?.count == expectedNames.count) + } +} + +/// The rule the grouping replaced, kept here as the reference: every symbol +/// the index lists at the address, demangled by name the way +/// `SymbolicDemangler.demangleSymbolReference` does, its owner taken and +/// printed, in listing order. +enum OneByOneOwnerRule { + struct Match: Equatable { + let name: String + let offset: Int + let node: StructuralNodeReferenceKey + + init(name: String, offset: Int, node: StructuralNodeReferenceKey) { + self.name = name + self.offset = offset + self.node = node + } + + init(_ demangledSymbol: DemangledSymbol) { + self.init(name: demangledSymbol.name, offset: demangledSymbol.offset, node: StructuralNodeReferenceKey(demangledSymbol.demangledNode)) + } + } + + static func matchesByOwnerName(at offset: Int, ownerKind: SymbolIndexStore.SymbolOwnerKind, options: DemangleOptions, in machO: MachOImage) -> [String: [Match]] { + guard let symbols = SymbolIndexStore.shared.symbols(for: offset, in: machO) else { return [:] } + var matchesByOwnerName: [String: [Match]] = [:] + for symbol in symbols { + guard let node = SymbolIndexStore.shared.demangledNodeReference(for: symbol, in: machO) else { continue } + let ownerNode: NodeReference? = switch ownerKind { + case .conformingType: + node.first(of: .protocolConformance)?.children.first + case .protocol: + node.first(of: .protocol) + } + guard let ownerNode else { continue } + matchesByOwnerName[ownerNode.print(using: options), default: []].append(Match(name: symbol.name, offset: symbol.offset, node: StructuralNodeReferenceKey(node))) + } + return matchesByOwnerName + } +} From 614a291016882f80ccfd66b3ce7918bd0f3a0b73 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 13 Oct 2026 12:36:08 +0800 Subject: [PATCH 43/49] perf(rendering): search the property wrapper catalog outside its lock `PropertyWrapperTypeCatalog.evidence(forWrapperCandidate:)` held its lock across the whole lookup: the export-trie searches of the root image and of its dependency closure, the demangling of their hits, and the first resolution of the closure itself. Printing an image four ways at once, every caller queued there, even for a prefix whose verdict was already known -- 8% of the time a Find corpus took. The lock now guards only the verdict cache: searches run outside it, concurrent first searches of one prefix each finish and the first stored verdict wins. The dependency lookups are resolved once under a lock of their own. With the lock gone, what remained was resolving the closure: `InProcessDependencyLocator` called `MachOImage(name:)` per dependency, which splits the path of every image mapped in the process, so a closure of a few hundred dependencies in a process with a thousand images mapped split paths hundreds of thousands of times while the other printing tasks waited. The locator now builds a bare-name table from one pass over the mapped images, keeping the first image per name -- the one `MachOImage(name:)` picks. An image mapped after the locator was made is not one it knows; `DependencyClosure(root: MachOImage)` makes a new locator each time. `PropertyWrapperTypeCatalogLockTests` holds one search in its lookup and requires an answered prefix to return meanwhile: it times out after 10 seconds on the old shape and passes now. `InProcessDependencyLocatorTests` compares the locator with `MachOImage(name:)` for every mapped image. ReviewAdjudications A61 item four is re-adjudicated: it weighed only thread hops under the lock, not the long critical section itself. Proposal: draft-faster-lazy-definition-indexing. --- .../Internal/Modules/MachODependencies.md | 3 +- .../Internal/ReviewAdjudications.md | 3 +- .../DependencyLocating.swift | 34 ++++++- .../PropertyWrapperTypeCatalog.swift | 61 +++++++++--- .../InProcessDependencyLocatorTests.swift | 50 ++++++++++ .../PropertyWrapperTypeCatalogLockTests.swift | 99 +++++++++++++++++++ 6 files changed, 234 insertions(+), 16 deletions(-) create mode 100644 Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift create mode 100644 Tests/SwiftDeclarationRenderingTests/PropertyWrapperTypeCatalogLockTests.swift diff --git a/Documentations/Internal/Modules/MachODependencies.md b/Documentations/Internal/Modules/MachODependencies.md index f905c0b84..e8348ef89 100644 --- a/Documentations/Internal/Modules/MachODependencies.md +++ b/Documentations/Internal/Modules/MachODependencies.md @@ -40,7 +40,7 @@ bare name 同时是所有依赖集合的**去重键**:同一个库会被不同 `DependencyLocating` 只有一个方法 `locate(loadName:)`,收到的是 load command 里的**原始拼写**,归一由实现自己做。这让遍历与「镜像从哪来」解耦:进程内、磁盘搜索路径、测试里手搭的表,都是一个实现。 -- **`InProcessDependencyLocator`**:归一后走 `MachOImage(name:)`。系统框架天然从 cache 解析;`@rpath` 依赖只要已映射进进程也能解析;弱链接但未映射的(如 `libswiftCoreAudio`)解析不到,进 `unresolvedLoadNames`。 +- **`InProcessDependencyLocator`**:归一后查一张「bare name → 镜像」表。系统框架天然从 cache 解析;`@rpath` 依赖只要已映射进进程也能解析;弱链接但未映射的(如 `libswiftCoreAudio`)解析不到,进 `unresolvedLoadNames`。表在定位器构造时建:遍历一遍 dyld 已映射的镜像,同名只留第一个——与 `MachOImage(name:)` 的选择逐个一致(同一条归一规则、同样「第一个匹配,没有 header 就是 nil」),只是不再每次查询都把所有镜像的路径重新拆一遍。改前一个几百个依赖的闭包、在映射了上千个镜像的进程里要拆几十万次路径,RuntimeViewer 并行打印时其余线程都排在第一个建闭包的 catalog 后面(2026-10-13,提案 `faster-lazy-definition-indexing`)。代价:定位器构造之后才映射的镜像它看不到,新建一个定位器就能看到;`DependencyClosure(root: MachOImage)` 每次都新建。 - **`FileDependencyLocator`**:两步查找,顺序固定: 1. **install path 精确匹配**——系统框架的 load name 就是 cache 镜像的 `imagePath`,命中即是编译器自己的答案。显式文件同时以「传入的磁盘路径」和「文件的 install name(`LC_ID_DYLIB`,通常 `@rpath/…`)」两种拼写登记,因为 `MachOFile.imagePath` 是 install name 而非磁盘路径。 2. **bare name 排序兜底**——`@rpath/…` 或 cache 不认识的路径拼写落到这里。cache 里 leaf name 不唯一:macOS cache 在 `/System/iOSSupport` 下带着 Mac Catalyst 版 SwiftUI,iOS cache 有同名 `.axbundle`。候选按 MachOKitExtensions 的 `DyldCacheImageSearchMode.matchRank` 排序(canonical framework > 普通 dylib > bundle,support root 降级),取最优。**旧的 SwiftLayout 定位器是「枚举顺序首写者胜」**,在 macOS cache 上可能选中 Catalyst 构建——这是合并时消除的潜在错配(`FileDependencyLocatorTests.bareNameFallbackPrefersTheNativeCanonicalFramework` 锁定)。`matchRank` 对多点 leaf(`libc++.1.dylib`)返回 `nil`,此时记为最差 rank 但仍可解析。 @@ -86,6 +86,7 @@ providerDependencies.unresolvedLoadNames // 精确报告解析不到的依赖 ## 测试锚点 - `Tests/MachODependenciesTests/DependencyLoadNameTests.swift` — 归一规则表 + 与 `MachOImage(name:)` 的契约。 +- `Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift` — 进程里每个已映射镜像的路径(加上几个不存在的拼写),定位器的答案与 `MachOImage(name:)` 指向同一个镜像。 - `Tests/MachODependenciesTests/DependencyClosureTests.swift` — direct / transitive 语义、BFS 前缀、去重、未解析报告、坏搜索路径不抛、自定义定位器收到原始 load name。 - `Tests/MachODependenciesTests/FileDependencyLocatorTests.swift` — 宿主 cache 上的精确路径优先与 Catalyst 降级(无宿主 cache 时跳过);平台守卫(`LC_BUILD_VERSION` 读取、`areCompatible` 规则、iOSSimulator root 在宿主 cache 上一无所获、zippered root 可取 Catalyst 镜像)。 - `Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift` — cache 里的 root 在自己的 cache 里找依赖(按 `LC_UUID` 认出找到的是 15.5 的 Foundation,前提是宿主的 Foundation 是另一个构建),两种打开方式各一例;点名同一个 cache 时用的仍是 root 来自的那个实例。没有归档的 15.5 cache 时跳过。 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index e361d7640..806ea562e 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -713,7 +713,7 @@ ## A61 — 持锁时 demangle 的五处:打印器的一次性建表、静态布局 provider、关联类型成员投影、property wrapper 目录、ObjC 祖先解析(「持锁时 demangle」横向排查) -- **裁决**:五处的锁都不改(2026-10-11)。排查中发现的入口漏包已修,见第三处。 +- **裁决**:五处的锁都不改(2026-10-11)。排查中发现的入口漏包已修,见第三处。第四处 2026-10-13 因并行打印下的实测排队改判为修,见第四处。 - **背景**:审查提案 [0063-private-declarations](../Evolutions/0063-private-declarations.md) 时,它的 index 持锁读名字,违反 AGENTS.md 当时的「Do not hold a lock across a demangle」。这条规则来自 [NodeStoreMigrationOpenIssues 第 9 条](NodeStoreMigrationOpenIssues.md):在 512 KB 栈的线程上,每次 demangle、打印都要切到大栈线程、用信号量等结果;持锁时这样一等,所有等这把锁的线程都排在后面。危害要两个条件同时成立:调用方在小栈上,并且有别的线程在等同一把锁。横向排查找到下面五处同样的写法,外加 `IndexerConformanceProvider.classHierarchy()` 一处。后者 RuntimeViewer 从 actor 里同步调用,已修:缓存没命中时先切一次大栈,再在大栈上取锁建表(`ClassHierarchyBuildStackTests`)。规则因此改写成「持锁时 demangle 不许切线程」:要么已经在大栈上(`LargeStackTaskExecution.run` 包过的入口里,或者取锁前先 `StackSafeExecutor.withLargeStack`),要么锁外 demangle、锁内 insert-if-absent。下面五处靠的是入口的执行器:库内和 RuntimeViewer 的调用都经包过执行器的 async 入口进来,macOS 15 起在 16 MB 栈上执行,持锁期间不切线程。 - **一、`SwiftDeclarationPrinter` 的两次建表**(`SwiftDeclarationPrinter.swift:93` 的 `@_rawLayout` 存储表、`:118` 的静态布局 provider):都是 printer 实例上的 `@Mutex`,第一次用到时在锁内建表,命中也拿同一把锁。`:93` 对每个 `__swift5_builtin` 描述符做一次 `demangleType`;`:118` 对 `MachOFile` 建依赖闭包,要把根镜像的全部描述符 demangle 一遍(`MachOImage` 直接返回 nil)。唯一入口 `printTypeDefinition` 已包执行器。 - **二、`MachOFileStaticFieldLayoutProvider`**(`StaticFieldLayoutProvider.swift:129` 的锁,11 个查询方法每次都拿):底层计算器的 memo 不是线程安全的(`:124-126` 的注释),所以每次查询都在锁内算;懒加载依赖镜像时,会在锁内把整个依赖镜像 demangle 一遍。只服务 `MachOFile`。异步入口(打印、dump)已包执行器。同步的 public 入口有 provider 自己的方法、`MachOFile.precomputedStaticAggregateFieldLayout` 和 `MachOFile.renderFieldOffsets`,库内和 RuntimeViewer 都没有从小栈调用。 @@ -721,6 +721,7 @@ - **排查中发现的入口漏包(已修)**:`TypeDefinition.specialize(...)` 的四个 async 重载(运行时两个、离线两个)没有包执行器。RuntimeViewer 在 actor 里调用其中一个(`RuntimeSwiftSection.swift:935`)。当某个 fixed 参数的 same-type 右侧代换后带 `dependentMemberType` 时,这条路会经 `GenericInstantiation` 在 512 KB 栈上拿这把锁,并逐次切线程。本批把四个重载都包上了 `LargeStackTaskExecution.run`(`SpecializationEntryPointExecutorTests`),和其它 async 入口一致。 - 同步的 `GenericSpecializer.specialize(_:with:)` / `staticPreflight` 也会走到这里,只服务 `MachOFile`。 - **四、`PropertyWrapperTypeCatalog`**(`:140`,每个镜像一个 catalog):每次查询都拿锁。没命中时在锁内 demangle 导出符号名(`:173`),第一次没命中还要建依赖闭包。入口是 `TypeDefinition.index(in:)`,调用方都在已包的入口里,包括打印、索引,以及 diff 和 evolution 渲染。同步 public 入口 `evidence(forWrapperCandidate:)` 没有人从小栈调用。 + - **改判为修(2026-10-13,提案 [draft-faster-lazy-definition-indexing](../Evolutions/draft-faster-lazy-definition-indexing.md))**:本条只考虑了「切线程时排队」,没有考虑长临界区本身。RuntimeViewer 的 Find 语料在一个镜像上 4 路并行打印,调用方都在大栈上、一次也不切线程,但锁里做的是根镜像加整个依赖闭包的导出表搜索,别的线程连已有结论的前缀都要排队:Release 采样里这把锁的等待占语料时间约 8%。锁现在只包结论缓存的读与写,搜索与 demangle 在锁外,并发的首次查询各算各的、先写入者胜;依赖闭包用另一把锁只建一次。`PropertyWrapperTypeCatalogLockTests` 在旧写法下 10 秒超时失败、新写法通过。其余四处的裁决不变,第五处 `ObjCAncestorResolver` 同样是「持锁建闭包」,进程内场景下它的类别扫描跳过 cache 内的全部镜像,开销主要是第一次建闭包,已随 `InProcessDependencyLocator` 改为查表而变小,先不改锁。 - **五、`ObjCAncestorResolver`**(`:92`、`:133`,每个镜像一个 resolver):原先列为疑似,核实属实,但有条件。依赖镜像的 `ObjCClassMethodIndex` 存储(进程级、按镜像共享)第一次建的时候,会在锁内给每个 Swift 类 demangle 一次限定名(`ObjCClassMethodIndex.swift:444` → `NodeTypeNaming`)。入口经 `index(in:)`、`prepare()` 和 `Class.dump`,都已包执行器。同步 public 入口是 `ObjCMembers.table(forSwiftClassQualifiedName:in:)`。 - **复现 / 是否误报**:五处的机制都属实。输出层面复现不出:结果不会错,只会在「小栈调用 + 有人等锁」时多等。第三处的漏包修掉之后,库内和 RuntimeViewer 的调用路径都不满足第一个条件。 - **与 main 基线对比**:五处的锁在 main(0.22.0)上都有。第二处按 binding 查询的四个方法和 `projectingConcreteMembers` 来自离线特化(`b72638f8`、`5308fa1a`),main 上没有。第三处的漏包入口里,运行时的两个重载 main 上就有;从它们走到这把锁的那一步(`GenericInstantiation`,`6c35e8c4`,2026-10-08)main 上没有。 diff --git a/Sources/MachO/MachODependencies/DependencyLocating.swift b/Sources/MachO/MachODependencies/DependencyLocating.swift index 5ff961276..76fef1f9a 100644 --- a/Sources/MachO/MachODependencies/DependencyLocating.swift +++ b/Sources/MachO/MachODependencies/DependencyLocating.swift @@ -1,3 +1,6 @@ +#if canImport(Darwin) +import Darwin +#endif import MachOKit import MachOKitExtensions @@ -17,12 +20,37 @@ public protocol DependencyLocating { /// Resolves dependencies through the active dyld: system frameworks resolve /// from the shared cache automatically, and locally loaded frameworks resolve /// as long as they are already mapped into this process. +/// +/// Answers from a table of the images dyld had mapped when the locator was +/// made: one pass over them, keeping the first image per bare name — the +/// image `MachOImage(name:)` picks, by the same naming rule — instead of that +/// initializer's own pass per lookup. A closure of a few hundred +/// dependencies, in a process with a thousand images mapped, split the same +/// paths hundreds of thousands of times and kept every other printing task +/// waiting on its catalog meanwhile (evolution proposal +/// `faster-lazy-definition-indexing`). An image mapped after the locator was +/// made is not found by it; a new locator sees it. public struct InProcessDependencyLocator: DependencyLocating, Sendable { - public init() {} + /// Per bare name, the first mapped image carrying it — `nil` when dyld + /// had no header for that image, as `MachOImage(name:)` answers then. + private let imagesByBareName: [String: MachOImage?] + + public init() { + var imagesByBareName: [String: MachOImage?] = [:] + #if canImport(Darwin) + for index in 0 ..< _dyld_image_count() { + guard let pathC = _dyld_get_image_name(index) else { continue } + let bareImageName = DependencyLoadName.bareImageName(of: String(cString: pathC)) + guard imagesByBareName[bareImageName] == nil else { continue } + imagesByBareName.updateValue(_dyld_get_image_header(index).map { MachOImage(ptr: $0) }, forKey: bareImageName) + } + #endif + self.imagesByBareName = imagesByBareName + } public func locate(loadName: String) -> MachOImage? { let bareImageName = DependencyLoadName.bareImageName(of: loadName) - guard !bareImageName.isEmpty else { return nil } - return MachOImage(name: bareImageName) + guard !bareImageName.isEmpty, let image = imagesByBareName[bareImageName] else { return nil } + return image } } diff --git a/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift index 58a8bb421..18ad413e6 100644 --- a/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift +++ b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift @@ -76,10 +76,23 @@ public final class PropertyWrapperTypeCatalog: @unchecked Sendable { private let rootLookup: ExportedSymbolNamesLookup? private let makeDependencyLookups: @Sendable () -> [ExportedSymbolNamesLookup] - private let lock = NSLock() - private var dependencyLookups: [ExportedSymbolNamesLookup]? + + /// Guards `memoizedEvidenceByPrefix` only, and is held only to read or + /// insert a verdict: the export-trie searches and the demangling of their + /// hits run outside it, so a verdict already known is never kept waiting + /// behind someone else's search (evolution proposal + /// `faster-lazy-definition-indexing` — printing an image four ways at + /// once spent 8% of its time queued here). + private let memoizedEvidenceLock = NSLock() private var memoizedEvidenceByPrefix: [String: PropertyWrapperEvidence?] = [:] + /// Guards the one-time resolution of the dependency closure. Held across + /// it on purpose: a caller that needs the dependency lookups has nothing + /// to do until they exist, and resolving the closure twice would load + /// every dependency twice. + private let dependencyLookupsLock = NSLock() + private var dependencyLookups: [ExportedSymbolNamesLookup]? + public init(rootLookup: ExportedSymbolNamesLookup?, dependencyLookups: @escaping @Sendable () -> [ExportedSymbolNamesLookup]) { self.rootLookup = rootLookup self.makeDependencyLookups = dependencyLookups @@ -135,11 +148,15 @@ public final class PropertyWrapperTypeCatalog: @unchecked Sendable { /// root image's exports first, then the dependency closure's in /// resolution order, stopping at the first image exporting a /// `wrappedValue` accessor of the type. `nil` when none does. + /// + /// A prefix asked for twice at once is searched twice; the first verdict + /// stored is the one every later caller gets. Both searches read the + /// same export tries, so both reach the same verdict. Concurrent callers + /// only ever come from parallel printing, which is supported on + /// in-process images alone, whose export tries are read from memory. public func evidence(forWrapperCandidate nominalTypeNode: Node) -> PropertyWrapperEvidence? { guard let prefix = Self.wrappedValueSymbolPrefix(of: nominalTypeNode) else { return nil } - lock.lock() - defer { lock.unlock() } - if let memoized = memoizedEvidenceByPrefix[prefix] { + if let memoized = memoizedEvidenceLock.withLock({ memoizedEvidenceByPrefix[prefix] }) { return memoized } var evidence: PropertyWrapperEvidence? @@ -147,18 +164,40 @@ public final class PropertyWrapperTypeCatalog: @unchecked Sendable { evidence = Self.evidence(fromExportedSymbolNames: rootLookup(prefix)) } if evidence == nil { - if dependencyLookups == nil { - dependencyLookups = makeDependencyLookups() - } - for dependencyLookup in dependencyLookups ?? [] { + for dependencyLookup in resolvedDependencyLookups() { if let found = Self.evidence(fromExportedSymbolNames: dependencyLookup(prefix)) { evidence = found break } } } - memoizedEvidenceByPrefix[prefix] = evidence - return evidence + return memoizedEvidenceLock.withLock { + if let winner = memoizedEvidenceByPrefix[prefix] { + return winner + } + // `updateValue` stores a `nil` verdict unambiguously, as + // `SymbolIndexStore`'s late-demangle cache does. + memoizedEvidenceByPrefix.updateValue(evidence, forKey: prefix) + return evidence + } + } + + /// The dependency closure's lookups, resolved on first use. + private func resolvedDependencyLookups() -> [ExportedSymbolNamesLookup] { + dependencyLookupsLock.withLock { + if let dependencyLookups { + return dependencyLookups + } + let resolvedLookups = makeDependencyLookups() + dependencyLookups = resolvedLookups + return resolvedLookups + } + } + + /// Whether `prefix` has a verdict yet, and which. Test seam: `.none` + /// until a search for the prefix has stored one. + package func memoizedEvidenceForTesting(prefix: String) -> PropertyWrapperEvidence?? { + memoizedEvidenceLock.withLock { memoizedEvidenceByPrefix[prefix] } } /// Folds the accessor symbols found under one prefix into evidence: diff --git a/Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift b/Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift new file mode 100644 index 000000000..5d15f24fe --- /dev/null +++ b/Tests/MachODependenciesTests/InProcessDependencyLocatorTests.swift @@ -0,0 +1,50 @@ +#if canImport(Darwin) +import Darwin +#endif +import Foundation +import MachOKit +import Testing +@testable import MachODependencies + +/// `InProcessDependencyLocator` answers from one pass over the images dyld +/// has mapped (evolution proposal `faster-lazy-definition-indexing`) and must +/// answer exactly what `MachOImage(name:)`, the per-lookup scan it replaced, +/// answers: the first mapped image carrying the bare name, or nothing. +/// +/// Every mapped image's own path is asked for — absolute paths of system +/// frameworks, Swift runtime dylibs and the test bundle alike, including +/// names several mapped images share — together with load-name spellings +/// that must not resolve. The paths are read before the locator is made: +/// other suites map fixtures while this one runs, and an image mapped after +/// the locator was made is, by design, not one it knows. +@Suite +struct InProcessDependencyLocatorTests { + @Test func answersLikeTheNameLookup() throws { + var loadNames: Set = [ + "/usr/lib/libNoSuchImage.dylib", + "@rpath/NoSuchFramework.framework/Versions/A/NoSuchFramework", + "", + ] + #if canImport(Darwin) + for index in 0 ..< _dyld_image_count() { + if let pathC = _dyld_get_image_name(index) { + loadNames.insert(String(cString: pathC)) + } + } + #endif + #expect(loadNames.count > 50) + let locator = InProcessDependencyLocator() + + var mismatchCount = 0 + for loadName in loadNames.sorted() { + let bareImageName = DependencyLoadName.bareImageName(of: loadName) + let expectedImage = bareImageName.isEmpty ? nil : MachOImage(name: bareImageName) + let locatedImage = locator.locate(loadName: loadName) + if locatedImage?.ptr != expectedImage?.ptr { + mismatchCount += 1 + Issue.record("\(loadName): located \(String(describing: locatedImage?.ptr)), MachOImage(name:) \(String(describing: expectedImage?.ptr))") + } + } + #expect(mismatchCount == 0) + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/PropertyWrapperTypeCatalogLockTests.swift b/Tests/SwiftDeclarationRenderingTests/PropertyWrapperTypeCatalogLockTests.swift new file mode 100644 index 000000000..7d187d4b4 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/PropertyWrapperTypeCatalogLockTests.swift @@ -0,0 +1,99 @@ +import Foundation +import Testing +import Demangling +@testable import SwiftDeclarationRendering + +/// `PropertyWrapperTypeCatalog.evidence(forWrapperCandidate:)` holds its lock +/// only to read or store a verdict; the export-trie searches and the +/// demangling of their hits run outside it (evolution proposal +/// `faster-lazy-definition-indexing`). Before, the whole search ran under the +/// lock, so with an image printed four ways at once a caller whose verdict +/// was already known queued behind every other caller's search — 8% of the +/// time the prints took. +/// +/// The searches here are closures the test controls: one of them stays in +/// its search until released, and a caller asking about another, already +/// answered type must get its verdict meanwhile. Both sides run on threads of +/// their own, never on the cooperative pool, and the waiting side waits with +/// a deadline, so a catalog that serializes again fails instead of hanging. +@Suite +struct PropertyWrapperTypeCatalogLockTests { + /// The `.type` node of a struct `module.name`, the shape + /// `WrappedPropertyRecovery.nominalTypeNode(ofFieldType:)` hands over. + private static func nominalTypeNode(module: String, name: String) throws -> Node { + let descriptorNode = try demangleAsNode("$s\(module.count)\(module)\(name.count)\(name)VMn") + return try #require(descriptorNode.first(of: .type)) + } + + @Test func knownVerdictIsNotQueuedBehindASearch() throws { + let answeredNode = try Self.nominalTypeNode(module: "Test", name: "Wrapper") + let searchedNode = try Self.nominalTypeNode(module: "Test", name: "Slow") + let searchedPrefix = try #require(PropertyWrapperTypeCatalog.wrappedValueSymbolPrefix(of: searchedNode)) + let searchStarted = DispatchSemaphore(value: 0) + let searchReleased = DispatchSemaphore(value: 0) + // Every prefix answers with the getter of an `Int` `wrappedValue`; + // the searched one only once released. + let catalog = PropertyWrapperTypeCatalog(rootLookup: { prefix in + if prefix == searchedPrefix { + searchStarted.signal() + searchReleased.wait() + } + return [prefix + "Sivg"] + }, dependencyLookups: { [] }) + + #expect(catalog.evidence(forWrapperCandidate: answeredNode) != nil) + + let searchFinished = DispatchSemaphore(value: 0) + Thread { + _ = catalog.evidence(forWrapperCandidate: searchedNode) + searchFinished.signal() + }.start() + searchStarted.wait() + + let answered = DispatchSemaphore(value: 0) + Thread { + _ = catalog.evidence(forWrapperCandidate: answeredNode) + answered.signal() + }.start() + let isAnsweredDuringTheSearch = answered.wait(timeout: .now() + 10) == .success + + searchReleased.signal() + searchFinished.wait() + if !isAnsweredDuringTheSearch { + answered.wait() + } + #expect(isAnsweredDuringTheSearch) + #expect(catalog.memoizedEvidenceForTesting(prefix: searchedPrefix) != nil) + } + + /// A type the search finds nothing for is remembered as such, and asked + /// again without searching. + @Test func absentVerdictIsRemembered() throws { + let node = try Self.nominalTypeNode(module: "Test", name: "NotAWrapper") + let prefix = try #require(PropertyWrapperTypeCatalog.wrappedValueSymbolPrefix(of: node)) + let searchCount = SearchCounter() + let catalog = PropertyWrapperTypeCatalog(rootLookup: { _ in + searchCount.increment() + return [] + }, dependencyLookups: { [] }) + + #expect(catalog.evidence(forWrapperCandidate: node) == nil) + #expect(catalog.evidence(forWrapperCandidate: node) == nil) + #expect(searchCount.value == 1) + let storedVerdict = try #require(catalog.memoizedEvidenceForTesting(prefix: prefix)) + #expect(storedVerdict == nil) + } +} + +private final class SearchCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + + var value: Int { + lock.withLock { count } + } + + func increment() { + lock.withLock { count += 1 } + } +} From 99c6e738d543953510ea76c53b010c82c5e77c74 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 13 Oct 2026 12:36:41 +0800 Subject: [PATCH 44/49] docs: land proposal 0065 (faster-lazy-definition-indexing) as Implemented --- AGENTS.md | 2 +- ...n-indexing.md => 0065-faster-lazy-definition-indexing.md} | 5 +++-- Documentations/Evolutions/README.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 4 ++-- Documentations/Internal/ReviewAdjudications.md | 2 +- Documentations/README.md | 2 +- 6 files changed, 9 insertions(+), 8 deletions(-) rename Documentations/Evolutions/{draft-faster-lazy-definition-indexing.md => 0065-faster-lazy-definition-indexing.md} (94%) diff --git a/AGENTS.md b/AGENTS.md index 1510d55d6..2ede5fb20 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -189,7 +189,7 @@ Each of these fails **silently**, and several produce a real, fully-qualified, * - **A runtime metatype becomes a node only through `RuntimeTypeNameDemangling.node(forMetatype:)`, never bare `_mangledTypeName` + demangle.** The runtime spells a private type's anonymous context by its descriptor address, which the printers render as nothing or as `(unknown context at $…)` — a specialized header read `struct .WindowPortal<…>`, and a private type argument lost its module and every enclosing type. - **An anonymous context's name is the compiler's whole mangling of what it stands for — a function, a closure, or the private or local type it wraps — never a fragment of it.** It comes from the descriptor's own name (debug builds only), the `$sMXX` symbol on the descriptor, or a `_symbolic` referent (`AnonymousContextNameIndex`); a private discriminator is read off the wrapped type's own `privateDeclName` and nothing else. Taking `first(of: .privateDeclName)` from the context's name borrowed an enclosing private function's discriminator and faked private types, and dropping the context lost every local type's function, so two methods' `Visitor`s merged into one definition. A local type no source names is position-named `Holder.(Visitor in $
)` — tell it from a private type with `localTypeNaming`, never by string ([0062-local-type-context-names](Documentations/Evolutions/0062-local-type-context-names.md)). - **Do NOT call bare `NodeReference(interning:)` on a batch path** — route through `InternedNodeReferenceCache`. -- **Picking the symbol that belongs to a given conformance or protocol out of an address's `Symbols` goes through `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)`, never a loop that demangles, searches and prints each symbol.** Identical code folding puts over a thousand names on one SwiftUI witness address and every conformance asks that address again: four such loops (extension and protocol indexing, both protocol dumpers) made the attribution quadratic — half the time of printing a whole image. The query groups an address once and answers from the grouping ([draft-faster-lazy-definition-indexing](Documentations/Evolutions/draft-faster-lazy-definition-indexing.md)). +- **Picking the symbol that belongs to a given conformance or protocol out of an address's `Symbols` goes through `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)`, never a loop that demangles, searches and prints each symbol.** Identical code folding puts over a thousand names on one SwiftUI witness address and every conformance asks that address again: four such loops (extension and protocol indexing, both protocol dumpers) made the attribution quadratic — half the time of printing a whole image. The query groups an address once and answers from the grouping ([0065-faster-lazy-definition-indexing](Documentations/Evolutions/0065-faster-lazy-definition-indexing.md)). - **A `_symbolic` symbol's referents are one mangling, not several.** The compiler appends them with one mangler, so a later referent reuses substitutions and words of the earlier ones (`7SwiftUI19_ConditionalContentV AA08ModifiedD0V`); demangled alone it fails or names something else. Take referents from `SymbolicManglingIndex.referentNode(of:in:)`, which demangles them together — and for the same reason never splice referents into the mangled name as text. - **Resolving one type's members/info/attributes must use the node-taking overloads** (`memberSymbols(of:for:node:in:)` and friends). The name-only forms flatten every sub-bucket on purpose: the name key is printed with `.interfaceTypeBuilderOnly`, which strips private discriminators, so same-named private types share a bucket (issue #115). - **Never let a demangle or print hop while you hold a lock.** On a 512 KB thread each call hops to a large-stack worker and blocks on it, so every thread waiting on the lock waits behind the hop — without bound once the pool saturates (`SymbolIndexStore.lateDemangledNode`, 2026-08-03). Under a lock, either be on a large stack already — inside a `LargeStackTaskExecution.run` entry point, or past one `StackSafeExecutor.withLargeStack` taken *before* locking (`IndexerConformanceProvider.classHierarchy()`) — or demangle outside the lock and insert-if-absent under it. A synchronous API runs on whatever thread its host calls it from. The sites that rely on their entry point's executor: [ReviewAdjudications A61](Documentations/Internal/ReviewAdjudications.md). diff --git a/Documentations/Evolutions/draft-faster-lazy-definition-indexing.md b/Documentations/Evolutions/0065-faster-lazy-definition-indexing.md similarity index 94% rename from Documentations/Evolutions/draft-faster-lazy-definition-indexing.md rename to Documentations/Evolutions/0065-faster-lazy-definition-indexing.md index 161cd0f67..04e892396 100644 --- a/Documentations/Evolutions/draft-faster-lazy-definition-indexing.md +++ b/Documentations/Evolutions/0065-faster-lazy-definition-indexing.md @@ -1,6 +1,6 @@ -# Draft - 并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找 +# 0065 - 并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-10-13 - **最后更新**: 2026-10-13 - **关联提案**: [draft-concurrent-definition-printing](draft-concurrent-definition-printing.md)(同版本内并行打印的前提)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(`SharedCache` 的现行形态) @@ -57,3 +57,4 @@ RuntimeViewer 的 Find 语料要把一个镜像的全部定义打印一遍(进 | 2026-10-13 | ReviewAdjudications A61 第四处(`PropertyWrapperTypeCatalog`)改判为修 | A61 只考虑了「小栈调用方持锁切线程」,没考虑长临界区本身:并行打印的调用方都在大栈上、不切线程,照样排在别人的导出表搜索后面。 | | 2026-10-13 | 验证通过 | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,`USING_LOCAL_DEPENDENCIES=1`):2442 个测试 / 468 个套件,原始退出码 1,失败的只有两条 `MultiPayloadEnumDescriptorCacheTests`,在基线 next `5dca3331` 的 release 测试包上同样两条、同样失败点。渲染 A/B(基线为钉在 `5dca3331` 的 detached worktree,两侧共用本地兄弟依赖与同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build`):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 缺的三个框架与 iOS 27.0 / 27.1 模拟器(框架在 cache 里)按设计跳过。 | | 2026-10-13 | 实测(RuntimeViewer 探针,进程内,每镜像 4 路,M1 Max,基线与候选交替两轮,负载 6–13):Release 合计 20.3 s → 8.4 s(SwiftUI 8.8 → 2.7,SwiftUICore 6.0 → 1.9,AppKit 2.9 → 2.4,Foundation 1.4 → 1.0,libswiftCore 1.2 → 0.4),CPU 64.5 s → 30 s;Debug 合计 103.7 s → 52.6 s(SwiftUI 47.0 → 18.1,SwiftUICore 32.2 → 12.3) | 同一份 RuntimeViewerCore(next `4fc214ad`)与锁文件,只把 MachOSwiftSection 用 SwiftPM edit 模式换成本分支。修后采样:`ExtensionDefinition` 索引从 53% 降到 7%,锁慢路径合计 1.7%;剩下的大头是 ObjC 打印(约四分之一)、`TypeDefinition` 索引(约五分之一)和字段布局(约 8%)。 | +| 2026-10-13 | 落地为 0065,Implemented:合入 next | 配套文档不另写:实现说明落在 [Modules/MachOSymbols.md](../Internal/Modules/MachOSymbols.md)「同一地址上的符号按归属分组」与 [Modules/MachODependencies.md](../Internal/Modules/MachODependencies.md)「定位器」,规则进了 AGENTS.md;术语表无新增(`SymbolOwnerKind` 是 API 名,不是新概念)。演进账本第 91 节。 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 91be05ac0..9707e2464 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -78,4 +78,4 @@ | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | | [0063](0063-private-declarations.md) | 私有声明:从名字取 discriminator,按镜像反推源文件 | Implemented | | [0064](0064-module-selectors.md) | 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 | Implemented | -| draft | [并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找](draft-faster-lazy-definition-indexing.md) | In Progress | +| [0065](0065-faster-lazy-definition-indexing.md) | 并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找 | Implemented | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 9829e992e..cc872c017 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2461,7 +2461,7 @@ - **关联文档**:[0064-module-selectors](../Evolutions/0064-module-selectors.md)、swift-demangling 提案 `0017-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 - **对应版本**:下一个版本(未发版);发版前 swift-demangling 要先发版(新选项 `useModuleSelectors`),再抬本库的版本范围。 -## 2026-10-13 并行打印下的惰性索引提速(节号落地时分配) +## 91. 并行打印下的惰性索引提速 - **时间段**:2026-10-13。 - **动机**:RuntimeViewer 用户报「Find 构建可搜索的语料还是太慢」。RuntimeViewer 的计时探针在 M1 Max 上测 AppKit、SwiftUI、SwiftUICore、libswiftCore、Foundation 的语料:Release 约 20 s,用户日常用的 Debug 约 104 s。整轮采样显示时间不在 RuntimeViewer,而在本库打印时触发的惰性索引:给 resilient witness 找实现符号占 50–53%,Release 下 `SharedCache` 的锁慢路径 25%,属性包装器目录持锁搜导出表 8%。 @@ -2477,7 +2477,7 @@ - RuntimeViewer 探针(同一份 RuntimeViewerCore 与锁文件,只把本库用 SwiftPM edit 模式换成本分支,基线与候选交替两轮,负载 6–13):Release 20.3 s → 8.4 s、CPU 64.5 s → 30 s;Debug 103.7 s → 52.6 s。 - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,`USING_LOCAL_DEPENDENCIES=1`):2442 个测试 / 468 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`(基线 next `5dca3331` 上同样失败)。 - 渲染 A/B(基线 next `5dca3331` 的 detached worktree,两侧共用本地兄弟依赖与同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build`):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对。 -- **关联文档**:[draft-faster-lazy-definition-indexing](../Evolutions/draft-faster-lazy-definition-indexing.md)、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「同一地址上的符号按归属分组」、[Modules/MachODependencies.md](Modules/MachODependencies.md)「定位器」、[ReviewAdjudications A61](ReviewAdjudications.md)。 +- **关联文档**:[0065-faster-lazy-definition-indexing](../Evolutions/0065-faster-lazy-definition-indexing.md)、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「同一地址上的符号按归属分组」、[Modules/MachODependencies.md](Modules/MachODependencies.md)「定位器」、[ReviewAdjudications A61](ReviewAdjudications.md)。 - **对应版本**:下一个版本(未发版)。 ## 维护约定 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 806ea562e..3e2672b93 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -721,7 +721,7 @@ - **排查中发现的入口漏包(已修)**:`TypeDefinition.specialize(...)` 的四个 async 重载(运行时两个、离线两个)没有包执行器。RuntimeViewer 在 actor 里调用其中一个(`RuntimeSwiftSection.swift:935`)。当某个 fixed 参数的 same-type 右侧代换后带 `dependentMemberType` 时,这条路会经 `GenericInstantiation` 在 512 KB 栈上拿这把锁,并逐次切线程。本批把四个重载都包上了 `LargeStackTaskExecution.run`(`SpecializationEntryPointExecutorTests`),和其它 async 入口一致。 - 同步的 `GenericSpecializer.specialize(_:with:)` / `staticPreflight` 也会走到这里,只服务 `MachOFile`。 - **四、`PropertyWrapperTypeCatalog`**(`:140`,每个镜像一个 catalog):每次查询都拿锁。没命中时在锁内 demangle 导出符号名(`:173`),第一次没命中还要建依赖闭包。入口是 `TypeDefinition.index(in:)`,调用方都在已包的入口里,包括打印、索引,以及 diff 和 evolution 渲染。同步 public 入口 `evidence(forWrapperCandidate:)` 没有人从小栈调用。 - - **改判为修(2026-10-13,提案 [draft-faster-lazy-definition-indexing](../Evolutions/draft-faster-lazy-definition-indexing.md))**:本条只考虑了「切线程时排队」,没有考虑长临界区本身。RuntimeViewer 的 Find 语料在一个镜像上 4 路并行打印,调用方都在大栈上、一次也不切线程,但锁里做的是根镜像加整个依赖闭包的导出表搜索,别的线程连已有结论的前缀都要排队:Release 采样里这把锁的等待占语料时间约 8%。锁现在只包结论缓存的读与写,搜索与 demangle 在锁外,并发的首次查询各算各的、先写入者胜;依赖闭包用另一把锁只建一次。`PropertyWrapperTypeCatalogLockTests` 在旧写法下 10 秒超时失败、新写法通过。其余四处的裁决不变,第五处 `ObjCAncestorResolver` 同样是「持锁建闭包」,进程内场景下它的类别扫描跳过 cache 内的全部镜像,开销主要是第一次建闭包,已随 `InProcessDependencyLocator` 改为查表而变小,先不改锁。 + - **改判为修(2026-10-13,提案 [0065-faster-lazy-definition-indexing](../Evolutions/0065-faster-lazy-definition-indexing.md))**:本条只考虑了「切线程时排队」,没有考虑长临界区本身。RuntimeViewer 的 Find 语料在一个镜像上 4 路并行打印,调用方都在大栈上、一次也不切线程,但锁里做的是根镜像加整个依赖闭包的导出表搜索,别的线程连已有结论的前缀都要排队:Release 采样里这把锁的等待占语料时间约 8%。锁现在只包结论缓存的读与写,搜索与 demangle 在锁外,并发的首次查询各算各的、先写入者胜;依赖闭包用另一把锁只建一次。`PropertyWrapperTypeCatalogLockTests` 在旧写法下 10 秒超时失败、新写法通过。其余四处的裁决不变,第五处 `ObjCAncestorResolver` 同样是「持锁建闭包」,进程内场景下它的类别扫描跳过 cache 内的全部镜像,开销主要是第一次建闭包,已随 `InProcessDependencyLocator` 改为查表而变小,先不改锁。 - **五、`ObjCAncestorResolver`**(`:92`、`:133`,每个镜像一个 resolver):原先列为疑似,核实属实,但有条件。依赖镜像的 `ObjCClassMethodIndex` 存储(进程级、按镜像共享)第一次建的时候,会在锁内给每个 Swift 类 demangle 一次限定名(`ObjCClassMethodIndex.swift:444` → `NodeTypeNaming`)。入口经 `index(in:)`、`prepare()` 和 `Class.dump`,都已包执行器。同步 public 入口是 `ObjCMembers.table(forSwiftClassQualifiedName:in:)`。 - **复现 / 是否误报**:五处的机制都属实。输出层面复现不出:结果不会错,只会在「小栈调用 + 有人等锁」时多等。第三处的漏包修掉之后,库内和 RuntimeViewer 的调用路径都不满足第一个条件。 - **与 main 基线对比**:五处的锁在 main(0.22.0)上都有。第二处按 binding 查询的四个方法和 `projectingConcreteMembers` 来自离线特化(`b72638f8`、`5308fa1a`),main 上没有。第三处的漏包入口里,运行时的两个重载 main 上就有;从它们走到这把锁的那一步(`GenericInstantiation`,`6c35e8c4`,2026-10-08)main 上没有。 diff --git a/Documentations/README.md b/Documentations/README.md index b1b28f16a..4591c0f03 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -169,7 +169,7 @@ selects names using each access's offset and width. | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | | [Evolutions/0063-private-declarations.md](Evolutions/0063-private-declarations.md) | **提案 0063(Implemented)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | | [Evolutions/0064-module-selectors.md](Evolutions/0064-module-selectors.md) | **提案 0064(Implemented)**:适配 SE-0491 模块选择器——默认关闭的开关(interface 的 `usesModuleSelectors` / `--module-selectors`,dump 的 swift-demangling 新选项 `useModuleSelectors` / `--enable-module-selectors`),打开后照 Swift 6.4 编译器写 `.swiftinterface` 的规则输出 `Swift::Int`,嵌套类型每层带声明它的模块(`Swift::Duration.Foundation::TimeFormatStyle`),局部类型与 `A.Element` 不加。`~Swift.Copyable` 改由类型打印器印协议节点;`OpaqueTypeResolving.opaqueType` 加参数。 | -| [Evolutions/draft-faster-lazy-definition-indexing.md](Evolutions/draft-faster-lazy-definition-indexing.md) | **提案 draft(In Progress)**:RuntimeViewer 的 Find 语料(进程内并行打印整个镜像)一半时间耗在给 resilient witness 找实现符号上——identical code folding 让一个地址挂成百上千个别名,每个 conformance 都从头逐个 demangle、搜索、打印比较,平方级。改为 `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` 按地址把别名按归属(被遵循类型 / 协议)分组一次、之后查表,`ExtensionDefinition`、`ProtocolDefinition` 与两个协议 dumper 都改用它;`PropertyWrapperTypeCatalog` 锁外搜导出表,`InProcessDependencyLocator` 一次建表代替逐个 `MachOImage(name:)`;`SharedCache` 重测后不改。M1 Max 五个系统框架:Release 20 s → 8.4 s,Debug 104 s → 53 s,输出逐字节不变。 | +| [Evolutions/0065-faster-lazy-definition-indexing.md](Evolutions/0065-faster-lazy-definition-indexing.md) | **提案 0065(Implemented)**:RuntimeViewer 的 Find 语料(进程内并行打印整个镜像)一半时间耗在给 resilient witness 找实现符号上——identical code folding 让一个地址挂成百上千个别名,每个 conformance 都从头逐个 demangle、搜索、打印比较,平方级。改为 `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` 按地址把别名按归属(被遵循类型 / 协议)分组一次、之后查表,`ExtensionDefinition`、`ProtocolDefinition` 与两个协议 dumper 都改用它;`PropertyWrapperTypeCatalog` 锁外搜导出表,`InProcessDependencyLocator` 一次建表代替逐个 `MachOImage(name:)`;`SharedCache` 重测后不改。M1 Max 五个系统框架:Release 20 s → 8.4 s,Debug 104 s → 53 s,输出逐字节不变。 | | [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 的数量与内存实测。 | From d66c6e26eba7c87c81feb00702de381c44b886d3 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 13 Oct 2026 18:02:32 +0800 Subject: [PATCH 45/49] build: require MachOObjCSection 0.8.111 0.8.111 reads the property and protocol lists a macOS 26.4+ dyld cache keeps in another file than the image's header. Those caches keep each group of images' data in .dylddata files, and the reader looked for a class's relative lists only in the file holding the header, so `objc` lost every instance property and adopted protocol of a class other images extend: NSView printed none of its 355 properties offline, and NSWindow, NSString and NSBundle lost theirs too. Methods were unaffected. Verified with the sibling dependencies (USING_LOCAL_DEPENDENCIES=1, MachOObjCSection next at 8e4cc08): the full suite (2442 tests, without IntegrationTests) fails only the two MultiPayloadEnumDescriptorCacheTests this machine already fails on next, and swift-section built from this branch prints NSView's 355 properties, 9 class properties and protocol list on macOS 26.7. Remote dependencies resolve 0.8.111, but next does not build on them yet: DemangleOptions.useModuleSelectors is only on swift-demangling's next. --- Documentations/Internal/ProjectEvolutionLog.md | 14 ++++++++++++++ Package.swift | 6 +++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index cc872c017..a8a25dff4 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2480,6 +2480,20 @@ - **关联文档**:[0065-faster-lazy-definition-indexing](../Evolutions/0065-faster-lazy-definition-indexing.md)、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「同一地址上的符号按归属分组」、[Modules/MachODependencies.md](Modules/MachODependencies.md)「定位器」、[ReviewAdjudications A61](ReviewAdjudications.md)。 - **对应版本**:下一个版本(未发版)。 +## 92. MachOObjCSection 下限抬到 0.8.111:离线读 macOS 26.4 起的 cache 不再丢属性与协议 + +- **时间段**:2026-10-13。 +- **动机**:用户发现 `swift-section objc`(0.22.0)离线读 macOS 26.4 起的 dyld cache 时,被别的镜像加过 category 的类读不出一个实例属性,也没有协议列表:NSView 的 355 个属性一个都没有,NSWindow、NSString、NSBundle 等同样;方法不受影响。根因在 MachOObjCSection:这类类的属性表、协议表经 relative list of lists 找到,读取器只在镜像 header 所在的 cache 文件里找列表,而 26.4 起 cache 把每组镜像的数据单独放进 `.dylddata` 文件。MachOObjCSection 移植上游 p-x9 的 `10b3dd5` 修复,发了 0.8.111。 +- **关键决策**: + - 本库只抬下限,不改代码:`objc` 子命令经 SwiftSectionKit 调 MachOObjCSection,修复全在那边。 + - 用户定这次**不发** swift-section:`next` 在 0.22.0 之后已有 51 个未发布提交,[0057](../Evolutions/0057-reading-context-migration.md) 又定在 0.23.0 删除弃用接口、下游尚未迁移,所以 `next` 现在不适合发;也不从 0.22.0 单独切补丁版。修复随下一次正常发版带出,在那之前 Homebrew 上的 0.22.0 仍有这个问题。 +- **落地**:`Package.swift`(MachOObjCSection `"0.8.111" ..< "0.9.0"`)。MachOObjCSection 的 `next` / `main` 为 `8e4cc08`,tag 0.8.111,GitHub Release 已发;问题与修复的记录在它的[实现说明](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/0.8.111/Documentations/Internal/RelativeListsAcrossSubCacheFiles.md)。 +- **验证**: + - 远端依赖、新鲜 scratch:解析到 MachOObjCSection 0.8.111。但 `next` 目前用远端依赖编不过:`DemangleOptions.useModuleSelectors` 只在 swift-demangling 的 `next` 上(第 90 节),与本次无关。 + - 本地兄弟依赖(`USING_LOCAL_DEPENDENCIES=1`,`workspace-state.json` 里五个兄弟依赖都是 `fileSystem`,MachOObjCSection 为 `next` @ `8e4cc08`):全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio)2442 个测试 / 468 个套件,原始退出码 1,失败的仍只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`,与第 91 节相同。 + - 端到端(macOS 26.7):本分支编出的 `swift-section objc interface NSView --uses-system-dyld-shared-cache -n AppKit` 读出 355 个实例属性、9 个类属性和协议列表;Homebrew 的 0.22.0 是 0 个、没有协议列表。 +- **对应版本**:下一个版本(未发版)。依赖下限:MachOObjCSection 0.8.111。发版说明要写:`objc` 读 macOS 26.4 起的 dyld shared cache 时,不再丢失部分类的属性与协议列表。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Package.swift b/Package.swift index 44fd3853a..94385fcdf 100644 --- a/Package.swift +++ b/Package.swift @@ -173,7 +173,11 @@ extension Package.Dependency { // runtime's frameworks bind to their own exports (`-interposable`), // which the static layout engine and the ObjC ancestor chain need, // and names a legacy LC_DYLD_INFO file's bound superclass itself. - "0.8.110" ..< "0.9.0", + // 0.8.111 reads the property and protocol lists a macOS 26.4+ cache + // keeps in another file than the image's header: `objc` lost every + // instance property and adopted protocol of a class other images + // extend, such as NSView. + "0.8.111" ..< "0.9.0", ), ) } From 3ba8fbf399bfc1b2e3ee9a8b31475611339b48fc Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 15 Oct 2026 11:11:52 +0800 Subject: [PATCH 46/49] build: require swift-demangling 0.7.2, swift-semantic-string 0.5.0 and MachOObjCSection 0.8.200 next already uses DemangleOptions.useModuleSelectors (swift-demangling 0.7.2) and DefinitionRegion (swift-semantic-string 0.5.0); with the old floors it resolved releases that lack them and did not compile against remote dependencies. MachOObjCSection 0.8.200 merges upstream 0.8.2 and reads every list an image attaches to a class, not just its first. --- Package.swift | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Package.swift b/Package.swift index 94385fcdf..b25a80ac1 100644 --- a/Package.swift +++ b/Package.swift @@ -176,8 +176,10 @@ extension Package.Dependency { // 0.8.111 reads the property and protocol lists a macOS 26.4+ cache // keeps in another file than the image's header: `objc` lost every // instance property and adopted protocol of a class other images - // extend, such as NSView. - "0.8.111" ..< "0.9.0", + // extend, such as NSView. 0.8.200 merges upstream 0.8.2 and reads + // every list an image attaches to a class, not just its first: + // `_UTCoreType` lost the methods of its second list. + "0.8.200" ..< "0.9.0", ), ) } @@ -192,7 +194,11 @@ extension Package.Dependency { url: "https://github.com/MxIris-Reverse-Engineering/swift-demangling", // 0.7.1 gives a private / local entity name its kind and scope when // printed, which `dump`'s semantic output of such names relies on. - "0.7.1" ..< "0.8.0", + // 0.7.2 adds `DemangleOptions.useModuleSelectors`, which + // `--module-selectors` prints with, and answers kind queries on a + // `NodeReference` without retaining its store, which parallel + // printing contended on. + "0.7.2" ..< "0.8.0", ), ) @@ -203,7 +209,9 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/swift-semantic-string", - from: "0.4.0", + // 0.5.0 adds definition regions, which `marksNestedDefinitions` + // wraps each nested definition in. + from: "0.5.0", ), ) From 4c738940e83d2f3863c668c9de34914a046921da Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 15 Oct 2026 11:12:17 +0800 Subject: [PATCH 47/49] docs: number proposals 0066-0069 and the evolution log's sections 93-97 The four proposals that landed with PR #131 (concurrent definition printing, nested field offset memoization, nested definition regions, offline generic specialization) were still drafts In Progress. They take 0066-0069, the next numbers after 0065 on every shared branch, and become Implemented now that the swift-semantic-string release they waited for is out; every link to them follows the rename. Their five evolution log sections had no number either. They take 93-97 and move after section 92, so the log stays in number order; sections 87-97 now say they ship in 0.23.0. --- AGENTS.md | 2 +- .../0065-faster-lazy-definition-indexing.md | 2 +- ...=> 0066-concurrent-definition-printing.md} | 9 +- ...> 0067-nested-field-offset-memoization.md} | 9 +- ...s.md => 0068-nested-definition-regions.md} | 7 +- ...=> 0069-offline-generic-specialization.md} | 7 +- Documentations/Evolutions/README.md | 8 +- Documentations/Glossary.md | 2 +- .../Internal/ExtensionContainerUnification.md | 2 +- .../LargeStackTaskExecutorAdoption.md | 2 +- .../Internal/Modules/MachOCaches.md | 2 +- .../Internal/Modules/SwiftDeclaration.md | 2 +- .../Internal/NestedFieldOffsetCycleGuard.md | 2 +- .../Internal/OfflineGenericSpecialization.md | 2 +- .../Internal/ProjectEvolutionLog.md | 138 +++++++++--------- .../Internal/ReviewAdjudications.md | 6 +- Documentations/Internal/StaticLayoutEngine.md | 2 +- Documentations/README.md | 8 +- Roadmaps/2026-10-08-pr131-review-findings.md | 12 +- 19 files changed, 114 insertions(+), 110 deletions(-) rename Documentations/Evolutions/{draft-concurrent-definition-printing.md => 0066-concurrent-definition-printing.md} (94%) rename Documentations/Evolutions/{draft-nested-field-offset-memoization.md => 0067-nested-field-offset-memoization.md} (94%) rename Documentations/Evolutions/{draft-nested-definition-regions.md => 0068-nested-definition-regions.md} (97%) rename Documentations/Evolutions/{draft-offline-generic-specialization.md => 0069-offline-generic-specialization.md} (98%) diff --git a/AGENTS.md b/AGENTS.md index 2ede5fb20..05af6255c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -276,7 +276,7 @@ Library entry points run their body on the demangler's large-stack task executor **Never start an unstructured `Task {}` inside a wrapped entry point**: SE-0417 means it does not inherit the preference (child tasks and default actors do). Nesting is a no-op, and below macOS 15 / iOS 18 the body runs unchanged. [LargeStackTaskExecutorAdoption.md](Documentations/Internal/LargeStackTaskExecutorAdoption.md). -Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [draft-concurrent-definition-printing](Documentations/Evolutions/draft-concurrent-definition-printing.md). +Cross-version work is parallel because versions are different files. **Within one version, only printing on the in-process `MachOImage` reader may run in parallel**: one printer instance may serve any number of tasks at once, including two printing the same definition, or a type and its nested types. That holds because `index(in:)` is synchronous and runs once behind `DefinitionIndexing`'s lock, and printing writes nothing to a definition — **keep both true**: no `await` inside an index pass, no index pass indexing another definition (it traps), no printer state stored on a definition. The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [0066-concurrent-definition-printing](Documentations/Evolutions/0066-concurrent-definition-printing.md). diff --git a/Documentations/Evolutions/0065-faster-lazy-definition-indexing.md b/Documentations/Evolutions/0065-faster-lazy-definition-indexing.md index 04e892396..f1e00655c 100644 --- a/Documentations/Evolutions/0065-faster-lazy-definition-indexing.md +++ b/Documentations/Evolutions/0065-faster-lazy-definition-indexing.md @@ -3,7 +3,7 @@ - **状态**: Implemented - **创建日期**: 2026-10-13 - **最后更新**: 2026-10-13 -- **关联提案**: [draft-concurrent-definition-printing](draft-concurrent-definition-printing.md)(同版本内并行打印的前提)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(`SharedCache` 的现行形态) +- **关联提案**: [0066-concurrent-definition-printing](0066-concurrent-definition-printing.md)(同版本内并行打印的前提)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(`SharedCache` 的现行形态) - **实现分支**: `feature/faster-lazy-definition-indexing` ## 摘要 diff --git a/Documentations/Evolutions/draft-concurrent-definition-printing.md b/Documentations/Evolutions/0066-concurrent-definition-printing.md similarity index 94% rename from Documentations/Evolutions/draft-concurrent-definition-printing.md rename to Documentations/Evolutions/0066-concurrent-definition-printing.md index bcc045152..60d854d66 100644 --- a/Documentations/Evolutions/draft-concurrent-definition-printing.md +++ b/Documentations/Evolutions/0066-concurrent-definition-printing.md @@ -1,8 +1,8 @@ -# Draft - 定义对象的并发打印安全:索引前置,打印期不再写定义 +# 0066 - 定义对象的并发打印安全:索引前置,打印期不再写定义 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-09-30 -- **最后更新**: 2026-10-01 +- **最后更新**: 2026-10-15 - **所属愿景**: 无 - **关联提案**: [0019-large-stack-executor-and-cross-version-parallelism](0019-large-stack-executor-and-cross-version-parallelism.md)(跨版本并行; 同版本内并行当时明确不做)、[0002-declaration-model-descriptor-slimming](0002-declaration-model-descriptor-slimming.md)(定义对象的惰性索引形态与物化纪律) @@ -72,8 +72,9 @@ | 2026-10-01 | 验证:先红后绿 | 改动前:不开 TSan 跑压力测试,进程直接崩在 `SwiftDeclarationPrinter.swift:237`(`for attribute in typeDefinition.attributes`,另一个任务刚给 `attributes` 重新赋值,旧数组被释放后又被读);release + TSan 报出 28 条数据竞争,全部落在 `TypeDefinition.index` 内部(成员构建、thunk 属性、wrapped property)、打印器写 `attributes` 那段,以及读写成员数组(含 `detachedFromSharedTable()` 新建的 `SymbolTable` 被另一个任务无同步地读),`swift test` 退出码 1。改动后:debug 三个用例全过(约 9 秒);release + TSan 三个用例全过、0 条报告、退出码 0;`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1` 下通过(7.5 秒),再关掉大栈执行器(`MACHO_SWIFT_SECTION_LARGE_STACK_EXECUTOR=0`)也通过(18 秒),说明阻塞等待不需要额外的池线程。 | | 2026-10-01 | 全量测试与渲染 A/B | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4):改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B:基线是改动前的 `4fd4049b`,两侧共用一份 `Package.resolved`,35 个依赖完全一致(其中 5 个是本地兄弟依赖),**92 对逐字节一致**——归档 cache 26.6 与 15.5 各 12 对、iOS 15.5–26.5 模拟器 44 对、MachOImage 腿 24 对。脚本写死的 `26.6.2` 归档目录在这台机器上叫 `26.6`,本轮用只改了这个常量的脚本副本跑。iOS 15.5 模拟器的 SwiftUI / WidgetKit 4 对两侧同样以 SIGTRAP 失败,记为 SKIPPED:本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后(上游 `7adae68` 开始校验 LINKEDIT 范围),导出信息为空(offset 0、size 0)的镜像让 `ExportTrie.init` 的强制解包崩溃,由 `ObjCAncestorResolver` 沿依赖闭包查导出表触发;仓库远程 pin 的 `0.52.103 ..< 0.53.0` 不含这个改动,与本提案无关。 | | 2026-10-01 | 计时:串行下没有额外开销;宽度 14 的并行反而更慢,原因在 swift-demangling | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`):libswiftCore A 1.02/1.03 s、B 1.03/1.02 s;Foundation A 4.15/4.27 s、B 4.19/4.15 s;SwiftUI A 39.93/40.31 s、B 38.75/45.59 s(第二次只用了 0.93 核,按噪声计)——索引加锁在串行下看不出成本。宽度 14(同一来源,改前 = A + 宽度 1,改后 = B + 宽度 14):SwiftUI 串行 42–50 s,并行 61 s / 约 400 s CPU,机器越空越慢(负载约 6 时 204 s / 2599 s CPU)。采样里热点是 `ExtensionDefinition` 索引体里按 conformance 找符号的 `first(of:)`:`NodeReference` 每复制一次都 retain 共享的 `NodeStore`,14 个线程同时给同一个对象加减引用计数。修在 swift-demangling(用户选「上游改遍历」,提案 `draft-unretained-kind-queries`),RuntimeViewer 在修好之前保持宽度 1。 | -| 2026-10-01 | swift-demangling 修好遍历(它的提案 0016,已快进合入它的 `next`,未推送、未发版);剩下的争用以后再说 | 用临时基准在沙盒里量(本分支的快照,只把 swift-demangling 换成修复分支):进程内打印 SwiftUI 的 17920 个定义,标记模式、一个共享 printer、`.utility` 有界任务组,每个宽度一个新进程,release,JHs-Mac-Studio-Ultra。改前:宽度 1 墙钟 37.74 s / CPU 37.77 s;宽度 14 墙钟 329.50 s / CPU 4446 s。改后:宽度 1 18.02 s / 18.08 s;宽度 4 8.87 s / 26.26 s;宽度 14 15.06–18.87 s / 约 165 s。串行本身也快了一倍:按 conformance 找符号的查询在单线程下同样是热点,省掉的是逐节点的引用计数和以 `NodeReference` 为元素的去重集合。改后在宽度 14 下再采样,剩下的争用在本库:`SymbolIndexStore.demangledNodeReference(for:in:)` 每查一个符号都经 `SharedCache.resolve` 取一次存储(同一把锁,`__ulock_wait2` 约 2750 个样本),以及 `ExtensionDefinition` 索引体里按 conformance 找符号时逐个造 `NodeReference`、retain 同一个 store。用户选择先做 `draft-nested-definition-regions`,这部分以后再说。全量 `swift test --skip IntegrationTests` 用修好的 swift-demangling 跑,2168 个全过(原始退出码 0)。RuntimeViewer 要拿到修复,构建需要解析到 swift-demangling 的 `next`。 | +| 2026-10-01 | swift-demangling 修好遍历(它的提案 0016,已快进合入它的 `next`,未推送、未发版);剩下的争用以后再说 | 用临时基准在沙盒里量(本分支的快照,只把 swift-demangling 换成修复分支):进程内打印 SwiftUI 的 17920 个定义,标记模式、一个共享 printer、`.utility` 有界任务组,每个宽度一个新进程,release,JHs-Mac-Studio-Ultra。改前:宽度 1 墙钟 37.74 s / CPU 37.77 s;宽度 14 墙钟 329.50 s / CPU 4446 s。改后:宽度 1 18.02 s / 18.08 s;宽度 4 8.87 s / 26.26 s;宽度 14 15.06–18.87 s / 约 165 s。串行本身也快了一倍:按 conformance 找符号的查询在单线程下同样是热点,省掉的是逐节点的引用计数和以 `NodeReference` 为元素的去重集合。改后在宽度 14 下再采样,剩下的争用在本库:`SymbolIndexStore.demangledNodeReference(for:in:)` 每查一个符号都经 `SharedCache.resolve` 取一次存储(同一把锁,`__ulock_wait2` 约 2750 个样本),以及 `ExtensionDefinition` 索引体里按 conformance 找符号时逐个造 `NodeReference`、retain 同一个 store。用户选择先做 `0068-nested-definition-regions`,这部分以后再说。全量 `swift test --skip IntegrationTests` 用修好的 swift-demangling 跑,2168 个全过(原始退出码 0)。RuntimeViewer 要拿到修复,构建需要解析到 swift-demangling 的 `next`。 | | 2026-10-01 | RuntimeViewer 用修好的 swift-demangling 复测:宽度 4 在三个镜像上都快约 2.5 倍,宽度 14 在 SwiftUI 上反而比宽度 4 慢 | RuntimeViewer 会话的 `CorpusBuildTimingProbe`(corpus 模式,Release,每次新进程,四档交替各两轮,负载 5–7;本库为 `937172ef` 的 git archive,swift-demangling 为 `e17ae7f`,对照组为 `35d550a`;RuntimeViewer Core 为 `c0ed5fe4`,只改 `defaultPrintingWidth`;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/fix-*`)。libswiftCore(660 个对象):修复前宽度 1 为 0.94 / 0.95 s;修复后宽度 1 为 0.84 / 0.86 s,宽度 4 为 0.34 / 0.34 s(CPU 1.1 s),宽度 14 为 0.36 / 0.35 s(CPU 3.6–3.8 s)。Foundation(2559 个):3.69 / 3.56 s → 3.34 / 3.36 s → 宽度 4 为 1.28 / 1.28 s(CPU 3.5 s)→ 宽度 14 为 0.84 / 0.84 s(CPU 4.6 s)。SwiftUI(7378 个):34.76 / 33.85 s → 17.44 / 16.30 s → 宽度 4 为 6.68 / 6.81 s(CPU 21.9–22.3 s)→ 宽度 14 为 11.95 / 11.58 s(CPU 144–149 s)。与沙盒基准一致:串行减半,宽度 4 收益最好,宽度 14 被本库符号索引里剩下的争用拖住。RuntimeViewer 准备在它的提案里建议宽度取 min(4, 核数 / 2)(下限 1),等它能解析到含 `9f5ffa92` 的本库和含 `d7693c2` 的 swift-demangling 之后再改代码,以免在没有索引锁的版本上并发打印。 | | 2026-10-08 | PR #131 review 第 7 条:`specializedChildren` 的读和四处追加都经一把进程级的锁(`TypeDefinition+Specialization.swift` 的 `@Mutex specializedChildrenAccess`);更正「RuntimeViewer 里写与读都在 section actor 上」 | 那个前提不成立:RuntimeViewer 的 `actor RuntimeSwiftSection` 在 `await baseTypeDefinition.specialize(...)`,这个方法是 nonisolated async,本库没开 `NonisolatedNonsendingByDefault`,所以它离开 actor 执行,而 actor 同时可能在读这个数组。复现测试 `ConcurrentSpecializationTests`(子进程里跑):512 个任务同时特化同一个定义,改前每次只留下 445 到 467 个,改后 512 个全在。关联对象保留,没有把存储挪进 `TypeDefinition`:那会改变它的实例大小,`DeclarationModelInstanceSizeTests` 钉着这个大小。AGENTS.md 那句「`specialize(...)` 无锁追加」同步改写。 | | 2026-10-08 | 第 7 条的横向排查:`MachOFile` 与 `DyldCache` 懒创建文件映射和句柄的四个 getter(`MachOReading/Extensions/MachOFile+.swift`、`DyldCache+.swift`)改为在一把锁下创建、只存一次 | 同一类写法(无锁地写一个 nonatomic 关联对象)。`FullDyldCache` 把同一批子 cache 实例交给它的所有镜像,`FullDyldCache.cachedHost` 又是进程级单例,`diff` 与 `evolution` 并行准备几个输入、各自经依赖查找读宿主 cache 时,会同时第一次读同一个子 cache:各自映射一次文件、互相覆盖,没被 retain 的读者还可能读到已经 unmap 的映射。新测试 `ConcurrentFileMappingTests`(`MachOSwiftSectionTests`)让 32 个线程同时做第一次读取、重复 20 轮:改前四个 getter 都失败(每个 getter 的 20 轮里有 12 到 19 轮,32 个读者拿到 2 到 7 个不同的对象),改后全部通过。热路径不变:第一次之后的读取仍然不拿锁。 | | 2026-10-08 | PR #131 review 第 9 条(等待别的线程跑完索引时不借出优先级)不修,登记 | 见 [ReviewAdjudications.md](../Internal/ReviewAdjudications.md) A53:没观察到延迟,修法要在 `SharedCacheBuildPromise` 里记下构建线程并处理它提前退出的情况;RuntimeViewer 出现能感觉到的等待时再做。 | +| 2026-10-15 | 取号 0066,In Progress → Implemented | 随 PR #131 合入 `next`(`cd248de9`),0.23.0 发版时取号(演进账本第 93 节)。配套文档已有:[Modules/SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](../Internal/LargeStackTaskExecutorAdoption.md);没有新术语。2026-10-01 记下的宽度 14 下剩余争用(逐个符号经 `SharedCache` 取存储、按 conformance 找符号时逐个造 `NodeReference`)已由 [0065](0065-faster-lazy-definition-indexing.md) 的按地址分组查询处理,本提案不再留后续。 | diff --git a/Documentations/Evolutions/draft-nested-field-offset-memoization.md b/Documentations/Evolutions/0067-nested-field-offset-memoization.md similarity index 94% rename from Documentations/Evolutions/draft-nested-field-offset-memoization.md rename to Documentations/Evolutions/0067-nested-field-offset-memoization.md index a0085785d..c37475d01 100644 --- a/Documentations/Evolutions/draft-nested-field-offset-memoization.md +++ b/Documentations/Evolutions/0067-nested-field-offset-memoization.md @@ -1,8 +1,8 @@ -# Draft - 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 +# 0067 - 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-09-30 -- **最后更新**: 2026-10-01 +- **最后更新**: 2026-10-15 - **所属愿景**: 无 - **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(RuntimeViewer 的语料按标记模式打印,所以每个类型都要付 `printExpandedFieldOffsets` 的全价)、[0053-shared-cache-composition-and-eviction-registry](0053-shared-cache-composition-and-eviction-registry.md)(进程作用域存储的形态) @@ -85,7 +85,7 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 | 2026-09-30 | 符号查找不做排序索引,改为记忆化判别符结果 | 进程内查找先逐个重建 dyld 镜像再线性扫 `LC_SYMTAB`,共享缓存镜像的本地符号已剥离,必落空;MachOKit 上游文件按 fork 政策不改。 | | 2026-09-30 | 第一轮审查:剪枝改为「保留行、剪子树」;缓存形态改按 0053;写明 enum payload 的 nil 不对称;修 TaskReports 链接 | 原稿把「剪掉节点」写成了字面意思,且引用 0053 的缓存形态与 0053 的决定相反。 | | 2026-09-30 | 第二轮审查:放弃「结构树 + 渲染期剪枝」,改为按 metatype 缓存单层展开记录、遍历原样不动;缓存形态改成 0053 采纳的 `private static let` + `@Mutex` 字典(第一轮改正时仍写成了 0053 否掉的常量键 `SharedCache`);记录记 `isLast`;展开入口保留 `?? getTypeByMangledNameInContext` 回退;`removeAll()` 带代数;补文档同步清单 | 审查指出树方案漏记 `isLast` 会在「末 payload 解析失败」时改掉 `├──` / `└──` 与祖先列,且子树是否跨根共享没定、两条路各有陷阱;单层记录方案把字节一致变成构造性的,也没有 in-flight 与剪枝问题。 | -| 2026-10-01 | Accepted | 与 [draft-concurrent-definition-printing](draft-concurrent-definition-printing.md) 同一次批准:用户在 RuntimeViewer 会话里批准开工,并在本仓库的会话里直接确认「两份都开工」。实现排在并发打印之后。 | +| 2026-10-01 | Accepted | 与 [0066-concurrent-definition-printing](0066-concurrent-definition-printing.md) 同一次批准:用户在 RuntimeViewer 会话里批准开工,并在本仓库的会话里直接确认「两份都开工」。实现排在并发打印之后。 | | 2026-10-01 | In Progress;修正配套文档链接 | 并发打印那份已提交(`9f5ffa92`),本提案接着做。配套文档写成了不存在的 `Internal/MachOCaches.md`,实际在 `Internal/Modules/MachOCaches.md`。 | | 2026-10-01 | 记下 Release 下的「改前」计时:展开字段偏移约占打印时间一成,不是 Debug 采样的 61% | RuntimeViewer 会话用 `CorpusBuildTimingProbe` 在 JHs-Mac-Studio-Ultra 上量(RuntimeViewer `72913c3d`,Release,MachOSwiftSection `next` 514bb4bd,每个预设一个进程;机器上同时有其他会话,负载 16–55,绝对值偏噪):Foundation(2559 个对象)`mcp` 3.72 s、`mcp-no-expanded-field-offset` 3.33 s,差 0.39 s,约 10.5%;SwiftUI(7378 个)51.95 s 对 47.0 s(两组负载不同,约 10%);libswiftCore(660 个)各预设都在 0.82–0.86 s,差别在噪声内。收益因此比提案动机写的小,但仍按批准的范围实现;「改后」数字等提交后由 RuntimeViewer 会话用同样的预设再量。 | | 2026-10-01 | 实现:`NestedFieldOffsetLevel` 与 `NestedFieldOffsetLevelMemo`(`SwiftDeclarationRendering/NestedFieldOffsetLevel.swift`);宿主入口是 `RuntimeFieldLayoutMemo.removeAll()` | 记录分 `structFields` / `enumPayloads` / `notExpanded` 三种,构建逻辑从原来的两个遍历函数原样搬出;遍历里只剩基址、祖先列、深度、路径环守卫和日志。memo 是一把 `@Mutex` 守着字典与代数计数,记录在锁外建、先存者赢。宿主入口做成 `public`(不加 SPI):`SwiftDeclarationRendering` 里给宿主的接口都是纯 `public`,RuntimeViewer 已经 import 这个模块。 | @@ -95,3 +95,4 @@ RuntimeViewer 给一个镜像的全部类型建搜索语料时,对正在打印 | 2026-10-01 | 验证 | 新测试与相关既有套件(嵌套展开、深度上限、特化字段类型、可见性区域投影、两个判别符套件、并发打印)全过。全量 `swift test --skip IntegrationTests` 2168 个测试全过,原始退出码 0,known issue 仍是 `SymbolicManglingIndexTests` 那一条。release + TSan 跑 `ConcurrentDefinitionPrintingTests`(标记模式打印含展开字段偏移,多线程同时查 memo)与 `NestedFieldOffsetMemoizationTests`:0 条报告,退出码 0。渲染 A/B 对 `9f5ffa92`(并发打印那份):92 对逐字节一致,SKIPPED 的仍是 iOS 15.5 模拟器 SwiftUI / WidgetKit 那 4 对(本地 MachOKit `next` 的既有问题)。A/B 的 MachOImage 腿默认不开展开字段偏移,所以另用 `RenderingVerificationTests` 打开全部选项(含 `expandedFieldOffsets`)对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍:16 对逐字节一致,进程内那几份带 17 到约 7800 行展开行。SwiftUI / SwiftUICore 没放进这一轮:该工具记着它们在开展开字段偏移时有既有的栈溢出。`NestedFieldOffsetMemoizationTests` 加进 CI 的主过滤列表。 | | 2026-10-01 | 「改后」计时:省 4–10% | 宽度 1(RuntimeViewer 会话的 `CorpusBuildTimingProbe` corpus 模式,Release,每次新进程,三档交替各两轮,负载 5–9;A = `next` 514bb4bd,B = `9f5ffa92`,C = `937172ef`,RuntimeViewer Core 同为 `8bbb46cf`、打印宽度 1,其余依赖逐项一致;原始数据在 `/Volumes/DerivedData/Agents.noindex/claude/ProbeRuns/20261001-163445-concurrent-printing/`;用 `nm` 确认只有 C 带 `RuntimeFieldLayoutMemo`):libswiftCore B 1.03/1.02 s → C 0.98/0.99 s(−4%);Foundation B 4.19/4.15 s → C 3.80/3.98 s(CPU 3.80/3.81,约 −9%);SwiftUI B 38.75/45.59 s → C 36.71/37.94 s(CPU 35.85/37.86,约 −7% 到 −10%)。与「展开字段偏移约占打印时间一成」的分项一致。 | | 2026-10-08 | PR #131 review 第 12 条(缓存会记住「这个字段类型解析不出」)本库不修,登记为 [ReviewAdjudications.md](../Internal/ReviewAdjudications.md) A54;转 RuntimeViewer | 这是方案里写明的取舍,清除入口 `RuntimeFieldLayoutMemo.removeAll()` 交给宿主在加载镜像后调用。review 查到 RuntimeViewer 的 find-navigator 分支只在它自己 `dlopen` 之后调用,被检查的进程自己加载的镜像不会触发;`DyldUtilities.observeDyldRegisterEvents()` 写好了 dyld 加载镜像的回调但从没被调用,那边要注册它并在回调里调用 `removeAll()`。 | +| 2026-10-15 | 取号 0067,In Progress → Implemented | 随 PR #131 合入 `next`(`cd248de9`),0.23.0 发版时取号(演进账本第 94 节)。配套文档已有:[NestedFieldOffsetCycleGuard.md](../Internal/NestedFieldOffsetCycleGuard.md)「每层从记录里读」、[Modules/MachOCaches.md](../Internal/Modules/MachOCaches.md);没有新术语。宿主在 dyld 加载镜像后调用 `RuntimeFieldLayoutMemo.removeAll()` 的接线归 RuntimeViewer(A54)。 | diff --git a/Documentations/Evolutions/draft-nested-definition-regions.md b/Documentations/Evolutions/0068-nested-definition-regions.md similarity index 97% rename from Documentations/Evolutions/draft-nested-definition-regions.md rename to Documentations/Evolutions/0068-nested-definition-regions.md index 12085ff99..7f8b3a74a 100644 --- a/Documentations/Evolutions/draft-nested-definition-regions.md +++ b/Documentations/Evolutions/0068-nested-definition-regions.md @@ -1,8 +1,8 @@ -# Draft - 在父定义的打印结果里标出嵌套子定义的边界 +# 0068 - 在父定义的打印结果里标出嵌套子定义的边界 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-10-01 -- **最后更新**: 2026-10-08 +- **最后更新**: 2026-10-15 - **所属愿景**: 无 - **关联提案**: [0056-visibility-regions](0056-visibility-regions.md)(同一手法:区域编码在原子的 `identifier` 里,冻结后分离成一张表);RuntimeViewer 的 `draft-find-navigator` §1.1 方案 D(使用方);swift-semantic-string 的设计记录 `docs/VisibilityRegions.md` - **实现分支 / PR**: 本库 `feature/runtime-viewer/find-navigator`;swift-semantic-string `feature/definition-regions` @@ -70,3 +70,4 @@ RuntimeViewer 建 Find 语料时,嵌套类型会被打印两遍:父类型的 | 2026-10-01 | 全量测试与渲染 A/B 通过;Foundation 上只挪动了两个扩展 | 全量 `swift test --skip IntegrationTests`(沙盒副本,本地兄弟依赖,swift-semantic-string 指向 `feature/definition-regions`)2174 个测试全部通过,原始退出码 0。渲染 A/B:基线是本分支 `ed289fb4` 的 git archive,候选是加上本提案改动的副本,两侧依赖相同、只有 swift-semantic-string 指向不同分支;92 对逐字节一致,iOS 15.5 模拟器的 SwiftUI / WidgetKit 两侧同样崩溃(MachOKit `ExportTrie.init`,见并发打印提案)。A/B 的框架里没有协议声明在别的模块类型的 extension 里,另用两侧 CLI 渲染当前系统 Foundation 的 interface 对比:只有 `NSNotificationCenter.AsyncMessage` 与 `NSNotificationCenter.MainActorMessage` 的两个默认实现扩展,从 `extension __C.NSNotificationCenter { … }` 的大括号里(顶格)挪到了顶层的嵌套协议扩展区块,其余四万多行逐字节相同。 | | 2026-10-08 | PR #131 review 第 4 条:interface 的嵌套协议默认实现区块读列表之前,先对协议调用 `index(in:)` | 声明在 extension 里的协议,要到后面的 extensions 区块才被打印、被索引;而它的默认实现列表只有在协议自己的索引过程里才完整——library evolution 下,默认实现来自父协议 extension 时,编译器生成一个挂在需求名下的默认 witness,`prepare()` 的符号扫描认不出它,由协议的索引过程兜底补出这个 extension。区块读列表时协议还没索引,列表是空的,打印器又不再在协议后面接它(本提案的改动),于是这个 extension 哪里都不打印;同一个 builder 打印两次,第二次才出现。改前它被打印在外层 extension 的大括号里(位置不合法,但打印了),所以这是本提案引入的回退,只出现在这个窄形状上。索引同步、可重复调用、只跑一次(`DefinitionIndexing`),区块顺序不动。复现测试 `ProtocolInExtensionDefaultWitnessTests`(library evolution 编的 fixture)先红后绿。RuntimeViewer 的 `defaultImplementationExtensionsLeftToPrint(of:)` 也是直接读这个列表,要同样先索引协议(那边改)。根因的另一种修法——让 `prepare()` 认出挂在需求名下的默认 witness——改动大得多,没做 | | 2026-10-08 | 「哪些协议在声明后面接着打印默认实现扩展」公开为 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration`,打印器与 `SwiftInterfaceBuilder` 都改读它 | RuntimeViewer PR #121 审查的第 PR121.27 条:它的 Find 语料与内容区要自己补印打印器不接在协议后面的默认实现扩展,此前只能照抄本提案定下的条件;本提案 2026-10-01 给条件加上 `extensionContext == nil` 时,它那份拷贝就错了,直到它的 74c349c7 跟上。库里也写了两份:打印器一份,`SwiftInterfaceBuilder` 的嵌套协议区块取反一份。现在规则只写在这个属性里(`parent == nil && extensionContext == nil`):打印器读它,区块读它的反面,宿主也读它;文档注释写明为什么嵌在类型里与声明在别的模块类型的 extension 里的协议不在其列。行为不变:JHs-Mac-Studio、Xcode 27.0、本地兄弟依赖,改动前后 SwiftInterfaceTests、SwiftSectionKitTests 与 SwiftPrintingTests(不含 `EnumCaseRenderingParityTests`)的逐条结果相同,289→290、64、42 个测试全部通过,原始退出码 0,多出的一条是新测试;整模块 interface 快照 `SymbolTestsCoreInterfaceSnapshotTests` 也在其中。`EnumCaseRenderingParityTests` 在这个环境里改动前后都在第一个测试崩溃(SIGSEGV),两侧单独跑结果相同,与本改动无关。`ProtocolInExtensionTests` 的 fixture 加了顶层协议 `Greeter`,新测试断言三种位置的协议这个属性分别为 true / false / false;把属性临时改回只看 `parent == nil`(本提案之前的规则)时,新测试与该套件原有的三条一起失败,说明打印器与区块都只经这个属性。渲染 A/B 没做:只是把已有条件抽成属性,不算 AGENTS.md 说的大型重构 | +| 2026-10-15 | 取号 0068,In Progress → Implemented | 随 PR #131 合入 `next`(`cd248de9`);swift-semantic-string 0.5.0 发版带出 `DefinitionRegion`,本库下限抬到 0.5.0,随 0.23.0 落地(演进账本第 95 节)。配套文档是 swift-semantic-string 的 `docs/DefinitionRegions.md`,术语「nested-definition region」已登记。 | diff --git a/Documentations/Evolutions/draft-offline-generic-specialization.md b/Documentations/Evolutions/0069-offline-generic-specialization.md similarity index 98% rename from Documentations/Evolutions/draft-offline-generic-specialization.md rename to Documentations/Evolutions/0069-offline-generic-specialization.md index 668524ee4..53e1b5dd1 100644 --- a/Documentations/Evolutions/draft-offline-generic-specialization.md +++ b/Documentations/Evolutions/0069-offline-generic-specialization.md @@ -1,8 +1,8 @@ -# Draft - 离线泛型特化:不经 runtime 特化泛型类型并完整打印 +# 0069 - 离线泛型特化:不经 runtime 特化泛型类型并完整打印 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-09-30 -- **最后更新**: 2026-10-02 +- **最后更新**: 2026-10-15 - **所属愿景**: 无 - **关联文档**: [StaticLayoutEngine.md](../Internal/StaticLayoutEngine.md)「后续工作」里的「用户手动特化前端」一条;[SpecializedInterfaceBoundRenderingRestoration.md](../Internal/SpecializedInterfaceBoundRenderingRestoration.md)(运行时特化的打印机制);RuntimeViewer 的 [0003-generic-type-specialization](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/main/Documentations/Evolutions/0003-generic-type-specialization.md)(消费方的 UI 流程) - **实现分支 / PR**: `feature/offline-generic-specialization`,叠在 `feature/runtime-viewer/find-navigator` 之上,须在它之后合入(见决策日志 2026-10-02) @@ -158,3 +158,4 @@ let interface = try await printer.printTypeDefinition(specializedDefinition) / | 2026-10-08 | PR #131 review 第 10 条:在线特化算实例化名字失败、退回扁平名时记一条错误日志 | 原来是 `try?`,没有日志也没有事件,类型头印着运行时的名字,同一个定义就有两个名字。修完第 3 条后基本走不到。另一处名字不一致(嵌套泛型类型的约束 extension 里,`typeName` 按层绑定而类型头是运行时的名字)是本提案 2026-10-01 定下的有意差异,登记为 [ReviewAdjudications.md](../Internal/ReviewAdjudications.md) A55 | | 2026-10-08 | PR #131 review 第 11 条:打印离线特化定义的字段时,关联类型投影走打印配置建好的依赖闭包;`StaticFieldLayoutProvider` 加带默认实现的 `projectingConcreteMembers(in:)`,`StaticLayoutCalculator` 开同名的公开方法 | 投影原先用的搜索路径来自 thunk 解析器或「文件所在位置推断 + 宿主 cache」,不看打印配置的 `staticLayoutDependencyResolution`,宿主的 macOS 镜像对 iOS 二进制又从来不是候选:iOS 模拟器二进制配 iOS 模拟器 cache 打印时,布局注释按 `Int?` 算(`size: 9`),字段类型却还是 `[Int].Element?`。现在字段类型与旁边的布局注释读同一批镜像。没打开布局注释(没有 provider)时退回原路径;`staticPreflight` 没有打印配置,仍走默认路径,写进实现说明。复现测试 `OfflineProjectionDependencyResolutionTests` 只在有 `/Volumes/DyldSharedCaches/iOS-Simulator/27.0` 的机器上跑 | | 2026-10-08 | 本轮修复的验证 | 修后全量与复现测试见演进账本「PR #131 review 的修复」一节;改动连同各自的复现测试分条提交 | +| 2026-10-15 | 取号 0069,In Progress → Implemented | 随 PR #131 合入 `next`(`cd248de9`),0.23.0 发版时取号(演进账本第 96 节,review 修复在第 97 节)。配套文档 [OfflineGenericSpecialization.md](../Internal/OfflineGenericSpecialization.md) 已有;术语「depth」「instantiated type name」「offline specialization」已登记。 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 9707e2464..aca67f42f 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -65,17 +65,17 @@ | [0054](0054-interface-descriptor-only-vtable-members.md) | interface 按 vtable 槽位顺序打印类成员,补上只剩 method descriptor 符号的成员 | Implemented | | [0055](0055-group-sources-by-layer.md) | `Sources/` 按层分组 | Implemented | | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | -| draft | [进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存](draft-nested-field-offset-memoization.md) | In Progress | -| draft | [定义对象的并发打印安全:索引前置,打印期不再写定义](draft-concurrent-definition-printing.md) | In Progress | -| draft | [在父定义的打印结果里标出嵌套子定义的边界](draft-nested-definition-regions.md) | In Progress | | [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | | [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | | [0058](0058-swift-section-kit.md) | 把 swift-section 的功能抽成 SwiftSectionKit 库,CLI 只剩一层包装 | Implemented | | [0059](0059-dump-declaration-identity.md) | SwiftSectionKit:dump 把每个声明的种类与名字一并交给输出端 | Implemented | | [0060](0060-evolution-interface-available-annotations.md) | evolution 联合接口的 @available 生命周期标注(真属性 + 位图注释保留) | Implemented | | [0061](0061-dyld-shared-cache-path-versions.md) | 测试用的 dyld shared cache 路径按版本取 | Implemented | -| draft | [离线泛型特化:不经 runtime 特化泛型类型并完整打印](draft-offline-generic-specialization.md) | In Progress | | [0062](0062-local-type-context-names.md) | 局部类型的名字:找回函数与闭包上下文 | Implemented | | [0063](0063-private-declarations.md) | 私有声明:从名字取 discriminator,按镜像反推源文件 | Implemented | | [0064](0064-module-selectors.md) | 适配 SE-0491:interface 与 dump 可用模块选择器(`Module::Name`)写限定名 | Implemented | | [0065](0065-faster-lazy-definition-indexing.md) | 并行打印下的惰性索引提速:同一地址的符号按归属查表、属性包装器目录锁外查找 | Implemented | +| [0066](0066-concurrent-definition-printing.md) | 定义对象的并发打印安全:索引前置,打印期不再写定义 | Implemented | +| [0067](0067-nested-field-offset-memoization.md) | 进程内嵌套字段偏移展开的记忆化与匿名上下文判别符缓存 | Implemented | +| [0068](0068-nested-definition-regions.md) | 在父定义的打印结果里标出嵌套子定义的边界 | Implemented | +| [0069](0069-offline-generic-specialization.md) | 离线泛型特化:不经 runtime 特化泛型类型并完整打印 | Implemented | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index c566f3e03..637d02882 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -225,7 +225,7 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 `SwiftDeclarationPrintConfiguration.marksNestedDefinitions` 为 `true` 时,父定义打印结果里每个内联打印的嵌套类型或协议被包进 swift-semantic-string 的 `DefinitionRegion`,身份是名字节点的 mangled name,与 RuntimeViewer 的对象名相同。冻结后用 `separatingDefinitionRegions()` 拆出区域表;对深度为 d 的区域,`content(ofDefinitionRegion:)` 再加 `removingIndentation(levels: d + 1)` 得到的值,与该定义单独打印的结果逐项相同(文本、span、identifier,以及两种分离得到的表)。宿主因此只需打印父定义,不必再单独打印每个嵌套定义。与标记模式同时打开时,定义区域的编码放在可见性标记的内层,两者互不影响。 - **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+DefinitionRegions.swift`、`SwiftDeclarationPrintConfiguration.swift` -- **延伸阅读**:[提案 draft-nested-definition-regions](Evolutions/draft-nested-definition-regions.md);swift-semantic-string 的 `docs/DefinitionRegions.md` +- **延伸阅读**:[提案 0068-nested-definition-regions](Evolutions/0068-nested-definition-regions.md);swift-semantic-string 的 `docs/DefinitionRegions.md` ### NodeStore / NodeReference diff --git a/Documentations/Internal/ExtensionContainerUnification.md b/Documentations/Internal/ExtensionContainerUnification.md index 6463b1928..03107fc18 100644 --- a/Documentations/Internal/ExtensionContainerUnification.md +++ b/Documentations/Internal/ExtensionContainerUnification.md @@ -19,7 +19,7 @@ **`updateConfiguration` 的 re-prepare 原为静默 no-op。** `prepare()` 的 `isPrepared` 门从无人复位,配置变更后的重建从未发生过。顺带修复(复位后重跑),它同时成为桶重置(`index()` 入口清空四桶)的确定性验证入口——修复前 re-run 会把所有 append 产线的块成倍复制。 -**嵌套协议的扩展块经由原死循环的修复版打印。** `printRoot` 里那个循环原来在 root 协议上过滤 `parent != nil`(恒空);修复为遍历 `allProtocolDefinitions` 的嵌套协议。fixture 的协议全部嵌套在 enum 命名空间里,所以快照中四个协议扩展块整体从 extensions 区迁到 protocols 区之后——纯迁移,零内容变化。顶层协议走 `printProtocolDefinition` 的尾随路径。哪些协议尾随由 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration` 一处回答(既没有 `parent` 也没有 `extensionContext`),这个循环取它的反面,所以声明在别的模块类型的 extension 里的协议也走这个循环(见 [draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md));宿主自己补印默认实现扩展时读的也是这个属性。 +**嵌套协议的扩展块经由原死循环的修复版打印。** `printRoot` 里那个循环原来在 root 协议上过滤 `parent != nil`(恒空);修复为遍历 `allProtocolDefinitions` 的嵌套协议。fixture 的协议全部嵌套在 enum 命名空间里,所以快照中四个协议扩展块整体从 extensions 区迁到 protocols 区之后——纯迁移,零内容变化。顶层协议走 `printProtocolDefinition` 的尾随路径。哪些协议尾随由 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration` 一处回答(既没有 `parent` 也没有 `extensionContext`),这个循环取它的反面,所以声明在别的模块类型的 extension 里的协议也走这个循环(见 [0068-nested-definition-regions](../Evolutions/0068-nested-definition-regions.md));宿主自己补印默认实现扩展时读的也是这个属性。 **`protocol-extension default` 标注落在 conformance 兜底分支。** `ExtensionDefinition.index()` 经 `element.defaultImplementationSymbols` 解析成功的 witness,其成员打 `isProtocolExtensionDefault`,interface(`renderMember`)与 dump(`ProtocolConformanceDumper`)在 `printMemberAddress` 开启时渲染标注。**SourceEditor 上未触发**:折叠地址上 `resilientWitness.implementationSymbols` 的首选分支总能命中(protocol witness 符号在场),兜底分支需要「witness 实现符号缺失而默认实现符号可解析」的组合——已落地待真实触发场景(fixture 非 resilient,`resilientWitnesses` 为空,同样够不到)。issue 点名的 `SourceEditorView.elide` 三兄弟经 `nm` 证实是**真类成员**被 ICF 折叠(提案 0006 的 `Tq` 门处理),并非误归属的协议默认实现。 diff --git a/Documentations/Internal/LargeStackTaskExecutorAdoption.md b/Documentations/Internal/LargeStackTaskExecutorAdoption.md index 6077568e0..2e3f185f6 100644 --- a/Documentations/Internal/LargeStackTaskExecutorAdoption.md +++ b/Documentations/Internal/LargeStackTaskExecutorAdoption.md @@ -58,7 +58,7 @@ SE-0417:非结构化 `Task {}` 不继承执行器偏好。核对 `Sources/` MachOKit 自己的读取有上百处 `fileHandle.seek` + `read` 共用一个句柄(`MachOFile.swift`、`DyldCache.swift` 等),两个线程交错就读错位置;`index(in:)` 的 `guard !isIndexed` 是非原子的检查加赋值。前者不在本仓库,需要 MachOKit 改 mmap 读或每个分片独立 `MachOFile` 实例,另起提案。 -后者已由提案 [draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md) 解决:`index(in:)` 改成同步函数,经进程级一把锁只跑一次,打印期不再写定义。所以 `MachOImage` 读者下同一版本内的**打印**可以并发(RuntimeViewer 建语料就这么做);`MachOFile` 读者仍受前者限制,版本内的 `prepare` 并行也仍然不做。 +后者已由提案 [0066-concurrent-definition-printing](../Evolutions/0066-concurrent-definition-printing.md) 解决:`index(in:)` 改成同步函数,经进程级一把锁只跑一次,打印期不再写定义。所以 `MachOImage` 读者下同一版本内的**打印**可以并发(RuntimeViewer 建语料就这么做);`MachOFile` 读者仍受前者限制,版本内的 `prepare` 并行也仍然不做。 ### `concurrentMap(maximumConcurrency:)` 的错误语义 diff --git a/Documentations/Internal/Modules/MachOCaches.md b/Documentations/Internal/Modules/MachOCaches.md index d88a17fb8..7596f0097 100644 --- a/Documentations/Internal/Modules/MachOCaches.md +++ b/Documentations/Internal/Modules/MachOCaches.md @@ -101,7 +101,7 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { **不受驱逐的**:进程作用域的 memo 都是 `static` 存储,不经过按镜像的字典,也不受注册表管: -- `InternedNodeReferenceCache` 与 `SymbolicDemanglerCache` 给没有 Mach-O 句柄的进程内读取路径用的那两份,大小由进程实际碰到的唯一名字数决定。`SymbolicDemanglerCache` 的这一份里还有一张按地址记的匿名上下文判别符表,`InProcessContext` 查判别符时用(提案 [draft-nested-field-offset-memoization](../../Evolutions/draft-nested-field-offset-memoization.md)):已经在内存里的匿名上下文,答案不会变。 +- `InternedNodeReferenceCache` 与 `SymbolicDemanglerCache` 给没有 Mach-O 句柄的进程内读取路径用的那两份,大小由进程实际碰到的唯一名字数决定。`SymbolicDemanglerCache` 的这一份里还有一张按地址记的匿名上下文判别符表,`InProcessContext` 查判别符时用(提案 [0067-nested-field-offset-memoization](../../Evolutions/0067-nested-field-offset-memoization.md)):已经在内存里的匿名上下文,答案不会变。 - `SwiftDeclarationRendering` 的 `NestedFieldOffsetLevelMemo`:进程内嵌套字段偏移展开按 metatype 记下的「一层」(同一提案),大小由进程展开过的唯一 metatype 数决定。它记下了「当时哪些字段类型解析不出」,进程之后加载的镜像可能让它们变得可解析,所以它有清除入口 `RuntimeFieldLayoutMemo.removeAll()`:宿主在进程里加载镜像之后调一次。其余几份没有这个问题,也没有清除入口。 ## 4. 契约与坑 diff --git a/Documentations/Internal/Modules/SwiftDeclaration.md b/Documentations/Internal/Modules/SwiftDeclaration.md index 0d3422fbc..924290634 100644 --- a/Documentations/Internal/Modules/SwiftDeclaration.md +++ b/Documentations/Internal/Modules/SwiftDeclaration.md @@ -45,7 +45,7 @@ SwiftDeclaration 是**共享声明模型**:`SwiftIndexing` 往里填,`SwiftP ### 每个定义只索引一次,可以被并发打印 -三个 Definition 的 `index(in:)` 是**同步**函数,都经 `DefinitionIndexing.swift` 执行(提案 [draft-concurrent-definition-printing](../../Evolutions/draft-concurrent-definition-printing.md))。进程级一把锁守着两样东西:一张「正在索引」的表(按 `ObjectIdentifier(定义)`),和每个定义自己的 `hasCompletedIndexing`。首个调用者认领后在自己的线程上跑完索引体;同时到来的调用者在认领者的 promise(复用 `SharedCacheBuildPromise`,载荷是 `Result`)上阻塞等待,拿到同一个结果。索引体抛错时定义回到未索引、错误交给全部等待者,下次调用重试。`isIndexed` 是只读的计算属性,读的就是锁下的那个标志。 +三个 Definition 的 `index(in:)` 是**同步**函数,都经 `DefinitionIndexing.swift` 执行(提案 [0066-concurrent-definition-printing](../../Evolutions/0066-concurrent-definition-printing.md))。进程级一把锁守着两样东西:一张「正在索引」的表(按 `ObjectIdentifier(定义)`),和每个定义自己的 `hasCompletedIndexing`。首个调用者认领后在自己的线程上跑完索引体;同时到来的调用者在认领者的 promise(复用 `SharedCacheBuildPromise`,载荷是 `Result`)上阻塞等待,拿到同一个结果。索引体抛错时定义回到未索引、错误交给全部等待者,下次调用重试。`isIndexed` 是只读的计算属性,读的就是锁下的那个标志。 阻塞等待不会死锁,靠两条前提,改索引时要守住: diff --git a/Documentations/Internal/NestedFieldOffsetCycleGuard.md b/Documentations/Internal/NestedFieldOffsetCycleGuard.md index 433431171..ce6635a14 100644 --- a/Documentations/Internal/NestedFieldOffsetCycleGuard.md +++ b/Documentations/Internal/NestedFieldOffsetCycleGuard.md @@ -96,7 +96,7 @@ struct 持有 `Optional>`,而这个 en ### 每层从记录里读(2026-10-01 起,运行时路径) -运行时路径每一层要读的东西——描述符、字段偏移、字段记录、每行的类型名、下一层的 metatype——按 metatype 记成一份 `NestedFieldOffsetLevel`,进程内只建一次(提案 [draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md))。遍历本身没动:基址偏移、树的祖先列、深度、路径环守卫和两条日志都还在 `walkNestedExpandedFieldOffsets` 里,所以两道守卫的行为与输出逐字节不变。记录里的 `isLast` 仍按全部字段记录、全部 payload case 计数:解析失败、没有行的那一项照样占位,前一行因此仍画 `├──`(`ValueSpec` 的最后一个 case `pair` 解析不出,`reference` 那行就是这样,`NestedFieldOffsetMemoizationTests` 钉住)。 +运行时路径每一层要读的东西——描述符、字段偏移、字段记录、每行的类型名、下一层的 metatype——按 metatype 记成一份 `NestedFieldOffsetLevel`,进程内只建一次(提案 [0067-nested-field-offset-memoization](../Evolutions/0067-nested-field-offset-memoization.md))。遍历本身没动:基址偏移、树的祖先列、深度、路径环守卫和两条日志都还在 `walkNestedExpandedFieldOffsets` 里,所以两道守卫的行为与输出逐字节不变。记录里的 `isLast` 仍按全部字段记录、全部 payload case 计数:解析失败、没有行的那一项照样占位,前一行因此仍画 `├──`(`ValueSpec` 的最后一个 case `pair` 解析不出,`reference` 那行就是这样,`NestedFieldOffsetMemoizationTests` 钉住)。 ## 影响面 diff --git a/Documentations/Internal/OfflineGenericSpecialization.md b/Documentations/Internal/OfflineGenericSpecialization.md index f0f038e9a..7373b4b66 100644 --- a/Documentations/Internal/OfflineGenericSpecialization.md +++ b/Documentations/Internal/OfflineGenericSpecialization.md @@ -1,6 +1,6 @@ # 离线泛型特化 -提案 [offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md) 的实现说明:不经 runtime 特化一个从文件读出的泛型类型,并像在线模式一样打印出绑定后的头部、代换后的字段类型和按实参计算的布局注释。给 RuntimeViewer 的离线模式用,本库没有 CLI 入口。 +提案 [offline-generic-specialization](../Evolutions/0069-offline-generic-specialization.md) 的实现说明:不经 runtime 特化一个从文件读出的泛型类型,并像在线模式一样打印出绑定后的头部、代换后的字段类型和按实参计算的布局注释。给 RuntimeViewer 的离线模式用,本库没有 CLI 入口。 ## 一句话 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index a8a25dff4..853cb5847 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2307,69 +2307,6 @@ - **关联文档**:[Changelogs/0.22.0.md](../../Changelogs/0.22.0.md)。 - **对应版本**:0.22.0。 -## 2026-10-01 定义对象可以并发打印:索引只跑一次,打印期不写定义 - -- **时间段**:2026-09-30(提案)— 2026-10-01(实现)。 -- **动机**:RuntimeViewer 的 Find 语料要并行打印一个镜像的全部定义,而定义对象在打印时才惰性索引,守卫是无锁的「检查再赋值」,打印器每次还要写 `TypeDefinition.attributes`。这个竞争在 RuntimeViewer 里已经在发生:`RuntimeSwiftSection` 是 actor,显示路径和语料路径都 `await` 到打印器的 nonisolated 入口,打印期间 actor 被释放,两条打印真并行地碰同一批定义。 -- **关键决策**:**① 索引改成同步函数,经 `DefinitionIndexing` 只跑一次**:进程级一把 `@Mutex` 守着 in-flight 表和每个定义的 `hasCompletedIndexing`;首个调用者认领后在自己线程上跑完,其余在 promise 上阻塞等待并共享结果(复用 `SharedCacheBuildPromise`,载荷是 `Result`),抛错则回到未索引、下次重试。**② 不死锁靠两条前提**:索引体没有 `await`(编译器保证),索引体不索引别的定义(所有 `SharedCache` 都在下层模块,结构上够不到定义;认领或等待时若当前线程正在跑某个索引体就 `precondition` trap)。**③ 打印期不写定义**:类型级 attribute 改成打印时的局部变量,删掉 `TypeDefinition.attributes`(三个下游都不读它);`TypeAttributeInferrer` 里三处读 `TypeDefinition.extensions` 的死代码删掉,并写明被它掩盖的缺口:声明在扩展里的 `buildBlock` / `subscript(dynamicMember:)` / `dynamicallyCall` 识别不到。**④ 三个定义类标 `@unchecked Sendable`**,理由写在类型上;`SymbolicDemangler.isCacheEnabled` 改成 `static let`。**⑤ 约定**:AGENTS.md 那条「同版本内不能并行」改成「`MachOImage` 读者下打印可以并行,`MachOFile` 读者仍不行,`specialize(...)` 不在承诺内」。 -- **落地模块**:SwiftDeclaration(`DefinitionIndexing`、三个定义类及其 `+Indexing`、`MutableDefinition` 的 requirement)、SwiftAttributeInference(`TypeAttributeInferrer`)、SwiftPrinting / SwiftInterface(打印器与 diff 渲染的两处 attribute、各处 `index(in:)` 调用)、SwiftInspection(`isCacheEnabled`)、MachOCaches(`SharedCacheBuildPromise` 的注释)。测试新增 `ConcurrentDefinitionPrintingTests`(CI 主过滤与单线程协作池两步都加了),其余测试去掉为定义不 `Sendable` 写的 `nonisolated(unsafe)` 绕法。 -- **验证**:改动前压力测试不开 TSan 直接崩(`attributes` 数组被另一个任务重新赋值后又被读),release + TSan 报 28 条数据竞争;改动后 debug、release + TSan(0 条报告)、单线程协作池、单线程协作池且关掉大栈执行器都通过。debug 下用 TSan 会在 MachOKit 读 fixture 时被对齐检查拦下(MachOKit 的既有问题),所以 TSan 一律用 release。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4)改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B 对改动前的 `4fd4049b` 共 92 对逐字节一致(归档 cache 26.6 / 15.5、iOS 15.5–26.5 模拟器、MachOImage 腿);iOS 15.5 模拟器 SwiftUI / WidgetKit 的 4 对两侧同样崩溃,原因是本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后 `ExportTrie.init` 对空导出信息强制解包,与本批无关,细节见提案决策日志。 -- **后续**:RuntimeViewer 量出宽度 14 的并行打印比串行还慢。根因在 swift-demangling:按种类找节点的查询每访问一个节点都复制一次 `NodeReference`,每次都 retain 镜像共享的 store,14 个线程抢同一个引用计数。修在 swift-demangling(它的提案 0016,合入它的 `next`,未发版)。进程内打印 SwiftUI 全部定义:改前宽度 1 37.7 s、宽度 14 329.5 s;改后宽度 1 18.0 s、宽度 4 8.9 s、宽度 14 15–19 s。宽度 14 下剩下的争用在本库(`SymbolIndexStore` 每查一个符号都经 `SharedCache` 取一次存储,以及按 conformance 找符号时逐个造 `NodeReference`),用户决定以后再说,细节在提案决策日志。RuntimeViewer 随后复测:宽度 4 在 libswiftCore、Foundation、SwiftUI 上都快约 2.5 倍(SwiftUI 从串行 17 s 降到 6.7 s),宽度 14 在 SwiftUI 上比宽度 4 慢;它准备把宽度取 min(4, 核数 / 2)。 -- **关联文档**:[draft-concurrent-definition-printing](../Evolutions/draft-concurrent-definition-printing.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「版本内并行为什么不做」。 -- **对应版本**:未发版。 - -## 2026-10-01 进程内嵌套字段偏移展开按 metatype 记一层;匿名上下文判别符按地址记 - -- **时间段**:2026-09-30(提案)— 2026-10-01(实现)。 -- **动机**:RuntimeViewer 建 Find 语料时打印镜像里的全部类型。Debug 采样里单个类型打印的 61% 落在进程内的嵌套字段偏移展开(同一个字段类型在每个出现处都重新递归、重新 demangle),9% 落在匿名上下文判别符的查找(共享缓存镜像的本地符号已剥离,线性扫符号表基本必落空),两处都没有缓存。Release 下量出来,展开字段偏移约占打印时间一成(Foundation 约 10.5%),收益比 Debug 采样小,按批准的范围照做。 -- **关键决策**:**① 缓存「一层」而不是整棵树**:按 metatype 记下这一层要打印的每行(字段名、类型名、相对偏移、`isLast`)和下一层的 metatype,遍历本身——基址、树的祖先列、深度、路径环守卫、日志——原样留着,所以输出逐字节不变是构造出来的;`isLast` 仍对全部字段记录计数,解析失败、没有行的那项照样占位。**② 进程级存储**:`static` 的 `@Mutex` 字典,键是 `ObjectIdentifier(metatype)`,记录在锁外建、先存者赢;一层记下了「当时哪些类型解析不出」,进程之后加载的镜像可能改变答案,所以给宿主一个 `RuntimeFieldLayoutMemo.removeAll()`,带代数计数防止跨越清除的构建写回。**③ `storedFieldComments` 每个字段最多解析一次 metatype**,且只在有消费方要用时解析。**④ 判别符按地址记忆化**,只在 `InProcessContext` 这条路上,存在 `SymbolicDemanglerCache` 的进程级存储里;查的是已在内存里的匿名上下文,不需要清除入口。 -- **落地模块**:SwiftDeclarationRendering(新文件 `NestedFieldOffsetLevel.swift`:`NestedFieldOffsetLevel`、`NestedFieldOffsetLevelMemo`、公开的 `RuntimeFieldLayoutMemo`;`RuntimeFieldLayoutBackend` 的展开与 `storedFieldComments`)、SwiftInspection(`SymbolicDemangler` 的 `SymbolLookupContext` 与 `SymbolicDemanglerCache`)。测试新增 `NestedFieldOffsetMemoizationTests`,`AnonymousContextPrivateDiscriminatorTests` 加一条冷热两次的判别符对照。 -- **验证**:全量 `swift test --skip IntegrationTests` 2168 个测试全过(原始退出码 0);release + TSan 跑并发打印与记忆化两个套件 0 条报告。渲染 A/B 对并发打印那份(`9f5ffa92`)92 对逐字节一致;因为 A/B 的进程内腿默认不开展开字段偏移,另用 `RenderingVerificationTests` 打开全部选项对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍,16 对逐字节一致(进程内那几份带 17 到约 7800 行展开行)。「改后」计时由 RuntimeViewer 会话补。 -- **关联文档**:[draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md)、[Modules/MachOCaches.md](Modules/MachOCaches.md)「不受驱逐的」、[NestedFieldOffsetCycleGuard.md](NestedFieldOffsetCycleGuard.md)「每层从记录里读」。 -- **对应版本**:未发版。 - -## 2026-10-01 嵌套定义在父定义的打印里标出边界(方案 D) - -- **时间段**:2026-10-01(提案、实现)。 -- **动机**:RuntimeViewer 建 Find 语料时,嵌套类型在父类型的打印里内联一遍,又作为自己的对象单独打印一遍,计时探针量出这部分约占打印时间四成(Foundation 只打顶层 2.23 s、全打 3.72 s;SwiftUI 31.15 s 对 51.95 s)。它的方案 D 是只打印父定义、从结果里把嵌套定义切出来;本库要给出边界,并承诺切出来的与单独打印的一样。 -- **关键决策**:**① 新开关 `marksNestedDefinitions`**(默认关,关着时输出逐字节不变),四处嵌套循环把子定义的打印包进 swift-semantic-string 新增的 `DefinitionRegion`,身份是名字节点的 mangled name;名字 remangle 失败或含控制字符就不标,宿主单独打印。**② 库接口在带标记的串上切**:`content(ofDefinitionRegion:)` 去掉外层身份、按首次使用顺序重建 identifier 表,`removingIndentation(levels:)` 按行去缩进,切出的串再分离出的两张表与单独打印的相同;原方案「连同可见性区域表一起切」改掉,因为条件按 identifier 表顺序编号,切表等于重写分离逻辑。定义区域的编码放在可见性标记里面一层,容器与可见性分离都不受影响。**③ 先修一个既有问题**:协议声明在别的模块类型的 extension 里(`extension Int { protocol Counter }`)时,默认实现扩展被打印在外层 extension 的大括号里、顶格,生成的 Swift 不合法;现在只有顶层协议原地带出扩展,这类协议的扩展与嵌在类型里的协议一样放进 interface 的顶层 extensions 区块。声明在本模块类型的 extension 里的协议被编译器直接挂在类型上,本来就打印正确。 -- **落地模块**:SwiftPrinting(`SwiftDeclarationPrintConfiguration.marksNestedDefinitions`、新文件 `SwiftDeclarationPrinter+DefinitionRegions.swift`、四处嵌套循环、协议默认实现扩展的条件)、SwiftInterface(顶层区块收录 extension 里的协议的扩展);swift-semantic-string(`DefinitionRegion`、`DefinitionRegionTable`、`separatingDefinitionRegions()`、`content(ofDefinitionRegion:)`、`removingIndentation(levels:)`)。测试新增 `NestedDefinitionRegionContractTests`、`ProtocolInExtensionTests`,两者加进 CI 主过滤列表。 -- **验证**:`ProtocolInExtensionTests` 先红后绿。契约测试对 SymbolTestsCore 每个有嵌套定义的根类型与 extension,在进程内与文件两种读取方式、三种配置(只标定义区域;加标记模式;全部选项加 Transformer 模板)下逐区域比较,全部通过,区域数与嵌套定义数一致。swift-semantic-string 全部 432 个测试通过,watchOS `arm64_32` 编译通过。全量测试与渲染 A/B 见提案决策日志。 -- **补记(2026-10-08)**:③ 定下的规则公开为 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration`(新增公开 API,写进 0.22.0 发版说明)。此前库里写了两份(打印器一份,`SwiftInterfaceBuilder` 的嵌套协议区块取反一份);RuntimeViewer 要知道哪些协议的默认实现得自己补印,只能再照抄一份,③ 改规则时它就跟着错过一次(RuntimeViewer PR #121 审查的第 PR121.27 条)。现在打印器、interface 生成器与宿主都读这个属性。行为不变,证据见提案决策日志。 -- **关联文档**:[draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md)、[Glossary.md](../Glossary.md)「nested-definition region」、swift-semantic-string 的 `docs/DefinitionRegions.md`。 -- **对应版本**:未发版。落地前要先发布带 `DefinitionRegion` 的 swift-semantic-string,并抬高本库对它的版本下限。 - -## 2026-10-01 离线泛型特化,参数层号只数声明了参数的上下文(节号落地时分配) - -- **时间段**:2026-09-30 — 2026-10-02。 -- **动机**:`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在加载进当前进程的 `MachOImage` 上用;RuntimeViewer 将来的离线模式读 `MachOFile`,完全不能特化。用户:「把离线泛型特化实现一下,我记得之前在做静态布局的时候就提到过这个,目前泛型特化只有运行时才能用」。 -- **关键决策**:**① 离线执行与在线一一对应**:`GenericSpecializer` 的 `specialize` / `staticPreflight`,实参变成类型节点(`.metatype` 等宿主类型用本进程运行时的名字),结果是实例化类型名加按层分组的实参(`GenericArgumentBinding`),打印器与静态布局引擎据此出绑定头部、代换并投影关联类型的字段类型、全部布局注释。**② 实例化类型名移植运行时 `_buildDemanglingForContext`**,非 key 参数由 same-type 约束补齐;只有嵌套泛型的约束 extension 一处有意与运行时不同(运行时拼出的名字畸形)。在线特化的 `typeName` 也改用它,不再把实参全放进最内层。**③ 约束检查两档**:确定违反报错,证明不了只警告;沿用现有的 error / warning case,RuntimeViewer 对它们做了穷尽 `switch`。**④ 参数层号整类修复**:用 0.21.0 的 CLI 证实未特化的 interface / dump 头部同样把 `Outer.Middle.Inner` 的 `B` 打成 `A2`;新增 `GenericParameterDepthLayout`(只数声明了参数的上下文,extension 按被扩展类型拆层),五处改用它,用户选择整类一起修。**⑤ 在线模式也给特化后的泛型 enum 出 Enum Layout 注释**,两条路径才能逐字节对照,用户选择。**⑥ 实现时发现并修的两处**:离线 request 丢掉跨镜像协议需求(读文件时协议引用落在 bind 上,`buildRequirement` 只认已解析的 descriptor);静态展开偏移树不投影具体类型的关联类型。 -- **落地模块**:`SwiftInspection`(`GenericParameterDepthLayout`、`GenericArgumentBinding`、`SymbolicDemangler.instantiatedTypeNode`、`RuntimeMetadataTypeBuilder` 的层号)、`SwiftSpecialization`(离线执行、`GenericInstantiation`、`StaticSpecializationResult`、`TypeDefinition` 的离线 `specialize` 重载、在线类型名、`buildRequirement`)、`SwiftDeclaration`(`TypeDefinition.staticSpecialization`)、`SwiftLayout`(带 binding 的四个入口、`make(forBinding:)`、穿过 extension 的实参遍历、`ImageUniverse.projectingConcreteMembers`、展开偏移树的投影)、`SwiftDeclarationRendering`(`StaticFieldLayoutProvider` 的四个新方法、`FieldLayoutRenderState.genericArgumentBinding`、离线字段代换、运行时后端的泛型 enum 布局、`GenericContext+Dump` 的层号、opaque type 的 thunk 实参布局)、`SwiftThunkAnalysis`(`AccessorThunkOwnerLayout` 带层号布局的初始化)、`SwiftDump` / `SwiftPrinting`(头部按层号命名,`boundTypeNode(of:)`)。测试支持新增 `GenericSpecializationFixture`(现场编译的 dylib,同一个文件按两种方式读)与 `GenericSpecializationFixtureIndexers`。 -- **验证**:39 个新测试;层号五处与另外四项修复都先确认修复前失败。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra)2210 个测试 / 420 个套件全部通过,原始退出码 0,known issue 只有早已登记的 `SymbolicManglingIndexTests`。渲染 A/B 以 `b2b7d997` 为基线,共 132 对,90 对逐字节一致;42 对差异全部是预期的改变,两侧重跑确认是确定性的。一是嵌在不声明参数的中间层下的类型头部从 `` 改成 ``(Combine 的 `Optional.Publisher.Inner` / `Result.Publisher.Inner`、SwiftUICore 的 `TimeDataSource.Resolver.ResolvedOffsetBox`,每个版本、每条 reader 路径都有);二是展开偏移树把具体类型的关联类型投影后命名并继续展开(`Angle.AnimatableData` → `Swift.Double` 等);三是约束 extension 里类型的实参代换修正(`MeasurementView` 里原先错印成 `Measurement`)。脚本写死的 `26.6.2` 归档目录不在(卷上叫 `26.6`),26.6 与 27.0 两份 cache 手动补跑;脚本的 CLI 腿不出布局注释,另跑了打开全部布局注释的 24 对。逐项明细在提案的「验证」一节。2026-10-02 分支 rebase 到 find-navigator(`86f65341`)之上,用本地兄弟依赖重跑全量:2224 个测试 / 424 个套件通过,原始退出码 0(rebase 前的 2210 个加上 find-navigator 新增的 14 个);渲染 A/B 未重跑。 -- **关联文档**:[draft-offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md)、[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[StaticLayoutEngine.md](StaticLayoutEngine.md)「后续工作」、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md)、[SpecializedInterfaceBoundRenderingRestoration.md](SpecializedInterfaceBoundRenderingRestoration.md)、[Glossary.md](../Glossary.md)「depth」「instantiated type name」「offline specialization」。 -- **对应版本**:0.22.0(未发版)。叠在 find-navigator 的三份提案之上,须在它们之后合入,也同样要等带 `DefinitionRegion` 的 swift-semantic-string 发版。 - -## 2026-10-08 PR #131 review 的修复:13 条修掉,第 9、12 条登记不修(节号落地时分配) - -- **时间段**:2026-10-07(review、复现测试)— 2026-10-08(修复落地)。 -- **动机**:`/code-review max` 对 PR #131(find-navigator 配套的三份提案加离线泛型特化)给出 15 条发现,逐条按四问裁决、写好复现测试与修法,记在 [Roadmaps/2026-10-08-pr131-review-findings.md](../../Roadmaps/2026-10-08-pr131-review-findings.md)。用户审完后说「把发现的问题修一下吧」。 -- **关键决策**: - - 有修法的 13 条全部落地,包括原本建议「离线模式接入前再修」的第 5、11 条(修法已写好、已验证)。每条修复连同它的复现测试一个 commit。 - - 第 1、8、13 条与 PR 已整类修掉的「泛型参数层号数错」同属一类,这次补齐:opaque 引用的实参表按位置当层号、opaque provider 按父链数层、thunk 类型构造器只数类型层。按全库扫描,除这八处外没有别的地方用父链或位置数层号。 - - 第 13 条保留旧逻辑作为第二条路:整个替换的第一版让 same-type 约束 extension 里的类型退化成 `accessor function at …`,加守护测试钉住那个形状。 - - 第 7 条(`specializedChildren` 无锁追加)的横向排查查出 MachOReading 里 `MachOFile` / `DyldCache` 懒创建文件映射和句柄的四个 getter 是同一类写法。`FullDyldCache` 把同一批子 cache 实例交给所有镜像、`cachedHost` 又是进程级单例,`diff` / `evolution` 并行准备输入时会同时第一次读同一个子 cache,所以按「同类一并修」改为持锁创建、只存一次(review 记录原把它列为「另开一项」)。 - - 登记不修:第 9 条(等待索引时不借出优先级)、第 12 条(嵌套偏移缓存记住解析失败,转 RuntimeViewer)、第 10 条里有意的名字差异、review 被条数上限砍掉的三个顺带项,以及核验时驳回的四条候选,见 [ReviewAdjudications.md](ReviewAdjudications.md) A53–A59。 - - 顺带:PR 重写过的几行缩写改成完整名称;`ProtocolInExtensionTests` 编 fixture 补 `-swift-version 5`;CI 主过滤列表补上离线特化、层号与这批新加的套件(依赖本机 cache 的 `OfflineProjectionDependencyResolutionTests` 除外),单线程协作池那一步之后另加一步,关掉大栈执行器再跑并发打印测试——原来那一步测不出它要防的问题,因为打印跑在 swift-demangling 自己的线程上,严格池缩不到它们。 -- **公开 API 与行为变化**(写进 0.22.0 发版说明):新增 `ConformanceProvider.superclassLink(of:)`、`ConformanceProvider.isConditionalConformance(of:to:)`(都有默认实现)与公开枚举 `SuperclassLink`,`StaticFieldLayoutProvider.projectingConcreteMembers(in:)`(有默认实现),`StaticLayoutCalculator.projectingConcreteMembers(in:)`。行为:opaque 类型的实参按描述符的层结构分组;离线父类检查遇到 ObjC 中间类只给警告;带条件的协议遵循给警告;extension 里协议兜底补出的默认实现重新打印出来;静态展开偏移不再把 opaque 实际类型印成占位符。 -- **落地模块**:SwiftDeclarationRendering(`Node+OpaqueType`、`DependentMemberProjection`、`StaticFieldLayoutProvider`、`StaticSpecializationNodeSubstitution`)、SwiftInterface(`SwiftInterfaceBuilder`、`SwiftInterfaceBuilderOpaqueTypeProvider`)、SwiftPrinting(`SwiftDeclarationPrinter+Headers`)、SwiftThunkAnalysis(`ThunkTypeNodeBuilder`)、SwiftSpecialization(`ConformanceProvider`、`GenericInstantiation`、`GenericSpecializer`、`GenericSpecializer+StaticSpecialization`、`TypeDefinition+Specialization`)、SwiftDeclaration(`TypeDefinition` 的说明)、SwiftLayout(`ImageUniverse+AssociatedTypeWitnessProjection`、`StaticLayoutCalculator`)、MachOReading(`MachOFile+`、`DyldCache+`);测试支持 `GenericSpecializationFixture` 加 `TiedParameterPair`;CI。 -- **验证**: - - JHs-Mac-Studio-Ultra(Swift 6.4)上 review 时验证过修法:复现测试在 PR 头上全红、修后全绿,全量 2354 个测试全部通过。 - - 落地时在 JHs-Mac-Studio 上重新验证,用的是 CI 的工具链(Xcode 26.6、Swift 6.3.3),依赖钉到与 Ultra 相同的版本(MachOKit 0.54.101、MachOKitExtensions 1.1.2、MachOObjCSection 0.8.109、swift-demangling 0.7.1,只有 swift-semantic-string 链本地的 `next`)。11 个复现套件(含新的 `ConcurrentFileMappingTests`)在 PR 头的源码上全部失败、修后全部通过。`OfflineProjectionDependencyResolutionTests` 写死的归档 cache 本机没有,在沙盒副本里临时改指本机装的 iOS 27.0 模拟器 runtime 里的 cache,同样是 PR 头上失败、修后通过。 - - 全量 `swift test --skip IntegrationTests`:2358 个测试、448 个套件(Ultra 上的 2354 / 447 加上新的 `ConcurrentFileMappingTests`),原始退出码 1。失败的只有 `MultiPayloadEnumDescriptorCacheTests` 的两条(`everyFixtureMultiPayloadEnumRendersALayout`、`noncopyableMultiPayloadEnumLaysOutFromItsResolvedPayloads`):换回 PR 头的源码,在同一环境里同样两条、同样位置失败,是这台机器上早就有的环境问题(进程内 enum 布局,这批改动不碰;`next` 上也是这样)。另有早已登记的 known issue(`SymbolicManglingIndexTests`)。 - - 渲染 A/B(基线 `beae202d`,候选是这批代码提交的末尾 `f108d5e6`;两侧 release,共用同一份 `Package.resolved`,经构建队列预构建后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 27.0 模拟器的框架在 cache 里、不是文件,那条腿按设计跳过。会改变输出的几条在这些框架与选项组合里都没有触发:第 1 条要外层有一层不声明参数的 opaque 引用,系统框架的 witness 记录里多半已被编译器代换成具体类型;第 6 条只在打开展开字段偏移时出现,A/B 的 CLI 腿不出布局注释、MachOImage 腿不开展开偏移。第 1 条在真实 app 上的效果另用两侧 CLI 对本机的 `/Applications/Xcodes.app` 复核:11599 行的 interface 只有两行不同,都是 `typealias Body` 里的 `TupleToolbarContent` 补上了实参;补出来的类型里露出 5 处本来就解不出的 kind-9 占位符,修前藏在 `A` 后面。 -- **关联文档**:review 记录;[ReviewAdjudications.md](ReviewAdjudications.md) A53–A59;四份提案的决策日志([并发打印](../Evolutions/draft-concurrent-definition-printing.md)、[离线特化](../Evolutions/draft-offline-generic-specialization.md)、[嵌套定义区域](../Evolutions/draft-nested-definition-regions.md)、[嵌套偏移记忆化](../Evolutions/draft-nested-field-offset-memoization.md));[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md)、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、[Modules/MachODependencies.md](Modules/MachODependencies.md)。 -- **对应版本**:0.22.0(未发版),随 PR #131 合入。 - ## 87. 局部类型的名字:找回函数与闭包上下文 - **时间段**:2026-10-10 — 2026-10-11。 @@ -2393,7 +2330,7 @@ - 系统框架 A/B(`Scripts/run-rendering-ab-verification.py`;基线是 next cd248de9 的 `git archive` 沙盒,两侧 release 预构建,共用同一份 `Package.resolved`):96 对里 30 对有差异,全部在 SwiftUI / SwiftUICore,逐对核对都来自局部类型——名字换成编译器全名,interface 加注释、conformance 的 extension 头印全名,以前丢掉的成员、字段和布局注释挂回来(`TableDataSource` 的 7 个 `Visitor` 各有自己的字段,基线是一份 `var result: SwiftUI.DeleteInteraction?` 印 6 遍)。按典型 witness 成员(`_rawHashValue`、`hash(into:)`、`_updateDefault`、`CodingKeys` 的初始化器等)计数,没有一对比基线少;缓存镜像的 SwiftUICore 还多出基线印成 `{}` 的 conformance 成员。第一轮 A/B 里 iOS 26.5 模拟器腿的成员丢失就是上面的整树搜索问题,修后第二轮消失;两轮的 96 份基线渲染逐字节相同。 - macOS 27.2 当前系统 cache 的 AppKit(剥光本地符号,只靠 `_symbolic`)手工对比 dump 与 interface:只有 3 个局部类型变化(`NSWMDeferrableWMWindowTransaction.deferCompletionUntil()` 里的 `DeferralState`、`_NSLocalizedIndexedCollation.sortedArray(from:collationStringSelector:)` 里的 `ObjectWrapper`、`NSView._HitTestMap.differencePairs(to:differences:)` 里的 `Pair`)。 - **关联文档**:[0062-local-type-context-names](../Evolutions/0062-local-type-context-names.md)、[Roadmaps/2026-09-24-local-type-context-names.md](../../Roadmaps/2026-09-24-local-type-context-names.md)、[SymbolicManglingSymbols.md](SymbolicManglingSymbols.md)「边界」、[Glossary.md](../Glossary.md)「position-based name」、`swift-section` agent skill 第 9 节。 -- **对应版本**:下一个版本(未发版)。 +- **对应版本**:0.23.0。 ## 88. 私有声明:从名字取 discriminator,按镜像反推源文件 @@ -2416,7 +2353,7 @@ - RuntimeViewer Core 用 SwiftPM 的 edit 模式指向本分支编译,私有声明相关的 3 个套件、14 个测试通过,其中包括经引擎命令反推出 `JSONEncoder.swift` 的那个。 - 没跑系统框架 A/B:打印只是把局部类型注释的写法挪进 `DefinitionName`,打印选项没变,SymbolTestsCore 的 interface 快照照旧通过。 - **关联文档**:[0063-private-declarations](../Evolutions/0063-private-declarations.md)、[Modules/SwiftPrivateDiscriminators.md](Modules/SwiftPrivateDiscriminators.md)、[Glossary.md](../Glossary.md)「private declaration」;展示一侧是 RuntimeViewer 的 `draft-private-discriminator-tag`。 -- **对应版本**:下一个版本(未发版)。 +- **对应版本**:0.23.0。 ## 89. 持锁时 demangle 不切线程:类继承表改在大栈上建,`TypeDefinition.specialize` 补上执行器 @@ -2439,7 +2376,7 @@ - `SpecializationEntryPointExecutorTests`:运行时、离线两个 deriving 重载各一条。修复前 provider 在 536,576 字节的栈上被调用,测试失败;修复后在执行器的大栈线程上,测试通过。两个新套件加进了 CI 的过滤清单。 - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,带 `USING_LOCAL_DEPENDENCIES=1`)在 `classHierarchy()` 修好之后跑过一次:2427 个测试、462 个套件全部通过,原始退出码 0。`specialize` 包上执行器之后,重跑了它在库内唯一的调用方 `SwiftSpecializationTests`(154 个测试、27 个套件),以及 `ContinuousIntegrationTestFilterTests`,全部通过,原始退出码 0。 - **关联文档**:AGENTS.md「Never let a demangle or print hop while you hold a lock」、[ReviewAdjudications A61](ReviewAdjudications.md)、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「包了哪些入口」、[NodeStoreMigrationOpenIssues 第 9 条](NodeStoreMigrationOpenIssues.md)(规则的来历)。 -- **对应版本**:下一个版本(未发版)。 +- **对应版本**:0.23.0。 ## 90. 适配 SE-0491:模块选择器写法 @@ -2459,7 +2396,7 @@ - 渲染 A/B(基线 next `cd248de9` + swift-demangling `next` `e17ae7f`,候选 `52fb45f9` + swift-demangling `8419460`;两侧 swift-semantic-string 都是本地 `next`,共用同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 26.6.2 与 15.5 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 15.5 模拟器缺的三个框架与 iOS 27.0 模拟器(框架在 cache 里)按设计跳过。开关关闭时输出不变。 - 落地(2026-10-12):rebase 到 `next` `b8db48bf`,与 0062(局部类型的名字)在 `TypeNodePrintable.printType` 和 extension 头上冲突,两边都保留;extension 头走 0062 的 `renderExtendedTypeName`,按位置命名的局部类型(`Holder.(Visitor in $…)`)也随开关带模块选择器,由新测试 `LocalTypeInterfaceTests.strippedInterfaceSpellsPositionBasedExtensionsWithModuleSelectors` 钉住:extension 头不带选择器时它的 3 条断言全部失败(印成 `LocalTypeFixtureStripped.Holder.(Key in $5e3c): Swift::Equatable`,一行里混着两种写法),带上后与相关的 7 个套件共 60 个测试一起通过,原始退出码 0。全量 `swift test --skip IntegrationTests`(同上的依赖配置):2436 个测试 / 465 个套件,原始退出码 1,失败的仍只有那两条 `MultiPayloadEnumDescriptorCacheTests`。冲突点小,没有重跑渲染 A/B。 - **关联文档**:[0064-module-selectors](../Evolutions/0064-module-selectors.md)、swift-demangling 提案 `0017-module-selectors`、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 2」、swift-section 插件 skill §0 / §4、`AGENTS.md`「printer path」一节新增的规则。 -- **对应版本**:下一个版本(未发版);发版前 swift-demangling 要先发版(新选项 `useModuleSelectors`),再抬本库的版本范围。 +- **对应版本**:0.23.0(swift-demangling 0.7.2 带出 `useModuleSelectors`,本库版本范围抬到 `"0.7.2" ..< "0.8.0"`)。 ## 91. 并行打印下的惰性索引提速 @@ -2478,7 +2415,7 @@ - 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio,`USING_LOCAL_DEPENDENCIES=1`):2442 个测试 / 468 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`(基线 next `5dca3331` 上同样失败)。 - 渲染 A/B(基线 next `5dca3331` 的 detached worktree,两侧共用本地兄弟依赖与同一份 `Package.resolved`,经构建队列各预构建一次 release 后带 `--skip-build`):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对。 - **关联文档**:[0065-faster-lazy-definition-indexing](../Evolutions/0065-faster-lazy-definition-indexing.md)、[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「同一地址上的符号按归属分组」、[Modules/MachODependencies.md](Modules/MachODependencies.md)「定位器」、[ReviewAdjudications A61](ReviewAdjudications.md)。 -- **对应版本**:下一个版本(未发版)。 +- **对应版本**:0.23.0。 ## 92. MachOObjCSection 下限抬到 0.8.111:离线读 macOS 26.4 起的 cache 不再丢属性与协议 @@ -2492,7 +2429,70 @@ - 远端依赖、新鲜 scratch:解析到 MachOObjCSection 0.8.111。但 `next` 目前用远端依赖编不过:`DemangleOptions.useModuleSelectors` 只在 swift-demangling 的 `next` 上(第 90 节),与本次无关。 - 本地兄弟依赖(`USING_LOCAL_DEPENDENCIES=1`,`workspace-state.json` 里五个兄弟依赖都是 `fileSystem`,MachOObjCSection 为 `next` @ `8e4cc08`):全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio)2442 个测试 / 468 个套件,原始退出码 1,失败的仍只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`,与第 91 节相同。 - 端到端(macOS 26.7):本分支编出的 `swift-section objc interface NSView --uses-system-dyld-shared-cache -n AppKit` 读出 355 个实例属性、9 个类属性和协议列表;Homebrew 的 0.22.0 是 0 个、没有协议列表。 -- **对应版本**:下一个版本(未发版)。依赖下限:MachOObjCSection 0.8.111。发版说明要写:`objc` 读 macOS 26.4 起的 dyld shared cache 时,不再丢失部分类的属性与协议列表。 +- **对应版本**:0.23.0(发版时 MachOObjCSection 下限再抬到 0.8.200,见第 98 节)。 + +## 93. 定义对象可以并发打印:索引只跑一次,打印期不写定义 + +- **时间段**:2026-09-30(提案)— 2026-10-01(实现)。 +- **动机**:RuntimeViewer 的 Find 语料要并行打印一个镜像的全部定义,而定义对象在打印时才惰性索引,守卫是无锁的「检查再赋值」,打印器每次还要写 `TypeDefinition.attributes`。这个竞争在 RuntimeViewer 里已经在发生:`RuntimeSwiftSection` 是 actor,显示路径和语料路径都 `await` 到打印器的 nonisolated 入口,打印期间 actor 被释放,两条打印真并行地碰同一批定义。 +- **关键决策**:**① 索引改成同步函数,经 `DefinitionIndexing` 只跑一次**:进程级一把 `@Mutex` 守着 in-flight 表和每个定义的 `hasCompletedIndexing`;首个调用者认领后在自己线程上跑完,其余在 promise 上阻塞等待并共享结果(复用 `SharedCacheBuildPromise`,载荷是 `Result`),抛错则回到未索引、下次重试。**② 不死锁靠两条前提**:索引体没有 `await`(编译器保证),索引体不索引别的定义(所有 `SharedCache` 都在下层模块,结构上够不到定义;认领或等待时若当前线程正在跑某个索引体就 `precondition` trap)。**③ 打印期不写定义**:类型级 attribute 改成打印时的局部变量,删掉 `TypeDefinition.attributes`(三个下游都不读它);`TypeAttributeInferrer` 里三处读 `TypeDefinition.extensions` 的死代码删掉,并写明被它掩盖的缺口:声明在扩展里的 `buildBlock` / `subscript(dynamicMember:)` / `dynamicallyCall` 识别不到。**④ 三个定义类标 `@unchecked Sendable`**,理由写在类型上;`SymbolicDemangler.isCacheEnabled` 改成 `static let`。**⑤ 约定**:AGENTS.md 那条「同版本内不能并行」改成「`MachOImage` 读者下打印可以并行,`MachOFile` 读者仍不行,`specialize(...)` 不在承诺内」。 +- **落地模块**:SwiftDeclaration(`DefinitionIndexing`、三个定义类及其 `+Indexing`、`MutableDefinition` 的 requirement)、SwiftAttributeInference(`TypeAttributeInferrer`)、SwiftPrinting / SwiftInterface(打印器与 diff 渲染的两处 attribute、各处 `index(in:)` 调用)、SwiftInspection(`isCacheEnabled`)、MachOCaches(`SharedCacheBuildPromise` 的注释)。测试新增 `ConcurrentDefinitionPrintingTests`(CI 主过滤与单线程协作池两步都加了),其余测试去掉为定义不 `Sendable` 写的 `nonisolated(unsafe)` 绕法。 +- **验证**:改动前压力测试不开 TSan 直接崩(`attributes` 数组被另一个任务重新赋值后又被读),release + TSan 报 28 条数据竞争;改动后 debug、release + TSan(0 条报告)、单线程协作池、单线程协作池且关掉大栈执行器都通过。debug 下用 TSan 会在 MachOKit 读 fixture 时被对齐检查拦下(MachOKit 的既有问题),所以 TSan 一律用 release。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4)改动前 2160 个、改动后 2163 个测试全部通过,原始退出码都是 0,唯一的 known issue(`SymbolicManglingIndexTests`)两边相同。渲染 A/B 对改动前的 `4fd4049b` 共 92 对逐字节一致(归档 cache 26.6 / 15.5、iOS 15.5–26.5 模拟器、MachOImage 腿);iOS 15.5 模拟器 SwiftUI / WidgetKit 的 4 对两侧同样崩溃,原因是本地兄弟依赖 MachOKit `next` 合入上游 0.53.0 后 `ExportTrie.init` 对空导出信息强制解包,与本批无关,细节见提案决策日志。 +- **后续**:RuntimeViewer 量出宽度 14 的并行打印比串行还慢。根因在 swift-demangling:按种类找节点的查询每访问一个节点都复制一次 `NodeReference`,每次都 retain 镜像共享的 store,14 个线程抢同一个引用计数。修在 swift-demangling(它的提案 0016,合入它的 `next`,未发版)。进程内打印 SwiftUI 全部定义:改前宽度 1 37.7 s、宽度 14 329.5 s;改后宽度 1 18.0 s、宽度 4 8.9 s、宽度 14 15–19 s。宽度 14 下剩下的争用在本库(`SymbolIndexStore` 每查一个符号都经 `SharedCache` 取一次存储,以及按 conformance 找符号时逐个造 `NodeReference`),用户决定以后再说,细节在提案决策日志。RuntimeViewer 随后复测:宽度 4 在 libswiftCore、Foundation、SwiftUI 上都快约 2.5 倍(SwiftUI 从串行 17 s 降到 6.7 s),宽度 14 在 SwiftUI 上比宽度 4 慢;它准备把宽度取 min(4, 核数 / 2)。 +- **关联文档**:[0066-concurrent-definition-printing](../Evolutions/0066-concurrent-definition-printing.md)、[Modules/SwiftDeclaration.md](Modules/SwiftDeclaration.md)「每个定义只索引一次,可以被并发打印」、[LargeStackTaskExecutorAdoption.md](LargeStackTaskExecutorAdoption.md)「版本内并行为什么不做」。 +- **对应版本**:0.23.0。 + +## 94. 进程内嵌套字段偏移展开按 metatype 记一层;匿名上下文判别符按地址记 + +- **时间段**:2026-09-30(提案)— 2026-10-01(实现)。 +- **动机**:RuntimeViewer 建 Find 语料时打印镜像里的全部类型。Debug 采样里单个类型打印的 61% 落在进程内的嵌套字段偏移展开(同一个字段类型在每个出现处都重新递归、重新 demangle),9% 落在匿名上下文判别符的查找(共享缓存镜像的本地符号已剥离,线性扫符号表基本必落空),两处都没有缓存。Release 下量出来,展开字段偏移约占打印时间一成(Foundation 约 10.5%),收益比 Debug 采样小,按批准的范围照做。 +- **关键决策**:**① 缓存「一层」而不是整棵树**:按 metatype 记下这一层要打印的每行(字段名、类型名、相对偏移、`isLast`)和下一层的 metatype,遍历本身——基址、树的祖先列、深度、路径环守卫、日志——原样留着,所以输出逐字节不变是构造出来的;`isLast` 仍对全部字段记录计数,解析失败、没有行的那项照样占位。**② 进程级存储**:`static` 的 `@Mutex` 字典,键是 `ObjectIdentifier(metatype)`,记录在锁外建、先存者赢;一层记下了「当时哪些类型解析不出」,进程之后加载的镜像可能改变答案,所以给宿主一个 `RuntimeFieldLayoutMemo.removeAll()`,带代数计数防止跨越清除的构建写回。**③ `storedFieldComments` 每个字段最多解析一次 metatype**,且只在有消费方要用时解析。**④ 判别符按地址记忆化**,只在 `InProcessContext` 这条路上,存在 `SymbolicDemanglerCache` 的进程级存储里;查的是已在内存里的匿名上下文,不需要清除入口。 +- **落地模块**:SwiftDeclarationRendering(新文件 `NestedFieldOffsetLevel.swift`:`NestedFieldOffsetLevel`、`NestedFieldOffsetLevelMemo`、公开的 `RuntimeFieldLayoutMemo`;`RuntimeFieldLayoutBackend` 的展开与 `storedFieldComments`)、SwiftInspection(`SymbolicDemangler` 的 `SymbolLookupContext` 与 `SymbolicDemanglerCache`)。测试新增 `NestedFieldOffsetMemoizationTests`,`AnonymousContextPrivateDiscriminatorTests` 加一条冷热两次的判别符对照。 +- **验证**:全量 `swift test --skip IntegrationTests` 2168 个测试全过(原始退出码 0);release + TSan 跑并发打印与记忆化两个套件 0 条报告。渲染 A/B 对并发打印那份(`9f5ffa92`)92 对逐字节一致;因为 A/B 的进程内腿默认不开展开字段偏移,另用 `RenderingVerificationTests` 打开全部选项对 Combine、SwiftData、WidgetKit、ActivityKit 两侧各跑一遍,16 对逐字节一致(进程内那几份带 17 到约 7800 行展开行)。「改后」计时由 RuntimeViewer 会话补。 +- **关联文档**:[0067-nested-field-offset-memoization](../Evolutions/0067-nested-field-offset-memoization.md)、[Modules/MachOCaches.md](Modules/MachOCaches.md)「不受驱逐的」、[NestedFieldOffsetCycleGuard.md](NestedFieldOffsetCycleGuard.md)「每层从记录里读」。 +- **对应版本**:0.23.0。 + +## 95. 嵌套定义在父定义的打印里标出边界(方案 D) + +- **时间段**:2026-10-01(提案、实现)。 +- **动机**:RuntimeViewer 建 Find 语料时,嵌套类型在父类型的打印里内联一遍,又作为自己的对象单独打印一遍,计时探针量出这部分约占打印时间四成(Foundation 只打顶层 2.23 s、全打 3.72 s;SwiftUI 31.15 s 对 51.95 s)。它的方案 D 是只打印父定义、从结果里把嵌套定义切出来;本库要给出边界,并承诺切出来的与单独打印的一样。 +- **关键决策**:**① 新开关 `marksNestedDefinitions`**(默认关,关着时输出逐字节不变),四处嵌套循环把子定义的打印包进 swift-semantic-string 新增的 `DefinitionRegion`,身份是名字节点的 mangled name;名字 remangle 失败或含控制字符就不标,宿主单独打印。**② 库接口在带标记的串上切**:`content(ofDefinitionRegion:)` 去掉外层身份、按首次使用顺序重建 identifier 表,`removingIndentation(levels:)` 按行去缩进,切出的串再分离出的两张表与单独打印的相同;原方案「连同可见性区域表一起切」改掉,因为条件按 identifier 表顺序编号,切表等于重写分离逻辑。定义区域的编码放在可见性标记里面一层,容器与可见性分离都不受影响。**③ 先修一个既有问题**:协议声明在别的模块类型的 extension 里(`extension Int { protocol Counter }`)时,默认实现扩展被打印在外层 extension 的大括号里、顶格,生成的 Swift 不合法;现在只有顶层协议原地带出扩展,这类协议的扩展与嵌在类型里的协议一样放进 interface 的顶层 extensions 区块。声明在本模块类型的 extension 里的协议被编译器直接挂在类型上,本来就打印正确。 +- **落地模块**:SwiftPrinting(`SwiftDeclarationPrintConfiguration.marksNestedDefinitions`、新文件 `SwiftDeclarationPrinter+DefinitionRegions.swift`、四处嵌套循环、协议默认实现扩展的条件)、SwiftInterface(顶层区块收录 extension 里的协议的扩展);swift-semantic-string(`DefinitionRegion`、`DefinitionRegionTable`、`separatingDefinitionRegions()`、`content(ofDefinitionRegion:)`、`removingIndentation(levels:)`)。测试新增 `NestedDefinitionRegionContractTests`、`ProtocolInExtensionTests`,两者加进 CI 主过滤列表。 +- **验证**:`ProtocolInExtensionTests` 先红后绿。契约测试对 SymbolTestsCore 每个有嵌套定义的根类型与 extension,在进程内与文件两种读取方式、三种配置(只标定义区域;加标记模式;全部选项加 Transformer 模板)下逐区域比较,全部通过,区域数与嵌套定义数一致。swift-semantic-string 全部 432 个测试通过,watchOS `arm64_32` 编译通过。全量测试与渲染 A/B 见提案决策日志。 +- **补记(2026-10-08)**:③ 定下的规则公开为 `ProtocolDefinition.printsDefaultImplementationExtensionsAfterDeclaration`(新增公开 API,写进 0.23.0 发版说明)。此前库里写了两份(打印器一份,`SwiftInterfaceBuilder` 的嵌套协议区块取反一份);RuntimeViewer 要知道哪些协议的默认实现得自己补印,只能再照抄一份,③ 改规则时它就跟着错过一次(RuntimeViewer PR #121 审查的第 PR121.27 条)。现在打印器、interface 生成器与宿主都读这个属性。行为不变,证据见提案决策日志。 +- **关联文档**:[0068-nested-definition-regions](../Evolutions/0068-nested-definition-regions.md)、[Glossary.md](../Glossary.md)「nested-definition region」、swift-semantic-string 的 `docs/DefinitionRegions.md`。 +- **对应版本**:0.23.0(swift-semantic-string 0.5.0 带出 `DefinitionRegion`,本库下限随之抬到 0.5.0)。 + +## 96. 离线泛型特化,参数层号只数声明了参数的上下文 + +- **时间段**:2026-09-30 — 2026-10-02。 +- **动机**:`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在加载进当前进程的 `MachOImage` 上用;RuntimeViewer 将来的离线模式读 `MachOFile`,完全不能特化。用户:「把离线泛型特化实现一下,我记得之前在做静态布局的时候就提到过这个,目前泛型特化只有运行时才能用」。 +- **关键决策**:**① 离线执行与在线一一对应**:`GenericSpecializer` 的 `specialize` / `staticPreflight`,实参变成类型节点(`.metatype` 等宿主类型用本进程运行时的名字),结果是实例化类型名加按层分组的实参(`GenericArgumentBinding`),打印器与静态布局引擎据此出绑定头部、代换并投影关联类型的字段类型、全部布局注释。**② 实例化类型名移植运行时 `_buildDemanglingForContext`**,非 key 参数由 same-type 约束补齐;只有嵌套泛型的约束 extension 一处有意与运行时不同(运行时拼出的名字畸形)。在线特化的 `typeName` 也改用它,不再把实参全放进最内层。**③ 约束检查两档**:确定违反报错,证明不了只警告;沿用现有的 error / warning case,RuntimeViewer 对它们做了穷尽 `switch`。**④ 参数层号整类修复**:用 0.21.0 的 CLI 证实未特化的 interface / dump 头部同样把 `Outer.Middle.Inner` 的 `B` 打成 `A2`;新增 `GenericParameterDepthLayout`(只数声明了参数的上下文,extension 按被扩展类型拆层),五处改用它,用户选择整类一起修。**⑤ 在线模式也给特化后的泛型 enum 出 Enum Layout 注释**,两条路径才能逐字节对照,用户选择。**⑥ 实现时发现并修的两处**:离线 request 丢掉跨镜像协议需求(读文件时协议引用落在 bind 上,`buildRequirement` 只认已解析的 descriptor);静态展开偏移树不投影具体类型的关联类型。 +- **落地模块**:`SwiftInspection`(`GenericParameterDepthLayout`、`GenericArgumentBinding`、`SymbolicDemangler.instantiatedTypeNode`、`RuntimeMetadataTypeBuilder` 的层号)、`SwiftSpecialization`(离线执行、`GenericInstantiation`、`StaticSpecializationResult`、`TypeDefinition` 的离线 `specialize` 重载、在线类型名、`buildRequirement`)、`SwiftDeclaration`(`TypeDefinition.staticSpecialization`)、`SwiftLayout`(带 binding 的四个入口、`make(forBinding:)`、穿过 extension 的实参遍历、`ImageUniverse.projectingConcreteMembers`、展开偏移树的投影)、`SwiftDeclarationRendering`(`StaticFieldLayoutProvider` 的四个新方法、`FieldLayoutRenderState.genericArgumentBinding`、离线字段代换、运行时后端的泛型 enum 布局、`GenericContext+Dump` 的层号、opaque type 的 thunk 实参布局)、`SwiftThunkAnalysis`(`AccessorThunkOwnerLayout` 带层号布局的初始化)、`SwiftDump` / `SwiftPrinting`(头部按层号命名,`boundTypeNode(of:)`)。测试支持新增 `GenericSpecializationFixture`(现场编译的 dylib,同一个文件按两种方式读)与 `GenericSpecializationFixtureIndexers`。 +- **验证**:39 个新测试;层号五处与另外四项修复都先确认修复前失败。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra)2210 个测试 / 420 个套件全部通过,原始退出码 0,known issue 只有早已登记的 `SymbolicManglingIndexTests`。渲染 A/B 以 `b2b7d997` 为基线,共 132 对,90 对逐字节一致;42 对差异全部是预期的改变,两侧重跑确认是确定性的。一是嵌在不声明参数的中间层下的类型头部从 `` 改成 ``(Combine 的 `Optional.Publisher.Inner` / `Result.Publisher.Inner`、SwiftUICore 的 `TimeDataSource.Resolver.ResolvedOffsetBox`,每个版本、每条 reader 路径都有);二是展开偏移树把具体类型的关联类型投影后命名并继续展开(`Angle.AnimatableData` → `Swift.Double` 等);三是约束 extension 里类型的实参代换修正(`MeasurementView` 里原先错印成 `Measurement`)。脚本写死的 `26.6.2` 归档目录不在(卷上叫 `26.6`),26.6 与 27.0 两份 cache 手动补跑;脚本的 CLI 腿不出布局注释,另跑了打开全部布局注释的 24 对。逐项明细在提案的「验证」一节。2026-10-02 分支 rebase 到 find-navigator(`86f65341`)之上,用本地兄弟依赖重跑全量:2224 个测试 / 424 个套件通过,原始退出码 0(rebase 前的 2210 个加上 find-navigator 新增的 14 个);渲染 A/B 未重跑。 +- **关联文档**:[0069-offline-generic-specialization](../Evolutions/0069-offline-generic-specialization.md)、[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[StaticLayoutEngine.md](StaticLayoutEngine.md)「后续工作」、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md)、[SpecializedInterfaceBoundRenderingRestoration.md](SpecializedInterfaceBoundRenderingRestoration.md)、[Glossary.md](../Glossary.md)「depth」「instantiated type name」「offline specialization」。 +- **对应版本**:0.23.0。 + +## 97. PR #131 review 的修复:13 条修掉,第 9、12 条登记不修 + +- **时间段**:2026-10-07(review、复现测试)— 2026-10-08(修复落地)。 +- **动机**:`/code-review max` 对 PR #131(find-navigator 配套的三份提案加离线泛型特化)给出 15 条发现,逐条按四问裁决、写好复现测试与修法,记在 [Roadmaps/2026-10-08-pr131-review-findings.md](../../Roadmaps/2026-10-08-pr131-review-findings.md)。用户审完后说「把发现的问题修一下吧」。 +- **关键决策**: + - 有修法的 13 条全部落地,包括原本建议「离线模式接入前再修」的第 5、11 条(修法已写好、已验证)。每条修复连同它的复现测试一个 commit。 + - 第 1、8、13 条与 PR 已整类修掉的「泛型参数层号数错」同属一类,这次补齐:opaque 引用的实参表按位置当层号、opaque provider 按父链数层、thunk 类型构造器只数类型层。按全库扫描,除这八处外没有别的地方用父链或位置数层号。 + - 第 13 条保留旧逻辑作为第二条路:整个替换的第一版让 same-type 约束 extension 里的类型退化成 `accessor function at …`,加守护测试钉住那个形状。 + - 第 7 条(`specializedChildren` 无锁追加)的横向排查查出 MachOReading 里 `MachOFile` / `DyldCache` 懒创建文件映射和句柄的四个 getter 是同一类写法。`FullDyldCache` 把同一批子 cache 实例交给所有镜像、`cachedHost` 又是进程级单例,`diff` / `evolution` 并行准备输入时会同时第一次读同一个子 cache,所以按「同类一并修」改为持锁创建、只存一次(review 记录原把它列为「另开一项」)。 + - 登记不修:第 9 条(等待索引时不借出优先级)、第 12 条(嵌套偏移缓存记住解析失败,转 RuntimeViewer)、第 10 条里有意的名字差异、review 被条数上限砍掉的三个顺带项,以及核验时驳回的四条候选,见 [ReviewAdjudications.md](ReviewAdjudications.md) A53–A59。 + - 顺带:PR 重写过的几行缩写改成完整名称;`ProtocolInExtensionTests` 编 fixture 补 `-swift-version 5`;CI 主过滤列表补上离线特化、层号与这批新加的套件(依赖本机 cache 的 `OfflineProjectionDependencyResolutionTests` 除外),单线程协作池那一步之后另加一步,关掉大栈执行器再跑并发打印测试——原来那一步测不出它要防的问题,因为打印跑在 swift-demangling 自己的线程上,严格池缩不到它们。 +- **公开 API 与行为变化**(写进 0.23.0 发版说明):新增 `ConformanceProvider.superclassLink(of:)`、`ConformanceProvider.isConditionalConformance(of:to:)`(都有默认实现)与公开枚举 `SuperclassLink`,`StaticFieldLayoutProvider.projectingConcreteMembers(in:)`(有默认实现),`StaticLayoutCalculator.projectingConcreteMembers(in:)`。行为:opaque 类型的实参按描述符的层结构分组;离线父类检查遇到 ObjC 中间类只给警告;带条件的协议遵循给警告;extension 里协议兜底补出的默认实现重新打印出来;静态展开偏移不再把 opaque 实际类型印成占位符。 +- **落地模块**:SwiftDeclarationRendering(`Node+OpaqueType`、`DependentMemberProjection`、`StaticFieldLayoutProvider`、`StaticSpecializationNodeSubstitution`)、SwiftInterface(`SwiftInterfaceBuilder`、`SwiftInterfaceBuilderOpaqueTypeProvider`)、SwiftPrinting(`SwiftDeclarationPrinter+Headers`)、SwiftThunkAnalysis(`ThunkTypeNodeBuilder`)、SwiftSpecialization(`ConformanceProvider`、`GenericInstantiation`、`GenericSpecializer`、`GenericSpecializer+StaticSpecialization`、`TypeDefinition+Specialization`)、SwiftDeclaration(`TypeDefinition` 的说明)、SwiftLayout(`ImageUniverse+AssociatedTypeWitnessProjection`、`StaticLayoutCalculator`)、MachOReading(`MachOFile+`、`DyldCache+`);测试支持 `GenericSpecializationFixture` 加 `TiedParameterPair`;CI。 +- **验证**: + - JHs-Mac-Studio-Ultra(Swift 6.4)上 review 时验证过修法:复现测试在 PR 头上全红、修后全绿,全量 2354 个测试全部通过。 + - 落地时在 JHs-Mac-Studio 上重新验证,用的是 CI 的工具链(Xcode 26.6、Swift 6.3.3),依赖钉到与 Ultra 相同的版本(MachOKit 0.54.101、MachOKitExtensions 1.1.2、MachOObjCSection 0.8.109、swift-demangling 0.7.1,只有 swift-semantic-string 链本地的 `next`)。11 个复现套件(含新的 `ConcurrentFileMappingTests`)在 PR 头的源码上全部失败、修后全部通过。`OfflineProjectionDependencyResolutionTests` 写死的归档 cache 本机没有,在沙盒副本里临时改指本机装的 iOS 27.0 模拟器 runtime 里的 cache,同样是 PR 头上失败、修后通过。 + - 全量 `swift test --skip IntegrationTests`:2358 个测试、448 个套件(Ultra 上的 2354 / 447 加上新的 `ConcurrentFileMappingTests`),原始退出码 1。失败的只有 `MultiPayloadEnumDescriptorCacheTests` 的两条(`everyFixtureMultiPayloadEnumRendersALayout`、`noncopyableMultiPayloadEnumLaysOutFromItsResolvedPayloads`):换回 PR 头的源码,在同一环境里同样两条、同样位置失败,是这台机器上早就有的环境问题(进程内 enum 布局,这批改动不碰;`next` 上也是这样)。另有早已登记的 known issue(`SymbolicManglingIndexTests`)。 + - 渲染 A/B(基线 `beae202d`,候选是这批代码提交的末尾 `f108d5e6`;两侧 release,共用同一份 `Package.resolved`,经构建队列预构建后带 `--skip-build` 跑):**90 对全部逐字节一致**——归档 cache 15.5 与 26.6.2 各 12 对,iOS 15.5 / 18.5 / 18.6 / 26.5 模拟器 42 对,MachOImage 腿 24 对;iOS 27.0 模拟器的框架在 cache 里、不是文件,那条腿按设计跳过。会改变输出的几条在这些框架与选项组合里都没有触发:第 1 条要外层有一层不声明参数的 opaque 引用,系统框架的 witness 记录里多半已被编译器代换成具体类型;第 6 条只在打开展开字段偏移时出现,A/B 的 CLI 腿不出布局注释、MachOImage 腿不开展开偏移。第 1 条在真实 app 上的效果另用两侧 CLI 对本机的 `/Applications/Xcodes.app` 复核:11599 行的 interface 只有两行不同,都是 `typealias Body` 里的 `TupleToolbarContent` 补上了实参;补出来的类型里露出 5 处本来就解不出的 kind-9 占位符,修前藏在 `A` 后面。 +- **关联文档**:review 记录;[ReviewAdjudications.md](ReviewAdjudications.md) A53–A59;四份提案的决策日志([并发打印](../Evolutions/0066-concurrent-definition-printing.md)、[离线特化](../Evolutions/0069-offline-generic-specialization.md)、[嵌套定义区域](../Evolutions/0068-nested-definition-regions.md)、[嵌套偏移记忆化](../Evolutions/0067-nested-field-offset-memoization.md));[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md)、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、[Modules/MachODependencies.md](Modules/MachODependencies.md)。 +- **对应版本**:0.23.0,随 PR #131 合入。 ## 维护约定 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 3e2672b93..17f4f250e 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -621,7 +621,7 @@ - **裁决**:本库不修(2026-10-08),转 RuntimeViewer。 - **发现**:`NestedFieldOffsetLevelMemo`(`Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift`)按 metatype 记下展开树的每一层,「当时哪些字段类型解析不出」也一起记住。宿主之后加载了定义那个类型的镜像,缓存仍说解析不出,展开树在那里停下。 -- **复现 / 是否误报**:属实,是设计本身的取舍,提案 [draft-nested-field-offset-memoization](../Evolutions/draft-nested-field-offset-memoization.md) 已写明,并判断为近乎理论。review 没有在 AppKit、SwiftUI、WebKit、Xcode IDE 框架里找到实例。 +- **复现 / 是否误报**:属实,是设计本身的取舍,提案 [0067-nested-field-offset-memoization](../Evolutions/0067-nested-field-offset-memoization.md) 已写明,并判断为近乎理论。review 没有在 AppKit、SwiftUI、WebKit、Xcode IDE 框架里找到实例。 - **与 main 基线对比**:PR 新引入(记忆化本身是这个 PR 的一部分)。 - **为什么不修**:库不知道宿主进程什么时候加载了新镜像(库不注册 dyld 回调),所以清除入口 `RuntimeFieldLayoutMemo.removeAll()` 交给宿主,在加载镜像之后调用。 - **转 RuntimeViewer**:它的 find-navigator 分支只在自己 `dlopen` 之后(`DyldUtilities.loadImage(at:)`)调用 `removeAll()`,被检查的进程自己加载的镜像不会触发。`DyldUtilities.observeDyldRegisterEvents()` 写了 dyld 加载镜像的回调,但从没被调用;那边要注册这个回调,在回调里调用 `removeAll()`。 @@ -634,7 +634,7 @@ - **裁决**:不修(2026-10-08)。发现 10 的另一部分(算类型名失败时静默退回扁平名)已修,见 [Roadmaps/2026-10-08-pr131-review-findings.md](../../Roadmaps/2026-10-08-pr131-review-findings.md) 第 10 条。 - **发现**:`extension Outer.SecondMiddle where … { struct DeepConstrainedInner }` 这类类型在线特化之后,`typeName` 按层绑定实参,类型头印的却是运行时 metadata 的名字。运行时只给被扩展类型最内层的列表换实参,把全部实参塞进 `SecondMiddle` 的列表、`Outer` 保持未绑定。 -- **复现 / 是否误报**:属实;提案 [draft-offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md) 的决策日志(2026-10-01「嵌套泛型的约束 extension 里的类型,实例化名字按层绑定,不照搬运行时」)写明这是有意的差异,[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)「实例化类型名」一节也有说明。 +- **复现 / 是否误报**:属实;提案 [0069-offline-generic-specialization](../Evolutions/0069-offline-generic-specialization.md) 的决策日志(2026-10-01「嵌套泛型的约束 extension 里的类型,实例化名字按层绑定,不照搬运行时」)写明这是有意的差异,[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)「实例化类型名」一节也有说明。 - **与 main 基线对比**:PR 新引入(在线特化的 `typeName` 是这个 PR 改成按层绑定的)。 - **为什么不修**:运行时拼出的名字不对应任何实例化。`typeName` 是 RuntimeViewer 侧边栏的显示名和标识,按层绑定的才是对的;类型头取 metadata 的名字是两条路径共有的做法,离线路径的类型头因此与在线逐字节相同。 - **既往修复**:无。 @@ -681,7 +681,7 @@ ## A59 — PR #131 review 中被核验驳回的四条候选(**误报**) - **裁决**:误报(2026-10-08,review 时各有一个核验 agent 读码与编译器源码后驳回)。登记在这里,下次 review 对照跳过。 -- **一、打印器改了「extension 里的协议」的默认实现扩展的打印位置,会让 RuntimeViewer 或库内的使用方丢掉这些扩展**:不成立。`SwiftDeclarationPrinter.swift` 只在 `parent` 与 `extensionContext` 都为空时把默认实现扩展接在协议后面,这是提案 [draft-nested-definition-regions](../Evolutions/draft-nested-definition-regions.md) 有意改的契约;库里唯一调用 `printProtocolDefinition` 的 `SwiftInterfaceBuilder` 在顶层区块按同一条件补上(diff / evolution 只打印协议头,扩展整桶另印,从不依赖打印器接在后面;dump 不走这个打印器)。RuntimeViewer 那边被点名的分支在跳过之后紧接着又把同一桶扩展无条件追加了一次,所以不丢;与本 PR 配套的是它的 `feature/find-navigator`,用的条件与这里相同。(本轮另修的第 4 条是另一回事:协议在第五块才被索引,第四块读到的列表是空的。) +- **一、打印器改了「extension 里的协议」的默认实现扩展的打印位置,会让 RuntimeViewer 或库内的使用方丢掉这些扩展**:不成立。`SwiftDeclarationPrinter.swift` 只在 `parent` 与 `extensionContext` 都为空时把默认实现扩展接在协议后面,这是提案 [0068-nested-definition-regions](../Evolutions/0068-nested-definition-regions.md) 有意改的契约;库里唯一调用 `printProtocolDefinition` 的 `SwiftInterfaceBuilder` 在顶层区块按同一条件补上(diff / evolution 只打印协议头,扩展整桶另印,从不依赖打印器接在后面;dump 不走这个打印器)。RuntimeViewer 那边被点名的分支在跳过之后紧接着又把同一桶扩展无条件追加了一次,所以不丢;与本 PR 配套的是它的 `feature/find-navigator`,用的条件与这里相同。(本轮另修的第 4 条是另一回事:协议在第五块才被索引,第四块读到的列表是空的。) - **二、离线特化把 `.metadata` 实参当指针用,文件里读出的 `Metadata` 会成野指针**:不成立。离线 `specialize` 的文档(`GenericSpecializer+StaticSpecialization.swift` 开头)与 [OfflineGenericSpecialization.md](OfflineGenericSpecialization.md) 都写明 `.metatype` / `.metadata` / `.specialized` 是宿主进程自己的类型;`.specialized` 的 `metadata()` 先从内存读 kind,只可能是已经解引用过的进程内地址。在线路径对 `.metadata` 一直有同样的前提,误用时同样会崩,不是本 PR 引入的新风险。 - **三、特化后的泛型 enum 跳过解析不出的 payload,会算出错误的 Enum Layout**:不成立。`RuntimeFieldLayoutBackend` 在打印布局前用 value witness table 的 size 交叉校验(`impliedTotalSize` 与 `typeLayout.size` 不等就不出注释),这条校验是 `12232bee` 专门为这类缺口加的,对特化的泛型 enum 同样生效;跳过 payload 只会让注释消失,不会印出错的布局。非泛型 enum 在基线上就这样跳过。 - **四、`GenericParameterDepthLayout` 跳过匿名上下文,让泛型方法的 opaque 描述符层号算错、thunk 名字跟着错**:不成立。层结构确实把方法的参数与 opaque 参数并成一层,但 kind-9 thunk 的实参缓冲只按命名声明的签名绑定(编译器 `AbstractMetadataAccessor::emit` 取 `O->getGenericSignature()`),不含 opaque 参数;两种层结构只在第三个字及以后不同,那里放的是 witness table,从不被命名。基线用 `AccessorThunkOwnerLayout(genericContext:)` 算出的是同一个结构,PR 只是把计算挪了位置。 diff --git a/Documentations/Internal/StaticLayoutEngine.md b/Documentations/Internal/StaticLayoutEngine.md index 882482959..8d95cf46c 100644 --- a/Documentations/Internal/StaticLayoutEngine.md +++ b/Documentations/Internal/StaticLayoutEngine.md @@ -198,7 +198,7 @@ Value-generic / pack(阶段 6)由 `ValueGenericAndPackLayoutTests` 验证: - **~~顶层具体泛型实例化的逐字段 offset~~(已完成)**:把阶段 5 的 `GenericArgumentEnvironment` 替换从「字段场景」**对称扩展**到「顶层请求场景」。新增两个公开入口:`StaticLayoutCalculator.fieldLayout(of:genericArguments:)`(descriptor + 具体实参 `Node`,按 depth-0 位置建环境)与 `fieldLayout(forInstantiationMangledName:)`(二进制里的 `Foo` 引用:demangle → 按限定名解析 descriptor → 经 `make(forBoundGenericNode:)` 建环境,故跨模块实例化在其**定义镜像**上展开)。实现上把富信息逐字段路径(`accumulateFieldLayout` → `AggregateFieldLayout`,**带逐字段降级**)线程化 `environment`(默认 `.empty` ⇒ 非泛型行为逐字节不变),并把私有 `fieldLayout(ofStruct:/ofClass:)` 抽出 `in image:` 以支持跨镜像;新增 `GenericArgumentEnvironment.make(forDepthZeroTypeArguments:)` 直接从实参 Node 列表建环境。仅 depth-0 参数;depth>0、裸泛型仍按字段降级。**未**引入对 `SwiftSpecialization` 的依赖——runtime 真值在测试侧用底层 accessor 传具体实参 metatype 取得(无约束泛型无需 PWT)。 - **~~阶段 6 value-generic(SE-0452)与 parameter-pack(SE-0393)实例化~~(已完成)**:环境接受 `.integer`/`.negativeInteger`/扁平 `.pack` 实参;替换改为自定义 top-down 递归,`.tuple`/`.pack` 内的具体 pack expansion 就地展开(逐元素 pattern 实例化、空 pack、单元素坍缩、`Foo` 转发扁平化);求解器新增 `builtinFixedArray` 分派与 `Swift.InlineArray` 特判(`size = stride = element.stride × count`,XI 取首元素);tuple XI 修正为取元素最大值;零大小字段 offset 镜像 IRGen 约定(上报 0)。官方离线 lowering(RemoteInspection `TypeLowering.cpp`)对 pack 直接报错、对裸 `Integer` 不 lower——本阶段以 runtime 替换语义为 ground truth,超越官方离线实现。仍降级:裸 pack/value 参数(无实参)、depth>0、pattern 内嵌套 expansion(见「已知降级」)。 - **~~阶段 9 class-bound 泛型参数不特化解析~~(已完成)**:`ClassBoundGenericParameterAnalysis` 从 descriptor 需求签名提取 class-bound 参数键,经 `GenericArgumentEnvironment.classBoundParameterKeys` + 占位 `.class` 替换,使未特化泛型类型的 class-bound 参数字段(及其后字段)精确解析,见上文「核心算法」。runtime 真值:class-bound 约束大多可经 accessor 传具体类 metatype 取得(`AnyObject` layout 约束 / ObjC 协议 / superclass 约束的签名不需要 witness table);Swift class-bound 协议约束的签名需 witness table,其 fixture 与 `AnyObject` 变体**共享同一字段形状**、经传递性锁定。仍不可静态定:无约束或非 class-bound 参数(`T`、`T: Equatable`、value/pack 参数)——不特化即缺实参。下一步若要继续推进泛型,候选是「扫二进制里出现的 bound-generic 引用逐个实例化枚举」与「用户手动特化前端(镜像 `SwiftSpecialization` 的 request/selection 两步式,执行端已就绪)」。 -- **~~用户手动特化前端~~(2026-10-01 已完成)**:离线泛型特化(提案 [offline-generic-specialization](../Evolutions/draft-offline-generic-specialization.md))镜像 `SwiftSpecialization` 的 request/selection 两步式,在 `MachOFile` 上产出 `GenericArgumentBinding`,引擎据此给特化后的定义算字段偏移、payload 布局、逐 case 的 enum 布局与展开偏移树(`StaticLayoutCalculator` 带 `genericArgumentBinding:` 的四个入口)。binding 覆盖全部层,故嵌套在特化父类型里的泛型类型也能整体实例化,不再局限于 depth-0 的 `genericArguments:`。另一条候选「扫二进制里出现的 bound-generic 引用逐个实例化枚举」仍未做。详见 [OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)。 +- **~~用户手动特化前端~~(2026-10-01 已完成)**:离线泛型特化(提案 [offline-generic-specialization](../Evolutions/0069-offline-generic-specialization.md))镜像 `SwiftSpecialization` 的 request/selection 两步式,在 `MachOFile` 上产出 `GenericArgumentBinding`,引擎据此给特化后的定义算字段偏移、payload 布局、逐 case 的 enum 布局与展开偏移树(`StaticLayoutCalculator` 带 `genericArgumentBinding:` 的四个入口)。binding 覆盖全部层,故嵌套在特化父类型里的泛型类型也能整体实例化,不再局限于 depth-0 的 `genericArguments:`。另一条候选「扫二进制里出现的 bound-generic 引用逐个实例化枚举」仍未做。详见 [OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)。 - **multi-payload enum 的 payload 内部偏移(可选,未做)**:当前结构化路径只给整体 size/stride/align(已满足「作为字段」需求,且对全部 fixture multi-payload enum 与 runtime VWT 逐一吻合)。若需逐 case 的 payload 投影/tag 编码细节,`EnumLayoutCalculator.LayoutResult.cases` 已含,可后续暴露。extra inhabitants:三条策略**均已精确**——tagged(依赖实参的泛型实例化)按 runtime 公式(阶段 8),**spare-bits/混合按 IRGen `MultiPayloadEnumImplStrategy::getFixedExtraInhabitantCount` 移植**(精度补漏):`totalTagBits = CommonSpareBits.count() + extra-tag 位按字节向上取整`,`≥ 32 → 0x7FFFFFFF`,否则 `2^totalTagBits − numTags`(capped);`__swift5_mpenum` 序列化 mask 仅裁剪首尾零字节(GenReflection.cpp `calculateSpareBitsMask`),置位数与 `CommonSpareBits.count()` 严格相等,故从 descriptor 重建的 `countSetBits` 可直接作公式输入。XI 统一由 `EnumLayoutCalculator.LayoutResult.extraInhabitantCount` 携带(bridge 不再自算)。注意官方离线实现(RemoteInspection `TypeLowering.cpp:2243`)**从不结构化推导 spare-bits XI**——无 builtin descriptor 时整体退化 tagged 公式(spare-bits 布局连 size 都会算错),有 builtin 时 XI 照抄 descriptor——本引擎在此再次超越官方离线实现(与阶段 6 的 pack 情形同款)。 - **~~预特化泛型 MPE 的 spare-bits 布局~~(2026-08-05 已解决,且定性修正)**:曾记为「预特化 metadata 按编译期 spare-bits 布局,需识别 canonical specialization 记录」的硬骨头,深挖后定性被推翻——真实机制是**布局与实参无关的泛型 MPE 由编译器静态布局**(完整 VWT 烘焙进 metadata pattern,全新参数的实例化也共享它,与预特化无关),且编译器已把裁决写进二进制:只有这类 fixed MPE 才有 builtin/mpenum 记录(`GenReflection.cpp` 门槛 `!needsPayloadSizeInMetadata()`;`!AllowFixedLayoutOptimizations` 时编译器自己也退 tagged 且不发记录,GenEnum.cpp:7192)。修复即放开 `EnumLayoutBridge` 的两道门(builtin 查表的 `environment.isEmpty`、spare-bits 分支的 `!descriptor.isGeneric`)+ `compute()` 补查定义镜像 builtin 索引,`AttributedString.Keys.SetIterator` / `SpatialEventCollection.Iterator` 与 `NSHostingView.AllowAutomationElementsState` / `AnimatedValueState` 一族随之修正,普查整型偏差清零。守卫:`GenericSpareBitsEnumLayoutTests`(fixture `SpareBitsVariantEnum` 24/24/XI 125 修复前红 + OS 迭代器端到端 + 记录存在性判别针)。裁决与全过程见 [TaskReports/2026-08-05-generic-fixed-mpe-spare-bits.md](TaskReports/2026-08-05-generic-fixed-mpe-spare-bits.md)。 - **`@rpath` 完整展开**:`MachOFile` 闭包 MVP 靠 dyld cache bare-name + 显式路径覆盖;完整 `@rpath`/`@loader_path`/`@executable_path` 展开(读 `LC_RPATH` + 相对 root 定位)未做,调用方可预先展开为绝对路径。 diff --git a/Documentations/README.md b/Documentations/README.md index 4591c0f03..a07eb97ba 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -162,14 +162,14 @@ selects names using each access's offset and width. | [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | | [Evolutions/0058-swift-section-kit.md](Evolutions/0058-swift-section-kit.md) | **提案 0058(Implemented)**:把 swift-section 的功能抽成对外 product `SwiftSectionKit`——每个子命令一个按用途建模的请求类型(`DumpRequest`、`ABIDiffRequest`……),输出交给调用方注入的输出端,测试换成内存记录器即可断言;CLI 只剩 flag 声明与校验、flag → 请求映射、库错误翻译回历史文案、诊断的流路由和退出码。输出逐字节保持,只有两处有意偏差(写流统一走 `fputs` / `fwrite`;参数层面的错误先于打开二进制报出)。 | | [Evolutions/0059-dump-declaration-identity.md](Evolutions/0059-dump-declaration-identity.md) | **提案 0059(Implemented)**:`DumpRequest` / `ObjCDumpRequest` 交出每个顶层声明时附上种类与名字(`DumpedDeclaration`),`SwiftSectionOutput` 新增带默认实现的 `write(_:declaring:)` 接收;默认实现转给 `write(_:)`,CLI 输出逐字节不变。让宿主不必自己重建索引就能按声明拆文件(首个宿主:ReverseEngineeringToolbox 的「每个类型一个文件」)。 | -| [Evolutions/draft-nested-field-offset-memoization.md](Evolutions/draft-nested-field-offset-memoization.md) | **提案 draft(In Progress)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | -| [Evolutions/draft-concurrent-definition-printing.md](Evolutions/draft-concurrent-definition-printing.md) | **提案 draft(In Progress)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | -| [Evolutions/draft-nested-definition-regions.md](Evolutions/draft-nested-definition-regions.md) | **提案 draft(In Progress)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | -| [Evolutions/draft-offline-generic-specialization.md](Evolutions/draft-offline-generic-specialization.md) | **提案 draft(In Progress)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | | [Evolutions/0063-private-declarations.md](Evolutions/0063-private-declarations.md) | **提案 0063(Implemented)**:RuntimeViewer 的 Private 标签背后两件逻辑下沉到本库。一是名字经过的私有声明:整树搜索,跳过函数与闭包的签名和占位名的 `$` 段。二是按镜像反推 discriminator 的源文件:MD5 撞候选文件名,新 target,候选从镜像取,结果按镜像缓存。另给局部类型一个给读者看的名字(`Visitor #1 in TableDataSource.performDrop(to:)`)。RuntimeViewer 只负责展示。 | | [Evolutions/0064-module-selectors.md](Evolutions/0064-module-selectors.md) | **提案 0064(Implemented)**:适配 SE-0491 模块选择器——默认关闭的开关(interface 的 `usesModuleSelectors` / `--module-selectors`,dump 的 swift-demangling 新选项 `useModuleSelectors` / `--enable-module-selectors`),打开后照 Swift 6.4 编译器写 `.swiftinterface` 的规则输出 `Swift::Int`,嵌套类型每层带声明它的模块(`Swift::Duration.Foundation::TimeFormatStyle`),局部类型与 `A.Element` 不加。`~Swift.Copyable` 改由类型打印器印协议节点;`OpaqueTypeResolving.opaqueType` 加参数。 | | [Evolutions/0065-faster-lazy-definition-indexing.md](Evolutions/0065-faster-lazy-definition-indexing.md) | **提案 0065(Implemented)**:RuntimeViewer 的 Find 语料(进程内并行打印整个镜像)一半时间耗在给 resilient witness 找实现符号上——identical code folding 让一个地址挂成百上千个别名,每个 conformance 都从头逐个 demangle、搜索、打印比较,平方级。改为 `SymbolIndexStore.symbols(for:ownedBy:ownerKind:printedWith:in:)` 按地址把别名按归属(被遵循类型 / 协议)分组一次、之后查表,`ExtensionDefinition`、`ProtocolDefinition` 与两个协议 dumper 都改用它;`PropertyWrapperTypeCatalog` 锁外搜导出表,`InProcessDependencyLocator` 一次建表代替逐个 `MachOImage(name:)`;`SharedCache` 重测后不改。M1 Max 五个系统框架:Release 20 s → 8.4 s,Debug 104 s → 53 s,输出逐字节不变。 | +| [Evolutions/0066-concurrent-definition-printing.md](Evolutions/0066-concurrent-definition-printing.md) | **提案 0066(Implemented)**:`TypeDefinition` 一族的惰性 `index(in:)` 改为同步函数,经进程级一把锁与 in-flight 表只索引一次,并发调用者在 promise 上等首个调用者;`attributes` 改为打印时的局部变量,打印期不再写定义——解除 `MachOImage` 读者下同版本内并发打印的限制,RuntimeViewer 据此按对象并行建语料。 | +| [Evolutions/0067-nested-field-offset-memoization.md](Evolutions/0067-nested-field-offset-memoization.md) | **提案 0067(Implemented)**:进程内嵌套字段偏移展开按 metatype 缓存「一层展开」的记录,遍历本身原样不动,输出逐字节不变;匿名上下文判别符按描述符地址记忆化,不再线性扫共享缓存镜像的符号表;宿主加载镜像后调一次 `removeAll()`。起因是 RuntimeViewer 的 Find 语料构建采样:61% 在嵌套展开、9% 在符号查找。 | +| [Evolutions/0068-nested-definition-regions.md](Evolutions/0068-nested-definition-regions.md) | **提案 0068(Implemented)**:新开关 `marksNestedDefinitions` 下,父定义打印结果里每个内联的嵌套子定义包进 `DefinitionRegion`(swift-semantic-string 新增,手法同可见性区域),身份是名字节点的 mangled name;承诺内联与单独打印除缩进外逐字节相同并用测试钉住,RuntimeViewer 据此从父定义切出子定义,省掉约四成重复打印。含先修「嵌在 extension 里的协议把默认实现扩展打在外层大括号里」。 | +| [Evolutions/0069-offline-generic-specialization.md](Evolutions/0069-offline-generic-specialization.md) | **提案 0069(Implemented)**:离线泛型特化——`GenericSpecializer.specialize` 要调用镜像里的 metadata accessor,只能在 `MachOImage` 上用;给 RuntimeViewer 将来的离线模式(读 `MachOFile`)补上不经 runtime 的执行路径:按运行时 `_buildDemanglingForContext` 的规则拼出实例化类型名与按层分组的实参,离线约束检查(确定违反才报错,证明不了只警告),特化后的 `TypeDefinition` 在 interface 里打出绑定头部、代换后的字段类型(关联类型经 witness 投影)和按实参计算的布局注释。顺带修参数层数误数(整类五处,未特化 interface 头部也受影响)、运行时特化类型名被拍平、离线 request 丢跨镜像协议需求、静态展开偏移树不投影关联类型。本库不提供 CLI 入口。实现说明见 [OfflineGenericSpecialization.md](Internal/OfflineGenericSpecialization.md)。 | | [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/Roadmaps/2026-10-08-pr131-review-findings.md b/Roadmaps/2026-10-08-pr131-review-findings.md index 82392c5d8..fc2879b06 100644 --- a/Roadmaps/2026-10-08-pr131-review-findings.md +++ b/Roadmaps/2026-10-08-pr131-review-findings.md @@ -893,15 +893,15 @@ try await withThrowingTaskGroup(of: Void.self) { group in --- a/AGENTS.md +++ b/AGENTS.md @@ -271,7 +271,7 @@ --… The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read) — and `specialize(...)` appends to the generic definition unlocked. [draft-concurrent-definition-printing](…). -+… The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [draft-concurrent-definition-printing](…). +-… The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read) — and `specialize(...)` appends to the generic definition unlocked. [0066-concurrent-definition-printing](…). ++… The `MachOFile` reader is still not safe — MachOKit's `MachOFile` reads share one `FileHandle` (seek + read). `specialize(...)` may run beside reads of the same definition's `specializedChildren`: the list is held under a lock of its own. [0066-concurrent-definition-printing](…). ``` **修后**:测试通过(512 个全部留下)。 **横向排查**:库里另有四处同样「懒创建、无锁、nonatomic」的关联对象:`MachOFile` 与 `DyldCache` 的 `_fileHandle`、`_fileIO`(`Sources/MachO/MachOReading/Extensions/MachOFile+.swift`、`DyldCache+.swift`)。`MachOFile` 本来就声明不支持同一版本内并发;但宿主的 dyld cache 对象会被多个版本共享(`FullDyldCache.cachedHost`),跨版本并行时这四处会不会真被并发首次访问,还没查。它们不在本 PR 范围内,建议另开一项。 -**落地时**:`draft-concurrent-definition-printing` 的决策日志补一条(前提更正 + 加锁)。 +**落地时**:`0066-concurrent-definition-printing` 的决策日志补一条(前提更正 + 加锁)。 ### 8. opaque provider 少数一层(低到中,基线就有) @@ -1707,9 +1707,9 @@ struct SimulatorProjectionFixture.ElementsHolder<[Swift.Int]> { 2. **渲染 A/B 必跑**(AGENTS.md 对动到打印和索引的改动的要求)。会改变既有输出的是第 1 条(普通 SwiftUI app 的 opaque 类型实参)、第 4 条(extension 里协议的默认实现块)、第 6 条(静态展开偏移里 opaque 实际类型那一行)、第 8 条(带 provider 的 interface)、第 13 条(kind-9 字段名)。PR 本身在 rebase 和合并 `next` 后也还没重跑 A/B。 3. **文档同批**: - 演进账本补一节。 - - `draft-concurrent-definition-printing` 决策日志:第 7 条(前提更正、加锁)、第 9 条(登记)。 - - `draft-offline-generic-specialization` 决策日志与 `Internal/OfflineGenericSpecialization.md`:第 2、3、5、10、11 条。 - - `draft-nested-definition-regions` 决策日志:第 4 条。 + - `0066-concurrent-definition-printing` 决策日志:第 7 条(前提更正、加锁)、第 9 条(登记)。 + - `0069-offline-generic-specialization` 决策日志与 `Internal/OfflineGenericSpecialization.md`:第 2、3、5、10、11 条。 + - `0068-nested-definition-regions` 决策日志:第 4 条。 - `Internal/OpaqueReturnTypeResolution.md`:第 1、8 条。 - `Internal/Modules/SwiftThunkAnalysis.md`:第 13 条。 - AGENTS.md 的 `specialize(...)` 那句(diff 见第 7 条)。 From fb8aeedf847604803e421073b23be1df81eefbe7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 15 Oct 2026 11:12:23 +0800 Subject: [PATCH 48/49] docs: keep the deprecated reading forms until 0.24.0 0057 set their removal for 0.23.0, with the downstream repositories migrated first. RuntimeViewer's next has moved off them; MachOKitUI (from: "0.19.0", so it resolves 0.23.0 on its own) and swift-decompiler (tracking next) have not, and removing them now would break both on their next resolution. The forwarders stay for one more release: AGENTS.md, the glossary, the implementation note and the index say 0.24.0, and 0057 records the decision. --- AGENTS.md | 2 +- Documentations/Evolutions/0057-reading-context-migration.md | 5 +++-- Documentations/Glossary.md | 2 +- Documentations/Internal/ReadingContextAbstraction.md | 6 +++--- Documentations/README.md | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 05af6255c..ea6d6f447 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -206,7 +206,7 @@ Detail: [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.m - **`LayoutWrapper` is `@dynamicMemberLookup` over `Layout`**, so every layout field already reads as `record.field`. Do NOT re-declare a property that only forwards to `layout`, nor one that only widens a field to `Int` (the house style casts at the use site). A same-named property of a different type shadows the dynamic member and reads as a trap. The lookup does not reach through an existential — code iterating erased conformers needs a genuine protocol member. - **`resolvedDirectOffset(from:)` needs a key path to a *stored* property of the CONCRETE `Layout`.** One formed in a generic context against a layout *protocol* addresses a witness instead; the lookup answers nil and the force-unwrap behind it traps at runtime — so a shared implementation over a layout protocol cannot use it, each conformer calls it itself. It always answers the DIRECT reading, so a relative-*indirectable* field rules out `isIndirect` first. A descriptor already exposing a named `…Offset` property is what a consumer calls; re-deriving it at the use site is what that property exists to prevent. - **Trap:** a generic read (`context.readElement(at:)`, `machO.readElement(offset:)`) whose result lands in an Optional is inferred AT the Optional and reads the Optional's in-memory shape — the field plus one tag byte — so it answers nil whenever the byte after the field is non-zero. Returning it from an optional-returning function, assigning it to an optional, `guard let x: T = try? …` and a `flatMap` closure all do this; read into an annotated non-optional local (or `… as T`) and wrap that. The byte is often padding the runtime never writes, so the symptom comes and goes with the allocator. -- **A reading API is written once, against `some ReadingContext`** (`x(in context:)`, static `resolve(at:in:)`). The Mach-O (`in machO:`) and pointer (no-argument) forms still in the tree are deprecated one-line forwarders kept for one release and removed in 0.23.0 ([0057-reading-context-migration](Documentations/Evolutions/0057-reading-context-migration.md)): never add a new one, never put logic in one, never call one — pass `machO.context` or `.inProcess`. A bind or rebase check goes through `context.bindRebaseResolver`, never `as? MachOFile`. +- **A reading API is written once, against `some ReadingContext`** (`x(in context:)`, static `resolve(at:in:)`). The Mach-O (`in machO:`) and pointer (no-argument) forms still in the tree are deprecated one-line forwarders kept until 0.24.0 ([0057-reading-context-migration](Documentations/Evolutions/0057-reading-context-migration.md)): never add a new one, never put logic in one, never call one — pass `machO.context` or `.inProcess`. A bind or rebase check goes through `context.bindRebaseResolver`, never `as? MachOFile`. - **Inside a constrained extension (`where Pointee: OptionalProtocol`), calling a method that is also a protocol requirement binds to the requirement — the unconstrained witness — not to the constrained overload beside it.** A guard that must run on every path lives in a private helper that the context form and the forwarders both call (`RelativeDirectPointerProtocol`); a forwarder that calls the context form by name skips it. diff --git a/Documentations/Evolutions/0057-reading-context-migration.md b/Documentations/Evolutions/0057-reading-context-migration.md index efe333385..1536c188e 100644 --- a/Documentations/Evolutions/0057-reading-context-migration.md +++ b/Documentations/Evolutions/0057-reading-context-migration.md @@ -261,7 +261,7 @@ extension ReadingContext { 10. 0.22.0 发布(Changelog 写明废弃清单与三处行为变化)。 11. RuntimeViewer、MachOKitUI、swift-decompiler 各提迁移 PR。 -12. 0.23.0:删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。 +12. 0.24.0(原定 0.23.0,2026-10-15 推迟,见决策日志):删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。 **收尾判断**(落地时写进决策日志):是否需要配套实现说明(预期更新 `ReadingContextAbstraction.md` 即可,不另写);新术语「缓存范围」登记进术语表。 @@ -306,7 +306,7 @@ extension ReadingContext { 1. 本批发现的既有问题:`FunctionTypeMetadata.extendedFlags(in:)` 与 `EnumMetadataProtocol.payloadSize(descriptor:in:)` 从泛型 `readElement` 直接返回 Optional,按 Optional 的内存形状多读一个字节,`FunctionTypeMetadataTests` 时好时坏就是它;`ContextDescriptorWrapper.resolve(at:in:) -> Self?` 出错时用 `print` 写 stdout,违反日志规则,也会弄脏 CLI 的输出。**已修复**:分支 `fix/optional-read-and-stdout-print`,[PR #130](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/130)(本 PR 合入后直接对 `next`);另查出并修了 `SwiftClassObjectIndex` 读 class flags 的一处同类写法,同批清掉的还有 `SubstitutionMap` 的 `print`。 2. 渲染 A/B 脚本加 `--skip-build`:直接使用预先经 `queued-build` 构建好的产物,脚本自己不再构建。**已合入**:分支 `chore/rendering-harness-skip-build`,合并提交 `01b57f74`(2026-10-01 直接合入 `next`,没有开 PR);用法见 [SystemFrameworkRenderingVerification.md](../Internal/SystemFrameworkRenderingVerification.md)「关键调用细节」。 -**合入之后**(编号与状态已在合入时完成):0.22.0 的 Changelog 写明废弃清单与三处行为变化;给 RuntimeViewer(`next`)、MachOKitUI、swift-decompiler 提迁移 PR;0.23.0 删除全部废弃转发、`DeprecatedReadingFormsTests`,以及覆盖率登记表里 13 个指针版初始化器的键。 +**合入之后**(编号与状态已在合入时完成):0.22.0 的 Changelog 写明废弃清单与三处行为变化;给 RuntimeViewer(`next`)、MachOKitUI、swift-decompiler 提迁移 PR;0.24.0(原定 0.23.0,2026-10-15 推迟,见决策日志)删除全部废弃转发、`DeprecatedReadingFormsTests`,以及覆盖率登记表里 13 个指针版初始化器的键。 ## 决策日志 @@ -340,3 +340,4 @@ extension ReadingContext { | 2026-09-30 | 既有的 Optional 读取陷阱与 `print` 写 stdout 另开分支修,A/B 脚本加 `--skip-build` 也另开分支 | 用户选定;本 PR 只做迁移,保持聚焦 | | 2026-10-01 | In Progress → Implemented,编号 0057,经 [PR #129](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/129) 合入 `next` | 用户:「继续合并吧」。各共享分支上的最大编号是 0056(`next`)。分支基于 `next` @ `f7c189b8`,此后 `next` 没有新提交,合入无冲突。最后一次代码改动之后只有文档 commit,验收数据沿用「当前进度」一节:全量测试 2157 个 / 410 个套件原始退出码 0,渲染 A/B 96 对逐字节一致,三条路径性能持平 | | 2026-10-01 | 收尾判断:不另写使用指南,实现说明是 `ReadingContextAbstraction.md`「单一实现与废弃」一节;术语表的「cache scope」与「context form / Mach-O form / pointer form」已在实现批次登记;账本记第 73 节 | 迁移写法只有三种替换(`x(in: machO)` → `x(in: machO.context)`,`x()` → `x(in: .inProcess)`,`resolve(from:in:)` → `resolve(at:in:)`),废弃消息本身就给出了替代写法,0.22.0 的 Changelog 再列一遍 | +| 2026-10-15 | 删除推迟到 0.24.0 | 用户决定:发 0.23.0 时 RuntimeViewer 的 `next` 已迁完(`44607ba6`),MachOKitUI(`from: "0.19.0"`,会自动解析到 0.23.0)与 swift-decompiler(跟本库 `next`)都还没迁,0.23.0 删除会让它们下次解析时编不过。0.23.0 的 Changelog 写明新期限;两个下游迁完后再删。 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 637d02882..781324851 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -75,7 +75,7 @@ ### context form / Mach-O form / pointer form(读取接口的三种形式) -同一个读取接口曾经最多有三份手写实现:context form 收 `some ReadingContext`(`name(in: context)`、静态 `resolve(at:in:)`),Mach-O form 收一个 Mach-O reader、按偏移读(`name(in: machO)`、`resolve(from:in:)`),pointer form 不收读取器、直接用裸指针读本进程内存(`name()`、`resolve(from: pointer)`)。2026-09-30 起 context form 是唯一实现,另外两种是 0.22.0 废弃、0.23.0 删除的一行转发(`machO.context` / `.inProcess`)。 +同一个读取接口曾经最多有三份手写实现:context form 收 `some ReadingContext`(`name(in: context)`、静态 `resolve(at:in:)`),Mach-O form 收一个 Mach-O reader、按偏移读(`name(in: machO)`、`resolve(from:in:)`),pointer form 不收读取器、直接用裸指针读本进程内存(`name()`、`resolve(from: pointer)`)。2026-09-30 起 context form 是唯一实现,另外两种是 0.22.0 废弃、0.24.0 删除的一行转发(`machO.context` / `.inProcess`)。 - **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`、`Sources/MachO/MachOPointers/`、`Sources/MachO/MachOResolving/Resolvable.swift` - **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) diff --git a/Documentations/Internal/ReadingContextAbstraction.md b/Documentations/Internal/ReadingContextAbstraction.md index c9c903e07..083824c4b 100644 --- a/Documentations/Internal/ReadingContextAbstraction.md +++ b/Documentations/Internal/ReadingContextAbstraction.md @@ -159,7 +159,7 @@ extension RelativeDirectPointerProtocol { ## Usage Examples -Since the single-implementation pass (below, 2026-09-30) the `ReadingContext` form is the only one to call. The Mach-O form (`in: machO`) and the pointer form (no reader argument) are deprecated forwarders until 0.23.0. +Since the single-implementation pass (below, 2026-09-30) the `ReadingContext` form is the only one to call. The Mach-O form (`in: machO`) and the pointer form (no reader argument) are deprecated forwarders until 0.24.0. ```swift // A Mach-O file or image: pass its context. @@ -261,7 +261,7 @@ Sources/ | **1. Add Infrastructure** | Add `ReadingContext`, `MachOContext`, `InProcessContext` | Non-breaking | | **2. Add Extensions** | Add `resolve(at:in:)` to `Resolvable` and pointer protocols | Non-breaking | | **3. Gradual Migration** | New code uses `ReadingContext` API | Progressive | -| **4. Deprecation** | The `ReadingContext` form becomes the only implementation; the Mach-O and pointer forms are deprecated forwarders (0.22.0) and removed (0.23.0) | Done 2026-09-30, see below | +| **4. Deprecation** | The `ReadingContext` form becomes the only implementation; the Mach-O and pointer forms are deprecated forwarders (0.22.0) and removed (0.24.0, postponed from 0.23.0) | Done 2026-09-30, see below | ## Benefits @@ -319,7 +319,7 @@ Two deliberate decisions worth keeping in mind: 提案:[0057-reading-context-migration](../Evolutions/0057-reading-context-migration.md)。 -每个读取接口原先最多有三份手写实现:按偏移读 Mach-O 的、用裸指针读本进程的、经 `ReadingContext` 读的。现在只剩 `ReadingContext` 那一份;另外两份是一行转发(`machO.context` / `InProcessContext.shared`),标 `@available(*, deprecated)`,0.23.0 删除。下面是代码里看不出来、下次维护会踩的几点。 +每个读取接口原先最多有三份手写实现:按偏移读 Mach-O 的、用裸指针读本进程的、经 `ReadingContext` 读的。现在只剩 `ReadingContext` 那一份;另外两份是一行转发(`machO.context` / `InProcessContext.shared`),标 `@available(*, deprecated)`,0.24.0 删除(原定 0.23.0,下游未迁完而推迟)。下面是代码里看不出来、下次维护会踩的几点。 ### 转发必须原地保留 diff --git a/Documentations/README.md b/Documentations/README.md index a07eb97ba..c8ffe1712 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -159,7 +159,7 @@ selects names using each access's offset and width. | [Evolutions/0053-shared-cache-composition-and-eviction-registry.md](Evolutions/0053-shared-cache-composition-and-eviction-registry.md) | **提案 0053(Implemented)**:按镜像缓存整治——`SharedCache` 的并发核心不动,改它周围四件事:每实例的内存压力 `removeAll()` 绕过「最后一个 indexer 才驱逐」的认领规则且回收不到被活引用钉住的存储,整个去掉、改为注册表暴露显式 API;基类 `buildStorage(for: some MachORepresentableWithCache)` 把读者类型擦掉、6 个子类各自 `as?` 再分派,改为不可继承的组合式原语、构建闭包在调用点给;每次查找把 identifier 装箱成 `AnyHashable` 并哈希整条路径,改为只哈希 UUID / 指针的 `SharedCacheKey`;同线程同键重入静默死锁,改为带信息的 precondition。驱逐收口到下沉至 `MachOCaches` 的 `SharedCacheRegistry`(eviction group 加 dependents 表),两个手写 Store 并入。暂不改名,句柄 API 待测量后另议。 | | [Evolutions/0054-interface-descriptor-only-vtable-members.md](Evolutions/0054-interface-descriptor-only-vtable-members.md) | **提案 0054(Implemented)**:interface 按 vtable 槽位顺序打印类成员,并补上 descriptor-only member——剥掉 local 符号的镜像(系统 dyld cache 里的 AppKit)里,class 的 public 方法实现没有符号、只剩 `Tj` / `Tq`,interface 过去只从实现符号建成员,于是 AppKit 的 `NSTableViewDiffableDataSource` / `NSCollectionViewDiffableDataSource` 只剩 `init` 和 `deinit`(整个 AppKit 少 53 个成员)。改为从 vtable 槽出发、用 `Tq` 建成员,vtable 成员按槽位顺序打印,没有名字的槽跳过;顺带修掉闭包参数返回 Optional 时 `init` 被误打成 `init?`。ABI snapshot `formatVersion` 5 → 6。 | | [Evolutions/0055-group-sources-by-layer.md](Evolutions/0055-group-sources-by-layer.md) | **提案 0055(Implemented)**:`Sources/` 按层分组——31 个平铺的 target 分进 `Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/` 八个目录,`Package.swift` 逐个声明 `path:`;target / product / 模块名不变,下游无感。连带修正靠 `#filePath` 深度找 fixture 与扫描源码的几处代码,以及 CI 里写死的 `Version.swift` 路径。 | -| [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | +| [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.24.0 删除(原定 0.23.0);范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | | [Evolutions/0058-swift-section-kit.md](Evolutions/0058-swift-section-kit.md) | **提案 0058(Implemented)**:把 swift-section 的功能抽成对外 product `SwiftSectionKit`——每个子命令一个按用途建模的请求类型(`DumpRequest`、`ABIDiffRequest`……),输出交给调用方注入的输出端,测试换成内存记录器即可断言;CLI 只剩 flag 声明与校验、flag → 请求映射、库错误翻译回历史文案、诊断的流路由和退出码。输出逐字节保持,只有两处有意偏差(写流统一走 `fputs` / `fwrite`;参数层面的错误先于打开二进制报出)。 | | [Evolutions/0059-dump-declaration-identity.md](Evolutions/0059-dump-declaration-identity.md) | **提案 0059(Implemented)**:`DumpRequest` / `ObjCDumpRequest` 交出每个顶层声明时附上种类与名字(`DumpedDeclaration`),`SwiftSectionOutput` 新增带默认实现的 `write(_:declaring:)` 接收;默认实现转给 `write(_:)`,CLI 输出逐字节不变。让宿主不必自己重建索引就能按声明拆文件(首个宿主:ReverseEngineeringToolbox 的「每个类型一个文件」)。 | | [Evolutions/0062-local-type-context-names.md](Evolutions/0062-local-type-context-names.md) | **提案 0062(Implemented)**:函数、闭包里的局部类型挂在一串不带名字的 anonymous context 下,`SymbolicDemangler` 要么整串丢掉(变成外层类型的成员,同名的互相覆盖,SwiftUI 的 `TableDataSource` 7 个 `Visitor` 丢 5 个),要么从外围 private 函数借 discriminator(伪造成 private 类型);debug 构建也错。改为从描述符名字、`MXX` 符号、`_symbolic` 符号三处找回完整名字,都没有时按地址起占位名 `(Visitor in $1a2b3c)`;runtime 名字同样处理;interface 类型位置印短名、声明前注释写出所在函数。 | From b7be58ecef72d0a330594d33dab38d46f1f2a812 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 15 Oct 2026 11:13:43 +0800 Subject: [PATCH 49/49] release: 0.23.0 Bumps BundledVersion and both agent plugin manifests to 0.23.0, adds Changelogs/0.23.0.md in the one-sentence-per-entry style and points the README's package snippet at 0.23.0. The agent skill dates interface --module-selectors, dump --enable-module-selectors and snapshot format 7 to 0.23.0. The evolution log gains section 98 for the release. Verification of this code with remote dependencies only (MachOKit 0.54.101, MachOKitExtensions 1.2.0, MachOObjCSection 0.8.200, swift-demangling 0.7.2, swift-semantic-string 0.5.0, swift-capstone 6.0.1) on Xcode 26.6: full suite 2442 tests / 468 suites, raw exit code 1 from the two MultiPayloadEnumDescriptorCacheTests that already fail on this machine (enumLayout -> nil at :101 and :130); release builds for x86_64 and arm64 with 0 warnings, both run; Claude Code plugin validation passes and every flag the agent skill names is in the CLI's --help. --- .../swift-section/.claude-plugin/plugin.json | 2 +- .../swift-section/.codex-plugin/plugin.json | 2 +- .../skills/swift-section-cli/SKILL.md | 6 +-- Changelogs/0.23.0.md | 38 +++++++++++++++++++ .../Internal/ProjectEvolutionLog.md | 18 +++++++++ README.md | 2 +- .../Executables/swift-section/Version.swift | 2 +- 7 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 Changelogs/0.23.0.md diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index 2a1d0e48b..9e2303a91 100644 --- a/AgentPlugins/swift-section/.claude-plugin/plugin.json +++ b/AgentPlugins/swift-section/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.22.0", + "version": "0.23.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/.codex-plugin/plugin.json b/AgentPlugins/swift-section/.codex-plugin/plugin.json index e4844778e..aa8ec0464 100644 --- a/AgentPlugins/swift-section/.codex-plugin/plugin.json +++ b/AgentPlugins/swift-section/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.22.0", + "version": "0.23.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index d6d45621f..d173cdf25 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -43,7 +43,7 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, `--emit-export-status`, `--exported-only`, `--jobs`, `evolution --interface`, `--supplementary-apinotes`, from 0.20.0 `--dependency-search-path`, `--infer-objc-overrides` and the whole `objc` subcommand group, from 0.22.0 -`evolution --emit-available` / `--platform`, and after 0.22.0 `interface --module-selectors` +`evolution --emit-available` / `--platform`, and from 0.23.0 `interface --module-selectors` / `dump --enable-module-selectors`. When one is missing, say so rather than silently producing a weaker answer — the alternative is usually "upgrade (`brew upgrade swift-section`), or do without that annotation". @@ -248,8 +248,8 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 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 of its local symbols the newer tool also records the class members that only their method - descriptor names (see §9), which an old baseline would report as added wholesale. Format 7 - rejects every format-6 baseline: a type declared in a function or closure body is recorded + 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. diff --git a/Changelogs/0.23.0.md b/Changelogs/0.23.0.md new file mode 100644 index 000000000..3eba33ba3 --- /dev/null +++ b/Changelogs/0.23.0.md @@ -0,0 +1,38 @@ +# 0.23.0 + +## Breaking + +- Local types are now named after the function or closure that declares them, such as `Visitor #1 in Holder.countValues()`. +- ABI snapshots now use format version 7; regenerate snapshots written by earlier versions. +- Removed `TypeDefinition.attributes`. +- `SymbolicDemangler.isCacheEnabled` can no longer be set. +- Types conforming to `OpaqueTypeResolving` must implement `opaqueType(forNode:index:usesModuleSelectors:)`. +- Reading APIs that take a Mach-O or a raw pointer now stay deprecated until 0.24.0 instead of 0.23.0. +- Requires swift-demangling 0.7.2, swift-semantic-string 0.5.0 and MachOObjCSection 0.8.200 or later. + +## New + +- `GenericSpecializer` and `TypeDefinition.specialize(...)` now work on a `MachOFile`, without loading the binary. +- New `interface --module-selectors` and `dump --enable-module-selectors` options, and `SwiftDeclarationPrintConfiguration.usesModuleSelectors`, write qualified names as `Swift::Int` (SE-0491). +- New `Node.privateDeclarations` lists the private declarations a name refers to, and the new `SwiftPrivateDiscriminators` product recovers their source file names. +- New `SwiftDeclarationPrintConfiguration.marksNestedDefinitions` marks each nested definition in its parent's output, so a host can cut it out instead of printing it again. +- Definitions read from a `MachOImage` can now be printed from several tasks at once. +- New `RuntimeFieldLayoutMemo.removeAll()` forgets remembered in-process field layouts, for hosts that load more images. + +## Improved + +- Indexing and printing large images such as SwiftUI is much faster, especially when printing in parallel. +- Printing expanded field offsets in process is faster. +- `GenericSpecializer` now names each generic argument at its own level, such as `Outer.Inner`. +- Specialized generic enums now get an enum layout comment. +- Expanded field offsets now resolve associated types of concrete types, such as `Angle.AnimatableData`. + +## Fixed + +- Fixed local types of the same name merging into one declaration and losing their members. +- Fixed generic parameters of a type nested below a type without parameters printing as `A2` instead of `A1`. +- Fixed expanded field offsets naming the wrong generic argument for types declared in a constrained extension, such as `Measurement` for `Measurement`. +- Fixed invalid Swift when a protocol declared in an extension of another module's type has default implementations. +- Fixed `swift-section objc` losing the properties, protocols or methods of some classes in dyld shared caches. +- Fixed slow `GenericSpecializer.makeRequest` and `TypeDefinition.specialize(...)` calls from an actor. +- Fixed a possible crash when several inputs of `diff` or `evolution` first read the same dyld shared cache at once. diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 853cb5847..59464dc18 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -2494,6 +2494,24 @@ - **关联文档**:review 记录;[ReviewAdjudications.md](ReviewAdjudications.md) A53–A59;四份提案的决策日志([并发打印](../Evolutions/0066-concurrent-definition-printing.md)、[离线特化](../Evolutions/0069-offline-generic-specialization.md)、[嵌套定义区域](../Evolutions/0068-nested-definition-regions.md)、[嵌套偏移记忆化](../Evolutions/0067-nested-field-offset-memoization.md));[OfflineGenericSpecialization.md](OfflineGenericSpecialization.md)、[OpaqueReturnTypeResolution.md](OpaqueReturnTypeResolution.md)、[Modules/SwiftThunkAnalysis.md](Modules/SwiftThunkAnalysis.md)、[Modules/MachODependencies.md](Modules/MachODependencies.md)。 - **对应版本**:0.23.0,随 PR #131 合入。 +## 98. 0.23.0 发版 + +- **时间段**:2026-10-15(单日)。 +- **动机**:用户指示「next 合并到 main 发新版本」。自 0.22.0 以来 `next` 多了 53 个提交,即第 87–97 节的工作。`next` 已经在用两个上游未发版的接口(swift-demangling 的 `DemangleOptions.useModuleSelectors`、swift-semantic-string 的 `DefinitionRegion`),按远端依赖编不过,所以先给两个上游发版。用户还问起 MachOObjCSection 那个 sub-cache 的修复是不是合了上游:查下来 0.8.111 只手工移植了上游 `10b3dd5`,上游 8 月就发了的 0.8.2(PR #37)没合,同 PR 的 `ff936fa`(同一镜像挂的多张列表全部读入)也没带上。用户定合上游并发 0.8.200。 +- **关键决策**: + - **① 三个上游先发版。** swift-demangling 0.7.2:0.7.1 之后只新增了接口(`useModuleSelectors`、两个 `firstNodeInDedupedPreorder`),照惯例以 `Merge branch 'next'` 合进 `main`,打空消息的注释 tag。swift-semantic-string 0.5.0:这个库以往每加一个功能升 minor;README 早已写好 Definition Regions,只把安装示例指向 0.5.0,以 `Merge: …` 合进 `main`,打带摘要的注释 tag。MachOObjCSection 0.8.200:合入上游 tag 0.8.2,`MachOFile+.swift` 整个保留 0.8.111 的移植版(fork 的 `_machO(at:)` 返回 `LocatedValue`,不是上游的元组,自动合入的上游写法编不过),依赖保留 MachOKit 0.54.101;新回归测试 `SameImageRelativeListsTests` 合并前两条都失败(`_UTCoreType` 只读出第一张表的 3 个方法),合并后通过。0.8.200 不符合它原来的 `0.8.1NN` 版本号形状,`release.yml` 的 tag 过滤与 `version-check.yml` 同步放宽为百位跟随合入的上游补丁号,见它的提案 0009 决策日志。 + - **② 废弃的读取接口推迟到 0.24.0 再删**(用户选择)。RuntimeViewer 的 `next` 已经迁完,MachOKitUI(`from: "0.19.0"`,会自动解析到 0.23.0)与 swift-decompiler(跟本库 `next`)还没迁。AGENTS.md、术语表、`ReadingContextAbstraction.md` 与文档索引改成 0.24.0,0057 的决策日志补记,Changelog 的 Breaking 写明新期限。 + - **③ 提案与本账本取号。** 随 PR #131 合入的四份提案取号 0066–0069、置为 Implemented;它们在本账本的五节补编为第 93–97 节,移到第 92 节之后;第 87–97 节的「对应版本」改为 0.23.0。 + - **④ Changelog 2,788 字符**,按 `write-release-notes` 一句话一条,超出普通版本 1,500 的预算:这一版有六条破坏性变化(局部类型改名、snapshot 格式 7、删 `TypeDefinition.attributes`、`SymbolicDemangler.isCacheEnabled` 改为常量、`OpaqueTypeResolving` 的新参数、废弃期限顺延)、离线特化与模块选择器等一批新接口,以及三个依赖下限变化。 + - **⑤ 不做发版审查与渲染 A/B**,沿用 0.22.0 的做法:各批合入时都跑过全量测试,涉及渲染的批次跑过 A/B;这次只在只含远端依赖的干净副本上重新验证。 + - **⑥ 版本号。** `Version.swift`、两个 `plugin.json` 改为 0.23.0,README 的安装示例同步;插件 skill 把 `interface --module-selectors`、`dump --enable-module-selectors` 与 snapshot 格式 7 标为 0.23.0 起。 +- **落地模块**:`Package.swift`(三个依赖下限)、`Sources/Executables/swift-section/Version.swift`、`AgentPlugins/swift-section/`(两个 `plugin.json`、skill)、`Changelogs/0.23.0.md`、`README.md`、四份提案与两个索引、本账本(第 93–97 节编号、第 87–97 节的对应版本、本节),以及 AGENTS.md、术语表、`ReadingContextAbstraction.md` 与 0057(废弃期限)。 +- **验证**: + - 本库:发版提交经 `git archive` 导出到外置卷上的干净副本,旁边没有兄弟依赖,新鲜 scratch,依赖全部从远端解析(MachOKit 0.54.101、MachOKitExtensions 1.2.0、MachOObjCSection 0.8.200、swift-demangling 0.7.2、swift-semantic-string 0.5.0、swift-capstone 6.0.1、swift-objc-dump 0.8.101),工具链 Xcode 26.6,fixture 用 Xcode 26.6 按 CI 的方式 ad-hoc 签名现编。全量 `swift test --skip IntegrationTests` 共 2442 个测试 / 468 个套件,原始退出码 1,失败的只有本机早已存在的两条 `MultiPayloadEnumDescriptorCacheTests`(`:101` 与 `:130` 的 `enumLayout → nil`,与第 90–92 节相同)。照 `release.yml` 分架构做的 release 构建(`swift-section`)x86_64 与 arm64 都是 0 warning,两个二进制都能运行、`--version` 输出 0.23.0;skill 写到的 55 个 flag 在各子命令的 `--help` 里都找得到。`claude plugin validate`(marketplace 加 `--strict`)通过。 + - 上游:swift-demangling `next` 624 个测试 / 43 个套件、swift-semantic-string `next` 432 个测试 / 60 个套件,原始退出码都是 0。MachOObjCSection 合并后按 CI 的方式(`--skip MachOObjCSectionTests`)173 个测试 / 24 个套件通过,推上 `main` 后 CI 与 Version Check 通过,0.8.200 的 Release 流程按放宽后的 tag 过滤触发并发布了 `objc-section-macos-universal.zip`。上游 PR 自带的 XCTest 在 `MachOObjCSectionTests` 里,它的 `setUp` 读本机不存在的 `~/Downloads/iOS18.5-SwiftUI`,在这台机器上跑不起来(CI 也跳过这个目标),同一行为由 `SameImageRelativeListsTests` 覆盖。 +- **关联文档**:[Changelogs/0.23.0.md](../../Changelogs/0.23.0.md);MachOObjCSection 的[实现说明](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/0.8.200/Documentations/Internal/RelativeListsAcrossSubCacheFiles.md)。 +- **对应版本**:0.23.0。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/README.md b/README.md index f8dc0d408..b38d469b8 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Add the package to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.22.0"), + .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.23.0"), ], targets: [ .target( diff --git a/Sources/Executables/swift-section/Version.swift b/Sources/Executables/swift-section/Version.swift index cef965f52..0d9f1af2e 100644 --- a/Sources/Executables/swift-section/Version.swift +++ b/Sources/Executables/swift-section/Version.swift @@ -4,5 +4,5 @@ // release with the same string. // Verified by .github/workflows/version-check.yml (PR) and .github/workflows/release.yml (tag). enum BundledVersion { - static let value = "0.22.0" + static let value = "0.23.0" }