From ff03a100449e653b977005cb0ef2d67b1f9c588e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:08:23 +0800 Subject: [PATCH 001/175] docs: propose the Tuist development workspace Accepted draft-tuist-workspace: a development-only MachOSwiftSection-Tuist workspace generated by TuistScript.sh, with third-party dependencies from Tuist's binary cache, the five upstream packages switchable to their local checkouts, and the packages' tests mapped through an env-gated manifest block. Implementation follows on feature/tuist-workspace. --- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-tuist-workspace.html | 867 ++++++++++++++++++ .../Evolutions/draft-tuist-workspace.md | 583 ++++++++++++ 3 files changed, 1451 insertions(+) create mode 100644 Documentations/Evolutions/draft-tuist-workspace.html create mode 100644 Documentations/Evolutions/draft-tuist-workspace.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 8009ed18..8d9e0600 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -113,3 +113,4 @@ | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | | [cross-repository MachOKitExtensions 0004](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md) | 符号语言的判断归各自的包:由那边维护唯一提案;本库在 `SwiftSymbols` 定义 `SymbolLanguage.swift` 与 Swift 名字的判断,新 C target `SwiftSymbolsRegistration` 在镜像加载时注册;MachOKitExtensions 下限抬到 3.0.0 | Implemented | +| draft | [Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出](draft-tuist-workspace.md) | Accepted | diff --git a/Documentations/Evolutions/draft-tuist-workspace.html b/Documentations/Evolutions/draft-tuist-workspace.html new file mode 100644 index 00000000..43c7e005 --- /dev/null +++ b/Documentations/Evolutions/draft-tuist-workspace.html @@ -0,0 +1,867 @@ + + + + + + +Draft - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 + + + + +
+ +
+

MachOSwiftSectionEvolutionsDraft

+

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

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

摘要

+

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

+

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

+
+ +
+

要你定

+
+

已定:本地模式下的测试

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

动机

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

提议方案

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

非目标

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

架构图

+

改了什么

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

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

+ +

生成出的 workspace 里有什么

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

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

+ +

一条命令怎么走

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

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

+ +

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

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

改动地图

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

详细设计

+
+ Package.swift 的适配块(本库与三个上游库原样共用) +
+

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

+
// The Tuist development workspace (MachOSwiftSection's Documentations/Internal/TuistDevelopment.md)
+// maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends
+// on an executable target, and a test that depends on a target no product contains. Only while Tuist
+// resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the
+// second kind gets a library product of its own. Nothing changes without the variable.
+if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" {
+    let executableTargetNames = Set(package.targets.filter { $0.type == .executable }.map(\.name))
+    func dependencyName(_ dependency: Target.Dependency) -> String? {
+        switch dependency {
+        case .targetItem(let name, _), .byNameItem(let name, _):
+            return name
+        default:
+            return nil
+        }
+    }
+    package.targets.removeAll { target in
+        target.type == .test && target.dependencies.contains { dependency in
+            dependencyName(dependency).map(executableTargetNames.contains) ?? false
+        }
+    }
+    let productTargetNames = Set(package.products.flatMap { product in (product as? Product.Library)?.targets ?? [] })
+    let testDependencyNames = Set(package.targets.filter { $0.type == .test }.flatMap { $0.dependencies.compactMap(dependencyName) })
+    package.products += package.targets
+        .filter { target in target.type == .regular && testDependencyNames.contains(target.name) && !productTargetNames.contains(target.name) }
+        .map { target in Product.library(name: target.name, targets: [target.name]) }
+}
+
    +
  • 本库:摘掉 SwiftSectionCommandTests,给 SwiftSectionFixtureSupport、SwiftSectionTestingSupport(以及测试直接依赖的其余普通 target)补 product。MachOObjCSection:摘掉 ObjCSectionCommandTests。MachOKitExtensions 与 swift-demangling:补 CPlusPlusSymbolsFixture、DemanglingTestingSupport 的 product。
  • +
  • 被摘掉的测试照旧用 swift test --filter 跑;本库的 SwiftSectionCommandTests 例外,它在 Tuist/CommandLine/Project.swift 里手写。ObjCSectionCommandTests 不手写:那要在本库描述另一个仓库的 target。
  • +
  • 只看 target 依赖(targetItem / byNameItem),不看 productItem:依赖别的包的可执行 product 的测试,Tuist 怎么处理没有实测,四个包里也没有。
  • +
+
+
+
+ Tuist/Package.swift +
+
// swift-tools-version: 6.2
+import Foundation
+import PackageDescription
+
+// The dependencies of MachOSwiftSection-Tuist.xcworkspace (Documentations/Internal/TuistDevelopment.md).
+// This package is declared by path, so its Package.swift stays the only definition of its targets.
+// In the local dependency mode TuistScript.sh names the upstream packages in TUIST_LOCAL_PACKAGE_NAMES
+// and their directory in TUIST_LOCAL_PACKAGE_CHECKOUTS; a root's path dependency stands in for every
+// declaration of the same package in the graph.
+let processEnvironment = ProcessInfo.processInfo.environment
+let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? ""
+let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "").split(separator: ",").map(String.init)
+let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty
+    ? []
+    : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") }
+
+#if TUIST
+    import ProjectDescription
+
+    func names(_ variable: String) -> [String] {
+        (processEnvironment[variable] ?? "").split(separator: ",").map(String.init)
+    }
+
+    // Tuist suppresses warnings in every package; Xcode does so for remote packages only.
+    let warningSettings: [String: Settings] = Dictionary(
+        names("TUIST_WARNING_TARGET_NAMES").map { targetName in
+            (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"]))
+        },
+        uniquingKeysWith: { first, _ in first }
+    )
+
+    // Tuist drops a setting whose only condition is a trait; this package enables swift-capstone's
+    // AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 that way.
+    let restatedTraitDefinitions: [String: Settings] = [
+        "Capstone": .settings(base: [
+            "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"],
+            "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"],
+        ]),
+        "Ccapstone": .settings(base: [
+            "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"],
+        ]),
+    ]
+
+    // Filled in by step 2 once the tests have been built: the deployment target SwiftPM gives a test
+    // target (macOS 14.0) and -ObjC, each only if the build shows it is needed.
+    let testTargetSettings: [String: Settings] = [:]
+
+    let packageSettings = PackageSettings(
+        targetSettings: warningSettings
+            .merging(restatedTraitDefinitions) { $1 }
+            .merging(testTargetSettings) { $1 },
+        includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1"
+    )
+#endif
+
+let package = Package(
+    name: "MachOSwiftSectionTuistDependencies",
+    dependencies: [
+        .package(path: ".."),
+        // Stands in for swift-syntax everywhere, as it does as a member of the native workspace.
+        .package(path: "../PrecompiledLibraries/swift-syntax"),
+        // Used only by tests, which Tuist needs declared here (MachOSwiftSection's requirement).
+        .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"),
+    ] + localPackageDependencies
+)
+
    +
  • 根包的路径依赖 .. 的身份是目录名:worktree 叫 MachOSwiftSection-<用途> 时身份就变了,而上游库的清单不按 URL 引用本库,所以不受影响;生成的工程名取自 Package(name:),仍是 MachOSwiftSection.xcodeproj。
  • +
  • TUIST_WARNING_TARGET_NAMES 是本库全部 target,本地模式下再加五个上游库的全部 target(与原生 workspace 一致:Xcode 只给远程包关警告)。
  • +
+
+
+
+ Tuist/CommandLine/Project.swift +
+
import ProjectDescription
+
+// What Tuist cannot convert from ../../Package.swift: the swift-section executable, and
+// SwiftSectionCommandTests, which imports the executable's module. swift_section compiles the same
+// sources as a static framework for that test; the tool compiles them again, so its link needs no
+// trick around the @main entry point. The dependency list mirrors Package.swift's swift-section
+// target and is the one hand-written copy in the Tuist description.
+let commandLineDependencies: [TargetDependency] = [
+    .external(name: "SwiftSectionKit"),
+    .external(name: "MachOFoundation"),
+    .external(name: "SwiftSymbols"),
+    .external(name: "SwiftDump"),
+    .external(name: "SwiftOutputTransformer"),
+    .external(name: "SwiftDeclaration"),
+    .external(name: "SwiftIndexing"),
+    .external(name: "Semantic"),
+    .external(name: "OutputTransformer"),
+    .external(name: "ObjCDeclarationRendering"),
+    .external(name: "ObjCOutputTransformer"),
+    .external(name: "Rainbow"),
+    .external(name: "ArgumentParser"),
+]
+
+let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"]
+
+// MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets;
+// TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read.
+let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: false)
+    ? .settings(base: ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]])
+    : .settings()
+
+let project = Project(
+    name: "MachOSwiftSectionCommandLine",
+    targets: [
+        .target(
+            name: "swift-section",
+            destinations: .macOS,
+            product: .commandLineTool,
+            bundleId: "com.machoswiftsection.swift-section",
+            deploymentTargets: .macOS("10.15"),
+            sources: commandLineSources,
+            dependencies: commandLineDependencies
+        ),
+        .target(
+            name: "swift_section",
+            destinations: .macOS,
+            product: .staticFramework,
+            bundleId: "com.machoswiftsection.swift-section.module",
+            deploymentTargets: .macOS("10.15"),
+            sources: commandLineSources,
+            dependencies: commandLineDependencies
+        ),
+        .target(
+            name: "SwiftSectionCommandTests",
+            destinations: .macOS,
+            product: .unitTests,
+            bundleId: "com.machoswiftsection.SwiftSectionCommandTests",
+            deploymentTargets: .macOS("14.0"),
+            sources: ["../../Tests/SwiftSectionCommandTests/**"],
+            dependencies: [
+                .target(name: "swift_section"),
+                .external(name: "SwiftDeclarationRendering"),
+                .external(name: "SwiftPrinting"),
+            ] + commandLineDependencies,
+            settings: commandTestSettings
+        ),
+    ]
+)
+
    +
  • CLI 的源码编两遍(tool 一遍、framework 一遍)。另一种写法是 tool 不带源码、只链 framework,靠链接器从静态库里取 _main;省一遍编译,但没实测,放进「替代方案」。
  • +
  • MACHO_SWIFT_SECTION_SILENT_TEST=1 在 Package.swift 里变成测试 target 的 SILENT_TEST 定义:tuist install 时设了它,转换出的测试就带上。手写的 SwiftSectionCommandTests 也要带:Tuist 的 manifest 只读得到 TUIST_ 开头的变量,所以脚本把它转成 TUIST_SILENT_TEST=1,Project.swift 据此给这个 target 加 SILENT_TEST。
  • +
+
+
+
+ Workspace.swift +
+
import ProjectDescription
+
+// "<package directory>=<test target>,<test target>;…" from TuistScript.sh, one entry per package whose
+// tests are mapped: this package always (directory "."), the upstream packages in the local mode.
+// IntegrationTests is never listed.
+let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets
+    .getString(default: "")
+    .split(separator: ";")
+    .compactMap { entry in
+        let parts = entry.split(separator: "=", maxSplits: 1).map(String.init)
+        guard parts.count == 2 else { return nil }
+        return (parts[0], parts[1].split(separator: ",").map(String.init))
+    }
+
+let workspace = Workspace(
+    name: "MachOSwiftSection-Tuist",
+    projects: ["Tuist/CommandLine"],
+    schemes: packageTestTargets.map { entry in
+        let packageName = entry.directory == "." ? "MachOSwiftSection" : (entry.directory as NSString).lastPathComponent
+        var testableTargets = entry.targets.map { targetName in
+            TestableTarget.testableTarget(target: .project(path: Path(entry.directory), target: targetName))
+        }
+        if entry.directory == "." {
+            testableTargets.append(.testableTarget(target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests")))
+        }
+        return .scheme(name: "\(packageName) Tests", testAction: .targets(testableTargets))
+    }
+)
+
    +
  • 上游库的目录是绝对路径;Path 接受绝对路径字符串,第 3 步验证。Workspace.swift 能否 import Foundation 用 NSString 没验证,不行就自己切最后一段。
  • +
  • 测试映射被预检关掉时 TUIST_PACKAGE_TEST_TARGETS 为空,只剩各 target 自己的 scheme;SwiftSectionCommandTests 仍在 MachOSwiftSectionCommandLine 工程里,Tuist 自动生成的 scheme 能跑它。
  • +
+
+
+
+ Tuist.swift +
+
import ProjectDescription
+
+// Every target of MachOSwiftSection and of the five upstream packages stays source, in both dependency
+// modes; every other dependency comes out of the binary cache once warmed. TuistScript.sh reads the
+// names from the packages' manifests. No fullHandle: the cache stays on this machine.
+let sourceTargetNames = Environment.sourceTargetNames
+    .getString(default: "")
+    .split(separator: ",")
+    .map(String.init)
+
+let tuist = Tuist(
+    project: .tuist(
+        cacheOptions: .options(
+            profiles: .profiles(
+                ["development": .profile(.onlyExternal, except: sourceTargetNames.map { .named($0) })],
+                default: "development"
+            )
+        )
+    )
+)
+
    +
  • 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库,第 4 步量出来后若差得多再议。
  • +
  • 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。
  • +
+
+
+
+ TuistScript.sh:命令、环境变量、名单、预检、锁文件、模式、存放位置、占用记录 +
+

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

+

命令

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

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

+

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

+
+ + + + + + + + + + + +
变量谁读内容
TUIST_MAPS_LOCAL_PACKAGE_TESTS四个包的 Package.swift,Tuist/Package.swift1:映射测试;预检不通过时 0
TUIST_LOCAL_PACKAGE_CHECKOUTS、TUIST_LOCAL_PACKAGE_NAMESTuist/Package.swift本地模式下上游库所在目录与名字;远程模式不设
TUIST_SOURCE_TARGET_NAMESTuist.swift本库与五个上游库的全部 target
TUIST_WARNING_TARGET_NAMESTuist/Package.swift恢复警告的 target:本库全部,本地模式再加上游库全部
TUIST_PACKAGE_TEST_TARGETSWorkspace.swift每个映射了测试的包的测试 target,不含 IntegrationTests
TUIST_SILENT_TESTTuist/CommandLine/Project.swift用户设了 MACHO_SWIFT_SECTION_SILENT_TEST=1 时为 1
SWIFTPM_BUILD_DIRTuist当前模式的依赖 checkout 目录
TUIST_XDG_CACHE_HOME、TUIST_CACHE_WARM_SCRATCH_DIRECTORYTuist二进制缓存与预热的临时目录
+

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

+

名单从哪来

+

本地依赖的名字读 MachOSwiftSection.xcworkspace/contents.xcworkspacedata 里的 container:../<名字>(不含 / 的那些),workspace 加了库这里自动跟上。target 名单用 swift package dump-package(带 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1,--scratch-path 放在 Work/<checkout>/Manifests/)读六个包的清单:本库与本地模式下的上游库读检出里的,远程模式下的上游库读 install 之后 SWIFTPM_BUILD_DIR/checkouts/<名字> 里的。远程模式下第一次 install 之前还没有 checkout,先用空名单装一次再算。

+

测试映射的预检

+

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

+

锁文件

+

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

+

依赖模式

+

模式记在 Tuist/.local-dependencies(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 .worktrees/;打开本地模式时设了 TUIST_LOCAL_PACKAGE_CHECKOUTS 就用它。两种模式各用一份依赖 checkout,共用 Tuist/Package.resolved,所以切换后、或上次解析用的是另一种模式时先重新 install。切到远程时释放五个上游库的占用。

+

存放位置

+

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

+

占用记录(与 RuntimeViewer 共用)

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

Tuist 版本与 agent 运行

+

读 mise.toml 的版本;有 mise 就 mise exec -- tuist,否则用 PATH 里的 tuist;版本不对就失败并提示 mise install。agent 运行时设 TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex/<agent>/Tuist-MachOSwiftSection,并写成 queued-build ./TuistScript.sh <命令>。

+
+
+
+ RuntimeViewer 那一侧 +
+
    +
  • claim_local_checkouts:先读共用记录与旧记录,任何一个有效且占用者不是自己就失败,报出占用者与释放命令;然后写共用记录(第二行是 ./TuistScript.sh generate --remote-dependencies),把路径写进自己的 Tuist/.claimed-checkouts,自己的旧记录删掉。
  • +
  • release_local_checkouts:删掉自己的共用记录(以及残留的旧记录),从 .claimed-checkouts 里去掉。
  • +
  • 今天它占着本库的集成 worktree 与五个上游检出(旧记录)。改完后它下一次 generate 就把记录换成新的;在那之前,本库的脚本按旧规则认出它的占用。
  • +
+
+
+
+ 已知要在实现中确认的点 +
+
    +
  1. swift_section 与 SwiftSectionCommandTests 能编、能链、@testable import 成立(第 2 步)。
  2. +
  3. 本库测试在 Tuist workspace 里要不要抬部署版本到 14.0、要不要 -ObjC(第 2 步,只加确实需要的)。
  4. +
  5. Capstone 的 trait 宏补上后 SwiftThunkAnalysis 能编(第 1 步)。
  6. +
  7. Workspace.swift 里按绝对路径引用上游库工程(第 3 步)。
  8. +
  9. 远程与本地两种模式下,Tuist workspace 跑出的测试数与 swift test --skip IntegrationTests 一致,失败的与原生路径相同(第 2、3 步,在 Ultra 上)。
  10. +
+
+
+
+ +
+

调研

+
+ 现状 +
+
    +
  • 原生 workspace 的成员:container:../MachOKit、container:../MachOObjCSection、group:(本库)、group:PrecompiledLibraries/swift-syntax。集成 worktree 里还有一处没提交的改动,又加了 container:../MachOKitExtensions、container:../swift-demangling、container:../swift-semantic-string。「本地依赖」指的就是这五个成员。
  • +
  • PrecompiledLibraries/swift-syntax 是一个按包身份顶替 swift-syntax 的包,每个 product 是一个 binaryTarget(PrecompiledLibraries/swift-syntax/Package.swift:46 起)。Tuist 这边要在 Tuist/Package.swift 里按路径声明它,两种模式都声明。
  • +
  • 本库 Package.swift 的本地依赖开关:usingLocalDependencies = envEnable("USING_LOCAL_DEPENDENCIES")(Package.swift:42);package(local:remote:) 在 #filePath 含 /checkouts/、/SourcePackages/ 或 /.build/ 时一律走远程(Package.swift:49-74)。
  • +
  • 可执行 target 与测试:swift-section、reader-benchmark、baseline-generator(Package.swift:929、956、972),命令插件 RegenerateBaselinesPlugin(Package.swift:987),22 个测试 target。SwiftSectionCommandTests(Package.swift:1305)依赖 swift-section,测试文件里是 @testable import swift_section(13 个文件),不启动子进程。SwiftSectionFixtureSupport、SwiftSectionTestingSupport、SwiftSectionTestingSupportC 不属于任何 product。
  • +
  • 没有提交的锁文件:.gitignore 有 *.resolved。
  • +
  • RuntimeViewer 的做法:Tuist/Package.swift 按路径声明四个本地包;缓存 profile 按名字把本地包与 MachO 那几个库的 target 留作源码;本地依赖模式记在 Tuist/.local-dependencies,两种模式各用一份 SWIFTPM_BUILD_DIR;占用记录写在被占检出的 git 目录里,有效与否看占用者的 Tuist/.local-dependencies;切回远程时删掉生成进库目录的工程;Tuist 生成的文件经 info/exclude 忽略。它的本地模式不映射测试,原因正是实测第 1 条与第 6 条。它钉的 Tuist 是 4.210.0。
  • +
+
+
+
+ 实测(2026-11-20,JH's Mac Studio,Xcode 27.2,Tuist 4.210.0),十条 +
+

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

+
    +
  1. 远程模式、打开 includeLocalPackageTestTargets:生成失败,SwiftSectionCommandTests 依赖可执行 target swift-section。这个选项对所有按路径声明的包一视同仁,没有按 target 排除的参数。
  2. +
  3. 用环境变量在 Package.swift 里摘掉它:开关生效(tuist install 的环境传得进依赖清单)。下一个错误:SwiftDumpTests 依赖的 SnapshotTesting 没在 Tuist/Package.swift 里声明。
  4. +
  5. 补上 swift-snapshot-testing:Couldn't find target 'SwiftSectionFixtureSupport'。
  6. +
  7. 给测试依赖的普通 target 补 library product:生成成功,48 个 target,其中 21 个测试 target(含 IntegrationTests)。原生 workspace 没被碰。
  8. +
  9. 在 Tuist 工程里手写 CLI 的三个 target:生成成功,放在 Tuist/CommandLine/ 下也行。没编译。
  10. +
  11. 本地模式:生成失败,MachOObjCSection 的 ObjCSectionCommandTests 依赖可执行 target objc-section。Tuist 4.218.1 同样失败。
  12. +
  13. 五个上游库副本都加通用适配:生成成功,本库 21、MachOKit 1、MachOKitExtensions 9、MachOObjCSection 8、swift-demangling 1、swift-semantic-string 2 个测试 target。逐个去掉后:MachOKit 与 swift-semantic-string 不加也能过;swift-demangling 不加时 DemanglingTestingSupport 找不到。最少改三个上游库。
  14. +
  15. 生成的工程写进各包自己的目录,本库副本根目录也是——这就是与 RuntimeViewer 冲突的地方。
  16. +
  17. Tuist.swift 能读环境变量:tuist dump config 显示 exceptTargetQueries 正是传入的名字。
  18. +
  19. 远程依赖清单:AssociatedObject、capstone、combine-schedulers、FrameworkToolbox、MetaCodable、Rainbow、SourceKitD、swift-apinotes、swift-argument-parser、swift-asn1、swift-async-algorithms、swift-binary-parse-support、swift-capstone、swift-clocks、swift-collections、swift-concurrency-extras、swift-crypto、swift-dependencies、swift-fileio、swift-fileio-extra、swift-issue-reporting、swift-literal-type-inference、swift-memberwise-init-macro、swift-object-association、swift-objc-dump、swift-snapshot-testing、Yams,加上五个上游库。
  20. +
+
+
+
+ 推测(未验证,落地步骤里验证) +
+
    +
  • 测试 target 的部署版本:SwiftPM 给测试 target 的部署版本不低于 macOS 14.0,Tuist 照搬包声明的 10.15,RuntimeViewer 因此编不过。本库测试大概率踩同一个坑。
  • +
  • -ObjC:Tuist 把包编成静态库,链接器只拉被符号引用到的成员。本库测试是否依赖按名字在运行时查找的类,没查过。
  • +
  • CAPSTONE_HAS_AARCH64:本库开了 swift-capstone 的 AARCH64 trait(Package.swift:291),Tuist 会丢掉只以 trait 为条件的设置。
  • +
  • swift_section 里有 @main,链进测试 bundle 后会多出一个 _main 符号;bundle 不是可执行文件,这应该无害。
  • +
+
+
+
+ +
+

替代方案

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

影响

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

落地步骤

+

在 Ultra 上构建与跑测试,用默认的 Xcode 27.2;第 2、3 步的测试结果另用 Xcode 26.6 的 swift test 结果对照。

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

收尾时判断:实现说明是否另写;「Tuist 开发 workspace」「本地依赖模式」「占用记录」是否进术语表。

+
+ +
+

决策日志

+
+ 4 条,最近一条:用户批准,开始实现 +
+
+ + + + + + + + +
日期变更说明
2026-11-20Created as Draft用户要一个照 RuntimeViewer 做法建的 Tuist 开发 workspace,依赖可在本地检出与远程版本之间切换,本地依赖就是原生 workspace 里放的那几个上游库。按轻量档处理:新增的开发路径,不改原有的构建、发版与 CI。
2026-11-20定下三个方向用户选定:提供二进制缓存与 warm;Tuist workspace 要能跑测试,先实测再定写法;与 RuntimeViewer 的本地依赖模式双向互斥,为此顺带改 RuntimeViewer 的脚本。
2026-11-20实测定下测试的写法Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;SwiftSectionCommandTests 手写。三个上游库要不要加,留给用户定。
2026-11-20用户批准,开始实现用户选定给 MachOKitExtensions、MachOObjCSection、swift-demangling 加适配块,本地模式带测试;状态改 Accepted。实现在本库的 feature/tuist-workspace,三个上游库与 RuntimeViewer 各用同名分支。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/draft-tuist-workspace.md new file mode 100644 index 00000000..477a4a2e --- /dev/null +++ b/Documentations/Evolutions/draft-tuist-workspace.md @@ -0,0 +1,583 @@ +# Draft - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: RuntimeViewer 仓库的 `Documentations/Evolutions/0053-tuist-coexistence.md`(Tuist workspace 与原生工程并存)与 `0082-tuist-local-dependencies.md`(本地依赖模式)。本提案的脚本照它们的做法写,并顺带改 RuntimeViewer 脚本里的占用检查,让两边的本地依赖模式互斥(落地步骤第 5 步)。 +- **跨仓库**: 本提案是唯一的一份。另外四个仓库只有配套小改动:MachOKitExtensions、MachOObjCSection、swift-demangling 的 `Package.swift` 末尾各加同一段适配(第 3 步),RuntimeViewer 改 `TuistScript.sh` 与它的使用指南(第 5 步)。它们的提交信息按 slug 指回本提案,各自的文档按各仓库自己的规定同步。 +- **实现分支 / PR**: 本库 `feature/tuist-workspace`,从 `next` 切出;另外四个仓库用同名分支,从各自的集成分支切出(MachOKitExtensions 是 `main`,其余是 `next`)。 +- **配套文档**: 使用指南 [`Documentations/Internal/TuistDevelopment.md`](../Internal/TuistDevelopment.md)(第 6 步新增) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +在原生的 `MachOSwiftSection.xcworkspace` 之外,加一条只供日常开发用的 Tuist 路:`./TuistScript.sh` 生成 `MachOSwiftSection-Tuist.xcworkspace`。本库照常从源码编,可以跳转、可以编辑;27 个真正的第三方依赖(swift-dependencies 一族、swift-collections、Capstone、swift-crypto、Yams……)预编进本机的 Tuist 二进制缓存,只编一次。原生 workspace 里放的五个上游库——MachOKit、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string——默认按锁文件版本从源码编;加上 `--local-dependencies` 就改用检出旁边(worktree 里就是 `.worktrees/` 下那组链接)的本地检出,没提交的改动也算,`--remote-dependencies` 切回,选过的模式会记住。Tuist workspace 能跑测试:本库 21 个测试 target 由 Tuist 从 `Package.swift` 转换过来,依赖可执行 target 的 `SwiftSectionCommandTests` 在一个小的 Tuist 工程里手写;本地模式下五个上游库的测试也一起进来。做到这一点要在本库和三个上游库的 `Package.swift` 末尾加同一段适配,它只在 Tuist 解析时设下的环境变量下生效,平时的 SwiftPM、Xcode 与 CI 一律不受影响。RuntimeViewer 的本地依赖模式也会往这几个检出里写同名工程,两边的脚本改成共用一份占用记录,一边占着时另一边直接报错。发版、CI、`swift build` / `swift test` 和原生 workspace 都不变。 + +## 动机 + +- **第三方依赖在每个干净的 DerivedData 里都要重编一遍。** 本库的依赖闭包里有 27 个与本仓库开发无关的包(`tuist install` 实测解析出的清单见「前期调研」):Capstone 的 C 库、swift-crypto、swift-collections、pointfree 的 swift-dependencies 一族、MetaCodable 与 MemberwiseInit 两个宏包、Yams、SourceKitD、swift-apinotes……原生 workspace 走 Xcode 自带的 SwiftPM 集成,每换一个 DerivedData(新 worktree、清缓存、换 Xcode)就全部从源码编一次。Tuist 的二进制缓存按内容寻址,同一台机器、同一个 Xcode 下只编一次。RuntimeViewer 用同样的做法量过:完整 App 从空 DerivedData 构建,不用缓存 504 秒,走缓存 155 秒。本库的数字还没量,第 4 步量。 +- **原生 workspace 切换本地上游库的方式太粗。** 今天的切换靠 `USING_LOCAL_DEPENDENCIES=1` 加兄弟目录是否存在(`Package.swift:42` 起的 `package(local:remote:)`):这个变量要进到 Xcode 的启动环境里才生效;对所有声明了本地路径的依赖一刀切,连 workspace 里没有列出的 swift-capstone(`Package.swift:275`,`../swift-capstone` 在 `.worktrees/` 下有链接)也会被换成本地;切换后要等 Xcode 重新解析。Tuist 这边由 `Tuist/Package.swift` 按路径逐个声明要本地化的库,SwiftPM 让根包的路径依赖顶替图里所有同名声明,名单就是 workspace 的成员,切换只发生在命令行上。 +- **RuntimeViewer 的本地依赖模式已经在往本仓库的检出里写工程,而没有任何东西拦着另一方。** 它在每个按路径声明的包目录里生成 `<包名>.xcodeproj` 与 `Derived/`。2026-11-20 实测:RuntimeViewer 的集成 worktree 正占着本库的集成 worktree(本 worktree 的 git 目录里 `runtimeviewer-tuist-local-dependencies` 记着 `/Volumes/Repositories/Private/Org/MxIris-Reverse-Engineering/RuntimeViewer/.worktrees/RuntimeViewer`),本 worktree 根目录那份被忽略的 `MachOSwiftSection.xcodeproj` 就是它生成的。本库自己的 Tuist 也会在同一位置生成同名工程,两边的 `PackageSettings` 不同(配置名、警告、测试映射),谁后生成谁就让另一边的 workspace 坏掉。 + +## 前期调研 + +### 现状 + +- **原生 workspace 的成员**(`MachOSwiftSection.xcworkspace/contents.xcworkspacedata`):`container:../MachOKit`、`container:../MachOObjCSection`、`group:`(本库)、`group:PrecompiledLibraries/swift-syntax`。集成 worktree 里还有一处没提交的改动,又加了 `container:../MachOKitExtensions`、`container:../swift-demangling`、`container:../swift-semantic-string`。「本地依赖」指的就是这五个 `container:../<名字>` 成员。 +- **`PrecompiledLibraries/swift-syntax`** 是一个按包身份顶替 swift-syntax 的包,每个 product 是一个 `binaryTarget`(`PrecompiledLibraries/swift-syntax/Package.swift:46` 起,xcframework 从 `MxIris-DeveloperTool/swift-syntax-builder` 的 release 下载)。原生 workspace 靠把它列为成员来顶替;Tuist 这边要在 `Tuist/Package.swift` 里按路径声明它,两种模式都声明。 +- **本库 `Package.swift` 的本地依赖开关**:`usingLocalDependencies = envEnable("USING_LOCAL_DEPENDENCIES")`(`Package.swift:42`);`package(local:remote:)` 在 `#filePath` 含 `/checkouts/`、`/SourcePackages/` 或 `/.build/` 时一律走远程(`Package.swift:49-74`),所以作为别人的远程依赖时不受这个变量影响。 +- **可执行 target 与测试**:`swift-section`、`reader-benchmark`、`baseline-generator` 三个可执行 target(`Package.swift:929`、`956`、`972`),一个命令插件 `RegenerateBaselinesPlugin`(`Package.swift:987`),22 个测试 target。`SwiftSectionCommandTests`(`Package.swift:1305`)依赖 `swift-section`,测试文件里是 `@testable import swift_section`(13 个文件),不启动子进程。`SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`、`SwiftSectionTestingSupportC` 是普通 target,不属于任何 product(`Package.swift` 的 `products:` 只有 20 个库与 `swift-section`)。 +- **没有提交的锁文件**:`.gitignore` 有 `*.resolved`,根目录的 `Package.resolved` 是每台机器、每个检出自己解析出来的。 +- **RuntimeViewer 的做法**(`RuntimeViewer/TuistScript.sh`,1774 行;`Documentations/Guides/TuistDevelopment.md`):`Tuist/Package.swift` 按路径声明四个本地包;`Tuist.swift` 的缓存 profile `development` 用 `.onlyExternal`,按名字把本地包与 MachO 那几个库的 target 留作源码;本地依赖模式在 `Tuist/.local-dependencies` 记住目录,两种模式各用一份 `SWIFTPM_BUILD_DIR`;占用记录写在被占检出的 git 目录里(`runtimeviewer-tuist-local-dependencies`,内容是占用者的路径),判断占用是否仍然有效的办法是看占用者的 `Tuist/.local-dependencies` 是否指向这个目录;切回远程时删掉生成进库目录的工程;Tuist 生成的文件经被占仓库的 `info/exclude` 忽略。它的本地模式不映射测试,原因正是下面的第 1 条与第 6 条。RuntimeViewer 钉的 Tuist 是 4.210.0(`mise.toml`),它记下的 Tuist 4.210 的坑(`${inherited}`、`-ObjC`、测试 target 部署版本、trait 宏、`--cache-profile`)大部分只与 App 工程有关,与本提案相关的三条在「详细设计」里逐条说明。 + +### 实测(2026-11-20,JH's Mac Studio,Xcode 27.2,Tuist 4.210.0) + +探针放在 `/Volumes/DerivedData/Agents.noindex/claude/Probes/MachOSwiftSection-Tuist/`:本库 `next` 与五个上游库集成分支的 HEAD 用 `git archive` 导出成副本,`Tuist/Package.swift` 按路径声明本库副本与预编译 swift-syntax,`Tuist/CommandLine/Project.swift` 放 CLI。只跑了 `tuist install` 与 `tuist generate`,没有编译。没碰任何真实检出。 + +1. **远程模式、打开 `includeLocalPackageTestTargets`**:生成失败。`The test target 'SwiftSectionCommandTests' in the local package 'MachOSwiftSection' depends on the executable target 'swift-section', which Tuist omits when mapping local package dependencies.` 这个选项对所有按路径声明的包一视同仁,没有按 target 排除的参数(`PackageSettings.init` 只有 `includeLocalPackageTestTargets: Bool`,见 Tuist 4.218.1 的 `ProjectDescription.swiftinterface`)。 +2. **用环境变量在 `Package.swift` 里摘掉 `SwiftSectionCommandTests`**:开关生效(`tuist install` 的环境能传进依赖清单的 `Context.environment`,而 Tuist 在 install 时就把清单解析结果缓存下来)。下一个错误:`The local package test target 'SwiftDumpTests' depends on 'SnapshotTesting', which is not a configured external dependency.` 只被测试用到的依赖必须在 `Tuist/Package.swift` 里声明。 +3. **补上 swift-snapshot-testing**:`Couldn't find target 'SwiftSectionFixtureSupport'`。测试依赖的普通 target 不属于任何 product 时,Tuist 找不到它。 +4. **同一开关下给测试依赖的普通 target 补 library product**:生成成功。`MachOSwiftSection.xcodeproj` 有 48 个 target,其中 21 个测试 target(除 `SwiftSectionCommandTests` 外全部,含 `IntegrationTests`)。原生 `MachOSwiftSection.xcworkspace` 没被碰,新生成的是 `MachOSwiftSection-Tuist.xcworkspace`。 +5. **在 Tuist 工程里手写 CLI**:`swift-section`(command line tool)、`swift_section`(static framework,同一批源码,模块名就是测试要的 `swift_section`)、`SwiftSectionCommandTests`(unit tests,依赖 `swift_section`)三个 target,都按 `.external(name:)` 依赖包的 product,生成成功。工程放在 `Tuist/CommandLine/` 下也能生成。没编译,链接与 `@testable import` 是否成立待第 2 步在 Ultra 上验证。 +6. **本地模式(五个上游库副本按路径声明)**:生成失败。`The test target 'ObjCSectionCommandTests' in the local package 'MachOObjCSection' depends on the executable target 'objc-section'`。换 Tuist 4.218.1 同样失败。 +7. **五个上游库副本的 `Package.swift` 末尾都加上同一段通用适配**(见「详细设计」,第 1、3 条的两种形态都按规则处理):生成成功,六个包的测试全部映射进来:本库 21、MachOKit 1、MachOKitExtensions 9、MachOObjCSection 8、swift-demangling 1、swift-semantic-string 2。再逐个去掉适配:MachOKit 与 swift-semantic-string 不加也能过;swift-demangling 不加时报 `Couldn't find target 'DemanglingTestingSupport'`。**最少要改三个上游库:MachOKitExtensions(`CPlusPlusSymbolsFixture`)、MachOObjCSection(`ObjCSectionCommandTests`)、swift-demangling(`DemanglingTestingSupport`)。** +8. **生成的工程确实写进各包自己的目录**:`Siblings/<名字>/<名字>.xcodeproj` 与 `Derived/`,本库副本根目录也是。这就是与 RuntimeViewer 冲突的地方。 +9. **`Tuist.swift` 能读环境变量**:把 `TUIST_SOURCE_TARGET_NAMES=Utilities,SwiftSymbols,MachOSwiftSection` 经 `Environment.sourceTargetNames` 读进缓存 profile,`tuist dump config` 显示 `exceptTargetQueries` 正是这三个名字。缓存例外名单因此可以由脚本从各包清单算出来,不用像 RuntimeViewer 那样手抄、再用 `check` 守着。 +10. **`tuist install` 解析出的远程依赖**(远程模式,种子锁文件取自集成 worktree 的 `Package.resolved`):AssociatedObject、capstone、combine-schedulers、FrameworkToolbox、MetaCodable、Rainbow、SourceKitD、swift-apinotes、swift-argument-parser、swift-asn1、swift-async-algorithms、swift-binary-parse-support、swift-capstone、swift-clocks、swift-collections、swift-concurrency-extras、swift-crypto、swift-dependencies、swift-fileio、swift-fileio-extra、swift-issue-reporting、swift-literal-type-inference、swift-memberwise-init-macro、swift-object-association、swift-objc-dump、swift-snapshot-testing、Yams,加上五个上游库。 + +### 推测(未验证,落地步骤里验证) + +- 测试 target 的部署版本:SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(macOS 14.0),Tuist 照搬包声明的 10.15,RuntimeViewer 因此在 `Duration`、`timeLimit` 上编不过。本库测试大概率踩同一个坑。 +- `-ObjC`:Tuist 把包编成静态库,链接器只拉被符号引用到的成员。本库测试是否依赖按名字在运行时查找的类,没查过。 +- `CAPSTONE_HAS_AARCH64`:本库开了 swift-capstone 的 `AARCH64` trait(`Package.swift:291` 的 `capstoneTraits`),Tuist 会丢掉只以 trait 为条件的设置,RuntimeViewer 因此手动补上了这个宏。 +- `swift_section` 这个 static framework 里有 `@main`,链进测试 bundle 后会多出一个 `_main` 符号。bundle 不是可执行文件,这应该无害。 + +## 提议方案 + +1. **新增 Tuist 描述**,全部是开发用的,不进发版与 CI: + - `mise.toml` 钉 Tuist 4.210.0,与 RuntimeViewer 相同(探针里用这个版本全部生成成功;4.218.1 的 `tuist install` 在本地模式下失败过一次,没查原因)。 + - `Tuist/Package.swift` 按路径声明本库(`..`)、预编译 swift-syntax、只被测试用到的 swift-snapshot-testing;本地模式下再按路径声明五个上游库。`PackageSettings` 恢复本库(以及本地模式下上游库)target 的警告,补上 Capstone 的 trait 宏,按需给测试 target 抬部署版本、加 `-ObjC`。 + - `Tuist/CommandLine/Project.swift` 是 Tuist 转换不了的那部分:`swift-section` CLI、给测试用的 `swift_section` 模块、`SwiftSectionCommandTests`。 + - `Workspace.swift` 命名 `MachOSwiftSection-Tuist`,每个映射了测试的包一个测试 scheme(不含 `IntegrationTests`)。 + - `Tuist.swift` 的缓存 profile:只缓存外部依赖,例外名单是本库与五个上游库的全部 target,名单由脚本经环境变量传入。两种模式下上游库都从源码编。 +2. **`Package.swift` 末尾加一段适配**,只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效:摘掉依赖本包可执行 target 的测试,给测试依赖却不属于任何 product 的普通 target 补 library product。同一段代码原样加进 MachOKitExtensions、MachOObjCSection、swift-demangling。规则是通用的,以后谁新加了这两种形态的测试都不用再改清单。 +3. **`TuistScript.sh`**:`install`、`generate`、`warm`、`build`、`test`、`release` 六个命令,`--local-dependencies` / `--remote-dependencies` 切换并记住模式,`--configuration Debug|Release`,`--dry-run`。依赖 checkout、二进制缓存、构建产物放 `/Volumes/DerivedData/MachOSwiftSection/Tuist/`,`TUIST_SCRIPT_ROOT` 可改。本地模式开始前先读各上游库的清单,有包会被 Tuist 拒掉测试时整体关掉测试映射并说明是哪个包,而不是让生成失败。 +4. **占用记录两边共用**:被占检出的 git 目录里写 `tuist-generated-project-owner`(占用者路径、释放它的命令),占用者在自己的 `Tuist/.claimed-checkouts` 列出手里的检出,列着才算有效。本库的脚本在任何模式下都占着自己的检出(根目录那份工程总要生成),本地模式下再占五个上游库;RuntimeViewer 的脚本改用同一份记录,旧记录仍然认。 +5. **文档**:使用指南 `Documentations/Internal/TuistDevelopment.md`,`AGENTS.md` 构建一节加一条,`Documentations/README.md` 登记。 + +### 非目标 + +- 不替代原生 workspace、`swift build` / `swift test` 与 CI;发版与 CI 只走原生路径。`Package.swift` 仍是 target 与依赖的唯一定义,Tuist 描述不另抄一份。 +- 不做 RuntimeViewer 那种「与原生工程对照」的 `check`,也不重排导航栏:本库没有原生 App 工程可对照,Tuist 直接读 `Package.swift`;唯一手抄的是 CLI 的依赖清单,编不过就会暴露。 +- 只做 macOS,只有 Debug 与 Release 两套配置。 +- 不映射 `reader-benchmark`、`baseline-generator` 两个维护者工具,也没有 `regen-baselines` 插件,照旧 `swift run` / `swift package`。 +- 不跑 `IntegrationTests`:target 会被转换进来,但不进任何 scheme(`AGENTS.md`:它是维护者手工查看用的)。 +- 不上传缓存:`Tuist.swift` 不设 `fullHandle`,二进制缓存只在本机。 +- MachOKit 与 swift-semantic-string 不改:实测它们现在不需要适配。以后它们新增了那两种形态的测试,脚本会关掉本地模式的测试映射并点名,到时再加同一段适配。 +- 不改 `USING_LOCAL_DEPENDENCIES` 机制:原生 workspace 的用法不变;脚本运行时忽略这个变量并提示。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `mise.toml` | 新增 | `[tools] tuist = "4.210.0"` | 两台机器、两个仓库用同一个 Tuist;RuntimeViewer 记下的坑都是这个版本 | 1 | +| `Tuist/Package.swift` | 新增 | 按路径声明本库、预编译 swift-syntax,按 URL 声明 swift-snapshot-testing;本地模式加五个上游库;`PackageSettings` | Tuist 的依赖图从这里来;路径依赖顶替图里同名的 URL 声明 | 1、2、3 | +| `Tuist/CommandLine/Project.swift` | 新增 | `swift-section`、`swift_section`、`SwiftSectionCommandTests` 三个 target | Tuist 不转换可执行 target,也不接受依赖它的测试(实测第 1、5 条) | 1、2 | +| `Workspace.swift` | 新增 | workspace 名 `MachOSwiftSection-Tuist`,成员 `Tuist/CommandLine`,按包生成测试 scheme | 不与原生 `MachOSwiftSection.xcworkspace` 同名;测试 target 在转换出的工程里,只能由 workspace 的 scheme 引用 | 1、2 | +| `Tuist.swift` | 新增 | 缓存 profile `development`:`.onlyExternal`,例外取 `TUIST_SOURCE_TARGET_NAMES` | 本库与上游库留作源码,其余进缓存;名单由脚本从清单算(实测第 9 条) | 4 | +| `TuistScript.sh` | 新增 | 六个命令、两种依赖模式、存放位置、日志、锁文件种子与比对、占用记录、测试映射的预检 | 直接跑 `tuist` 拿不到正确的环境变量与占用保护 | 1–5 | +| `Package.swift` | 修改 | 文件末尾加 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 适配块 | 让 Tuist 能映射本库测试(实测第 1–4 条);变量不设时什么都不变 | 2 | +| `MachOSwiftSection.xcworkspace/contents.xcworkspacedata` | 修改 | 加入 MachOKitExtensions、swift-demangling、swift-semantic-string 三个成员,与集成 worktree 里那处未提交的改动内容相同 | 脚本从这里读本地依赖名单,五个都要在 | 1 | +| `.gitignore` | 修改 | 忽略 `MachOSwiftSection-Tuist.xcworkspace/`、根目录的 `MachOSwiftSection.xcodeproj/` 与 `Derived/`、`Tuist/.build*/`、`Tuist/CommandLine/` 下生成的工程与 `Derived/`、`Tuist/.local-dependencies`、`Tuist/.claimed-checkouts` | 生成物不提交;根目录那两项今天只靠 RuntimeViewer 写进 `info/exclude` 才被忽略 | 1 | +| MachOKitExtensions `Package.swift` | 修改 | 末尾加同一段适配块 | 本地模式下 `CPlusPlusSymbolsFixture` 找不到(实测第 7 条) | 3 | +| MachOObjCSection `Package.swift` | 修改 | 同上 | 本地模式下 `ObjCSectionCommandTests` 被拒(实测第 6 条) | 3 | +| swift-demangling `Package.swift` | 修改 | 同上 | 本地模式下 `DemanglingTestingSupport` 找不到(实测第 7 条) | 3 | +| RuntimeViewer `TuistScript.sh` · `claim_local_checkouts` / `release_local_checkouts` | 修改 | 改用共用的 `tuist-generated-project-owner` 与 `Tuist/.claimed-checkouts`;旧的 `runtimeviewer-tuist-local-dependencies` 照旧认、自己占着的顺手删掉 | 双向互斥:今天它看不见本库的占用 | 5 | +| RuntimeViewer `Documentations/Guides/TuistDevelopment.md` | 修改 | 「写进库目录的文件」「同一时刻只让一个检出用这组库」两段改写成共用的占用记录 | 文档与代码同批 | 5 | +| `Documentations/Internal/TuistDevelopment.md` | 新增 | 使用指南:第一次使用、日常用法、两种模式、占用记录、存放位置、已知的坑 | 维护者要知道怎么用、什么时候要重新 `install` / `generate` | 6 | +| `AGENTS.md` | 修改 | 构建一节加一条:Tuist workspace 是开发用的第二条路,只经脚本运行,agent 设 `TUIST_SCRIPT_ROOT` 并经 `queued-build` | agent 默认会直接跑 `tuist generate`,那样既没有环境变量也没有占用保护 | 6 | +| `Documentations/README.md` | 修改 | Internal 一节登记新指南 | 文档索引 | 6 | +| `Documentations/Evolutions/README.md` | 修改 | 状态表加本提案 | 提案索引 | 创建时、落地时 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时加一节 | 演进账本 | 落地时 | + +## 架构图 + +改了什么(文件与生成物): + +```text +MachOSwiftSection/ (a checkout) +├── MachOSwiftSection.xcworkspace ~ members: + MachOKitExtensions, swift-demangling, swift-semantic-string +├── Package.swift ~ + TUIST_MAPS_LOCAL_PACKAGE_TESTS block at the end +├── + mise.toml tuist 4.210.0 +├── + Tuist.swift cache profile "development" +├── + Workspace.swift MachOSwiftSection-Tuist +├── + TuistScript.sh +├── + Tuist/ +│ ├── + Package.swift the dependency graph Tuist converts +│ └── + CommandLine/Project.swift swift-section, swift_section, SwiftSectionCommandTests +└── generated, ignored: + ├── MachOSwiftSection-Tuist.xcworkspace + ├── MachOSwiftSection.xcodeproj, Derived/ (converted from ./Package.swift) + └── Tuist/CommandLine/MachOSwiftSectionCommandLine.xcodeproj + +../MachOKitExtensions/Package.swift ~ + the same block +../MachOObjCSection/Package.swift ~ + the same block +../swift-demangling/Package.swift ~ + the same block +RuntimeViewer/TuistScript.sh ~ shared claim record +``` + +生成出的 workspace 里有什么: + +```text +MachOSwiftSection-Tuist.xcworkspace +├── Tuist/CommandLine/MachOSwiftSectionCommandLine.xcodeproj (+ hand-written Tuist targets) +│ ├── swift-section commandLineTool sources: Sources/Executables/swift-section/** +│ ├── swift_section staticFramework same sources, for @testable import +│ └── SwiftSectionCommandTests unitTests ──► swift_section +│ (all three ──► .external(SwiftSectionKit, MachOFoundation, ArgumentParser, …)) +├── MachOSwiftSection.xcodeproj source, 27 library/macro/C targets + 21 test targets +├── remote mode: checkouts//… source (cache exception), no tests +├── local mode: ..//.xcodeproj source from the local checkout, + its tests +└── third-party packages binary cache after `warm`, source before +``` + +一条命令怎么走(`./TuistScript.sh generate --local-dependencies`): + +```text +TuistScript.sh generate --local-dependencies +├── check the pinned Tuist (mise.toml), unset USING_LOCAL_DEPENDENCIES +├── read the local package names MachOSwiftSection.xcworkspace: container:../ +├── record the mode Tuist/.local-dependencies ← +├── read the manifests swift package dump-package, TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 +│ ├── TUIST_SOURCE_TARGET_NAMES every target of this package and the five upstream ones +│ ├── TUIST_PACKAGE_TEST_TARGETS =,…;… +│ └── tests rejected by Tuist anywhere? → TUIST_MAPS_LOCAL_PACKAGE_TESTS=0 + a warning naming the package +├── ensure_dependencies SWIFTPM_BUILD_DIR per mode; seed Tuist/Package.resolved; tuist install +├── claim_checkouts this checkout + the five upstream checkouts +│ └── another live owner? → fail with the owner's release command +└── tuist generate --no-open +``` + +占用记录(两个仓库的脚本共用): + +```text +/tuist-generated-project-owner + line 1: /path/to/owner/checkout + line 2: ./TuistScript.sh release (MachOSwiftSection) + ./TuistScript.sh generate --remote-dependencies (RuntimeViewer) + +/Tuist/.claimed-checkouts one real path per line + +a claim is live ⇔ the owner's .claimed-checkouts lists the claimed checkout's real path +legacy: /runtimeviewer-tuist-local-dependencies is live + ⇔ /Tuist/.local-dependencies/ is the claimed checkout +``` + +## 详细设计 + +### `Package.swift` 的适配块 + +本库与三个上游库的 `Package.swift` 末尾原样加这一段(探针里五个上游库副本都用它通过了 `swift package dump-package` 与 `tuist generate`)。它读的是 `Context.environment`,平时这个变量不存在,块里什么都不做;作为别人的远程依赖时也一样。 + +```swift +// The Tuist development workspace (MachOSwiftSection's Documentations/Internal/TuistDevelopment.md) +// maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends +// on an executable target, and a test that depends on a target no product contains. Only while Tuist +// resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the +// second kind gets a library product of its own. Nothing changes without the variable. +if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" { + let executableTargetNames = Set(package.targets.filter { $0.type == .executable }.map(\.name)) + func dependencyName(_ dependency: Target.Dependency) -> String? { + switch dependency { + case .targetItem(let name, _), .byNameItem(let name, _): + return name + default: + return nil + } + } + package.targets.removeAll { target in + target.type == .test && target.dependencies.contains { dependency in + dependencyName(dependency).map(executableTargetNames.contains) ?? false + } + } + let productTargetNames = Set(package.products.flatMap { product in (product as? Product.Library)?.targets ?? [] }) + let testDependencyNames = Set(package.targets.filter { $0.type == .test }.flatMap { $0.dependencies.compactMap(dependencyName) }) + package.products += package.targets + .filter { target in target.type == .regular && testDependencyNames.contains(target.name) && !productTargetNames.contains(target.name) } + .map { target in Product.library(name: target.name, targets: [target.name]) } +} +``` + +- 在本库里它摘掉 `SwiftSectionCommandTests`,给 `SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`(以及测试直接依赖的其余普通 target)补 product。在 MachOObjCSection 里摘掉 `ObjCSectionCommandTests`;在 MachOKitExtensions 与 swift-demangling 里补 `CPlusPlusSymbolsFixture`、`DemanglingTestingSupport` 的 product。 +- 被摘掉的测试 Tuist workspace 里就没有了,照旧用 `swift test --filter` 跑;本库的 `SwiftSectionCommandTests` 例外,它在 `Tuist/CommandLine/Project.swift` 里手写(下文)。MachOObjCSection 的 `ObjCSectionCommandTests` 不手写:那要在本库描述另一个仓库的 target,非目标。 +- 只看 target 依赖(`targetItem` / `byNameItem`),不看 `productItem`:依赖别的包的可执行 product 的测试,Tuist 怎么处理没有实测,目前四个包里也没有。 + +### `Tuist/Package.swift` + +```swift +// swift-tools-version: 6.2 +import Foundation +import PackageDescription + +// The dependencies of MachOSwiftSection-Tuist.xcworkspace (Documentations/Internal/TuistDevelopment.md). +// This package is declared by path, so its Package.swift stays the only definition of its targets. +// In the local dependency mode TuistScript.sh names the upstream packages in TUIST_LOCAL_PACKAGE_NAMES +// and their directory in TUIST_LOCAL_PACKAGE_CHECKOUTS; a root's path dependency stands in for every +// declaration of the same package in the graph. +let processEnvironment = ProcessInfo.processInfo.environment +let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? "" +let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "").split(separator: ",").map(String.init) +let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty + ? [] + : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") } + +#if TUIST + import ProjectDescription + + func names(_ variable: String) -> [String] { + (processEnvironment[variable] ?? "").split(separator: ",").map(String.init) + } + + // Tuist suppresses warnings in every package; Xcode does so for remote packages only. + let warningSettings: [String: Settings] = Dictionary( + names("TUIST_WARNING_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // Tuist drops a setting whose only condition is a trait; this package enables swift-capstone's + // AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 that way. + let restatedTraitDefinitions: [String: Settings] = [ + "Capstone": .settings(base: [ + "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"], + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + "Ccapstone": .settings(base: [ + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + ] + + // Filled in by step 2 once the tests have been built: the deployment target SwiftPM gives a test + // target (macOS 14.0) and -ObjC, each only if the build shows it is needed. + let testTargetSettings: [String: Settings] = [:] + + let packageSettings = PackageSettings( + targetSettings: warningSettings + .merging(restatedTraitDefinitions) { $1 } + .merging(testTargetSettings) { $1 }, + includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" + ) +#endif + +let package = Package( + name: "MachOSwiftSectionTuistDependencies", + dependencies: [ + .package(path: ".."), + // Stands in for swift-syntax everywhere, as it does as a member of the native workspace. + .package(path: "../PrecompiledLibraries/swift-syntax"), + // Used only by tests, which Tuist needs declared here (MachOSwiftSection's requirement). + .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"), + ] + localPackageDependencies +) +``` + +- 包名 `MachOSwiftSectionTuistDependencies`。根包的路径依赖 `..` 的身份是目录名:worktree 叫 `MachOSwiftSection-<用途>` 时身份就变了,而上游库的清单不按 URL 引用本库,所以不受影响;生成的工程名取自 `Package(name:)`,仍是 `MachOSwiftSection.xcodeproj`。 +- `TUIST_WARNING_TARGET_NAMES` 是本库全部 target,本地模式下再加五个上游库的全部 target(与原生 workspace 一致:Xcode 只给远程包关警告)。 + +### `Tuist/CommandLine/Project.swift` + +```swift +import ProjectDescription + +// What Tuist cannot convert from ../../Package.swift: the swift-section executable, and +// SwiftSectionCommandTests, which imports the executable's module. swift_section compiles the same +// sources as a static framework for that test; the tool compiles them again, so its link needs no +// trick around the @main entry point. The dependency list mirrors Package.swift's swift-section +// target and is the one hand-written copy in the Tuist description. +let commandLineDependencies: [TargetDependency] = [ + .external(name: "SwiftSectionKit"), + .external(name: "MachOFoundation"), + .external(name: "SwiftSymbols"), + .external(name: "SwiftDump"), + .external(name: "SwiftOutputTransformer"), + .external(name: "SwiftDeclaration"), + .external(name: "SwiftIndexing"), + .external(name: "Semantic"), + .external(name: "OutputTransformer"), + .external(name: "ObjCDeclarationRendering"), + .external(name: "ObjCOutputTransformer"), + .external(name: "Rainbow"), + .external(name: "ArgumentParser"), +] + +let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] + +// MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; +// TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. +let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: false) + ? .settings(base: ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]]) + : .settings() + +let project = Project( + name: "MachOSwiftSectionCommandLine", + targets: [ + .target( + name: "swift-section", + destinations: .macOS, + product: .commandLineTool, + bundleId: "com.machoswiftsection.swift-section", + deploymentTargets: .macOS("10.15"), + sources: commandLineSources, + dependencies: commandLineDependencies + ), + .target( + name: "swift_section", + destinations: .macOS, + product: .staticFramework, + bundleId: "com.machoswiftsection.swift-section.module", + deploymentTargets: .macOS("10.15"), + sources: commandLineSources, + dependencies: commandLineDependencies + ), + .target( + name: "SwiftSectionCommandTests", + destinations: .macOS, + product: .unitTests, + bundleId: "com.machoswiftsection.SwiftSectionCommandTests", + deploymentTargets: .macOS("14.0"), + sources: ["../../Tests/SwiftSectionCommandTests/**"], + dependencies: [ + .target(name: "swift_section"), + .external(name: "SwiftDeclarationRendering"), + .external(name: "SwiftPrinting"), + ] + commandLineDependencies, + settings: commandTestSettings + ), + ] +) +``` + +- CLI 的源码编两遍(tool 一遍、framework 一遍)。另一种写法是 tool 不带源码、只链 framework,靠链接器从静态库里取 `_main`;省一遍编译,但能否链接成功依赖链接器怎么处理入口符号,没实测,放进「替代方案」。 +- `MACHO_SWIFT_SECTION_SILENT_TEST=1` 在 `Package.swift` 里变成测试 target 的 `SILENT_TEST` 定义:`tuist install` 时设了它,转换出的测试就带上。手写的 `SwiftSectionCommandTests` 也要带:Tuist 的 manifest 只读得到 `TUIST_` 开头的变量,所以脚本把它转成 `TUIST_SILENT_TEST=1`,`Project.swift` 据此给这个 target 加 `SILENT_TEST`。 + +### `Workspace.swift` + +```swift +import ProjectDescription + +// "=,;…" from TuistScript.sh, one entry per package whose +// tests are mapped: this package always (directory "."), the upstream packages in the local mode. +// IntegrationTests is never listed. +let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets + .getString(default: "") + .split(separator: ";") + .compactMap { entry in + let parts = entry.split(separator: "=", maxSplits: 1).map(String.init) + guard parts.count == 2 else { return nil } + return (parts[0], parts[1].split(separator: ",").map(String.init)) + } + +let workspace = Workspace( + name: "MachOSwiftSection-Tuist", + projects: ["Tuist/CommandLine"], + schemes: packageTestTargets.map { entry in + let packageName = entry.directory == "." ? "MachOSwiftSection" : (entry.directory as NSString).lastPathComponent + var testableTargets = entry.targets.map { targetName in + TestableTarget.testableTarget(target: .project(path: Path(entry.directory), target: targetName)) + } + if entry.directory == "." { + testableTargets.append(.testableTarget(target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"))) + } + return .scheme(name: "\(packageName) Tests", testAction: .targets(testableTargets)) + } +) +``` + +- 上游库的目录是绝对路径;`Path` 接受绝对路径字符串,第 3 步验证。`Workspace.swift` 能否 `import Foundation` 用 `NSString` 没验证,不行就自己切最后一段。 +- 测试映射被预检关掉时 `TUIST_PACKAGE_TEST_TARGETS` 为空,只剩各 target 自己的 scheme;`SwiftSectionCommandTests` 仍在 `MachOSwiftSectionCommandLine` 工程里,Tuist 自动生成的 scheme 能跑它。 + +### `Tuist.swift` + +```swift +import ProjectDescription + +// Every target of MachOSwiftSection and of the five upstream packages stays source, in both dependency +// modes; every other dependency comes out of the binary cache once warmed. TuistScript.sh reads the +// names from the packages' manifests. No fullHandle: the cache stays on this machine. +let sourceTargetNames = Environment.sourceTargetNames + .getString(default: "") + .split(separator: ",") + .map(String.init) + +let tuist = Tuist( + project: .tuist( + cacheOptions: .options( + profiles: .profiles( + ["development": .profile(.onlyExternal, except: sourceTargetNames.map { .named($0) })], + default: "development" + ) + ) + ) +) +``` + +- 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;它们留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库,第 4 步量出来后若差得多再议。 +- 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。 + +### `TuistScript.sh` + +照 RuntimeViewer 的脚本写,只保留与本库有关的部分。 + +**命令**: + +| 命令 | 做什么 | +|---|---| +| `install` | 从种子锁文件开始解析当前模式的依赖(`tuist install`),结束时与种子比对 pin | +| `generate [--configuration ]` | 需要时先 `install`,占用检出,生成 workspace(默认 Debug) | +| `warm [--configuration ]` | 带 `--cache-profile development` 把第三方依赖编进缓存,再生成 | +| `build [--configuration ]` | 生成后用 `xcodebuild` 编 `swift-section` scheme | +| `test [-- ]` | 生成后用 `xcodebuild test` 跑 `MachOSwiftSection Tests` scheme,退出码就是 `xcodebuild` 的 | +| `release` | 放弃所有占用:删掉生成进各检出的工程(git 跟踪的不删)、占用记录与 `MachOSwiftSection-Tuist.xcworkspace`;`Derived/` 留着 | + +`--local-dependencies` / `--remote-dependencies` 可以跟在任何命令后面,从这条命令起切换模式;`--dry-run` 打印要做的事;`--help` 打印脚本头部的说明。 + +**环境变量**(脚本设,manifest 读): + +| 变量 | 谁读 | 内容 | +|---|---|---| +| `TUIST_MAPS_LOCAL_PACKAGE_TESTS` | 四个包的 `Package.swift`,`Tuist/Package.swift` | `1`:映射测试;预检不通过时 `0` | +| `TUIST_LOCAL_PACKAGE_CHECKOUTS`、`TUIST_LOCAL_PACKAGE_NAMES` | `Tuist/Package.swift` | 本地模式下上游库所在目录与名字;远程模式不设 | +| `TUIST_SOURCE_TARGET_NAMES` | `Tuist.swift` | 本库与五个上游库的全部 target | +| `TUIST_WARNING_TARGET_NAMES` | `Tuist/Package.swift` | 恢复警告的 target:本库全部,本地模式再加上游库全部 | +| `TUIST_PACKAGE_TEST_TARGETS` | `Workspace.swift` | 每个映射了测试的包的测试 target,不含 `IntegrationTests` | +| `TUIST_SILENT_TEST` | `Tuist/CommandLine/Project.swift` | 用户设了 `MACHO_SWIFT_SECTION_SILENT_TEST=1` 时为 `1` | +| `SWIFTPM_BUILD_DIR` | Tuist | 当前模式的依赖 checkout 目录 | +| `TUIST_XDG_CACHE_HOME`、`TUIST_CACHE_WARM_SCRATCH_DIRECTORY` | Tuist | 二进制缓存与预热的临时目录 | + +`USING_LOCAL_DEPENDENCIES` 被设了就提示一句并 `unset`:它会让本库清单自己换上本地兄弟,连 swift-capstone 一起,与 `Tuist/Package.swift` 的名单对不上。 + +**名单从哪来**:本地依赖的名字读 `MachOSwiftSection.xcworkspace/contents.xcworkspacedata` 里的 `container:../<名字>`(不含 `/` 的那些),workspace 加了库这里自动跟上。target 名单用 `swift package dump-package`(带 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1`,`--scratch-path` 放在 `Work//Manifests/`)读六个包的清单:本库与本地模式下的上游库读检出里的,远程模式下的上游库读 `install` 之后 `SWIFTPM_BUILD_DIR/checkouts/<名字>` 里的。远程模式下第一次 `install` 之前还没有 checkout,先用空名单装一次再算。 + +**测试映射的预检**:对每个按路径声明的包,在它的清单 JSON 里找 Tuist 会拒绝的两种形态——测试依赖本包的可执行 target、测试依赖不属于任何 product 的普通 target(实测第 1、3、6 条)。适配块生效时这两种都不该剩下;还剩,说明那个包没有适配块(比如本地检出停在加块之前的提交),这次就整体设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=0`,警告点名那个包,生成照常进行。只被测试用到的外部依赖(实测第 2 条)预检查不出来,生成时 Tuist 自己会报,指南里写怎么补。 + +**锁文件**:`Tuist/Package.resolved` 不提交(`*.resolved` 已忽略)。每次 `install` 前用本检出根目录的 `Package.resolved` 当种子(没有就不种,由 Tuist 解析最新版本),结束时逐条比对,不同就警告;swift-syntax(这边是预编译包,没有 pin)与本地模式下的五个库不参与比对。 + +**依赖模式**:模式记在 `Tuist/.local-dependencies`(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 `.worktrees/`;打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS` 就用它。两种模式各用一份依赖 checkout(`Dependencies/` 与 `Dependencies/-LocalDependencies`),共用 `Tuist/Package.resolved`,所以切换后、或上次解析用的是另一种模式时先重新 `install`(`Work//InstalledDependencies` 记着上次)。切到远程时释放五个上游库的占用。 + +**存放位置**:`/Volumes/DerivedData` 挂着时全放在 `/Volumes/DerivedData/MachOSwiftSection/Tuist/` 下(`Cache/`、`Dependencies/[-LocalDependencies]/`、`WarmScratch//`、`Work//`),`` 是目录名加路径的短 hash;没挂载时放在仓库里的 `Tuist/.build/`、`Tuist/.build-LocalDependencies/` 与 `DerivedData/Tuist/`(都已忽略)。`TUIST_SCRIPT_ROOT` 指定别处。`build` / `test` 的 DerivedData 在 `Work//DerivedData`。日志在 `Products/Logs/Tuist/`;Tuist 的输出原样显示并记进日志,`xcodebuild` 的输出只进日志,失败时显示错误摘要。 + +**占用记录**(与 RuntimeViewer 共用): + +- 被占的检出:它的 git 目录(`git rev-parse --absolute-git-dir`,worktree 各有一份)里的 `tuist-generated-project-owner`,第一行是占用者检出的路径,第二行是在占用者检出里释放它的命令。 +- 占用者:自己的 `Tuist/.claimed-checkouts`,每行一个被占检出的真实路径(`pwd -P`)。 +- 有效:占用者的 `.claimed-checkouts` 列着这个路径。占用者不在了、或已经不列了,记录就是陈旧的,可以直接覆盖。 +- 旧记录 `runtimeviewer-tuist-local-dependencies`:占用者的 `Tuist/.local-dependencies` 加上包名指向这个检出时算有效(RuntimeViewer 今天的规则)。 +- 本库的脚本在 `generate` 前占用自己的检出与(本地模式下)五个上游库;遇到别人的有效占用就失败,报出占用者路径与它的释放命令。检出里 git 跟踪着 `<包名>.xcodeproj` 时也失败(Tuist 会覆盖它)。上游库的 `<包名>.xcodeproj/` 与 `Derived/` 写进那个仓库的 `info/exclude`,本库自己的生成物走 `.gitignore`。 +- 释放:删掉生成进那个检出的工程、占用记录,并从 `.claimed-checkouts` 里去掉。 + +**Tuist 版本**:读 `mise.toml` 的版本;有 mise 就 `mise exec -- tuist`,否则用 PATH 里的 `tuist`;版本不对就失败并提示 `mise install`。 + +**agent 运行**:`TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection`,并写成 `queued-build ./TuistScript.sh <命令>`。 + +### RuntimeViewer 那一侧 + +- `claim_local_checkouts`:先读共用记录与旧记录,任何一个有效且占用者不是自己就失败,报出占用者与释放命令;然后写共用记录(第二行是 `./TuistScript.sh generate --remote-dependencies`),把路径写进自己的 `Tuist/.claimed-checkouts`,自己的旧记录删掉。 +- `release_local_checkouts`:删掉自己的共用记录(以及残留的旧记录),从 `.claimed-checkouts` 里去掉。 +- 今天它占着本库的集成 worktree 与五个上游检出(旧记录)。改完后它下一次 `generate` 就把记录换成新的;在那之前,本库的脚本按旧规则认出它的占用。 + +### 已知要在实现中确认的点 + +1. `swift_section` 与 `SwiftSectionCommandTests` 能编、能链、`@testable import` 成立(第 2 步)。 +2. 本库测试在 Tuist workspace 里要不要抬部署版本到 14.0、要不要 `-ObjC`(第 2 步,只加确实需要的)。 +3. `Capstone` 的 trait 宏补上后 `SwiftThunkAnalysis` 能编(第 1 步)。 +4. `Workspace.swift` 里按绝对路径引用上游库工程(第 3 步)。 +5. 远程与本地两种模式下,Tuist workspace 跑出的测试数与 `swift test --skip IntegrationTests` 一致,失败的与原生路径相同(第 2、3 步,在 Ultra 上)。 + +## 替代方案考量 + +- **Tuist 的「把 `Package.swift` 当工程」**(beta,`tuist generate` 直接读根目录的 `Package.swift`):不用 `Tuist/Package.swift`,可本地 / 远程切换要靠顶替同名包,还是得有一个根清单按路径声明上游库;文档写明它不打算支持 SwiftPM 的全部特性;它很可能按包名生成 `MachOSwiftSection.xcworkspace`,与原生 workspace 同名(推测,没实测)。否。 +- **在 `Project.swift` 里手写全部 target**:生成的工程名可以避开 RuntimeViewer 用的 `MachOSwiftSection.xcodeproj`,冲突自然消失;但要把五十来个 target 的依赖关系从 `Package.swift` 再抄一份,必然漂移,还得写一个 `check` 守着。否。 +- **Tuist 的 Xcode 原生包集成**(生成的工程里仍用 Xcode 的 SwiftPM 集成):不往包目录写工程,冲突也消失;但它没有二进制缓存,与原生 workspace 相比什么也没得到。否。 +- **本地模式不映射测试**(RuntimeViewer 的做法):不用改任何上游库;但本库跨仓库改动时用的正是本地模式,那时 Tuist workspace 里跑不了任何测试,本库自己的也跑不了(这个选项对所有路径包一刀切)。用户选了加适配块(决策日志「用户批准,开始实现」)。 +- **只针对点名的 target 打补丁**(在本库清单里按名字摘掉 `SwiftSectionCommandTests`、按名字补 product):探针第一版就是这么做的;但三个上游库各要写一份不同的补丁,以后每加一个这种形态的测试都要回来改。通用规则一段代码四个仓库共用。否。 +- **CLI 只链 framework、不带源码**:省一遍 CLI 源码的编译;能否链接成功取决于链接器会不会为入口符号 `_main` 从静态库里取成员,没实测,失败了还得改成给 framework 加 `-entry-point-function-name`。编两遍的写法没有这个风险,CLI 模块也不大。否,可以在第 2 步顺手试一次,成了再换。 +- **远程模式下把五个上游库也放进缓存**:远程模式从空 DerivedData 构建会更快;但它们的 pin 动得勤,每次都要重新预热,缓存里旧版本越积越多,也跳不进源码。暂否,第 4 步量出差距后可以重议。 +- **只在本库这边检查 RuntimeViewer 的占用**:不用改 RuntimeViewer;但 RuntimeViewer 的本地模式照样会盖掉本库生成的工程。用户选了双向互斥。 +- **用 `USING_LOCAL_DEPENDENCIES=1` 实现本地模式**:本库清单自己就会换上本地兄弟;但它对所有带本地路径的依赖一刀切(含 swift-capstone),三个上游库的清单也各有自己的开关,结果取决于每个清单怎么写。按路径逐个声明更精确,与 RuntimeViewer 一致。否。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增。没有任何公开 API 变化。`Package.swift` 的适配块只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效,`swift build`、`swift test`、Xcode 的原生 workspace、CI 与下游的 SwiftPM 解析都不会设这个变量;三个上游库同样。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本仓库内**:没有 target 受影响。`.gitignore` 多了几项生成物,`MachOSwiftSection.xcworkspace` 多了三个成员(它们本来就在集成 worktree 的未提交改动里)。 +- **RuntimeViewer**:`TuistScript.sh` 换用共用的占用记录(第 5 步)。它的 Tuist 在本地模式下按路径读本库与三个上游库的清单,但不设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS`,适配块不生效,它生成的工程不变。 +- **MachOKitExtensions、MachOObjCSection、swift-demangling**:清单末尾多一段默认不生效的代码,不需要发版——只有本地模式读它们的本地检出时才用到。它们的其他下游(MachOKitUI、SymbolViewer……)不受影响。 + +### 文档与示例 + +- 新增使用指南 `Documentations/Internal/TuistDevelopment.md`,登记进 `Documentations/README.md`。 +- `AGENTS.md` 构建一节加一条。 +- `README.md` 不改:Tuist workspace 只给维护者用。 +- RuntimeViewer 的 `Documentations/Guides/TuistDevelopment.md` 改两段(第 5 步)。 + +## API 演进与废弃策略 + +无:没有公开 API 变化,不涉及版本号。 + +## 落地步骤 + +在 Ultra 上构建与跑测试(本机是 10 核那台),用默认的 Xcode 27.2;第 2、3 步的测试结果另用 Xcode 26.6 的 `swift test` 结果对照。 + +1. **骨架:远程模式能生成、能编 CLI** —— 改动地图里 `mise.toml`、`Tuist/Package.swift`(不含测试相关)、`Tuist/CommandLine/Project.swift`(只有 `swift-section`)、`Workspace.swift`(无测试 scheme)、`TuistScript.sh`(`install`、`generate`、`build`、`release`,存放位置,锁文件,自己检出的占用)、`.gitignore`、workspace 成员 + - 行为:`generateCreatesTheTuistWorkspaceAndLeavesTheNativeWorkspaceUntouched` + - 行为:`buildCompilesSwiftSectionFromTheTuistWorkspace` + - 行为:`generateFailsNamingTheOwnerWhenAnotherCheckoutHoldsThisOne` + - 行为:`releaseRemovesTheGeneratedProjectsAndTheClaim` + - 行为:`installWarnsWhenTheResolvedPinsDifferFromTheSeedLockFile` + - 行为:`usingLocalDependenciesIsIgnoredWithAWarning` +2. **本库的测试** —— `Package.swift` 适配块,`Tuist/Package.swift` 的 swift-snapshot-testing 与测试设置,`Project.swift` 的 `swift_section` 与 `SwiftSectionCommandTests`,`Workspace.swift` 的测试 scheme,脚本的 `test` 命令与清单读取 + - 行为:`theTestSchemeHoldsEveryTestTargetExceptIntegrationTests` + - 行为:`swiftSectionCommandTestsImportTheCommandModuleAndPass` + - 行为:`theTuistTestRunMatchesSwiftTestTargetByTarget` + - 行为:`packageManifestIsUnchangedWithoutTheTuistVariable`(`swift package dump-package` 不带变量时与改动前逐字节相同) +3. **本地模式** —— 三个上游库的适配块(各自的功能分支),`Tuist/Package.swift` 的本地依赖,脚本的模式切换、上游库占用、预检 + - 行为:`localDependenciesBuildTheUpstreamPackagesFromTheirCheckoutsWithUncommittedEdits` + - 行为:`theModeIsRememberedAndSwitchingResolvesAgain` + - 行为:`localModeMapsTheTestsOfAllSixPackages` + - 行为:`anUpstreamCheckoutWithoutTheBlockTurnsTestMappingOffWithAWarning` + - 行为:`switchingToRemoteReleasesTheUpstreamCheckouts` +4. **二进制缓存** —— `Tuist.swift`,脚本的 `warm` 与 `TUIST_SOURCE_TARGET_NAMES` + - 行为:`warmCachesEveryThirdPartyPackageAndNoneOfTheSixOwnPackages` + - 行为:`generateAfterWarmLinksTheCachedBinaries` + - 行为:`aThirdPartyTargetNamedLikeAnOwnTargetIsReported` + - 记录:空 DerivedData 下不用缓存与走缓存各编一次 `swift-section` 与测试 scheme 的时间,写进决策日志与指南。 +5. **与 RuntimeViewer 互斥** —— RuntimeViewer 的 `TuistScript.sh` 与指南 + - 行为:`runtimeViewerLocalModeFailsWhileMachOSwiftSectionHoldsTheCheckout` + - 行为:`machOSwiftSectionFailsWhileRuntimeViewerHoldsAnUpstreamCheckout`(新旧两种记录各一次) + - 行为:`aStaleClaimIsTakenOverSilently` +6. **文档** —— 使用指南、`AGENTS.md`、`Documentations/README.md` + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 本提案已定要写使用指南 `Documentations/Internal/TuistDevelopment.md`;实现说明是否另写,收尾时判断。 +- **有没有引入新术语** —— 「Tuist 开发 workspace」「本地依赖模式」「占用记录」是否进 `Documentations/Glossary.md`,收尾时判断。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户要一个照 RuntimeViewer 做法建的 Tuist 开发 workspace,依赖可在本地检出与远程版本之间切换,本地依赖就是原生 workspace 里放的那几个上游库。按轻量档处理:新增的开发路径,不改原有的构建、发版与 CI。 | +| 2026-11-20 | 定下三个方向 | 用户选定:提供二进制缓存与 `warm`;Tuist workspace 要能跑测试,先实测再定写法;与 RuntimeViewer 的本地依赖模式双向互斥,为此顺带改 RuntimeViewer 的脚本。 | +| 2026-11-20 | 实测定下测试的写法 | 十项实测见「前期调研」:Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;`SwiftSectionCommandTests` 在 `Tuist/CommandLine/Project.swift` 里手写。三个上游库要不要加,留给用户定。 | +| 2026-11-20 | 用户批准,开始实现 | 用户选定给 MachOKitExtensions、MachOObjCSection、swift-demangling 加适配块,本地模式带测试;状态改 Accepted。实现在本库的 `feature/tuist-workspace`,三个上游库与 RuntimeViewer 各用同名分支。 | From 544e55cb0226ee14bec76118a0554789810f109b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:20:04 +0800 Subject: [PATCH 002/175] feat: add the Tuist development workspace TuistScript.sh generates MachOSwiftSection-Tuist.xcworkspace beside the native workspace: Tuist/Package.swift declares this package by path, Tuist/CommandLine/Project.swift describes the swift-section tool and SwiftSectionCommandTests (which Tuist cannot convert), and Workspace.swift lists the package's tests in a scheme. Package.swift ends with a block that, only under TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, leaves out the tests Tuist rejects and gives test-support targets a product. The native workspace now lists all five upstream packages the local mode takes. Proposal: draft-tuist-workspace --- .gitignore | 15 + Documentations/Evolutions/README.md | 2 +- .../Evolutions/draft-tuist-workspace.html | 2 +- .../Evolutions/draft-tuist-workspace.md | 2 +- .../contents.xcworkspacedata | 11 +- Package.swift | 29 + Tuist.swift | 23 + Tuist/CommandLine/Project.swift | 72 ++ Tuist/Package.swift | 77 ++ TuistScript.sh | 789 ++++++++++++++++++ Workspace.swift | 46 + mise.toml | 5 + 12 files changed, 1069 insertions(+), 4 deletions(-) create mode 100644 Tuist.swift create mode 100644 Tuist/CommandLine/Project.swift create mode 100644 Tuist/Package.swift create mode 100755 TuistScript.sh create mode 100644 Workspace.swift create mode 100644 mise.toml diff --git a/.gitignore b/.gitignore index 3e28e3bb..e1a6e04c 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,18 @@ Tests/Projects/SymbolTests/DerivedData .omc .swiftpm/xcode/xcshareddata/xcschemes __pycache__/ + +# The Tuist development workspace (Documentations/Internal/TuistDevelopment.md): everything +# ./TuistScript.sh and Tuist generate inside the checkout. +/MachOSwiftSection-Tuist.xcworkspace/ +/MachOSwiftSection.xcodeproj/ +/Derived/ +/PrecompiledLibraries/swift-syntax/swift-syntax.xcodeproj/ +/PrecompiledLibraries/swift-syntax/Derived/ +/PrecompiledLibraries/swift-syntax/.build/ +/Tuist/.build/ +/Tuist/.build-LocalDependencies/ +/Tuist/CommandLine/*.xcodeproj/ +/Tuist/CommandLine/Derived/ +/Tuist/.local-dependencies +/Tuist/.claimed-checkouts diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 8d9e0600..71820648 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -113,4 +113,4 @@ | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | | [cross-repository MachOKitExtensions 0004](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md) | 符号语言的判断归各自的包:由那边维护唯一提案;本库在 `SwiftSymbols` 定义 `SymbolLanguage.swift` 与 Swift 名字的判断,新 C target `SwiftSymbolsRegistration` 在镜像加载时注册;MachOKitExtensions 下限抬到 3.0.0 | Implemented | -| draft | [Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出](draft-tuist-workspace.md) | Accepted | +| draft | [Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出](draft-tuist-workspace.md) | In Progress | diff --git a/Documentations/Evolutions/draft-tuist-workspace.html b/Documentations/Evolutions/draft-tuist-workspace.html index 43c7e005..e58337df 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.html +++ b/Documentations/Evolutions/draft-tuist-workspace.html @@ -163,7 +163,7 @@

MachOSwiftSectionEvolutionsDraft

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

-
状态
Accepted
+
状态
In Progress
最后更新
2026-11-20
项目类型
库
原文
draft-tuist-workspace.md
diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/draft-tuist-workspace.md index 477a4a2e..163b608f 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.md +++ b/Documentations/Evolutions/draft-tuist-workspace.md @@ -1,6 +1,6 @@ # Draft - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-20 - **最后更新**: 2026-11-20 diff --git a/MachOSwiftSection.xcworkspace/contents.xcworkspacedata b/MachOSwiftSection.xcworkspace/contents.xcworkspacedata index 13acd86a..c28ff301 100644 --- a/MachOSwiftSection.xcworkspace/contents.xcworkspacedata +++ b/MachOSwiftSection.xcworkspace/contents.xcworkspacedata @@ -4,12 +4,21 @@ - + + + + + + diff --git a/Package.swift b/Package.swift index c9bf092d..3d9959c9 100644 --- a/Package.swift +++ b/Package.swift @@ -1546,3 +1546,32 @@ extension SwiftSetting { static let nonisolatedNonsendingByDefault: Self = .enableUpcomingFeature("NonisolatedNonsendingByDefault") // SE-0461, Swift 6.2, SwiftPM 6.2+ static let immutableWeakCaptures: Self = .enableUpcomingFeature("ImmutableWeakCaptures") // SE-0481, Swift 6.2, SwiftPM 6.2+ } + +// MARK: - Tuist development workspace + +// MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md) +// maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends +// on an executable target, and a test that depends on a target no product contains. Only while Tuist +// resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the +// second kind gets a library product of its own. Nothing changes without the variable. +if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" { + let executableTargetNames = Set(package.targets.filter { $0.type == .executable }.map(\.name)) + func dependencyName(_ dependency: Target.Dependency) -> String? { + switch dependency { + case .targetItem(let name, _), .byNameItem(let name, _): + return name + default: + return nil + } + } + package.targets.removeAll { target in + target.type == .test && target.dependencies.contains { dependency in + dependencyName(dependency).map(executableTargetNames.contains) ?? false + } + } + let productTargetNames = Set(package.products.flatMap { product in (product as? Product.Library)?.targets ?? [] }) + let testDependencyNames = Set(package.targets.filter { $0.type == .test }.flatMap { $0.dependencies.compactMap(dependencyName) }) + package.products += package.targets + .filter { target in target.type == .regular && testDependencyNames.contains(target.name) && !productTargetNames.contains(target.name) } + .map { target in Product.library(name: target.name, targets: [target.name]) } +} diff --git a/Tuist.swift b/Tuist.swift new file mode 100644 index 00000000..33249a24 --- /dev/null +++ b/Tuist.swift @@ -0,0 +1,23 @@ +import ProjectDescription + +// Every target of MachOSwiftSection and of the five upstream packages its native workspace lists +// (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) stays +// source, in both dependency modes; every other dependency comes out of the binary cache once +// `./TuistScript.sh warm` has filled it. The script reads the names from the packages' manifests and +// passes them in TUIST_SOURCE_TARGET_NAMES. No fullHandle: the cache stays on this machine and +// nothing is uploaded. Documentations/Internal/TuistDevelopment.md. +let sourceTargetNames = Environment.sourceTargetNames + .getString(default: "") + .split(separator: ",") + .map(String.init) + +let tuist = Tuist( + project: .tuist( + cacheOptions: .options( + profiles: .profiles( + ["development": .profile(.onlyExternal, except: sourceTargetNames.map { .named($0) })], + default: "development" + ) + ) + ) +) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift new file mode 100644 index 00000000..794f412f --- /dev/null +++ b/Tuist/CommandLine/Project.swift @@ -0,0 +1,72 @@ +import ProjectDescription + +// What Tuist cannot convert from ../../Package.swift (Documentations/Internal/TuistDevelopment.md): +// the swift-section executable, and SwiftSectionCommandTests, which imports the executable's module +// (`@testable import swift_section`). Tuist converts no executable target and rejects a test that +// depends on one, so Package.swift leaves that test out while Tuist resolves it and it is described +// here instead. swift_section compiles the command's sources as a static framework for the test; the +// tool compiles them again, so its link needs no trick around the @main entry point. +// +// The dependency list mirrors the swift-section target in Package.swift and is the one hand-written +// copy in the Tuist description: a dependency added there that is missing here fails to compile. +let commandLineDependencies: [TargetDependency] = [ + .external(name: "SwiftSectionKit"), + .external(name: "MachOFoundation"), + .external(name: "SwiftSymbols"), + .external(name: "SwiftDump"), + .external(name: "SwiftOutputTransformer"), + .external(name: "SwiftDeclaration"), + .external(name: "SwiftIndexing"), + .external(name: "Semantic"), + .external(name: "OutputTransformer"), + .external(name: "ObjCDeclarationRendering"), + .external(name: "ObjCOutputTransformer"), + .external(name: "Rainbow"), + .external(name: "ArgumentParser"), +] + +let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] + +// MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; +// TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. +let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: false) + ? .settings(base: ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]]) + : .settings() + +let project = Project( + name: "MachOSwiftSectionCommandLine", + targets: [ + .target( + name: "swift-section", + destinations: .macOS, + product: .commandLineTool, + bundleId: "com.machoswiftsection.swift-section", + deploymentTargets: .macOS("10.15"), + sources: commandLineSources, + dependencies: commandLineDependencies + ), + .target( + name: "swift_section", + destinations: .macOS, + product: .staticFramework, + bundleId: "com.machoswiftsection.swift-section.module", + deploymentTargets: .macOS("10.15"), + sources: commandLineSources, + dependencies: commandLineDependencies + ), + .target( + name: "SwiftSectionCommandTests", + destinations: .macOS, + product: .unitTests, + bundleId: "com.machoswiftsection.SwiftSectionCommandTests", + deploymentTargets: .macOS("14.0"), + sources: ["../../Tests/SwiftSectionCommandTests/**"], + dependencies: [ + .target(name: "swift_section"), + .external(name: "SwiftDeclarationRendering"), + .external(name: "SwiftPrinting"), + ] + commandLineDependencies, + settings: commandTestSettings + ), + ] +) diff --git a/Tuist/Package.swift b/Tuist/Package.swift new file mode 100644 index 00000000..4fb8585c --- /dev/null +++ b/Tuist/Package.swift @@ -0,0 +1,77 @@ +// swift-tools-version: 6.2 +import Foundation +import PackageDescription + +// The dependencies of MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +// (Documentations/Internal/TuistDevelopment.md). Generate it with ./TuistScript.sh, never with a bare +// `tuist generate`: the script sets the variables everything below reads. +// +// MachOSwiftSection itself is declared by path, so its Package.swift stays the only definition of its +// targets and dependencies. In the local dependency mode (`./TuistScript.sh +// --local-dependencies`) the script names the upstream packages the native workspace lists beside +// the checkout in TUIST_LOCAL_PACKAGE_NAMES and the directory holding them in +// TUIST_LOCAL_PACKAGE_CHECKOUTS. A root's path dependency stands in for every other declaration of the +// same package in the graph — MachOSwiftSection's URLs and the upstream packages' own — so they build +// from those checkouts, uncommitted edits included. A path package's identity is its directory's name. +let processEnvironment = ProcessInfo.processInfo.environment +let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? "" +let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "") + .split(separator: ",") + .map(String.init) +// Qualified: Tuist evaluates this file with ProjectDescription imported too, which has a Package of +// its own. +let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty + ? [] + : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") } + +#if TUIST + import ProjectDescription + + func targetNames(in variable: String) -> [String] { + (processEnvironment[variable] ?? "").split(separator: ",").map(String.init) + } + + // Tuist suppresses warnings in every package; Xcode does so for remote packages only. The targets + // of the packages declared by path get theirs back: MachOSwiftSection always, the upstream + // packages in the local dependency mode. + let warningSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_WARNING_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // Tuist drops a package setting whose only condition is a trait. MachOSwiftSection enables + // swift-capstone's AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 for both the Swift wrapper and + // the C library that way. Without it the wrapper does not compile, and the C library would compile + // but support no architecture at all. + let restatedTraitDefinitions: [String: Settings] = [ + "Capstone": .settings(base: [ + "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"], + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + "Ccapstone": .settings(base: [ + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + ] + + let packageSettings = PackageSettings( + targetSettings: warningSettings.merging(restatedTraitDefinitions) { $1 }, + // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of + // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). + includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" + ) +#endif + +let package = Package( + name: "MachOSwiftSectionTuistDependencies", + dependencies: [ + .package(path: ".."), + // Stands in for swift-syntax in every macro package, as it does as a member of the native + // workspace: SwiftPM matches it by package identity. + .package(path: "../PrecompiledLibraries/swift-syntax"), + // Used only by MachOSwiftSection's tests. Tuist maps a test target only when every package + // its dependencies come from is declared here, with the requirement Package.swift gives it. + .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"), + ] + localPackageDependencies +) diff --git a/TuistScript.sh b/TuistScript.sh new file mode 100755 index 00000000..9765bb9a --- /dev/null +++ b/TuistScript.sh @@ -0,0 +1,789 @@ +#!/usr/bin/env bash +# TuistScript.sh — MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace: this +# package and the five upstream packages the native MachOSwiftSection.xcworkspace lists beside the +# checkout (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) +# built from source, every other dependency taken from Tuist's binary cache on this machine, and the +# packages' tests mapped into schemes. Releases, CI, `swift build` / `swift test` and the native +# workspace do not use it. Documentations/Internal/TuistDevelopment.md explains the setup. +# +# Usage: +# ./TuistScript.sh install # resolve the dependencies (tuist install) +# ./TuistScript.sh generate [--configuration ] +# # generate MachOSwiftSection-Tuist.xcworkspace +# # against the binary cache of one configuration +# # (Debug or Release; default: Debug) +# ./TuistScript.sh warm [--configuration ] # build the third-party dependencies into the +# # binary cache of one configuration, then generate +# ./TuistScript.sh build [--configuration ] [-- ] +# # generate, then build the swift-section scheme +# ./TuistScript.sh test [--configuration ] [-- ] +# # generate, then run the "MachOSwiftSection Tests" +# # scheme; exits with xcodebuild's exit code +# ./TuistScript.sh release # give up every checkout this one claimed: remove the +# # projects Tuist generated into them and the workspace +# ./TuistScript.sh --local-dependencies +# # from now on take the five upstream packages from +# # the checkouts beside this one (`.worktrees/` in a +# # worktree), uncommitted edits included +# ./TuistScript.sh --remote-dependencies +# # from now on take them at the lock file's pins again +# # (the default) +# ./TuistScript.sh --dry-run # print what would run +# ./TuistScript.sh --help +# +# The mode holds for the commands after the one that switched it ($LOCAL_DEPENDENCIES_MARKER records +# it). Each mode has its own dependency checkouts; switching resolves again. When the local mode is +# switched on, TUIST_LOCAL_PACKAGE_CHECKOUTS names another directory to take the upstream packages +# from, each in a directory named like the package. +# +# Tuist writes a project into every package declared by path — this checkout always, the upstream +# checkouts in the local mode — and RuntimeViewer's TuistScript.sh does the same into the same +# checkouts. Both scripts claim a checkout before generating into it (the claim record below), and +# refuse a checkout another one holds. +# +# Every command uses the Xcode that DEVELOPER_DIR or xcode-select names. Tuist's dependency +# checkouts, its binary cache and the build products live under /Volumes/DerivedData/MachOSwiftSection/ +# Tuist when that volume is mounted, and inside the checkout otherwise; TUIST_SCRIPT_ROOT names another +# directory. `warm`, `build` and `test` compile: run them through queued-build where that applies. +set -euo pipefail + +PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_REAL_PATH="$(cd "$PROJECT_DIR" && pwd -P)" +cd "$PROJECT_DIR" + +WORKSPACE="MachOSwiftSection-Tuist.xcworkspace" +NATIVE_WORKSPACE="MachOSwiftSection.xcworkspace" +PACKAGE_NAME="MachOSwiftSection" +BUILD_SCHEME="swift-section" +TEST_SCHEME="MachOSwiftSection Tests" +COMMAND_LINE_PROJECT_DIRECTORY="Tuist/CommandLine" +# The lock file SwiftPM and Xcode resolved for this checkout, not committed: Tuist starts from its pins. +SEED_LOCK_FILE="Package.resolved" +TUIST_PACKAGE_RESOLVED="Tuist/Package.resolved" +# Test targets no scheme lists: IntegrationTests is the maintainer's manual-inspection target. +UNLISTED_TEST_TARGETS="IntegrationTests" +# The local dependency mode: the file recording the directory the upstream packages are taken from +# (absent in the remote mode). +LOCAL_DEPENDENCIES_MARKER="Tuist/.local-dependencies" +# The claim record, shared with RuntimeViewer's TuistScript.sh. A claimed checkout's git directory +# holds $OWNER_RECORD_NAME: the owner checkout's path, the command that releases the claim there, and +# the project Tuist generated into the claimed checkout. The owner lists the real paths it holds in +# its $CLAIMED_CHECKOUTS_FILE; a claim is live only while that list holds the claimed checkout. +OWNER_RECORD_NAME="tuist-generated-project-owner" +CLAIMED_CHECKOUTS_FILE="Tuist/.claimed-checkouts" +RELEASE_COMMAND="./TuistScript.sh release" +# RuntimeViewer's record before the shared one: live while its owner's Tuist/.local-dependencies, +# joined with the package's name, is the claimed checkout. +LEGACY_OWNER_RECORD_NAME="runtimeviewer-tuist-local-dependencies" +EXCLUDE_COMMENT="# Generated by MachOSwiftSection's TuistScript.sh" + +COMMAND="" +CONFIGURATION="Debug" +DRY_RUN=false +REQUESTED_DEPENDENCY_MODE="" +EXTRA_ARGUMENTS=() + +fail() { echo "error: $*" >&2; exit 1; } +log() { echo "[TuistScript] $*"; } +warn() { echo "[TuistScript] warning: $*" >&2; } + +run() { + if $DRY_RUN; then + printf '+ '; printf '%q ' "$@"; echo + else + "$@" + fi +} + +# Runs a command with its output in a log under $LOG_DIR, echoing only its errors and last lines when +# it fails. For xcodebuild, whose output runs to thousands of lines. Returns the command's exit code. +run_logged() { + local log_name="$1"; shift + if $DRY_RUN; then + printf '+ '; printf '%q ' "$@"; printf '> %q\n' "$LOG_DIR/$log_name.log" + return 0 + fi + mkdir -p "$LOG_DIR" + local log_path="$LOG_DIR/$log_name.log" + log " log: $log_path" + local exit_code=0 + "$@" > "$log_path" 2>&1 || exit_code=$? + if [[ $exit_code -ne 0 ]]; then + grep -E 'error:|✘|failed' "$log_path" | head -20 | sed 's/^/ /' >&2 || true + tail -5 "$log_path" | sed 's/^/ /' >&2 + fi + return $exit_code +} + +# Runs a Tuist command with its output on the terminal as well as in a log under $LOG_DIR. On a +# terminal it runs under script(1), which keeps Tuist's colors; anywhere else through tee. Returns the +# command's own exit code either way. +run_tuist() { + local log_name="$1"; shift + if $DRY_RUN; then + printf '+ '; printf '%q ' "$@"; printf '| tee %q\n' "$LOG_DIR/$log_name.log" + return 0 + fi + mkdir -p "$LOG_DIR" + local log_path="$LOG_DIR/$log_name.log" + log " log: $log_path" + local exit_code=0 + if [[ -t 0 && -t 1 ]]; then + script -q "$log_path" "$@" || exit_code=$? + else + "$@" 2>&1 | tee "$log_path" || exit_code=${PIPESTATUS[0]} + fi + return $exit_code +} + +while [[ $# -gt 0 ]]; do + case "$1" in + install|generate|warm|build|test|release) + [[ -z "$COMMAND" ]] || fail "one command at a time: $COMMAND, $1" + COMMAND="$1"; shift;; + --configuration) + [[ $# -ge 2 ]] || fail "--configuration needs a name (Debug or Release)" + CONFIGURATION="$2"; shift 2;; + --local-dependencies|--remote-dependencies) + [[ -z "$REQUESTED_DEPENDENCY_MODE" ]] || fail "one of --local-dependencies and --remote-dependencies at a time" + REQUESTED_DEPENDENCY_MODE="${1#--}"; REQUESTED_DEPENDENCY_MODE="${REQUESTED_DEPENDENCY_MODE%-dependencies}"; shift;; + --dry-run) DRY_RUN=true; shift;; + --) shift; EXTRA_ARGUMENTS=("$@"); break;; + -h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; exit 0;; + *) fail "unknown argument: $1 (see --help)";; + esac +done +[[ -n "$COMMAND" ]] || fail "no command given (see --help)" +case "$CONFIGURATION" in + Debug|Release) ;; + *) fail "unknown configuration: $CONFIGURATION (expected Debug or Release)";; +esac +if [[ ${#EXTRA_ARGUMENTS[@]} -gt 0 && "$COMMAND" != build && "$COMMAND" != test ]]; then + fail "only build and test pass arguments on to xcodebuild" +fi + +# One directory per checkout: two worktrees must not share Tuist's dependency checkouts, which record +# where the packages declared by path are. The binary cache is shared; it is keyed by content. +CHECKOUT_NAME="$(basename "$PROJECT_DIR")-$(printf '%s' "$PROJECT_DIR" | shasum | cut -c1-8)" +if [[ -n "${TUIST_SCRIPT_ROOT:-}" ]]; then + STORAGE_ROOT="$TUIST_SCRIPT_ROOT" +elif [[ -d "/Volumes/DerivedData" ]]; then + STORAGE_ROOT="/Volumes/DerivedData/MachOSwiftSection/Tuist" +else + STORAGE_ROOT="" +fi +if [[ -n "$STORAGE_ROOT" ]]; then + export TUIST_XDG_CACHE_HOME="$STORAGE_ROOT/Cache" + export TUIST_CACHE_WARM_SCRATCH_DIRECTORY="$STORAGE_ROOT/WarmScratch/$CHECKOUT_NAME" + WORK_ROOT="$STORAGE_ROOT/Work/$CHECKOUT_NAME" +else + WORK_ROOT="$PROJECT_DIR/DerivedData/Tuist" +fi +LOG_DIR="${LOG_DIR:-$PROJECT_DIR/Products/Logs/Tuist}" +# What the dependencies were last resolved for: the mode and the manifests. The two modes share +# Tuist/Package.resolved, so running in the other one, or after a manifest changed, resolves again. +INSTALLED_DEPENDENCIES_STAMP="$WORK_ROOT/InstalledDependencies" +# Every package's evaluated manifest, read once per install (dump_manifests). +MANIFESTS_DIRECTORY="$WORK_ROOT/Manifests" + +# The manifests choose local checkouts or remote packages by this variable, for every package at +# once, swift-capstone included. The upstream packages come from their checkouts through +# --local-dependencies instead. +if [[ -n "${USING_LOCAL_DEPENDENCIES:-}" ]]; then + warn "ignoring USING_LOCAL_DEPENDENCIES=$USING_LOCAL_DEPENDENCIES; --local-dependencies takes the upstream packages from their checkouts" + unset USING_LOCAL_DEPENDENCIES +fi + +# The Tuist that mise.toml pins: through mise when it is installed, from PATH otherwise. +PINNED_TUIST_VERSION="$(sed -n 's/^tuist *= *"\(.*\)"$/\1/p' mise.toml)" +if command -v mise >/dev/null 2>&1; then + TUIST=(mise exec -- tuist) +elif command -v tuist >/dev/null 2>&1; then + TUIST=(tuist) +else + fail "Tuist not found. Install mise (https://mise.jdx.dev) and run \`mise install\` here, or install Tuist $PINNED_TUIST_VERSION." +fi +if ! $DRY_RUN; then + tuist_version="$("${TUIST[@]}" version 2>/dev/null | tail -1)" || fail "\`${TUIST[*]} version\` failed; run \`mise install\` here" + [[ "$tuist_version" == "$PINNED_TUIST_VERSION" ]] \ + || fail "Tuist $tuist_version found, mise.toml pins $PINNED_TUIST_VERSION; run \`mise install\` here" +fi + +command -v xcodebuild >/dev/null 2>&1 || fail "xcodebuild not found" +command -v python3 >/dev/null 2>&1 || fail "python3 not found (the script reads the manifests with it)" + +# The upstream packages the local mode takes from their checkouts: the members of the native +# workspace beside the checkout (`container:../`), so a package added there is local here too. +read_local_package_names() { + python3 - "$PROJECT_DIR/$NATIVE_WORKSPACE/contents.xcworkspacedata" <<'PYTHON' +import sys +import xml.etree.ElementTree as ElementTree + +prefix = "container:../" +for element in ElementTree.parse(sys.argv[1]).getroot().iter("FileRef"): + location = element.get("location", "") + if location.startswith(prefix) and "/" not in location[len(prefix):]: + print(location[len(prefix):]) +PYTHON +} + +LOCAL_PACKAGE_NAMES=() +local_package_names_output="$(read_local_package_names)" \ + || fail "cannot read which packages $NATIVE_WORKSPACE takes from beside the checkout" +for package_name in $local_package_names_output; do + LOCAL_PACKAGE_NAMES+=("$package_name") +done +[[ ${#LOCAL_PACKAGE_NAMES[@]} -gt 0 ]] || fail "$NATIVE_WORKSPACE takes no package from beside the checkout" + +# --- The claim record ----------------------------------------------------------------------------- + +git_directory_of() { # $1: a checkout; prints nothing when it is not a git checkout + git -C "$1" rev-parse --absolute-git-dir 2>/dev/null || true +} + +real_path_of() { + (cd "$1" 2>/dev/null && pwd -P) || true +} + +# Prints "\t" for a live claim another checkout holds on $1 (a checkout), +# $2 being the package's name; prints nothing when none does. +foreign_live_claim() { + local checkout="$1" package_name="$2" git_directory checkout_real_path owner release_command owner_directory + git_directory="$(git_directory_of "$checkout")" + [[ -n "$git_directory" ]] || return 0 + checkout_real_path="$(real_path_of "$checkout")" + if [[ -f "$git_directory/$OWNER_RECORD_NAME" ]]; then + owner="$(sed -n 1p "$git_directory/$OWNER_RECORD_NAME")" + release_command="$(sed -n 2p "$git_directory/$OWNER_RECORD_NAME")" + if [[ -n "$owner" && "$(real_path_of "$owner")" != "$PROJECT_REAL_PATH" ]] \ + && grep -qxF -- "$checkout_real_path" "$owner/$CLAIMED_CHECKOUTS_FILE" 2>/dev/null; then + printf '%s\t%s\n' "$owner" "${release_command:-its TuistScript.sh}" + return 0 + fi + fi + if [[ -f "$git_directory/$LEGACY_OWNER_RECORD_NAME" ]]; then + owner="$(sed -n 1p "$git_directory/$LEGACY_OWNER_RECORD_NAME")" + if [[ -n "$owner" && "$(real_path_of "$owner")" != "$PROJECT_REAL_PATH" ]]; then + owner_directory="$(cat "$owner/Tuist/.local-dependencies" 2>/dev/null || true)" + if [[ -n "$owner_directory" && "$(real_path_of "$owner_directory/$package_name")" == "$checkout_real_path" ]]; then + printf '%s\t%s\n' "$owner" "./TuistScript.sh generate --remote-dependencies" + fi + fi + fi +} + +# Claims $1 (a checkout) for this one before Tuist generates $3 into it; $2 is the package's name. +# Refuses a checkout another checkout's Tuist workspace holds and a project file git tracks. An upstream +# checkout's repository gets the generated files in its info/exclude, which stays on this Mac; this +# checkout ignores its own in .gitignore. +claim_checkout() { + local checkout="$1" package_name="$2" project_name="$3" claim git_directory checkout_real_path exclude_file pattern + git_directory="$(git_directory_of "$checkout")" + [[ -n "$git_directory" ]] || return 0 + claim="$(foreign_live_claim "$checkout" "$package_name")" + if [[ -n "$claim" ]]; then + fail "$checkout is in the Tuist workspace of ${claim%%$'\t'*}, and generating here would replace the project that workspace uses; run \`${claim#*$'\t'}\` there first" + fi + if git -C "$checkout" ls-files --error-unmatch "$project_name.xcodeproj" >/dev/null 2>&1; then + fail "$checkout tracks $project_name.xcodeproj, which Tuist would overwrite" + fi + checkout_real_path="$(real_path_of "$checkout")" + if $DRY_RUN; then + log "would claim $checkout_real_path ($project_name.xcodeproj)" + return 0 + fi + printf '%s\n%s\n%s\n' "$PROJECT_DIR" "$RELEASE_COMMAND" "$project_name.xcodeproj" > "$git_directory/$OWNER_RECORD_NAME" + mkdir -p "$(dirname "$CLAIMED_CHECKOUTS_FILE")" + grep -qxF -- "$checkout_real_path" "$CLAIMED_CHECKOUTS_FILE" 2>/dev/null \ + || printf '%s\n' "$checkout_real_path" >> "$CLAIMED_CHECKOUTS_FILE" + if [[ "$checkout_real_path" != "$PROJECT_REAL_PATH" ]]; then + exclude_file="$(git -C "$checkout" rev-parse --path-format=absolute --git-path info/exclude)" + mkdir -p "$(dirname "$exclude_file")" + for pattern in "$EXCLUDE_COMMENT" "/$project_name.xcodeproj/" "/Derived/"; do + grep -qxF -- "$pattern" "$exclude_file" 2>/dev/null || printf '%s\n' "$pattern" >> "$exclude_file" + done + fi +} + +# Gives up the claim on $1 (a checkout's real path) when this checkout holds it: removes the project +# Tuist generated there unless git tracks it, so that opening the folder in Xcode opens its +# Package.swift again, and the record. Derived/ stays; it changes nothing for Xcode. +release_checkout() { + local checkout_real_path="$1" git_directory project_file_name remaining + git_directory="$(git_directory_of "$checkout_real_path")" + if [[ -n "$git_directory" && -f "$git_directory/$OWNER_RECORD_NAME" ]] \ + && [[ "$(real_path_of "$(sed -n 1p "$git_directory/$OWNER_RECORD_NAME")")" == "$PROJECT_REAL_PATH" ]]; then + project_file_name="$(sed -n 3p "$git_directory/$OWNER_RECORD_NAME")" + if [[ -n "$project_file_name" && "$project_file_name" == *.xcodeproj ]] \ + && ! git -C "$checkout_real_path" ls-files --error-unmatch "$project_file_name" >/dev/null 2>&1; then + run rm -rf "$checkout_real_path/$project_file_name" + fi + run rm -f "$git_directory/$OWNER_RECORD_NAME" + fi + if [[ -f "$CLAIMED_CHECKOUTS_FILE" ]] && ! $DRY_RUN; then + remaining="$(grep -vxF -- "$checkout_real_path" "$CLAIMED_CHECKOUTS_FILE" || true)" + if [[ -n "$remaining" ]]; then + printf '%s\n' "$remaining" > "$CLAIMED_CHECKOUTS_FILE" + else + rm -f "$CLAIMED_CHECKOUTS_FILE" + fi + fi +} + +# Gives up every claim on a checkout other than this one: the upstream checkouts of the local mode. +release_upstream_checkouts() { + local checkout_real_path + [[ -f "$CLAIMED_CHECKOUTS_FILE" ]] || return 0 + while IFS= read -r checkout_real_path; do + [[ -n "$checkout_real_path" && "$checkout_real_path" != "$PROJECT_REAL_PATH" ]] || continue + release_checkout "$checkout_real_path" + done < <(cat "$CLAIMED_CHECKOUTS_FILE") +} + +# --- The dependency mode -------------------------------------------------------------------------- + +# Points this process at the dependencies of one mode ($1: local or remote). Each mode resolves into a +# directory of its own, so switching back and forth keeps both sets of checkouts. +use_dependency_mode() { + CURRENT_DEPENDENCY_MODE="$1" + local directory_suffix="" + if [[ "$1" == local ]]; then + directory_suffix="-LocalDependencies" + export TUIST_LOCAL_PACKAGE_CHECKOUTS="$LOCAL_DEPENDENCIES_DIRECTORY" + export TUIST_LOCAL_PACKAGE_NAMES + TUIST_LOCAL_PACKAGE_NAMES="$(IFS=,; printf '%s' "${LOCAL_PACKAGE_NAMES[*]}")" + else + unset TUIST_LOCAL_PACKAGE_CHECKOUTS TUIST_LOCAL_PACKAGE_NAMES + fi + if [[ -n "$STORAGE_ROOT" ]]; then + export SWIFTPM_BUILD_DIR="$STORAGE_ROOT/Dependencies/$CHECKOUT_NAME$directory_suffix" + elif [[ -n "$directory_suffix" ]]; then + export SWIFTPM_BUILD_DIR="$PROJECT_DIR/Tuist/.build$directory_suffix" + else + unset SWIFTPM_BUILD_DIR + fi + DEPENDENCIES_DIRECTORY="${SWIFTPM_BUILD_DIR:-$PROJECT_DIR/Tuist/.build}" +} + +# The mode from now on: what --local-dependencies or --remote-dependencies asks for, or what +# $LOCAL_DEPENDENCIES_MARKER recorded the last time. +RECORDED_LOCAL_DEPENDENCIES_DIRECTORY="$(cat "$LOCAL_DEPENDENCIES_MARKER" 2>/dev/null || true)" +case "$REQUESTED_DEPENDENCY_MODE" in + local) LOCAL_DEPENDENCIES_DIRECTORY="${TUIST_LOCAL_PACKAGE_CHECKOUTS:-$(dirname "$PROJECT_DIR")}";; + remote) LOCAL_DEPENDENCIES_DIRECTORY="";; + *) LOCAL_DEPENDENCIES_DIRECTORY="$RECORDED_LOCAL_DEPENDENCIES_DIRECTORY";; +esac +if [[ -n "$LOCAL_DEPENDENCIES_DIRECTORY" ]]; then + resolved_directory="$(cd "$LOCAL_DEPENDENCIES_DIRECTORY" 2>/dev/null && pwd)" \ + || fail "no directory $LOCAL_DEPENDENCIES_DIRECTORY to take the local dependencies from (./TuistScript.sh --remote-dependencies goes back to the remote packages)" + LOCAL_DEPENDENCIES_DIRECTORY="$resolved_directory" + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + [[ -f "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name/Package.swift" ]] \ + || fail "no package $package_name in $LOCAL_DEPENDENCIES_DIRECTORY. The local dependency mode takes the packages $NATIVE_WORKSPACE lists beside the checkout, from directories with the same names." + done + DEPENDENCY_MODE=local +else + DEPENDENCY_MODE=remote +fi + +# A switch gives up the upstream checkouts the old mode generated projects into and records the new +# mode; ensure_dependencies resolves again before Tuist next runs. +if [[ "$LOCAL_DEPENDENCIES_DIRECTORY" != "$RECORDED_LOCAL_DEPENDENCIES_DIRECTORY" ]]; then + log "switching to the $DEPENDENCY_MODE dependencies" + release_upstream_checkouts + if $DRY_RUN; then + log "would record the $DEPENDENCY_MODE mode in $LOCAL_DEPENDENCIES_MARKER" + elif [[ "$DEPENDENCY_MODE" == local ]]; then + printf '%s\n' "$LOCAL_DEPENDENCIES_DIRECTORY" > "$LOCAL_DEPENDENCIES_MARKER" + else + rm -f "$LOCAL_DEPENDENCIES_MARKER" + fi +fi +use_dependency_mode "$DEPENDENCY_MODE" + +# The manifests evaluate MACHO_SWIFT_SECTION_SILENT_TEST; the hand-written test target reads it as +# TUIST_SILENT_TEST, the only form a Tuist manifest sees. +if [[ "${MACHO_SWIFT_SECTION_SILENT_TEST:-}" == "1" ]]; then + export TUIST_SILENT_TEST=1 +else + unset TUIST_SILENT_TEST +fi + +log "command=$COMMAND configuration=$CONFIGURATION tuist=$PINNED_TUIST_VERSION" +log "xcode: $(xcodebuild -version | tr '\n' ' ')(${DEVELOPER_DIR:-$(xcode-select -p)})" +log "storage: ${STORAGE_ROOT:-inside the checkout} (dependencies: $DEPENDENCIES_DIRECTORY)" +if [[ "$DEPENDENCY_MODE" == local ]]; then + log "upstream packages: the checkouts in $LOCAL_DEPENDENCIES_DIRECTORY (${LOCAL_PACKAGE_NAMES[*]})" +else + log "upstream packages: the lock file's pins (--local-dependencies takes them from their checkouts)" +fi + +# --- Resolving ----------------------------------------------------------------------------------- + +# Compares the pins of Tuist/Package.resolved with those of the seed lock file, leaving out the +# packages named in the arguments: swift-syntax, which Tuist takes from PrecompiledLibraries, and the +# local mode's packages, which have no pin when they are declared by path. Prints the differences and +# returns 1 when there are any. +compare_lock_files() { + python3 - "$TUIST_PACKAGE_RESOLVED" "$SEED_LOCK_FILE" "$@" <<'PYTHON' +import json +import sys + +def read_pins(path): + with open(path) as handle: + document = json.load(handle) + pins = {} + for pin in document.get("pins", []): + state = pin.get("state", {}) + pins[pin["identity"]] = state.get("version") or f"{state.get('branch')}@{state.get('revision', '')[:8]}" + return pins + +tuist_path, seed_path = sys.argv[1:3] +left_out = {package_name.lower() for package_name in sys.argv[3:]} +try: + tuist_pins, seed_pins = read_pins(tuist_path), read_pins(seed_path) +except OSError as error: + print(f" cannot compare the lock files: {error}") + sys.exit(1) +differences = [ + f" {identity}: Tuist {tuist_pins.get(identity, 'absent')}, {seed_path} {seed_pins.get(identity, 'absent')}" + for identity in sorted((tuist_pins.keys() | seed_pins.keys()) - left_out) + if tuist_pins.get(identity) != seed_pins.get(identity) +] +if differences: + print("\n".join(differences)) + sys.exit(1) +PYTHON +} + +# What $INSTALLED_DEPENDENCIES_STAMP says once the current mode's dependencies are resolved: the mode, +# and the manifests and seed lock file the resolution read. +installed_dependencies_description() { + local package_name + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + echo "local $LOCAL_DEPENDENCIES_DIRECTORY" + else + echo "remote" + fi + echo "silent test: ${MACHO_SWIFT_SECTION_SILENT_TEST:-}" + shasum Tuist/Package.swift Package.swift 2>/dev/null || true + [[ -f "$SEED_LOCK_FILE" ]] && shasum "$SEED_LOCK_FILE" + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + shasum "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name/Package.swift" + done + fi +} + +install_dependencies() { + # Tuist/Package.resolved is not committed. Every install starts it from the lock file SwiftPM + # resolved for this checkout, so Tuist resolves the versions `swift build` and the native + # workspace use rather than the newest ones. + if [[ -f "$SEED_LOCK_FILE" ]]; then + run cp "$SEED_LOCK_FILE" "$TUIST_PACKAGE_RESOLVED" + else + warn "no $SEED_LOCK_FILE to start from; Tuist resolves the newest versions the manifests allow" + run rm -f "$TUIST_PACKAGE_RESOLVED" + fi + log "Resolving the $CURRENT_DEPENDENCY_MODE dependencies (tuist install)" + # The manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block leaves out or gives a product to the tests + # Tuist would reject; Tuist records each manifest as it evaluates it here. + run_tuist "install" env TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 "${TUIST[@]}" install || fail "tuist install failed" + if ! $DRY_RUN; then + if [[ -f "$SEED_LOCK_FILE" ]]; then + local differences + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + differences="$(compare_lock_files swift-syntax "${LOCAL_PACKAGE_NAMES[@]}")" || true + else + differences="$(compare_lock_files swift-syntax)" || true + fi + if [[ -n "$differences" ]]; then + warn "$TUIST_PACKAGE_RESOLVED resolved other versions than $SEED_LOCK_FILE:" + printf '%s\n' "$differences" >&2 + warn "usually another Xcode resolved one of them: some packages pick their manifest by Swift version" + fi + fi + mkdir -p "$WORK_ROOT" + dump_manifests + installed_dependencies_description > "$INSTALLED_DEPENDENCIES_STAMP" + fi +} + +# Evaluates the manifest of every package in the graph the way Tuist did, with +# TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, into $MANIFESTS_DIRECTORY: this package and the upstream ones +# (from their checkouts in the local mode, from Tuist's checkouts in the remote mode), and every +# third-party checkout. $MANIFESTS_DIRECTORY/packages.tsv lists them as +# "\t\t", the role being own-path, own-remote or third-party. +dump_manifests() { + local package_name identity directory checkout + run rm -rf "$MANIFESTS_DIRECTORY" + mkdir -p "$MANIFESTS_DIRECTORY" + { + printf '%s\t%s\t%s\n' "$(lowercased "$PACKAGE_NAME")" own-path "$PROJECT_DIR" + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + printf '%s\t%s\t%s\n' "$(lowercased "$package_name")" own-path "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name" + else + printf '%s\t%s\t%s\n' "$(lowercased "$package_name")" own-remote "$DEPENDENCIES_DIRECTORY/checkouts/$package_name" + fi + done + for checkout in "$DEPENDENCIES_DIRECTORY"/checkouts/*; do + [[ -f "$checkout/Package.swift" ]] || continue + identity="$(lowercased "$(basename "$checkout")")" + is_local_package_name "$identity" || printf '%s\t%s\t%s\n' "$identity" third-party "$checkout" + done + } > "$MANIFESTS_DIRECTORY/packages.tsv" + log "Reading the manifests of $(wc -l < "$MANIFESTS_DIRECTORY/packages.tsv" | tr -d ' ') packages" + # Eight at a time; each is a manifest evaluation, not a build. + cut -f1,3 "$MANIFESTS_DIRECTORY/packages.tsv" | tr '\t' '\n' | tr '\n' '\0' \ + | xargs -0 -n 2 -P 8 /bin/bash -c ' + TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 swift package --package-path "$2" --scratch-path "$0/Scratch/$1" dump-package \ + > "$0/$1.json" 2> "$0/$1.err" || rm -f "$0/$1.json" + ' "$MANIFESTS_DIRECTORY" + while IFS=$'\t' read -r identity _ directory; do + if [[ ! -f "$MANIFESTS_DIRECTORY/$identity.json" ]]; then + cat "$MANIFESTS_DIRECTORY/$identity.err" >&2 2>/dev/null || true + fail "cannot read the manifest of $directory" + fi + done < <(grep -v $'\tthird-party\t' "$MANIFESTS_DIRECTORY/packages.tsv") +} + +lowercased() { + printf '%s' "$1" | tr '[:upper:]' '[:lower:]' +} + +is_local_package_name() { # $1: an identity + local package_name + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + [[ "$(lowercased "$package_name")" == "$1" ]] && return 0 + done + return 1 +} + +# Resolves the dependencies unless they were last resolved for the current mode and manifests. +ensure_dependencies() { + if [[ ! -d "$DEPENDENCIES_DIRECTORY/checkouts" || ! -f "$MANIFESTS_DIRECTORY/packages.tsv" ]]; then + install_dependencies + elif [[ "$(cat "$INSTALLED_DEPENDENCIES_STAMP" 2>/dev/null || true)" != "$(installed_dependencies_description)" ]]; then + log "the dependencies were last resolved for another mode or other manifests" + install_dependencies + fi +} + +# --- Reading the manifests ------------------------------------------------------------------------ + +# Reads $MANIFESTS_DIRECTORY and sets what the Tuist manifests read: the targets that stay source, the +# targets that get their warnings back, the test targets each scheme lists, and whether the tests can +# be mapped at all. Tuist maps the tests of every package declared by path or of none, and rejects a +# test that depends on an executable target or on a target no product contains; the manifests' block +# takes both away, so one left means that package's manifest has no block yet (an upstream checkout +# at an older commit, say), and the tests stay out this time. +read_manifests() { + $DRY_RUN && return 0 + local key value analysis_path="$WORK_ROOT/ManifestAnalysis.txt" + python3 - "$MANIFESTS_DIRECTORY" "$(lowercased "$PACKAGE_NAME")" "$UNLISTED_TEST_TARGETS" > "$analysis_path" <<'PYTHON' \ + || fail "cannot read the manifests in $MANIFESTS_DIRECTORY; run ./TuistScript.sh install" +import json +import os +import sys + +manifests_directory, own_identity, unlisted_tests = sys.argv[1:4] +unlisted_tests = set(unlisted_tests.split(",")) + +packages = [] +with open(os.path.join(manifests_directory, "packages.tsv")) as handle: + for line in handle: + identity, role, directory = line.rstrip("\n").split("\t") + packages.append((identity, role, directory)) + +def load(identity): + with open(os.path.join(manifests_directory, f"{identity}.json")) as handle: + return json.load(handle) + +def dependency_name(dependency): + for kind in ("target", "byName"): + if kind in dependency: + return dependency[kind][0] + return None + +source_targets, warning_targets, test_entries, rejected = [], [], [], [] +own_target_names = set() +for identity, role, directory in packages: + if role == "third-party": + continue + manifest = load(identity) + targets = manifest["targets"] + names = [target["name"] for target in targets] + # Tuist names the resource bundle of a target with resources _. + names += [f"{manifest['name']}_{target['name']}" for target in targets if target.get("resources")] + own_target_names.update(names) + source_targets += names + if role != "own-path": + continue + warning_targets += [target["name"] for target in targets if target["type"] != "test"] + executable_names = {target["name"] for target in targets if target["type"] == "executable"} + product_target_names = { + name + for product in manifest["products"] if "library" in product["type"] + for name in product["targets"] + } + regular_names = {target["name"] for target in targets if target["type"] == "regular"} + tests = [target for target in targets if target["type"] == "test"] + for test in tests: + for dependency in test["dependencies"]: + name = dependency_name(dependency) + if name in executable_names: + rejected.append(f"{manifest['name']}'s {test['name']}, which depends on the executable target {name}") + elif name in regular_names and name not in product_target_names: + rejected.append(f"{manifest['name']}'s {test['name']}, which depends on {name}, a target no product contains") + listed = [test["name"] for test in tests if test["name"] not in unlisted_tests] + if listed: + test_entries.append(f"{'.' if identity == own_identity else directory}={','.join(listed)}") + +# Cache exceptions match target names in every package: a third-party target named like one of ours +# stays source too. +for identity, role, directory in packages: + if role != "third-party": + continue + try: + manifest = load(identity) + except OSError: + print(f"UNREAD={directory}") + continue + shared = sorted(own_target_names & {target["name"] for target in manifest["targets"]}) + if shared: + print(f"SHARED_NAME={manifest['name']} has targets named like ones that stay source ({', '.join(shared)}); they stay source too") + +print("SOURCE_TARGETS=" + ",".join(source_targets)) +print("WARNING_TARGETS=" + ",".join(warning_targets)) +print("TEST_TARGETS=" + ";".join(test_entries)) +for reason in rejected: + print("REJECTED=" + reason) +PYTHON + TUIST_SOURCE_TARGET_NAMES="" + TUIST_WARNING_TARGET_NAMES="" + TUIST_PACKAGE_TEST_TARGETS="" + TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 + while IFS='=' read -r key value; do + case "$key" in + SOURCE_TARGETS) TUIST_SOURCE_TARGET_NAMES="$value";; + WARNING_TARGETS) TUIST_WARNING_TARGET_NAMES="$value";; + TEST_TARGETS) TUIST_PACKAGE_TEST_TARGETS="$value";; + REJECTED) + warn "Tuist would reject $value" + TUIST_MAPS_LOCAL_PACKAGE_TESTS=0;; + SHARED_NAME) warn "$value";; + UNREAD) warn "cannot read the manifest of $value; a target of it named like one of ours would stay source unnoticed";; + esac + done < "$analysis_path" + if [[ "$TUIST_MAPS_LOCAL_PACKAGE_TESTS" != 1 ]]; then + warn "the tests stay out of the workspace this time. Each manifest above needs the TUIST_MAPS_LOCAL_PACKAGE_TESTS block MachOSwiftSection's Package.swift ends with (Documentations/Internal/TuistDevelopment.md)." + TUIST_PACKAGE_TEST_TARGETS="" + fi + export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_MAPS_LOCAL_PACKAGE_TESTS +} + +# --- Commands ------------------------------------------------------------------------------------- + +claim_checkouts() { + local package_name + claim_checkout "$PROJECT_DIR" "$PACKAGE_NAME" "$PACKAGE_NAME" + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + claim_checkout "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name" "$package_name" \ + "$(local_package_project_name "$package_name")" + done + fi +} + +# The name Tuist gives the project it generates into an upstream checkout: the package's own name. +local_package_project_name() { + python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["name"])' \ + "$MANIFESTS_DIRECTORY/$(lowercased "$1").json" 2>/dev/null || printf '%s\n' "$1" +} + +# Generates the workspace against the binary cache of one configuration ($1, $CONFIGURATION by +# default). +generate_workspace() { + local configuration="${1:-$CONFIGURATION}" + ensure_dependencies + read_manifests + claim_checkouts + log "Generating $WORKSPACE ($configuration, $CURRENT_DEPENDENCY_MODE dependencies)" + run_tuist "generate-$configuration" "${TUIST[@]}" generate --no-open --configuration "$configuration" \ + || fail "tuist generate failed" +} + +warm_cache() { + ensure_dependencies + read_manifests + claim_checkouts + if [[ -n "$STORAGE_ROOT" ]]; then + # Tuist refuses to start with anything left in it from an earlier run, and never empties it. + run rm -rf "$TUIST_CACHE_WARM_SCRATCH_DIRECTORY" + run mkdir -p "$TUIST_CACHE_WARM_SCRATCH_DIRECTORY" + fi + log "Building the third-party dependencies into the binary cache ($CONFIGURATION)" + # Without --cache-profile, `tuist cache warm` ignores the default profile in Tuist.swift and caches + # every target it can, ours included. + run_tuist "warm-$CONFIGURATION" "${TUIST[@]}" cache warm --configuration "$CONFIGURATION" \ + --cache-profile development --no-upload \ + || fail "tuist cache warm failed" + # A workspace generated before the warm-up still builds the dependencies from source. + generate_workspace "$CONFIGURATION" +} + +xcodebuild_arguments() { + printf '%s\n' -workspace "$WORKSPACE" -configuration "$CONFIGURATION" -destination 'platform=macOS' \ + -derivedDataPath "$WORK_ROOT/DerivedData/$CONFIGURATION" -skipPackagePluginValidation -skipMacroValidation +} + +build_command() { + generate_workspace + local arguments=() + while IFS= read -r argument; do arguments+=("$argument"); done < <(xcodebuild_arguments) + log "Building $BUILD_SCHEME ($CONFIGURATION)" + run_logged "build-$CONFIGURATION" xcodebuild build -scheme "$BUILD_SCHEME" "${arguments[@]}" \ + ${EXTRA_ARGUMENTS[@]+"${EXTRA_ARGUMENTS[@]}"} || fail "the build failed" + $DRY_RUN || log "swift-section: $WORK_ROOT/DerivedData/$CONFIGURATION/Build/Products/$CONFIGURATION/swift-section" +} + +test_command() { + generate_workspace + [[ -n "${TUIST_PACKAGE_TEST_TARGETS:-}" ]] || $DRY_RUN \ + || fail "the workspace has no test scheme this time (see the warning above)" + local arguments=() result_bundle exit_code=0 + while IFS= read -r argument; do arguments+=("$argument"); done < <(xcodebuild_arguments) + result_bundle="$WORK_ROOT/TestResults/$(date +%Y%m%d-%H%M%S).xcresult" + log "Testing $TEST_SCHEME ($CONFIGURATION)" + log " result bundle: $result_bundle" + run_logged "test-$CONFIGURATION" xcodebuild test -scheme "$TEST_SCHEME" "${arguments[@]}" \ + -resultBundlePath "$result_bundle" ${EXTRA_ARGUMENTS[@]+"${EXTRA_ARGUMENTS[@]}"} || exit_code=$? + if ! $DRY_RUN && [[ -d "$result_bundle" ]]; then + xcrun xcresulttool get test-results summary --path "$result_bundle" --compact 2>/dev/null \ + | python3 -c 'import json, sys; summary = json.load(sys.stdin); print("[TuistScript] result: {result}, {passedTests} passed, {failedTests} failed, {skippedTests} skipped".format(**summary))' \ + || true + fi + exit $exit_code +} + +release_command() { + local checkout_real_path + if [[ -f "$CLAIMED_CHECKOUTS_FILE" ]]; then + while IFS= read -r checkout_real_path; do + [[ -n "$checkout_real_path" ]] && release_checkout "$checkout_real_path" + done < <(cat "$CLAIMED_CHECKOUTS_FILE") + fi + run rm -f "$CLAIMED_CHECKOUTS_FILE" + run rm -rf "$WORKSPACE" "$COMMAND_LINE_PROJECT_DIRECTORY/MachOSwiftSectionCommandLine.xcodeproj" + log "released every checkout this one claimed; ./TuistScript.sh generate claims them again" +} + +case "$COMMAND" in + install) install_dependencies;; + generate) generate_workspace;; + warm) warm_cache;; + build) build_command;; + test) test_command;; + release) release_command;; +esac diff --git a/Workspace.swift b/Workspace.swift new file mode 100644 index 00000000..88de0fc7 --- /dev/null +++ b/Workspace.swift @@ -0,0 +1,46 @@ +import ProjectDescription + +// MachOSwiftSection-Tuist.xcworkspace, the development-only workspace Tuist generates beside the +// native MachOSwiftSection.xcworkspace (Documentations/Internal/TuistDevelopment.md). +// +// The packages' test targets live in the projects Tuist converts from their Package.swift files, which +// only a workspace scheme can reference. TuistScript.sh lists them in TUIST_PACKAGE_TEST_TARGETS as +// "=,;…", one entry per package whose tests are mapped: +// MachOSwiftSection always (directory "."), the upstream packages in the local dependency mode +// (absolute directories). IntegrationTests, the maintainer's manual-inspection target, is never listed. +let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets + .getString(default: "") + .split(separator: ";") + .compactMap { entry in + let parts = entry.split(separator: "=", maxSplits: 1).map(String.init) + guard parts.count == 2 else { return nil } + return (parts[0], parts[1].split(separator: ",").map(String.init)) + } + +func packageName(ofDirectory directory: String) -> String { + directory == "." ? "MachOSwiftSection" : String(directory.split(separator: "/").last ?? Substring(directory)) +} + +func projectPath(ofDirectory directory: String) -> Path { + directory.hasPrefix("/") ? .path(directory) : .relativeToRoot(directory) +} + +let workspace = Workspace( + name: "MachOSwiftSection-Tuist", + projects: ["Tuist/CommandLine"], + schemes: packageTestTargets.map { entry in + var testableTargets = entry.targets.map { targetName in + TestableTarget.testableTarget( + target: .project(path: projectPath(ofDirectory: entry.directory), target: targetName), + parallelization: .swiftTestingOnly + ) + } + if entry.directory == "." { + testableTargets.append(.testableTarget( + target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"), + parallelization: .swiftTestingOnly + )) + } + return .scheme(name: "\(packageName(ofDirectory: entry.directory)) Tests", testAction: .targets(testableTargets)) + } +) diff --git a/mise.toml b/mise.toml new file mode 100644 index 00000000..bac4a79e --- /dev/null +++ b/mise.toml @@ -0,0 +1,5 @@ +# The Tuist that generates MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +# (Documentations/Internal/TuistDevelopment.md). Releases, CI and `swift build` / `swift test` do not +# use it. RuntimeViewer pins the same version. +[tools] +tuist = "4.210.0" From ee95c009a391c36689b46edc3c8530f58dacda5f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:24:23 +0800 Subject: [PATCH 003/175] fix: build the Tuist workspace's swift-section for macOS 12 Tuist builds swift-argument-parser for the macOS 12 it declares, and a 10.15 swift-section cannot import it there. Proposal: draft-tuist-workspace --- Tuist/CommandLine/Project.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift index 794f412f..72df2619 100644 --- a/Tuist/CommandLine/Project.swift +++ b/Tuist/CommandLine/Project.swift @@ -25,6 +25,10 @@ let commandLineDependencies: [TargetDependency] = [ .external(name: "ArgumentParser"), ] +// Tuist builds swift-argument-parser for macOS 12, the minimum that package declares; the package's +// own 10.15 does not reach the executable here the way SwiftPM's build of it does. +let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") + let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] // MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; @@ -41,7 +45,7 @@ let project = Project( destinations: .macOS, product: .commandLineTool, bundleId: "com.machoswiftsection.swift-section", - deploymentTargets: .macOS("10.15"), + deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, dependencies: commandLineDependencies ), @@ -50,7 +54,7 @@ let project = Project( destinations: .macOS, product: .staticFramework, bundleId: "com.machoswiftsection.swift-section.module", - deploymentTargets: .macOS("10.15"), + deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, dependencies: commandLineDependencies ), From a5e9ae4b5b27e54fd7db10a680ca38795ef3fd1e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:29:39 +0800 Subject: [PATCH 004/175] fix: build the Tuist workspace's package tests for macOS 14 SwiftPM builds a test target for at least the macOS version XCTest and Swift Testing require; Tuist took the package's 10.15, and TypeIndexingTests lost the macOS 13 APIs it tests. TuistScript.sh passes every mapped test target in TUIST_TEST_TARGET_NAMES and Tuist/Package.swift raises them. Proposal: draft-tuist-workspace --- Tuist/Package.swift | 18 +++++++++++++++++- TuistScript.sh | 10 ++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 4fb8585c..4c334aed 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -55,8 +55,24 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac ]), ] + // SwiftPM builds a test target for at least the macOS version XCTest and Swift Testing require + // (14.0 with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, + // and MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build + // of the whole workspace compiles too. + let testTargetSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: ["MACOSX_DEPLOYMENT_TARGET": "14.0"])) + }, + uniquingKeysWith: { first, _ in first } + ) + let packageSettings = PackageSettings( - targetSettings: warningSettings.merging(restatedTraitDefinitions) { $1 }, + targetSettings: warningSettings + .merging(restatedTraitDefinitions) { $1 } + .merging(testTargetSettings) { first, second in + .settings(base: first.base.merging(second.base) { $1 }) + }, // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" diff --git a/TuistScript.sh b/TuistScript.sh index 9765bb9a..64942c2d 100755 --- a/TuistScript.sh +++ b/TuistScript.sh @@ -606,7 +606,7 @@ def dependency_name(dependency): return dependency[kind][0] return None -source_targets, warning_targets, test_entries, rejected = [], [], [], [] +source_targets, warning_targets, test_entries, test_names, rejected = [], [], [], [], [] own_target_names = set() for identity, role, directory in packages: if role == "third-party": @@ -629,6 +629,7 @@ for identity, role, directory in packages: } regular_names = {target["name"] for target in targets if target["type"] == "regular"} tests = [target for target in targets if target["type"] == "test"] + test_names += [test["name"] for test in tests] for test in tests: for dependency in test["dependencies"]: name = dependency_name(dependency) @@ -657,18 +658,21 @@ for identity, role, directory in packages: print("SOURCE_TARGETS=" + ",".join(source_targets)) print("WARNING_TARGETS=" + ",".join(warning_targets)) print("TEST_TARGETS=" + ";".join(test_entries)) +print("TEST_TARGET_NAMES=" + ",".join(test_names)) for reason in rejected: print("REJECTED=" + reason) PYTHON TUIST_SOURCE_TARGET_NAMES="" TUIST_WARNING_TARGET_NAMES="" TUIST_PACKAGE_TEST_TARGETS="" + TUIST_TEST_TARGET_NAMES="" TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 while IFS='=' read -r key value; do case "$key" in SOURCE_TARGETS) TUIST_SOURCE_TARGET_NAMES="$value";; WARNING_TARGETS) TUIST_WARNING_TARGET_NAMES="$value";; TEST_TARGETS) TUIST_PACKAGE_TEST_TARGETS="$value";; + TEST_TARGET_NAMES) TUIST_TEST_TARGET_NAMES="$value";; REJECTED) warn "Tuist would reject $value" TUIST_MAPS_LOCAL_PACKAGE_TESTS=0;; @@ -679,8 +683,10 @@ PYTHON if [[ "$TUIST_MAPS_LOCAL_PACKAGE_TESTS" != 1 ]]; then warn "the tests stay out of the workspace this time. Each manifest above needs the TUIST_MAPS_LOCAL_PACKAGE_TESTS block MachOSwiftSection's Package.swift ends with (Documentations/Internal/TuistDevelopment.md)." TUIST_PACKAGE_TEST_TARGETS="" + TUIST_TEST_TARGET_NAMES="" fi - export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_MAPS_LOCAL_PACKAGE_TESTS + export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_TEST_TARGET_NAMES \ + TUIST_MAPS_LOCAL_PACKAGE_TESTS } # --- Commands ------------------------------------------------------------------------------------- From 4fac4ba4e7af0a3efd37a959bbce1b1e1359f426 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:32:08 +0800 Subject: [PATCH 005/175] fix: give the hand-written Tuist targets MachOSwiftSection's package name SwiftSectionCommandTests calls a `package` method of SwiftSectionKit, which only modules of the same package see. Tuist sets SWIFT_PACKAGE_NAME on the targets it converts; the hand-written ones now carry the same value. Proposal: draft-tuist-workspace --- Tuist/CommandLine/Project.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift index 72df2619..7bc6053f 100644 --- a/Tuist/CommandLine/Project.swift +++ b/Tuist/CommandLine/Project.swift @@ -39,6 +39,10 @@ let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: f let project = Project( name: "MachOSwiftSectionCommandLine", + // In SwiftPM these targets belong to the MachOSwiftSection package, whose `package` declarations + // they use (SwiftSectionCommandTests calls SwiftSectionKit's applyTransformersEnablingCommentKinds). + // Tuist gives the targets it converts SWIFT_PACKAGE_NAME = MachOSwiftSection; these need the same. + settings: .settings(base: ["SWIFT_PACKAGE_NAME": "MachOSwiftSection"]), targets: [ .target( name: "swift-section", From 521d41b25af2432fbb2eca4dbf0d6929abd85b0d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:34:31 +0800 Subject: [PATCH 006/175] fix: point the Tuist workspace's testing-support libraries at TestingMacros SwiftSectionTestingSupport, a library target, uses Swift Testing's #require. SwiftPM gives every target the toolchain's TestingMacros plugin; Xcode only gives it to test targets. TuistScript.sh finds the library targets whose sources import Testing and Tuist/Package.swift adds the plugin path to them. Proposal: draft-tuist-workspace --- Tuist/Package.swift | 27 ++++++++++++++++++++++----- TuistScript.sh | 22 ++++++++++++++++++++-- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 4c334aed..35dd3c19 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -67,12 +67,29 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac uniquingKeysWith: { first, _ in first } ) + // A library target that imports Testing, such as a package's testing support, uses Swift Testing's + // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros + // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library + // targets whose sources import Testing. + let testingSupportSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TESTING_SUPPORT_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: [ + "ENABLE_TESTING_SEARCH_PATHS": "YES", + "OTHER_SWIFT_FLAGS": ["$(inherited)", "-plugin-path", "$(TOOLCHAIN_DIR)/usr/lib/swift/host/plugins/testing"], + ])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // One target may need several of the settings above; their keys never overlap. + func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { + settingsByTarget.reduce(into: [:]) { merged, settings in + merged.merge(settings) { first, second in .settings(base: first.base.merging(second.base) { $1 }) } + } + } + let packageSettings = PackageSettings( - targetSettings: warningSettings - .merging(restatedTraitDefinitions) { $1 } - .merging(testTargetSettings) { first, second in - .settings(base: first.base.merging(second.base) { $1 }) - }, + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" diff --git a/TuistScript.sh b/TuistScript.sh index 64942c2d..a45cd00a 100755 --- a/TuistScript.sh +++ b/TuistScript.sh @@ -585,6 +585,7 @@ read_manifests() { || fail "cannot read the manifests in $MANIFESTS_DIRECTORY; run ./TuistScript.sh install" import json import os +import re import sys manifests_directory, own_identity, unlisted_tests = sys.argv[1:4] @@ -606,7 +607,18 @@ def dependency_name(dependency): return dependency[kind][0] return None -source_targets, warning_targets, test_entries, test_names, rejected = [], [], [], [], [] +source_targets, warning_targets, test_entries, test_names, testing_support_names, rejected = [], [], [], [], [], [] +testing_import = re.compile(r"^\s*(@\w+\s+)*((public|package|internal)\s+)?import\s+Testing\b", re.MULTILINE) + +def imports_testing(package_directory, target): + target_directory = os.path.join(package_directory, target.get("path") or os.path.join("Sources", target["name"])) + for root, _, file_names in os.walk(target_directory): + for file_name in file_names: + if file_name.endswith(".swift"): + with open(os.path.join(root, file_name), errors="replace") as handle: + if testing_import.search(handle.read()): + return True + return False own_target_names = set() for identity, role, directory in packages: if role == "third-party": @@ -621,6 +633,9 @@ for identity, role, directory in packages: if role != "own-path": continue warning_targets += [target["name"] for target in targets if target["type"] != "test"] + testing_support_names += [ + target["name"] for target in targets if target["type"] == "regular" and imports_testing(directory, target) + ] executable_names = {target["name"] for target in targets if target["type"] == "executable"} product_target_names = { name @@ -659,6 +674,7 @@ print("SOURCE_TARGETS=" + ",".join(source_targets)) print("WARNING_TARGETS=" + ",".join(warning_targets)) print("TEST_TARGETS=" + ";".join(test_entries)) print("TEST_TARGET_NAMES=" + ",".join(test_names)) +print("TESTING_SUPPORT_TARGET_NAMES=" + ",".join(testing_support_names)) for reason in rejected: print("REJECTED=" + reason) PYTHON @@ -666,6 +682,7 @@ PYTHON TUIST_WARNING_TARGET_NAMES="" TUIST_PACKAGE_TEST_TARGETS="" TUIST_TEST_TARGET_NAMES="" + TUIST_TESTING_SUPPORT_TARGET_NAMES="" TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 while IFS='=' read -r key value; do case "$key" in @@ -673,6 +690,7 @@ PYTHON WARNING_TARGETS) TUIST_WARNING_TARGET_NAMES="$value";; TEST_TARGETS) TUIST_PACKAGE_TEST_TARGETS="$value";; TEST_TARGET_NAMES) TUIST_TEST_TARGET_NAMES="$value";; + TESTING_SUPPORT_TARGET_NAMES) TUIST_TESTING_SUPPORT_TARGET_NAMES="$value";; REJECTED) warn "Tuist would reject $value" TUIST_MAPS_LOCAL_PACKAGE_TESTS=0;; @@ -686,7 +704,7 @@ PYTHON TUIST_TEST_TARGET_NAMES="" fi export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_TEST_TARGET_NAMES \ - TUIST_MAPS_LOCAL_PACKAGE_TESTS + TUIST_TESTING_SUPPORT_TARGET_NAMES TUIST_MAPS_LOCAL_PACKAGE_TESTS } # --- Commands ------------------------------------------------------------------------------------- From 2e52588e807dfdd1d9a5dac5829b62fa4d452e89 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 12:37:06 +0800 Subject: [PATCH 007/175] docs: add the Tuist development workspace guide; build and test take --scheme Documentations/Internal/TuistDevelopment.md explains the workspace, the local dependency mode, the claim record shared with RuntimeViewer, how the tests are mapped, and the Tuist 4.210 workarounds. AGENTS.md points agents at the script; the proposal records what the implementation changed. TuistScript.sh build and test take --scheme, for the upstream packages' test schemes of the local mode. Proposal: draft-tuist-workspace --- AGENTS.md | 1 + .../Evolutions/draft-tuist-workspace.md | 9 ++ Documentations/Internal/TuistDevelopment.md | 102 ++++++++++++++++++ Documentations/README.md | 1 + TuistScript.sh | 27 +++-- 5 files changed, 133 insertions(+), 7 deletions(-) create mode 100644 Documentations/Internal/TuistDevelopment.md diff --git a/AGENTS.md b/AGENTS.md index 628f9821..bc76bb6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,6 +147,7 @@ python3 Scripts/test-run-rendering-ab-verification.py - **The rendering A/B verification is mandatory after any large refactor** touching demangling, printing, indexing, or the reader stack: byte-identical `dump` + `interface` output over real system frameworks through all three reader paths (archived dyld caches, simulator-runtime files, in-process `MachOImage`). Procedure, fallback rules, pitfalls: [SystemFrameworkRenderingVerification.md](Documentations/Internal/SystemFrameworkRenderingVerification.md). - **Re-run the harness's own unit tests after touching `compare_all_pairs` or the skip-marker writing.** Every hole found there so far was the same shape — the harness reporting a pass over a comparison it never made (zero pairs compared; both sides failing with *different* exit codes, leaving no `.txt` for either glob to see). Its green light is what this file makes acceptance evidence, so a harness that cannot fail is worse than no harness. - CI runs only a subset of suites. A green CI is not a green full suite; run the full suite locally before claiming one. +- **`./TuistScript.sh` generates `MachOSwiftSection-Tuist.xcworkspace`, a development-only second path**: third-party dependencies from Tuist's binary cache, `--local-dependencies` for the native workspace's upstream packages. Never run a bare `tuist` command — it gets none of the variables the manifests read and skips the claim RuntimeViewer's Tuist workspace shares on the same checkouts. As an agent set `TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection` and run `warm` / `build` / `test` through `queued-build`. The `TUIST_MAPS_LOCAL_PACKAGE_TESTS` block at the end of `Package.swift` exists for it; a test-only dependency added to `Package.swift` also goes into `Tuist/Package.swift`, a new dependency of `swift-section` into `Tuist/CommandLine/Project.swift`. [TuistDevelopment.md](Documentations/Internal/TuistDevelopment.md). diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/draft-tuist-workspace.md index 163b608f..a61796d8 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.md +++ b/Documentations/Evolutions/draft-tuist-workspace.md @@ -581,3 +581,12 @@ let tuist = Tuist( | 2026-11-20 | 定下三个方向 | 用户选定:提供二进制缓存与 `warm`;Tuist workspace 要能跑测试,先实测再定写法;与 RuntimeViewer 的本地依赖模式双向互斥,为此顺带改 RuntimeViewer 的脚本。 | | 2026-11-20 | 实测定下测试的写法 | 十项实测见「前期调研」:Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;`SwiftSectionCommandTests` 在 `Tuist/CommandLine/Project.swift` 里手写。三个上游库要不要加,留给用户定。 | | 2026-11-20 | 用户批准,开始实现 | 用户选定给 MachOKitExtensions、MachOObjCSection、swift-demangling 加适配块,本地模式带测试;状态改 Accepted。实现在本库的 `feature/tuist-workspace`,三个上游库与 RuntimeViewer 各用同名分支。 | +| 2026-11-20 | 清单改由脚本自己读 | 本想直接读 Tuist 缓存的清单索引(`swifterpm/package-info/index.json`),实测设了 `SWIFTPM_BUILD_DIR` 时 Tuist 不产出这份索引,靠它不可靠。改回提案原写法:每次 `install` 之后脚本用 `swift package dump-package`(带 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1`,8 个并行)读一遍所有包的清单存进 `Work//Manifests/`,名单、预检和同名检查都读它(35 个包)。Python 出错时脚本直接失败,而不是带着空名单生成。 | +| 2026-11-20 | 解析依赖的记号带上清单的 hash | `Work//InstalledDependencies` 除了模式,还记 `Tuist/Package.swift`、`Package.swift`、种子锁文件与(本地模式下)上游库清单的 hash:改了 `Package.swift` 或换了根目录的 `Package.resolved`,下一次 `generate` 自己重新解析,不必记得先跑 `install`。 | +| 2026-11-20 | CLI 的部署版本改为 macOS 12.0 | Ultra 首次构建:Tuist 把 swift-argument-parser 编成它声明的 macOS 12,10.15 的 `swift-section` import 不了它(11 处同一错误,其余全部编过)。 | +| 2026-11-20 | 测试 target 抬到 macOS 14.0(原定「按需」,确认需要) | `TypeIndexingTests` 用的 macOS 13 API 在 10.15 下编不过。脚本把所有转换进来的测试 target(含 `IntegrationTests`)传进新变量 `TUIST_TEST_TARGET_NAMES`。 | +| 2026-11-20 | 手写的 target 设 `SWIFT_PACKAGE_NAME = MachOSwiftSection` | `SwiftSectionCommandTests` 调用 SwiftSectionKit 的 `package` 方法;Tuist 转换的 target 都带这个设置,手写的没有。 | +| 2026-11-20 | 导入 Testing 的库 target 加 TestingMacros 插件路径 | `SwiftSectionTestingSupport` 用了 `#require`,Xcode 只给测试 target 带 TestingMacros 插件。脚本扫描路径包里普通 target 的源码找 `import Testing`,传进新变量 `TUIST_TESTING_SUPPORT_TARGET_NAMES`;本地模式下 swift-demangling 的 `DemanglingTestingSupport` 也会被找到。 | +| 2026-11-20 | `build` / `test` 加 `--scheme` | 本地模式下要跑上游库各自的测试 scheme(`<包名> Tests`)。 | +| 2026-11-20 | MachOKitExtensions 的 `next` 已不需要适配块,仍按决定加上 | 探针用的是它的 `main`(有 `CPlusPlusSymbolsFixture`),`next` 上这个测试支撑 target 已经没有了,块目前不起作用。另:本库 `.worktrees/MachOKitExtensions` 链接指向它的主检出(`main`),不是它的 `next` worktree,所以公司那台上的本地模式编的是 `main`,预检会因为那个 target 关掉测试并点名。 | +| 2026-11-20 | Tuist 往 `PrecompiledLibraries/swift-syntax/` 里写 `.build/` | 它是按路径声明的包,Tuist 在那里下载二进制产物;与它生成的工程一起写进 `.gitignore`。 | diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md new file mode 100644 index 00000000..3aec60fd --- /dev/null +++ b/Documentations/Internal/TuistDevelopment.md @@ -0,0 +1,102 @@ +# 使用指南:Tuist 开发 workspace + +- **面向**: 在本仓库做日常开发、想让第三方依赖走二进制缓存的人;同时改本库和上游那几个库的人;改 `Package.swift` 的 target、依赖或测试的人(同步规则) +- **对应提案**: [draft-tuist-workspace](../Evolutions/draft-tuist-workspace.md) +- **最后更新**: 2026-11-20 + +`MachOSwiftSection-Tuist.xcworkspace` 是原生 `MachOSwiftSection.xcworkspace` 之外的第二条路,只供日常开发。它由 `./TuistScript.sh` 用 Tuist 生成:本库照常从源码编,可以跳转、可以编辑;原生 workspace 里放的五个上游库(MachOKit、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string)也从源码编;其余 27 个第三方包(swift-dependencies 一族、swift-collections、Capstone、swift-crypto、Yams……)预编进本机的 Tuist 二进制缓存,只编一次。 + +**`Package.swift` 仍是 target 与依赖的唯一定义。** Tuist 直接读它,把本库转换成 `MachOSwiftSection.xcodeproj`;手写的只有 Tuist 转换不了的那部分(`Tuist/CommandLine/Project.swift`,见下文)。 + +**发版、CI、`swift build` / `swift test` 和原生 workspace 都不走这里**,Tuist 这边出问题不影响它们。生成的工程文件都已忽略,不提交。 + +## 第一次使用 + +```bash +mise install # 装 mise.toml 钉的 Tuist(4.210.0,与 RuntimeViewer 相同) +./TuistScript.sh warm # 解析依赖 → 把第三方依赖编进缓存 → 生成 workspace +open MachOSwiftSection-Tuist.xcworkspace +``` + +- **锁文件**:脚本每次解析都从本检出根目录的 `Package.resolved`(`swift build` 与原生 workspace 解析出的那份,不提交)开始,所以 Tuist 用的是同样的版本。没有这个文件时 Tuist 解析各清单允许的最新版本,并提示一句;新 worktree 里可以先从集成检出拷一份过来。解析完与它不一致时会列出差异,多半是换了 Xcode:有些包按 Swift 版本选用不同的清单。 +- **Xcode**:脚本和 Tuist 都用 `DEVELOPER_DIR` 或 `xcode-select` 选中的那个,打开 workspace 也用同一个。二进制缓存按 Xcode 版本分开,换了 Xcode 要重新 `warm`。 + +## 日常用法 + +| 要做的事 | 做法 | +|---|---| +| 编辑、构建、运行 CLI | scheme `swift-section` | +| 跑本库的测试 | scheme `MachOSwiftSection Tests`:`Package.swift` 里除 `IntegrationTests` 外的全部测试 target | +| 命令行构建 / 测试 | `./TuistScript.sh build`、`./TuistScript.sh test`,`--` 之后的参数原样交给 `xcodebuild`(例如 `-- -only-testing:SwiftDumpTests`) | +| 增删了源文件 | `./TuistScript.sh generate`(Tuist 转换包时按 glob 展开文件;只改已有文件不用) | +| 改了 `Package.swift`、换了根目录的 `Package.resolved` | `./TuistScript.sh generate`:脚本发现清单或种子锁文件变了,会先重新解析 | +| 第三方依赖升级、换了 Xcode | `./TuistScript.sh warm`(只重编变了的) | +| 同时改上游库 | `./TuistScript.sh generate --local-dependencies`,见下文 | +| 不再用这个 workspace,或要把本检出让给 RuntimeViewer 的本地模式 | `./TuistScript.sh release` | + +**别直接跑 `tuist generate` / `tuist install`。** 清单读的环境变量(哪些 target 留作源码、哪些测试进 scheme、要不要映射测试、本地模式的目录)都由脚本算好再传进去;直接跑 Tuist 拿不到它们,也没有下文的占用保护。 + +**生成出的工程只链接一套配置的缓存。** 默认按 Debug 生成;要在 Xcode 里编 Release,先 `./TuistScript.sh generate --configuration Release`,编完不带参数再 `generate` 回到 Debug。缓存也按配置分开预热(`warm --configuration Release`)。 + +## 用本地检出的上游库 + +同时改本库和上游库时,Tuist workspace 也能像原生 workspace 的本地依赖那样,直接编它们的本地检出,其余第三方依赖照旧走缓存: + +```bash +./TuistScript.sh generate --local-dependencies # 打开;之后不带参数的命令都沿用 +./TuistScript.sh generate --remote-dependencies # 回到锁文件钉住的版本(默认) +``` + +- **哪几个库、从哪取**:原生 workspace 的 `container:../<名字>` 成员,现在是上面五个;原生 workspace 加了库,这里自动跟上。默认从检出的上一级目录取,worktree 里就是 `.worktrees/` 下那组链接,所以编的是那组链接指向的检出(比如 `.worktrees/MachOKitExtensions` 指向 MachOKitExtensions 的主检出时,编的就是它当前所在的分支)。打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS`,就改从它指的目录取:每个库一个子目录,名字与库相同(SwiftPM 按目录名认包,经符号链接也一样按真实目录名认)。 +- **效果**:`Tuist/Package.swift` 按路径声明这几个库,顶替依赖图里所有按 URL 声明的同名包。它们从本地源码编,没提交的改动也算;改已有文件后在 Xcode 里直接编就生效。它们的编译警告照常显示。 +- **测试**:六个包的测试都进 workspace,每个包一个 scheme(`<包名> Tests`)。做到这一点要每个库的 `Package.swift` 末尾都有那段 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 适配块(见下一节);MachOKitExtensions、MachOObjCSection、swift-demangling 已经加了,MachOKit 与 swift-semantic-string 现在用不着。某个库的检出停在加块之前的提交、又有 Tuist 不接受的测试时,脚本会警告并点名那个库,这一次整个 workspace 都不带测试(Tuist 对按路径声明的包只能全映射或全不映射),生成照常进行。 +- **模式会记住**:记在 `Tuist/.local-dependencies`(已忽略),之后不带参数的命令都沿用;每条命令开头都打印当前用的是哪种依赖。两种模式各有一份依赖 checkout,切换后会先重新解析。 +- **写进库目录的文件**:Tuist 会在每个按路径声明的包目录里生成 `<包名>.xcodeproj/` 和 `Derived/`。脚本把这两项写进那个仓库的 `info/exclude`(只在本机,不提交),`git status` 里看不到;切回远程模式时删掉 `<包名>.xcodeproj/`,`Derived/` 留着。git 跟踪着 `<包名>.xcodeproj` 的库,脚本直接报错,不让 Tuist 覆盖。 + +## 与 RuntimeViewer 共用的占用记录 + +RuntimeViewer 的 Tuist workspace 在它的本地依赖模式下也往这几个检出里生成同名工程,其中也包括本库的检出;而本库的 Tuist workspace 每次都往本检出根目录生成 `MachOSwiftSection.xcodeproj`。两边的设置不同,谁后生成谁就让另一边的 workspace 坏掉,所以两个脚本生成之前都先「占用」检出: + +- 被占检出的 git 目录里写 `tuist-generated-project-owner`:占用者检出的路径、在占用者那里释放它的命令、生成进来的工程名。 +- 占用者在自己的 `Tuist/.claimed-checkouts`(已忽略)里列出手里的检出,列着才算有效;占用者已经不在或不再列着,记录就是陈旧的,直接接管。 +- 另一个检出占着时,命令报错并给出在那边要跑的释放命令:本库是 `./TuistScript.sh release`,RuntimeViewer 是 `./TuistScript.sh generate --remote-dependencies`。RuntimeViewer 旧版脚本写的 `runtimeviewer-tuist-local-dependencies` 记录也认。 +- **本库的检出在两种模式下都被自己占着**,本地模式下再加五个上游库。所以要让 RuntimeViewer 的本地模式用这个检出,先在这里 `./TuistScript.sh release`;反过来,RuntimeViewer 的本地模式占着这个检出时,这里的 `generate` 会报错,先在 RuntimeViewer 那边切回远程。 + +## 测试是怎么映射进来的 + +Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` 的 `includeLocalPackageTestTargets`),但它拒绝两种 SwiftPM 接受的测试:依赖可执行 target 的(本库的 `SwiftSectionCommandTests`、MachOObjCSection 的 `ObjCSectionCommandTests`),和依赖一个不属于任何 product 的普通 target 的(本库的 `SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`,swift-demangling 的 `DemanglingTestingSupport`)。 + +- **适配块**:`Package.swift` 末尾那段代码只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效——脚本解析依赖时设它——把第一种测试拿掉,给第二种依赖的 target 补一个 library product。平时这个变量不存在,块里什么都不做:`swift package dump-package` 的输出与没有这段代码时逐字节相同。规则是通用的,以后新加的这两种测试不用再改清单。三个上游库的清单末尾是同一段代码,改的时候四处一起改。 +- **`SwiftSectionCommandTests` 手写在 `Tuist/CommandLine/Project.swift`**:它 `@testable import swift_section`,也就是可执行 target 自己的模块。那里把 CLI 的源码编成静态 framework `swift_section` 给它用,`swift-section` 工具再编一遍同样的源码,链接时不用绕开 `@main` 的入口。**CLI 的依赖列表是 Tuist 描述里唯一手抄的一份**:`Package.swift` 里 `swift-section` 加了依赖,这里也要加,否则编不过。MachOObjCSection 的 `ObjCSectionCommandTests` 不手写,留在 `swift test` 里跑。 +- **只被测试用到的外部依赖要在 `Tuist/Package.swift` 里声明**(现在只有 swift-snapshot-testing),否则 Tuist 报 `… depends on 'X', which is not a configured external dependency`。按 `Package.swift` 里的版本要求加上即可。 +- **`IntegrationTests`** 会被转换进来,但不进任何 scheme(`AGENTS.md`:维护者手工查看用的,不跑)。 + +## 存放位置 + +`/Volumes/DerivedData` 挂载时,全部放在 `/Volumes/DerivedData/MachOSwiftSection/Tuist/` 下;没挂载时放在仓库里(`Tuist/.build/`、`Tuist/.build-LocalDependencies/`、`DerivedData/Tuist/`,都已忽略)。`TUIST_SCRIPT_ROOT` 可以指定别处。 + +| 目录 | 内容 | +|---|---| +| `Cache/` | Tuist 的二进制缓存与清单缓存,所有检出共用(按内容寻址) | +| `Dependencies//` | 远程模式的依赖 checkout,每个检出一份;`-LocalDependencies` 后缀的是本地模式那份 | +| `WarmScratch//` | 预热时的临时构建目录,每次预热前清空 | +| `Work//` | `build` / `test` 的 DerivedData 与 `.xcresult`、各包解析后的清单(`Manifests/`)、上次解析依赖用的模式与清单(`InstalledDependencies`) | + +`` 是检出目录名加路径的短 hash,同名的两个 worktree 不会混用。想从头来:删掉 `Dependencies//` 与 `Work//InstalledDependencies` 后 `install`,删掉 `Cache/` 后 `warm`。 + +脚本的日志在仓库内的 `Products/Logs/Tuist/`(已忽略)。Tuist 命令的输出原样显示在终端,同时记进日志;`xcodebuild` 的输出只记进日志,失败时终端只显示错误摘要。`test` 结束时打印通过 / 失败 / 跳过的个数,`.xcresult` 的路径在日志开头。 + +**Agent 运行时**用 `TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection`。`install`、`generate`、`release` 不编译,可以直接跑;`warm`、`build`、`test` 要编译,经 `queued-build` 运行,在公司那台 Mac Studio 上按远程构建的规矩放到 Ultra 上跑。 + +## 已知的坑:清单里那些看着奇怪的写法 + +都是为了绕开 Tuist 4.210 的行为,改之前先看这里。 + +- **CLI 的部署版本是 macOS 12.0**(`Tuist/CommandLine/Project.swift`):Tuist 把 swift-argument-parser 编成它声明的最低版本 macOS 12,10.15 的 `swift-section` import 不了它。 +- **测试 target 的部署版本抬到 macOS 14.0**(`Tuist/Package.swift` 的 `testTargetSettings`):SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(Xcode 26、27 都是 14.0),包声明的更低也一样;Tuist 照搬包声明的 10.15,`TypeIndexingTests` 于是找不到它测的 macOS 13 API。脚本把所有转换进来的测试 target(含 `IntegrationTests`,免得编整个 workspace 时它编不过)传进 `TUIST_TEST_TARGET_NAMES`。 +- **导入了 Testing 的库 target 加上 TestingMacros 插件路径**(`Tuist/Package.swift` 的 `testingSupportSettings`):`SwiftSectionTestingSupport` 是普通的库 target,却用了 Swift Testing 的 `#require`。SwiftPM 给每个 target 都带上工具链的 TestingMacros 插件,Xcode 只给测试 target 带,于是报 `plugin for module 'TestingMacros' not found`。脚本读清单时找出源码里 `import Testing` 的库 target(本地模式下还有上游库的,比如 swift-demangling 的 `DemanglingTestingSupport`),传进 `TUIST_TESTING_SUPPORT_TARGET_NAMES`。 +- **手写的 target 设了 `SWIFT_PACKAGE_NAME = MachOSwiftSection`**(`Tuist/CommandLine/Project.swift`):`SwiftSectionCommandTests` 调用 SwiftSectionKit 的 `package` 方法,只有同一个包的模块看得见;Tuist 给它转换的 target 都设了这个值,手写的也要设。 +- **`CAPSTONE_HAS_AARCH64` 手动补上**:Tuist 丢掉只以 trait 为条件的设置;本库开了 swift-capstone 的 `AARCH64` trait,不补的话 Swift 包装编不过,C 库能编过但没有任何架构可用。 +- **警告还给按路径声明的包**:Tuist 对所有包都关掉警告,Xcode 只关远程包的;本库(本地模式下还有五个上游库)的 target 经 `TUIST_WARNING_TARGET_NAMES` 把警告要回来。 +- **预热要带 `--cache-profile development`**(脚本已经带上):`tuist cache warm` 不读 `Tuist.swift` 里的默认配置,不传就连本库与上游库也一起缓存。缓存例外按 target 名字匹配所有包,脚本读完清单会警告名字撞上的第三方 target。 +- **Tuist 会往 `PrecompiledLibraries/swift-syntax/` 里写 `swift-syntax.xcodeproj`、`Derived/` 与 `.build/`**:它也是按路径声明的包。都已忽略。 diff --git a/Documentations/README.md b/Documentations/README.md index be8fecfe..100726d0 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -224,6 +224,7 @@ selects names using each access's offset and width. | [DeclarationModelMemoryFootprint.md](Internal/DeclarationModelMemoryFootprint.md) | NodeStore 迁移后的声明模型内存足迹量测:`TypeDefinition` 1272 字节的逐属性构成(两份 `TypeContextWrapper` 占 74%)、`TypeContextWrapper` 按最大 case `Class` 定尺的原因、`parentContext` 是被当成永久字段的临时值、mini-store 增殖与 `MetadataReaderCache` 仍持 `Node` 树;含四项可回收估算(合计 ~8–10%)与「当前不建议实施、应先剖析其余 90%」的结论。 | | [NodeStoreMigrationOpenIssues.md](Internal/NodeStoreMigrationOpenIssues.md) | NodeStore 迁移的遗留问题台账:每条问题记录成因、影响面、修复位置与当前状态(已修 / 裁决不修 / 仍打开),闭环的条目保留成因备回溯。大部分条目已闭环或已终审;与 `Reviews/` 下两份审查记录冲突时以后者为准。 | | [SystemFrameworkRenderingVerification.md](Internal/SystemFrameworkRenderingVerification.md) | 系统框架渲染 A/B 验证流程(大重构必跑):两个检出对同一批真实输入(归档 dyld cache → 无则当前系统 cache、模拟器 runtime → 无则现有 runtime、当前系统 MachOImage)逐字节比对 dump+interface;入口脚本 `Scripts/run-rendering-ab-verification.py`,含回退规则、踩坑清单(`-p` 消歧、fat 二进制 `-a`、同 boot 会话、scratch 隔离)与 2026-08-03 基线运行记录。 | +| [TuistDevelopment.md](Internal/TuistDevelopment.md) | **使用指南:Tuist 开发 workspace**:`./TuistScript.sh` 生成的 `MachOSwiftSection-Tuist.xcworkspace`,第三方依赖走本机二进制缓存,`--local-dependencies` 改用五个上游库的本地检出;测试怎么映射进来(`Package.swift` 末尾的 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 块、手写的 `SwiftSectionCommandTests`)、与 RuntimeViewer 共用的占用记录、存放位置与 Tuist 4.210 的坑。提案 [draft-tuist-workspace](Evolutions/draft-tuist-workspace.md)。 | | [TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) | **`__C` 模块归属索引管线**(提案 0009 + 0010 的实现说明):`__C.NSString` → `Foundation.NSString` 的三源合并(SourceKit 生成 interface 的 substructure 提取(零 SwiftSyntax)→ APINotes 权威归属覆盖 → 依赖 image ObjC 元数据懒索引兜底)、补充映射包(私有框架外部知识入口,CF-bridged 类型三种 mangling 形态与各自覆盖机制)、按 SDK 精确构建分层的 per-module JSON 缓存、过滤前移的性能形态(历史全 SDK 生成为何小时级)、`@Loggable` 在 `@available` 类型上必须走 protocol 形态的坑、与提案的差异(swift-dependencies 未引入、兜底解析器未编写、MachOObjCSection 下限 0.8.105)。 | | [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 的防优化手段与回归防线。 | diff --git a/TuistScript.sh b/TuistScript.sh index a45cd00a..6cf8b38e 100755 --- a/TuistScript.sh +++ b/TuistScript.sh @@ -14,11 +14,14 @@ # # (Debug or Release; default: Debug) # ./TuistScript.sh warm [--configuration ] # build the third-party dependencies into the # # binary cache of one configuration, then generate -# ./TuistScript.sh build [--configuration ] [-- ] -# # generate, then build the swift-section scheme -# ./TuistScript.sh test [--configuration ] [-- ] +# ./TuistScript.sh build [--configuration ] [--scheme ] [-- ] +# # generate, then build the swift-section scheme, or +# # another +# ./TuistScript.sh test [--configuration ] [--scheme ] [-- ] # # generate, then run the "MachOSwiftSection Tests" -# # scheme; exits with xcodebuild's exit code +# # scheme, or another (in the local mode each upstream +# # package has " Tests"); exits with +# # xcodebuild's exit code # ./TuistScript.sh release # give up every checkout this one claimed: remove the # # projects Tuist generated into them and the workspace # ./TuistScript.sh --local-dependencies @@ -79,6 +82,7 @@ EXCLUDE_COMMENT="# Generated by MachOSwiftSection's TuistScript.sh" COMMAND="" CONFIGURATION="Debug" +REQUESTED_SCHEME="" DRY_RUN=false REQUESTED_DEPENDENCY_MODE="" EXTRA_ARGUMENTS=() @@ -144,6 +148,9 @@ while [[ $# -gt 0 ]]; do --configuration) [[ $# -ge 2 ]] || fail "--configuration needs a name (Debug or Release)" CONFIGURATION="$2"; shift 2;; + --scheme) + [[ $# -ge 2 ]] || fail "--scheme needs a scheme name" + REQUESTED_SCHEME="$2"; shift 2;; --local-dependencies|--remote-dependencies) [[ -z "$REQUESTED_DEPENDENCY_MODE" ]] || fail "one of --local-dependencies and --remote-dependencies at a time" REQUESTED_DEPENDENCY_MODE="${1#--}"; REQUESTED_DEPENDENCY_MODE="${REQUESTED_DEPENDENCY_MODE%-dependencies}"; shift;; @@ -158,8 +165,12 @@ case "$CONFIGURATION" in Debug|Release) ;; *) fail "unknown configuration: $CONFIGURATION (expected Debug or Release)";; esac -if [[ ${#EXTRA_ARGUMENTS[@]} -gt 0 && "$COMMAND" != build && "$COMMAND" != test ]]; then - fail "only build and test pass arguments on to xcodebuild" +if [[ ( ${#EXTRA_ARGUMENTS[@]} -gt 0 || -n "$REQUESTED_SCHEME" ) && "$COMMAND" != build && "$COMMAND" != test ]]; then + fail "only build and test take --scheme and pass arguments on to xcodebuild" +fi +if [[ -n "$REQUESTED_SCHEME" ]]; then + BUILD_SCHEME="$REQUESTED_SCHEME" + TEST_SCHEME="$REQUESTED_SCHEME" fi # One directory per checkout: two worktrees must not share Tuist's dependency checkouts, which record @@ -769,7 +780,9 @@ build_command() { log "Building $BUILD_SCHEME ($CONFIGURATION)" run_logged "build-$CONFIGURATION" xcodebuild build -scheme "$BUILD_SCHEME" "${arguments[@]}" \ ${EXTRA_ARGUMENTS[@]+"${EXTRA_ARGUMENTS[@]}"} || fail "the build failed" - $DRY_RUN || log "swift-section: $WORK_ROOT/DerivedData/$CONFIGURATION/Build/Products/$CONFIGURATION/swift-section" + if ! $DRY_RUN && [[ "$BUILD_SCHEME" == swift-section ]]; then + log "swift-section: $WORK_ROOT/DerivedData/$CONFIGURATION/Build/Products/$CONFIGURATION/swift-section" + fi } test_command() { From 8bce49341f328adea0392795d54c71dd14124690 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 13:06:15 +0800 Subject: [PATCH 008/175] fix: load SwiftSymbolsRegistration whole in the Tuist workspace's links SwiftSymbolsRegistration registers Swift as a symbol language from a static load-time constructor nothing refers to. SwiftPM links each target's object files whole; Tuist builds a static framework, the linker loaded no member of it, and SwiftSymbolsTests found no Swift language registered. TuistScript.sh finds the targets with a load-time constructor and the test and executable targets that reach them, and those links -force_load the archive. Proposal: draft-tuist-workspace --- Tuist/CommandLine/Project.swift | 23 ++++++++++++++--- Tuist/Package.swift | 20 ++++++++++++++- TuistScript.sh | 44 ++++++++++++++++++++++++++++++++- 3 files changed, 81 insertions(+), 6 deletions(-) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift index 7bc6053f..7ee01a4c 100644 --- a/Tuist/CommandLine/Project.swift +++ b/Tuist/CommandLine/Project.swift @@ -31,11 +31,25 @@ let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] +// The constructor targets the swift-section executable reaches in Package.swift, which must be loaded +// whole (Tuist/Package.swift explains why); TuistScript.sh lists them in TUIST_FORCE_LOADS. +let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "") + .split(separator: ",") + .compactMap { pair in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil + } +let forceLoadFlags: SettingsDictionary = forceLoadedTargetNames.isEmpty ? [:] : [ + "OTHER_LDFLAGS": .array(["$(inherited)"] + forceLoadedTargetNames.map { targetName in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)" + }), +] + // MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; // TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. -let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: false) - ? .settings(base: ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]]) - : .settings() +let commandTestSettings: Settings = .settings(base: forceLoadFlags.merging( + Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:] +) { $1 }) let project = Project( name: "MachOSwiftSectionCommandLine", @@ -51,7 +65,8 @@ let project = Project( bundleId: "com.machoswiftsection.swift-section", deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, - dependencies: commandLineDependencies + dependencies: commandLineDependencies, + settings: .settings(base: forceLoadFlags) ), .target( name: "swift_section", diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 35dd3c19..fe7701b7 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -81,6 +81,24 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac uniquingKeysWith: { first, _ in first } ) + // MachOSwiftSection's SwiftSymbolsRegistration does its whole job in a load-time constructor, a + // static function nothing refers to. SwiftPM links each target's object files whole; Tuist builds a + // static framework, and the linker loads no archive member nothing refers to, so Swift would never + // be registered as a symbol language. TUIST_FORCE_LOADS pairs each final link (a test target, the + // swift-section executable) with the constructor targets its in-package dependencies reach, as + // ":,…"; those archives are loaded whole. + let forceLoads: [(linkingTarget: String, loadedTarget: String)] = targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 ? (parts[0], parts[1]) : nil + } + let forceLoadSettings: [String: Settings] = Dictionary(grouping: forceLoads, by: \.linkingTarget).mapValues { pairs in + Settings.settings(base: [ + "OTHER_LDFLAGS": .array(["$(inherited)"] + pairs.map { pair in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(pair.loadedTarget).framework/\(pair.loadedTarget)" + }), + ]) + } + // One target may need several of the settings above; their keys never overlap. func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { settingsByTarget.reduce(into: [:]) { merged, settings in @@ -89,7 +107,7 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac } let packageSettings = PackageSettings( - targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings, forceLoadSettings), // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" diff --git a/TuistScript.sh b/TuistScript.sh index 6cf8b38e..6757f189 100755 --- a/TuistScript.sh +++ b/TuistScript.sh @@ -621,6 +621,39 @@ def dependency_name(dependency): source_targets, warning_targets, test_entries, test_names, testing_support_names, rejected = [], [], [], [], [], [] testing_import = re.compile(r"^\s*(@\w+\s+)*((public|package|internal)\s+)?import\s+Testing\b", re.MULTILINE) +constructor_attribute = re.compile(r"__attribute__\s*\(\(\s*constructor\b") + +def target_files(package_directory, target, extensions): + target_directory = os.path.join(package_directory, target.get("path") or os.path.join("Sources", target["name"])) + for root, _, file_names in os.walk(target_directory): + for file_name in file_names: + if file_name.endswith(extensions): + yield os.path.join(root, file_name) + +def has_load_time_constructor(package_directory, target): + for path in target_files(package_directory, target, (".c", ".m", ".mm", ".cpp", ".cc")): + with open(path, errors="replace") as handle: + if constructor_attribute.search(handle.read()): + return True + return False + +# The final links (test bundles, the swift-section executable) that reach, through the package's own +# target dependencies, a target whose only job happens in a load-time constructor. SwiftPM links each +# target's object files whole; Tuist builds a static library, and the linker loads no member nothing +# refers to, so the constructor would never run. +force_loads = [] + +def force_loaded_targets(targets, root_name, constructor_names): + dependencies_by_name = {target["name"]: [dependency_name(dependency) for dependency in target["dependencies"]] for target in targets} + reached, pending = set(), [root_name] + while pending: + name = pending.pop() + for dependency in dependencies_by_name.get(name, []): + if dependency in dependencies_by_name and dependency not in reached: + reached.add(dependency) + pending.append(dependency) + return sorted(reached & constructor_names) + def imports_testing(package_directory, target): target_directory = os.path.join(package_directory, target.get("path") or os.path.join("Sources", target["name"])) for root, _, file_names in os.walk(target_directory): @@ -647,6 +680,12 @@ for identity, role, directory in packages: testing_support_names += [ target["name"] for target in targets if target["type"] == "regular" and imports_testing(directory, target) ] + constructor_names = {target["name"] for target in targets if target["type"] == "regular" and has_load_time_constructor(directory, target)} + if constructor_names: + for target in targets: + if target["type"] in ("test", "executable"): + for name in force_loaded_targets(targets, target["name"], constructor_names): + force_loads.append(f"{target['name']}:{name}") executable_names = {target["name"] for target in targets if target["type"] == "executable"} product_target_names = { name @@ -686,6 +725,7 @@ print("WARNING_TARGETS=" + ",".join(warning_targets)) print("TEST_TARGETS=" + ";".join(test_entries)) print("TEST_TARGET_NAMES=" + ",".join(test_names)) print("TESTING_SUPPORT_TARGET_NAMES=" + ",".join(testing_support_names)) +print("FORCE_LOADS=" + ",".join(force_loads)) for reason in rejected: print("REJECTED=" + reason) PYTHON @@ -694,6 +734,7 @@ PYTHON TUIST_PACKAGE_TEST_TARGETS="" TUIST_TEST_TARGET_NAMES="" TUIST_TESTING_SUPPORT_TARGET_NAMES="" + TUIST_FORCE_LOADS="" TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 while IFS='=' read -r key value; do case "$key" in @@ -702,6 +743,7 @@ PYTHON TEST_TARGETS) TUIST_PACKAGE_TEST_TARGETS="$value";; TEST_TARGET_NAMES) TUIST_TEST_TARGET_NAMES="$value";; TESTING_SUPPORT_TARGET_NAMES) TUIST_TESTING_SUPPORT_TARGET_NAMES="$value";; + FORCE_LOADS) TUIST_FORCE_LOADS="$value";; REJECTED) warn "Tuist would reject $value" TUIST_MAPS_LOCAL_PACKAGE_TESTS=0;; @@ -715,7 +757,7 @@ PYTHON TUIST_TEST_TARGET_NAMES="" fi export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_TEST_TARGET_NAMES \ - TUIST_TESTING_SUPPORT_TARGET_NAMES TUIST_MAPS_LOCAL_PACKAGE_TESTS + TUIST_TESTING_SUPPORT_TARGET_NAMES TUIST_FORCE_LOADS TUIST_MAPS_LOCAL_PACKAGE_TESTS } # --- Commands ------------------------------------------------------------------------------------- From 7d37be72958003cdd6011a6cd028289316a5263e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 13:10:13 +0800 Subject: [PATCH 009/175] fix: link the Tuist workspace's tests and executable with -ObjC Tuist links static frameworks, and the linker loads only the members something refers to by symbol; a protocol conformance nothing names went missing, and the readers wrapping a MachOImage or MachOFile read as neither. -ObjC loads every member defining a Swift type or extension, as RuntimeViewer's Tuist workspace does. The test targets' and the executable's link flags are now built in one place each, -force_load included. Proposal: draft-tuist-workspace --- Tuist/CommandLine/Project.swift | 14 ++++--- Tuist/Package.swift | 67 ++++++++++++++++++--------------- 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift index 7ee01a4c..7ede8d4e 100644 --- a/Tuist/CommandLine/Project.swift +++ b/Tuist/CommandLine/Project.swift @@ -31,23 +31,25 @@ let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] -// The constructor targets the swift-section executable reaches in Package.swift, which must be loaded -// whole (Tuist/Package.swift explains why); TuistScript.sh lists them in TUIST_FORCE_LOADS. +// The link flags Tuist/Package.swift gives the package's test targets, for the same reasons: -ObjC, so +// that the archive members defining Swift types and extensions (protocol conformances among them) are +// loaded, and -force_load of the constructor targets the swift-section executable reaches in +// Package.swift, which TuistScript.sh lists in TUIST_FORCE_LOADS. let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "") .split(separator: ",") .compactMap { pair in let parts = pair.split(separator: ":").map(String.init) return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil } -let forceLoadFlags: SettingsDictionary = forceLoadedTargetNames.isEmpty ? [:] : [ - "OTHER_LDFLAGS": .array(["$(inherited)"] + forceLoadedTargetNames.map { targetName in +let linkFlags: SettingsDictionary = [ + "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadedTargetNames.map { targetName in "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)" }), ] // MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; // TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. -let commandTestSettings: Settings = .settings(base: forceLoadFlags.merging( +let commandTestSettings: Settings = .settings(base: linkFlags.merging( Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:] ) { $1 }) @@ -66,7 +68,7 @@ let project = Project( deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, dependencies: commandLineDependencies, - settings: .settings(base: forceLoadFlags) + settings: .settings(base: linkFlags) ), .target( name: "swift_section", diff --git a/Tuist/Package.swift b/Tuist/Package.swift index fe7701b7..4924e03f 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -55,18 +55,6 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac ]), ] - // SwiftPM builds a test target for at least the macOS version XCTest and Swift Testing require - // (14.0 with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, - // and MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. - // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build - // of the whole workspace compiles too. - let testTargetSettings: [String: Settings] = Dictionary( - targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in - (targetName, Settings.settings(base: ["MACOSX_DEPLOYMENT_TARGET": "14.0"])) - }, - uniquingKeysWith: { first, _ in first } - ) - // A library target that imports Testing, such as a package's testing support, uses Swift Testing's // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library @@ -81,23 +69,42 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac uniquingKeysWith: { first, _ in first } ) - // MachOSwiftSection's SwiftSymbolsRegistration does its whole job in a load-time constructor, a - // static function nothing refers to. SwiftPM links each target's object files whole; Tuist builds a - // static framework, and the linker loads no archive member nothing refers to, so Swift would never - // be registered as a symbol language. TUIST_FORCE_LOADS pairs each final link (a test target, the - // swift-section executable) with the constructor targets its in-package dependencies reach, as - // ":,…"; those archives are loaded whole. - let forceLoads: [(linkingTarget: String, loadedTarget: String)] = targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair in - let parts = pair.split(separator: ":").map(String.init) - return parts.count == 2 ? (parts[0], parts[1]) : nil - } - let forceLoadSettings: [String: Settings] = Dictionary(grouping: forceLoads, by: \.linkingTarget).mapValues { pairs in - Settings.settings(base: [ - "OTHER_LDFLAGS": .array(["$(inherited)"] + pairs.map { pair in - "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(pair.loadedTarget).framework/\(pair.loadedTarget)" - }), - ]) - } + // The test targets, which SwiftPM builds and links differently in three ways: + // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0 + // with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and + // MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // - It links each package target's object files whole, where Tuist links static frameworks and the + // linker loads only the archive members something refers to by symbol. A protocol conformance + // nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage + // or MachOFile (MachOReaderWrapper) read as neither. -ObjC also loads every member that defines an + // Objective-C class or category or a Swift type or extension (Xcode 27's linker), as it does for + // RuntimeViewer's Tuist workspace. + // - A load-time constructor nothing refers to never runs that way at all: MachOSwiftSection's + // SwiftSymbolsRegistration registers Swift as a symbol language from one. TUIST_FORCE_LOADS pairs + // each final link with the constructor targets its in-package dependencies reach, as + // ":,…"; those archives are loaded whole. + // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build + // of the whole workspace compiles and links too. Tuist/CommandLine/Project.swift gives the + // swift-section executable and SwiftSectionCommandTests the same link flags. + let forceLoadedTargetsByLinkingTarget: [String: [String]] = Dictionary( + targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair -> (String, [String])? in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 ? (parts[0], [parts[1]]) : nil + }, + uniquingKeysWith: + + ) + let testTargetSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in + let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)" + } + return (targetName, Settings.settings(base: [ + "MACOSX_DEPLOYMENT_TARGET": "14.0", + "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags), + ])) + }, + uniquingKeysWith: { first, _ in first } + ) // One target may need several of the settings above; their keys never overlap. func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { @@ -107,7 +114,7 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac } let packageSettings = PackageSettings( - targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings, forceLoadSettings), + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" From 6ed0e6039813be012932a810760d014af5e1f563 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 13:14:48 +0800 Subject: [PATCH 010/175] fix: raise only the test targets of packages declaring less than macOS 14 A package that declares macOS 15 would have had its tests lowered to 14. TuistScript.sh lists the test targets whose package declares less than the minimum XCTest and Swift Testing need; every test target keeps -ObjC and its -force_load. The guide and the proposal record the two link workarounds. Proposal: draft-tuist-workspace --- .../Evolutions/draft-tuist-workspace.md | 2 ++ Documentations/Internal/TuistDevelopment.md | 2 ++ Tuist/Package.swift | 11 +++++++---- TuistScript.sh | 16 ++++++++++++++++ 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/draft-tuist-workspace.md index a61796d8..848e6325 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.md +++ b/Documentations/Evolutions/draft-tuist-workspace.md @@ -590,3 +590,5 @@ let tuist = Tuist( | 2026-11-20 | `build` / `test` 加 `--scheme` | 本地模式下要跑上游库各自的测试 scheme(`<包名> Tests`)。 | | 2026-11-20 | MachOKitExtensions 的 `next` 已不需要适配块,仍按决定加上 | 探针用的是它的 `main`(有 `CPlusPlusSymbolsFixture`),`next` 上这个测试支撑 target 已经没有了,块目前不起作用。另:本库 `.worktrees/MachOKitExtensions` 链接指向它的主检出(`main`),不是它的 `next` worktree,所以公司那台上的本地模式编的是 `main`,预检会因为那个 target 关掉测试并点名。 | | 2026-11-20 | Tuist 往 `PrecompiledLibraries/swift-syntax/` 里写 `.build/` | 它是按路径声明的包,Tuist 在那里下载二进制产物;与它生成的工程一起写进 `.gitignore`。 | +| 2026-11-20 | `SwiftSymbolsRegistration` 整个 `-force_load` | Ultra 上第一次跑通测试 scheme:2,935 通过、8 失败,原生 `swift test` 同一台、同一个 Xcode 27.2 全部通过(21 个 bundle、2,905 个测试)。`SwiftSymbolsTests` 里 `registeredLanguages → []`:这个 C target 只有一个 `static` 的加载期 constructor、没有全局符号,SwiftPM 整块链接 target 所以它总会跑,Tuist 的静态 framework 里这个成员没人引用、链接器不拉。脚本找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出会链到它的测试与可执行 target,传进 `TUIST_FORCE_LOADS`。同一机制意味着 RuntimeViewer 的 Tuist workspace(静态 framework,只加了 `-ObjC`)里 Swift 也没注册成符号语言——按链接方式推断,没有实测,不在本提案范围内修。 | +| 2026-11-20 | 测试与 `swift-section` 链接时加 `-ObjC` | 修好注册后还剩 4 条,都在包装读取器(`MachOReaderWrapper`)上:没人点名的 protocol conformance 所在的归档成员没被链进来,`as?` 静默失败。与 RuntimeViewer 的 Tuist workspace 一样加 `-ObjC`;测试 target 的部署版本、`-ObjC` 与 `-force_load` 合进同一份设置,免得两处 `OTHER_LDFLAGS` 互相覆盖。`SwiftSymbolsTests` 与 `SwiftInspectionTests` 重跑 227 个全部通过。 | diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index 3aec60fd..000f5c91 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -94,6 +94,8 @@ Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` - **CLI 的部署版本是 macOS 12.0**(`Tuist/CommandLine/Project.swift`):Tuist 把 swift-argument-parser 编成它声明的最低版本 macOS 12,10.15 的 `swift-section` import 不了它。 - **测试 target 的部署版本抬到 macOS 14.0**(`Tuist/Package.swift` 的 `testTargetSettings`):SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(Xcode 26、27 都是 14.0),包声明的更低也一样;Tuist 照搬包声明的 10.15,`TypeIndexingTests` 于是找不到它测的 macOS 13 API。脚本把所有转换进来的测试 target(含 `IntegrationTests`,免得编整个 workspace 时它编不过)传进 `TUIST_TEST_TARGET_NAMES`。 +- **测试 target 与 `swift-section` 链接时带 `-ObjC`**(`Tuist/Package.swift` 的 `testTargetSettings`,`Tuist/CommandLine/Project.swift` 的 `linkFlags`):SwiftPM 把每个包 target 的目标文件整块链进去;Tuist 编的是静态 framework,链接器只拉被符号引用到的归档成员。没人点名的 protocol conformance 于是丢了,`as?` 静默失败:包装 `MachOImage` / `MachOFile` 的读取器(`MachOReaderWrapper`)两样都不像,`WrappedReaderSymbolTests` 与 `WrappedReaderDemanglingTests` 红了 4 条。Xcode 27 的链接器下 `-ObjC` 会拉进所有定义了 ObjC 类或分类、Swift 类型或 extension 的成员,与 RuntimeViewer 的 Tuist workspace 同一个做法。 +- **`SwiftSymbolsRegistration` 被整个 `-force_load`**:它只有一个 `static` 的加载期 constructor(把 Swift 注册成符号语言),没有任何全局符号,`-ObjC` 也拉不进它。不加的话 Swift 语言没注册,`SwiftSymbolsTests` 红 281 处,Tuist 编的 `swift-section` 也会把 Swift 符号当成 C。脚本读清单时找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出哪些测试 target 与可执行 target 会链到它,传进 `TUIST_FORCE_LOADS`;这些链接对那个归档加 `-force_load`。 - **导入了 Testing 的库 target 加上 TestingMacros 插件路径**(`Tuist/Package.swift` 的 `testingSupportSettings`):`SwiftSectionTestingSupport` 是普通的库 target,却用了 Swift Testing 的 `#require`。SwiftPM 给每个 target 都带上工具链的 TestingMacros 插件,Xcode 只给测试 target 带,于是报 `plugin for module 'TestingMacros' not found`。脚本读清单时找出源码里 `import Testing` 的库 target(本地模式下还有上游库的,比如 swift-demangling 的 `DemanglingTestingSupport`),传进 `TUIST_TESTING_SUPPORT_TARGET_NAMES`。 - **手写的 target 设了 `SWIFT_PACKAGE_NAME = MachOSwiftSection`**(`Tuist/CommandLine/Project.swift`):`SwiftSectionCommandTests` 调用 SwiftSectionKit 的 `package` 方法,只有同一个包的模块看得见;Tuist 给它转换的 target 都设了这个值,手写的也要设。 - **`CAPSTONE_HAS_AARCH64` 手动补上**:Tuist 丢掉只以 trait 为条件的设置;本库开了 swift-capstone 的 `AARCH64` trait,不补的话 Swift 包装编不过,C 库能编过但没有任何架构可用。 diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 4924e03f..51a516d0 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -73,6 +73,7 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0 // with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and // MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // TUIST_RAISED_TEST_TARGET_NAMES lists the test targets of the packages that declare less. // - It links each package target's object files whole, where Tuist links static frameworks and the // linker loads only the archive members something refers to by symbol. A protocol conformance // nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage @@ -93,15 +94,17 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac }, uniquingKeysWith: + ) + let raisedTestTargetNames = Set(targetNames(in: "TUIST_RAISED_TEST_TARGET_NAMES")) let testTargetSettings: [String: Settings] = Dictionary( targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)" } - return (targetName, Settings.settings(base: [ - "MACOSX_DEPLOYMENT_TARGET": "14.0", - "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags), - ])) + var settings: SettingsDictionary = ["OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags)] + if raisedTestTargetNames.contains(targetName) { + settings["MACOSX_DEPLOYMENT_TARGET"] = "14.0" + } + return (targetName, Settings.settings(base: settings)) }, uniquingKeysWith: { first, _ in first } ) diff --git a/TuistScript.sh b/TuistScript.sh index 6757f189..fcae6597 100755 --- a/TuistScript.sh +++ b/TuistScript.sh @@ -619,6 +619,15 @@ def dependency_name(dependency): return None source_targets, warning_targets, test_entries, test_names, testing_support_names, rejected = [], [], [], [], [], [] +# The test targets of a package that declares a macOS minimum below the one XCTest and Swift Testing need. +raised_test_names = [] +minimum_test_macos = (14, 0) + +def declared_macos(manifest): + for platform in manifest.get("platforms", []): + if platform["platformName"] == "macos": + return tuple(int(part) for part in platform["version"].split(".")) + return (10, 13) testing_import = re.compile(r"^\s*(@\w+\s+)*((public|package|internal)\s+)?import\s+Testing\b", re.MULTILINE) constructor_attribute = re.compile(r"__attribute__\s*\(\(\s*constructor\b") @@ -695,6 +704,8 @@ for identity, role, directory in packages: regular_names = {target["name"] for target in targets if target["type"] == "regular"} tests = [target for target in targets if target["type"] == "test"] test_names += [test["name"] for test in tests] + if declared_macos(manifest) < minimum_test_macos: + raised_test_names += [test["name"] for test in tests] for test in tests: for dependency in test["dependencies"]: name = dependency_name(dependency) @@ -724,6 +735,7 @@ print("SOURCE_TARGETS=" + ",".join(source_targets)) print("WARNING_TARGETS=" + ",".join(warning_targets)) print("TEST_TARGETS=" + ";".join(test_entries)) print("TEST_TARGET_NAMES=" + ",".join(test_names)) +print("RAISED_TEST_TARGET_NAMES=" + ",".join(raised_test_names)) print("TESTING_SUPPORT_TARGET_NAMES=" + ",".join(testing_support_names)) print("FORCE_LOADS=" + ",".join(force_loads)) for reason in rejected: @@ -733,6 +745,7 @@ PYTHON TUIST_WARNING_TARGET_NAMES="" TUIST_PACKAGE_TEST_TARGETS="" TUIST_TEST_TARGET_NAMES="" + TUIST_RAISED_TEST_TARGET_NAMES="" TUIST_TESTING_SUPPORT_TARGET_NAMES="" TUIST_FORCE_LOADS="" TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 @@ -742,6 +755,7 @@ PYTHON WARNING_TARGETS) TUIST_WARNING_TARGET_NAMES="$value";; TEST_TARGETS) TUIST_PACKAGE_TEST_TARGETS="$value";; TEST_TARGET_NAMES) TUIST_TEST_TARGET_NAMES="$value";; + RAISED_TEST_TARGET_NAMES) TUIST_RAISED_TEST_TARGET_NAMES="$value";; TESTING_SUPPORT_TARGET_NAMES) TUIST_TESTING_SUPPORT_TARGET_NAMES="$value";; FORCE_LOADS) TUIST_FORCE_LOADS="$value";; REJECTED) @@ -755,8 +769,10 @@ PYTHON warn "the tests stay out of the workspace this time. Each manifest above needs the TUIST_MAPS_LOCAL_PACKAGE_TESTS block MachOSwiftSection's Package.swift ends with (Documentations/Internal/TuistDevelopment.md)." TUIST_PACKAGE_TEST_TARGETS="" TUIST_TEST_TARGET_NAMES="" + TUIST_RAISED_TEST_TARGET_NAMES="" fi export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_TEST_TARGET_NAMES \ + TUIST_RAISED_TEST_TARGET_NAMES \ TUIST_TESTING_SUPPORT_TARGET_NAMES TUIST_FORCE_LOADS TUIST_MAPS_LOCAL_PACKAGE_TESTS } From ca9733e6edbffb2a76e0e133140c839792c7d1f9 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 13:53:03 +0800 Subject: [PATCH 011/175] fix: run the Tuist test schemes without Xcode's runtime checkers; name the tool swift-section The Thread Performance Checker inserts libRPAC.dylib into the test process and rebinds calls in the loaded images, so a cross-reference test comparing a cache image read in process with its file saw calls into libRPAC. The test schemes turn it and the Main Thread Checker off; Tuist 4.210 writes only the latter's attribute, so TuistScript.sh adds disablePerformanceAntipatternChecker after generating. Tuist named the executable swift_section; productName restores swift-section. Proposal: draft-tuist-workspace --- Tuist/CommandLine/Project.swift | 3 +++ TuistScript.sh | 29 +++++++++++++++++++++++++++++ Workspace.swift | 14 +++++++++++++- 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift index 7ede8d4e..30ffd914 100644 --- a/Tuist/CommandLine/Project.swift +++ b/Tuist/CommandLine/Project.swift @@ -64,6 +64,9 @@ let project = Project( name: "swift-section", destinations: .macOS, product: .commandLineTool, + // Tuist would name the executable swift_section, as it turns every dash of a target's name + // into an underscore. + productName: "swift-section", bundleId: "com.machoswiftsection.swift-section", deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, diff --git a/TuistScript.sh b/TuistScript.sh index fcae6597..2085e937 100755 --- a/TuistScript.sh +++ b/TuistScript.sh @@ -805,6 +805,35 @@ generate_workspace() { log "Generating $WORKSPACE ($configuration, $CURRENT_DEPENDENCY_MODE dependencies)" run_tuist "generate-$configuration" "${TUIST[@]}" generate --no-open --configuration "$configuration" \ || fail "tuist generate failed" + turn_off_the_thread_performance_checker +} + +# The test schemes run their tests the way `swift test` does, without Xcode's Thread Performance +# Checker: it inserts libRPAC.dylib, which rebinds calls in the loaded images, and the cross-reference +# tests that compare a cache image read in process with the same image read from its file then see +# calls into libRPAC. Workspace.swift asks for it to be off, but Tuist 4.210 writes only the Main +# Thread Checker's attribute into a scheme's TestAction, so this adds the other one. +turn_off_the_thread_performance_checker() { + $DRY_RUN && return 0 + python3 - "$WORKSPACE/xcshareddata/xcschemes" <<'SCHEME_EDIT' +import glob +import os +import re +import sys + +for path in glob.glob(os.path.join(sys.argv[1], "* Tests.xcscheme")): + with open(path) as handle: + scheme = handle.read() + def add_attribute(match): + element = match.group(0) + if "disablePerformanceAntipatternChecker" in element: + return element + return element[:-1].rstrip() + '\n disablePerformanceAntipatternChecker = "YES">' + updated = re.sub(r"]*>", add_attribute, scheme, count=1) + if updated != scheme: + with open(path, "w") as handle: + handle.write(updated) +SCHEME_EDIT } warm_cache() { diff --git a/Workspace.swift b/Workspace.swift index 88de0fc7..d3a111ff 100644 --- a/Workspace.swift +++ b/Workspace.swift @@ -41,6 +41,18 @@ let workspace = Workspace( parallelization: .swiftTestingOnly )) } - return .scheme(name: "\(packageName(ofDirectory: entry.directory)) Tests", testAction: .targets(testableTargets)) + return .scheme( + name: "\(packageName(ofDirectory: entry.directory)) Tests", + testAction: .targets( + testableTargets, + // The test process as `swift test` runs it. The Thread Performance Checker inserts + // libRPAC.dylib, which rebinds calls in the loaded images: the cross-reference tests that + // compare a cache image read in process with the same image read from its file then + // see calls into libRPAC. The Main Thread Checker swizzles Objective-C methods the same + // way. Tuist 4.210 writes only the Main Thread Checker's attribute; TuistScript.sh adds + // disablePerformanceAntipatternChecker to the generated schemes. + diagnosticsOptions: .options(mainThreadCheckerEnabled: false, performanceAntipatternCheckerEnabled: false) + ) + ) } ) From 7861e59071f7a3c76de416cc342a85486e04f589 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 14:11:17 +0800 Subject: [PATCH 012/175] docs: record the Tuist test schemes' runtime checkers and the tool's product name Proposal: draft-tuist-workspace --- Documentations/Evolutions/draft-tuist-workspace.md | 3 +++ Documentations/Internal/TuistDevelopment.md | 2 ++ 2 files changed, 5 insertions(+) diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/draft-tuist-workspace.md index 848e6325..0decf81c 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.md +++ b/Documentations/Evolutions/draft-tuist-workspace.md @@ -592,3 +592,6 @@ let tuist = Tuist( | 2026-11-20 | Tuist 往 `PrecompiledLibraries/swift-syntax/` 里写 `.build/` | 它是按路径声明的包,Tuist 在那里下载二进制产物;与它生成的工程一起写进 `.gitignore`。 | | 2026-11-20 | `SwiftSymbolsRegistration` 整个 `-force_load` | Ultra 上第一次跑通测试 scheme:2,935 通过、8 失败,原生 `swift test` 同一台、同一个 Xcode 27.2 全部通过(21 个 bundle、2,905 个测试)。`SwiftSymbolsTests` 里 `registeredLanguages → []`:这个 C target 只有一个 `static` 的加载期 constructor、没有全局符号,SwiftPM 整块链接 target 所以它总会跑,Tuist 的静态 framework 里这个成员没人引用、链接器不拉。脚本找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出会链到它的测试与可执行 target,传进 `TUIST_FORCE_LOADS`。同一机制意味着 RuntimeViewer 的 Tuist workspace(静态 framework,只加了 `-ObjC`)里 Swift 也没注册成符号语言——按链接方式推断,没有实测,不在本提案范围内修。 | | 2026-11-20 | 测试与 `swift-section` 链接时加 `-ObjC` | 修好注册后还剩 4 条,都在包装读取器(`MachOReaderWrapper`)上:没人点名的 protocol conformance 所在的归档成员没被链进来,`as?` 静默失败。与 RuntimeViewer 的 Tuist workspace 一样加 `-ObjC`;测试 target 的部署版本、`-ObjC` 与 `-force_load` 合进同一份设置,免得两处 `OTHER_LDFLAGS` 互相覆盖。`SwiftSymbolsTests` 与 `SwiftInspectionTests` 重跑 227 个全部通过。 | +| 2026-11-20 | 只给声明低于 macOS 14 的包的测试抬部署版本 | 六个包今天都声明 10.15,但以后有包声明 15 时,统一设 14.0 会把它的测试调低。脚本另传 `TUIST_RAISED_TEST_TARGET_NAMES`;`-ObjC` 与 `-force_load` 照旧给全部测试。 | +| 2026-11-20 | 测试 scheme 关掉 Xcode 的两个运行时检查 | 全量重跑后只剩 `FileModeTests.fileModeMatchesInProcessReferencesOnTheRunningSystemCache` 一条:进程内的调用目标落在 `/usr/lib/libRPAC.dylib`。那是 Thread Performance Checker 插入的库,它改写了已加载镜像里的调用;`swift test` 的进程里没有它。`Workspace.swift` 的测试 scheme 关掉它与 Main Thread Checker;Tuist 4.210 只写后者的属性,脚本生成后给 `* Tests.xcscheme` 的 TestAction 补 `disablePerformanceAntipatternChecker = "YES"`。 | +| 2026-11-20 | 工具 target 写明 `productName` | Tuist 把 target 名里的 `-` 换成 `_`,可执行文件成了 `swift_section`。 | diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index 000f5c91..8ba87cff 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -92,6 +92,8 @@ Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` 都是为了绕开 Tuist 4.210 的行为,改之前先看这里。 +- **测试 scheme 关掉了 Main Thread Checker 与 Thread Performance Checker**(`Workspace.swift`,以及脚本生成后补的 `disablePerformanceAntipatternChecker`):后者往测试进程里插入 `libRPAC.dylib`,改写已加载镜像里的调用,`CrossReferenceAnalysisTests` 里拿进程内读到的 cache 镜像和同一镜像的文件比对的测试就看到一批指向 `libRPAC` 的调用而失败。关掉之后测试进程与 `swift test` 的一样。Tuist 4.210 只往 TestAction 写主线程检查那一项,另一项由脚本在生成后补上,所以别直接跑 `tuist generate`。 +- **工具 target 写明 `productName: "swift-section"`**:Tuist 会把 target 名里的 `-` 换成 `_`,不写的话编出来的可执行文件叫 `swift_section`。 - **CLI 的部署版本是 macOS 12.0**(`Tuist/CommandLine/Project.swift`):Tuist 把 swift-argument-parser 编成它声明的最低版本 macOS 12,10.15 的 `swift-section` import 不了它。 - **测试 target 的部署版本抬到 macOS 14.0**(`Tuist/Package.swift` 的 `testTargetSettings`):SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(Xcode 26、27 都是 14.0),包声明的更低也一样;Tuist 照搬包声明的 10.15,`TypeIndexingTests` 于是找不到它测的 macOS 13 API。脚本把所有转换进来的测试 target(含 `IntegrationTests`,免得编整个 workspace 时它编不过)传进 `TUIST_TEST_TARGET_NAMES`。 - **测试 target 与 `swift-section` 链接时带 `-ObjC`**(`Tuist/Package.swift` 的 `testTargetSettings`,`Tuist/CommandLine/Project.swift` 的 `linkFlags`):SwiftPM 把每个包 target 的目标文件整块链进去;Tuist 编的是静态 framework,链接器只拉被符号引用到的归档成员。没人点名的 protocol conformance 于是丢了,`as?` 静默失败:包装 `MachOImage` / `MachOFile` 的读取器(`MachOReaderWrapper`)两样都不像,`WrappedReaderSymbolTests` 与 `WrappedReaderDemanglingTests` 红了 4 条。Xcode 27 的链接器下 `-ObjC` 会拉进所有定义了 ObjC 类或分类、Swift 类型或 extension 的成员,与 RuntimeViewer 的 Tuist workspace 同一个做法。 From 5c73a64a709e0fbc3a93b7888d075dc64b4cae93 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 15:18:11 +0800 Subject: [PATCH 013/175] docs: record the Tuist workspace's local-mode run and cache timing; mark the implementation done Sync the proposal's detailed design with the files as implemented, record the local-mode test results and the binary-cache timing measured on Ultra, and add the timing and the upstream fixed-path test failures to the guide. --- .../Evolutions/draft-tuist-workspace.md | 267 ++++++++++++++---- Documentations/Internal/TuistDevelopment.md | 3 +- 2 files changed, 209 insertions(+), 61 deletions(-) diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/draft-tuist-workspace.md index 0decf81c..e603663f 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.md +++ b/Documentations/Evolutions/draft-tuist-workspace.md @@ -47,7 +47,7 @@ 9. **`Tuist.swift` 能读环境变量**:把 `TUIST_SOURCE_TARGET_NAMES=Utilities,SwiftSymbols,MachOSwiftSection` 经 `Environment.sourceTargetNames` 读进缓存 profile,`tuist dump config` 显示 `exceptTargetQueries` 正是这三个名字。缓存例外名单因此可以由脚本从各包清单算出来,不用像 RuntimeViewer 那样手抄、再用 `check` 守着。 10. **`tuist install` 解析出的远程依赖**(远程模式,种子锁文件取自集成 worktree 的 `Package.resolved`):AssociatedObject、capstone、combine-schedulers、FrameworkToolbox、MetaCodable、Rainbow、SourceKitD、swift-apinotes、swift-argument-parser、swift-asn1、swift-async-algorithms、swift-binary-parse-support、swift-capstone、swift-clocks、swift-collections、swift-concurrency-extras、swift-crypto、swift-dependencies、swift-fileio、swift-fileio-extra、swift-issue-reporting、swift-literal-type-inference、swift-memberwise-init-macro、swift-object-association、swift-objc-dump、swift-snapshot-testing、Yams,加上五个上游库。 -### 推测(未验证,落地步骤里验证) +### 推测(写提案时未验证;实现中全部证实,见决策日志) - 测试 target 的部署版本:SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(macOS 14.0),Tuist 照搬包声明的 10.15,RuntimeViewer 因此在 `Duration`、`timeLimit` 上编不过。本库测试大概率踩同一个坑。 - `-ObjC`:Tuist 把包编成静态库,链接器只拉被符号引用到的成员。本库测试是否依赖按名字在运行时查找的类,没查过。 @@ -182,7 +182,7 @@ legacy: /runtimeviewer-tuist-local-dependencies is live 本库与三个上游库的 `Package.swift` 末尾原样加这一段(探针里五个上游库副本都用它通过了 `swift package dump-package` 与 `tuist generate`)。它读的是 `Context.environment`,平时这个变量不存在,块里什么都不做;作为别人的远程依赖时也一样。 ```swift -// The Tuist development workspace (MachOSwiftSection's Documentations/Internal/TuistDevelopment.md) +// MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md) // maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends // on an executable target, and a test that depends on a target no product contains. Only while Tuist // resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the @@ -221,14 +221,24 @@ if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" { import Foundation import PackageDescription -// The dependencies of MachOSwiftSection-Tuist.xcworkspace (Documentations/Internal/TuistDevelopment.md). -// This package is declared by path, so its Package.swift stays the only definition of its targets. -// In the local dependency mode TuistScript.sh names the upstream packages in TUIST_LOCAL_PACKAGE_NAMES -// and their directory in TUIST_LOCAL_PACKAGE_CHECKOUTS; a root's path dependency stands in for every -// declaration of the same package in the graph. +// The dependencies of MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +// (Documentations/Internal/TuistDevelopment.md). Generate it with ./TuistScript.sh, never with a bare +// `tuist generate`: the script sets the variables everything below reads. +// +// MachOSwiftSection itself is declared by path, so its Package.swift stays the only definition of its +// targets and dependencies. In the local dependency mode (`./TuistScript.sh +// --local-dependencies`) the script names the upstream packages the native workspace lists beside +// the checkout in TUIST_LOCAL_PACKAGE_NAMES and the directory holding them in +// TUIST_LOCAL_PACKAGE_CHECKOUTS. A root's path dependency stands in for every other declaration of the +// same package in the graph — MachOSwiftSection's URLs and the upstream packages' own — so they build +// from those checkouts, uncommitted edits included. A path package's identity is its directory's name. let processEnvironment = ProcessInfo.processInfo.environment let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? "" -let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "").split(separator: ",").map(String.init) +let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "") + .split(separator: ",") + .map(String.init) +// Qualified: Tuist evaluates this file with ProjectDescription imported too, which has a Package of +// its own. let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty ? [] : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") } @@ -236,20 +246,24 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac #if TUIST import ProjectDescription - func names(_ variable: String) -> [String] { + func targetNames(in variable: String) -> [String] { (processEnvironment[variable] ?? "").split(separator: ",").map(String.init) } - // Tuist suppresses warnings in every package; Xcode does so for remote packages only. + // Tuist suppresses warnings in every package; Xcode does so for remote packages only. The targets + // of the packages declared by path get theirs back: MachOSwiftSection always, the upstream + // packages in the local dependency mode. let warningSettings: [String: Settings] = Dictionary( - names("TUIST_WARNING_TARGET_NAMES").map { targetName in + targetNames(in: "TUIST_WARNING_TARGET_NAMES").map { targetName in (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"])) }, uniquingKeysWith: { first, _ in first } ) - // Tuist drops a setting whose only condition is a trait; this package enables swift-capstone's - // AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 that way. + // Tuist drops a package setting whose only condition is a trait. MachOSwiftSection enables + // swift-capstone's AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 for both the Swift wrapper and + // the C library that way. Without it the wrapper does not compile, and the C library would compile + // but support no architecture at all. let restatedTraitDefinitions: [String: Settings] = [ "Capstone": .settings(base: [ "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"], @@ -260,14 +274,71 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac ]), ] - // Filled in by step 2 once the tests have been built: the deployment target SwiftPM gives a test - // target (macOS 14.0) and -ObjC, each only if the build shows it is needed. - let testTargetSettings: [String: Settings] = [:] + // A library target that imports Testing, such as a package's testing support, uses Swift Testing's + // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros + // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library + // targets whose sources import Testing. + let testingSupportSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TESTING_SUPPORT_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: [ + "ENABLE_TESTING_SEARCH_PATHS": "YES", + "OTHER_SWIFT_FLAGS": ["$(inherited)", "-plugin-path", "$(TOOLCHAIN_DIR)/usr/lib/swift/host/plugins/testing"], + ])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // The test targets, which SwiftPM builds and links differently in three ways: + // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0 + // with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and + // MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // TUIST_RAISED_TEST_TARGET_NAMES lists the test targets of the packages that declare less. + // - It links each package target's object files whole, where Tuist links static frameworks and the + // linker loads only the archive members something refers to by symbol. A protocol conformance + // nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage + // or MachOFile (MachOReaderWrapper) read as neither. -ObjC also loads every member that defines an + // Objective-C class or category or a Swift type or extension (Xcode 27's linker), as it does for + // RuntimeViewer's Tuist workspace. + // - A load-time constructor nothing refers to never runs that way at all: MachOSwiftSection's + // SwiftSymbolsRegistration registers Swift as a symbol language from one. TUIST_FORCE_LOADS pairs + // each final link with the constructor targets its in-package dependencies reach, as + // ":,…"; those archives are loaded whole. + // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build + // of the whole workspace compiles and links too. Tuist/CommandLine/Project.swift gives the + // swift-section executable and SwiftSectionCommandTests the same link flags. + let forceLoadedTargetsByLinkingTarget: [String: [String]] = Dictionary( + targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair -> (String, [String])? in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 ? (parts[0], [parts[1]]) : nil + }, + uniquingKeysWith: + + ) + let raisedTestTargetNames = Set(targetNames(in: "TUIST_RAISED_TEST_TARGET_NAMES")) + let testTargetSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in + let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)" + } + var settings: SettingsDictionary = ["OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags)] + if raisedTestTargetNames.contains(targetName) { + settings["MACOSX_DEPLOYMENT_TARGET"] = "14.0" + } + return (targetName, Settings.settings(base: settings)) + }, + uniquingKeysWith: { first, _ in first } + ) + + // One target may need several of the settings above; their keys never overlap. + func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { + settingsByTarget.reduce(into: [:]) { merged, settings in + merged.merge(settings) { first, second in .settings(base: first.base.merging(second.base) { $1 }) } + } + } let packageSettings = PackageSettings( - targetSettings: warningSettings - .merging(restatedTraitDefinitions) { $1 } - .merging(testTargetSettings) { $1 }, + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), + // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of + // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" ) #endif @@ -276,9 +347,11 @@ let package = Package( name: "MachOSwiftSectionTuistDependencies", dependencies: [ .package(path: ".."), - // Stands in for swift-syntax everywhere, as it does as a member of the native workspace. + // Stands in for swift-syntax in every macro package, as it does as a member of the native + // workspace: SwiftPM matches it by package identity. .package(path: "../PrecompiledLibraries/swift-syntax"), - // Used only by tests, which Tuist needs declared here (MachOSwiftSection's requirement). + // Used only by MachOSwiftSection's tests. Tuist maps a test target only when every package + // its dependencies come from is declared here, with the requirement Package.swift gives it. .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"), ] + localPackageDependencies ) @@ -292,11 +365,15 @@ let package = Package( ```swift import ProjectDescription -// What Tuist cannot convert from ../../Package.swift: the swift-section executable, and -// SwiftSectionCommandTests, which imports the executable's module. swift_section compiles the same -// sources as a static framework for that test; the tool compiles them again, so its link needs no -// trick around the @main entry point. The dependency list mirrors Package.swift's swift-section -// target and is the one hand-written copy in the Tuist description. +// What Tuist cannot convert from ../../Package.swift (Documentations/Internal/TuistDevelopment.md): +// the swift-section executable, and SwiftSectionCommandTests, which imports the executable's module +// (`@testable import swift_section`). Tuist converts no executable target and rejects a test that +// depends on one, so Package.swift leaves that test out while Tuist resolves it and it is described +// here instead. swift_section compiles the command's sources as a static framework for the test; the +// tool compiles them again, so its link needs no trick around the @main entry point. +// +// The dependency list mirrors the swift-section target in Package.swift and is the one hand-written +// copy in the Tuist description: a dependency added there that is missing here fails to compile. let commandLineDependencies: [TargetDependency] = [ .external(name: "SwiftSectionKit"), .external(name: "MachOFoundation"), @@ -313,32 +390,60 @@ let commandLineDependencies: [TargetDependency] = [ .external(name: "ArgumentParser"), ] +// Tuist builds swift-argument-parser for macOS 12, the minimum that package declares; the package's +// own 10.15 does not reach the executable here the way SwiftPM's build of it does. +let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") + let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] +// The link flags Tuist/Package.swift gives the package's test targets, for the same reasons: -ObjC, so +// that the archive members defining Swift types and extensions (protocol conformances among them) are +// loaded, and -force_load of the constructor targets the swift-section executable reaches in +// Package.swift, which TuistScript.sh lists in TUIST_FORCE_LOADS. +let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "") + .split(separator: ",") + .compactMap { pair in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil + } +let linkFlags: SettingsDictionary = [ + "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadedTargetNames.map { targetName in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)" + }), +] + // MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; // TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. -let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: false) - ? .settings(base: ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]]) - : .settings() +let commandTestSettings: Settings = .settings(base: linkFlags.merging( + Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:] +) { $1 }) let project = Project( name: "MachOSwiftSectionCommandLine", + // In SwiftPM these targets belong to the MachOSwiftSection package, whose `package` declarations + // they use (SwiftSectionCommandTests calls SwiftSectionKit's applyTransformersEnablingCommentKinds). + // Tuist gives the targets it converts SWIFT_PACKAGE_NAME = MachOSwiftSection; these need the same. + settings: .settings(base: ["SWIFT_PACKAGE_NAME": "MachOSwiftSection"]), targets: [ .target( name: "swift-section", destinations: .macOS, product: .commandLineTool, + // Tuist would name the executable swift_section, as it turns every dash of a target's name + // into an underscore. + productName: "swift-section", bundleId: "com.machoswiftsection.swift-section", - deploymentTargets: .macOS("10.15"), + deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, - dependencies: commandLineDependencies + dependencies: commandLineDependencies, + settings: .settings(base: linkFlags) ), .target( name: "swift_section", destinations: .macOS, product: .staticFramework, bundleId: "com.machoswiftsection.swift-section.module", - deploymentTargets: .macOS("10.15"), + deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, dependencies: commandLineDependencies ), @@ -368,9 +473,14 @@ let project = Project( ```swift import ProjectDescription -// "=,;…" from TuistScript.sh, one entry per package whose -// tests are mapped: this package always (directory "."), the upstream packages in the local mode. -// IntegrationTests is never listed. +// MachOSwiftSection-Tuist.xcworkspace, the development-only workspace Tuist generates beside the +// native MachOSwiftSection.xcworkspace (Documentations/Internal/TuistDevelopment.md). +// +// The packages' test targets live in the projects Tuist converts from their Package.swift files, which +// only a workspace scheme can reference. TuistScript.sh lists them in TUIST_PACKAGE_TEST_TARGETS as +// "=,;…", one entry per package whose tests are mapped: +// MachOSwiftSection always (directory "."), the upstream packages in the local dependency mode +// (absolute directories). IntegrationTests, the maintainer's manual-inspection target, is never listed. let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets .getString(default: "") .split(separator: ";") @@ -380,18 +490,43 @@ let packageTestTargets: [(directory: String, targets: [String])] = Environment.p return (parts[0], parts[1].split(separator: ",").map(String.init)) } +func packageName(ofDirectory directory: String) -> String { + directory == "." ? "MachOSwiftSection" : String(directory.split(separator: "/").last ?? Substring(directory)) +} + +func projectPath(ofDirectory directory: String) -> Path { + directory.hasPrefix("/") ? .path(directory) : .relativeToRoot(directory) +} + let workspace = Workspace( name: "MachOSwiftSection-Tuist", projects: ["Tuist/CommandLine"], schemes: packageTestTargets.map { entry in - let packageName = entry.directory == "." ? "MachOSwiftSection" : (entry.directory as NSString).lastPathComponent var testableTargets = entry.targets.map { targetName in - TestableTarget.testableTarget(target: .project(path: Path(entry.directory), target: targetName)) + TestableTarget.testableTarget( + target: .project(path: projectPath(ofDirectory: entry.directory), target: targetName), + parallelization: .swiftTestingOnly + ) } if entry.directory == "." { - testableTargets.append(.testableTarget(target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"))) + testableTargets.append(.testableTarget( + target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"), + parallelization: .swiftTestingOnly + )) } - return .scheme(name: "\(packageName) Tests", testAction: .targets(testableTargets)) + return .scheme( + name: "\(packageName(ofDirectory: entry.directory)) Tests", + testAction: .targets( + testableTargets, + // The test process as `swift test` runs it. The Thread Performance Checker inserts + // libRPAC.dylib, which rebinds calls in the loaded images: the cross-reference tests that + // compare a cache image read in process with the same image read from its file then + // see calls into libRPAC. The Main Thread Checker swizzles Objective-C methods the same + // way. Tuist 4.210 writes only the Main Thread Checker's attribute; TuistScript.sh adds + // disablePerformanceAntipatternChecker to the generated schemes. + diagnosticsOptions: .options(mainThreadCheckerEnabled: false, performanceAntipatternCheckerEnabled: false) + ) + ) } ) ``` @@ -404,9 +539,12 @@ let workspace = Workspace( ```swift import ProjectDescription -// Every target of MachOSwiftSection and of the five upstream packages stays source, in both dependency -// modes; every other dependency comes out of the binary cache once warmed. TuistScript.sh reads the -// names from the packages' manifests. No fullHandle: the cache stays on this machine. +// Every target of MachOSwiftSection and of the five upstream packages its native workspace lists +// (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) stays +// source, in both dependency modes; every other dependency comes out of the binary cache once +// `./TuistScript.sh warm` has filled it. The script reads the names from the packages' manifests and +// passes them in TUIST_SOURCE_TARGET_NAMES. No fullHandle: the cache stays on this machine and +// nothing is uploaded. Documentations/Internal/TuistDevelopment.md. let sourceTargetNames = Environment.sourceTargetNames .getString(default: "") .split(separator: ",") @@ -438,8 +576,8 @@ let tuist = Tuist( | `install` | 从种子锁文件开始解析当前模式的依赖(`tuist install`),结束时与种子比对 pin | | `generate [--configuration ]` | 需要时先 `install`,占用检出,生成 workspace(默认 Debug) | | `warm [--configuration ]` | 带 `--cache-profile development` 把第三方依赖编进缓存,再生成 | -| `build [--configuration ]` | 生成后用 `xcodebuild` 编 `swift-section` scheme | -| `test [-- ]` | 生成后用 `xcodebuild test` 跑 `MachOSwiftSection Tests` scheme,退出码就是 `xcodebuild` 的 | +| `build [--configuration ] [--scheme ] [-- ]` | 生成后用 `xcodebuild` 编 `swift-section` scheme,或另一个 | +| `test [--configuration ] [--scheme ] [-- ]` | 生成后用 `xcodebuild test` 跑 `MachOSwiftSection Tests` scheme(本地模式下上游库各有 `<包名> Tests`),结果存进 `Work//TestResults/*.xcresult` 并打印通过 / 失败 / 跳过的个数,退出码就是 `xcodebuild` 的 | | `release` | 放弃所有占用:删掉生成进各检出的工程(git 跟踪的不删)、占用记录与 `MachOSwiftSection-Tuist.xcworkspace`;`Derived/` 留着 | `--local-dependencies` / `--remote-dependencies` 可以跟在任何命令后面,从这条命令起切换模式;`--dry-run` 打印要做的事;`--help` 打印脚本头部的说明。 @@ -453,25 +591,29 @@ let tuist = Tuist( | `TUIST_SOURCE_TARGET_NAMES` | `Tuist.swift` | 本库与五个上游库的全部 target | | `TUIST_WARNING_TARGET_NAMES` | `Tuist/Package.swift` | 恢复警告的 target:本库全部,本地模式再加上游库全部 | | `TUIST_PACKAGE_TEST_TARGETS` | `Workspace.swift` | 每个映射了测试的包的测试 target,不含 `IntegrationTests` | +| `TUIST_TEST_TARGET_NAMES` | `Tuist/Package.swift` | 所有转换进来的测试 target(含 `IntegrationTests`),给它们 `-ObjC` 与 `-force_load` | +| `TUIST_RAISED_TEST_TARGET_NAMES` | `Tuist/Package.swift` | 声明的 macOS 最低版本低于 14 的包的测试 target,部署版本抬到 14.0 | +| `TUIST_TESTING_SUPPORT_TARGET_NAMES` | `Tuist/Package.swift` | 源码里 `import Testing` 的库 target,加 TestingMacros 插件路径 | +| `TUIST_FORCE_LOADS` | `Tuist/Package.swift`、`Tuist/CommandLine/Project.swift` | `<链接的 target>:<有加载期 constructor 的 target>,…`,后者整个 `-force_load` | | `TUIST_SILENT_TEST` | `Tuist/CommandLine/Project.swift` | 用户设了 `MACHO_SWIFT_SECTION_SILENT_TEST=1` 时为 `1` | | `SWIFTPM_BUILD_DIR` | Tuist | 当前模式的依赖 checkout 目录 | | `TUIST_XDG_CACHE_HOME`、`TUIST_CACHE_WARM_SCRATCH_DIRECTORY` | Tuist | 二进制缓存与预热的临时目录 | `USING_LOCAL_DEPENDENCIES` 被设了就提示一句并 `unset`:它会让本库清单自己换上本地兄弟,连 swift-capstone 一起,与 `Tuist/Package.swift` 的名单对不上。 -**名单从哪来**:本地依赖的名字读 `MachOSwiftSection.xcworkspace/contents.xcworkspacedata` 里的 `container:../<名字>`(不含 `/` 的那些),workspace 加了库这里自动跟上。target 名单用 `swift package dump-package`(带 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1`,`--scratch-path` 放在 `Work//Manifests/`)读六个包的清单:本库与本地模式下的上游库读检出里的,远程模式下的上游库读 `install` 之后 `SWIFTPM_BUILD_DIR/checkouts/<名字>` 里的。远程模式下第一次 `install` 之前还没有 checkout,先用空名单装一次再算。 +**名单从哪来**:本地依赖的名字读 `MachOSwiftSection.xcworkspace/contents.xcworkspacedata` 里的 `container:../<名字>`(不含 `/` 的那些),workspace 加了库这里自动跟上。每次 `install` 之后,脚本用 `swift package dump-package`(带 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1`,8 个并行,`--scratch-path` 放在 `Work//Manifests/Scratch/`)读一遍所有包的清单,存进 `Work//Manifests/`:本库与本地模式下的上游库读检出里的,远程模式下的上游库和全部第三方包读 `SWIFTPM_BUILD_DIR/checkouts/` 里的。`generate`、`warm` 前由 Python 从这些清单算出上表的各个名单,并扫描路径包里 target 的源码找 `import Testing` 与 `__attribute__((constructor))`;Python 出错脚本就失败,不带着空名单生成。 **测试映射的预检**:对每个按路径声明的包,在它的清单 JSON 里找 Tuist 会拒绝的两种形态——测试依赖本包的可执行 target、测试依赖不属于任何 product 的普通 target(实测第 1、3、6 条)。适配块生效时这两种都不该剩下;还剩,说明那个包没有适配块(比如本地检出停在加块之前的提交),这次就整体设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=0`,警告点名那个包,生成照常进行。只被测试用到的外部依赖(实测第 2 条)预检查不出来,生成时 Tuist 自己会报,指南里写怎么补。 **锁文件**:`Tuist/Package.resolved` 不提交(`*.resolved` 已忽略)。每次 `install` 前用本检出根目录的 `Package.resolved` 当种子(没有就不种,由 Tuist 解析最新版本),结束时逐条比对,不同就警告;swift-syntax(这边是预编译包,没有 pin)与本地模式下的五个库不参与比对。 -**依赖模式**:模式记在 `Tuist/.local-dependencies`(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 `.worktrees/`;打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS` 就用它。两种模式各用一份依赖 checkout(`Dependencies/` 与 `Dependencies/-LocalDependencies`),共用 `Tuist/Package.resolved`,所以切换后、或上次解析用的是另一种模式时先重新 `install`(`Work//InstalledDependencies` 记着上次)。切到远程时释放五个上游库的占用。 +**依赖模式**:模式记在 `Tuist/.local-dependencies`(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 `.worktrees/`;打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS` 就用它。两种模式各用一份依赖 checkout(`Dependencies/` 与 `Dependencies/-LocalDependencies`),共用 `Tuist/Package.resolved`,所以切换后、或上次解析用的是另一种模式时先重新 `install`(`Work//InstalledDependencies` 记着上次)。这个记号还带着 `Tuist/Package.swift`、`Package.swift`、种子锁文件与本地模式下各上游库清单的 hash:改了其中任何一个,下一次 `generate` 自己重新解析。切到远程时释放五个上游库的占用。 **存放位置**:`/Volumes/DerivedData` 挂着时全放在 `/Volumes/DerivedData/MachOSwiftSection/Tuist/` 下(`Cache/`、`Dependencies/[-LocalDependencies]/`、`WarmScratch//`、`Work//`),`` 是目录名加路径的短 hash;没挂载时放在仓库里的 `Tuist/.build/`、`Tuist/.build-LocalDependencies/` 与 `DerivedData/Tuist/`(都已忽略)。`TUIST_SCRIPT_ROOT` 指定别处。`build` / `test` 的 DerivedData 在 `Work//DerivedData`。日志在 `Products/Logs/Tuist/`;Tuist 的输出原样显示并记进日志,`xcodebuild` 的输出只进日志,失败时显示错误摘要。 **占用记录**(与 RuntimeViewer 共用): -- 被占的检出:它的 git 目录(`git rev-parse --absolute-git-dir`,worktree 各有一份)里的 `tuist-generated-project-owner`,第一行是占用者检出的路径,第二行是在占用者检出里释放它的命令。 +- 被占的检出:它的 git 目录(`git rev-parse --absolute-git-dir`,worktree 各有一份)里的 `tuist-generated-project-owner`,第一行是占用者检出的路径,第二行是在占用者检出里释放它的命令,第三行是生成进这个检出的工程名(释放时删它)。 - 占用者:自己的 `Tuist/.claimed-checkouts`,每行一个被占检出的真实路径(`pwd -P`)。 - 有效:占用者的 `.claimed-checkouts` 列着这个路径。占用者不在了、或已经不列了,记录就是陈旧的,可以直接覆盖。 - 旧记录 `runtimeviewer-tuist-local-dependencies`:占用者的 `Tuist/.local-dependencies` 加上包名指向这个检出时算有效(RuntimeViewer 今天的规则)。 @@ -480,7 +622,9 @@ let tuist = Tuist( **Tuist 版本**:读 `mise.toml` 的版本;有 mise 就 `mise exec -- tuist`,否则用 PATH 里的 `tuist`;版本不对就失败并提示 `mise install`。 -**agent 运行**:`TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection`,并写成 `queued-build ./TuistScript.sh <命令>`。 +**生成之后**:给每个 `* Tests.xcscheme` 的 TestAction 补 `disablePerformanceAntipatternChecker = "YES"`(Tuist 4.210 只写主线程检查那一项,见决策日志)。 + +**agent 运行**:`TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection`;`warm`、`build`、`test` 要编译,写成 `queued-build ./TuistScript.sh <命令>`,`install`、`generate`、`release` 不编译。 ### RuntimeViewer 那一侧 @@ -488,13 +632,13 @@ let tuist = Tuist( - `release_local_checkouts`:删掉自己的共用记录(以及残留的旧记录),从 `.claimed-checkouts` 里去掉。 - 今天它占着本库的集成 worktree 与五个上游检出(旧记录)。改完后它下一次 `generate` 就把记录换成新的;在那之前,本库的脚本按旧规则认出它的占用。 -### 已知要在实现中确认的点 +### 实现中确认的点(Ultra,Xcode 27.2) -1. `swift_section` 与 `SwiftSectionCommandTests` 能编、能链、`@testable import` 成立(第 2 步)。 -2. 本库测试在 Tuist workspace 里要不要抬部署版本到 14.0、要不要 `-ObjC`(第 2 步,只加确实需要的)。 -3. `Capstone` 的 trait 宏补上后 `SwiftThunkAnalysis` 能编(第 1 步)。 -4. `Workspace.swift` 里按绝对路径引用上游库工程(第 3 步)。 -5. 远程与本地两种模式下,Tuist workspace 跑出的测试数与 `swift test --skip IntegrationTests` 一致,失败的与原生路径相同(第 2、3 步,在 Ultra 上)。 +1. `swift_section` 与 `SwiftSectionCommandTests` 能编、能链、`@testable import` 成立:124 个测试全部通过。另需 `SWIFT_PACKAGE_NAME = MachOSwiftSection`(它调用 SwiftSectionKit 的 `package` 方法),工具 target 写明 `productName`。 +2. 部署版本与链接参数:测试 target 要抬到 macOS 14.0(`TypeIndexingTests`),CLI 要 macOS 12.0(swift-argument-parser);测试与 CLI 都要 `-ObjC`(包装读取器的 conformance)和对 `SwiftSymbolsRegistration` 的 `-force_load`(Swift 符号语言的注册);导入 Testing 的库 target 要 TestingMacros 插件路径;测试 scheme 要关掉两个运行时检查。逐条见决策日志。 +3. `Capstone` 的 trait 宏补上后 `SwiftThunkAnalysis` 编过,它的测试通过(86 个通过、2 个跳过)。 +4. 远程模式:Tuist workspace 的测试 scheme 与原生 `swift test --skip IntegrationTests` 在同一台机器、同一个 Xcode 下逐 bundle 对照,全部通过;Tuist 编的 `swift-section` 与原生编的对 SymbolTestsCore 输出的 `dump`、`interface` 逐字节相同。 +5. 本地模式与按绝对路径引用上游库工程:见决策日志「本地模式实测」。 ## 替代方案考量 @@ -539,34 +683,34 @@ let tuist = Tuist( 在 Ultra 上构建与跑测试(本机是 10 核那台),用默认的 Xcode 27.2;第 2、3 步的测试结果另用 Xcode 26.6 的 `swift test` 结果对照。 -1. **骨架:远程模式能生成、能编 CLI** —— 改动地图里 `mise.toml`、`Tuist/Package.swift`(不含测试相关)、`Tuist/CommandLine/Project.swift`(只有 `swift-section`)、`Workspace.swift`(无测试 scheme)、`TuistScript.sh`(`install`、`generate`、`build`、`release`,存放位置,锁文件,自己检出的占用)、`.gitignore`、workspace 成员 +1. **骨架:远程模式能生成、能编 CLI**(已完成) —— 改动地图里 `mise.toml`、`Tuist/Package.swift`(不含测试相关)、`Tuist/CommandLine/Project.swift`(只有 `swift-section`)、`Workspace.swift`(无测试 scheme)、`TuistScript.sh`(`install`、`generate`、`build`、`release`,存放位置,锁文件,自己检出的占用)、`.gitignore`、workspace 成员 - 行为:`generateCreatesTheTuistWorkspaceAndLeavesTheNativeWorkspaceUntouched` - 行为:`buildCompilesSwiftSectionFromTheTuistWorkspace` - 行为:`generateFailsNamingTheOwnerWhenAnotherCheckoutHoldsThisOne` - 行为:`releaseRemovesTheGeneratedProjectsAndTheClaim` - 行为:`installWarnsWhenTheResolvedPinsDifferFromTheSeedLockFile` - 行为:`usingLocalDependenciesIsIgnoredWithAWarning` -2. **本库的测试** —— `Package.swift` 适配块,`Tuist/Package.swift` 的 swift-snapshot-testing 与测试设置,`Project.swift` 的 `swift_section` 与 `SwiftSectionCommandTests`,`Workspace.swift` 的测试 scheme,脚本的 `test` 命令与清单读取 +2. **本库的测试**(已完成) —— `Package.swift` 适配块,`Tuist/Package.swift` 的 swift-snapshot-testing 与测试设置,`Project.swift` 的 `swift_section` 与 `SwiftSectionCommandTests`,`Workspace.swift` 的测试 scheme,脚本的 `test` 命令与清单读取 - 行为:`theTestSchemeHoldsEveryTestTargetExceptIntegrationTests` - 行为:`swiftSectionCommandTestsImportTheCommandModuleAndPass` - 行为:`theTuistTestRunMatchesSwiftTestTargetByTarget` - 行为:`packageManifestIsUnchangedWithoutTheTuistVariable`(`swift package dump-package` 不带变量时与改动前逐字节相同) -3. **本地模式** —— 三个上游库的适配块(各自的功能分支),`Tuist/Package.swift` 的本地依赖,脚本的模式切换、上游库占用、预检 +3. **本地模式**(已完成) —— 三个上游库的适配块(各自的功能分支),`Tuist/Package.swift` 的本地依赖,脚本的模式切换、上游库占用、预检 - 行为:`localDependenciesBuildTheUpstreamPackagesFromTheirCheckoutsWithUncommittedEdits` - 行为:`theModeIsRememberedAndSwitchingResolvesAgain` - 行为:`localModeMapsTheTestsOfAllSixPackages` - 行为:`anUpstreamCheckoutWithoutTheBlockTurnsTestMappingOffWithAWarning` - 行为:`switchingToRemoteReleasesTheUpstreamCheckouts` -4. **二进制缓存** —— `Tuist.swift`,脚本的 `warm` 与 `TUIST_SOURCE_TARGET_NAMES` +4. **二进制缓存**(已完成) —— `Tuist.swift`,脚本的 `warm` 与 `TUIST_SOURCE_TARGET_NAMES` - 行为:`warmCachesEveryThirdPartyPackageAndNoneOfTheSixOwnPackages` - 行为:`generateAfterWarmLinksTheCachedBinaries` - 行为:`aThirdPartyTargetNamedLikeAnOwnTargetIsReported` - 记录:空 DerivedData 下不用缓存与走缓存各编一次 `swift-section` 与测试 scheme 的时间,写进决策日志与指南。 -5. **与 RuntimeViewer 互斥** —— RuntimeViewer 的 `TuistScript.sh` 与指南 +5. **与 RuntimeViewer 互斥**(已完成) —— RuntimeViewer 的 `TuistScript.sh` 与指南 - 行为:`runtimeViewerLocalModeFailsWhileMachOSwiftSectionHoldsTheCheckout` - 行为:`machOSwiftSectionFailsWhileRuntimeViewerHoldsAnUpstreamCheckout`(新旧两种记录各一次) - 行为:`aStaleClaimIsTakenOverSilently` -6. **文档** —— 使用指南、`AGENTS.md`、`Documentations/README.md` +6. **文档**(已完成) —— 使用指南、`AGENTS.md`、`Documentations/README.md` **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -595,3 +739,6 @@ let tuist = Tuist( | 2026-11-20 | 只给声明低于 macOS 14 的包的测试抬部署版本 | 六个包今天都声明 10.15,但以后有包声明 15 时,统一设 14.0 会把它的测试调低。脚本另传 `TUIST_RAISED_TEST_TARGET_NAMES`;`-ObjC` 与 `-force_load` 照旧给全部测试。 | | 2026-11-20 | 测试 scheme 关掉 Xcode 的两个运行时检查 | 全量重跑后只剩 `FileModeTests.fileModeMatchesInProcessReferencesOnTheRunningSystemCache` 一条:进程内的调用目标落在 `/usr/lib/libRPAC.dylib`。那是 Thread Performance Checker 插入的库,它改写了已加载镜像里的调用;`swift test` 的进程里没有它。`Workspace.swift` 的测试 scheme 关掉它与 Main Thread Checker;Tuist 4.210 只写后者的属性,脚本生成后给 `* Tests.xcscheme` 的 TestAction 补 `disablePerformanceAntipatternChecker = "YES"`。 | | 2026-11-20 | 工具 target 写明 `productName` | Tuist 把 target 名里的 `-` 换成 `_`,可执行文件成了 `swift_section`。 | +| 2026-11-20 | 本地模式实测 | Ultra 上用五个上游库的沙盒副本(`TUIST_LOCAL_PACKAGE_CHECKOUTS` 指过去,各在本提案的功能分支上)打开本地模式:解析、读清单、生成都成功,六个包各有一个 `<包名> Tests` scheme,副本的 `git status` 保持干净。`MachOSwiftSection Tests` 全量 2,943 个通过、0 失败、7 个跳过(修完前面几处之后的第一次全量);MachOKitExtensions 171 个、swift-demangling 641 个、swift-semantic-string 464 个全部通过。MachOKit 10 个失败、MachOObjCSection 26 个失败,全是测试自己读写死的路径或系统文件:`AotCachePrintTests` 读不存在的 `aot_shared_cache.0`,`ArchiveFileTests` 读 clang 17 目录(Xcode 27.2 是 21),`MachOObjCSectionTests` 的 `setUp` 读 `/Users/JH/Downloads/iOS18.5-SwiftUI`,两条 `testDylibsPreBuildLoaderSet` 在 macOS 27 的系统 cache 上读不出 loader set 版本。这些按源码判断与 Tuist 无关,没有再用原生 `swift test` 对照。切回远程模式后副本的占用全部释放。 | +| 2026-11-20 | 缓存计时 | Ultra(28 核,Xcode 27.2),清空 DerivedData 后编 `swift-section`(Debug):不走缓存 63 秒,走缓存 46 秒;`warm` 把 70 个第三方 target 编成 xcframework 用了 60 秒,再生成时这 70 个都换成了缓存。测试 scheme 走缓存的全量重跑用户嫌慢叫停了,没有结果;远程模式下修完的那几处都按 bundle 重跑过,本地模式的全量也已通过。写进使用指南。 | +| 2026-11-20 | 实现完成,待用户看过后收尾 | 配套文档:使用指南已写;实现说明不另写,清单里每处特殊写法的原因都在指南「已知的坑」与本决策日志里。术语表(「Tuist 开发 workspace」「本地依赖模式」「占用记录」)留到正式收尾时判断。 | diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index 8ba87cff..65a0b924 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -20,6 +20,7 @@ open MachOSwiftSection-Tuist.xcworkspace - **锁文件**:脚本每次解析都从本检出根目录的 `Package.resolved`(`swift build` 与原生 workspace 解析出的那份,不提交)开始,所以 Tuist 用的是同样的版本。没有这个文件时 Tuist 解析各清单允许的最新版本,并提示一句;新 worktree 里可以先从集成检出拷一份过来。解析完与它不一致时会列出差异,多半是换了 Xcode:有些包按 Swift 版本选用不同的清单。 - **Xcode**:脚本和 Tuist 都用 `DEVELOPER_DIR` 或 `xcode-select` 选中的那个,打开 workspace 也用同一个。二进制缓存按 Xcode 版本分开,换了 Xcode 要重新 `warm`。 +- **缓存省多少**:2026-11-20 在 Ultra(M3 Ultra 28 核,Xcode 27.2)上,清空 DerivedData 后编 `swift-section`(Debug),不走缓存 63 秒,走缓存 46 秒;`warm` 把 70 个第三方 target 编成 xcframework 用了 60 秒。省下的是第三方依赖那部分,本库与上游库照旧从源码编;核心少的机器上没有测过。 ## 日常用法 @@ -49,7 +50,7 @@ open MachOSwiftSection-Tuist.xcworkspace - **哪几个库、从哪取**:原生 workspace 的 `container:../<名字>` 成员,现在是上面五个;原生 workspace 加了库,这里自动跟上。默认从检出的上一级目录取,worktree 里就是 `.worktrees/` 下那组链接,所以编的是那组链接指向的检出(比如 `.worktrees/MachOKitExtensions` 指向 MachOKitExtensions 的主检出时,编的就是它当前所在的分支)。打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS`,就改从它指的目录取:每个库一个子目录,名字与库相同(SwiftPM 按目录名认包,经符号链接也一样按真实目录名认)。 - **效果**:`Tuist/Package.swift` 按路径声明这几个库,顶替依赖图里所有按 URL 声明的同名包。它们从本地源码编,没提交的改动也算;改已有文件后在 Xcode 里直接编就生效。它们的编译警告照常显示。 -- **测试**:六个包的测试都进 workspace,每个包一个 scheme(`<包名> Tests`)。做到这一点要每个库的 `Package.swift` 末尾都有那段 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 适配块(见下一节);MachOKitExtensions、MachOObjCSection、swift-demangling 已经加了,MachOKit 与 swift-semantic-string 现在用不着。某个库的检出停在加块之前的提交、又有 Tuist 不接受的测试时,脚本会警告并点名那个库,这一次整个 workspace 都不带测试(Tuist 对按路径声明的包只能全映射或全不映射),生成照常进行。 +- **测试**:六个包的测试都进 workspace,每个包一个 scheme(`<包名> Tests`)。做到这一点要每个库的 `Package.swift` 末尾都有那段 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 适配块(见下一节);MachOKitExtensions、MachOObjCSection、swift-demangling 已经加了,MachOKit 与 swift-semantic-string 现在用不着。某个库的检出停在加块之前的提交、又有 Tuist 不接受的测试时,脚本会警告并点名那个库,这一次整个 workspace 都不带测试(Tuist 对按路径声明的包只能全映射或全不映射),生成照常进行。上游库自己的测试里有读写死路径的(MachOKit 的 `AotCachePrintTests`、`ArchiveFileTests`,MachOObjCSection 的 `MachOObjCSectionTests` 读 `/Users/JH/Downloads/iOS18.5-SwiftUI`),在没有这些文件的机器上照样失败,与 Tuist 无关。 - **模式会记住**:记在 `Tuist/.local-dependencies`(已忽略),之后不带参数的命令都沿用;每条命令开头都打印当前用的是哪种依赖。两种模式各有一份依赖 checkout,切换后会先重新解析。 - **写进库目录的文件**:Tuist 会在每个按路径声明的包目录里生成 `<包名>.xcodeproj/` 和 `Derived/`。脚本把这两项写进那个仓库的 `info/exclude`(只在本机,不提交),`git status` 里看不到;切回远程模式时删掉 `<包名>.xcodeproj/`,`Derived/` 留着。git 跟踪着 `<包名>.xcodeproj` 的库,脚本直接报错,不让 Tuist 覆盖。 From 73c9ccb726ab2e606c9a75f56128c38769af641e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 16:00:22 +0800 Subject: [PATCH 014/175] docs: land the Tuist development workspace as proposal 0099 Number the proposal, mark it Implemented and regenerate its web page from the final text; record the landing in ledger section 143 and register the Tuist development workspace and its claim record in the glossary. --- ...rkspace.html => 0099-tuist-workspace.html} | 457 ++++++++++++------ ...t-workspace.md => 0099-tuist-workspace.md} | 13 +- Documentations/Evolutions/README.md | 2 +- Documentations/Glossary.md | 16 + .../Internal/ProjectEvolutionLog.md | 13 + Documentations/Internal/TuistDevelopment.md | 2 +- Documentations/README.md | 2 +- 7 files changed, 348 insertions(+), 157 deletions(-) rename Documentations/Evolutions/{draft-tuist-workspace.html => 0099-tuist-workspace.html} (50%) rename Documentations/Evolutions/{draft-tuist-workspace.md => 0099-tuist-workspace.md} (97%) diff --git a/Documentations/Evolutions/draft-tuist-workspace.html b/Documentations/Evolutions/0099-tuist-workspace.html similarity index 50% rename from Documentations/Evolutions/draft-tuist-workspace.html rename to Documentations/Evolutions/0099-tuist-workspace.html index e58337df..c4b9912e 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.html +++ b/Documentations/Evolutions/0099-tuist-workspace.html @@ -160,13 +160,13 @@
-

MachOSwiftSectionEvolutionsDraft

-

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

+

MachOSwiftSectionEvolutions0099

+

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

-
状态
In Progress
+
状态
Implemented
最后更新
2026-11-20
项目类型
库
-
原文
draft-tuist-workspace.md
+
原文
0099-tuist-workspace.md
@@ -208,7 +208,7 @@

要你定

动机

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

改动地图

详细设计

- Package.swift 的适配块(本库与三个上游库原样共用) + Package.swift 的适配块
-

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

-
// The Tuist development workspace (MachOSwiftSection's Documentations/Internal/TuistDevelopment.md)
+

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

+
// MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md)
 // maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends
 // on an executable target, and a test that depends on a target no product contains. Only while Tuist
 // resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the
@@ -410,9 +410,9 @@ 

详细设计

.map { target in Product.library(name: target.name, targets: [target.name]) } }
    -
  • 本库:摘掉 SwiftSectionCommandTests,给 SwiftSectionFixtureSupport、SwiftSectionTestingSupport(以及测试直接依赖的其余普通 target)补 product。MachOObjCSection:摘掉 ObjCSectionCommandTests。MachOKitExtensions 与 swift-demangling:补 CPlusPlusSymbolsFixture、DemanglingTestingSupport 的 product。
  • -
  • 被摘掉的测试照旧用 swift test --filter 跑;本库的 SwiftSectionCommandTests 例外,它在 Tuist/CommandLine/Project.swift 里手写。ObjCSectionCommandTests 不手写:那要在本库描述另一个仓库的 target。
  • -
  • 只看 target 依赖(targetItem / byNameItem),不看 productItem:依赖别的包的可执行 product 的测试,Tuist 怎么处理没有实测,四个包里也没有。
  • +
  • 在本库里它摘掉 SwiftSectionCommandTests,给 SwiftSectionFixtureSupport、SwiftSectionTestingSupport(以及测试直接依赖的其余普通 target)补 product。在 MachOObjCSection 里摘掉 ObjCSectionCommandTests;在 MachOKitExtensions 与 swift-demangling 里补 CPlusPlusSymbolsFixture、DemanglingTestingSupport 的 product。
  • +
  • 被摘掉的测试 Tuist workspace 里就没有了,照旧用 swift test --filter 跑;本库的 SwiftSectionCommandTests 例外,它在 Tuist/CommandLine/Project.swift 里手写(下文)。MachOObjCSection 的 ObjCSectionCommandTests 不手写:那要在本库描述另一个仓库的 target,非目标。
  • +
  • 只看 target 依赖(targetItem / byNameItem),不看 productItem:依赖别的包的可执行 product 的测试,Tuist 怎么处理没有实测,目前四个包里也没有。
@@ -423,14 +423,24 @@

详细设计

import Foundation import PackageDescription -// The dependencies of MachOSwiftSection-Tuist.xcworkspace (Documentations/Internal/TuistDevelopment.md). -// This package is declared by path, so its Package.swift stays the only definition of its targets. -// In the local dependency mode TuistScript.sh names the upstream packages in TUIST_LOCAL_PACKAGE_NAMES -// and their directory in TUIST_LOCAL_PACKAGE_CHECKOUTS; a root's path dependency stands in for every -// declaration of the same package in the graph. +// The dependencies of MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +// (Documentations/Internal/TuistDevelopment.md). Generate it with ./TuistScript.sh, never with a bare +// `tuist generate`: the script sets the variables everything below reads. +// +// MachOSwiftSection itself is declared by path, so its Package.swift stays the only definition of its +// targets and dependencies. In the local dependency mode (`./TuistScript.sh <command> +// --local-dependencies`) the script names the upstream packages the native workspace lists beside +// the checkout in TUIST_LOCAL_PACKAGE_NAMES and the directory holding them in +// TUIST_LOCAL_PACKAGE_CHECKOUTS. A root's path dependency stands in for every other declaration of the +// same package in the graph — MachOSwiftSection's URLs and the upstream packages' own — so they build +// from those checkouts, uncommitted edits included. A path package's identity is its directory's name. let processEnvironment = ProcessInfo.processInfo.environment let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? "" -let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "").split(separator: ",").map(String.init) +let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "") + .split(separator: ",") + .map(String.init) +// Qualified: Tuist evaluates this file with ProjectDescription imported too, which has a Package of +// its own. let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty ? [] : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") } @@ -438,20 +448,24 @@

详细设计

#if TUIST import ProjectDescription - func names(_ variable: String) -> [String] { + func targetNames(in variable: String) -> [String] { (processEnvironment[variable] ?? "").split(separator: ",").map(String.init) } - // Tuist suppresses warnings in every package; Xcode does so for remote packages only. + // Tuist suppresses warnings in every package; Xcode does so for remote packages only. The targets + // of the packages declared by path get theirs back: MachOSwiftSection always, the upstream + // packages in the local dependency mode. let warningSettings: [String: Settings] = Dictionary( - names("TUIST_WARNING_TARGET_NAMES").map { targetName in + targetNames(in: "TUIST_WARNING_TARGET_NAMES").map { targetName in (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"])) }, uniquingKeysWith: { first, _ in first } ) - // Tuist drops a setting whose only condition is a trait; this package enables swift-capstone's - // AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 that way. + // Tuist drops a package setting whose only condition is a trait. MachOSwiftSection enables + // swift-capstone's AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 for both the Swift wrapper and + // the C library that way. Without it the wrapper does not compile, and the C library would compile + // but support no architecture at all. let restatedTraitDefinitions: [String: Settings] = [ "Capstone": .settings(base: [ "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"], @@ -462,14 +476,71 @@

详细设计

]), ] - // Filled in by step 2 once the tests have been built: the deployment target SwiftPM gives a test - // target (macOS 14.0) and -ObjC, each only if the build shows it is needed. - let testTargetSettings: [String: Settings] = [:] + // A library target that imports Testing, such as a package's testing support, uses Swift Testing's + // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros + // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library + // targets whose sources import Testing. + let testingSupportSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TESTING_SUPPORT_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: [ + "ENABLE_TESTING_SEARCH_PATHS": "YES", + "OTHER_SWIFT_FLAGS": ["$(inherited)", "-plugin-path", "$(TOOLCHAIN_DIR)/usr/lib/swift/host/plugins/testing"], + ])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // The test targets, which SwiftPM builds and links differently in three ways: + // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0 + // with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and + // MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // TUIST_RAISED_TEST_TARGET_NAMES lists the test targets of the packages that declare less. + // - It links each package target's object files whole, where Tuist links static frameworks and the + // linker loads only the archive members something refers to by symbol. A protocol conformance + // nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage + // or MachOFile (MachOReaderWrapper) read as neither. -ObjC also loads every member that defines an + // Objective-C class or category or a Swift type or extension (Xcode 27's linker), as it does for + // RuntimeViewer's Tuist workspace. + // - A load-time constructor nothing refers to never runs that way at all: MachOSwiftSection's + // SwiftSymbolsRegistration registers Swift as a symbol language from one. TUIST_FORCE_LOADS pairs + // each final link with the constructor targets its in-package dependencies reach, as + // "<linking target>:<constructor target>,…"; those archives are loaded whole. + // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build + // of the whole workspace compiles and links too. Tuist/CommandLine/Project.swift gives the + // swift-section executable and SwiftSectionCommandTests the same link flags. + let forceLoadedTargetsByLinkingTarget: [String: [String]] = Dictionary( + targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair -> (String, [String])? in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 ? (parts[0], [parts[1]]) : nil + }, + uniquingKeysWith: + + ) + let raisedTestTargetNames = Set(targetNames(in: "TUIST_RAISED_TEST_TARGET_NAMES")) + let testTargetSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in + let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)" + } + var settings: SettingsDictionary = ["OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags)] + if raisedTestTargetNames.contains(targetName) { + settings["MACOSX_DEPLOYMENT_TARGET"] = "14.0" + } + return (targetName, Settings.settings(base: settings)) + }, + uniquingKeysWith: { first, _ in first } + ) + + // One target may need several of the settings above; their keys never overlap. + func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { + settingsByTarget.reduce(into: [:]) { merged, settings in + merged.merge(settings) { first, second in .settings(base: first.base.merging(second.base) { $1 }) } + } + } let packageSettings = PackageSettings( - targetSettings: warningSettings - .merging(restatedTraitDefinitions) { $1 } - .merging(testTargetSettings) { $1 }, + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), + // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of + // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" ) #endif @@ -478,15 +549,17 @@

详细设计

name: "MachOSwiftSectionTuistDependencies", dependencies: [ .package(path: ".."), - // Stands in for swift-syntax everywhere, as it does as a member of the native workspace. + // Stands in for swift-syntax in every macro package, as it does as a member of the native + // workspace: SwiftPM matches it by package identity. .package(path: "../PrecompiledLibraries/swift-syntax"), - // Used only by tests, which Tuist needs declared here (MachOSwiftSection's requirement). + // Used only by MachOSwiftSection's tests. Tuist maps a test target only when every package + // its dependencies come from is declared here, with the requirement Package.swift gives it. .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"), ] + localPackageDependencies )
    -
  • 根包的路径依赖 .. 的身份是目录名:worktree 叫 MachOSwiftSection-<用途> 时身份就变了,而上游库的清单不按 URL 引用本库,所以不受影响;生成的工程名取自 Package(name:),仍是 MachOSwiftSection.xcodeproj。
  • -
  • TUIST_WARNING_TARGET_NAMES 是本库全部 target,本地模式下再加五个上游库的全部 target(与原生 workspace 一致:Xcode 只给远程包关警告)。
  • +
  • 包名 MachOSwiftSectionTuistDependencies。根包的路径依赖 .. 的身份是目录名:worktree 叫 MachOSwiftSection-<用途> 时身份就变了,而上游库的清单不按 URL 引用本库,所以不受影响;生成的工程名取自 Package(name:),仍是 MachOSwiftSection.xcodeproj。
  • +
  • TUIST_WARNING_TARGET_NAMES 是本库全部 target,本地模式下再加五个上游库的全部 target(与原生 workspace 一致:Xcode 只给远程包关警告)。
@@ -495,11 +568,15 @@

详细设计

import ProjectDescription
 
-// What Tuist cannot convert from ../../Package.swift: the swift-section executable, and
-// SwiftSectionCommandTests, which imports the executable's module. swift_section compiles the same
-// sources as a static framework for that test; the tool compiles them again, so its link needs no
-// trick around the @main entry point. The dependency list mirrors Package.swift's swift-section
-// target and is the one hand-written copy in the Tuist description.
+// What Tuist cannot convert from ../../Package.swift (Documentations/Internal/TuistDevelopment.md):
+// the swift-section executable, and SwiftSectionCommandTests, which imports the executable's module
+// (`@testable import swift_section`). Tuist converts no executable target and rejects a test that
+// depends on one, so Package.swift leaves that test out while Tuist resolves it and it is described
+// here instead. swift_section compiles the command's sources as a static framework for the test; the
+// tool compiles them again, so its link needs no trick around the @main entry point.
+//
+// The dependency list mirrors the swift-section target in Package.swift and is the one hand-written
+// copy in the Tuist description: a dependency added there that is missing here fails to compile.
 let commandLineDependencies: [TargetDependency] = [
     .external(name: "SwiftSectionKit"),
     .external(name: "MachOFoundation"),
@@ -516,32 +593,60 @@ 

详细设计

.external(name: "ArgumentParser"), ] +// Tuist builds swift-argument-parser for macOS 12, the minimum that package declares; the package's +// own 10.15 does not reach the executable here the way SwiftPM's build of it does. +let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") + let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] +// The link flags Tuist/Package.swift gives the package's test targets, for the same reasons: -ObjC, so +// that the archive members defining Swift types and extensions (protocol conformances among them) are +// loaded, and -force_load of the constructor targets the swift-section executable reaches in +// Package.swift, which TuistScript.sh lists in TUIST_FORCE_LOADS. +let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "") + .split(separator: ",") + .compactMap { pair in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil + } +let linkFlags: SettingsDictionary = [ + "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadedTargetNames.map { targetName in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)" + }), +] + // MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; // TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. -let commandTestSettings: Settings = Environment.silentTest.getBoolean(default: false) - ? .settings(base: ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]]) - : .settings() +let commandTestSettings: Settings = .settings(base: linkFlags.merging( + Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:] +) { $1 }) let project = Project( name: "MachOSwiftSectionCommandLine", + // In SwiftPM these targets belong to the MachOSwiftSection package, whose `package` declarations + // they use (SwiftSectionCommandTests calls SwiftSectionKit's applyTransformersEnablingCommentKinds). + // Tuist gives the targets it converts SWIFT_PACKAGE_NAME = MachOSwiftSection; these need the same. + settings: .settings(base: ["SWIFT_PACKAGE_NAME": "MachOSwiftSection"]), targets: [ .target( name: "swift-section", destinations: .macOS, product: .commandLineTool, + // Tuist would name the executable swift_section, as it turns every dash of a target's name + // into an underscore. + productName: "swift-section", bundleId: "com.machoswiftsection.swift-section", - deploymentTargets: .macOS("10.15"), + deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, - dependencies: commandLineDependencies + dependencies: commandLineDependencies, + settings: .settings(base: linkFlags) ), .target( name: "swift_section", destinations: .macOS, product: .staticFramework, bundleId: "com.machoswiftsection.swift-section.module", - deploymentTargets: .macOS("10.15"), + deploymentTargets: commandLineDeploymentTargets, sources: commandLineSources, dependencies: commandLineDependencies ), @@ -562,8 +667,8 @@

详细设计

] )
    -
  • CLI 的源码编两遍(tool 一遍、framework 一遍)。另一种写法是 tool 不带源码、只链 framework,靠链接器从静态库里取 _main;省一遍编译,但没实测,放进「替代方案」。
  • -
  • MACHO_SWIFT_SECTION_SILENT_TEST=1 在 Package.swift 里变成测试 target 的 SILENT_TEST 定义:tuist install 时设了它,转换出的测试就带上。手写的 SwiftSectionCommandTests 也要带:Tuist 的 manifest 只读得到 TUIST_ 开头的变量,所以脚本把它转成 TUIST_SILENT_TEST=1,Project.swift 据此给这个 target 加 SILENT_TEST。
  • +
  • CLI 的源码编两遍(tool 一遍、framework 一遍)。另一种写法是 tool 不带源码、只链 framework,靠链接器从静态库里取 _main;省一遍编译,但能否链接成功依赖链接器怎么处理入口符号,没实测,放进「替代方案」。
  • +
  • MACHO_SWIFT_SECTION_SILENT_TEST=1 在 Package.swift 里变成测试 target 的 SILENT_TEST 定义:tuist install 时设了它,转换出的测试就带上。手写的 SwiftSectionCommandTests 也要带:Tuist 的 manifest 只读得到 TUIST_ 开头的变量,所以脚本把它转成 TUIST_SILENT_TEST=1,Project.swift 据此给这个 target 加 SILENT_TEST。
@@ -572,9 +677,14 @@

详细设计

import ProjectDescription
 
-// "<package directory>=<test target>,<test target>;…" from TuistScript.sh, one entry per package whose
-// tests are mapped: this package always (directory "."), the upstream packages in the local mode.
-// IntegrationTests is never listed.
+// MachOSwiftSection-Tuist.xcworkspace, the development-only workspace Tuist generates beside the
+// native MachOSwiftSection.xcworkspace (Documentations/Internal/TuistDevelopment.md).
+//
+// The packages' test targets live in the projects Tuist converts from their Package.swift files, which
+// only a workspace scheme can reference. TuistScript.sh lists them in TUIST_PACKAGE_TEST_TARGETS as
+// "<package directory>=<test target>,<test target>;…", one entry per package whose tests are mapped:
+// MachOSwiftSection always (directory "."), the upstream packages in the local dependency mode
+// (absolute directories). IntegrationTests, the maintainer's manual-inspection target, is never listed.
 let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets
     .getString(default: "")
     .split(separator: ";")
@@ -584,23 +694,48 @@ 

详细设计

return (parts[0], parts[1].split(separator: ",").map(String.init)) } +func packageName(ofDirectory directory: String) -> String { + directory == "." ? "MachOSwiftSection" : String(directory.split(separator: "/").last ?? Substring(directory)) +} + +func projectPath(ofDirectory directory: String) -> Path { + directory.hasPrefix("/") ? .path(directory) : .relativeToRoot(directory) +} + let workspace = Workspace( name: "MachOSwiftSection-Tuist", projects: ["Tuist/CommandLine"], schemes: packageTestTargets.map { entry in - let packageName = entry.directory == "." ? "MachOSwiftSection" : (entry.directory as NSString).lastPathComponent var testableTargets = entry.targets.map { targetName in - TestableTarget.testableTarget(target: .project(path: Path(entry.directory), target: targetName)) + TestableTarget.testableTarget( + target: .project(path: projectPath(ofDirectory: entry.directory), target: targetName), + parallelization: .swiftTestingOnly + ) } if entry.directory == "." { - testableTargets.append(.testableTarget(target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"))) + testableTargets.append(.testableTarget( + target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"), + parallelization: .swiftTestingOnly + )) } - return .scheme(name: "\(packageName) Tests", testAction: .targets(testableTargets)) + return .scheme( + name: "\(packageName(ofDirectory: entry.directory)) Tests", + testAction: .targets( + testableTargets, + // The test process as `swift test` runs it. The Thread Performance Checker inserts + // libRPAC.dylib, which rebinds calls in the loaded images: the cross-reference tests that + // compare a cache image read in process with the same image read from its file then + // see calls into libRPAC. The Main Thread Checker swizzles Objective-C methods the same + // way. Tuist 4.210 writes only the Main Thread Checker's attribute; TuistScript.sh adds + // disablePerformanceAntipatternChecker to the generated schemes. + diagnosticsOptions: .options(mainThreadCheckerEnabled: false, performanceAntipatternCheckerEnabled: false) + ) + ) } )
    -
  • 上游库的目录是绝对路径;Path 接受绝对路径字符串,第 3 步验证。Workspace.swift 能否 import Foundation 用 NSString 没验证,不行就自己切最后一段。
  • -
  • 测试映射被预检关掉时 TUIST_PACKAGE_TEST_TARGETS 为空,只剩各 target 自己的 scheme;SwiftSectionCommandTests 仍在 MachOSwiftSectionCommandLine 工程里,Tuist 自动生成的 scheme 能跑它。
  • +
  • 上游库的目录是绝对路径;Path 接受绝对路径字符串(第 3 步验证过:本地模式下六个包的 scheme 都生成了)。包名取目录的最后一段,自己切,不 import Foundation。
  • +
  • 测试映射被预检关掉时 TUIST_PACKAGE_TEST_TARGETS 为空,只剩各 target 自己的 scheme;SwiftSectionCommandTests 仍在 MachOSwiftSectionCommandLine 工程里,Tuist 自动生成的 scheme 能跑它。
@@ -609,9 +744,12 @@

详细设计

import ProjectDescription
 
-// Every target of MachOSwiftSection and of the five upstream packages stays source, in both dependency
-// modes; every other dependency comes out of the binary cache once warmed. TuistScript.sh reads the
-// names from the packages' manifests. No fullHandle: the cache stays on this machine.
+// Every target of MachOSwiftSection and of the five upstream packages its native workspace lists
+// (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) stays
+// source, in both dependency modes; every other dependency comes out of the binary cache once
+// `./TuistScript.sh warm` has filled it. The script reads the names from the packages' manifests and
+// passes them in TUIST_SOURCE_TARGET_NAMES. No fullHandle: the cache stays on this machine and
+// nothing is uploaded. Documentations/Internal/TuistDevelopment.md.
 let sourceTargetNames = Environment.sourceTargetNames
     .getString(default: "")
     .split(separator: ",")
@@ -628,29 +766,29 @@ 

详细设计

) )
    -
  • 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库,第 4 步量出来后若差得多再议。
  • -
  • 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。
  • +
  • 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;它们留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库;第 4 步量出 CLI 冷编 63 秒、走缓存 46 秒,暂不改。
  • +
  • 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。
- TuistScript.sh:命令、环境变量、名单、预检、锁文件、模式、存放位置、占用记录 + TuistScript.sh

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

-

命令

+

命令:

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

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

-

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

+

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

@@ -659,54 +797,54 @@

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

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

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

-

名单从哪来

-

本地依赖的名字读 MachOSwiftSection.xcworkspace/contents.xcworkspacedata 里的 container:../<名字>(不含 / 的那些),workspace 加了库这里自动跟上。target 名单用 swift package dump-package(带 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1,--scratch-path 放在 Work/<checkout>/Manifests/)读六个包的清单:本库与本地模式下的上游库读检出里的,远程模式下的上游库读 install 之后 SWIFTPM_BUILD_DIR/checkouts/<名字> 里的。远程模式下第一次 install 之前还没有 checkout,先用空名单装一次再算。

-

测试映射的预检

-

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

-

锁文件

-

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

-

依赖模式

-

模式记在 Tuist/.local-dependencies(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 .worktrees/;打开本地模式时设了 TUIST_LOCAL_PACKAGE_CHECKOUTS 就用它。两种模式各用一份依赖 checkout,共用 Tuist/Package.resolved,所以切换后、或上次解析用的是另一种模式时先重新 install。切到远程时释放五个上游库的占用。

-

存放位置

-

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

-

占用记录(与 RuntimeViewer 共用)

+

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

+

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

+

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

+

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

+

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

+

占用记录(与 RuntimeViewer 共用):

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

Tuist 版本与 agent 运行

-

读 mise.toml 的版本;有 mise 就 mise exec -- tuist,否则用 PATH 里的 tuist;版本不对就失败并提示 mise install。agent 运行时设 TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex/<agent>/Tuist-MachOSwiftSection,并写成 queued-build ./TuistScript.sh <命令>。

+

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

+

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

+

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

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

调研

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

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

+

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

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

影响

落地步骤

-

在 Ultra 上构建与跑测试,用默认的 Xcode 27.2;第 2、3 步的测试结果另用 Xcode 26.6 的 swift test 结果对照。

-
    -
  1. 骨架:远程模式能生成、能编 CLI——mise.toml、Tuist/Package.swift(不含测试相关)、Project.swift(只有 swift-section)、Workspace.swift(无测试 scheme)、脚本的 install / generate / build / release、存放位置、锁文件、自己检出的占用、.gitignore、workspace 成员 +

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

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

    收尾时判断:实现说明是否另写;「Tuist 开发 workspace」「本地依赖模式」「占用记录」是否进术语表。

    +
  2. 文档(已完成) —— 使用指南、AGENTS.md、Documentations/README.md
  3. +
+

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

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

决策日志

- 4 条,最近一条:用户批准,开始实现 + 22 条,最近一条:Implemented,编号 0099
@@ -852,8 +995,26 @@

决策日志

- + + + + + + + + + + + + + + + + + + +
2026-11-20Created as Draft用户要一个照 RuntimeViewer 做法建的 Tuist 开发 workspace,依赖可在本地检出与远程版本之间切换,本地依赖就是原生 workspace 里放的那几个上游库。按轻量档处理:新增的开发路径,不改原有的构建、发版与 CI。
2026-11-20定下三个方向用户选定:提供二进制缓存与 warm;Tuist workspace 要能跑测试,先实测再定写法;与 RuntimeViewer 的本地依赖模式双向互斥,为此顺带改 RuntimeViewer 的脚本。
2026-11-20实测定下测试的写法Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;SwiftSectionCommandTests 手写。三个上游库要不要加,留给用户定。
2026-11-20实测定下测试的写法十项实测见「前期调研」:Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;SwiftSectionCommandTests 在 Tuist/CommandLine/Project.swift 里手写。三个上游库要不要加,留给用户定。
2026-11-20用户批准,开始实现用户选定给 MachOKitExtensions、MachOObjCSection、swift-demangling 加适配块,本地模式带测试;状态改 Accepted。实现在本库的 feature/tuist-workspace,三个上游库与 RuntimeViewer 各用同名分支。
2026-11-20清单改由脚本自己读本想直接读 Tuist 缓存的清单索引(swifterpm/package-info/index.json),实测设了 SWIFTPM_BUILD_DIR 时 Tuist 不产出这份索引,靠它不可靠。改回提案原写法:每次 install 之后脚本用 swift package dump-package(带 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1,8 个并行)读一遍所有包的清单存进 Work/<checkout>/Manifests/,名单、预检和同名检查都读它(35 个包)。Python 出错时脚本直接失败,而不是带着空名单生成。
2026-11-20解析依赖的记号带上清单的 hashWork/<checkout>/InstalledDependencies 除了模式,还记 Tuist/Package.swift、Package.swift、种子锁文件与(本地模式下)上游库清单的 hash:改了 Package.swift 或换了根目录的 Package.resolved,下一次 generate 自己重新解析,不必记得先跑 install。
2026-11-20CLI 的部署版本改为 macOS 12.0Ultra 首次构建:Tuist 把 swift-argument-parser 编成它声明的 macOS 12,10.15 的 swift-section import 不了它(11 处同一错误,其余全部编过)。
2026-11-20测试 target 抬到 macOS 14.0(原定「按需」,确认需要)TypeIndexingTests 用的 macOS 13 API 在 10.15 下编不过。脚本把所有转换进来的测试 target(含 IntegrationTests)传进新变量 TUIST_TEST_TARGET_NAMES。
2026-11-20手写的 target 设 SWIFT_PACKAGE_NAME = MachOSwiftSectionSwiftSectionCommandTests 调用 SwiftSectionKit 的 package 方法;Tuist 转换的 target 都带这个设置,手写的没有。
2026-11-20导入 Testing 的库 target 加 TestingMacros 插件路径SwiftSectionTestingSupport 用了 #require,Xcode 只给测试 target 带 TestingMacros 插件。脚本扫描路径包里普通 target 的源码找 import Testing,传进新变量 TUIST_TESTING_SUPPORT_TARGET_NAMES;本地模式下 swift-demangling 的 DemanglingTestingSupport 也会被找到。
2026-11-20build / test 加 --scheme本地模式下要跑上游库各自的测试 scheme(<包名> Tests)。
2026-11-20MachOKitExtensions 的 next 已不需要适配块,仍按决定加上探针用的是它的 main(有 CPlusPlusSymbolsFixture),next 上这个测试支撑 target 已经没有了,块目前不起作用。另:本库 .worktrees/MachOKitExtensions 链接指向它的主检出(main),不是它的 next worktree,所以公司那台上的本地模式编的是 main,预检会因为那个 target 关掉测试并点名。
2026-11-20Tuist 往 PrecompiledLibraries/swift-syntax/ 里写 .build/它是按路径声明的包,Tuist 在那里下载二进制产物;与它生成的工程一起写进 .gitignore。
2026-11-20SwiftSymbolsRegistration 整个 -force_loadUltra 上第一次跑通测试 scheme:2,935 通过、8 失败,原生 swift test 同一台、同一个 Xcode 27.2 全部通过(21 个 bundle、2,905 个测试)。SwiftSymbolsTests 里 registeredLanguages → []:这个 C target 只有一个 static 的加载期 constructor、没有全局符号,SwiftPM 整块链接 target 所以它总会跑,Tuist 的静态 framework 里这个成员没人引用、链接器不拉。脚本找出源码里有 __attribute__((constructor)) 的 target,沿包内依赖算出会链到它的测试与可执行 target,传进 TUIST_FORCE_LOADS。同一机制意味着 RuntimeViewer 的 Tuist workspace(静态 framework,只加了 -ObjC)里 Swift 也没注册成符号语言——按链接方式推断,没有实测,不在本提案范围内修。
2026-11-20测试与 swift-section 链接时加 -ObjC修好注册后还剩 4 条,都在包装读取器(MachOReaderWrapper)上:没人点名的 protocol conformance 所在的归档成员没被链进来,as? 静默失败。与 RuntimeViewer 的 Tuist workspace 一样加 -ObjC;测试 target 的部署版本、-ObjC 与 -force_load 合进同一份设置,免得两处 OTHER_LDFLAGS 互相覆盖。SwiftSymbolsTests 与 SwiftInspectionTests 重跑 227 个全部通过。
2026-11-20只给声明低于 macOS 14 的包的测试抬部署版本六个包今天都声明 10.15,但以后有包声明 15 时,统一设 14.0 会把它的测试调低。脚本另传 TUIST_RAISED_TEST_TARGET_NAMES;-ObjC 与 -force_load 照旧给全部测试。
2026-11-20测试 scheme 关掉 Xcode 的两个运行时检查全量重跑后只剩 FileModeTests.fileModeMatchesInProcessReferencesOnTheRunningSystemCache 一条:进程内的调用目标落在 /usr/lib/libRPAC.dylib。那是 Thread Performance Checker 插入的库,它改写了已加载镜像里的调用;swift test 的进程里没有它。Workspace.swift 的测试 scheme 关掉它与 Main Thread Checker;Tuist 4.210 只写后者的属性,脚本生成后给 * Tests.xcscheme 的 TestAction 补 disablePerformanceAntipatternChecker = "YES"。
2026-11-20工具 target 写明 productNameTuist 把 target 名里的 - 换成 _,可执行文件成了 swift_section。
2026-11-20本地模式实测Ultra 上用五个上游库的沙盒副本(TUIST_LOCAL_PACKAGE_CHECKOUTS 指过去,各在本提案的功能分支上)打开本地模式:解析、读清单、生成都成功,六个包各有一个 <包名> Tests scheme,副本的 git status 保持干净。MachOSwiftSection Tests 全量 2,943 个通过、0 失败、7 个跳过(修完前面几处之后的第一次全量);MachOKitExtensions 171 个、swift-demangling 641 个、swift-semantic-string 464 个全部通过。MachOKit 10 个失败、MachOObjCSection 26 个失败,全是测试自己读写死的路径或系统文件:AotCachePrintTests 读不存在的 aot_shared_cache.0,ArchiveFileTests 读 clang 17 目录(Xcode 27.2 是 21),MachOObjCSectionTests 的 setUp 读 /Users/JH/Downloads/iOS18.5-SwiftUI,两条 testDylibsPreBuildLoaderSet 在 macOS 27 的系统 cache 上读不出 loader set 版本。这些按源码判断与 Tuist 无关,没有再用原生 swift test 对照。切回远程模式后副本的占用全部释放。
2026-11-20缓存计时Ultra(28 核,Xcode 27.2),清空 DerivedData 后编 swift-section(Debug):不走缓存 63 秒,走缓存 46 秒;warm 把 70 个第三方 target 编成 xcframework 用了 60 秒,再生成时这 70 个都换成了缓存。测试 scheme 走缓存的全量重跑用户嫌慢叫停了,没有结果;远程模式下修完的那几处都按 bundle 重跑过,本地模式的全量也已通过。写进使用指南。
2026-11-20实现完成,待用户看过后收尾配套文档:使用指南已写;实现说明不另写,清单里每处特殊写法的原因都在指南「已知的坑」与本决策日志里。术语表(「Tuist 开发 workspace」「本地依赖模式」「占用记录」)留到正式收尾时判断。
2026-11-20Implemented,编号 0099用户看过后收尾。术语表登记「Tuist 开发 workspace」与「占用记录」(后者另注明与 SharedCacheRegistry 的 claim 无关);「本地依赖模式」就是本地依赖的字面意思,不登记。落地前用 Xcode 27.2 与 26.6 各解析一遍四个包的清单:都能解析,不带变量时与改动前一致,带变量时补的 product 与拿掉的测试和设计相符(MachOKitExtensions 的 main 上补 CPlusPlusDemangling、CPlusPlusSymbolsFixture)。MachOKitExtensions 的功能分支切自它本地一条没推送过的 next(只有一个空合并,比 main 落后 10 个提交),落地时把那一个提交接到 main 上推送;那条本地 next 原样留着。账本第 143 节。
diff --git a/Documentations/Evolutions/draft-tuist-workspace.md b/Documentations/Evolutions/0099-tuist-workspace.md similarity index 97% rename from Documentations/Evolutions/draft-tuist-workspace.md rename to Documentations/Evolutions/0099-tuist-workspace.md index e603663f..5901caac 100644 --- a/Documentations/Evolutions/draft-tuist-workspace.md +++ b/Documentations/Evolutions/0099-tuist-workspace.md @@ -1,13 +1,13 @@ -# Draft - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 +# 0099 - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 -- **状态**: In Progress +- **状态**: Implemented - **作者**: JH - **创建日期**: 2026-11-20 - **最后更新**: 2026-11-20 - **所属愿景**: 无 - **关联提案**: RuntimeViewer 仓库的 `Documentations/Evolutions/0053-tuist-coexistence.md`(Tuist workspace 与原生工程并存)与 `0082-tuist-local-dependencies.md`(本地依赖模式)。本提案的脚本照它们的做法写,并顺带改 RuntimeViewer 脚本里的占用检查,让两边的本地依赖模式互斥(落地步骤第 5 步)。 - **跨仓库**: 本提案是唯一的一份。另外四个仓库只有配套小改动:MachOKitExtensions、MachOObjCSection、swift-demangling 的 `Package.swift` 末尾各加同一段适配(第 3 步),RuntimeViewer 改 `TuistScript.sh` 与它的使用指南(第 5 步)。它们的提交信息按 slug 指回本提案,各自的文档按各仓库自己的规定同步。 -- **实现分支 / PR**: 本库 `feature/tuist-workspace`,从 `next` 切出;另外四个仓库用同名分支,从各自的集成分支切出(MachOKitExtensions 是 `main`,其余是 `next`)。 +- **实现分支 / PR**: 本库 `feature/tuist-workspace`,从 `next` 切出;另外四个仓库用同名分支,从各自的 `next` 切出。落地:本库、MachOObjCSection、swift-demangling、RuntimeViewer 合进 `next`,MachOKitExtensions 接到 `main` 上(它只有 `main` 一条远端分支,见决策日志最后一行)。 - **配套文档**: 使用指南 [`Documentations/Internal/TuistDevelopment.md`](../Internal/TuistDevelopment.md)(第 6 步新增) - **网页版**: 同目录同名的 `.html` @@ -17,7 +17,7 @@ ## 动机 -- **第三方依赖在每个干净的 DerivedData 里都要重编一遍。** 本库的依赖闭包里有 27 个与本仓库开发无关的包(`tuist install` 实测解析出的清单见「前期调研」):Capstone 的 C 库、swift-crypto、swift-collections、pointfree 的 swift-dependencies 一族、MetaCodable 与 MemberwiseInit 两个宏包、Yams、SourceKitD、swift-apinotes……原生 workspace 走 Xcode 自带的 SwiftPM 集成,每换一个 DerivedData(新 worktree、清缓存、换 Xcode)就全部从源码编一次。Tuist 的二进制缓存按内容寻址,同一台机器、同一个 Xcode 下只编一次。RuntimeViewer 用同样的做法量过:完整 App 从空 DerivedData 构建,不用缓存 504 秒,走缓存 155 秒。本库的数字还没量,第 4 步量。 +- **第三方依赖在每个干净的 DerivedData 里都要重编一遍。** 本库的依赖闭包里有 27 个与本仓库开发无关的包(`tuist install` 实测解析出的清单见「前期调研」):Capstone 的 C 库、swift-crypto、swift-collections、pointfree 的 swift-dependencies 一族、MetaCodable 与 MemberwiseInit 两个宏包、Yams、SourceKitD、swift-apinotes……原生 workspace 走 Xcode 自带的 SwiftPM 集成,每换一个 DerivedData(新 worktree、清缓存、换 Xcode)就全部从源码编一次。Tuist 的二进制缓存按内容寻址,同一台机器、同一个 Xcode 下只编一次。RuntimeViewer 用同样的做法量过:完整 App 从空 DerivedData 构建,不用缓存 504 秒,走缓存 155 秒。本库在 Ultra 上量的:清空 DerivedData 编 `swift-section`,不走缓存 63 秒,走缓存 46 秒(决策日志「缓存计时」)。 - **原生 workspace 切换本地上游库的方式太粗。** 今天的切换靠 `USING_LOCAL_DEPENDENCIES=1` 加兄弟目录是否存在(`Package.swift:42` 起的 `package(local:remote:)`):这个变量要进到 Xcode 的启动环境里才生效;对所有声明了本地路径的依赖一刀切,连 workspace 里没有列出的 swift-capstone(`Package.swift:275`,`../swift-capstone` 在 `.worktrees/` 下有链接)也会被换成本地;切换后要等 Xcode 重新解析。Tuist 这边由 `Tuist/Package.swift` 按路径逐个声明要本地化的库,SwiftPM 让根包的路径依赖顶替图里所有同名声明,名单就是 workspace 的成员,切换只发生在命令行上。 - **RuntimeViewer 的本地依赖模式已经在往本仓库的检出里写工程,而没有任何东西拦着另一方。** 它在每个按路径声明的包目录里生成 `<包名>.xcodeproj` 与 `Derived/`。2026-11-20 实测:RuntimeViewer 的集成 worktree 正占着本库的集成 worktree(本 worktree 的 git 目录里 `runtimeviewer-tuist-local-dependencies` 记着 `/Volumes/Repositories/Private/Org/MxIris-Reverse-Engineering/RuntimeViewer/.worktrees/RuntimeViewer`),本 worktree 根目录那份被忽略的 `MachOSwiftSection.xcodeproj` 就是它生成的。本库自己的 Tuist 也会在同一位置生成同名工程,两边的 `PackageSettings` 不同(配置名、警告、测试映射),谁后生成谁就让另一边的 workspace 坏掉。 @@ -531,7 +531,7 @@ let workspace = Workspace( ) ``` -- 上游库的目录是绝对路径;`Path` 接受绝对路径字符串,第 3 步验证。`Workspace.swift` 能否 `import Foundation` 用 `NSString` 没验证,不行就自己切最后一段。 +- 上游库的目录是绝对路径;`Path` 接受绝对路径字符串(第 3 步验证过:本地模式下六个包的 scheme 都生成了)。包名取目录的最后一段,自己切,不 `import Foundation`。 - 测试映射被预检关掉时 `TUIST_PACKAGE_TEST_TARGETS` 为空,只剩各 target 自己的 scheme;`SwiftSectionCommandTests` 仍在 `MachOSwiftSectionCommandLine` 工程里,Tuist 自动生成的 scheme 能跑它。 ### `Tuist.swift` @@ -562,7 +562,7 @@ let tuist = Tuist( ) ``` -- 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;它们留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库,第 4 步量出来后若差得多再议。 +- 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;它们留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库;第 4 步量出 CLI 冷编 63 秒、走缓存 46 秒,暂不改。 - 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。 ### `TuistScript.sh` @@ -742,3 +742,4 @@ let tuist = Tuist( | 2026-11-20 | 本地模式实测 | Ultra 上用五个上游库的沙盒副本(`TUIST_LOCAL_PACKAGE_CHECKOUTS` 指过去,各在本提案的功能分支上)打开本地模式:解析、读清单、生成都成功,六个包各有一个 `<包名> Tests` scheme,副本的 `git status` 保持干净。`MachOSwiftSection Tests` 全量 2,943 个通过、0 失败、7 个跳过(修完前面几处之后的第一次全量);MachOKitExtensions 171 个、swift-demangling 641 个、swift-semantic-string 464 个全部通过。MachOKit 10 个失败、MachOObjCSection 26 个失败,全是测试自己读写死的路径或系统文件:`AotCachePrintTests` 读不存在的 `aot_shared_cache.0`,`ArchiveFileTests` 读 clang 17 目录(Xcode 27.2 是 21),`MachOObjCSectionTests` 的 `setUp` 读 `/Users/JH/Downloads/iOS18.5-SwiftUI`,两条 `testDylibsPreBuildLoaderSet` 在 macOS 27 的系统 cache 上读不出 loader set 版本。这些按源码判断与 Tuist 无关,没有再用原生 `swift test` 对照。切回远程模式后副本的占用全部释放。 | | 2026-11-20 | 缓存计时 | Ultra(28 核,Xcode 27.2),清空 DerivedData 后编 `swift-section`(Debug):不走缓存 63 秒,走缓存 46 秒;`warm` 把 70 个第三方 target 编成 xcframework 用了 60 秒,再生成时这 70 个都换成了缓存。测试 scheme 走缓存的全量重跑用户嫌慢叫停了,没有结果;远程模式下修完的那几处都按 bundle 重跑过,本地模式的全量也已通过。写进使用指南。 | | 2026-11-20 | 实现完成,待用户看过后收尾 | 配套文档:使用指南已写;实现说明不另写,清单里每处特殊写法的原因都在指南「已知的坑」与本决策日志里。术语表(「Tuist 开发 workspace」「本地依赖模式」「占用记录」)留到正式收尾时判断。 | +| 2026-11-20 | Implemented,编号 0099 | 用户看过后收尾。术语表登记「Tuist 开发 workspace」与「占用记录」(后者另注明与 `SharedCacheRegistry` 的 claim 无关);「本地依赖模式」就是本地依赖的字面意思,不登记。落地前用 Xcode 27.2 与 26.6 各解析一遍四个包的清单:都能解析,不带变量时与改动前一致,带变量时补的 product 与拿掉的测试和设计相符(MachOKitExtensions 的 `main` 上补 `CPlusPlusDemangling`、`CPlusPlusSymbolsFixture`)。MachOKitExtensions 的功能分支切自它本地一条没推送过的 `next`(只有一个空合并,比 `main` 落后 10 个提交),落地时把那一个提交接到 `main` 上推送;那条本地 `next` 原样留着。账本第 143 节。 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 71820648..0ec5dc3c 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -113,4 +113,4 @@ | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | | [cross-repository MachOKitExtensions 0004](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md) | 符号语言的判断归各自的包:由那边维护唯一提案;本库在 `SwiftSymbols` 定义 `SymbolLanguage.swift` 与 Swift 名字的判断,新 C target `SwiftSymbolsRegistration` 在镜像加载时注册;MachOKitExtensions 下限抬到 3.0.0 | Implemented | -| draft | [Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出](draft-tuist-workspace.md) | In Progress | +| [0099](0099-tuist-workspace.md) | Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 | Implemented | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index b18aa182..03ace4ec 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -103,6 +103,14 @@ macOS 27 与 iOS 27 的 dyld shared cache 不再给每个镜像留自己的 `__o - **主要出现在**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift`、`ObjCImplementationClassIndex.swift` 的 `importedMethods(of:)` - **延伸阅读**:[0090-objc-imported-declarations](Evolutions/0090-objc-imported-declarations.md) +### claim record(占用记录,Tuist 开发 workspace) + +本库与 RuntimeViewer 的 `TuistScript.sh` 共用的互斥记录:往一个检出里生成工程之前先「占用」它。被占检出的 git 目录里写 `tuist-generated-project-owner`(占用者检出的路径、在占用者那里释放它的命令、生成进来的工程名),占用者在自己的 `Tuist/.claimed-checkouts` 里列着它才算有效,否则是陈旧记录、直接接管。另一个检出占着时命令失败,并给出那边的释放命令。 + +- **不要混淆**:与按镜像缓存的 claim(`SharedCacheRegistry`,见「eviction group、claim、live owner」)无关。 +- **主要出现在**:`TuistScript.sh`(`claim_checkout`、`release_checkout`)、RuntimeViewer 的 `TuistScript.sh` +- **延伸阅读**:[TuistDevelopment.md](Internal/TuistDevelopment.md)「与 RuntimeViewer 共用的占用记录」、[提案 0099](Evolutions/0099-tuist-workspace.md) + ### class without a class object(没有 class object 的类,`SwiftClassWithoutClassObject`) `__objc_classlist` 里没有 class object 的 Swift 类:泛型类,父类在别的 resilience domain 的类,父类是本模块泛型类的类。它们的 `class_ro_t` 都静态存在,但只有经 Swift 元数据才找得到(generic metadata pattern、`ResilientClassMetadataPattern`、静态的 incomplete metadata)。后两种有 ObjC 祖先时还在 `__objc_stublist` 里登记一个 stub。交给 MachOObjCSection 时它们叫 supplied class(`ObjCSuppliedClass`),即宿主补进 ObjC 索引器的类。与 `@objc @implementation` 类的区别:那种类有 class object,没有的是 Swift 元数据。 @@ -489,6 +497,14 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 - **不要混淆**:`.machOFile(path:)` 是显式指定一个文件;system root 是按 install name 在目录树里现找。 - **延伸阅读**:MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md)、[提案 standalone-file-thunk-resolution](Evolutions/0030-standalone-file-thunk-resolution.md) +### Tuist development workspace(Tuist 开发 workspace) + +`./TuistScript.sh` 用 Tuist 生成的 `MachOSwiftSection-Tuist.xcworkspace`,原生 `MachOSwiftSection.xcworkspace` 之外只供日常开发的第二条路:第三方依赖预编进本机的 Tuist 二进制缓存,本库与五个上游库从源码编,上游库可用 `--local-dependencies` 切到本地检出。发版、CI、`swift build` / `swift test` 都不走它。 + +- **不要混淆**:「原生 workspace」指 `MachOSwiftSection.xcworkspace`(SwiftPM 包直接放进 Xcode),与它无关。 +- **主要出现在**:`TuistScript.sh`、`Tuist/`、`Workspace.swift`、`Tuist.swift` +- **延伸阅读**:[TuistDevelopment.md](Internal/TuistDevelopment.md)、[提案 0099](Evolutions/0099-tuist-workspace.md) + ### type-construction evaluation(类型构造求值) 离线读 kind-9 accessor thunk 的方法:不执行 thunk,按指令顺序做符号求值——寄存器和栈槽里放「类型表达式」(参数缓冲区第 k 个词、某 descriptor 的 accessor 以若干实参调用的结果、常量 metadata 地址、mangled name 实例化)而不是数值。thunk 只用几种运行时入口(泛型类型的 metadata accessor、`swift_getWitnessTable`、`__swift_instantiateConcreteTypeFromMangledName`)构造类型,每一种的语义都是类型层面的,所以函数返回时 `x0` 里的表达式就是答案。条件跳转能判定的(运行时能力标志、已知立即数)直接判定,判定不了的(版本检查的结果)按「假设为假 / 假设为真」各跑一遍,两次结果即 `if #available` 的两支。与「查表」读法(只认 `csel` 的两个操作数或分支里唯一一次调用)的区别:后者忽略了尾调用,会把 `ModifiedContent<…, X>` 读成 `X`、把中间调用的结果当答案。 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 7a0572fe..077e8bdf 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3425,6 +3425,19 @@ - **关联文档**:[Changelogs/0.26.0.md](../../Changelogs/0.26.0.md)。 - **对应版本**:0.26.0。 +## 143. Tuist 开发 workspace + +- **时间段**:2026-11-20,五个仓库同名的分支 `feature/tuist-workspace`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上构建与测试。 +- **动机**:日常开发时第三方依赖(swift-dependencies 一族、swift-syntax、Capstone……)每次清空 DerivedData 都要重编。照 RuntimeViewer 的做法加一条只供开发用的 Tuist 路:第三方依赖走本机二进制缓存,本库与五个上游库从源码编,上游库可切换为本地检出。 +- **关键决策**: + - `Package.swift` 仍是唯一定义;Tuist 拒绝的两种测试形态(依赖可执行 target、依赖不属于任何 product 的 target)由清单末尾一段只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效的适配块处理,MachOKitExtensions、MachOObjCSection、swift-demangling 加同一段,本地模式下六个包都带测试;`SwiftSectionCommandTests` 与 CLI 手写在 `Tuist/CommandLine/Project.swift`。 + - Tuist 的静态 framework 链接与 SwiftPM 不同:测试与 CLI 要 `-ObjC`,只有加载期 constructor 的 `SwiftSymbolsRegistration` 要整个 `-force_load`;这些名单由 `TuistScript.sh` 读清单与源码算出,不手抄。 + - 与 RuntimeViewer 的 Tuist 本地依赖模式共用一份占用记录,两边互斥。 +- **落地模块**:`TuistScript.sh`、`Tuist.swift`、`Workspace.swift`、`mise.toml`、`Tuist/`、`Package.swift` 末尾、`.gitignore`、原生 workspace 补齐三个成员;三个上游库的 `Package.swift`;RuntimeViewer 的 `TuistScript.sh`。 +- **文档**:提案 [0099-tuist-workspace](../Evolutions/0099-tuist-workspace.md);使用指南 [TuistDevelopment.md](TuistDevelopment.md);`AGENTS.md` 构建一节;术语表两条。 +- **验证**:Ultra,Xcode 27.2。远程模式的测试 scheme 与原生 `swift test --skip IntegrationTests` 逐 bundle 对照全部通过;本地模式全量 2,943 个通过;Tuist 编的 `swift-section` 与原生编的对 SymbolTestsCore 的 `dump`、`interface` 逐字节相同;清空 DerivedData 编 CLI 不走缓存 63 秒、走缓存 46 秒。四个清单在 Xcode 26.6 下也能解析。 +- **对应版本**:未发布(0.26.0 之后);只影响开发,不进发版产物。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index 65a0b924..d1a8e123 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -1,7 +1,7 @@ # 使用指南:Tuist 开发 workspace - **面向**: 在本仓库做日常开发、想让第三方依赖走二进制缓存的人;同时改本库和上游那几个库的人;改 `Package.swift` 的 target、依赖或测试的人(同步规则) -- **对应提案**: [draft-tuist-workspace](../Evolutions/draft-tuist-workspace.md) +- **对应提案**: [0099-tuist-workspace](../Evolutions/0099-tuist-workspace.md) - **最后更新**: 2026-11-20 `MachOSwiftSection-Tuist.xcworkspace` 是原生 `MachOSwiftSection.xcworkspace` 之外的第二条路,只供日常开发。它由 `./TuistScript.sh` 用 Tuist 生成:本库照常从源码编,可以跳转、可以编辑;原生 workspace 里放的五个上游库(MachOKit、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string)也从源码编;其余 27 个第三方包(swift-dependencies 一族、swift-collections、Capstone、swift-crypto、Yams……)预编进本机的 Tuist 二进制缓存,只编一次。 diff --git a/Documentations/README.md b/Documentations/README.md index 100726d0..b371e22e 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -224,7 +224,7 @@ selects names using each access's offset and width. | [DeclarationModelMemoryFootprint.md](Internal/DeclarationModelMemoryFootprint.md) | NodeStore 迁移后的声明模型内存足迹量测:`TypeDefinition` 1272 字节的逐属性构成(两份 `TypeContextWrapper` 占 74%)、`TypeContextWrapper` 按最大 case `Class` 定尺的原因、`parentContext` 是被当成永久字段的临时值、mini-store 增殖与 `MetadataReaderCache` 仍持 `Node` 树;含四项可回收估算(合计 ~8–10%)与「当前不建议实施、应先剖析其余 90%」的结论。 | | [NodeStoreMigrationOpenIssues.md](Internal/NodeStoreMigrationOpenIssues.md) | NodeStore 迁移的遗留问题台账:每条问题记录成因、影响面、修复位置与当前状态(已修 / 裁决不修 / 仍打开),闭环的条目保留成因备回溯。大部分条目已闭环或已终审;与 `Reviews/` 下两份审查记录冲突时以后者为准。 | | [SystemFrameworkRenderingVerification.md](Internal/SystemFrameworkRenderingVerification.md) | 系统框架渲染 A/B 验证流程(大重构必跑):两个检出对同一批真实输入(归档 dyld cache → 无则当前系统 cache、模拟器 runtime → 无则现有 runtime、当前系统 MachOImage)逐字节比对 dump+interface;入口脚本 `Scripts/run-rendering-ab-verification.py`,含回退规则、踩坑清单(`-p` 消歧、fat 二进制 `-a`、同 boot 会话、scratch 隔离)与 2026-08-03 基线运行记录。 | -| [TuistDevelopment.md](Internal/TuistDevelopment.md) | **使用指南:Tuist 开发 workspace**:`./TuistScript.sh` 生成的 `MachOSwiftSection-Tuist.xcworkspace`,第三方依赖走本机二进制缓存,`--local-dependencies` 改用五个上游库的本地检出;测试怎么映射进来(`Package.swift` 末尾的 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 块、手写的 `SwiftSectionCommandTests`)、与 RuntimeViewer 共用的占用记录、存放位置与 Tuist 4.210 的坑。提案 [draft-tuist-workspace](Evolutions/draft-tuist-workspace.md)。 | +| [TuistDevelopment.md](Internal/TuistDevelopment.md) | **使用指南:Tuist 开发 workspace**:`./TuistScript.sh` 生成的 `MachOSwiftSection-Tuist.xcworkspace`,第三方依赖走本机二进制缓存,`--local-dependencies` 改用五个上游库的本地检出;测试怎么映射进来(`Package.swift` 末尾的 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 块、手写的 `SwiftSectionCommandTests`)、与 RuntimeViewer 共用的占用记录、存放位置与 Tuist 4.210 的坑。提案 [0099-tuist-workspace](Evolutions/0099-tuist-workspace.md)。 | | [TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) | **`__C` 模块归属索引管线**(提案 0009 + 0010 的实现说明):`__C.NSString` → `Foundation.NSString` 的三源合并(SourceKit 生成 interface 的 substructure 提取(零 SwiftSyntax)→ APINotes 权威归属覆盖 → 依赖 image ObjC 元数据懒索引兜底)、补充映射包(私有框架外部知识入口,CF-bridged 类型三种 mangling 形态与各自覆盖机制)、按 SDK 精确构建分层的 per-module JSON 缓存、过滤前移的性能形态(历史全 SDK 生成为何小时级)、`@Loggable` 在 `@available` 类型上必须走 protocol 形态的坑、与提案的差异(swift-dependencies 未引入、兜底解析器未编写、MachOObjCSection 下限 0.8.105)。 | | [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 的防优化手段与回归防线。 | From a84c83ef11ea5207770a3a2c1088d696a0894281 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 16:30:37 +0800 Subject: [PATCH 015/175] fix: let a static-archive link load the Swift symbol language registration SwiftSymbolsRegistration.c held only a static load-time constructor, so it defined no symbol: a linker reading SwiftSymbols from a static archive (a Tuist static framework, a static library) never loaded it, -ObjC included, and the binary ran with no Swift symbol language registered. The file now exports a no-op anchor that SymbolLanguage+Swift.swift calls from the registration function; any link that loads that file - every use of the Swift symbol index, every link with -ObjC - loads the constructor with it. --- AGENTS.md | 2 +- .../Internal/Modules/SwiftSymbols.md | 2 +- .../Internal/ProjectEvolutionLog.md | 10 +++++++ Documentations/Internal/TuistDevelopment.md | 2 +- .../SwiftSymbols/SymbolLanguage+Swift.swift | 6 +++++ .../SwiftSymbolsRegistration.c | 20 ++++++++++---- .../include/SwiftSymbolsRegistration.h | 12 +++++++-- ...SwiftSymbolLanguageRegistrationTests.swift | 26 +++++++++++++++++++ 8 files changed, 70 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bc76bb6d..7e44fc2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,7 @@ Everything in this section except `SwiftSymbols` is external: since 0.25.0 these - **MachOFoundation** (external, MachOKitExtensions) — `MachOBase` + `MachOSymbols` + `MachODependencies`: the umbrella for everything above the ABI model, which imports `SwiftSymbols` beside it. - **MachOReading / MachOResolving** (external, MachOKitExtensions) — reading abstractions; address/offset resolution. `MachOResolving` also holds the symbol *value* types (`Symbol`, `Symbols`, `SymbolOrElement`), which carry no lookup behavior — "the symbols at this offset" is a query, not a read. Implementation note: MachOKitExtensions' `Documentations/Internal/ReadingContextAbstraction.md`. - **MachOPointers** (external, MachOKitExtensions) — relative and indirect pointer types, plus `SymbolOrElementPointer`. -- **MachOSymbols** (external, MachOKitExtensions) — the language-neutral half of the symbol index: the 16-byte-row `SymbolTable`, `SymbolRowBucket`, `SymbolValueOffsetConverter`, the `NlistProtocol` checks, `SymbolLanguage` with its `SymbolLanguageRegistry` (C++ is recognized there; Swift is registered by this repo's `SwiftSymbols`, which defines `.swift`, from the C target `SwiftSymbolsRegistration`'s load-time constructor), the one-pass sweep over symbol table and export trie (`SymbolSweep`, steered by a `SymbolTableRouting`), and a `SymbolIndexStore` that holds C and C++ names only, keeping registered languages' symbols as offsets alone (eviction group `.symbolStore`). The building blocks this repo uses are `@_spi(Internals)`. [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md). +- **MachOSymbols** (external, MachOKitExtensions) — the language-neutral half of the symbol index: the 16-byte-row `SymbolTable`, `SymbolRowBucket`, `SymbolValueOffsetConverter`, the `NlistProtocol` checks, `SymbolLanguage` with its `SymbolLanguageRegistry` (C++ is recognized there; Swift is registered by this repo's `SwiftSymbols`, which defines `.swift`, from the C target `SwiftSymbolsRegistration`'s load-time constructor — which a static-archive link (a Tuist static framework) loads only because `SymbolLanguage+Swift.swift` calls the no-op `swift_symbols_registration_anchor()`; never remove that call), the one-pass sweep over symbol table and export trie (`SymbolSweep`, steered by a `SymbolTableRouting`), and a `SymbolIndexStore` that holds C and C++ names only, keeping registered languages' symbols as offsets alone (eviction group `.symbolStore`). The building blocks this repo uses are `@_spi(Internals)`. [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md). - **SwiftSymbols** (this repo, `Sources/Symbols/SwiftSymbols`) — the Swift symbol index: `SwiftSymbolIndexStore` routes the sweep through `SwiftSymbolTableRouting`, then demangles, classifies and holds the per-image node stores; also `LargeStackTaskExecution`, and the image's `_symbolic` symbols in a table of their own that no offset or name query sees (`symbolicManglingSymbols(in:)`). Eviction group `.swiftSymbolStore`, dependency key `swiftSymbolIndexStore`. [Modules/SwiftSymbols.md](Documentations/Internal/Modules/SwiftSymbols.md). - **MachOCaches** (external, MachOKitExtensions) — the per-image cache primitive, NOT dyld shared cache support (that is `MachOKitExtensions` and `MachODependencies`): `SharedCache` (get-or-build per image, one build shared by concurrent callers, the build closure supplied at the call site), `SharedCacheKey` (hashes a file on its UUID alone, an image read from a dyld cache on its own and its cache's) and `SharedCacheRegistry` + `SharedCacheEvictionGroup` (which caches an indexer claims for an image and what its last live instance evicts). [SharedCache.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md). - **MachODependencies** (external, MachOKitExtensions) — the one dependency-resolution implementation every feature shares (`DependencyClosure`, the in-process and file locators, `DependencySearchPath`, `SharedDependencyClosure` for consumers of one root that resolve lazily). The file locator filters dyld-cache candidates by platform (`DependencyPlatforms`, from `LC_BUILD_VERSION`): the host's macOS cache is every root's default search path and carries Mac Catalyst UIKit / SwiftUI under `/System/iOSSupport`, which an iOS root used to resolve to by bare name. Reach the host's cache through `FullDyldCache.cachedHost` (MachOKitExtensions), never `FullDyldCache.host`: `host` opens and maps all 82 files of a macOS 27 cache on every read, and a locator is built per root — an evolution over 51 archived caches held 51 copies open (`FileDependencyLocatorTests` in MachOKitExtensions pins the sharing). [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md). diff --git a/Documentations/Internal/Modules/SwiftSymbols.md b/Documentations/Internal/Modules/SwiftSymbols.md index 02b41f4b..f5097344 100644 --- a/Documentations/Internal/Modules/SwiftSymbols.md +++ b/Documentations/Internal/Modules/SwiftSymbols.md @@ -29,7 +29,7 @@ SwiftSymbols 是 **Swift 符号索引**层:在 MachOKitExtensions `MachOSymbol `SymbolLanguage.swift` 定义在本模块(`SymbolLanguage+Swift.swift`),不在 MachOKitExtensions:Swift 名字怎么认归本包管(MachOKitExtensions 提案 [split-symbol-language](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md))。 - **识别**:`SwiftSymbolNameRecognition.recognizes` 只看名字开头的字节——`$s` `_$s` `$S` `_$S` `$e` `_$e` `_T0` `@__swiftmacro_`,以及链接器去重名 `_symbolic `、`_default assoc type `。前缀集合必须与 swift-demangling 的 `isSwiftSymbol` 一致,`SymbolTableEquivalenceTests.swiftRecognitionMatchesDemanglingIsSwiftSymbol` 在真实符号表上钉住。 -- **注册**:C target `SwiftSymbolsRegistration` 里的 `__attribute__((constructor))` 在镜像加载时调用本模块用 `@c` 导出的 `swift_symbols_register_symbol_language`,向 `SymbolLanguageRegistry.shared` 登记 `.swift`。`SwiftSymbols` 依赖这个 C target,链接 `SwiftSymbols` 就带上了 constructor,调用方什么都不用做。Swift 自己没有加载时初始化:SE-0492 的 `@section` 写进 `__mod_init_func` 在 Swift 6.4.2 上链接失败,所以用 C target。 +- **注册**:C target `SwiftSymbolsRegistration` 里的 `__attribute__((constructor))` 在镜像加载时调用本模块用 `@c` 导出的 `swift_symbols_register_symbol_language`,向 `SymbolLanguageRegistry.shared` 登记 `.swift`。`SwiftSymbols` 依赖这个 C target。SwiftPM 与 Xcode 自带的包集成整块链接每个 target,constructor 总会带上;从静态归档链接时(Tuist 的静态 framework、静态库),链接器只拉被符号引用到的成员,而 constructor 是 `static` 的,所以这个 C 文件另外导出一个什么都不做的锚点 `swift_symbols_registration_anchor`,由 `SymbolLanguage+Swift.swift` 的注册函数调用:用到 Swift 索引、或带 `-ObjC` 的链接会拉进那个 Swift 文件,它对锚点的引用再把 C 文件连同 constructor 拉进来。调用方什么都不用做;`SwiftSymbolLanguageRegistrationTests.languageFileRefersToTheRegistrationAnchor` 钉住引用的两端。Swift 自己没有加载时初始化:SE-0492 的 `@section` 写进 `__mod_init_func` 在 Swift 6.4.2 上链接失败,所以用 C target。 - **效果**:注册之后,MachOKitExtensions 的 C/C++ 索引不再收 Swift 名字,只留它们的偏移,地址落在 Swift 函数里时 `closestSymbols` 答 `nil`。`SwiftSymbolLanguageRegistrationTests` 钉住这三件事。 ## 子系统 1:索引本体 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 077e8bdf..341acdd0 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3438,6 +3438,16 @@ - **验证**:Ultra,Xcode 27.2。远程模式的测试 scheme 与原生 `swift test --skip IntegrationTests` 逐 bundle 对照全部通过;本地模式全量 2,943 个通过;Tuist 编的 `swift-section` 与原生编的对 SymbolTestsCore 的 `dump`、`interface` 逐字节相同;清空 DerivedData 编 CLI 不走缓存 63 秒、走缓存 46 秒。四个清单在 Xcode 26.6 下也能解析。 - **对应版本**:未发布(0.26.0 之后);只影响开发,不进发版产物。 +## 144. 静态链接也带上符号语言注册 + +- **时间段**:2026-11-20,`feature/registration-link-anchor`(本库与 MachOObjCSection 同名)。 +- **动机**:Swift 与 ObjC 两种符号语言由 C 文件里的 `static` 加载期 constructor 登记(第 141 节),文件里没有别的符号。SwiftPM 与 Xcode 自带的包集成整块链接 target,constructor 总会带上;从静态归档链接的使用方(Tuist 的静态 framework、静态库)只拉被引用的成员,`-ObjC` 也不拉它,注册表就是空的。本库的 Tuist workspace 当时靠脚本给它加 `-force_load` 绕过(第 143 节),RuntimeViewer 的 Tuist workspace 漏了,用链接探针实测证实;用户要求在库里根治。 +- **关键决策**:注册用的 C 文件另外导出一个什么都不做的锚点函数,由定义该语言、注册该语言的那个 Swift 文件在注册函数里调用。那个 Swift 文件定义了 extension,带 `-ObjC` 的链接一定拉进它;本库的 Swift 索引扫描每次都用它的识别规则,用到索引也会拉进它。它对锚点的引用再把 C 文件连同 constructor 拉进来。constructor 照旧负责在任何代码查询之前完成注册。没有改成显式注册(使用方调用一个函数):那要所有使用方都记得调用。 +- **落地模块**:`Sources/Symbols/SwiftSymbolsRegistration/`(锚点与头文件)、`Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift`;MachOObjCSection 的 `MachOObjCSectionC/symbol_language_registration.c` 与 `SymbolLanguage+ObjectiveC.swift`。本库 `TuistScript.sh` 对带 constructor 的 target 加 `-force_load` 的通用规则保留作保险。 +- **文档**:`Modules/SwiftSymbols.md` 注册一条、`TuistDevelopment.md` 已知的坑、`AGENTS.md` 的 MachOSymbols 一条(别删那个调用)。 +- **验证**:`SwiftSymbolLanguageRegistrationTests.languageFileRefersToTheRegistrationAnchor` 钉住引用的两端(SwiftPM 整块链接,单元测试看不到静态归档漏掉成员);用真实目标文件做的静态归档链接验证见提交说明。 +- **对应版本**:未发布(0.26.0 之后)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index d1a8e123..1a2f934c 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -98,7 +98,7 @@ Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` - **CLI 的部署版本是 macOS 12.0**(`Tuist/CommandLine/Project.swift`):Tuist 把 swift-argument-parser 编成它声明的最低版本 macOS 12,10.15 的 `swift-section` import 不了它。 - **测试 target 的部署版本抬到 macOS 14.0**(`Tuist/Package.swift` 的 `testTargetSettings`):SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(Xcode 26、27 都是 14.0),包声明的更低也一样;Tuist 照搬包声明的 10.15,`TypeIndexingTests` 于是找不到它测的 macOS 13 API。脚本把所有转换进来的测试 target(含 `IntegrationTests`,免得编整个 workspace 时它编不过)传进 `TUIST_TEST_TARGET_NAMES`。 - **测试 target 与 `swift-section` 链接时带 `-ObjC`**(`Tuist/Package.swift` 的 `testTargetSettings`,`Tuist/CommandLine/Project.swift` 的 `linkFlags`):SwiftPM 把每个包 target 的目标文件整块链进去;Tuist 编的是静态 framework,链接器只拉被符号引用到的归档成员。没人点名的 protocol conformance 于是丢了,`as?` 静默失败:包装 `MachOImage` / `MachOFile` 的读取器(`MachOReaderWrapper`)两样都不像,`WrappedReaderSymbolTests` 与 `WrappedReaderDemanglingTests` 红了 4 条。Xcode 27 的链接器下 `-ObjC` 会拉进所有定义了 ObjC 类或分类、Swift 类型或 extension 的成员,与 RuntimeViewer 的 Tuist workspace 同一个做法。 -- **`SwiftSymbolsRegistration` 被整个 `-force_load`**:它只有一个 `static` 的加载期 constructor(把 Swift 注册成符号语言),没有任何全局符号,`-ObjC` 也拉不进它。不加的话 Swift 语言没注册,`SwiftSymbolsTests` 红 281 处,Tuist 编的 `swift-section` 也会把 Swift 符号当成 C。脚本读清单时找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出哪些测试 target 与可执行 target 会链到它,传进 `TUIST_FORCE_LOADS`;这些链接对那个归档加 `-force_load`。 +- **有加载期 constructor 的 target 被整个 `-force_load`**:`SwiftSymbolsRegistration` 的 constructor 把 Swift 注册成符号语言。它原先是那个 C 文件唯一的内容,又是 `static`,文件里没有全局符号,`-ObjC` 也拉不进来;不加的话 Swift 语言没注册,`SwiftSymbolsTests` 红 281 处,Tuist 编的 `swift-section` 也会把 Swift 符号当成 C。如今这个文件导出了锚点 `swift_symbols_registration_anchor`,`SymbolLanguage+Swift.swift` 调用它,带 `-ObjC` 的链接已经能把它拉进来(MachOObjCSection 的 `MachOObjCSectionC` 同样处理)。脚本仍然保留这条通用规则,作为保险:读清单时找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出哪些测试 target 与可执行 target 会链到它,传进 `TUIST_FORCE_LOADS`,这些链接对那个归档加 `-force_load`。 - **导入了 Testing 的库 target 加上 TestingMacros 插件路径**(`Tuist/Package.swift` 的 `testingSupportSettings`):`SwiftSectionTestingSupport` 是普通的库 target,却用了 Swift Testing 的 `#require`。SwiftPM 给每个 target 都带上工具链的 TestingMacros 插件,Xcode 只给测试 target 带,于是报 `plugin for module 'TestingMacros' not found`。脚本读清单时找出源码里 `import Testing` 的库 target(本地模式下还有上游库的,比如 swift-demangling 的 `DemanglingTestingSupport`),传进 `TUIST_TESTING_SUPPORT_TARGET_NAMES`。 - **手写的 target 设了 `SWIFT_PACKAGE_NAME = MachOSwiftSection`**(`Tuist/CommandLine/Project.swift`):`SwiftSectionCommandTests` 调用 SwiftSectionKit 的 `package` 方法,只有同一个包的模块看得见;Tuist 给它转换的 target 都设了这个值,手写的也要设。 - **`CAPSTONE_HAS_AARCH64` 手动补上**:Tuist 丢掉只以 trait 为条件的设置;本库开了 swift-capstone 的 `AARCH64` trait,不补的话 Swift 包装编不过,C 库能编过但没有任何架构可用。 diff --git a/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift b/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift index 9fedc8d4..2d07b386 100644 --- a/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift +++ b/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift @@ -1,4 +1,5 @@ import MachOSymbols +import SwiftSymbolsRegistration extension SymbolLanguage { /// A Swift-mangled name (`$s`, `_$s`, `$S`, `_$S`, `$e`, `_$e`, `_T0`, @@ -52,4 +53,9 @@ enum SwiftSymbolNameRecognition { @c(swift_symbols_register_symbol_language) func registerSwiftSymbolLanguage() { SymbolLanguageRegistry.shared.register(.swift, where: SwiftSymbolNameRecognition.recognizes) + // Does nothing at run time. The reference is what counts: a static link + // that loads this file (any use of the Swift symbol index, any link with + // -ObjC) loads SwiftSymbolsRegistration.c and its constructor with it, + // which nothing else refers to. See that file. + swift_symbols_registration_anchor() } diff --git a/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c b/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c index 8730be95..c16266d5 100644 --- a/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c +++ b/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c @@ -2,11 +2,11 @@ // SwiftSymbolsRegistration.c // SwiftSymbolsRegistration // -// Registers `SymbolLanguage.swift` with MachOKitExtensions' symbol language -// registry when the image holding SwiftSymbols loads, so that every -// classification and the C/C++ symbol index see the language before any -// code asks. Swift has no load-time initializers; a constructor here, in a -// C target SwiftSymbols depends on, runs with no caller involved. +// Registers `SymbolLanguage.swift` with MachOKitExtensions' symbol +// language registry when the image holding SwiftSymbols loads, so that +// every classification and the C/C++ symbol index see the language before +// any code asks. Swift has no load-time initializers; a constructor here, +// in a C target SwiftSymbols depends on, runs with no caller involved. // #include "SwiftSymbolsRegistration.h" @@ -18,3 +18,13 @@ __attribute__((constructor)) static void registerSymbolLanguageAtLoad(void) { swift_symbols_register_symbol_language(); } + +// A linker that reads SwiftSymbols from a static archive (a Tuist static +// framework, a static library) loads an object only for a symbol something +// refers to, and -ObjC does not load an object that defines no Objective-C +// class or category and no Swift type. The constructor above is static, so +// without this function the object would define nothing and never be loaded: +// the image would run without the Swift symbol language registered. SwiftSymbols +// calls this function from the file that registers the language, which every +// use of the Swift symbol index and every link with -ObjC loads. +void swift_symbols_registration_anchor(void) {} diff --git a/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h b/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h index b3a8af95..db609643 100644 --- a/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h +++ b/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h @@ -2,6 +2,14 @@ // SwiftSymbolsRegistration.h // SwiftSymbolsRegistration // -// Nothing to import: the target exists for the constructor in -// SwiftSymbolsRegistration.c. +// The target exists for the constructor in SwiftSymbolsRegistration.c. // + +#ifndef SWIFT_SYMBOLS_REGISTRATION_H +#define SWIFT_SYMBOLS_REGISTRATION_H + +/// Does nothing. Calling it makes a static link that loads the caller load +/// SwiftSymbolsRegistration.c — and its constructor — too. +void swift_symbols_registration_anchor(void); + +#endif diff --git a/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift b/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift index 18dc9c72..9558a254 100644 --- a/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift +++ b/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift @@ -29,6 +29,32 @@ struct SwiftSymbolLanguageRegistrationTests { #expect(SymbolLanguage(ofSymbolNamed: "__ZN4llvm5Value4dumpEv") == .cPlusPlus) } + /// A static link (a Tuist static framework, a static library) loads + /// SwiftSymbolsRegistration.c, and the constructor that registers the + /// language, only because SymbolLanguage+Swift.swift refers to its anchor: + /// the constructor is static, so the file defines nothing else, and -ObjC + /// does not load it either. SwiftPM links every target whole, so no test + /// here can watch an archive leave the file out; this pins both halves of + /// the reference instead. + @Test func languageFileRefersToTheRegistrationAnchor() throws { + let packageRoot = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + let symbolSources = packageRoot.appendingPathComponent("Sources/Symbols") + let registrationSource = try String( + contentsOf: symbolSources.appendingPathComponent("SwiftSymbolsRegistration/SwiftSymbolsRegistration.c"), + encoding: .utf8 + ) + let languageSource = try String( + contentsOf: symbolSources.appendingPathComponent("SwiftSymbols/SymbolLanguage+Swift.swift"), + encoding: .utf8 + ) + // Not static: a static function is no symbol a reference can name. + #expect(registrationSource.contains("\nvoid swift_symbols_registration_anchor(void) {")) + #expect(languageSource.contains("\n swift_symbols_registration_anchor()\n")) + } + @Test func cAndCPlusPlusStoreLeavesSwiftNamesOut() throws { let (swiftCore, swiftSymbols, otherSymbols) = try Self.swiftCoreSymbols() try #require(!swiftSymbols.isEmpty && !otherSymbols.isEmpty) From 56205abbe0eb60b25d118d20388eb7b7986cd86c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 16:37:24 +0800 Subject: [PATCH 016/175] docs: record the static-archive link verification of the registration anchor --- Documentations/Internal/ProjectEvolutionLog.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 341acdd0..ec5db637 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3445,7 +3445,10 @@ - **关键决策**:注册用的 C 文件另外导出一个什么都不做的锚点函数,由定义该语言、注册该语言的那个 Swift 文件在注册函数里调用。那个 Swift 文件定义了 extension,带 `-ObjC` 的链接一定拉进它;本库的 Swift 索引扫描每次都用它的识别规则,用到索引也会拉进它。它对锚点的引用再把 C 文件连同 constructor 拉进来。constructor 照旧负责在任何代码查询之前完成注册。没有改成显式注册(使用方调用一个函数):那要所有使用方都记得调用。 - **落地模块**:`Sources/Symbols/SwiftSymbolsRegistration/`(锚点与头文件)、`Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift`;MachOObjCSection 的 `MachOObjCSectionC/symbol_language_registration.c` 与 `SymbolLanguage+ObjectiveC.swift`。本库 `TuistScript.sh` 对带 constructor 的 target 加 `-force_load` 的通用规则保留作保险。 - **文档**:`Modules/SwiftSymbols.md` 注册一条、`TuistDevelopment.md` 已知的坑、`AGENTS.md` 的 MachOSymbols 一条(别删那个调用)。 -- **验证**:`SwiftSymbolLanguageRegistrationTests.languageFileRefersToTheRegistrationAnchor` 钉住引用的两端(SwiftPM 整块链接,单元测试看不到静态归档漏掉成员);用真实目标文件做的静态归档链接验证见提交说明。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 27.2。 + - `SwiftSymbolLanguageRegistrationTests` 4 个通过,含新的 `languageFileRefersToTheRegistrationAnchor`:它钉住引用的两端,因为 SwiftPM 整块链接,单元测试看不到静态归档漏掉成员。MachOObjCSection 的 `ObjectiveCSymbolLanguageTests` 5 个通过。两个库的改动用 Xcode 26.6 也编得过。 + - 静态归档链接:用 `swift build` 编出的 11 个 SwiftSymbols 目标文件打成归档,只带 `-ObjC` 链接。注册文件带锚点时 constructor 被拉进来;换回改动前的注册文件,其余不变,constructor 不在。 + - RuntimeViewer 的 Tuist workspace 改动前没有这两个 constructor,它先在清单里对 15 个链到本库的 target 加了 `-force_load`。改后 App、插件、两个注入载荷、`runtime-viewer-cli` 与 10 个测试 bundle 里都有,见它 0053 的决策日志;它跟上本库与 MachOObjCSection 的 `next` 之后,那些 `-force_load` 可以去掉。 - **对应版本**:未发布(0.26.0 之后)。 ## 维护约定 From 7228547adddf19bd5f5eaefe34d2913186508a8a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:19:45 +0800 Subject: [PATCH 017/175] docs: propose Swift 6 mode for MachOKit and three upcoming features across the MachO packages Accepted draft: MachOKit moves to tools 6.2 (Swift 6 language mode), and every Swift target of the six MachO packages enables ExistentialAny, MemberImportVisibility and InferIsolatedConformances. Co-Authored-By: Claude --- Documentations/Evolutions/README.md | 1 + ...aft-swift6-mode-and-upcoming-features.html | 504 ++++++++++++++++++ ...draft-swift6-mode-and-upcoming-features.md | 326 +++++++++++ Documentations/README.md | 1 + 4 files changed, 832 insertions(+) create mode 100644 Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html create mode 100644 Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 0ec5dc3c..bbda5f56 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -114,3 +114,4 @@ | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | | [cross-repository MachOKitExtensions 0004](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md) | 符号语言的判断归各自的包:由那边维护唯一提案;本库在 `SwiftSymbols` 定义 `SymbolLanguage.swift` 与 Swift 名字的判断,新 C target `SwiftSymbolsRegistration` 在镜像加载时注册;MachOKitExtensions 下限抬到 3.0.0 | Implemented | | [0099](0099-tuist-workspace.md) | Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 | Implemented | +| draft | [MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature](draft-swift6-mode-and-upcoming-features.md):MachOKit 切 Swift 6,六个包开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`(跨仓库唯一提案) | Accepted | diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html new file mode 100644 index 00000000..1cabcda7 --- /dev/null +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html @@ -0,0 +1,504 @@ + + + + + + +Draft - MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature + + + + +
+ +
+

MachOSwiftSectionEvolutionsDraft

+

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

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

摘要

+

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

+

源码改动约 900 处,绝大部分是补 import 与补 any;非测试 target 用 swift package migrate 自动改,测试 target 照诊断清单手改,另有 6 处工具处理不了、要先手工改好。同为 Swift 7 默认的 NonisolatedNonsendingByDefault、InternalImportsByDefault、ImmutableWeakCaptures,以及独立的 StrictMemorySafety,量过之后明确不做。

+
+ +
+

要你定

+
+

批准这份提案

+
    +
  1. 按「落地步骤」开工:六个仓库各开 feature/swift6-mode-and-upcoming-features 分支,构建与测试都在 Ultra 上跑。
  2. +
+
+
+

没问用户就采用的假设

+
    +
  • 三项特性也开在 MachOKit fork 上(49 个文件补 import),不提给上游。
  • +
  • MachOKit 的 tools-version 直接升到 6.2,与另外五个包一致。
  • +
  • 测试 target 与 IntegrationTests 一起开。
  • +
  • 各仓库不为此单独发版,随下一次正常发版带出。
  • +
  • 本库最后跑一遍渲染 A/B,用来兜住名字遮蔽一类不报错的变化。
  • +
+
+
+ +
+

架构图

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

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

+ +
+ + Pre-fix what migrate mode cannot expressMachOSwiftSection: 4 imports + 2 Swift.Error + swift package migrate --to-feature …non-test targets; fails at the manifest step by design + swift build --build-tests + three :migrate flagslists what is left under Tests/ + Fix every remaining warning under Tests/ by handimports, any, nonisolated conformances + Add the loop to Package.swiftfeatures on for every Swift target + swift build --build-tests → swift testzero errors, suite green (Xcode 27.2) + DEVELOPER_DIR=Xcode-26.6 swift build --build-testsCI toolchain, Swift 6.3 + + + + + + + +
+

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

+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
MachOSwiftSection Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md、同名 .html新增本提案与网页版唯一提案1
MachOSwiftSection Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案索引1
MachOKitExtensions、MachOObjCSection Documentations/Evolutions/README.md修改各加一行 cross-repository 指向本提案跨仓库提案的约定1
MachOKit Package.swift:1修改swift-tools-version 5.10 → 6.2进入 Swift 6 语言模式2
MachOKit Package.swift:76、:145–171 · extension SwiftSetting修改 删除MachOKit target 不再拼 SwiftSetting.allCases;删掉九项 Swift 6 默认特性与 CaseIterable 扩展;末尾加统一开关循环Swift 6 模式下那九项是空操作;与另外五个包同一写法2
MachOKit Sources/MachOKit/**(49 个文件)修改补 56 处 importMemberImportVisibility2
MachOKit Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift修改(可选)消掉 2 条 SendableClosureCaptures 与 1 条 AddPreconcurrencyImport 警告Swift 6 模式下仍是警告,不挡编译2
swift-semantic-string Package.swift(第 94 行之后)修改加统一开关循环开启三项特性3
swift-semantic-string AnyComponent.swift、FrozenSemanticString+Codable.swift、SemanticString+Conformances.swift修改补 6 处 anyExistentialAny3
swift-demangling Package.swift(第 171 行之后)修改加统一开关循环开启三项特性3
swift-demangling Sources/DemanglingTestingSupport/Required.swift修改补 1 处 anyExistentialAny3
swift-demangling DefectRegressionTests.swift、NodeTests.swift、TransientRemangleParityTests.swift修改补 3 处 importMemberImportVisibility3
MachOKitExtensions Package.swift(第 390 行之后)修改加统一开关循环开启三项特性4
MachOKitExtensions RequiredNonOptional.swift、String+.swift、DependencyLoadName.swift修改1 处 any、2 处 import两项特性4
MachOKitExtensions Tests/(5 个文件)修改2 处 any、3 处 import两项特性4
MachOObjCSection Package.swift(第 421 行之后)修改加统一开关循环开启三项特性5
MachOObjCSection Sources/(五个模块)修改补 15 处 importMemberImportVisibility5
MachOObjCSection Tests/(约 19 个文件)修改21 处 import、2 处 any两项特性5
MachOSwiftSection TypeAttributeInferrer.swift修改加 import SwiftObjCInterop迁移模式下第 143 行的 switch 报不完备6
MachOSwiftSection ABIDiffer.swift修改加 import MachOSwiftSection迁移模式下第 289 行 .enum 解析错6
MachOSwiftSection ObjCAPIRequests.swift:295、ABIEvolutionRequest.swift:180修改: Error → : Swift.Errormigrate 补的 import Semantic 让 Error 解析成 Semantic.Error6
MachOSwiftSection Sources/**(约 258 个文件,其中 SwiftSectionFixtureSupport 约 176 个)修改swift package migrate 的 300 个 fix-it:import 与 any两项特性6
MachOSwiftSection Package.swift:1541–1548 之后、:1550 的 Tuist 块之前修改加统一开关循环,用已有常量开启三项特性;Tuist 改写 target 时设置已在6
MachOSwiftSection ExtensionContainerUnificationTests.swift、SymbolTestsCoreIntegrationTests.swift修改加 import OrderedCollections迁移模式下 .values 解析错7
MachOSwiftSection Tests/**(约 180 个文件)修改手改约 235 处 import、41 处 any两项特性;migrate 不改测试7
MachOSwiftSection Tests/IntegrationTests/(6 个文件)修改33 处 conformance 标 nonisolatedInferIsolatedConformances,保持现有行为7
MachOSwiftSection Documentations/Internal/ProjectEvolutionLog.md修改加一节账本9
+
+
+ +
+

提议方案与非目标

+
    +
  1. MachOKit 进 Swift 6 语言模式。第 1 行改成 // swift-tools-version: 6.2,tools 6.x 不声明 swiftLanguageModes 时默认 Swift 6。删掉九项 Swift 6 已默认开启的 upcoming setting 与 CaseIterable 扩展,改用统一开关;AccessLevelOnImport 实验特性保留,编译器提示多余再删。
  2. +
  3. 六个包的每个 Swift target 统一开启三项特性。每份清单在 let package = Package(...) 之后加一个循环,给除 system、binary、plugin 以外的所有 target 追加同一组设置;本库沿用 Package.swift:1541 已有的常量。test、macro、executable target 都包括在内。
  4. +
  5. 源码按三类处理。先手工改好 6 处预修;再对非测试 target 跑 swift package migrate(改清单那步报错是预期的,以「Applied N fix-its」为准);测试 target 用 --build-tests 加三个 :migrate 开关构建,照警告逐条手改。最后才加清单里的开关,正式开启后确认零错误。
  6. +
  7. 每加一条 import Semantic,就检查那个文件里裸写的 Error、Numeric、Argument。类型位置写 Swift.Error / Swift.Numeric;as Error、is Error 与 catch 模式逐个看;「cast always fails」警告按错误对待。
  8. +
  9. 从下往上落地,不为此单独发版。MachOKit → swift-semantic-string → swift-demangling → MachOKitExtensions → MachOObjCSection → 本库。设置只影响包自身的编译,不改公开 API。
  10. +
+
+

非目标

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

详细设计

+
+ 统一开关(五个兄弟包写在清单末尾) +
+
let upcomingFeatureSettings: [SwiftSetting] = [
+    .enableUpcomingFeature("ExistentialAny"),
+    .enableUpcomingFeature("MemberImportVisibility"),
+    .enableUpcomingFeature("InferIsolatedConformances"),
+]
+
+for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin {
+    target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings
+}
+

本库写在 extension SwiftSetting(Package.swift:1541)之后、Tuist 块(:1550)之前,数组里用已有的 .existentialAny、.memberImportVisibility、.inferIsolatedConformances;另外三个未用的常量留着,将来开时直接加进数组。

+
+
+
+ MachOKit 清单 +
+

第 1 行改为 // swift-tools-version: 6.2;MachOKit target 的 swiftSettings 只剩 .enableExperimentalFeature("AccessLevelOnImport", .when(configuration: .debug));原来的 extension SwiftSetting { static let forwardTrailingClosures … } 与 extension SwiftSetting: @retroactive CaseIterable 整段删除;末尾加与兄弟包相同的循环。

+
+
+
+ 迁移命令与日志处理 +
+
queued-build swift package --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \
+    migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances
+
+queued-build swift build --build-tests \
+    --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \
+    -Xswiftc -print-diagnostic-groups \
+    -Xswiftc -enable-upcoming-feature -Xswiftc ExistentialAny:migrate \
+    -Xswiftc -enable-upcoming-feature -Xswiftc MemberImportVisibility:migrate \
+    -Xswiftc -enable-upcoming-feature -Xswiftc InferIsolatedConformances:migrate
+

第一条退出码是 1 属正常(改清单失败),看输出里的 Applied N fix-its in M files。第二条列出测试 target 里剩下的警告。日志带 ANSI 颜色与 OSC 8 超链接,按 [#组名] 计数前要先去掉转义;同一条诊断会打印两遍,按「文件:行:列 + 文字」去重。

+

手改测试:import of module 'X' is required 就在 import 区按字母序补 import X(已有 @testable 或 @_spi(...) 形式的不重复加);ExistentialAny 补 any;conformance of 'T' to 'P' should be marked 'nonisolated' 照写 nonisolated P。批量补 import 的脚本先给用户看过再跑。

+
+
+
+ +
+

调研

+

2026-11-20 在 Ultra(Xcode 27.2,Swift 6.4.2)上把六个包的当前提交各自 clone,以每个包为根编 swift build --build-tests;新特性用 SE-0486 的迁移模式(:migrate)只出警告,按诊断组计数,只统计包根目录下的文件。日志与改过的 clone 在 /Volumes/DerivedData/Agents.noindex/claude/Probes/Swift6Migration/。

+
+ 三项要开的特性:各包改动处数(源码 / 测试) +
+
+ + + + + + + + + + +
包ExistentialAnyMemberImportVisibilityInferIsolatedConformances
MachOKit已开启(0)56 / 00 / 0
MachOKitExtensions1 / 22 / 30 / 0
MachOObjCSection0 / 215 / 210 / 0
swift-demangling1 / 00 / 30 / 0
swift-semantic-string6 / 00 / 00 / 0
MachOSwiftSection57 / 41245 / 2350 / 33
+
+

本库 MemberImportVisibility 的 245 处源码里有 189 处在测试基线生成器 SwiftSectionFixtureSupport;InferIsolatedConformances 的 33 处全在 IntegrationTests。

+
+
+
+ 量过、决定不做的四项 +
+
+ + + + + + + + +
特性改动处(源码 / 测试)不做的原因
NonisolatedNonsendingByDefault778 / 347,本库占 729 / 234改运行语义:nonisolated async 函数改在调用方的 actor 上执行,RuntimeViewer 从主线程调用时解析会跑到主线程;保留现状要给上千个函数加 @concurrent
InternalImportsByDefault4,124 行 import(约 1,400 个文件)没有迁移模式;约一半必须保持 public import;下游可能因失去传递可见性而编不过
ImmutableWeakCaptures约 0收益近乎为零,随将来的 Swift 7 模式一起处理
StrictMemorySafety2,440 / 658不属于 Swift 6 或 7;几千处 unsafe 标注只会是噪音
+
+
+
+
+ MachOKit 进 Swift 6 模式 +
+

Swift 5 模式加 -strict-concurrency=complete:Sources 零并发诊断,Tests 3 条警告。直接 -swift-version 6(从构建数据库核实四个 target 都拿到了):全部编过、零错误。上游 p-x9/MachOKit 同样是 tools 5.10;fork 比上游多 35 个提交、少 40 个。

+
+
+
+ swift package migrate 的实际表现与迁移模式的坑 +
+
    +
  • 非测试 target:258 个文件里套用了 300 个 fix-it(+304 / −57),然后在改清单那一步失败(unable to find target named 'Utilities' in package),源码已经改好。
  • +
  • 测试 target:一处都不改,显式 --target 也是 Applied 0 fix-its。
  • +
  • 构建一失败就一处都不改。本库 4 处在迁移模式下直接报错:TypeAttributeInferrer.swift:143(switch must be exhaustive)、ABIDiffer.swift:289(.enum 解析成实例成员)、两个测试文件的 .values 落到 dynamic member lookup。
  • +
  • swift-semantic-string 公开声明了 struct Error、struct Numeric、Argument。文件直接 import Semantic 后裸写的 Error 解析成 Semantic.Error:ObjCAPIRequests.swift:295 与 ABIEvolutionRequest.swift:180 因此编不过;as Error 一类转型则不报错、只变成永远失败。
  • +
  • 补完 6 处、migrate 跑完、清单手加开关后,Sources 全部编过;测试 target 逐个报缺 import,与警告清单一致。
  • +
  • 清单里给 C target 加 swiftSettings 无害:同一个循环在六个包上都照常编过。
  • +
+
+
+
+ +
+

替代方案

+
+ 六条,都否了或改了形状 +
+
    +
  • MachOKit 只加 StrictConcurrency:Swift 5 模式下只是警告,约束力不够。
  • +
  • MachOKit 用 swiftLanguageVersions: [.version("6")]:tools 6 已废弃改名,写法与兄弟包不一致,第 1 行的上游冲突也省不掉。
  • +
  • 逐个 target 写或让 migrate 改清单:本库 53 个 target、MachOKitExtensions 24 个、MachOObjCSection 19 个,容易漏;migrate 在本库清单上直接失败。选统一循环。
  • +
  • 四项全开:调研结果摆出来之后,用户选了只开三项低风险的。
  • +
  • 不开 MemberImportVisibility:它改动最大、坑最多,但正是「依赖写在自己的 import 里」的来源,坑也都已找全。保留。
  • +
  • 给 Semantic.Error 改名:公开 API 破坏,不在本次范围;只在调用点写 Swift.Error。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增。六个包都不改任何公开声明的签名;MachOKit 换语言模式不改变公开 API。upcoming feature 只作用于开启它的 target 本身,不传给下游。
  • +
  • ABI:不适用,SPM 源码分发。
  • +
  • 下游:RuntimeViewer、MachOKitUI、SymbolViewer 不用改代码;RuntimeViewer 与本库的 Tuist workspace 重新生成后带上新设置,最后一步编一遍确认。上游 p-x9/MachOKit 不提交,合上游 tag 时清单两处会冲突,按 fork 写法解决。
  • +
  • 文档:账本加一节、索引登记;CLAUDE.md 预计不加条目(编译器会当场指出漏写),落地时再判断。
  • +
  • API 演进:没有废弃的 API,不需要 major 跃迁,不单独发版。
  • +
+
+ +
+

落地步骤

+
    +
  1. 提案进集成分支,跨仓库登记。proposalIsListedInBothIndexes、siblingIndexesPointAtTheProposal
  2. +
  3. MachOKit 进 Swift 6 并开三项特性。machOKitTargetsCompileInSwift6Mode、machOKitBuildsWithAllThreeUpcomingFeatures、machOKitTestsPassSkippingAotCachePrintTests、machOKitBuildsWithXcode26_6
  4. +
  5. swift-semantic-string 与 swift-demangling。semanticStringBuildsAndTestsWithUpcomingFeatures、demanglingBuildsAndTestsWithUpcomingFeatures、demanglingLifetimesFeatureStillEnabledInBothTargets、两者 buildsWithXcode26_6
  6. +
  7. MachOKitExtensions(从 origin/main 切)。machOKitExtensionsBuildsAndTestsWithUpcomingFeatures、buildsWithXcode26_6
  8. +
  9. MachOObjCSection。machOObjCSectionBuildsAndTestsWithUpcomingFeatures、buildsWithXcode26_6
  10. +
  11. 本库 Sources:预修、migrate、开关。preFixedSitesCompileUnderMigrationMode、migrateAppliesAllNonTestFixIts、noFileImportingSemanticSpellsBareErrorOrNumeric、allNonTestTargetsBuildWithUpcomingFeatures
  12. +
  13. 本库 Tests:手改剩余警告。allTestTargetsBuildWithUpcomingFeatures、noMigrationWarningRemains
  14. +
  15. 本库全量验证。fullSuitePassesSkippingIntegrationTests、fullSuitePassesWithXcode26_6、renderingABVerificationIsByteIdentical、tuistWorkspaceGeneratesAndBuilds、noCastAlwaysFailsWarning
  16. +
  17. 落地。六个仓库按各自流程合进集成分支,提案取号、改 Implemented,账本加一节。
  18. +
+

构建与测试一律在 Ultra 上跑;第 2–5 步互不依赖,可以并行。收尾时判断要不要配套专题文章(预计不需要)与新术语(预计没有),结论写进决策日志。

+
+ +
+

决策日志

+
+ 2 条,最近一条:Accepted +
+
+ + + + + + +
日期变更说明
2026-11-20Created as Draft用户要求把 MachO 系列库迁到 Swift 6、开启严格并发,并评估开启全部新特性的改动量。实测五个包已是 Swift 6 模式,只有 MachOKit 停在 Swift 5 且切换后零错误;六项 Swift 7 默认特性逐项量过之后,用户选定「MachOKit 切 Swift 6 + ExistentialAny、MemberImportVisibility、InferIsolatedConformances」,另外三项与 StrictMemorySafety 不做
2026-11-20Accepted用户批准,开始实现
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md new file mode 100644 index 00000000..23a072f9 --- /dev/null +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md @@ -0,0 +1,326 @@ +# Draft - MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: 无 +- **跨仓库**: 本提案是 MachOKit(fork)、swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection 与本库共用的唯一提案。MachOKitExtensions 与 MachOObjCSection 的提案索引各加一行 cross-repository 指向这里(落地步骤第 1 步);另外三个仓库没有提案目录,不加。 +- **实现分支 / PR**: 六个仓库都是 `feature/swift6-mode-and-upcoming-features`。MachOKitExtensions 从 `origin/main` 切(它只有 `main`,本地那条没推过的 `next` 不能用),其余五个从各自的 `next` 切。 +- **配套文档**: 待定 —— 落地时判断 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +六个 MachO 系列包里有五个已经在 Swift 6 语言模式下编译,complete strict concurrency checking 早已按错误执行;唯一的例外是 MachOKit(fork),它的清单还是 `swift-tools-version: 5.10`。本提案做两件事:把 MachOKit 升到 tools 6.2,让它也进入 Swift 6 语言模式(实测零错误,Sources 里零并发诊断);然后在六个包的每个 Swift target 上开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` 三项 upcoming feature(编译器把它们标为 Swift 7 默认开启),开关在每份清单末尾用一个循环统一加,不逐个 target 写。源码改动约 900 处,绝大部分是补 `import` 与补 `any`;非测试 target 用 `swift package migrate` 自动改,测试 target 照诊断清单手改,另有 6 处工具处理不了、要先手工改好。同为 Swift 7 默认的 `NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`,以及独立的 `StrictMemorySafety`,量过之后明确不做(见「非目标」)。 + +## 动机 + +**MachOKit 是整条栈里唯一不做 complete concurrency checking 的一层,而它被并发读得最狠。** 上层的读取路径会从多个线程同时读 MachOKit:同一份定义可以被任意多个任务并行打印(提案 0066),交叉引用的整 cache 扫描用 28 个线程(`CrossReferenceAnalysis`),MachOKit 自己的测试里也有 `Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift`。fork 里修过一次懒加载缓存的竞态(MachOKit 0.55.102 一带)。今天 MachOKit 新写的全局可变状态、跨线程传的非 Sendable 值,编译器在 Swift 5 模式下一声不吭;另外五个包同样的写法会直接编不过。实测表明这一层其实已经是 Swift 6 干净的(见前期调研),差的只是清单里的模式声明。 + +**本库清单早就为这几项特性备好了设置,却一直没用上。** `Package.swift:1541` 的 `extension SwiftSetting` 定义了 `existentialAny`、`internalImportsByDefault`、`memberImportVisibility`、`inferIsolatedConformances`、`nonisolatedNonsendingByDefault`、`immutableWeakCaptures` 六个常量,全仓库没有一处引用。 + +**每个文件依赖哪些模块,今天写在源码里的和实际用到的对不上,模块一搬家就暴露。** 不开 `MemberImportVisibility` 时,只要某个模块被同一进程里任何地方加载过,它给已有类型加的 extension 成员在所有文件里都能用,哪怕文件根本没 import 它。实测本库有 480 处这样的用法(Sources 245、Tests 235)。近一年模块搬了三轮(提案 0055 按层分组、0097 拆层、0098 把三层迁出本库),每轮都要在编译失败之后才补 import。更要紧的是,名字解析结果随「碰巧加载了哪些模块」而变:探针里有两处现在就靠这种可见性才解析成今天的意思(`TypeAttributeInferrer.swift:143` 的 `switch` 只在看得见 `SwiftObjCInterop` 时才是完备的,`ABIDiffer.swift:289` 的 `.enum` 只在看得见 `MachOSwiftSection` 时才是枚举 case 而不是别处 extension 加的同名实例成员)。开了这项特性,每个文件的依赖都写在它自己的 import 里。 + +**`any` 关键字项目里已经在用,只是没人强制。** `CLAUDE.md` 要求打印路径把 existential 写成 `any P`(提案 0092),MachOKit 的 target 也早就开了 `ExistentialAny`;本库源码里还有 57 处、测试里 41 处没写 `any` 的 existential。开了之后由编译器统一要求。 + +**`InferIsolatedConformances` 将来会默认开启,现在开的代价最小。** 它决定 global-actor 隔离类型的 conformance 是否自动推断为隔离的。六个包的 Sources 里一处受影响的都没有,只有本库 `Tests/IntegrationTests` 里 33 处(6 个文件)。现在开就是把这 33 处标好,以后不用等到 Swift 7 模式时再回头处理。 + +## 前期调研 + +**方法。** 2026-11-20 在 `JHs-Mac-Studio-Ultra`(Xcode 27.2,Swift 6.4.2)上,把六个包的当前提交(MachOKit `af92491`、MachOKitExtensions `249897b`、MachOObjCSection `4796434`、swift-demangling `815fe91`、swift-semantic-string `f14caa4`、本库 `73c9ccb7`)各自 clone 到 `/Volumes/DerivedData/Agents.noindex/claude/Probes/Swift6Migration/`,以每个包为根各编一次 `swift build --build-tests`,依赖都解析远端版本。新特性用 SE-0486 的迁移模式(`-enable-upcoming-feature <名字>:migrate`)开启,只出带 fix-it 的警告、不挡编译,加 `-print-diagnostic-groups` 按诊断组计数,只统计包根目录下的文件。日志与改过的 clone 都还留在那个目录下。 + +**各包当前的语言模式。** 从 SwiftPM 生成的 PIF 读每个 target 的 `SWIFT_VERSION`:MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string 与本库的 target 都是 `6`(tools-version 6.x 且没声明 `swiftLanguageModes` 时 SwiftPM 默认 Swift 6),MachOKit 的四个 target 是 `5`。不在本次范围内的 FrameworkToolbox 的 `FoundationToolbox` 也是 `5`。 + +**编译器认得哪些特性。** `swiftc -print-supported-features` 列出的 upcoming feature 里,`enabled_in: 7` 的有六个:`ExistentialAny`、`InternalImportsByDefault`、`MemberImportVisibility`、`InferIsolatedConformances`、`NonisolatedNonsendingByDefault`、`ImmutableWeakCaptures`;其中 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`、`NonisolatedNonsendingByDefault` 四个标了 migratable,可以用迁移模式和 `swift package migrate`。另有可选的 `StrictMemorySafety`(`-strict-memory-safety`),不属于任何语言模式。 + +**MachOKit 进 Swift 6 模式。** 两次编译:Swift 5 模式加 `-strict-concurrency=complete`,Sources 零并发诊断,Tests 3 条警告(`DyldCacheConcurrentReadTests.swift` 里 2 条 `SendableClosureCaptures`、1 条 `AddPreconcurrencyImport`);直接 `-swift-version 6`(从构建数据库核实过 MachOKit、MachOArchiveKit、MachOKitReadable、MachOKitTests 四个 target 都拿到了 `-swift-version 6`),全部编过,零错误,只剩同样那 2 条测试警告和 1 条无关的 deprecation 警告。上游 p-x9/MachOKit 的 `main` 同样是 tools 5.10、没开严格并发;fork 比上游多 35 个提交、少 40 个。 + +**三项要开的特性,各包的改动处数(源码 / 测试):** + +| 包 | `ExistentialAny` | `MemberImportVisibility` | `InferIsolatedConformances` | +|---|---|---|---| +| MachOKit | 已开启(0) | 56 / 0(49 个文件) | 0 / 0 | +| MachOKitExtensions | 1 / 2 | 2 / 3 | 0 / 0 | +| MachOObjCSection | 0 / 2 | 15 / 21 | 0 / 0 | +| swift-demangling | 1 / 0 | 0 / 3 | 0 / 0 | +| swift-semantic-string | 6 / 0 | 0 / 0 | 0 / 0 | +| MachOSwiftSection | 57 / 41(73 个文件) | 245 / 235(373 个文件) | 0 / 33(全在 `IntegrationTests`) | + +本库 `MemberImportVisibility` 的 245 处源码里有 189 处在测试基线生成器 `Sources/TestSupport/SwiftSectionFixtureSupport`,真正的库模块只有五十来处。 + +**量过、决定不做的四项(源码 / 测试):** + +| 特性 | 改动处 | 不做的原因 | +|---|---|---| +| `NonisolatedNonsendingByDefault` | 778 / 347,本库占 729 / 234 | 改的是运行语义:每个 nonisolated async 函数改为在调用方的 actor 上执行。RuntimeViewer 从主线程调用库入口时,解析工作会跑到主线程;保留现状要给上千个函数逐个加 `@concurrent` | +| `InternalImportsByDefault` | 4,124 行 import(约 1,400 个文件) | 没有迁移模式,只能手改;约一半必须保持 `public import`;下游可能因失去传递可见性而编不过 | +| `ImmutableWeakCaptures` | 约 0(全仓库只有本库 4 处 `[weak` 捕获) | 收益近乎为零,单独开不值得占一次提交;随将来的 Swift 7 模式一起处理 | +| `StrictMemorySafety` | 2,440 / 658 | 不属于 Swift 6 或 7;这是一个以 unsafe pointer 为本的二进制解析库,几千处 `unsafe` 标注只会是噪音 | + +`InternalImportsByDefault` 的「约一半必须保持 public」是这样量的:在 clone 里把 Sources 的每条 import 改成 `public import`、清单里只给本包 target 开这项特性,再数编译器报的 `UnusedImportAccess`(「public import 没被公开声明用到」)。MachOKit 320 条里 194 条可降为 internal,MachOKitExtensions 232 / 122,MachOObjCSection 320 / 157,swift-demangling 36 / 28,swift-semantic-string 6 / 2,本库 3,210 条里至少 1,513 条(有两个测试支撑文件因探针跳过了 `@testable import` 而没编完)。直接用 `-Xswiftc -enable-upcoming-feature InternalImportsByDefault` 不可行:它会连第三方依赖一起改导入规则,swift-fileio 等先编不过。 + +**`swift package migrate` 的实际表现(在本库 clone 上试跑):** + +- 非测试 target:在 258 个文件里套用了 300 个 fix-it(diff +304 / −57),然后在改清单那一步失败:本库的 target 写成 `extension Target` 上的静态常量,工具找不到 target(`unable to find target named 'Utilities' in package`),所以清单必须手改。退出码是 1,但源码已经改好。 +- 测试 target:一处都不改,显式 `--target <全部测试 target>` 也是 `Applied 0 fix-its`;它构建时不带测试。测试部分只能照 `--build-tests` 的迁移警告手改。 +- 构建一失败就一处都不改。`MemberImportVisibility` 的迁移模式并不只出警告:本库有 4 处直接报错,必须先手工补 import,`migrate` 才跑得起来: + + | 位置 | 报错 | 补什么 | + |---|---|---| + | `Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift:143` | `switch must be exhaustive`(枚举 case 看不见) | `import SwiftObjCInterop` | + | `Sources/Output/SwiftDiffing/ABIDiffer.swift:289` | `instance member 'enum' cannot be used on type 'TypeContextDescriptorWrapper'` | `import MachOSwiftSection` | + | `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift:164` | `.values` 落到了 dynamic member lookup | `import OrderedCollections` | + | `Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift:135` | 同上 | `import OrderedCollections` | + +- **`migrate` 补的 import 会遮蔽标准库的名字。** swift-semantic-string 公开声明了 `struct Error`(`Sources/Semantic/Components/Error.swift:8`)和 `struct Numeric`,与 `Swift.Error`、`Swift.Numeric` 同名;还有 `Argument`,与 ArgumentParser 的同名。文件一旦直接 `import Semantic`,裸写的 `Error` 就解析成 `Semantic.Error`。`migrate` 给本库 6 个文件加了 `import Semantic`,其中两处因此编不过:`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:295` 与 `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:180`(`enum …Error: Error` 被当成以 `Semantic.Error` 为 raw type),改成 `Swift.Error` 就好。危险的是不报错的情形:`catch let error as Error`、`is Error` 这类转型照样能编,只是变成永远失败的转型,编译器只给一条警告。 +- 补完上面 6 处、`migrate` 跑完、清单里手加开关之后,Sources 全部编过;测试 target 从第一个失败的文件开始逐个报缺 import(`TypeNameRetentionTests.swift` 缺 `MachOKit`、`SymbolicationTests.swift` 缺 `MachOKitExtensions`),与警告清单一致。 + +**清单里给 C target 加 `swiftSettings` 是无害的。** `InternalImportsByDefault` 那轮探针在六份清单末尾用同一个循环给所有 target 追加了设置,包括 `MachOKitC`、`MachOSwiftSectionC`、`SwiftSymbolsRegistration` 这些 C target,六个包都照常编过。 + +## 提议方案 + +1. **MachOKit 进 Swift 6 语言模式。** `Package.swift` 第 1 行改成 `// swift-tools-version: 6.2`(与另外五个兄弟包一致)。tools 6.x 不声明 `swiftLanguageModes` 时默认 Swift 6,不必另写。清单末尾的 `extension SwiftSetting` 里那九项 Swift 6 已经默认开启的 upcoming feature(`ForwardTrailingClosures` 到 `GlobalConcurrency`)在 Swift 6 模式下是空操作,删掉;`SwiftSetting.allCases` 的 `CaseIterable` 扩展随之删除,改用下面的统一开关。`AccessLevelOnImport` 实验特性(只在 debug 开)保留不动,实现时如果编译器提示它多余再删。 +2. **六个包的每个 Swift target 统一开启三项特性。** 每份清单在 `let package = Package(...)` 之后加一个循环,给除 `system`、`binary`、`plugin` 以外的所有 target 追加同一组设置;本库沿用 `Package.swift:1541` 已有的常量。test、macro、executable target 都包括在内,`IntegrationTests` 也开(它只编译不运行)。 +3. **源码按三类处理。** 先手工改好「前期调研」里那 6 处(4 处补 import、2 处 `Swift.Error`);再对非测试 target 跑 `swift package migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances`,它在改清单那一步报错是预期的,以它报告的「Applied N fix-its」为准;测试 target 用 `--build-tests` 加三个 `:migrate` 开关构建,照警告逐条手改(补 import、补 `any`、给 `IntegrationTests` 的 conformance 标 `nonisolated`)。最后才加清单里的开关,正式开启后编一遍确认零错误。 +4. **每加一条 `import Semantic`,就检查那个文件里裸写的 `Error`、`Numeric`、`Argument`。** 类型位置一律写成 `Swift.Error` / `Swift.Numeric`;`as Error`、`is Error` 之类的转型与 `catch` 模式逐个看。编译器的「cast always fails」警告按错误对待。 +5. **从下往上落地,不为此单独发版。** 顺序是 MachOKit、swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection、本库。这些设置只影响包自身的编译,不改任何公开 API,下游用的仍是已发布的版本,所以各仓库照各自的流程合进集成分支即可,随下一次正常发版带出去。 + +### 非目标 + +- 不开 `NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`,也不开 `StrictMemorySafety`(原因见「前期调研」的第二张表)。 +- 不动 FrameworkToolbox:它不属于 MachO 系列,`FoundationToolbox` 停在 Swift 5 模式与本提案无关。 +- 不给 swift-semantic-string 的 `Error`、`Numeric`、`Argument` 改名:那是公开 API 的破坏性改动,下游全都要跟着改。本提案只在调用点写全限定名。 +- 不清理现有的 `@unchecked Sendable`(本库 84 处)与 `nonisolated(unsafe)`(本库 37 处):它们大多是锁保护的状态,部署目标 macOS 10.15 用不了 `Mutex`;它们在 Swift 6 模式下本来就合法。 +- 不采用其他 Swift 6 时代的新语言特性(typed throws、`~Copyable`、`Span` 之类),那是逐处设计取舍,不是开关。 +- 不把这些改动提给上游 p-x9/MachOKit:开关与补 import 只为我们自己的检查,按「fork 自用改动不提上游」的约定留在 fork。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| MachOSwiftSection `Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md`、同名 `.html` | 新增 | 本提案与网页版 | 唯一提案 | 1 | +| MachOSwiftSection `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案 | 索引 | 1 | +| MachOKitExtensions、MachOObjCSection `Documentations/Evolutions/README.md` | 修改 | 各加一行 cross-repository 指向本提案 | 跨仓库提案的约定 | 1 | +| MachOKit `Package.swift:1` | 修改 | `swift-tools-version` 5.10 → 6.2 | 进入 Swift 6 语言模式 | 2 | +| MachOKit `Package.swift:76`、`:145–171` · `extension SwiftSetting` | 修改 / 删除 | MachOKit target 不再拼 `SwiftSetting.allCases`;删掉九项 Swift 6 默认特性与 `CaseIterable` 扩展;末尾加统一开关循环 | Swift 6 模式下那九项是空操作;与另外五个包同一写法 | 2 | +| MachOKit `Sources/MachOKit/**`(49 个文件) | 修改 | 补 56 处 import | `MemberImportVisibility` | 2 | +| MachOKit `Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift` | 修改(可选) | 消掉 2 条 `SendableClosureCaptures` 与 1 条 `AddPreconcurrencyImport` 警告 | Swift 6 模式下仍是警告,不挡编译 | 2 | +| swift-semantic-string `Package.swift`(第 94 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | +| swift-semantic-string `Sources/Semantic/Components/AnyComponent.swift`、`Frozen/FrozenSemanticString+Codable.swift`、`SemanticString+Conformances.swift` | 修改 | 补 6 处 `any` | `ExistentialAny` | 3 | +| swift-demangling `Package.swift`(第 171 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | +| swift-demangling `Sources/DemanglingTestingSupport/Required.swift` | 修改 | 补 1 处 `any` | `ExistentialAny` | 3 | +| swift-demangling `Tests/DemanglingTests/DefectRegressionTests.swift`、`NodeTests.swift`、`TransientRemangleParityTests.swift` | 修改 | 补 3 处 import | `MemberImportVisibility` | 3 | +| MachOKitExtensions `Package.swift`(第 390 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 4 | +| MachOKitExtensions `Sources/MachOKitExtensions/RequiredNonOptional.swift`、`String+.swift`,`Sources/MachODependencies/DependencyLoadName.swift` | 修改 | 1 处 `any`、2 处 import | 两项特性 | 4 | +| MachOKitExtensions `Tests/`(5 个文件:`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`CPlusPlusSymbolIndexCensusTests`、`DependencyLoadNameTests`、`SymbolIndexStoreTests`) | 修改 | 2 处 `any`、3 处 import | 两项特性 | 4 | +| MachOObjCSection `Package.swift`(第 421 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 5 | +| MachOObjCSection `Sources/`(`MachOObjCSection` 9、`ObjCCodeReferences` 3、`ObjCMetadataSource`、`ObjCDeclarationRendering`、`ObjCInterface` 各 1) | 修改 | 补 15 处 import | `MemberImportVisibility` | 5 | +| MachOObjCSection `Tests/`(约 19 个文件) | 修改 | 21 处 import、2 处 `any` | 两项特性 | 5 | +| MachOSwiftSection `Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift` | 修改 | 加 `import SwiftObjCInterop` | 迁移模式下第 143 行的 `switch` 报不完备 | 6 | +| MachOSwiftSection `Sources/Output/SwiftDiffing/ABIDiffer.swift` | 修改 | 加 `import MachOSwiftSection` | 迁移模式下第 289 行 `.enum` 解析错 | 6 | +| MachOSwiftSection `Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:295`、`Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:180` | 修改 | `: Error` → `: Swift.Error` | `migrate` 补的 `import Semantic` 让 `Error` 解析成 `Semantic.Error` | 6 | +| MachOSwiftSection `Sources/**`(约 258 个文件,其中 `SwiftSectionFixtureSupport` 约 176 个) | 修改 | `swift package migrate` 的 300 个 fix-it:import 与 `any` | 两项特性 | 6 | +| MachOSwiftSection `Package.swift:1541–1548` 之后、`:1550` 的 Tuist 块之前 | 修改 | 加统一开关循环,用已有的 `.existentialAny`、`.memberImportVisibility`、`.inferIsolatedConformances` | 开启三项特性;放在 Tuist 块之前,Tuist 改写 target 时设置已经在了 | 6 | +| MachOSwiftSection `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift`、`Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift` | 修改 | 加 `import OrderedCollections` | 迁移模式下 `.values` 解析错 | 7 | +| MachOSwiftSection `Tests/**`(约 180 个文件) | 修改 | 手改约 235 处 import、41 处 `any` | 两项特性;`migrate` 不改测试 | 7 | +| MachOSwiftSection `Tests/IntegrationTests/`(`OpaqueTypeTests`、`ObjCAPIEvolutionTests`、`ABIEvolutionTests`、`SwiftDiffableInterfaceBuilderTests`、`SwiftEvolutionInterfaceBuilderTests`、`SwiftInterfaceBuilderTests`) | 修改 | 33 处 conformance 标 `nonisolated` | `InferIsolatedConformances`,保持现有行为 | 7 | +| MachOSwiftSection `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 加一节 | 账本 | 9 | + +## 架构图 + +改了什么:每个包的编译设置。 + +```text +package language mode upcoming features (every Swift target) +----------------------- --------------------- ------------------------------------------------------ +MachOKit (fork) - Swift 5 (tools 5.10) - 9 Swift-6-era features (MachOKit target only) + + Swift 6 (tools 6.2) - ExistentialAny (MachOKit target only) + + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +swift-semantic-string Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +swift-demangling Swift 6 (tools 6.2) Lifetimes (experimental, two targets, kept) + + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +MachOKitExtensions Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +MachOObjCSection Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +MachOSwiftSection Swift 6 (tools 6.3) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances + (statics already declared at Package.swift:1541, now used) +``` + +每份清单里开关的位置: + +```text +Package.swift + let package = Package(name:, platforms:, products:, dependencies:, targets: [...]) ++ let upcomingFeatureSettings: [SwiftSetting] = [ExistentialAny, MemberImportVisibility, InferIsolatedConformances] ++ for target in package.targets where type is not system / binary / plugin { ++ target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings ++ } + // MachOSwiftSection only: Tuist block (TUIST_MAPS_LOCAL_PACKAGE_TESTS) stays after the loop +``` + +迁移流程(每个包相同,本库多一步预修): + +```text +pre-fix sites migrate mode cannot express (MachOSwiftSection: 4 imports + 2 Swift.Error) + -> swift package migrate --to-feature ... (non-test targets; fails at manifest step by design) + -> swift build --build-tests -Xswiftc -enable-upcoming-feature -Xswiftc :migrate + -> fix every remaining warning under Tests/ by hand + -> add the loop to Package.swift + -> swift build --build-tests (features on, zero errors) -> swift test + -> DEVELOPER_DIR=Xcode-26.6 swift build --build-tests (CI toolchain, Swift 6.3) +``` + +## 详细设计 + +**统一开关**(swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection、MachOKit 写在清单末尾): + +```swift +let upcomingFeatureSettings: [SwiftSetting] = [ + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("InferIsolatedConformances"), +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} +``` + +本库写在 `extension SwiftSetting`(`Package.swift:1541`)之后、Tuist 块(`:1550`)之前,用已有常量: + +```swift +let upcomingFeatureSettings: [SwiftSetting] = [ + .existentialAny, + .memberImportVisibility, + .inferIsolatedConformances, +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} +``` + +`static let` 在 `extension SwiftSetting` 里声明、在顶层代码里引用,清单求值顺序没有问题;另外三个未用的常量(`internalImportsByDefault`、`nonisolatedNonsendingByDefault`、`immutableWeakCaptures`)留着,将来开时直接加进数组。 + +**MachOKit 清单**改后的相关部分: + +```swift +// swift-tools-version: 6.2 + +// ... + .target( + name: "MachOKit", + dependencies: [ + // unchanged + ], + swiftSettings: [ + .enableExperimentalFeature("AccessLevelOnImport", .when(configuration: .debug)), + ] + ), +// ... + +let upcomingFeatureSettings: [SwiftSetting] = [ + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("InferIsolatedConformances"), +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} +``` + +原来的 `extension SwiftSetting { static let forwardTrailingClosures … }` 与 `extension SwiftSetting: @retroactive CaseIterable` 整段删除。循环要放在清单里 `let machOKit = package.targets.first(...)` 那段 binary-parse-support 依赖处理之后或之前都可以,它只追加 `swiftSettings`。 + +**迁移命令**(以本库为例,在 Ultra 的功能 worktree 里,`queued-build` 前缀照写): + +```bash +queued-build swift package --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \ + migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances + +queued-build swift build --build-tests \ + --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \ + -Xswiftc -print-diagnostic-groups \ + -Xswiftc -enable-upcoming-feature -Xswiftc ExistentialAny:migrate \ + -Xswiftc -enable-upcoming-feature -Xswiftc MemberImportVisibility:migrate \ + -Xswiftc -enable-upcoming-feature -Xswiftc InferIsolatedConformances:migrate +``` + +第一条退出码是 1 属正常(改清单失败),看输出里的 `Applied N fix-its in M files`。第二条用来列出测试 target 里剩下的警告。日志带 ANSI 颜色与 OSC 8 超链接,按 `[#组名]` 计数前要先去掉转义;同一条诊断会打印两遍(一行摘要、一行带源码框的),按「文件:行:列 + 文字」去重。 + +**手改测试的规则**:`MemberImportVisibility` 的警告形如 `import of module 'X' is required`,在文件的 import 区按字母序补 `import X`(文件里已有 `@testable import X` 或 `@_spi(...) import X` 的,不重复加);`ExistentialAny` 补 `any`;`InferIsolatedConformances` 的警告形如 `conformance of 'T' to 'P' should be marked 'nonisolated'`,照写 `nonisolated P`。补了 `import Semantic` 的文件按「提议方案」第 4 条检查。要是用脚本批量补 import,脚本先给用户看过再跑。 + +## 替代方案考量 + +- **MachOKit 保持 tools 5.10,只加 `.enableUpcomingFeature("StrictConcurrency")`。** Swift 5 模式下这只给 complete checking 的警告,不是错误;以后新代码出问题只是多一条警告,达不到另外五个包的约束力。否。 +- **MachOKit 保持 tools 5.10,靠 `swiftLanguageVersions: [.version("6")]` 进 Swift 6。** 能少改一行,但 `swiftLanguageVersions` 在 tools 6 已废弃改名,与五个兄弟包写法不一致,跟上游同步时第 1 行的冲突也省不掉(上游以后升 tools-version 照样冲突)。否。 +- **逐个 target 写 `swiftSettings:`,或让 `swift package migrate` 改清单。** 本库有 53 个 target,MachOKitExtensions 24 个、MachOObjCSection 19 个,逐个写容易漏,新加的 target 也得记着写;`migrate` 在本库的清单上直接失败。统一循环一处搞定,新 target 自动带上。选循环。 +- **四项全开(再加 `NonisolatedNonsendingByDefault` 与 `InternalImportsByDefault`)。** 2026-11-20 的调研结果摆给用户之后,用户选了只开三项低风险的。理由见「前期调研」第二张表。 +- **只开 `ExistentialAny` 与 `InferIsolatedConformances`,不开 `MemberImportVisibility`。** 后者是三项里改动最大、坑最多的(4 处迁移模式硬错误、`Semantic.Error` 遮蔽),但它正是动机里「每个文件的依赖写在自己的 import 里」的来源,而且坑都已经在探针里找全并给出了改法。保留。 +- **给 swift-semantic-string 的 `Error` 改名,从根上避开遮蔽。** 公开 API 的破坏性改动,下游(本库、RuntimeViewer)都得跟着改,不属于这次的范围。只在调用点写 `Swift.Error`;改名另行考虑。 + +## 影响 + +### 源码兼容性(source compatibility) + +**纯新增**——六个包都不改任何公开声明的签名。`any` 关键字、补的 import、`Swift.Error` 全限定、`nonisolated` conformance 都不改变声明的类型。MachOKit 换语言模式不改变它的公开 API:它的类型的 Sendable 标注早已写好(Swift 5 模式下就在),全局函数与类型没有 global actor 隔离,Swift 6 模式下推断出的隔离与今天相同。 + +upcoming feature 只作用于开启它的 target 本身的编译,不传给依赖它的包:下游即使不开这三项,也照样能用这六个包。 + +### ABI 兼容性(条件项) + +不适用 —— 六个包都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本仓库**:所有 target 都开三项特性,包括 `IntegrationTests`(只编译不运行)、`SwiftSectionMacros`(macro target)、`swift-section` 等 executable target。 +- **RuntimeViewer、MachOKitUI、SymbolViewer**:它们从源码编这六个包,编的时候用的是各包自己的设置,所以不用改任何代码;RuntimeViewer 的 Tuist workspace 重新生成后带上新设置。它们自己的 target 不受影响。 +- **Tuist 开发 workspace**(`./TuistScript.sh`):Tuist 读 `Package.swift` 求值后的结果,循环加的设置会照常映射过去;最后一步编一遍确认。 +- **上游 p-x9/MachOKit**:不提交。fork 的清单第 1 行与 `extension SwiftSetting` 一段与上游不同,以后合上游 tag 时这两处会冲突,按 fork 的写法解决。 + +### 文档与示例 + +- 本库 `Documentations/Internal/ProjectEvolutionLog.md` 加一节;两个提案索引登记本提案;MachOKitExtensions、MachOObjCSection 的索引加 cross-repository 行。 +- `CLAUDE.md` / `AGENTS.md` 不加条目:开了特性之后,漏写 `any` 或漏 import 会被编译器当场指出,agent 不会默默写错。唯一不报错的是 `Semantic.Error` 遮蔽下的转型,但那会有「cast always fails」警告;落地时再判断是否值得在本库 `CLAUDE.md` 加一句。 +- 没有 DocC、README 或示例代码受影响。 + +## API 演进与废弃策略 + +- 没有被替代或废弃的 API。 +- 不需要 semver major 跃迁;各仓库不必为此单独发版,随下一次正常发版带出。 + +## 落地步骤 + +1. **提案进集成分支,跨仓库登记** —— 改动地图第 1–3 行 + - 行为:`proposalIsListedInBothIndexes`、`siblingIndexesPointAtTheProposal` +2. **MachOKit 进 Swift 6 并开三项特性**(fork 的 `.worktrees/MachOKit-Swift6UpcomingFeatures`,从 `next` 切) —— 第 4–7 行 + - 行为:`machOKitTargetsCompileInSwift6Mode`、`machOKitBuildsWithAllThreeUpcomingFeatures`、`machOKitTestsPassSkippingAotCachePrintTests`(已知 5 个环境失败照旧)、`machOKitBuildsWithXcode26_6` +3. **swift-semantic-string 与 swift-demangling 开三项特性** —— 第 8–12 行 + - 行为:`semanticStringBuildsAndTestsWithUpcomingFeatures`、`demanglingBuildsAndTestsWithUpcomingFeatures`、`demanglingLifetimesFeatureStillEnabledInBothTargets`、两者 `buildsWithXcode26_6` +4. **MachOKitExtensions 开三项特性**(从 `origin/main` 切) —— 第 13–15 行 + - 行为:`machOKitExtensionsBuildsAndTestsWithUpcomingFeatures`、`buildsWithXcode26_6` +5. **MachOObjCSection 开三项特性** —— 第 16–18 行 + - 行为:`machOObjCSectionBuildsAndTestsWithUpcomingFeatures`、`buildsWithXcode26_6` +6. **本库 Sources:预修、migrate、开关** —— 第 19–22 行 + - 行为:`preFixedSitesCompileUnderMigrationMode`、`migrateAppliesAllNonTestFixIts`、`noFileImportingSemanticSpellsBareErrorOrNumeric`、`allNonTestTargetsBuildWithUpcomingFeatures` +7. **本库 Tests:手改剩余警告** —— 第 23–25 行 + - 行为:`allTestTargetsBuildWithUpcomingFeatures`(含 `IntegrationTests`)、`noMigrationWarningRemains` +8. **本库全量验证** —— 不改代码 + - 行为:`fullSuitePassesSkippingIntegrationTests`、`fullSuitePassesWithXcode26_6`、`renderingABVerificationIsByteIdentical`(`SystemFrameworkRenderingVerification.md` 的三条腿,对照组为 `next`;补 import 只改名字解析,A/B 用来兜住遮蔽一类不报错的变化)、`tuistWorkspaceGeneratesAndBuilds`、`noCastAlwaysFailsWarning` +9. **落地** —— 第 26 行 + - 行为:六个仓库按各自流程合进集成分支(MachOKitExtensions 推 `main`),本提案取号、状态改 Implemented,账本加一节 + +构建与测试一律远程在 Ultra 上跑(公司那台不编这些工程),产物目录用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/<包名>`;第 2–5 步的仓库互不依赖,可以并行。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:没有新的调用方契约;「迁移模式的四类坑」已在本提案里写全。落地时再确认。 +- **有没有引入新术语** —— 预计没有。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户要求把 MachO 系列库迁到 Swift 6、开启严格并发,并评估开启全部新特性的改动量。实测发现五个包已是 Swift 6 模式,只有 MachOKit 停在 Swift 5 且切换后零错误;Swift 7 默认的六项特性逐项量过之后,用户选定「MachOKit 切 Swift 6 + `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`」,另外三项与 `StrictMemorySafety` 不做 | +| 2026-11-20 | Accepted | 用户批准,开始实现 | diff --git a/Documentations/README.md b/Documentations/README.md index b371e22e..5f319fa4 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -218,6 +218,7 @@ selects names using each access's offset and width. | [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | | [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | | [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | +| [Evolutions/draft-swift6-mode-and-upcoming-features.md](Evolutions/draft-swift6-mode-and-upcoming-features.md) | **提案 draft(Accepted)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.2 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [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) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | From 63ef0b37670b4c36b882a34f64db2e13b231dee9 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:27:06 +0800 Subject: [PATCH 018/175] fix: import the modules three lookups rely on and spell Swift.Error where Semantic is imported MemberImportVisibility makes a member visible only through a direct import. Three lookups compile today only because the defining module is loaded elsewhere: TypeAttributeInferrer's switch over a SwiftObjCInterop enum, ABIDiffer's .enum case of a MachOSwiftSection type, and two tests' .values of an OrderedDictionary. Two SwiftSectionKit errors spell Swift.Error, since the import of Semantic the migration adds would otherwise bind Error to Semantic.Error. Proposal swift6-mode-and-upcoming-features moves to In Progress. --- Documentations/Evolutions/README.md | 2 +- .../Evolutions/draft-swift6-mode-and-upcoming-features.html | 2 +- .../Evolutions/draft-swift6-mode-and-upcoming-features.md | 2 +- Documentations/README.md | 2 +- Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift | 2 +- .../Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift | 2 +- .../SwiftAttributeInference/TypeAttributeInferrer.swift | 1 + Sources/Output/SwiftDiffing/ABIDiffer.swift | 1 + Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift | 1 + .../ExtensionContainerUnificationTests.swift | 1 + 10 files changed, 10 insertions(+), 6 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index bbda5f56..fef80bcb 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -114,4 +114,4 @@ | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | | [cross-repository MachOKitExtensions 0004](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md) | 符号语言的判断归各自的包:由那边维护唯一提案;本库在 `SwiftSymbols` 定义 `SymbolLanguage.swift` 与 Swift 名字的判断,新 C target `SwiftSymbolsRegistration` 在镜像加载时注册;MachOKitExtensions 下限抬到 3.0.0 | Implemented | | [0099](0099-tuist-workspace.md) | Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 | Implemented | -| draft | [MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature](draft-swift6-mode-and-upcoming-features.md):MachOKit 切 Swift 6,六个包开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`(跨仓库唯一提案) | Accepted | +| draft | [MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature](draft-swift6-mode-and-upcoming-features.md):MachOKit 切 Swift 6,六个包开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`(跨仓库唯一提案) | In Progress | diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html index 1cabcda7..6da1810d 100644 --- a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html @@ -163,7 +163,7 @@

MachOSwiftSectionEvolutionsDraft

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

-
状态
Accepted
+
状态
In Progress
最后更新
2026-11-20
项目类型
库(源码分发)
原文
draft-swift6-mode-and-upcoming-features.md
diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md index 23a072f9..6682d04b 100644 --- a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md @@ -1,6 +1,6 @@ # Draft - MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-20 - **最后更新**: 2026-11-20 diff --git a/Documentations/README.md b/Documentations/README.md index 5f319fa4..8c7db79f 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -218,7 +218,7 @@ selects names using each access's offset and width. | [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | | [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | | [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | -| [Evolutions/draft-swift6-mode-and-upcoming-features.md](Evolutions/draft-swift6-mode-and-upcoming-features.md) | **提案 draft(Accepted)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.2 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | +| [Evolutions/draft-swift6-mode-and-upcoming-features.md](Evolutions/draft-swift6-mode-and-upcoming-features.md) | **提案 draft(In Progress)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.2 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [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) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift index a2046d3d..98368d92 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift @@ -290,7 +290,7 @@ public struct ObjCAPIEvolutionRequest: Sendable, Equatable { /// found no one platform to spell the availability macros for. Naming the /// platform with ``ObjCAPIEvolutionRequest/AvailabilityAttributes/platform(_:)`` /// avoids both. -public enum ObjCAvailabilityPlatformInferenceError: Error, LocalizedError, Sendable, Equatable { +public enum ObjCAvailabilityPlatformInferenceError: Swift.Error, LocalizedError, Sendable, Equatable { /// The binary at `path` has no `LC_BUILD_VERSION`, or names a platform /// the availability macros have no name for, such as bridgeOS. case noPlatform(path: String) diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift index d940fa74..1d24a7d7 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift @@ -176,7 +176,7 @@ public struct ABIEvolutionRequest: Sendable, Equatable { /// Why ``ABIEvolutionRequest/AvailabilityAttributes/inferredPlatform`` found /// no one platform to spell the attributes for. Naming the platform with /// ``ABIEvolutionRequest/AvailabilityAttributes/platform(_:)`` avoids both. -public enum AvailabilityPlatformInferenceError: Error, LocalizedError, Sendable, Equatable { +public enum AvailabilityPlatformInferenceError: Swift.Error, LocalizedError, Sendable, Equatable { /// The binary at `path` has no `LC_BUILD_VERSION`, or names a platform /// `@available` has no spelling for, such as DriverKit. case noPlatform(path: String) diff --git a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift index 39488eea..c0daa65d 100644 --- a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift +++ b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift @@ -1,6 +1,7 @@ import SwiftDeclaration import MachOSwiftSection import Demangling +import SwiftObjCInterop /// Infers type-level Swift attributes by analyzing a `TypeDefinition`'s members and metadata flags. /// diff --git a/Sources/Output/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift index af46ccc5..7d3f876d 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffer.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffer.swift @@ -1,4 +1,5 @@ import Demangling +import MachOSwiftSection import OrderedCollections import SwiftDeclaration diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index e458c4c5..62566069 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -6,6 +6,7 @@ import Foundation import Testing import MachOKit import Dependencies +import OrderedCollections @_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface diff --git a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift index be52598a..a9588074 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift @@ -4,6 +4,7 @@ import Foundation import Testing import MachOKit +import OrderedCollections @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport From 0390b1bc8419256836bf4a1738d1e81d1b24404c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:40:10 +0800 Subject: [PATCH 019/175] refactor: apply the migration fix-its for ExistentialAny, MemberImportVisibility and InferIsolatedConformances Generated by swift package --build-system native migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances. An import the fix-it wrote as internal is a plain import unless this package already imports that module internally, so no module is imported at two access levels. --- .../Extensions/String+.swift | 1 + .../Models/Metadata/MetadataProtocol.swift | 2 ++ .../Models/Metadata/MetadataWrapper.swift | 1 + .../Protocols/TopLevelDescriptor.swift | 1 + .../CrossReferenceAnalyzer.swift | 1 + .../RuntimeMetadataTypeBuilder.swift | 2 +- .../SwiftInspection/SymbolicDemangler.swift | 6 ++--- .../ClassBoundGenericParameterAnalysis.swift | 1 + .../StaticTypeLayoutResolver.swift | 1 + .../ClassHierarchyDumper.swift | 1 + .../ObjCMembers/ObjCMembers.swift | 1 + .../ObjCMethodThunkReferences.swift | 2 ++ .../ObjC/ObjCAPIRequests.swift | 2 ++ .../Swift/ABIDiffRequest.swift | 1 + .../Swift/ABIEvolutionRequest.swift | 1 + .../Swift/InterfaceRequest.swift | 1 + .../Events/SwiftIndexEvents.swift | 6 ++--- .../DemanglingNode+StoredVariable.swift | 1 + .../FieldRecord+DemangledType.swift | 1 + .../Building/MemberSymbolBucketing.swift | 1 + .../Indexing/Building/ObjCMemberMatcher.swift | 1 + .../Building/StandInMemberSymbolBuilder.swift | 1 + .../ExtensionDefinition+Indexing.swift | 1 + .../TypeDefinition+ClassDispatch.swift | 1 + .../TypeDefinition+Indexing.swift | 1 + .../Model/Members/OrderedMember.swift | 1 + .../Members/ResolvedObjCMemberFacts.swift | 1 + ...ationIndexer+ObjCImportedDefinitions.swift | 1 + .../SwiftDeclarationIndexer.swift | 2 +- .../PrivateDiscriminatorSourceFileIndex.swift | 1 + .../ConformanceProvider.swift | 2 ++ ...ericSpecializer+StaticSpecialization.swift | 6 ++--- .../GenericSpecializer.swift | 9 ++++--- .../TypeDefinition+Specialization.swift | 2 +- .../TypeIndexing/SourceKitManager.swift | 2 +- .../TypeIndexing/TypeDatabase.swift | 1 + .../reader-benchmark/ReaderBenchmark.swift | 1 + .../Commands/InterfaceCommand.swift | 1 + .../Commands/TransformerCommand.swift | 1 + .../Models/DemangleOptionGroup.swift | 1 + .../ConditionalWitnessComment.swift | 1 + .../Extensions/GenericContext+Dump.swift | 1 + .../GenericRequirement+Inherited.swift | 1 + .../Extensions/OpaqueType+.swift | 1 + .../OpaqueReferenceSpelling.swift | 1 + .../StaticFieldLayoutBackend.swift | 1 + Sources/Output/SwiftDiffing/ABIDiffer.swift | 1 + Sources/Output/SwiftDiffing/ABIKey.swift | 1 + .../Dumper/ObjCMemberRendering.swift | 1 + .../AnySwiftEvolutionInterfaceBuilder.swift | 10 ++++---- .../InterfaceVersionRendering.swift | 4 +-- ...wiftDeclarationPrinter+DiffRendering.swift | 1 + .../SwiftDiffableInterfaceBuilder.swift | 3 ++- .../SwiftEvolutionInterfaceBuilder.swift | 2 +- .../SwiftInterfaceBuilder.swift | 6 ++--- .../SwiftInterfaceBuilderDependencies.swift | 4 +-- ...ftInterfaceBuilderOpaqueTypeProvider.swift | 1 + .../NodePrintables/NodePrintable.swift | 2 +- .../NodePrintables/TypeNodePrintable.swift | 1 + .../ProtocolRequirementPartition.swift | 1 + .../SwiftDeclarationPrinter+Headers.swift | 1 + ...ationPrinter+RawLayoutBuiltinStorage.swift | 1 + .../SwiftDeclarationPrinter.swift | 4 +-- .../SwiftSectionMacros/MachOMacroPlugin.swift | 2 +- Sources/Support/Utilities/StringBuilder.swift | 8 +++--- .../Symbols/SwiftSymbols/MachO+Symbol.swift | 1 + .../Baseline/BaselineGenerator.swift | 1 + ...sibleFunctionRecordBaselineGenerator.swift | 2 ++ .../AnonymousContextBaselineGenerator.swift | 1 + ...usContextDescriptorBaselineGenerator.swift | 1 + ...textDescriptorFlagsBaselineGenerator.swift | 1 + ...tDescriptorProtocolBaselineGenerator.swift | 1 + .../AssociatedTypeBaselineGenerator.swift | 1 + ...iatedTypeDescriptorBaselineGenerator.swift | 1 + ...ssociatedTypeRecordBaselineGenerator.swift | 1 + .../BuiltinTypeBaselineGenerator.swift | 1 + ...iltinTypeDescriptorBaselineGenerator.swift | 1 + .../CaptureDescriptorBaselineGenerator.swift | 2 ++ .../CaptureTypeRecordBaselineGenerator.swift | 1 + ...etadataSourceRecordBaselineGenerator.swift | 1 + .../AnyClassMetadataBaselineGenerator.swift | 1 + ...MetadataObjCInteropBaselineGenerator.swift | 1 + ...ObjCInteropProtocolBaselineGenerator.swift | 1 + ...assMetadataProtocolBaselineGenerator.swift | 1 + .../Class/ClassBaselineGenerator.swift | 1 + .../ClassDescriptorBaselineGenerator.swift | 1 + .../Class/ClassFlagsBaselineGenerator.swift | 1 + .../ClassMetadataBaselineGenerator.swift | 1 + ...ClassMetadataBoundsBaselineGenerator.swift | 1 + ...adataBoundsProtocolBaselineGenerator.swift | 1 + ...MetadataObjCInteropBaselineGenerator.swift | 1 + ...lassDescriptorFlagsBaselineGenerator.swift | 1 + ...assMetadataProtocolBaselineGenerator.swift | 1 + ...tOverrideDescriptorBaselineGenerator.swift | 1 + ...OverrideTableHeaderBaselineGenerator.swift | 1 + .../MethodDescriptorBaselineGenerator.swift | 1 + ...thodDescriptorFlagsBaselineGenerator.swift | 1 + ...ethodDescriptorKindBaselineGenerator.swift | 1 + ...dOverrideDescriptorBaselineGenerator.swift | 1 + ...lassWrapperMetadataBaselineGenerator.swift | 1 + ...ilientClassStubInfoBaselineGenerator.swift | 1 + ...OverrideTableHeaderBaselineGenerator.swift | 1 + ...ResilientSuperclassBaselineGenerator.swift | 1 + ...ClassMetadataBoundsBaselineGenerator.swift | 1 + ...bleDescriptorHeaderBaselineGenerator.swift | 1 + .../ContextDescriptorBaselineGenerator.swift | 1 + ...textDescriptorFlagsBaselineGenerator.swift | 1 + ...ntextDescriptorKindBaselineGenerator.swift | 1 + ...orKindSpecificFlagsBaselineGenerator.swift | 1 + ...tDescriptorProtocolBaselineGenerator.swift | 1 + ...xtDescriptorWrapperBaselineGenerator.swift | 1 + .../ContextProtocolBaselineGenerator.swift | 1 + .../ContextWrapperBaselineGenerator.swift | 1 + ...spatchClassMetadataBaselineGenerator.swift | 1 + .../Enum/EnumBaselineGenerator.swift | 1 + .../EnumDescriptorBaselineGenerator.swift | 1 + .../Enum/EnumFunctionsBaselineGenerator.swift | 1 + .../Enum/EnumMetadataBaselineGenerator.swift | 1 + ...numMetadataProtocolBaselineGenerator.swift | 1 + ...yloadEnumDescriptorBaselineGenerator.swift | 1 + ...ialMetatypeMetadataBaselineGenerator.swift | 1 + ...xistentialTypeFlagsBaselineGenerator.swift | 1 + ...tentialTypeMetadataBaselineGenerator.swift | 1 + ...tentialTypeMetadataBaselineGenerator.swift | 1 + ...xistentialTypeShapeBaselineGenerator.swift | 1 + ...ntialTypeShapeFlagsBaselineGenerator.swift | 1 + ...xistentialTypeShapeBaselineGenerator.swift | 1 + .../ExtensionContextBaselineGenerator.swift | 1 + ...onContextDescriptorBaselineGenerator.swift | 1 + ...tDescriptorProtocolBaselineGenerator.swift | 1 + .../FieldDescriptorBaselineGenerator.swift | 1 + .../FieldRecordBaselineGenerator.swift | 1 + .../FieldRecordFlagsBaselineGenerator.swift | 1 + ...oreignClassMetadataBaselineGenerator.swift | 1 + ...ferenceTypeMetadataBaselineGenerator.swift | 1 + .../FunctionTypeFlagsBaselineGenerator.swift | 1 + ...unctionTypeMetadataBaselineGenerator.swift | 2 ++ ...syncFunctionPointerBaselineGenerator.swift | 2 ++ .../GenericContextBaselineGenerator.swift | 1 + ...textDescriptorFlagsBaselineGenerator.swift | 1 + ...extDescriptorHeaderBaselineGenerator.swift | 2 ++ .../GenericEnvironmentBaselineGenerator.swift | 1 + ...ricEnvironmentFlagsBaselineGenerator.swift | 1 + ...PackShapeDescriptorBaselineGenerator.swift | 1 + ...ericPackShapeHeaderBaselineGenerator.swift | 1 + ...ericParamDescriptorBaselineGenerator.swift | 1 + .../GenericRequirementBaselineGenerator.swift | 1 + ...cRequirementContentBaselineGenerator.swift | 1 + ...quirementDescriptorBaselineGenerator.swift | 1 + ...ricRequirementFlagsBaselineGenerator.swift | 1 + ...ericValueDescriptorBaselineGenerator.swift | 1 + .../GenericValueHeaderBaselineGenerator.swift | 1 + ...GenericWitnessTableBaselineGenerator.swift | 1 + ...lassMetadataPatternBaselineGenerator.swift | 2 ++ ...adataPartialPatternBaselineGenerator.swift | 2 ++ ...dataPatternProtocolBaselineGenerator.swift | 2 ++ ...alueMetadataPatternBaselineGenerator.swift | 2 ++ ...lassMetadataPatternBaselineGenerator.swift | 2 ++ ...extDescriptorHeaderBaselineGenerator.swift | 1 + ...ericBoxHeapMetadataBaselineGenerator.swift | 1 + ...calVariableMetadataBaselineGenerator.swift | 1 + ...PathComponentHeaderBaselineGenerator.swift | 1 + ...omputedPropertyBodyBaselineGenerator.swift | 1 + ...thStoredFieldOffsetBaselineGenerator.swift | 1 + .../PropertyDescriptorBaselineGenerator.swift | 1 + .../MangledNameBaselineGenerator.swift | 1 + .../BorrowTypeMetadataBaselineGenerator.swift | 1 + ...aAccessorsListEntryBaselineGenerator.swift | 1 + ...tasCachingOnceTokenBaselineGenerator.swift | 1 + ...dMetadatasListCountBaselineGenerator.swift | 1 + ...dMetadatasListEntryBaselineGenerator.swift | 1 + ...edArrayTypeMetadataBaselineGenerator.swift | 1 + .../FullMetadataBaselineGenerator.swift | 1 + .../HeapMetadataHeaderBaselineGenerator.swift | 1 + ...etadataHeaderPrefixBaselineGenerator.swift | 1 + ...eMetadataHeaderBaseBaselineGenerator.swift | 1 + .../TypeMetadataHeaderBaselineGenerator.swift | 1 + ...etadataLayoutPrefixBaselineGenerator.swift | 1 + ...ataAccessorFunctionBaselineGenerator.swift | 1 + .../Metadata/MetadataBaselineGenerator.swift | 1 + .../MetadataBoundsBaselineGenerator.swift | 1 + ...adataBoundsProtocolBaselineGenerator.swift | 1 + ...adataInitializationBaselineGenerator.swift | 1 + ...adataInitializationBaselineGenerator.swift | 1 + .../MetadataProtocolBaselineGenerator.swift | 1 + .../MetadataRequestBaselineGenerator.swift | 1 + .../MetadataResponseBaselineGenerator.swift | 1 + .../MetadataWrapperBaselineGenerator.swift | 1 + .../MetatypeMetadataBaselineGenerator.swift | 1 + ...etonMetadataPointerBaselineGenerator.swift | 1 + .../ModuleContextBaselineGenerator.swift | 1 + ...leContextDescriptorBaselineGenerator.swift | 1 + ...tDescriptorProtocolBaselineGenerator.swift | 1 + .../OpaqueMetadataBaselineGenerator.swift | 1 + .../OpaqueTypeBaselineGenerator.swift | 1 + ...paqueTypeDescriptorBaselineGenerator.swift | 1 + ...eDescriptorProtocolBaselineGenerator.swift | 1 + ...vertibleProtocolSetBaselineGenerator.swift | 1 + ...olsRequirementCountBaselineGenerator.swift | 1 + .../ObjCProtocolPrefixBaselineGenerator.swift | 1 + ...eObjCProtocolPrefixBaselineGenerator.swift | 1 + ...ocolBaseRequirementBaselineGenerator.swift | 1 + .../Protocol/ProtocolBaselineGenerator.swift | 1 + ...textDescriptorFlagsBaselineGenerator.swift | 1 + .../ProtocolDescriptorBaselineGenerator.swift | 1 + ...ocolDescriptorFlagsBaselineGenerator.swift | 1 + ...otocolDescriptorRefBaselineGenerator.swift | 1 + .../ProtocolRecordBaselineGenerator.swift | 1 + ...ProtocolRequirementBaselineGenerator.swift | 1 + ...colRequirementFlagsBaselineGenerator.swift | 1 + ...ocolRequirementKindBaselineGenerator.swift | 1 + ...rotocolWitnessTableBaselineGenerator.swift | 1 + .../ResilientWitnessBaselineGenerator.swift | 1 + ...ientWitnessesHeaderBaselineGenerator.swift | 1 + ...lobalActorReferenceBaselineGenerator.swift | 1 + ...ProtocolConformanceBaselineGenerator.swift | 1 + ...nformanceDescriptorBaselineGenerator.swift | 1 + ...colConformanceFlagsBaselineGenerator.swift | 1 + .../Generators/StructBaselineGenerator.swift | 1 + .../StructDescriptorBaselineGenerator.swift | 1 + .../StructMetadataBaselineGenerator.swift | 1 + ...uctMetadataProtocolBaselineGenerator.swift | 1 + .../TupleTypeMetadataBaselineGenerator.swift | 1 + ...TypeMetadataElementBaselineGenerator.swift | 1 + ...peContextDescriptorBaselineGenerator.swift | 1 + ...textDescriptorFlagsBaselineGenerator.swift | 1 + ...tDescriptorProtocolBaselineGenerator.swift | 1 + ...xtDescriptorWrapperBaselineGenerator.swift | 1 + .../TypeContextWrapperBaselineGenerator.swift | 1 + .../TypeMetadataRecordBaselineGenerator.swift | 1 + .../Type/TypeReferenceBaselineGenerator.swift | 1 + .../Type/ValueMetadataBaselineGenerator.swift | 1 + ...lueMetadataProtocolBaselineGenerator.swift | 1 + ...peDescriptorWrapperBaselineGenerator.swift | 1 + .../TypeLayoutBaselineGenerator.swift | 1 + .../ValueWitnessFlagsBaselineGenerator.swift | 1 + .../ValueWitnessTableBaselineGenerator.swift | 1 + .../DemangleOptions.swift | 1 + .../DumpableTests.swift | 2 ++ .../Extensions.swift | 1 + .../SnapshotDumpableTests.swift | 1 + .../SnapshotInterfaceTests.swift | 3 +++ .../ClassesWithoutClassObjectsFixture.swift | 2 +- .../ExistentialAnyFixture.swift | 2 +- .../ExportedOnlyFixture.swift | 2 +- .../ExtensionContextExportFixture.swift | 2 +- .../GenericSpecializationFixture.swift | 2 +- ...GenericSpecializationFixtureIndexers.swift | 1 + .../ImageGroupFixture.swift | 2 +- .../InitAccessorFixture.swift | 4 +-- .../LocalTypeFixture.swift | 2 +- .../ModuleSelectorFixture.swift | 2 +- .../ObjCImplementationFixture.swift | 2 +- .../ObservableMacroFixture.swift | 4 +-- .../RenamedObjCClassFixture.swift | 2 +- .../Swift64DeclarationShapesFixture.swift | 2 +- .../SwiftDeclaredObjCProtocolsFixture.swift | 2 +- .../ThunkOnlyMemberFixture.swift | 2 +- .../UnobservablePresenceFixture.swift | 2 +- .../SymbolicationTests.swift | 1 + .../TypeNameRetentionTests.swift | 1 + .../DyldCacheAssociatedTypeTests.swift | 3 +++ .../MetadataAccessorTests.swift | 1 + .../MachOSwiftSection/OpaqueTypeTests.swift | 7 +++--- .../ProtocolGenericContextTests.swift | 3 +++ .../ProtocolRequirementSignatureTests.swift | 1 + .../MachOSymbols/ExternalSymbolTests.swift | 3 +++ .../SymbolIndexStoreBaselineTests.swift | 1 + .../ObjCDiffing/ObjCAPIEvolutionTests.swift | 25 ++++++++++--------- .../SwiftDiffing/ABIEvolutionTests.swift | 8 +++--- .../RenderingVerificationTests.swift | 2 ++ .../SwiftDiffableInterfaceBuilderTests.swift | 11 ++++---- .../SwiftEvolutionInterfaceBuilderTests.swift | 11 ++++---- .../SwiftInterfaceBuilderTests.swift | 9 ++++--- .../SwiftInterfaceIndexerTests.swift | 1 + .../SwiftInterfaceTestSupport.swift | 2 ++ .../TypeIndexing/TypeNameProviderTests.swift | 4 +++ .../AccessibleFunctionRecordTests.swift | 1 + .../CoroFunctionPointerTests.swift | 2 +- .../GenericClassMetadataPatternTests.swift | 1 + .../HeapMetadataHeaderPrefixTests.swift | 1 + .../Headers/HeapMetadataHeaderTests.swift | 1 + .../StoredClassMetadataBoundsTests.swift | 1 + .../Enum/Metadata/EnumMetadataTests.swift | 1 + .../Type/Struct/StructMetadataTests.swift | 1 + ...outRendererReaderSpecializationTests.swift | 1 + .../NestedFieldOffsetMemoizationTests.swift | 1 + .../OpaqueTypeArgumentDepthTests.swift | 2 +- .../OpaqueTypeOrdinalTests.swift | 2 +- ...rsiveNestedFieldOffsetExpansionTests.swift | 1 + .../RuntimeEnumLayoutRenderingTests.swift | 1 + .../CustomObjCClassNameDumpTests.swift | 2 ++ .../ExistentialAnyDumpTests.swift | 3 +++ .../ExportStatusDumpAnnotationTests.swift | 1 + .../GenericParameterDepthDumpTests.swift | 3 +++ .../InitAccessorDumpTests.swift | 3 +++ Tests/SwiftDumpTests/LocalTypeDumpTests.swift | 3 +++ .../ModuleSelectorDumpTests.swift | 3 +++ .../ObjCImplementationClassDumpTests.swift | 2 ++ .../SwiftDumpTests/ObjCMemberDumpTests.swift | 2 ++ .../ObservableMacroDumpTests.swift | 3 +++ .../OpaqueWitnessDumpAnnotationTests.swift | 4 ++- .../PrivateTypeMemberAttributionTests.swift | 2 ++ ...colRequirementRightHandSideDumpTests.swift | 3 +++ .../Swift64DeclarationShapeDumpTests.swift | 3 +++ .../SwiftDeclaredObjCProtocolDumpTests.swift | 2 ++ .../ThunkOnlyObjCMemberDumpTests.swift | 2 ++ .../VTableSlotAttributionTests.swift | 4 ++- .../CImportedExtensionKindTests.swift | 3 ++- .../InitAccessorIndexingTests.swift | 2 ++ .../LocalTypeDisplayNameTests.swift | 1 + .../ObjCProtocolDefinitionIndexingTests.swift | 1 + ...bservableMacroExpansionRecoveryTests.swift | 2 ++ .../ObservableMacroRecognitionTests.swift | 1 + .../PrivateDeclarationsWholeTreeTests.swift | 1 + .../SymbolTestsCoreIntegrationTests.swift | 1 + .../WrappedPropertyRecoveryTests.swift | 3 ++- .../CImportedTypeIdentityTests.swift | 2 +- .../DyldCacheTwinImageTests.swift | 1 + .../EnumLayoutVerificationTests.swift | 1 + .../MalformedSymbolValueTests.swift | 4 ++- ...icDemanglerFixedShapeExtractionTests.swift | 2 +- .../BoundedConcurrentMapTests.swift | 1 + ...mportedTypeConformanceInterfaceTests.swift | 3 ++- ...sesWithoutClassObjectsInterfaceTests.swift | 3 +++ .../CommentStructureContractTests.swift | 1 + .../CommentStructureShapeTests.swift | 1 + ...ditionalWitnessCommentStructureTests.swift | 2 +- ...onformanceProtocolNameSemanticsTests.swift | 1 + .../CrossImageOpaqueReferenceTests.swift | 3 ++- .../CustomObjCClassNameInterfaceTests.swift | 4 +++ .../DescriptorOnlyVTableMemberTests.swift | 4 ++- .../SwiftInterfaceTests/DiffFormatTests.swift | 1 + .../DiffMemberIndentationTests.swift | 2 +- .../DiffRendererHeaderFailureTests.swift | 4 ++- .../ExecutableImageSymbolOffsetTests.swift | 4 ++- .../ExistentialAnyInterfaceTests.swift | 1 + .../ExportStatusAnnotationTests.swift | 2 ++ .../ExportStatusTests.swift | 4 +++ .../ExportedOnlyInterfaceTests.swift | 2 ++ ...rtedOnlyLibraryEvolutionFixtureTests.swift | 1 + .../ExtensionContainerUnificationTests.swift | 2 ++ .../ExtensionContextExportStatusTests.swift | 6 +++++ .../ExtensionContextTypeNameTests.swift | 3 ++- .../FinalKeywordICFRegressionTests.swift | 1 + .../FinalMemberRecoveryTests.swift | 3 +++ .../GenericParameterDepthNamingTests.swift | 1 + .../ImageGroupEvolutionTests.swift | 1 + .../InitAccessorInterfaceTests.swift | 1 + .../InterfaceHeaderTests.swift | 1 + .../LegacyDyldInfoBindTests.swift | 3 ++- .../LocalTypeInterfaceTests.swift | 1 + .../MembersOfAnotherImagesTypeTests.swift | 1 + .../ModuleSelectorInterfaceTests.swift | 1 + .../NestedDefinitionRegionContractTests.swift | 1 + ...CImplementationClassRecognitionTests.swift | 2 ++ .../ObjCMemberRecoveryTests.swift | 5 ++++ .../ObservableMacroInterfaceTests.swift | 1 + .../OpaqueAttributionImageE2ETests.swift | 3 +++ .../OpaqueConstraintRenderingTests.swift | 3 ++- .../OpaqueParameterDepthTests.swift | 3 ++- ...eParameterInMultiDepthExtensionTests.swift | 3 ++- ...meterWithoutProtocolRequirementTests.swift | 3 ++- .../PrintFailureEventTests.swift | 2 ++ .../ProjectedOpaqueMemberWitnessTests.swift | 3 ++- ...ropertyWrapperSynthesizedMemberTests.swift | 3 ++- ...otocolInExtensionDefaultWitnessTests.swift | 3 ++- .../ProtocolInExtensionTests.swift | 3 ++- ...olRequirementPlacementInterfaceTests.swift | 4 +++ .../RawLayoutAttributeRenderingTests.swift | 1 + ...ayoutBuiltinDescriptorRenderingTests.swift | 3 ++- ...trippedWrappedPropertyRenderingTests.swift | 3 ++- ...ftDeclaredObjCProtocolInterfaceTests.swift | 2 ++ .../SwiftEvolutionInterfaceBuilderTests.swift | 2 +- .../SymbolTableRetentionTests.swift | 2 ++ .../SymbolTestsCoreE2ETests.swift | 1 + .../ThunkOnlyObjCMemberTests.swift | 2 ++ .../UnobservablePresenceTests.swift | 1 + .../VisibilityRegionProjectionTests.swift | 1 + .../WrappedReaderInterfaceTests.swift | 1 + .../NestedFieldExtentTests.swift | 1 + .../NestedFieldOffsetOpaqueWitnessTests.swift | 2 +- ...awLayoutBuiltinDescriptorLayoutTests.swift | 2 +- .../SameTypePinnedParameterLayoutTests.swift | 1 + .../ConcurrentDefinitionPrintingTests.swift | 1 + .../EnumCaseRenderingParityTests.swift | 2 ++ .../InitializerFailabilityPrintingTests.swift | 1 + .../NodeKindParityTests.swift | 2 ++ .../SwiftPrintingTests/NodePrinterTests.swift | 1 + .../PackExpansionRenderingTests.swift | 1 + .../RecordingPrinterTargetTests.swift | 1 + ...ateDiscriminatorSourceFileIndexTests.swift | 2 ++ ...criminatorSourceFileSystemImageTests.swift | 2 ++ .../CommandLineErrorTranslationTests.swift | 4 +-- .../CommandRequestMappingTests.swift | 3 +++ .../ObjC/ObjCAPICommandParsingTests.swift | 1 + .../ObjC/ObjCSectionCommandTests.swift | 1 + .../TransformerOptionGroupTests.swift | 1 + .../DumpAndInterfaceRequestTests.swift | 2 ++ .../MachOSourceTests.swift | 1 + .../Support/DeclarationRecordingOutput.swift | 1 + .../Support/RecordingOutput.swift | 1 + .../ClassHierarchyBuildStackTests.swift | 1 + .../GenericSpecializationTests.swift | 2 ++ .../GenericTypeNameSubstitutionTests.swift | 1 + .../OfflineObjectiveCBaseClassTests.swift | 4 ++- ...eProjectionDependencyResolutionTests.swift | 5 +++- .../OfflineSpecializationParityTests.swift | 1 + .../OfflineSpecializationTests.swift | 1 + .../SpecializedRuntimeTypeNameTests.swift | 1 + ...bclassMapMaterializationFailureTests.swift | 3 ++- .../ExportedSymbolFactsTests.swift | 1 + .../SymbolIndexDemangledIndexTests.swift | 1 + .../SymbolIndexStoreFixtureTests.swift | 1 + ...ymbolicManglingSymbolCollectionTests.swift | 1 + ...ssorThunkTypeInGenericExtensionTests.swift | 2 +- .../MergedAccessorFixtureTests.swift | 2 +- .../OpaqueTypeRenderingIntegrationTests.swift | 1 + ...SimulatorRuntimeThunkResolutionTests.swift | 1 + .../StandaloneFileThunkResolutionTests.swift | 4 +-- 420 files changed, 605 insertions(+), 131 deletions(-) diff --git a/Sources/ABI/MachOSwiftSection/Extensions/String+.swift b/Sources/ABI/MachOSwiftSection/Extensions/String+.swift index 3bb6d049..063423c6 100644 --- a/Sources/ABI/MachOSwiftSection/Extensions/String+.swift +++ b/Sources/ABI/MachOSwiftSection/Extensions/String+.swift @@ -1,3 +1,4 @@ +import Foundation extension String { var countedString: String { guard !isEmpty else { return "" } diff --git a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift index e8970b97..0824e008 100644 --- a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift @@ -1,6 +1,8 @@ import Foundation import MachOKit import MachOReading +import FrameworkToolbox +import SwiftStdlibToolbox public protocol MetadataProtocol: ResolvableLocatableLayoutWrapper where Layout: MetadataLayout { associatedtype HeaderType: ResolvableLocatableLayoutWrapper = TypeMetadataHeader diff --git a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift index 975181dd..e3bb1b84 100644 --- a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift @@ -1,6 +1,7 @@ import Foundation import MachOBase import SwiftStdlibToolbox +import BinaryParseSupport @CaseCheckable(.public) @AssociatedValue(.public) diff --git a/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift b/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift index d527463f..f18e2bf6 100644 --- a/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift @@ -1,3 +1,4 @@ +import BinaryParseSupport public protocol TopLevelDescriptor: ResolvableLocatableLayoutWrapper { var actualSize: Int { get } } diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift index 4c0968eb..a457883f 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift @@ -2,6 +2,7 @@ import Foundation import MachOKit @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences +import MachOKitExtensions /// Reads what each function of an image references, from its arm64 /// machine code, inside the current process. diff --git a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift index 0ebf5f25..cbc25075 100644 --- a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift +++ b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift @@ -1116,7 +1116,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { "Swift.PartialRangeFrom": PartialRangeFrom.self, "Swift.PartialRangeUpTo": PartialRangeUpTo.self, "Swift.PartialRangeThrough": PartialRangeThrough.self, - "Swift.Result": Result.self, + "Swift.Result": Result.self, "Swift.Unmanaged": Unmanaged.self, "Swift.UnsafePointer": UnsafePointer.self, "Swift.UnsafeMutablePointer": UnsafeMutablePointer.self, diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index 456e88be..83f022e3 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -641,7 +641,7 @@ extension SymbolicDemangler { // It contributes a discriminator only when it wraps a private // type; otherwise it is skipped, and a type inside demangles as if // it were internal. - if let lookupContext = readingContext as? SymbolLookupContext, + if let lookupContext = readingContext as? (any SymbolLookupContext), let privateDeclNameIdentifier = lookupContext.privateDiscriminatorIdentifier(forAnonymousContextAt: context.contextDescriptor.offset) { if let parentDemangling { return Node.createTransient(kind: .anonymousContext, children: [privateDeclNameIdentifier, parentDemangling]) @@ -746,7 +746,7 @@ extension SymbolicDemangler { let symbolNode = try demangle(for: mangledName, kind: .symbol, in: readingContext) return symbolNode.kind == .global ? symbolNode.children.first : symbolNode } - guard let lookupContext = readingContext as? SymbolLookupContext else { return nil } + guard let lookupContext = readingContext as? (any SymbolLookupContext) else { return nil } return lookupContext.anonymousContextName(forAnonymousContextAt: anonymousContext.offset) } @@ -764,7 +764,7 @@ extension SymbolicDemangler { private static func positionNameOfUnnamedLocalType(inside parent: SymbolOrElement?, in readingContext: some ReadingContext) throws -> String? { guard case .element(.anonymous(let anonymousContext))? = parent, isAnonymousContext(try anonymousContext.parent(in: readingContext)), - let lookupContext = readingContext as? SymbolLookupContext + let lookupContext = readingContext as? (any SymbolLookupContext) else { return nil } return lookupContext.positionName(forAnonymousContextAt: anonymousContext.offset) } diff --git a/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift index 908cb80f..4eb29656 100644 --- a/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift +++ b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift @@ -1,6 +1,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import Demangling +import BinaryParseSupport /// The layout facts a generic type descriptor's requirement signature yields /// **without any instantiation argument** — what the signature alone pins about diff --git a/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift b/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift index c288bace..a9183742 100644 --- a/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift +++ b/Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift @@ -2,6 +2,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftObjCInterop import Demangling +import BinaryParseSupport /// Resolves a Swift type (given by its mangled name or demangled `Node`) to its /// `StaticTypeLayout`, recursing into struct/tuple fields and stopping class diff --git a/Sources/Analysis/SwiftObjCInterop/ClassHierarchyDumper.swift b/Sources/Analysis/SwiftObjCInterop/ClassHierarchyDumper.swift index 2153e77d..0a464399 100644 --- a/Sources/Analysis/SwiftObjCInterop/ClassHierarchyDumper.swift +++ b/Sources/Analysis/SwiftObjCInterop/ClassHierarchyDumper.swift @@ -5,6 +5,7 @@ import MachOKitExtensions import MachOFoundation import MachOSwiftSection @_spi(Core) import MachOObjCSection +import ObjCDump @_spi(Internals) public struct ClassHierarchyDumper { diff --git a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift index fa78e950..0a39a706 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift @@ -6,6 +6,7 @@ import MachOKitExtensions @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import MachOResolving /// The public face of the ObjC member recovery (evolution proposals /// `objc-ancestor-override-recovery` and `objc-member-selector-recovery`): diff --git a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift index c741862e..94e77191 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift @@ -3,6 +3,8 @@ import MachOKit @_spi(Internals) import MachOAddressResolution import MachOKitExtensions @_spi(Internals) import SwiftSymbols +import MachOReading +import MachOResolving /// What an ObjC method's IMP references (evolution proposal /// `objc-ancestor-override-recovery`): the addresses its code calls, diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift index 98368d92..efe57ce8 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift @@ -5,6 +5,8 @@ import ObjCIndexing import ObjCInterface import ObjCMetadataSource import SwiftIndexing +import MachOKitExtensions +import Semantic /// `swift-section objc snapshot`: index a binary's ObjC API and persist it as a /// baseline document — or relabel an existing document. diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift index c377c9a0..c9bec916 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift @@ -5,6 +5,7 @@ import SwiftDiffing import SwiftIndexing import SwiftInterface import Utilities +import Semantic /// `swift-section diff`: compare the Swift ABI of two binaries, or of a binary /// and a persisted baseline. diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift index 1d24a7d7..d02fb0a6 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift @@ -5,6 +5,7 @@ import SwiftDiffing import SwiftIndexing import SwiftInterface import Utilities +import Semantic /// `swift-section evolution`: track the Swift ABI of one module across an /// ordered series of versions. diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index e52a6237..2cea9133 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -11,6 +11,7 @@ import OutputTransformer import SwiftOutputTransformer #if os(macOS) import TypeIndexing +import Semantic #endif /// `swift-section interface`: generate a `.swiftinterface` from a binary. diff --git a/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift b/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift index 7466339b..0748eff7 100644 --- a/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift +++ b/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift @@ -90,15 +90,15 @@ public enum SwiftIndexEvents { @Loggable(.private, subsystem: "com.machoswiftsection.swift-declaration", category: "SwiftIndexEvents.unhandled") public final class Dispatcher: Sendable { @Mutex - private var handlers: [Handler] = [] + private var handlers: [any Handler] = [] public init() {} - public func addHandler(_ handler: Handler) { + public func addHandler(_ handler: any Handler) { handlers.append(handler) } - public func addHandlers(_ newHandlers: [Handler]) { + public func addHandlers(_ newHandlers: [any Handler]) { handlers.append(contentsOf: newHandlers) } diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift index ffcbf2eb..3073d4bf 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift @@ -1,4 +1,5 @@ import Demangling +import SwiftSymbols extension DemanglingNode where Self: Sequence { var isStoredVariable: Bool { diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift index 6e6ab7a9..a0539fe7 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift @@ -3,6 +3,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import Semantic +import SwiftDeclarationRendering extension FieldRecord { package func demangledTypeNode(in context: some ReadingContext) throws -> Node { try SymbolicDemangler.demangleType(for: mangledTypeName(in: context), in: context) diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift index 5aed201e..4746d1b0 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift @@ -1,5 +1,6 @@ @_spi(Internals) import SwiftSymbols import OrderedCollections +import Demangling extension Definition { func addSymbol(_ symbol: MemberSymbol, memberSymbolsByKind: inout OrderedDictionary, inExtension: Bool) { diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift index 8d32cfdb..16431a35 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift @@ -2,6 +2,7 @@ import Demangling import SwiftInspection import SwiftObjCInterop import SwiftThunkAnalysis +import SwiftSymbols /// Joins an `ObjCMemberTable` — the class's ObjC method table tied to its /// Swift members — onto already-built member definitions (evolution diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift index e61087c9..37802194 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift @@ -2,6 +2,7 @@ import MachOSwiftSection import OrderedCollections @_spi(Internals) import SwiftSymbols +import Foundation /// Member symbols that stand in for an implementation symbol the image does /// not have. diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift index 355edf5f..c20b8e92 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift @@ -3,6 +3,7 @@ import MachOSwiftSection import OrderedCollections @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import BinaryParseSupport extension ExtensionDefinition: OnceIndexedDefinition { /// Resolves a conformance's resilient witnesses to members. Idempotent, diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift index 981c0866..62bae730 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift @@ -4,6 +4,7 @@ import OrderedCollections import SwiftDeclarationRendering @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import BinaryParseSupport extension TypeDefinition { /// The dynamic-dispatch lookups this type's vtable and override tables diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift index 77ed82a5..c10c69dd 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift @@ -7,6 +7,7 @@ import SwiftThunkAnalysis @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import BinaryParseSupport extension TypeDefinition: OnceIndexedDefinition { /// Fills the definition from the image: fields, members, the facts that diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift index 036afcd8..d1d54d1f 100644 --- a/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift @@ -1,4 +1,5 @@ import MachOSwiftSection +import SwiftSymbols public enum OrderedMember: Sendable { case allocator(FunctionDefinition) diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift index 364e26d8..7659d17d 100644 --- a/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift @@ -1,5 +1,6 @@ import SwiftInspection import SwiftObjCInterop +import MachOSwiftSection /// A member's ObjC-derived source facts, resolved against one consumer's /// verdict on NAME-only evidence (evolution proposal diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift index 603a12a4..70b676d9 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift @@ -5,6 +5,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftObjCInterop import SwiftDeclaration +import OrderedCollections /// The image's Objective-C classes, categories and protocols as Swift imports /// them (evolution proposal `objc-imported-declarations`). A definition is diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift index e77b3e5f..45e8616c 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift @@ -183,7 +183,7 @@ public final class SwiftDeclarationIndexer String { var charIndex = index diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift index 12f74633..51ff3daa 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift @@ -1,4 +1,5 @@ import MachOSwiftSection +import BinaryParseSupport extension GenericRequirement { /// A protocol-signature requirement that represents an *inherited protocol* diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift index d2e90e92..a88bf07c 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift @@ -2,6 +2,7 @@ import Foundation import Demangling import MachOSwiftSection @_spi(Internals) import SwiftInspection +import SwiftSymbols extension OpaqueType { package func requirements(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [GenericRequirementDescriptor] { diff --git a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift index 20a0e6cb..d927d65c 100644 --- a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift +++ b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift @@ -5,6 +5,7 @@ import SwiftSymbols import MachOSwiftSection @_spi(Internals) import Demangling @_spi(Internals) import SwiftInspection +import OrderedCollections /// How an opaque reference the rewriter could not expand is spelled in the /// tree it leaves behind (evolution proposal diff --git a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift index 5f70e6ba..806d9f2c 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import SwiftLayout import Utilities @_spi(Internals) import SwiftInspection +import SwiftStdlibToolbox /// `MachOFile` renders field comments **statically** through the `SwiftLayout` /// engine — no process, no metadata accessor. diff --git a/Sources/Output/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift index 7d3f876d..892d95d0 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffer.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffer.swift @@ -2,6 +2,7 @@ import Demangling import MachOSwiftSection import OrderedCollections import SwiftDeclaration +import SwiftSymbols /// Diffs the Swift ABI of two indexed modules by keying every declaration on /// its remangled `Node` and computing a recursive three-way set difference. diff --git a/Sources/Output/SwiftDiffing/ABIKey.swift b/Sources/Output/SwiftDiffing/ABIKey.swift index 415beea3..6e9cc730 100644 --- a/Sources/Output/SwiftDiffing/ABIKey.swift +++ b/Sources/Output/SwiftDiffing/ABIKey.swift @@ -1,4 +1,5 @@ import Demangling +import Foundation /// A stable, version-independent identity for a Swift declaration, derived by /// *remangling* its demangled `Node` back into a canonical symbol string. diff --git a/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift b/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift index 599a0f28..8c5bed47 100644 --- a/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift +++ b/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift @@ -2,6 +2,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import Demangling /// Comment text the dumpers share for the ObjC member facts (evolution /// proposals `objc-ancestor-override-recovery` and diff --git a/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift b/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift index add6a0e9..af564d6e 100644 --- a/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift @@ -72,8 +72,8 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// `.labelCountMismatch` on invalid input shapes. public init( configuration: SwiftDeclarationIndexConfiguration = .init(), - eventHandlers: [SwiftIndexEvents.Handler] = [], - eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [SwiftIndexEvents.Handler])? = nil, + eventHandlers: [any SwiftIndexEvents.Handler] = [], + eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [any SwiftIndexEvents.Handler])? = nil, versions: [MachO], labels: [String], availabilityAnnotationPlatform: String? = nil @@ -108,8 +108,8 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// `.labelCountMismatch` on invalid input shapes. public init( configuration: SwiftDeclarationIndexConfiguration = .init(), - eventHandlers: [SwiftIndexEvents.Handler] = [], - eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [SwiftIndexEvents.Handler])? = nil, + eventHandlers: [any SwiftIndexEvents.Handler] = [], + eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [any SwiftIndexEvents.Handler])? = nil, imageGroups: [[SwiftEvolutionInterfaceImage]], labels: [String], availabilityAnnotationPlatform: String? = nil @@ -133,7 +133,7 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// available everywhere the package deploys. public init( configuration: SwiftDeclarationIndexConfiguration = .init(), - eventHandlers: [SwiftIndexEvents.Handler] = [], + eventHandlers: [any SwiftIndexEvents.Handler] = [], versions: repeat each Reader, labels: [String], availabilityAnnotationPlatform: String? = nil diff --git a/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift b/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift index 52109a49..3a65a4f0 100644 --- a/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift +++ b/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift @@ -108,7 +108,7 @@ final class InterfaceVersionUnit: InterfaceVe /// path, where each version arrives as a bare reader. convenience init( configuration: SwiftDeclarationIndexConfiguration, - eventHandlers: [SwiftIndexEvents.Handler], + eventHandlers: [any SwiftIndexEvents.Handler], machO: MachO, imageName: String? = nil ) { @@ -214,7 +214,7 @@ final class InterfaceVersionGroupUnit: Interf @Mutex private var routing: Routing = Routing() - init(configuration: SwiftDeclarationIndexConfiguration, eventHandlers: [SwiftIndexEvents.Handler], images: [(imageName: String, machO: MachO)]) { + init(configuration: SwiftDeclarationIndexConfiguration, eventHandlers: [any SwiftIndexEvents.Handler], images: [(imageName: String, machO: MachO)]) { self.imageUnits = images.map { image in InterfaceVersionUnit(configuration: configuration, eventHandlers: eventHandlers, machO: image.machO, imageName: image.imageName) } diff --git a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift index 864e6ea4..c8944118 100644 --- a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift +++ b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift @@ -4,6 +4,7 @@ import MachOSwiftSection import Semantic import Demangling @_spi(Support) import SwiftPrinting +import SwiftDeclarationRendering /// Diff-only rendering entry points on `SwiftDeclarationPrinter`. /// diff --git a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift index 74d41afd..ded37271 100644 --- a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift @@ -5,6 +5,7 @@ import SwiftDiffing import MachOSwiftSection @_spi(Internals) import SwiftSymbols import Dependencies +import OrderedCollections /// The ABI-diff analogue of ``SwiftInterfaceBuilder``. /// @@ -24,7 +25,7 @@ public final class SwiftDiffableInterfaceBuilder: Sen public private(set) var importedModules: OrderedSet = [] @Mutex - public private(set) var extraDataProviders: [SwiftInterfaceBuilderExtraDataProvider] = [] + public private(set) var extraDataProviders: [any SwiftInterfaceBuilderExtraDataProvider] = [] private let eventDispatcher: SwiftIndexEvents.Dispatcher @@ -55,7 +55,7 @@ public final class SwiftInterfaceBuilder: Sen /// - eventDispatcher: An event dispatcher for handling logging and progress events. A new one is created by default. /// - machO: The Mach-O binary to analyze and generate interfaces from. /// - Throws: An error if the binary cannot be read or if required Swift sections are missing. - public init(configuration: SwiftInterfaceBuilderConfiguration = .init(), eventHandlers: [SwiftIndexEvents.Handler] = [], in machO: MachO) throws { + public init(configuration: SwiftInterfaceBuilderConfiguration = .init(), eventHandlers: [any SwiftIndexEvents.Handler] = [], in machO: MachO) throws { self.eventDispatcher = .init() self.machO = machO self.indexer = .init(configuration: configuration.indexConfiguration, eventHandlers: eventHandlers, in: machO) @@ -65,7 +65,7 @@ public final class SwiftInterfaceBuilder: Sen } @_spi(Support) - public init(indexer: SwiftDeclarationIndexer, printer: SwiftDeclarationPrinter, eventHandlers: [SwiftIndexEvents.Handler] = [], in machO: MachO) { + public init(indexer: SwiftDeclarationIndexer, printer: SwiftDeclarationPrinter, eventHandlers: [any SwiftIndexEvents.Handler] = [], in machO: MachO) { self.eventDispatcher = .init() self.machO = machO self.indexer = indexer diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift index 121dbe69..98fe967e 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift @@ -50,7 +50,7 @@ extension SwiftInterfaceBuilderDependencies { /// open. Defaulted, so existing call sites are unaffected — and passing /// none is safe rather than silent: `SwiftIndexEvents.Dispatcher` reports /// an unhandled failure to os_log rather than dropping it. - public init(machO: MachO, searchPaths: [DependencySearchPath], eventHandlers: [SwiftIndexEvents.Handler] = []) { + public init(machO: MachO, searchPaths: [DependencySearchPath], eventHandlers: [any SwiftIndexEvents.Handler] = []) { let closure = DependencyClosure(root: machO, searchPaths: searchPaths, traversal: .direct) if !closure.searchPathLoadFailures.isEmpty { let eventDispatcher = SwiftIndexEvents.Dispatcher() @@ -68,7 +68,7 @@ extension SwiftInterfaceBuilderDependencies { } @available(*, deprecated, renamed: "init(machO:searchPaths:eventHandlers:)") - public init(machO: MachO, paths: [DependencyPath], eventHandlers: [SwiftIndexEvents.Handler] = []) { + public init(machO: MachO, paths: [DependencyPath], eventHandlers: [any SwiftIndexEvents.Handler] = []) { self.init(machO: machO, searchPaths: paths.map(\.searchPath), eventHandlers: eventHandlers) } diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift index 3fcd2476..1e0fc124 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift @@ -10,6 +10,7 @@ import Dependencies import SwiftStdlibToolbox import SwiftDeclarationRendering @_spi(Internals) import SwiftInspection +import Semantic /// Carries the logging floor onto the provider. /// diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift index 620944e5..05c468d7 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift @@ -65,7 +65,7 @@ protocol NodePrintable { /// `*NodePrintableContext` refinement declares. var context: Context { get set } - var delegate: NodePrintableDelegate? { get } + var delegate: any NodePrintableDelegate? { get } mutating func printName(_ name: Node, options: NodePrintOptions) async } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index 58b4d8d7..ab404e14 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -3,6 +3,7 @@ import SwiftDeclarationRendering import SwiftInspection import Demangling import Semantic +import SwiftStdlibToolbox /// The slice of printer state the type layer reads. protocol TypeNodePrintableContext: NodePrintableContext { diff --git a/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift b/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift index 0d17ef2f..a50ac9a5 100644 --- a/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift +++ b/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift @@ -2,6 +2,7 @@ import MachOSwiftSection import Demangling import SwiftDeclarationRendering @_spi(Internals) import SwiftInspection +import BinaryParseSupport /// A protocol's requirement signature split by where each requirement prints /// (evolution proposal `protocol-requirement-placement`). diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 781c747a..85f7b755 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -8,6 +8,7 @@ import Dependencies import SwiftDeclarationRendering @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import SwiftStdlibToolbox /// Model-driven declaration-header rendering for the interface path. /// diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift index bc51c298..e6ef426e 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift @@ -3,6 +3,7 @@ import MachOSwiftSection import SwiftDeclaration @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import BinaryParseSupport /// The layout a `@_rawLayout` struct records outside its field descriptor. /// diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 76975004..565730ea 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -166,7 +166,7 @@ public final class SwiftDeclarationPrinter: S } } - public init(configuration: SwiftDeclarationPrintConfiguration = .init(), eventHandlers: [SwiftIndexEvents.Handler] = [], in machO: MachO) { + public init(configuration: SwiftDeclarationPrintConfiguration = .init(), eventHandlers: [any SwiftIndexEvents.Handler] = [], in machO: MachO) { self.machO = machO // Before `configuration`: that property is `@Mutex`-wrapped with a // default, so assigning it counts as using `self`, which is only legal @@ -778,7 +778,7 @@ public final class SwiftDeclarationPrinter: S @SemanticStringBuilder private func printDefinitionContents(_ definition: some Definition, level: Int, refinedForSwiftCommentsByVariableKey: [String: [StructuredComment]] = [:]) async throws -> SemanticString { - if let mutableDefinition = definition as? MutableDefinition { + if let mutableDefinition = definition as? (any MutableDefinition) { try mutableDefinition.index(in: machO) } diff --git a/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift b/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift index 69dfef48..e23ffbda 100644 --- a/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift +++ b/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift @@ -3,7 +3,7 @@ import SwiftSyntaxMacros @main struct MachOMacroPlugin: CompilerPlugin { - let providingMacros: [Macro.Type] = [ + let providingMacros: [any Macro.Type] = [ LayoutMacro.self, ResolvableLocatableLayoutWrapperMacro.self, ] diff --git a/Sources/Support/Utilities/StringBuilder.swift b/Sources/Support/Utilities/StringBuilder.swift index 0b744c63..07d9cfd6 100644 --- a/Sources/Support/Utilities/StringBuilder.swift +++ b/Sources/Support/Utilities/StringBuilder.swift @@ -8,7 +8,7 @@ package enum StringBuilder { components } - package static func buildBlock(_ components: CustomStringConvertible...) -> [String] { + package static func buildBlock(_ components: any CustomStringConvertible...) -> [String] { components.map { $0.description } } @@ -16,7 +16,7 @@ package enum StringBuilder { components.flatMap { $0 } } - package static func buildBlock(_ components: [CustomStringConvertible]...) -> [String] { + package static func buildBlock(_ components: [any CustomStringConvertible]...) -> [String] { components.flatMap { $0.map { $0.description } } } @@ -26,11 +26,11 @@ package enum StringBuilder { } extension StringBuilder { - package static func buildPartialBlock(first: CustomStringConvertible) -> [String] { + package static func buildPartialBlock(first: any CustomStringConvertible) -> [String] { [first.description] } - package static func buildPartialBlock(accumulated: [String], next: CustomStringConvertible) -> [String] { + package static func buildPartialBlock(accumulated: [String], next: any CustomStringConvertible) -> [String] { accumulated + [next.description] } diff --git a/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift b/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift index 426f150d..26e58f22 100644 --- a/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift +++ b/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift @@ -2,6 +2,7 @@ import MachOKit import MachOKitExtensions import MachOResolving @_spi(Internals) import MachOSymbols +import Demangling extension MachORepresentableWithCache { /// Every symbol the image's index knows at `offset`, building the index diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift index 0888770b..f6c7a62e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift @@ -4,6 +4,7 @@ import MachOKit import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Top-level dispatcher for the per-suite baseline sub-generators. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift index b401fc8e..35e0f214 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/AccessibleFunctionRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift index 305765e8..a277c1fa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift index 8bf06358..c5e4c82a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift index 41d04307..62055eac 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift index a0f16b18..d1e9c9a7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift index 279661e1..2087eed2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AssociatedTypeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift index 9ffa4901..df14d7ad 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AssociatedTypeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift index fa67ea94..f26985ac 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AssociatedTypeRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift index 1b704c3a..8718c3fc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/BuiltinTypeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift index c9aa15ee..2f0fe7a6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/BuiltinTypeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift index 2f425f37..0a6c13b3 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/CaptureDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift index 75fae01c..1c498cfb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/CaptureTypeRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift index fe6b8de9..29905eba 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MetadataSourceRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift index 144886b3..6013c2de 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift index 4e7aa33c..9083b35c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataObjCInteropBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift index c23cbf33..16ba2d97 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataObjCInteropProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift index 2790b391..0fdd8fd1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift index 4aed247d..8d77b0ca 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ClassBaseline.swift` from the `SymbolTestsCore` /// fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift index 920da1f2..29f55ec7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ClassDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift index b39c4d59..c352ace8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift index 2a90ba2e..f8975276 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift index b419feda..4c0d2efb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataBoundsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift index a86c3663..9441938f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataBoundsProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift index d9f3a342..852ee2d7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataObjCInteropBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift index 8577f611..a36c93d7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtraClassDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift index e61d1d0f..be03cb55 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/FinalClassMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift index c8626d87..28cf29f4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MethodDefaultOverrideDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift index b2db676f..8419e8fc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MethodDefaultOverrideTableHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift index ddb55de3..65472ee5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MethodDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift index edf21537..1e03f77c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MethodDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift index 98c3fa1b..df2192d8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MethodDescriptorKindBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift index 3a78ee4e..a92864ed 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MethodOverrideDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift index c66f4b07..6865dd20 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ObjCClassWrapperMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift index 4215421a..39f07572 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ObjCResilientClassStubInfoBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift index d0a0cdd3..098ef9dc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/OverrideTableHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift index 5073a291..dd3d6d52 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ResilientSuperclassBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift index 26e8e029..886bfefb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/StoredClassMetadataBoundsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift index 34812f88..1a7b2958 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/VTableDescriptorHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift index de7afd0e..e8c00e7c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift index 3a9a0baf..86d926c2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift index b5170737..28a37cd9 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorKindBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift index 6be978cd..f575354f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorKindSpecificFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift index 98bb1b2c..4c6bd1cc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift index 5c5c87b3..82c00ebd 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift index 6e86650a..57475aa6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift index 359a26bc..1718a539 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift index 734d101a..84f381fe 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/DispatchClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift index 7d80cffb..dbda5fe4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/EnumBaseline.swift` from the `SymbolTestsCore` /// fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift index 962d00e2..2b1fcbf2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/EnumDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift index 5cf3690c..13aa9f72 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/EnumFunctionsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift index a2fb8674..0c313dea 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/EnumMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift index 76f256bd..7fdb2289 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/EnumMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift index 2bfe7be2..f88c552d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MultiPayloadEnumDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift index b21e91ec..e4f90504 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExistentialMetatypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift index 70b3de31..2cd69be1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExistentialTypeFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift index b65e85f2..08748b34 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExistentialTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift index 3dd7105a..3de15de8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtendedExistentialTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift index 4a9a3e31..00c4a5a6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtendedExistentialTypeShapeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift index b40a4bb3..42bf659a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtendedExistentialTypeShapeFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift index 1fe14758..03064ac7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/NonUniqueExtendedExistentialTypeShapeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift index 069bdf7f..61e1c6fb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtensionContextBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift index 0e1c0389..63b4458c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtensionContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift index 132cb380..e55a9b2d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtensionContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift index 9e2f6519..d4af59f3 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FieldDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift index 9615b8ba..4b88a1da 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FieldRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift index cdc6cb3f..080f7a2f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FieldRecordFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift index a042489f..da9c641b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ForeignClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift index 2468a564..e71f9e6e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ForeignReferenceTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift index d81f5183..18130760 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FunctionTypeFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift index 788c1660..84ca17d4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift @@ -2,6 +2,8 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import BinaryParseSupport +import SwiftBasicFormat /// Emits `__Baseline__/FunctionTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift index b1804be1..0a42a9c8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import BinaryParseSupport +import SwiftBasicFormat /// Emits `__Baseline__/AsyncFunctionPointerBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift index 1bd2bb7a..02dbabdf 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericContextBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift index 2b0abee0..59b73f16 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift index 7587e6e2..fa024b54 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericContextDescriptorHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift index c1b50541..ec0f1948 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/GenericEnvironmentBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift index a6f73014..bae297f8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericEnvironmentFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift index b36cca70..70a32fd4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericPackShapeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift index 24555a72..f48ee859 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericPackShapeHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift index 762c1c0d..0a244b40 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericParamDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift index 9540eebf..6428f4b8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift index 586bb3c9..6c59615e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementContentBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift index 249d0946..df5c1ad1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift index c1ee1d8c..9f66da2a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift index 1a6a31d2..19a740b7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericValueDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift index 2d191ce0..896f5e17 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericValueHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift index 7362113d..b7e5b1dc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/GenericWitnessTableBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift index 82ae6b0e..9cd6e8a2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericClassMetadataPatternBaseline.swift`. package enum GenericClassMetadataPatternBaselineGenerator { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift index 10f63df8..5283b52f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericMetadataPartialPatternBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift index 19e7d8a5..f1696b99 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericMetadataPatternProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift index 6787a1a3..94c62fa8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericValueMetadataPatternBaseline.swift`. package enum GenericValueMetadataPatternBaselineGenerator { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift index b96a60b0..55d5a8c4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/ResilientClassMetadataPatternBaseline.swift`. package enum ResilientClassMetadataPatternBaselineGenerator { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift index cf278df7..734adcdc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeGenericContextDescriptorHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift index 3c152405..7538e31c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/GenericBoxHeapMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift index 3493fcf1..f8edcb00 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/HeapLocalVariableMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift index 80acffb5..95348b82 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/KeyPathComponentHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift index aa576c0e..122497ee 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/KeyPathComputedPropertyBodyBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift index d9065b46..bc1ef7be 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/KeyPathStoredFieldOffsetBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift index f652a1a8..ef759b91 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/PropertyDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift index 9d7ee643..7cc1a319 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MangledNameBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift index e056a801..5f1d5f4d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/BorrowTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift index 9aa1ad97..10e0db5c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadataAccessorsListEntryBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift index cb03e4e6..a139dc35 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadatasCachingOnceTokenBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift index 37ae2fd0..954673aa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadatasListCountBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift index 3af0def0..6b645e54 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadatasListEntryBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift index 7420bb0f..f3b8d68a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/FixedArrayTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift index 0236db4e..f5fcf89b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/FullMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift index ca86f404..131f167c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/HeapMetadataHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift index 38a8b4da..0a9f4a78 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/HeapMetadataHeaderPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift index 6fa85f9e..82fa9ead 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataHeaderBaseBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift index c5323993..7a47491d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift index acc708fc..45d25d5f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataLayoutPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift index 36cfefbf..ba9b777d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataAccessorFunctionBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift index 66c1c8b9..cc37f944 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift index 05a3b2f7..e8f0948b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataBoundsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift index b4293c5d..8f49f661 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataBoundsProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift index 38a68845..1872bca5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ForeignMetadataInitializationBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift index 544e4a45..14ef7cbf 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/SingletonMetadataInitializationBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift index 69f302b4..1d9fd0d5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift index 0f851c13..3bb5d5eb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataRequestBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift index 18e91918..da0288ea 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataResponseBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift index 5e4eae3d..46e024cb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift index 47c9bcb6..add600d1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MetatypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift index 24fb0e92..3b370e51 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/SingletonMetadataPointerBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift index 6dbd54ff..a61d3aae 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ModuleContextBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift index bc367c64..b54e5994 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ModuleContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift index 425696bc..e4a39a93 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/NamedContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift index 51a15e95..59718e9c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift index 35d4574d..3df881fb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueTypeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift index 5b67b702..e02e27c6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueTypeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift index ef066a9e..3cc8fed0 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueTypeDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift index 850202eb..0f09285f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/InvertibleProtocolSetBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift index 63528e82..32b4aafa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/InvertibleProtocolsRequirementCountBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift index c3f81dd7..6f749336 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ObjCProtocolPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift index 4eca5d22..b111d04a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/RelativeObjCProtocolPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift index b6b7f464..91f91229 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolBaseRequirementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift index 834c6798..d4c4a708 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift index 56f06c68..de3f105f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift index 36495331..99e202e8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift index ed1b2133..7742907f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift index 1c197e8f..6318d88e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolDescriptorRefBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift index 512c3d4f..25ec8338 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift @@ -4,6 +4,7 @@ import SwiftSyntaxBuilder import MachOFoundation import MachOKit @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift index dfc416b8..5e9f08a7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRequirementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift index 6f1a38f1..058b87dd 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRequirementFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift index 80bbf6f0..82881fa6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRequirementKindBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift index d6251138..b8c410eb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolWitnessTableBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift index 7c5eb575..38bf4987 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ResilientWitnessBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift index 2c649724..68f556f7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ResilientWitnessesHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift index a285da59..d4d1dfa1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GlobalActorReferenceBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift index 8748700d..9a43e7fa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolConformanceBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift index c4572437..87aaf4f3 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolConformanceDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift index 957bb48d..a7a75e58 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolConformanceFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift index 0a56c36e..441c83b8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat // Pattern note: this generator and its corresponding Suite use **presence flags** // (`hasGenericContext: Bool`, etc.) for heavy optional ivars rather than full diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift index 74c5b255..f77a65f3 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/StructDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift index d9765679..37998ac2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/StructMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift index 6615e1d5..15ac669e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/StructMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift index 0ea47cbb..452a507e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TupleTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift index 932762d8..908ce989 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TupleTypeMetadataElementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift index b36b9b34..4e3aec4c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift index 7bae5758..a879395f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift index 03f786fd..0e216bc3 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift index cf84721e..01fc0d87 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift index a55c2a3c..17fec8ea 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift index 59f12f12..f31cc653 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift @@ -4,6 +4,7 @@ import SwiftSyntaxBuilder import MachOFoundation import MachOKit @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift index 9b3b14ab..01f8cd17 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift @@ -4,6 +4,7 @@ import SwiftSyntaxBuilder import MachOFoundation import MachOKit @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeReferenceBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift index eea88ff9..34dd4dfe 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ValueMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift index fa022104..e48d54cf 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ValueMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift index 16b185d6..4e02c0d1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ValueTypeDescriptorWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift index 4cba0dae..0a479032 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeLayoutBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift index 6e251b51..cb0d2b1e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ValueWitnessFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift index 1647f8f6..48811bf4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ValueWitnessTableBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift index 4e424930..026b6469 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift @@ -1,6 +1,7 @@ import Foundation import MachOSwiftSection import SwiftDump +import Demangling extension DemangleOptions { /// Snapshot/baseline fixtures are recorded with interface-style printing: diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift index 97f223e5..581d1ca9 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift @@ -7,6 +7,8 @@ import SwiftDeclarationRendering import Dependencies @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import Semantic +import Demangling @MainActor package protocol DumpableTests { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift index 7f71a78a..063c3eca 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift @@ -1,6 +1,7 @@ import Foundation import MachOKit import UniformTypeIdentifiers +import MachOKitExtensions package func loadFromFile(named: MachOFileName) throws -> File { let url: URL diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift index f952c3c7..3df134a7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift @@ -7,6 +7,7 @@ import SwiftDeclarationRendering import Demangling // Needs SPI access to SymbolicDemangler.demangleType for associated-type owning-protocol lookup. @_spi(Internals) import SwiftInspection +import Semantic @MainActor package protocol SnapshotDumpableTests {} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift index 24c90054..52581ad5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift @@ -3,6 +3,9 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftInterface +import SwiftIndexing +import Semantic +import SwiftPrinting @MainActor package protocol SnapshotInterfaceTests {} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift index cffffc7e..b22514af 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift @@ -144,7 +144,7 @@ package enum ClassesWithoutClassObjectsFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift index 6df9396e..7f63d7f4 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift @@ -106,7 +106,7 @@ package enum ExistentialAnyFixture { } /// Compiled once per process. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift index 2f8131b4..e36c25d3 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift @@ -160,7 +160,7 @@ package enum ExportedOnlyFixture { } /// Compiled once per process. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift index 640b2b07..1873a842 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift @@ -137,7 +137,7 @@ package enum ExtensionContextExportFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ExtensionContextExportFixture-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift index 265a6b96..f4b3e11d 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift @@ -233,7 +233,7 @@ package enum GenericSpecializationFixture { }() } - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift index 708769ec..6b55ea01 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift @@ -4,6 +4,7 @@ import Foundation import Testing import MachOKit import MachOSwiftSection +import OrderedCollections /// The `GenericSpecializationFixture`'s prepared indexers, one per reading /// path, each built once per process and shared by every suite: the runtime diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift index e9f3b37a..f2b4aa48 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift @@ -222,7 +222,7 @@ package enum ImageGroupFixture { /// Compiled once per process, each version in a directory of its own, /// since every version reuses the two module names. Per version the /// libraries' URLs, the core image's first when there is one. - private static let compilationResult: Result<[[(name: String, libraryURL: URL)]], Swift.Error> = { + private static let compilationResult: Result<[[(name: String, libraryURL: URL)]], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift index 2686b5b1..2ee8c92a 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift @@ -272,8 +272,8 @@ package enum InitAccessorFixture { private final class OneTimeCompilation: @unchecked Sendable { private let lock = NSLock() - private var result: Result<[Variant: URL], Swift.Error>? - private var waiters: [CheckedContinuation<[Variant: URL], Swift.Error>] = [] + private var result: Result<[Variant: URL], any Swift.Error>? + private var waiters: [CheckedContinuation<[Variant: URL], any Swift.Error>] = [] private var hasStarted = false func libraries() async throws -> [Variant: URL] { diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift index bc11675a..14a13fd8 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift @@ -351,7 +351,7 @@ package enum LocalTypeFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("LocalTypeFixture-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift index 5102fd3a..8c974d05 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift @@ -109,7 +109,7 @@ package enum ModuleSelectorFixture { } /// Compiled once per process. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift index 453a7a15..201df54d 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift @@ -369,7 +369,7 @@ package enum ObjCImplementationFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift index 05e278b3..283a3b23 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift @@ -187,8 +187,8 @@ package enum ObservableMacroFixture { private final class OneTimeCompilation: @unchecked Sendable { private let lock = NSLock() - private var result: Result<[Variant: URL], Swift.Error>? - private var waiters: [CheckedContinuation<[Variant: URL], Swift.Error>] = [] + private var result: Result<[Variant: URL], any Swift.Error>? + private var waiters: [CheckedContinuation<[Variant: URL], any Swift.Error>] = [] private var hasStarted = false func libraries() async throws -> [Variant: URL] { diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift index a62167e2..09029a38 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift @@ -160,7 +160,7 @@ package enum RenamedObjCClassFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift index 2feab426..3a5be1dd 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift @@ -199,7 +199,7 @@ package enum Swift64DeclarationShapesFixture { } /// Compiled once per process. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { guard let toolchain else { throw CompilationError(diagnostics: "no Swift 6.4 or newer toolchain is installed") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift index 7dec3ae0..f19f30f8 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift @@ -204,7 +204,7 @@ package enum SwiftDeclaredObjCProtocolsFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift index 9bddb589..11ee2c4e 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift @@ -129,7 +129,7 @@ package enum ThunkOnlyMemberFixture { } /// Compiled once per process; both variants share one working directory. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift index cb318845..9e56d04c 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift @@ -167,7 +167,7 @@ package enum UnobservablePresenceFixture { } /// Compiled once per process; the versions share one working directory. - private static let compilationResult: Result<[URL], Swift.Error> = { + private static let compilationResult: Result<[URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift index 268bdf2f..81d2c1fa 100644 --- a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift +++ b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift @@ -5,6 +5,7 @@ import MachOKit @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import ARM64InstructionDecoding @testable import CrossReferenceAnalysis +import MachOKitExtensions /// What an address is (evolution proposal /// `offline-cross-references-and-symbolication`, step 6). diff --git a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift index ea57e008..a2373d2b 100644 --- a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift +++ b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift @@ -7,6 +7,7 @@ import MachOSwiftSection @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import SwiftInspection @testable import CrossReferenceAnalysis +import MachOKit /// A type of this test bundle that nothing else names: its key comes from /// its `…Mn` symbol. Internal, so that no private discriminator joins it. diff --git a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift index 18c4c1af..fcd1b280 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift @@ -6,6 +6,9 @@ import Demangling import SwiftSectionFixtureSupport @_spi(Internals) @testable import SwiftSymbols @testable @_spi(Internals) import SwiftInspection +import MachOReading +import SwiftDeclaration +import MachOSwiftSection final class DyldCacheAssociatedTypeTests: DyldCacheTests, @unchecked Sendable { @MainActor diff --git a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift index c5402f45..08f63bb9 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift @@ -12,6 +12,7 @@ import SwiftInspection #if canImport(SwiftUI) import SwiftUI +import Semantic #endif struct GenericStructNonRequirement { diff --git a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift index 5ad3485c..f30dee22 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift @@ -9,6 +9,7 @@ import MachOSwiftSection @testable import SwiftDump @_spi(Internals) import SwiftSymbols @testable @_spi(Internals) import SwiftInspection +import Semantic protocol OpaqueTypeTests {} @@ -42,7 +43,7 @@ extension OpaqueTypeTests { } } -final class OpaqueTypeDyldCacheTests: DyldCacheTests, OpaqueTypeTests, @unchecked Sendable { +final class OpaqueTypeDyldCacheTests: DyldCacheTests, nonisolated OpaqueTypeTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { .SwiftUI } @MainActor @@ -58,7 +59,7 @@ final class OpaqueTypeDyldCacheTests: DyldCacheTests, OpaqueTypeTests, @unchecke } } -final class OpaqueTypeMachOFileTests: MachOFileTests, OpaqueTypeTests, @unchecked Sendable { +final class OpaqueTypeMachOFileTests: MachOFileTests, nonisolated OpaqueTypeTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @MainActor @@ -67,7 +68,7 @@ final class OpaqueTypeMachOFileTests: MachOFileTests, OpaqueTypeTests, @unchecke } } -final class OpaqueTypeMachOImageTests: MachOImageTests, OpaqueTypeTests, @unchecked Sendable { +final class OpaqueTypeMachOImageTests: MachOImageTests, nonisolated OpaqueTypeTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } @MainActor diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift index 6c6ed9ce..aadbf0b8 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift @@ -4,6 +4,9 @@ import Testing @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport import SwiftInspection +import Demangling +import Semantic +import SwiftDeclarationRendering final class ProtocolGenericContextTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift index 96a90eea..2fef5b99 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift @@ -4,6 +4,7 @@ import Testing @testable import SwiftDump @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport final class ProtocolRequirementSignatureTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } diff --git a/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift b/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift index 0b5c2e78..0f02e989 100644 --- a/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift @@ -4,6 +4,9 @@ import Testing @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftSymbols +import MachOKit +import Demangling final class ExternalSymbolTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } diff --git a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift index 54e6913c..a3b3a01e 100644 --- a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift @@ -6,6 +6,7 @@ import Demangling @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Stage 0 of the NodeStore migration plan: capture per-image baseline /// metrics for `SwiftSymbolIndexStore.buildStorage` so Stage 1/4 can compare diff --git a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift index bf756080..a69587d8 100644 --- a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift +++ b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift @@ -9,6 +9,7 @@ import ObjCMetadataSource import ObjCIndexing import ObjCInterface import ObjCDiffing +import Semantic /// One image indexed the way the `objc` subcommands index it: the Swift /// classes that keep no class object supplied from Swift metadata. @@ -159,7 +160,7 @@ enum ObjCAPIEvolutionTestSuite { /// AppKit across the three macOS caches the Swift evolution suites /// default to (15.5 → 26.5.2 → 27.0), so the Objective-C report can be /// read beside theirs. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func evolutionFile() async throws { try await evolutionFile(versions: versions) @@ -181,7 +182,7 @@ enum ObjCAPIEvolutionTestSuite { /// selector base, and an earlier reader made every class and category /// method of 11.x garbage — 11.7 → 12.0.1 then reported about 47,000 /// removals and 53,000 additions instead of about 1,200 and 1,400. - final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths } @@ -201,7 +202,7 @@ enum ObjCAPIEvolutionTestSuite { /// UIFoundation, CollectionViewCore, CoreAutoLayout — across the default /// three caches (15.5 → 26.5.2 → 27.0), each version one group of images /// (evolution proposal `image-group-evolution`). - final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -220,7 +221,7 @@ enum ObjCAPIEvolutionTestSuite { /// UIFoundation and CollectionViewCore in 13.0 and 15.0 — where an /// evolution of AppKit alone reads them as removed or added — read as /// moved. CollectionViewCore joins the group in 13.0. - final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { ArchivedDyldCacheTests.cachePaths } @@ -240,7 +241,7 @@ enum ObjCAPIEvolutionTestSuite { /// SwiftUI together with SwiftUICore across the default three caches — /// the Objective-C side of `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -256,7 +257,7 @@ enum ObjCAPIEvolutionTestSuite { /// The same group across every archived macOS cache: SwiftUI alone until /// 14.8, SwiftUICore joining it in 15.0. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { ArchivedDyldCacheTests.cachePaths } @@ -380,7 +381,7 @@ enum ObjCEvolutionInterfaceTestSuite { /// (15.5 → 26.5.2 → 27.0) — the axis of /// `ObjCAPIEvolutionTestSuite.DyldCacheTests`, so the header and the /// report can be read side by side. - final class DyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + final class DyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func evolutionInterfaceFile() async throws { try await evolutionInterfaceFile(versions: versions) @@ -396,7 +397,7 @@ enum ObjCEvolutionInterfaceTestSuite { /// `ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests`. Every label is a /// version number, so the header also spells each lifecycle one macro can /// express as `API_AVAILABLE` / `API_OBSOLETED`. - final class ArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + final class ArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths } @@ -415,7 +416,7 @@ enum ObjCEvolutionInterfaceTestSuite { /// AppKit with UIFoundation, CollectionViewCore and CoreAutoLayout across /// the default three caches — the axis of /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests`. - final class AppKitImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + final class AppKitImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cacheImageNames: [MachOImageName] { ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames } @@ -434,7 +435,7 @@ enum ObjCEvolutionInterfaceTestSuite { /// The same group across every archived macOS cache, on the axis of /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupArchivedDyldCacheTests`, /// with the availability macros. - final class AppKitImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + final class AppKitImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths } @@ -456,7 +457,7 @@ enum ObjCEvolutionInterfaceTestSuite { /// SwiftUI with SwiftUICore across the default three caches — the axis /// of `ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. - final class SwiftUIImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cacheImageNames: [MachOImageName] { ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames } @@ -474,7 +475,7 @@ enum ObjCEvolutionInterfaceTestSuite { /// The same group across every archived macOS cache, with the /// availability macros. - final class SwiftUIImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths } diff --git a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift index c68b3801..05f559b8 100644 --- a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift +++ b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift @@ -220,7 +220,7 @@ enum ABIEvolutionTestSuite { /// AppKit across three macOS caches (15.5 → 26.5.1 → 27.0 beta 1) — the /// flagship N == 3 lineage: introduced/modified/removed/re-added stories /// only visible with more than two versions. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { + final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func evolutionFile() async throws { try await evolutionFile(versions: versions) @@ -236,7 +236,7 @@ enum ABIEvolutionTestSuite { /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution /// proposal `image-group-evolution`): what moved between the two images /// after the split reads as moved, not as removed and added. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -255,7 +255,7 @@ enum ABIEvolutionTestSuite { /// SwiftUI alone until 14.8, SwiftUICore joining it in 15.0 — where an /// evolution of SwiftUI alone reads every declaration moved into /// SwiftUICore as removed. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths } @@ -276,7 +276,7 @@ enum ABIEvolutionTestSuite { /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the /// N == 2 case, whose printed pairwise cross-check line must agree with /// the two-sided differ. - final class SwiftUICoreTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, ABIEvolutionDumpTests, @unchecked Sendable { + final class SwiftUICoreTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } diff --git a/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift b/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift index 56bb26a3..f4fa1f6a 100644 --- a/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface import SwiftSectionFixtureSupport import Demangling +import Semantic +import SwiftPrinting /// Maintainer-only rendering-verification harness (no assertions — like the rest /// of `IntegrationTests`). diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift index c475fbf9..a6e309e8 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift @@ -8,6 +8,7 @@ import SwiftSectionTestingSupport @testable import SwiftInterface @_spi(Support) @testable import SwiftIndexing import SwiftDiffing +import Semantic /// The ABI-diff analogue of ``SwiftInterfaceBuilderTests``. /// @@ -172,7 +173,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { } /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.2). - final class SwiftUICoreTests: CrossVersionMachOFileTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { + final class SwiftUICoreTests: CrossVersionMachOFileTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } @@ -188,7 +189,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { } /// SwiftUI across two simulator runtimes (iOS 18.5 → 26.2). - final class SwiftUITests: CrossVersionMachOFileTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { + final class SwiftUITests: CrossVersionMachOFileTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUI } @@ -205,7 +206,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { /// The same macOS image (SwiftUI) extracted from two dyld shared caches /// (macOS 15.5 → current). Cross-image references resolve through each cache. - final class DyldCacheTests: CrossVersionDyldCacheImageTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { + final class DyldCacheTests: CrossVersionDyldCacheImageTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { override class var oldCachePath: DyldSharedCachePath { .macOS_26_5_1 } override class var newCachePath: DyldSharedCachePath { .macOS_27_0 } override class var cacheImageName: MachOImageName { .AppKit } @@ -224,7 +225,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { /// The same image from two archived macOS caches, picked by version: point /// the two versions at any directories under `/Volumes/DyldSharedCaches/macOS` /// that hold a cache. - final class ArchivedDyldCacheTests: CrossVersionDyldCacheImageTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { + final class ArchivedDyldCacheTests: CrossVersionDyldCacheImageTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { class var oldCacheVersion: String { "26.6" } class var newCacheVersion: String { "27.0" } override class var oldCachePath: DyldSharedCachePath { .macOS(oldCacheVersion) } @@ -245,7 +246,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { /// The DVTProductsUI shared framework across two installed Xcode versions /// (26.3 → 26.4) — mirrors the framework the interface builder tests use, /// loaded by path so the diff can compare two Xcodes. - final class XcodeFrameworkTests: CrossVersionXcodeFrameworkTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { + final class XcodeFrameworkTests: CrossVersionXcodeFrameworkTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { override class var oldXcodeApplicationPath: String { "/Applications/Xcode-26.3.0.app" } override class var newXcodeApplicationPath: String { "/Applications/Xcode-26.4.0.app" } override class var sharedFrameworkName: String { "DVTProductsUI" } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift index cce847f5..b8626911 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift @@ -8,6 +8,7 @@ import SwiftSectionTestingSupport @_spi(Support) @testable import SwiftInterface @_spi(Support) @testable import SwiftIndexing import SwiftDiffing +import Semantic /// The annotated-union-interface analogue of ``ABIEvolutionDumpTests``. /// @@ -136,7 +137,7 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { /// AppKit across three macOS caches (15.5 → 26.5.1 → 27.0 beta 1) — the /// same axis as `ABIEvolutionTestSuite.DyldCacheTests`' lineage dumps, so /// the interface and the report can be inspected side by side. - final class DyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + final class DyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func evolutionInterfaceFile() async throws { try await evolutionInterfaceFile(versions: versions) @@ -171,7 +172,7 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { /// SwiftUICore across the same three macOS caches — the Swift-rich axis /// (AppKit's Swift section is comparatively thin), exercising the union /// interface over heavy generics, opaque returns, and extension blocks. - final class SwiftUICoreDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + final class SwiftUICoreDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { .SwiftUICore } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -194,7 +195,7 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { /// attribute can express as `@available(macOS, …)`. A version whose image /// carries no Swift metadata drops off the axis (see /// `MultiVersionDyldCacheImageTests`). - final class ArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + final class ArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { class var cacheVersions: [String] { [ "11.0.1", @@ -282,7 +283,7 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { /// proposal `image-group-evolution`) — the axis of /// `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`, so the /// interface and the report can be read side by side. - final class SwiftUIImageGroupDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -300,7 +301,7 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { /// axis): SwiftUI alone until 14.8, SwiftUICore joining it in 15.0. Every /// label is a version number, so the interface also spells each /// lifecycle one attribute can express as `@available(macOS, …)`. - final class SwiftUIImageGroupArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + final class SwiftUIImageGroupArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { ArchivedDyldCacheTests.cachePaths } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift index dffd7785..4d033d39 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift @@ -12,6 +12,7 @@ import SwiftSectionFixtureSupport @testable import SwiftInterface @_spi(Internals) @testable import SwiftSymbols @_spi(Internals) @testable import MachOCaches +import Semantic protocol SwiftInterfaceBuilderTests: SwiftInterfaceDumpTests { var builderConfiguration: SwiftInterfaceBuilderConfiguration { get } @@ -68,7 +69,7 @@ extension SwiftInterfaceBuilderTests { } enum SwiftInterfaceBuilderTestSuite { - class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { .AppKit } @@ -91,7 +92,7 @@ enum SwiftInterfaceBuilderTestSuite { /// The same image from an archived macOS cache, picked by version: point /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` /// that holds a cache. - class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { class var cacheVersion: String { "26.6" } @@ -115,7 +116,7 @@ enum SwiftInterfaceBuilderTestSuite { } } - class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @@ -131,7 +132,7 @@ enum SwiftInterfaceBuilderTestSuite { } } - class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, SwiftInterfaceBuilderTests, @unchecked Sendable { + class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift index d9661cbe..cd0d2c27 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift @@ -11,6 +11,7 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections final class SwiftDeclarationIndexerTests: MachOImageTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift index 1a30807c..edd2b785 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift @@ -2,6 +2,8 @@ import Foundation import MachOKit import SwiftSectionFixtureSupport @testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox /// Shared scaffolding for the `SwiftInterface`-level integration dumps. /// diff --git a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift index 8ab542be..14d880a5 100644 --- a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift +++ b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift @@ -8,6 +8,10 @@ import SwiftInterface import Testing import TypeIndexing @testable import SwiftSectionTestingSupport +import MachODependencies +import SwiftPrinting +import SwiftIndexing +import Semantic /// Maintainer-run end-to-end for the TypeIndexing provider (evolution /// proposal 0008): builds the fixture's interface with and without diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift index 4ff2ef24..4a4b4e12 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `AccessibleFunctionRecord`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift index 23aeeeca..8c2b636b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift @@ -71,7 +71,7 @@ final class CoroFunctionPointerTests: FixtureSuite, @unchecked Sendable { var description: String { "coro-function-pointer fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CoroFunctionPointerFixture-\(UUID().uuidString)") diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift index 4f8e6e02..96192651 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `GenericClassMetadataPattern`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift index c7f7529a..532f354d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `HeapMetadataHeaderPrefix`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift index 0bd74276..5fc601f1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `HeapMetadataHeader`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift index a3b7681d..e8a8acc9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `StoredClassMetadataBounds`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift index a1cae5a8..08af2172 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKit /// Fixture-based Suite for `EnumMetadata`. /// diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift index 93d5440a..d1016363 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKit /// Fixture-based Suite for `StructMetadata`. /// diff --git a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift index 64102905..a25f8fc9 100644 --- a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift @@ -9,6 +9,7 @@ import SwiftDeclarationRendering import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Verifies the reader-specialized `FieldLayoutRenderer`: /// diff --git a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift index d9ee4f55..b389a0b0 100644 --- a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift @@ -8,6 +8,7 @@ import MachOFoundation import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// The in-process nested field-offset expansion reads byte for byte the same /// with its per-metatype memo as without it (evolution proposal diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift index c97ba0bf..e9b9ca9a 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift @@ -88,7 +88,7 @@ struct OpaqueTypeArgumentDepthTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift index 3a43c19b..49fc772a 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift @@ -77,7 +77,7 @@ struct OpaqueTypeOrdinalTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueTypeOrdinalFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift index 99ba55f1..4c74bb7e 100644 --- a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift @@ -8,6 +8,7 @@ import MachOFoundation import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Regression coverage for the nested expanded-field-offset walk on a **cyclic** /// field graph. diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift index 731a345a..25f889d5 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift @@ -8,6 +8,7 @@ import MachOFoundation import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Verifies the **MachOImage** (runtime) enum-layout path end-to-end on the /// fixture: single-payload empty cases render their *exact* extra-inhabitant diff --git a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift index 8a8cfede..dcee45f1 100644 --- a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift +++ b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInspection import SwiftObjCInterop @testable import SwiftSectionTestingSupport +import Semantic +import SwiftSectionFixtureSupport /// The dump path's rendering of a class the source renamed for the /// Objective-C runtime (evolution proposal `objc-custom-class-name`): the diff --git a/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift b/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift index d2318ae4..b0523127 100644 --- a/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift +++ b/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import Demangling +import SwiftDeclarationRendering +import Semantic /// `dump` with `DemangleOptions.useExistentialAny` (evolution proposal /// `existential-any`): the field types swift-demangling prints spell diff --git a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift index b4371ed4..e9595822 100644 --- a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift @@ -8,6 +8,7 @@ import SwiftDeclarationRendering @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Dump-path coverage for the `// not exported` annotation (evolution /// proposal 0008), pinning the two false-positive classes the member-symbol diff --git a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift index ca505c8b..368bb438 100644 --- a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift +++ b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import SwiftDeclarationRendering +import Semantic /// The dump path's half of `GenericParameterDepthNamingTests`: the dumpers /// render a generic declaration's parameter clause through the same diff --git a/Tests/SwiftDumpTests/InitAccessorDumpTests.swift b/Tests/SwiftDumpTests/InitAccessorDumpTests.swift index 84c78e39..f07a9d25 100644 --- a/Tests/SwiftDumpTests/InitAccessorDumpTests.swift +++ b/Tests/SwiftDumpTests/InitAccessorDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftDeclarationRendering +import Semantic +import Demangling /// `dump` lists a property's SE-0400 init accessor among its type's variable /// symbols, with the address and export status every member symbol gets diff --git a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift index 7b8bbdcc..d73d4b1c 100644 --- a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift +++ b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic +import SwiftDeclarationRendering /// The dump declares a local type under the compiler's full name and lists /// the members its symbols attribute to it (evolution proposal diff --git a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift index 9e28b40a..475eb96c 100644 --- a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift +++ b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import Demangling +import Semantic +import SwiftDeclarationRendering /// `dump` with `DemangleOptions.useModuleSelectors` (evolution proposal /// `module-selectors`): the names swift-demangling prints follow the option, diff --git a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift index 52589d0e..29078a91 100644 --- a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift @@ -5,6 +5,8 @@ import MachOFoundation import SwiftDump import SwiftDeclarationRendering @testable import SwiftSectionTestingSupport +import Semantic +import SwiftSectionFixtureSupport /// The dump path's rendering of an `@objc @implementation` class (evolution /// proposal `objc-implementation-class-recognition`): everything the binary diff --git a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift index 5fd06e5d..be628600 100644 --- a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift @@ -9,6 +9,8 @@ import SwiftInspection import SwiftObjCInterop import SwiftThunkAnalysis @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic /// The dump path's rendering of the ObjC member facts (evolution proposals /// `objc-ancestor-override-recovery` and `objc-member-selector-recovery`): diff --git a/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift b/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift index 77417b07..ed62d930 100644 --- a/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift +++ b/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import Semantic +import SwiftDeclarationRendering +import Demangling /// `dump` names the macro that generated an `@Observable` class's members on /// its header line and keeps every member as the records have them diff --git a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift index bceca48a..fd9401d8 100644 --- a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift @@ -7,6 +7,8 @@ import SwiftDeclarationRendering import SwiftDump @_spi(Internals) import SwiftInspection import SwiftThunkAnalysis +import Demangling +import Semantic /// What the dump adds on top of the interface's spelling for an /// associated-type witness built from another module's opaque archetype @@ -38,7 +40,7 @@ struct OpaqueWitnessDumpAnnotationTests { let clientLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueWitnessDumpFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift index e805785e..e47df99b 100644 --- a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift +++ b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift @@ -6,6 +6,8 @@ import MachOFoundation @testable import SwiftDump @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftDeclarationRendering +import Semantic /// Issue #115: two top-level `private struct PrivateDoppelganger` declarations /// (one per fixture file) share their interface-printed name — the private diff --git a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift index b77ab749..fb57f022 100644 --- a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift +++ b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftDeclarationRendering +import Semantic +import Demangling /// A protocol's same-type or superclass requirement whose right-hand side is /// a composite type prints that type (evolution proposal diff --git a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift index 5fbc568b..4d5c553b 100644 --- a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift +++ b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import SwiftDeclarationRendering +import Semantic /// The dump of the declaration shapes Swift 6.4 introduced (evolution /// proposal `borrow-accessors-and-suppressed-associated-types`): a member diff --git a/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift b/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift index db949d9a..ced8d14b 100644 --- a/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift +++ b/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftObjCInterop @testable import SwiftSectionTestingSupport +import Semantic +import SwiftSectionFixtureSupport /// The dump of an `@objc` protocol declared in Swift (evolution proposal /// `swift-declared-objc-protocols`): each requirement as a Swift declaration diff --git a/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift index 24403904..7e7eadac 100644 --- a/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift +++ b/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift @@ -6,6 +6,8 @@ import MachOFoundation @testable import SwiftDump import SwiftDeclarationRendering @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic /// The dump path's listing of the members an image keeps only as their /// `@objc` thunk (evolution proposal `thunk-only-objc-members`): the diff --git a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift index ef5d6df4..5dd0b97f 100644 --- a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift +++ b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift @@ -7,6 +7,8 @@ import MachOFoundation import SwiftDeclarationRendering @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic /// Vtable slot attribution under identical code folding. /// @@ -58,7 +60,7 @@ struct VTableSlotAttributionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("VTableAttributionFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift b/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift index 3fe8db3c..cc348473 100644 --- a/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift +++ b/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift @@ -4,6 +4,7 @@ import MachOKit @testable import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing +import OrderedCollections /// A type declared inside `extension { … }` is filed under a /// synthetic extension of that C type, keyed by an `ExtensionName` whose @@ -67,7 +68,7 @@ struct CImportedExtensionKindTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CImportedExtensionKindFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift b/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift index 2f657790..d41176eb 100644 --- a/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift +++ b/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift @@ -7,6 +7,8 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @testable import SwiftSectionTestingSupport +import OrderedCollections +import SwiftSymbols /// A SE-0400 init accessor is one of its property's accessors (evolution /// proposal `init-accessor-recovery`): the index files its symbol with the diff --git a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift index 085ffa43..4efb778c 100644 --- a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift +++ b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import SwiftDeclaration @_spi(Support) import SwiftIndexing import SwiftInspection +import OrderedCollections /// The name a reader is shown of a type declared in a function or closure /// body, or of a type nested in one (evolution proposal diff --git a/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift b/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift index 5b3944be..f650c486 100644 --- a/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift +++ b/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift @@ -7,6 +7,7 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @testable import SwiftSectionTestingSupport +import OrderedCollections /// The declaration model of the `@objc` protocols a Swift module declares /// (evolution proposal `swift-declared-objc-protocols`): one diff --git a/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift b/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift index c5b49d6d..d2d06009 100644 --- a/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift @@ -8,6 +8,8 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftIndexing import SwiftInspection @testable import SwiftSectionTestingSupport +import SwiftSymbols +import OrderedCollections /// `TypeDefinition.observableMacroExpansion` sorts an `@Observable` class's /// stored `var`s into the storage of the properties the macro tracks and the diff --git a/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift b/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift index 53302a6a..199a7e33 100644 --- a/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift +++ b/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift @@ -8,6 +8,7 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftIndexing @testable import SwiftInspection @testable import SwiftSectionTestingSupport +import OrderedCollections /// `TypeDefinition.attachedMacros` recognizes a class `@Observable` expanded /// from its field records when the definition is built, before anything is diff --git a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift index 2d9133a1..f98052fa 100644 --- a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift +++ b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift @@ -7,6 +7,7 @@ import Demangling import SwiftDeclaration @_spi(Support) import SwiftIndexing import SwiftInspection +import OrderedCollections /// `privateDeclarations` reads a name's whole tree but for two parts: the /// signature of a function, closure, variable, subscript, initializer or diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index 62566069..e7d5409e 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -14,6 +14,7 @@ import OrderedCollections @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport @testable import SwiftDump +import Semantic // MARK: - Shared Setup diff --git a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift index 0ca9e8fb..e31edf1c 100644 --- a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift @@ -6,6 +6,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing +import OrderedCollections /// Two modules compiled on the fly, each carrying a class (a struct-only /// fixture dylib has no `__DATA` segment and MachOKit before 0.52.103 mis-walked @@ -88,7 +89,7 @@ enum WrappedPropertyFixture { let clientURL: URL } - static let compilationResult: Result = { + static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("WrappedPropertyFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift index 1f2ccdf7..54c10fd0 100644 --- a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift +++ b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift @@ -208,7 +208,7 @@ struct CImportedTypeIdentityFixtureTests { ("sdkRenamedTag", "So8_NSRangeV", "__C._NSRange"), ] - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CImportedTypeIdentityFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift index b07d8234..3962eeef 100644 --- a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift +++ b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOObjCSection @testable import SwiftInspection @testable import SwiftObjCInterop +import MachOKitExtensions private enum TwinSwiftUICaches { static let swiftUIPath = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" diff --git a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift index 26aeb13f..0f73a2c0 100644 --- a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift +++ b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift @@ -5,6 +5,7 @@ import MachOKit @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection +import Demangling // MARK: - Test Enum Definitions diff --git a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift index 1310c304..9d833df5 100644 --- a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift +++ b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift @@ -6,6 +6,8 @@ import Demangling @_spi(Internals) import SwiftSymbols @testable @_spi(Internals) import SwiftInspection @testable @_spi(Internals) import SwiftObjCInterop +import MachOKitExtensions +import MachOResolving /// A symbol's value is the binary's own claim about where something sits, and /// two indexes read the bytes there: `SymbolicManglingIndex` (the mangled name @@ -50,7 +52,7 @@ struct MalformedSymbolValueTests { var description: String { "malformed symbol value fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("MalformedSymbolValueFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift index 4700e05a..0c3773c1 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift @@ -170,7 +170,7 @@ struct SymbolicDemanglerFixedShapeExtractionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ObjCProtocolReferenceFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift b/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift index 4f639e97..d920edf3 100644 --- a/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift +++ b/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOFoundation +import Utilities /// Pins `concurrentMap(maximumConcurrency:_:)` (evolution proposal /// `large-stack-executor-and-cross-version-parallelism`), the windowed diff --git a/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift b/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift index 79100581..79fce5b0 100644 --- a/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift @@ -4,6 +4,7 @@ import MachOKit @testable import MachOSwiftSection @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface +import Semantic /// Evolution proposal `type-import-info-identity`: the conformance extensions /// the importer synthesizes for C-imported types render as ONE block per @@ -70,7 +71,7 @@ struct CImportedTypeConformanceInterfaceTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CImportedTypeConformanceFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift b/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift index b1065e79..b790b258 100644 --- a/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift @@ -9,6 +9,9 @@ import SwiftInterface import SwiftThunkAnalysis @_spi(Internals) import SwiftInspection @testable import SwiftSectionTestingSupport +import Semantic +import SwiftIndexing +import SwiftObjCInterop /// Swift classes without a class object on the interface path (evolution /// proposal `objc-classes-without-class-objects`): a generic class, or one diff --git a/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift b/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift index 2f3ec831..ef60a77a 100644 --- a/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift +++ b/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift @@ -13,6 +13,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// With `SwiftDeclarationPrintConfiguration.marksCommentStructure`, every /// definition of the SymbolTestsCore fixture separates to exactly its print diff --git a/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift b/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift index f1aa7af6..31441986 100644 --- a/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift +++ b/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift @@ -10,6 +10,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// The shapes RuntimeViewer draws its comment tags and folds from (evolution /// proposal `comment-structure`), read from the table a marked print of the diff --git a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift index 67bdce37..c9537bf4 100644 --- a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift +++ b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift @@ -68,7 +68,7 @@ struct ConditionalWitnessCommentStructureTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift b/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift index c1ae60d2..ffb493de 100644 --- a/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift +++ b/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift @@ -9,6 +9,7 @@ import Semantic @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// The protocol a conformance extension names is a type reference like any /// other, so its name must carry the semantic type the rest of the interface diff --git a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift index fc519210..19e2df44 100644 --- a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift +++ b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift @@ -7,6 +7,7 @@ import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface +import Semantic /// An associated-type witness built from a `some` result that lives in /// ANOTHER image — the shape SwiftUI's `SidebarListBody.CollectionViewBody.Body` @@ -48,7 +49,7 @@ struct CrossImageOpaqueReferenceTests { let clientLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CrossImageOpaqueFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift index a6c17d13..b4816ad6 100644 --- a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift @@ -10,6 +10,10 @@ import SwiftThunkAnalysis @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftObjCInterop @testable import SwiftSectionTestingSupport +import SwiftIndexing +import Semantic +import SwiftPrinting +import SwiftSectionFixtureSupport /// Classes a source renamed for the Objective-C runtime on the interface /// path (evolution proposal `objc-custom-class-name`): the attribute the diff --git a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift index 80124f91..479f102b 100644 --- a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift +++ b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift @@ -6,6 +6,8 @@ import MachOSwiftSection import SwiftDeclarationRendering import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic +import SwiftPrinting /// An on-the-fly fixture for class members whose only symbol is their method /// descriptor, compiled twice over: `.full` keeps every symbol, and @@ -81,7 +83,7 @@ enum DescriptorOnlyMemberFixture { } /// Compiled once per process. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/DiffFormatTests.swift b/Tests/SwiftInterfaceTests/DiffFormatTests.swift index 4d2c26c9..f110ad79 100644 --- a/Tests/SwiftInterfaceTests/DiffFormatTests.swift +++ b/Tests/SwiftInterfaceTests/DiffFormatTests.swift @@ -1,6 +1,7 @@ import Testing import Semantic @testable import SwiftInterface +import Foundation /// Builds a one-line ``DiffLine`` for the synthetic block fixtures below. private func line(_ marker: DiffMarker, _ content: SemanticString, indent: Int = 0) -> DiffLine { diff --git a/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift b/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift index ddab5b87..ed323770 100644 --- a/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift +++ b/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift @@ -67,7 +67,7 @@ struct DiffMemberIndentationTests { // `Swift.Error` spelled out: the `Semantic` import brings its own `Error` // type into scope, which would otherwise win the lookup. - private static let fixtureCompilationResult: Result<[URL], Swift.Error> = { + private static let fixtureCompilationResult: Result<[URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("DiffIndentFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift index 9bd4e262..98ebf6f7 100644 --- a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift +++ b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift @@ -10,6 +10,8 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic +import OrderedCollections /// The diff renderer's header contract: a declaration whose HEADER cannot be /// rendered must be dropped whole, never rendered as a body under a blank @@ -32,7 +34,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable override class var fileName: MachOFileName { .SymbolTestsCore } private func preparedBuilder( - eventHandlers: [SwiftIndexEvents.Handler] = [] + eventHandlers: [any SwiftIndexEvents.Handler] = [] ) async throws -> SwiftDiffableInterfaceBuilder { let unsafeMachOFile = machOFile let builder = SwiftDiffableInterfaceBuilder(eventHandlers: eventHandlers, in: unsafeMachOFile) diff --git a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift index f9d76473..e306a2aa 100644 --- a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift +++ b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift @@ -11,6 +11,8 @@ import SwiftInterface @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftPrinting +import Semantic /// An on-the-fly fixture compiled twice from one class: as a main executable, /// whose `__TEXT` sits at 0x100000000, and as a dylib, whose `__TEXT` sits at @@ -71,7 +73,7 @@ enum ExecutableImageFixture { } /// Compiled once per process. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift b/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift index 6c1f7fe2..eea61255 100644 --- a/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift @@ -4,6 +4,7 @@ import MachOKit @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// `SwiftDeclarationPrintConfiguration.usesExistentialAny`, on by default, /// spells existential types with the `any` keyword by the rules the compiler diff --git a/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift b/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift index 593983c4..072c559b 100644 --- a/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift +++ b/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift @@ -7,6 +7,8 @@ import MachOKit @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic +import SwiftIndexing /// End-to-end coverage for the `// not exported` annotation (evolution /// proposal 0008) on the `SymbolTestsCore` fixture — a library-evolution diff --git a/Tests/SwiftInterfaceTests/ExportStatusTests.swift b/Tests/SwiftInterfaceTests/ExportStatusTests.swift index 0234731f..88a514d9 100644 --- a/Tests/SwiftInterfaceTests/ExportStatusTests.swift +++ b/Tests/SwiftInterfaceTests/ExportStatusTests.swift @@ -7,6 +7,10 @@ import MachOKit @_spi(Support) @testable import SwiftIndexing @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKitExtensions +import OrderedCollections +import MachOResolving +import MachOSwiftSection /// `TypeDefinition.exportStatus` / `ProtocolDefinition.exportStatus` — the /// export fact carried on the declaration model (evolution proposal diff --git a/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift b/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift index 0e89c38d..4a2c343c 100644 --- a/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift @@ -7,6 +7,8 @@ import MachOKit @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic +import SwiftIndexing /// End-to-end coverage for the exported-only filter (evolution proposal /// `exported-only-interface`) on the `SymbolTestsCore` fixture — a diff --git a/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift b/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift index 71beeff6..93b7f17c 100644 --- a/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift +++ b/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift @@ -9,6 +9,7 @@ import SwiftDeclaration @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface import SwiftSectionTestingSupport +import OrderedCollections /// The exported-only filter (evolution proposal /// `exported-only-interface`) over `internal` declarations, on the diff --git a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift index a9588074..7b739fbe 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift @@ -9,6 +9,8 @@ import OrderedCollections @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Demangling +import Semantic /// Coverage for the extension-container unification (evolution proposal 0007): /// same-identity bucket merging, protocol attachment (a protocol's extension diff --git a/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift index 009cfaf0..1931b617 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift @@ -7,6 +7,12 @@ import MachOKit @_spi(Support) @testable import SwiftIndexing import SwiftInterface @testable import SwiftSectionTestingSupport +import MachOResolving +import SwiftPrinting +import MachOKitExtensions +import Semantic +import MachOSwiftSection +import OrderedCollections /// The export verdict of declarations in extensions of another module's /// types, in images that keep no symbol at a non-exported descriptor diff --git a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift index 97ea327d..ad5bb092 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// A type declared in an extension of another module's type is parented on an /// extension context descriptor, so every name for it — the offline one from @@ -34,7 +35,7 @@ struct ExtensionContextTypeNameTests { var description: String { "extension-context fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ExtensionContextFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift index a2b817fb..494fcc7e 100644 --- a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift +++ b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift @@ -8,6 +8,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Regression coverage for the identical-code-folding false positive in the /// `final` recovery (evolution proposal 0006), pinned against Xcode's real diff --git a/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift index 05b3888e..87859426 100644 --- a/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift @@ -8,6 +8,9 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections +import Semantic +import Demangling /// End-to-end coverage for the `final` keyword recovery and the lazy-var /// accessor-type correction (evolution proposal 0006), pinned against the diff --git a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift index 1b51a291..a06685e3 100644 --- a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift +++ b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import SwiftSectionTestingSupport +import Semantic /// A generic parameter's printed name encodes its depth (`A1` is depth 1, /// index 0), and a depth counts only the contexts that declare parameters. diff --git a/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift b/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift index 89ba8ae5..0ae17453 100644 --- a/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift +++ b/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift @@ -4,6 +4,7 @@ import MachOKit import SwiftDiffing import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// An evolution whose versions are groups of images (evolution proposal /// `image-group-evolution`), over `ImageGroupFixture`: one module split from diff --git a/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift b/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift index c98dfa33..612056de 100644 --- a/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift @@ -9,6 +9,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @testable import SwiftSectionTestingSupport +import OrderedCollections /// The interface opens a property's accessor block with its SE-0400 `init` /// (evolution proposal `init-accessor-recovery`): `@storageRestrictions(initializes: _x) init` diff --git a/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift b/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift index cc726eb2..45007573 100644 --- a/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift +++ b/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift @@ -6,6 +6,7 @@ import Semantic @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftIndexing /// Coverage for the interface header block (evolution proposal 0008): /// pure-value rendering (line composition, per-field omission, the diff --git a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift index 09aade77..5cecc0c0 100644 --- a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift +++ b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOKitExtensions @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// Regression tests for binaries carrying the legacy `LC_DYLD_INFO(_ONLY)` /// opcode-based fixups (deployment target < macOS 12 / iOS 16, e.g. every @@ -37,7 +38,7 @@ struct LegacyDyldInfoBindTests { }() } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("LegacyDyldInfoBindFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift index ff2b490b..55c8fb82 100644 --- a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift @@ -9,6 +9,7 @@ import SwiftPrinting @_spi(Support) import SwiftInterface import Semantic @testable import SwiftSectionTestingSupport +import OrderedCollections /// Local types on the indexing and interface paths (evolution proposal /// `local-type-context-names`). Named after their method, two methods' diff --git a/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift b/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift index 8b2c743f..206832d4 100644 --- a/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift +++ b/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift @@ -7,6 +7,7 @@ import SwiftDiffing import SwiftInterface @_spi(Internals) import SwiftSymbols @testable import SwiftSectionTestingSupport +import Semantic /// A member an image declares on a type another image defines, with no /// extension context in its mangling (evolution proposal diff --git a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift index f3e5dda2..741acf3b 100644 --- a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift @@ -4,6 +4,7 @@ import MachOKit @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// `SwiftDeclarationPrintConfiguration.usesModuleSelectors` qualifies the /// interface's names with SE-0491 module selectors, by the rules the Swift diff --git a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift index 7b6e9c77..ddc4ea8a 100644 --- a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift +++ b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift @@ -14,6 +14,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// With `SwiftDeclarationPrintConfiguration.marksNestedDefinitions`, every /// nested type and protocol taken out of its parent's print — diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 55290c78..a1702ae6 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -9,6 +9,8 @@ import SwiftObjCInterop import Semantic @_spi(Internals) import SwiftSymbols @testable import SwiftSectionTestingSupport +import SwiftPrinting +import SwiftSectionFixtureSupport /// `@objc @implementation` recognition on the interface path (evolution /// proposal `objc-implementation-class-recognition`), over the on-the-fly diff --git a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift index 9d743b28..2f3873ec 100644 --- a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift @@ -13,6 +13,11 @@ import SwiftInspection import SwiftObjCInterop import SwiftThunkAnalysis @testable import SwiftSectionTestingSupport +import MachOObjCSection +import SwiftPrinting +import Semantic +import OrderedCollections +import SwiftSectionFixtureSupport /// The ObjC member recovery over the shared `@objc @implementation` fixture /// (evolution proposals `objc-ancestor-override-recovery` and diff --git a/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift b/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift index a5102032..9d80b3be 100644 --- a/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift @@ -10,6 +10,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import OrderedCollections /// The interface folds what `@Observable` generated (evolution proposal /// `observable-macro-folding`): by default a class the macro expanded reads diff --git a/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift b/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift index 06d14a14..ec6003c7 100644 --- a/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift @@ -4,6 +4,9 @@ import MachOKit @testable import SwiftSectionTestingSupport @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection +import Semantic +import SwiftIndexing +import SwiftPrinting /// MachOImage-side counterpart of the opaque-attribution tests: the /// in-process reader resolves cross-image protocol descriptors (the third diff --git a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift index 79f75739..b7387fbd 100644 --- a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// The spelling of an opaque result type's constraints beyond the plain /// `some Protocol` shape the fixture covers. @@ -42,7 +43,7 @@ struct OpaqueConstraintRenderingTests { var description: String { "opaque-constraint fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueConstraintFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift index 17e1d6fd..18af29f3 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface +import Semantic /// The depth of an opaque result's parameters: the innermost depth of the /// descriptor's own layout, counted over every context above it that adds @@ -150,7 +151,7 @@ struct OpaqueParameterDepthTests { /// core image exports. private static let inProcessReaderExpectedInterfaceLine = "var foreignValues: some Swift.Sequence {" - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterDepthFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift index a495e47c..de850352 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// `SwiftInterfaceBuilderOpaqueTypeProvider` finds an opaque result's /// constraint at the depth of the opaque parameters, which it counts from the @@ -60,7 +61,7 @@ struct OpaqueParameterInMultiDepthExtensionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterExtensionDepthFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift index 35f86001..0407aede 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// An opaque parameter that carries no runtime-visible protocol requirement. /// @@ -43,7 +44,7 @@ struct OpaqueParameterWithoutProtocolRequirementTests { var description: String { "opaque-parameter fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift index d8603bd6..57405104 100644 --- a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift +++ b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift @@ -9,6 +9,8 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections +import Semantic /// A definition that cannot be printed must be **reported**, not printed away. /// diff --git a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift index 1be05d8c..dfbeaeef 100644 --- a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift @@ -7,6 +7,7 @@ import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface +import Semantic /// An associated-type witness that is a *member* of another module's opaque /// archetype — `(↻τ.Element)` in the generics book's notation, spelled @@ -49,7 +50,7 @@ struct ProjectedOpaqueMemberWitnessTests { let clientInterfaceText: String } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ProjectedOpaqueMemberFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift index 28eaa5bd..ea8b3ee5 100644 --- a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift +++ b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// `@Wrapper var x: Int` makes the compiler synthesize a stored `_x` of the /// wrapper type and, when the wrapper projects, a computed `$x`. The source @@ -32,7 +33,7 @@ struct PropertyWrapperSynthesizedMemberTests { var description: String { "property-wrapper fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("PropertyWrapperFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift index 771e1d85..3503dae6 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic /// A protocol declared in an extension of another module's type prints its /// default-implementation extensions in the interface's top-level block for @@ -56,7 +57,7 @@ struct ProtocolInExtensionDefaultWitnessTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ProtocolInExtensionDefaultWitnessFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift index 117413a0..9d704a08 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -9,6 +9,7 @@ import Demangling @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface +import OrderedCollections /// A protocol declared inside an extension (SE-0404) — `extension Host { /// protocol Delegate {…} }` — has no parent type definition, only an @@ -39,7 +40,7 @@ struct ProtocolInExtensionTests { var description: String { "protocol-in-extension fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ProtocolInExtensionFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift index 938a37c4..cae16e1a 100644 --- a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift @@ -7,6 +7,10 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import OrderedCollections +import Demangling +import SwiftDeclaration +import Semantic /// How the interface prints a protocol's requirement signature (evolution /// proposal `protocol-requirement-placement`): every requirement in the diff --git a/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift b/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift index 60f71996..dd9206df 100644 --- a/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftInterface +import Semantic /// Where the archived-cache-gated suite below finds its cache (see the /// SwiftLayout suite of the same shape for why this is a separate type). diff --git a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift index 08a31630..53c6bb6b 100644 --- a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift @@ -8,6 +8,7 @@ import SwiftInterface import struct Semantic.SemanticString import struct Semantic.FrozenSemanticString import SwiftSectionTestingSupport +import SwiftPrinting /// `@_rawLayout` is an experimental feature any module can enable, not a /// standard-library privilege, and only its `like:` spelling leaves a field @@ -42,7 +43,7 @@ struct RawLayoutBuiltinDescriptorRenderingTests { var description: String { "raw-layout fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("RawLayoutRenderingFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift index 258e70fc..416eaf3d 100644 --- a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift @@ -9,6 +9,7 @@ import SwiftPrinting import struct Semantic.SemanticString import struct Semantic.FrozenSemanticString import SwiftSectionTestingSupport +import SwiftIndexing /// The interface side of wrapped-property recovery for the two cases the /// same-image suite (`PropertyWrapperSynthesizedMemberTests`) cannot show: @@ -72,7 +73,7 @@ struct StrippedWrappedPropertyRenderingTests { } """ - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("StrippedWrappedPropertyFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift b/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift index b9b5423b..03d85287 100644 --- a/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface import Semantic @testable import SwiftSectionTestingSupport +import SwiftIndexing +import SwiftPrinting /// The `@objc` protocols a Swift module declares, on the interface path /// (evolution proposal `swift-declared-objc-protocols`): they have no diff --git a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift index 725dabe4..ac4c073e 100644 --- a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift @@ -80,7 +80,7 @@ struct SwiftEvolutionInterfaceBuilderTests { // `Swift.Error` spelled out: the `Semantic` import brings its own `Error` // type into scope, which would otherwise win the lookup. - private static let fixtureCompilationResult: Result<[URL], Swift.Error> = { + private static let fixtureCompilationResult: Result<[URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("EvolutionInterfaceFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift b/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift index cdc194bc..d76dedaa 100644 --- a/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift +++ b/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift @@ -10,6 +10,8 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Demangling +import OrderedCollections /// A `DemangledSymbol` stored in the declaration model must not keep the /// shared per-image symbol table alive. diff --git a/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift b/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift index beb9314b..9a0e9457 100644 --- a/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift +++ b/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift @@ -12,6 +12,7 @@ import Dependencies @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport @testable import SwiftDump +import Semantic @Suite(.serialized) final class STCoreE2ETests: MachOFileTests, @unchecked Sendable { diff --git a/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift b/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift index e247f83c..e07b3532 100644 --- a/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift +++ b/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface @_spi(Internals) import SwiftSymbols @testable import SwiftSectionTestingSupport +import Semantic +import SwiftPrinting /// Members whose implementation symbol the optimizer deleted while another of /// their entry points survived (evolution proposal `thunk-only-objc-members`): diff --git a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift index 30c7a4e3..d7d24af3 100644 --- a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift +++ b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift @@ -4,6 +4,7 @@ import MachOKit import SwiftDiffing import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// Telling a declaration a version cannot show from one that is gone /// (evolution proposal `evolution-unobservable-presence`), over diff --git a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift index 6436c530..583c9bac 100644 --- a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift +++ b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift @@ -10,6 +10,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// A marked print (`SwiftDeclarationPrintConfiguration.marksOptionalContent`), /// projected to a configuration, reads byte for byte as printing with that diff --git a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift index 06ad5da9..04a460d6 100644 --- a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift @@ -7,6 +7,7 @@ import SwiftPrinting import SwiftInterface import SwiftDeclarationRendering @testable import SwiftSectionTestingSupport +import Semantic /// The fixture's interface printed through a host's wrapper — a type that /// forwards every read to a `MachOFile` or an in-process `MachOImage`, as diff --git a/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift b/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift index 4c981e94..adf4e54f 100644 --- a/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift +++ b/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift @@ -3,6 +3,7 @@ import MachOKit import MachOSwiftSection import SwiftLayout import Testing +import MachODependencies /// Real compiler-emitted records, independent of the shared SymbolTestsCore /// binary. The source layouts below are the expected values, not a snapshot of diff --git a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift index 3fe47be7..2041f93b 100644 --- a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift +++ b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift @@ -78,7 +78,7 @@ struct NestedFieldOffsetOpaqueWitnessTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift index 92e3c043..64667b2e 100644 --- a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift @@ -62,7 +62,7 @@ enum RawLayoutBuiltinDescriptorFixture { } """ - static let compilationResult: Result = { + static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("RawLayoutLayoutFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift b/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift index d8620d74..326b2592 100644 --- a/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift +++ b/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift @@ -7,6 +7,7 @@ import MachOFoundation @testable import SwiftLayout @testable import SwiftSectionTestingSupport import Demangling +import SwiftStdlibToolbox /// Validates concrete same-type pinning: a generic parameter pinned to a /// concrete type by a **constrained extension** (`extension Foo where Value == diff --git a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift index 2e4a8b29..5a2e3fed 100644 --- a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift +++ b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift @@ -9,6 +9,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftPrinting @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Printing the SymbolTestsCore fixture's definitions from several tasks at /// once reads byte for byte as printing them one after another (evolution diff --git a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift index 731524a9..b304ca67 100644 --- a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift +++ b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift @@ -8,6 +8,8 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftDump +import Semantic +import SwiftDeclarationRendering // MARK: - In-process fixture diff --git a/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift b/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift index 3ae95af1..8a27500d 100644 --- a/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift +++ b/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift @@ -1,6 +1,7 @@ @_spi(Support) @testable import SwiftPrinting import Demangling import Testing +import Semantic /// An initializer is failable when ITS OWN result is `Optional` — not /// when an Optional appears somewhere else in its signature. diff --git a/Tests/SwiftPrintingTests/NodeKindParityTests.swift b/Tests/SwiftPrintingTests/NodeKindParityTests.swift index 5b6efad2..9697693e 100644 --- a/Tests/SwiftPrintingTests/NodeKindParityTests.swift +++ b/Tests/SwiftPrintingTests/NodeKindParityTests.swift @@ -6,6 +6,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Internals) import SwiftInspection +import SwiftSectionFixtureSupport +import Semantic // MARK: - Shared survey diff --git a/Tests/SwiftPrintingTests/NodePrinterTests.swift b/Tests/SwiftPrintingTests/NodePrinterTests.swift index 246c9832..8873e1cf 100644 --- a/Tests/SwiftPrintingTests/NodePrinterTests.swift +++ b/Tests/SwiftPrintingTests/NodePrinterTests.swift @@ -12,6 +12,7 @@ import SwiftSectionFixtureSupport @testable import SwiftDump @testable import SwiftInterface @testable @_spi(Internals) import SwiftInspection +import Semantic // MARK: - Unit Tests (Self-contained, no external dependencies) diff --git a/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift b/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift index 5ba0bc53..940bae32 100644 --- a/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift +++ b/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift @@ -2,6 +2,7 @@ import Foundation import Demangling import Testing +import Semantic /// Pins the `each` / `repeat` spelling of parameter packs. /// diff --git a/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift b/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift index ea295f81..adbd7b0f 100644 --- a/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift +++ b/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift @@ -1,6 +1,7 @@ @_spi(Support) @testable import SwiftPrinting import Demangling import Testing +import Semantic /// A `NodePrinterTarget` that records every call the printers make. /// diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift index f6c82797..8fe6f83e 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift @@ -7,6 +7,8 @@ import SwiftSectionFixtureSupport import SwiftInspection import SwiftDeclarationRendering @testable @_spi(Support) import SwiftPrivateDiscriminators +import OrderedCollections +import SwiftDeclaration /// An image's private discriminators, recovered from candidates the image's /// own names make (evolution proposal `private-declarations`). diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift index 706959d3..8373139c 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift @@ -5,6 +5,8 @@ import SwiftSectionFixtureSupport @_spi(Support) import SwiftIndexing import SwiftInspection @_spi(Support) import SwiftPrivateDiscriminators +import OrderedCollections +import SwiftDeclaration /// Private discriminators of the running system's own images, read out of its /// dyld shared cache (evolution proposal `private-declarations`). diff --git a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift index 437d22f8..1a885b50 100644 --- a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift @@ -13,7 +13,7 @@ struct CommandLineErrorTranslationTests { @Test("A fat binary without -a names the option, and the slices") func fatBinary() { let translated = CommandLineErrorTranslation.translated(MachOSourceError.fatBinaryRequiresArchitecture(availableArchitectures: ["arm64", "x86_64"])) - #expect((translated as? LocalizedError)?.errorDescription == "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). Available architectures: arm64, x86_64") + #expect((translated as? (any LocalizedError))?.errorDescription == "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). Available architectures: arm64, x86_64") } @Test("The other loading errors keep their historical wording", arguments: [ @@ -21,7 +21,7 @@ struct CommandLineErrorTranslationTests { (.dyldSharedCacheImageNotFound(.name("Foundation")), "The specified image was not found in the dyld shared cache."), ]) func loadingErrors(error: MachOSourceError, expectedDescription: String) { - #expect((CommandLineErrorTranslation.translated(error) as? LocalizedError)?.errorDescription == expectedDescription) + #expect((CommandLineErrorTranslation.translated(error) as? (any LocalizedError))?.errorDescription == expectedDescription) } @Test("A snapshot document given to diff --interface is a usage error in diff's words") diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index 6e16f97a..f582b006 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -4,6 +4,9 @@ import ArgumentParser import MachOFoundation import SwiftSectionKit @testable import swift_section +import SwiftOutputTransformer +import Demangling +import SwiftPrinting /// The wrapper's one job besides wording and streams: turning flags into the /// library request. A flag that stops reaching its field produces a diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift index bbdb2d2e..d8308b7f 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift @@ -2,6 +2,7 @@ import ArgumentParser import Foundation import Testing @testable import swift_section +import SwiftSectionKit /// Option parsing for the API commands introduced by proposal 0006 /// (`snapshot` / `diff` / `evolution`). Same rationale as the dump/interface diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift index 4044e134..5f2b58a4 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift @@ -4,6 +4,7 @@ import Foundation import ObjCDeclarationRendering import ObjCOutputTransformer @testable import swift_section +import SwiftSectionKit /// Option parsing is the CLI's contract with its users: a flag that silently /// stops reaching the library, or one that lands on the wrong switch, produces diff --git a/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift b/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift index 3cefea1f..747a4fd0 100644 --- a/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift +++ b/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift @@ -7,6 +7,7 @@ import SwiftDeclarationRendering import SwiftPrinting import SwiftSectionKit @testable import swift_section +import Demangling /// Unit tests for the `swift-section` comment-template command-line surface: /// how a template value resolves (built-in name vs literal template), how the diff --git a/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift index a9bedbbb..52cc7d7d 100644 --- a/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift +++ b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift @@ -3,6 +3,8 @@ import Testing import OutputTransformer import SwiftOutputTransformer import SwiftSectionKit +import SwiftPrinting +import Semantic /// `dump` and `interface` against the SymbolTestsCore fixture: which sections /// are read and how a failure surfaces, where the product goes, and the diff --git a/Tests/SwiftSectionKitTests/MachOSourceTests.swift b/Tests/SwiftSectionKitTests/MachOSourceTests.swift index 7eb82dfb..f1d56467 100644 --- a/Tests/SwiftSectionKitTests/MachOSourceTests.swift +++ b/Tests/SwiftSectionKitTests/MachOSourceTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import SwiftSectionKit +import MachOKit /// `MachOSource.load()` is the one loader every request shares; these pin the /// fat-binary affordance and the cache-image lookup it centralizes. diff --git a/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift b/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift index ff130f8e..05628f6f 100644 --- a/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift +++ b/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift @@ -1,5 +1,6 @@ import Foundation import SwiftSectionKit +import Semantic /// A `SwiftSectionOutput` that also takes the declarations `dump` and /// `objc dump` name, keeping every product piece beside the declaration it diff --git a/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift b/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift index dd39701a..32aaf44e 100644 --- a/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift +++ b/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift @@ -1,6 +1,7 @@ import Foundation import SwiftDeclaration import SwiftSectionKit +import Semantic /// A `SwiftSectionOutput` that keeps everything it is handed, in order. /// diff --git a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift index 13b9f703..8bfdf022 100644 --- a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift +++ b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift @@ -9,6 +9,7 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// `IndexerConformanceProvider` builds its class hierarchy on a large stack. /// diff --git a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift index e6a70a43..92fa8be7 100644 --- a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift @@ -16,6 +16,8 @@ import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection @testable import Demangling import OrderedCollections +import Semantic +import SwiftDeclarationRendering @Suite(.serialized) struct GenericSpecializationTests { diff --git a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift index 798d86cc..921dc6b6 100644 --- a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift +++ b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift @@ -11,6 +11,7 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport @_spi(Internals) import SwiftInspection +import Semantic // MARK: - Pure helper unit tests (no fixture) diff --git a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift index e9304ca5..99fd7caf 100644 --- a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift @@ -6,6 +6,8 @@ import Testing import MachOKit @testable import MachOSwiftSection import SwiftSectionTestingSupport +import OrderedCollections +import Demangling /// A base-class requirement on an Objective-C class, checked offline /// (evolution proposal `offline-generic-specialization`). @@ -51,7 +53,7 @@ struct OfflineObjectiveCBaseClassTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift index afab5025..cdc3aee0 100644 --- a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift @@ -8,6 +8,9 @@ import MachOKit @testable import MachOSwiftSection import SwiftSectionTestingSupport import SwiftDeclarationRendering +import MachODependencies +import Semantic +import OrderedCollections /// An archived iOS simulator cache: the dependency closure an iOS simulator /// binary is printed against here. Machine-specific, hence the suite's @@ -55,7 +58,7 @@ struct OfflineProjectionDependencyResolutionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift index e02f204a..b612a225 100644 --- a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift @@ -9,6 +9,7 @@ import Demangling @testable import MachOSwiftSection import SwiftSectionTestingSupport import SwiftDeclarationRendering +import Semantic /// One instantiation, specialized and printed both ways, must read the same /// byte for byte (evolution proposal `offline-generic-specialization`): the diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift index 814b6430..122f47c0 100644 --- a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift @@ -8,6 +8,7 @@ import Demangling @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftSectionTestingSupport +import OrderedCollections /// A host type with no conformance any indexed image records. private struct HostUnmarked { diff --git a/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift b/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift index a4ba5bfe..9700f877 100644 --- a/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift +++ b/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift @@ -7,6 +7,7 @@ import Testing import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport +import Semantic // MARK: - Fixtures // diff --git a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift index 69d70734..bc64d6b6 100644 --- a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift +++ b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift @@ -9,6 +9,7 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// `IndexerConformanceProvider`'s subclass map must not lose a class silently. /// @@ -29,7 +30,7 @@ final class SubclassMapMaterializationFailureTests: MachOFileTests, @unchecked S override class var fileName: MachOFileName { .SymbolTestsCore } private func preparedIndexer( - eventHandlers: [SwiftIndexEvents.Handler] = [] + eventHandlers: [any SwiftIndexEvents.Handler] = [] ) async throws -> SwiftDeclarationIndexer { let unsafeMachOFile = machOFile let indexer = SwiftDeclarationIndexer(eventHandlers: eventHandlers, in: unsafeMachOFile) diff --git a/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift b/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift index a6fe31aa..da8e5aac 100644 --- a/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift +++ b/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift @@ -6,6 +6,7 @@ import Testing @_spi(Internals) import MachOCaches @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKit /// Fixture-based coverage for the export facts (evolution proposal 0008): /// `isExported(name:in:)` answering the export-trie membership FACT, and diff --git a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift index 75056dae..1d083a4f 100644 --- a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift @@ -7,6 +7,7 @@ import MachOResolving @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Pins when a symbol index demangles its names (evolution proposal /// `machofile-performance`): the storage's first stage — the symbol table, diff --git a/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift index 530995e8..ee696f3a 100644 --- a/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift @@ -7,6 +7,7 @@ import Testing @_spi(Internals) import MachOSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Fixture-based unit coverage for `SwiftSymbolIndexStore` against the /// `SymbolTestsCore` framework (self-built fixture, no external Xcode diff --git a/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift b/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift index 48a94f19..1bdcea6d 100644 --- a/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift @@ -6,6 +6,7 @@ import MachOKit @_spi(Internals) import MachOSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOResolving /// The collection layer of evolution proposal `symbolic-mangling-symbol-index`: /// the build sweep gathers every `_symbolic ` / `_default assoc type ` symbol diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift index 10865c71..19ad06dc 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift @@ -69,7 +69,7 @@ struct AccessorThunkTypeInGenericExtensionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("AccessorThunkGenericExtensionFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift index 94ce47b0..0b329d1e 100644 --- a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift +++ b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift @@ -48,7 +48,7 @@ struct MergedAccessorFixtureTests { let strippedLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("MergedAccessorProbeFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift index 91c9c1ab..8eac51b2 100644 --- a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift +++ b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift @@ -10,6 +10,7 @@ import Demangling import SwiftDeclarationRendering import SwiftThunkAnalysis import SwiftDump +import Semantic /// The point of the whole module: an associated-type witness that rendered as /// a bare address renders as a type once the thunk is read — and, since the diff --git a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift index ac4f0b19..bf0de23c 100644 --- a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift @@ -10,6 +10,7 @@ import Demangling import SwiftDeclarationRendering import SwiftThunkAnalysis import SwiftDump +import Semantic /// Where the simulator-runtime-gated suites below find their binaries. /// diff --git a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift index fcc10e2c..960906dd 100644 --- a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift @@ -45,7 +45,7 @@ struct StandaloneFileThunkResolutionTests { /// The compiled dylib, placed under a fake system root at its own install /// name so the file's location also exercises search-path inference. - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ThunkProbeFixture-\(UUID().uuidString)") @@ -107,7 +107,7 @@ struct StandaloneFileThunkResolutionTests { /// `__swift_instantiateConcreteTypeFromMangledNameV2`, found by its local /// symbol — whose value is an address, which a dylib's `__TEXT` at 0 had /// let pass for a file offset. - private static let executableCompilationResult: Result = { + private static let executableCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ThunkProbeExecutableFixture-\(UUID().uuidString)") From 0b4340d4c698f8f3f8938aabff05984bf906b4e5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:41:22 +0800 Subject: [PATCH 020/175] build: enable ExistentialAny, MemberImportVisibility and InferIsolatedConformances on every Swift target One loop at the end of the manifest appends the three settings to every target that is not a system, binary or plugin target, so a new target gets them too. --- Package.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Package.swift b/Package.swift index 3d9959c9..d516e29c 100644 --- a/Package.swift +++ b/Package.swift @@ -1547,6 +1547,23 @@ extension SwiftSetting { static let immutableWeakCaptures: Self = .enableUpcomingFeature("ImmutableWeakCaptures") // SE-0481, Swift 6.2, SwiftPM 6.2+ } +// MARK: - Upcoming features + +// Every Swift target adopts three upcoming features that Swift 7 turns on +// (proposal swift6-mode-and-upcoming-features, shared with the other MachO +// packages). The loop runs before the Tuist block so a target Tuist reshapes +// already carries them. The other three settings above stay unused: they +// change run-time behavior or every import, and were measured and declined. +let upcomingFeatureSettings: [SwiftSetting] = [ + .existentialAny, + .memberImportVisibility, + .inferIsolatedConformances, +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} + // MARK: - Tuist development workspace // MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md) From 6db3711b41c5acabd3a521b9015302f5926da22d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:41:28 +0800 Subject: [PATCH 021/175] docs: propose sharing the generic test support with MachOKitExtensions --- Documentations/Evolutions/README.md | 1 + .../draft-shared-macho-testing-support.html | 390 ++++++++++++++++++ .../draft-shared-macho-testing-support.md | 305 ++++++++++++++ Documentations/README.md | 1 + 4 files changed, 697 insertions(+) create mode 100644 Documentations/Evolutions/draft-shared-macho-testing-support.html create mode 100644 Documentations/Evolutions/draft-shared-macho-testing-support.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index bbda5f56..eae655f1 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -109,6 +109,7 @@ | [0097](0097-offline-cross-references-and-symbolication.md) | 交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | | draft | [SwiftDeclaration 的目录分成公开模型与索引代码两块](draft-swift-declaration-model-indexing-layout.md) | In Progress | | draft | [SwiftDeclaration 的类型名按角色统一后缀](draft-swift-declaration-type-naming.md) | In Progress | +| draft | [测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport](draft-shared-macho-testing-support.md) | Accepted | | [0098](0098-move-cross-reference-layers.md) | 交叉引用的核心层与 ObjC 层迁出本库,进 MachOKitExtensions 与 MachOObjCSection(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.html b/Documentations/Evolutions/draft-shared-macho-testing-support.html new file mode 100644 index 00000000..24f7327f --- /dev/null +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.html @@ -0,0 +1,390 @@ + + + + + + +Draft - 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport + + + + +
+
+

MachOSwiftSectionEvolutionsDraft

+

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

+
+
状态
Accepted
+
最后更新
2026-11-20
+
项目类型
库
+
原文
draft-shared-macho-testing-support.md
+
+
+
+
+
+

摘要

+

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

+
+ +
+

要你定

+

已批准(Accepted)。实现等 MachOKitExtensions 的 C++ 类恢复收尾(3.1.0)之后开始。

+
+ +
+

架构图

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

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

+ +

一个夹具测试的调用链

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

改动地图

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

提议方案

+
  1. MKE 新增两个 product(3.2.0):
    • MachOFixtureSupport(Sources/MachOFixtureSupport,不 import Testing):DyldSharedCachePath、MachOImageName / MachOFileName / XcodeMachOFileName(可扩展的 struct)、打开 cache 与镜像的扩展、hostSlice(of:)、取进程内镜像(按锚点地址 dladdr、按名字)、「cache 里的文件与进程内同一镜像」成对返回、FixtureCompiler(clang 与 swiftc,同一份源码与参数只编一次,进程结束时清理临时目录)、ForwardingReader、TestActor、ProcessMemory、.print()。
    • MachOTestingSupport(Sources/MachOTestingSupport,import Testing,依赖前者与 MachOReading):ExclusiveImageAccess、MachOFileTests、MachOImageTests、DyldCacheTests、XcodeMachOFileTests,以及新的 MachOFixtureTests。
  2. 测试基类原样搬:保留「继承基类拿到镜像」的写法,只改访问级别(open / public)与上面列出的必要改动。改成 Swift Testing trait 的写法以后另写提案。
  3. **MachOFixtureTests:不绑定夹具的基类**。子类用一个 MachOFixture 值说明夹具从哪来(磁盘路径,或进程里某个锚点地址所在的镜像,以及是否要 dlopen);基类据此建出 machOFile、machOImage 与 fileContext、imageContext、inProcessContext,提供 acrossAllReaders、acrossAllContexts、usingInProcessOnly,签名与本包现在的一致。
  4. 本机 cache 统一为进程共用:DyldSharedCachePath.current 与 DyldCacheTests 都经 FullDyldCache.cachedHost / DyldCache.host 的 URL,不写死路径;确实需要新实例的测试显式开一份(DyldCache(path:) 照旧可用)。
  5. 跨读取器统一用闭包式:MKE 约 25 个 @Test(arguments: Reader.allCases) 的测试改写成 MachOFixtureTests 子类里的 acrossAllReaders,比对两种读取器的结果相等后再断言。
  6. MKE 自己的重复辅助全部换成共享版本(动机一节的表)。
  7. 本包随后改依赖:两个 support target 依赖 MKE 的新 product,删掉搬走的文件;MachOFileName / MachOImageName 的 SymbolTests 条目改为对 MKE struct 的 extension;ExclusiveImageAccess 保留一个按本包镜像名的便捷初始化;MachOSwiftSectionFixtureTests 改成 MachOFixtureTests 的子类;17 个 Swift 夹具改用 FixtureCompiler;DyldCache(path: .current) 的 25 处改为共用实例后,逐个复查依赖新实例的测试。
  8. 发版顺序:MKE 先收尾 C++ 类恢复发 3.1.0;本提案的 MKE 部分从收尾后的 main 切分支,发 3.2.0;本包在 3.2.0 发布后改依赖(之前用 USING_LOCAL_DEPENDENCIES=1 本地验证)。
+

非目标

+
  • 把测试基类改成 Swift Testing trait 的写法。
  • 搬 Swift 专用的支持代码(夹具内容、baseline、coverage、快照对比、SymbolTestsCore 相关)。
  • 搬测试本身(CrossReferenceAnalysisTests 等依赖本包与 MachOObjCSection 的模块)。
  • 统一两个包的 ForwardingMachOReader / ForwardingReader:协议层级不同,本包那份保留。
  • MachOObjCSection、MachOKitUI 等其他仓库的测试改用新 product:各自另议。
  • 给 MKE 加 CI(MKE 0003 记下的后续项,另写提案)。
+
+ +
+

详细设计

+
+ 公开 API 草图 +
+
// MachOFixtureSupport
+public struct DyldSharedCachePath: Hashable, Sendable, CustomStringConvertible {
+    public let path: String
+    public init(path: String)
+    /// This Mac's cache, as the system locates it.
+    public static var current: DyldSharedCachePath { get }
+    public static func macOS(_ version: String) -> DyldSharedCachePath
+    public static func iOS(_ version: String) -> DyldSharedCachePath
+}
+
+public struct MachOImageName: Hashable, Sendable, ExpressibleByStringLiteral {
+    public let name: String
+    public init(_ name: String)
+    public static let foundation: MachOImageName   // the system images both packages use
+}
+
+public struct MachOFileName: Hashable, Sendable {
+    /// A path, absolute or relative to `anchor` — the caller's `#filePath`
+    /// climbed to its package root.
+    public init(path: String, relativeTo anchor: URL? = nil)
+    public var url: URL { get }
+}
+
+public enum HostSlice {
+    /// The slice of a file for this process's CPU, matching type and subtype.
+    public static func machOFile(at url: URL) throws -> MachOFile
+}
+
+public enum ProcessImages {
+    public static func image(containing address: UnsafeRawPointer) -> MachOImage?
+    /// The image of this Mac's cache at `path`, and the same image loaded here.
+    public static func cacheFileAndLoadedImage(path: String) throws -> (file: MachOFile, image: MachOImage)
+}
+
+public struct FixtureCompiler: Sendable {
+    public enum Language: Sendable { case c, cPlusPlus, swift }
+    public static let shared: FixtureCompiler
+    /// Compiles `source` into a dynamic library once per process for the same
+    /// source and arguments; the directory goes away when the process exits.
+    public func dynamicLibrary(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL
+}
+
+// MachOTestingSupport
+public struct ExclusiveImageAccess: SuiteTrait, TestTrait, TestScoping {
+    public init(_ imageName: String)
+}
+
+public struct MachOFixture: Sendable {
+    public init(fileURL: URL, imageName: String, loadsIntoProcess: Bool)
+    public init(imageContaining anchor: UnsafeRawPointer)
+}
+
+@MainActor
+open class MachOFixtureTests {
+    open class var fixture: MachOFixture { get }
+    public let machOFile: MachOFile
+    public let machOImage: MachOImage
+    public let fileContext: MachOContext<MachOFile>
+    public let imageContext: MachOContext<MachOImage>
+    public let inProcessContext: InProcessContext
+    public init() throws
+    public func acrossAllReaders<Value: Equatable>(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value
+    public func acrossAllContexts<Value: Equatable>(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value
+    public func usingInProcessOnly<Value: Equatable>(_ work: (InProcessContext) throws -> Value, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value
+}
+
  • 签名以本包现有的为准,只把泛型参数改成完整的单词(本包的 T 换成 Value),调用点不变。
  • FixtureCompiler 按「语言 + 源码 + 参数」的摘要缓存产物 URL,锁保护;失败把编译器输出原样放进错误。
  • MachOFixtureTests.fixture 的默认实现 fatalError,提醒子类必须给出夹具。
+
+
+
+ +
+

动机

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

调研

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

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

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

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

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

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

+

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

+

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

+

约束

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

替代方案

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

影响

+

源码兼容性(source compatibility)

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

ABI 兼容性(条件项)

+

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

+

下游影响

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

文档与示例

+

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

+

API 演进与废弃策略

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

落地步骤

+

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

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

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

+
  1. 改依赖、删重复 —— 本包 Package.swift、Sources/TestSupport/、Tests/SwiftSectionTestingSupportTests/、DyldCache(path: .current) 的 25 处
    • 行为:本包全部测试(IntegrationTests 除外,照 AGENTS.md)照常通过
    • 行为:SymbolTestsCoreFixtureLoadsThroughTheSharedBaseClass
    • 行为:17 个 Swift 夹具经 FixtureCompiler 编出、结果与改前一致
  2. 本包文档 —— AGENTS.md、FixtureTestingAndContinuousIntegration.md、Modules/README.md、ProjectEvolutionLog.md
+

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

+
+ +
+

决策日志

+
+ 10 条,最近一条:状态 → Accepted +
+
日期变更说明
2026-11-20Created as Draft用户希望把本包 TestingSupport 的通用部分搬到 MachOKitExtensions,统一两个包的测试用例。先由只读调研查清可搬与不可搬的部分、两边的重复与分叉,再经两轮澄清提问定下方案。
2026-11-20两个包一起统一,走完整档用户选择。否决:只统一 MKE 内部;先不做。
2026-11-20拆成 MachOFixtureSupport(无 Testing)与 MachOTestingSupport(Testing)用户选择。否决:一个 product。依据 write-tests skill 对外 product 的规则与本包当年的拆法。
2026-11-20测试基类原样搬用户选择。否决:顺便改成 Swift Testing trait(另议)。
2026-11-20本机 cache 统一为进程共用用户选择。否决:两种入口并存。本包依赖新实例的测试逐个复查。
2026-11-20跨读取器统一用闭包式 acrossAllReaders用户选择。否决:统一用参数化(本包 429 处要改写)。
2026-11-20夹具基类泛化为 MachOFixtureTests用户选择。否决:值类型组合(两种形状会并存)。
2026-11-20MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0用户选择。否决:一起发 3.1.0。
2026-11-20按事实或先例自定的四条名字类型改成 struct、#filePath 锚点由调用方传(跨包后锚点位置变了);FixtureCompiler 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。
2026-11-20状态 → Accepted用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md new file mode 100644 index 00000000..41ab0580 --- /dev/null +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -0,0 +1,305 @@ +# Draft - 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: [0003(MachOKitExtensions)move-macho-infrastructure-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md)(`MachO` 前缀的模块归 MachOKitExtensions,本包的测试支持因此改名 `SwiftSection…`);[0098 move-cross-reference-layers](0098-move-cross-reference-layers.md)(跨仓库迁移、由本包维护唯一提案的先例);MachOKitExtensions 的 `draft-cplusplus-class-hierarchy`(它新加的测试辅助是本提案要合并的重复代码之一,须先发 3.1.0) +- **实现分支 / PR**: 待定(两个仓库各一条功能分支:MachOKitExtensions 从 C++ 类恢复收尾后的 `main` 切出,本包从 `next` 切出) +- **配套文档**: 待定 —— 落地时登记 MachOKitExtensions 的实现说明 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +把本包测试支持里与 Swift 无关的部分搬到 MachOKitExtensions(下称 MKE),作为两个对外 product 发布,两个包从此共用一套。`MachOFixtureSupport` 不依赖 Testing:dyld cache 路径、打开 cache 与镜像、按本机架构选 slice、取进程内镜像、测试运行时用 `xcrun` 现编 dylib(clang 与 swiftc 都支持)、只转发不加逻辑的包装读取器。`MachOTestingSupport` 依赖 Testing:按镜像互斥的 trait `ExclusiveImageAccess`、测试基类 `MachOFileTests` / `MachOImageTests` / `DyldCacheTests`,以及从本包 `MachOSwiftSectionFixtureTests` 泛化出来、不绑定夹具的基类与闭包式跨读取器写法 `acrossAllReaders`。本包的 `MachOSwiftSectionFixtureTests` 变成它的子类,218 个子类与 429 处 `acrossAllReaders` 调用不动;MKE 自己十几处重复的辅助与约 25 个参数化的跨读取器测试改用共享版本。取本机 cache 统一为整个进程共用一份。MKE 先发 3.1.0(C++ 类恢复),本提案在 MKE 3.2.0 发布,本包随后改依赖。 + +## 动机 + +- **两个包各写一套,而且在分叉。** 自 MKE 2.0.0 接过 Mach-O 层以后,MKE 的测试没有可用的测试支持,只能各写各的(下表,路径相对 MKE 的 `Tests/`)。同一件事在两边实现不同: + + | 辅助 | 本包 | MKE | + |---|---|---| + | 取本机 cache | `DyldCache(path: .current)`,路径写死在 Cryptexes(`DyldSharedCachePath.swift:45`),每次重新打开(`DyldCacheTests.swift:30-32`) | `FullDyldCache.cachedHost`,由系统定位、整个进程只打开一次(`Sources/MachOKitExtensions/Cached/FullDyldCache+Cached.swift:13-27`);另有 3 处写死 Cryptexes 路径(`DyldCacheImageSearchTests.swift:161`、`MachOAddressResolutionTests.swift:18`、`SharedDyldCacheOpeningTests.swift:30`) | + | 选 slice | 固定选 `.arm64`,否则取第一个(`MachOFileTests.swift:19`) | 按进程的 CPU 类型与去掉标志位的子类型匹配(`CPlusPlusSymbolsTests/ClassIndexTestImages.swift:50-63`);另有 3 处手写 `loadFromFile` 的 switch | + | 现编 dylib | 17 个 `*Fixture.swift` 各自复制一份 `Process` 加 `Pipe` 的 swiftc 调用,结束时清理临时目录(如 `ExistentialAnyFixture.swift:100-140`) | 5 份 clang 调用(`FixupResolutionMemoTests.swift:122-176`、`SelfBindResolutionTests.swift:80-115`、`ClassIndexTestImages.swift:70-159`、`ClassIndexDemoTests.swift:34-60` 等),不清理 | + | 归档 cache 路径 | `DyldSharedCachePath.macOS(_:)` / `iOS(_:)` | 3 份各写一遍(`DyldCacheImageIdentifierTests.swift:7-11`、`CacheRootDependencyClosureTests.swift:10-11`、`MachOAddressResolutionTests.swift:81`) | + | 跨读取器 | `acrossAllReaders`,429 处,但写死 SymbolTestsCore | `@Test(arguments: Reader.allCases)` 参数化,约 25 处 | + | 包装读取器 | `ForwardingMachOReader`,约束在本包的协议上 | `Support/ForwardingReader.swift`,约束在 `MachORepresentableWithCache`,internal | + +- **MKE 的新功能还在继续加重复。** C++ 类恢复(MKE `draft-cplusplus-class-hierarchy`)一次就新增了两份现编 dylib、一份选 slice、两份「cache 文件加进程内同一镜像」。 +- **这些代码本该在 MKE。** 0003 定下 `MachO` 前缀的模块归 MKE,本包的测试支持为此从 `MachOFixtureSupport` / `MachOTestingSupport` 改名为 `SwiftSection…`(MKE 0003 的 `:102`),两个名字现在空着。 + +## 前期调研 + +**本包的测试支持**(`Sources/TestSupport/`,三个 target,都不是 product,`Package.swift:1020-1080`) + +- `SwiftSectionFixtureSupport`:不 import Testing,`baseline-generator` 也用它。依赖 MachOKit、Demangling、SwiftSyntax 三件套、MKE 的 MachOFoundation / MachOReading / MachOResolving,以及本包的 SwiftSymbols、SwiftDump、SwiftDeclaration、SwiftIndexing、SwiftPrinting、SwiftInterface、MachOSwiftSectionC 和 TestingSupportC。 +- `SwiftSectionTestingSupport`:放 Testing 基类,另依赖 MachOSwiftSection、SwiftSpecialization、Semantic。 +- `SwiftSectionTestingSupportC`:`CDemangleTree.cpp`。 +- 17 个测试 target 依赖 `SwiftSectionTestingSupport`(`Package.swift:1069-1411`),CrossReferenceAnalysisTests 只依赖 FixtureSupport。 + +**哪些可以搬**(只依赖 MachOKit、Foundation、Testing 或 MKE 已有的模块) + +| 文件 | 去处 | 要改的 | +|---|---|---| +| `FixtureSupport/DyldSharedCachePath.swift`(无 import) | `MachOFixtureSupport` | `.current` 改由本机 cache 的 URL 得出,不写死 Cryptexes | +| `FixtureSupport/Extensions.swift`(只 import MachOKit;`UniformTypeIdentifiers` 在 `:3` 导入了没用) | `MachOFixtureSupport` | `loadFromFile(named:)` 的 `#filePath` 锚点(`:9`)改由调用方传入;`DyldCache`/`FullDyldCache` 的 `init(path:)`、`machOFile(named:)`、受 `SILENT_TEST` 控制的 `.print()` 原样 | +| `FixtureSupport/MachOFileName.swift`、`MachOImageName.swift` | `MachOFixtureSupport` | 封闭的 `package enum` 改成「struct 加静态成员」,SymbolTests 的条目(`MachOFileName.swift:20-26`、`MachOImageName.swift:26-27`)留在本包用 extension 补 | +| `FixtureSupport/XcodeMachOFileName.swift`(Foundation、Darwin) | `MachOFixtureSupport` | 同上改成 struct | +| `TestingSupport/ExclusiveImageAccess.swift`(只 import Testing) | `MachOTestingSupport` | 只留按 `String` 的初始化;按本包镜像名的便捷初始化(`:89-95`)留在本包 | +| `TestingSupport/TestActor.swift`、`ProcessMemory.swift`(Foundation) | `MachOFixtureSupport` | 无 | +| `TestingSupport/MachOFileTests.swift`、`MachOImageTests.swift`、`DyldCacheTests.swift`、`XcodeMachOFileTests.swift`(MachOKit、MachOFoundation、FixtureSupport) | `MachOTestingSupport` | 选 slice 改用统一的按进程 CPU 匹配;`DyldCacheTests` 的 `.current` 改为共用的本机 cache | +| `TestingSupport/MachOSwiftSectionFixtureTests.swift` 的跨读取器部分(`acrossAllReaders` `:104-118`、`acrossAllContexts` `:121-135`、`usingInProcessOnly` `:147-152`,上下文来自 MKE 的 MachOReading) | `MachOTestingSupport` 的新基类 `MachOFixtureTests` | 夹具改由子类描述;SymbolTestsCore 的加载(`:18-19`、`:70`)留在本包的子类里 | +| `SwiftSectionTestingSupportTests` 里的 `DyldSharedCachePathTests`、`ExclusiveImageAccessTests` | MKE 新测试 target `MachOTestingSupportTests` | 跟着代码走 | + +**不搬**:`ForwardingMachOReader`(约束在 `MachOSwiftSectionRepresentableWithCache`,`:5`、`:27`)、`DemangleOptions`、`DumpableTests` / `Snapshot*Tests`、`CommentStructureContract`、`SwiftIndexEventCollector`、`DefinitionName+DeclaredNameForTesting`、`URL+`(依赖 swift-dependencies)、`FixtureLoadError`、`InProcessMetadataPicker`、177 个 Baseline 文件、5 个 Coverage 文件、17 个 Swift 夹具的内容(只把编译那段换成共享的编译器)、TestingSupportC、`ContinuousIntegrationTestFilterTests`。 + +**用量**(本包 `Tests/` 计数):`acrossAllReaders` 429、继承 `MachOSwiftSectionFixtureTests` 218、`usingInProcessOnly` 73、`acrossAllContexts` 68、`.print()` 44、`ExclusiveImageAccess(` 42、继承 `MachOFileTests` 37、`machOFile(named:)` 32、`DyldCache(path: .current` 25、继承 `MachOImageTests` 13、继承 `DyldCacheTests` 5。 + +**测试本身不搬**:本包的 `CrossReferenceAnalysisTests` 测的是 MKE 的 `MachOCodeReferences` 等模块,但几乎每个文件都 import 本包的 `CrossReferenceAnalysis` 与 MachOObjCSection 的 `ObjCCodeReferences`,MKE 不能依赖它们。 + +**约束** + +- 跨包使用只能是 `public`。全局 write-tests skill 的默认做法是包内 `TestingSupport` target、`package` 访问级别、不进 products;要给别的包用时另拆对外 product,对外 API 尽量小,能不 import Testing 就不 import(`references/testing-support.md` 第 11 节)。拆成不依赖 Testing 的 `MachOFixtureSupport` 与依赖 Testing 的 `MachOTestingSupport` 正是这条规则,也是本包当年的拆法(`Package.swift:1020-1050` 的注释)。 +- MKE 的 `Package.swift` 末尾有 Tuist 适配块,只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时给「被测试依赖、但不在 product 里」的 target 补 product。两个新 target 是正式 product,无条件声明,不靠它。 +- 本包 `AGENTS.md` 规定 `#filePath` 定位源码的深度(0055),`MachOFileName` 从 `Sources//` 往上爬三层到包根。搬到 MKE 后锚点必须由调用方传入。 +- 本包 `AGENTS.md` 规定共享整进程状态的套件都要声明 `ExclusiveImageAccess(.TheFixture)`。trait 搬走后,规则与用法不变,只是类型来自 MKE。 + +## 提议方案 + +1. **MKE 新增两个 product**(3.2.0): + - `MachOFixtureSupport`(`Sources/MachOFixtureSupport`,不 import Testing):`DyldSharedCachePath`、`MachOImageName` / `MachOFileName` / `XcodeMachOFileName`(可扩展的 struct)、打开 cache 与镜像的扩展、`hostSlice(of:)`、取进程内镜像(按锚点地址 `dladdr`、按名字)、「cache 里的文件与进程内同一镜像」成对返回、`FixtureCompiler`(clang 与 swiftc,同一份源码与参数只编一次,进程结束时清理临时目录)、`ForwardingReader`、`TestActor`、`ProcessMemory`、`.print()`。 + - `MachOTestingSupport`(`Sources/MachOTestingSupport`,import Testing,依赖前者与 MachOReading):`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`,以及新的 `MachOFixtureTests`。 +2. **测试基类原样搬**:保留「继承基类拿到镜像」的写法,只改访问级别(`open` / `public`)与上面列出的必要改动。改成 Swift Testing trait 的写法以后另写提案。 +3. **`MachOFixtureTests`:不绑定夹具的基类**。子类用一个 `MachOFixture` 值说明夹具从哪来(磁盘路径,或进程里某个锚点地址所在的镜像,以及是否要 `dlopen`);基类据此建出 `machOFile`、`machOImage` 与 `fileContext`、`imageContext`、`inProcessContext`,提供 `acrossAllReaders`、`acrossAllContexts`、`usingInProcessOnly`,签名与本包现在的一致。 +4. **本机 cache 统一为进程共用**:`DyldSharedCachePath.current` 与 `DyldCacheTests` 都经 `FullDyldCache.cachedHost` / `DyldCache.host` 的 URL,不写死路径;确实需要新实例的测试显式开一份(`DyldCache(path:)` 照旧可用)。 +5. **跨读取器统一用闭包式**:MKE 约 25 个 `@Test(arguments: Reader.allCases)` 的测试改写成 `MachOFixtureTests` 子类里的 `acrossAllReaders`,比对两种读取器的结果相等后再断言。 +6. **MKE 自己的重复辅助全部换成共享版本**(动机一节的表)。 +7. **本包随后改依赖**:两个 support target 依赖 MKE 的新 product,删掉搬走的文件;`MachOFileName` / `MachOImageName` 的 SymbolTests 条目改为对 MKE struct 的 extension;`ExclusiveImageAccess` 保留一个按本包镜像名的便捷初始化;`MachOSwiftSectionFixtureTests` 改成 `MachOFixtureTests` 的子类;17 个 Swift 夹具改用 `FixtureCompiler`;`DyldCache(path: .current)` 的 25 处改为共用实例后,逐个复查依赖新实例的测试。 +8. **发版顺序**:MKE 先收尾 C++ 类恢复发 3.1.0;本提案的 MKE 部分从收尾后的 `main` 切分支,发 3.2.0;本包在 3.2.0 发布后改依赖(之前用 `USING_LOCAL_DEPENDENCIES=1` 本地验证)。 + +### 非目标 + +- 把测试基类改成 Swift Testing trait 的写法。 +- 搬 Swift 专用的支持代码(夹具内容、baseline、coverage、快照对比、SymbolTestsCore 相关)。 +- 搬测试本身(`CrossReferenceAnalysisTests` 等依赖本包与 MachOObjCSection 的模块)。 +- 统一两个包的 `ForwardingMachOReader` / `ForwardingReader`:协议层级不同,本包那份保留。 +- MachOObjCSection、MachOKitUI 等其他仓库的测试改用新 product:各自另议。 +- 给 MKE 加 CI(MKE 0003 记下的后续项,另写提案)。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| MKE `Package.swift` | 修改 | 新增 target 与 product `MachOFixtureSupport`、`MachOTestingSupport`,测试 target `MachOTestingSupportTests`;各测试 target 加依赖;Tuist 适配块留在文件末尾 | 对外发布 | 1 | +| MKE `Sources/MachOFixtureSupport/`(`DyldSharedCachePath`、`MachOImageName`、`MachOFileName`、`XcodeMachOFileName`、`DyldCache+Fixture`、`HostSlice`、`ProcessImages`、`FixtureCompiler`、`ForwardingReader`、`TestActor`、`ProcessMemory`、`Printing`) | 新增 | 从本包搬来并改为 `public`;名字类型改成 struct;`.current` 不写死;锚点由调用方传;编译器统一 clang 与 swiftc | 共用的夹具支持 | 1、2 | +| MKE `Sources/MachOTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`MachOFixture`、`MachOFixtureTests`) | 新增 | 搬来并改为 `open` / `public`;新的夹具基类与跨读取器写法 | 共用的测试基类与 trait | 1、2 | +| MKE `Tests/MachOTestingSupportTests/` | 新增 | 搬来 `DyldSharedCachePathTests`、`ExclusiveImageAccessTests`;新增 `FixtureCompilerTests`、`HostSliceTests`、`MachOFixtureTestsTests` | 共享库自己的测试 | 1、2 | +| MKE `Tests/MachOKitExtensionsTests/`(`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`DyldCacheImageSearchTests`、`DyldCacheImageIdentifierTests`、`DyldCacheSubCacheLookupTests`、`MachOReaderWrapperTests`、`Support/ForwardingReader.swift`、`Support/ChainedFixupsFixture.swift`) | 修改 / 删除 | 现编 dylib、本机 cache、归档 cache 路径、选 slice、包装读取器改用共享版本 | 去重 | 3 | +| MKE `Tests/MachOSymbolsTests/`、`MachODependenciesTests/`、`MachOAddressResolutionTests/`、`MachOReadingTests/` | 修改 | 同上 | 去重 | 3 | +| MKE `Tests/CPlusPlusSymbolsTests/`(`ClassIndexTestImages.swift` 删除,`CPlusPlusClassIndexStoreTests`、`CPlusPlusSymbolIndexStoreTests`、`ImagePointerSlotsTests`、普查、`ClassIndexDemoTests`、`CPlusPlusVirtualFunctionNamingTests`) | 修改 / 删除 | 夹具镜像改用 `MachOFixtureTests` 子类;约 25 个参数化测试改写成 `acrossAllReaders`;现编 dylib 改用 `FixtureCompiler` | 统一写法 | 3 | +| MKE `Documentations/Internal/TestingSupport.md`、`README.md`、索引 | 新增 / 修改 | 两个 product 的用法与契约(只能链接到测试 target、锚点由调用方传、共用本机 cache) | 对外说明 | 4 | +| 本包 `Package.swift` | 修改 | 两个 support target 依赖 MKE 的新 product;去掉不再需要的依赖 | 改依赖 | 5 | +| 本包 `Sources/TestSupport/SwiftSectionFixtureSupport/`(`DyldSharedCachePath`、`Extensions` 的通用部分、`MachOFileName`、`MachOImageName`、`XcodeMachOFileName`) | 删除 / 修改 | 删掉搬走的;`MachOFileName` / `MachOImageName` 只剩 SymbolTests 条目的 extension;本包的 `#filePath` 锚点在这里传给 MKE | 改用共享版本 | 5 | +| 本包 `Sources/TestSupport/SwiftSectionTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`TestActor`、`ProcessMemory`、`MachOSwiftSectionFixtureTests`、17 个 `*Fixture.swift`) | 删除 / 修改 | 删掉搬走的;`ExclusiveImageAccess` 只剩按本包镜像名的便捷初始化;夹具基类改成 `MachOFixtureTests` 子类;夹具的编译改用 `FixtureCompiler` | 改用共享版本 | 5 | +| 本包 `Tests/SwiftSectionTestingSupportTests/` | 修改 | 删掉随代码搬走的两个测试 | 去重 | 5 | +| 本包用 `DyldCache(path: .current)` 的 25 处 | 复查 | 依赖新实例的显式开一份,其余改用共用实例 | 行为统一后的复查 | 5 | +| 本包 `AGENTS.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md`、`Documentations/Internal/Modules/README.md`、`ProjectEvolutionLog.md` | 修改 | 测试支持的来源、`ExclusiveImageAccess` 与 `acrossAllReaders` 的出处、锚点规则 | 文档同步 | 6 | + +## 架构图 + +改了什么: + +```text +MachOKitExtensions (package) + MachOKit, MachOKitExtensions, MachOFoundation, MachOReading, ... (unchanged) ++ MachOFixtureSupport (product, no Testing) ++ DyldSharedCachePath, MachOImageName/MachOFileName (extensible structs) ++ HostSlice, ProcessImages, DyldCache+Fixture, FixtureCompiler (clang, swiftc) ++ ForwardingReader, TestActor, ProcessMemory, print() ++ MachOTestingSupport (product, Testing) -> MachOFixtureSupport, MachOReading ++ ExclusiveImageAccess, MachOFileTests, MachOImageTests, DyldCacheTests ++ MachOFixture, MachOFixtureTests (acrossAllReaders, acrossAllContexts, usingInProcessOnly) +~ Tests/* -> MachOFixtureSupport / MachOTestingSupport + +MachOSwiftSection (package) +~ SwiftSectionFixtureSupport -> + MachOFixtureSupport +- DyldSharedCachePath, generic Extensions, MachOFileName/MachOImageName enums +~ MachOFileName/MachOImageName extensions: SymbolTests entries +~ SwiftSectionTestingSupport -> + MachOTestingSupport +- ExclusiveImageAccess, MachOFileTests, MachOImageTests, DyldCacheTests, TestActor, ProcessMemory +~ MachOSwiftSectionFixtureTests : MachOFixtureTests (SymbolTestsCore fixture) +~ 17 *Fixture.swift compile through FixtureCompiler + Baseline, Coverage, Snapshot, ForwardingMachOReader, ... (unchanged) +``` + +一个夹具测试的调用链: + +```text +SomeSuite : MachOSwiftSectionFixtureTests (MSS) : MachOFixtureTests (MKE) + ├─ class var fixture -> MachOFixture(SymbolTestsCore path, anchored at MSS's #filePath; dlopen) + ├─ MachOFixtureTests.init + │ ├─ hostSlice(of: url) -> machOFile; dlopen + MachOImage -> machOImage + │ └─ MachOContext(machOFile), MachOContext(machOImage), InProcessContext + └─ acrossAllReaders(file: { ... machOFile ... }, image: { ... machOImage ... }) + └─ #expect(fromFile == fromImage) +``` + +## 详细设计 + +```swift +// MachOFixtureSupport +public struct DyldSharedCachePath: Hashable, Sendable, CustomStringConvertible { + public let path: String + public init(path: String) + /// This Mac's cache, as the system locates it. + public static var current: DyldSharedCachePath { get } + public static func macOS(_ version: String) -> DyldSharedCachePath + public static func iOS(_ version: String) -> DyldSharedCachePath +} + +public struct MachOImageName: Hashable, Sendable, ExpressibleByStringLiteral { + public let name: String + public init(_ name: String) + public static let foundation: MachOImageName // the system images both packages use +} + +public struct MachOFileName: Hashable, Sendable { + /// A path, absolute or relative to `anchor` — the caller's `#filePath` + /// climbed to its package root. + public init(path: String, relativeTo anchor: URL? = nil) + public var url: URL { get } +} + +public enum HostSlice { + /// The slice of a file for this process's CPU, matching type and subtype. + public static func machOFile(at url: URL) throws -> MachOFile +} + +public enum ProcessImages { + public static func image(containing address: UnsafeRawPointer) -> MachOImage? + /// The image of this Mac's cache at `path`, and the same image loaded here. + public static func cacheFileAndLoadedImage(path: String) throws -> (file: MachOFile, image: MachOImage) +} + +public struct FixtureCompiler: Sendable { + public enum Language: Sendable { case c, cPlusPlus, swift } + public static let shared: FixtureCompiler + /// Compiles `source` into a dynamic library once per process for the same + /// source and arguments; the directory goes away when the process exits. + public func dynamicLibrary(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL +} + +// MachOTestingSupport +public struct ExclusiveImageAccess: SuiteTrait, TestTrait, TestScoping { + public init(_ imageName: String) +} + +public struct MachOFixture: Sendable { + public init(fileURL: URL, imageName: String, loadsIntoProcess: Bool) + public init(imageContaining anchor: UnsafeRawPointer) +} + +@MainActor +open class MachOFixtureTests { + open class var fixture: MachOFixture { get } + public let machOFile: MachOFile + public let machOImage: MachOImage + public let fileContext: MachOContext + public let imageContext: MachOContext + public let inProcessContext: InProcessContext + public init() throws + public func acrossAllReaders(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + public func acrossAllContexts(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + public func usingInProcessOnly(_ work: (InProcessContext) throws -> Value, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value +} +``` + +- 签名以本包现有的为准,只把泛型参数改成完整的单词(本包的 `T` 换成 `Value`),调用点不变。 +- `FixtureCompiler` 按「语言 + 源码 + 参数」的摘要缓存产物 URL,锁保护;失败把编译器输出原样放进错误。 +- `MachOFixtureTests.fixture` 的默认实现 `fatalError`,提醒子类必须给出夹具。 + +## 替代方案考量 + +- **只在 MKE 内部统一,本包不动**:改动小,但两套继续分叉;用户选择两个包一起统一。 +- **一个 product**:简单,但只想要路径与打开镜像的使用方也要链接 Testing;用户选择拆两个。 +- **测试基类顺便改成 Swift Testing trait**:更现代,但本包 55 个、218 个子类都要改写,风险高;用户选择原样搬,改写另议。 +- **保留「每次重开」与「共用」两种取 cache 的入口**:不动行为,但两套写法并存;用户选择统一为共用。 +- **跨读取器统一用参数化**:每种读取器在报告里单独成用例,但本包 429 处都要改写;用户选择闭包式。 +- **夹具用值类型组合**:更现代,但与「基类原样搬」不一致、两种形状并存;用户选择泛化基类。 +- **与 C++ 类恢复一起发 3.1.0**:少发一个版本,但推迟已做完的功能;用户选择 C++ 先发。 + +## 影响 + +### 源码兼容性(source compatibility) + +- MKE:纯新增两个 product;改的只有 MKE 自己的测试。 +- 本包:只改测试支持与测试,对外 product 不变。测试代码的 import 从本包的 support target 换成 MKE 的 product(经本包 support target 的 `@_exported import` 转出,多数测试文件不用改)。 + +### ABI 兼容性(条件项) + +不适用 —— 两个包都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- MKE 3.2.0 新增 product,不影响现有使用方(RuntimeViewer、MachOObjCSection、MachOKitUI)。 +- MachOObjCSection、MachOKitUI 的测试以后可以改用这两个 product,各自另议。 +- 本包依赖 MKE 的版本下限升到 3.2.0。 + +### 文档与示例 + +MKE 新增实现说明 `Internal/TestingSupport.md`、README 的 product 表;本包 `AGENTS.md` 里 `ExclusiveImageAccess` 与 `acrossAllReaders` 两条规则注明类型来自 MKE,`FixtureTestingAndContinuousIntegration.md` 更新锚点规则。 + +## API 演进与废弃策略 + +- 本包搬走的类型直接删除,不留废弃期:它们是 `package` 级别,只有本包自己的测试在用,同一批次改完。 +- MKE 新 product 的公开 API 尽量小;名字类型用 struct 加静态成员,以后加镜像不破坏调用方。 +- semver:MKE 3.2.0(minor);本包对外 product 不变,随下一个常规版本。 + +## 落地步骤 + +MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): + +1. **两个 product 的骨架与搬来的代码** —— MKE `Package.swift`、`Sources/MachOFixtureSupport/`、`Sources/MachOTestingSupport/`、`Tests/MachOTestingSupportTests/` + - 行为:`currentCachePathIsTheOneTheSystemLocates` + - 行为:`archivedCachePathsKeepTheirLayout` + - 行为:`hostSliceMatchesTheProcessSubtype` + - 行为:`exclusiveImageAccessSerializesSuitesOfOneImage`(搬来) + - 行为:`imageNamesAndFileNamesTakeExtensions` +2. **夹具基类与编译器** —— `MachOFixture`、`MachOFixtureTests`、`FixtureCompiler` + - 行为:`fixtureTestsBuildBothReadersAndAllContextsFromAFile` + - 行为:`fixtureTestsReachAnImageOfThisProcessByAnAnchor` + - 行为:`acrossAllReadersReportsWhichReaderDiverged` + - 行为:`compilerBuildsEachSourceOncePerProcess` + - 行为:`compilerFailureCarriesTheDiagnostics` + - 行为:`compilerBuildsSwiftAndCPlusPlus` +3. **MKE 的测试改用共享版本** —— 动机一节的表,以及 `Tests/CPlusPlusSymbolsTests/` + - 行为:MKE 全部测试照常通过,跨读取器的约 25 个测试改写为 `acrossAllReaders` 后断言不变 + - 行为:仓库里不再有 `Process` 调用 `xcrun` 的测试辅助、写死 Cryptexes 路径的常量、手写的选 slice +4. **MKE 文档与发版** —— `Internal/TestingSupport.md`、README、索引;发 3.2.0 + +本包(MKE 3.2.0 发布后,从 `next` 切出): + +5. **改依赖、删重复** —— 本包 `Package.swift`、`Sources/TestSupport/`、`Tests/SwiftSectionTestingSupportTests/`、`DyldCache(path: .current)` 的 25 处 + - 行为:本包全部测试(`IntegrationTests` 除外,照 `AGENTS.md`)照常通过 + - 行为:`SymbolTestsCoreFixtureLoadsThroughTheSharedBaseClass` + - 行为:17 个 Swift 夹具经 `FixtureCompiler` 编出、结果与改前一致 +6. **本包文档** —— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md`、`Modules/README.md`、`ProjectEvolutionLog.md` + +收尾判断:MKE 写实现说明(两个 product 的契约:只能链接到测试 target、锚点由调用方传、共用本机 cache);不写使用指南;本包与 MKE 都没有新术语要登记(`ExclusiveImageAccess`、`acrossAllReaders` 已在本包术语里)。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户希望把本包 TestingSupport 的通用部分搬到 MachOKitExtensions,统一两个包的测试用例。先由只读调研查清可搬与不可搬的部分、两边的重复与分叉,再经两轮澄清提问定下方案。 | +| 2026-11-20 | 两个包一起统一,走完整档 | 用户选择。否决:只统一 MKE 内部;先不做。 | +| 2026-11-20 | 拆成 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing) | 用户选择。否决:一个 product。依据 write-tests skill 对外 product 的规则与本包当年的拆法。 | +| 2026-11-20 | 测试基类原样搬 | 用户选择。否决:顺便改成 Swift Testing trait(另议)。 | +| 2026-11-20 | 本机 cache 统一为进程共用 | 用户选择。否决:两种入口并存。本包依赖新实例的测试逐个复查。 | +| 2026-11-20 | 跨读取器统一用闭包式 `acrossAllReaders` | 用户选择。否决:统一用参数化(本包 429 处要改写)。 | +| 2026-11-20 | 夹具基类泛化为 `MachOFixtureTests` | 用户选择。否决:值类型组合(两种形状会并存)。 | +| 2026-11-20 | MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0 | 用户选择。否决:一起发 3.1.0。 | +| 2026-11-20 | 按事实或先例自定的四条 | 名字类型改成 struct、`#filePath` 锚点由调用方传(跨包后锚点位置变了);`FixtureCompiler` 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。 | +| 2026-11-20 | 状态 → Accepted | 用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。 | diff --git a/Documentations/README.md b/Documentations/README.md index 5f319fa4..e8b55ec3 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -218,6 +218,7 @@ selects names using each access's offset and width. | [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | | [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | | [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | +| [Evolutions/draft-shared-macho-testing-support.md](Evolutions/draft-shared-macho-testing-support.md) | **提案 draft(Accepted)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | | [Evolutions/draft-swift6-mode-and-upcoming-features.md](Evolutions/draft-swift6-mode-and-upcoming-features.md) | **提案 draft(Accepted)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.2 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [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) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | From c6ce05466e63652587bc7951db5dc7e6bd785af9 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:46:39 +0800 Subject: [PATCH 022/175] fix: spell an optional existential as (any P)? so Swift 6.3 accepts it The ExistentialAny fix-it Swift 6.4 writes, any P?, is rejected by Swift 6.3 (optional 'any' type must be written '(any P)?'), the toolchain CI builds with. --- ...draft-swift6-mode-and-upcoming-features.md | 72 +++++++++---------- .../NodePrintables/NodePrintable.swift | 2 +- 2 files changed, 36 insertions(+), 38 deletions(-) diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md index 6682d04b..3b5f3713 100644 --- a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md @@ -13,7 +13,7 @@ ## 摘要 -六个 MachO 系列包里有五个已经在 Swift 6 语言模式下编译,complete strict concurrency checking 早已按错误执行;唯一的例外是 MachOKit(fork),它的清单还是 `swift-tools-version: 5.10`。本提案做两件事:把 MachOKit 升到 tools 6.2,让它也进入 Swift 6 语言模式(实测零错误,Sources 里零并发诊断);然后在六个包的每个 Swift target 上开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` 三项 upcoming feature(编译器把它们标为 Swift 7 默认开启),开关在每份清单末尾用一个循环统一加,不逐个 target 写。源码改动约 900 处,绝大部分是补 `import` 与补 `any`;非测试 target 用 `swift package migrate` 自动改,测试 target 照诊断清单手改,另有 6 处工具处理不了、要先手工改好。同为 Swift 7 默认的 `NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`,以及独立的 `StrictMemorySafety`,量过之后明确不做(见「非目标」)。 +六个 MachO 系列包里有五个已经在 Swift 6 语言模式下编译,complete strict concurrency checking 早已按错误执行;唯一的例外是 MachOKit(fork),它的清单还是 `swift-tools-version: 5.10`。本提案做两件事:把 MachOKit 升到 tools 6.0,让它也进入 Swift 6 语言模式(实测零错误,Sources 里零并发诊断;停在 6.0 而不是 6.2,是为了 fork 的 CI 所用的 Swift 6.0 工具链还读得了清单);然后在六个包的每个 Swift target 上开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` 三项 upcoming feature(编译器把它们标为 Swift 7 默认开启),开关在每份清单末尾用一个循环统一加,不逐个 target 写。源码改动 723 处(717 个 fix-it 加 6 处预修),绝大部分是补 `import` 与补 `any`,源码与测试都由 `swift package --build-system native migrate` 自动改出;另有 6 处工具处理不了、要先手工改好,它写成 `internal import` 的补丁按各仓库的惯例改回普通 `import`。同为 Swift 7 默认的 `NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`,以及独立的 `StrictMemorySafety`,量过之后明确不做(见「非目标」)。 ## 动机 @@ -64,7 +64,8 @@ **`swift package migrate` 的实际表现(在本库 clone 上试跑):** - 非测试 target:在 258 个文件里套用了 300 个 fix-it(diff +304 / −57),然后在改清单那一步失败:本库的 target 写成 `extension Target` 上的静态常量,工具找不到 target(`unable to find target named 'Utilities' in package`),所以清单必须手改。退出码是 1,但源码已经改好。 -- 测试 target:一处都不改,显式 `--target <全部测试 target>` 也是 `Applied 0 fix-its`;它构建时不带测试。测试部分只能照 `--build-tests` 的迁移警告手改。 +- 测试 target:默认的构建系统(SwiftPM 6.4 起是 Swift Build)下一处都不改。它确实编了测试、也打出了 450 条测试里的迁移警告,可显式 `--target <全部测试 target>`、换全新构建目录,都是 `Applied 0 fix-its`。改用旧的构建系统(`swift package --build-system native migrate …`)就正常:探针里测试 target 套用了 303 个 fix-it(160 个文件);正式实现时不带 `--target` 跑一遍,源码与测试一起改完(本库 605 个 fix-it、420 个文件)。 +- **native 构建系统下,`migrate` 补的 import 常常带 `internal`。** 在仓库已经 `internal import` 过的模块上(MachOKit 的 `FileIO`、`FileIOBinary`,MachOObjCSection 的 `FileIO`、`MachOKitExtensions`)这是对的;但它对别的模块也写 `internal import X`,而 Swift 6 不许同一个模块里一个文件写 `internal import X`、另一个文件写普通的 `import X`(`ambiguous implicit access level for import of 'Foundation'; it is imported as 'internal' elsewhere`),本库因此 17 个文件编不过。默认构建系统的那次探针补的都是普通 `import`。 - 构建一失败就一处都不改。`MemberImportVisibility` 的迁移模式并不只出警告:本库有 4 处直接报错,必须先手工补 import,`migrate` 才跑得起来: | 位置 | 报错 | 补什么 | @@ -74,16 +75,16 @@ | `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift:164` | `.values` 落到了 dynamic member lookup | `import OrderedCollections` | | `Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift:135` | 同上 | `import OrderedCollections` | -- **`migrate` 补的 import 会遮蔽标准库的名字。** swift-semantic-string 公开声明了 `struct Error`(`Sources/Semantic/Components/Error.swift:8`)和 `struct Numeric`,与 `Swift.Error`、`Swift.Numeric` 同名;还有 `Argument`,与 ArgumentParser 的同名。文件一旦直接 `import Semantic`,裸写的 `Error` 就解析成 `Semantic.Error`。`migrate` 给本库 6 个文件加了 `import Semantic`,其中两处因此编不过:`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:295` 与 `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:180`(`enum …Error: Error` 被当成以 `Semantic.Error` 为 raw type),改成 `Swift.Error` 就好。危险的是不报错的情形:`catch let error as Error`、`is Error` 这类转型照样能编,只是变成永远失败的转型,编译器只给一条警告。 +- **`migrate` 补的 import 会遮蔽标准库的名字。** swift-semantic-string 公开声明了 `struct Error`(`Sources/Semantic/Components/Error.swift:8`)和 `struct Numeric`,与 `Swift.Error`、`Swift.Numeric` 同名;还有 `Argument`,与 ArgumentParser 的同名。文件一旦直接 `import Semantic`,裸写的 `Error` 就解析成 `Semantic.Error`。`migrate` 给本库 6 个文件加了 `import Semantic`,其中两处因此编不过:`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:293` 与 `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:179`(`enum …Error: Error` 被当成以 `Semantic.Error` 为 raw type),改成 `Swift.Error` 就好。危险的是不报错的情形:`catch let error as Error`、`is Error` 这类转型照样能编,只是变成永远失败的转型,编译器只给一条警告。 - 补完上面 6 处、`migrate` 跑完、清单里手加开关之后,Sources 全部编过;测试 target 从第一个失败的文件开始逐个报缺 import(`TypeNameRetentionTests.swift` 缺 `MachOKit`、`SymbolicationTests.swift` 缺 `MachOKitExtensions`),与警告清单一致。 **清单里给 C target 加 `swiftSettings` 是无害的。** `InternalImportsByDefault` 那轮探针在六份清单末尾用同一个循环给所有 target 追加了设置,包括 `MachOKitC`、`MachOSwiftSectionC`、`SwiftSymbolsRegistration` 这些 C target,六个包都照常编过。 ## 提议方案 -1. **MachOKit 进 Swift 6 语言模式。** `Package.swift` 第 1 行改成 `// swift-tools-version: 6.2`(与另外五个兄弟包一致)。tools 6.x 不声明 `swiftLanguageModes` 时默认 Swift 6,不必另写。清单末尾的 `extension SwiftSetting` 里那九项 Swift 6 已经默认开启的 upcoming feature(`ForwardTrailingClosures` 到 `GlobalConcurrency`)在 Swift 6 模式下是空操作,删掉;`SwiftSetting.allCases` 的 `CaseIterable` 扩展随之删除,改用下面的统一开关。`AccessLevelOnImport` 实验特性(只在 debug 开)保留不动,实现时如果编译器提示它多余再删。 +1. **MachOKit 进 Swift 6 语言模式。** `Package.swift` 第 1 行改成 `// swift-tools-version: 6.0`。tools 6.x 不声明 `swiftLanguageModes` 时默认 Swift 6,不必另写。不跟另外五个兄弟包一样用 6.2:fork 的 CI(`.github/workflows/ci.yml`)在 Xcode 16.2 与 Linux 的 Swift 6.0.3 上编,2026-08 的提交「preserve Swift 6.0 dependency compatibility」也专门为 Swift 6.0 工具链保留了依赖范围;6.2 的清单 6.0 读不了。编译器不认识的 upcoming feature 名字(`MemberImportVisibility` 要 6.1,`InferIsolatedConformances` 要 6.2)会被忽略,所以 6.0 照样能编。清单末尾的 `extension SwiftSetting` 里那九项 Swift 6 已经默认开启的 upcoming feature(`ForwardTrailingClosures` 到 `GlobalConcurrency`)在 Swift 6 模式下是空操作,删掉;`SwiftSetting.allCases` 的 `CaseIterable` 扩展随之删除,改用下面的统一开关。`AccessLevelOnImport` 实验特性(只在 debug 开)保留不动,实现时如果编译器提示它多余再删。 2. **六个包的每个 Swift target 统一开启三项特性。** 每份清单在 `let package = Package(...)` 之后加一个循环,给除 `system`、`binary`、`plugin` 以外的所有 target 追加同一组设置;本库沿用 `Package.swift:1541` 已有的常量。test、macro、executable target 都包括在内,`IntegrationTests` 也开(它只编译不运行)。 -3. **源码按三类处理。** 先手工改好「前期调研」里那 6 处(4 处补 import、2 处 `Swift.Error`);再对非测试 target 跑 `swift package migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances`,它在改清单那一步报错是预期的,以它报告的「Applied N fix-its」为准;测试 target 用 `--build-tests` 加三个 `:migrate` 开关构建,照警告逐条手改(补 import、补 `any`、给 `IntegrationTests` 的 conformance 标 `nonisolated`)。最后才加清单里的开关,正式开启后编一遍确认零错误。 +3. **源码由 `migrate` 改,前后各补一手。** 先手工改好「前期调研」里那 6 处(4 处补 import、2 处 `Swift.Error`);再在清单还没开特性时跑 `swift package --build-system native migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances`,源码与测试一起改(补 import、补 `any`、给 `IntegrationTests` 的 conformance 标 `nonisolated`)。本库在改清单那一步报错是预期的,以它报告的「Applied N fix-its」为准,`Package.swift` 的改动丢弃。然后把它写成 `internal import X` 的补丁改回普通 `import X`,除非这个仓库本来就 `internal import` 这个模块。最后才加清单里的开关,正式开启后编一遍确认零错误。 4. **每加一条 `import Semantic`,就检查那个文件里裸写的 `Error`、`Numeric`、`Argument`。** 类型位置一律写成 `Swift.Error` / `Swift.Numeric`;`as Error`、`is Error` 之类的转型与 `catch` 模式逐个看。编译器的「cast always fails」警告按错误对待。 5. **从下往上落地,不为此单独发版。** 顺序是 MachOKit、swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection、本库。这些设置只影响包自身的编译,不改任何公开 API,下游用的仍是已发布的版本,所以各仓库照各自的流程合进集成分支即可,随下一次正常发版带出去。 @@ -103,29 +104,26 @@ | MachOSwiftSection `Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md`、同名 `.html` | 新增 | 本提案与网页版 | 唯一提案 | 1 | | MachOSwiftSection `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案 | 索引 | 1 | | MachOKitExtensions、MachOObjCSection `Documentations/Evolutions/README.md` | 修改 | 各加一行 cross-repository 指向本提案 | 跨仓库提案的约定 | 1 | -| MachOKit `Package.swift:1` | 修改 | `swift-tools-version` 5.10 → 6.2 | 进入 Swift 6 语言模式 | 2 | +| MachOKit `Package.swift:1` | 修改 | `swift-tools-version` 5.10 → 6.0 | 进入 Swift 6 语言模式;6.0 而不是 6.2,CI 的 Swift 6.0 工具链才读得了 | 2 | | MachOKit `Package.swift:76`、`:145–171` · `extension SwiftSetting` | 修改 / 删除 | MachOKit target 不再拼 `SwiftSetting.allCases`;删掉九项 Swift 6 默认特性与 `CaseIterable` 扩展;末尾加统一开关循环 | Swift 6 模式下那九项是空操作;与另外五个包同一写法 | 2 | -| MachOKit `Sources/MachOKit/**`(49 个文件) | 修改 | 补 56 处 import | `MemberImportVisibility` | 2 | +| MachOKit `Sources/MachOKit/**`(49 个文件) | 修改 | 补 56 处 import:55 处 `internal import FileIO` / `FileIOBinary`(MachOKit 本来就这样 import 这两个模块),1 处普通 import | `MemberImportVisibility` | 2 | | MachOKit `Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift` | 修改(可选) | 消掉 2 条 `SendableClosureCaptures` 与 1 条 `AddPreconcurrencyImport` 警告 | Swift 6 模式下仍是警告,不挡编译 | 2 | | swift-semantic-string `Package.swift`(第 94 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | | swift-semantic-string `Sources/Semantic/Components/AnyComponent.swift`、`Frozen/FrozenSemanticString+Codable.swift`、`SemanticString+Conformances.swift` | 修改 | 补 6 处 `any` | `ExistentialAny` | 3 | -| swift-demangling `Package.swift`(第 171 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | +| swift-demangling `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | | swift-demangling `Sources/DemanglingTestingSupport/Required.swift` | 修改 | 补 1 处 `any` | `ExistentialAny` | 3 | -| swift-demangling `Tests/DemanglingTests/DefectRegressionTests.swift`、`NodeTests.swift`、`TransientRemangleParityTests.swift` | 修改 | 补 3 处 import | `MemberImportVisibility` | 3 | -| MachOKitExtensions `Package.swift`(第 390 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 4 | +| swift-demangling `Tests/DemanglingTests/DefectRegressionTests.swift`、`NodeTests.swift`、`TransientRemangleParityTests.swift` | 修改 | 补 3 处 `import SwiftStdlibToolbox`(`migrate` 写成 `internal`,改回普通 import) | `MemberImportVisibility` | 3 | +| MachOKitExtensions `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 4 | | MachOKitExtensions `Sources/MachOKitExtensions/RequiredNonOptional.swift`、`String+.swift`,`Sources/MachODependencies/DependencyLoadName.swift` | 修改 | 1 处 `any`、2 处 import | 两项特性 | 4 | | MachOKitExtensions `Tests/`(5 个文件:`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`CPlusPlusSymbolIndexCensusTests`、`DependencyLoadNameTests`、`SymbolIndexStoreTests`) | 修改 | 2 处 `any`、3 处 import | 两项特性 | 4 | -| MachOObjCSection `Package.swift`(第 421 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 5 | -| MachOObjCSection `Sources/`(`MachOObjCSection` 9、`ObjCCodeReferences` 3、`ObjCMetadataSource`、`ObjCDeclarationRendering`、`ObjCInterface` 各 1) | 修改 | 补 15 处 import | `MemberImportVisibility` | 5 | -| MachOObjCSection `Tests/`(约 19 个文件) | 修改 | 21 处 import、2 处 `any` | 两项特性 | 5 | +| MachOObjCSection `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 5 | +| MachOObjCSection `Sources/`、`Tests/`(33 个文件) | 修改 | 38 个 fix-it:36 处 import(其中 `internal import FileIO` 6 处、`internal import MachOKitExtensions` 12 处沿用本库已有写法,`ObjCTypeDecodeKit`、`ObjCMetadataSource` 改回普通 import)、2 处 `any` | 两项特性 | 5 | | MachOSwiftSection `Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift` | 修改 | 加 `import SwiftObjCInterop` | 迁移模式下第 143 行的 `switch` 报不完备 | 6 | | MachOSwiftSection `Sources/Output/SwiftDiffing/ABIDiffer.swift` | 修改 | 加 `import MachOSwiftSection` | 迁移模式下第 289 行 `.enum` 解析错 | 6 | -| MachOSwiftSection `Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:295`、`Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:180` | 修改 | `: Error` → `: Swift.Error` | `migrate` 补的 `import Semantic` 让 `Error` 解析成 `Semantic.Error` | 6 | -| MachOSwiftSection `Sources/**`(约 258 个文件,其中 `SwiftSectionFixtureSupport` 约 176 个) | 修改 | `swift package migrate` 的 300 个 fix-it:import 与 `any` | 两项特性 | 6 | +| MachOSwiftSection `Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:293`、`Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:179` | 修改 | `: Error` → `: Swift.Error` | `migrate` 补的 `import Semantic` 让 `Error` 解析成 `Semantic.Error` | 6 | +| MachOSwiftSection `Sources/**`、`Tests/**`(420 个文件,其中 `SwiftSectionFixtureSupport` 约 176 个) | 修改 | `swift package --build-system native migrate` 的 605 个 fix-it:import、`any`、`IntegrationTests` 的 33 处 `nonisolated` conformance;`migrate` 写成 `internal import` 的 266 处全部改回普通 import | 三项特性 | 6 | | MachOSwiftSection `Package.swift:1541–1548` 之后、`:1550` 的 Tuist 块之前 | 修改 | 加统一开关循环,用已有的 `.existentialAny`、`.memberImportVisibility`、`.inferIsolatedConformances` | 开启三项特性;放在 Tuist 块之前,Tuist 改写 target 时设置已经在了 | 6 | -| MachOSwiftSection `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift`、`Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift` | 修改 | 加 `import OrderedCollections` | 迁移模式下 `.values` 解析错 | 7 | -| MachOSwiftSection `Tests/**`(约 180 个文件) | 修改 | 手改约 235 处 import、41 处 `any` | 两项特性;`migrate` 不改测试 | 7 | -| MachOSwiftSection `Tests/IntegrationTests/`(`OpaqueTypeTests`、`ObjCAPIEvolutionTests`、`ABIEvolutionTests`、`SwiftDiffableInterfaceBuilderTests`、`SwiftEvolutionInterfaceBuilderTests`、`SwiftInterfaceBuilderTests`) | 修改 | 33 处 conformance 标 `nonisolated` | `InferIsolatedConformances`,保持现有行为 | 7 | +| MachOSwiftSection `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift`、`Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift` | 修改 | 加 `import OrderedCollections` | 迁移模式下 `.values` 解析错 | 6 | | MachOSwiftSection `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 加一节 | 账本 | 9 | ## 架构图 @@ -136,7 +134,7 @@ package language mode upcoming features (every Swift target) ----------------------- --------------------- ------------------------------------------------------ MachOKit (fork) - Swift 5 (tools 5.10) - 9 Swift-6-era features (MachOKit target only) - + Swift 6 (tools 6.2) - ExistentialAny (MachOKit target only) + + Swift 6 (tools 6.0) - ExistentialAny (MachOKit target only) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances swift-semantic-string Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances swift-demangling Swift 6 (tools 6.2) Lifetimes (experimental, two targets, kept) @@ -156,24 +154,27 @@ Package.swift + for target in package.targets where type is not system / binary / plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings + } - // MachOSwiftSection only: Tuist block (TUIST_MAPS_LOCAL_PACKAGE_TESTS) stays after the loop + // swift-demangling, MachOKitExtensions, MachOObjCSection, MachOSwiftSection: + // the Tuist block (TUIST_MAPS_LOCAL_PACKAGE_TESTS) stays after the loop ``` 迁移流程(每个包相同,本库多一步预修): ```text pre-fix sites migrate mode cannot express (MachOSwiftSection: 4 imports + 2 Swift.Error) - -> swift package migrate --to-feature ... (non-test targets; fails at manifest step by design) - -> swift build --build-tests -Xswiftc -enable-upcoming-feature -Xswiftc :migrate - -> fix every remaining warning under Tests/ by hand - -> add the loop to Package.swift + -> swift package --build-system native migrate --to-feature ... + (sources and tests together; MachOSwiftSection fails at the manifest step by design) + -> git checkout Package.swift; turn each added `internal import X` into `import X` + unless the package already imports X internally + -> commit the fix-its; then add the loop to Package.swift -> swift build --build-tests (features on, zero errors) -> swift test -> DEVELOPER_DIR=Xcode-26.6 swift build --build-tests (CI toolchain, Swift 6.3) + -> MachOKit only: CI on Xcode 16.2 and Linux Swift 6.0.3 (workflow_dispatch) ``` ## 详细设计 -**统一开关**(swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection、MachOKit 写在清单末尾): +**统一开关**(swift-semantic-string、MachOKit 写在清单末尾;swift-demangling、MachOKitExtensions、MachOObjCSection 写在末尾的 Tuist 块之前,前面加一段 `// MARK: - Upcoming features` 注释): ```swift let upcomingFeatureSettings: [SwiftSetting] = [ @@ -206,7 +207,7 @@ for target in package.targets where target.type != .system && target.type != .bi **MachOKit 清单**改后的相关部分: ```swift -// swift-tools-version: 6.2 +// swift-tools-version: 6.0 // ... .target( @@ -231,30 +232,27 @@ for target in package.targets where target.type != .system && target.type != .bi } ``` -原来的 `extension SwiftSetting { static let forwardTrailingClosures … }` 与 `extension SwiftSetting: @retroactive CaseIterable` 整段删除。循环要放在清单里 `let machOKit = package.targets.first(...)` 那段 binary-parse-support 依赖处理之后或之前都可以,它只追加 `swiftSettings`。 +原来的 `extension SwiftSetting { static let forwardTrailingClosures … }` 与 `extension SwiftSetting: @retroactive CaseIterable` 整段删除,循环放在清单末尾、binary-parse-support 依赖处理之后,前面加一段注释说明 6.0 的取舍与「不认识的特性名会被忽略」。 **迁移命令**(以本库为例,在 Ultra 的功能 worktree 里,`queued-build` 前缀照写): ```bash -queued-build swift package --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \ +queued-build swift package --build-system native \ + --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Swift6UpcomingFeatures-Migrate \ migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances - -queued-build swift build --build-tests \ - --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \ - -Xswiftc -print-diagnostic-groups \ - -Xswiftc -enable-upcoming-feature -Xswiftc ExistentialAny:migrate \ - -Xswiftc -enable-upcoming-feature -Xswiftc MemberImportVisibility:migrate \ - -Xswiftc -enable-upcoming-feature -Xswiftc InferIsolatedConformances:migrate +git checkout -- Package.swift ``` -第一条退出码是 1 属正常(改清单失败),看输出里的 `Applied N fix-its in M files`。第二条用来列出测试 target 里剩下的警告。日志带 ANSI 颜色与 OSC 8 超链接,按 `[#组名]` 计数前要先去掉转义;同一条诊断会打印两遍(一行摘要、一行带源码框的),按「文件:行:列 + 文字」去重。 +不带 `--target` 就连测试一起改;`--build-system native` 不能省,默认的构建系统改不了测试(见前期调研)。本库退出码是 1 属正常(改清单失败),看输出里的 `Applied N fix-its in M files`;另外五个包退出码是 0,但它们改出的清单同样丢弃,统一用手写的循环。迁移用单独的构建目录,与之后用默认构建系统的验证构建分开。日志带 ANSI 颜色与 OSC 8 超链接,按 `[#组名]` 计数前要先去掉转义;同一条诊断会打印两遍(一行摘要、一行带源码框的),按「文件:行:列 + 文字」去重。 -**手改测试的规则**:`MemberImportVisibility` 的警告形如 `import of module 'X' is required`,在文件的 import 区按字母序补 `import X`(文件里已有 `@testable import X` 或 `@_spi(...) import X` 的,不重复加);`ExistentialAny` 补 `any`;`InferIsolatedConformances` 的警告形如 `conformance of 'T' to 'P' should be marked 'nonisolated'`,照写 `nonisolated P`。补了 `import Semantic` 的文件按「提议方案」第 4 条检查。要是用脚本批量补 import,脚本先给用户看过再跑。 +**`internal import` 的处理**:对 `migrate` 新加的每一行 `internal import X`,看这个仓库的 Sources 与 Tests 里原来有没有 `internal import X`。有(MachOKit 的 `FileIO`、`FileIOBinary`,MachOObjCSection 的 `FileIO`、`MachOKitExtensions`)就保留;没有就改成普通 `import X`,与仓库里绝大多数 import 一致,也不会和别的文件里的普通 `import X` 冲突。补了 `import Semantic` 的文件按「提议方案」第 4 条检查。 ## 替代方案考量 - **MachOKit 保持 tools 5.10,只加 `.enableUpcomingFeature("StrictConcurrency")`。** Swift 5 模式下这只给 complete checking 的警告,不是错误;以后新代码出问题只是多一条警告,达不到另外五个包的约束力。否。 - **MachOKit 保持 tools 5.10,靠 `swiftLanguageVersions: [.version("6")]` 进 Swift 6。** 能少改一行,但 `swiftLanguageVersions` 在 tools 6 已废弃改名,与五个兄弟包写法不一致,跟上游同步时第 1 行的冲突也省不掉(上游以后升 tools-version 照样冲突)。否。 +- **MachOKit 升到 tools 6.2,与五个兄弟包一致。** 草案原本这样定;实现时发现 fork 的 CI 用 Xcode 16.2 与 Linux 的 Swift 6.0.3,6.2 的清单它们读不了。改为 6.0。 +- **测试 target 照警告清单手改,或写脚本批量补 import。** 草案原本这样定(本库测试约 310 处、180 个文件);实现时发现 `migrate` 换成 native 构建系统就能改测试,不再需要手改或脚本。 - **逐个 target 写 `swiftSettings:`,或让 `swift package migrate` 改清单。** 本库有 53 个 target,MachOKitExtensions 24 个、MachOObjCSection 19 个,逐个写容易漏,新加的 target 也得记着写;`migrate` 在本库的清单上直接失败。统一循环一处搞定,新 target 自动带上。选循环。 - **四项全开(再加 `NonisolatedNonsendingByDefault` 与 `InternalImportsByDefault`)。** 2026-11-20 的调研结果摆给用户之后,用户选了只开三项低风险的。理由见「前期调研」第二张表。 - **只开 `ExistentialAny` 与 `InferIsolatedConformances`,不开 `MemberImportVisibility`。** 后者是三项里改动最大、坑最多的(4 处迁移模式硬错误、`Semantic.Error` 遮蔽),但它正是动机里「每个文件的依赖写在自己的 import 里」的来源,而且坑都已经在探针里找全并给出了改法。保留。 diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift index 05c468d7..3bfbe142 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift @@ -65,7 +65,7 @@ protocol NodePrintable { /// `*NodePrintableContext` refinement declares. var context: Context { get set } - var delegate: any NodePrintableDelegate? { get } + var delegate: (any NodePrintableDelegate)? { get } mutating func printName(_ name: Node, options: NodePrintOptions) async } From be27b6fd5143ff6e1b5254eaa09f6deafe94181e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:50:51 +0800 Subject: [PATCH 023/175] docs: add one-closure cross-reader overloads and the Tuist plugin path to the shared test support proposal --- .../draft-shared-macho-testing-support.html | 26 ++++++++++++----- .../draft-shared-macho-testing-support.md | 29 ++++++++++++++++--- 2 files changed, 44 insertions(+), 11 deletions(-) diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.html b/Documentations/Evolutions/draft-shared-macho-testing-support.html index 24f7327f..14a250f5 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.html +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.html @@ -231,14 +231,16 @@

一个夹具测试的调用链

改动地图

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

提议方案

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

非目标

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

详细设计

public func acrossAllReaders<Value: Equatable>(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value public func acrossAllContexts<Value: Equatable>(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value public func usingInProcessOnly<Value: Equatable>(_ work: (InProcessContext) throws -> Value, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + + /// The same work on the subject each reader gives: `work` runs on + /// `fileSubject`, then on `imageSubject`, and the results must agree. + public func acrossAllReaders<Subject, Value: Equatable>(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject) throws -> Value) throws -> Value + /// The same, reading through each subject's context: `fileContext` for + /// `fileSubject`, `imageContext` for `imageSubject`. + public func acrossAllContexts<Subject, Value: Equatable>(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject, any ReadingContext) throws -> Value) throws -> Value }
  • 签名以本包现有的为准,只把泛型参数改成完整的单词(本包的 T 换成 Value),调用点不变。
  • FixtureCompiler 按「语言 + 源码 + 参数」的摘要缓存产物 URL,锁保护;失败把编译器输出原样放进错误。
  • MachOFixtureTests.fixture 的默认实现 fatalError,提醒子类必须给出夹具。
+
@@ -368,20 +378,22 @@

API 演进与废弃策略

落地步骤

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

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

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

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

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

+

决策日志

- 10 条,最近一条:状态 → Accepted + 13 条,最近一条:用量更正
-
日期变更说明
2026-11-20Created as Draft用户希望把本包 TestingSupport 的通用部分搬到 MachOKitExtensions,统一两个包的测试用例。先由只读调研查清可搬与不可搬的部分、两边的重复与分叉,再经两轮澄清提问定下方案。
2026-11-20两个包一起统一,走完整档用户选择。否决:只统一 MKE 内部;先不做。
2026-11-20拆成 MachOFixtureSupport(无 Testing)与 MachOTestingSupport(Testing)用户选择。否决:一个 product。依据 write-tests skill 对外 product 的规则与本包当年的拆法。
2026-11-20测试基类原样搬用户选择。否决:顺便改成 Swift Testing trait(另议)。
2026-11-20本机 cache 统一为进程共用用户选择。否决:两种入口并存。本包依赖新实例的测试逐个复查。
2026-11-20跨读取器统一用闭包式 acrossAllReaders用户选择。否决:统一用参数化(本包 429 处要改写)。
2026-11-20夹具基类泛化为 MachOFixtureTests用户选择。否决:值类型组合(两种形状会并存)。
2026-11-20MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0用户选择。否决:一起发 3.1.0。
2026-11-20按事实或先例自定的四条名字类型改成 struct、#filePath 锚点由调用方传(跨包后锚点位置变了);FixtureCompiler 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。
2026-11-20状态 → Accepted用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。
+
日期变更说明
2026-11-20Created as Draft用户希望把本包 TestingSupport 的通用部分搬到 MachOKitExtensions,统一两个包的测试用例。先由只读调研查清可搬与不可搬的部分、两边的重复与分叉,再经两轮澄清提问定下方案。
2026-11-20两个包一起统一,走完整档用户选择。否决:只统一 MKE 内部;先不做。
2026-11-20拆成 MachOFixtureSupport(无 Testing)与 MachOTestingSupport(Testing)用户选择。否决:一个 product。依据 write-tests skill 对外 product 的规则与本包当年的拆法。
2026-11-20测试基类原样搬用户选择。否决:顺便改成 Swift Testing trait(另议)。
2026-11-20本机 cache 统一为进程共用用户选择。否决:两种入口并存。本包依赖新实例的测试逐个复查。
2026-11-20跨读取器统一用闭包式 acrossAllReaders用户选择。否决:统一用参数化(本包 429 处要改写)。
2026-11-20夹具基类泛化为 MachOFixtureTests用户选择。否决:值类型组合(两种形状会并存)。
2026-11-20MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0用户选择。否决:一起发 3.1.0。
2026-11-20按事实或先例自定的四条名字类型改成 struct、#filePath 锚点由调用方传(跨包后锚点位置变了);FixtureCompiler 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。
2026-11-20状态 → Accepted用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。
2026-11-20加入成对传入、单个闭包的 acrossAllReaders / acrossAllContexts 重载用户问能否加宏减少测试样板。调研:486 处跨读取器调用里 480 处的 image: 闭包只是换了变量名,但每处只重复约一行;做成宏要按命名约定改写标识符,也会让按标识符识别测试的扫描器失效。用户选择改用普通函数重载,并把能改的调用改过去。另一处值得用宏的样板——170 个夹具套件开头的固定 5 行——用户选择另写一份本包提案(@FixtureSuite)。
2026-11-20加入 TuistScript.sh 的改动维护提案 0099 的会话提醒:远程模式下 MKE 是 own-remote,不在扫描 TestingMacros 插件路径的范围内,新的 MachOTestingSupport 会编不过。
2026-11-20用量更正本包手写 xcrun 的测试文件是 57 个(原写 17 个 Swift 夹具),手写选 slice 70 处;都改用共享版本。
+
diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index 41ab0580..ae2d5dbf 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -75,9 +75,11 @@ 3. **`MachOFixtureTests`:不绑定夹具的基类**。子类用一个 `MachOFixture` 值说明夹具从哪来(磁盘路径,或进程里某个锚点地址所在的镜像,以及是否要 `dlopen`);基类据此建出 `machOFile`、`machOImage` 与 `fileContext`、`imageContext`、`inProcessContext`,提供 `acrossAllReaders`、`acrossAllContexts`、`usingInProcessOnly`,签名与本包现在的一致。 4. **本机 cache 统一为进程共用**:`DyldSharedCachePath.current` 与 `DyldCacheTests` 都经 `FullDyldCache.cachedHost` / `DyldCache.host` 的 URL,不写死路径;确实需要新实例的测试显式开一份(`DyldCache(path:)` 照旧可用)。 5. **跨读取器统一用闭包式**:MKE 约 25 个 `@Test(arguments: Reader.allCases)` 的测试改写成 `MachOFixtureTests` 子类里的 `acrossAllReaders`,比对两种读取器的结果相等后再断言。 -6. **MKE 自己的重复辅助全部换成共享版本**(动机一节的表)。 -7. **本包随后改依赖**:两个 support target 依赖 MKE 的新 product,删掉搬走的文件;`MachOFileName` / `MachOImageName` 的 SymbolTests 条目改为对 MKE struct 的 extension;`ExclusiveImageAccess` 保留一个按本包镜像名的便捷初始化;`MachOSwiftSectionFixtureTests` 改成 `MachOFixtureTests` 的子类;17 个 Swift 夹具改用 `FixtureCompiler`;`DyldCache(path: .current)` 的 25 处改为共用实例后,逐个复查依赖新实例的测试。 -8. **发版顺序**:MKE 先收尾 C++ 类恢复发 3.1.0;本提案的 MKE 部分从收尾后的 `main` 切分支,发 3.2.0;本包在 3.2.0 发布后改依赖(之前用 `USING_LOCAL_DEPENDENCIES=1` 本地验证)。 +6. **成对传入、单个闭包的重载**:本包 486 处 `acrossAllReaders` / `acrossAllContexts` 调用里,480 处的 `image:` 闭包只是把 `file:` 闭包里的读取器与被测对象换成 image 版(按读取器命名的被测对象也算在内)。新增两个同名重载,被测对象成对传入、只写一个闭包:`acrossAllReaders(fileSubject, imageSubject) { $0.offset }`;`acrossAllContexts(fileSubject, imageSubject) { subject, context in try subject.mangledTypeName(in: context) }`,`context` 是 `any ReadingContext`,被测 API 收 `some ReadingContext` 时经 SE-0352 隐式打开。先编译验证这两种写法对两种读取器与三种上下文都写得通,再把只差变量名的调用改成单闭包形式;三闭包形式保留给有实质差异的 6 处(`inProcess:` 多一层 `asPointerWrapper`)。名字不变,本包按标识符识别跨读取器测试的 `SuiteBehaviorScanner`(`:150`)不受影响。 +7. **MKE 自己的重复辅助全部换成共享版本**(动机一节的表)。 +8. **本包随后改依赖**:两个 support target 依赖 MKE 的新 product,删掉搬走的文件;`MachOFileName` / `MachOImageName` 的 SymbolTests 条目改为对 MKE struct 的 extension;`ExclusiveImageAccess` 保留一个按本包镜像名的便捷初始化;`MachOSwiftSectionFixtureTests` 改成 `MachOFixtureTests` 的子类;17 个 Swift 夹具与 57 个测试文件里手写的 `xcrun` 调用改用 `FixtureCompiler`,70 处手写的选 slice 改用 `HostSlice`;`DyldCache(path: .current)` 的 25 处改为共用实例后,逐个复查依赖新实例的测试。 +9. **Tuist 开发 workspace**(提案 0099):`TuistScript.sh` 只给角色是 own-path 的包扫描「import Testing 的普通 target」并补 TestingMacros 插件路径(`:686-689` 的 `if role != "own-path"` 之后)。远程模式下 MKE 是 own-remote,它的 `MachOTestingSupport` 用了 `#expect` 等宏,编到它时会报 `plugin for module 'TestingMacros' not found`。改法:把 `testing_support_names` 那几行挪到 `if role != "own-path"` 之前(own-remote 包的检出目录已记在 `packages.tsv`)。在 Ultra 上用 `./TuistScript.sh test` 跑一次远程模式验证。这一条由维护 0099 的会话提醒。 +10. **发版顺序**:MKE 先收尾 C++ 类恢复发 3.1.0;本提案的 MKE 部分从收尾后的 `main` 切分支,发 3.2.0;本包在 3.2.0 发布后改依赖(之前用 `USING_LOCAL_DEPENDENCIES=1` 本地验证)。 ### 非目标 @@ -85,6 +87,8 @@ - 搬 Swift 专用的支持代码(夹具内容、baseline、coverage、快照对比、SymbolTestsCore 相关)。 - 搬测试本身(`CrossReferenceAnalysisTests` 等依赖本包与 MachOObjCSection 的模块)。 - 统一两个包的 `ForwardingMachOReader` / `ForwardingReader`:协议层级不同,本包那份保留。 +- `@FixtureSuite` 宏(本包 170 个夹具套件开头的固定 5 行):只涉及本包的 Swift 夹具覆盖率体系,另写一份本包的提案。 +- 把 `acrossAllReaders` 做成宏:每处只重复约一行,宏得按 `fileX`→`imageX` 的命名约定改写标识符,脆弱,也会让按标识符识别测试的扫描器失效;用上面的普通函数重载代替。 - MachOObjCSection、MachOKitUI 等其他仓库的测试改用新 product:各自另议。 - 给 MKE 加 CI(MKE 0003 记下的后续项,另写提案)。 @@ -94,7 +98,7 @@ |---|---|---|---|---| | MKE `Package.swift` | 修改 | 新增 target 与 product `MachOFixtureSupport`、`MachOTestingSupport`,测试 target `MachOTestingSupportTests`;各测试 target 加依赖;Tuist 适配块留在文件末尾 | 对外发布 | 1 | | MKE `Sources/MachOFixtureSupport/`(`DyldSharedCachePath`、`MachOImageName`、`MachOFileName`、`XcodeMachOFileName`、`DyldCache+Fixture`、`HostSlice`、`ProcessImages`、`FixtureCompiler`、`ForwardingReader`、`TestActor`、`ProcessMemory`、`Printing`) | 新增 | 从本包搬来并改为 `public`;名字类型改成 struct;`.current` 不写死;锚点由调用方传;编译器统一 clang 与 swiftc | 共用的夹具支持 | 1、2 | -| MKE `Sources/MachOTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`MachOFixture`、`MachOFixtureTests`) | 新增 | 搬来并改为 `open` / `public`;新的夹具基类与跨读取器写法 | 共用的测试基类与 trait | 1、2 | +| MKE `Sources/MachOTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`MachOFixture`、`MachOFixtureTests`) | 新增 | 搬来并改为 `open` / `public`;新的夹具基类与跨读取器写法,含成对传入、单个闭包的重载 | 共用的测试基类与 trait | 1、2 | | MKE `Tests/MachOTestingSupportTests/` | 新增 | 搬来 `DyldSharedCachePathTests`、`ExclusiveImageAccessTests`;新增 `FixtureCompilerTests`、`HostSliceTests`、`MachOFixtureTestsTests` | 共享库自己的测试 | 1、2 | | MKE `Tests/MachOKitExtensionsTests/`(`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`DyldCacheImageSearchTests`、`DyldCacheImageIdentifierTests`、`DyldCacheSubCacheLookupTests`、`MachOReaderWrapperTests`、`Support/ForwardingReader.swift`、`Support/ChainedFixupsFixture.swift`) | 修改 / 删除 | 现编 dylib、本机 cache、归档 cache 路径、选 slice、包装读取器改用共享版本 | 去重 | 3 | | MKE `Tests/MachOSymbolsTests/`、`MachODependenciesTests/`、`MachOAddressResolutionTests/`、`MachOReadingTests/` | 修改 | 同上 | 去重 | 3 | @@ -103,6 +107,9 @@ | 本包 `Package.swift` | 修改 | 两个 support target 依赖 MKE 的新 product;去掉不再需要的依赖 | 改依赖 | 5 | | 本包 `Sources/TestSupport/SwiftSectionFixtureSupport/`(`DyldSharedCachePath`、`Extensions` 的通用部分、`MachOFileName`、`MachOImageName`、`XcodeMachOFileName`) | 删除 / 修改 | 删掉搬走的;`MachOFileName` / `MachOImageName` 只剩 SymbolTests 条目的 extension;本包的 `#filePath` 锚点在这里传给 MKE | 改用共享版本 | 5 | | 本包 `Sources/TestSupport/SwiftSectionTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`TestActor`、`ProcessMemory`、`MachOSwiftSectionFixtureTests`、17 个 `*Fixture.swift`) | 删除 / 修改 | 删掉搬走的;`ExclusiveImageAccess` 只剩按本包镜像名的便捷初始化;夹具基类改成 `MachOFixtureTests` 子类;夹具的编译改用 `FixtureCompiler` | 改用共享版本 | 5 | +| 本包 `Tests/MachOSwiftSectionTests/` 里只差变量名的约 480 处 `acrossAllReaders` / `acrossAllContexts` | 修改 | 改成成对传入、单个闭包的重载 | 去掉重复的 `image:` 闭包 | 5 | +| 本包测试里 57 个手写 `xcrun` 的文件、70 处手写选 slice | 修改 | 改用 `FixtureCompiler`、`HostSlice` | 去重 | 5 | +| 本包 `TuistScript.sh` | 修改 | `testing_support_names` 挪到 `if role != "own-path"` 之前 | 远程模式下给 MKE 的 `MachOTestingSupport` 补 TestingMacros 插件路径 | 5 | | 本包 `Tests/SwiftSectionTestingSupportTests/` | 修改 | 删掉随代码搬走的两个测试 | 去重 | 5 | | 本包用 `DyldCache(path: .current)` 的 25 处 | 复查 | 依赖新实例的显式开一份,其余改用共用实例 | 行为统一后的复查 | 5 | | 本包 `AGENTS.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md`、`Documentations/Internal/Modules/README.md`、`ProjectEvolutionLog.md` | 修改 | 测试支持的来源、`ExclusiveImageAccess` 与 `acrossAllReaders` 的出处、锚点规则 | 文档同步 | 6 | @@ -213,6 +220,13 @@ open class MachOFixtureTests { public func acrossAllReaders(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value public func acrossAllContexts(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value public func usingInProcessOnly(_ work: (InProcessContext) throws -> Value, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + + /// The same work on the subject each reader gives: `work` runs on + /// `fileSubject`, then on `imageSubject`, and the results must agree. + public func acrossAllReaders(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject) throws -> Value) throws -> Value + /// The same, reading through each subject's context: `fileContext` for + /// `fileSubject`, `imageContext` for `imageSubject`. + public func acrossAllContexts(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject, any ReadingContext) throws -> Value) throws -> Value } ``` @@ -274,6 +288,8 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): - 行为:`compilerBuildsEachSourceOncePerProcess` - 行为:`compilerFailureCarriesTheDiagnostics` - 行为:`compilerBuildsSwiftAndCPlusPlus` + - 行为:`pairedSubjectsRunOneClosureOnEachReader` + - 行为:`pairedSubjectsOpenTheContextForAnAPITakingSomeReadingContext`(编译验证单闭包写法) 3. **MKE 的测试改用共享版本** —— 动机一节的表,以及 `Tests/CPlusPlusSymbolsTests/` - 行为:MKE 全部测试照常通过,跨读取器的约 25 个测试改写为 `acrossAllReaders` 后断言不变 - 行为:仓库里不再有 `Process` 调用 `xcrun` 的测试辅助、写死 Cryptexes 路径的常量、手写的选 slice @@ -285,6 +301,8 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): - 行为:本包全部测试(`IntegrationTests` 除外,照 `AGENTS.md`)照常通过 - 行为:`SymbolTestsCoreFixtureLoadsThroughTheSharedBaseClass` - 行为:17 个 Swift 夹具经 `FixtureCompiler` 编出、结果与改前一致 + - 行为:约 480 处跨读取器调用改成单闭包形式后,`SuiteBehaviorScanner` 认出的跨读取器测试数不变 + - 行为:`./TuistScript.sh test` 的远程模式在 Ultra 上编过 MKE 的 `MachOTestingSupport` 6. **本包文档** —— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md`、`Modules/README.md`、`ProjectEvolutionLog.md` 收尾判断:MKE 写实现说明(两个 product 的契约:只能链接到测试 target、锚点由调用方传、共用本机 cache);不写使用指南;本包与 MKE 都没有新术语要登记(`ExclusiveImageAccess`、`acrossAllReaders` 已在本包术语里)。 @@ -303,3 +321,6 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-20 | MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0 | 用户选择。否决:一起发 3.1.0。 | | 2026-11-20 | 按事实或先例自定的四条 | 名字类型改成 struct、`#filePath` 锚点由调用方传(跨包后锚点位置变了);`FixtureCompiler` 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。 | | 2026-11-20 | 状态 → Accepted | 用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。 | +| 2026-11-20 | 加入成对传入、单个闭包的 `acrossAllReaders` / `acrossAllContexts` 重载 | 用户问能否加宏减少测试样板。调研:486 处跨读取器调用里 480 处的 `image:` 闭包只是换了变量名,但每处只重复约一行;做成宏要按命名约定改写标识符,也会让按标识符识别测试的扫描器失效。用户选择改用普通函数重载,并把能改的调用改过去。另一处值得用宏的样板——170 个夹具套件开头的固定 5 行——用户选择另写一份本包提案(`@FixtureSuite`)。 | +| 2026-11-20 | 加入 `TuistScript.sh` 的改动 | 维护提案 0099 的会话提醒:远程模式下 MKE 是 own-remote,不在扫描 TestingMacros 插件路径的范围内,新的 `MachOTestingSupport` 会编不过。 | +| 2026-11-20 | 用量更正 | 本包手写 `xcrun` 的测试文件是 57 个(原写 17 个 Swift 夹具),手写选 slice 70 处;都改用共享版本。 | From 03e00826cd0fe7b55b870c71a9fcf055c7625ad4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:51:37 +0800 Subject: [PATCH 024/175] test: spell Swift.Error in the tests the migration made import Semantic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Semantic declares a public struct Error. Once a file imports Semantic directly, a bare Error binds to it: struct …: Error and any Error stop compiling, and a cast to Error would silently never succeed. --- Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift | 4 ++-- .../SymbolTestsCoreIntegrationTests.swift | 2 +- .../CrossImageOpaqueReferenceTests.swift | 4 ++-- .../DiffRendererHeaderFailureTests.swift | 2 +- .../SwiftInterfaceTests/ExtensionContextTypeNameTests.swift | 4 ++-- Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift | 4 ++-- .../OpaqueConstraintRenderingTests.swift | 4 ++-- Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift | 6 +++--- .../OpaqueParameterInMultiDepthExtensionTests.swift | 6 +++--- .../OpaqueParameterWithoutProtocolRequirementTests.swift | 4 ++-- Tests/SwiftInterfaceTests/PrintFailureEventTests.swift | 6 +++--- .../ProjectedOpaqueMemberWitnessTests.swift | 4 ++-- .../PropertyWrapperSynthesizedMemberTests.swift | 4 ++-- .../GenericTypeNameSubstitutionTests.swift | 2 +- 14 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift index fd9401d8..d1809043 100644 --- a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift @@ -30,7 +30,7 @@ struct OpaqueWitnessDumpAnnotationTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque witness dump fixture compilation failed:\n\(diagnostics)" } } @@ -40,7 +40,7 @@ struct OpaqueWitnessDumpAnnotationTests { let clientLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueWitnessDumpFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index e7d5409e..ae07d60c 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -541,7 +541,7 @@ extension STCoreTests { ) let printer = SwiftDeclarationPrinter(in: machOFile) - await #expect(throws: (any Error).self) { + await #expect(throws: (any Swift.Error).self) { _ = try await printer.printExtensionHeader(unreadableExtensionDefinition, level: 1) } } diff --git a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift index 19e2df44..a8ddfb92 100644 --- a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift +++ b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift @@ -39,7 +39,7 @@ struct CrossImageOpaqueReferenceTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "cross-image opaque fixture compilation failed:\n\(diagnostics)" } } @@ -49,7 +49,7 @@ struct CrossImageOpaqueReferenceTests { let clientLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CrossImageOpaqueFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift index 98ebf6f7..aece5139 100644 --- a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift +++ b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift @@ -223,7 +223,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable ) } - private enum UnrenderableDefinitionError: Error { + private enum UnrenderableDefinitionError: Swift.Error { case donorIsNotAStruct } } diff --git a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift index ad5bb092..484292ea 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift @@ -30,12 +30,12 @@ struct ExtensionContextTypeNameTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "extension-context fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ExtensionContextFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift index 5cecc0c0..185c2591 100644 --- a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift +++ b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift @@ -38,7 +38,7 @@ struct LegacyDyldInfoBindTests { }() } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("LegacyDyldInfoBindFixture-\(UUID().uuidString)") @@ -76,7 +76,7 @@ struct LegacyDyldInfoBindTests { } }() - private struct LegacyFixtureCompilationError: Error, CustomStringConvertible { + private struct LegacyFixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "Legacy fixture compilation failed:\n\(diagnostics)" } } diff --git a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift index b7387fbd..02d196cd 100644 --- a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift @@ -38,12 +38,12 @@ struct OpaqueConstraintRenderingTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque-constraint fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueConstraintFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift index 18af29f3..c3eaf372 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift @@ -57,12 +57,12 @@ struct OpaqueParameterDepthTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque-parameter depth fixture compilation failed:\n\(diagnostics)" } } - private struct UnexpectedInterface: Error, CustomStringConvertible { + private struct UnexpectedInterface: Swift.Error, CustomStringConvertible { let interface: String var description: String { "the opaque results did not print their own constraints:\n\(interface)" } } @@ -151,7 +151,7 @@ struct OpaqueParameterDepthTests { /// core image exports. private static let inProcessReaderExpectedInterfaceLine = "var foreignValues: some Swift.Sequence {" - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterDepthFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift index de850352..fcbbb497 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift @@ -31,12 +31,12 @@ struct OpaqueParameterInMultiDepthExtensionTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque-parameter extension-depth fixture compilation failed:\n\(diagnostics)" } } - private struct MissingConstraint: Error, CustomStringConvertible { + private struct MissingConstraint: Swift.Error, CustomStringConvertible { let interface: String var description: String { "the opaque result did not print its constraint:\n\(interface)" } } @@ -61,7 +61,7 @@ struct OpaqueParameterInMultiDepthExtensionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterExtensionDepthFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift index 0407aede..7f808570 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift @@ -39,12 +39,12 @@ struct OpaqueParameterWithoutProtocolRequirementTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque-parameter fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift index 57405104..3aa09d11 100644 --- a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift +++ b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift @@ -90,7 +90,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { ) } - private enum PrintFailureEventTestError: Error { + private enum PrintFailureEventTestError: Swift.Error { case fixtureTypeIsNotAStruct } @@ -329,7 +329,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { /// write; on the diff path, where no sink existed at all, `case foo(Payload)` /// became `case foo` in silence. @Test func catchWithoutDefinitionIdentityReportsDegradation() async throws { - struct UnrenderableNodeError: Error {} + struct UnrenderableNodeError: Swift.Error {} let collector = SwiftIndexEventCollector() let eventDispatcher = SwiftIndexEvents.Dispatcher() @@ -357,7 +357,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { /// Assert the partition directly; the os_log write itself is not observable /// in-process. @Test func everyFailureEventIsRecognizedByTheFloor() async throws { - struct SomeError: Error {} + struct SomeError: Swift.Error {} let context = SwiftIndexEvents.PrintingContext(name: "Foo", kind: .type) #expect(SwiftIndexEvents.Payload.definitionPrintFailed(context: context, error: SomeError()).unhandledFailureDescription != nil) diff --git a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift index dfbeaeef..8085d377 100644 --- a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift @@ -39,7 +39,7 @@ struct ProjectedOpaqueMemberWitnessTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "projected opaque member fixture compilation failed:\n\(diagnostics)" } } @@ -50,7 +50,7 @@ struct ProjectedOpaqueMemberWitnessTests { let clientInterfaceText: String } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ProjectedOpaqueMemberFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift index ea8b3ee5..700b2465 100644 --- a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift +++ b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift @@ -28,12 +28,12 @@ struct PropertyWrapperSynthesizedMemberTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "property-wrapper fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("PropertyWrapperFixture-\(UUID().uuidString)") diff --git a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift index 921dc6b6..38036bdc 100644 --- a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift +++ b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift @@ -498,7 +498,7 @@ struct GenericTypeNameSubstitutionEndToEndTests: GenericSpecializationTestingEnv "expected LayoutConstrainedInner among outer's typeChildren" ) let layoutRequest = try specializer.makeRequest(for: layoutConstrainedChild.typeContextDescriptorWrapper) - #expect(throws: (any Error).self, + #expect(throws: (any Swift.Error).self, "LayoutConstrainedInner must reject A = Int so the outer catch actually fires") { _ = try specializer.specialize(layoutRequest, with: ["A": .metatype(Int.self)]) } From dd258e97ea081724ac09c2d535c1d4f2c175affe Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:53:43 +0800 Subject: [PATCH 025/175] docs: propose a FixtureSuite macro for fixture suite headers --- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-fixture-suite-macro.html | 307 ++++++++++++++++++ .../Evolutions/draft-fixture-suite-macro.md | 183 +++++++++++ Documentations/README.md | 1 + 4 files changed, 492 insertions(+) create mode 100644 Documentations/Evolutions/draft-fixture-suite-macro.html create mode 100644 Documentations/Evolutions/draft-fixture-suite-macro.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index eae655f1..a86aaf34 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -110,6 +110,7 @@ | draft | [SwiftDeclaration 的目录分成公开模型与索引代码两块](draft-swift-declaration-model-indexing-layout.md) | In Progress | | draft | [SwiftDeclaration 的类型名按角色统一后缀](draft-swift-declaration-type-naming.md) | In Progress | | draft | [测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport](draft-shared-macho-testing-support.md) | Accepted | +| draft | [`@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成](draft-fixture-suite-macro.md) | Draft | | [0098](0098-move-cross-reference-layers.md) | 交叉引用的核心层与 ObjC 层迁出本库,进 MachOKitExtensions 与 MachOObjCSection(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.html b/Documentations/Evolutions/draft-fixture-suite-macro.html new file mode 100644 index 00000000..21dcaccb --- /dev/null +++ b/Documentations/Evolutions/draft-fixture-suite-macro.html @@ -0,0 +1,307 @@ + + + + + + +Draft - @FixtureSuite 宏:夹具测试套件开头的固定写法由宏生成 + + + + +
+
+

MachOSwiftSectionEvolutionsDraft

+

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

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

摘要

+

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

+
+ +
+

要你定

+

轻量档:你点头即可开工。

  1. 可以开工吗?
+
+ +
+

架构图

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

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

+ +

展开前后

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

改动地图

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

提议方案

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

非目标

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

详细设计

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

动机

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

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

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

调研

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

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

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

替代方案

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

影响

+

源码兼容性(source compatibility)

+

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

+

ABI 兼容性(条件项)

+

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

+

下游影响

+

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

+

文档与示例

+

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

+

API 演进与废弃策略

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

落地步骤

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

决策日志

+
+ 3 条,最近一条:宏与协议同名 FixtureSuite +
+
日期变更说明
2026-11-20Created as Draft用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;acrossAllReaders 改用普通函数重载(归 draft-shared-macho-testing-support)。用户选择把这个宏另写一份本包提案。
2026-11-20宏实现放新 target SwiftSectionTestingMacros生产代码链接的 SwiftSectionMacros 插件不带测试用的宏。
2026-11-20宏与协议同名 FixtureSuite照 Observation 的 Observable 先例,@FixtureSuite 读起来就是「这是一个夹具套件」。
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.md b/Documentations/Evolutions/draft-fixture-suite-macro.md new file mode 100644 index 00000000..24db7675 --- /dev/null +++ b/Documentations/Evolutions/draft-fixture-suite-macro.md @@ -0,0 +1,183 @@ +# Draft - `@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成 + +- **状态**: Draft +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: [draft-shared-macho-testing-support](draft-shared-macho-testing-support.md)(同一次「减少测试样板」的讨论里拆出来;那份统一跨包的测试支持,这份只管本包的 Swift 夹具覆盖率体系,两份互不依赖) +- **实现分支 / PR**: 待定(预定 `feature/fixture-suite-macro`,从 `next` 切出) +- **配套文档**: 待定 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +新增 attached 宏 `@FixtureSuite`,挂在夹具测试套件类上,生成 `static let testedTypeName`、`static var registeredTestMethodNames`,并补上对 `FixtureSuite` 协议的遵循。被测类型名默认取类名去掉 `Tests` 后缀,baseline 默认取「类名去掉 `Tests` 加 `Baseline`」;少数例外用参数写明。`SuiteBehaviorScanner` 改为也认宏的写法。`MachOSwiftSectionTests` 里的夹具套件全部改用宏,每处省 3 行。宏的实现放在新的宏 target `SwiftSectionTestingMacros`,声明放在 `SwiftSectionTestingSupport`,只有测试链接它。 + +## 动机 + +- **同样的 5 行写了 176 遍。** `MachOSwiftSectionTests` 里每个夹具套件的开头都是: + + ```swift + @Suite + final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { + static let testedTypeName = "StructDescriptor" + static var registeredTestMethodNames: Set { + StructDescriptorBaseline.registeredTestMethodNames + } + ``` + + (`Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift:16-21`)176 个类声明遵循 `FixtureSuite`;按完整写法匹配的 170 个里,165 个的被测类型名就是类名去掉 `Tests`,只有 5 个例外。 +- **手抄容易抄错。** `testedTypeName` 决定覆盖率不变式按哪个类型检查成员(`FixtureSuite.swift` 的文档注释),抄错一个字母,这个套件就静默地对不上源码里的类型。 +- **起因**:用户问能否给测试加便捷的宏减少样板。调研后,跨读取器写法 `acrossAllReaders` 不适合做宏(改用普通函数重载,归 `draft-shared-macho-testing-support`),套件开头这一处适合,另写本提案。 + +## 前期调研 + +- **协议**:`package protocol FixtureSuite`(`Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/FixtureSuite.swift`),`@MainActor`,两个要求:`static var testedTypeName: String`、`static var registeredTestMethodNames: Set`。 +- **谁读这两个值**: + - 覆盖率不变式测试 `Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift:53-55` 在运行时读 `suite.testedTypeName` 与 `registeredTestMethodNames`——宏生成的成员照样读得到。 + - `SuiteBehaviorScanner`(`Coverage/SuiteBehaviorScanner.swift:118-133`)**按源码语法**读 `testedTypeName`:在类的成员里找 `static` 且初始值是字符串字面量的 `testedTypeName`。宏生成的成员不在源码里,所以扫描器要改,认 `@FixtureSuite` 的参数或类名。它的样例源码在 `Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt`。 + - `BaselineGenerator.writeAllFixtureSuitesIndex`(`Baseline/BaselineGenerator.swift:693-710`)用手维护的类名清单生成 `__Baseline__/AllFixtureSuites.swift`,不读 `testedTypeName`,不受影响。 +- **5 个例外**(类名 → `testedTypeName`、baseline): + - `OpaqueTypeFixtureTests` → `"OpaqueType"`、`OpaqueTypeBaseline`(类名加了 `Fixture` 避开同 target 里的快照套件 `OpaqueTypeTests`,见 `BaselineGenerator.swift:701-704`) + - `EnumFunctionsTests` → `"EnumTagCounts"`、`EnumFunctionsBaseline` + - `TupleTypeMetadataElementTests` → `"Element"`、`TupleTypeMetadataElementBaseline` + - `GenericContextTests` → `"TargetGenericContext"`、`GenericContextBaseline` + - `GenericRequirementContentTests` → `"InvertedProtocols"`、`GenericRequirementContentBaseline` + + baseline 名除 `OpaqueTypeFixtureTests` 外都是「类名去掉 `Tests` 加 `Baseline`」。 +- **现有的宏**:宏 target `SwiftSectionMacros`(`Package.swift:1007-1016`,`Sources/Support/SwiftSectionMacros`,`@Layout` 等),供 `Utilities`、`MachOSwiftSection` 两个生产 target 用;本包没有宏的展开测试。swift-syntax 依赖是 `602.0.0..<605.0.0`(`Package.swift:93`)。 +- **同名先例**:Observation 里协议 `Observable` 与宏 `@Observable` 同名,`@Observable` 解析到宏;本提案的宏与协议同名同理。 +- **宏的硬规则**(`swift-macro-patterns` skill):`conformances:` 只列一定会添加的协议——本宏总是添加 `FixtureSuite`,满足;生成代码里的类型写全名(`Swift.Set`)。 + +## 提议方案 + +1. **宏声明**放在 `SwiftSectionTestingSupport`(夹具套件都 import 它),`package` 可见:member 角色生成两个静态成员,extension 角色添加 `FixtureSuite`。 +2. **宏实现**放在新的宏 target `SwiftSectionTestingMacros`(`Sources/TestSupport/SwiftSectionTestingMacros`),只给 `SwiftSectionTestingSupport` 依赖,生产的 `SwiftSectionMacros` 插件不带测试代码。 +3. **默认值**:`testedTypeName` 取类名去掉 `Tests` 后缀;baseline 取同一个词干加 `Baseline`。类名不以 `Tests` 结尾时报错并给 Fix-It(写明 `testedTypeName:`)。 +4. **参数**:`@FixtureSuite(testedTypeName: "EnumTagCounts")`、`@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self)`。两个参数都只收字面量(字符串字面量、`类型.self`),给变量就报错,不静默退回默认值。 +5. **扫描器**:`SuiteBehaviorScanner` 先看类上有没有 `@FixtureSuite`:有就取 `testedTypeName:` 参数的字面量,没有参数就取类名去掉 `Tests`;没有宏的类照旧读静态成员。 +6. **迁移**:176 个夹具套件全部改用宏——类声明里去掉 `FixtureSuite` 遵循和两个静态成员,挂上 `@FixtureSuite`;5 个例外带参数。 +7. 本包 `AGENTS.md`「添加夹具测试」那几条(`:186` 一带)改成用宏的写法。 + +### 非目标 + +- 给 `MachOFileTests` 等其他基类的子类(`override class var fileName` 之类)做宏:属于基类配置,宏省不了几行。 +- 把 `acrossAllReaders` 做成宏:归 `draft-shared-macho-testing-support`,用普通函数重载。 +- 自动维护 `BaselineGenerator` 里手写的套件清单(`AllFixtureSuites` 的来源)。 +- `@Suite` 与 `ExclusiveImageAccess` 等 trait 的组合:已经只有一行。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 修改 | 新增宏 target `SwiftSectionTestingMacros`(SwiftSyntax、SwiftSyntaxMacros、SwiftCompilerPlugin、SwiftSyntaxBuilder)与测试 target `SwiftSectionTestingMacrosTests`(加 `SwiftSyntaxMacrosGenericTestSupport`);`SwiftSectionTestingSupport` 依赖新宏 target;Tuist 适配块留在文件末尾 | 宏的实现与测试 | 1 | +| `Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift`、`TestingMacroPlugin.swift` | 新增 | `FixtureSuiteMacro`(`MemberMacro`、`ExtensionMacro`):推出类名词干、读两个字面量参数、生成成员与遵循、诊断与 Fix-It | 宏实现 | 1 | +| `Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift` | 新增 | `package macro FixtureSuite(testedTypeName:baseline:)` 声明 | 宏声明 | 1 | +| `Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift` | 新增 | 展开测试:默认、只给 `testedTypeName`、两个都给、类名不以 `Tests` 结尾、参数不是字面量 | 宏的行为 | 1 | +| `Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift` | 修改 | 认 `@FixtureSuite`:取参数或类名词干 | 扫描器按源码读被测类型名 | 2 | +| `Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift`、`Fixtures/SuiteSampleSource.swift.txt` | 修改 | 加宏写法的样例与测试 | 扫描器的行为 | 2 | +| `Tests/MachOSwiftSectionTests/Fixtures/**/*Tests.swift`(176 个夹具套件) | 修改 | 改用 `@FixtureSuite` | 去掉样板 | 3 | +| `AGENTS.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md` | 修改 | 添加夹具测试的写法 | 文档同步 | 4 | + +## 架构图 + +```text +Package (MachOSwiftSection) + SwiftSectionMacros (macro) @Layout, ... (unchanged, production) ++ SwiftSectionTestingMacros (macro) FixtureSuiteMacro: member + extension + SwiftSectionFixtureSupport + Coverage/FixtureSuite (protocol) (unchanged) +~ Coverage/SuiteBehaviorScanner reads @FixtureSuite too +~ SwiftSectionTestingSupport -> + SwiftSectionTestingMacros ++ macro FixtureSuite(testedTypeName:baseline:) +~ MachOSwiftSectionTests 176 suites: @FixtureSuite ++ SwiftSectionTestingMacrosTests expansion tests +``` + +展开前后: + +```text +@Suite @FixtureSuite +final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { ... } + + ↓ member + static let testedTypeName: Swift.String = "StructDescriptor" + static var registeredTestMethodNames: Swift.Set { StructDescriptorBaseline.registeredTestMethodNames } + ↓ extension +extension StructDescriptorTests: SwiftSectionFixtureSupport.FixtureSuite {} +``` + +## 详细设计 + +```swift +// SwiftSectionTestingSupport +@attached(member, names: named(testedTypeName), named(registeredTestMethodNames)) +@attached(extension, conformances: FixtureSuite) +package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = nil) = + #externalMacro(module: "SwiftSectionTestingMacros", type: "FixtureSuiteMacro") +``` + +- **词干**:类名去掉末尾的 `Tests`。类名不以 `Tests` 结尾且没给 `testedTypeName:` → 诊断「类名不以 Tests 结尾,写明 testedTypeName:」并给 Fix-It。 +- **baseline**:参数写 `X.self` 时取 `X`,否则取「词干 + `Baseline`」。 +- **只收字面量**:`testedTypeName:` 不是字符串字面量(含插值)、`baseline:` 不是 `类型.self` → 诊断落在参数上。 +- **挂错地方**:挂在非 class 声明上 → 诊断。 +- **全名**:生成代码写 `Swift.String`、`Swift.Set`、`SwiftSectionFixtureSupport.FixtureSuite`。 +- **隔离**:套件类继承 `@MainActor` 的 `MachOSwiftSectionFixtureTests`,协议也是 `@MainActor`,生成成员不另加隔离标注。 +- **扫描器**:`SuiteBehaviorVisitor.visit(_ node: ClassDeclSyntax)` 先查 `node.attributes` 里名字最后一段是 `FixtureSuite` 的属性;有 `testedTypeName:` 字符串字面量就用它,否则用类名词干;没有该属性才走现有的静态成员读取。 + +## 替代方案考量 + +- **把宏实现放进现有的 `SwiftSectionMacros`**:少一个 target,但生产代码链接的插件会带上测试用的宏。否决。 +- **只用基类或协议扩展给默认值**:协议扩展能给 `testedTypeName` 一个按类型名推的默认实现(运行时 `String(describing: Self.self)` 去掉 `Tests`),但 `registeredTestMethodNames` 要引用 baseline 类型,运行时拿不到,且扫描器按源码读不到运行时默认值。否决。 +- **做成宏后不改扫描器、保留手写的 `testedTypeName`**:省一行都不到。否决。 + +## 影响 + +### 源码兼容性(source compatibility) + +只改测试支持与测试,对外 product 不变。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +无:新宏 target 与测试支持都不是 product。`draft-shared-macho-testing-support` 落地时,`MachOSwiftSectionFixtureTests` 变成共享基类的子类,`@FixtureSuite` 不受影响;两份提案改到同一批测试文件(这份改类声明,那份改 `acrossAllReaders` 调用),先落地的一份之后,另一份在合并时解冲突。 + +### 文档与示例 + +`AGENTS.md` 的「添加夹具测试」步骤与 `FixtureTestingAndContinuousIntegration.md`。 + +## API 演进与废弃策略 + +- `package` 级别的宏,只给本包测试用,没有对外承诺。 +- 不保留旧写法的兼容:迁移在同一批完成,扫描器两种写法都认,所以中途也不会坏。 + +## 落地步骤 + +1. **宏与展开测试** —— `Package.swift`、`SwiftSectionTestingMacros`、宏声明、`FixtureSuiteMacroTests` + - 行为:`defaultsTakeTheTestedTypeAndBaselineFromTheClassName` + - 行为:`anExplicitTestedTypeNameKeepsTheBaselineFromTheClassName` + - 行为:`anExplicitBaselineIsUsedAsWritten` + - 行为:`aClassNameWithoutTestsAsksForTheTestedTypeName`(诊断加 Fix-It) + - 行为:`aNonLiteralArgumentIsRejected` + - 行为:`theMacroAddsTheFixtureSuiteConformance` +2. **扫描器认宏** —— `SuiteBehaviorScanner`、样例源码与测试 + - 行为:`scannerReadsTheTestedTypeNameFromTheMacroArgument` + - 行为:`scannerTakesTheClassNameStemWhenTheMacroHasNoArgument` + - 行为:`scannerStillReadsAStaticTestedTypeName` +3. **迁移 176 个套件** —— `Tests/MachOSwiftSectionTests/Fixtures/**` + - 行为:覆盖率不变式测试照常通过,迁移前后 `allFixtureSuites` 各套件的 `testedTypeName` 与 `registeredTestMethodNames` 逐个相等 + - 行为:`SuiteBehaviorScanner` 认出的「被测类型 → 测试方法 → 行为」与迁移前逐条相同 +4. **文档** —— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md` + - 收尾判断:实现说明不必单写,`AGENTS.md` 的步骤与宏的文档注释够用;没有新术语。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;`acrossAllReaders` 改用普通函数重载(归 `draft-shared-macho-testing-support`)。用户选择把这个宏另写一份本包提案。 | +| 2026-11-20 | 宏实现放新 target `SwiftSectionTestingMacros` | 生产代码链接的 `SwiftSectionMacros` 插件不带测试用的宏。 | +| 2026-11-20 | 宏与协议同名 `FixtureSuite` | 照 Observation 的 `Observable` 先例,`@FixtureSuite` 读起来就是「这是一个夹具套件」。 | diff --git a/Documentations/README.md b/Documentations/README.md index e8b55ec3..12931946 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -218,6 +218,7 @@ selects names using each access's offset and width. | [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | | [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | | [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | +| [Evolutions/draft-fixture-suite-macro.md](Evolutions/draft-fixture-suite-macro.md) | **提案 draft**:attached 宏 `@FixtureSuite` 生成夹具测试套件的 `testedTypeName`、`registeredTestMethodNames` 与 `FixtureSuite` 遵循(176 个套件各省 3 行),宏放新的 `SwiftSectionTestingMacros`,`SuiteBehaviorScanner` 改为也认宏的写法。 | | [Evolutions/draft-shared-macho-testing-support.md](Evolutions/draft-shared-macho-testing-support.md) | **提案 draft(Accepted)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | | [Evolutions/draft-swift6-mode-and-upcoming-features.md](Evolutions/draft-swift6-mode-and-upcoming-features.md) | **提案 draft(Accepted)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.2 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [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),不重复登记。提案与专题文档引入新术语时同批登记。 | From 7d00c052394975a9ea50b11f5b33f7afce293b1b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 17:56:11 +0800 Subject: [PATCH 026/175] docs: record where the implementation of swift6-mode-and-upcoming-features departed from the draft MachOKit uses tools 6.0 for its Swift 6.0 CI, migrate runs on the native build system so it fixes tests too, internal imports it adds become plain unless the package already imports that module internally, optional existentials are parenthesized for Swift 6.3, and tests importing Semantic spell Swift.Error. --- ...draft-swift6-mode-and-upcoming-features.md | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md index 3b5f3713..71d04616 100644 --- a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md @@ -108,13 +108,14 @@ | MachOKit `Package.swift:76`、`:145–171` · `extension SwiftSetting` | 修改 / 删除 | MachOKit target 不再拼 `SwiftSetting.allCases`;删掉九项 Swift 6 默认特性与 `CaseIterable` 扩展;末尾加统一开关循环 | Swift 6 模式下那九项是空操作;与另外五个包同一写法 | 2 | | MachOKit `Sources/MachOKit/**`(49 个文件) | 修改 | 补 56 处 import:55 处 `internal import FileIO` / `FileIOBinary`(MachOKit 本来就这样 import 这两个模块),1 处普通 import | `MemberImportVisibility` | 2 | | MachOKit `Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift` | 修改(可选) | 消掉 2 条 `SendableClosureCaptures` 与 1 条 `AddPreconcurrencyImport` 警告 | Swift 6 模式下仍是警告,不挡编译 | 2 | +| MachOKit `Tests/MachOKitTests/MachOPrintTests.swift` · `testFindSymbolByName` | 修改 | 期望的 thunk 名字换成带 `Yb` 的 Swift 6 mangling | Swift 6 模式下未调用的枚举 case 引用推断为 `@Sendable`(SE-0418) | 2 | | swift-semantic-string `Package.swift`(第 94 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | | swift-semantic-string `Sources/Semantic/Components/AnyComponent.swift`、`Frozen/FrozenSemanticString+Codable.swift`、`SemanticString+Conformances.swift` | 修改 | 补 6 处 `any` | `ExistentialAny` | 3 | | swift-demangling `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | -| swift-demangling `Sources/DemanglingTestingSupport/Required.swift` | 修改 | 补 1 处 `any` | `ExistentialAny` | 3 | +| swift-demangling `Sources/DemanglingTestingSupport/Required.swift:8` | 修改 | `error: Error?` → `error: (any Error)?` | `ExistentialAny`;括号是 Swift 6.3 要求的 | 3 | | swift-demangling `Tests/DemanglingTests/DefectRegressionTests.swift`、`NodeTests.swift`、`TransientRemangleParityTests.swift` | 修改 | 补 3 处 `import SwiftStdlibToolbox`(`migrate` 写成 `internal`,改回普通 import) | `MemberImportVisibility` | 3 | | MachOKitExtensions `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 4 | -| MachOKitExtensions `Sources/MachOKitExtensions/RequiredNonOptional.swift`、`String+.swift`,`Sources/MachODependencies/DependencyLoadName.swift` | 修改 | 1 处 `any`、2 处 import | 两项特性 | 4 | +| MachOKitExtensions `Sources/MachOKitExtensions/RequiredNonOptional.swift:8`、`String+.swift`,`Sources/MachODependencies/DependencyLoadName.swift` | 修改 | `(any Error)?`、2 处 import(`BinaryParseSupport` 改回普通 import) | 两项特性 | 4 | | MachOKitExtensions `Tests/`(5 个文件:`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`CPlusPlusSymbolIndexCensusTests`、`DependencyLoadNameTests`、`SymbolIndexStoreTests`) | 修改 | 2 处 `any`、3 处 import | 两项特性 | 4 | | MachOObjCSection `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 5 | | MachOObjCSection `Sources/`、`Tests/`(33 个文件) | 修改 | 38 个 fix-it:36 处 import(其中 `internal import FileIO` 6 处、`internal import MachOKitExtensions` 12 处沿用本库已有写法,`ObjCTypeDecodeKit`、`ObjCMetadataSource` 改回普通 import)、2 处 `any` | 两项特性 | 5 | @@ -124,6 +125,8 @@ | MachOSwiftSection `Sources/**`、`Tests/**`(420 个文件,其中 `SwiftSectionFixtureSupport` 约 176 个) | 修改 | `swift package --build-system native migrate` 的 605 个 fix-it:import、`any`、`IntegrationTests` 的 33 处 `nonisolated` conformance;`migrate` 写成 `internal import` 的 266 处全部改回普通 import | 三项特性 | 6 | | MachOSwiftSection `Package.swift:1541–1548` 之后、`:1550` 的 Tuist 块之前 | 修改 | 加统一开关循环,用已有的 `.existentialAny`、`.memberImportVisibility`、`.inferIsolatedConformances` | 开启三项特性;放在 Tuist 块之前,Tuist 改写 target 时设置已经在了 | 6 | | MachOSwiftSection `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift`、`Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift` | 修改 | 加 `import OrderedCollections` | 迁移模式下 `.values` 解析错 | 6 | +| MachOSwiftSection `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift:68` | 修改 | `any NodePrintableDelegate?` → `(any NodePrintableDelegate)?` | Swift 6.4 的 fix-it 写法 Swift 6.3 不接受 | 6 | +| MachOSwiftSection `Tests/`(14 个文件:`OpaqueWitnessDumpAnnotationTests`、`SymbolTestsCoreIntegrationTests`、`CrossImageOpaqueReferenceTests`、`DiffRendererHeaderFailureTests`、`ExtensionContextTypeNameTests`、`LegacyDyldInfoBindTests`、`OpaqueConstraintRenderingTests`、`OpaqueParameterDepthTests`、`OpaqueParameterInMultiDepthExtensionTests`、`OpaqueParameterWithoutProtocolRequirementTests`、`PrintFailureEventTests`、`ProjectedOpaqueMemberWitnessTests`、`PropertyWrapperSynthesizedMemberTests`、`GenericTypeNameSubstitutionTests`) | 修改 | 28 处类型位置的 `Error` → `Swift.Error` | `migrate` 补的 `import Semantic` 让裸 `Error` 解析成 `Semantic.Error` | 6 | | MachOSwiftSection `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 加一节 | 账本 | 9 | ## 架构图 @@ -293,17 +296,16 @@ upcoming feature 只作用于开启它的 target 本身的编译,不传给依 1. **提案进集成分支,跨仓库登记** —— 改动地图第 1–3 行 - 行为:`proposalIsListedInBothIndexes`、`siblingIndexesPointAtTheProposal` 2. **MachOKit 进 Swift 6 并开三项特性**(fork 的 `.worktrees/MachOKit-Swift6UpcomingFeatures`,从 `next` 切) —— 第 4–7 行 - - 行为:`machOKitTargetsCompileInSwift6Mode`、`machOKitBuildsWithAllThreeUpcomingFeatures`、`machOKitTestsPassSkippingAotCachePrintTests`(已知 5 个环境失败照旧)、`machOKitBuildsWithXcode26_6` + - 行为:`machOKitTargetsCompileInSwift6Mode`、`machOKitBuildsWithAllThreeUpcomingFeatures`、`machOKitTestsPassSkippingAotCachePrintTests`(已知 5 个环境失败照旧)、`machOKitBuildsWithXcode26_6`、`machOKitCIPassesOnSwift6_0`(手动触发 fork 的 `ci.yml`:Xcode 16.2 与 Linux Swift 6.0.3)、`findSymbolByNameLooksUpTheSwift6Mangling` 3. **swift-semantic-string 与 swift-demangling 开三项特性** —— 第 8–12 行 - 行为:`semanticStringBuildsAndTestsWithUpcomingFeatures`、`demanglingBuildsAndTestsWithUpcomingFeatures`、`demanglingLifetimesFeatureStillEnabledInBothTargets`、两者 `buildsWithXcode26_6` 4. **MachOKitExtensions 开三项特性**(从 `origin/main` 切) —— 第 13–15 行 - 行为:`machOKitExtensionsBuildsAndTestsWithUpcomingFeatures`、`buildsWithXcode26_6` 5. **MachOObjCSection 开三项特性** —— 第 16–18 行 - 行为:`machOObjCSectionBuildsAndTestsWithUpcomingFeatures`、`buildsWithXcode26_6` -6. **本库 Sources:预修、migrate、开关** —— 第 19–22 行 - - 行为:`preFixedSitesCompileUnderMigrationMode`、`migrateAppliesAllNonTestFixIts`、`noFileImportingSemanticSpellsBareErrorOrNumeric`、`allNonTestTargetsBuildWithUpcomingFeatures` -7. **本库 Tests:手改剩余警告** —— 第 23–25 行 - - 行为:`allTestTargetsBuildWithUpcomingFeatures`(含 `IntegrationTests`)、`noMigrationWarningRemains` +6. **本库:预修、migrate、开关** —— 第 19–24 行 + - 行为:`preFixedSitesCompileUnderMigrationMode`、`migrateAppliesSourceAndTestFixIts`、`noModuleIsImportedAtTwoAccessLevels`、`noFileImportingSemanticSpellsBareErrorOrNumeric`、`optionalExistentialsAreParenthesizedForSwift6_3`、`allTargetsBuildWithUpcomingFeatures`(含 `IntegrationTests`,Xcode 27.2 与 26.6 都编) +7. **(并入第 6 步)** 草案里「测试照警告手改」这一步不再需要:`--build-system native` 的 `migrate` 连测试一起改了。 8. **本库全量验证** —— 不改代码 - 行为:`fullSuitePassesSkippingIntegrationTests`、`fullSuitePassesWithXcode26_6`、`renderingABVerificationIsByteIdentical`(`SystemFrameworkRenderingVerification.md` 的三条腿,对照组为 `next`;补 import 只改名字解析,A/B 用来兜住遮蔽一类不报错的变化)、`tuistWorkspaceGeneratesAndBuilds`、`noCastAlwaysFailsWarning` 9. **落地** —— 第 26 行 @@ -322,3 +324,9 @@ upcoming feature 只作用于开启它的 target 本身的编译,不传给依 |------|------|------| | 2026-11-20 | Created as Draft | 用户要求把 MachO 系列库迁到 Swift 6、开启严格并发,并评估开启全部新特性的改动量。实测发现五个包已是 Swift 6 模式,只有 MachOKit 停在 Swift 5 且切换后零错误;Swift 7 默认的六项特性逐项量过之后,用户选定「MachOKit 切 Swift 6 + `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`」,另外三项与 `StrictMemorySafety` 不做 | | 2026-11-20 | Accepted | 用户批准,开始实现 | +| 2026-11-20 | MachOKit 用 tools 6.0 | 草案定的 6.2 会让 fork 的 CI(Xcode 16.2、Linux Swift 6.0.3)读不了清单;6.0 同样默认 Swift 6 模式。手动触发的 CI 两项都通过,证明 Swift 6.0 在 Swift 6 模式下能编、不认识的特性名被忽略 | +| 2026-11-20 | 测试也交给 `migrate` | 默认构建系统下 `migrate` 不改测试(450 条测试警告、0 个 fix-it);`--build-system native` 下一遍就改完源码与测试,草案里的手改与批量脚本都不需要了 | +| 2026-11-20 | `internal import` 改回普通 import | native 构建系统下 `migrate` 会写 `internal import X`,在本库与已有的普通 `import X` 冲突(17 个文件报访问级别有歧义)。规则:仓库对这个模块已有 `internal import` 先例的保留,其余改成普通 import | +| 2026-11-20 | `any P?` 改成 `(any P)?` | Swift 6.4 的 fix-it 写出的 `any P?` 在 Swift 6.3(CI 的 Xcode 26.6)下报错;swift-demangling、MachOKitExtensions、本库各一处 | +| 2026-11-20 | 14 个测试文件写 `Swift.Error` | 除了预修的两处,`migrate` 还给 93 个文件加了 `import Semantic`,其中 14 个测试文件里有类型位置的裸 `Error`(`struct …Error: Error`、`any Error`、`(any Error).self`),全部改成 `Swift.Error`;源码里没有,也没有出现「转型永远失败」的警告 | +| 2026-11-20 | MachOKit 一个测试的期望符号名 | `MachOPrintTests.testFindSymbolByName` 按名字找测试二进制里的一个 curry thunk;Swift 6 模式把对 `LoadCommand.dylib` 的未调用引用推断为 `@Sendable`(SE-0418),mangling 多了 `Yb`,测试改为新名字。其余失败的 5 个用例在基线上同样失败(`libclang_rt.osx.a` 不存在等环境原因) | From 5f4b25a2b56b440c60f7f12ed72c93f526fd637b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 18:00:00 +0800 Subject: [PATCH 027/175] docs: accept the FixtureSuite macro proposal --- Documentations/Evolutions/README.md | 2 +- Documentations/Evolutions/draft-fixture-suite-macro.html | 4 ++-- Documentations/Evolutions/draft-fixture-suite-macro.md | 5 +++-- Documentations/README.md | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index a86aaf34..c016bc8c 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -110,7 +110,7 @@ | draft | [SwiftDeclaration 的目录分成公开模型与索引代码两块](draft-swift-declaration-model-indexing-layout.md) | In Progress | | draft | [SwiftDeclaration 的类型名按角色统一后缀](draft-swift-declaration-type-naming.md) | In Progress | | draft | [测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport](draft-shared-macho-testing-support.md) | Accepted | -| draft | [`@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成](draft-fixture-suite-macro.md) | Draft | +| draft | [`@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成](draft-fixture-suite-macro.md) | Accepted | | [0098](0098-move-cross-reference-layers.md) | 交叉引用的核心层与 ObjC 层迁出本库,进 MachOKitExtensions 与 MachOObjCSection(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.html b/Documentations/Evolutions/draft-fixture-suite-macro.html index 21dcaccb..b237b930 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.html +++ b/Documentations/Evolutions/draft-fixture-suite-macro.html @@ -162,7 +162,7 @@

MachOSwiftSectionEvolutionsDraft

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

-
状态
Draft
+
状态
Accepted
最后更新
2026-11-20
项目类型
库
原文
draft-fixture-suite-macro.md
@@ -179,7 +179,7 @@

摘要

要你定

-

轻量档:你点头即可开工。

  1. 可以开工吗?
+

已批准,实现中。

diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.md b/Documentations/Evolutions/draft-fixture-suite-macro.md index 24db7675..fe85d469 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.md +++ b/Documentations/Evolutions/draft-fixture-suite-macro.md @@ -1,12 +1,12 @@ # Draft - `@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成 -- **状态**: Draft +- **状态**: Accepted - **作者**: JH - **创建日期**: 2026-11-20 - **最后更新**: 2026-11-20 - **所属愿景**: 无 - **关联提案**: [draft-shared-macho-testing-support](draft-shared-macho-testing-support.md)(同一次「减少测试样板」的讨论里拆出来;那份统一跨包的测试支持,这份只管本包的 Swift 夹具覆盖率体系,两份互不依赖) -- **实现分支 / PR**: 待定(预定 `feature/fixture-suite-macro`,从 `next` 切出) +- **实现分支 / PR**: `feature/fixture-suite-macro`,从 `next` 切出;worktree 在 `.worktrees/MachOSwiftSection-FixtureSuiteMacro` - **配套文档**: 待定 - **网页版**: 同目录同名的 `.html` @@ -181,3 +181,4 @@ package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = | 2026-11-20 | Created as Draft | 用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;`acrossAllReaders` 改用普通函数重载(归 `draft-shared-macho-testing-support`)。用户选择把这个宏另写一份本包提案。 | | 2026-11-20 | 宏实现放新 target `SwiftSectionTestingMacros` | 生产代码链接的 `SwiftSectionMacros` 插件不带测试用的宏。 | | 2026-11-20 | 宏与协议同名 `FixtureSuite` | 照 Observation 的 `Observable` 先例,`@FixtureSuite` 读起来就是「这是一个夹具套件」。 | +| 2026-11-20 | 状态 → Accepted | 用户批准,开始实现。 | diff --git a/Documentations/README.md b/Documentations/README.md index 12931946..b3015823 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -218,7 +218,7 @@ selects names using each access's offset and width. | [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | | [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | | [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | -| [Evolutions/draft-fixture-suite-macro.md](Evolutions/draft-fixture-suite-macro.md) | **提案 draft**:attached 宏 `@FixtureSuite` 生成夹具测试套件的 `testedTypeName`、`registeredTestMethodNames` 与 `FixtureSuite` 遵循(176 个套件各省 3 行),宏放新的 `SwiftSectionTestingMacros`,`SuiteBehaviorScanner` 改为也认宏的写法。 | +| [Evolutions/draft-fixture-suite-macro.md](Evolutions/draft-fixture-suite-macro.md) | **提案 draft(Accepted)**:attached 宏 `@FixtureSuite` 生成夹具测试套件的 `testedTypeName`、`registeredTestMethodNames` 与 `FixtureSuite` 遵循(176 个套件各省 3 行),宏放新的 `SwiftSectionTestingMacros`,`SuiteBehaviorScanner` 改为也认宏的写法。 | | [Evolutions/draft-shared-macho-testing-support.md](Evolutions/draft-shared-macho-testing-support.md) | **提案 draft(Accepted)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | | [Evolutions/draft-swift6-mode-and-upcoming-features.md](Evolutions/draft-swift6-mode-and-upcoming-features.md) | **提案 draft(Accepted)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.2 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [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),不重复登记。提案与专题文档引入新术语时同批登记。 | From e086c114f61dfa6d8b4d5eec9a3974b422c6f63b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 18:02:47 +0800 Subject: [PATCH 028/175] feat: generate a fixture suite's FixtureSuite requirements with a macro, and let the scanner read it --- Documentations/Evolutions/README.md | 2 +- .../Evolutions/draft-fixture-suite-macro.md | 2 +- Package.swift | 37 ++++ .../Coverage/SuiteBehaviorScanner.swift | 24 ++- .../FixtureSuiteMacro.swift | 176 ++++++++++++++++ .../TestingMacroPlugin.swift | 9 + .../FixtureSuiteMacro.swift | 27 +++ .../FixtureSuiteMacroTests.swift | 188 ++++++++++++++++++ .../Fixtures/SuiteSampleSource.swift.txt | 23 +++ .../Coverage/SuiteBehaviorScannerTests.swift | 22 ++ 10 files changed, 507 insertions(+), 3 deletions(-) create mode 100644 Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift create mode 100644 Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift create mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift create mode 100644 Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index c016bc8c..54e9fd24 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -110,7 +110,7 @@ | draft | [SwiftDeclaration 的目录分成公开模型与索引代码两块](draft-swift-declaration-model-indexing-layout.md) | In Progress | | draft | [SwiftDeclaration 的类型名按角色统一后缀](draft-swift-declaration-type-naming.md) | In Progress | | draft | [测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport](draft-shared-macho-testing-support.md) | Accepted | -| draft | [`@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成](draft-fixture-suite-macro.md) | Accepted | +| draft | [`@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成](draft-fixture-suite-macro.md) | In Progress | | [0098](0098-move-cross-reference-layers.md) | 交叉引用的核心层与 ObjC 层迁出本库,进 MachOKitExtensions 与 MachOObjCSection(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.md b/Documentations/Evolutions/draft-fixture-suite-macro.md index fe85d469..cdde4f8d 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.md +++ b/Documentations/Evolutions/draft-fixture-suite-macro.md @@ -1,6 +1,6 @@ # Draft - `@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-20 - **最后更新**: 2026-11-20 diff --git a/Package.swift b/Package.swift index 3d9959c9..8db671d2 100644 --- a/Package.swift +++ b/Package.swift @@ -409,6 +409,14 @@ extension Target.Dependency { name: "SwiftSyntaxBuilder", package: "swift-syntax", ) + static let SwiftSyntaxMacroExpansion = Target.Dependency.product( + name: "SwiftSyntaxMacroExpansion", + package: "swift-syntax", + ) + static let SwiftSyntaxMacrosGenericTestSupport = Target.Dependency.product( + name: "SwiftSyntaxMacrosGenericTestSupport", + package: "swift-syntax", + ) static let SwiftTUI = Target.Dependency.product( name: "SwiftTUI", package: "SwiftTUI", @@ -1015,6 +1023,20 @@ extension Target { path: "Sources/Support/SwiftSectionMacros", ) + /// The test support's macros: `@FixtureSuite`. Kept apart from + /// `SwiftSectionMacros`, so the plugin the production targets load + /// carries no test-only macro. + static let SwiftSectionTestingMacros = Target.macro( + name: "SwiftSectionTestingMacros", + dependencies: [ + .product(.SwiftSyntax), + .product(.SwiftSyntaxMacros), + .product(.SwiftCompilerPlugin), + .product(.SwiftSyntaxBuilder), + ], + path: "Sources/TestSupport/SwiftSectionTestingMacros", + ) + // MARK: - Testing /// Fixture-loading helpers, baseline generators, coverage scanners, and @@ -1064,6 +1086,7 @@ extension Target { .target(.SwiftPrinting), .target(.SwiftSpecialization), .target(.SwiftInterface), + .target(.SwiftSectionTestingMacros), .product(.Semantic), ], path: "Sources/TestSupport/SwiftSectionTestingSupport", @@ -1389,6 +1412,18 @@ extension Target { swiftSettings: testSettings, ) + static let SwiftSectionTestingMacrosTests = Target.testTarget( + name: "SwiftSectionTestingMacrosTests", + dependencies: [ + .target(.SwiftSectionTestingMacros), + .product(.SwiftSyntax), + .product(.SwiftSyntaxMacros), + .product(.SwiftSyntaxMacroExpansion), + .product(.SwiftSyntaxMacrosGenericTestSupport), + ], + swiftSettings: testSettings, + ) + static let SwiftSectionTestingSupportTests = Target.testTarget( name: "SwiftSectionTestingSupportTests", dependencies: [ @@ -1500,6 +1535,7 @@ let package = Package( .TypeIndexing, .SwiftSectionKit, .SwiftSectionMacros, + .SwiftSectionTestingMacros, .SwiftSectionFixtureSupport, .SwiftSectionTestingSupport, .SwiftSectionTestingSupportC, @@ -1533,6 +1569,7 @@ let package = Package( .SwiftPrivateDiscriminatorsTests, .SwiftSpecializationTests, .SwiftInterfaceTests, + .SwiftSectionTestingMacrosTests, .SwiftSectionTestingSupportTests, .IntegrationTests, ], diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift index fd5c03e2..f43a77aa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift @@ -79,7 +79,7 @@ private final class SuiteBehaviorVisitor: SyntaxVisitor { private var currentEnclosingClassBodyText: String? override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { - currentTestedTypeName = extractTestedTypeName(from: node.memberBlock) + currentTestedTypeName = Self.testedTypeName(fromFixtureSuiteAttributeOf: node) ?? extractTestedTypeName(from: node.memberBlock) currentEnclosingClassBodyText = node.memberBlock.description return .visitChildren } @@ -116,6 +116,28 @@ private final class SuiteBehaviorVisitor: SyntaxVisitor { return .skipChildren } + /// The tested type's name a `@FixtureSuite` attribute gives the class: + /// its `testedTypeName:` literal, else the class name without its + /// `Tests` suffix — the macro's own rule. `nil` without the attribute. + private static func testedTypeName(fromFixtureSuiteAttributeOf node: ClassDeclSyntax) -> String? { + for element in node.attributes { + guard let attribute = element.as(AttributeSyntax.self), + attribute.attributeName.trimmedDescription.split(separator: ".").last == "FixtureSuite" else { + continue + } + for argument in attribute.arguments?.as(LabeledExprListSyntax.self) ?? [] where argument.label?.text == "testedTypeName" { + if let literal = argument.expression.as(StringLiteralExprSyntax.self) { + let value = literal.segments.compactMap { $0.as(StringSegmentSyntax.self)?.content.text }.joined() + if !value.isEmpty { return value } + } + } + let className = node.name.text + guard className.hasSuffix("Tests"), className.count > "Tests".count else { return nil } + return String(className.dropLast("Tests".count)) + } + return nil + } + private func extractTestedTypeName(from memberBlock: MemberBlockSyntax) -> String? { for member in memberBlock.members { guard let varDecl = member.decl.as(VariableDeclSyntax.self) else { continue } diff --git a/Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift b/Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift new file mode 100644 index 00000000..d280dbd1 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift @@ -0,0 +1,176 @@ +import SwiftDiagnostics +import SwiftSyntax +import SwiftSyntaxBuilder +import SwiftSyntaxMacros + +/// `@FixtureSuite`: the two `FixtureSuite` requirements of a fixture suite +/// class, and its conformance. +/// +/// The tested type's name defaults to the class name without its `Tests` +/// suffix, and the baseline to the same stem followed by `Baseline`: +/// +/// @FixtureSuite +/// final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable {} +/// +/// gets `static let testedTypeName = "StructDescriptor"` and +/// `static var registeredTestMethodNames` returning +/// `StructDescriptorBaseline.registeredTestMethodNames`. Either is named +/// explicitly with a literal: `@FixtureSuite(testedTypeName: "EnumTagCounts")`, +/// `@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self)`. +public struct FixtureSuiteMacro: MemberMacro, ExtensionMacro { + public static func expansion( + of node: AttributeSyntax, + providingMembersOf declaration: some DeclGroupSyntax, + conformingTo protocols: [TypeSyntax], + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { + guard let suite = FixtureSuiteDescription(attribute: node, declaration: declaration, context: context) else { + return [] + } + return [ + "static let testedTypeName: Swift.String = \(literal: suite.testedTypeName)", + """ + static var registeredTestMethodNames: Swift.Set { + \(raw: suite.baselineTypeName).registeredTestMethodNames + } + """, + ] + } + + public static func expansion( + of node: AttributeSyntax, + attachedTo declaration: some DeclGroupSyntax, + providingExtensionsOf type: some TypeSyntaxProtocol, + conformingTo protocols: [TypeSyntax], + in context: some MacroExpansionContext + ) throws -> [ExtensionDeclSyntax] { + // The member role reports a misuse; this role only stays silent. + guard declaration.is(ClassDeclSyntax.self), !protocols.isEmpty else { return [] } + let conformances = protocols.map(\.trimmedDescription).joined(separator: ", ") + return [try ExtensionDeclSyntax("extension \(type.trimmed): \(raw: conformances) {}")] + } +} + +/// What a `@FixtureSuite` attribute and the class it is attached to say. +struct FixtureSuiteDescription { + static let classNameSuffix = "Tests" + + let testedTypeName: String + let baselineTypeName: String + + /// `nil` after diagnosing a misuse. + init?(attribute: AttributeSyntax, declaration: some DeclGroupSyntax, context: some MacroExpansionContext) { + guard let classDeclaration = declaration.as(ClassDeclSyntax.self) else { + context.diagnose(Diagnostic(node: attribute, message: FixtureSuiteDiagnostic.notAClass)) + return nil + } + let className = classDeclaration.name.text + let stem = className.hasSuffix(Self.classNameSuffix) && className.count > Self.classNameSuffix.count + ? String(className.dropLast(Self.classNameSuffix.count)) + : nil + + var explicitTestedTypeName: String? + var explicitBaselineTypeName: String? + for argument in attribute.arguments?.as(LabeledExprListSyntax.self) ?? [] { + switch argument.label?.text { + case "testedTypeName": + if argument.expression.is(NilLiteralExprSyntax.self) { continue } + guard let literal = Self.plainStringLiteral(argument.expression) else { + context.diagnose(Diagnostic(node: argument.expression, message: FixtureSuiteDiagnostic.testedTypeNameIsNotALiteral)) + return nil + } + explicitTestedTypeName = literal + case "baseline": + if argument.expression.is(NilLiteralExprSyntax.self) { continue } + guard let memberAccess = argument.expression.as(MemberAccessExprSyntax.self), + memberAccess.declName.baseName.tokenKind == .keyword(.self), + let base = memberAccess.base else { + context.diagnose(Diagnostic(node: argument.expression, message: FixtureSuiteDiagnostic.baselineIsNotATypeLiteral)) + return nil + } + explicitBaselineTypeName = base.trimmedDescription + default: + continue + } + } + + guard let testedTypeName = explicitTestedTypeName ?? stem, + let baselineTypeName = explicitBaselineTypeName ?? stem.map({ $0 + "Baseline" }) else { + var fixed = attribute + let arguments: LabeledExprListSyntax = [ + LabeledExprSyntax(label: "testedTypeName", expression: StringLiteralExprSyntax(content: explicitTestedTypeName ?? className)) + .with(\.trailingComma, .commaToken(trailingTrivia: .space)), + LabeledExprSyntax(label: "baseline", expression: ExprSyntax("\(raw: explicitBaselineTypeName ?? className + "Baseline").self")), + ] + fixed.leftParen = .leftParenToken() + fixed.arguments = .argumentList(arguments) + fixed.rightParen = .rightParenToken() + context.diagnose(Diagnostic( + node: attribute, + message: FixtureSuiteDiagnostic.classNameHasNoTestsSuffix(className: className), + fixIt: FixIt(message: FixtureSuiteFixIt.nameTheTestedTypeAndBaseline, changes: [.replace(oldNode: Syntax(attribute), newNode: Syntax(fixed))]) + )) + return nil + } + self.testedTypeName = testedTypeName + self.baselineTypeName = baselineTypeName + } + + /// The text of a string literal without interpolation; `nil` for any + /// other expression. + private static func plainStringLiteral(_ expression: ExprSyntax) -> String? { + guard let literal = expression.as(StringLiteralExprSyntax.self) else { return nil } + var text = "" + for segment in literal.segments { + guard let plainSegment = segment.as(StringSegmentSyntax.self) else { return nil } + text += plainSegment.content.text + } + return text + } +} + +enum FixtureSuiteDiagnostic: DiagnosticMessage { + case notAClass + case testedTypeNameIsNotALiteral + case baselineIsNotATypeLiteral + case classNameHasNoTestsSuffix(className: String) + + var message: String { + switch self { + case .notAClass: + "@FixtureSuite applies to a fixture suite class" + case .testedTypeNameIsNotALiteral: + "testedTypeName: must be a string literal without interpolation" + case .baselineIsNotATypeLiteral: + "baseline: must be a type literal such as SomeBaseline.self" + case .classNameHasNoTestsSuffix(let className): + "'\(className)' does not end with 'Tests'; name the tested type and the baseline" + } + } + + var diagnosticID: MessageID { + let identifier = switch self { + case .notAClass: "notAClass" + case .testedTypeNameIsNotALiteral: "testedTypeNameIsNotALiteral" + case .baselineIsNotATypeLiteral: "baselineIsNotATypeLiteral" + case .classNameHasNoTestsSuffix: "classNameHasNoTestsSuffix" + } + return MessageID(domain: "SwiftSectionTestingMacros", id: identifier) + } + + var severity: DiagnosticSeverity { + .error + } +} + +enum FixtureSuiteFixIt: FixItMessage { + case nameTheTestedTypeAndBaseline + + var message: String { + "Name the tested type and the baseline" + } + + var fixItID: MessageID { + MessageID(domain: "SwiftSectionTestingMacros", id: "nameTheTestedTypeAndBaseline") + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift b/Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift new file mode 100644 index 00000000..0ac8ad91 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift @@ -0,0 +1,9 @@ +import SwiftCompilerPlugin +import SwiftSyntaxMacros + +@main +struct TestingMacroPlugin: CompilerPlugin { + let providingMacros: [any Macro.Type] = [ + FixtureSuiteMacro.self, + ] +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift b/Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift new file mode 100644 index 00000000..3ad39007 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift @@ -0,0 +1,27 @@ +import SwiftSectionFixtureSupport + +/// Makes a fixture suite class a ``FixtureSuite``: adds `testedTypeName`, +/// `registeredTestMethodNames` and the conformance. +/// +/// ```swift +/// @Suite +/// @FixtureSuite +/// final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { … } +/// ``` +/// +/// The tested type's name defaults to the class name without its `Tests` +/// suffix (`StructDescriptor`), and the baseline whose +/// `registeredTestMethodNames` the suite reports to the same stem followed by +/// `Baseline` (`StructDescriptorBaseline`). Name either when it differs, with +/// a literal: +/// +/// ```swift +/// @FixtureSuite(testedTypeName: "EnumTagCounts") +/// @FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self) +/// ``` +/// +/// `SuiteBehaviorScanner` reads the tested type's name from this attribute +/// the same way. +@attached(member, names: named(testedTypeName), named(registeredTestMethodNames)) +@attached(extension, conformances: FixtureSuite) +package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = nil) = #externalMacro(module: "SwiftSectionTestingMacros", type: "FixtureSuiteMacro") diff --git a/Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift b/Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift new file mode 100644 index 00000000..d483fe0c --- /dev/null +++ b/Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift @@ -0,0 +1,188 @@ +import Testing +import SwiftSyntaxMacros +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacrosGenericTestSupport +@testable import SwiftSectionTestingMacros + +/// Expansions of `@FixtureSuite`. +@Suite +struct FixtureSuiteMacroTests { + private static let macroSpecs: [String: MacroSpec] = [ + "FixtureSuite": MacroSpec(type: FixtureSuiteMacro.self, conformances: ["FixtureSuite"]), + ] + + private static func assertExpansion( + _ originalSource: String, + expandedSource: String, + diagnostics: [DiagnosticSpec] = [], + applyFixIts: [String]? = nil, + fixedSource: String? = nil, + sourceLocation: SourceLocation = #_sourceLocation + ) { + assertMacroExpansion( + originalSource, + expandedSource: expandedSource, + diagnostics: diagnostics, + macroSpecs: macroSpecs, + applyFixIts: applyFixIts, + fixedSource: fixedSource, + failureHandler: { failure in + Issue.record(Comment(rawValue: failure.message), sourceLocation: sourceLocation) + } + ) + } + + @Test func defaultsTakeTheTestedTypeAndBaselineFromTheClassName() { + Self.assertExpansion( + """ + @FixtureSuite + final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + } + """, + expandedSource: """ + final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + + static let testedTypeName: Swift.String = "StructDescriptor" + + static var registeredTestMethodNames: Swift.Set { + StructDescriptorBaseline.registeredTestMethodNames + } + } + + extension StructDescriptorTests: FixtureSuite { + } + """ + ) + } + + @Test func anExplicitTestedTypeNameKeepsTheBaselineFromTheClassName() { + Self.assertExpansion( + """ + @FixtureSuite(testedTypeName: "EnumTagCounts") + final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + } + """, + expandedSource: """ + final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + + static let testedTypeName: Swift.String = "EnumTagCounts" + + static var registeredTestMethodNames: Swift.Set { + EnumFunctionsBaseline.registeredTestMethodNames + } + } + + extension EnumFunctionsTests: FixtureSuite { + } + """ + ) + } + + @Test func anExplicitBaselineIsUsedAsWritten() { + Self.assertExpansion( + """ + @FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self) + final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + } + """, + expandedSource: """ + final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + + static let testedTypeName: Swift.String = "OpaqueType" + + static var registeredTestMethodNames: Swift.Set { + OpaqueTypeBaseline.registeredTestMethodNames + } + } + + extension OpaqueTypeFixtureTests: FixtureSuite { + } + """ + ) + } + + @Test func aClassNameWithoutTestsAsksForTheTestedTypeName() { + Self.assertExpansion( + """ + @FixtureSuite + final class StructDescriptorChecks: MachOSwiftSectionFixtureTests { + } + """, + expandedSource: """ + final class StructDescriptorChecks: MachOSwiftSectionFixtureTests { + } + + extension StructDescriptorChecks: FixtureSuite { + } + """, + diagnostics: [ + DiagnosticSpec( + message: "'StructDescriptorChecks' does not end with 'Tests'; name the tested type and the baseline", + line: 1, + column: 1, + fixIts: [FixItSpec(message: "Name the tested type and the baseline")] + ), + ], + applyFixIts: ["Name the tested type and the baseline"], + fixedSource: """ + @FixtureSuite(testedTypeName: "StructDescriptorChecks", baseline: StructDescriptorChecksBaseline.self) + final class StructDescriptorChecks: MachOSwiftSectionFixtureTests { + } + """ + ) + } + + @Test func aNonLiteralArgumentIsRejected() { + Self.assertExpansion( + """ + @FixtureSuite(testedTypeName: name) + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + """, + expandedSource: """ + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + + extension StructDescriptorTests: FixtureSuite { + } + """, + diagnostics: [ + DiagnosticSpec(message: "testedTypeName: must be a string literal without interpolation", line: 1, column: 31), + ] + ) + Self.assertExpansion( + """ + @FixtureSuite(baseline: baselineType) + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + """, + expandedSource: """ + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + + extension StructDescriptorTests: FixtureSuite { + } + """, + diagnostics: [ + DiagnosticSpec(message: "baseline: must be a type literal such as SomeBaseline.self", line: 1, column: 25), + ] + ) + } + + @Test func theMacroAppliesOnlyToAClass() { + Self.assertExpansion( + """ + @FixtureSuite + struct StructDescriptorTests { + } + """, + expandedSource: """ + struct StructDescriptorTests { + } + """, + diagnostics: [ + DiagnosticSpec(message: "@FixtureSuite applies to a fixture suite class", line: 1, column: 1), + ] + ) + } +} diff --git a/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt b/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt index 2c6ed5f5..21d69421 100644 --- a/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt +++ b/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt @@ -72,3 +72,26 @@ final class HelperReaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unc #expect(value == 42) } } + +@Suite +@FixtureSuite +final class MacroDefaultTypeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + @Test func macroDefaultMethod() async throws { + let result = try acrossAllReaders( + file: { 1 }, + image: { 1 } + ) + #expect(result == 1) + } +} + +@Suite +@FixtureSuite(testedTypeName: "MacroNamedType") +final class MacroNamedTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + @Test func macroNamedMethod() async throws { + let result = try usingInProcessOnly { context in + 42 + } + #expect(result == 42) + } +} diff --git a/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift b/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift index 5921c641..e2f788a4 100644 --- a/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift @@ -79,4 +79,26 @@ struct SuiteBehaviorScannerTests { let key = MethodKey(typeName: "HelperReaderType", memberName: "helperUsingMethod") #expect(result[key] == .acrossAllReaders) } + + @Test func scannerTakesTheClassNameStemWhenTheMacroHasNoArgument() throws { + let root = try makeScanRoot() + defer { try? FileManager.default.removeItem(at: root) } + let result = try SuiteBehaviorScanner(suiteRoot: root).scan() + #expect(result[MethodKey(typeName: "MacroDefaultType", memberName: "macroDefaultMethod")] == .acrossAllReaders) + } + + @Test func scannerReadsTheTestedTypeNameFromTheMacroArgument() throws { + let root = try makeScanRoot() + defer { try? FileManager.default.removeItem(at: root) } + let result = try SuiteBehaviorScanner(suiteRoot: root).scan() + #expect(result[MethodKey(typeName: "MacroNamedType", memberName: "macroNamedMethod")] == .inProcessOnly) + #expect(result[MethodKey(typeName: "MacroNamed", memberName: "macroNamedMethod")] == nil) + } + + @Test func scannerStillReadsAStaticTestedTypeName() throws { + let root = try makeScanRoot() + defer { try? FileManager.default.removeItem(at: root) } + let result = try SuiteBehaviorScanner(suiteRoot: root).scan() + #expect(result[MethodKey(typeName: "CrossReaderType", memberName: "liveMethod")] == .acrossAllReaders) + } } From ae0cb4e79176f998a77c546f53ac91c10e2bb650 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 18:08:13 +0800 Subject: [PATCH 029/175] test: declare the fixture suites with @FixtureSuite --- AGENTS.md | 2 ++ .../Evolutions/draft-fixture-suite-macro.md | 6 ++++-- .../FixtureTestingAndContinuousIntegration.md | 12 ++++++++++++ .../AccessibleFunctionRecordTests.swift | 8 ++------ .../AnonymousContextDescriptorFlagsTests.swift | 8 ++------ .../AnonymousContextDescriptorProtocolTests.swift | 8 ++------ .../Anonymous/AnonymousContextDescriptorTests.swift | 8 ++------ .../Fixtures/Anonymous/AnonymousContextTests.swift | 8 ++------ .../AssociatedTypeDescriptorTests.swift | 8 ++------ .../AssociatedType/AssociatedTypeRecordTests.swift | 8 ++------ .../AssociatedType/AssociatedTypeTests.swift | 8 ++------ .../BuiltinType/BuiltinTypeDescriptorTests.swift | 8 ++------ .../Fixtures/BuiltinType/BuiltinTypeTests.swift | 8 ++------ .../Fixtures/Capture/CaptureDescriptorTests.swift | 8 ++------ .../Fixtures/Capture/CaptureTypeRecordTests.swift | 8 ++------ .../Fixtures/Capture/MetadataSourceRecordTests.swift | 8 ++------ .../ContextDescriptorFlagsTests.swift | 8 ++------ .../ContextDescriptorKindSpecificFlagsTests.swift | 8 ++------ .../ContextDescriptorKindTests.swift | 8 ++------ .../ContextDescriptorProtocolTests.swift | 8 ++------ .../ContextDescriptor/ContextDescriptorTests.swift | 8 ++------ .../ContextDescriptorWrapperTests.swift | 8 ++------ .../ContextDescriptor/ContextProtocolTests.swift | 8 ++------ .../ContextDescriptor/ContextWrapperTests.swift | 8 ++------ .../NamedContextDescriptorProtocolTests.swift | 8 ++------ .../DispatchClass/DispatchClassMetadataTests.swift | 8 ++------ .../ExistentialMetatypeMetadataTests.swift | 8 ++------ .../ExistentialType/ExistentialTypeFlagsTests.swift | 8 ++------ .../ExistentialTypeMetadataTests.swift | 8 ++------ .../ExtendedExistentialTypeMetadataTests.swift | 8 ++------ .../ExtendedExistentialTypeShapeFlagsTests.swift | 8 ++------ .../ExtendedExistentialTypeShapeTests.swift | 8 ++------ .../NonUniqueExtendedExistentialTypeShapeTests.swift | 8 ++------ .../ExtensionContextDescriptorProtocolTests.swift | 8 ++------ .../Extension/ExtensionContextDescriptorTests.swift | 8 ++------ .../Fixtures/Extension/ExtensionContextTests.swift | 8 ++------ .../FieldDescriptor/FieldDescriptorTests.swift | 8 ++------ .../Fixtures/FieldRecord/FieldRecordFlagsTests.swift | 8 ++------ .../Fixtures/FieldRecord/FieldRecordTests.swift | 8 ++------ .../ForeignType/ForeignClassMetadataTests.swift | 8 ++------ .../ForeignReferenceTypeMetadataTests.swift | 8 ++------ .../Fixtures/Function/FunctionTypeFlagsTests.swift | 8 ++------ .../Function/FunctionTypeMetadataTests.swift | 8 ++------ .../FunctionPointer/AsyncFunctionPointerTests.swift | 8 ++------ .../Generic/GenericContextDescriptorFlagsTests.swift | 8 ++------ .../GenericContextDescriptorHeaderTests.swift | 8 ++------ .../Fixtures/Generic/GenericContextTests.swift | 8 ++------ .../Generic/GenericEnvironmentFlagsTests.swift | 8 ++------ .../Fixtures/Generic/GenericEnvironmentTests.swift | 8 ++------ .../Generic/GenericPackShapeDescriptorTests.swift | 8 ++------ .../Generic/GenericPackShapeHeaderTests.swift | 8 ++------ .../Generic/GenericParamDescriptorTests.swift | 8 ++------ .../Generic/GenericRequirementContentTests.swift | 8 ++------ .../Generic/GenericRequirementDescriptorTests.swift | 8 ++------ .../Generic/GenericRequirementFlagsTests.swift | 8 ++------ .../Fixtures/Generic/GenericRequirementTests.swift | 8 ++------ .../Generic/GenericValueDescriptorTests.swift | 8 ++------ .../Fixtures/Generic/GenericValueHeaderTests.swift | 8 ++------ .../Fixtures/Generic/GenericWitnessTableTests.swift | 8 ++------ .../Pattern/GenericClassMetadataPatternTests.swift | 8 ++------ .../Pattern/GenericMetadataPartialPatternTests.swift | 8 ++------ .../GenericMetadataPatternProtocolTests.swift | 8 ++------ .../Pattern/GenericValueMetadataPatternTests.swift | 8 ++------ .../Pattern/ResilientClassMetadataPatternTests.swift | 8 ++------ .../TypeGenericContextDescriptorHeaderTests.swift | 8 ++------ .../Fixtures/Heap/GenericBoxHeapMetadataTests.swift | 8 ++------ .../Heap/HeapLocalVariableMetadataTests.swift | 8 ++------ .../KeyPath/KeyPathComponentHeaderTests.swift | 8 ++------ .../KeyPath/KeyPathComputedPropertyBodyTests.swift | 8 ++------ .../KeyPath/KeyPathStoredFieldOffsetTests.swift | 8 ++------ .../Fixtures/KeyPath/PropertyDescriptorTests.swift | 8 ++------ .../Fixtures/Mangling/MangledNameTests.swift | 8 ++------ .../Fixtures/Metadata/BorrowTypeMetadataTests.swift | 8 ++------ ...lSpecializedMetadataAccessorsListEntryTests.swift | 8 ++------ ...alSpecializedMetadatasCachingOnceTokenTests.swift | 8 ++------ ...CanonicalSpecializedMetadatasListCountTests.swift | 8 ++------ ...CanonicalSpecializedMetadatasListEntryTests.swift | 8 ++------ .../Metadata/FixedArrayTypeMetadataTests.swift | 8 ++------ .../Fixtures/Metadata/FullMetadataTests.swift | 8 ++------ .../Headers/HeapMetadataHeaderPrefixTests.swift | 8 ++------ .../Metadata/Headers/HeapMetadataHeaderTests.swift | 8 ++------ .../Headers/TypeMetadataHeaderBaseTests.swift | 8 ++------ .../Metadata/Headers/TypeMetadataHeaderTests.swift | 8 ++------ .../Headers/TypeMetadataLayoutPrefixTests.swift | 8 ++------ .../Metadata/MetadataAccessorFunctionTests.swift | 8 ++------ .../Metadata/MetadataBoundsProtocolTests.swift | 8 ++------ .../Fixtures/Metadata/MetadataBoundsTests.swift | 8 ++------ .../ForeignMetadataInitializationTests.swift | 8 ++------ .../SingletonMetadataInitializationTests.swift | 8 ++------ .../Fixtures/Metadata/MetadataProtocolTests.swift | 8 ++------ .../Fixtures/Metadata/MetadataRequestTests.swift | 8 ++------ .../Fixtures/Metadata/MetadataResponseTests.swift | 8 ++------ .../Fixtures/Metadata/MetadataTests.swift | 8 ++------ .../Fixtures/Metadata/MetadataWrapperTests.swift | 8 ++------ .../Fixtures/Metadata/MetatypeMetadataTests.swift | 8 ++------ .../Metadata/SingletonMetadataPointerTests.swift | 8 ++------ .../Module/ModuleContextDescriptorTests.swift | 8 ++------ .../Fixtures/Module/ModuleContextTests.swift | 8 ++------ .../Fixtures/OpaqueType/OpaqueMetadataTests.swift | 8 ++------ .../OpaqueTypeDescriptorProtocolTests.swift | 8 ++------ .../OpaqueType/OpaqueTypeDescriptorTests.swift | 8 ++------ .../Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift | 8 ++------ .../Invertible/InvertibleProtocolSetTests.swift | 8 ++------ .../InvertibleProtocolsRequirementCountTests.swift | 8 ++------ .../Protocol/ObjC/ObjCProtocolPrefixTests.swift | 8 ++------ .../ObjC/RelativeObjCProtocolPrefixTests.swift | 8 ++------ .../Protocol/ProtocolBaseRequirementTests.swift | 8 ++------ .../ProtocolContextDescriptorFlagsTests.swift | 8 ++------ .../Protocol/ProtocolDescriptorFlagsTests.swift | 8 ++------ .../Protocol/ProtocolDescriptorRefTests.swift | 8 ++------ .../Fixtures/Protocol/ProtocolDescriptorTests.swift | 8 ++------ .../Fixtures/Protocol/ProtocolRecordTests.swift | 8 ++------ .../Protocol/ProtocolRequirementFlagsTests.swift | 8 ++------ .../Protocol/ProtocolRequirementKindTests.swift | 8 ++------ .../Fixtures/Protocol/ProtocolRequirementTests.swift | 8 ++------ .../Fixtures/Protocol/ProtocolTests.swift | 8 ++------ .../Protocol/ProtocolWitnessTableTests.swift | 8 ++------ .../Fixtures/Protocol/ResilientWitnessTests.swift | 8 ++------ .../Protocol/ResilientWitnessesHeaderTests.swift | 8 ++------ .../GlobalActorReferenceTests.swift | 8 ++------ .../ProtocolConformanceDescriptorTests.swift | 8 ++------ .../ProtocolConformanceFlagsTests.swift | 8 ++------ .../ProtocolConformanceTests.swift | 8 ++------ .../TupleType/TupleTypeMetadataElementTests.swift | 8 ++------ .../Fixtures/TupleType/TupleTypeMetadataTests.swift | 8 ++------ .../Fixtures/Type/Class/ClassDescriptorTests.swift | 8 ++------ .../Fixtures/Type/Class/ClassFlagsTests.swift | 8 ++------ .../Fixtures/Type/Class/ClassTests.swift | 8 ++------ .../Type/Class/ExtraClassDescriptorFlagsTests.swift | 8 ++------ .../AnyClassMetadataProtocolTests.swift | 8 ++------ .../AnyClassMetadata/AnyClassMetadataTests.swift | 8 ++------ .../AnyClassMetadataObjCInteropProtocolTests.swift | 8 ++------ .../AnyClassMetadataObjCInteropTests.swift | 8 ++------ .../Bounds/ClassMetadataBoundsProtocolTests.swift | 8 ++------ .../Metadata/Bounds/ClassMetadataBoundsTests.swift | 8 ++------ .../Bounds/StoredClassMetadataBoundsTests.swift | 8 ++------ .../Metadata/ClassMetadata/ClassMetadataTests.swift | 8 ++------ .../ClassMetadataObjCInteropTests.swift | 8 ++------ .../Metadata/FinalClassMetadataProtocolTests.swift | 8 ++------ .../Metadata/ObjCClassWrapperMetadataTests.swift | 8 ++------ .../MethodDefaultOverrideDescriptorTests.swift | 8 ++------ .../MethodDefaultOverrideTableHeaderTests.swift | 8 ++------ .../Class/Method/MethodDescriptorFlagsTests.swift | 8 ++------ .../Class/Method/MethodDescriptorKindTests.swift | 8 ++------ .../Type/Class/Method/MethodDescriptorTests.swift | 8 ++------ .../Class/Method/MethodOverrideDescriptorTests.swift | 8 ++------ .../Type/Class/Method/OverrideTableHeaderTests.swift | 8 ++------ .../Class/Method/VTableDescriptorHeaderTests.swift | 8 ++------ .../Resilient/ObjCResilientClassStubInfoTests.swift | 8 ++------ .../Class/Resilient/ResilientSuperclassTests.swift | 8 ++------ .../Fixtures/Type/Enum/EnumDescriptorTests.swift | 8 ++------ .../Fixtures/Type/Enum/EnumFunctionsTests.swift | 8 ++------ .../Fixtures/Type/Enum/EnumTests.swift | 8 ++------ .../Enum/Metadata/EnumMetadataProtocolTests.swift | 8 ++------ .../Type/Enum/Metadata/EnumMetadataTests.swift | 8 ++------ .../Type/Enum/MultiPayloadEnumDescriptorTests.swift | 8 ++------ .../Fixtures/Type/Struct/StructDescriptorTests.swift | 8 ++------ .../Type/Struct/StructMetadataProtocolTests.swift | 8 ++------ .../Fixtures/Type/Struct/StructMetadataTests.swift | 8 ++------ .../Fixtures/Type/Struct/StructTests.swift | 8 ++------ .../Type/TypeContextDescriptorFlagsTests.swift | 8 ++------ .../Type/TypeContextDescriptorProtocolTests.swift | 8 ++------ .../Fixtures/Type/TypeContextDescriptorTests.swift | 8 ++------ .../Type/TypeContextDescriptorWrapperTests.swift | 8 ++------ .../Fixtures/Type/TypeContextWrapperTests.swift | 8 ++------ .../Fixtures/Type/TypeMetadataRecordTests.swift | 8 ++------ .../Fixtures/Type/TypeReferenceTests.swift | 8 ++------ .../Fixtures/Type/ValueMetadataProtocolTests.swift | 8 ++------ .../Fixtures/Type/ValueMetadataTests.swift | 8 ++------ .../Type/ValueTypeDescriptorWrapperTests.swift | 8 ++------ .../Fixtures/ValueWitnessTable/TypeLayoutTests.swift | 8 ++------ .../ValueWitnessTable/ValueWitnessFlagsTests.swift | 8 ++------ .../ValueWitnessTable/ValueWitnessTableTests.swift | 8 ++------ 173 files changed, 358 insertions(+), 1022 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7e44fc2c..d199d191 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -188,6 +188,8 @@ That directory is exhaustively covered by `Tests/MachOSwiftSectionTests/Fixtures 5. `swift package --allow-writing-to-package-directory regen-baselines --suite `. 6. Re-run the affected Suite. +A new Suite is a class marked `@FixtureSuite` (SwiftSectionTestingSupport): the macro adds `testedTypeName` — the class name without `Tests` — and `registeredTestMethodNames` read from `Baseline`, plus the `FixtureSuite` conformance. Name either with a literal only when it differs (`@FixtureSuite(testedTypeName: "EnumTagCounts")`); `SuiteBehaviorScanner` reads the tested type from the attribute the same way. [draft-fixture-suite-macro](Documentations/Evolutions/draft-fixture-suite-macro.md). + A type with genuinely nothing to test goes on the sentinel allowlist with a typed `SentinelReason` (`pureDataUtility` / `runtimeOnly` / `needsFixtureExtension`) in `CoverageAllowlistEntries.swift`. Rationale and history: [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.md b/Documentations/Evolutions/draft-fixture-suite-macro.md index cdde4f8d..8feeba91 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.md +++ b/Documentations/Evolutions/draft-fixture-suite-macro.md @@ -157,14 +157,14 @@ package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = ## 落地步骤 -1. **宏与展开测试** —— `Package.swift`、`SwiftSectionTestingMacros`、宏声明、`FixtureSuiteMacroTests` +1. **宏与展开测试**(完成)—— `Package.swift`、`SwiftSectionTestingMacros`、宏声明、`FixtureSuiteMacroTests` - 行为:`defaultsTakeTheTestedTypeAndBaselineFromTheClassName` - 行为:`anExplicitTestedTypeNameKeepsTheBaselineFromTheClassName` - 行为:`anExplicitBaselineIsUsedAsWritten` - 行为:`aClassNameWithoutTestsAsksForTheTestedTypeName`(诊断加 Fix-It) - 行为:`aNonLiteralArgumentIsRejected` - 行为:`theMacroAddsTheFixtureSuiteConformance` -2. **扫描器认宏** —— `SuiteBehaviorScanner`、样例源码与测试 +2. **扫描器认宏**(完成)—— `SuiteBehaviorScanner`、样例源码与测试 - 行为:`scannerReadsTheTestedTypeNameFromTheMacroArgument` - 行为:`scannerTakesTheClassNameStemWhenTheMacroHasNoArgument` - 行为:`scannerStillReadsAStaticTestedTypeName` @@ -182,3 +182,5 @@ package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = | 2026-11-20 | 宏实现放新 target `SwiftSectionTestingMacros` | 生产代码链接的 `SwiftSectionMacros` 插件不带测试用的宏。 | | 2026-11-20 | 宏与协议同名 `FixtureSuite` | 照 Observation 的 `Observable` 先例,`@FixtureSuite` 读起来就是「这是一个夹具套件」。 | | 2026-11-20 | 状态 → Accepted | 用户批准,开始实现。 | +| 2026-11-20 | 第 1、2 步完成 | 宏的 6 个展开测试与扫描器的 9 个测试在 MacBook 上通过(Ultra 负载过高,按规则分流)。 | +| 2026-11-20 | 套件数更正:171 个,迁 170 个 | 提案里的 176 是 grep 把扫描器样例文本里的几个类也数进去了。`CoroFunctionPointerTests` 自己编夹具、没有 baseline,注册名单是字面量,套不上宏,保持手写。 | diff --git a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md index c286c56b..f51c0141 100644 --- a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md +++ b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md @@ -117,6 +117,18 @@ fixture.framework (SymbolTestsCore) `MethodKey`,在单个 `@Test` 内一并验证;覆盖守护按 `(typeName, memberName)` 比对不区分重载。 - baseline 头部记录 toolchain 版本 + 生成日期;`--suite ` 支持局部重生成以缩小 review 面。 +### 套件头由 `@FixtureSuite` 生成(2026-11-20) + +夹具套件开头原本要手抄三样东西:遵循 `FixtureSuite`、`static let testedTypeName = "X"`、返回 +`XBaseline.registeredTestMethodNames` 的 `registeredTestMethodNames`。171 个套件里 170 个照这个形状写, +被测类型名抄错一个字母,覆盖率守护就静默地对不上源码里的类型。现在由 attached 宏 `@FixtureSuite` +(声明在 `SwiftSectionTestingSupport`,实现在只给测试用的宏 target `SwiftSectionTestingMacros`)生成: +被测类型名默认取类名去掉 `Tests`,baseline 默认取同一个词干加 `Baseline`,不同时用字面量写明 +(`OpaqueTypeFixtureTests`、`EnumFunctionsTests`、`TupleTypeMetadataElementTests`、`GenericContextTests`、 +`GenericRequirementContentTests` 五处)。`SuiteBehaviorScanner` 按源码读被测类型名,所以同时认宏的参数与 +类名词干。`CoroFunctionPointerTests` 自己编夹具、没有 baseline,注册名单是字面量,保持手写。 +提案:[draft-fixture-suite-macro](../Evolutions/draft-fixture-suite-macro.md)。 + ### 信任危机与 sentinel 收紧(2026-05-05) 原始落地被 review 发现**系统性失真**:157 个 suite 里 88 个(56%)从不调用 diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift index 4ff2ef24..ea6a0e65 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// environment pointer is null, and the one generic target, whose is not, so /// the nullable pointer is exercised in both states. @Suite -final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AccessibleFunctionRecord" - static var registeredTestMethodNames: Set { - AccessibleFunctionRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: AccessibleFunctionRecord diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift index 2a92540a..abb43d36 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// descriptor and assert the `rawValue` and the derived `hasMangledName` /// match the baseline; we also verify the `init(rawValue:)` round-trip. @Suite -final class AnonymousContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContextDescriptorFlags" - static var registeredTestMethodNames: Set { - AnonymousContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `AnonymousContextDescriptorFlags` from the /// fixture's first anonymous descriptor against both readers. private func loadFirstFlags() throws -> (file: AnonymousContextDescriptorFlags, image: AnonymousContextDescriptorFlags) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift index d6ce2a62..5c281822 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// The MangledName payload is a deep ABI tree we don't embed as a literal; /// instead we verify cross-reader-consistent results at runtime. @Suite -final class AnonymousContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - AnonymousContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func hasMangledName() async throws { let fileDescriptor = try BaselineFixturePicker.anonymous_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.anonymous_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift index 02b15b6b..e804f32b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `hasMangledName`) live on `AnonymousContextDescriptorProtocol` and are /// covered by `AnonymousContextDescriptorProtocolTests`. @Suite -final class AnonymousContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContextDescriptor" - static var registeredTestMethodNames: Set { - AnonymousContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let fileSubject = try BaselineFixturePicker.anonymous_first(in: machOFile) let imageSubject = try BaselineFixturePicker.anonymous_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift index a147b395..5e3636e6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// established presence-flag pattern (`MangledName` and `GenericContext` /// aren't cheaply Equatable). @Suite -final class AnonymousContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContext" - static var registeredTestMethodNames: Set { - AnonymousContextBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `AnonymousContext` wrapper against both /// readers through their reading contexts. private func loadFirstAnonymousContexts() throws -> (file: AnonymousContext, image: AnonymousContext) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift index 172b3554..a679935f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// to `AssociatedTypeWitnessPatterns.AssociatedPatternProtocol` (5 concrete /// witnesses). @Suite -final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AssociatedTypeDescriptor" - static var registeredTestMethodNames: Set { - AssociatedTypeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadDescriptors() throws -> (file: AssociatedTypeDescriptor, image: AssociatedTypeDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift index 9e6539e4..dca0e66b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `AssociatedTypeWitnessPatterns.ConcreteWitnessTest`'s /// `AssociatedTypeDescriptor` (witnessing `First = Int`). @Suite -final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AssociatedTypeRecord" - static var registeredTestMethodNames: Set { - AssociatedTypeRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadFirstRecord() throws -> (file: AssociatedTypeRecord, image: AssociatedTypeRecord) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift index 02a0164f..83006cea 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// to `AssociatedTypeWitnessPatterns.AssociatedPatternProtocol` (5 concrete /// witnesses). @Suite -final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AssociatedType" - static var registeredTestMethodNames: Set { - AssociatedTypeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadAssociatedTypes() throws -> (file: AssociatedType, image: AssociatedType) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift index 089e852b..bb4c7b83 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "BuiltinTypeDescriptor" - static var registeredTestMethodNames: Set { - BuiltinTypeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadDescriptors() throws -> (file: BuiltinTypeDescriptor, image: BuiltinTypeDescriptor) { let file = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOFile) let image = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift index 92c96244..8a0b7f66 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// `__swift5_builtin` section (matches `BuiltinTypeDescriptorBaseline`'s /// carrier). @Suite -final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "BuiltinType" - static var registeredTestMethodNames: Set { - BuiltinTypeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadBuiltins() throws -> (file: BuiltinType, image: BuiltinType) { let fileDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift index 27371b80..5b3bf8d9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// non-generic closure's context, a closure in a one-parameter generic /// function, and one in a two-parameter generic function. @Suite -final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CaptureDescriptor" - static var registeredTestMethodNames: Set { - CaptureDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: CaptureDescriptor diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift index 4b5a0d2a..679462ff 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// the record's location and the fact that the payload resolves; the payload /// itself is only required to agree across readers. @Suite -final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CaptureTypeRecord" - static var registeredTestMethodNames: Set { - CaptureTypeRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let index: Int let file: CaptureTypeRecord diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift index 810f4369..96d97297 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// in the metadata source grammar, not in Swift's type mangling, and this /// library deliberately reports it unparsed. @Suite -final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataSourceRecord" - static var registeredTestMethodNames: Set { - MetadataSourceRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let index: Int let file: MetadataSourceRecord diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift index 383857a5..5caca616 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// name-only key; we register one entry per name and exercise the /// instance-derivation path here. @Suite -final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorFlags" - static var registeredTestMethodNames: Set { - ContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `ContextDescriptorFlags` from /// `Structs.StructTest`'s descriptor against both readers. private func loadStructTestFlags() throws -> (file: ContextDescriptorFlags, image: ContextDescriptorFlags) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift index 56a1660b..3d6b58fd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// other two `nil`). PublicMemberScanner does NOT emit MethodKey entries /// for enum cases. @Suite -final class ContextDescriptorKindSpecificFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorKindSpecificFlags" - static var registeredTestMethodNames: Set { - ContextDescriptorKindSpecificFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorKindSpecificFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `ContextDescriptorKindSpecificFlags` from /// `Structs.StructTest`'s descriptor against both readers. private func loadStructTestKindSpecificFlags() throws -> (file: ContextDescriptorKindSpecificFlags, image: ContextDescriptorKindSpecificFlags) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift index a05f3496..03332943 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// The kind value is sampled off `Structs.StructTest`'s descriptor — a /// `.struct` kind whose `description == "struct"` and `mangledType == "V"`. @Suite -final class ContextDescriptorKindTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorKind" - static var registeredTestMethodNames: Set { - ContextDescriptorKindBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorKindTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `ContextDescriptorKind` from /// `Structs.StructTest`'s descriptor against both readers. private func loadStructTestKinds() throws -> (file: ContextDescriptorKind, image: ContextDescriptorKind) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift index 3df35e1a..2a3941d4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// `GenericContext?`, etc.) aren't trivially Equatable, so we assert on /// presence flags recorded in the baseline. @Suite -final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - ContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func parent() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift index a64e5d33..c0869367 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// offset of `Structs.StructTest` (the same path `ContextDescriptorWrapper.resolve` /// uses to dispatch on the `kind` byte). @Suite -final class ContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptor" - static var registeredTestMethodNames: Set { - ContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: read the bare `ContextDescriptor` header at the /// `Structs.StructTest` offset against both readers. private func loadStructTestContextDescriptors() throws -> (file: ContextDescriptor, image: ContextDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift index 948c0235..72f07611 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// accessor `false`, `hasTypeContextDescriptor: true`, etc. Broader kind /// coverage lives in the dedicated concrete-kind Suites in Tasks 7-11. @Suite -final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorWrapper" - static var registeredTestMethodNames: Set { - ContextDescriptorWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: build a `ContextDescriptorWrapper` of the /// `Structs.StructTest` descriptor against both readers. private func loadStructTestWrappers() throws -> (file: ContextDescriptorWrapper, image: ContextDescriptorWrapper) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift index 527f81e4..6a1a811f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// We exercise the protocol-extension method through a `Struct` context /// built off `Structs.StructTest`'s descriptor. @Suite -final class ContextProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextProtocol" - static var registeredTestMethodNames: Set { - ContextProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func parent() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift index 5d4f7ce9..6abb5588 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `ContextWrapper.forContextDescriptorWrapper` to produce a /// `.type(.struct(...))` wrapper. @Suite -final class ContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextWrapper" - static var registeredTestMethodNames: Set { - ContextWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: build a `ContextWrapper` of the `Structs.StructTest` /// descriptor against both readers via /// `forContextDescriptorWrapper(_:in:)`. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift index 25ec4eb2..4af6fd47 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `StructDescriptor`. The MangledName payload is a deep ABI tree we don't /// embed as a literal; we assert its presence and the stable `name` string. @Suite -final class NamedContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "NamedContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - NamedContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class NamedContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func name() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift index 52fa77c5..bd26ac7e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift @@ -26,12 +26,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class DispatchClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "DispatchClassMetadata" - static var registeredTestMethodNames: Set { - DispatchClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class DispatchClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Mangled symbol of the metadata accessor for /// `SymbolTestsCore.Classes.ClassTest`. Used by `fixtureMetadata(symbol:)` /// to obtain the runtime-allocated class metadata pointer. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift index 87fa4fd6..8206eaf9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ExistentialMetatypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExistentialMetatypeMetadata" - static var registeredTestMethodNames: Set { - ExistentialMetatypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExistentialMetatypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try ExistentialMetatypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyMetatype, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift index cd1b7d76..3ae4187a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// - `AnyObject.self` flags (`0x0`) — anchor `classConstraint` (`.class`); /// `Any.self` reading `.any` is pinned by `FlagWordDecodingTests`. @Suite -final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExistentialTypeFlags" - static var registeredTestMethodNames: Set { - ExistentialTypeFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializer() async throws { let result = try usingInProcessOnly { context in let metadata = try ExistentialTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyExistential, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift index eab4bce0..a25a0ada 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift @@ -24,12 +24,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExistentialTypeMetadata" - static var registeredTestMethodNames: Set { - ExistentialTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try ExistentialTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyExistential, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift index 23cd23a6..6f92547d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift @@ -23,12 +23,8 @@ import SwiftSectionFixtureSupport /// at the language-runtime level. Tests guard the in-process metadata /// access with `if #available` rather than annotating the suite class. @Suite -final class ExtendedExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtendedExistentialTypeMetadata" - static var registeredTestMethodNames: Set { - ExtendedExistentialTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtendedExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { guard #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) else { return } // Returning a struct directly as a tuple is not Equatable, so diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift index 5a8d1fff..56df8788 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// at the language-runtime level. Tests guard the in-process metadata /// access with `if #available` rather than annotating the suite class. @Suite -final class ExtendedExistentialTypeShapeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtendedExistentialTypeShapeFlags" - static var registeredTestMethodNames: Set { - ExtendedExistentialTypeShapeFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtendedExistentialTypeShapeFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializer() async throws { guard #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) else { return } let result = try usingInProcessOnly { context in diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift index f4392031..9d75e8bb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift @@ -23,12 +23,8 @@ import SwiftSectionFixtureSupport /// at the language-runtime level. Tests guard the in-process metadata /// access with `if #available` rather than annotating the suite class. @Suite -final class ExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtendedExistentialTypeShape" - static var registeredTestMethodNames: Set { - ExtendedExistentialTypeShapeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { guard #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) else { return } let flagsRaw = try usingInProcessOnly { context in diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift index 0551e479..2163876c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class NonUniqueExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "NonUniqueExtendedExistentialTypeShape" - static var registeredTestMethodNames: Set { - NonUniqueExtendedExistentialTypeShapeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class NonUniqueExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func syntheticShape() -> NonUniqueExtendedExistentialTypeShape { NonUniqueExtendedExistentialTypeShape( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift index bdf7179e..350c727b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// consistent results at runtime against the presence flag in the /// baseline. @Suite -final class ExtensionContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtensionContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - ExtensionContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtensionContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func extendedContext() async throws { let fileSubject = try BaselineFixturePicker.extension_first(in: machOFile) let imageSubject = try BaselineFixturePicker.extension_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift index 154c6d7d..02ec3d7c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// `PublicMemberScanner` and is covered by /// `ExtensionContextDescriptorProtocolTests`. @Suite -final class ExtensionContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtensionContextDescriptor" - static var registeredTestMethodNames: Set { - ExtensionContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtensionContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let fileSubject = try BaselineFixturePicker.extension_first(in: machOFile) let imageSubject = try BaselineFixturePicker.extension_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift index cee55c32..1108eb56 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `__swift5_types`/`__swift5_types2` records. The optional `genericContext` /// and `extendedContextMangledName` ivars use the presence-flag pattern. @Suite -final class ExtensionContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtensionContext" - static var registeredTestMethodNames: Set { - ExtensionContextBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtensionContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `ExtensionContext` wrapper for the /// fixture's first extension descriptor against both readers. private func loadFirstExtensionContexts() throws -> (file: ExtensionContext, image: ExtensionContext) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift index 87ca2c07..1ea21f25 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// - `structTest` — zero records (StructTest declares only a computed /// property, no stored fields) @Suite -final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FieldDescriptor" - static var registeredTestMethodNames: Set { - FieldDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadGenericStructFieldDescriptors() throws -> (file: FieldDescriptor, image: FieldDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift index 3dc26ed7..c7656d24 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// exercises each membership predicate against synthetic raw values /// embedded in the baseline. @Suite -final class FieldRecordFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FieldRecordFlags" - static var registeredTestMethodNames: Set { - FieldRecordFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FieldRecordFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = FieldRecordFlags(rawValue: FieldRecordFlagsBaseline.allBits.rawValue) #expect(flags.rawValue == FieldRecordFlagsBaseline.allBits.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift index aace6531..517004e1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// the first two to exercise both a concrete-type field and a /// generic-parameter field. @Suite -final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FieldRecord" - static var registeredTestMethodNames: Set { - FieldRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FieldRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadRecords() throws -> (file: [FieldRecord], image: [FieldRecord]) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift index 4c37c8e7..c1344721 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift @@ -27,12 +27,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ForeignClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ForeignClassMetadata" - static var registeredTestMethodNames: Set { - ForeignClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ForeignClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let kindRaw = try usingInProcessOnly { context in let metadata = try ForeignClassMetadata.resolve( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift index a7109dea..ba81cdf6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ForeignReferenceTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ForeignReferenceTypeMetadata" - static var registeredTestMethodNames: Set { - ForeignReferenceTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ForeignReferenceTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func syntheticForeignReference() -> ForeignReferenceTypeMetadata { ForeignReferenceTypeMetadata( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift index 07ff7dfb..93aefd1a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// `isThrowing`, etc.) are pure raw-value bit decoders and are tracked /// via the sentinel allowlist (`pureDataUtilityEntries`). @Suite -final class FunctionTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FunctionTypeFlags" - static var registeredTestMethodNames: Set { - FunctionTypeFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FunctionTypeFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func numberOfParameters() async throws { let result = try usingInProcessOnly { context in try FunctionTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibFunctionIntToVoid, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift index 02278d74..3ac51269 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// assertions strong: a mis-computed offset by even one word lands on /// something else entirely. @Suite -final class FunctionTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FunctionTypeMetadata" - static var registeredTestMethodNames: Set { - FunctionTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FunctionTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let pointer: UnsafeRawPointer diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift index 3ece8a41..f04175aa 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// assertion runs across both readers, because everything the record exposes /// is either a raw word or pure relative-pointer arithmetic. @Suite -final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AsyncFunctionPointer" - static var registeredTestMethodNames: Set { - AsyncFunctionPointerBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: AsyncFunctionPointer diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift index 186e03d3..5538915e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `init(rawValue:)` round-trip against synthetic raw values from the /// baseline. @Suite -final class GenericContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericContextDescriptorFlags" - static var registeredTestMethodNames: Set { - GenericContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let allFlags = GenericContextDescriptorFlags( rawValue: GenericContextDescriptorFlagsBaseline.all.rawValue diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift index 70419ae9..e4dc58c7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// asserts cross-reader equality on `offset` and the four scalar layout /// fields (`numParams`, `numRequirements`, `numKeyArguments`, `flags`). @Suite -final class GenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericContextDescriptorHeader" - static var registeredTestMethodNames: Set { - GenericContextDescriptorHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `GenericContextDescriptorHeader` from the first /// generic extension context against both readers, mirroring the /// generator's pick logic. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift index 6704677d..37649f04 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift @@ -27,12 +27,8 @@ import SwiftSectionFixtureSupport /// - `parameterPack` — typePackHeader/typePacks /// - `invertibleProtocol` — invertedProtocols requirement @Suite -final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TargetGenericContext" - static var registeredTestMethodNames: Set { - GenericContextBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "TargetGenericContext") +final class GenericContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadContextsFromFile( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift index 8209b248..7609c866 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// synthetic raw values from the baseline (no live carrier exists in /// SymbolTestsCore — see the Generator's note). @Suite -final class GenericEnvironmentFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericEnvironmentFlags" - static var registeredTestMethodNames: Set { - GenericEnvironmentFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericEnvironmentFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let max = GenericEnvironmentFlags(rawValue: GenericEnvironmentFlagsBaseline.maxAll.rawValue) #expect(max.rawValue == GenericEnvironmentFlagsBaseline.maxAll.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift index ab0c5e08..86e79a1c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// surface (`offset`, `layout`) for the Coverage Invariant test and /// documents the missing runtime coverage. @Suite -final class GenericEnvironmentTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericEnvironment" - static var registeredTestMethodNames: Set { - GenericEnvironmentBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericEnvironmentTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live carrier surfaced by the static reader — see Generator note. #expect(GenericEnvironmentBaseline.registeredTestMethodNames.contains("layout")) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift index 866b3b13..681eff7f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `ParameterPackRequirementTest` generic struct's /// `typeGenericContext.typePacks` array. @Suite -final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericPackShapeDescriptor" - static var registeredTestMethodNames: Set { - GenericPackShapeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstPack() throws -> (file: GenericPackShapeDescriptor, image: GenericPackShapeDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift index 6ace24aa..c07a81ca 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `ParameterPackRequirementTest` generic struct's /// `typeGenericContext.typePackHeader`. @Suite -final class GenericPackShapeHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericPackShapeHeader" - static var registeredTestMethodNames: Set { - GenericPackShapeHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericPackShapeHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadHeaders() throws -> (file: GenericPackShapeHeader, image: GenericPackShapeHeader) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift index 2ed7e6a5..73d56dec 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// (`GenericStructLayoutRequirement.parameters[0]`), one for a typePack /// parameter (`ParameterPackRequirementTest.parameters[0]`). @Suite -final class GenericParamDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericParamDescriptor" - static var registeredTestMethodNames: Set { - GenericParamDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericParamDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadLayoutRequirementParam0() throws -> (file: GenericParamDescriptor, image: GenericParamDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift index b5b1632d..903c12e6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// `InvertibleProtocolRequirementTest: ~Copyable` /// generic struct, which surfaces a `.invertedProtocols` requirement. @Suite -final class GenericRequirementContentTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "InvertedProtocols" - static var registeredTestMethodNames: Set { - GenericRequirementContentBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "InvertedProtocols") +final class GenericRequirementContentTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInvertedProtocols() throws -> (file: GenericRequirementContent.InvertedProtocols, image: GenericRequirementContent.InvertedProtocols) { let fileDescriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift index 80d8c4bf..f2ea62cd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// - baseClass (`Element: GenericBaseClassForRequirementTest`) /// - sameType (`First == Second`) @Suite -final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericRequirementDescriptor" - static var registeredTestMethodNames: Set { - GenericRequirementDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadFirstRequirement( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift index 6d14e0d3..2f9b0f78 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `hasKeyArgument`, `isValueRequirement`). The Suite exercises each /// branch against synthetic raw values from the baseline. @Suite -final class GenericRequirementFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericRequirementFlags" - static var registeredTestMethodNames: Set { - GenericRequirementFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericRequirementFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = GenericRequirementFlags(rawValue: GenericRequirementFlagsBaseline.protocolWithKey.rawValue) #expect(flags.rawValue == GenericRequirementFlagsBaseline.protocolWithKey.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift index 9e1858f3..342e05c0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// baseClass / sameType) and asserts cross-reader equality of the /// resolved content discriminant against the baseline. @Suite -final class GenericRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericRequirement" - static var registeredTestMethodNames: Set { - GenericRequirementBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericRequirementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadFirstRequirement( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift index 23d8c2e6..fa3d5d8a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// (Phase B7) and asserts cross-reader equality on `offset`, /// `layout.type`, and `type.rawValue`. @Suite -final class GenericValueDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericValueDescriptor" - static var registeredTestMethodNames: Set { - GenericValueDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericValueDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the first `GenericValueDescriptor` from /// `FixedSizeArray`'s generic context against both readers. private func loadFirstValue() throws -> (file: GenericValueDescriptor, image: GenericValueDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift index d0c10ee5..7fe98526 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// (Phase B7) and asserts cross-reader equality on `offset` and /// `layout.numValues`. @Suite -final class GenericValueHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericValueHeader" - static var registeredTestMethodNames: Set { - GenericValueHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericValueHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `GenericValueHeader` from `FixedSizeArray`'s /// generic context against both readers. private func loadValueHeaders() throws -> (file: GenericValueHeader, image: GenericValueHeader) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift index 785924a2..38b4ad06 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// `layout`) for the Coverage Invariant test and documents the missing /// runtime coverage. @Suite -final class GenericWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericWitnessTable" - static var registeredTestMethodNames: Set { - GenericWitnessTableBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericWitnessTableTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live carrier surfaced by the current public API — see // Generator note. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift index 4f8e6e02..65ed6c7d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// simplest generic class in the fixture, and the only pattern that trails a /// partial pattern. @Suite -final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericClassMetadataPattern" - static var registeredTestMethodNames: Set { - GenericClassMetadataPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPatterns() throws -> (file: GenericClassMetadataPattern, image: GenericClassMetadataPattern) { ( file: try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOFile), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift index cd1094c8..b010aad2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `GenericClassNonRequirement`'s class pattern — the one partial pattern /// the fixture contains. @Suite -final class GenericMetadataPartialPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericMetadataPartialPattern" - static var registeredTestMethodNames: Set { - GenericMetadataPartialPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericMetadataPartialPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPartialPatterns() throws -> (file: GenericMetadataPartialPattern, image: GenericMetadataPartialPattern) { let filePattern = try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOFile) let imagePattern = try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift index 9e617f36..667c5880 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// is the one part of the two layouts that must agree, and the class carrier /// is the only one with a trailing partial pattern. @Suite -final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericMetadataPatternProtocol" - static var registeredTestMethodNames: Set { - GenericMetadataPatternProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: any GenericMetadataPatternProtocol diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift index 61081901..31a8bcbb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// context header — so the picker itself exercises /// `TypeGenericContextDescriptorHeader.defaultInstantiationPatternOffset`. @Suite -final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericValueMetadataPattern" - static var registeredTestMethodNames: Set { - GenericValueMetadataPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPatterns() throws -> (file: GenericValueMetadataPattern, image: GenericValueMetadataPattern) { ( file: try BaselineFixturePicker.genericValueMetadataPattern_structNonRequirement(in: machOFile), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift index bd7dfb8e..615b74f7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// field, not through a generic context — that route is what this Suite /// exercises end to end. @Suite -final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientClassMetadataPattern" - static var registeredTestMethodNames: Set { - ResilientClassMetadataPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPatterns() throws -> (file: ResilientClassMetadataPattern, image: ResilientClassMetadataPattern) { ( file: try BaselineFixturePicker.resilientClassMetadataPattern_resilientChild(in: machOFile), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift index 444bb103..901e2aeb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// on `offset` and the four scalar fields exposed via the /// `GenericContextDescriptorHeaderLayout` protocol. @Suite -final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeGenericContextDescriptorHeader" - static var registeredTestMethodNames: Set { - TypeGenericContextDescriptorHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `TypeGenericContextDescriptorHeader` from /// `GenericStructLayoutRequirement` against both readers. private func loadGenericStructLayoutRequirementHeaders() throws -> (file: TypeGenericContextDescriptorHeader, image: TypeGenericContextDescriptorHeader) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift index 9b76321d..f73273ae 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class GenericBoxHeapMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericBoxHeapMetadata" - static var registeredTestMethodNames: Set { - GenericBoxHeapMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericBoxHeapMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = GenericBoxHeapMetadata( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift index 7081a0f0..fa7a0b96 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class HeapLocalVariableMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "HeapLocalVariableMetadata" - static var registeredTestMethodNames: Set { - HeapLocalVariableMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class HeapLocalVariableMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = HeapLocalVariableMetadata( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift index e4c57be0..40277500 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// path pattern, and the header models the pattern encoding too (evolution /// proposal 0025). @Suite -final class KeyPathComponentHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "KeyPathComponentHeader" - static var registeredTestMethodNames: Set { - KeyPathComponentHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class KeyPathComponentHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Shape { let label: String let file: KeyPathComponentHeader diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift index 2cff7d2b..8badc4e2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// relative-pointer arithmetic off the body's own location, so both readers /// must agree, and the values are pinned as literals. @Suite -final class KeyPathComputedPropertyBodyTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "KeyPathComputedPropertyBody" - static var registeredTestMethodNames: Set { - KeyPathComputedPropertyBodyBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class KeyPathComputedPropertyBodyTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private var expected: KeyPathComputedPropertyBodyBaseline.Entry { KeyPathComputedPropertyBodyBaseline.codableClassIdentifier } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift index 59236466..4aa432c7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// exists to make, so both are asserted here. The two remaining cases have no /// fixture carrier and are constructed directly. @Suite -final class KeyPathStoredFieldOffsetTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "KeyPathStoredFieldOffset" - static var registeredTestMethodNames: Set { - KeyPathStoredFieldOffsetBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class KeyPathStoredFieldOffsetTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Shape { let label: String let file: KeyPathStoredFieldOffset diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift index e1b55351..83076909 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// offset only lives in the metadata, and a resilient class's settable /// computed property. Every assertion runs across both readers. @Suite -final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "PropertyDescriptor" - static var registeredTestMethodNames: Set { - PropertyDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Shape { let label: String let file: PropertyDescriptor diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift index 4c807e9f..e3e97845 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// element-array isn't deep-compared because it carries reader- /// specific offset values). @Suite -final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MangledName" - static var registeredTestMethodNames: Set { - MangledNameBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MangledNameTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadMangledNames() throws -> (file: MangledName, image: MangledName) { let fileDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift index ad25f602..5aeeb4e5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class BorrowTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "BorrowTypeMetadata" - static var registeredTestMethodNames: Set { - BorrowTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class BorrowTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = BorrowTypeMetadata( layout: .init(kind: 0x309, referent: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift index e2edefa1..96e508f4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class CanonicalSpecializedMetadataAccessorsListEntryTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadataAccessorsListEntry" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadataAccessorsListEntryBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadataAccessorsListEntryTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `offset` is set by the memberwise initialiser; cross-reader /// agreement is trivial (no MachO read is involved). @Test func offset() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift index 1f5a630e..1b311b8e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class CanonicalSpecializedMetadatasCachingOnceTokenTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadatasCachingOnceToken" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadatasCachingOnceTokenBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadatasCachingOnceTokenTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let token = CanonicalSpecializedMetadatasCachingOnceToken( layout: .init(token: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift index 4493f720..651c5a55 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `SymbolTestsCore` fixture declares no prespecializations, so the type is /// exercised via constant round-trip through `init(rawValue:)` / `rawValue`. @Suite -final class CanonicalSpecializedMetadatasListCountTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadatasListCount" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadatasListCountBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadatasListCountTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `init(rawValue:)` constructs the wrapper from a raw `UInt32`. @Test("init(rawValue:)") func initializerWithRawValue() async throws { let count = CanonicalSpecializedMetadatasListCount( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift index 26a0db65..509c990a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class CanonicalSpecializedMetadatasListEntryTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadatasListEntry" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadatasListEntryBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadatasListEntryTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let entry = CanonicalSpecializedMetadatasListEntry( layout: .init(metadata: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift index ce3a4f1f..85572523 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class FixedArrayTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FixedArrayTypeMetadata" - static var registeredTestMethodNames: Set { - FixedArrayTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FixedArrayTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = FixedArrayTypeMetadata( layout: .init(kind: 0x308, count: 0, element: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift index 26837d62..d54e37c5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class FullMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FullMetadata" - static var registeredTestMethodNames: Set { - FullMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FullMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a `FullMetadata` for `Structs.StructTest` /// from a MachOImage metadata accessor. private func loadFullStructMetadata() throws -> FullMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift index c7f7529a..63624673 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift @@ -24,12 +24,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class HeapMetadataHeaderPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "HeapMetadataHeaderPrefix" - static var registeredTestMethodNames: Set { - HeapMetadataHeaderPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class HeapMetadataHeaderPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `HeapMetadataHeaderPrefix` for `Classes.ClassTest` from /// the loaded MachOImage. The class metadata is loaded as /// `ClassMetadataObjCInterop`; the heap-header prefix lives at diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift index 0bd74276..2bc62277 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class HeapMetadataHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "HeapMetadataHeader" - static var registeredTestMethodNames: Set { - HeapMetadataHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class HeapMetadataHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `HeapMetadataHeader` for `Classes.ClassTest` from the /// loaded MachOImage's metadata accessor. The class metadata is loaded /// as `ClassMetadataObjCInterop`; the heap header lives at diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift index 4b034965..2fda78e1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TypeMetadataHeaderBaseTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataHeaderBase" - static var registeredTestMethodNames: Set { - TypeMetadataHeaderBaseBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataHeaderBaseTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let base = TypeMetadataHeaderBase( layout: .init(valueWitnesses: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift index c4d17616..22525bf2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TypeMetadataHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataHeader" - static var registeredTestMethodNames: Set { - TypeMetadataHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `TypeMetadataHeader` for `Structs.StructTest` from /// the loaded MachOImage's metadata accessor via the full-metadata /// header projection. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift index cb43f8f5..e0cdf694 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TypeMetadataLayoutPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataLayoutPrefix" - static var registeredTestMethodNames: Set { - TypeMetadataLayoutPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataLayoutPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let prefix = TypeMetadataLayoutPrefix( layout: .init(layoutString: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift index ceab142f..072ac7af 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// `init(ptr:)` is `package`-scoped and not visited by `PublicMemberScanner`; /// the six `callAsFunction` overloads collapse to a single `MethodKey`. @Suite -final class MetadataAccessorFunctionTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataAccessorFunction" - static var registeredTestMethodNames: Set { - MetadataAccessorFunctionBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataAccessorFunctionTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `callAsFunction(request:)` invokes the accessor with no metadata or /// witness-table arguments and returns a complete metadata response. @Test func callAsFunction() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift index e8d9545f..7a87375b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `totalSizeInBytes = (neg + pos) * sizeof(UnsafeRawPointer)` /// `addressPointInBytes = neg * sizeof(UnsafeRawPointer)` @Suite -final class MetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataBoundsProtocol" - static var registeredTestMethodNames: Set { - MetadataBoundsProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func makeBounds() -> MetadataBounds { MetadataBounds( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift index 9de65fa2..89e0ea1f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// derived sizes (`totalSizeInBytes`, `addressPointInBytes`) are inherited /// from `MetadataBoundsProtocol` and covered by that Suite. @Suite -final class MetadataBoundsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataBounds" - static var registeredTestMethodNames: Set { - MetadataBoundsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataBoundsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let bounds = MetadataBounds( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift index 938a2c58..6780b6ae 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ForeignMetadataInitializationTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ForeignMetadataInitialization" - static var registeredTestMethodNames: Set { - ForeignMetadataInitializationBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ForeignMetadataInitializationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let initialization = ForeignMetadataInitialization( layout: .init(completionFunction: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift index d6f6fe7a..1c39565a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "SingletonMetadataInitialization" - static var registeredTestMethodNames: Set { - SingletonMetadataInitializationBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the picked class descriptor and its /// SingletonMetadataInitialization payload from both readers. private func loadInits() throws -> (file: SingletonMetadataInitialization, image: SingletonMetadataInitialization) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift index 2394bfb3..f8100011 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// accessor; `MachOFile` cannot invoke metadata accessors. Members are /// exercised via the carrier's imageContext / in-process paths. @Suite -final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataProtocol" - static var registeredTestMethodNames: Set { - MetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `StructMetadata`-conforming carrier for /// `Structs.StructTest` from a MachOImage metadata accessor. private func loadStructTestStructMetadata() throws -> StructMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift index 66165e08..8e9da2d4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// (rather than `.sentinel`). The `InProcessContext` is unused; the /// assertions exercise the flag-set bit-packing accessors directly. @Suite -final class MetadataRequestTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataRequest" - static var registeredTestMethodNames: Set { - MetadataRequestBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataRequestTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Default `init()` produces a zero-valued request (`.complete` state, /// non-blocking). @Test("init") func defaultInitializer() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift index 983deb0c..52ae2b12 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// **Reader asymmetry:** the response originates from MachOImage's accessor /// invocation; `MachOFile` cannot invoke runtime functions. @Suite -final class MetadataResponseTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataResponse" - static var registeredTestMethodNames: Set { - MetadataResponseBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataResponseTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestResponse() throws -> MetadataResponse { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift index 384fc16a..5080598e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class MetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Metadata" - static var registeredTestMethodNames: Set { - MetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a kind-erased `Metadata` for `Structs.StructTest`. private func loadStructTestMetadata() throws -> Metadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift index 7c811a6a..791a3bf0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// metadata accessor (`StructTest.metadataAccessorFunction`); `MachOFile` /// cannot invoke runtime functions. @Suite -final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataWrapper" - static var registeredTestMethodNames: Set { - MetadataWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise an image-relative wrapper for the imageContext code /// paths. private func loadStructTestImageWrapper() throws -> MetadataWrapper { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift index 3c62f080..bb8f9d80 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class MetatypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetatypeMetadata" - static var registeredTestMethodNames: Set { - MetatypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetatypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try MetatypeMetadata.resolve(at: InProcessMetadataPicker.stdlibIntMetatype, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift index c02546c6..544de0a5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class SingletonMetadataPointerTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "SingletonMetadataPointer" - static var registeredTestMethodNames: Set { - SingletonMetadataPointerBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class SingletonMetadataPointerTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let pointer = SingletonMetadataPointer( layout: .init(metadata: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift index f65c4212..97821260 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// surface is exercised through the wrapper Suite (`ModuleContextTests`) /// to avoid duplicating coverage here. @Suite -final class ModuleContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ModuleContextDescriptor" - static var registeredTestMethodNames: Set { - ModuleContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ModuleContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let fileSubject = try BaselineFixturePicker.module_SymbolTestsCore(in: machOFile) let imageSubject = try BaselineFixturePicker.module_SymbolTestsCore(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift index 96e7575d..b409f17b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `ModuleContext` only carries `descriptor` and `name`; `name` is a /// stable string literal we embed in the baseline. @Suite -final class ModuleContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ModuleContext" - static var registeredTestMethodNames: Set { - ModuleContextBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ModuleContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `ModuleContext` wrapper for the /// `SymbolTestsCore` module against both readers. private func loadSymbolTestsCoreContexts() throws -> (file: ModuleContext, image: ModuleContext) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift index c43bda67..2fc06bd7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class OpaqueMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueMetadata" - static var registeredTestMethodNames: Set { - OpaqueMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OpaqueMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = OpaqueMetadata( layout: .init(kind: 0x300), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift index 39afc7d2..f46a67ea 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `OpaqueTypeDescriptor` instances whose `ContextDescriptorFlags` /// kind-specific bits encode known counts. @Suite -final class OpaqueTypeDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueTypeDescriptorProtocol" - static var registeredTestMethodNames: Set { - OpaqueTypeDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OpaqueTypeDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func descriptor(withUnderlyingTypeArguments count: UInt16) -> OpaqueTypeDescriptor { // ContextDescriptorFlags kind in low 5 bits + kindSpecificFlagsRawValue // in upper 16 bits. We pack `count` into the upper 16 bits to diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift index 43c6697f..2c7301b6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class OpaqueTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueTypeDescriptor" - static var registeredTestMethodNames: Set { - OpaqueTypeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OpaqueTypeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func syntheticDescriptor() -> OpaqueTypeDescriptor { OpaqueTypeDescriptor( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift index 8fedfdcd..4efd2008 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// public surface and exercises members against a synthetic memberwise /// instance. @Suite -final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueType" - static var registeredTestMethodNames: Set { - OpaqueTypeBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self) +final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Synthetic descriptor — flags layout uses /// `ContextDescriptorKind.opaqueType` (4) with no kind-specific /// flags, so `numUnderlyingTypeArguments == 0`. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift index bfd1bb76..f4e903be 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// `RequirementInSignature`), so the Suite exercises the accessors /// against the synthetic raw values embedded in the baseline. @Suite -final class InvertibleProtocolSetTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "InvertibleProtocolSet" - static var registeredTestMethodNames: Set { - InvertibleProtocolSetBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class InvertibleProtocolSetTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let set = InvertibleProtocolSet(rawValue: InvertibleProtocolSetBaseline.both.rawValue) #expect(set.rawValue == InvertibleProtocolSetBaseline.both.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift index 20a73c21..c251fac9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// exercises the round-trip via the synthetic raw values embedded in /// the baseline. @Suite -final class InvertibleProtocolsRequirementCountTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "InvertibleProtocolsRequirementCount" - static var registeredTestMethodNames: Set { - InvertibleProtocolsRequirementCountBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class InvertibleProtocolsRequirementCountTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let zero = InvertibleProtocolsRequirementCount(rawValue: InvertibleProtocolsRequirementCountBaseline.zero.rawValue) #expect(zero.rawValue == InvertibleProtocolsRequirementCountBaseline.zero.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift index 459cc2bd..e78d1970 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `Protocols.ObjCInheritingProtocolTest: NSObjectProtocol` requirement, /// which surfaces an `ObjCProtocolPrefix` resolving to `NSObject`. @Suite -final class ObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ObjCProtocolPrefix" - static var registeredTestMethodNames: Set { - ObjCProtocolPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstPrefixes() throws -> (file: ObjCProtocolPrefix, image: ObjCProtocolPrefix) { let file = try BaselineFixturePicker.objcProtocolPrefix_first(in: machOFile) let image = try BaselineFixturePicker.objcProtocolPrefix_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift index 304c808f..96a84cd8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// (`offset`, `layout`, `mangledName`) for the Coverage Invariant test /// and documents the missing runtime coverage. @Suite -final class RelativeObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "RelativeObjCProtocolPrefix" - static var registeredTestMethodNames: Set { - RelativeObjCProtocolPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class RelativeObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live instance available in SymbolTestsCore; the Suite registers // the public surface (offset, layout, mangledName) for the Coverage diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift index 44913905..d56c5517 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// We pick a live instance via `Protocols.ProtocolWitnessTableTest`'s /// `baseRequirement` slot. @Suite -final class ProtocolBaseRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolBaseRequirement" - static var registeredTestMethodNames: Set { - ProtocolBaseRequirementBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolBaseRequirementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadBaseRequirements() throws -> (file: ProtocolBaseRequirement, image: ProtocolBaseRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift index 65c38088..9530e0ec 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// We exercise it against `Protocols.ProtocolTest` whose kind-specific /// flags slot resolves to a real value. @Suite -final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolContextDescriptorFlags" - static var registeredTestMethodNames: Set { - ProtocolContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadProtocolTestFlags() throws -> (file: ProtocolContextDescriptorFlags, image: ProtocolContextDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift index 183b2811..7f70ce8e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// the Suite exercises the flag accessors against synthetic raw values /// embedded in the baseline. @Suite -final class ProtocolDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolDescriptorFlags" - static var registeredTestMethodNames: Set { - ProtocolDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = ProtocolDescriptorFlags(rawValue: ProtocolDescriptorFlagsBaseline.swift.rawValue) #expect(flags.rawValue == ProtocolDescriptorFlagsBaseline.swift.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift index fc079c5a..340e8579 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// from the baseline, plus exercises `name(in:)` end-to-end via the /// fixture's ObjC inheriting protocol. @Suite -final class ProtocolDescriptorRefTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolDescriptorRef" - static var registeredTestMethodNames: Set { - ProtocolDescriptorRefBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolDescriptorRefTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Synthetic Swift / ObjC factories @Test("init(storage:)") func initializerWithStorage() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift index f12a0743..4840b944 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// on `NamedContextDescriptorProtocol` and are exercised in Task 6 under /// `NamedContextDescriptorProtocolTests`. @Suite -final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolDescriptor" - static var registeredTestMethodNames: Set { - ProtocolDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadProtocolTestDescriptors() throws -> (file: ProtocolDescriptor, image: ProtocolDescriptor) { let file = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let image = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift index c571eefa..fef36be7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `__swift5_protos` section. We pick the first record from the fixture /// and verify its offset and resolved descriptor offset/name. @Suite -final class ProtocolRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRecord" - static var registeredTestMethodNames: Set { - ProtocolRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstRecords() throws -> (file: ProtocolRecord, image: ProtocolRecord) { let file = try BaselineFixturePicker.protocolRecord_first(in: machOFile) let image = try BaselineFixturePicker.protocolRecord_first(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift index aac9fee0..f044f7c8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// for the `kind = .method` branch and synthetic raw values for the /// remaining branches. @Suite -final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRequirementFlags" - static var registeredTestMethodNames: Set { - ProtocolRequirementFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstRequirementFlags() throws -> (file: ProtocolRequirementFlags, image: ProtocolRequirementFlags) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift index 434fb259..ce36b7dc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// themselves are out of scope for `PublicMemberScanner`. We assert the /// description string for every case to exercise the switch coverage. @Suite -final class ProtocolRequirementKindTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRequirementKind" - static var registeredTestMethodNames: Set { - ProtocolRequirementKindBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRequirementKindTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func description() async throws { #expect(ProtocolRequirementKind.baseProtocol.description == ProtocolRequirementKindBaseline.baseProtocolDescription) #expect(ProtocolRequirementKind.method.description == ProtocolRequirementKindBaseline.methodDescription) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift index 20350d1a..a0e8fe21 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// `ProtocolBaseRequirement` (the second struct in the same file) gets /// its own Suite (`ProtocolBaseRequirementTests`). @Suite -final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRequirement" - static var registeredTestMethodNames: Set { - ProtocolRequirementBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstRequirements() throws -> (file: ProtocolRequirement, image: ProtocolRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift index 282f6cc1..9d01f3d0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `Protocols.ProtocolWitnessTableTest` (5 method requirements, no /// requirement-in-signature). @Suite -final class ProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Protocol" - static var registeredTestMethodNames: Set { - ProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadProtocolTestProtocols() throws -> (file: MachOSwiftSection.`Protocol`, image: MachOSwiftSection.`Protocol`) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift index 6869cd00..cac9abb2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `ProtocolConformance` in the fixture that surfaces one and verify /// the offset equals the baseline. @Suite -final class ProtocolWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolWitnessTable" - static var registeredTestMethodNames: Set { - ProtocolWitnessTableBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolWitnessTableTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstWitnessTables() throws -> (file: ProtocolWitnessTable, image: ProtocolWitnessTable) { let fileConformance = try required( try machOFile.swift.protocolConformances.first(where: { $0.witnessTablePattern != nil }) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift index 5f80acdd..6c441d7d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// MachO-only debug formatter `implementationAddressString(in:)` must /// produce a non-empty hex string. @Suite -final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientWitness" - static var registeredTestMethodNames: Set { - ResilientWitnessBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstWitnesses() throws -> (file: ResilientWitness, image: ResilientWitness) { let fileConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift index 02562764..f1d29e37 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// Picker: the first `ProtocolConformance` from the fixture with a /// non-empty `resilientWitnesses` array (so the header materializes). @Suite -final class ResilientWitnessesHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientWitnessesHeader" - static var registeredTestMethodNames: Set { - ResilientWitnessesHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientWitnessesHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstHeaders() throws -> (file: ResilientWitnessesHeader, image: ResilientWitnessesHeader) { let fileConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift index dba9dbce..51a32c07 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// collapses to a single MethodKey under PublicMemberScanner's name-based /// deduplication; the Suite exercises both reader paths. @Suite -final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GlobalActorReference" - static var registeredTestMethodNames: Set { - GlobalActorReferenceBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstReferences() throws -> (file: GlobalActorReference, image: GlobalActorReference) { let fileConformance = try BaselineFixturePicker.protocolConformance_globalActorFirst(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_globalActorFirst(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift index f767935f..0b27f28a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// — non-retroactive, no global-actor isolation, simplest path with a /// resolvable witness table and a `directTypeDescriptor` type reference. @Suite -final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolConformanceDescriptor" - static var registeredTestMethodNames: Set { - ProtocolConformanceDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestProtocolTestDescriptors() throws -> (file: ProtocolConformanceDescriptor, image: ProtocolConformanceDescriptor) { let fileConformance = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift index c7cdc221..7d5175cf 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// asserts each accessor against the baseline literal — this validates both /// the bitfield parsing and the `init(rawValue:)`/`rawValue` round-trip. @Suite -final class ProtocolConformanceFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolConformanceFlags" - static var registeredTestMethodNames: Set { - ProtocolConformanceFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolConformanceFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = ProtocolConformanceFlags(rawValue: ProtocolConformanceFlagsBaseline.structTestProtocolTest.rawValue) #expect(flags.rawValue == ProtocolConformanceFlagsBaseline.structTestProtocolTest.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift index 2f894c46..7ef8d233 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift @@ -25,12 +25,8 @@ import SwiftSectionFixtureSupport /// - The first resilient-witness conformance — surfaces /// `resilientWitnessesHeader` and `resilientWitnesses`. @Suite -final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolConformance" - static var registeredTestMethodNames: Set { - ProtocolConformanceBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestProtocolTest() throws -> (file: ProtocolConformance, image: ProtocolConformance) { let file = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOFile) let image = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift index 71c100be..f27e4840 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// keys nested types by their inner struct name, so the /// `testedTypeName` here is `"Element"`. @Suite -final class TupleTypeMetadataElementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Element" - static var registeredTestMethodNames: Set { - TupleTypeMetadataElementBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "Element") +final class TupleTypeMetadataElementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func type() async throws { let address = try usingInProcessOnly { context in let tuple = try TupleTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibTupleIntString, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift index b706dc56..4f63ba95 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TupleTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TupleTypeMetadata" - static var registeredTestMethodNames: Set { - TupleTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TupleTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try TupleTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibTupleIntString, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift index aea1d755..9145db9a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// Two pickers feed the assertions: `Classes.ClassTest` (no superclass) /// and `Classes.SubclassTest` (has a superclass mangled name). @Suite -final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassDescriptor" - static var registeredTestMethodNames: Set { - ClassDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadClassTestDescriptors() throws -> (file: ClassDescriptor, image: ClassDescriptor) { let file = try BaselineFixturePicker.class_ClassTest(in: machOFile) let image = try BaselineFixturePicker.class_ClassTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift index 48e72e9c..7945778c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// records no member names because neither the `Flag` cases nor the /// statics `@FlagSet` generates are scanner-visible as method-keyed members. @Suite -final class ClassFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassFlags" - static var registeredTestMethodNames: Set { - ClassFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func rawValuesMatchBaseline() async throws { #expect(ClassFlags.isSwiftPreStableABI.rawValue == ClassFlagsBaseline.isSwiftPreStableABI) #expect(ClassFlags.usesSwiftRefcounting.rawValue == ClassFlagsBaseline.usesSwiftRefcounting) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift index 2581befc..02cda54b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `init(descriptor:in:)` is exercised by dedicated tests over the file /// and image contexts and over the in-process context. @Suite -final class ClassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Class" - static var registeredTestMethodNames: Set { - ClassBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `Class` wrapper for `Classes.ClassTest` /// against both readers through their reading contexts. private func loadClassTestClasses() throws -> (file: Class, image: Class) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift index e027b4ec..a36a466b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// resilient ObjC stub, so we exercise the flag derivation by /// constructing instances with known raw values. @Suite -final class ExtraClassDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtraClassDescriptorFlags" - static var registeredTestMethodNames: Set { - ExtraClassDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtraClassDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func rawValue() async throws { let zero = ExtraClassDescriptorFlags(rawValue: ExtraClassDescriptorFlagsBaseline.zeroRawValue) #expect(zero.rawValue == ExtraClassDescriptorFlagsBaseline.zeroRawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift index 1953498c..d940ebfe 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class AnyClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadataProtocol" - static var registeredTestMethodNames: Set { - AnyClassMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load `ClassMetadataObjCInterop` for `ClassTest`, then /// re-resolve at the same offset as a slim `AnyClassMetadata`. private func loadAnyClassMetadata() throws -> AnyClassMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift index fdfafdda..326d8bfa 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift @@ -24,12 +24,8 @@ import SwiftSectionFixtureSupport /// down via the protocol's `asFinalClassMetadata(in:)` helper, then /// performing structural checks on the slim header. @Suite -final class AnyClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadata" - static var registeredTestMethodNames: Set { - AnyClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the `ClassMetadataObjCInterop` for `ClassTest` and /// re-resolve at the same offset as an `AnyClassMetadata` slim view. /// The two layouts overlap in their leading fields (kind + diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift index 34e27a45..6499f756 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the source metadata originates from MachOImage. @Suite -final class AnyClassMetadataObjCInteropProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadataObjCInteropProtocol" - static var registeredTestMethodNames: Set { - AnyClassMetadataObjCInteropProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataObjCInteropProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift index df9a163e..ea0a4fbf 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class AnyClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadataObjCInterop" - static var registeredTestMethodNames: Set { - AnyClassMetadataObjCInteropBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load `ClassMetadataObjCInterop` for ClassTest, then take /// its superclass to get an `AnyClassMetadataObjCInterop` slim view. private func loadAnyInteropSuperclass() throws -> AnyClassMetadataObjCInterop { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift index ca7fcf79..f60340c7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// two static factories (`forAddressPointAndSize`, `forSwiftRootClass`). /// We exercise them on `ClassMetadataBounds` with known inputs. @Suite -final class ClassMetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadataBoundsProtocol" - static var registeredTestMethodNames: Set { - ClassMetadataBoundsProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `forAddressPointAndSize(addressPoint:totalSize:offset:)` derives /// negative/positive sizes from a (pointer-aligned) address point and /// total size. Use known multiples of pointer size to verify the diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift index 23a9ff35..8266d229 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// the static factories on `ClassMetadataBoundsProtocol`. We construct /// instances with known scalars and verify the layout fields round-trip. @Suite -final class ClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadataBounds" - static var registeredTestMethodNames: Set { - ClassMetadataBoundsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { // Construct a deterministic instance and verify the `offset` ivar // is set as supplied. (Default-init through the public layout diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift index a3b7681d..17f46861 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift @@ -25,12 +25,8 @@ import SwiftSectionFixtureSupport /// successfully and is the canonical path the Swift runtime takes. /// Phase B2 settled on InProcess-only coverage for this Suite. @Suite -final class StoredClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StoredClassMetadataBounds" - static var registeredTestMethodNames: Set { - StoredClassMetadataBoundsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StoredClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Mangled symbol of the nominal type descriptor for /// `SymbolTestsCore.ResilientClassFixtures.ResilientChild`. Used by /// `fixtureSymbol(_:)` to obtain the descriptor pointer directly. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift index 1bc4c3d3..7389d2e6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class ClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadata" - static var registeredTestMethodNames: Set { - ClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load `ClassTest`'s metadata via the accessor (returned as /// `ClassMetadataObjCInterop`); the related `descriptorOffset` is a /// static lookup on `ClassMetadata`. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift index 7d211869..07b0ce38 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class ClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadataObjCInterop" - static var registeredTestMethodNames: Set { - ClassMetadataObjCInteropBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift index 14c8dee8..460f2b01 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// the protocol methods accept any `ReadingContext` so we exercise the /// ReadingContext overloads here. @Suite -final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FinalClassMetadataProtocol" - static var registeredTestMethodNames: Set { - FinalClassMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift index 3a39d162..8a3c73f6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift @@ -23,12 +23,8 @@ import SwiftSectionFixtureSupport /// (reached via `Foundation`'s in-process metadata) is the canonical /// `ObjCClassWrapperMetadata` carrier. @Suite -final class ObjCClassWrapperMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ObjCClassWrapperMetadata" - static var registeredTestMethodNames: Set { - ObjCClassWrapperMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ObjCClassWrapperMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let kindRaw = try usingInProcessOnly { context in let metadata = try ObjCClassWrapperMetadata.resolve( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift index 849f38ec..eba9d440 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// cannot be sourced. The Suite documents the missing runtime coverage /// and registers the public surface for the Coverage Invariant test. @Suite -final class MethodDefaultOverrideDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDefaultOverrideDescriptor" - static var registeredTestMethodNames: Set { - MethodDefaultOverrideDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDefaultOverrideDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Sentinel test ensuring the Suite is loaded by swift-testing. The /// real coverage will land when a fixture surfaces a default-override /// table. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift index fa588018..33cad1b9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// default-override table, so a live header cannot be sourced. The Suite /// documents the missing runtime coverage. @Suite -final class MethodDefaultOverrideTableHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDefaultOverrideTableHeader" - static var registeredTestMethodNames: Set { - MethodDefaultOverrideTableHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDefaultOverrideTableHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live instance available in SymbolTestsCore; the Suite registers // the public surface (offset, layout) for the Coverage Invariant diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift index eefa3bbb..0ca88fd5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `instanceVariable` getter — kind `.getter`, isInstance `true`, /// other bits clear. @Suite -final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDescriptorFlags" - static var registeredTestMethodNames: Set { - MethodDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the first vtable entry's flags from each reader. private func loadFirstFlags() throws -> (file: MethodDescriptorFlags, image: MethodDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift index a95f1973..80654a5d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// Suite pins both the raw values and the `description` strings, so any /// accidental renumbering or display tweak fails a test. @Suite -final class MethodDescriptorKindTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDescriptorKind" - static var registeredTestMethodNames: Set { - MethodDescriptorKindBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDescriptorKindTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func description() async throws { // Pin raw values + descriptions per case. #expect(MethodDescriptorKind.method.rawValue == MethodDescriptorKindBaseline.method.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift index b25045a8..bddc0e58 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// resolves to (pinned as a baseline literal; the ReadingContext leg must /// report the same location as a context address). @Suite -final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDescriptor" - static var registeredTestMethodNames: Set { - MethodDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the first vtable entry of `Classes.ClassTest` from /// each reader. private func loadFirstMethods() throws -> (file: MethodDescriptor, image: MethodDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift index d287ef8f..ed31b5c8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// implementation offset, and presence-flags for the resolved class/method /// pointers. @Suite -final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodOverrideDescriptor" - static var registeredTestMethodNames: Set { - MethodOverrideDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the first override entry of `Classes.SubclassTest` /// from each reader. private func loadFirstOverrides() throws -> (file: MethodOverrideDescriptor, image: MethodOverrideDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift index 303e3a1a..2427ffca 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// The Suite picks the override-table header from `Classes.SubclassTest` /// and asserts cross-reader equality on `offset` and `numEntries`. @Suite -final class OverrideTableHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OverrideTableHeader" - static var registeredTestMethodNames: Set { - OverrideTableHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OverrideTableHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadSubclassOverrideHeaders() throws -> (file: OverrideTableHeader, image: OverrideTableHeader) { let fileDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift index caea6960..8732fbf3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// The Suite picks the vtable header from `Classes.ClassTest` and asserts /// cross-reader equality on `offset`, `vTableOffset`, and `vTableSize`. @Suite -final class VTableDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "VTableDescriptorHeader" - static var registeredTestMethodNames: Set { - VTableDescriptorHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class VTableDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadClassTestVTableHeaders() throws -> (file: VTableDescriptorHeader, image: VTableDescriptorHeader) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift index 1d14fcf8..c38ae324 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `SymbolTestsHelper.Object`, cross-module) and asserts cross-reader /// agreement on the discovered scalars. @Suite -final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ObjCResilientClassStubInfo" - static var registeredTestMethodNames: Set { - ObjCResilientClassStubInfoBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the `ObjCResilientClassStubInfo` record from /// `ObjCResilientStubFixtures.ResilientObjCStubChild`. private func loadResilientObjCStubChildStub( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift index edef621a..8d9bce9d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// child's class context descriptor carries the trailing record) and /// asserts cross-reader agreement on the discovered scalar offset. @Suite -final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientSuperclass" - static var registeredTestMethodNames: Set { - ResilientSuperclassBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the `ResilientSuperclass` record from /// `ResilientClassFixtures.ResilientChild` (whose parent /// `SymbolTestsHelper.ResilientBase` is cross-module — only that diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift index 6c32998c..9f8b3d3e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// - `Enums.MultiPayloadEnumTests` — the canonical `isMultiPayload` path /// (3 payload cases + 1 empty) @Suite -final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumDescriptor" - static var registeredTestMethodNames: Set { - EnumDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadNoPayloadDescriptors() throws -> (file: EnumDescriptor, image: EnumDescriptor) { let file = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOFile) let image = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift index aaa09591..3f85335d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// against deterministic inputs and compare against the literal baseline /// — there is no MachO dependency here. @Suite -final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumTagCounts" - static var registeredTestMethodNames: Set { - EnumFunctionsBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "EnumTagCounts") +final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func numTags() async throws { for entry in EnumFunctionsBaseline.cases { let result = getEnumTagCounts( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift index f54e2da1..9345da1f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `init(descriptor:in:)` is exercised by dedicated tests over the file /// and image contexts and over the in-process context. @Suite -final class EnumTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Enum" - static var registeredTestMethodNames: Set { - EnumBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `Enum` wrapper for `Enums.NoPayloadEnumTest` /// against both readers through their reading contexts. private func loadNoPayloadEnums() throws -> (file: Enum, image: Enum) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift index 9bf7c694..2c309b31 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// baseline records this invariant. (No fixture in `SymbolTestsCore` /// currently surfaces a non-nil `payloadSize`.) @Suite -final class EnumMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumMetadataProtocol" - static var registeredTestMethodNames: Set { - EnumMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadNoPayloadEnumMetadata() throws -> EnumMetadata { let descriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift index a1cae5a8..e44e12f1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class EnumMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumMetadata" - static var registeredTestMethodNames: Set { - EnumMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize an `EnumMetadata` for `Enums.NoPayloadEnumTest` by /// calling the MachOImage metadata accessor and resolving the /// response's value-type wrapper. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift index d2ac005f..39f90b5c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// All assertions use the multi-payload picker /// (`Enums.MultiPayloadEnumTests`). @Suite -final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MultiPayloadEnumDescriptor" - static var registeredTestMethodNames: Set { - MultiPayloadEnumDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadDescriptors() throws -> (file: MultiPayloadEnumDescriptor, image: MultiPayloadEnumDescriptor) { let file = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOFile) let image = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift index 6bdb14b6..2bf735ab 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// `TypeContextDescriptorProtocol` and are exercised in Task 9 under /// `TypeContextDescriptorProtocolTests`. @Suite -final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StructDescriptor" - static var registeredTestMethodNames: Set { - StructDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `StructDescriptor.offset` is the file/image position of the descriptor /// record. Cross-reader equality holds: both `MachOFile` and `MachOImage` /// resolve the same offset (in-process pointer arithmetic relative to the diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift index 4811c684..0cd8c659 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// asymmetric (the metadata originates from MachOImage but its methods /// accept the file/image/inProcess context families). @Suite -final class StructMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StructMetadataProtocol" - static var registeredTestMethodNames: Set { - StructMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestMetadata() throws -> StructMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift index 93d5440a..bd75354d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class StructMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StructMetadata" - static var registeredTestMethodNames: Set { - StructMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a `StructMetadata` for `Structs.StructTest` by calling the /// MachOImage metadata accessor and resolving the response. Returns `nil` /// only if the accessor isn't reachable for the descriptor (which we diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift index d7ae16c2..e9303bec 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// `Struct`; we surface explicit `@Test func init...` entries for coverage /// purposes. @Suite -final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Struct" - static var registeredTestMethodNames: Set { - StructBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `Struct` wrapper for `Structs.StructTest` against /// both the file and image readers through their reading contexts. /// Used by every ivar test — the file/image-context and in-process diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift index 6318fdcb..dcd4fae0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// - `Classes.ClassTest` for the class-specific accessors (so /// `classHasVTable` and friends have a real-world value to assert). @Suite -final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptorFlags" - static var registeredTestMethodNames: Set { - TypeContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestFlags() throws -> (file: TypeContextDescriptorFlags, image: TypeContextDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift index ee739b3c..e2bbe435 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// /// Picker: `Structs.StructTest`'s descriptor. @Suite -final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - TypeContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestDescriptors() throws -> (file: StructDescriptor, image: StructDescriptor) { let file = try BaselineFixturePicker.struct_StructTest(in: machOFile) let image = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift index b0e3c1da..6f499ada 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// header at its offset gives us `structDescriptor()` non-nil and the /// other two kind-projections nil. @Suite -final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptor" - static var registeredTestMethodNames: Set { - TypeContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: read the bare `TypeContextDescriptor` header at the /// `Structs.StructTest` offset against both readers. private func loadStructTestDescriptors() throws -> (file: TypeContextDescriptor, image: TypeContextDescriptor) { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift index 61f2edce..6d296cc6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// /// Picker: `Structs.StructTest`'s descriptor wrapped in `.struct(...)`. @Suite -final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptorWrapper" - static var registeredTestMethodNames: Set { - TypeContextDescriptorWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestWrappers() throws -> (file: TypeContextDescriptorWrapper, image: TypeContextDescriptorWrapper) { let file = try BaselineFixturePicker.struct_StructTest(in: machOFile) let image = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift index 4016556c..b28015f8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `TypeContextWrapper.forTypeContextDescriptorWrapper` to materialize a /// `.struct(...)` wrapper. @Suite -final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextWrapper" - static var registeredTestMethodNames: Set { - TypeContextWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestWrappers() throws -> (file: TypeContextWrapper, image: TypeContextWrapper) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift index 4181e37b..01cf3065 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// We materialize a representative record by walking the section and /// finding the entry that resolves to `Structs.StructTest`. @Suite -final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataRecord" - static var registeredTestMethodNames: Set { - TypeMetadataRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Walks `__swift5_types`/`__swift5_types2` and returns the /// `TypeMetadataRecord` whose resolved descriptor lives at /// `targetOffset`. Two specializations follow because the `section(for:)` diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift index 58bc1bf4..ae9886f9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// `typeKind` byte to materialize a `TypeReference.directTypeDescriptor(...)` /// via `forKind(.directTypeDescriptor, at: …)`. @Suite -final class TypeReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeReference" - static var registeredTestMethodNames: Set { - TypeReferenceBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeReferenceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Find the `TypeMetadataRecord` for `Structs.StructTest` and project /// its (record-field-offset, relative-offset, kind) tuple — the /// inputs to `TypeReference.forKind(_:at:)`. Two specializations diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift index 45cd392d..52e9be93 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// `ValueMetadata` instances are only obtainable via a loaded MachOImage's /// metadata accessor, so the cross-reader assertions here are asymmetric. @Suite -final class ValueMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueMetadataProtocol" - static var registeredTestMethodNames: Set { - ValueMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a concrete `ValueMetadataProtocol`-conforming instance /// (a `StructMetadata` for `Structs.StructTest`). private func loadStructTestStructMetadata() throws -> StructMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift index dc867af1..f15c93b6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ValueMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueMetadata" - static var registeredTestMethodNames: Set { - ValueMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a `ValueMetadata` by reading the kind-erased layout at /// the offset of the metadata for `Structs.StructTest`. The struct's /// metadata is a `StructMetadata` whose layout shares the diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift index 332e98e1..9bfc14bc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// Picker: `Structs.StructTest`'s descriptor wrapped in `.struct(...)`. @Suite -final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueTypeDescriptorWrapper" - static var registeredTestMethodNames: Set { - ValueTypeDescriptorWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestWrappers() throws -> (file: ValueTypeDescriptorWrapper, image: ValueTypeDescriptorWrapper) { let file = try BaselineFixturePicker.struct_StructTest(in: machOFile) let image = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift index d2eb236a..db539339 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// quadruple projected from a `ValueWitnessTable`. Pure value-type — /// the Suite re-evaluates each accessor against a synthetic instance. @Suite -final class TypeLayoutTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeLayout" - static var registeredTestMethodNames: Set { - TypeLayoutBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeLayoutTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Construct a synthetic `TypeLayout` representing a non-POD, /// inline, bitwise-takable, copyable type with alignment 8 (mask 7), /// size 16, stride 16, no extra inhabitants. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift index 47617227..34cdda65 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// static-constant smoke checks verify the raw-value constants haven't /// drifted. @Suite -final class ValueWitnessFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueWitnessFlags" - static var registeredTestMethodNames: Set { - ValueWitnessFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueWitnessFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializer() async throws { for entry in ValueWitnessFlagsBaseline.cases { let flags = ValueWitnessFlags(rawValue: entry.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift index ca1a5aa1..a5236026 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ValueWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueWitnessTable" - static var registeredTestMethodNames: Set { - ValueWitnessTableBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueWitnessTableTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestValueWitnesses() throws -> ValueWitnessTable { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) From 8b859082e59af6e3c4a5a22ae632827a874923c1 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 18:32:47 +0800 Subject: [PATCH 030/175] docs: record the verification of swift6-mode-and-upcoming-features and regenerate its web page Every package builds with Xcode 27.2 and 26.6; the test suites pass apart from failures the baseline shares; the rendering A/B is byte-identical over 84 pairs; the Tuist workspace builds; MachOKit's CI passes on Swift 6.0. --- ...aft-swift6-mode-and-upcoming-features.html | 185 +++++++++--------- ...draft-swift6-mode-and-upcoming-features.md | 11 +- 2 files changed, 97 insertions(+), 99 deletions(-) diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html index 6da1810d..e7e2b455 100644 --- a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.html @@ -190,23 +190,23 @@

Draft MachO 系列库统一 Swift 6 语

摘要

-

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

-

源码改动约 900 处,绝大部分是补 import 与补 any;非测试 target 用 swift package migrate 自动改,测试 target 照诊断清单手改,另有 6 处工具处理不了、要先手工改好。同为 Swift 7 默认的 NonisolatedNonsendingByDefault、InternalImportsByDefault、ImmutableWeakCaptures,以及独立的 StrictMemorySafety,量过之后明确不做。

+

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

+

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

要你定

-

批准这份提案

+

实现已完成,等你看过后收尾

    -
  1. 按「落地步骤」开工:六个仓库各开 feature/swift6-mode-and-upcoming-features 分支,构建与测试都在 Ultra 上跑。
  2. +
  3. 看过没问题就用 finish-feature 落地:六个仓库按各自流程合进集成分支,本提案取号、改 Implemented。

没问用户就采用的假设

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

    架构图

    packagelanguage modeupcoming features (every Swift target) MachOKit (fork) - Swift 5 → 6 (tools 6.2) + Swift 5 → 6 (tools 6.0) + ExistentialAny · MemberImportVisibility · InferIsolatedConformances 9 Swift-6-era settings + ExistentialAny (MachOKit target only) @@ -254,23 +254,25 @@

    架构图

    + the same three (statics at Package.swift:1541, now used)
-

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

+

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

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

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

@@ -285,29 +287,27 @@

改动地图

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

改动地图

提议方案与非目标

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

非目标

@@ -329,7 +329,7 @@

提议方案与非目标

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

    提议方案与非目标

    详细设计

    - 统一开关(五个兄弟包写在清单末尾) + 统一开关
    let upcomingFeatureSettings: [SwiftSetting] = [
         .enableUpcomingFeature("ExistentialAny"),
    @@ -350,36 +350,24 @@ 

    详细设计

    for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings }
    -

    本库写在 extension SwiftSetting(Package.swift:1541)之后、Tuist 块(:1550)之前,数组里用已有的 .existentialAny、.memberImportVisibility、.inferIsolatedConformances;另外三个未用的常量留着,将来开时直接加进数组。

    +

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

    - MachOKit 清单 + 迁移命令与 internal import 的处理
    -

    第 1 行改为 // swift-tools-version: 6.2;MachOKit target 的 swiftSettings 只剩 .enableExperimentalFeature("AccessLevelOnImport", .when(configuration: .debug));原来的 extension SwiftSetting { static let forwardTrailingClosures … } 与 extension SwiftSetting: @retroactive CaseIterable 整段删除;末尾加与兄弟包相同的循环。

    -
    -
    -
    - 迁移命令与日志处理 -
    -
    queued-build swift package --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \
    +
    queued-build swift package --build-system native \
    +    --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Swift6UpcomingFeatures-Migrate \
         migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances
    -
    -queued-build swift build --build-tests \
    -    --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection \
    -    -Xswiftc -print-diagnostic-groups \
    -    -Xswiftc -enable-upcoming-feature -Xswiftc ExistentialAny:migrate \
    -    -Xswiftc -enable-upcoming-feature -Xswiftc MemberImportVisibility:migrate \
    -    -Xswiftc -enable-upcoming-feature -Xswiftc InferIsolatedConformances:migrate
    -

    第一条退出码是 1 属正常(改清单失败),看输出里的 Applied N fix-its in M files。第二条列出测试 target 里剩下的警告。日志带 ANSI 颜色与 OSC 8 超链接,按 [#组名] 计数前要先去掉转义;同一条诊断会打印两遍,按「文件:行:列 + 文字」去重。

    -

    手改测试:import of module 'X' is required 就在 import 区按字母序补 import X(已有 @testable 或 @_spi(...) 形式的不重复加);ExistentialAny 补 any;conformance of 'T' to 'P' should be marked 'nonisolated' 照写 nonisolated P。批量补 import 的脚本先给用户看过再跑。

    +git checkout -- Package.swift
    +

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

    调研

    -

    2026-11-20 在 Ultra(Xcode 27.2,Swift 6.4.2)上把六个包的当前提交各自 clone,以每个包为根编 swift build --build-tests;新特性用 SE-0486 的迁移模式(:migrate)只出警告,按诊断组计数,只统计包根目录下的文件。日志与改过的 clone 在 /Volumes/DerivedData/Agents.noindex/claude/Probes/Swift6Migration/。

    +

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

    三项要开的特性:各包改动处数(源码 / 测试)
    @@ -396,7 +384,6 @@

    调研

    -

    本库 MemberImportVisibility 的 245 处源码里有 189 处在测试基线生成器 SwiftSectionFixtureSupport;InferIsolatedConformances 的 33 处全在 IntegrationTests。

    @@ -406,9 +393,9 @@

    调研

    - - - + + +
    特性改动处(源码 / 测试)不做的原因
    NonisolatedNonsendingByDefault778 / 347,本库占 729 / 234改运行语义:nonisolated async 函数改在调用方的 actor 上执行,RuntimeViewer 从主线程调用时解析会跑到主线程;保留现状要给上千个函数加 @concurrent
    InternalImportsByDefault4,124 行 import(约 1,400 个文件)没有迁移模式;约一半必须保持 public import;下游可能因失去传递可见性而编不过
    ImmutableWeakCaptures约 0收益近乎为零,随将来的 Swift 7 模式一起处理
    NonisolatedNonsendingByDefault778 / 347改运行语义:RuntimeViewer 从主线程调用时解析会跑到主线程
    InternalImportsByDefault4,124 行 import没有迁移模式;约一半必须保持 public import;下游可能编不过
    ImmutableWeakCaptures约 0收益近乎为零
    StrictMemorySafety2,440 / 658不属于 Swift 6 或 7;几千处 unsafe 标注只会是噪音
    @@ -416,21 +403,16 @@

    调研

    - MachOKit 进 Swift 6 模式 -
    -

    Swift 5 模式加 -strict-concurrency=complete:Sources 零并发诊断,Tests 3 条警告。直接 -swift-version 6(从构建数据库核实四个 target 都拿到了):全部编过、零错误。上游 p-x9/MachOKit 同样是 tools 5.10;fork 比上游多 35 个提交、少 40 个。

    -
    -
    -
    - swift package migrate 的实际表现与迁移模式的坑 + swift package migrate 的实际表现与迁移的坑
      -
    • 非测试 target:258 个文件里套用了 300 个 fix-it(+304 / −57),然后在改清单那一步失败(unable to find target named 'Utilities' in package),源码已经改好。
    • -
    • 测试 target:一处都不改,显式 --target 也是 Applied 0 fix-its。
    • -
    • 构建一失败就一处都不改。本库 4 处在迁移模式下直接报错:TypeAttributeInferrer.swift:143(switch must be exhaustive)、ABIDiffer.swift:289(.enum 解析成实例成员)、两个测试文件的 .values 落到 dynamic member lookup。
    • -
    • swift-semantic-string 公开声明了 struct Error、struct Numeric、Argument。文件直接 import Semantic 后裸写的 Error 解析成 Semantic.Error:ObjCAPIRequests.swift:295 与 ABIEvolutionRequest.swift:180 因此编不过;as Error 一类转型则不报错、只变成永远失败。
    • -
    • 补完 6 处、migrate 跑完、清单手加开关后,Sources 全部编过;测试 target 逐个报缺 import,与警告清单一致。
    • -
    • 清单里给 C target 加 swiftSettings 无害:同一个循环在六个包上都照常编过。
    • +
    • 本库清单写成 extension Target 上的静态常量,migrate 改清单那一步失败,源码照样改好;清单一律手改。
    • +
    • 默认构建系统下 migrate 不改测试(450 条测试警告、0 个 fix-it);--build-system native 下一遍改完源码与测试。
    • +
    • native 构建系统下它常写 internal import X,与别的文件的普通 import X 冲突(本库 17 个文件报访问级别有歧义)。
    • +
    • 迁移模式本身有 4 处硬错误(switch 不完备、.enum 解析成实例成员、两处 .values 落到 dynamic member lookup),构建一失败 migrate 就一处都不改,所以要预修。
    • +
    • swift-semantic-string 公开声明了 Error、Numeric、Argument;文件直接 import Semantic 后裸 Error 就是 Semantic.Error:源码 2 处、测试 14 个文件编不过,改成 Swift.Error。
    • +
    • Swift 6.4 的 fix-it 写出 any P?,Swift 6.3 要求 (any P)?:三处。
    • +
    • MachOKit 进 Swift 6 模式后,测试二进制里一个 curry thunk 的 mangling 多了 Yb(SE-0418),按名字找它的测试要跟着改。
    @@ -439,15 +421,17 @@

    调研

    替代方案

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

    替代方案

    影响

      -
    • 源码兼容性:纯新增。六个包都不改任何公开声明的签名;MachOKit 换语言模式不改变公开 API。upcoming feature 只作用于开启它的 target 本身,不传给下游。
    • +
    • 源码兼容性:纯新增。六个包都不改任何公开声明的签名;upcoming feature 只作用于开启它的 target 本身,不传给下游。
    • ABI:不适用,SPM 源码分发。
    • -
    • 下游:RuntimeViewer、MachOKitUI、SymbolViewer 不用改代码;RuntimeViewer 与本库的 Tuist workspace 重新生成后带上新设置,最后一步编一遍确认。上游 p-x9/MachOKit 不提交,合上游 tag 时清单两处会冲突,按 fork 写法解决。
    • -
    • 文档:账本加一节、索引登记;CLAUDE.md 预计不加条目(编译器会当场指出漏写),落地时再判断。
    • +
    • 下游:RuntimeViewer、MachOKitUI、SymbolViewer 不用改代码。上游 p-x9/MachOKit 不提交,合上游 tag 时清单两处会冲突,按 fork 写法解决。
    • +
    • 文档:账本加一节、索引登记;CLAUDE.md 预计不加条目,落地时再判断。
    • API 演进:没有废弃的 API,不需要 major 跃迁,不单独发版。
    @@ -467,23 +451,22 @@

    影响

    落地步骤

      -
    1. 提案进集成分支,跨仓库登记。proposalIsListedInBothIndexes、siblingIndexesPointAtTheProposal
    2. -
    3. MachOKit 进 Swift 6 并开三项特性。machOKitTargetsCompileInSwift6Mode、machOKitBuildsWithAllThreeUpcomingFeatures、machOKitTestsPassSkippingAotCachePrintTests、machOKitBuildsWithXcode26_6
    4. -
    5. swift-semantic-string 与 swift-demangling。semanticStringBuildsAndTestsWithUpcomingFeatures、demanglingBuildsAndTestsWithUpcomingFeatures、demanglingLifetimesFeatureStillEnabledInBothTargets、两者 buildsWithXcode26_6
    6. -
    7. MachOKitExtensions(从 origin/main 切)。machOKitExtensionsBuildsAndTestsWithUpcomingFeatures、buildsWithXcode26_6
    8. -
    9. MachOObjCSection。machOObjCSectionBuildsAndTestsWithUpcomingFeatures、buildsWithXcode26_6
    10. -
    11. 本库 Sources:预修、migrate、开关。preFixedSitesCompileUnderMigrationMode、migrateAppliesAllNonTestFixIts、noFileImportingSemanticSpellsBareErrorOrNumeric、allNonTestTargetsBuildWithUpcomingFeatures
    12. -
    13. 本库 Tests:手改剩余警告。allTestTargetsBuildWithUpcomingFeatures、noMigrationWarningRemains
    14. -
    15. 本库全量验证。fullSuitePassesSkippingIntegrationTests、fullSuitePassesWithXcode26_6、renderingABVerificationIsByteIdentical、tuistWorkspaceGeneratesAndBuilds、noCastAlwaysFailsWarning
    16. +
    17. 提案进集成分支,跨仓库登记。(已完成)
    18. +
    19. MachOKit 进 Swift 6 并开三项特性。(已完成)Ultra 上 27.2 与 26.6 都编过;测试只剩基线上同样失败的 5 个环境用例;CI 在 Xcode 16.2 与 Linux Swift 6.0.3 上通过。
    20. +
    21. swift-semantic-string 与 swift-demangling。(已完成)两个 Xcode 都编过,测试全过。
    22. +
    23. MachOKitExtensions。(已完成)两个 Xcode 都编过,测试全过。
    24. +
    25. MachOObjCSection。(已完成)两个 Xcode 都编过;测试里 MachOObjCSectionTests 这个 XCTest 类读用户本机的一个文件,在基线上同样崩溃,跳过它后其余全过。
    26. +
    27. 本库:预修、migrate、开关。(已完成)全部 target 在 27.2 与 26.6 下都编过。
    28. +
    29. (并入第 6 步)
    30. +
    31. 本库全量验证。(已完成)Xcode 26.6 下 554 个 suite、2,906 个测试全过;渲染 A/B 84 对逐字节一致;Tuist 工作区编过。
    32. 落地。六个仓库按各自流程合进集成分支,提案取号、改 Implemented,账本加一节。
    -

    构建与测试一律在 Ultra 上跑;第 2–5 步互不依赖,可以并行。收尾时判断要不要配套专题文章(预计不需要)与新术语(预计没有),结论写进决策日志。

    决策日志

    - 2 条,最近一条:Accepted + 11 条,最近一条:实现完成,待用户看过后收尾
    @@ -491,6 +474,16 @@

    决策日志

    + + + + + + + + + +
    2026-11-20Created as Draft用户要求把 MachO 系列库迁到 Swift 6、开启严格并发,并评估开启全部新特性的改动量。实测五个包已是 Swift 6 模式,只有 MachOKit 停在 Swift 5 且切换后零错误;六项 Swift 7 默认特性逐项量过之后,用户选定「MachOKit 切 Swift 6 + ExistentialAny、MemberImportVisibility、InferIsolatedConformances」,另外三项与 StrictMemorySafety 不做
    2026-11-20Accepted用户批准,开始实现
    2026-11-20MachOKit 用 tools 6.0草案定的 6.2 会让 fork 的 CI(Xcode 16.2、Linux Swift 6.0.3)读不了清单;6.0 同样默认 Swift 6 模式。手动触发的 CI 两项都通过
    2026-11-20测试也交给 migrate默认构建系统下 migrate 不改测试;--build-system native 下一遍改完源码与测试,手改与批量脚本都不需要了
    2026-11-20internal import 改回普通 importnative 构建系统下 migrate 写的 internal import X 与已有的普通 import X 冲突(本库 17 个文件)。仓库已有 internal import 先例的保留,其余改成普通 import
    2026-11-20any P? 改成 (any P)?Swift 6.4 的 fix-it 写法在 Swift 6.3(CI 的 Xcode 26.6)下报错;三处
    2026-11-2014 个测试文件写 Swift.Errormigrate 给 93 个文件加了 import Semantic,其中 14 个测试文件里有类型位置的裸 Error,全部改成 Swift.Error;源码里没有,也没有「转型永远失败」的警告
    2026-11-20MachOKit 一个测试的期望符号名Swift 6 模式下 curry thunk 的 mangling 多了 Yb(SE-0418),testFindSymbolByName 改为新名字;其余 5 个失败在基线上同样失败
    2026-11-20验证结果六个包用 Xcode 27.2 与 26.6 都编过;swift-semantic-string、swift-demangling、MachOKitExtensions 测试全过;MachOKit 只剩基线同样失败的 5 个环境用例;MachOObjCSection 跳过读用户本机文件的那个 XCTest 类后全过;本库 2,906 个测试全过;渲染 A/B 84 对逐字节一致;Tuist 工作区 warm 与 build 成功;fork 的 CI 通过
    2026-11-20文档判断不配使用指南或实现说明,没有新术语,CLAUDE.md 不加条目;账本一节留到正式收尾
    2026-11-20实现完成,待用户看过后收尾六个仓库的功能分支都已推送
    diff --git a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md index 71d04616..81ddd6d0 100644 --- a/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md +++ b/Documentations/Evolutions/draft-swift6-mode-and-upcoming-features.md @@ -8,7 +8,7 @@ - **关联提案**: 无 - **跨仓库**: 本提案是 MachOKit(fork)、swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection 与本库共用的唯一提案。MachOKitExtensions 与 MachOObjCSection 的提案索引各加一行 cross-repository 指向这里(落地步骤第 1 步);另外三个仓库没有提案目录,不加。 - **实现分支 / PR**: 六个仓库都是 `feature/swift6-mode-and-upcoming-features`。MachOKitExtensions 从 `origin/main` 切(它只有 `main`,本地那条没推过的 `next` 不能用),其余五个从各自的 `next` 切。 -- **配套文档**: 待定 —— 落地时判断 +- **配套文档**: 无 —— 没有新的调用方契约,迁移的坑记在本提案里(决策日志「文档判断」) - **网页版**: 同目录同名的 `.html` ## 摘要 @@ -315,8 +315,10 @@ upcoming feature 只作用于开启它的 target 本身的编译,不传给依 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): -- **要不要配套专题文章** —— 预计不需要:没有新的调用方契约;「迁移模式的四类坑」已在本提案里写全。落地时再确认。 -- **有没有引入新术语** —— 预计没有。 +- **要不要配套专题文章** —— 不需要:没有新的调用方契约;迁移时踩到的坑已在本提案里写全(决策日志「文档判断」)。 +- **有没有引入新术语** —— 没有。 + +第 1–8 步已完成,验证结果见决策日志「验证结果」;第 9 步留给正式收尾。 ## 决策日志 @@ -330,3 +332,6 @@ upcoming feature 只作用于开启它的 target 本身的编译,不传给依 | 2026-11-20 | `any P?` 改成 `(any P)?` | Swift 6.4 的 fix-it 写出的 `any P?` 在 Swift 6.3(CI 的 Xcode 26.6)下报错;swift-demangling、MachOKitExtensions、本库各一处 | | 2026-11-20 | 14 个测试文件写 `Swift.Error` | 除了预修的两处,`migrate` 还给 93 个文件加了 `import Semantic`,其中 14 个测试文件里有类型位置的裸 `Error`(`struct …Error: Error`、`any Error`、`(any Error).self`),全部改成 `Swift.Error`;源码里没有,也没有出现「转型永远失败」的警告 | | 2026-11-20 | MachOKit 一个测试的期望符号名 | `MachOPrintTests.testFindSymbolByName` 按名字找测试二进制里的一个 curry thunk;Swift 6 模式把对 `LoadCommand.dylib` 的未调用引用推断为 `@Sendable`(SE-0418),mangling 多了 `Yb`,测试改为新名字。其余失败的 5 个用例在基线上同样失败(`libclang_rt.osx.a` 不存在等环境原因) | +| 2026-11-20 | 验证结果 | 全部在 Ultra 上跑。六个包用 Xcode 27.2 与 26.6 都编过(含全部测试目标)。测试:swift-semantic-string、swift-demangling、MachOKitExtensions 全过;MachOKit 只剩基线上同样失败的 5 个环境用例;MachOObjCSection 的 `MachOObjCSectionTests` 这个 XCTest 类在 `setUp` 读用户本机的 `/Users/JH/Downloads/iOS18.5-SwiftUI`,在基线上同样崩溃,跳过它后其余全过;本库在 Xcode 26.6 下 554 个 suite、2,906 个测试全过。渲染 A/B(基线 `next`,三条腿含归档 cache 26.6 与 15.5、模拟器 runtime、进程内 MachOImage)84 对逐字节一致。Tuist 工作区 `warm` 与 `build` 都成功。fork 的 CI 在 Xcode 16.2 与 Linux Swift 6.0.3 上通过 | +| 2026-11-20 | 文档判断 | 不配使用指南或实现说明:没有新的调用方契约,迁移时踩到的坑都写在本提案里;没有新术语;`CLAUDE.md` 不加条目,漏写 `any` 或漏 import 编译器当场报错,`Semantic.Error` 遮蔽也会让类型位置编不过。账本一节留到正式收尾时随取号一起写 | +| 2026-11-20 | 实现完成,待用户看过后收尾 | 六个仓库的功能分支都已推送 | From a12e942ba00d08ae10c2cc666c70d93fbb17f681 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 18:33:17 +0800 Subject: [PATCH 031/175] docs: record the FixtureSuite macro's verification --- .../Evolutions/draft-fixture-suite-macro.html | 24 ++++++++++++------- .../Evolutions/draft-fixture-suite-macro.md | 17 ++++++------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.html b/Documentations/Evolutions/draft-fixture-suite-macro.html index b237b930..141fdb74 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.html +++ b/Documentations/Evolutions/draft-fixture-suite-macro.html @@ -162,7 +162,7 @@

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-20
    项目类型
    库
    原文
    draft-fixture-suite-macro.md
    @@ -174,7 +174,8 @@

    Draft @FixtureSuite 宏:

    摘要

    -

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

    +

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

    +
    @@ -215,14 +216,16 @@

    展开前后

    改动地图

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

    提议方案

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

    非目标

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

    详细设计

    动机

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

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

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

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

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

    API 演进与废弃策略

    落地步骤

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

    决策日志

    - 3 条,最近一条:宏与协议同名 FixtureSuite + 7 条,最近一条:实现完成,待用户看过后收尾
    -
    日期变更说明
    2026-11-20Created as Draft用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;acrossAllReaders 改用普通函数重载(归 draft-shared-macho-testing-support)。用户选择把这个宏另写一份本包提案。
    2026-11-20宏实现放新 target SwiftSectionTestingMacros生产代码链接的 SwiftSectionMacros 插件不带测试用的宏。
    2026-11-20宏与协议同名 FixtureSuite照 Observation 的 Observable 先例,@FixtureSuite 读起来就是「这是一个夹具套件」。
    +
    日期变更说明
    2026-11-20Created as Draft用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;acrossAllReaders 改用普通函数重载(归 draft-shared-macho-testing-support)。用户选择把这个宏另写一份本包提案。
    2026-11-20宏实现放新 target SwiftSectionTestingMacros生产代码链接的 SwiftSectionMacros 插件不带测试用的宏。
    2026-11-20宏与协议同名 FixtureSuite照 Observation 的 Observable 先例,@FixtureSuite 读起来就是「这是一个夹具套件」。
    2026-11-20状态 → Accepted用户批准,开始实现。
    2026-11-20第 1、2 步完成宏的 6 个展开测试与扫描器的 9 个测试在 MacBook 上通过(Ultra 负载过高,按规则分流)。
    2026-11-20套件数更正:171 个,迁 170 个提案里的 176 是 grep 把扫描器样例文本里的几个类也数进去了。CoroFunctionPointerTests 自己编夹具、没有 baseline,注册名单是字面量,套不上宏,保持手写。
    2026-11-20实现完成,待用户看过后收尾在 MacBook 上按 CI 的 ad-hoc 签名编出 SymbolTestsCore,跑 swift test --skip IntegrationTests:MachOSwiftSectionCoverageInvariantTests、宏与扫描器的测试全部通过。另有 150 组失败——夹具套件的 offset()、layout() 等与 baseline 写死的偏移不符,以及 SymbolicDemanglerTests 找不到 iOS 26.5 模拟器运行时——在同一台机器、同一份夹具上切到 next 跑同一批,失败逐条相同,是 MacBook 的环境(夹具与 baseline 的产物不一致、没装该运行时),不是本次引入的。Ultra 负载过高(1 分钟负载约 90–107),没在 Ultra 上跑。文档:AGENTS.md 与 FixtureTestingAndContinuousIntegration.md 已写明用法;不另写实现说明;没有新术语。
    +
    diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.md b/Documentations/Evolutions/draft-fixture-suite-macro.md index 8feeba91..5e1f5c0a 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.md +++ b/Documentations/Evolutions/draft-fixture-suite-macro.md @@ -12,11 +12,11 @@ ## 摘要 -新增 attached 宏 `@FixtureSuite`,挂在夹具测试套件类上,生成 `static let testedTypeName`、`static var registeredTestMethodNames`,并补上对 `FixtureSuite` 协议的遵循。被测类型名默认取类名去掉 `Tests` 后缀,baseline 默认取「类名去掉 `Tests` 加 `Baseline`」;少数例外用参数写明。`SuiteBehaviorScanner` 改为也认宏的写法。`MachOSwiftSectionTests` 里的夹具套件全部改用宏,每处省 3 行。宏的实现放在新的宏 target `SwiftSectionTestingMacros`,声明放在 `SwiftSectionTestingSupport`,只有测试链接它。 +新增 attached 宏 `@FixtureSuite`,挂在夹具测试套件类上,生成 `static let testedTypeName`、`static var registeredTestMethodNames`,并补上对 `FixtureSuite` 协议的遵循。被测类型名默认取类名去掉 `Tests` 后缀,baseline 默认取「类名去掉 `Tests` 加 `Baseline`」;少数例外用参数写明。`SuiteBehaviorScanner` 改为也认宏的写法。`MachOSwiftSectionTests` 里按固定写法写的 170 个夹具套件改用宏,每处省 3 行(`CoroFunctionPointerTests` 没有 baseline,保持手写)。宏的实现放在新的宏 target `SwiftSectionTestingMacros`,声明放在 `SwiftSectionTestingSupport`,只有测试链接它。 ## 动机 -- **同样的 5 行写了 176 遍。** `MachOSwiftSectionTests` 里每个夹具套件的开头都是: +- **同样的 5 行写了 170 遍。** `MachOSwiftSectionTests` 里每个夹具套件的开头都是: ```swift @Suite @@ -27,7 +27,7 @@ } ``` - (`Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift:16-21`)176 个类声明遵循 `FixtureSuite`;按完整写法匹配的 170 个里,165 个的被测类型名就是类名去掉 `Tests`,只有 5 个例外。 + (`Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift:16-21`)171 个夹具套件遵循 `FixtureSuite`;按完整写法匹配的 170 个里,165 个的被测类型名就是类名去掉 `Tests`,只有 5 个例外。 - **手抄容易抄错。** `testedTypeName` 决定覆盖率不变式按哪个类型检查成员(`FixtureSuite.swift` 的文档注释),抄错一个字母,这个套件就静默地对不上源码里的类型。 - **起因**:用户问能否给测试加便捷的宏减少样板。调研后,跨读取器写法 `acrossAllReaders` 不适合做宏(改用普通函数重载,归 `draft-shared-macho-testing-support`),套件开头这一处适合,另写本提案。 @@ -57,7 +57,7 @@ 3. **默认值**:`testedTypeName` 取类名去掉 `Tests` 后缀;baseline 取同一个词干加 `Baseline`。类名不以 `Tests` 结尾时报错并给 Fix-It(写明 `testedTypeName:`)。 4. **参数**:`@FixtureSuite(testedTypeName: "EnumTagCounts")`、`@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self)`。两个参数都只收字面量(字符串字面量、`类型.self`),给变量就报错,不静默退回默认值。 5. **扫描器**:`SuiteBehaviorScanner` 先看类上有没有 `@FixtureSuite`:有就取 `testedTypeName:` 参数的字面量,没有参数就取类名去掉 `Tests`;没有宏的类照旧读静态成员。 -6. **迁移**:176 个夹具套件全部改用宏——类声明里去掉 `FixtureSuite` 遵循和两个静态成员,挂上 `@FixtureSuite`;5 个例外带参数。 +6. **迁移**:按完整写法写的 170 个夹具套件改用宏——类声明里去掉 `FixtureSuite` 遵循和两个静态成员,挂上 `@FixtureSuite`;5 个例外带参数。`CoroFunctionPointerTests` 没有 baseline、注册名单是字面量,保持手写。 7. 本包 `AGENTS.md`「添加夹具测试」那几条(`:186` 一带)改成用宏的写法。 ### 非目标 @@ -77,7 +77,7 @@ | `Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift` | 新增 | 展开测试:默认、只给 `testedTypeName`、两个都给、类名不以 `Tests` 结尾、参数不是字面量 | 宏的行为 | 1 | | `Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift` | 修改 | 认 `@FixtureSuite`:取参数或类名词干 | 扫描器按源码读被测类型名 | 2 | | `Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift`、`Fixtures/SuiteSampleSource.swift.txt` | 修改 | 加宏写法的样例与测试 | 扫描器的行为 | 2 | -| `Tests/MachOSwiftSectionTests/Fixtures/**/*Tests.swift`(176 个夹具套件) | 修改 | 改用 `@FixtureSuite` | 去掉样板 | 3 | +| `Tests/MachOSwiftSectionTests/Fixtures/**/*Tests.swift`(170 个夹具套件) | 修改 | 改用 `@FixtureSuite` | 去掉样板 | 3 | | `AGENTS.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md` | 修改 | 添加夹具测试的写法 | 文档同步 | 4 | ## 架构图 @@ -91,7 +91,7 @@ Package (MachOSwiftSection) ~ Coverage/SuiteBehaviorScanner reads @FixtureSuite too ~ SwiftSectionTestingSupport -> + SwiftSectionTestingMacros + macro FixtureSuite(testedTypeName:baseline:) -~ MachOSwiftSectionTests 176 suites: @FixtureSuite +~ MachOSwiftSectionTests 170 suites: @FixtureSuite + SwiftSectionTestingMacrosTests expansion tests ``` @@ -168,10 +168,10 @@ package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = - 行为:`scannerReadsTheTestedTypeNameFromTheMacroArgument` - 行为:`scannerTakesTheClassNameStemWhenTheMacroHasNoArgument` - 行为:`scannerStillReadsAStaticTestedTypeName` -3. **迁移 176 个套件** —— `Tests/MachOSwiftSectionTests/Fixtures/**` +3. **迁移 170 个套件**(完成)—— `Tests/MachOSwiftSectionTests/Fixtures/**` - 行为:覆盖率不变式测试照常通过,迁移前后 `allFixtureSuites` 各套件的 `testedTypeName` 与 `registeredTestMethodNames` 逐个相等 - 行为:`SuiteBehaviorScanner` 认出的「被测类型 → 测试方法 → 行为」与迁移前逐条相同 -4. **文档** —— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md` +4. **文档**(完成)—— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md` - 收尾判断:实现说明不必单写,`AGENTS.md` 的步骤与宏的文档注释够用;没有新术语。 ## 决策日志 @@ -184,3 +184,4 @@ package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = | 2026-11-20 | 状态 → Accepted | 用户批准,开始实现。 | | 2026-11-20 | 第 1、2 步完成 | 宏的 6 个展开测试与扫描器的 9 个测试在 MacBook 上通过(Ultra 负载过高,按规则分流)。 | | 2026-11-20 | 套件数更正:171 个,迁 170 个 | 提案里的 176 是 grep 把扫描器样例文本里的几个类也数进去了。`CoroFunctionPointerTests` 自己编夹具、没有 baseline,注册名单是字面量,套不上宏,保持手写。 | +| 2026-11-20 | 实现完成,待用户看过后收尾 | 在 MacBook 上按 CI 的 ad-hoc 签名编出 `SymbolTestsCore`,跑 `swift test --skip IntegrationTests`:`MachOSwiftSectionCoverageInvariantTests`、宏与扫描器的测试全部通过。另有 150 组失败——夹具套件的 `offset()`、`layout()` 等与 baseline 写死的偏移不符,以及 `SymbolicDemanglerTests` 找不到 iOS 26.5 模拟器运行时——在同一台机器、同一份夹具上切到 `next` 跑同一批,失败逐条相同,是 MacBook 的环境(夹具与 baseline 的产物不一致、没装该运行时),不是本次引入的。Ultra 负载过高(1 分钟负载约 90–107),没在 Ultra 上跑。文档:`AGENTS.md` 与 `FixtureTestingAndContinuousIntegration.md` 已写明用法;不另写实现说明;没有新术语。 | From 30d9b7d9c54ce6111b389638fcc3c89765c19458 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 20 Nov 2026 20:38:57 +0800 Subject: [PATCH 032/175] docs: land the FixtureSuite macro as proposal 0100, and number ledger section 145 --- AGENTS.md | 2 +- ...cro.html => 0100-fixture-suite-macro.html} | 28 +++++++++---------- ...e-macro.md => 0100-fixture-suite-macro.md} | 10 ++++--- Documentations/Evolutions/README.md | 2 +- .../FixtureTestingAndContinuousIntegration.md | 2 +- .../Internal/ProjectEvolutionLog.md | 18 ++++++++++++ Documentations/README.md | 2 +- 7 files changed, 42 insertions(+), 22 deletions(-) rename Documentations/Evolutions/{draft-fixture-suite-macro.html => 0100-fixture-suite-macro.html} (92%) rename Documentations/Evolutions/{draft-fixture-suite-macro.md => 0100-fixture-suite-macro.md} (93%) diff --git a/AGENTS.md b/AGENTS.md index d199d191..ff01b680 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -188,7 +188,7 @@ That directory is exhaustively covered by `Tests/MachOSwiftSectionTests/Fixtures 5. `swift package --allow-writing-to-package-directory regen-baselines --suite `. 6. Re-run the affected Suite. -A new Suite is a class marked `@FixtureSuite` (SwiftSectionTestingSupport): the macro adds `testedTypeName` — the class name without `Tests` — and `registeredTestMethodNames` read from `Baseline`, plus the `FixtureSuite` conformance. Name either with a literal only when it differs (`@FixtureSuite(testedTypeName: "EnumTagCounts")`); `SuiteBehaviorScanner` reads the tested type from the attribute the same way. [draft-fixture-suite-macro](Documentations/Evolutions/draft-fixture-suite-macro.md). +A new Suite is a class marked `@FixtureSuite` (SwiftSectionTestingSupport): the macro adds `testedTypeName` — the class name without `Tests` — and `registeredTestMethodNames` read from `Baseline`, plus the `FixtureSuite` conformance. Name either with a literal only when it differs (`@FixtureSuite(testedTypeName: "EnumTagCounts")`); `SuiteBehaviorScanner` reads the tested type from the attribute the same way. [0100-fixture-suite-macro](Documentations/Evolutions/0100-fixture-suite-macro.md). A type with genuinely nothing to test goes on the sentinel allowlist with a typed `SentinelReason` (`pureDataUtility` / `runtimeOnly` / `needsFixtureExtension`) in `CoverageAllowlistEntries.swift`. Rationale and history: [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). diff --git a/Documentations/Evolutions/draft-fixture-suite-macro.html b/Documentations/Evolutions/0100-fixture-suite-macro.html similarity index 92% rename from Documentations/Evolutions/draft-fixture-suite-macro.html rename to Documentations/Evolutions/0100-fixture-suite-macro.html index 141fdb74..f051cd21 100644 --- a/Documentations/Evolutions/draft-fixture-suite-macro.html +++ b/Documentations/Evolutions/0100-fixture-suite-macro.html @@ -4,7 +4,7 @@ -Draft - @FixtureSuite 宏:夹具测试套件开头的固定写法由宏生成 +0100 - @FixtureSuite 宏:夹具测试套件开头的固定写法由宏生成 + + + + + diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md new file mode 100644 index 00000000..f283e9a3 --- /dev/null +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -0,0 +1,398 @@ +# Draft - 长类型拆行:放不下的类型按括号结构拆成多行 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-21 +- **最后更新**: 2026-11-21 +- **所属愿景**: 无 +- **关联提案**: 无 +- **实现分支 / PR**: `feature/multiline-type-formatting` +- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +新增一个公开的格式化值类型 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把已经打印好的 Swift 源码(`SemanticString`)里放不下的类型按括号拆成多行:一个类型一行放得下就不动;放不下时,整个类型照 [TypeAliasFormatter](https://github.com/OpenSwiftUIProject/TypeAliasFormatter) 的结构规则拆开——有两个及以上参数的泛型参数列表每个参数一行,单参数泛型、元组、函数类型与声明的参数列表、`[…]` 集合语法糖只在里面有拆开的部分时才拆。它只插入换行和缩进,文字、semantic type、identifier 和各种 region 原样保留。`swift-section dump` / `interface` 新增 `--multiline-types` 与 `--maximum-line-width`,`InterfaceRequest` / `DumpRequest` 新增同名字段;默认关闭,关闭时输出逐字节不变。RuntimeViewer 在拿到一个定义的完整打印之后调用一次即可,打印器本身一行不改。 + +## 动机 + +SwiftUI 视图的 `Body`、modifier 链、`TupleView` 之类的类型在二进制里是完整展开的泛型树,打印出来是一整行。RuntimeViewer 里打开 Preferences.app 的 `SettingsApp.SettingsNavigationSplitView`,`extension … : SwiftUI.View` 里的 `typealias Body = SwiftUI.ModifiedContent` 挤在一起,看不出哪个参数属于哪一层。dump 与 CLI 的 interface 输出同样如此,同类问题也出现在任何带长泛型的成员签名、`where` 子句和关联类型 witness 上。 + +这类类型只能靠拆行看懂层级。社区里已有专门的工具(TypeAliasFormatter:粘贴一个 typealias,按括号结构排版),说明这个需求是真实存在的;但它工作在纯文本上,复制出来、粘进去、再对照回来,丢掉了 RuntimeViewer 的语法着色、跳转链接与各种 region。本提案把同样的排版放进库里,直接作用在打印结果上。 + +## 前期调研 + +- **类型由两套打印器拼成 `SemanticString`。** interface 走本仓库的 `SwiftPrinting`(`TypeNodePrinter` 等,`Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift:8`),泛型参数列表由 `printBoundGenericNoSugar` 写出(`Sources/Output/SwiftPrinting/NodePrintables/BoundGenericNodePrintable.swift:66`:`printChildren(typeList, prefix: "<", suffix: ">", separator: ", ")`);dump 走上游 swift-demangling 的 `NodePrinter`,经 `DemangleResolver.options`(`Sources/Output/SwiftDeclarationRendering/DemangleResolver.swift:31`)。两边写括号和逗号都用不带 context 的 `write(_:)`,`SemanticString` 把它记成 `.standard` 类型的独立 atom(`swift-semantic-string/Sources/Semantic/SemanticString+Conformances.swift:32`),而类型名、模块名、关键字、声明名、注释各有自己的 semantic type。 +- **`typealias Body` 这一行是怎么拼出来的。** `renderMergedAssociatedTypeRecords`(`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift:305`)依次写 `Indent`、`typealias`、名字、`=`,再把 `resolver.resolve(for:)` 打印出的整个类型接在同一行(`:318`–`:326`)。成员签名里的类型则由 `FunctionNodePrinter` / `VariableNodePrinter` 在打印整条声明时递归写出,没有单独的「一个类型」的 `SemanticString`。 +- **region 编码在 atom 的 `identifier` 上。** `AnnotationRegion`、`VisibilityRegion`、`DefinitionRegion` 都不占文字,而是把标记写进每个 atom 的 `identifier`,冻结后再分离出来(`swift-semantic-string/Sources/Semantic/AnnotationRegions/AnnotationRegion.swift` 的类型注释);同一种 region 中间夹进一个不带编码的 atom,会被读成两个。所以插入的换行与缩进 atom 必须沿用相邻 atom 的 `identifier`。 +- **嵌套定义的契约只允许缩进随层级变化。** `marksNestedDefinitions` 承诺:父定义打印里深度为 `d` 的子定义,取出后 `removingIndentation(levels: d + 1)`,等于子定义单独打印的结果(`Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift:198`–`:236`)。`removingIndentation` 按字节从每个非空行开头删 `levels * 4` 个空格(`swift-semantic-string/Sources/Semantic/Frozen/FrozenSemanticString+Indentation.swift:28`–`:61`)。因此拆不拆一行,不能取决于这一行缩进了多深——否则同一个子定义在父定义里和单独打印时会拆得不一样。 +- **运算符名在 dump 里是带 `<` 的 `.standard` atom。** 上游 `NodePrinter` 把 `infixOperator` 写成 `"\(name) infix"`(`swift-demangling/Sources/Demangling/Node/Printer/NodePrinter.swift:499`),`static func < infix(…)` 里的 `<` 和泛型括号同为 `.standard`。扫描器必须容忍括号不配对的行,而不是猜。 +- **宿主是怎么拿到一个定义的。** RuntimeViewer 把一个运行时对象的所有打印(`printTypeDefinition`、`printExtensionDefinition`、`printProtocolDefinition`)拼进一个 `newInterfaceString`,再缓存成 `RuntimeObjectInterface`(RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCore/Core/RuntimeSwiftSection.swift:284`–`:364`),且它已经依赖 `SwiftDeclarationRendering` product(同仓库 `RuntimeViewerCore/Package.swift:178`)。SwiftSectionKit 里 interface 在 `InterfaceRequest.run` 拿到 `builder.printRoot()` 的整份结果(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:225`),dump 在 `DumpSession.dump` 一次处理一个顶层声明(`Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift:513`–`:530`)。三处都是「打印完、交出去之前」的唯一出口。 +- **TypeAliasFormatter 的规则。** 它的 `Renderer`(`Packages/TypeAliasFormatterCore/Sources/TypeAliasFormatterCore/TypeAliasFormatter.swift`):`<` 有两个及以上参数时一律展开、每个参数一行;只有一个参数时保持一行,除非某个参数已是多行;`(` 与 `[` 只在某个元素是多行时展开;`->` 不算括号;反引号里的内容不解析;另有 `expandSingleArguments` 选项把单参数泛型也展开。它不看行宽,任何输入都整个排版。该仓库没有 license 文件,本提案只借用规则,不复制代码。 +- **用户选定的规则。** 本次澄清提问里比较过三种:纯按行宽逐层决定、完全照 TypeAliasFormatter、两者结合。选定两者结合:放得下的类型不动(`Swift.Result` 这类短类型不会在每个签名里被拆成四行),放不下的类型整个按结构规则拆(同一个类型无论嵌在第几层,拆出来的形状都一样)。适用于所有出现类型的位置,元组与函数类型的括号一起处理。 + +## 提议方案 + +在 `SwiftDeclarationRendering` 里加一个纯函数式的格式化值类型: + +```swift +let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +let formatted = formatting.format(printedDefinition) +``` + +它逐行处理输入,规则如下: + +1. **一行的内容宽度不超过 `maximumLineWidth` 就原样保留。** 内容宽度是这一行的字符数减去行首缩进——缩进不计入,所以拆不拆与嵌套深度无关,嵌套定义的契约自然成立。 +2. **超宽的行解析成括号树。** 只在 `.standard` 类型的 atom 里找括号;类型名、模块名、关键字、声明名、注释等其它 atom 整体当作文字。字符串字面量、反引号标识符、`//` 之后的内容是文字;`->` 不是括号。括号不配对(例如 dump 里的运算符声明)就整行原样保留。 +3. **找出放不下的类型。** 不在其它泛型参数列表里面的泛型参数列表,算作一个类型的最外层;它的 `>` 落在第 `maximumLineWidth` 列之后,这个类型就算放不下。只有泛型参数列表会触发拆行;行之所以超宽是因为别的东西(一长串参数、行尾注释),这一行不动。 +4. **放不下的类型按结构规则拆。** 在这个类型内部:有两个及以上参数的泛型参数列表一律每个参数一行;单参数的泛型参数列表、元组、函数类型的参数列表、`[…]` 集合语法糖,只在某个元素已是多行时才拆。 +5. **外层括号跟着拆。** 类型之外的括号——函数声明的参数列表、enum case 的 payload、元组、泛型参数子句(紧跟在声明名后面的 `<…>`)、attribute 的参数——只在某个元素已是多行时才拆,否则保持一行。泛型参数子句因此不会仅仅因为有两个参数就被拆开。 +6. **拆开的列表这样排。** 开括号留在原行末尾;每个参数另起一行,缩进为这一行的行首缩进加 4 个空格乘以嵌套层数;参数之间的 `, ` 变成 `,`;闭括号另起一行,缩进回到上一层。 + +截图里那个 `Body` 的开头一段,按默认宽度格式化后是这样: + +```swift +extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent< + SwiftUI.ModifiedContent< + SwiftUI.SceneBridgeReader< + SwiftUI.SubscriptionView< + Combine.PassthroughSubject< + Any, + Swift.Never + >, + SwiftUI.NavigationSplitView< + SwiftUI.ModifiedContent< + SettingsApp.SettingsSidebarList, + SwiftUI.ToolbarRemovingModifier + >, + SettingsApp.SettingsSecondaryColumn + > + > + >, + SwiftUI._EnvironmentKeyWritingModifier + >, + SwiftUI.OnTestViewModifier + > +} +``` + +同一个文件里放得下的类型不受影响: + +```swift +var result: Swift.Result +var selection: SwiftUI.Binding> +``` + +函数签名里有一个类型放不下时,参数列表随之拆开,其余参数保持一行: + +```swift +func update( + model: Swift.Result, + content: SwiftUI.ModifiedContent< + SwiftUI.TupleView<…>, + SwiftUI._EnvironmentKeyWritingModifier + > +) -> Swift.Bool +``` + +接入点只有调用方的出口:`InterfaceRequest` 与 `DumpRequest` 各加一个 `multilineTypeFormatting: MultilineTypeFormatting?` 字段(默认 `nil`),在交出产物前调用一次;CLI 的 `dump` 与 `interface` 加 `--multiline-types` 与 `--maximum-line-width `。RuntimeViewer 在 `RuntimeSwiftSection` 缓存 `RuntimeObjectInterface` 之前调用一次(下游后续改动,不在本提案的实现范围内)。打印器、`SwiftDeclarationPrintConfiguration` 与 `DeclarationRenderConfiguration` 都不改。 + +### 非目标 + +- **不改打印器。** `SwiftPrinting`、`SwiftDump`、上游 swift-demangling 与 swift-semantic-string 一行不动;默认关闭时所有输出逐字节不变,fixture baseline 与渲染 A/B 不受影响。 +- **diff、evolution、snapshot 不接。** diff 与 evolution 的输出按行标记增删,拆行会让一个声明的标记散到多行;snapshot 是 JSON。这三个请求不加字段。 +- **ObjC 输出不接。** `swift-section objc …` 打印的是 Objective-C 头文件,没有本提案要拆的 Swift 泛型。 +- **不单独拆长参数列表。** 一个函数声明有十个短参数而超宽,本提案不拆它;参数列表只在某个参数的类型被拆开时随之拆开。按行宽拆参数列表是另一个功能。 +- **不做 TypeAliasFormatter 的其它能力。** 单参数泛型也展开的 `expandSingleArguments`、2 / 8 空格或 Tab 缩进、类型树的图形视图都不做;`MultilineTypeFormatting` 是 struct,以后要加选项时加带默认值的属性即可。 +- **不解决 SwiftUI modifier 链缩进很深的问题。** `ModifiedContent, M>` 是向左嵌套的,二十多层 modifier 拆开后第一个参数会缩进二十多层。把这种链压平成一层需要按语义改写类型,不属于排版。 +- **RuntimeViewer 的设置界面与接入不在本提案里实现。** 本提案只交付库与 CLI;RuntimeViewer 的开关、调用与缓存失效由它自己的改动完成。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift` · `MultilineTypeFormatting` | 新增 | 公开 struct:`maximumLineWidth`、`init(maximumLineWidth:)`、`format(_:)`;`format` 逐行调用下面三块 | dump 与 interface 共用的位置,RuntimeViewer 已依赖这个 product | 1 | +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift` · `MultilineTypeFormatting.Line`(internal) | 新增 | 把 atom 序列按 `\n` 切成行(切开的 atom 保留 type 与 identifier)、算行首缩进与内容宽度、把处理后的行拼回去 | 规则 1:宽度不超的行不解析,直接复制 | 1 | +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift` · `MultilineTypeFormatting.BracketTree`(internal) | 新增 | 把一行解析成括号树:只扫 `.standard` atom,字符串、反引号、`//`、`->` 当文字;括号种类分为泛型参数列表、泛型参数子句、圆括号、方括号;不配对返回 `nil` | 规则 2 | 2 | +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift` · `MultilineTypeFormatting.Layout`(internal) | 新增 | 判定放不下的类型、自下而上决定哪些列表拆开、按规则 6 生成 atom(插入的换行与缩进沿用相邻括号或逗号 atom 的 identifier) | 规则 3–6 | 3 | +| `Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift` | 新增 | 行切分、解析、排版的单元测试,输入用手工拼的 `SemanticString`,形状与两套打印器的输出一致 | 每步的行为清单 | 1–3 | +| `Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift` | 新增 | 保持性测试:semantic type 与 identifier 不变、去掉插入的换行能还原原文、幂等、与缩进可交换、region 读回不变 | 规则 6 的「只加换行和缩进」承诺 | 4 | +| `Tests/SwiftInterfaceTests/MultilineTypeFormattingNestedDefinitionTests.swift` | 新增 | 打开 `marksNestedDefinitions` 打印 SymbolTestsCore 里带嵌套类型的定义,格式化父定义后取出的子定义等于子定义单独打印后格式化 | 嵌套定义契约在格式化后仍成立 | 4 | +| `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | 新字段 `multilineTypeFormatting`(init 参数默认 `nil`),`run` 里 `printRoot()` 之后、写文件或交给 output 之前调用 | interface 的唯一出口 | 5 | +| `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift` · `DumpRequest`、`DumpSession` | 修改 | 新字段 `multilineTypeFormatting`;`DumpSession.dump` 拿到 `dumpedDeclaration` 后调用 | dump 的唯一出口,一次一个顶层声明 | 5 | +| `Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift` | 新增 | 两个请求打开与关闭字段时的输出 | 接入正确、关闭时不变 | 5 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift`、`DumpCommand.swift` | 修改 | `--multiline-types` flag、`--maximum-line-width ` option;`validate()` 拒绝单独给宽度和非正数宽度;`makeRequest()` 映射 | CLI 是 SwiftSectionKit 的包装 | 6 | +| `Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift` | 新增 | flag 映射到请求、校验错误的退出码 64 | CLI 两侧都要有测试 | 6 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 写明两个新 flag 与默认宽度 | CLI 改动要同批更新这份 skill | 6 | +| `Documentations/SwiftSectionKit.md`、`Documentations/Internal/Modules/SwiftSectionKit.md` | 修改 | 两个请求的新字段 | 调用方指南与模块参考 | 7 | +| `CLAUDE.md` | 修改 | SwiftDeclarationRendering 一条补一句它还提供 `MultilineTypeFormatting` | 模块清单与代码同步 | 7 | +| `Documentations/Internal/ProjectEvolutionLog.md`、`Documentations/Glossary.md`、`Documentations/README.md`、`Documentations/Evolutions/README.md` | 修改 | 账本一节、术语 multiline type formatting / long type、索引 | 文档纪律 | 7 | + +## 架构图 + +改了什么: + +```text +SwiftDeclarationRendering ++ ├── MultilineTypeFormatting.swift public struct, format(_:) ++ ├── MultilineTypeFormatting+Lines.swift split atoms into lines, width gate ++ ├── MultilineTypeFormatting+BracketTree.swift parse one line into a bracket tree ++ └── MultilineTypeFormatting+Layout.swift decide breaks, emit atoms +SwiftSectionKit +~ ├── Swift/InterfaceRequest.swift + multilineTypeFormatting, applied after printRoot() +~ └── Swift/DumpRequest.swift + multilineTypeFormatting, applied per declaration in DumpSession +swift-section +~ ├── Commands/InterfaceCommand.swift + --multiline-types, --maximum-line-width +~ └── Commands/DumpCommand.swift + --multiline-types, --maximum-line-width +SwiftPrinting, SwiftDump, swift-demangling, swift-semantic-string (unchanged) +``` + +数据流: + +```text +SwiftDeclarationPrinter / Dumpable (unchanged: one line per declaration) + │ SemanticString + ▼ ++ MultilineTypeFormatting.format(_:) (only when the caller opts in) + │ SemanticString: same text, types, identifiers, regions; long types broken + ▼ +InterfaceRequest / DumpSession ──► SwiftSectionOutput / file +RuntimeSwiftSection (RuntimeViewer, follow-up) ──► RuntimeObjectInterface cache +``` + +`format(_:)` 内部: + +```text +format(source) +└── for each line (atoms split at "\n" keep type + identifier) + ├── content width (minus leading indentation) <= maximumLineWidth ──► copy unchanged + └── BracketTree(line) (.standard atoms only; strings, backticks, "//", "->" are text) + ├── nil (unbalanced) ──► copy unchanged + └── Layout + ├── outermost generic argument list whose ">" lies past the width ──► long type + ├── inside a long type: generic argument list with >= 2 arguments ──► break + ├── any list with a multi-line element ──► break (bottom-up) + └── emit "<" "\n" indent(L + 4k) element "," "\n" … "\n" indent(L + 4(k - 1)) ">" +``` + +## 详细设计 + +### 公开 API + +```swift +/// Lays the long types of printed Swift source out over several lines. +/// +/// A type that runs past `maximumLineWidth` is broken at its brackets: every +/// generic argument list with two or more arguments puts each argument on a +/// line of its own, and a single-argument generic list, a tuple, a parameter +/// list or collection sugar breaks only when one of its elements spans +/// several lines. A type that fits, and every line that fits, stays as +/// printed. +/// +/// Formatting only adds line breaks and indentation, and drops the space of +/// each `, ` between broken elements: the text otherwise, every component's +/// semantic type and identifier, and so every visibility, definition and +/// annotation region, stay as they were. +public struct MultilineTypeFormatting: Hashable, Sendable { + /// The widest a line's content may be, in characters. A line's own + /// indentation does not count, so a declaration breaks the same way at + /// any nesting depth. + public var maximumLineWidth: Int + + /// - Precondition: `maximumLineWidth > 0`. + public init(maximumLineWidth: Int = 100) + + /// `source` with its long types laid out over several lines. + public func format(_ source: SemanticString) -> SemanticString +} +``` + +`SwiftSectionKit`: + +```swift +extension InterfaceRequest { + /// Lays long types out over several lines; `nil` prints every type on one line. + public var multilineTypeFormatting: MultilineTypeFormatting? { get set } +} + +extension DumpRequest { + public var multilineTypeFormatting: MultilineTypeFormatting? { get set } +} +``` + +两个请求的 memberwise `init` 各加一个参数 `multilineTypeFormatting: MultilineTypeFormatting? = nil`,放在 `commentTransformers` 之前,与现有的带默认值参数同列。 + +CLI(`dump` 与 `interface` 相同): + +```text +--multiline-types Break a type that runs past the line width over several lines, at its brackets. +--maximum-line-width The widest a line may be, not counting its indentation, before + --multiline-types breaks its types. (default: 100) +``` + +`validate()`:给了 `--maximum-line-width` 却没给 `--multiline-types`,或宽度不是正数,抛 `ValidationError`(退出码 64)。 + +### 行与宽度 + +- `format` 先把 `source.components` 按 `\n` 切成行。一个 atom 内含 `\n` 时在 `\n` 处切开,各段保留原 atom 的 `type` 与 `identifier`;`\n` 本身单独成段,原样输出。 +- 行首缩进是这一行开头连续空格的个数 `L`(跨 atom 计)。内容宽度是这一行的 `Character` 数减去 `L`。 +- 内容宽度不超过 `maximumLineWidth` 的行,其 atom 原样复制,不做任何解析。绝大多数行走这条路,`format` 的开销主要是一次按行扫描。 +- 行之间互不影响:括号跨行的输入(例如已经格式化过的输出)里,每一行单独看都不配对,因此原样保留——这正是 `format` 幂等的原因。 + +### 括号树 + +```swift +extension MultilineTypeFormatting { + enum BracketKind { + case genericArguments // "<" after anything but a declaration name + case genericParameters // "<" right after a declaration name + case parentheses // "(": tuples, function types, parameter lists, attribute arguments + case squareBrackets // "[": array and dictionary sugar + } + + indirect enum BracketTreeNode { + /// A run of a line's characters that is not a bracket, located by atom index and range. + case text(AtomRun) + /// A bracketed list: the opening and closing brackets' locations and the elements between the commas. + case list(kind: BracketKind, opening: AtomPosition, closing: AtomPosition, separators: [AtomPosition], elements: [[BracketTreeNode]]) + } +} +``` + +- 只有 `.standard` atom 参与扫描;其它 semantic type 的 atom 整体是一个 `text`。这样类型名、声明名(包括 interface 里的运算符名)、注释里的括号都不会被当成结构。 +- 在 `.standard` atom 里:`"` 开始一个字符串字面量,到未转义的 `"` 结束;反引号同理;`//` 之后到行末都是文字;`-` 紧跟 `>` 是箭头,不关闭任何列表;`<`、`(`、`[` 开列表,`>`、`)`、`]` 必须关闭同种列表;深度大于 0 时的 `,` 分隔元素。 +- `<` 前面(跳过空白)的 atom 的 semantic type 是 `.type(_, .declaration)`、`.function(.declaration)` 或 `.member(.declaration)` 时,这个列表是 `genericParameters`;否则是 `genericArguments`。 +- 关闭括号与种类不符、或行末仍有未关闭的列表,返回 `nil`,整行原样保留。dump 里的 `static func < infix(…)` 就走这条路。 + +### 排版 + +- **放不下的类型。** 只看「不在任何 `genericArguments` 里面」的 `genericArguments` 列表:它的闭括号 `>` 的内容列号(相对行首缩进,从 1 数)大于 `maximumLineWidth`,就把它标为长类型的根。列号按这一行原样打印时的位置算。 +- **决定拆哪些列表**,自下而上: + - 长类型根及其内部的 `genericArguments`,元素数不少于 2 时拆。 + - 任何列表,有元素是多行时拆(元素多行 = 元素里有被拆的列表)。 + - 其余不拆。长类型根之外的 `genericArguments` 内部不会有被拆的列表,因此整体保持一行。 +- **生成 atom。** 对每个要拆的列表,嵌套层数 `k` 是它自身加上包住它的被拆列表的个数: + - 开括号 atom 原样输出,后面插入 `\n` 与 `L + 4k` 个空格的缩进 atom; + - 每个元素去掉首尾空白后输出; + - 元素之间的分隔:原来的 `, `(或 `,`)atom 换成只含 `,` 的 atom(type 与 identifier 不变),后面插入 `\n` 与缩进; + - 闭括号前插入 `\n` 与 `L + 4(k − 1)` 个空格; + - 插入的 atom 都是 `.standard`,`identifier` 取它前面那个括号或逗号 atom 的 `identifier`。括号若和别的字符在同一个 atom 里,就在括号处切开,各段保留原 type 与 identifier。 +- 一个列表为空(`()`)时从不拆。 + +### 保持性 + +以下性质是公开承诺,各有测试: + +1. 内容宽度不超的行逐 atom 不变。 +2. 去掉插入的换行与缩进、把被改的 `,` 还原成 `, `,得到与输入相同的文字。 +3. 每个原有字符所在 atom 的 semantic type 与 identifier 不变;冻结后各种 region 分离出来与格式化前相同(位置随文字平移)。 +4. 幂等:`format(format(x)) == format(x)`。 +5. 与缩进可交换:把输入每个非空行多缩进 4 个空格再格式化,等于先格式化再多缩进 4 个空格。由此,格式化后的父定义里取出的嵌套定义,等于嵌套定义单独打印再格式化。 + +## 替代方案考量 + +- **纯按行宽、逐层决定(Wadler / Oppen 式的 group)。** 每个括号列表一行放得下就不拆。否:同一个类型嵌在不同深度时排版不同;短的多参数泛型时拆时不拆,读者没法靠形状认出结构。用户在澄清提问里否掉了。 +- **完全照 TypeAliasFormatter,不看行宽。** 否:适用于所有类型位置后,每个 `Swift.Result`、`Swift.Dictionary<…>` 都会被拆成多行,整份 interface 变长数倍。用户在澄清提问里否掉了。 +- **在打印器里拆:打印泛型参数时直接写换行或「可断点」标记。** 否:类型来自两套打印器(本仓库的 `SwiftPrinting` 与上游 swift-demangling 的 `NodePrinter`),要改两处并给上游的 `NodePrinterTarget` 加要求——这个协议刻意不给默认实现,加一条要求就要上游发版、所有 target 都改;打印器按节点身份 memoize 的片段会带上依赖列号的排版决定;嵌套定义契约要求的「只有缩进随层级变化」也得在递归里处处维护。 +- **做成 `SwiftDeclarationPrintConfiguration` 的选项,由每个公开打印入口在返回前格式化。** 否:公开入口有二十来个且互相调用(嵌套类型会再次进入 `printTypeDefinition`),要么重复格式化,要么把每个入口拆成「公开入口 + 内部实现」;dump 的 `DeclarationRenderConfiguration` 还得另接一遍。三个真正的调用方(两个请求、RuntimeViewer)都只有一个出口,在出口调用一次更简单。 +- **在纯文本上格式化(照搬 TypeAliasFormatter 的做法)。** 否:会丢掉 semantic type、identifier 与 region,RuntimeViewer 的着色、跳转与嵌套定义拆分都依赖它们。 +- **扫描所有 atom 的所有字符。** 否:interface 里运算符名、私有类型名 `(Visitor in $…)` 等 atom 也含括号;只扫 `.standard` atom,再对不配对的行放弃,误判面最小。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增。`MultilineTypeFormatting` 是新类型;`InterfaceRequest` 与 `DumpRequest` 的新字段和 init 参数都有默认值 `nil`,现有调用点不受影响;CLI 新增的两个参数不改变任何已有参数的含义与默认输出。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftDeclarationRendering` 加文件;`SwiftSectionKit` 与 `swift-section` 加字段与参数。打印器、索引、ABI 层不动。 +- **RuntimeViewer**:要用这个功能,需要在设置里加一个开关(可附宽度),在 `RuntimeSwiftSection` 生成 `RuntimeObjectInterface` 之前(`RuntimeSwiftSection.swift:364`)调用 `format`,并在开关变化时清掉 `interfaceByObject` 缓存。它已依赖 `SwiftDeclarationRendering`,不必改依赖声明。这是 RuntimeViewer 自己的后续改动。 +- MachOKitUI、SymbolViewer:不受影响。 + +### 文档与示例 + +- `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`:两个新 flag。 +- `Documentations/SwiftSectionKit.md`(调用方指南)与 `Documentations/Internal/Modules/SwiftSectionKit.md`:新字段。 +- `CLAUDE.md` 的模块清单:SwiftDeclarationRendering 一条。 +- 发版时 `Changelogs/.md` 写一条。 + +## API 演进与废弃策略 + +- 不替代任何旧 API,没有废弃。 +- 以后要加 TypeAliasFormatter 的「单参数泛型也展开」、其它缩进宽度等选项时,给 `MultilineTypeFormatting` 加带默认值的存储属性,现有调用点不变;不把它改成 enum。 +- 不需要 semver major 跃迁。 + +## 落地步骤 + +1. **骨架:类型、行切分与宽度闸门** —— 改动地图第 1、2、5 行 + - 行为:`emptySourceIsUnchanged` + - 行为:`linesWithinWidthAreUnchangedAtomForAtom` + - 行为:`contentWidthIgnoresLeadingIndentation` + - 行为:`atomsContainingLineBreaksAreSplitKeepingTypeAndIdentifier` + - 行为:`nonPositiveWidthIsAPreconditionFailure`(exit test) +2. **括号树** —— 改动地图第 3、5 行 + - 行为:`genericArgumentListsNestInsideParenthesesAndBrackets` + - 行为:`angleBracketAfterDeclarationNameIsGenericParameterClause` + - 行为:`arrowIsNotAClosingBracket` + - 行为:`bracketsInsideStringLiteralsAreText` + - 行为:`bracketsInsideBackticksAreText` + - 行为:`bracketsAfterLineCommentAreText` + - 行为:`bracketsInNonStandardAtomsAreText`(类型名、声明名、注释 atom) + - 行为:`unbalancedLineIsLeftUnchanged` + - 行为:`operatorDeclarationFromDumpIsLeftUnchanged`(`static func < infix(…)`) +3. **排版与生成** —— 改动地图第 4、5 行 + - 行为:`multiArgumentGenericBreaksOneArgumentPerLine` + - 行为:`singleArgumentGenericStaysInlineUnlessItsArgumentBreaks` + - 行为:`tupleBreaksOnlyWhenAnElementBreaks` + - 行为:`functionTypeParametersBreakOnlyWhenAParameterBreaks` + - 行为:`collectionSugarBreaksOnlyWhenAnElementBreaks` + - 行为:`typeThatFitsStaysOnOneLineInAnOverlongLine` + - 行为:`overlongLineWithoutLongTypeIsUnchanged`(十个短参数、行尾长注释) + - 行为:`declarationParameterListBreaksWhenAParameterTypeBreaks` + - 行为:`genericParameterClauseDoesNotBreakForHavingTwoParameters` + - 行为:`continuationLinesIndentFromTheLineIndentation` + - 行为:`separatorLosesItsSpaceWhenBroken` + - 行为:`swiftUIBodyIsLaidOutByStructure`(本提案「提议方案」一节的例子) +4. **保持性与嵌套定义契约** —— 改动地图第 6、7 行 + - 行为:`formattingKeepsSemanticTypesAndIdentifiers` + - 行为:`removingInsertedBreaksRestoresTheOriginalText` + - 行为:`formattingIsIdempotent` + - 行为:`formattingCommutesWithIndentation` + - 行为:`annotationAndVisibilityRegionsReadBackUnchanged` + - 行为:`nestedDefinitionTakenOutOfFormattedParentEqualsFormattedChildPrint` +5. **SwiftSectionKit 接入** —— 改动地图第 8、9、10 行 + - 行为:`interfaceRequestFormatsLongTypesWhenAsked` + - 行为:`dumpRequestFormatsEachDeclarationWhenAsked` + - 行为:`requestsWithoutFormattingPrintAsBefore` + - 行为:`interfaceWrittenToFileIsFormattedToo` +6. **CLI 与 agent 插件** —— 改动地图第 11、12、13 行 + - 行为:`multilineTypesFlagMapsOntoTheRequest` + - 行为:`maximumLineWidthMapsOntoTheRequest` + - 行为:`maximumLineWidthWithoutMultilineTypesIsAUsageError` + - 行为:`nonPositiveMaximumLineWidthIsAUsageError` + - 行为:插件 skill 里出现的每个 flag 都存在于对应子命令的 `--help` +7. **文档** —— 改动地图第 14、15、16 行 + - 行为:文档索引、账本、术语表、模块清单与代码一致 + +验证:每步 `swift build` 通过、本步新测试通过;收尾跑 `swift test --skip IntegrationTests` 全量。打印器不改、默认关闭,渲染 A/B 不适用(照 `SystemFrameworkRenderingVerification.md` 的判据,它针对改动打印、索引或读取器的重构),但会对一份真实 SwiftUI interface 打开格式化,记录 `format` 的耗时与输出行数,作为性能与效果的留档。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 规则 1–6 与保持性承诺若在实现中出现代码看不出来的取舍(例如列号的算法、region 编码在切分 atom 时的处理),写一篇 `Documentations/Internal/MultilineTypeFormatting.md` 实现说明,登记到头部的「配套文档」。 +- **有没有引入新术语** —— 预计引入 multiline type formatting、long type(放不下的类型)两条,登记进 `Documentations/Glossary.md`。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-21 | Created as Draft | RuntimeViewer 里 SwiftUI 视图的 `typealias Body` 印成一行几千个字符,看不出泛型的层级,需要像展开括号一样按层拆行。 | +| 2026-11-21 | 规则选定 | 澄清提问后用户选定:一行放得下的类型不动,放不下的类型整个按 TypeAliasFormatter 的结构规则拆;适用于所有出现类型的位置;元组与函数类型的括号同样处理。纯按行宽和完全照 TypeAliasFormatter 两种都被否掉,理由见「替代方案考量」。 | +| 2026-11-21 | 接入方式 | 做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置项:两套打印器、互相调用的公开入口与嵌套定义契约都让「在打印器里拆」代价过高。 | +| 2026-11-21 | 宽度不计缩进 | 内容宽度减去行首缩进,使同一个声明在任何嵌套深度都拆得一样,`marksNestedDefinitions` 的契约不受影响。 | +| 2026-11-21 | Accepted | 用户批准,开始实现。功能分支 `feature/multiline-type-formatting`,从 `next` 切出。 | diff --git a/Documentations/README.md b/Documentations/README.md index 245f778e..292f1c7c 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -221,6 +221,7 @@ selects names using each access's offset and width. | [Evolutions/0100-fixture-suite-macro.md](Evolutions/0100-fixture-suite-macro.md) | **提案 0100(Implemented)**:attached 宏 `@FixtureSuite` 生成夹具测试套件的 `testedTypeName`、`registeredTestMethodNames` 与 `FixtureSuite` 遵循(170 个套件各省 3 行,没有 baseline 的 `CoroFunctionPointerTests` 保持手写),宏放新的 `SwiftSectionTestingMacros`,`SuiteBehaviorScanner` 改为也认宏的写法。 | | [Evolutions/0101-swift6-mode-and-upcoming-features.md](Evolutions/0101-swift6-mode-and-upcoming-features.md) | **提案 0101(Implemented)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.0 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [Evolutions/draft-shared-macho-testing-support.md](Evolutions/draft-shared-macho-testing-support.md) | **提案 draft(Accepted)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | +| [Evolutions/draft-multiline-type-formatting.md](Evolutions/draft-multiline-type-formatting.md) | **提案 draft(Accepted)**:长类型拆行——新增 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把打印好的 `SemanticString` 里放不下的类型按括号拆成多行:放得下的类型不动,放不下的类型照 TypeAliasFormatter 的结构规则拆(多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表只在里面有拆开的部分时才拆);行首缩进不计入宽度,嵌套定义契约不受影响;只加换行与缩进,semantic type、identifier 与 region 原样保留。`InterfaceRequest` / `DumpRequest` 加字段,`dump` / `interface` 加 `--multiline-types` 与 `--maximum-line-width`;默认关闭,打印器不改。 | | [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) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | From 4a6fe0e5f4ac510ab6ef6741f613fad9744400ee Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:37:07 +0800 Subject: [PATCH 045/175] feat(swift-declaration-rendering): add MultilineTypeFormatting with its line split and width gate The formatter takes printed source apart into lines, measures each line without its indentation, and copies every line that fits component for component. Breaking a long line lands with the bracket tree and the layout. Co-Authored-By: Claude --- Documentations/Evolutions/README.md | 2 +- .../draft-multiline-type-formatting.html | 2 +- .../draft-multiline-type-formatting.md | 4 +- Documentations/README.md | 2 +- .../MultilineTypeFormatting+Layout.swift | 14 ++ .../MultilineTypeFormatting+Lines.swift | 67 +++++++++ .../MultilineTypeFormatting.swift | 142 ++++++++++++++++++ .../MultilineTypeFormattingTests.swift | 111 ++++++++++++++ 8 files changed, 339 insertions(+), 5 deletions(-) create mode 100644 Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift create mode 100644 Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift create mode 100644 Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift create mode 100644 Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index fe90254d..3be122c2 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -117,4 +117,4 @@ | [0099](0099-tuist-workspace.md) | Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 | Implemented | | [0100](0100-fixture-suite-macro.md) | `@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成 | Implemented | | [0101](0101-swift6-mode-and-upcoming-features.md) | MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature:MachOKit 切 Swift 6,六个包开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`(跨仓库唯一提案) | Implemented | -| draft | [长类型拆行:放不下的类型按括号结构拆成多行](draft-multiline-type-formatting.md) | Accepted | +| draft | [长类型拆行:放不下的类型按括号结构拆成多行](draft-multiline-type-formatting.md) | In Progress | diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.html b/Documentations/Evolutions/draft-multiline-type-formatting.html index 52e92180..7476f171 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.html +++ b/Documentations/Evolutions/draft-multiline-type-formatting.html @@ -162,7 +162,7 @@

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-21
    项目类型
    库
    原文
    draft-multiline-type-formatting.md
    diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index f283e9a3..200e6741 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -1,6 +1,6 @@ # Draft - 长类型拆行:放不下的类型按括号结构拆成多行 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-21 - **最后更新**: 2026-11-21 @@ -330,7 +330,7 @@ extension MultilineTypeFormatting { ## 落地步骤 -1. **骨架:类型、行切分与宽度闸门** —— 改动地图第 1、2、5 行 +1. **骨架:类型、行切分与宽度闸门**(已完成) —— 改动地图第 1、2、5 行 - 行为:`emptySourceIsUnchanged` - 行为:`linesWithinWidthAreUnchangedAtomForAtom` - 行为:`contentWidthIgnoresLeadingIndentation` diff --git a/Documentations/README.md b/Documentations/README.md index 292f1c7c..1df036f2 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -221,7 +221,7 @@ selects names using each access's offset and width. | [Evolutions/0100-fixture-suite-macro.md](Evolutions/0100-fixture-suite-macro.md) | **提案 0100(Implemented)**:attached 宏 `@FixtureSuite` 生成夹具测试套件的 `testedTypeName`、`registeredTestMethodNames` 与 `FixtureSuite` 遵循(170 个套件各省 3 行,没有 baseline 的 `CoroFunctionPointerTests` 保持手写),宏放新的 `SwiftSectionTestingMacros`,`SuiteBehaviorScanner` 改为也认宏的写法。 | | [Evolutions/0101-swift6-mode-and-upcoming-features.md](Evolutions/0101-swift6-mode-and-upcoming-features.md) | **提案 0101(Implemented)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.0 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [Evolutions/draft-shared-macho-testing-support.md](Evolutions/draft-shared-macho-testing-support.md) | **提案 draft(Accepted)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | -| [Evolutions/draft-multiline-type-formatting.md](Evolutions/draft-multiline-type-formatting.md) | **提案 draft(Accepted)**:长类型拆行——新增 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把打印好的 `SemanticString` 里放不下的类型按括号拆成多行:放得下的类型不动,放不下的类型照 TypeAliasFormatter 的结构规则拆(多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表只在里面有拆开的部分时才拆);行首缩进不计入宽度,嵌套定义契约不受影响;只加换行与缩进,semantic type、identifier 与 region 原样保留。`InterfaceRequest` / `DumpRequest` 加字段,`dump` / `interface` 加 `--multiline-types` 与 `--maximum-line-width`;默认关闭,打印器不改。 | +| [Evolutions/draft-multiline-type-formatting.md](Evolutions/draft-multiline-type-formatting.md) | **提案 draft(In Progress)**:长类型拆行——新增 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把打印好的 `SemanticString` 里放不下的类型按括号拆成多行:放得下的类型不动,放不下的类型照 TypeAliasFormatter 的结构规则拆(多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表只在里面有拆开的部分时才拆);行首缩进不计入宽度,嵌套定义契约不受影响;只加换行与缩进,semantic type、identifier 与 region 原样保留。`InterfaceRequest` / `DumpRequest` 加字段,`dump` / `interface` 加 `--multiline-types` 与 `--maximum-line-width`;默认关闭,打印器不改。 | | [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) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift new file mode 100644 index 00000000..28cad310 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift @@ -0,0 +1,14 @@ +import Semantic + +extension MultilineTypeFormatting { + /// How one line that runs past the width is laid out over several lines. + /// + /// `nil` when the line has nothing to break, and so stays as printed. + struct LineLayout { + init?(line: SourceLine, sourceComponents: [AtomicComponent], maximumLineWidth: Int) { + return nil + } + + func emit(into builder: inout FormattedComponentBuilder) {} + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift new file mode 100644 index 00000000..ba11b840 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift @@ -0,0 +1,67 @@ +import Semantic + +extension MultilineTypeFormatting { + /// One line of the source: the fragments between two line breaks, and + /// the line break ending it. + struct SourceLine { + /// The line's text, without its line break. + let fragments: [SourceFragment] + + /// The `"\n"` ending the line; `nil` for the last line. + let terminator: SourceFragment? + + /// How many spaces the line starts with. + let leadingIndentation: Int + + /// The line's length in characters, less its leading indentation. + let contentWidth: Int + + init(fragments: [SourceFragment], terminator: SourceFragment?) { + self.fragments = fragments + self.terminator = terminator + var characterCount = 0 + var leadingSpaceCount = 0 + var isInLeadingIndentation = true + for fragment in fragments { + for character in fragment.text { + characterCount += 1 + if isInLeadingIndentation { + if character == " " { + leadingSpaceCount += 1 + } else { + isInLeadingIndentation = false + } + } + } + } + self.leadingIndentation = leadingSpaceCount + self.contentWidth = characterCount - leadingSpaceCount + } + + /// The lines of `components`, split at every `"\n"` — including one + /// inside a component, whose pieces each keep the component's index. + static func lines(in components: [AtomicComponent]) -> [SourceLine] { + var lines: [SourceLine] = [] + var currentFragments: [SourceFragment] = [] + for (componentIndex, component) in components.enumerated() { + let string = component.string + var segmentStart = string.startIndex + while let lineBreakIndex = string[segmentStart...].firstIndex(of: "\n") { + if segmentStart < lineBreakIndex { + currentFragments.append(SourceFragment(componentIndex: componentIndex, text: string[segmentStart ..< lineBreakIndex])) + } + let afterLineBreak = string.index(after: lineBreakIndex) + let terminator = SourceFragment(componentIndex: componentIndex, text: string[lineBreakIndex ..< afterLineBreak]) + lines.append(SourceLine(fragments: currentFragments, terminator: terminator)) + currentFragments = [] + segmentStart = afterLineBreak + } + if segmentStart < string.endIndex { + currentFragments.append(SourceFragment(componentIndex: componentIndex, text: string[segmentStart...])) + } + } + lines.append(SourceLine(fragments: currentFragments, terminator: nil)) + return lines + } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift new file mode 100644 index 00000000..1f4adb96 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift @@ -0,0 +1,142 @@ +import Semantic + +/// Lays the long types of printed Swift source out over several lines. +/// +/// A type that runs past `maximumLineWidth` is broken at its brackets: every +/// generic argument list with two or more arguments puts each argument on a +/// line of its own, and a single-argument generic list, a tuple, a parameter +/// list or collection sugar breaks only when one of its elements spans +/// several lines. A type that fits, and every line that fits, stays as +/// printed. Only a generic argument list running past the width starts a +/// break: a line that is long for any other reason — many short parameters, +/// a trailing comment — is left alone. +/// +/// ```swift +/// let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +/// let interface = formatting.format(try await printer.printTypeDefinition(definition)) +/// ``` +/// +/// Formatting only adds line breaks and indentation, and drops the space of +/// each `, ` between broken elements. Everything else — the text, every +/// component's semantic type and identifier, and so every visibility, +/// definition and annotation region — stays as it was. Format a finished +/// print, not a piece still being composed into a container: when a line +/// changes, the result keeps one element per component rather than the +/// source's element boundaries. When no line changes, the result is `source` +/// itself. +/// +/// The width does not count a line's own indentation, so a declaration +/// breaks the same way at any nesting depth: a nested definition taken out +/// of its formatted parent and stripped of its indentation reads exactly as +/// the definition printed on its own and then formatted. +public struct MultilineTypeFormatting: Hashable, Sendable { + /// The widest a line's content may be, in characters, not counting the + /// line's own indentation. + public var maximumLineWidth: Int + + /// - Precondition: `maximumLineWidth > 0`. + public init(maximumLineWidth: Int = 100) { + precondition(maximumLineWidth > 0, "MultilineTypeFormatting needs a positive maximum line width, got \(maximumLineWidth)") + self.maximumLineWidth = maximumLineWidth + } + + /// `source` with its long types laid out over several lines. + /// + /// - Precondition: `maximumLineWidth > 0`. + public func format(_ source: SemanticString) -> SemanticString { + precondition(maximumLineWidth > 0, "MultilineTypeFormatting needs a positive maximum line width, got \(maximumLineWidth)") + let sourceComponents = source.components + var builder = FormattedComponentBuilder(sourceComponents: sourceComponents) + var hasChangedLine = false + for line in SourceLine.lines(in: sourceComponents) { + if line.contentWidth > maximumLineWidth, let layout = LineLayout(line: line, sourceComponents: sourceComponents, maximumLineWidth: maximumLineWidth) { + layout.emit(into: &builder) + hasChangedLine = true + } else { + builder.append(contentsOf: line.fragments) + } + if let terminator = line.terminator { + builder.append(terminator) + } + } + guard hasChangedLine else { return source } + return SemanticString(components: builder.finish()) + } +} + +// MARK: - Fragments + +extension MultilineTypeFormatting { + /// A run of one source component's text. + /// + /// Fragments are how a line is taken apart without losing where its text + /// came from: every piece of output that is not an inserted line break or + /// indentation is a fragment, and adjacent fragments of one component + /// join back into that component on output. + struct SourceFragment { + let componentIndex: Int + let text: Substring + } + + /// Collects the output components, joining adjacent fragments of one + /// source component back into a single component, so an unchanged run + /// of the source comes out component for component as it went in. + struct FormattedComponentBuilder { + let sourceComponents: [AtomicComponent] + + private var components: [AtomicComponent] = [] + + private var pendingFragment: SourceFragment? + + init(sourceComponents: [AtomicComponent]) { + self.sourceComponents = sourceComponents + } + + mutating func append(_ fragment: SourceFragment) { + guard !fragment.text.isEmpty else { return } + if let pendingFragment, + pendingFragment.componentIndex == fragment.componentIndex, + pendingFragment.text.endIndex == fragment.text.startIndex { + let joinedText = pendingFragment.text.base[pendingFragment.text.startIndex ..< fragment.text.endIndex] + self.pendingFragment = SourceFragment(componentIndex: fragment.componentIndex, text: joinedText) + return + } + flushPendingFragment() + pendingFragment = fragment + } + + mutating func append(contentsOf fragments: [SourceFragment]) { + for fragment in fragments { + append(fragment) + } + } + + /// A line break and the indentation after it, both carrying + /// `identifier` so they sit in the same regions as the component + /// they were inserted next to. + mutating func appendLineBreak(indentation: Int, identifier: String?) { + flushPendingFragment() + components.append(AtomicComponent(string: "\n", type: .standard, identifier: identifier)) + if indentation > 0 { + components.append(AtomicComponent(string: String(repeating: " ", count: indentation), type: .standard, identifier: identifier)) + } + } + + mutating func finish() -> [AtomicComponent] { + flushPendingFragment() + return components + } + + private mutating func flushPendingFragment() { + guard let pendingFragment else { return } + let sourceComponent = sourceComponents[pendingFragment.componentIndex] + if pendingFragment.text.startIndex == pendingFragment.text.base.startIndex, + pendingFragment.text.endIndex == pendingFragment.text.base.endIndex { + components.append(sourceComponent) + } else { + components.append(AtomicComponent(string: String(pendingFragment.text), type: sourceComponent.type, identifier: sourceComponent.identifier)) + } + self.pendingFragment = nil + } + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift new file mode 100644 index 00000000..190a0139 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift @@ -0,0 +1,111 @@ +import Foundation +import Testing +import Semantic +@testable import SwiftDeclarationRendering + +/// Builds a `SemanticString` split into components the way both printers split +/// a declaration: each bracket, each `", "`, each run of spaces and each +/// `" -> "` its own `.standard` component, and each word one component of its +/// own — `.keyword` for a keyword, `.type(.other, .name)` for anything else. +/// A test then reads as the text it prints. +enum PrinterShapedSource { + static let keywords: Set = [ + "any", "case", "class", "enum", "extension", "func", "init", "inout", + "let", "some", "static", "struct", "typealias", "var", "where", + ] + + static func make(_ text: String) -> SemanticString { + var components: [AtomicComponent] = [] + var remainingText = Substring(text) + while let firstCharacter = remainingText.first { + if remainingText.hasPrefix(", ") { + components.append(AtomicComponent(string: ", ", type: .standard)) + remainingText = remainingText.dropFirst(2) + } else if remainingText.hasPrefix(" -> ") { + components.append(AtomicComponent(string: " -> ", type: .standard)) + remainingText = remainingText.dropFirst(4) + } else if firstCharacter == " " { + let spaces = remainingText.prefix(while: { $0 == " " }) + components.append(AtomicComponent(string: String(spaces), type: .standard)) + remainingText = remainingText.dropFirst(spaces.count) + } else if isWordCharacter(firstCharacter) { + let word = String(remainingText.prefix(while: isWordCharacter)) + components.append(AtomicComponent(string: word, type: keywords.contains(word) ? .keyword : .type(.other, .name))) + remainingText = remainingText.dropFirst(word.count) + } else { + components.append(AtomicComponent(string: String(firstCharacter), type: .standard)) + remainingText = remainingText.dropFirst() + } + } + return SemanticString(components: components) + } + + private static func isWordCharacter(_ character: Character) -> Bool { + character.isLetter || character.isNumber || character == "_" || character == "." || character == "$" + } +} + +@Suite +struct MultilineTypeFormattingTests { + // MARK: - Lines and the width gate + + @Test func emptySourceIsUnchanged() { + let formatted = MultilineTypeFormatting(maximumLineWidth: 10).format(SemanticString()) + #expect(formatted.components.isEmpty) + } + + @Test func linesWithinWidthAreUnchangedComponentForComponent() { + let source = PrinterShapedSource.make(""" + struct Holder { + var result: Swift.Result + typealias Body = SwiftUI.ModifiedContent + } + """) + let formatted = MultilineTypeFormatting(maximumLineWidth: 120).format(source) + #expect(formatted.components == source.components) + } + + @Test func contentWidthIgnoresLeadingIndentation() throws { + let lines = MultilineTypeFormatting.SourceLine.lines(in: PrinterShapedSource.make(" var count: Int").components) + let line = try #require(lines.only) + #expect(line.leadingIndentation == 8) + #expect(line.contentWidth == "var count: Int".count) + } + + @Test func linesSplitAtLineBreaksInsideAComponent() { + let components = [ + AtomicComponent(string: "first\n second", type: .comment, identifier: "identity"), + AtomicComponent(string: " tail", type: .standard), + ] + let lines = MultilineTypeFormatting.SourceLine.lines(in: components) + #expect(lines.count == 2) + #expect(lines[0].fragments.map(\.text) == ["first"]) + #expect(lines[0].terminator?.componentIndex == 0) + #expect(lines[1].fragments.map(\.text) == [" second", " tail"]) + #expect(lines[1].fragments.map(\.componentIndex) == [0, 1]) + #expect(lines[1].leadingIndentation == 4) + #expect(lines[1].contentWidth == "second tail".count) + } + + @Test func unchangedLinesSplitInsideAComponentComeBackAsThatComponent() { + let source = SemanticString(components: [ + AtomicComponent(string: "// first\n // second", type: .comment, identifier: "identity"), + AtomicComponent(string: "\n", type: .standard), + ]) + let formatted = MultilineTypeFormatting(maximumLineWidth: 4).format(source) + #expect(formatted.components == source.components) + } + + @Test func nonPositiveWidthIsAPreconditionFailure() async { + await #expect(processExitsWith: .failure) { + _ = MultilineTypeFormatting(maximumLineWidth: 0) + } + } +} + +extension Collection { + /// The collection's single element; `nil` when it has none or several. + var only: Element? { + count == 1 ? first : nil + } +} From 0e4efed6c27f682aab65f4a6de89cad27f477491 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:38:12 +0800 Subject: [PATCH 046/175] feat(swift-declaration-rendering): parse a long line into a bracket tree Brackets count only in .standard components, where both printers write punctuation; string literals, backtick names, line comments and the > of -> are text, and a line whose brackets do not pair up is not parsed. Co-Authored-By: Claude --- .../draft-multiline-type-formatting.md | 2 +- .../MultilineTypeFormatting+BracketTree.swift | 296 ++++++++++++++++++ .../MultilineTypeFormattingTests.swift | 159 ++++++++++ 3 files changed, 456 insertions(+), 1 deletion(-) create mode 100644 Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 200e6741..118b2da1 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -336,7 +336,7 @@ extension MultilineTypeFormatting { - 行为:`contentWidthIgnoresLeadingIndentation` - 行为:`atomsContainingLineBreaksAreSplitKeepingTypeAndIdentifier` - 行为:`nonPositiveWidthIsAPreconditionFailure`(exit test) -2. **括号树** —— 改动地图第 3、5 行 +2. **括号树**(已完成) —— 改动地图第 3、5 行 - 行为:`genericArgumentListsNestInsideParenthesesAndBrackets` - 行为:`angleBracketAfterDeclarationNameIsGenericParameterClause` - 行为:`arrowIsNotAClosingBracket` diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift new file mode 100644 index 00000000..1bddbfe1 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift @@ -0,0 +1,296 @@ +import Semantic + +extension MultilineTypeFormatting { + /// What a bracketed list is, which decides when it breaks. + enum BracketKind: Equatable { + /// `<…>` after a type: the arguments of a generic type, the only + /// list that breaks for having two or more elements. + case genericArguments + + /// `<…>` right after a declaration's name: the declaration's generic + /// parameters. + case genericParameters + + /// `(…)`: a tuple, a function type's parameters, a declaration's + /// parameters, an enum case's payload, an attribute's arguments. + case parentheses + + /// `[…]`: array and dictionary sugar. + case squareBrackets + + var closingCharacter: Character { + switch self { + case .genericArguments, + .genericParameters: + ">" + case .parentheses: + ")" + case .squareBrackets: + "]" + } + } + } + + /// One bracketed list of a line: its brackets, the commas between its + /// elements, and the elements themselves. + struct BracketList { + let kind: BracketKind + + let opening: SourceFragment + + let closing: SourceFragment + + /// The `,` between the elements, one fewer than `elements`. + let separators: [SourceFragment] + + var elements: [[BracketTreeNode]] + + /// Where the closing bracket stands on its line, counting from 1 at + /// the first character after the line's indentation. + let closingColumn: Int + + /// Whether the list puts each element on a line of its own. Decided + /// by `LineLayout`; the parser leaves it `false`. + var isBroken = false + } + + indirect enum BracketTreeNode { + case text(SourceFragment) + case list(BracketList) + } + + enum BracketTree { + /// `line` taken apart into text and bracketed lists; `nil` when its + /// brackets do not pair up, and the line is then left as printed. + /// + /// Brackets count only in `.standard` components, which is where + /// both printers write punctuation: a type name, a declaration name + /// (an operator's included), a keyword or a comment is text whatever + /// it contains. In a `.standard` component, a string literal, a + /// backtick-quoted name and everything after `//` are text, and the + /// `>` of `->` closes nothing. A line whose brackets still do not + /// pair up — the dump spells an operator `< infix` — is not guessed + /// at. + static func parse(_ line: SourceLine, sourceComponents: [AtomicComponent]) -> [BracketTreeNode]? { + var parser = BracketTreeParser(leadingIndentation: line.leadingIndentation) + for fragment in line.fragments { + let sourceComponent = sourceComponents[fragment.componentIndex] + if sourceComponent.type == .standard { + guard parser.scanPunctuation(in: fragment) else { return nil } + } else { + parser.appendText(fragment, type: sourceComponent.type) + } + } + return parser.finish() + } + } +} + +private struct BracketTreeParser { + typealias SourceFragment = MultilineTypeFormatting.SourceFragment + typealias BracketKind = MultilineTypeFormatting.BracketKind + typealias BracketList = MultilineTypeFormatting.BracketList + typealias BracketTreeNode = MultilineTypeFormatting.BracketTreeNode + + private enum Punctuation { + case opening(Character) + case closing(Character) + case separator + } + + /// A list whose closing bracket has not been read yet. + private struct OpenList { + let kind: BracketKind + let opening: SourceFragment + var separators: [SourceFragment] = [] + var elements: [[BracketTreeNode]] = [] + var currentElement: [BracketTreeNode] = [] + } + + let leadingIndentation: Int + + private var rootNodes: [BracketTreeNode] = [] + + private var openLists: [OpenList] = [] + + /// How many characters of the line have been read, its indentation + /// included. + private var readCharacterCount = 0 + + private var previousCharacter: Character? + + /// The semantic type of the last component that held more than + /// whitespace — what a `<` follows decides whether it opens generic + /// arguments or a declaration's generic parameters. + private var lastSignificantType: SemanticType? + + private var isInStringLiteral = false + + private var escapesNextCharacter = false + + private var isInBacktickName = false + + private var isInLineComment = false + + init(leadingIndentation: Int) { + self.leadingIndentation = leadingIndentation + } + + /// A component that is not punctuation: text whatever it contains. + mutating func appendText(_ fragment: SourceFragment, type: SemanticType) { + appendNode(.text(fragment)) + readCharacterCount += fragment.text.count + if fragment.text.contains(where: { !$0.isWhitespace }) { + lastSignificantType = type + } + previousCharacter = fragment.text.last ?? previousCharacter + } + + /// Reads a `.standard` component, splitting it at every bracket and + /// list separator. `false` when a closing bracket does not match the + /// list it would close. + mutating func scanPunctuation(in fragment: SourceFragment) -> Bool { + let text = fragment.text + var textRunStart = text.startIndex + var characterIndex = text.startIndex + while characterIndex < text.endIndex { + let character = text[characterIndex] + readCharacterCount += 1 + if let punctuation = punctuation(for: character) { + appendStandardText(SourceFragment(componentIndex: fragment.componentIndex, text: text[textRunStart ..< characterIndex])) + let nextIndex = text.index(after: characterIndex) + let punctuationFragment = SourceFragment(componentIndex: fragment.componentIndex, text: text[characterIndex ..< nextIndex]) + switch punctuation { + case .opening(let bracket): + open(bracket, at: punctuationFragment) + case .closing(let bracket): + guard close(bracket, at: punctuationFragment) else { return false } + case .separator: + separate(at: punctuationFragment) + } + textRunStart = nextIndex + } + previousCharacter = character + characterIndex = text.index(after: characterIndex) + } + appendStandardText(SourceFragment(componentIndex: fragment.componentIndex, text: text[textRunStart ..< text.endIndex])) + return true + } + + /// The tree read so far; `nil` while a list is still open. + func finish() -> [BracketTreeNode]? { + openLists.isEmpty ? rootNodes : nil + } + + // MARK: - Reading + + private mutating func punctuation(for character: Character) -> Punctuation? { + if isInLineComment { + return nil + } + if isInStringLiteral { + if escapesNextCharacter { + escapesNextCharacter = false + } else if character == "\\" { + escapesNextCharacter = true + } else if character == "\"" { + isInStringLiteral = false + } + return nil + } + if isInBacktickName { + if character == "`" { + isInBacktickName = false + } + return nil + } + switch character { + case "\"": + isInStringLiteral = true + return nil + case "`": + isInBacktickName = true + return nil + case "/": + if previousCharacter == "/" { + isInLineComment = true + } + return nil + case "<", "(", "[": + return .opening(character) + case ">": + return previousCharacter == "-" ? nil : .closing(character) + case ")", "]": + return .closing(character) + case ",": + return openLists.isEmpty ? nil : .separator + default: + return nil + } + } + + private mutating func appendStandardText(_ fragment: SourceFragment) { + guard !fragment.text.isEmpty else { return } + appendNode(.text(fragment)) + if fragment.text.contains(where: { !$0.isWhitespace }) { + lastSignificantType = .standard + } + } + + private mutating func open(_ bracket: Character, at fragment: SourceFragment) { + let kind: BracketKind + switch bracket { + case "<": + kind = lastSignificantType.map(Self.namesADeclaration) == true ? .genericParameters : .genericArguments + case "(": + kind = .parentheses + default: + kind = .squareBrackets + } + openLists.append(OpenList(kind: kind, opening: fragment)) + lastSignificantType = .standard + } + + private mutating func close(_ bracket: Character, at fragment: SourceFragment) -> Bool { + guard var list = openLists.popLast(), list.kind.closingCharacter == bracket else { return false } + list.elements.append(list.currentElement) + let closedList = BracketList( + kind: list.kind, + opening: list.opening, + closing: fragment, + separators: list.separators, + elements: list.elements, + closingColumn: readCharacterCount - leadingIndentation + ) + appendNode(.list(closedList)) + lastSignificantType = .standard + return true + } + + private mutating func separate(at fragment: SourceFragment) { + let innermostIndex = openLists.count - 1 + openLists[innermostIndex].elements.append(openLists[innermostIndex].currentElement) + openLists[innermostIndex].currentElement = [] + openLists[innermostIndex].separators.append(fragment) + lastSignificantType = .standard + } + + private mutating func appendNode(_ node: BracketTreeNode) { + if openLists.isEmpty { + rootNodes.append(node) + } else { + openLists[openLists.count - 1].currentElement.append(node) + } + } + + private static func namesADeclaration(_ type: SemanticType) -> Bool { + switch type { + case .type(_, .declaration), + .function(.declaration), + .member(.declaration): + true + default: + false + } + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift index 190a0139..93c6c017 100644 --- a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift @@ -101,6 +101,165 @@ struct MultilineTypeFormattingTests { _ = MultilineTypeFormatting(maximumLineWidth: 0) } } + + // MARK: - The bracket tree + + /// The bracket tree of the single line `source` holds, written back as + /// text: each list with its elements separated by `|` instead of their + /// commas, a declaration's generic parameters in `‹›`. `nil` when the + /// line does not parse. + private func bracketStructure(of source: SemanticString) throws -> String? { + let components = source.components + let line = try #require(MultilineTypeFormatting.SourceLine.lines(in: components).only) + return MultilineTypeFormatting.BracketTree.parse(line, sourceComponents: components).map(describe) + } + + private func describe(_ nodes: [MultilineTypeFormatting.BracketTreeNode]) -> String { + nodes.map { node in + switch node { + case .text(let fragment): + return String(fragment.text) + case .list(let list): + let brackets: (opening: String, closing: String) = switch list.kind { + case .genericArguments: ("<", ">") + case .genericParameters: ("‹", "›") + case .parentheses: ("(", ")") + case .squareBrackets: ("[", "]") + } + return brackets.opening + list.elements.map(describe).joined(separator: "|") + brackets.closing + } + }.joined() + } + + @Test func genericArgumentListsNestInsideParenthesesAndBrackets() throws { + let structure = try bracketStructure(of: PrinterShapedSource.make("var value: ([Pair], C) -> Box")) + #expect(structure == "var value: ([Pair]| C) -> Box") + } + + @Test func angleBracketAfterDeclarationNameIsGenericParameterClause() throws { + let function = SemanticString(components: [ + AtomicComponent(string: "func", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "make", type: .function(.declaration)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: ")", type: .standard), + ]) + #expect(try bracketStructure(of: function) == "func make‹A| B›()") + + let structure = SemanticString(components: [ + AtomicComponent(string: "struct", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "Holder", type: .type(.struct, .declaration)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "Element", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + ]) + #expect(try bracketStructure(of: structure) == "struct Holder‹Element›") + } + + @Test func arrowIsNotAClosingBracket() throws { + #expect(try bracketStructure(of: PrinterShapedSource.make("Box<(A) -> B>")) == "Box<(A) -> B>") + + let arrowAcrossComponents = SemanticString(components: [ + AtomicComponent(string: "Box", type: .type(.other, .name)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: ")", type: .standard), + AtomicComponent(string: " -", type: .standard), + AtomicComponent(string: "> ", type: .standard), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + ]) + #expect(try bracketStructure(of: arrowAcrossComponents) == "Box<() -> B>") + } + + @Test func bracketsInsideStringLiteralsAreText() throws { + let attribute = SemanticString(components: [ + AtomicComponent(string: "@available", type: .keyword), + AtomicComponent(string: "(*, deprecated, message: \"use Box or \\\"(\\\"\")", type: .standard), + ]) + #expect(try bracketStructure(of: attribute) == "@available(*| deprecated| message: \"use Box or \\\"(\\\"\")") + } + + @Test func bracketsInsideBackticksAreText() throws { + let name = SemanticString(components: [ + AtomicComponent(string: "Box<`<(`, B>", type: .standard), + ]) + #expect(try bracketStructure(of: name) == "Box<`<(`| B>") + } + + @Test func bracketsAfterLineCommentAreText() throws { + let line = SemanticString(components: [ + AtomicComponent(string: "var value: Box // Box // Box")) == nil) + #expect(try bracketStructure(of: PrinterShapedSource.make("Box ", type: .standard), + AtomicComponent(string: "Swift.Bool", type: .type(.struct, .name)), + ]) + #expect(try bracketStructure(of: line) == nil) + } + + @Test func closingColumnCountsFromTheEndOfIndentation() throws { + let components = PrinterShapedSource.make(" Box>").components + let line = try #require(MultilineTypeFormatting.SourceLine.lines(in: components).only) + let nodes = try #require(MultilineTypeFormatting.BracketTree.parse(line, sourceComponents: components)) + guard case .list(let outerList) = try #require(nodes.last) else { + Issue.record("the line should end in a list") + return + } + #expect(outerList.closingColumn == "Box>".count) + guard case .list(let innerList) = try #require(outerList.elements.only?.last) else { + Issue.record("the outer list should hold a list") + return + } + #expect(innerList.closingColumn == "Box".count) + } } extension Collection { From 4878cc91b6efe4558677a8f48c879e61711fe653 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:39:51 +0800 Subject: [PATCH 047/175] feat(swift-declaration-rendering): break long types at their brackets A generic argument list that is the outermost list of a type and closes past the width makes that type long. Inside a long type every generic argument list with two or more arguments breaks; any list breaks when one of its elements spans several lines. Broken elements indent four spaces a level from the line's own indentation. Co-Authored-By: Claude --- .../draft-multiline-type-formatting.md | 2 +- .../MultilineTypeFormatting+Layout.swift | 156 +++++++++++++- .../MultilineTypeFormattingTests.swift | 194 ++++++++++++++++++ 3 files changed, 348 insertions(+), 4 deletions(-) diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 118b2da1..167b3ab3 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -346,7 +346,7 @@ extension MultilineTypeFormatting { - 行为:`bracketsInNonStandardAtomsAreText`(类型名、声明名、注释 atom) - 行为:`unbalancedLineIsLeftUnchanged` - 行为:`operatorDeclarationFromDumpIsLeftUnchanged`(`static func < infix(…)`) -3. **排版与生成** —— 改动地图第 4、5 行 +3. **排版与生成**(已完成) —— 改动地图第 4、5 行 - 行为:`multiArgumentGenericBreaksOneArgumentPerLine` - 行为:`singleArgumentGenericStaysInlineUnlessItsArgumentBreaks` - 行为:`tupleBreaksOnlyWhenAnElementBreaks` diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift index 28cad310..2f04dd2f 100644 --- a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift @@ -3,12 +3,162 @@ import Semantic extension MultilineTypeFormatting { /// How one line that runs past the width is laid out over several lines. /// - /// `nil` when the line has nothing to break, and so stays as printed. + /// A generic argument list inside no other generic argument list is the + /// outermost list of a type; when its closing `>` lies past the width, + /// that type is long. Inside a long type, every generic argument list + /// with two or more elements breaks. Any list — a long type's or not — + /// breaks when one of its elements spans several lines. Nothing else + /// breaks. + /// + /// `nil` when the line does not parse or has nothing to break, and so + /// stays as printed. struct LineLayout { + /// How many spaces one level of a broken list indents by. + static let indentationWidth = 4 + + private let nodes: [BracketTreeNode] + + private let leadingIndentation: Int + + private let sourceComponents: [AtomicComponent] + init?(line: SourceLine, sourceComponents: [AtomicComponent], maximumLineWidth: Int) { - return nil + guard let parsedNodes = BracketTree.parse(line, sourceComponents: sourceComponents) else { return nil } + let decision = Self.decidingBreaks( + in: parsedNodes, + maximumLineWidth: maximumLineWidth, + isInsideGenericArguments: false, + isInsideLongType: false + ) + guard decision.containsBrokenList else { return nil } + self.nodes = decision.nodes + self.leadingIndentation = line.leadingIndentation + self.sourceComponents = sourceComponents + } + + func emit(into builder: inout FormattedComponentBuilder) { + emit(nodes, depth: 0, into: &builder) + } + + // MARK: - Deciding + + /// `nodes` with every list's `isBroken` decided, bottom-up. + private static func decidingBreaks( + in nodes: [BracketTreeNode], + maximumLineWidth: Int, + isInsideGenericArguments: Bool, + isInsideLongType: Bool + ) -> (nodes: [BracketTreeNode], containsBrokenList: Bool) { + var decidedNodes: [BracketTreeNode] = [] + decidedNodes.reserveCapacity(nodes.count) + var containsBrokenList = false + for node in nodes { + guard case .list(var list) = node else { + decidedNodes.append(node) + continue + } + let isLongTypeRoot = list.kind == .genericArguments + && !isInsideGenericArguments + && list.closingColumn > maximumLineWidth + let isInLongType = isInsideLongType || isLongTypeRoot + let elementsAreInsideGenericArguments = isInsideGenericArguments || list.kind == .genericArguments + var hasMultilineElement = false + var decidedElements: [[BracketTreeNode]] = [] + decidedElements.reserveCapacity(list.elements.count) + for element in list.elements { + let decision = decidingBreaks( + in: element, + maximumLineWidth: maximumLineWidth, + isInsideGenericArguments: elementsAreInsideGenericArguments, + isInsideLongType: isInLongType + ) + hasMultilineElement = hasMultilineElement || decision.containsBrokenList + decidedElements.append(decision.nodes) + } + list.elements = decidedElements + let hasElements = list.elements.contains { !$0.isEmpty } + let breaksForItsArguments = isInLongType && list.kind == .genericArguments && list.elements.count >= 2 + list.isBroken = hasElements && (hasMultilineElement || breaksForItsArguments) + containsBrokenList = containsBrokenList || list.isBroken + decidedNodes.append(.list(list)) + } + return (decidedNodes, containsBrokenList) } - func emit(into builder: inout FormattedComponentBuilder) {} + // MARK: - Emitting + + private func emit(_ nodes: [BracketTreeNode], depth: Int, into builder: inout FormattedComponentBuilder) { + for node in nodes { + switch node { + case .text(let fragment): + builder.append(fragment) + case .list(let list): + emit(list, depth: depth, into: &builder) + } + } + } + + /// A list as printed, or — broken — its opening bracket closing its + /// line, each element on a line of its own one level deeper, and its + /// closing bracket on a line of its own back at `depth`. + private func emit(_ list: BracketList, depth: Int, into builder: inout FormattedComponentBuilder) { + builder.append(list.opening) + guard list.isBroken else { + for (elementIndex, element) in list.elements.enumerated() { + emit(element, depth: depth, into: &builder) + if elementIndex < list.separators.count { + builder.append(list.separators[elementIndex]) + } + } + builder.append(list.closing) + return + } + let elementDepth = depth + 1 + for (elementIndex, element) in list.elements.enumerated() { + let precedingPunctuation = elementIndex == 0 ? list.opening : list.separators[elementIndex - 1] + builder.appendLineBreak( + indentation: leadingIndentation + Self.indentationWidth * elementDepth, + identifier: identifier(of: precedingPunctuation) + ) + emit(Self.trimmingWhitespace(of: element), depth: elementDepth, into: &builder) + if elementIndex < list.separators.count { + builder.append(list.separators[elementIndex]) + } + } + builder.appendLineBreak( + indentation: leadingIndentation + Self.indentationWidth * depth, + identifier: identifier(of: list.closing) + ) + builder.append(list.closing) + } + + private func identifier(of fragment: SourceFragment) -> String? { + sourceComponents[fragment.componentIndex].identifier + } + + /// `element` without the whitespace it starts and ends with — the + /// space after a `, ` above all, which a broken list replaces with a + /// line break. + private static func trimmingWhitespace(of element: [BracketTreeNode]) -> [BracketTreeNode] { + var nodes = element + while case .text(let fragment) = nodes.first { + let trimmedText = fragment.text.drop(while: \.isWhitespace) + if trimmedText.isEmpty { + nodes.removeFirst() + continue + } + nodes[0] = .text(SourceFragment(componentIndex: fragment.componentIndex, text: trimmedText)) + break + } + while case .text(let fragment) = nodes.last { + guard let lastVisibleIndex = fragment.text.lastIndex(where: { !$0.isWhitespace }) else { + nodes.removeLast() + continue + } + nodes[nodes.count - 1] = .text(SourceFragment(componentIndex: fragment.componentIndex, text: fragment.text[...lastVisibleIndex])) + break + } + return nodes + } } } diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift index 93c6c017..0b4ff5be 100644 --- a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift @@ -260,6 +260,200 @@ struct MultilineTypeFormattingTests { } #expect(innerList.closingColumn == "Box".count) } + + // MARK: - Layout + + private func formatted(_ text: String, maximumLineWidth: Int) -> String { + MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(PrinterShapedSource.make(text)).string + } + + private func isLeftUnchanged(_ source: SemanticString, maximumLineWidth: Int) -> Bool { + MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(source).components == source.components + } + + @Test func multiArgumentGenericBreaksOneArgumentPerLine() { + #expect(formatted("typealias Body = Pair", maximumLineWidth: 40) == """ + typealias Body = Pair< + Swift.Int, + Swift.String + > + """) + } + + @Test func singleArgumentGenericStaysInlineUnlessItsArgumentBreaks() { + #expect(formatted("var value: Box>", maximumLineWidth: 40) == """ + var value: Box< + Pair< + Swift.Int, + Swift.String + > + > + """) + #expect(isLeftUnchanged(PrinterShapedSource.make("var value: Box>>"), maximumLineWidth: 10)) + } + + @Test func tupleBreaksOnlyWhenAnElementBreaks() { + #expect(formatted("var pair: (Swift.Int, Swift.String, Pair)", maximumLineWidth: 40) == """ + var pair: ( + Swift.Int, + Swift.String, + Pair< + A, + B + > + ) + """) + #expect(isLeftUnchanged(PrinterShapedSource.make("var tuple: (Swift.Int, Swift.String, Swift.Double, Swift.Float)"), maximumLineWidth: 20)) + } + + @Test func functionTypeParametersBreakOnlyWhenAParameterBreaks() { + #expect(formatted("var handler: (Pair) -> Swift.Void", maximumLineWidth: 40) == """ + var handler: ( + Pair< + Swift.Int, + Swift.String + > + ) -> Swift.Void + """) + } + + @Test func collectionSugarBreaksOnlyWhenAnElementBreaks() { + #expect(formatted("var table: [Swift.String : Pair]", maximumLineWidth: 40) == """ + var table: [ + Swift.String : Pair< + Swift.Int, + Swift.String + > + ] + """) + } + + @Test func typeThatFitsStaysOnOneLineInAnOverlongLine() { + let line = "func update(model: Swift.Result, content: Pair) -> Swift.Bool" + #expect(formatted(line, maximumLineWidth: 60) == """ + func update( + model: Swift.Result, + content: Pair< + Swift.Int, + Swift.String + > + ) -> Swift.Bool + """) + } + + @Test func overlongLineWithoutLongTypeIsUnchanged() { + let parameters = "func update(first: Swift.Int, second: Swift.Int, third: Swift.Int) // and a trailing comment" + #expect(isLeftUnchanged(PrinterShapedSource.make(parameters), maximumLineWidth: 30)) + let comment = "var value: Pair // a trailing comment long enough to run past the width" + #expect(isLeftUnchanged(PrinterShapedSource.make(comment), maximumLineWidth: 30)) + } + + @Test func genericParameterClauseDoesNotBreakForHavingTwoParameters() { + let function = SemanticString(components: [ + AtomicComponent(string: "func", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "make", type: .function(.declaration)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: "value", type: .argument), + AtomicComponent(string: ": ", type: .standard), + AtomicComponent(string: "Pair", type: .type(.struct, .name)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "Swift.Int", type: .type(.struct, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "Swift.String", type: .type(.struct, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: ")", type: .standard), + ]) + #expect(MultilineTypeFormatting(maximumLineWidth: 12).format(function).string == """ + func make( + value: Pair< + Swift.Int, + Swift.String + > + ) + """) + } + + @Test func emptyParenthesesNeverBreak() { + #expect(formatted("func make() -> Pair", maximumLineWidth: 10) == """ + func make() -> Pair< + A, + B + > + """) + } + + @Test func continuationLinesIndentFromTheLineIndentation() { + #expect(formatted(" var value: Pair", maximumLineWidth: 10) == """ + var value: Pair< + A, + B + > + """) + } + + @Test func separatorLosesItsSpaceWhenBroken() { + let formattedSource = MultilineTypeFormatting(maximumLineWidth: 10).format(PrinterShapedSource.make("var value: Pair")) + #expect(formattedSource.components.contains(AtomicComponent(string: ",", type: .standard))) + #expect(!formattedSource.components.contains { $0.string.hasSuffix(" ") && $0.string.contains(",") }) + } + + @Test func operatorDeclarationFromDumpIsLeftUnchanged() { + let line = SemanticString(components: [ + AtomicComponent(string: "static func", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "< infix", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: "Pair", type: .type(.struct, .name)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "Swift.Int", type: .type(.struct, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "Swift.Int", type: .type(.struct, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: ")", type: .standard), + AtomicComponent(string: " -> ", type: .standard), + AtomicComponent(string: "Swift.Bool", type: .type(.struct, .name)), + ]) + #expect(isLeftUnchanged(line, maximumLineWidth: 10)) + } + + @Test func swiftUIBodyIsLaidOutByStructure() { + let source = """ + extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent, SwiftUI.NavigationSplitView, SettingsApp.SettingsSecondaryColumn>>>, SwiftUI._EnvironmentKeyWritingModifier>, SwiftUI.OnTestViewModifier> + } + """ + #expect(formatted(source, maximumLineWidth: 100) == """ + extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent< + SwiftUI.ModifiedContent< + SwiftUI.SceneBridgeReader< + SwiftUI.SubscriptionView< + Combine.PassthroughSubject< + Any, + Swift.Never + >, + SwiftUI.NavigationSplitView< + SwiftUI.ModifiedContent< + SettingsApp.SettingsSidebarList, + SwiftUI.ToolbarRemovingModifier + >, + SettingsApp.SettingsSecondaryColumn + > + > + >, + SwiftUI._EnvironmentKeyWritingModifier + >, + SwiftUI.OnTestViewModifier + > + } + """) + } } extension Collection { From e06d18095323fca2883498afdcf6d202343195bd Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:46:58 +0800 Subject: [PATCH 048/175] test: pin what multiline type formatting keeps Types and identifiers of every visible character, the identifiers of the inserted line breaks, the text once the breaks are taken out, idempotence, indentation, the visibility and annotation regions, and the nested definition contract: a variant of its suite formats both prints first. Co-Authored-By: Claude --- .../draft-multiline-type-formatting.md | 15 +- ...ilineTypeFormattingPreservationTests.swift | 159 ++++++++++++++++++ .../NestedDefinitionRegionContractTests.swift | 43 ++++- 3 files changed, 210 insertions(+), 7 deletions(-) create mode 100644 Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 167b3ab3..0ac12068 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -118,7 +118,7 @@ func update( | `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift` · `MultilineTypeFormatting.Layout`(internal) | 新增 | 判定放不下的类型、自下而上决定哪些列表拆开、按规则 6 生成 atom(插入的换行与缩进沿用相邻括号或逗号 atom 的 identifier) | 规则 3–6 | 3 | | `Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift` | 新增 | 行切分、解析、排版的单元测试,输入用手工拼的 `SemanticString`,形状与两套打印器的输出一致 | 每步的行为清单 | 1–3 | | `Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift` | 新增 | 保持性测试:semantic type 与 identifier 不变、去掉插入的换行能还原原文、幂等、与缩进可交换、region 读回不变 | 规则 6 的「只加换行和缩进」承诺 | 4 | -| `Tests/SwiftInterfaceTests/MultilineTypeFormattingNestedDefinitionTests.swift` | 新增 | 打开 `marksNestedDefinitions` 打印 SymbolTestsCore 里带嵌套类型的定义,格式化父定义后取出的子定义等于子定义单独打印后格式化 | 嵌套定义契约在格式化后仍成立 | 4 | +| `Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift` | 修改 | 新变体 `everyOptionFormattedAsMultilineTypes`:父定义的打印与子定义自己的打印都按 30 列格式化后再比较;另加 `formattedVariantBreaksTheFixtureTypes`,确认 fixture 在这个宽度下真的有类型被拆开 | 嵌套定义契约在格式化后仍成立;复用这个套件的整套比较(文字、span、identifier、三种 region) | 4 | | `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | 新字段 `multilineTypeFormatting`(init 参数默认 `nil`),`run` 里 `printRoot()` 之后、写文件或交给 output 之前调用 | interface 的唯一出口 | 5 | | `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift` · `DumpRequest`、`DumpSession` | 修改 | 新字段 `multilineTypeFormatting`;`DumpSession.dump` 拿到 `dumpedDeclaration` 后调用 | dump 的唯一出口,一次一个顶层声明 | 5 | | `Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift` | 新增 | 两个请求打开与关闭字段时的输出 | 接入正确、关闭时不变 | 5 | @@ -277,7 +277,8 @@ extension MultilineTypeFormatting { - 每个元素去掉首尾空白后输出; - 元素之间的分隔:原来的 `, `(或 `,`)atom 换成只含 `,` 的 atom(type 与 identifier 不变),后面插入 `\n` 与缩进; - 闭括号前插入 `\n` 与 `L + 4(k − 1)` 个空格; - - 插入的 atom 都是 `.standard`,`identifier` 取它前面那个括号或逗号 atom 的 `identifier`。括号若和别的字符在同一个 atom 里,就在括号处切开,各段保留原 type 与 identifier。 + - 插入的 atom 都是 `.standard`。开括号与逗号之后的换行和缩进取那个开括号或逗号 atom 的 `identifier`;闭括号之前的换行和缩进取闭括号 atom 的 `identifier`——不取它前面那个元素的,因为元素的最后一个 atom 往往是带着类型引用 identifier 的类型名,换行不该算进那个引用。括号若和别的字符在同一个 atom 里,就在括号处切开,各段保留原 type 与 identifier。 + - 有任何一行被改时,结果按 atom 一个元素重建(`SemanticString(components:)`),不保留输入的元素边界——公开 API 读不到元素边界;所以 `format` 用在打印完成的结果上,不用在还要拼进容器的半成品上。没有任何一行被改时直接返回输入本身。 - 一个列表为空(`()`)时从不拆。 ### 保持性 @@ -359,13 +360,16 @@ extension MultilineTypeFormatting { - 行为:`continuationLinesIndentFromTheLineIndentation` - 行为:`separatorLosesItsSpaceWhenBroken` - 行为:`swiftUIBodyIsLaidOutByStructure`(本提案「提议方案」一节的例子) -4. **保持性与嵌套定义契约** —— 改动地图第 6、7 行 +4. **保持性与嵌套定义契约**(已完成) —— 改动地图第 6、7 行 - 行为:`formattingKeepsSemanticTypesAndIdentifiers` + - 行为:`insertedLineBreaksCarryTheIdentifierOfTheirBracketOrComma` + - 行为:`unchangedLinesAroundAChangedLineKeepTheirComponents` - 行为:`removingInsertedBreaksRestoresTheOriginalText` - 行为:`formattingIsIdempotent` - 行为:`formattingCommutesWithIndentation` - 行为:`annotationAndVisibilityRegionsReadBackUnchanged` - - 行为:`nestedDefinitionTakenOutOfFormattedParentEqualsFormattedChildPrint` + - 行为:`NestedDefinitionRegionContractTests` 的 `everyOptionFormattedAsMultilineTypes` 变体(进程内与文件两种读取器) + - 行为:`formattedVariantBreaksTheFixtureTypes` 5. **SwiftSectionKit 接入** —— 改动地图第 8、9、10 行 - 行为:`interfaceRequestFormatsLongTypesWhenAsked` - 行为:`dumpRequestFormatsEachDeclarationWhenAsked` @@ -396,3 +400,6 @@ extension MultilineTypeFormatting { | 2026-11-21 | 接入方式 | 做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置项:两套打印器、互相调用的公开入口与嵌套定义契约都让「在打印器里拆」代价过高。 | | 2026-11-21 | 宽度不计缩进 | 内容宽度减去行首缩进,使同一个声明在任何嵌套深度都拆得一样,`marksNestedDefinitions` 的契约不受影响。 | | 2026-11-21 | Accepted | 用户批准,开始实现。功能分支 `feature/multiline-type-formatting`,从 `next` 切出。 | +| 2026-11-21 | 闭括号前的换行取闭括号的 identifier | 详细设计原写「取前一个括号或逗号的」;闭括号前面紧挨的是元素末尾,常是带类型引用 identifier 的类型名,换行不该算进那个引用的 span,所以改取闭括号自己的。 | +| 2026-11-21 | 不保留元素边界 | `SemanticString` 的元素边界没有公开读取的接口,有一行被改时结果按 atom 一个元素重建;文档注释写明 `format` 用于打印完成的结果。没有行被改时返回输入本身,边界原样。 | +| 2026-11-21 | 嵌套定义契约测试并入现有套件 | 改动地图原计划新建 `MultilineTypeFormattingNestedDefinitionTests.swift`;改为给 `NestedDefinitionRegionContractTests` 加一个格式化变体,直接复用它对文字、span、identifier 与三种 region 的整套比较。宽度取 30 列:fixture 的长泛型类型不多(主要是 `GenericFieldLayout` 各嵌套类型的字段),40 列下只有 4 个根类型有改动,30 列下新增约一百行。 | diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift new file mode 100644 index 00000000..a3652761 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift @@ -0,0 +1,159 @@ +import Foundation +import Testing +import Semantic +@testable import SwiftDeclarationRendering + +/// What formatting promises to keep: it adds line breaks and indentation and +/// drops the space of a broken `, `, and nothing else changes — not the +/// text, not a component's semantic type or identifier, not the regions a +/// host reads back out of the identifiers. +@Suite +struct MultilineTypeFormattingPreservationTests { + private static let swiftUIBody = """ + extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent, SwiftUI.NavigationSplitView, SettingsApp.SettingsSecondaryColumn>>>, SwiftUI._EnvironmentKeyWritingModifier>, SwiftUI.OnTestViewModifier> + func update(model: Swift.Result, content: Pair])>) -> Swift.Bool + var handler: (Pair) -> Swift.Void + } + """ + + private static let sources: [String] = [ + swiftUIBody, + "var value: Box>", + " var pair: (Swift.Int, Swift.String, Pair)", + "func make() -> Pair", + ] + + private static let widths = [10, 30, 60, 100] + + /// `source` with every component carrying an identifier of its own, the + /// way a printer stamps type references and regions. + private static func identified(_ source: SemanticString) -> SemanticString { + SemanticString(components: source.components.enumerated().map { componentIndex, component in + AtomicComponent(string: component.string, type: component.type, identifier: "component\(componentIndex)") + }) + } + + /// Every character of `string` that is not whitespace, with the semantic + /// type and identifier of the component it lies in. + private static func visibleCharacters(of string: SemanticString) -> [(character: Character, type: SemanticType, identifier: String?)] { + string.components.flatMap { component in + component.string.filter { !$0.isWhitespace }.map { (character: $0, type: component.type, identifier: component.identifier) } + } + } + + @Test(arguments: sources, widths) + func formattingKeepsSemanticTypesAndIdentifiers(source: String, maximumLineWidth: Int) { + let identifiedSource = Self.identified(PrinterShapedSource.make(source)) + let formatted = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(identifiedSource) + let sourceCharacters = Self.visibleCharacters(of: identifiedSource) + let formattedCharacters = Self.visibleCharacters(of: formatted) + #expect(sourceCharacters.count == formattedCharacters.count) + for (sourceCharacter, formattedCharacter) in zip(sourceCharacters, formattedCharacters) { + #expect(sourceCharacter.character == formattedCharacter.character) + #expect(sourceCharacter.type == formattedCharacter.type) + #expect(sourceCharacter.identifier == formattedCharacter.identifier) + } + } + + @Test func insertedLineBreaksCarryTheIdentifierOfTheirBracketOrComma() { + let source = SemanticString(components: [ + AtomicComponent(string: "Pair", type: .type(.struct, .name), identifier: "pair"), + AtomicComponent(string: "<", type: .standard, identifier: "opening"), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ", ", type: .standard, identifier: "separator"), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard, identifier: "closing"), + ]) + let formatted = MultilineTypeFormatting(maximumLineWidth: 5).format(source) + #expect(formatted.components == [ + AtomicComponent(string: "Pair", type: .type(.struct, .name), identifier: "pair"), + AtomicComponent(string: "<", type: .standard, identifier: "opening"), + AtomicComponent(string: "\n", type: .standard, identifier: "opening"), + AtomicComponent(string: " ", type: .standard, identifier: "opening"), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ",", type: .standard, identifier: "separator"), + AtomicComponent(string: "\n", type: .standard, identifier: "separator"), + AtomicComponent(string: " ", type: .standard, identifier: "separator"), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: "\n", type: .standard, identifier: "closing"), + AtomicComponent(string: ">", type: .standard, identifier: "closing"), + ]) + } + + @Test func unchangedLinesAroundAChangedLineKeepTheirComponents() { + let comment = AtomicComponent(string: "// first\n// second\n", type: .comment, identifier: "comment") + var source = SemanticString(components: [comment]) + source.append(PrinterShapedSource.make("var value: Pair\n")) + source.append(AtomicComponent(string: "// third", type: .comment, identifier: "trailing")) + let formatted = MultilineTypeFormatting(maximumLineWidth: 10).format(source) + #expect(formatted.components.first == comment) + #expect(formatted.components.last == AtomicComponent(string: "// third", type: .comment, identifier: "trailing")) + #expect(formatted.string == """ + // first + // second + var value: Pair< + A, + B + > + // third + """) + } + + @Test(arguments: sources, widths) + func removingInsertedBreaksRestoresTheOriginalText(source: String, maximumLineWidth: Int) throws { + let formatted = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(PrinterShapedSource.make(source)).string + var restored = formatted + for (pattern, template) in [(#"([<(\[])\n +"#, "$1"), (#",\n +"#, ", "), (#"\n +([>)\]])"#, "$1"), (#"\n([>)\]])"#, "$1")] { + let expression = try NSRegularExpression(pattern: pattern) + restored = expression.stringByReplacingMatches(in: restored, range: NSRange(restored.startIndex..., in: restored), withTemplate: template) + } + #expect(restored == source) + } + + @Test(arguments: sources, widths) + func formattingIsIdempotent(source: String, maximumLineWidth: Int) { + let formatting = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth) + let formattedOnce = formatting.format(PrinterShapedSource.make(source)) + let formattedTwice = formatting.format(formattedOnce) + #expect(formattedTwice.components == formattedOnce.components) + } + + /// Indenting every non-empty line by four spaces. + private static func indented(_ text: String) -> String { + text.split(separator: "\n", omittingEmptySubsequences: false) + .map { $0.isEmpty ? String($0) : " " + $0 } + .joined(separator: "\n") + } + + @Test(arguments: sources, widths) + func formattingCommutesWithIndentation(source: String, maximumLineWidth: Int) { + let formatting = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth) + let formattedThenIndented = Self.indented(formatting.format(PrinterShapedSource.make(source)).string) + let indentedThenFormatted = formatting.format(PrinterShapedSource.make(Self.indented(source))).string + #expect(indentedThenFormatted == formattedThenIndented) + } + + @Test func annotationAndVisibilityRegionsReadBackUnchanged() throws { + let typeAlias = " typealias Body = Pair, Pair>" + var source = PrinterShapedSource.make("struct Holder {\n") + source.append(VisibilityRegion(.enabled("printsTypeAliases"), content: SemanticString(AnnotationRegion(AnnotationRegion.Kind("note"), content: PrinterShapedSource.make(typeAlias))))) + source.append(PrinterShapedSource.make("\n}")) + let formatting = MultilineTypeFormatting(maximumLineWidth: 30) + let formattedTypeAlias = formatting.format(PrinterShapedSource.make(typeAlias)).string + + let formatted = formatting.format(source).frozen() + let visibility = formatted.separatingVisibilityRegions() + #expect(visibility.regions.regions.count == 1) + let hidden = visibility.regions.projection(of: visibility.text, where: { _ in false }).text.string + #expect(hidden == "struct Holder {\n\n}") + let shown = visibility.regions.projection(of: visibility.text, where: { _ in true }).text + #expect(shown.string == "struct Holder {\n" + formattedTypeAlias + "\n}") + + let annotations = shown.separatingAnnotationRegions() + let region = try #require(annotations.annotations.regions.only) + #expect(region.kind == AnnotationRegion.Kind("note")) + let regionBytes = Array(annotations.text.string.utf8)[Int(region.utf8Offset) ..< Int(region.utf8Offset + region.utf8Length)] + #expect(String(decoding: regionBytes, as: UTF8.self) == formattedTypeAlias.trimmingCharacters(in: .whitespaces)) + } +} diff --git a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift index ddc4ea8a..153040e1 100644 --- a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift +++ b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift @@ -53,6 +53,13 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, /// proposal `comment-structure`): the marks of a nested definition's /// comments must not depend on where it prints. case everyOptionMarkingCommentStructure + /// The marked print with every option, its long types laid out over + /// several lines (evolution proposal `multiline-type-formatting`) — + /// the parent's print and the definition's own each formatted. The + /// width is narrow so that the fixture's long generic types break; it + /// does not count indentation, so a definition must break the same + /// way at every depth. + case everyOptionFormattedAsMultilineTypes var description: String { switch self { @@ -61,9 +68,20 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, case .everyOptionWithTransformers: "every option with transformers" case .privateDeclarationSourceFiles: "private declaration source files" case .everyOptionMarkingCommentStructure: "every option marking comment structure" + case .everyOptionFormattedAsMultilineTypes: "every option formatted as multiline types" } } + /// How a print of this variant is formatted before it is compared; + /// `nil` leaves it as printed. + var multilineTypeFormatting: MultilineTypeFormatting? { + self == .everyOptionFormattedAsMultilineTypes ? MultilineTypeFormatting(maximumLineWidth: 30) : nil + } + + func finished(_ printed: SemanticString) -> SemanticString { + multilineTypeFormatting?.format(printed) ?? printed + } + var configuration: SwiftDeclarationPrintConfiguration { var configuration = SwiftDeclarationPrintConfiguration() configuration.marksNestedDefinitions = true @@ -88,7 +106,8 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, transformers.swiftTypeLayout.isEnabled = true transformers.swiftEnumLayout.isEnabled = true configuration.applyTransformers(transformers) - case .everyOptionMarkingCommentStructure: + case .everyOptionMarkingCommentStructure, + .everyOptionFormattedAsMultilineTypes: configuration.printFieldOffset = true configuration.printExpandedFieldOffsets = true configuration.printMemberAddress = true @@ -252,7 +271,7 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, var exceptionRegionCount = 0 var mismatches: [String] = [] for parent in parents { - let printed = try await parent.print(printer).frozen() + let printed = try await variant.finished(parent.print(printer)).frozen() let regions = printed.separatingDefinitionRegions().definitions.regions if regions.count != parent.nestedDefinitionCount { mismatches.append("\(parent.label): \(regions.count) regions for \(parent.nestedDefinitionCount) nested definitions") @@ -264,7 +283,7 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, mismatches.append("\(label): no definition has this identity") continue } - let ownPrint = try await ownPrinting(printer).frozen() + let ownPrint = try await variant.finished(ownPrinting(printer)).frozen() let regionContent = printed.content(ofDefinitionRegion: region) guard let takenOut = regionContent.removingIndentation(levels: region.depth + 1) else { mismatches.append("\(label): the indentation could not be removed\n\(regionContent.string)") @@ -305,6 +324,24 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") } + /// The formatted variant proves something only if the fixture's prints + /// actually break at its width. The fixture has few long generic types — + /// most of them fields of `GenericFieldLayout`'s nested types — and at 30 + /// columns they insert about a hundred lines. + @Test func formattedVariantBreaksTheFixtureTypes() async throws { + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + let variant = Variant.everyOptionFormattedAsMultilineTypes + let printer = SwiftDeclarationPrinter(configuration: variant.configuration, in: machOFile) + var insertedLineCount = 0 + for typeDefinition in indexer.rootTypeDefinitions.values { + let printed = try await printer.printTypeDefinition(typeDefinition) + let formatted = variant.finished(printed) + insertedLineCount += formatted.string.count { $0 == "\n" } - printed.string.count { $0 == "\n" } + } + #expect(insertedLineCount > 50) + } + /// The exception on `ExportedOnlyFixture`, whose `UnexportedParent` the /// link leaves unexported while its nested `ExportedNested` stays /// exported — the shape of Foundation's From 912684b3780816a8a3fe7e212b98e8fc8ad9be54 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:50:54 +0800 Subject: [PATCH 049/175] docs: record that the shared testing support's MachOKitExtensions part is on its main --- .../Evolutions/draft-shared-macho-testing-support.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index 463a9bdf..8d468f87 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -369,4 +369,5 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-20 | `FixtureCompiler` 的锁改用 FrameworkToolbox 的 `OSToolbox.Mutex`,MKE 因此新增依赖 FrameworkToolbox(只有 `MachOFixtureSupport` 用) | 用户要求:不用 `NSLock`,尽量不写 `@unchecked Sendable`。标准库的 `Mutex` 要 macOS 15、`OSAllocatedUnfairLock` 要 macOS 13,MKE 的下限是 macOS 10.15,OSToolbox 的 `Mutex` 用法相同、没有版本限制。产物目录与退出时清理改成两个全局 `let`;`ProcessMemory` 的格式化器改为用时现建,去掉 `nonisolated(unsafe)`;测试里 `MachOFixtureTests` 子类多写的 `@unchecked Sendable` 删掉(MainActor 基类本就 Sendable)。MKE 全量测试通过,退出码 0。本包第 5 步同样不要再写 `NSLock`。 | | 2026-11-20 | MKE 其余模块的 `NSLock` 也一并换成 `OSToolbox.Mutex`,随 3.2.0 发布 | 用户决定:FrameworkToolbox 本来就是 MSS 与 RuntimeViewer 的依赖。19 个文件、7 个库 target;每段临界区的范围保持不变(先查、出锁构建、再进锁写回的照旧);能被编译器认作 `Sendable` 的类型去掉了 `@unchecked`,还持有 `DyldCache`、`FullDyldCache`、指针的 5 个保留并写明原因。非 `Sendable` 的值存进锁时用 `withLockUnchecked`(6 处),各有注释。MKE 全量测试与 TSTables、Espresso 普查通过,退出码 0。 | | 2026-11-20 | MKE 撤掉 Linux 支持 | OSToolbox 的 `Mutex` 基于 `os_unfair_lock`,只在 Apple 平台上有,换锁后 Linux 编不过。用户选择撤掉承诺(否决:给 OSToolbox 补 Linux 实现;在 MKE 里按平台分开用标准库的 `Mutex`)。此前从没有 Linux CI,也没在 Linux 上验证过。MachOObjCSection 依赖 MKE,它对 Linux 的承诺随之失效。 | -| 2026-11-20 | MKE 的 `Sources/` 按层分组,两个测试支持 target 在 `Sources/TestSupport/` 下 | 用户要求照本包 0055 分组,MKE 另写了提案 `draft-group-sources-by-layer`,同一分支、随 3.2.0。本提案改动地图里 MKE 的源码路径随之更新。 | +| 2026-11-20 | MKE 的 `Sources/` 按层分组,两个测试支持 target 在 `Sources/TestSupport/` 下 | 用户要求照本包 0055 分组,MKE 另写了提案 0007-group-sources-by-layer,同一分支、随 3.2.0。本提案改动地图里 MKE 的源码路径随之更新。 | +| 2026-11-21 | MKE 部分合入 MachOKitExtensions `main` 并推送,未发版 | 用户看过后收尾:测试支持的两个 product、MKE 测试改用它们、全部 `NSLock` 换成 `Mutex`、撤掉 Linux 与 `Sources/` 分组(MKE 0007)一起进了 `main`,最终代码上 MKE 全量测试通过。3.2.0 还没发;本包第 5、6 步等它发布后在本分支继续。 | From 3dba53080361a7930fd078d4b2a7c07e577cc729 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:50:59 +0800 Subject: [PATCH 050/175] feat(swift-section-kit): format long types in dump and interface on request InterfaceRequest formats the interface once printRoot() returns, and DumpRequest each declaration before it is delivered. Without the field nothing changes. Co-Authored-By: Claude --- .../draft-multiline-type-formatting.md | 11 ++- Package.swift | 9 +- .../SwiftSectionKit/Swift/DumpRequest.swift | 15 +++- .../Swift/InterfaceRequest.swift | 9 +- .../MultilineTypeFormattingRequestTests.swift | 82 +++++++++++++++++++ Tuist/CommandLine/Project.swift | 1 + 6 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 0ac12068..67779cc7 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -122,6 +122,8 @@ func update( | `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | 新字段 `multilineTypeFormatting`(init 参数默认 `nil`),`run` 里 `printRoot()` 之后、写文件或交给 output 之前调用 | interface 的唯一出口 | 5 | | `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift` · `DumpRequest`、`DumpSession` | 修改 | 新字段 `multilineTypeFormatting`;`DumpSession.dump` 拿到 `dumpedDeclaration` 后调用 | dump 的唯一出口,一次一个顶层声明 | 5 | | `Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift` | 新增 | 两个请求打开与关闭字段时的输出 | 接入正确、关闭时不变 | 5 | +| `Package.swift` · `swift-section`、`SwiftSectionKitTests` | 修改 | 两个 target 各加 `SwiftDeclarationRendering` 直接依赖 | SwiftSectionKit 不重新导出任何模块,调用方构造 `MultilineTypeFormatting` 要自己导入它 | 5 | +| `Tuist/CommandLine/Project.swift` · `commandLineDependencies` | 修改 | 加 `.external(name: "SwiftDeclarationRendering")` | 项目规定 `swift-section` 的新依赖同步进 Tuist 工程;测试目标的依赖由 `Package.swift` 末尾的映射自动带上 | 5 | | `Sources/Executables/swift-section/Commands/InterfaceCommand.swift`、`DumpCommand.swift` | 修改 | `--multiline-types` flag、`--maximum-line-width ` option;`validate()` 拒绝单独给宽度和非正数宽度;`makeRequest()` 映射 | CLI 是 SwiftSectionKit 的包装 | 6 | | `Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift` | 新增 | flag 映射到请求、校验错误的退出码 64 | CLI 两侧都要有测试 | 6 | | `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 写明两个新 flag 与默认宽度 | CLI 改动要同批更新这份 skill | 6 | @@ -370,10 +372,10 @@ extension MultilineTypeFormatting { - 行为:`annotationAndVisibilityRegionsReadBackUnchanged` - 行为:`NestedDefinitionRegionContractTests` 的 `everyOptionFormattedAsMultilineTypes` 变体(进程内与文件两种读取器) - 行为:`formattedVariantBreaksTheFixtureTypes` -5. **SwiftSectionKit 接入** —— 改动地图第 8、9、10 行 - - 行为:`interfaceRequestFormatsLongTypesWhenAsked` - - 行为:`dumpRequestFormatsEachDeclarationWhenAsked` - - 行为:`requestsWithoutFormattingPrintAsBefore` +5. **SwiftSectionKit 接入**(已完成) —— 改动地图第 8、9、10 行与依赖清单两行 + - 行为:`requestsFormatNothingUnlessAsked` + - 行为:`interfaceRequestFormatsLongTypesWhenAsked`(产物等于把不格式化的产物整份格式化) + - 行为:`dumpRequestFormatsEachDeclarationWhenAsked`(每个声明等于把它不格式化的打印格式化) - 行为:`interfaceWrittenToFileIsFormattedToo` 6. **CLI 与 agent 插件** —— 改动地图第 11、12、13 行 - 行为:`multilineTypesFlagMapsOntoTheRequest` @@ -403,3 +405,4 @@ extension MultilineTypeFormatting { | 2026-11-21 | 闭括号前的换行取闭括号的 identifier | 详细设计原写「取前一个括号或逗号的」;闭括号前面紧挨的是元素末尾,常是带类型引用 identifier 的类型名,换行不该算进那个引用的 span,所以改取闭括号自己的。 | | 2026-11-21 | 不保留元素边界 | `SemanticString` 的元素边界没有公开读取的接口,有一行被改时结果按 atom 一个元素重建;文档注释写明 `format` 用于打印完成的结果。没有行被改时返回输入本身,边界原样。 | | 2026-11-21 | 嵌套定义契约测试并入现有套件 | 改动地图原计划新建 `MultilineTypeFormattingNestedDefinitionTests.swift`;改为给 `NestedDefinitionRegionContractTests` 加一个格式化变体,直接复用它对文字、span、identifier 与三种 region 的整套比较。宽度取 30 列:fixture 的长泛型类型不多(主要是 `GenericFieldLayout` 各嵌套类型的字段),40 列下只有 4 个根类型有改动,30 列下新增约一百行。 | +| 2026-11-21 | 调用方直接依赖 `SwiftDeclarationRendering` | `SwiftSectionKit` 不重新导出任何模块,它的公开字段类型 `MultilineTypeFormatting` 由调用方自己导入:`swift-section` 与 `SwiftSectionKitTests` 各加一条直接依赖,Tuist 的命令行工程同步加上。不为一个类型在 Kit 里开 `@_exported`,与 Kit 现有字段(`Transformer.SwiftConfiguration` 等)的做法一致。 | diff --git a/Package.swift b/Package.swift index 8d2af964..a030bb69 100644 --- a/Package.swift +++ b/Package.swift @@ -940,13 +940,15 @@ extension Target { .target(.SwiftSectionKit), // What the wrapper names itself while mapping its flags onto the // library's requests: `DependencySearchPath`, `DemangleOptions`, - // `Transformer.SwiftConfiguration`, `ConsoleEventHandler`, the - // ObjC generation options and C type presets. + // `Transformer.SwiftConfiguration`, `ConsoleEventHandler`, + // `MultilineTypeFormatting`, the ObjC generation options and C + // type presets. .product(.MachOFoundation), .target(.SwiftSymbols), .target(.SwiftDump), .target(.SwiftOutputTransformer), .target(.SwiftDeclaration), + .target(.SwiftDeclarationRendering), .target(.SwiftIndexing), .product(.Semantic), .product(.OutputTransformer), @@ -1356,6 +1358,9 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftDiffing), .target(.SwiftOutputTransformer), + // `MultilineTypeFormatting`, which the `dump` and `interface` + // requests take. + .target(.SwiftDeclarationRendering), // What `refs` and `symbolicate` return. .target(.CrossReferenceAnalysis), .product(.Semantic), diff --git a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift index 5a37dd13..7ec11c22 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift @@ -97,6 +97,10 @@ public struct DumpRequest: Sendable, Equatable { /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool + /// Lays a type that runs past the line width out over several lines, at + /// its brackets, in each declaration (evolution proposal + /// `multiline-type-formatting`). `nil` prints every type on one line. + public var multilineTypeFormatting: MultilineTypeFormatting? /// The comment templates. `nil` keeps the built-in rendering; a module the /// configuration enables also turns its comment kind on. public var commentTransformers: Transformer.SwiftConfiguration? @@ -117,6 +121,7 @@ public struct DumpRequest: Sendable, Equatable { emitsExportStatus: Bool = false, emitsPrivateDeclarationSourceFiles: Bool = false, emitsHeader: Bool = false, + multilineTypeFormatting: MultilineTypeFormatting? = nil, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output ) { @@ -134,6 +139,7 @@ public struct DumpRequest: Sendable, Equatable { self.emitsExportStatus = emitsExportStatus self.emitsPrivateDeclarationSourceFiles = emitsPrivateDeclarationSourceFiles self.emitsHeader = emitsHeader + self.multilineTypeFormatting = multilineTypeFormatting self.commentTransformers = commentTransformers self.destination = destination } @@ -144,7 +150,7 @@ public struct DumpRequest: Sendable, Equatable { public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws { try await withAccessorThunkResolver(searchPaths: dependencySearchPaths) { let machOFile = try source.load() - let session = DumpSession(output: output, destination: destination) + let session = DumpSession(output: output, destination: destination, multilineTypeFormatting: multilineTypeFormatting) try await dump(machOFile, into: session, environment: environment) try session.finish() } @@ -500,11 +506,13 @@ private enum DumpTopLevelContext { private final class DumpSession { let output: Output let destination: ProductDestination + let multilineTypeFormatting: MultilineTypeFormatting? private var dumpedText = "" - init(output: Output, destination: ProductDestination) { + init(output: Output, destination: ProductDestination, multilineTypeFormatting: MultilineTypeFormatting?) { self.output = output self.destination = destination + self.multilineTypeFormatting = multilineTypeFormatting } /// Dumps one top-level declaration and hands it to the output with what it @@ -513,7 +521,8 @@ private final class DumpSession { func dump(_ topLevelContext: DumpTopLevelContext, using configuration: DumperConfiguration, in machOFile: MachOFile) async throws { let dumpedDeclaration: SemanticString do { - dumpedDeclaration = try await topLevelContext.dump(using: configuration, in: machOFile) + let printedDeclaration = try await topLevelContext.dump(using: configuration, in: machOFile) + dumpedDeclaration = multilineTypeFormatting?.format(printedDeclaration) ?? printedDeclaration } catch { reportError(error) return diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index 2cea9133..5e5eaa1c 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -88,6 +88,10 @@ public struct InterfaceRequest: Sendable, Equatable { /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool + /// Lays a type that runs past the line width out over several lines, at + /// its brackets (evolution proposal `multiline-type-formatting`). `nil` + /// prints every type on one line. + public var multilineTypeFormatting: MultilineTypeFormatting? public var commentTransformers: Transformer.SwiftConfiguration? public var destination: ProductDestination @@ -112,6 +116,7 @@ public struct InterfaceRequest: Sendable, Equatable { expandsMacros: Bool = false, protocolRequirementPlacement: ProtocolRequirementPlacement = .protocolWhereClause, emitsHeader: Bool = false, + multilineTypeFormatting: MultilineTypeFormatting? = nil, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output ) { @@ -135,6 +140,7 @@ public struct InterfaceRequest: Sendable, Equatable { self.expandsMacros = expandsMacros self.protocolRequirementPlacement = protocolRequirementPlacement self.emitsHeader = emitsHeader + self.multilineTypeFormatting = multilineTypeFormatting self.commentTransformers = commentTransformers self.destination = destination } @@ -222,7 +228,8 @@ public struct InterfaceRequest: Sendable, Equatable { output.reportProgress("Building Swift interface...") - let interfaceString = try await builder.printRoot() + let printedInterface = try await builder.printRoot() + let interfaceString = multilineTypeFormatting?.format(printedInterface) ?? printedInterface output.reportProgress("Swift interface built successfully.") diff --git a/Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift b/Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift new file mode 100644 index 00000000..e81eff08 --- /dev/null +++ b/Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift @@ -0,0 +1,82 @@ +import Foundation +import Testing +import SwiftSectionKit +import SwiftDeclarationRendering +import Semantic + +/// `multilineTypeFormatting` on the `dump` and `interface` requests +/// (evolution proposal `multiline-type-formatting`): with it, the product is +/// exactly what formatting the product printed without it gives — the whole +/// interface at once, the dump one declaration at a time — and without it +/// nothing changes. +@Suite +struct MultilineTypeFormattingRequestTests { + private static let fixture = MachOSource.file(path: FixtureFiles.symbolTestsCore, architecture: nil) + + /// Narrow enough that the fixture's long generic field types break. + private static let formatting = MultilineTypeFormatting(maximumLineWidth: 30) + + /// A field the formatting breaks, as printed on one line. + private static let oneLineField = "var nested: SymbolTestsCore.GenericFieldLayout.Pair, Swift.Int>" + + private static func declarations(of output: RecordingOutput) -> [SemanticString] { + output.products.compactMap { product in + if case .declarations(let semanticString) = product { semanticString } else { nil } + } + } + + @Test func requestsFormatNothingUnlessAsked() { + #expect(InterfaceRequest(source: Self.fixture).multilineTypeFormatting == nil) + #expect(DumpRequest(source: Self.fixture).multilineTypeFormatting == nil) + } + + @Test func interfaceRequestFormatsLongTypesWhenAsked() async throws { + let plain = RecordingOutput() + try await InterfaceRequest(source: Self.fixture).run(output: plain, environment: .testing) + let formatted = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, multilineTypeFormatting: Self.formatting).run(output: formatted, environment: .testing) + + let plainInterface = try #require(Self.declarations(of: plain).only) + let formattedInterface = try #require(Self.declarations(of: formatted).only) + #expect(plainInterface.string.contains(Self.oneLineField)) + #expect(!formattedInterface.string.contains(Self.oneLineField)) + #expect(formattedInterface.components == Self.formatting.format(plainInterface).components) + } + + @Test func interfaceWrittenToFileIsFormattedToo() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let interfacePath = directoryURL.appendingPathComponent("interface.swift").path + + let printed = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, multilineTypeFormatting: Self.formatting).run(output: printed, environment: .testing) + try await InterfaceRequest(source: Self.fixture, multilineTypeFormatting: Self.formatting, destination: .file(path: interfacePath)).run(output: RecordingOutput(), environment: .testing) + + let printedInterface = try #require(Self.declarations(of: printed).only) + #expect(!printedInterface.string.contains(Self.oneLineField)) + #expect(try String(contentsOfFile: interfacePath, encoding: .utf8) == printedInterface.string) + } + + @Test func dumpRequestFormatsEachDeclarationWhenAsked() async throws { + let plain = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types])).run(output: plain, environment: .testing) + let formatted = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types]), multilineTypeFormatting: Self.formatting).run(output: formatted, environment: .testing) + + let plainDeclarations = Self.declarations(of: plain) + let formattedDeclarations = Self.declarations(of: formatted) + #expect(plainDeclarations.count == formattedDeclarations.count) + #expect(plainDeclarations.contains { $0.string.contains(Self.oneLineField) }) + #expect(!formattedDeclarations.contains { $0.string.contains(Self.oneLineField) }) + for (plainDeclaration, formattedDeclaration) in zip(plainDeclarations, formattedDeclarations) { + #expect(formattedDeclaration.components == Self.formatting.format(plainDeclaration).components) + } + } +} + +extension Collection { + /// The collection's single element; `nil` when it has none or several. + fileprivate var only: Element? { + count == 1 ? first : nil + } +} diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift index 30ffd914..cd70aa1b 100644 --- a/Tuist/CommandLine/Project.swift +++ b/Tuist/CommandLine/Project.swift @@ -16,6 +16,7 @@ let commandLineDependencies: [TargetDependency] = [ .external(name: "SwiftDump"), .external(name: "SwiftOutputTransformer"), .external(name: "SwiftDeclaration"), + .external(name: "SwiftDeclarationRendering"), .external(name: "SwiftIndexing"), .external(name: "Semantic"), .external(name: "OutputTransformer"), From 74fa78eb18c5dd2d29dfa1ca17cf01fc05cc7703 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:52:10 +0800 Subject: [PATCH 051/175] docs: note what the fixture compiler still lacks for MachOSwiftSection's step --- Documentations/Evolutions/draft-shared-macho-testing-support.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index 8d468f87..671a06ac 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -371,3 +371,4 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-20 | MKE 撤掉 Linux 支持 | OSToolbox 的 `Mutex` 基于 `os_unfair_lock`,只在 Apple 平台上有,换锁后 Linux 编不过。用户选择撤掉承诺(否决:给 OSToolbox 补 Linux 实现;在 MKE 里按平台分开用标准库的 `Mutex`)。此前从没有 Linux CI,也没在 Linux 上验证过。MachOObjCSection 依赖 MKE,它对 Linux 的承诺随之失效。 | | 2026-11-20 | MKE 的 `Sources/` 按层分组,两个测试支持 target 在 `Sources/TestSupport/` 下 | 用户要求照本包 0055 分组,MKE 另写了提案 0007-group-sources-by-layer,同一分支、随 3.2.0。本提案改动地图里 MKE 的源码路径随之更新。 | | 2026-11-21 | MKE 部分合入 MachOKitExtensions `main` 并推送,未发版 | 用户看过后收尾:测试支持的两个 product、MKE 测试改用它们、全部 `NSLock` 换成 `Mutex`、撤掉 Linux 与 `Sources/` 分组(MKE 0007)一起进了 `main`,最终代码上 MKE 全量测试通过。3.2.0 还没发;本包第 5、6 步等它发布后在本分支继续。 | +| 2026-11-21 | 第 5 步的已知缺口:`FixtureCompiler` 还不能完全替代本包的 `CompiledFixture` | 本包 `Tests/CrossReferenceAnalysisTests/CompiledFixture.swift` 的 `build(libraryName:sources:compilerArguments:isExecutable:)` 能编可执行文件(`FileModeTests`、`FunctionStartOutsideTextTests` 两处用 `isExecutable: true`)、一次编多个源文件、按参数指定架构;MKE 3.1.0 之后的 `FixtureCompiler` 只把单个源字符串编成动态库。要么在发 3.2.0 之前给 `FixtureCompiler` 补可执行文件与多源文件,要么这几处在本包保留自己的辅助,待用户定。另:next 上新进的 `FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText` 用到 `CompiledFixture.build(…isExecutable:)` 与 `InstructionEncoding.branchWithLink(at:to:)`,第 5 步若搬走或改名它们,这条测试一起改,本分支合 next 时会遇到它。 | From 18e34ce1adf4c6c90d9849fda65b3a055d29ad26 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:53:51 +0800 Subject: [PATCH 052/175] feat(swift-section): add --multiline-types and --maximum-line-width to dump and interface A width without the flag, or a width below one column, is a usage error. The agent plugin's skill describes both flags and their traps. Co-Authored-By: Claude --- .../skills/swift-section-cli/SKILL.md | 18 +++++- .../draft-multiline-type-formatting.md | 12 ++-- .../swift-section/Commands/DumpCommand.swift | 4 ++ .../Commands/InterfaceCommand.swift | 4 ++ .../Models/MultilineTypeOptionGroup.swift | 29 +++++++++ .../MultilineTypesFlagTests.swift | 59 +++++++++++++++++++ 6 files changed, 119 insertions(+), 7 deletions(-) create mode 100644 Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift create mode 100644 Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index f0b61a56..8efebac2 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -50,7 +50,8 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, `interface --requirements-on-associated-types` and `--emit-private-source-files`, and from 0.25.0 `objc evolution --interface` / `--emit-available` / `--platform`, `objc interface --swift`, `interface --no-existential-any` / `dump --disable-existential-any`, -`interface --expand-macros` and the `refs` and `symbolicate` subcommands. +`interface --expand-macros` and the `refs` and `symbolicate` subcommands, and after 0.26.0 +`--multiline-types` / `--maximum-line-width` on `dump` and `interface`. 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". @@ -152,7 +153,20 @@ The single most common mistake. Same underlying comment, different name: Spelled the same on both: `--emit-type-layout`, `--emit-enum-layout`, `--emit-member-addresses`, `--emit-vtable-offsets`, `--emit-expanded-field-offsets` (implies the field-offset flag), `--emit-header`, `--emit-export-status`, `--emit-private-source-files`, `--color-scheme`, -`--output-path`, `--dependency-search-path` (§2). +`--output-path`, `--dependency-search-path` (§2), `--multiline-types`, `--maximum-line-width`. + +`--multiline-types` breaks a long type over several lines at its brackets — a SwiftUI view's +`typealias Body = SwiftUI.ModifiedContent<…>` otherwise prints as one line thousands of +characters long. A type whose closing `>` lies past `--maximum-line-width` (default 100; a +line's indentation does not count) puts each argument of every generic with two or more +arguments on a line of its own; a single-argument generic, a tuple, a parameter list or +`[…]` sugar breaks only when something inside it breaks, so a signature's parameter list opens +up around a broken parameter type. A type that fits stays on one line, and so does a line that +is long for any other reason (many parameters, a trailing comment). Off by default. With it on, +a declaration no longer sits on one line: grep for a short name, not a whole one-line type +spelling, and do not feed the output to anything that expects one declaration per line. +`--maximum-line-width` without `--multiline-types` is a usage error. `diff`, `evolution` and +`snapshot` do not take these flags. `--emit-private-source-files` puts a comment above each declaration whose name carries a private discriminator, naming the source file the discriminator was derived from: diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 67779cc7..03e708bb 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -124,7 +124,8 @@ func update( | `Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift` | 新增 | 两个请求打开与关闭字段时的输出 | 接入正确、关闭时不变 | 5 | | `Package.swift` · `swift-section`、`SwiftSectionKitTests` | 修改 | 两个 target 各加 `SwiftDeclarationRendering` 直接依赖 | SwiftSectionKit 不重新导出任何模块,调用方构造 `MultilineTypeFormatting` 要自己导入它 | 5 | | `Tuist/CommandLine/Project.swift` · `commandLineDependencies` | 修改 | 加 `.external(name: "SwiftDeclarationRendering")` | 项目规定 `swift-section` 的新依赖同步进 Tuist 工程;测试目标的依赖由 `Package.swift` 末尾的映射自动带上 | 5 | -| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift`、`DumpCommand.swift` | 修改 | `--multiline-types` flag、`--maximum-line-width ` option;`validate()` 拒绝单独给宽度和非正数宽度;`makeRequest()` 映射 | CLI 是 SwiftSectionKit 的包装 | 6 | +| `Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift` · `MultilineTypeOptionGroup` | 新增 | `--multiline-types` flag、`--maximum-line-width ` option;`validate()` 拒绝单独给宽度和非正数宽度;`multilineTypeFormatting` 把两者换成请求要的值;帮助里的默认宽度取自 `MultilineTypeFormatting()` | 两个子命令共用一组参数,照 `ObjCMemberOptionGroup` 的做法放进 option group | 6 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift`、`DumpCommand.swift` | 修改 | `@OptionGroup(title: "Long Types")` 引入上面那组参数,`makeRequest()` 映射到 `multilineTypeFormatting` | CLI 是 SwiftSectionKit 的包装 | 6 | | `Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift` | 新增 | flag 映射到请求、校验错误的退出码 64 | CLI 两侧都要有测试 | 6 | | `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 写明两个新 flag 与默认宽度 | CLI 改动要同批更新这份 skill | 6 | | `Documentations/SwiftSectionKit.md`、`Documentations/Internal/Modules/SwiftSectionKit.md` | 修改 | 两个请求的新字段 | 调用方指南与模块参考 | 7 | @@ -377,12 +378,13 @@ extension MultilineTypeFormatting { - 行为:`interfaceRequestFormatsLongTypesWhenAsked`(产物等于把不格式化的产物整份格式化) - 行为:`dumpRequestFormatsEachDeclarationWhenAsked`(每个声明等于把它不格式化的打印格式化) - 行为:`interfaceWrittenToFileIsFormattedToo` -6. **CLI 与 agent 插件** —— 改动地图第 11、12、13 行 +6. **CLI 与 agent 插件**(已完成) —— 改动地图第 11、12、13 行与 `MultilineTypeOptionGroup` 一行 + - 行为:`formattingIsOffByDefault` - 行为:`multilineTypesFlagMapsOntoTheRequest` - 行为:`maximumLineWidthMapsOntoTheRequest` - - 行为:`maximumLineWidthWithoutMultilineTypesIsAUsageError` - - 行为:`nonPositiveMaximumLineWidthIsAUsageError` - - 行为:插件 skill 里出现的每个 flag 都存在于对应子命令的 `--help` + - 行为:`usageMistakesAreValidationErrors`(只给宽度、宽度不是正数,两个子命令都是退出码 64) + - 行为:`helpNamesTheDefaultWidth` + - 行为:插件 skill 里出现的每个 flag 都存在于对应子命令的 `--help`(逐个核对过);`claude plugin validate` 两项通过 7. **文档** —— 改动地图第 14、15、16 行 - 行为:文档索引、账本、术语表、模块清单与代码一致 diff --git a/Sources/Executables/swift-section/Commands/DumpCommand.swift b/Sources/Executables/swift-section/Commands/DumpCommand.swift index 716b8ec4..8cd28b91 100644 --- a/Sources/Executables/swift-section/Commands/DumpCommand.swift +++ b/Sources/Executables/swift-section/Commands/DumpCommand.swift @@ -17,6 +17,9 @@ struct DumpCommand: AsyncParsableCommand, Sendable { @OptionGroup(title: "Comment Templates") var transformerOptions: TransformerOptionGroup + @OptionGroup(title: "Long Types") + var multilineTypeOptions: MultilineTypeOptionGroup + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) var outputPath: String? @@ -76,6 +79,7 @@ struct DumpCommand: AsyncParsableCommand, Sendable { emitsExportStatus: emitExportStatus, emitsPrivateDeclarationSourceFiles: emitPrivateSourceFiles, emitsHeader: emitHeader, + multilineTypeFormatting: multilineTypeOptions.multilineTypeFormatting, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output ) diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index a1751304..79462ccb 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -18,6 +18,9 @@ struct InterfaceCommand: AsyncParsableCommand { @OptionGroup(title: "Comment Templates") var transformerOptions: TransformerOptionGroup + @OptionGroup(title: "Long Types") + var multilineTypeOptions: MultilineTypeOptionGroup + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) var outputPath: String? @@ -104,6 +107,7 @@ struct InterfaceCommand: AsyncParsableCommand { expandsMacros: expandMacros, protocolRequirementPlacement: requirementsOnAssociatedTypes ? .associatedTypes : .protocolWhereClause, emitsHeader: emitHeader, + multilineTypeFormatting: multilineTypeOptions.multilineTypeFormatting, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output ) diff --git a/Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift b/Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift new file mode 100644 index 00000000..6b7474ad --- /dev/null +++ b/Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift @@ -0,0 +1,29 @@ +import ArgumentParser +import SwiftDeclarationRendering + +/// `--multiline-types` and `--maximum-line-width`, on `dump` and `interface` +/// (evolution proposal `multiline-type-formatting`). +struct MultilineTypeOptionGroup: ParsableArguments, Sendable { + @Flag(name: .customLong("multiline-types"), help: "Break a type that runs past the line width over several lines, at its brackets: each argument of a generic with two or more arguments on a line of its own, and a single-argument generic, a tuple, a parameter list or [...] sugar only when something inside it breaks. A type that fits stays on one line, and so does a line that is long for any other reason.") + var multilineTypes: Bool = false + + @Option(name: .customLong("maximum-line-width"), help: ArgumentHelp("The widest a line may be, not counting its indentation, before --multiline-types breaks its types. (default: \(MultilineTypeFormatting().maximumLineWidth))", valueName: "columns")) + var maximumLineWidth: Int? + + mutating func validate() throws { + guard let maximumLineWidth else { return } + guard multilineTypes else { + throw ValidationError("--maximum-line-width needs --multiline-types.") + } + guard maximumLineWidth > 0 else { + throw ValidationError("--maximum-line-width must be a positive number of columns, got \(maximumLineWidth).") + } + } + + /// The formatting these options ask for; `nil` without `--multiline-types`. + var multilineTypeFormatting: MultilineTypeFormatting? { + guard multilineTypes else { return nil } + guard let maximumLineWidth else { return MultilineTypeFormatting() } + return MultilineTypeFormatting(maximumLineWidth: maximumLineWidth) + } +} diff --git a/Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift b/Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift new file mode 100644 index 00000000..1c75ffbe --- /dev/null +++ b/Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing +import ArgumentParser +import SwiftSectionKit +import SwiftDeclarationRendering +@testable import swift_section + +/// `--multiline-types` and `--maximum-line-width` on `dump` and `interface` +/// (evolution proposal `multiline-type-formatting`): off by default, mapped +/// onto the request's `multilineTypeFormatting`, and a width without the flag +/// or below one column is a usage error, exit code 64. +@Suite +struct MultilineTypesFlagTests { + @Test func formattingIsOffByDefault() throws { + #expect(try DumpCommand.parse(["/tmp/example"]).makeRequest().multilineTypeFormatting == nil) + #expect(try InterfaceCommand.parse(["/tmp/example"]).makeRequest().multilineTypeFormatting == nil) + } + + @Test func multilineTypesFlagMapsOntoTheRequest() throws { + #expect(try DumpCommand.parse(["/tmp/example", "--multiline-types"]).makeRequest().multilineTypeFormatting == MultilineTypeFormatting()) + #expect(try InterfaceCommand.parse(["/tmp/example", "--multiline-types"]).makeRequest().multilineTypeFormatting == MultilineTypeFormatting()) + } + + @Test func maximumLineWidthMapsOntoTheRequest() throws { + let arguments = ["/tmp/example", "--multiline-types", "--maximum-line-width", "120"] + #expect(try DumpCommand.parse(arguments).makeRequest().multilineTypeFormatting == MultilineTypeFormatting(maximumLineWidth: 120)) + #expect(try InterfaceCommand.parse(arguments).makeRequest().multilineTypeFormatting == MultilineTypeFormatting(maximumLineWidth: 120)) + } + + @Test(arguments: [ + (["/tmp/example", "--maximum-line-width", "120"], "--maximum-line-width needs --multiline-types"), + (["/tmp/example", "--multiline-types", "--maximum-line-width", "0"], "--maximum-line-width must be a positive number of columns"), + ]) + func usageMistakesAreValidationErrors(arguments: [String], messagePart: String) { + #expect( + performing: { + _ = try DumpCommand.parse(arguments) + }, + throws: { error in + DumpCommand.message(for: error).contains(messagePart) && DumpCommand.exitCode(for: error) == ExitCode(64) + } + ) + #expect( + performing: { + _ = try InterfaceCommand.parse(arguments) + }, + throws: { error in + InterfaceCommand.message(for: error).contains(messagePart) && InterfaceCommand.exitCode(for: error) == ExitCode(64) + } + ) + } + + @Test func helpNamesTheDefaultWidth() { + for helpMessage in [DumpCommand.helpMessage(columns: 1000), InterfaceCommand.helpMessage(columns: 1000)] { + #expect(helpMessage.contains("--maximum-line-width ")) + #expect(helpMessage.contains("--multiline-types breaks its types. (default: 100)")) + } + } +} From 1597660d93ab680be394c30fef9af12a2900d66e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:56:47 +0800 Subject: [PATCH 053/175] docs: record MachOKitExtensions 3.2.0 in the shared testing support proposal --- .../draft-shared-macho-testing-support.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index 671a06ac..1cb94eb1 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -212,12 +212,21 @@ public struct FixtureCompiler: Sendable { // macOS only public enum Language: Sendable { case c, cPlusPlus, swift } public static let shared: FixtureCompiler /// Compiles `source` into `lib.dylib` (install name `@rpath/lib.dylib`) once per - /// process for the same name, language, source and arguments; the directory goes away when - /// the process exits. + /// process for the same name, language, kind, sources and arguments; the directory goes away + /// when the process exits. Architecture, optimization and target come in `arguments`. public func dynamicLibrary(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL + public func dynamicLibrary(named name: String, language: Language, sourceFiles: [FixtureSourceFile], arguments: [String] = []) throws -> URL + /// The main executable `name`. + public func executable(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL + public func executable(named name: String, language: Language, sourceFiles: [FixtureSourceFile], arguments: [String] = []) throws -> URL public var productsDirectory: URL { get } } +/// A file of a build, written under `name`; its extension tells the driver how to read it. +public struct FixtureSourceFile: Hashable, Sendable { + public init(name: String, contents: String) +} + public struct ForwardingReader: MachORepresentableWithCache /// `print()` on `CustomStringConvertible` and `Error`, quiet when `MACHO_TESTING_SILENT=1`. @@ -325,7 +334,7 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): 3. **MKE 的测试改用共享版本**(完成)—— 动机一节的表,以及 `Tests/CPlusPlusSymbolsTests/` - 行为:MKE 全部测试照常通过,跨读取器的约 25 个测试改写为 `acrossAllReaders` 后断言不变 - 行为:仓库里不再有 `Process` 调用 `xcrun` 的测试辅助、写死 Cryptexes 路径的常量、手写的选 slice -4. **MKE 文档与发版**(文档完成,发版待确认)—— `Internal/TestingSupport.md`、README、索引;发 3.2.0 +4. **MKE 文档与发版**(完成,3.2.0)—— `Internal/TestingSupport.md`、README、索引;发 3.2.0 本包(MKE 3.2.0 发布后,从 `next` 切出): @@ -372,3 +381,4 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-20 | MKE 的 `Sources/` 按层分组,两个测试支持 target 在 `Sources/TestSupport/` 下 | 用户要求照本包 0055 分组,MKE 另写了提案 0007-group-sources-by-layer,同一分支、随 3.2.0。本提案改动地图里 MKE 的源码路径随之更新。 | | 2026-11-21 | MKE 部分合入 MachOKitExtensions `main` 并推送,未发版 | 用户看过后收尾:测试支持的两个 product、MKE 测试改用它们、全部 `NSLock` 换成 `Mutex`、撤掉 Linux 与 `Sources/` 分组(MKE 0007)一起进了 `main`,最终代码上 MKE 全量测试通过。3.2.0 还没发;本包第 5、6 步等它发布后在本分支继续。 | | 2026-11-21 | 第 5 步的已知缺口:`FixtureCompiler` 还不能完全替代本包的 `CompiledFixture` | 本包 `Tests/CrossReferenceAnalysisTests/CompiledFixture.swift` 的 `build(libraryName:sources:compilerArguments:isExecutable:)` 能编可执行文件(`FileModeTests`、`FunctionStartOutsideTextTests` 两处用 `isExecutable: true`)、一次编多个源文件、按参数指定架构;MKE 3.1.0 之后的 `FixtureCompiler` 只把单个源字符串编成动态库。要么在发 3.2.0 之前给 `FixtureCompiler` 补可执行文件与多源文件,要么这几处在本包保留自己的辅助,待用户定。另:next 上新进的 `FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText` 用到 `CompiledFixture.build(…isExecutable:)` 与 `InstructionEncoding.branchWithLink(at:to:)`,第 5 步若搬走或改名它们,这条测试一起改,本分支合 next 时会遇到它。 | +| 2026-11-21 | `FixtureCompiler` 补上可执行文件与多源文件,MKE 3.2.0 发布 | 用户选择发版前先补:新增 `executable(named:language:source:arguments:)`、两个收 `sourceFiles: [FixtureSourceFile]` 的重载,单段源码的写法不变;本包 `CompiledFixture.build` 的可执行文件、多源文件与指定架构(经参数 `-arch`)都能用它替代。`CompiledFixture.load` 的链接后改写、重新签名、再加载留在本包,在复制出的产物上做(共享编译器的产物是缓存,不能原地改)。MKE 全量测试通过,原始退出码 0;随后在 `main` 上打 3.2.0(附注 tag,同以往不建 Release 页面)。本包第 5、6 步可以开始。 | From ff2eeb2c0b6e0173819370542cd5f141b75664cd Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 09:58:39 +0800 Subject: [PATCH 054/175] fix(swift-declaration-rendering): treat angle brackets holding requirements as a generic signature The dump spells a constrained extension's context as _ConditionalContent< where A: P, B: Q> right after a type name, and the formatter broke its two requirements as if they were type arguments. A <...> list one of whose elements says where, `A: P` or == at its own level is now a generic signature, which breaks only around a broken element. Co-Authored-By: Claude --- .../draft-multiline-type-formatting.md | 5 +-- .../MultilineTypeFormatting+BracketTree.swift | 22 +++++++++++- .../MultilineTypeFormattingTests.swift | 34 +++++++++++++++++++ 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 03e708bb..3965e76c 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -46,7 +46,7 @@ let formatted = formatting.format(printedDefinition) 2. **超宽的行解析成括号树。** 只在 `.standard` 类型的 atom 里找括号;类型名、模块名、关键字、声明名、注释等其它 atom 整体当作文字。字符串字面量、反引号标识符、`//` 之后的内容是文字;`->` 不是括号。括号不配对(例如 dump 里的运算符声明)就整行原样保留。 3. **找出放不下的类型。** 不在其它泛型参数列表里面的泛型参数列表,算作一个类型的最外层;它的 `>` 落在第 `maximumLineWidth` 列之后,这个类型就算放不下。只有泛型参数列表会触发拆行;行之所以超宽是因为别的东西(一长串参数、行尾注释),这一行不动。 4. **放不下的类型按结构规则拆。** 在这个类型内部:有两个及以上参数的泛型参数列表一律每个参数一行;单参数的泛型参数列表、元组、函数类型的参数列表、`[…]` 集合语法糖,只在某个元素已是多行时才拆。 -5. **外层括号跟着拆。** 类型之外的括号——函数声明的参数列表、enum case 的 payload、元组、泛型参数子句(紧跟在声明名后面的 `<…>`)、attribute 的参数——只在某个元素已是多行时才拆,否则保持一行。泛型参数子句因此不会仅仅因为有两个参数就被拆开。 +5. **外层括号跟着拆。** 类型之外的括号——函数声明的参数列表、enum case 的 payload、元组、泛型签名(紧跟在声明名后面的 `<…>`,以及里面写着 `where`、`A: P` 或 `==` 的 `<…>`)、attribute 的参数——只在某个元素已是多行时才拆,否则保持一行。泛型签名因此不会仅仅因为有两项就被拆开。 6. **拆开的列表这样排。** 开括号留在原行末尾;每个参数另起一行,缩进为这一行的行首缩进加 4 个空格乘以嵌套层数;参数之间的 `, ` 变成 `,`;闭括号另起一行,缩进回到上一层。 截图里那个 `Body` 的开头一段,按默认宽度格式化后是这样: @@ -265,7 +265,7 @@ extension MultilineTypeFormatting { - 只有 `.standard` atom 参与扫描;其它 semantic type 的 atom 整体是一个 `text`。这样类型名、声明名(包括 interface 里的运算符名)、注释里的括号都不会被当成结构。 - 在 `.standard` atom 里:`"` 开始一个字符串字面量,到未转义的 `"` 结束;反引号同理;`//` 之后到行末都是文字;`-` 紧跟 `>` 是箭头,不关闭任何列表;`<`、`(`、`[` 开列表,`>`、`)`、`]` 必须关闭同种列表;深度大于 0 时的 `,` 分隔元素。 -- `<` 前面(跳过空白)的 atom 的 semantic type 是 `.type(_, .declaration)`、`.function(.declaration)` 或 `.member(.declaration)` 时,这个列表是 `genericParameters`;否则是 `genericArguments`。 +- `<` 前面(跳过空白)的 atom 的 semantic type 是 `.type(_, .declaration)`、`.function(.declaration)` 或 `.member(.declaration)` 时,这个列表是 `genericParameters`;否则是 `genericArguments`。闭括号读到时再看一次:有一项在自己这一层(不算嵌在里面的列表)写着 `where` 这个词、`: `(冒号后带空格)或 `==`,这是 dump 写在类型名后面的泛型签名(`_ConditionalContent< where A: P, B: Q>`、`make`),也改为 `genericParameters`。类型参数里不会出现这三种:模块选择器的 `::` 与 dump 的 `(extension in M):` 前缀冒号后没有空格,元组的标签在它自己的列表里。 - 关闭括号与种类不符、或行末仍有未关闭的列表,返回 `nil`,整行原样保留。dump 里的 `static func < infix(…)` 就走这条路。 ### 排版 @@ -408,3 +408,4 @@ extension MultilineTypeFormatting { | 2026-11-21 | 不保留元素边界 | `SemanticString` 的元素边界没有公开读取的接口,有一行被改时结果按 atom 一个元素重建;文档注释写明 `format` 用于打印完成的结果。没有行被改时返回输入本身,边界原样。 | | 2026-11-21 | 嵌套定义契约测试并入现有套件 | 改动地图原计划新建 `MultilineTypeFormattingNestedDefinitionTests.swift`;改为给 `NestedDefinitionRegionContractTests` 加一个格式化变体,直接复用它对文字、span、identifier 与三种 region 的整套比较。宽度取 30 列:fixture 的长泛型类型不多(主要是 `GenericFieldLayout` 各嵌套类型的字段),40 列下只有 4 个根类型有改动,30 列下新增约一百行。 | | 2026-11-21 | 调用方直接依赖 `SwiftDeclarationRendering` | `SwiftSectionKit` 不重新导出任何模块,它的公开字段类型 `MultilineTypeFormatting` 由调用方自己导入:`swift-section` 与 `SwiftSectionKitTests` 各加一条直接依赖,Tuist 的命令行工程同步加上。不为一个类型在 Kit 里开 `@_exported`,与 Kit 现有字段(`Transformer.SwiftConfiguration` 等)的做法一致。 | +| 2026-11-21 | 尖括号里写着要求的是泛型签名 | 对系统 SwiftUI 跑 `dump --multiline-types` 时发现:dump 把受约束扩展的上下文印成 `_ConditionalContent< where A: P, B: Q>`,这个 `<…>` 跟在类型名后面,被当成两个泛型参数拆开了。规则补一条:`<…>` 里有一项在自己这一层写着 `where`、`A: P`(冒号后带空格)或 `==`,就是泛型签名,按泛型参数子句处理(只在元素已是多行时才拆)。模块选择器的 `::` 与 dump 的 `(extension in M):` 前缀冒号后都没有空格,不受影响。先写了变红的测试 `angleBracketsHoldingRequirementsAreAGenericSignature`、`genericSignatureIsNotBrokenForItsRequirements`,修复后通过;另加 `moduleSelectorsAndExtensionContextsLeaveAnArgumentList`、`moduleSelectorsStillBreakAsArguments` 守住不误判。 | diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift index 1bddbfe1..e23b4f82 100644 --- a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift @@ -1,3 +1,4 @@ +import Foundation import Semantic extension MultilineTypeFormatting { @@ -254,8 +255,9 @@ private struct BracketTreeParser { private mutating func close(_ bracket: Character, at fragment: SourceFragment) -> Bool { guard var list = openLists.popLast(), list.kind.closingCharacter == bracket else { return false } list.elements.append(list.currentElement) + let kind: BracketKind = list.kind == .genericArguments && Self.holdsRequirements(list.elements) ? .genericParameters : list.kind let closedList = BracketList( - kind: list.kind, + kind: kind, opening: list.opening, closing: fragment, separators: list.separators, @@ -283,6 +285,24 @@ private struct BracketTreeParser { } } + /// Whether a `<…>` list holds requirements rather than types — a generic + /// signature, which the dump writes after a type name too + /// (`_ConditionalContent< where A: P, B: Q>`, `make`). + /// One element says `where`, `A: P` or `A == B` at its own level, outside + /// any list nested in it. A type argument never does: a module selector's + /// `::` and the dump's `(extension in M):` prefix have no space after the + /// colon, and a tuple's labels sit in a list of their own. + private static func holdsRequirements(_ elements: [[BracketTreeNode]]) -> Bool { + elements.contains { element in + let topLevelText = element.map { node in + if case .text(let fragment) = node { String(fragment.text) } else { " " } + }.joined() + return topLevelText.split(whereSeparator: \.isWhitespace).contains("where") + || topLevelText.contains(": ") + || topLevelText.contains("==") + } + } + private static func namesADeclaration(_ type: SemanticType) -> Bool { switch type { case .type(_, .declaration), diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift index 0b4ff5be..4e400e0d 100644 --- a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift @@ -219,6 +219,21 @@ struct MultilineTypeFormattingTests { #expect(try bracketStructure(of: line) == "static func < (lhs: (Visitor in $1234)| rhs: Box) // Box` + /// — and a function's as ``: requirements, not + /// arguments, whatever name they follow. + @Test func angleBracketsHoldingRequirementsAreAGenericSignature() throws { + let extensionContext = "(extension in SwiftUI):SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC)" + #expect(try bracketStructure(of: PrinterShapedSource.make(extensionContext)) == "(extension in SwiftUI):SwiftUI._ConditionalContent‹ where A: SwiftUI.TableColumnContent| B: SwiftUI.TableColumnContent›.(Provider in _ABC)") + #expect(try bracketStructure(of: PrinterShapedSource.make("Holder.make()")) == "Holder.make‹A| B where A == B.Element›()") + } + + @Test func moduleSelectorsAndExtensionContextsLeaveAnArgumentList() throws { + #expect(try bracketStructure(of: PrinterShapedSource.make("var value: Swift::Dictionary")) == "var value: Swift::Dictionary") + #expect(try bracketStructure(of: PrinterShapedSource.make("var value: Pair<(extension in SwiftUI):SwiftUI.Box, Swift.Int>")) == "var value: Pair<(extension in SwiftUI):SwiftUI.Box| Swift.Int>") + } + @Test func commaOutsideBracketsIsText() throws { #expect(try bracketStructure(of: PrinterShapedSource.make("case first, second")) == "case first, second") } @@ -379,6 +394,25 @@ struct MultilineTypeFormattingTests { """) } + @Test func genericSignatureIsNotBrokenForItsRequirements() { + let line = "(extension in SwiftUI):SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC).init() -> SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC)" + #expect(formatted(line, maximumLineWidth: 100) == """ + (extension in SwiftUI):SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC).init() -> SwiftUI._ConditionalContent< + A, + B + >< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC) + """) + } + + @Test func moduleSelectorsStillBreakAsArguments() { + #expect(formatted("var value: Swift::Dictionary", maximumLineWidth: 20) == """ + var value: Swift::Dictionary< + Swift::String, + Swift::Int + > + """) + } + @Test func emptyParenthesesNeverBreak() { #expect(formatted("func make() -> Pair", maximumLineWidth: 10) == """ func make() -> Pair< From d425338912954bfb23a3b5c78c5ebc01abfac518 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 10:18:04 +0800 Subject: [PATCH 055/175] docs: document multiline type formatting The glossary gains long type and multiline type formatting, the SwiftSectionKit guides and module reference describe the new request field, the agent instructions name MultilineTypeFormatting under SwiftDeclarationRendering, and the ledger and the proposal record the verification. Co-Authored-By: Claude --- AGENTS.md | 2 +- .../draft-multiline-type-formatting.html | 26 +++++++++++++------ .../draft-multiline-type-formatting.md | 6 +++-- Documentations/Glossary.md | 9 +++++++ .../Internal/Modules/SwiftSectionKit.md | 1 + .../Internal/ProjectEvolutionLog.md | 18 +++++++++++++ Documentations/SwiftSectionKit.md | 11 ++++++++ Documentations/SwiftSectionKit_zh.md | 11 ++++++++ 8 files changed, 73 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ff01b680..f3ac8e5a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,7 +51,7 @@ One or two lines each; the linked document is the authority. - **SwiftObjCInterop** — the Objective-C side of Swift types, and where `MachOObjCSection` enters the Swift-facing stack: per-image indexes of `@objc @implementation` classes, of the Swift classes a source renamed for the ObjC runtime (`SwiftClassObjectIndex` — every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss), of the Swift classes with no class object in `__objc_classlist`, and of the `@objc` protocols declared in Swift; the seam through which a host hands over the ObjC class hierarchies it already indexed (`ObjCClassHierarchyProviding`), the library's own reader behind it and the ancestor chain followed into a standalone file's dependency closure; the per-class ObjC member table (`ObjCMemberTable`); the ClangImporter's naming rules, and the records an ObjC class, category or protocol is imported into Swift from (`ObjCImportedContainerIndex`). A Swift class's ObjC-side name is not always `_TtC…`: in a file, a category on another image's Swift class names it by the class metadata symbol it is bound to (`_$s…CN`). Read every such name through `NodeTypeNaming.swiftClassNode(fromRuntimeName:)`, never a `hasPrefix("_Tt")` check — one printed `extension __C._$s…` and found none of its `@objc` witnesses. The linker merges a binary's categories on its own classes into those classes, so `__objc_catlist` lists only categories on other images' classes. An `@objc` protocol declared in Swift has NO protocol descriptor and a class's conformance to an ObjC protocol has NO conformance record — the facts live in `__swift5_fieldmd`, `protocol_t` and `class_ro_t`. [Modules/SwiftObjCInterop.md](Documentations/Internal/Modules/SwiftObjCInterop.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. Its files split by visibility: a `public` type that stays in the model after indexing goes under `Model/`; code that only runs while the model is built (`package` / `internal`) goes under `Indexing/` — a new `TypeDefinition+…` step goes in `Indexing/TypeDefinition/`, never beside `TypeDefinition.swift`. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). -- **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). +- **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). Also `MultilineTypeFormatting`, which breaks a finished print's long types at their brackets — applied once at the output (the `dump` / `interface` requests, a host's assembled print), never inside a printer ([draft-multiline-type-formatting](Documentations/Evolutions/draft-multiline-type-formatting.md)). - **SwiftIndexing** — builds the declaration model from an image (`SwiftDeclarationIndexer.prepare()`), unifies extension containers, owns the per-image cache eviction. - **SwiftPrivateDiscriminators** — recovers the source file a private discriminator was derived from (`MD5(module name + file name)`): candidate file names hashed until one matches — a generated list of known ones, then names the image itself declares. `PrivateDiscriminatorSourceFileIndex` holds one image's candidates and remembers every answer. `dump` / `interface --emit-private-source-files` reach it through `SwiftDeclarationRendering`'s `PrivateDeclarationSourceFileProviding`, after one search over the whole image (`recoverSourceFiles(ofEveryDeclarationIn:)`) — asked one declaration at a time, every discriminator nothing recovers runs through all the candidates again. [Modules/SwiftPrivateDiscriminators.md](Documentations/Internal/Modules/SwiftPrivateDiscriminators.md). - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.html b/Documentations/Evolutions/draft-multiline-type-formatting.html index 7476f171..b6f2be93 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.html +++ b/Documentations/Evolutions/draft-multiline-type-formatting.html @@ -196,9 +196,9 @@

    摘要

    要你定

    -

    批准后开工

    +

    已批准并实现

      -
    1. 批准这份提案、按落地步骤开始实现?
    2. +
    3. 看过效果后收尾(编号、合进 next、推送)。
    @@ -219,7 +219,7 @@

    方案

  • 超宽的行解析成括号树。只在 .standard 类型的 atom 里找括号;字符串字面量、反引号标识符、// 之后的内容是文字;-> 不是括号。括号不配对就整行原样保留。
  • 找出放不下的类型。不在其它泛型参数列表里面的泛型参数列表算作一个类型的最外层;它的 > 落在第 maximumLineWidth 列之后,这个类型就算放不下。
  • 放不下的类型按结构规则拆。有两个及以上参数的泛型参数列表一律每个参数一行;单参数泛型、元组、函数类型的参数列表、[…] 只在某个元素已是多行时才拆。
  • -
  • 外层括号跟着拆。函数声明的参数列表、enum case payload、元组、泛型参数子句、attribute 参数,只在某个元素已是多行时才拆。
  • +
  • 外层括号跟着拆。函数声明的参数列表、enum case payload、元组、泛型签名(紧跟在声明名后面的 <…>,以及里面写着 where、A: P 或 == 的 <…>)、attribute 参数,只在某个元素已是多行时才拆。
  • 拆开的列表这样排。开括号留在原行末尾;参数另起一行,缩进为行首缩进加 4 个空格乘以嵌套层数;, 变成 ,;闭括号另起一行回到上一层。
  • extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View {
    @@ -332,11 +332,14 @@ 

    改动地图

    MultilineTypeFormatting+Layout.swift · Layout(internal)新增判定长类型、自下而上决定拆哪些列表、生成 atom(插入的 atom 沿用相邻括号或逗号的 identifier)规则 3–63 Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift新增行切分、解析、排版的单元测试每步的行为清单1–3 Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift新增type 与 identifier 不变、可还原原文、幂等、与缩进可交换、region 读回不变「只加换行和缩进」的承诺4 - Tests/SwiftInterfaceTests/MultilineTypeFormattingNestedDefinitionTests.swift新增格式化父定义后取出的子定义等于子定义单独打印再格式化嵌套定义契约在格式化后仍成立4 + Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift修改新变体 everyOptionFormattedAsMultilineTypes:两份打印都按 30 列格式化后再比较;另加 formattedVariantBreaksTheFixtureTypes嵌套定义契约在格式化后仍成立;复用这个套件的整套比较4 Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift修改新字段 multilineTypeFormatting,printRoot() 之后调用interface 的唯一出口5 Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift修改新字段;DumpSession.dump 拿到声明后调用dump 的唯一出口5 Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift新增两个请求打开与关闭时的输出接入正确、关闭时不变5 - Sources/Executables/swift-section/Commands/InterfaceCommand.swift、DumpCommand.swift修改--multiline-types、--maximum-line-width,validate()、makeRequest()CLI 是 SwiftSectionKit 的包装6 + Package.swift · swift-section、SwiftSectionKitTests修改各加 SwiftDeclarationRendering 直接依赖Kit 不重新导出模块,调用方自己导入5 + Tuist/CommandLine/Project.swift修改命令行依赖加 SwiftDeclarationRenderingTuist 工程与清单同步5 + Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift新增--multiline-types、--maximum-line-width,validate(),换成请求要的值两个子命令共用一组参数6 + Sources/Executables/swift-section/Commands/InterfaceCommand.swift、DumpCommand.swift修改引入上面那组参数,makeRequest() 映射CLI 是 SwiftSectionKit 的包装6 Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift新增映射与校验(退出码 64)CLI 两侧都要有测试6 AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md修改两个新 flag 与默认宽度CLI 改动同批更新6 Documentations/SwiftSectionKit.md、Internal/Modules/SwiftSectionKit.md修改新字段调用方指南与模块参考7 @@ -392,7 +395,7 @@

    详细设计

    • 只有 .standard atom 参与扫描;类型名、声明名(含 interface 里的运算符名)、注释等 atom 整体是文字。
    • " 与反引号之间是文字;// 之后到行末是文字;-> 是箭头;深度大于 0 时的 , 分隔元素。
    • -
    • < 前面(跳过空白)的 atom 是 .type(_, .declaration)、.function(.declaration) 或 .member(.declaration) 时,这个列表是泛型参数子句,否则是泛型参数列表。
    • +
    • < 前面(跳过空白)的 atom 是 .type(_, .declaration)、.function(.declaration) 或 .member(.declaration) 时,这个列表是泛型参数子句,否则是泛型参数列表。闭括号读到时再看一次:有一项在自己这一层写着 where、: (冒号后带空格)或 ==,是 dump 写在类型名后面的泛型签名(_ConditionalContent< where A: P, B: Q>),也按参数子句处理。
    • 括号不配对或未关闭返回 nil,整行原样保留;dump 里的 static func < infix(…) 就走这条路。
    @@ -404,7 +407,8 @@

    详细设计

  • 不在任何泛型参数列表里面的泛型参数列表,> 的内容列号大于 maximumLineWidth 时,标为长类型的根。
  • 自下而上:长类型内部元素数不少于 2 的泛型参数列表拆;任何列表有元素是多行时拆;其余不拆。
  • 拆开的列表:开括号后插入 \n 与 L + 4k 个空格;, 换成 , 再插入换行与缩进;闭括号前插入 \n 与 L + 4(k − 1) 个空格。
  • -
  • 插入的 atom 都是 .standard,identifier 取前一个括号或逗号 atom 的 identifier,region 不会被切断。
  • +
  • 插入的 atom 都是 .standard:开括号与逗号之后的换行和缩进取那个开括号或逗号的 identifier,闭括号之前的取闭括号的 identifier,region 不会被切断。
  • +
  • 有一行被改时,结果按 atom 一个元素重建,不保留输入的元素边界;没有行被改时直接返回输入本身。
  • 空列表 () 从不拆。
  • + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

    +

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

    +
    + +
    +

    要你定

    +
    +

    批准后开工

    +
      +
    1. 批准这份提案、按落地步骤开始实现?
    2. +
    +
    +
    +

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

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

    方案

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

    做不到的

    +

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

    +
    +

    非目标

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

    架构图

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

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

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

    改动地图

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

    详细设计

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

    调研

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

    替代方案

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

    影响

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

    落地步骤

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

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

    +
    + +
    +

    决策日志

    +
    + 4 条,最近一条:宽度不计缩进 +
    +
    + + + + + + + + +
    日期变更说明
    2026-11-21Created as DraftRuntimeViewer 里 SwiftUI 视图的 typealias Body 印成一行几千个字符,看不出泛型的层级,需要像展开括号一样按层拆行。
    2026-11-21规则选定放得下的类型不动,放不下的类型整个按 TypeAliasFormatter 的结构规则拆;适用于所有类型位置;元组与函数类型的括号同样处理。
    2026-11-21接入方式做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置项。
    2026-11-21宽度不计缩进同一个声明在任何嵌套深度都拆得一样,marksNestedDefinitions 的契约不受影响。
    +
    +
    +
    +
    + +
    +

    @@ -486,7 +490,7 @@

    落地步骤

    决策日志

    - 4 条,最近一条:宽度不计缩进 + 10 条,最近一条:尖括号里写着要求的是泛型签名
    @@ -496,6 +500,12 @@

    决策日志

    + + + + + +
    2026-11-21规则选定放得下的类型不动,放不下的类型整个按 TypeAliasFormatter 的结构规则拆;适用于所有类型位置;元组与函数类型的括号同样处理。
    2026-11-21接入方式做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置项。
    2026-11-21宽度不计缩进同一个声明在任何嵌套深度都拆得一样,marksNestedDefinitions 的契约不受影响。
    2026-11-21Accepted用户批准,开始实现。功能分支 feature/multiline-type-formatting,从 next 切出。
    2026-11-21闭括号前的换行取闭括号的 identifier闭括号前面紧挨的常是带类型引用 identifier 的类型名,换行不该算进那个引用。
    2026-11-21不保留元素边界元素边界没有公开读取接口;format 用于打印完成的结果,没有行被改时返回输入本身。
    2026-11-21嵌套定义契约测试并入现有套件给 NestedDefinitionRegionContractTests 加格式化变体,复用整套比较;宽度取 30 列,fixture 的长泛型类型不多。
    2026-11-21调用方直接依赖 SwiftDeclarationRenderingKit 不重新导出模块;swift-section 与 SwiftSectionKitTests 各加一条依赖,Tuist 命令行工程同步。
    2026-11-21尖括号里写着要求的是泛型签名对系统 SwiftUI 跑 dump 时发现 _ConditionalContent< where A: P, B: Q> 被当成两个参数拆开;补规则并先写了变红的测试。
    diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.md b/Documentations/Evolutions/draft-multiline-type-formatting.md index 3965e76c..d34fdbf9 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.md +++ b/Documentations/Evolutions/draft-multiline-type-formatting.md @@ -385,8 +385,8 @@ extension MultilineTypeFormatting { - 行为:`usageMistakesAreValidationErrors`(只给宽度、宽度不是正数,两个子命令都是退出码 64) - 行为:`helpNamesTheDefaultWidth` - 行为:插件 skill 里出现的每个 flag 都存在于对应子命令的 `--help`(逐个核对过);`claude plugin validate` 两项通过 -7. **文档** —— 改动地图第 14、15、16 行 - - 行为:文档索引、账本、术语表、模块清单与代码一致 +7. **文档**(已完成) —— 改动地图第 14、15、16 行 + - 行为:文档索引、账本、术语表、模块清单与代码一致;`SwiftSectionKit_zh.md` 与英文版同步 验证:每步 `swift build` 通过、本步新测试通过;收尾跑 `swift test --skip IntegrationTests` 全量。打印器不改、默认关闭,渲染 A/B 不适用(照 `SystemFrameworkRenderingVerification.md` 的判据,它针对改动打印、索引或读取器的重构),但会对一份真实 SwiftUI interface 打开格式化,记录 `format` 的耗时与输出行数,作为性能与效果的留档。 @@ -409,3 +409,5 @@ extension MultilineTypeFormatting { | 2026-11-21 | 嵌套定义契约测试并入现有套件 | 改动地图原计划新建 `MultilineTypeFormattingNestedDefinitionTests.swift`;改为给 `NestedDefinitionRegionContractTests` 加一个格式化变体,直接复用它对文字、span、identifier 与三种 region 的整套比较。宽度取 30 列:fixture 的长泛型类型不多(主要是 `GenericFieldLayout` 各嵌套类型的字段),40 列下只有 4 个根类型有改动,30 列下新增约一百行。 | | 2026-11-21 | 调用方直接依赖 `SwiftDeclarationRendering` | `SwiftSectionKit` 不重新导出任何模块,它的公开字段类型 `MultilineTypeFormatting` 由调用方自己导入:`swift-section` 与 `SwiftSectionKitTests` 各加一条直接依赖,Tuist 的命令行工程同步加上。不为一个类型在 Kit 里开 `@_exported`,与 Kit 现有字段(`Transformer.SwiftConfiguration` 等)的做法一致。 | | 2026-11-21 | 尖括号里写着要求的是泛型签名 | 对系统 SwiftUI 跑 `dump --multiline-types` 时发现:dump 把受约束扩展的上下文印成 `_ConditionalContent< where A: P, B: Q>`,这个 `<…>` 跟在类型名后面,被当成两个泛型参数拆开了。规则补一条:`<…>` 里有一项在自己这一层写着 `where`、`A: P`(冒号后带空格)或 `==`,就是泛型签名,按泛型参数子句处理(只在元素已是多行时才拆)。模块选择器的 `::` 与 dump 的 `(extension in M):` 前缀冒号后都没有空格,不受影响。先写了变红的测试 `angleBracketsHoldingRequirementsAreAGenericSignature`、`genericSignatureIsNotBrokenForItsRequirements`,修复后通过;另加 `moduleSelectorsAndExtensionContextsLeaveAnArgumentList`、`moduleSelectorsStillBreakAsArguments` 守住不误判。 | +| 2026-11-21 | 不跑全量,以定向测试交付 | 机器负载高,全量两次开跑都停掉了;`swift test` 没法把进程限制在指定核数(`SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH` 只限同时跑几个测试,测试内部建索引照样铺满全部核)。用户决定以定向测试交付:本提案涉及的八个套件都通过。功能默认关闭、打印器未改,关闭时的输出由构造保证不变。 | +| 2026-11-21 | 实现完成,待用户看过后收尾 | 文档判断:不另写实现说明,规则与取舍都在本提案和 `MultilineTypeFormatting` 的文档注释里;新术语 long type / multiline type formatting 已登记进 `Documentations/Glossary.md`;`SwiftSectionKit.md`(中英)、`Modules/SwiftSectionKit.md`、agent 插件 skill、`AGENTS.md` 模块清单、演进账本同批更新。RuntimeViewer 的开关与调用是它自己的后续改动。 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 03ace4ec..9d933ef6 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -252,6 +252,15 @@ sweep 覆盖范围之外的名字走的旁路:demangle 后 intern 进 `Storage - **主要出现在**:`Sources/Output/SwiftInterface/EvolutionMarking.swift`、`EvolutionAnnotationIndex.swift` - **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md)、[提案 0060](Evolutions/0060-evolution-interface-available-annotations.md)(`@available` 属性) +### long type(长类型)与 multiline type formatting(长类型拆行,`MultilineTypeFormatting`) + +**long type** 指一行里放不下的类型:一个不在其它泛型参数列表里面的泛型参数列表(类型的最外层 `<…>`),它的闭括号 `>` 落在第 `maximumLineWidth` 列之后。列号从这一行的缩进之后数起,所以同一个声明嵌得多深都算得一样。只有泛型参数列表会让一个类型成为 long type:行之所以长是因为参数多或行尾注释时,这一行不算。 + +**multiline type formatting** 是把打印好的源码里每个 long type 按括号结构拆成多行的那一步:long type 内部,有两个及以上参数的泛型参数列表每个参数一行;任何列表(单参数泛型、元组、函数类型与声明的参数列表、`[…]`)在某个元素已是多行时才拆。它在打印完成之后、交出产物之前做一次,只加换行和缩进,打印器本身不知道它的存在。规则借自 TypeAliasFormatter,加了行宽这道闸门。 + +- **主要出现在**:`Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting*.swift`;`InterfaceRequest` / `DumpRequest` 的 `multilineTypeFormatting`;CLI `--multiline-types` / `--maximum-line-width` +- **延伸阅读**:[提案 multiline-type-formatting](Evolutions/draft-multiline-type-formatting.md) + ### macro folding(宏展开的折叠,folded form / expanded form) interface 把一个 attached macro 生成的东西收回成源码里的写法:`@Observable` 展开的类印成 `@Observation.Observable` 加普通的 `var x: T`,这是**折叠形态**;`expandsMacros` 打开时照二进制原样印出 registrar、存储 `_x`、computed `x`、生成的方法与 conformance,这是**展开形态**。二进制不记宏本身,只记它生成的东西,所以「这个类用了宏」是从生成物推断出来的(`TypeDefinition.attachedMacros`)。折叠只发生在单版本 interface;模型、dump、diff、evolution 始终是展开形态,dump 另在类头上写出宏的名字。 diff --git a/Documentations/Internal/Modules/SwiftSectionKit.md b/Documentations/Internal/Modules/SwiftSectionKit.md index ed27ddca..180765d7 100644 --- a/Documentations/Internal/Modules/SwiftSectionKit.md +++ b/Documentations/Internal/Modules/SwiftSectionKit.md @@ -67,6 +67,7 @@ SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命 - **请求是 `Equatable` 的值**,`run` 的依赖(输出端、环境)是参数而不是字段。包装层的测试靠这一点:解析 flag → `makeRequest()` → 与期望请求比较(`CommandRequestMappingTests`)。 - **库只报告,不退出**:`ABIDiffOutcome.hasBreakingChange` 等结论由包装层对照 `--fail-on-breaking` 决定是否 `throw ExitCode.failure`。`diff --interface` 只在 `includesBreakingChangeVerdict` 时才额外算一遍 change-list diff,和原来「只有 CI 闸门需要它」的取舍一致。 - **私有声明的源文件**(`emitsPrivateDeclarationSourceFiles`,提案 [0074-private-declaration-source-files](../../Evolutions/0074-private-declaration-source-files.md)):两个请求共用 `PrivateDeclarationSourceFileRecovery`,先对整个镜像批量反推一次,再把 index 交给 dumper(`DeclarationRenderConfiguration.privateDeclarationSourceFileProvider`)或打印器(`setPrivateDeclarationSourceFileProvider(_:)`)。`interface` 用 builder 自己的索引器,在 `prepare()` 之后装上。`dump` 本来不建索引器,打开时另建一个只为让 index 读名字,并且**让它活到 dump 结束**:索引器最后一次释放会回收它 `prepare()` 建的缓存,其中就有 dump 读每一行成员的符号索引,提前放掉的话 dump 后半段要重建一遍。关着时两条路径都不建 index、不多 `prepare()`。 +- **长类型拆行**(`multilineTypeFormatting`,提案 [multiline-type-formatting](../../Evolutions/draft-multiline-type-formatting.md)):两个请求都只在出口调用一次 `MultilineTypeFormatting.format(_:)`——`InterfaceRequest.run` 在 `printRoot()` 之后、写文件或交给 output 之前,`DumpSession.dump` 在拿到一个顶层声明之后;打印器与 `DumperConfiguration` 都不知道这件事。dump 的头部注释块(`InterfaceHeaderBlock`)不经过它。`MultilineTypeFormatting` 来自 `SwiftDeclarationRendering`,本模块不重新导出它:`swift-section` 与 `SwiftSectionKitTests` 各自直接依赖那个模块。默认 `nil`,产物逐字节不变。测试在 `MultilineTypeFormattingRequestTests`:打开时的产物必须等于把关闭时的产物格式化一遍。 - **命令行拼写留在包装层**:模板名还是字面模板(`TransformerTemplateResolver`)、`--transformer-config` 的 JSON 文件、逗号分隔的 `--labels` / `--sections`、`--c-type-replacement` 的 `a=b`、demangle 的二十多个覆盖开关,都由包装层解释成库的值类型(`Transformer.SwiftConfiguration`、`[ObjCPrimitiveTypePattern: String]`、`DemangleOptions`…)再交给请求。代价见下一节的偏差 2。 ## 5. 与拆分前的行为差异(只有两类) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index d27a307e..29d96ae0 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3501,6 +3501,24 @@ - 没跑全量,也没做渲染 A/B:只改了交叉引用索引存偏移的起点,不碰 demangle、打印、索引器与读取层。 - **对应版本**:未发布(0.26.0 之后)。 +## 2026-11-21 · 长类型按括号拆成多行(`MultilineTypeFormatting`) + +- **时间段**:2026-11-21,`feature/multiline-type-formatting`,在 JHs-Mac-Studio-Ultra 上写与验证。 +- **动机**:RuntimeViewer 里 SwiftUI 视图的 `typealias Body = SwiftUI.ModifiedContent<…>` 印成一行几千个字符,看不出泛型的层级;dump、interface 的长成员签名同样如此。社区工具 TypeAliasFormatter 能按括号排版,但只吃纯文本,丢掉着色、链接与 region。 +- **关键决策**: + - 规则由用户在澄清提问里选定:一行放得下的类型不动;放不下的类型(最外层泛型参数列表的 `>` 落在行宽之后)整个照 TypeAliasFormatter 的结构规则拆——多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表、`[…]` 只在里面有拆开的部分时才拆。适用于所有类型位置。 + - 做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置:类型来自两套打印器,公开打印入口互相调用,嵌套定义契约只允许缩进随层级变化。 + - 行宽不计行首缩进,同一个声明在任何嵌套深度拆得一样,`marksNestedDefinitions` 的契约格式化后仍成立;插入的换行与缩进沿用相邻括号或逗号的 identifier,region 不会被切断。 + - 括号只在 `.standard` 组件里认,字符串、反引号、行注释、`->` 不算;括号不配对的行(dump 的 `< infix` 运算符)原样保留。`<…>` 里写着 `where`、`A: P` 或 `==` 的是泛型签名,不按参数拆——这条是对系统 SwiftUI 实测时发现后补的。 +- **落地模块**:`SwiftDeclarationRendering`(`MultilineTypeFormatting` 与三个 internal 扩展)、`SwiftSectionKit`(`InterfaceRequest` / `DumpRequest` 的 `multilineTypeFormatting`)、`swift-section`(`MultilineTypeOptionGroup`:`--multiline-types`、`--maximum-line-width`)、`Package.swift` 与 Tuist 命令行工程的依赖。 +- **文档**:提案 [multiline-type-formatting](../Evolutions/draft-multiline-type-formatting.md);术语表新增 long type / multiline type formatting;`SwiftSectionKit.md`(中英两份)、[Modules/SwiftSectionKit.md](Modules/SwiftSectionKit.md)、agent 插件的 swift-section skill、`AGENTS.md` 的模块清单。不另写实现说明:规则与取舍都在提案和类型的文档注释里。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 26.6。 + - 定向测试全过:`MultilineTypeFormattingTests`、`MultilineTypeFormattingPreservationTests`、`NestedDefinitionRegionContractTests`(含新变体,进程内与文件两种读取器)、`MultilineTypeFormattingRequestTests`、`DumpAndInterfaceRequestTests`、`MultilineTypesFlagTests`、`CommandRequestMappingTests`、`CommandLineStreamWriteScanTests`。 + - 没跑全量:机器负载高,两次开跑都停掉了,用户决定以定向测试交付。`swift test` 没法把进程限制在指定核数——`SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH` 只限同时跑几个测试,测试内部建索引照样铺满全部核。功能默认关闭、打印器未改,关闭时的输出由构造保证不变;渲染 A/B 不适用。 + - 对系统 SwiftUI 实测(debug 构建的 CLI):`dump --sections types` 23.0 秒对 23.3 秒,65,207 行变 77,333 行;`interface` 124,716 行变 145,625 行,CPU 时间多约 4 秒(这一组与别的测试同时跑,墙钟不作数)。实测时发现并修掉了 dump 泛型签名被误拆的问题。 + - `swift-section` 实跑:`--multiline-types --maximum-line-width 60` 拆开 fixture 的长字段;只给宽度时退出码 64。`claude plugin validate` 两项通过;Codex 的 `validate_plugin.py` 本机没有,未跑。 +- **对应版本**:未发布(0.26.0 之后)。RuntimeViewer 的开关与调用是它自己的后续改动。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/SwiftSectionKit.md b/Documentations/SwiftSectionKit.md index b12aef19..ab1e8353 100644 --- a/Documentations/SwiftSectionKit.md +++ b/Documentations/SwiftSectionKit.md @@ -64,6 +64,17 @@ if outcome.hasBreakingChange == true { Options that exclude each other are one enum rather than several flags: an `ABIDiffRequest.Report` is a change list, a summary, JSON or an annotated interface, never two at once. Where the command line has a flag that implies another (`--emit-expanded-field-offsets` implies field offsets), the request has one value covering both (`FieldOffsetComments.expanded`). +`DumpRequest` and `InterfaceRequest` take `multilineTypeFormatting: MultilineTypeFormatting?` (`--multiline-types` and `--maximum-line-width`). With it, a type that runs past the line width — a SwiftUI view's `Body` above all — is broken over several lines at its brackets before the product is handed over: the whole interface at once, the dump one declaration at a time. `MultilineTypeFormatting` lives in `SwiftDeclarationRendering`; import that module to make one. A host that prints declarations itself formats them the same way, by calling `format(_:)` on a finished print: + +```swift +import SwiftDeclarationRendering + +let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +let interface = formatting.format(try await printer.printTypeDefinition(definition)) +``` + +Formatting only adds line breaks and indentation; text, semantic types, identifiers and every visibility, definition and annotation region stay as printed, and a nested definition taken out of a formatted parent reads as that definition printed and formatted on its own. + A binary is named by a `MachOSource` — a thin or fat file, an image inside a dyld shared cache file, or an image of the running system's cache. `refs` and `symbolicate` read machine code across many images, so they take a `CrossReferenceInput` instead: a set of files read together, a whole cache file, or the whole running system's cache, read from its files. Their results carry `CrossReferenceAnalysis` types (`CodeReference`, `AddressSymbolication`); import that module to inspect them. `snapshot`, `diff` and `evolution` take `SnapshotSource.path`, which may name a binary or a snapshot document; the file's first non-whitespace byte tells them apart, as on the command line. ## The output contract diff --git a/Documentations/SwiftSectionKit_zh.md b/Documentations/SwiftSectionKit_zh.md index 6a5905f1..cc3049c7 100644 --- a/Documentations/SwiftSectionKit_zh.md +++ b/Documentations/SwiftSectionKit_zh.md @@ -62,6 +62,17 @@ if outcome.hasBreakingChange == true { 互斥的选项是一个 enum 而不是几个开关:`ABIDiffRequest.Report` 只能是 change list、summary、JSON、annotated interface 之一,不会同时是两个。命令行上一个 flag 隐含另一个的(`--emit-expanded-field-offsets` 隐含字段偏移),请求里是一个值同时表达两者(`FieldOffsetComments.expanded`)。 +`DumpRequest` 与 `InterfaceRequest` 收 `multilineTypeFormatting: MultilineTypeFormatting?`(命令行的 `--multiline-types` 与 `--maximum-line-width`)。给了它,超过行宽的类型——首先是 SwiftUI 视图的 `Body`——在交出产物之前按括号拆成多行:interface 整份做一次,dump 每个声明做一次。`MultilineTypeFormatting` 在 `SwiftDeclarationRendering` 里,构造它要导入这个模块。自己打印声明的宿主用同样的办法,对打印完成的结果调用 `format(_:)`: + +```swift +import SwiftDeclarationRendering + +let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +let interface = formatting.format(try await printer.printTypeDefinition(definition)) +``` + +格式化只加换行和缩进;文字、semantic type、identifier 以及各种 visibility / definition / annotation region 都和打印时一样,从格式化过的父定义里取出的嵌套定义,等于这个定义单独打印再格式化。 + 二进制用 `MachOSource` 指明:瘦或胖的文件、dyld shared cache 文件里的一个镜像、或运行系统 cache 里的一个镜像。`snapshot`、`diff`、`evolution` 收 `SnapshotSource.path`,它可以指向二进制,也可以指向 snapshot 文档;和命令行一样,按文件第一个非空白字节区分。 ## 输出端契约 From 64a3336358671245533b04faffb13a469f14a6be Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 11:07:21 +0800 Subject: [PATCH 056/175] test: build the test support on MachOKitExtensions' MachOFixtureSupport and MachOTestingSupport --- .github/workflows/macOS.yml | 3 + .../draft-shared-macho-testing-support.md | 1 + Package.swift | 28 +- .../DyldSharedCachePath+NamedCaches.swift | 17 + .../DyldSharedCachePath.swift | 56 --- .../SwiftSectionFixtureSupport/Exports.swift | 7 + .../Extensions.swift | 57 --- .../InProcess/InProcessMetadataPicker.swift | 27 +- .../MachOFileName+SymbolTests.swift | 26 + .../MachOFileName.swift | 27 -- .../MachOImageName+SymbolTests.swift | 9 + .../MachOImageName.swift | 32 -- .../XcodeMachOFileName.swift | 459 ------------------ .../DyldCacheTests.swift | 37 -- .../ExclusiveImageAccess+FixtureNames.swift | 36 ++ .../ExclusiveImageAccess.swift | 129 ----- .../SwiftSectionTestingSupport/Exports.swift | 10 + ...ardingMachOReader+MachOReaderWrapper.swift | 1 + .../ForwardingMachOReader.swift | 19 +- .../GenericSpecializationFixture.swift | 2 +- .../MachOFileTests.swift | 26 - .../MachOImageTests.swift | 16 - .../MachOSwiftSectionFixtureTests.swift | 163 +------ .../ProcessMemory.swift | 79 --- .../TestActor.swift | 6 - .../XcodeMachOFileTests.swift | 25 - .../DyldCacheSymbolSimpleTests.swift | 2 +- .../ObjCDiffing/ObjCAPIEvolutionTests.swift | 4 +- .../SwiftDiffing/ABIEvolutionTests.swift | 2 +- .../SwiftEvolutionInterfaceBuilderTests.swift | 4 +- .../FileMappingTests.swift | 4 +- .../ReadingContextRelocationTests.swift | 2 +- .../StandaloneFileReadingTests.swift | 4 +- .../FinalKeywordICFRegressionTests.swift | 2 +- .../CacheRootDependencyLayoutTests.swift | 2 +- .../DyldSharedCachePathTests.swift | 23 +- .../ExclusiveImageAccessKeyTests.swift | 30 ++ .../ExclusiveImageAccessTests.swift | 89 ---- .../WrappedReaderSymbolTests.swift | 2 +- ...SimulatorRuntimeThunkResolutionTests.swift | 6 +- 40 files changed, 222 insertions(+), 1252 deletions(-) create mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift delete mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift create mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift delete mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift create mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift delete mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift create mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift delete mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift delete mode 100644 Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift create mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift create mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift delete mode 100644 Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift create mode 100644 Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift delete mode 100644 Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index b4157c4b..95c09b29 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -26,6 +26,9 @@ jobs: configuration: [debug, release] env: MACHO_SWIFT_SECTION_SILENT_TEST: 1 + # Quiets `.print()` of MachOKitExtensions' MachOFixtureSupport, which + # reads it at run time. + MACHO_TESTING_SILENT: 1 GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v4 diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index 1cb94eb1..b0203ff4 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -382,3 +382,4 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-21 | MKE 部分合入 MachOKitExtensions `main` 并推送,未发版 | 用户看过后收尾:测试支持的两个 product、MKE 测试改用它们、全部 `NSLock` 换成 `Mutex`、撤掉 Linux 与 `Sources/` 分组(MKE 0007)一起进了 `main`,最终代码上 MKE 全量测试通过。3.2.0 还没发;本包第 5、6 步等它发布后在本分支继续。 | | 2026-11-21 | 第 5 步的已知缺口:`FixtureCompiler` 还不能完全替代本包的 `CompiledFixture` | 本包 `Tests/CrossReferenceAnalysisTests/CompiledFixture.swift` 的 `build(libraryName:sources:compilerArguments:isExecutable:)` 能编可执行文件(`FileModeTests`、`FunctionStartOutsideTextTests` 两处用 `isExecutable: true`)、一次编多个源文件、按参数指定架构;MKE 3.1.0 之后的 `FixtureCompiler` 只把单个源字符串编成动态库。要么在发 3.2.0 之前给 `FixtureCompiler` 补可执行文件与多源文件,要么这几处在本包保留自己的辅助,待用户定。另:next 上新进的 `FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText` 用到 `CompiledFixture.build(…isExecutable:)` 与 `InstructionEncoding.branchWithLink(at:to:)`,第 5 步若搬走或改名它们,这条测试一起改,本分支合 next 时会遇到它。 | | 2026-11-21 | `FixtureCompiler` 补上可执行文件与多源文件,MKE 3.2.0 发布 | 用户选择发版前先补:新增 `executable(named:language:source:arguments:)`、两个收 `sourceFiles: [FixtureSourceFile]` 的重载,单段源码的写法不变;本包 `CompiledFixture.build` 的可执行文件、多源文件与指定架构(经参数 `-arch`)都能用它替代。`CompiledFixture.load` 的链接后改写、重新签名、再加载留在本包,在复制出的产物上做(共享编译器的产物是缓存,不能原地改)。MKE 全量测试通过,原始退出码 0;随后在 `main` 上打 3.2.0(附注 tag,同以往不建 Release 页面)。本包第 5、6 步可以开始。 | +| 2026-11-21 | 第 5 步第一部分:测试支持改接 MKE 3.2.0 | MKE 下限升到 3.2.0;两个 support target 依赖并 re-export `MachOFixtureSupport` / `MachOTestingSupport`,搬走的 12 个文件删除;SymbolTests 的文件名与镜像名、本包命名的 cache、按本包名字的 `ExclusiveImageAccess` 初始化留在本包作 extension。`ExclusiveImageAccess` 的 key 取镜像名(文件名取路径最后一段去扩展名),同一夹具按文件或按镜像声明仍互斥,新测试 `ExclusiveImageAccessKeyTests` 钉住这一点。`MachOSwiftSectionFixtureTests` 改为 `MachOFixtureTests` 的子类,读不到夹具时把 `MachOFixtureError` 转成带重编说明的 `FixtureLoadError`。MKE 也有公开的 `DeclaredWrapper` / `UndeclaredWrapper`,与本包同名标记冲突,`ForwardingMachOReader` 改用 MKE 的标记(读取器本身留在本包)。CI 加 `MACHO_TESTING_SILENT: 1`。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0(基线 2,916:删 4 个搬走的测试,加 2 个);IntegrationTests 与可执行文件都编过。 | diff --git a/Package.swift b/Package.swift index 8d2af964..7b098c09 100644 --- a/Package.swift +++ b/Package.swift @@ -175,7 +175,9 @@ extension Package.Dependency { // 3.0.0 leaves Swift symbol names to this package: `SwiftSymbols` // defines `SymbolLanguage.swift` and registers it when the image // loads (proposal split-symbol-language). - from: "3.0.0", + // 3.2.0 ships the test support this package builds on: the + // `MachOFixtureSupport` and `MachOTestingSupport` products. + from: "3.2.0", ), ) @@ -361,6 +363,19 @@ extension Target.Dependency { name: "MachOFoundation", package: "MachOKitExtensions", ) + // The Swift-free half of the test support, shared with + // MachOKitExtensions' own tests since its 3.2.0: fixture names, opening + // caches and images, slice picking, the fixture compiler + // (`MachOFixtureSupport`, no Testing), and the trait and base classes on + // top of it (`MachOTestingSupport`). + static let MachOFixtureSupport = Target.Dependency.product( + name: "MachOFixtureSupport", + package: "MachOKitExtensions", + ) + static let MachOTestingSupport = Target.Dependency.product( + name: "MachOTestingSupport", + package: "MachOKitExtensions", + ) static let MachOKitMain = Target.Dependency.product( name: "MachOKit", package: "MachOKit", @@ -1042,11 +1057,14 @@ extension Target { /// Fixture-loading helpers, baseline generators, coverage scanners, and /// non-Testing-dependent code. Importable from non-test targets (e.g. /// `baseline-generator`) without dragging in `Testing.framework`. + /// Re-exports MachOKitExtensions' `MachOFixtureSupport`, which it adds + /// this package's fixture names and named caches to. static let SwiftSectionFixtureSupport = Target.target( name: "SwiftSectionFixtureSupport", dependencies: [ .product(.MachOKit), .product(.MachOFoundation), + .product(.MachOFixtureSupport), .target(.SwiftSymbols), .product(.MachOReading), .product(.MachOResolving), @@ -1066,8 +1084,11 @@ extension Target { swiftSettings: testSettings, ) - /// `swift-testing` base classes (`MachOFileTests`, `MachOImageTests`, - /// `DyldCacheTests`, `XcodeMachOFileTests`, `MachOSwiftSectionFixtureTests`). + /// `swift-testing` support: `MachOSwiftSectionFixtureTests` and the Swift + /// fixtures, on top of MachOKitExtensions' `MachOTestingSupport` (the + /// `MachOFileTests`, `MachOImageTests`, `DyldCacheTests`, + /// `XcodeMachOFileTests` and `MachOFixtureTests` base classes and + /// `ExclusiveImageAccess`), which it re-exports. /// Splitting this out from `SwiftSectionFixtureSupport` keeps `Testing.framework` /// out of the link line for non-test targets. static let SwiftSectionTestingSupport = Target.target( @@ -1080,6 +1101,7 @@ extension Target { .product(.MachOReading), .product(.MachOResolving), .target(.SwiftSectionFixtureSupport), + .product(.MachOTestingSupport), .target(.MachOSwiftSection), .target(.SwiftDeclaration), .target(.SwiftIndexing), diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift new file mode 100644 index 00000000..7898cac2 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift @@ -0,0 +1,17 @@ +import MachOFixtureSupport + +/// The caches this package's tests name, beside the running system's +/// (`current`) and the archived ones any version names (`macOS(_:)`, +/// `iOS(_:)`) that MachOKitExtensions provides. +extension DyldSharedCachePath { + package static let iOS_18_5 = DyldSharedCachePath(path: "/Volumes/Generic/iOS Systems/22F76__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "18.5") + package static let iOS_26_1 = DyldSharedCachePath(path: "/Volumes/Generic/iOS Systems/23B85__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "26.1") + package static let macOS_15_5 = macOS("15.5") + package static let macOS_26_5_1 = macOS("26.5.1") + package static let macOS_26_5_2 = macOS("26.5.2") + package static let macOS_27_0 = macOS("27.0") + /// From iOS 27 beta 3 on a simulator runtime ships its frameworks in a + /// cache of its own instead of as files under `RuntimeRoot`. The runtime's + /// volume is named after its build, so no version alone spells this path. + package static let iOS_27_0_Simulator = DyldSharedCachePath(path: "/Library/Developer/CoreSimulator/Volumes/iOS_24A434/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 27.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Caches/com.apple.dyld/dyld_sim_shared_cache_arm64", versionLabel: "27.0") +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift deleted file mode 100644 index a9b811fb..00000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift +++ /dev/null @@ -1,56 +0,0 @@ -/// A dyld shared cache file the tests open, and what a version axis calls it. -/// -/// A struct with static members rather than an enum, so that besides the -/// caches named below any archived cache can be named by its version: -/// `.macOS("26.6")`. Not `RawRepresentable`: every value carries a label, -/// which a path alone does not give. -package struct DyldSharedCachePath: Hashable, Sendable { - package let rawValue: String - - /// What a version axis calls this cache, such as the evolution dumps' - /// labels: the version an archived cache was named by, or the label a - /// named cache states. Not necessarily a system version — `current` is - /// labeled `current`. - package let versionLabel: String - - package init(rawValue: String, versionLabel: String) { - self.rawValue = rawValue - self.versionLabel = versionLabel - } - - /// The archived macOS cache of `version`, labeled `version`: - /// `/Volumes/DyldSharedCaches/macOS//dyld_shared_cache_arm64e`. - /// - /// `version` is the directory name on the volume (`26.5.2`, - /// `14.0(Internal)`). Whether that directory holds a cache is the - /// caller's to check; some hold only exported headers. - package static func macOS(_ version: String) -> DyldSharedCachePath { - archived(platformDirectoryName: "macOS", version: version) - } - - /// The archived iOS device cache of `version`, labeled `version`: - /// `/Volumes/DyldSharedCaches/iOS//dyld_shared_cache_arm64e`. - package static func iOS(_ version: String) -> DyldSharedCachePath { - archived(platformDirectoryName: "iOS", version: version) - } - - private static func archived(platformDirectoryName: String, version: String) -> DyldSharedCachePath { - DyldSharedCachePath( - rawValue: "/Volumes/DyldSharedCaches/\(platformDirectoryName)/\(version)/dyld_shared_cache_arm64e", - versionLabel: version - ) - } - - /// The running system's cache. - package static let current = DyldSharedCachePath(rawValue: "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e", versionLabel: "current") - package static let iOS_18_5 = DyldSharedCachePath(rawValue: "/Volumes/Generic/iOS Systems/22F76__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "18.5") - package static let iOS_26_1 = DyldSharedCachePath(rawValue: "/Volumes/Generic/iOS Systems/23B85__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "26.1") - package static let macOS_15_5 = macOS("15.5") - package static let macOS_26_5_1 = macOS("26.5.1") - package static let macOS_26_5_2 = macOS("26.5.2") - package static let macOS_27_0 = macOS("27.0") - /// From iOS 27 beta 3 on a simulator runtime ships its frameworks in a - /// cache of its own instead of as files under `RuntimeRoot`. The runtime's - /// volume is named after its build, so no version alone spells this path. - package static let iOS_27_0_Simulator = DyldSharedCachePath(rawValue: "/Library/Developer/CoreSimulator/Volumes/iOS_24A434/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 27.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Caches/com.apple.dyld/dyld_sim_shared_cache_arm64", versionLabel: "27.0") -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift new file mode 100644 index 00000000..d1b113a0 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift @@ -0,0 +1,7 @@ +// The Swift-free test support shared with MachOKitExtensions: fixture names, +// opening caches and images, slice picking, the fixture compiler and +// `.print()`. Re-exported so that a test importing this module reaches it +// without an import of its own; this module adds the package's own fixture +// names and named caches to it (`MachOFileName+SymbolTests.swift`, +// `MachOImageName+SymbolTests.swift`, `DyldSharedCachePath+NamedCaches.swift`). +@_exported import MachOFixtureSupport diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift deleted file mode 100644 index 063c3eca..00000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift +++ /dev/null @@ -1,57 +0,0 @@ -import Foundation -import MachOKit -import UniformTypeIdentifiers -import MachOKitExtensions - -package func loadFromFile(named: MachOFileName) throws -> File { - let url: URL - let filePath = named.rawValue - if filePath.starts(with: "../") || filePath.starts(with: "./") { - url = URL(fileURLWithPath: filePath, relativeTo: URL(fileURLWithPath: #filePath)) - } else { - url = URL(fileURLWithPath: filePath) - } - return try File.loadFromFile(url: url) -} - -extension MachOImage { - package init?(named: MachOImageName) { - self.init(name: named.rawValue) - } -} - -extension FullDyldCache { - package convenience init(path: DyldSharedCachePath) throws { - try self.init(url: URL(fileURLWithPath: path.rawValue)) - } - - package func machOFile(named: MachOImageName) -> MachOFile? { - machOFile(by: .name(named.rawValue)) - } -} - -extension DyldCache { - package convenience init(path: DyldSharedCachePath) throws { - try self.init(url: URL(fileURLWithPath: path.rawValue)) - } - - package func machOFile(named: MachOImageName) -> MachOFile? { - machOFile(by: .name(named.rawValue)) - } -} - -extension CustomStringConvertible { - package func print() { - #if !SILENT_TEST - Swift.print(self) - #endif - } -} - -extension Error { - package func print() { - #if !SILENT_TEST - Swift.print(self) - #endif - } -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift index 3cf8bb1c..1f63e106 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift @@ -222,33 +222,14 @@ extension InProcessMetadataPicker { /// Idempotently dlopens `SymbolTestsCore.framework` so that subsequent /// `dlsym(RTLD_NOW, ...)` calls can locate fixture-binary symbols. - /// Resolves the framework path relative to this source file, mirroring - /// `MachOSwiftSectionFixtureTests.dlopenOnce` so the test process and - /// the standalone `baseline-generator` process behave identically. + /// Loads the file `MachOFileName.SymbolTestsCore` names, the one + /// `MachOSwiftSectionFixtureTests` loads, so the test process and the + /// standalone `baseline-generator` process behave identically. private static func ensureFixtureLoaded() throws { _ = dlopenOnce } private static let dlopenOnce: Void = { - let absolute = resolveFixturePath(MachOImageName.SymbolTestsCore.rawValue) - _ = absolute.withCString { dlopen($0, RTLD_LAZY) } + _ = MachOFileName.SymbolTestsCore.path.withCString { dlopen($0, RTLD_LAZY) } }() - - /// Resolve a relative `MachOImageName` path (rooted at the package-relative - /// `../../../Tests/...` convention used by `loadFromFile`) to an absolute path. - /// - /// Caveat: `MachOImageName.SymbolTestsCore.rawValue` is rooted as if the - /// caller lives in `Sources///Foo.swift`, i.e. exactly three - /// `../` hops to reach the package root. This file lives one level deeper - /// in `Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/`, so we anchor - /// against `Sources/TestSupport/SwiftSectionFixtureSupport/` (one path component up - /// from `#filePath`'s parent) to make the existing `../../../...` rawValue - /// resolve correctly. - private static func resolveFixturePath(_ relativePath: String) -> String { - if relativePath.hasPrefix("/") { return relativePath } - let parentOfThisFile = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - let oneLevelUp = parentOfThisFile.deletingLastPathComponent() - let url = URL(fileURLWithPath: relativePath, relativeTo: oneLevelUp) - return url.standardizedFileURL.path - } } diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift new file mode 100644 index 00000000..7489a8d4 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift @@ -0,0 +1,26 @@ +import Foundation +import MachOFixtureSupport + +extension MachOFileName { + /// The package root, which the SymbolTests fixtures are built under. + /// + /// Anchored at this file, `Sources/TestSupport/SwiftSectionFixtureSupport/`, + /// so a path relative to it climbs three levels to reach the root (see + /// `AGENTS.md` on `Sources/` grouping and `#filePath`). + private static let packageRootAnchor = URL(fileURLWithPath: #filePath) + + private static func symbolTestsProduct(_ productName: String) -> MachOFileName { + MachOFileName( + path: "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/\(productName).framework/Versions/A/\(productName)", + relativeTo: packageRootAnchor + ) + } + + package static let SymbolTests = symbolTestsProduct("SymbolTests") + package static let SymbolTestsCore = symbolTestsProduct("SymbolTestsCore") + /// SymbolTestsCore's resilient-parent dependency. Kept OUT of the shared + /// suites deliberately: `PerImageCacheEvictionTests` needs an image no + /// concurrently-running suite touches, so its cache-membership + /// assertions cannot race another suite's indexer lifecycle. + package static let SymbolTestsHelper = symbolTestsProduct("SymbolTestsHelper") +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift deleted file mode 100644 index 089a173a..00000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift +++ /dev/null @@ -1,27 +0,0 @@ -import Foundation - -package enum MachOFileName: String { - case iOS_18_5_Simulator_SwiftUI = "/Library/Developer/CoreSimulator/Volumes/iOS_22F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI" - case iOS_18_5_Simulator_SwiftUICore = "/Library/Developer/CoreSimulator/Volumes/iOS_22F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore" - case iOS_26_5_Simulator_SwiftUI = "/Library/Developer/CoreSimulator/Volumes/iOS_23F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 26.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI" - case iOS_26_5_Simulator_SwiftUICore = "/Library/Developer/CoreSimulator/Volumes/iOS_23F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 26.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore" - - case SourceEdit = "/Applications/SourceEdit.app" - case SourceEditorFromSourceEdit = "/Applications/SourceEdit.app/Contents/Frameworks/SourceEditor.framework" - case SourceEditorFromXcode = "/Applications/Xcode.app/Contents/SharedFrameworks/SourceEditor.framework" - - case Finder = "/System/Library/CoreServices/Finder.app" - case Dock = "/System/Library/CoreServices/Dock.app" - case iPhoneMirroring = "/System/Applications/iPhone Mirroring.app" - case ScreenContinuityUI = "/System/Applications/iPhone Mirroring.app/Contents/Frameworks/ScreenContinuityUI.framework" - case ControlCenter = "/System/Library/CoreServices/ControlCenter.app" - case Freeform = "/System/Applications/Freeform.app" - - case SymbolTests = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTests.framework/Versions/A/SymbolTests" - case SymbolTestsCore = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore" - /// SymbolTestsCore's resilient-parent dependency. Kept OUT of the shared - /// suites deliberately: `PerImageCacheEvictionTests` needs an image no - /// concurrently-running suite touches, so its cache-membership - /// assertions cannot race another suite's indexer lifecycle. - case SymbolTestsHelper = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsHelper.framework/Versions/A/SymbolTestsHelper" -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift new file mode 100644 index 00000000..a15931a9 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift @@ -0,0 +1,9 @@ +import MachOFixtureSupport + +extension MachOImageName { + /// The SymbolTests fixtures as this process knows them once loaded: the + /// bare image name `MachOImage(name:)` matches. Their files are the + /// `MachOFileName` members of the same names. + package static let SymbolTests: MachOImageName = "SymbolTests" + package static let SymbolTestsCore: MachOImageName = "SymbolTestsCore" +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift deleted file mode 100644 index b7a94897..00000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift +++ /dev/null @@ -1,32 +0,0 @@ -package enum MachOImageName: String { - case AppKit - case UIFoundation - case CollectionViewCore - case CoreAutoLayout - case SwiftUI - case SwiftUICore - case AttributeGraph - case Foundation - case Combine - case DeveloperToolsSupport - case CodableSwiftUI - case AAAFoundationSwift - case UIKitCore - case HomeKit - case Network - case ScreenContinuityServices - case Sharing - case FeatureFlags - case ScreenSharingKit - case DesignLibrary - case SFSymbols - case SnippetUI - case SiriOntology - - case SymbolTests = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTests.framework/Versions/A/SymbolTests" - case SymbolTestsCore = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore" - - var path: String { - "/\(rawValue)" - } -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift deleted file mode 100644 index 9fabfd89..00000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift +++ /dev/null @@ -1,459 +0,0 @@ -package enum XcodeMachOFileName: CaseIterable { - package enum Frameworks: String, CaseIterable { - case AssetCatalogAppleTVFoundation - case AssetCatalogAppleTVKit - case AssetCatalogCocoaTouchFoundation - case AssetCatalogCocoaTouchKit - case AssetCatalogFoundation - case AssetCatalogKit - case AssetCatalogVisionExtensions - case AssetCatalogVisionFoundation - case AssetCatalogVisionKit - case DVTNFASupport - case DebuggerFoundation - case DevToolsCore - case DevToolsSupport - case GameCenterResourcesAppStoreConnectClient - case GameCenterResourcesCore - case GameCenterResourcesCoreModels - case IBAutolayoutFoundation - case IBCocoaTouchToolFoundation - case IDEEditorGalleryPreviewSupport - case IDEEvaluationKit - case IDEFoundation - case IDEGameKitCommonEditor - case IDEGameKitEditor - case IDEGameKitInspectorCore - case IDEGameKitInspectorEditor - case IDEKit - case IDELanguageModelKit - case IDENoticesFoundation - case IDENoticesKit - case IDESettingsPanel - case IDESimulatorFoundation - case IDESourceEditorGalleryExhibit - case IDETrayKit - case SiriSSUKit - case SiriSSUKitModel - case Xcode3Core - case Xcode3UI - case libIDEApplicationLoader - case libLTO - case libclang - case libswiftDemangle - case libxcodebuildLoader - } - - package enum SharedFrameworks: String, CaseIterable { - case AccessibilityAudit - case AccessibilitySupport - case AppResourceGeneration - case AppThinning - case AssetRuntimeSupport - case AuthenticationAPI - case BuildServerProtocol - case ChooseIdentity - case CodeCompletionFoundation - case CodeCompletionKit - case CodeGenerationIntelligence - case CombineXPC - case CommonXcodeCloudAPI - case ContentDelivery - case ContentDeliveryServices - case CoreDocumentation - case CoreSymbolicationDT - case CreateMLSwiftProtobuf - case DNTDocumentationModel - case DNTDocumentationSupport - case DNTSourceKitSupport - case DNTTransformer - case DTDeviceKit - case DTDeviceKitBase - case DTDeviceServices - case DTGTGraph - case DTGTTimeline - case DTGanache - case DTGanacheBufferViewer - case DTGanacheImageProcessor - case DTGanacheImageViewer - case DTGanacheTensorViewer - case DTGraphKit - case DTMLOpGraph - case DTXConnectionServices - case DVTAnalytics - case DVTAnalyticsClient - case DVTAnalyticsKit - case DVTAnalyticsMetrics - case DVTAnalyticsMetricsClient - case DVTAppStoreConnect - case DVTCocoaAdditionsKit - case DVTCoreDeviceCore - case DVTCoreGlyphs - case DVTCrashLogFoundation - case DVTDeviceFoundation - case DVTDeviceKit - case DVTDeviceProvisioning - case DVTDocumentation - case DVTExplorableKit - case DVTFeedbackReporting - case DVTFoundation - case DVTITunesSoftware - case DVTITunesSoftwareServiceFoundation - case DVTIconKit - case DVTInstrumentsAnalysisCore - case DVTInstrumentsFoundation - case DVTInstrumentsUtilities - case DVTKeychain - case DVTKeychainService - case DVTKeychainUtilities - case DVTKit - case DVTLibraryKit - case DVTMacroFoundation - case DVTMarkup - case DVTPlaygroundCommunication - case DVTPlaygroundStubMacServices - case DVTPortal - case DVTProducts - case DVTProductsUI - case DVTServices - case DVTSmartSearch - case DVTSourceControl - case DVTSourceEditor - case DVTStructuredLayoutKit - case DVTSystemPrerequisites - case DVTSystemPrerequisitesUI - case DVTUserInterfaceKit - case DVTViewControllerKit - case DebugHierarchyFoundation - case DebugHierarchyKit - case DebugSymbolsDT - case DeltaFoundation - case DeltaKit - case EventsAPI - case GLTools - case GLToolsAnalysisEngine - case GLToolsCore - case GLToolsExpert - case GLToolsInterface - case GLToolsServices - case GLToolsShaderProfiler - case GPUTools - case GPUToolsCore - case GPUToolsDesktopFoundation - case GPUToolsMobileFoundation - case GPUToolsPlatform - case GPUToolsRenderer - case GPUToolsServices - case GPUToolsShaderProfiler - case GameToolsFoundation - case HexFiend - case IDEAnalyticsMetrics - case IDECodeGenerationIntelligence - case IDEDistribution - case IDEDistributionKit - case IDEMLCompilerCore - case IDEMLModelCore - case IDEMLModelEditorKit - case IDENotifications - case IDENotificationsKit - case IDEPlaygroundEditor - case IDEPlaygroundExecution - case IDEPlaygroundResultsFoundation - case IDEPlaygroundResultsKit - case IDEPlaygroundsFoundation - case IDEPlaygroundsKit - case IDEProducts - case IDEResultKit - case IndexStoreDB_CIndexStoreDB - case IndexStoreDB_Core - case IndexStoreDB_Database - case IndexStoreDB_Index - case IndexStoreDB_LLVMSupport - case IndexStoreDB_Support - case IndexStoreDatabase - case LLDB - case LLDBRPC - case LanguageServerProtocol - case LiveExecutionResultsFoundation - case LiveExecutionResultsHost - case Localization - case LoggingSupportHost - case MLCloudDeployment - case MLCloudDeploymentXPCServiceProtocol - case MLCore - case MLCoreKit - case MLDataSource - case MLDataSourceKit - case MLDocumentFormat - case MLEvaluation - case MLEvaluationKit - case MLExperiment - case MLExplorationKit - case MLFeature - case MLKnownObjectTracking - case MLModelCore - case MLModelFormatEditor - case MLModelKit - case MLPersistenceEngine - case MLPersistenceEntity - case MLRecipeCore - case MLRecipeExecutionController - case MLRecipeExecutionServiceProtocol - case MLShared - case MLSharedKit - case MLToolsCoreML - case MLTraceReport - case MTLTools - case MTLToolsAnalysisEngine - case MTLToolsServices - case MTLToolsShaderProfiler - case MallocStackLoggingDT - case ManagedBackgroundAssetsXcodeSupport - case MarkupSupport - case Notarization - case ODTDevTool - case OpenAPIRuntime - case OpenAPIURLSession - case PackedPaths - case PreviewsDeveloperTools - case PreviewsFoundationHost - case PreviewsMessagingHost - case PreviewsModel - case PreviewsPipeline - case PreviewsPlatforms - case PreviewsScenes - case PreviewsSyntax - case PreviewsUI - case PreviewsXROSMessaging - case PreviewsXROSServices - case PreviewsXcodeUI - case RealityKitAdditions - case RealityKitInspection - case RealityToolKit - case RealityToolsDeviceSupport - case RecountDT - case SourceEditor - case SourceEditorRegExSupport - case SourceEditorSwiftSupport - case SourceKit - case SourceKitLSPSupport - case SourceKitSupport - case SourceModel - case SourceModelSupport - case SpatialInspectorFoundation - case SpatialInspectorHost - case StatusAPI - case SwiftBasicFormat - case SwiftBuild - case SwiftDiagnostics - case SwiftIDEUtils - case SwiftOperators - case SwiftPM - case SwiftParser - case SwiftParserDiagnostics - case SwiftRefactor - case SwiftSyntax - case SwiftSyntaxBuilder - case SwiftSyntaxCShims - case SwiftSyntaxSupport - case SwiftUITracingSupportDT - case SymbolCache - case SymbolCacheIndexing - case SymbolCacheSupport - case SymbolicationDT - case TestResultsUI - case Testing - case USDLib_FormatLoaderProxy_Xcode - case UVTestSupport - case XCBuild - case XCResultKit - case XCServices - case XCSourceControl - case XCStringsParser - case XCTAutomationSupport - case XCTDaemonControl - case XCTDaemonControlMobileDevice - case XCTHarness - case XCTest - case XCTestCore - case XCTestSupport - case XCUIAutomation - case XCUnit - case XcodeCloudAPI - case XcodeCloudCombineAPI - case XcodeCloudDataSource - case XcodeCloudFoundation - case XcodeCloudKit - case XcodeCloudModels - case XcodeCloudUI - case _CodeCompletionFoundation - case _Testing_Foundation - case kperfdataDT - case ktraceDT - case libXCTestSwiftSupport - case llbuild - case swiftargumentparser_ArgumentParser - package var pathComponent: String { - "/SharedFrameworks/\(rawValue).framework" - } - } - - package enum Plugins: String, CaseIterable { - case AppShortcutsEditor - case AppShortcutsEditorUI - case DVTCorePlistStructDefs - case DVTFeedbackReportingDiagnosticExtension - case DVTiOSPlistStructDefs - case DebugHelperSupportUI - case DebuggerKit - case DebuggerLLDB - case DebuggerLLDBService - case DebuggerUI - case GPUDebugger - case GPUDebuggerGLSupport - case HexEditor - case IBBuildSupport - case IBCocoaBuildSupport - case IBExternalGeniusResults - case IDEAnalytics - case IDEAnalyticsKit - case IDEAnalyticsMetricsKit - case IDEAnalyticsMetricsNotifications - case IDEConsoleKit - case IDEDelta - case IDEDocViewer - case IDEDocumentation - case IDEDocumentationLivePreview - case IDEIODebugGaugesCore - case IDEIODebugGaugesUI - case IDEInstrumentsService - case IDEIntelligenceChat - case IDEIntelligenceFoundation - case IDEIntelligenceMessaging - case IDEIntelligenceModelService - case IDEIntentBuilderCore - case IDEIntentBuilderEditor - case IDEInterfaceBuilderCocoaIntegration - case IDEInterfaceBuilderCocoaTouchIntegration - case IDEInterfaceBuilderDFRSupport - case IDEInterfaceBuilderEditorDFRSupport - case IDEInterfaceBuilderKit - case IDEInterfaceBuilderiOSIntegration - case IDEInterfaceBuilderiOSMacIntegration - case IDELocalizationCatalogCore - case IDELocalizationCatalogEditor - case IDEMLCodeGeneratorPlugin - case IDEMLModelEditorPlugin - case IDEMemoryGraphDebugger - case IDEModelEditor - case IDEModelFoundation - case IDEPDFViewer - case IDEPegasusSourceEditor - case IDEPerformanceDebugger - case IDEPlaygroundSimulator - case IDEProductsUI - case IDEQuickHelp - case IDEQuickLookEditor - case IDERTFEditor - case IDESceneKitEditor - case IDESourceControlUI - case IDESourceEditor - case IDESpriteKitParticleEditor - case IDEStandardExecutionActionsCore - case IDEStandardExecutionActionsUI - case IDEStoreKitCore - case IDEStoreKitEditor - case IDESwiftPackageCore - case IDESwiftPackageUI - case IDETestPlanEditor - case IDETestResultsUI - case IDETestingPlatformSupport - case IDETimeline - case IDEXCBuildSupportCore - case IDEXCBuildSupportUI - case IDEXCStringsCommentGenerationSupport - case IDEXCStringsSupport - case IDEXCStringsSupportCore - case IDEiOSDebugger - case IDEiOSSupportCore - case IDEiPhoneSupport - case PlaygroundLiveExecution - case PlistEditor - case PreviewsIDEAPI - case PreviewsXcode - case PreviewsXcodeXROSSupport - case PreviewsXcodeXROSUI - case ProvisoningProfileQuicklookExtension - case RCPIDEFoundation - case RCPIDESupportCore - case RCPIDESupportUI - case ScriptingDefinitionEditor - case SpatialInspectorXcodePlugin - case XCCFeedbackReportingDiagnosticExtension - case XcodeCloud - } - - case frameworks(Frameworks) - case sharedFrameworks(SharedFrameworks) - case plugins(Plugins) - - package var contentsDirectory: String { - "/Applications/Xcode.app/Contents/" - } - - package var rawValue: String { - switch self { - case .frameworks(let framework): - return "Frameworks/" + framework.rawValue - case .sharedFrameworks(let framework): - return "SharedFrameworks/" + framework.rawValue - case .plugins(let plugin): - return "Plugins/" + plugin.rawValue - } - } - - package var url: URL { - return URL(fileURLWithPathWithoutExtension: "\(contentsDirectory)\(rawValue)") - } - - package static var allCases: [XcodeMachOFileName] { - Frameworks.allCases.map { .frameworks($0) } + - SharedFrameworks.allCases.map { .sharedFrameworks($0) } + - Plugins.allCases.map { .plugins($0) } - } -} - -import Foundation -import Darwin - -extension URL { - init(fileURLWithPathWithoutExtension pathWithoutExtension: String) { - // 1. Create a glob pattern by appending ".*" - // e.g., "/Folder/A" becomes "/Folder/A.*" - let pattern = pathWithoutExtension + ".*" - - // 2. Prepare a glob_t structure to hold the results. - var globResult = glob_t() - - // 3. Call the glob function. - // It takes the pattern, flags, an error function (nil), and a pointer to the result struct. - let returnCode = glob(pattern, 0, nil, &globResult) - - // IMPORTANT: Always free the memory allocated by glob when you're done. - // `defer` ensures this is called before the function exits. - defer { - globfree(&globResult) - } - - // 4. Check if glob succeeded (returnCode == 0) and found at least one match. - if returnCode == 0, let firstMatchPath = globResult.gl_pathv[0] { - // 5. Convert the C string result back to a Swift String. - let swiftPath = String(cString: firstMatchPath) - // 6. Create and return a URL from the path. - self = URL(fileURLWithPath: swiftPath) - } else { - // If no matches were found or an error occurred, return nil. - fatalError() - } - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift deleted file mode 100644 index 70810e2a..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift +++ /dev/null @@ -1,37 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -@MainActor -package class DyldCacheTests: Sendable { - package let mainCache: DyldCache - - package let subCache: DyldCache - - package let fullCache: FullDyldCache - - package let machOFileInMainCache: MachOFile - - package let machOFileInSubCache: MachOFile - - package let machOFileInCache: MachOFile - - package class var platform: MachOKit.Platform { .macOS } - - package class var mainCacheImageName: MachOImageName { .SwiftUI } - - package class var cacheImageName: MachOImageName { .SwiftUI } - - package class var cachePath: DyldSharedCachePath { .current } - - package init() async throws { - self.mainCache = try DyldCache(path: Self.cachePath) - self.subCache = try required(mainCache.subCaches?.first?.subcache(for: mainCache)) - self.fullCache = try FullDyldCache(path: Self.cachePath) - self.machOFileInCache = try #require(fullCache.machOFile(named: Self.cacheImageName)) - self.machOFileInMainCache = try #require(mainCache.machOFile(named: Self.mainCacheImageName)) - self.machOFileInSubCache = try #require(subCache.machOFiles().first(where: { _ in true })) - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift new file mode 100644 index 00000000..c2db7a92 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift @@ -0,0 +1,36 @@ +import Foundation +import MachOTestingSupport +import SwiftSectionFixtureSupport + +extension ExclusiveImageAccess { + /// Spelled from the fixture's name so a typo is a compile error rather + /// than a silently ineffective exclusion. `package`, matching the fixture + /// names this package adds — a suite reaching the image by a hand-built + /// path (which is how the sharing went unnoticed) uses the `String` + /// initializer with the same key, the image's name. + package init(_ fileName: MachOFileName) { + self.init(fileName.exclusiveAccessKey) + } + + package init(_ imageName: MachOImageName) { + self.init(imageName.exclusiveAccessKey) + } +} + +extension MachOFileName { + /// What ``ExclusiveImageAccess`` keys this file by: the name of the image + /// it holds, the last path component without its extension, so that a + /// suite naming a fixture by its file and one naming it by its image + /// (`MachOImageName`) exclude each other. + package var exclusiveAccessKey: String { + url.deletingPathExtension().lastPathComponent + } +} + +extension MachOImageName { + /// What ``ExclusiveImageAccess`` keys this image by: its name, the same + /// key as the file it was loaded from (``MachOFileName/exclusiveAccessKey``). + package var exclusiveAccessKey: String { + name + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift deleted file mode 100644 index 194ea034..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift +++ /dev/null @@ -1,129 +0,0 @@ -import Foundation -import SwiftSectionFixtureSupport -import Testing - -/// Serializes every test that declares the same fixture image — **across -/// suites and across test targets**. -/// -/// `.serialized` cannot do this. Its documentation is explicit: it "does not -/// affect the execution of a test relative to its peers or to unrelated tests", -/// so it orders tests *within* one container and nothing more. A whole-process -/// resource like a per-image cache needs ordering between containers. -/// -/// A global actor cannot do it either. These tests are `async`, and `await` -/// suspends and yields the actor: an actor guarantees no *concurrent* execution, -/// not the absence of *interleaving*, so a sibling test resumes in the middle of -/// one that is mid-way through clearing and re-checking a cache. `TestScoping` -/// wraps the entire test body, suspension points included, which is the one -/// primitive that gives a real critical section. -/// -/// Apply it to every suite that touches the image, not just the one making the -/// assertions — an exclusion held by one side is not an exclusion: -/// -/// @Suite(.serialized, ExclusiveImageAccess(.SymbolTestsHelper)) -/// final class PerImageCacheEvictionTests: MachOFileTests { … } -/// -/// @Suite(ExclusiveImageAccess(.SymbolTestsHelper)) -/// final class DependencyClosureLayoutTests: MachOSwiftSectionFixtureTests { … } -/// -/// It also makes the sharing *greppable*, which is the failure this exists to -/// prevent. `PerImageCacheEvictionTests` documented in prose that it ran against -/// "an image no other suite indexes"; that was true of every suite naming the -/// image through `MachOFileName`, and false in fact, because -/// `DependencyClosureLayoutTests` reached the same binary by building its path -/// by hand. Searching for the fixture case name could not find it. Searching for -/// `ExclusiveImageAccess` finds every declared user. -public struct ExclusiveImageAccess: TestTrait, SuiteTrait, TestScoping { - private let imageName: String - - public init(_ imageName: String) { - self.imageName = imageName - } - - /// Applied to a suite, this must reach the suite's tests — the scope is - /// provided per test function, never at the suite level (verified against - /// the 6.3.3 runtime: `provideScope` is called only for functions, so the - /// non-reentrant lock below cannot nest with itself). - public var isRecursive: Bool { true } - - public func provideScope( - for test: Test, - testCase: Test.Case?, - performing function: () async throws -> Void - ) async throws { - try await FixtureImageExclusion.withExclusiveAccess(to: imageName, performing: function) - } -} - -/// Runs `body` while holding the image, then releases it. -/// -/// Free-standing rather than a method on the actor: the test body is a -/// non-`Sendable` closure, and handing it to an actor method would cross an -/// isolation boundary, which Swift 6 rejects (`sending value of non-Sendable -/// type … risks causing data races`). Only the *lock state* belongs on the -/// actor; the body stays in its caller's isolation, where the testing library -/// put it. -public enum FixtureImageExclusion { - public static func withExclusiveAccess( - to imageName: String, - performing body: () async throws -> Void - ) async rethrows { - await FixtureImageLock.shared.acquire(imageName) - do { - try await body() - } catch { - // Release before rethrowing: leaving the image held would turn one - // failing test into a hang for every later test that declares it. - await FixtureImageLock.shared.release(imageName) - throw error - } - await FixtureImageLock.shared.release(imageName) - } -} - -extension ExclusiveImageAccess { - /// Spelled from the fixture case so a typo is a compile error rather than a - /// silently ineffective exclusion. `package`, matching the fixture enums — - /// a suite reaching the image by a hand-built path (which is how the sharing - /// went unnoticed) uses the `String` initializer with the same key. - package init(_ fileName: MachOFileName) { - self.init(fileName.rawValue) - } - - package init(_ imageName: MachOImageName) { - self.init(imageName.rawValue) - } -} - -/// Process-wide mutual exclusion keyed on a fixture image. -/// -/// Non-reentrant on purpose: a scope is only ever provided per test function -/// (never additionally at the suite level), so nesting cannot arise, and the -/// simpler invariant is easier to keep true than a reentrancy counter. -actor FixtureImageLock { - static let shared = FixtureImageLock() - - private var busyImageNames: Set = [] - private var waitersByImageName: [String: [CheckedContinuation]] = [:] - - func acquire(_ imageName: String) async { - // A loop, not a single check: being resumed only means the previous - // holder released. Re-acquiring the actor is itself a suspension, so a - // newly arriving test can slip in first and take the image — at which - // point this one waits again. - while busyImageNames.contains(imageName) { - await withCheckedContinuation { continuation in - waitersByImageName[imageName, default: []].append(continuation) - } - } - busyImageNames.insert(imageName) - } - - func release(_ imageName: String) { - busyImageNames.remove(imageName) - guard var waiters = waitersByImageName[imageName], !waiters.isEmpty else { return } - let next = waiters.removeFirst() - waitersByImageName[imageName] = waiters.isEmpty ? nil : waiters - next.resume() - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift b/Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift new file mode 100644 index 00000000..df486100 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift @@ -0,0 +1,10 @@ +// The Testing half of the test support shared with MachOKitExtensions: +// `ExclusiveImageAccess`, the `MachOFileTests`, `MachOImageTests`, +// `DyldCacheTests`, `XcodeMachOFileTests` and `MachOFixtureTests` base +// classes. Re-exported so that a test importing this module reaches them +// without an import of its own. +@_exported import MachOTestingSupport +// The Swift-free half too: `ForwardingMachOReader` takes its +// `DeclaredWrapper` / `UndeclaredWrapper` markers from it, so a test naming +// one through this module alone still finds it. +@_exported import MachOFixtureSupport diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift index 96cf97f3..aed04a82 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift @@ -1,4 +1,5 @@ import MachOKitExtensions +import SwiftSectionFixtureSupport import SwiftDeclarationRendering /// A wrapper that declares what it wraps can say so to the library: the diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift index 1d51746d..cdf95cc4 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift @@ -3,17 +3,14 @@ import MachOKit import MachOKitExtensions import MachOReading import MachOSwiftSection +import SwiftSectionFixtureSupport -/// Whether a ``ForwardingMachOReader`` tells the library what it wraps. -package protocol ForwardingMachOReaderDeclaration: Sendable {} - -/// The reader declares the reader it forwards to — a host's wrapper that -/// adopted `MachOReaderWrapper`. -package enum DeclaredWrapper: ForwardingMachOReaderDeclaration {} - -/// The reader forwards every read and says nothing about it — a host's -/// wrapper written before `MachOReaderWrapper` existed. -package enum UndeclaredWrapper: ForwardingMachOReaderDeclaration {} +// Whether a ``ForwardingMachOReader`` tells the library what it wraps is said +// with MachOKitExtensions' markers for its own `ForwardingReader`: +// `DeclaredWrapper` — a host's wrapper that adopted `MachOReaderWrapper` — +// and `UndeclaredWrapper` — one written before `MachOReaderWrapper` existed. +// The reader itself stays here: it forwards this package's reading protocol, +// `MachOSwiftSectionRepresentableWithCache`, which `ForwardingReader` does not. /// A reader that forwards every requirement to `base` and adds nothing. /// @@ -24,7 +21,7 @@ package enum UndeclaredWrapper: ForwardingMachOReaderDeclaration {} /// requirement is forwarded, the defaulted ones too, so nothing a default /// implementation computes differently from `base`'s own can tell the two /// apart. -package struct ForwardingMachOReader: MachOSwiftSectionRepresentableWithCache { +package struct ForwardingMachOReader: MachOSwiftSectionRepresentableWithCache { package let base: Base package init(_ base: Base) { diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift index f4b3e11d..2393c7d8 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift @@ -307,7 +307,7 @@ package enum GenericSpecializationFixture { /// the offline indexer's sub-indexer for the standard library's /// protocols and conformances. package static func systemStandardLibraryFile() throws -> MachOFile { - let cache = try DyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + let cache = try DyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.path)) return try #require(cache.machOFile(by: .name("libswiftCore")), "libswiftCore not found in the running system's dyld shared cache") } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift deleted file mode 100644 index 063cd74e..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift +++ /dev/null @@ -1,26 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -@MainActor -package class MachOFileTests: Sendable { - package let machOFile: MachOFile - - package class var fileName: MachOFileName { .Finder } - - package class var preferredArchitecture: CPUType { .arm64 } - - package init() async throws { - let file = try loadFromFile(named: Self.fileName) - switch file { - case .fat(let fatFile): - self.machOFile = try required(fatFile.machOFiles().first(where: { $0.header.cpuType == Self.preferredArchitecture }) ?? fatFile.machOFiles().first) - case .machO(let machO): - self.machOFile = machO - @unknown default: - fatalError() - } - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift deleted file mode 100644 index 28e4f955..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift +++ /dev/null @@ -1,16 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -@MainActor -package class MachOImageTests: Sendable { - package let machOImage: MachOImage - - package class var imageName: MachOImageName { .Foundation } - - package init() async throws { - self.machOImage = try #require(MachOImage(named: Self.imageName)) - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift index 007637af..80685c17 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift @@ -1,153 +1,32 @@ import Foundation -import Testing -import MachOKit -import MachOFoundation -import MachOReading -import MachOResolving +import MachOTestingSupport import SwiftSectionFixtureSupport -@MainActor -package class MachOSwiftSectionFixtureTests: Sendable { - package let machOFile: MachOFile - package let machOImage: MachOImage - - package let fileContext: MachOContext - package let imageContext: MachOContext - package let inProcessContext: InProcessContext - +/// A suite that reads the SymbolTestsCore fixture both from its file and as +/// this process loaded it. +/// +/// The readers, the reading contexts and `acrossAllReaders` / +/// `acrossAllContexts` / `usingInProcessOnly` come from MachOKitExtensions' +/// `MachOFixtureTests`; this class says which fixture to read and turns a +/// fixture that cannot be read into a `FixtureLoadError` that tells how to +/// rebuild it. +package class MachOSwiftSectionFixtureTests: MachOFixtureTests { package class var fixtureFileName: MachOFileName { .SymbolTestsCore } package class var fixtureImageName: MachOImageName { .SymbolTestsCore } - package class var preferredArchitecture: CPUType { .arm64 } - - package init() async throws { - // 1) Load MachO from disk. - let file: File - do { - file = try loadFromFile(named: Self.fixtureFileName) - } catch { - // If the file doesn't exist on disk, surface a fixture-specific - // error with rebuild instructions. Otherwise propagate the original - // error so unrelated load failures aren't masked. - let resolvedPath = Self.resolveFixturePath(Self.fixtureFileName.rawValue) - if !FileManager.default.fileExists(atPath: resolvedPath) { - throw FixtureLoadError.fixtureFileMissing(path: resolvedPath) - } - throw error - } - switch file { - case .fat(let fatFile): - self.machOFile = try required( - fatFile.machOFiles().first(where: { $0.header.cpuType == Self.preferredArchitecture }) - ?? fatFile.machOFiles().first - ) - case .machO(let machO): - self.machOFile = machO - @unknown default: - fatalError() - } - - // 2) Ensure fixture is dlopen'd into the test process so MachOImage(name:) succeeds. - // `MachOImage(name:)` matches by the bare module name (last path component - // with extension stripped), not by the full path. Derive that from the - // fixtureImageName rawValue, which is a relative filesystem path. - try Self.ensureFixtureLoaded() - let imageLookupName = Self.imageLookupName(from: Self.fixtureImageName.rawValue) - guard let image = MachOImage(name: imageLookupName) else { - throw FixtureLoadError.imageNotFoundAfterDlopen( - path: Self.fixtureImageName.rawValue, - dlerror: Self.lastDlerror() - ) - } - self.machOImage = image - - // 3) Three ReadingContext instances over the same fixture. - self.fileContext = MachOContext(machOFile) - self.imageContext = MachOContext(machOImage) - self.inProcessContext = InProcessContext() - } - - private static let dlopenOnce: Void = { - let absolute = resolveFixturePath(MachOImageName.SymbolTestsCore.rawValue) - _ = absolute.withCString { dlopen($0, RTLD_LAZY) } - }() - - private static func ensureFixtureLoaded() throws { - _ = dlopenOnce - } - /// Resolve a relative MachOImageName path (rooted at the package-relative `../../../Tests/...` - /// convention) to an absolute filesystem path. Uses the same anchor strategy as - /// `loadFromFile` for parity: relative paths resolve against the directory containing - /// this source file (i.e. `Sources/TestSupport/SwiftSectionTestingSupport/`). - private static func resolveFixturePath(_ relativePath: String) -> String { - if relativePath.hasPrefix("/") { return relativePath } - let url = URL(fileURLWithPath: relativePath, relativeTo: URL(fileURLWithPath: #filePath)) - return url.standardizedFileURL.path + /// The file of ``fixtureFileName``, found in this process by + /// ``fixtureImageName`` after loading it. + override package class var fixture: MachOFixture { + MachOFixture(fileURL: fixtureFileName.url, imageName: fixtureImageName.name, loadsIntoProcess: true) } - private static func lastDlerror() -> String? { - guard let cString = dlerror() else { return nil } - return String(cString: cString) - } - - /// Derive the bare module name `MachOImage(name:)` expects (last path component - /// with extension stripped) from a path-form `MachOImageName.rawValue`. - private static func imageLookupName(from rawValue: String) -> String { - let lastComponent = rawValue.components(separatedBy: "/").last ?? rawValue - return lastComponent.components(separatedBy: ".").first ?? lastComponent - } -} - -extension MachOSwiftSectionFixtureTests { - /// Run `body` against each (label, reader) pair, asserting all results equal the first. - /// Returns the unique value. Fails fast with the label of the first mismatching reader. - package func acrossAllReaders( - file fileWork: () throws -> T, - image imageWork: () throws -> T, - inProcess inProcessWork: (() throws -> T)? = nil, - sourceLocation: SourceLocation = #_sourceLocation - ) throws -> T { - let fromFile = try fileWork() - let fromImage = try imageWork() - #expect(fromFile == fromImage, "MachOFile vs MachOImage diverged", sourceLocation: sourceLocation) - if let inProcessWork { - let fromInProcess = try inProcessWork() - #expect(fromFile == fromInProcess, "MachOFile vs InProcess diverged", sourceLocation: sourceLocation) - } - return fromFile - } - - /// Run `body` against each ReadingContext (file/image/inProcess), asserting all equal. - package func acrossAllContexts( - file fileWork: () throws -> T, - image imageWork: () throws -> T, - inProcess inProcessWork: (() throws -> T)? = nil, - sourceLocation: SourceLocation = #_sourceLocation - ) throws -> T { - let fromFileCtx = try fileWork() - let fromImageCtx = try imageWork() - #expect(fromFileCtx == fromImageCtx, "fileContext vs imageContext diverged", sourceLocation: sourceLocation) - if let inProcessWork { - let fromInProcessCtx = try inProcessWork() - #expect(fromFileCtx == fromInProcessCtx, "fileContext vs inProcessContext diverged", sourceLocation: sourceLocation) + package override init() async throws { + do { + try await super.init() + } catch MachOFixtureError.fileMissing(let path) { + throw FixtureLoadError.fixtureFileMissing(path: path) + } catch MachOFixtureError.imageNotLoaded(_, let dynamicLoaderError) { + throw FixtureLoadError.imageNotFoundAfterDlopen(path: Self.fixtureFileName.path, dlerror: dynamicLoaderError) } - return fromFileCtx - } -} - -extension MachOSwiftSectionFixtureTests { - /// Run `body` against the in-process reader only. Used by Suites covering - /// runtime-only metadata types (MetatypeMetadata, TupleTypeMetadata, - /// FunctionTypeMetadata, etc.) — types that the Swift runtime allocates - /// at type-load time and that have no Mach-O section to read from. - /// - /// Cross-reader equality is not asserted because `MachOFile` and - /// `MachOImage` cannot reach this metadata. Single-reader assertion + - /// baseline literal pinning is the deepest coverage achievable. - package func usingInProcessOnly( - _ work: (InProcessContext) throws -> T, - sourceLocation: SourceLocation = #_sourceLocation - ) throws -> T { - try work(inProcessContext) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift deleted file mode 100644 index 250b0200..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift +++ /dev/null @@ -1,79 +0,0 @@ -import Foundation - -public enum ProcessMemory { - public enum Metric { - case physicalFootprint - - case residentSize - - case compressed - - case virtualSize - - var displayName: String { - switch self { - case .physicalFootprint: return "Physical Footprint" - case .residentSize: return "Resident Size (RSS)" - case .compressed: return "Compressed Memory" - case .virtualSize: return "Virtual Size" - } - } - } - - private nonisolated(unsafe) static let byteFormatter: ByteCountFormatter = { - let formatter = ByteCountFormatter() - formatter.countStyle = .memory - formatter.allowsNonnumericFormatting = false - formatter.includesUnit = true - return formatter - }() - - public static func value(of metric: Metric) -> UInt64 { - guard let info = getTaskVMInfo() else { return 0 } - - switch metric { - case .physicalFootprint: return UInt64(info.phys_footprint) - case .residentSize: return UInt64(info.resident_size) - case .compressed: return UInt64(info.compressed) - case .virtualSize: return UInt64(info.virtual_size) - } - } - - public static func formatted(of metric: Metric) -> String { - let bytes = value(of: metric) - return byteFormatter.string(fromByteCount: Int64(bytes)) - } - - public static func report() { - guard let info = getTaskVMInfo() else { - print("❌ [ProcessMemory] Failed to retrieve task info.") - return - } - - print("====== 🧠 Process Memory Report ======") - printItem(name: Metric.physicalFootprint.displayName, bytes: UInt64(info.phys_footprint)) - printItem(name: Metric.residentSize.displayName, bytes: UInt64(info.resident_size)) - printItem(name: Metric.compressed.displayName, bytes: UInt64(info.compressed)) - print("--------------------------------------") - } - - // MARK: - Private Helpers - - private static func printItem(name: String, bytes: UInt64) { - let str = byteFormatter.string(fromByteCount: Int64(bytes)) - print(String(format: "%-20@ : %@", name, str)) - } - - private static func getTaskVMInfo() -> task_vm_info_data_t? { - var info = task_vm_info_data_t() - var count = mach_msg_type_number_t(MemoryLayout.size) / 4 - - let result: kern_return_t = withUnsafeMutablePointer(to: &info) { - $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { - task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) - } - } - - return result == KERN_SUCCESS ? info : nil - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift b/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift deleted file mode 100644 index 86f461b3..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift +++ /dev/null @@ -1,6 +0,0 @@ -import Foundation - -@globalActor -public actor TestActor { - public static let shared = TestActor() -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift deleted file mode 100644 index 520cef0a..00000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -package class XcodeMachOFileTests { - package let machOFile: MachOFile - - package class var fileName: XcodeMachOFileName { .sharedFrameworks(.DNTDocumentationModel) } - - package class var preferredArchitecture: CPUType { .arm64 } - - package init() async throws { - let file = try File.loadFromFile(url: Self.fileName.url) - switch file { - case .fat(let fatFile): - self.machOFile = try required(fatFile.machOFiles().first(where: { $0.header.cpuType == Self.preferredArchitecture }) ?? fatFile.machOFiles().first) - case .machO(let machO): - self.machOFile = machO - @unknown default: - fatalError() - } - } -} diff --git a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift index c578f077..111b439b 100644 --- a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift @@ -35,7 +35,7 @@ final class DyldCacheSymbolSimpleTests: DyldCacheSymbolTests, @unchecked Sendabl let directoryURL = URL.documentsDirectory.appending(component: "SwiftSymbolExpanded") try directoryURL.createDirectoryIfNeeded() - try string.write(to: directoryURL.appending(components: "\(imageName.rawValue).txt"), atomically: true, encoding: .utf8) + try string.write(to: directoryURL.appending(components: "\(imageName.name).txt"), atomically: true, encoding: .utf8) } @Test func demangle() async throws { diff --git a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift index a69587d8..4ffe7019 100644 --- a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift +++ b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift @@ -116,7 +116,7 @@ extension ObjCAPIEvolutionDumpTests { var imageSnapshots: [ObjCAPIImageSnapshot] = [] for image in version.images { let document = try await snapshotDocument(of: image.machO, label: version.label) - imageSnapshots.append(ObjCAPIImageSnapshot(imageName: image.imageName.rawValue, snapshot: document.snapshot)) + imageSnapshots.append(ObjCAPIImageSnapshot(imageName: image.imageName.name, snapshot: document.snapshot)) } imageGroups.append(imageSnapshots) } @@ -323,7 +323,7 @@ extension ObjCEvolutionInterfaceDumpTests { var images: [ObjCEvolutionInterfaceImage] = [] for image in version.images { let indexer = try await preparedObjCIndexer(of: image.machO) - images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName.rawValue, indexer: indexer, machO: image.machO)) + images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName.name, indexer: indexer, machO: image.machO)) } builder.addVersion(images: images, version: ObjCAPIVersionDescriptor(label: version.label)) } diff --git a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift index 05f559b8..1a555bd1 100644 --- a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift +++ b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift @@ -114,7 +114,7 @@ extension ABIEvolutionDumpTests { snapshot: builder.snapshot() ) imageSnapshots.append(ABIImageSnapshot( - imageName: image.imageName.rawValue, + imageName: image.imageName.name, snapshot: try ABISnapshotDocument.decode(from: document.encoded()).snapshot )) } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift index b8626911..f8a0ade3 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift @@ -100,7 +100,7 @@ extension SwiftEvolutionInterfaceDumpTests { let builder = try AnySwiftEvolutionInterfaceBuilder( configuration: indexConfiguration, imageGroups: imageGroupVersions.map { version in - version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName.rawValue, machO: $0.machO) } + version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName.name, machO: $0.machO) } }, labels: imageGroupVersions.map(\.label), availabilityAnnotationPlatform: availabilityAnnotationPlatform @@ -261,7 +261,7 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { cacheVersions.map { cacheVersion in let cachePath = DyldSharedCachePath.macOS(cacheVersion) guard let versionLabel = versionLabelsByCacheVersion[cacheVersion] else { return cachePath } - return DyldSharedCachePath(rawValue: cachePath.rawValue, versionLabel: versionLabel) + return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) } } diff --git a/Tests/MachOSwiftSectionTests/FileMappingTests.swift b/Tests/MachOSwiftSectionTests/FileMappingTests.swift index ae739fa0..c0fa0233 100644 --- a/Tests/MachOSwiftSectionTests/FileMappingTests.swift +++ b/Tests/MachOSwiftSectionTests/FileMappingTests.swift @@ -26,7 +26,7 @@ import SwiftSectionFixtureSupport @Suite struct FileMappingTests { private static var isHostDyldCacheAvailable: Bool { - FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.path) } /// More Swift images than an XPC service may hold descriptors: mapped per @@ -62,7 +62,7 @@ struct FileMappingTests { guard setrlimit(RLIMIT_NOFILE, &limit) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EINVAL) } - let cache = try FullDyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + let cache = try FullDyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.path)) let swiftImages = Array( cache.machOFiles() .lazy diff --git a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift index d55aa253..eec7704d 100644 --- a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift +++ b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift @@ -65,7 +65,7 @@ final class ReadingContextRelocationTests: MachOSwiftSectionFixtureTests, @unche /// files, so a cross-image reference is a bind rather than a rebase. enum StandaloneSimulatorRuntimeLibraries { static let synchronizationPath: String = { - let swiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.rawValue + let swiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.path let runtimeRoot = swiftUIPath.dropLast("/System/Library/Frameworks/SwiftUI.framework/SwiftUI".count) return runtimeRoot + "/usr/lib/swift/libswiftSynchronization.dylib" }() diff --git a/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift b/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift index a30ce930..ca39d96e 100644 --- a/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift +++ b/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift @@ -19,7 +19,7 @@ import SwiftSectionFixtureSupport @Suite struct StandaloneFileReadingTests { private static var isHostDyldCacheAvailable: Bool { - FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.path) } @Test(.enabled(if: isHostDyldCacheAvailable)) @@ -55,7 +55,7 @@ struct StandaloneFileReadingTests { /// The first bytes of the host's dyld cache: enough for MachOKit to accept /// a file as a cache. private static func hostCacheHeaderBytes() throws -> Data { - let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: DyldSharedCachePath.current.path)) defer { try? fileHandle.close() } return try #require(try fileHandle.read(upToCount: 0x10000)) } diff --git a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift index 494fcc7e..5b69b7d4 100644 --- a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift +++ b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift @@ -22,7 +22,7 @@ import Semantic /// evidence gate is what this suite pins. /// /// Environment-gated: skipped on machines without Xcode's SourceEditor. -@Suite(.serialized, .enabled(if: FileManager.default.fileExists(atPath: MachOFileName.SourceEditorFromXcode.rawValue))) +@Suite(.serialized, .enabled(if: FileManager.default.fileExists(atPath: MachOFileName.SourceEditorFromXcode.path))) final class FinalKeywordICFRegressionTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SourceEditorFromXcode } diff --git a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift index e9a0ccf3..e2a296ae 100644 --- a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift +++ b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift @@ -12,7 +12,7 @@ import SwiftSectionFixtureSupport /// of the suite it decorates is a circular macro reference. enum ArchivedMacOS15LayoutFixtures { static let cachePath = DyldSharedCachePath.macOS_15_5 - static var hasCache: Bool { FileManager.default.fileExists(atPath: cachePath.rawValue) } + static var hasCache: Bool { FileManager.default.fileExists(atPath: cachePath.path) } static func swiftUICore() throws -> MachOFile { let cache = try FullDyldCache(path: cachePath) diff --git a/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift b/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift index 14d02294..83dd6983 100644 --- a/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift @@ -1,24 +1,13 @@ import Testing import SwiftSectionFixtureSupport -/// `DyldSharedCachePath` builds an archived cache's path and label from its -/// version. The named macOS caches are built that way too, and only the -/// integration dumps — which nothing runs automatically — open them, so a -/// path or a label that came out wrong would go unnoticed until someone ran -/// one by hand. +/// The named macOS caches this package adds to `DyldSharedCachePath` are +/// built from a version. Only the integration dumps — which nothing runs +/// automatically — open them, so a path or a label that came out wrong would +/// go unnoticed until someone ran one by hand. How a version spells an +/// archived path is MachOKitExtensions' to test. @Suite struct DyldSharedCachePathTests { - @Test("A version names the cache file in that version's directory on the volume, and labels it") - func versionSpellsTheArchivedPathAndLabel() { - let internalBuild = DyldSharedCachePath.macOS("14.0(Internal)") - #expect(internalBuild.rawValue == "/Volumes/DyldSharedCaches/macOS/14.0(Internal)/dyld_shared_cache_arm64e") - #expect(internalBuild.versionLabel == "14.0(Internal)") - - let device = DyldSharedCachePath.iOS("27.0") - #expect(device.rawValue == "/Volumes/DyldSharedCaches/iOS/27.0/dyld_shared_cache_arm64e") - #expect(device.versionLabel == "27.0") - } - /// The paths these named caches spelled out before they were built from a /// version, and the labels the evolution dumps used to write out for /// them by hand. @@ -29,7 +18,7 @@ struct DyldSharedCachePathTests { (.macOS_27_0, "/Volumes/DyldSharedCaches/macOS/27.0/dyld_shared_cache_arm64e", "27.0"), ]) func namedCacheKeepsItsPathAndLabel(cachePath: DyldSharedCachePath, expectedPath: String, expectedVersionLabel: String) { - #expect(cachePath.rawValue == expectedPath) + #expect(cachePath.path == expectedPath) #expect(cachePath.versionLabel == expectedVersionLabel) } } diff --git a/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift new file mode 100644 index 00000000..43cbe4b1 --- /dev/null +++ b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift @@ -0,0 +1,30 @@ +import Testing +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport + +/// `ExclusiveImageAccess` excludes only suites that spell the same key. A +/// suite may name a SymbolTests fixture by its file and another by its image; +/// both must reach the same key, or the two run at once while each believes +/// it holds the image alone. (The trait itself is tested in +/// MachOKitExtensions.) +@Suite +struct ExclusiveImageAccessKeyTests { + @Test("A SymbolTests fixture keys the exclusion the same by its file and by its image", arguments: [ + (MachOFileName.SymbolTests, MachOImageName.SymbolTests), + (.SymbolTestsCore, .SymbolTestsCore), + ]) + func fileAndImageOfOneFixtureShareTheKey(fileName: MachOFileName, imageName: MachOImageName) { + #expect(fileName.exclusiveAccessKey == imageName.exclusiveAccessKey) + #expect(imageName.exclusiveAccessKey == imageName.name) + } + + @Test("Different SymbolTests fixtures key the exclusion differently") + func differentFixturesHaveDifferentKeys() { + let keys: Set = [ + MachOFileName.SymbolTests.exclusiveAccessKey, + MachOFileName.SymbolTestsCore.exclusiveAccessKey, + MachOFileName.SymbolTestsHelper.exclusiveAccessKey, + ] + #expect(keys.count == 3) + } +} diff --git a/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift deleted file mode 100644 index 60caffd2..00000000 --- a/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift +++ /dev/null @@ -1,89 +0,0 @@ -import Foundation -import Testing -@testable import SwiftSectionTestingSupport - -/// The exclusion must be demonstrated, not asserted in prose — a promise in a -/// doc comment is exactly what failed here the first time. -/// -/// Both suites below carry `ExclusiveImageAccess` for the same key and run in -/// separate containers, so the testing library is free to interleave them. A -/// shared observer records every enter/exit; overlapping intervals would appear -/// as an enter arriving while another test is still inside. -@Suite -struct ExclusiveImageAccessTests { - @Test func concurrentAcquirersOfOneImageNeverOverlap() async throws { - let observer = OverlapObserver() - - await withTaskGroup(of: Void.self) { group in - for _ in 0 ..< 8 { - group.addTask { - await FixtureImageExclusion.withExclusiveAccess(to: "SharedImage") { - await observer.enter() - // Yield repeatedly: a lock that only excluded synchronous - // work — a global actor, say — lets a sibling run here. - for _ in 0 ..< 4 { await Task.yield() } - await observer.exit() - } - } - } - } - - #expect(await observer.maximumConcurrentHolders == 1, "two tests held the same image at once") - #expect(await observer.completedHolderCount == 8, "every acquirer must get its turn") - } - - /// Different keys must not block each other, or the trait would serialize - /// the whole suite tree instead of one image. - @Test func differentImagesProceedConcurrently() async throws { - let observer = OverlapObserver() - - await withTaskGroup(of: Void.self) { group in - for index in 0 ..< 6 { - group.addTask { - await FixtureImageExclusion.withExclusiveAccess(to: "Image\(index)") { - await observer.enter() - for _ in 0 ..< 4 { await Task.yield() } - await observer.exit() - } - } - } - } - - #expect(await observer.maximumConcurrentHolders > 1, "distinct images must not serialize against each other") - } - - /// A throwing body must still release, or one failed test wedges every later - /// one that declares the image — turning a single failure into a hang. - @Test func releasesAfterAThrowingBody() async throws { - struct BodyError: Error {} - - await #expect(throws: BodyError.self) { - try await FixtureImageExclusion.withExclusiveAccess(to: "ThrowingImage") { - throw BodyError() - } - } - - // Would hang rather than fail if the lock leaked. - var reacquired = false - await FixtureImageExclusion.withExclusiveAccess(to: "ThrowingImage") { - reacquired = true - } - #expect(reacquired) - } -} - -private actor OverlapObserver { - private var currentHolders = 0 - private(set) var maximumConcurrentHolders = 0 - private(set) var completedHolderCount = 0 - - func enter() { - currentHolders += 1 - maximumConcurrentHolders = max(maximumConcurrentHolders, currentHolders) - } - - func exit() { - currentHolders -= 1 - completedHolderCount += 1 - } -} diff --git a/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift b/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift index 1d7c1a18..34cb0108 100644 --- a/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift +++ b/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift @@ -17,7 +17,7 @@ import SwiftSectionFixtureSupport /// /// Combine is an image no other suite reads, so the symbol index this suite /// builds for it is built through the wrapper. -@Suite(ExclusiveImageAccess(MachOImageName.Combine.rawValue)) +@Suite(ExclusiveImageAccess(MachOImageName.Combine.name)) struct WrappedReaderSymbolTests { @Test("a wrapper of a cache file files its Swift symbols where the file does") func cacheFileWrapperFilesSwiftSymbolsLikeTheFile() throws { diff --git a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift index bf0de23c..41f25253 100644 --- a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift @@ -18,14 +18,14 @@ import Semantic /// reads a static of the suite it decorates is a circular macro reference. enum SimulatorRuntimeThunkFixtures { /// iOS 26.5: the last runtime that ships SwiftUI as a standalone file. - static let standaloneSwiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.rawValue - static let standaloneSwiftUICorePath = MachOFileName.iOS_26_5_Simulator_SwiftUICore.rawValue + static let standaloneSwiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.path + static let standaloneSwiftUICorePath = MachOFileName.iOS_26_5_Simulator_SwiftUICore.path static var hasStandaloneSwiftUI: Bool { FileManager.default.fileExists(atPath: standaloneSwiftUIPath) && FileManager.default.fileExists(atPath: standaloneSwiftUICorePath) } /// iOS 27.0: SwiftUI lives in the runtime's own dyld cache. - static let simulatorCachePath = DyldSharedCachePath.iOS_27_0_Simulator.rawValue + static let simulatorCachePath = DyldSharedCachePath.iOS_27_0_Simulator.path static var hasSimulatorCache: Bool { FileManager.default.fileExists(atPath: simulatorCachePath) } } From a426f943ed5f17f7d1cd753a93d0d3de4052357a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 11:45:09 +0800 Subject: [PATCH 057/175] test: compile fixtures and pick slices through MachOKitExtensions' shared support --- .../draft-shared-macho-testing-support.md | 2 + .../Baseline/BaselineGenerator.swift | 13 +-- .../ClassesWithoutClassObjectsFixture.swift | 8 +- .../ExistentialAnyFixture.swift | 69 ++---------- .../ExportedOnlyFixture.swift | 64 ++--------- .../ExtensionContextExportFixture.swift | 8 +- .../GenericSpecializationFixture.swift | 69 +++--------- .../ImageGroupFixture.swift | 12 +-- .../InitAccessorFixture.swift | 8 +- .../LocalTypeFixture.swift | 8 +- .../ModuleSelectorFixture.swift | 69 ++---------- .../ObjCImplementationFixture.swift | 10 +- .../ObservableMacroFixture.swift | 8 +- .../ProtocolRequirementPlacementFixture.swift | 91 +++------------- .../RenamedObjCClassFixture.swift | 8 +- .../Swift64DeclarationShapesFixture.swift | 8 +- .../SwiftDeclaredObjCProtocolsFixture.swift | 8 +- .../ThunkOnlyMemberFixture.swift | 8 +- .../UnobservablePresenceFixture.swift | 8 +- .../ClassOfReceiverSendTests.swift | 2 +- .../CompiledFixture.swift | 69 ++++-------- .../FileModeTests.swift | 39 ++++--- .../FunctionStartOutsideTextTests.swift | 19 ++-- .../LazyBindingTests.swift | 29 ++--- .../LinkerOptimizationHintTests.swift | 4 +- .../ReferenceKindAndRouteTests.swift | 35 +++--- .../RuntimeSendEntryPointTests.swift | 2 +- .../SymbolicationTests.swift | 25 ++--- .../SwiftDiffableInterfaceBuilderTests.swift | 23 +--- .../CoroFunctionPointerTests.swift | 100 +++++------------- .../OpaqueTypeArgumentDepthTests.swift | 64 ++--------- .../OpaqueTypeOrdinalTests.swift | 64 ++--------- .../OpaqueWitnessDumpAnnotationTests.swift | 8 +- .../VTableSlotAttributionTests.swift | 76 +++---------- .../CImportedExtensionKindTests.swift | 12 +-- .../PrivateDeclarationsWholeTreeTests.swift | 8 +- .../WrappedPropertyRecoveryTests.swift | 8 +- .../Arm64eSignedVWTPointerTests.swift | 18 ++-- .../CImportedTypeIdentityTests.swift | 12 +-- .../MalformedSymbolValueTests.swift | 9 +- ...icDemanglerFixedShapeExtractionTests.swift | 66 +++--------- ...mportedTypeConformanceInterfaceTests.swift | 12 +-- ...ditionalWitnessCommentStructureTests.swift | 64 ++--------- .../CrossImageOpaqueReferenceTests.swift | 8 +- .../DescriptorOnlyVTableMemberTests.swift | 8 +- .../DiffMemberIndentationTests.swift | 12 +-- .../ExecutableImageSymbolOffsetTests.swift | 87 ++++----------- .../ExtensionContextTypeNameTests.swift | 66 ++---------- .../LegacyDyldInfoBindTests.swift | 76 ++----------- .../ObjCImportedDefinitionTests.swift | 8 +- .../OpaqueConstraintRenderingTests.swift | 66 ++---------- .../OpaqueParameterDepthTests.swift | 9 +- ...eParameterInMultiDepthExtensionTests.swift | 63 ++--------- ...meterWithoutProtocolRequirementTests.swift | 69 ++---------- .../ProjectedOpaqueMemberWitnessTests.swift | 8 +- ...ropertyWrapperSynthesizedMemberTests.swift | 70 +++--------- ...otocolInExtensionDefaultWitnessTests.swift | 66 ++---------- .../ProtocolInExtensionTests.swift | 68 ++---------- ...ayoutBuiltinDescriptorRenderingTests.swift | 75 +++---------- ...trippedWrappedPropertyRenderingTests.swift | 8 +- .../SwiftEvolutionInterfaceBuilderTests.swift | 16 +-- .../DependencyClosureTests.swift | 4 +- .../NestedFieldOffsetOpaqueWitnessTests.swift | 66 ++---------- ...awLayoutBuiltinDescriptorLayoutTests.swift | 59 +++-------- ...ulatorRuntimeObjCAncestorLayoutTests.swift | 9 +- .../OfflineObjectiveCBaseClassTests.swift | 64 ++--------- ...eProjectionDependencyResolutionTests.swift | 9 +- .../SymbolIndexDemangledIndexTests.swift | 8 +- ...ssorThunkTypeInGenericExtensionTests.swift | 64 ++--------- .../MergedAccessorFixtureTests.swift | 59 ++++------- ...SimulatorRuntimeThunkResolutionTests.swift | 7 +- .../StandaloneFileThunkResolutionTests.swift | 61 +++-------- 72 files changed, 482 insertions(+), 1958 deletions(-) diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index b0203ff4..02d5ba55 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -383,3 +383,5 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-21 | 第 5 步的已知缺口:`FixtureCompiler` 还不能完全替代本包的 `CompiledFixture` | 本包 `Tests/CrossReferenceAnalysisTests/CompiledFixture.swift` 的 `build(libraryName:sources:compilerArguments:isExecutable:)` 能编可执行文件(`FileModeTests`、`FunctionStartOutsideTextTests` 两处用 `isExecutable: true`)、一次编多个源文件、按参数指定架构;MKE 3.1.0 之后的 `FixtureCompiler` 只把单个源字符串编成动态库。要么在发 3.2.0 之前给 `FixtureCompiler` 补可执行文件与多源文件,要么这几处在本包保留自己的辅助,待用户定。另:next 上新进的 `FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText` 用到 `CompiledFixture.build(…isExecutable:)` 与 `InstructionEncoding.branchWithLink(at:to:)`,第 5 步若搬走或改名它们,这条测试一起改,本分支合 next 时会遇到它。 | | 2026-11-21 | `FixtureCompiler` 补上可执行文件与多源文件,MKE 3.2.0 发布 | 用户选择发版前先补:新增 `executable(named:language:source:arguments:)`、两个收 `sourceFiles: [FixtureSourceFile]` 的重载,单段源码的写法不变;本包 `CompiledFixture.build` 的可执行文件、多源文件与指定架构(经参数 `-arch`)都能用它替代。`CompiledFixture.load` 的链接后改写、重新签名、再加载留在本包,在复制出的产物上做(共享编译器的产物是缓存,不能原地改)。MKE 全量测试通过,原始退出码 0;随后在 `main` 上打 3.2.0(附注 tag,同以往不建 Release 页面)。本包第 5、6 步可以开始。 | | 2026-11-21 | 第 5 步第一部分:测试支持改接 MKE 3.2.0 | MKE 下限升到 3.2.0;两个 support target 依赖并 re-export `MachOFixtureSupport` / `MachOTestingSupport`,搬走的 12 个文件删除;SymbolTests 的文件名与镜像名、本包命名的 cache、按本包名字的 `ExclusiveImageAccess` 初始化留在本包作 extension。`ExclusiveImageAccess` 的 key 取镜像名(文件名取路径最后一段去扩展名),同一夹具按文件或按镜像声明仍互斥,新测试 `ExclusiveImageAccessKeyTests` 钉住这一点。`MachOSwiftSectionFixtureTests` 改为 `MachOFixtureTests` 的子类,读不到夹具时把 `MachOFixtureError` 转成带重编说明的 `FixtureLoadError`。MKE 也有公开的 `DeclaredWrapper` / `UndeclaredWrapper`,与本包同名标记冲突,`ForwardingMachOReader` 改用 MKE 的标记(读取器本身留在本包)。CI 加 `MACHO_TESTING_SILENT: 1`。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0(基线 2,916:删 4 个搬走的测试,加 2 个);IntegrationTests 与可执行文件都编过。 | +| 2026-11-21 | 第 5 步第二部分:现编与选 slice 改用共享版本 | 41 处现编改用 `FixtureCompiler`(5 个 Swift 夹具、交叉引用测试 11 处、其余 25 处),源文件名一律照旧(private 判别符由文件名哈希得出);约 66 处手写选 slice 改用 `HostSlice`,故意选 arm64e 的 `StandaloneFileReferenceDumpTests` 照旧。`CompiledFixture` 只剩 `load`:经共享编译器编出后复制一份再改写、重签名、加载,不碰共享的缓存产物;`build` 与 `buildSwift` 删除。改过去的库 install name 从绝对临时路径变成 `@rpath/lib<名字>.dylib`;`ReferenceKindAndRouteTests` 的 Swift 库因模块名必须是 `Fixture` 改叫 `libFixture.dylib`(没有断言读文件名)。约 25 处共享编译器表达不了,保留手写,见后续项。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0。 | +| 2026-11-21 | 后续项:`FixtureCompiler` 还替代不了的现编 | 留着手写的约 25 处要的是:产物名与 Swift 模块名不同(`lib<模块>-<变体>` 之类);`-emit-module`、`.swiftinterface`、bridging header、modulemap 写到调用方选的路径;编完再 `strip` / `codesign`;先编 `.o` 再链接;另一套工具链(`DEVELOPER_DIR`)或 `--sdk iphonesimulator`;放进假系统根里由 install name 决定的路径。要全部收掉,`FixtureCompiler` 得加模块名参数、编译前就能拿到的产物目录和一个后处理步骤,留待以后另议(MKE 次版本)。 | diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift index f6c7a62e..703b585e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift @@ -678,18 +678,7 @@ package enum BaselineGenerator { } private static func loadFixtureMachOFile() throws -> MachOFile { - let file = try loadFromFile(named: .SymbolTestsCore) - switch file { - case .fat(let fat): - return try required( - fat.machOFiles().first(where: { $0.header.cpuType == .arm64 }) - ?? fat.machOFiles().first - ) - case .machO(let machO): - return machO - @unknown default: - fatalError() - } + try HostSlice.machOFile(in: loadFromFile(named: .SymbolTestsCore)) } /// Hand-maintained index of every Suite type registered in `dispatchSuite`. diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift index b22514af..35eba53a 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift @@ -224,13 +224,7 @@ package enum ClassesWithoutClassObjectsFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.full` client loaded into the test process — only that variant: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift index 7f63d7f4..b757f26f 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift @@ -89,64 +89,17 @@ package enum ExistentialAnyFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local - // one must compile the same source the same way. - "swiftc", "-swift-version", "5", "-emit-library", "-enable-library-evolution", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. The source keeps + /// the file name it always had, which private discriminators hash. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: source)], + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + arguments: ["-swift-version", "5", "-enable-library-evolution"] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift index e36c25d3..1613ccc6 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift @@ -143,62 +143,14 @@ package enum ExportedOnlyFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-enable-library-evolution", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] + unexportedSymbolNames.flatMap { ["-Xlinker", "-unexported_symbol", "-Xlinker", $0] } - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + source: source, + arguments: ["-enable-library-evolution"] + unexportedSymbolNames.flatMap { ["-Xlinker", "-unexported_symbol", "-Xlinker", $0] } + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift index 1873a842..524c9700 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift @@ -220,12 +220,6 @@ package enum ExtensionContextExportFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraries = try compilationResult.get() let libraryURL = try #require(libraries[variant], "no library for variant \(variant.rawValue)") - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift index 2393c7d8..355ee24c 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift @@ -222,68 +222,23 @@ package enum GenericSpecializationFixture { package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } } - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local one - // must compile the same source the same way. `-Onone` keeps the - // private type, which nothing references. - "swiftc", "-swift-version", "5", "-Onone", "-emit-library", - "-module-name", moduleName, - // The absolute output path as the install name, so the - // in-process leg loads with no rpath. - "-Xlinker", "-install_name", "-Xlinker", libraryURL.path, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. The source keeps + /// the file name it always had, which private discriminators hash. package static func libraryURL() throws -> URL { - try compilationResult.get() + try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: source)], + // The language mode pinned: CI's toolchain and a newer local one + // must compile the same source the same way. `-Onone` keeps the + // private type, which nothing references. + arguments: ["-swift-version", "5", "-Onone"] + ) } /// The fixture read from disk — what the offline path sees. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: libraryURL()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL()) } /// The fixture loaded into the test process — what the runtime path sees. diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift index f2b4aa48..55973d6b 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift @@ -288,7 +288,7 @@ package enum ImageGroupFixture { package static func imageGroups() throws -> [[Image]] { try compilationResult.get().map { libraries in try libraries.map { library in - try Image(name: library.name, machOFile: machOFile(at: library.libraryURL)) + try Image(name: library.name, machOFile: HostSlice.machOFile(at: library.libraryURL)) } } } @@ -298,14 +298,4 @@ package enum ImageGroupFixture { let image = try imageGroups()[versionIndex].first { $0.name == imageName } return try #require(image, "\(imageName) is not part of version \(labels[versionIndex])").machOFile } - - private static func machOFile(at libraryURL: URL) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } - } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift index 2ee8c92a..2c46c19e 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift @@ -363,13 +363,7 @@ package enum InitAccessorFixture { package static func machOFile(_ variant: Variant) async throws -> MachOFile { let libraryURL = try await libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.release` variant loaded into the test process — only that one: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift index 14a13fd8..01803311 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift @@ -472,13 +472,7 @@ package enum LocalTypeFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The variant loaded into the test process. diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift index 8c974d05..8c1405f9 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift @@ -92,57 +92,6 @@ package enum ModuleSelectorFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local - // one must compile the same source the same way. - "swiftc", "-swift-version", "5", "-emit-library", "-enable-library-evolution", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - /// Every name in `output` still qualified the dotted way by a module that /// `output` spells with a selector somewhere — what a print path writing a /// qualified name by hand, instead of through the type printer, leaves @@ -164,13 +113,17 @@ package enum ModuleSelectorFixture { return dottedQualifications } + /// Compiled once per process by the shared compiler. The source keeps + /// the file name it always had, which private discriminators hash. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: source)], + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + arguments: ["-swift-version", "5", "-enable-library-evolution"] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift index 201df54d..a4ded2f9 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift @@ -440,7 +440,7 @@ package enum ObjCImplementationFixture { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -470,12 +470,6 @@ package enum ObjCImplementationFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift index 283a3b23..419bd4e4 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift @@ -278,13 +278,7 @@ package enum ObservableMacroFixture { package static func machOFile(_ variant: Variant) async throws -> MachOFile { let libraryURL = try await libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.release` variant loaded into the test process — only that one: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift index b296b48c..76240f08 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift @@ -124,11 +124,6 @@ package enum ProtocolRequirementPlacementFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - /// The fixture: `supportSource` and `protocolSource` in one library. package static func machOFile() throws -> MachOFile { try machOFile(compiling: protocolSource) @@ -137,80 +132,18 @@ package enum ProtocolRequirementPlacementFixture { /// `supportSource` and `protocolDeclarations` compiled into one library /// named `moduleName`, as the fixture itself is, so every name a printed /// protocol mentions resolves to the same declaration again. Each - /// distinct source compiles once per process. + /// distinct source compiles once per process, by the shared compiler; + /// the source keeps the file name it always had, which private + /// discriminators hash. package static func machOFile(compiling protocolDeclarations: String) throws -> MachOFile { - let libraryURL = try CompiledLibraries.shared.libraryURL(for: supportSource + "\n\n" + protocolDeclarations) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private final class CompiledLibraries: @unchecked Sendable { - static let shared = CompiledLibraries() - - private let lock = NSLock() - - private var libraryURLsBySource: [String: URL] = [:] - - /// Compiles under the lock: two tests asking for the same source wait - /// for one compiler run. The wait is on `swiftc`, never on a pool - /// thread. - func libraryURL(for source: String) throws -> URL { - lock.lock() - defer { lock.unlock() } - if let libraryURL = libraryURLsBySource[source] { - return libraryURL - } - let libraryURL = try Self.compile(source) - libraryURLsBySource[source] = libraryURL - return libraryURL - } - - private static func compile(_ source: String) throws -> URL { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local - // one must compile the same source the same way. - "swiftc", "-swift-version", "5", "-emit-library", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: supportSource + "\n\n" + protocolDeclarations)], + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + arguments: ["-swift-version", "5"] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift index 09029a38..afba1a87 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift @@ -251,13 +251,7 @@ package enum RenamedObjCClassFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.full` client loaded into the test process — only that variant: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift index 3a5be1dd..8e065ee7 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift @@ -226,12 +226,6 @@ package enum Swift64DeclarationShapesFixture { }() package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: compilationResult.get()) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift index f19f30f8..e669b187 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift @@ -285,13 +285,7 @@ package enum SwiftDeclaredObjCProtocolsFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.full` client loaded into the test process — only that variant: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift index 11ee2c4e..2d5d8f75 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift @@ -183,13 +183,7 @@ package enum ThunkOnlyMemberFixture { } package static func machOFile(_ variant: Variant) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try libraryURL(variant)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL(variant)) } /// The `.wholeModuleOptimized` build loaded into the test process — only diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift index 9e56d04c..3ed5ba37 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift @@ -220,13 +220,7 @@ package enum UnobservablePresenceFixture { /// The compiled versions as readers, oldest first. package static func machOFiles() throws -> [MachOFile] { try libraryURLs().map { libraryURL in - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } } } diff --git a/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift b/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift index 3f60219c..f964789f 100644 --- a/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift @@ -21,7 +21,7 @@ struct ClassOfReceiverSendTests { private static let fixture = Result { // Without ARC, so no call the compiler adds stands among them. try CompiledFixture.load( - libraryName: "libCrossReferenceClassOfReceiver.dylib", + named: "CrossReferenceClassOfReceiver", sources: [ "ClassOfReceiver.m": """ #import diff --git a/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift b/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift index 310217b5..e18e7e29 100644 --- a/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift +++ b/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift @@ -1,38 +1,42 @@ import Foundation import MachOKit +import SwiftSectionFixtureSupport @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences /// A dynamic library compiled from source for one suite, rewritten after -/// linking when the suite asks, and loaded into the test process. +/// linking when the suite asks, and loaded into the test process. Suites that +/// only read a compiled binary as a file call `FixtureCompiler` directly. enum CompiledFixture { struct Failure: Error, CustomStringConvertible { let description: String } /// Compiles `sources` — file names and their contents — into the arm64 - /// library `libraryName`, hands the linked bytes to `rewrite` and signs - /// the result again when there is one, and loads it. The library stays - /// loaded after its directory is removed; the analyzers made from then on - /// see it under the path this returns. + /// library `lib.dylib` through the shared compiler, copies it to a + /// directory of its own, hands the copied bytes to `rewrite` and signs the + /// result again when there is one, and loads the copy. The compiled + /// library is shared by every test, so it is never rewritten itself. The + /// copy stays loaded after its directory is removed; the analyzers made + /// from then on see it under the path this returns. @discardableResult static func load( - libraryName: String, + named name: String, sources: KeyValuePairs, compilerArguments: [String], rewrite: ((inout Data, MachOFile) throws -> Void)? = nil ) throws -> String { + let compiledLibrary = try FixtureCompiler.shared.dynamicLibrary( + named: name, + language: .c, + sourceFiles: sources.map { FixtureSourceFile(name: $0.key, contents: $0.value) }, + arguments: ["-arch", "arm64"] + compilerArguments + ) let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } - var sourcePaths: [String] = [] - for (fileName, contents) in sources { - let sourceURL = directory.appendingPathComponent(fileName) - try contents.write(to: sourceURL, atomically: true, encoding: .utf8) - sourcePaths.append(sourceURL.path) - } - let library = directory.appendingPathComponent(libraryName) - try run("/usr/bin/xcrun", arguments: ["clang", "-dynamiclib", "-arch", "arm64"] + compilerArguments + ["-o", library.path] + sourcePaths) + let library = directory.appendingPathComponent(compiledLibrary.lastPathComponent) + try FileManager.default.copyItem(at: compiledLibrary, to: library) if let rewrite { var bytes = try Data(contentsOf: library) try rewrite(&bytes, try MachOFile(url: library)) @@ -41,46 +45,11 @@ enum CompiledFixture { try run("/usr/bin/codesign", arguments: ["--force", "--sign", "-", library.path]) } guard dlopen(library.path, RTLD_NOW | RTLD_LOCAL) != nil else { - throw Failure(description: "could not load \(libraryName): \(dlerror().map { String(cString: $0) } ?? "")") + throw Failure(description: "could not load \(library.lastPathComponent): \(dlerror().map { String(cString: $0) } ?? "")") } return library.path } - /// Compiles `sources` into the arm64 library `libraryName` and leaves it - /// on disk, unloaded, for a suite that reads it as a file. The caller - /// removes `directory`. - static func build( - libraryName: String, - sources: KeyValuePairs, - compilerArguments: [String], - architecture: String = "arm64", - isExecutable: Bool = false - ) throws -> (directory: URL, library: URL) { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - var sourcePaths: [String] = [] - for (fileName, contents) in sources { - let sourceURL = directory.appendingPathComponent(fileName) - try contents.write(to: sourceURL, atomically: true, encoding: .utf8) - sourcePaths.append(sourceURL.path) - } - let library = directory.appendingPathComponent(libraryName) - try run("/usr/bin/xcrun", arguments: ["clang"] + (isExecutable ? [] : ["-dynamiclib"]) + ["-arch", architecture] + compilerArguments + ["-o", library.path] + sourcePaths) - return (directory, library) - } - - /// Compiles one Swift source into the arm64 library `libraryName`, - /// optimized, and leaves it on disk. The caller removes `directory`. - static func buildSwift(libraryName: String, source: String) throws -> (directory: URL, library: URL) { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - let sourceURL = directory.appendingPathComponent("Fixture.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let library = directory.appendingPathComponent(libraryName) - try run("/usr/bin/xcrun", arguments: ["swiftc", "-O", "-emit-library", "-target", "arm64-apple-macos14", "-module-name", "Fixture", "-o", library.path, sourceURL.path]) - return (directory, library) - } - private static func run(_ executablePath: String, arguments: [String]) throws { let process = Process() process.executableURL = URL(fileURLWithPath: executablePath) diff --git a/Tests/CrossReferenceAnalysisTests/FileModeTests.swift b/Tests/CrossReferenceAnalysisTests/FileModeTests.swift index 3a54295a..f3a3efdf 100644 --- a/Tests/CrossReferenceAnalysisTests/FileModeTests.swift +++ b/Tests/CrossReferenceAnalysisTests/FileModeTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport import MachOKitExtensions @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @@ -192,16 +193,16 @@ struct FileModeTests { /// slot binds by name, to itself. The bind leads to the function; a call /// into a library the analyzer does not cover stays an imported name. @Test func standaloneAppResolvesImportedAndSelfBoundSymbols() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libSelfBound.dylib", - sources: ["SelfBound.c": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SelfBound", + language: .c, + sourceFiles: [FixtureSourceFile(name: "SelfBound.c", contents: """ #include __attribute__((noinline)) int selfBoundCallee(int value) { return value * 3; } int selfBoundCaller(int value) { puts("called"); return selfBoundCallee(value) + 1; } - """], - compilerArguments: ["-O1", "-Wl,-interposable"] + """)], + arguments: ["-arch", "arm64", "-O1", "-Wl,-interposable"] ) - defer { try? FileManager.default.removeItem(at: directory) } let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) #expect(analyzer.imageCount == 1) #expect(analyzer.images.isEmpty) @@ -220,19 +221,18 @@ struct FileModeTests { /// start, so the cleanup's calls are found: `_Unwind_Resume` is called /// nowhere else. @Test func fileModeScansExceptionCleanupCodeAfterReturn() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libCleanup.dylib", - sources: ["Cleanup.cpp": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "Cleanup", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Cleanup.cpp", contents: """ #include extern "C" __attribute__((noinline)) void cleanupCallee(void) { asm volatile(""); } struct Guard { ~Guard() { cleanupCallee(); } }; __attribute__((noinline)) void mayThrow(int value) { if (value > 3) throw std::runtime_error("too large"); } extern "C" int withCleanup(int value) { Guard guard; mayThrow(value); return value + 1; } - """], - compilerArguments: ["-O1", "-lc++"], - architecture: "arm64e" + """)], + arguments: ["-arch", "arm64e", "-O1", "-lc++"] ) - defer { try? FileManager.default.removeItem(at: directory) } let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) let withCleanup = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_withCleanup") }) let references = analyzer.references(madeBy: withCleanup) @@ -294,9 +294,10 @@ struct FileModeTests { /// selector references of `__objc_stubs` then lead nowhere, and every /// send through one reads as an unrecognized call. @Test func standaloneExecutableResolvesRebasesAndObjectiveCStubs() throws { - let (directory, executable) = try CompiledFixture.build( - libraryName: "ObjectiveCExecutable", - sources: ["Main.m": """ + let executable = try FixtureCompiler.shared.executable( + named: "ObjectiveCExecutable", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Main.m", contents: """ #import __attribute__((noinline)) static void target(void) { asm volatile(""); } void (*volatile functionPointer)(void) = target; @@ -308,11 +309,9 @@ struct FileModeTests { return (int)[array count]; } } - """], - compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"], - isExecutable: true + """)], + arguments: ["-arch", "arm64", "-O1", "-fobjc-arc", "-framework", "Foundation"] ) - defer { try? FileManager.default.removeItem(at: directory) } let file = try MachOFile(url: executable) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) let main = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_main") }) diff --git a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift index 1494d8a1..dc5ba4cd 100644 --- a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift +++ b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport @testable import CrossReferenceAnalysis @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @@ -48,19 +49,18 @@ struct FunctionStartOutsideTextTests { /// call planted in the padding before `__text` stands for whatever the /// load commands happen to decode to. @Test func anIndexKeepsTheReferencesOfAFunctionBelowText() throws { - let (directory, executable) = try CompiledFixture.build( - libraryName: "Executable", - sources: ["Main.c": """ + let executable = try FixtureCompiler.shared.executable( + named: "Executable", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Main.c", contents: """ __attribute__((noinline)) void target(void) { __asm__ volatile(""); } int main(void) { target(); return 0; } - """], - compilerArguments: ["-O1"], - isExecutable: true + """)], + arguments: ["-arch", "arm64", "-O1"] ) - defer { try? FileManager.default.removeItem(at: directory) } let linked = try MachOFile(url: executable) let textSection = try #require(linked.sections64.first { $0.segmentName == "__TEXT" && $0.sectionName == "__text" }) let loadCommandsEnd = MemoryLayout.size + Int(linked.header.sizeofcmds) @@ -72,6 +72,11 @@ struct FunctionStartOutsideTextTests { var bytes = try Data(contentsOf: executable) let call = InstructionEncoding.branchWithLink(at: siteAddress, to: target.location.address) withUnsafeBytes(of: call.littleEndian) { bytes.replaceSubrange(siteOffset ..< siteOffset + 4, with: $0) } + // The compiled executable is shared by every test; the patched copy + // goes to a directory of its own. + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } let patched = directory.appendingPathComponent("PatchedExecutable") try bytes.write(to: patched) diff --git a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift index db5fb296..27708177 100644 --- a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift +++ b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift @@ -1,5 +1,6 @@ import Foundation import Testing +import SwiftSectionFixtureSupport @testable import CrossReferenceAnalysis @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @@ -15,24 +16,16 @@ import Testing @Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) struct LazyBindingTests { @Test func aLazilyBoundStubReachesItsTarget() throws { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - let source = directory.appendingPathComponent("LazyBinding.c") - try "#include \nvoid crossReferenceLazyBindingCall(void) { puts(\"called\"); }\n".write(to: source, atomically: true, encoding: .utf8) - let library = directory.appendingPathComponent("libLazyBinding.dylib") - - let compiler = Process() - compiler.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - compiler.arguments = [ - "clang", "-dynamiclib", "-arch", "arm64", "-O1", - // Classic dyld info rather than chained fixups: lazy pointers and a __stub_helper. - "-mmacosx-version-min=11.0", "-Wl,-no_fixup_chains", - "-o", library.path, source.path, - ] - try compiler.run() - compiler.waitUntilExit() - try #require(compiler.terminationStatus == 0, "could not build the lazily bound fixture") + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "LazyBinding", + language: .c, + sourceFiles: [FixtureSourceFile(name: "LazyBinding.c", contents: "#include \nvoid crossReferenceLazyBindingCall(void) { puts(\"called\"); }\n")], + arguments: [ + "-arch", "arm64", "-O1", + // Classic dyld info rather than chained fixups: lazy pointers and a __stub_helper. + "-mmacosx-version-min=11.0", "-Wl,-no_fixup_chains", + ] + ) _ = try #require(dlopen(library.path, RTLD_LAZY | RTLD_LOCAL)) let analyzer = try #require(CrossReferenceAnalyzer()) diff --git a/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift b/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift index 82d5d6ac..e06ee55c 100644 --- a/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift +++ b/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift @@ -36,7 +36,7 @@ struct LinkerOptimizationHintTests { /// Both libraries, loaded before the analyzer that reads them is made. private static let fixtures = Result { try CompiledFixture.load( - libraryName: "libCrossReferenceLinkerHints.dylib", + named: "CrossReferenceLinkerHints", sources: [ "Probe.m": """ #import @@ -75,7 +75,7 @@ struct LinkerOptimizationHintTests { // A stub is shared by every call to its function, so the stub fixture // imports nothing a send needs. try CompiledFixture.load( - libraryName: "libCrossReferenceRewrittenStub.dylib", + named: "CrossReferenceRewrittenStub", sources: ["Stub.c": "#include \nvoid crossReferenceCallsThroughARewrittenStub(void) { puts(\"called\"); }\n"], compilerArguments: ["-O1", "-mmacosx-version-min=12.0"] ) { bytes, machO in diff --git a/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift b/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift index 6ffa3117..723d3672 100644 --- a/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import ARM64InstructionDecoding @@ -42,13 +43,14 @@ struct ReferenceKindAndRouteTests { } """ - private func objectiveCLibrary(stripped: Bool = false) throws -> (directory: URL, file: MachOFile) { - let (directory, library) = try CompiledFixture.build( - libraryName: "libKinds.dylib", - sources: ["Kinds.m": Self.objectiveCSource], - compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"] + (stripped ? ["-Wl,-x"] : []) + private func objectiveCLibrary(stripped: Bool = false) throws -> MachOFile { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "Kinds", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Kinds.m", contents: Self.objectiveCSource)], + arguments: ["-arch", "arm64", "-O1", "-fobjc-arc", "-framework", "Foundation"] + (stripped ? ["-Wl,-x"] : []) ) - return (directory, try MachOFile(url: library)) + return try MachOFile(url: library) } private func function(named name: String, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { @@ -67,8 +69,7 @@ struct ReferenceKindAndRouteTests { /// list, whose entry points at the same variable. @Test(arguments: [false, true]) func instanceVariableOffsetLoadsBecomeInstanceVariableReferences(stripped: Bool) throws { - let (directory, file) = try objectiveCLibrary(stripped: stripped) - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary(stripped: stripped) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) for method in ["-[Counter increment]", "-[Counter describe]"] { let references = analyzer.references(madeBy: try function(named: method, in: analyzer)) @@ -83,8 +84,7 @@ struct ReferenceKindAndRouteTests { /// Strings are recorded when the analyzer is made to, or for a query for /// a string key — not in a whole-image table otherwise. @Test func stringReferencesAreRecordedOnlyWhenRequested() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let withoutStrings = try CrossReferenceAnalyzer(machOFiles: [file]) #expect(!withoutStrings.recordsStringReferences) #expect(!withoutStrings.referenceTable(ofImageAt: 0).references.contains { reference in @@ -106,8 +106,7 @@ struct ReferenceKindAndRouteTests { /// A constant `CFString` is referenced by its characters, eight-bit or /// UTF-16 alike. @Test func constantStringReferencesCarryTheirCharacters() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let ascii = analyzer.references(madeBy: try function(named: "_constantStringFunction", in: analyzer)).map(\.target) #expect(ascii.contains(.constantString("a constant string literal")), "\(ascii)") @@ -121,12 +120,12 @@ struct ReferenceKindAndRouteTests { /// `add` to the characters, `sub #0x20`. The `add` names the string; the /// subtraction names no other. @Test func swiftLargeStringLiteralPointsAtItsCharacters() throws { - let (directory, library) = try CompiledFixture.buildSwift(libraryName: "libLargeString.dylib", source: """ + // The module is `Fixture`, which the expected symbol spells. + let library = try FixtureCompiler.shared.dynamicLibrary(named: "Fixture", language: .swift, source: """ @inline(never) public func largeStringLiteral() -> String { "a string literal longer than fifteen bytes" } - """) - defer { try? FileManager.default.removeItem(at: directory) } + """, arguments: ["-O", "-target", "arm64-apple-macos14"]) let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)], recordingStringReferences: true) let function = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_$s7Fixture18largeStringLiteralSSyF") }) let strings = analyzer.references(madeBy: function).filter { if case .cString = $0.target { true } else { false } } @@ -139,8 +138,7 @@ struct ReferenceKindAndRouteTests { /// address is built, an instance variable's offset is loaded through its /// slot. @Test func everyReferenceCarriesTheRouteItTook() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let references = analyzer.references(madeBy: try function(named: "_callEverything", in: analyzer)) func route(of target: CodeReferenceTarget) -> CodeReferenceRoute? { @@ -180,8 +178,7 @@ struct ReferenceKindAndRouteTests { /// The table and the index a host keeps answer the same — the new kinds /// and every route included. @Test func referenceIndexRoundTripsNewTargetsAndRoutes() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let table = analyzer.referenceTable(ofImageAt: 0) let index = analyzer.referenceIndex(ofImageAt: 0) diff --git a/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift b/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift index 3cc6a968..a0e05710 100644 --- a/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift +++ b/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift @@ -21,7 +21,7 @@ struct RuntimeSendEntryPointTests { private static let fixture = Result { // Without ARC, so no call the compiler adds stands among them. try CompiledFixture.load( - libraryName: "libCrossReferenceRuntimeSends.dylib", + named: "CrossReferenceRuntimeSends", sources: [ "Sends.m": """ #import diff --git a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift index 81d2c1fa..82ade1c2 100644 --- a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift +++ b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import ARM64InstructionDecoding @@ -113,16 +114,16 @@ struct SymbolicationTests { /// library the analyzer does not cover, or — linked `-interposable` — to /// its own function. @Test func symbolicatesGlobalOffsetTableSlotToItsBoundSymbol() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libSlots.dylib", - sources: ["Slots.c": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "Slots", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Slots.c", contents: """ #include __attribute__((noinline)) int slotCallee(int value) { return value * 5; } int slotCaller(int value) { puts("calling"); return slotCallee(value); } - """], - compilerArguments: ["-O1", "-Wl,-interposable"] + """)], + arguments: ["-arch", "arm64", "-O1", "-Wl,-interposable"] ) - defer { try? FileManager.default.removeItem(at: directory) } let file = try MachOFile(url: library) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) let callee = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_slotCallee") }) @@ -173,9 +174,10 @@ struct SymbolicationTests { /// Strings, an instance variable's offset variable and a selector /// reference, in a library compiled for the test. @Test func symbolicatesStringsAndObjectiveCSlots() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libObjectiveCSlots.dylib", - sources: ["Slots.m": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "ObjectiveCSlots", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Slots.m", contents: """ #import @interface Holder : NSOperation { @public long _held; } @end @@ -184,10 +186,9 @@ struct SymbolicationTests { long readHeld(Holder *holder) { return holder->_held; } const char *cString(void) { return "symbolicated characters"; } NSString *constantString(void) { return @"symbolicated constant"; } - """], - compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"] + """)], + arguments: ["-arch", "arm64", "-O1", "-fobjc-arc", "-framework", "Foundation"] ) - defer { try? FileManager.default.removeItem(at: directory) } let file = try MachOFile(url: library) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let references = analyzer.referenceTable(ofImageAt: 0).references diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift index a6e309e8..e560e2c7 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift @@ -88,21 +88,6 @@ extension SwiftDiffableInterfaceBuilderTests { } } -/// Selects the preferred-architecture slice from a loaded `File`, mirroring the -/// loading convention of `SwiftSectionTestingSupport`'s single-binary base classes. -/// Shared by every cross-version base class below so the fat/thin handling lives -/// in one place. -private func selectMachOFile(from file: File, architecture: CPUType) throws -> MachOFile { - switch file { - case .fat(let fatFile): - return try required(fatFile.machOFiles().first(where: { $0.header.cpuType == architecture }) ?? fatFile.machOFiles().first) - case .machO(let machO): - return machO - @unknown default: - fatalError() - } -} - enum SwiftDiffableInterfaceBuilderTestSuite { /// Loads a fixed `(old, new)` pair of `MachOFile`s by name — the two-binary /// counterpart of `SwiftSectionTestingSupport.MachOFileTests`, which only loads one. @@ -113,11 +98,10 @@ enum SwiftDiffableInterfaceBuilderTestSuite { class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - class var preferredArchitecture: CPUType { .arm64 } init() async throws { - self.oldMachOFile = try selectMachOFile(from: loadFromFile(named: Self.oldFileName), architecture: Self.preferredArchitecture) - self.newMachOFile = try selectMachOFile(from: loadFromFile(named: Self.newFileName), architecture: Self.preferredArchitecture) + self.oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.oldFileName)) + self.newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.newFileName)) } } @@ -158,7 +142,6 @@ enum SwiftDiffableInterfaceBuilderTestSuite { class var oldXcodeApplicationPath: String { "/Applications/Xcode-26.3.0.app" } class var newXcodeApplicationPath: String { "/Applications/Xcode-26.4.0.app" } class var sharedFrameworkName: String { "DVTProductsUI" } - class var preferredArchitecture: CPUType { .arm64 } init() async throws { self.oldMachOFile = try Self.loadSharedFramework(inXcodeAt: Self.oldXcodeApplicationPath) @@ -168,7 +151,7 @@ enum SwiftDiffableInterfaceBuilderTestSuite { private class func loadSharedFramework(inXcodeAt xcodeApplicationPath: String) throws -> MachOFile { let name = sharedFrameworkName let binaryPath = "\(xcodeApplicationPath)/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" - return try selectMachOFile(from: File.loadFromFile(url: URL(fileURLWithPath: binaryPath)), architecture: preferredArchitecture) + return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift index 8c2b636b..975f5c7b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift @@ -34,17 +34,6 @@ final class CoroFunctionPointerTests: FixtureSuite, @unchecked Sendable { // MARK: - Fixture - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, /// "On-the-fly-compiled fixture dylibs need a class"). `Holder.first` is /// the payload: a `_read` accessor, which under CoroutineAccessors lowers @@ -66,71 +55,40 @@ final class CoroFunctionPointerTests: FixtureSuite, @unchecked Sendable { } """ - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "coro-function-pointer fixture compilation failed:\n\(diagnostics)" } + /// Both compiles failed; carries what each one reported. + private struct BothCompilationsFailedError: Swift.Error, CustomStringConvertible { + let withFeatureFlagFailure: any Swift.Error + let withoutFeatureFlagFailure: any Swift.Error + var description: String { "coro-function-pointer fixture compilation failed:\n\(withFeatureFlagFailure)\n\(withoutFeatureFlagFailure)" } } - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("CoroFunctionPointerFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("CoroFunctionPointerFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libCoroFunctionPointerFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - // The feature is still experimental, so it must be requested by - // name; should it ever graduate, the flag becomes unknown and the - // compile fails, so fall back to building without it — the - // accessors lower to `yield_once_2` either way once it is on by - // default. `-enable-library-evolution` is what forces the - // accessors to be dispatched (and therefore emitted) at all. - var lastDiagnostics = "" - func compile(withCoroutineAccessorsFlag requestsFeature: Bool) throws -> Int32 { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - var arguments = [ - "swiftc", "-emit-library", - "-module-name", "CoroFunctionPointerFixture", - "-enable-library-evolution", - ] - if requestsFeature { - arguments += ["-enable-experimental-feature", "CoroutineAccessors"] - } - arguments += [sourceURL.path, "-o", libraryURL.path] - process.arguments = arguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - lastDiagnostics = String(decoding: standardErrorPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) - process.waitUntilExit() - return process.terminationStatus - } - - if try compile(withCoroutineAccessorsFlag: true) != 0 { - let withFlagDiagnostics = lastDiagnostics - guard try compile(withCoroutineAccessorsFlag: false) == 0 else { - throw FixtureCompilationError(diagnostics: withFlagDiagnostics + lastDiagnostics) - } - } - return libraryURL + private func loadFixtureMachOFile() throws -> MachOFile { + // The feature is still experimental, so it must be requested by + // name; should it ever graduate, the flag becomes unknown and the + // compile fails, so fall back to building without it — the + // accessors lower to `yield_once_2` either way once it is on by + // default. `-enable-library-evolution` is what forces the + // accessors to be dispatched (and therefore emitted) at all. + func compile(withCoroutineAccessorsFlag requestsFeature: Bool) throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "CoroFunctionPointerFixture", + language: .swift, + source: Self.fixtureSource, + arguments: ["-enable-library-evolution"] + (requestsFeature ? ["-enable-experimental-feature", "CoroutineAccessors"] : []) + ) } - }() - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + let libraryURL: URL + do { + libraryURL = try compile(withCoroutineAccessorsFlag: true) + } catch let withFeatureFlagFailure { + do { + libraryURL = try compile(withCoroutineAccessorsFlag: false) + } catch let withoutFeatureFlagFailure { + throw BothCompilationsFailedError(withFeatureFlagFailure: withFeatureFlagFailure, withoutFeatureFlagFailure: withoutFeatureFlagFailure) + } } + return try HostSlice.machOFile(at: libraryURL) } /// The one `…Twc` record in the fixture, plus the file it came from. diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift index e9b9ca9a..d57aacd8 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift @@ -7,6 +7,7 @@ import MachOFoundation import Demangling @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftSymbols +import SwiftSectionFixtureSupport /// An opaque type reference spells its generic arguments as one list per /// declaration around the opaque result, outermost first, and the mangler @@ -29,22 +30,6 @@ import Demangling /// carries the argument lists the mangler writes for these declarations. @Suite struct OpaqueTypeArgumentDepthTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-type-argument-depth fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "OpaqueTypeArgumentDepthFixture" /// `FixtureAnchor` is ballast: a fixture dylib with no class has no @@ -88,47 +73,14 @@ struct OpaqueTypeArgumentDepthTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// The offset of the opaque type descriptor of the declaration named diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift index 49fc772a..ffabf0ce 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift @@ -7,6 +7,7 @@ import MachOFoundation import Demangling @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftSymbols +import SwiftSectionFixtureSupport /// A declaration may produce more than one opaque type — `-> Pair` /// is two — and the demangled `opaqueType` node says which one it is in its @@ -23,17 +24,6 @@ import Demangling /// survived a full dump of both. @Suite struct OpaqueTypeOrdinalTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, /// "On-the-fly-compiled fixture dylibs need a class"). /// @@ -77,52 +67,14 @@ struct OpaqueTypeOrdinalTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueTypeOrdinalFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("OpaqueTypeOrdinalFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libOpaqueTypeOrdinalFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "OpaqueTypeOrdinalFixture", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-type-ordinal fixture compilation failed:\n\(diagnostics)" } - } - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "OpaqueTypeOrdinalFixture", + language: .swift, + source: Self.fixtureSource, + arguments: ["-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// `…QOMQ` is the opaque type descriptor's own symbol; `makeOpaquePair`'s diff --git a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift index d1809043..4d057756 100644 --- a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection import SwiftDeclarationRendering import SwiftDump +import SwiftSectionFixtureSupport @_spi(Internals) import SwiftInspection import SwiftThunkAnalysis import Demangling @@ -129,12 +130,7 @@ struct OpaqueWitnessDumpAnnotationTests { private func loadClient() throws -> (client: MachOFile, corePath: String) { let fixture = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: fixture.clientLibraryURL) { - case .machO(let machOFile): - return (machOFile, fixture.coreLibraryURL.path) - case .fat(let fatFile): - return (try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }), fixture.coreLibraryURL.path) - } + return (try HostSlice.machOFile(at: fixture.clientLibraryURL), fixture.coreLibraryURL.path) } /// The dump of every conformance in the client, keyed by diff --git a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift index 5dd0b97f..5a0acd84 100644 --- a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift +++ b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift @@ -27,17 +27,6 @@ import Semantic /// premise of every test here rather than a soft check. @Suite(.serialized) struct VTableSlotAttributionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `alpha` / `beta` / `gamma` have byte-identical (empty) bodies and fold /// onto one address. `Nested.nestedNoop` folds onto the SAME address and is /// the cross-type trap: its demangled tree's first class node is `Host`, so @@ -60,54 +49,23 @@ struct VTableSlotAttributionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("VTableAttributionFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("VTableAttributionFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libVTableAttributionFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + private struct FixtureLookupError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "vtable-attribution fixture lookup failed:\n\(diagnostics)" } + } - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "VTableAttributionFixture", - sourceURL.path, "-o", libraryURL.path, + private func loadFixtureMachOFile() throws -> MachOFile { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "VTableAttributionFixture", + language: .swift, + source: Self.fixtureSource, + arguments: [ // ld64's identical-code-folding switch: without it the empty // bodies keep four distinct addresses and nothing is ambiguous. "-Xlinker", "-deduplicate", ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "vtable-attribution fixture compilation failed:\n\(diagnostics)" } - } - - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + ) + return try HostSlice.machOFile(at: libraryURL) } private func classDescriptor(named name: String, in machOFile: MachOFile) throws -> ClassDescriptor { @@ -117,7 +75,7 @@ struct VTableSlotAttributionTests { return classDescriptor } Issue.record("fixture is missing the class \(name)") - throw FixtureCompilationError(diagnostics: "class \(name) not found") + throw FixtureLookupError(diagnostics: "class \(name) not found") } /// The vtable slot declarations of a dumped class, in slot order, as @@ -292,13 +250,7 @@ enum SimulatorRuntimeSwiftUICore { struct GraphHostVTableAttributionTests { private func graphHostDump() async throws -> String { let url = try #require(SimulatorRuntimeSwiftUICore.url) - let machOFile: MachOFile - switch try MachOKit.loadFromFile(url: url) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: url) for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor, diff --git a/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift b/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift index cc348473..5fdc5676 100644 --- a/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift +++ b/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift @@ -5,6 +5,7 @@ import MachOKit @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing import OrderedCollections +import SwiftSectionFixtureSupport /// A type declared inside `extension { … }` is filed under a /// synthetic extension of that C type, keyed by an `ExtensionName` whose @@ -93,7 +94,7 @@ struct CImportedExtensionKindTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -109,14 +110,7 @@ struct CImportedExtensionKindTests { } private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) } private func typeExtensionKind(of extendedTypeName: String) async throws -> ExtensionKind { diff --git a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift index f98052fa..4e03ab4d 100644 --- a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift +++ b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift @@ -107,13 +107,7 @@ struct PrivateDeclarationsWholeTreeTests { /// SymbolTestsCore declares private types (`PrivateDoppelgangers.swift`, /// `Structs.swift`), so here the names compared do read some. @Test func symbolTestsCore() async throws { - let machOFile: MachOFile - switch try loadFromFile(named: .SymbolTestsCore) { - case .machO(let thinMachOFile): - machOFile = thinMachOFile - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(in: loadFromFile(named: .SymbolTestsCore)) let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: machOFile) try await indexer.prepare() diff --git a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift index e31edf1c..c2cc595b 100644 --- a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift @@ -7,6 +7,7 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing import OrderedCollections +import SwiftSectionFixtureSupport /// Two modules compiled on the fly, each carrying a class (a struct-only /// fixture dylib has no `__DATA` segment and MachOKit before 0.52.103 mis-walked @@ -139,12 +140,7 @@ enum WrappedPropertyFixture { } static func machOFile(at url: URL) throws -> MachOFile { - switch try File.loadFromFile(url: url) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: url) } /// Loads both dylibs into the test process (the kit first, so the diff --git a/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift b/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift index 37680ea5..f0404f15 100644 --- a/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift +++ b/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift @@ -1,5 +1,6 @@ import Foundation import Testing +import SwiftSectionFixtureSupport @testable import SwiftInspection // MARK: - Test Enum @@ -42,17 +43,12 @@ private enum Arm64eProbeHost { /// `nil` when the host can execute arm64e third-party processes; otherwise /// the reason the probe layer must skip. static let arm64eExecutionUnavailabilityReason: String? = { - let canarySourceURL = temporaryDirectoryURL.appendingPathComponent("canary.c") - let canaryBinaryURL = temporaryDirectoryURL.appendingPathComponent("canary") - do { - try "int main(void) { return 42; }\n".write(to: canarySourceURL, atomically: true, encoding: .utf8) - } catch { - return "cannot write canary source: \(error)" - } - guard let compileResult = try? spawn( - executablePath: "/usr/bin/xcrun", - arguments: ["clang", "-arch", "arm64e", "-o", canaryBinaryURL.path, canarySourceURL.path] - ), compileResult.exitCode == 0 else { + guard let canaryBinaryURL = try? FixtureCompiler.shared.executable( + named: "canary", + language: .c, + source: "int main(void) { return 42; }\n", + arguments: ["-arch", "arm64e"] + ) else { return "clang cannot produce an arm64e canary on this host" } guard let runResult = try? spawn(executablePath: canaryBinaryURL.path, arguments: []) else { diff --git a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift index 54c10fd0..4ae5534d 100644 --- a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift +++ b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift @@ -5,6 +5,7 @@ import MachOFoundation @_spi(Internals) import Demangling @testable import MachOSwiftSection @_spi(Internals) @testable import SwiftInspection +import SwiftSectionFixtureSupport // Evolution proposal `type-import-info-identity`: a descriptor-derived // demangling of a C-imported type must spell the type the way the compiler @@ -237,7 +238,7 @@ struct CImportedTypeIdentityFixtureTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -253,14 +254,7 @@ struct CImportedTypeIdentityFixtureTests { } private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: try Self.fixtureCompilationResult.get()) } private func holderFieldMangledTypeNames(in machOFile: MachOFile) throws -> [String: MangledName] { diff --git a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift index 9d833df5..8f34205a 100644 --- a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift +++ b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift @@ -8,6 +8,7 @@ import Demangling @testable @_spi(Internals) import SwiftObjCInterop import MachOKitExtensions import MachOResolving +import SwiftSectionFixtureSupport /// A symbol's value is the binary's own claim about where something sits, and /// two indexes read the bytes there: `SymbolicManglingIndex` (the mangled name @@ -99,13 +100,7 @@ struct MalformedSymbolValueTests { } private static func fixtureFile() throws -> MachOFile { - let libraryURL = try fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: fixtureCompilationResult.get()) } @Test("a symbolic-mangling symbol whose value is no offset is counted unpaired instead of read") diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift index 0c3773c1..19d4d3f1 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift @@ -5,6 +5,7 @@ import MachOFoundation @_spi(Internals) import Demangling @testable import MachOSwiftSection @_spi(Internals) @testable import SwiftInspection +import SwiftSectionFixtureSupport /// `SymbolicDemangler`'s two fixed-shape node extractions (evolution proposal /// `metadata-reader-deterministic-node-extraction`). @@ -138,17 +139,6 @@ struct SymbolicDemanglerFixedShapeExtractionTests { // MARK: - Real `\x0C` references from an on-the-fly fixture - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, /// "On-the-fly-compiled fixture dylibs need a class"). `Holder`'s two /// fields are what put ObjC protocols into mangled type names: a single @@ -170,54 +160,24 @@ struct SymbolicDemanglerFixedShapeExtractionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ObjCProtocolReferenceFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("ObjCProtocolReferenceFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libObjCProtocolReferenceFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "ObjCProtocolReferenceFixture", - // The deployment target that turns ObjC-protocol symbolic - // references on (feature availability 6.0 = macOS 15). - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "ObjC-protocol-reference fixture compilation failed:\n\(diagnostics)" } } + /// Compiled once per process by the shared compiler. private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ObjCProtocolReferenceFixture", + language: .swift, + source: Self.fixtureSource, + arguments: [ + // The deployment target that turns ObjC-protocol symbolic + // references on (feature availability 6.0 = macOS 15). + "-target", "arm64-apple-macosx15.0", + ] + ) + return try HostSlice.machOFile(at: libraryURL) } private func holderFieldMangledTypeName(named fieldName: String, in machOFile: MachOFile) throws -> MangledName { diff --git a/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift b/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift index 79fce5b0..2a9e7bdf 100644 --- a/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift @@ -5,6 +5,7 @@ import MachOKit @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionTestingSupport /// Evolution proposal `type-import-info-identity`: the conformance extensions /// the importer synthesizes for C-imported types render as ONE block per @@ -96,7 +97,7 @@ struct CImportedTypeConformanceInterfaceTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -112,14 +113,7 @@ struct CImportedTypeConformanceInterfaceTests { } private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) } private func buildInterface() async throws -> String { diff --git a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift index c9537bf4..c021da68 100644 --- a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift +++ b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift @@ -22,22 +22,6 @@ import SwiftSectionTestingSupport /// written into the witness record, so the fixture here is built for it. @Suite struct ConditionalWitnessCommentStructureTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "conditional-witness fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "CommentStructureConditionalWitnessFixture" /// `FixtureAnchor` is ballast: a fixture dylib with no class has no @@ -68,48 +52,14 @@ struct ConditionalWitnessCommentStructureTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", - "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private func printInterface(marksCommentStructure: Bool) async throws -> FrozenSemanticString { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + let machOFile = try HostSlice.machOFile(at: libraryURL) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.marksCommentStructure = marksCommentStructure let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) diff --git a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift index a8ddfb92..b489c02e 100644 --- a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift +++ b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift @@ -8,6 +8,7 @@ import Demangling import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionTestingSupport /// An associated-type witness built from a `some` result that lives in /// ANOTHER image — the shape SwiftUI's `SidebarListBody.CollectionViewBody.Body` @@ -135,12 +136,7 @@ struct CrossImageOpaqueReferenceTests { private func loadClient() throws -> (client: MachOFile, corePath: String) { let fixture = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: fixture.clientLibraryURL) { - case .machO(let machOFile): - return (machOFile, fixture.coreLibraryURL.path) - case .fat(let fatFile): - return (try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }), fixture.coreLibraryURL.path) - } + return (try HostSlice.machOFile(at: fixture.clientLibraryURL), fixture.coreLibraryURL.path) } /// How the two unexpandable witnesses must be spelled: the attribute the diff --git a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift index 479f102b..ba535ff0 100644 --- a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift +++ b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift @@ -136,13 +136,7 @@ enum DescriptorOnlyMemberFixture { } static func machOFile(_ variant: Variant) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try libraryURL(variant)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL(variant)) } /// The `.strippedLocals` copy loaded into the test process — only that diff --git a/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift b/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift index ed323770..01ba30df 100644 --- a/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift +++ b/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift @@ -4,6 +4,7 @@ import MachOKit import Semantic @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import SwiftSectionTestingSupport /// The diff path's member-indentation contract, unified with the evolution /// path: members render at printer level 0 — the accessor block's interior @@ -90,7 +91,7 @@ struct DiffMemberIndentationTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -110,14 +111,7 @@ struct DiffMemberIndentationTests { private func loadFixtureMachOFiles() throws -> [MachOFile] { try Self.fixtureCompilationResult.get().map { libraryURL in - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL) } } diff --git a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift index e306a2aa..392e6bbb 100644 --- a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift +++ b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift @@ -55,79 +55,30 @@ enum ExecutableImageFixture { print(host.alpha() + host.beta(), OffsetHost.sharedNames.count) """ - struct CompilationError: Swift.Error, CustomStringConvertible { - let step: String - let diagnostics: String - var description: String { "\(ExecutableImageFixture.moduleName) fixture \(step) failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let librarySourceURL = workingDirectory.appendingPathComponent("OffsetHost.swift") - let mainSourceURL = workingDirectory.appendingPathComponent("main.swift") - try librarySource.write(to: librarySourceURL, atomically: true, encoding: .utf8) - try mainSource.write(to: mainSourceURL, atomically: true, encoding: .utf8) - let executableURL = workingDirectory.appendingPathComponent(moduleName) - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - // The language mode pinned so CI's toolchain and a newer local one - // compile the same source the same way; `-g` leaves the debug map - // in the symbol table. - let commonArguments = ["swiftc", "-swift-version", "5", "-Onone", "-g", "-module-name", moduleName] - try run(step: "swiftc (executable)", commonArguments + [librarySourceURL.path, mainSourceURL.path, "-o", executableURL.path]) - try run(step: "swiftc (library)", commonArguments + ["-emit-library", librarySourceURL.path, "-o", libraryURL.path]) - return [.executable: executableURL, .library: libraryURL] - } - }() - - private static func run(step: String, _ arguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = arguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - + /// The executable links `OffsetHost.swift` and `main.swift`; the library + /// is `OffsetHost.swift` alone. The shared compiler builds each once per + /// process. static func url(_ variant: Variant) throws -> URL { - let products = try compilationResult.get() - guard let url = products[variant] else { - throw CompilationError(step: "lookup", diagnostics: "no product for variant \(variant.rawValue)") + let librarySourceFile = FixtureSourceFile(name: "OffsetHost.swift", contents: librarySource) + // The language mode pinned so CI's toolchain and a newer local one + // compile the same source the same way; `-g` leaves the debug map + // in the symbol table. + let arguments = ["-swift-version", "5", "-Onone", "-g"] + switch variant { + case .executable: + return try FixtureCompiler.shared.executable( + named: moduleName, + language: .swift, + sourceFiles: [librarySourceFile, FixtureSourceFile(name: "main.swift", contents: mainSource)], + arguments: arguments + ) + case .library: + return try FixtureCompiler.shared.dynamicLibrary(named: moduleName, language: .swift, sourceFiles: [librarySourceFile], arguments: arguments) } - return url } static func machOFile(_ variant: Variant) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try url(variant)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: url(variant)) } /// The library loaded into the test process. The executable cannot be: diff --git a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift index 484292ea..55704144 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionTestingSupport /// A type declared in an extension of another module's type is parented on an /// extension context descriptor, so every name for it — the offline one from @@ -19,56 +20,6 @@ import Semantic /// interface cannot spell. @Suite(.serialized) struct ExtensionContextTypeNameTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "extension-context fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ExtensionContextFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("ExtensionContexts.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeExtensionContext.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeExtensionContext", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// `FixtureAnchor` is ballast: a struct-only fixture dylib has no `__DATA` /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. /// `Holder` is what references the nested types, so their names are printed @@ -104,14 +55,13 @@ struct ExtensionContextTypeNameTests { """ private func renderInterface() async throws -> String { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeExtensionContext", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ExtensionContexts.swift", contents: Self.source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + let machOFile = try HostSlice.machOFile(at: libraryURL) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) try await builder.prepare() return try await builder.printRoot().string diff --git a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift index 185c2591..63ae3b21 100644 --- a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift +++ b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift @@ -5,6 +5,7 @@ import MachOKitExtensions @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionTestingSupport /// Regression tests for binaries carrying the legacy `LC_DYLD_INFO(_ONLY)` /// opcode-based fixups (deployment target < macOS 12 / iOS 16, e.g. every @@ -23,64 +24,6 @@ import Semantic /// format as the iOS 15.5 simulator frameworks that surfaced the bug. @Suite(.serialized) struct LegacyDyldInfoBindTests { - /// The fixture's working directory must outlive every test in the - /// (serialized) suite, so it is removed at process exit rather than per - /// test. A crashed run still leaks one directory; the unique name keeps - /// that harmless and non-colliding across parallel test processes. - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("LegacyDyldInfoBindFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("LegacyFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libLegacyFixture.dylib") - try Self.fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - // macOS 11 predates chained fixups, forcing LC_DYLD_INFO_ONLY output. - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "LegacyFixture", - "-target", "arm64-apple-macosx11.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit: diagnostics beyond the ~64 KB pipe - // buffer would otherwise deadlock compiler and parent (the child - // blocked writing, the parent parked waiting) — and because this - // is a static let under a serialized suite, that deadlock would - // hang the whole test run instead of reporting a failure. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - let diagnostics = String(decoding: diagnosticsData, as: UTF8.self) - throw LegacyFixtureCompilationError(diagnostics: diagnostics) - } - return libraryURL - } - }() - - private struct LegacyFixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "Legacy fixture compilation failed:\n\(diagnostics)" } - } - private static let fixtureSource = """ import Foundation @@ -108,15 +51,14 @@ struct LegacyDyldInfoBindTests { """ private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "LegacyFixture", + language: .swift, + source: Self.fixtureSource, + // macOS 11 predates chained fixups, forcing LC_DYLD_INFO_ONLY output. + arguments: ["-target", "arm64-apple-macosx11.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } private func buildInterfaceOutput(of machOFile: MachOFile) async throws -> String { diff --git a/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift index 031b7800..f39a5b8c 100644 --- a/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift @@ -254,13 +254,7 @@ struct ObjCImportedDefinitionTests { /// separately shipped dylib: a category on a class of another image /// stays a category. @Test func aCategoryOnAClassOfAnotherImage() async throws { - let categoriesLibrary: MachOFile - switch try MachOKit.loadFromFile(url: ObjCImplementationFixture.categoriesLibraryURL()) { - case .machO(let machOFile): - categoriesLibrary = machOFile - case .fat(let fatFile): - categoriesLibrary = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let categoriesLibrary = try HostSlice.machOFile(at: ObjCImplementationFixture.categoriesLibraryURL()) let builder = try await builder(of: categoriesLibrary) #expect(builder.indexer.objcImportedCategoryUniqueNames == ["NSObject(SeparatelyShipped)"]) let definition = try #require(builder.indexer.objcImportedCategoryDefinition(uniqueName: "NSObject(SeparatelyShipped)")) diff --git a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift index 02d196cd..36d75cfc 100644 --- a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionTestingSupport /// The spelling of an opaque result type's constraints beyond the plain /// `some Protocol` shape the fixture covers. @@ -27,56 +28,6 @@ import Semantic /// its `` and `Set` printed as `Swift.Set`. @Suite(.serialized) struct OpaqueConstraintRenderingTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-constraint fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueConstraintFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("OpaqueConstraints.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueConstraint.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeOpaqueConstraint", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// The classes double as ballast: a struct-only fixture dylib has no /// `__DATA` segment and MachOKit before 0.52.103 mis-walked its chained-fixup /// pages. @@ -104,14 +55,13 @@ struct OpaqueConstraintRenderingTests { """ private func renderInterface() async throws -> String { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeOpaqueConstraint", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "OpaqueConstraints.swift", contents: Self.source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + let machOFile = try HostSlice.machOFile(at: libraryURL) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) try await builder.prepare() diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift index c3eaf372..627e9685 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift @@ -7,6 +7,7 @@ import MachOSwiftSection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionTestingSupport /// The depth of an opaque result's parameters: the innermost depth of the /// descriptor's own layout, counted over every context above it that adds @@ -198,13 +199,7 @@ struct OpaqueParameterDepthTests { } private static func machOFile() throws -> MachOFile { - let libraryURL = try fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - return file - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: fixtureCompilationResult.get()) } /// The fixture loaded into the process, read the way RuntimeViewer reads diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift index fcbbb497..919f869d 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionFixtureSupport /// `SwiftInterfaceBuilderOpaqueTypeProvider` finds an opaque result's /// constraint at the depth of the opaque parameters, which it counts from the @@ -20,22 +21,6 @@ import Semantic /// 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: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-parameter extension-depth fixture compilation failed:\n\(diagnostics)" } - } - private struct MissingConstraint: Swift.Error, CustomStringConvertible { let interface: String var description: String { "the opaque result did not print its constraint:\n\(interface)" } @@ -61,48 +46,20 @@ struct OpaqueParameterInMultiDepthExtensionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueParameterExtensionDepthFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("OpaqueParameterExtensionDepth.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueExtensionDepth.dylib") - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeOpaqueExtensionDepth", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeOpaqueExtensionDepth", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "OpaqueParameterExtensionDepth.swift", contents: source)], + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } /// The fixture's interface with the opaque type provider attached, as /// `interface --parse-opaque-return-type` and RuntimeViewer print it; it /// throws unless the opaque result names its constraint. static func printInterfaceNamingTheOpaqueConstraint() async throws { - let libraryURL = try fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: libraryURL()) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) try await builder.prepare() diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift index 7f808570..0e223ab9 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionFixtureSupport /// An opaque parameter that carries no runtime-visible protocol requirement. /// @@ -28,56 +29,6 @@ import Semantic /// plus one for a generic member's own parameters. @Suite(.serialized) struct OpaqueParameterWithoutProtocolRequirementTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-parameter fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueParameterFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("OpaqueParameters.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueParameter.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeOpaqueParameter", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// The class is ballast: a struct-only fixture dylib has no `__DATA` /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. private static let source = """ @@ -102,15 +53,17 @@ struct OpaqueParameterWithoutProtocolRequirementTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeOpaqueParameter", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "OpaqueParameters.swift", contents: source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + } + private func renderInterface() async throws -> String { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: Self.libraryURL()) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) try await builder.prepare() diff --git a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift index 8085d377..77ebf26d 100644 --- a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift @@ -8,6 +8,7 @@ import Demangling import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionFixtureSupport /// An associated-type witness that is a *member* of another module's opaque /// archetype — `(↻τ.Element)` in the generics book's notation, spelled @@ -134,12 +135,7 @@ struct ProjectedOpaqueMemberWitnessTests { private func loadClient() throws -> (client: MachOFile, corePath: String) { let fixture = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: fixture.clientLibraryURL) { - case .machO(let machOFile): - return (machOFile, fixture.coreLibraryURL.path) - case .fat(let fatFile): - return (try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }), fixture.coreLibraryURL.path) - } + return (try HostSlice.machOFile(at: fixture.clientLibraryURL), fixture.coreLibraryURL.path) } /// `typealias = …` as the compiler's own interface spells it, keyed diff --git a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift index 700b2465..3057ada7 100644 --- a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift +++ b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionFixtureSupport /// `@Wrapper var x: Int` makes the compiler synthesize a stored `_x` of the /// wrapper type and, when the wrapper projects, a computed `$x`. The source @@ -17,56 +18,6 @@ import Semantic /// chained-fixup pages). @Suite(.serialized) struct PropertyWrapperSynthesizedMemberTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "property-wrapper fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("PropertyWrapperFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("Wrappers.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeWrappers.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeWrappers", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - private static let source = """ public final class ProbeAnchor {} @@ -100,14 +51,17 @@ struct PropertyWrapperSynthesizedMemberTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeWrappers", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Wrappers.swift", contents: source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + } + private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: Self.libraryURL()) } @Test func theInterfaceShowsTheDeclaredPropertyNotItsSynthesizedMembers() async throws { @@ -157,7 +111,7 @@ struct PropertyWrapperSynthesizedMemberTests { /// that drives `SwiftDeclarationPrinter` directly, as RuntimeViewer /// does, gets the hiding and the attribute without any wiring. @Test func theInProcessReaderRendersTheSameWrapperAttribute() async throws { - let libraryURL = try Self.fixtureCompilationResult.get() + let libraryURL = try Self.libraryURL() _ = libraryURL.path.withCString { dlopen($0, RTLD_LAZY) } // `MachOImage(name:)` matches the loaded image by its bare file name. let machOImage = try #require(MachOImage(name: "libProbeWrappers"), "the fixture dylib did not load in-process") diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift index 3503dae6..260959f0 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import Semantic +import SwiftSectionFixtureSupport /// A protocol declared in an extension of another module's type prints its /// default-implementation extensions in the interface's top-level block for @@ -23,22 +24,6 @@ import Semantic /// 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 = """ @@ -57,52 +42,19 @@ struct ProtocolInExtensionDefaultWitnessTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ProtocolInExtensionDefaultWitnessFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("ProtocolInExtensionDefaultWitness.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeDefaultWitness.dylib") + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeDefaultWitness", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ProtocolInExtensionDefaultWitness.swift", contents: source)], // Library evolution makes `Labeled` resilient, which is what // gives its requirement a default witness of its own. - try run(swiftcArguments: [ - "-swift-version", "5", "-O", "-emit-library", "-enable-library-evolution", - "-module-name", "ProbeDefaultWitness", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } + arguments: ["-swift-version", "5", "-O", "-enable-library-evolution", "-target", "arm64-apple-macosx15.0"] + ) } private func makeBuilder() async throws -> SwiftInterfaceBuilder { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: Self.libraryURL()) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) try await builder.prepare() return builder diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift index 9d704a08..a19aa9d5 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import Semantic +import SwiftSectionFixtureSupport import Demangling @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @@ -24,56 +25,6 @@ import OrderedCollections /// extensions block, like the extensions of a protocol nested in a type. @Suite(.serialized) struct ProtocolInExtensionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "protocol-in-extension fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ProtocolInExtensionFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("ProtocolsInExtensions.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeProtocolInExtension.dylib") - try run(swiftcArguments: [ - "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// `FixtureAnchor` is ballast: a fixture dylib with no class has no /// `__DATA` segment, which older MachOKit releases mis-walked. /// @@ -123,14 +74,17 @@ struct ProtocolInExtensionTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeProtocolInExtension", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ProtocolsInExtensions.swift", contents: source)], + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } + private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - return file - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: Self.libraryURL()) } /// The lines starting an `extension` while inside another declaration's diff --git a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift index 53c6bb6b..63e00f4a 100644 --- a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift @@ -27,58 +27,6 @@ import SwiftPrinting /// record does not — the assertions hold; see the last test. @Suite(.serialized) struct RawLayoutBuiltinDescriptorRenderingTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "raw-layout fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("RawLayoutRenderingFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("RawLayouts.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeRawLayout.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeRawLayout", - "-enable-experimental-feature", "RawLayout", - // Value generics (`let count: Int`) need macOS 26. - "-target", "arm64-apple-macosx26.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - private static let source = """ public final class ProbeAnchor {} @@ -113,19 +61,26 @@ struct RawLayoutBuiltinDescriptorRenderingTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeRawLayout", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "RawLayouts.swift", contents: source)], + arguments: [ + "-O", + "-enable-experimental-feature", "RawLayout", + // Value generics (`let count: Int`) need macOS 26. + "-target", "arm64-apple-macosx26.0", + ] + ) + } + private func renderInterface() async throws -> String { try await printInterface(marksCommentStructure: false).string } private func printInterface(marksCommentStructure: Bool) async throws -> SemanticString { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: Self.libraryURL()) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.marksCommentStructure = marksCommentStructure let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) diff --git a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift index 416eaf3d..2e44056e 100644 --- a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift @@ -124,13 +124,7 @@ struct StrippedWrappedPropertyRenderingTests { private func printOfflineInterface(marksCommentStructure: Bool) async throws -> SemanticString { let products = try Self.compilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: products.clientURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: products.clientURL) var printConfiguration = SwiftDeclarationPrintConfiguration() printConfiguration.marksCommentStructure = marksCommentStructure let configuration = SwiftInterfaceBuilderConfiguration( diff --git a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift index ac4c073e..9c33405e 100644 --- a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift @@ -6,10 +6,11 @@ import SwiftDiffing import SwiftDeclaration @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import SwiftSectionFixtureSupport /// End-to-end tests for the annotated evolution interface over three -/// on-the-fly-compiled versions of one fixture module (the -/// `LegacyDyldInfoBindTests` compilation approach, minus the legacy target): +/// on-the-fly-compiled versions of one fixture module (each built with +/// `swiftc` at test time): /// /// - v1 → v2: `Alpha.bar(id:)` added, `Legacy` (whole class) removed. /// - v2 → v3: `Alpha.bar()` and the computed `Alpha.summary` removed, @@ -105,7 +106,7 @@ struct SwiftEvolutionInterfaceBuilderTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -125,14 +126,7 @@ struct SwiftEvolutionInterfaceBuilderTests { private func loadFixtureMachOFiles() throws -> [MachOFile] { try Self.fixtureCompilationResult.get().map { libraryURL in - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL) } } diff --git a/Tests/SwiftLayoutTests/DependencyClosureTests.swift b/Tests/SwiftLayoutTests/DependencyClosureTests.swift index 56fd1220..04e53861 100644 --- a/Tests/SwiftLayoutTests/DependencyClosureTests.swift +++ b/Tests/SwiftLayoutTests/DependencyClosureTests.swift @@ -165,7 +165,7 @@ final class DependencyClosureTests: MachOSwiftSectionFixtureTests, @unchecked Se @MainActor @Test func sameImageReachedUnderTwoLoadNamesIsCollectedOnce() throws { let root = machOFile - let helperFile = try #require(File.loadFromFile(url: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)).machOFiles.first) + let helperFile = try HostSlice.machOFile(at: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)) // Two of the root's direct load names, both answered by the same file. let locator = RecordingLocator(imagesByBareImageName: ["SymbolTestsHelper": helperFile, "libswiftCore": helperFile]) @@ -180,7 +180,7 @@ final class DependencyClosureTests: MachOSwiftSectionFixtureTests, @unchecked Se @MainActor @Test func customLocatorReceivesRawLoadNamesAndSuppliesTheImages() throws { let root = machOFile - let helperFile = try #require(File.loadFromFile(url: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)).machOFiles.first) + let helperFile = try HostSlice.machOFile(at: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)) let locator = RecordingLocator(imagesByBareImageName: ["SymbolTestsHelper": helperFile]) let closure = DependencyClosure(root: root, traversal: .direct, locator: locator) diff --git a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift index 2041f93b..2fb4ad9a 100644 --- a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift +++ b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift @@ -6,6 +6,7 @@ import MachOFoundation @_spi(Internals) import SwiftInspection @testable import SwiftLayout import Demangling +import SwiftSectionFixtureSupport /// The static expanded field-offset tree names a member of a concrete type by /// the type its conformance's witness record names (evolution proposal @@ -21,22 +22,6 @@ import Demangling /// member, `DynamicConcrete.Body`. @Suite struct NestedFieldOffsetOpaqueWitnessTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "nested-field-offset opaque-witness fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "NestedFieldOffsetOpaqueWitnessFixture" /// `FixtureAnchor` is ballast: a fixture dylib with no class has no @@ -78,48 +63,15 @@ struct NestedFieldOffsetOpaqueWitnessTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", - "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } @Test("a member whose witness is an opaque type is not named by a placeholder", arguments: ["DynamicHolder", "ConditionalHolder"]) diff --git a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift index 64667b2e..90c4e7aa 100644 --- a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift @@ -6,6 +6,7 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftLayout @_spi(Internals) import SwiftInspection +import SwiftSectionFixtureSupport /// The fixture the two suites below share: a module with `@_rawLayout` /// enabled, compiled on the fly (it carries a class: a struct-only fixture @@ -22,22 +23,6 @@ import Demangling /// under Swift 6.4 or newer; the whole-type suite reads nothing but the /// struct declarations and runs everywhere. enum RawLayoutBuiltinDescriptorFixture { - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct CompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "raw-layout layout fixture compilation failed:\n\(diagnostics)" } - } - static let moduleName = "ProbeRawLayoutLayout" private static let source = """ @@ -62,29 +47,8 @@ enum RawLayoutBuiltinDescriptorFixture { } """ - static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("RawLayoutLayoutFixture-\(UUID().uuidString)") - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("RawLayouts.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - let output = try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", moduleName, - "-enable-experimental-feature", "RawLayout", - "-target", "arm64-apple-macos27.0", - sourceURL.path, "-o", libraryURL.path, - ]) - guard output.terminationStatus == 0 else { throw CompilationError(diagnostics: output.standardError) } - return libraryURL - } - }() - /// `xcrun swiftc -version` reports a Swift 6.4 or newer toolchain — the - /// same toolchain `compilationResult` compiles the fixture with. + /// same toolchain `image()` compiles the fixture with. static let compilesWithSwift64OrNewer: Bool = { guard let output = try? run(swiftcArguments: ["-version"]), output.terminationStatus == 0 else { return false } let combined = output.standardOutput + output.standardError @@ -110,14 +74,19 @@ enum RawLayoutBuiltinDescriptorFixture { return (process.terminationStatus, String(decoding: standardOutputData, as: UTF8.self), String(decoding: standardErrorData, as: UTF8.self)) } + /// Compiled once per process by the shared compiler. static func image() throws -> MachOFile { - let libraryURL = try compilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "RawLayouts.swift", contents: source)], + arguments: [ + "-O", + "-enable-experimental-feature", "RawLayout", + "-target", "arm64-apple-macos27.0", + ] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift b/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift index fafdd3c5..c466580b 100644 --- a/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftLayout +import SwiftSectionFixtureSupport /// Where the simulator-runtime-gated suite below finds its runtime. A /// separate type on purpose: a `@Suite(.enabled(if:))` condition that reads a @@ -21,13 +22,7 @@ enum IOS18SimulatorRuntimeFixtures { }() static func swiftUI(underRuntimeRoot runtimeRootPath: String) throws -> MachOFile { - let url = URL(fileURLWithPath: "\(runtimeRootPath)/System/Library/Frameworks/SwiftUI.framework/SwiftUI") - switch try MachOKit.loadFromFile(url: url) { - case .machO(let thinFile): - return thinFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }, "the runtime's SwiftUI has no arm64 slice") - } + try HostSlice.machOFile(at: URL(fileURLWithPath: "\(runtimeRootPath)/System/Library/Frameworks/SwiftUI.framework/SwiftUI")) } } diff --git a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift index 99fd7caf..01840d57 100644 --- a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift @@ -23,22 +23,6 @@ import Demangling /// 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 = """ @@ -53,47 +37,15 @@ struct OfflineObjectiveCBaseClassTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// The offline specializer over the fixture file, the request for diff --git a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift index cdc3aee0..06435849 100644 --- a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift @@ -92,14 +92,7 @@ struct OfflineProjectionDependencyResolutionTests { }() private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) } @Test("a field's projected member and its layout are read from the same images") diff --git a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift index 1d083a4f..e3308f09 100644 --- a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift @@ -140,13 +140,7 @@ final class SymbolIndexDemangledIndexTests: MachOFileTests, @unchecked Sendable }.start() let machOFile: MachOFile do { - switch try loadFromFile(named: .SymbolTestsCore) { - case .machO(let machO): - machOFile = machO - case .fat(let fatFile): - guard let machO = try fatFile.machOFiles().first(where: { $0.header.cpuType == .arm64 }) else { exit(EXIT_FAILURE) } - machOFile = machO - } + machOFile = try HostSlice.machOFile(in: try loadFromFile(named: .SymbolTestsCore)) } catch { exit(EXIT_FAILURE) } diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift index 19ad06dc..e52d2226 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering +import SwiftSectionFixtureSupport @testable import SwiftThunkAnalysis /// A kind-9 accessor thunk names the type it instantiates by the accessor it @@ -20,22 +21,6 @@ import SwiftDeclarationRendering /// `offline-generic-specialization` is the reading side of the same shape. @Suite(.serialized) struct AccessorThunkTypeInGenericExtensionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "accessor-thunk generic-extension fixture compilation failed:\n\(diagnostics)" } - } - /// `Inner` is `~Copyable`, so a field of it is instantiated by a thunk /// that first asks whether the runtime supports noncopyable types — a /// kind-9 accessor function reference in the field record. The class is @@ -69,46 +54,15 @@ struct AccessorThunkTypeInGenericExtensionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("AccessorThunkGenericExtensionFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("AccessorThunkGenericExtension.swift") - let libraryURL = workingDirectory.appendingPathComponent("libProbeThunkExtension.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - // Optimized so the thunk takes the shape a shipping binary carries. - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeThunkExtension", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeThunkExtension", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "AccessorThunkGenericExtension.swift", contents: Self.fixtureSource)], + // Optimized so the thunk takes the shape a shipping binary carries. + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// The `inner` field's type of the holder named `holderName`, read diff --git a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift index 0b329d1e..453b6e50 100644 --- a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift +++ b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering +import SwiftSectionFixtureSupport @testable import SwiftThunkAnalysis /// A kind-9 field thunk that calls a **compiler-merged accessor** — the @@ -27,20 +28,9 @@ import SwiftDeclarationRendering /// `accessor function at N`, with and without symbols. @Suite(.serialized) struct MergedAccessorFixtureTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct StripError: Error, CustomStringConvertible { let diagnostics: String - var description: String { "MergedAccessorProbe fixture compilation failed:\n\(diagnostics)" } + var description: String { "stripping the MergedAccessorProbe fixture failed:\n\(diagnostics)" } } private struct CompiledFixture { @@ -50,25 +40,27 @@ struct MergedAccessorFixtureTests { private static let fixtureCompilationResult: Result = { Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("MergedAccessorProbeFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("MergedAccessorProbe.swift") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libMergedAccessorProbe.dylib") - let strippedLibraryURL = workingDirectory.appendingPathComponent("libMergedAccessorProbeStripped.dylib") - // `Synchronization.Mutex` needs macOS 15; optimized so the // accessors take the shapes a shipping binary carries and the // optimizer merges them. - try run(tool: "swiftc", arguments: [ - "-O", "-emit-library", "-module-name", "MergedAccessorProbe", - "-target", "arm64-apple-macosx15.0", - "-Xfrontend", "-disable-concrete-type-metadata-mangled-name-accessors", - sourceURL.path, "-o", libraryURL.path, - ]) + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "MergedAccessorProbe", + language: .swift, + source: fixtureSource, + arguments: [ + "-O", + "-target", "arm64-apple-macosx15.0", + "-Xfrontend", "-disable-concrete-type-metadata-mangled-name-accessors", + ] + ) + // The compiled library is shared with every other request for it, + // so the stripped variant is a copy in a directory of its own, + // under the compiler's products directory the process removes at + // exit. + let strippedDirectory = FixtureCompiler.shared.productsDirectory + .appendingPathComponent("MergedAccessorProbeStripped-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: strippedDirectory, withIntermediateDirectories: true) + let strippedLibraryURL = strippedDirectory.appendingPathComponent("libMergedAccessorProbeStripped.dylib") try FileManager.default.copyItem(at: libraryURL, to: strippedLibraryURL) // `-x` removes the local symbols — every `…MaTm` and specialized // accessor name — the way a shipping app is stripped. @@ -88,7 +80,7 @@ struct MergedAccessorFixtureTests { let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + throw StripError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) } } @@ -123,12 +115,7 @@ struct MergedAccessorFixtureTests { """ private func load(_ libraryURL: URL) throws -> MachOFile { - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: libraryURL) } /// Every kind-9 field of the fixture, keyed `Owner.field`, resolved diff --git a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift index 41f25253..d23c8928 100644 --- a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift @@ -45,12 +45,7 @@ struct SimulatorStandaloneSwiftUIThunkTests { } private func load(path: String) throws -> MachOFile { - switch try File.loadFromFile(url: URL(fileURLWithPath: path)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: URL(fileURLWithPath: path)) } private func resolvedFieldTexts(ofTypeNamed typeName: String, in machOFile: MachOFile) throws -> [String: String] { diff --git a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift index 960906dd..892af009 100644 --- a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering +import SwiftSectionFixtureSupport @testable import SwiftThunkAnalysis /// A kind-9 thunk in a file that is **not** in a dyld shared cache calls the @@ -107,39 +108,17 @@ struct StandaloneFileThunkResolutionTests { /// `__swift_instantiateConcreteTypeFromMangledNameV2`, found by its local /// symbol — whose value is an address, which a dylib's `__TEXT` at 0 had /// let pass for a file offset. - private static let executableCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ThunkProbeExecutableFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("ThunkProbe.swift") - let mainSourceURL = workingDirectory.appendingPathComponent("main.swift") - let executableURL = workingDirectory.appendingPathComponent("ThunkProbe") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - try executableMainSource.write(to: mainSourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-O", "-module-name", "ThunkProbe", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, mainSourceURL.path, "-o", executableURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return executableURL - } - }() + private static func compileExecutableFixture() throws -> URL { + try FixtureCompiler.shared.executable( + named: "ThunkProbe", + language: .swift, + sourceFiles: [ + FixtureSourceFile(name: "ThunkProbe.swift", contents: fixtureSource), + FixtureSourceFile(name: "main.swift", contents: executableMainSource), + ], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + } private static let executableMainSource = """ let holder = ProbeHolder() @@ -147,23 +126,11 @@ struct StandaloneFileThunkResolutionTests { """ private func loadExecutableFixture() throws -> MachOFile { - let executableURL = try Self.executableCompilationResult.get() - switch try File.loadFromFile(url: executableURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: try Self.compileExecutableFixture()) } private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: try Self.fixtureCompilationResult.get()) } private struct ResolvedField { From 25c4515c965a3c35af018a746e661b94668f49da Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 12:21:42 +0800 Subject: [PATCH 058/175] docs: land the multiline type formatting proposal as 0102, and number ledger section 148 Co-Authored-By: Claude --- AGENTS.md | 2 +- ...ml => 0102-multiline-type-formatting.html} | 19 +++++++++++-------- ...g.md => 0102-multiline-type-formatting.md} | 11 ++++++----- Documentations/Evolutions/README.md | 2 +- Documentations/Glossary.md | 2 +- .../Internal/Modules/SwiftSectionKit.md | 2 +- .../Internal/ProjectEvolutionLog.md | 4 ++-- Documentations/README.md | 2 +- 8 files changed, 24 insertions(+), 20 deletions(-) rename Documentations/Evolutions/{draft-multiline-type-formatting.html => 0102-multiline-type-formatting.html} (96%) rename Documentations/Evolutions/{draft-multiline-type-formatting.md => 0102-multiline-type-formatting.md} (98%) diff --git a/AGENTS.md b/AGENTS.md index f3ac8e5a..2141ca44 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,7 +51,7 @@ One or two lines each; the linked document is the authority. - **SwiftObjCInterop** — the Objective-C side of Swift types, and where `MachOObjCSection` enters the Swift-facing stack: per-image indexes of `@objc @implementation` classes, of the Swift classes a source renamed for the ObjC runtime (`SwiftClassObjectIndex` — every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss), of the Swift classes with no class object in `__objc_classlist`, and of the `@objc` protocols declared in Swift; the seam through which a host hands over the ObjC class hierarchies it already indexed (`ObjCClassHierarchyProviding`), the library's own reader behind it and the ancestor chain followed into a standalone file's dependency closure; the per-class ObjC member table (`ObjCMemberTable`); the ClangImporter's naming rules, and the records an ObjC class, category or protocol is imported into Swift from (`ObjCImportedContainerIndex`). A Swift class's ObjC-side name is not always `_TtC…`: in a file, a category on another image's Swift class names it by the class metadata symbol it is bound to (`_$s…CN`). Read every such name through `NodeTypeNaming.swiftClassNode(fromRuntimeName:)`, never a `hasPrefix("_Tt")` check — one printed `extension __C._$s…` and found none of its `@objc` witnesses. The linker merges a binary's categories on its own classes into those classes, so `__objc_catlist` lists only categories on other images' classes. An `@objc` protocol declared in Swift has NO protocol descriptor and a class's conformance to an ObjC protocol has NO conformance record — the facts live in `__swift5_fieldmd`, `protocol_t` and `class_ro_t`. [Modules/SwiftObjCInterop.md](Documentations/Internal/Modules/SwiftObjCInterop.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. Its files split by visibility: a `public` type that stays in the model after indexing goes under `Model/`; code that only runs while the model is built (`package` / `internal`) goes under `Indexing/` — a new `TypeDefinition+…` step goes in `Indexing/TypeDefinition/`, never beside `TypeDefinition.swift`. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). -- **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). Also `MultilineTypeFormatting`, which breaks a finished print's long types at their brackets — applied once at the output (the `dump` / `interface` requests, a host's assembled print), never inside a printer ([draft-multiline-type-formatting](Documentations/Evolutions/draft-multiline-type-formatting.md)). +- **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). Also `MultilineTypeFormatting`, which breaks a finished print's long types at their brackets — applied once at the output (the `dump` / `interface` requests, a host's assembled print), never inside a printer ([0102-multiline-type-formatting](Documentations/Evolutions/0102-multiline-type-formatting.md)). - **SwiftIndexing** — builds the declaration model from an image (`SwiftDeclarationIndexer.prepare()`), unifies extension containers, owns the per-image cache eviction. - **SwiftPrivateDiscriminators** — recovers the source file a private discriminator was derived from (`MD5(module name + file name)`): candidate file names hashed until one matches — a generated list of known ones, then names the image itself declares. `PrivateDiscriminatorSourceFileIndex` holds one image's candidates and remembers every answer. `dump` / `interface --emit-private-source-files` reach it through `SwiftDeclarationRendering`'s `PrivateDeclarationSourceFileProviding`, after one search over the whole image (`recoverSourceFiles(ofEveryDeclarationIn:)`) — asked one declaration at a time, every discriminator nothing recovers runs through all the candidates again. [Modules/SwiftPrivateDiscriminators.md](Documentations/Internal/Modules/SwiftPrivateDiscriminators.md). - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). diff --git a/Documentations/Evolutions/draft-multiline-type-formatting.html b/Documentations/Evolutions/0102-multiline-type-formatting.html similarity index 96% rename from Documentations/Evolutions/draft-multiline-type-formatting.html rename to Documentations/Evolutions/0102-multiline-type-formatting.html index b6f2be93..949ccdc8 100644 --- a/Documentations/Evolutions/draft-multiline-type-formatting.html +++ b/Documentations/Evolutions/0102-multiline-type-formatting.html @@ -4,7 +4,7 @@ -Draft - 长类型拆行:放不下的类型按括号结构拆成多行 +0102 - 长类型拆行:放不下的类型按括号结构拆成多行 + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

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

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

    +
    + +
    +

    要你定

    +
    +

    轻量档:看过简报点头即可开工

    +
      +
    1. 名额取半数核心(Ultra 上 14 个)、至少 2 个,可以吗?
    2. +
    3. -O 只给采样里出现的两个模块,本包自己的 CrossReferenceAnalysis 保持可调试,可以吗?
    4. +
    +
    +
    +

    未实测

    +

    「开 -O 后接近 Release 的速度」是推测;Tuist 的 base 设置能否覆盖按配置写的 -Onone 也未验证。落地第 1、4、5 步分别量基线、验证设置、复测。

    +
    +
    + +
    +

    架构图

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

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

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

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

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

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

    +
    + +
    +

    改动地图

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

    详细设计

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

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

    +

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

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

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

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

    调研

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

    替代方案

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

    影响

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

    落地步骤

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

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

    +
    + +
    +

    决策日志

    +
    + 2 条,最近一条:Accepted +
    +
    + + + + + + +
    日期变更说明
    2026-11-21Created as DraftUltra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。
    2026-11-21Accepted用户批准,开始实现。
    +
    +
    +
    +
    + +
    +
    + + diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md new file mode 100644 index 00000000..44cb5307 --- /dev/null +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -0,0 +1,317 @@ +# Draft - 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-21 +- **最后更新**: 2026-11-21 +- **所属愿景**: 无 +- **关联提案**: [0099-tuist-workspace](0099-tuist-workspace.md)(本提案改的 Tuist 开发工作区) +- **实现分支 / PR**: `feature/cross-reference-test-scan-load`(从 `next` 切出,worktree `.worktrees/MachOSwiftSection-CrossReferenceTestScanLoad`) +- **配套文档**: 待定 —— 落地时判断;预计只更新既有文档(见「文档与示例」),不新写专题文章 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +`CrossReferenceAnalysisTests` 里有四个测试辅助函数用不设上限的 `DispatchQueue.concurrentPerform` 扫描整份 dyld shared cache,Debug 构建下每次跑测试都把机器的全部核心占满好几分钟。本提案做两件事: + +1. **测试限并发**:测试 target 里新增一个全进程共用的扫描名额 `ImageScanConcurrency`,默认 `max(2, 核心数 / 2)`,四处扫描改走它;Swift Testing 并行跑多个套件时,所有扫描加起来也不超过这个名额。另加一个源码扫描测试,禁止以后在这个 target 里绕过它直接调 `concurrentPerform`。 +2. **Debug 提速**:Tuist 开发工作区里,让采样中占满时间的两个扫描模块 `MachOCodeReferences`、`ARM64InstructionDecoding`(都在 MachOKitExtensions)在 Debug 配置下也用 `-O` 编译,去掉 Debug 下每条指令一次的 Swift 运行时元数据查找。 + +库的公开 API、原生 `MachOSwiftSection.xcworkspace`、`swift test` 与 CI 的行为都不变。 + +## 动机 + +- **跑一次测试,机器被占满好几分钟。** 2026-11-21 在 Ultra(M3 Ultra,28 核)上用 `./TuistScript.sh test` 跑 Debug 测试,xctest 进程持续占 2369% CPU(约 24 个核心),采样时已经跑了 8 分多钟、仍未结束。这台机器上 `queued-build` 不限核,测试期间同机的编译、其他 agent 会话和前台应用都被挤占。 +- **占满核心的是测试辅助函数,不是库本身。** 对 xctest 采样 3 秒(`sample 3`),28 个工作线程全部落在 `ObjectiveCClassReferenceTests.imagesReferencing(_:at:among:)` 里的 `concurrentPerform` → `CrossReferenceAnalyzer.references(to:inImageAt:)` → `ReferenceScanner.scanFunction(at:)`。四个同类辅助函数(见「前期调研」)都按镜像数开满并发,没有上限。 +- **Debug 下扫描慢在 Swift 运行时,而不是扫描算法。** 同一份采样里,工作线程约 11 600 个样本中,栈顶是 `LockingConcurrentMap::getOrInsert`(元组类型元数据缓存,带锁)的有 4762 个(约 41%);经过 `swift_getTupleTypeMetadata2` 的帧合计 5380 个(约 46%),再加泛型元数据实例化约 1510 个(约 13%)。来源是扫描热路径上的 `for … in` 区间循环:`-Onone` 下它们走 libswiftCore 里未特化的 `IndexingIterator.next()`,每走一步都要查一次元组元数据,28 个线程争同一把锁。按 AGENTS.md 的记载,Release 下整份 macOS shared cache 两三秒扫完;`ObjectiveCClassReferenceTests` 的注释则写明 Debug 构建「扫整份 cache 要几分钟」。 +- **只限并发不够。** 限到一半核心后,同样的工作要跑更久;不把 Debug 下的这份运行时开销去掉,测试总时长会明显变长。两件事要一起做。 + +## 前期调研 + +- **四处不限并发的整份 cache 扫描**(路径相对 `Tests/CrossReferenceAnalysisTests/`,行号取自 `next` 25c4515c): + - `CrossReferenceAnalyzerTests.swift:259` · `imagesReferencing(_:among:)` —— 调用者预筛的抽样复查 + - `SwiftTypeReferenceTests.swift:324` · `imagesReferencing(_:among:)` —— Swift 类型引用的预筛复查 + - `ObjectiveCClassReferenceTests.swift:196` · `imagesReferencing(_:at:among:)` —— ObjC 类引用的预筛复查(这次采样抓到的就是它) + - `FunctionStartOutsideTextTests.swift:25` · `imagesWithAStartOutsideText()` —— 对每个镜像建一次函数表 +- **不在范围内的 `concurrentPerform`**:`ScanThroughputBenchmarkTests.swift:48/64/90` 是吞吐基准,套件带 `.enabled(if: ScanThroughputBenchmarkEnvironment.outputPath != nil)`,要设 `CROSS_REFERENCE_BENCHMARK_OUTPUT` 才跑,量的就是全核吞吐;库内 `Sources/Support/Utilities/ConcurrentMap.swift`、`Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift:146`、`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift:1757` 与 MachOKitExtensions 的 `RenamedReexportIndex.swift:45` 是给 CLI 与宿主用的,应当用满核心。 +- **Swift Testing 并行跑套件**:上面四处分属四个套件,`.serialized` 只约束套件内部。每次调用各自限宽的话,几个套件同时扫描时会叠加回满核,所以名额必须是全进程共用的。 +- **既有先例**:`Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift:70` 的 `taskGroupWidth = max(2, ProcessInfo.processInfo.activeProcessorCount / 2)`;收集结果的 `ImageIndexCollector`(`CrossReferenceAnalyzerTests.swift:325`)用 `NSLock`。测试 target 的部署版本在 SwiftPM 与 Tuist 下都是 macOS 14(`Tuist/Package.swift` 的 `testTargetSettings`),用不了要求 macOS 15 的 `Synchronization.Atomic` / `Mutex`,沿用 `NSLock`。 +- **热点循环的位置**(MachOKitExtensions 主检出,`Sources/Analysis/MachOCodeReferences/Scanning/`): + - `RegisterFile.swift:148` · `clobberCallerSavedRegisters()` 的 `for register in 0 ... 18` + - `RegisterFile.swift:48` · `Snapshot.meet(_:)` 的 `for register in 0 ..< RegisterFile.registerCount` + - `ReferenceScanner.swift:150`、`:292` · `scanFunction(at:)` 里逐条指令的 `for instructionIndex in 0 ..< instructionCount` + - 采样栈顶里自家函数还有 `RegisterFile.Snapshot.agrees(with:on:)`、`ReferenceScanner.scanFunction(at:)`(MachOCodeReferences)与 `ARM64InstructionWord.conditionalBranchTarget(_:at:)`(ARM64InstructionDecoding)。前 30 名里没有 `CrossReferenceAnalysis` 与 `ObjCCodeReferences` 的函数。 +- **开 `-O` 不会丢掉检查**:`MachOCodeReferences`、`ARM64InstructionDecoding` 里没有 `assert` / `assertionFailure`(`-O` 会去掉它们),`MachOCodeReferences` 的两处 `precondition` 在 `-O` 下保留。本包的 `CrossReferenceAnalysis` 有一处 `assert`,这也是它不进名单的原因之一。 +- **Tuist 工作区里这两个模块从源码编**:TuistDevelopment.md 写明原生 workspace 里的五个上游库(含 MachOKitExtensions)在两种依赖模式下都从源码编、不进二进制缓存,`PackageSettings.targetSettings` 按 target 名对它们生效(已有先例:`restatedTraitDefinitions` 给远程包 Capstone 加设置)。 +- **Tuist 生成的工程把优化级别写在每个配置里**:现有生成结果 `…/Dependencies//tuist-derived/Projects/MachOKitExtensions/MachOKitExtensions.xcodeproj/project.pbxproj` 中,每个 target 的 Debug 配置写 `SWIFT_OPTIMIZATION_LEVEL = "-Onone"`、Release 写 `"-O"`。**未验证**:`targetSettings` 的 `base` 是否覆盖这个按配置写的值。落地第 4 步先验证,不行就改用按配置的设置(见「详细设计」)。 +- **预期收益是推测**:「Debug 下这两个模块开 `-O` 后,扫描接近 Release 的速度」没有实测。落地第 1 步与第 5 步各量一次,结论写回本提案。 + +## 提议方案 + +1. 测试 target 新增 `ImageScanConcurrency`:一个进程内共用的计数信号量(`DispatchSemaphore`,值为 `maximumConcurrentScans`),加一个与 `DispatchQueue.concurrentPerform(iterations:execute:)` 同形的入口。每次调用最多起 `maximumConcurrentScans` 个工作者,从共享游标领下一个下标,每扫一个镜像前先取一个名额、扫完归还。所以不管同时有几个套件在扫,正在扫描的镜像总数都不超过名额。 +2. 四处辅助函数把 `DispatchQueue.concurrentPerform(iterations:)` 换成 `ImageScanConcurrency.concurrentPerform(iterations:)`,闭包体不动。 +3. 新增源码扫描测试 `ParallelScanSourceTests`:这个 target 里除 `ImageScanConcurrency.swift` 与 `ScanThroughputBenchmarkTests.swift` 外,出现 `DispatchQueue.concurrentPerform(` 就失败;照项目惯例配一个 `theScanDiscriminates` 证明扫描本身能区分。 +4. `Tuist/Package.swift` 新增 `optimizedScanSettings`,给 `MachOCodeReferences`、`ARM64InstructionDecoding` 设 `SWIFT_OPTIMIZATION_LEVEL = -O`,并入 `PackageSettings.targetSettings`。本包自己的 `CrossReferenceAnalysis` 保持 Debug 不优化。 +5. 改前、改后各量一次 `CrossReferenceAnalysisTests` 的墙钟时间、xctest 的累计 CPU 时间与 CPU 占用峰值,写回本提案。 + +### 非目标 + +- **不改库代码**:不改 MachOKitExtensions 里的热点循环。那条路让 `swift test` 与原生 workspace 也受益,但要发 MachOKitExtensions 新版,这次不做(见「替代方案」)。 +- **不动库内与 CLI 的并发**:`ConcurrentMap`、`ReferencesRequest`、`SwiftSymbolIndexStore`、`RenamedReexportIndex` 照旧用满核心。 +- **不动吞吐基准**:`ScanThroughputBenchmarkTests` 要手动开启,量的就是全核吞吐。 +- **不改原生 workspace、`swift test` 与 CI**:CI 的 runner 只有 3 核,名额算出来是 2,与现在差别不大;CI 用 `swift test`,不经 Tuist,所以 `-O` 设置也碰不到它。 +- **名额不做成可配置**:不加环境变量;真要调,改 `maximumConcurrentScans` 一处。 +- **不改 RuntimeViewer 的 Tuist 工作区**:它有自己的 `TuistScript.sh` 与清单。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift` · `ImageScanConcurrency` | 新增 | 进程共用的名额 `maximumConcurrentScans` 与信号量,入口 `concurrentPerform(iterations:execute:)`;私有的 `IterationCursor`(`NSLock` 保护的下一个下标) | 四处扫描共用一份上限,并行的套件不叠加 | 2 | +| `Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift` · `ImageScanConcurrencyTests` | 新增 | 四个行为测试(见落地步骤 2) | 钉住「每个下标只跑一次」与「同时进行的不超过名额」 | 2 | +| `Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift` · `imagesReferencing(_:among:)` | 修改 | `DispatchQueue.concurrentPerform` → `ImageScanConcurrency.concurrentPerform` | 不限并发的整份 cache 扫描 | 3 | +| `Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift` · `imagesReferencing(_:among:)` | 修改 | 同上 | 同上 | 3 | +| `Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift` · `imagesReferencing(_:at:among:)` | 修改 | 同上 | 同上(这次采样抓到的那处) | 3 | +| `Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift` · `imagesWithAStartOutsideText()` | 修改 | 同上 | 同上 | 3 | +| `Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift` · `ParallelScanSourceTests` | 新增 | 扫本 target 源码,禁止名额与基准之外直接调 `DispatchQueue.concurrentPerform(`;`theScanDiscriminates` | 以后新写的整份 cache 测试默认会照抄 `concurrentPerform`,靠测试拦住 | 3 | +| `Tuist/Package.swift` · `optimizedScanSettings` | 新增 | 两个扫描模块 `SWIFT_OPTIMIZATION_LEVEL = -O`,并入 `mergingSettings(...)` | Debug 下扫描的时间过半花在运行时元数据查找 | 4 | +| `Documentations/Internal/TuistDevelopment.md` | 修改 | 「已知的坑」加一条:两个扫描模块在 Debug 下也开 `-O`,在 Tuist 里对它们打断点会看到优化后的代码;要调试时从名单里临时拿掉再生成 | 这是 Tuist 工作区与原生 workspace 的一处有意差异 | 5 | +| `Documentations/Internal/FixtureTestingAndContinuousIntegration.md` | 修改 | 新增一小节「整份 cache 扫描共用一份并发名额(2026-11-21)」:为什么要全进程共用、名额怎么算、哪些地方例外 | 记录设计来历 | 5 | +| `AGENTS.md`(`CLAUDE.md` 是指向它的符号链接) | 修改 | 「writing or modifying tests」块加一条:并行扫描很多镜像的测试走 `ImageScanConcurrency.concurrentPerform`,不直接调 `DispatchQueue.concurrentPerform` | agent 默认会照抄旧写法 | 5 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时追加一节,节号按落地规则取 | 项目要求每个非平凡批次记一节 | 落地 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案(现在一次,落地改名时一次) | 索引 | 现在 / 落地 | + +## 架构图 + +改了什么: + +```text +Tests/CrossReferenceAnalysisTests/ + CrossReferenceAnalyzerTests.imagesReferencing(_:among:) + SwiftTypeReferenceTests.imagesReferencing(_:among:) + ObjectiveCClassReferenceTests.imagesReferencing(_:at:among:) + FunctionStartOutsideTextTests.imagesWithAStartOutsideText() +- └── DispatchQueue.concurrentPerform(iterations:) (every core, per call) ++ └── ImageScanConcurrency.concurrentPerform(iterations:) (one process-wide budget) ++ ImageScanConcurrency maximumConcurrentScans = max(2, activeProcessorCount / 2) ++ ImageScanConcurrencyTests ++ ParallelScanSourceTests no bare concurrentPerform outside the budget and the benchmark + ScanThroughputBenchmarkTests unchanged (opt-in, every core) + +Tuist/Package.swift PackageSettings.targetSettings ++ optimizedScanSettings ++ MachOCodeReferences SWIFT_OPTIMIZATION_LEVEL = -O (Debug too) ++ ARM64InstructionDecoding SWIFT_OPTIMIZATION_LEVEL = -O (Debug too) + CrossReferenceAnalysis unchanged (-Onone in Debug) + ObjCCodeReferences unchanged (-Onone in Debug) +``` + +名额怎么在并行的套件之间共用: + +```text +suite A ─ concurrentPerform(iterations: 1600) ─┐ workers ≤ maximumConcurrentScans per call +suite B ─ concurrentPerform(iterations: 110) ─┼─ each worker: cursor.next() → permits.wait() +suite C ─ concurrentPerform(iterations: 1700) ─┘ → scan one image → permits.signal() + +permits = DispatchSemaphore(value: maximumConcurrentScans) shared by every call in the process +⇒ images being scanned at once, across all suites ≤ maximumConcurrentScans +``` + +Debug 下热路径为什么慢(改前)与开 `-O` 后(改后): + +```text +ReferenceScanner.scanFunction(at:) MachOCodeReferences, -Onone +- for instructionIndex in 0 ..< instructionCount +- IndexingIterator>.next() libswiftCore, unspecialized +- Range.formIndex(after:) witness +- swift_getTupleTypeMetadata2 locked global cache, 28 threads contend ++ for instructionIndex in 0 ..< instructionCount MachOCodeReferences, -O ++ specialized and inlined integer loop no runtime metadata lookup +``` + +## 详细设计 + +### `ImageScanConcurrency` + +```swift +import Foundation + +/// How many images the test target's parallel scans may read at once: half of +/// the cores, at least two. A Debug scan of the whole shared cache keeps every +/// core it is given busy for minutes, and Swift Testing runs the suites holding +/// these scans in parallel — so the budget is one for the whole process, not +/// one per call, or four suites at once would add up to every core again. +enum ImageScanConcurrency { + static let maximumConcurrentScans = max(2, ProcessInfo.processInfo.activeProcessorCount / 2) + + private static let permits = DispatchSemaphore(value: maximumConcurrentScans) + + /// Runs `body` once for every index in `0 ..< iterations`, the way + /// `DispatchQueue.concurrentPerform(iterations:execute:)` does, with at most + /// `maximumConcurrentScans` bodies running at once across the process. + /// + /// `body` must not call this function again: a nested call waits for a + /// permit while its caller holds one, and with every permit held that way + /// nothing is ever released. + static func concurrentPerform(iterations: Int, execute body: (Int) -> Void) { + guard iterations > 0 else { return } + let cursor = IterationCursor(iterationCount: iterations) + DispatchQueue.concurrentPerform(iterations: min(maximumConcurrentScans, iterations)) { _ in + while let index = cursor.next() { + permits.wait() + defer { permits.signal() } + body(index) + } + } + } +} + +/// Hands out each index of `0 ..< iterationCount` once, to whichever worker asks first. +private final class IterationCursor: @unchecked Sendable { + private let lock = NSLock() + private let iterationCount: Int + private var nextIndex = 0 + + init(iterationCount: Int) { + self.iterationCount = iterationCount + } + + func next() -> Int? { + lock.lock() + defer { lock.unlock() } + guard nextIndex < iterationCount else { return nil } + defer { nextIndex += 1 } + return nextIndex + } +} +``` + +- **为什么每次调用也限工作者数**:只靠信号量的话,`concurrentPerform` 仍按核心数起线程,多出来的线程全阻塞在 `permits.wait()` 上;内核的 workqueue 看到线程阻塞还会补新线程。先把每次调用的工作者限到名额以内,阻塞的线程数就有上界(同时在扫的套件数 × 名额)。 +- **为什么不会卡死**:名额只在扫一个镜像的期间持有,扫描是同步的 CPU 工作,不等任何线程池上的工作,持有者总会归还。调用线程可能是 Swift Testing 的 cooperative thread(同步测试函数跑在它上面,`concurrentPerform` 也在调用线程上执行迭代),它在 `permits.wait()` 上等的是别的扫描线程归还名额,而那些线程不需要 cooperative pool。这与 AGENTS.md「不要让 cooperative thread 不设超时地等需要池线程的工作」不冲突。嵌套调用会卡死,文档注释写明禁止;四处调用点的闭包体都不嵌套。 +- **CI**:runner 3 核,`activeProcessorCount / 2 = 1`,取下限 2。CI 跑的是 `swift test`,同样经过这份名额。 + +### 调用点(以 `ObjectiveCClassReferenceTests` 为例) + +```swift +// before +DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + let imageIndex = imageIndices[position] + … +} +// after +ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in + let imageIndex = imageIndices[position] + … +} +``` + +闭包体、收集结果的 `ImageIndexCollector` 与 `FunctionStartOutsideTextTests` 的 `flagsBase` 写法都不变。 + +### `ParallelScanSourceTests` + +照 `MemoryAccessScanTests` 的写法:从 `#filePath` 取本 target 目录,逐行扫 `.swift` 文件,跳过 `//` 开头的行,匹配 `DispatchQueue.concurrentPerform(`;`ImageScanConcurrency.swift` 与 `ScanThroughputBenchmarkTests.swift` 两个文件名在允许名单里。`theScanDiscriminates` 断言:`DispatchQueue.concurrentPerform(iterations: n) {` 命中,`ImageScanConcurrency.concurrentPerform(iterations: n) {` 与注释行不命中。 + +### `Tuist/Package.swift` + +```swift + // A Debug build of the cross-reference scan spends most of its time in the Swift runtime, not in + // the scan: an unspecialized range loop looks tuple metadata up on every instruction, under one + // lock every thread shares, so CrossReferenceAnalysisTests' whole-cache scans take minutes instead + // of the seconds a Release build needs. The scan's two hottest modules compile optimized in every + // configuration here; this package's own CrossReferenceAnalysis stays debuggable. + // (Evolution proposal cross-reference-test-scan-load.) + let optimizedScanSettings: [String: Settings] = Dictionary( + ["MachOCodeReferences", "ARM64InstructionDecoding"].map { targetName in + (targetName, Settings.settings(base: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])) + }, + uniquingKeysWith: { first, _ in first } + ) +``` + +并入 `PackageSettings(targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings, optimizedScanSettings), …)`。`mergingSettings` 合并的是各自的 build setting 键,`SWIFT_OPTIMIZATION_LEVEL` 与其它几组的键不重叠,它头上「keys never overlap」的注释仍然成立。 + +**`base` 覆盖不了按配置写的值时的后备**(第 4 步验证结果决定):改成 + +```swift +Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])]) +``` + +并让 `mergingSettings` 连同 `configurations` 一起合并(现在它只合并 `base`,会把 `configurations` 丢掉)。这条后备只在验证失败时启用,结果记入决策日志。 + +### 怎么量 + +- 在不跑其它测试的时候量(同机别的 xctest 会争核心),`TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex/claude/Tuist-MachOSwiftSection`。 +- 先 `queued-build ./TuistScript.sh build --scheme "MachOSwiftSection Tests"`,把编译排除在外;再 `queued-build ./TuistScript.sh test --scheme "MachOSwiftSection Tests" -- -only-testing:CrossReferenceAnalysisTests`。 +- 测试期间每 10 秒读一次 `ps -o %cpu=,time= -p `:取 `%cpu` 的峰值,以及进程结束前最后一次的累计 CPU 时间;墙钟时间取 `.xcresult` 里这个 target 的总耗时。 +- 测试成败按全局规则只认原始退出码。 + +## 替代方案考量 + +- **改 MachOKitExtensions 里的热点循环**(把 `for … in` 区间循环改成 Debug 下不查元数据的写法):`swift test`、原生 workspace 与 CI 都受益,但收益只有元数据那一块(估计快一倍左右,未实测),要发 MachOKitExtensions 新版本,热路径上的写法也变得不自然,以后新写的循环还会再犯。这次选了 Tuist 配置,这条留作以后 `swift test` 也嫌慢时的选项。 +- **整个 Debug 工作区开 `-O`,或用 Release 跑测试**:失去所有模块的调试能力;Release 下 `@testable import` 还要额外开 `ENABLE_TESTABILITY`,二进制缓存按配置分份,整套都要重做。范围远超问题本身。 +- **`CrossReferenceAnalysis`、`ObjCCodeReferences` 也开 `-O`**:采样栈顶的前 30 名里没有它们;`CrossReferenceAnalysis` 是本包自己的代码,最常被调试,还有一处 `assert` 会被 `-O` 去掉。等第 5 步的采样说明它们也是瓶颈再加。 +- **每次调用各自限宽,不共用名额**:Swift Testing 并行跑四个套件时,加起来又是满核。 +- **把四个套件串行化**:`.serialized` 只管套件内部;要跨套件串行得把它们挪进同一个父套件,改动面大,而且把不扫描的测试也拖慢了。 +- **降低扫描线程的 QoS 而不限并发**:CPU 照样占满,只是让出优先级;Apple Silicon 上 `.background` 还会把工作压到能效核,测试会慢很多。 +- **用库里现成的 `concurrentMap(maximumConcurrency:)`**(`Sources/Support/Utilities/BoundedConcurrentMap.swift`):它是 async 的 task group,测试是同步函数;在 cooperative thread 上跑这种同步的重活正是 AGENTS.md 要避免的;它的上限也是每次调用各算各的。 + +## 影响 + +### 源码兼容性(source compatibility) + +**纯新增**。改动全在测试 target 与 Tuist 开发清单里,库的公开 API 不变。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:只有 `CrossReferenceAnalysisTests`(四处调用点与三个新文件)和 Tuist 工作区的生成结果。 +- 下游仓库:无。`Tuist/Package.swift` 只用于本仓库的开发工作区,RuntimeViewer、MachOKitUI 等用的是 SwiftPM 清单。 +- **并行进行的功能分支**:`feature/shared-macho-testing-support` 也改了 `FunctionStartOutsideTextTests.swift`(19 行),合并时可能有小冲突;本提案只改其中一行调用。 + +### 文档与示例 + +- `Documentations/Internal/TuistDevelopment.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md`、`AGENTS.md`:见改动地图。 +- `Documentations/Internal/ProjectEvolutionLog.md`:落地时追加一节。 +- README、DocC、示例代码:无需改动(不涉及用法)。 + +## API 演进与废弃策略 + +不适用 —— 没有新增、修改或废弃任何公开 API,不需要版本号跃迁。 + +## 落地步骤 + +1. **量基线** —— 不改代码 + - 行为:`baselineWallTimeCpuTimeAndPeakAreRecordedInTheProposal`(按「怎么量」在 `next` 上量一次,数字写进决策日志) +2. **加名额与它的测试** —— 改动地图第 1、2 行 + - 行为:`everyIterationRunsExactlyOnce`(1000 次迭代,每个下标恰好执行一次) + - 行为:`noMoreThanTheBudgetRunAtOnce`(闭包里记录同时在跑的数目,最大值不超过 `maximumConcurrentScans`) + - 行为:`twoCallsAtOnceShareTheBudget`(两个线程同时调用,合计同时在跑的数目不超过名额) + - 行为:`zeroIterationsReturnWithoutRunning` + - 实现时临时把入口换成裸 `DispatchQueue.concurrentPerform`,确认后三条里与上限有关的两条会失败(证明测试抓得住),再换回来;这一步不提交。 +3. **四处调用点改走名额,加源码扫描测试** —— 改动地图第 3–7 行 + - 行为:`everyParallelScanGoesThroughTheSharedBudget` + - 行为:`theScanDiscriminates` + - 行为:四个套件原有的测试照旧全部通过 +4. **Tuist 里两个扫描模块开 `-O`** —— 改动地图第 8 行 + - 行为:`debugConfigurationCompilesTheScanModulesOptimized`(重新生成后,生成的 `MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,构建日志里它们的编译命令带 `-O`) + - 行为:`crossReferenceAnalysisStaysUnoptimizedInDebug` + - 验证不通过就启用「详细设计」里的后备写法,再验证一次 +5. **复测并更新文档** —— 改动地图第 9–11 行 + - 行为:`cpuPeakStaysWithinTheBudget`(xctest 的 `%cpu` 峰值不超过 `maximumConcurrentScans × 100%` 加少量余量) + - 行为:`wallTimeAndCpuTimeAreRecordedAgainstTheBaseline` + - 复测时再采样一次;`CrossReferenceAnalysis` 或 `ObjCCodeReferences` 的帧占比明显时,把结论记进决策日志,再决定要不要扩大 `-O` 名单 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的「已知的坑」。 +- **有没有引入新术语** —— 预计没有:「扫描名额」只在本提案与那一小节里用,不登记术语表。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-21 | Created as Draft | Ultra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到两个原因:四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。 | +| 2026-11-21 | Accepted | 用户批准,开始实现。 | diff --git a/Documentations/README.md b/Documentations/README.md index a87cd256..ec269176 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -222,6 +222,7 @@ selects names using each access's offset and width. | [Evolutions/0101-swift6-mode-and-upcoming-features.md](Evolutions/0101-swift6-mode-and-upcoming-features.md) | **提案 0101(Implemented)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.0 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | | [Evolutions/0102-multiline-type-formatting.md](Evolutions/0102-multiline-type-formatting.md) | **提案 0102(Implemented)**:长类型拆行——新增 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把打印好的 `SemanticString` 里放不下的类型按括号拆成多行:放得下的类型不动,放不下的类型照 TypeAliasFormatter 的结构规则拆(多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表只在里面有拆开的部分时才拆,`<…>` 里写着要求的泛型签名不按参数拆);行首缩进不计入宽度,嵌套定义契约不受影响;只加换行与缩进,semantic type、identifier 与 region 原样保留。`InterfaceRequest` / `DumpRequest` 加字段,`dump` / `interface` 加 `--multiline-types` 与 `--maximum-line-width`;默认关闭,打印器不改。RuntimeViewer 的「Break Long Types」由那边的提案接入。 | | [Evolutions/draft-shared-macho-testing-support.md](Evolutions/draft-shared-macho-testing-support.md) | **提案 draft(Accepted)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | +| [Evolutions/draft-cross-reference-test-scan-load.md](Evolutions/draft-cross-reference-test-scan-load.md) | **提案 draft(Accepted)**:`CrossReferenceAnalysisTests` 的四处整份 dyld cache 扫描改走全进程共用的并发名额 `ImageScanConcurrency`(`max(2, 核心数 / 2)`),Swift Testing 并行跑套件时也不叠加回满核;Tuist 开发工作区里 `MachOCodeReferences`、`ARM64InstructionDecoding` 在 Debug 下也用 `-O` 编,去掉每条指令一次的运行时元数据查找。库 API、原生 workspace、`swift test` 与 CI 不变。 | | [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) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | From e9be8deddc6690d5ad8ac5c30207fb4299d74e62 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:07:51 +0800 Subject: [PATCH 063/175] test: give the cross-reference tests' parallel scans one process-wide budget of half the cores --- .../draft-cross-reference-test-scan-load.md | 9 +- .../ImageScanConcurrency.swift | 63 +++++++++++ .../ImageScanConcurrencyTests.swift | 107 ++++++++++++++++++ 3 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift create mode 100644 Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md index 44cb5307..73d2583d 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -1,6 +1,6 @@ # Draft - 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-21 - **最后更新**: 2026-11-21 @@ -283,9 +283,9 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI ## 落地步骤 -1. **量基线** —— 不改代码 +1. **量基线** —— 不改代码(已完成,数字见决策日志) - 行为:`baselineWallTimeCpuTimeAndPeakAreRecordedInTheProposal`(按「怎么量」在 `next` 上量一次,数字写进决策日志) -2. **加名额与它的测试** —— 改动地图第 1、2 行 +2. **加名额与它的测试** —— 改动地图第 1、2 行(已完成) - 行为:`everyIterationRunsExactlyOnce`(1000 次迭代,每个下标恰好执行一次) - 行为:`noMoreThanTheBudgetRunAtOnce`(闭包里记录同时在跑的数目,最大值不超过 `maximumConcurrentScans`) - 行为:`twoCallsAtOnceShareTheBudget`(两个线程同时调用,合计同时在跑的数目不超过名额) @@ -315,3 +315,6 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI |------|------|------| | 2026-11-21 | Created as Draft | Ultra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到两个原因:四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。 | | 2026-11-21 | Accepted | 用户批准,开始实现。 | +| 2026-11-21 | 测量时临时套用另一分支的修复 | `next` 上 `./TuistScript.sh test` 编不过:`SwiftSectionTestingMacrosTests` 报 `Unable to resolve module dependency: 'SwiftSectionTestingMacros'`。`feature/shared-macho-testing-support` 已经修了(Tuist 映射测试时把依赖宏 target 的测试也拿掉,改 `Package.swift` 两行),还没合进 `next`。本分支只在工作区里临时套用这两行来测量,不提交;改前改后在同样条件下量。 | +| 2026-11-21 | 基线 | Ultra,`next` 的代码,Tuist Debug,`-only-testing:CrossReferenceAnalysisTests`:124 个测试用时 841 秒(Swift Testing 的报告);xctest 累计 CPU 时间约 234 分钟(约 14 030 秒,平均约 17 个核心);`ps` 读到的 `%cpu` 峰值 2356%。同机另有一个会话的 `swift test` 占着约 4 个核心。3 个失败是新 worktree 缺 `SymbolTestsCore` 夹具,按 AGENTS.md 链接主检出的 `DerivedData` 后解决,与本提案无关。 | +| 2026-11-21 | 第 2 步验证 | 入口临时换成裸 `concurrentPerform` 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 `twoCallsAtOnceShareTheBudget` 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。 | diff --git a/Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift new file mode 100644 index 00000000..02a286a4 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift @@ -0,0 +1,63 @@ +import Foundation + +/// How many images this target's parallel scans may read at once: half of the +/// cores, at least two. +/// +/// A Debug scan of the whole shared cache keeps every core it is given busy +/// for minutes, and Swift Testing runs the suites holding these scans in +/// parallel. The budget is therefore one for the whole process, not one per +/// call: four suites with a width each would add up to every core again +/// (evolution proposal `cross-reference-test-scan-load`). +/// `ParallelScanSourceTests` keeps every parallel scan of the target on it. +enum ImageScanConcurrency { + static let maximumConcurrentScans = max(2, ProcessInfo.processInfo.activeProcessorCount / 2) + + private static let permits = DispatchSemaphore(value: maximumConcurrentScans) + + /// Runs `body` once for every index in `0 ..< iterations`, as + /// `DispatchQueue.concurrentPerform(iterations:execute:)` does, with at + /// most `maximumConcurrentScans` bodies running at once across the + /// process. + /// + /// Each call starts no more workers than the budget, so the threads + /// waiting for a permit stay bounded; each worker takes the next index and + /// holds a permit only while its body runs. A permit is never held across + /// a wait for other work, so the callers — the calling thread of + /// `concurrentPerform` may be a cooperative thread — always get one in the + /// end. + /// + /// `body` must not call this function again: a nested call waits for a + /// permit while its caller holds one, and with every permit held that way + /// none is ever released. + static func concurrentPerform(iterations: Int, execute body: (Int) -> Void) { + guard iterations > 0 else { return } + let cursor = IterationCursor(iterationCount: iterations) + DispatchQueue.concurrentPerform(iterations: min(maximumConcurrentScans, iterations)) { _ in + while let index = cursor.next() { + permits.wait() + defer { permits.signal() } + body(index) + } + } + } +} + +/// Hands out each index of `0 ..< iterationCount` once, to whichever worker +/// asks first. +private final class IterationCursor: @unchecked Sendable { + private let lock = NSLock() + private let iterationCount: Int + private var nextIndex = 0 + + init(iterationCount: Int) { + self.iterationCount = iterationCount + } + + func next() -> Int? { + lock.lock() + defer { lock.unlock() } + guard nextIndex < iterationCount else { return nil } + defer { nextIndex += 1 } + return nextIndex + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift new file mode 100644 index 00000000..b82c73fe --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift @@ -0,0 +1,107 @@ +import Foundation +import Testing + +/// Pins `ImageScanConcurrency` (evolution proposal +/// `cross-reference-test-scan-load`): every index runs once, and no more +/// bodies run at once than the budget — within one call, and across calls +/// made at the same time, which is what Swift Testing's parallel suites do. +@Suite +struct ImageScanConcurrencyTests { + @Test func everyIterationRunsExactlyOnce() { + let runs = RunCounter(iterationCount: 1000) + ImageScanConcurrency.concurrentPerform(iterations: 1000) { index in + runs.record(index) + } + #expect(runs.indicesNotRunExactlyOnce.isEmpty) + } + + @Test func noMoreThanTheBudgetRunAtOnce() { + let tracker = InFlightTracker() + ImageScanConcurrency.concurrentPerform(iterations: 300) { _ in + tracker.run { Thread.sleep(forTimeInterval: 0.002) } + } + #expect(tracker.completedCount == 300) + #expect(tracker.peak <= ImageScanConcurrency.maximumConcurrentScans) + } + + /// The other call runs on a thread of its own, never on a pool thread + /// this test would block waiting for. + @Test func twoCallsAtOnceShareTheBudget() { + let tracker = InFlightTracker() + let otherCallFinished = DispatchSemaphore(value: 0) + Thread { + ImageScanConcurrency.concurrentPerform(iterations: 300) { _ in + tracker.run { Thread.sleep(forTimeInterval: 0.002) } + } + otherCallFinished.signal() + }.start() + ImageScanConcurrency.concurrentPerform(iterations: 300) { _ in + tracker.run { Thread.sleep(forTimeInterval: 0.002) } + } + otherCallFinished.wait() + #expect(tracker.completedCount == 600) + #expect(tracker.peak <= ImageScanConcurrency.maximumConcurrentScans) + } + + @Test func zeroIterationsReturnWithoutRunning() { + let tracker = InFlightTracker() + ImageScanConcurrency.concurrentPerform(iterations: 0) { _ in + tracker.run {} + } + #expect(tracker.completedCount == 0) + } +} + +/// How many times each index ran. +private final class RunCounter: @unchecked Sendable { + private let lock = NSLock() + private var counts: [Int] + + init(iterationCount: Int) { + counts = Array(repeating: 0, count: iterationCount) + } + + func record(_ index: Int) { + lock.lock() + defer { lock.unlock() } + counts[index] += 1 + } + + var indicesNotRunExactlyOnce: [Int] { + lock.lock() + defer { lock.unlock() } + return counts.indices.filter { counts[$0] != 1 } + } +} + +/// The most bodies seen running at once, and how many finished. +private final class InFlightTracker: @unchecked Sendable { + private let lock = NSLock() + private var running = 0 + private var highestRunning = 0 + private var completed = 0 + + func run(_ body: () -> Void) { + lock.lock() + running += 1 + highestRunning = max(highestRunning, running) + lock.unlock() + body() + lock.lock() + running -= 1 + completed += 1 + lock.unlock() + } + + var peak: Int { + lock.lock() + defer { lock.unlock() } + return highestRunning + } + + var completedCount: Int { + lock.lock() + defer { lock.unlock() } + return completed + } +} From a71e98a02c1310a72a2df399038148897b90bbef Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:10:11 +0800 Subject: [PATCH 064/175] test: run the four whole-cache scans through the shared budget, and keep new ones on it with a source scan --- .../draft-cross-reference-test-scan-load.md | 3 +- .../CrossReferenceAnalyzerTests.swift | 2 +- .../FunctionStartOutsideTextTests.swift | 2 +- .../ObjectiveCClassReferenceTests.swift | 2 +- .../ParallelScanSourceTests.swift | 53 +++++++++++++++++++ .../SwiftTypeReferenceTests.swift | 2 +- 6 files changed, 59 insertions(+), 5 deletions(-) create mode 100644 Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md index 73d2583d..10e8553b 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -291,7 +291,7 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI - 行为:`twoCallsAtOnceShareTheBudget`(两个线程同时调用,合计同时在跑的数目不超过名额) - 行为:`zeroIterationsReturnWithoutRunning` - 实现时临时把入口换成裸 `DispatchQueue.concurrentPerform`,确认后三条里与上限有关的两条会失败(证明测试抓得住),再换回来;这一步不提交。 -3. **四处调用点改走名额,加源码扫描测试** —— 改动地图第 3–7 行 +3. **四处调用点改走名额,加源码扫描测试** —— 改动地图第 3–7 行(已完成;四个套件原有的测试在第 5 步的整批复测里一起验证) - 行为:`everyParallelScanGoesThroughTheSharedBudget` - 行为:`theScanDiscriminates` - 行为:四个套件原有的测试照旧全部通过 @@ -318,3 +318,4 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI | 2026-11-21 | 测量时临时套用另一分支的修复 | `next` 上 `./TuistScript.sh test` 编不过:`SwiftSectionTestingMacrosTests` 报 `Unable to resolve module dependency: 'SwiftSectionTestingMacros'`。`feature/shared-macho-testing-support` 已经修了(Tuist 映射测试时把依赖宏 target 的测试也拿掉,改 `Package.swift` 两行),还没合进 `next`。本分支只在工作区里临时套用这两行来测量,不提交;改前改后在同样条件下量。 | | 2026-11-21 | 基线 | Ultra,`next` 的代码,Tuist Debug,`-only-testing:CrossReferenceAnalysisTests`:124 个测试用时 841 秒(Swift Testing 的报告);xctest 累计 CPU 时间约 234 分钟(约 14 030 秒,平均约 17 个核心);`ps` 读到的 `%cpu` 峰值 2356%。同机另有一个会话的 `swift test` 占着约 4 个核心。3 个失败是新 worktree 缺 `SymbolTestsCore` 夹具,按 AGENTS.md 链接主检出的 `DerivedData` 后解决,与本提案无关。 | | 2026-11-21 | 第 2 步验证 | 入口临时换成裸 `concurrentPerform` 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 `twoCallsAtOnceShareTheBudget` 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。 | +| 2026-11-21 | 第 3 步验证 | 把一处调用点临时改回 `DispatchQueue.concurrentPerform` 时 `everyParallelScanGoesThroughTheSharedBudget` 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。 | diff --git a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift index a131cb41..6888c0f7 100644 --- a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift +++ b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift @@ -256,7 +256,7 @@ struct CrossReferenceAnalyzerTests { private func imagesReferencing(_ keys: Set, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer - DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in let imageIndex = imageIndices[position] if !analyzer.references(to: keys, inImageAt: imageIndex).isEmpty { found.insert(imageIndex) } } diff --git a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift index 1494d8a1..5505b120 100644 --- a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift +++ b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift @@ -21,7 +21,7 @@ struct FunctionStartOutsideTextTests { defer { flags.deallocate() } nonisolated(unsafe) let flagsBase = flags.baseAddress! let analyzer = self.analyzer - DispatchQueue.concurrentPerform(iterations: imageCount) { imageIndex in + ImageScanConcurrency.concurrentPerform(iterations: imageCount) { imageIndex in let table = analyzer.imageSet.transientFunctionTable(ofImageAt: imageIndex) (flagsBase + imageIndex).pointee = table.starts.contains { $0 < table.textStart || $0 >= table.textEnd } } diff --git a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift index 038d13ee..a4e987fe 100644 --- a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift @@ -193,7 +193,7 @@ struct ObjectiveCClassReferenceTests { private func imagesReferencing(_ className: String, at location: CodeLocation, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer - DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in let imageIndex = imageIndices[position] let references = analyzer.references(to: [.objectiveCClass(className)], inImageAt: imageIndex) if references.contains(where: { $0.target == .objectiveCClass(name: className, location: location) }) { found.insert(imageIndex) } diff --git a/Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift b/Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift new file mode 100644 index 00000000..5c82d52f --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift @@ -0,0 +1,53 @@ +import Foundation +import Testing + +/// Every parallel scan of this target goes through `ImageScanConcurrency`, +/// whose one budget keeps the suites Swift Testing runs at once from taking +/// every core between them (evolution proposal +/// `cross-reference-test-scan-load`). The throughput benchmark is the +/// exception: it measures the scan on every core, and runs only when asked. +@Suite +struct ParallelScanSourceTests { + /// The budget itself, the benchmark, and this file, whose discrimination + /// test spells the call it looks for. + private static let filesAllowedToCallDispatchDirectly: Set = [ + "ImageScanConcurrency.swift", + "ScanThroughputBenchmarkTests.swift", + "ParallelScanSourceTests.swift", + ] + + @Test func everyParallelScanGoesThroughTheSharedBudget() throws { + let fileURLs = try Self.targetSourceFiles() + try #require(fileURLs.contains { $0.lastPathComponent == "ImageScanConcurrency.swift" }, "not this target's directory") + var offendingLines: [String] = [] + for fileURL in fileURLs where !Self.filesAllowedToCallDispatchDirectly.contains(fileURL.lastPathComponent) { + let contents = try String(contentsOf: fileURL, encoding: .utf8) + for (lineNumber, line) in contents.components(separatedBy: .newlines).enumerated() { + let code = line.trimmingCharacters(in: .whitespaces) + guard !code.hasPrefix("//"), Self.callsDispatchDirectly(code) else { continue } + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(code)") + } + } + #expect(offendingLines.isEmpty, "scan through `ImageScanConcurrency.concurrentPerform`:\n\(offendingLines.joined(separator: "\n"))") + } + + /// The scan must see a direct call, and nothing else — its silence proves + /// nothing otherwise. + @Test func theScanDiscriminates() { + #expect(Self.callsDispatchDirectly("DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in")) + #expect(Self.callsDispatchDirectly("DispatchQueue.concurrentPerform(iterations: imageCount, execute: readTrie)")) + #expect(!Self.callsDispatchDirectly("ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in")) + #expect(!Self.callsDispatchDirectly("DispatchQueue.global().async {")) + } + + private static func callsDispatchDirectly(_ code: String) -> Bool { + code.contains("DispatchQueue.concurrentPerform(") + } + + private static func targetSourceFiles() throws -> [URL] { + let targetDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() // CrossReferenceAnalysisTests + return try FileManager.default + .contentsOfDirectory(at: targetDirectory, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "swift" } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift index 99e2e984..a2949e03 100644 --- a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift +++ b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift @@ -321,7 +321,7 @@ struct SwiftTypeReferenceTests { private func imagesReferencing(_ identity: SwiftTypeIdentity, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer - DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in if !analyzer.references(toSwiftType: identity, inImageAt: imageIndices[position]).isEmpty { found.insert(imageIndices[position]) } } return found.indices From 9a66ee17e529dd45273e6a12ae6df93483c80839 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:11:12 +0800 Subject: [PATCH 065/175] build: compile the cross-reference scan's two hottest modules optimized in the Tuist workspace's Debug builds --- .../draft-cross-reference-test-scan-load.md | 3 ++- Tuist/Package.swift | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md index 10e8553b..8aa0d2fe 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -295,7 +295,7 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI - 行为:`everyParallelScanGoesThroughTheSharedBudget` - 行为:`theScanDiscriminates` - 行为:四个套件原有的测试照旧全部通过 -4. **Tuist 里两个扫描模块开 `-O`** —— 改动地图第 8 行 +4. **Tuist 里两个扫描模块开 `-O`** —— 改动地图第 8 行(已完成) - 行为:`debugConfigurationCompilesTheScanModulesOptimized`(重新生成后,生成的 `MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,构建日志里它们的编译命令带 `-O`) - 行为:`crossReferenceAnalysisStaysUnoptimizedInDebug` - 验证不通过就启用「详细设计」里的后备写法,再验证一次 @@ -319,3 +319,4 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI | 2026-11-21 | 基线 | Ultra,`next` 的代码,Tuist Debug,`-only-testing:CrossReferenceAnalysisTests`:124 个测试用时 841 秒(Swift Testing 的报告);xctest 累计 CPU 时间约 234 分钟(约 14 030 秒,平均约 17 个核心);`ps` 读到的 `%cpu` 峰值 2356%。同机另有一个会话的 `swift test` 占着约 4 个核心。3 个失败是新 worktree 缺 `SymbolTestsCore` 夹具,按 AGENTS.md 链接主检出的 `DerivedData` 后解决,与本提案无关。 | | 2026-11-21 | 第 2 步验证 | 入口临时换成裸 `concurrentPerform` 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 `twoCallsAtOnceShareTheBudget` 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。 | | 2026-11-21 | 第 3 步验证 | 把一处调用点临时改回 `DispatchQueue.concurrentPerform` 时 `everyParallelScanGoesThroughTheSharedBudget` 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。 | +| 2026-11-21 | 第 4 步验证 | `base` 里的 `SWIFT_OPTIMIZATION_LEVEL` 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,`MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,同工程没进名单的 `MachOAddressResolution` 仍是 `-Onone`;本包 `MachOSwiftSection.xcodeproj` 里 `CrossReferenceAnalysis` 的 Debug 仍是 `-Onone`。 | diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 51a516d0..236637f7 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -109,6 +109,19 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac uniquingKeysWith: { first, _ in first } ) + // A Debug build of the cross-reference scan spends most of its time in the Swift runtime, not in + // the scan: an unspecialized range loop looks tuple metadata up on every instruction, under one + // lock every thread shares, so CrossReferenceAnalysisTests' whole-cache scans take minutes instead + // of the seconds a Release build needs. The scan's two hottest modules, both MachOKitExtensions', + // compile optimized in every configuration here; this package's own CrossReferenceAnalysis stays + // debuggable (evolution proposal cross-reference-test-scan-load). + let optimizedScanSettings: [String: Settings] = Dictionary( + ["MachOCodeReferences", "ARM64InstructionDecoding"].map { targetName in + (targetName, Settings.settings(base: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])) + }, + uniquingKeysWith: { first, _ in first } + ) + // One target may need several of the settings above; their keys never overlap. func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { settingsByTarget.reduce(into: [:]) { merged, settings in @@ -117,7 +130,7 @@ let localPackageDependencies: [PackageDescription.Package.Dependency] = localPac } let packageSettings = PackageSettings( - targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings, optimizedScanSettings), // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" From 3487469f14cd23effa18909c44760e8424778658 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:13:44 +0800 Subject: [PATCH 066/175] docs: note that the Tuist mapping's macro rule is synced to the upstream packages --- Documentations/Evolutions/draft-shared-macho-testing-support.md | 1 + Documentations/Internal/TuistDevelopment.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-shared-macho-testing-support.md b/Documentations/Evolutions/draft-shared-macho-testing-support.md index 546c9ed5..5c8a1448 100644 --- a/Documentations/Evolutions/draft-shared-macho-testing-support.md +++ b/Documentations/Evolutions/draft-shared-macho-testing-support.md @@ -389,3 +389,4 @@ MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): | 2026-11-21 | 第 5 步第四部分:本机 cache 共用、Tuist 远程模式 | `DyldCache(path: .current)` 等 27 处只读本机 cache,全部改用 `FullDyldCache.cachedHost`(要 `DyldCache` 的取它的 `mainCache`),`GenericSpecializationFixture` 也一并改;`FileMappingTests` 要在调低的描述符上限下打开这些文件,保留新实例并注明。缓存按镜像路径与 UUID 分,不认实例,共用不改变缓存行为。`TuistScript.sh` 的 `testing_support_names` 扫描挪到 `if role != "own-path"` 之前,own-remote 的包也扫;`Workspace.swift` 在设了 `MACHO_SWIFT_SECTION_SILENT_TEST=1` 时给测试 scheme 的环境加 `MACHO_TESTING_SILENT=1`;`TuistDevelopment.md` 同步。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0。`./TuistScript.sh test` 远程模式退出码 65,没走到 MKE 的 `MachOTestingSupport`:`SwiftSectionTestingMacrosTests` 的 `@testable import SwiftSectionTestingMacros` 在 Tuist 里解析不到宏 target。这个测试 target 随 0100 进入 next,Tuist 的适配段没处理依赖宏 target 的测试,是 next 上已有的问题,与本提案无关;已确认远程模式的扫描结果含 `MachOTestingSupport`、生成的工程带 TestingMacros 插件路径、scheme 带 `MACHO_TESTING_SILENT=1`。这一条验证待那个问题修好后补跑。 | | 2026-11-21 | 修好 Tuist workspace 的宏测试,补跑远程模式 | 用户选择在本分支一起修:清单末尾的 Tuist 适配段把依赖宏 target 的测试也拿掉(与依赖可执行 target 的测试同样处理),宏的展开测试只在 `swift test` 里跑。三个上游库清单末尾的同一段代码按约定该一起改,它们没有宏 target,这次没同步,`TuistDevelopment.md` 记了这一点。`./TuistScript.sh test` 远程模式退出码 0(`TEST SUCCEEDED`,约 26 分钟,2,953 个测试),编过了 MKE 的 `MachOTestingSupport`。 | | 2026-11-21 | 实现完成,待用户看过后收尾 | 第 5、6 步都已完成。文档:`AGENTS.md`(`Sources/` 一节的锚点、测试一节的测试支持来源与本机 cache、`ExclusiveImageAccess` 的 key、静默变量、新增套件时的写法)、`FixtureTestingAndContinuousIntegration.md`(路径锚定与新的一节)、`Modules/README.md`、`TuistDevelopment.md`、`ProjectEvolutionLog.md`(节号落地时定)。不另写实现说明(契约在 MachOKitExtensions 的 `TestingSupport.md`),没有新术语。后续项:`FixtureCompiler` 还替代不了的约 25 处现编(见上)。 | +| 2026-11-21 | Tuist 适配段的「宏 target」一条同步到三个上游库 | 用户选择保持四份一致:MachOKitExtensions `main`、MachOObjCSection `next`、swift-demangling `next` 各一个提交并推送;三者都没有宏 target,设与不设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 时清单解析结果与改前相同。不发版。 | diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index b539a228..3f367fc9 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -69,7 +69,7 @@ RuntimeViewer 的 Tuist workspace 在它的本地依赖模式下也往这几个 Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` 的 `includeLocalPackageTestTargets`),但它拒绝几种 SwiftPM 接受的测试:依赖可执行 target 的(本库的 `SwiftSectionCommandTests`、MachOObjCSection 的 `ObjCSectionCommandTests`);依赖宏 target 的(本库的 `SwiftSectionTestingMacrosTests`:Tuist 把宏编成插件,`@testable import SwiftSectionTestingMacros` 找不到模块);和依赖一个不属于任何 product 的普通 target 的(本库的 `SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`,swift-demangling 的 `DemanglingTestingSupport`)。 -- **适配块**:`Package.swift` 末尾那段代码只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效——脚本解析依赖时设它——把依赖可执行 target 或宏 target 的测试拿掉(宏的展开测试因此只在 `swift test` 里跑),给依赖非 product target 的测试所依赖的 target 补一个 library product。平时这个变量不存在,块里什么都不做:`swift package dump-package` 的输出与没有这段代码时逐字节相同。规则是通用的,以后新加的这几种测试不用再改清单。三个上游库的清单末尾是同一段代码,改的时候四处一起改;2026-11-21 本库加上「宏 target」一条时,三个上游库没有宏 target,暂未同步(见 `draft-shared-macho-testing-support` 决策日志)。 +- **适配块**:`Package.swift` 末尾那段代码只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效——脚本解析依赖时设它——把依赖可执行 target 或宏 target 的测试拿掉(宏的展开测试因此只在 `swift test` 里跑),给依赖非 product target 的测试所依赖的 target 补一个 library product。平时这个变量不存在,块里什么都不做:`swift package dump-package` 的输出与没有这段代码时逐字节相同。规则是通用的,以后新加的这几种测试不用再改清单。三个上游库的清单末尾是同一段代码,改的时候四处一起改(2026-11-21 加「宏 target」一条时四处同步改了,三个上游库没有宏 target,对它们没有实际作用)。 - **`SwiftSectionCommandTests` 手写在 `Tuist/CommandLine/Project.swift`**:它 `@testable import swift_section`,也就是可执行 target 自己的模块。那里把 CLI 的源码编成静态 framework `swift_section` 给它用,`swift-section` 工具再编一遍同样的源码,链接时不用绕开 `@main` 的入口。**CLI 的依赖列表是 Tuist 描述里唯一手抄的一份**:`Package.swift` 里 `swift-section` 加了依赖,这里也要加,否则编不过。MachOObjCSection 的 `ObjCSectionCommandTests` 不手写,留在 `swift test` 里跑。 - **只被测试用到的外部依赖要在 `Tuist/Package.swift` 里声明**(现在只有 swift-snapshot-testing),否则 Tuist 报 `… depends on 'X', which is not a configured external dependency`。按 `Package.swift` 里的版本要求加上即可。 - **`IntegrationTests`** 会被转换进来,但不进任何 scheme(`AGENTS.md`:维护者手工查看用的,不跑)。 From 9b6f123483fae1f2d738c0d6e1e89859283f652f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:18:41 +0800 Subject: [PATCH 067/175] docs: record the shared scan budget and the Tuist workspace's optimized scan modules, with the measured run times --- AGENTS.md | 1 + .../draft-cross-reference-test-scan-load.html | 33 +++++++++++++------ .../draft-cross-reference-test-scan-load.md | 11 +++++-- .../FixtureTestingAndContinuousIntegration.md | 13 ++++++++ Documentations/Internal/TuistDevelopment.md | 11 +++++++ 5 files changed, 56 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2141ca44..9ac059ad 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,6 +155,7 @@ python3 Scripts/test-run-rendering-ab-verification.py - Swift Testing runs test bodies on **512 KB cooperative threads**. A test calling a library entry point gets the large-stack executor from that entry's own `LargeStackTaskExecution.run`; a test driving the demangler or printer *directly* in deep recursion does not — wrap such a body in `LargeStackTaskExecution.run` when the hop cost or the 8 MB pool depth is what is being measured. "The suite passed" is not evidence the executor was used. - **Never block a cooperative thread with an untimed wait on work that itself needs a pool thread** — a `DispatchQueue.global()` block, a `Task`. The CI runner has 3 cores, so the pool is 3 threads wide: on 2026-09-29 three such tests froze the whole test process there, while a 10-core machine never lines three up. Give the counterpart a `Thread { … }.start()` of its own, or run the blocking side on one. CI re-runs `ConcurrentDefinitionPrintingTests` on a one-thread pool (`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`) to catch this — the `SharedCache` suites that step was written for moved to MachOKitExtensions with the cache; a new suite that blocks on purpose belongs in that step. [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). +- **A test that scans many images in parallel goes through `ImageScanConcurrency.concurrentPerform(iterations:execute:)` (CrossReferenceAnalysisTests), never a bare `DispatchQueue.concurrentPerform`.** A Debug whole-cache scan keeps every core it gets busy for minutes, and Swift Testing runs suites in parallel, so the budget — half the cores, at least two — is one for the whole process. Its body must not call it again (a nested call waits for a permit its caller holds). `ParallelScanSourceTests` enforces the rule; only the opt-in `ScanThroughputBenchmarkTests` is exempt. [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). - **Look a definition up by its full `name` or by `declaredNameForTesting` (SwiftSectionTestingSupport), never by `currentName`.** `currentName` is the display name dump and interface print in a declaration header — the printed name's last dot-separated component — and a function-local type's is the tail of its enclosing function's signature. A test indexing the test binary sees the library's local types: a `Hashable` enum declared in a function returning `Int` read as a second `Int` candidate, and a specialization test passed or failed on `Set` order ([ReviewAdjudications A52](Documentations/Internal/ReviewAdjudications.md)). - **A suite asserting on whole-process state derived from an image must declare `ExclusiveImageAccess(.TheFixture)` — and so must every other suite touching that image.** A one-sided declaration excludes nothing. `.serialized` does not work (it orders within one container only, and `swift test` links everything into one process) and neither does a global actor (these tests are `async`, and `await` yields the actor). Do not assert exclusivity in a doc comment: `grep ExclusiveImageAccess` finds every declared user, grepping a fixture name does not. - **A `swift test` process never enforces pointer authentication, even built and reported as arm64e** — auth fixups are strip-applied there, so signed slots read back bare. Any "verified because the suite passed as arm64e" claim is a placebo; verify by spawning a real arm64e child process, as `Arm64eSignedVWTPointerTests` does. diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html b/Documentations/Evolutions/draft-cross-reference-test-scan-load.html index aab11614..fc8e01b8 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.html @@ -163,7 +163,7 @@

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-21
    项目类型
    库
    原文
    draft-cross-reference-test-scan-load.md
    @@ -200,15 +200,18 @@

    摘要

    要你定

    -

    轻量档:看过简报点头即可开工

    +

    已批准并实现;剩一个后续问题

      -
    1. 名额取半数核心(Ultra 上 14 个)、至少 2 个,可以吗?
    2. -
    3. -O 只给采样里出现的两个模块,本包自己的 CrossReferenceAnalysis 保持可调试,可以吗?
    4. +
    5. 开头约 35 秒仍会用满核心,那是 Swift Testing 同时跑着二十多个测试,不在本提案范围。要不要另外限制测试运行器的并行度?
    -
    -

    未实测

    -

    「开 -O 后接近 Release 的速度」是推测;Tuist 的 base 设置能否覆盖按配置写的 -Onone 也未验证。落地第 1、4、5 步分别量基线、验证设置、复测。

    +
    +

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

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

    落地步骤

  • 加名额与测试 —— everyIterationRunsExactlyOnce、noMoreThanTheBudgetRunAtOnce、twoCallsAtOnceShareTheBudget、zeroIterationsReturnWithoutRunning;临时换回裸 concurrentPerform 确认上限相关的两条会失败
  • 四处调用点改走名额,加源码扫描测试 —— everyParallelScanGoesThroughTheSharedBudget、theScanDiscriminates,原有测试全部通过
  • Tuist 里两个模块开 -O —— debugConfigurationCompilesTheScanModulesOptimized、crossReferenceAnalysisStaysUnoptimizedInDebug;不通过就启用后备写法
  • -
  • 复测并更新文档 —— cpuPeakStaysWithinTheBudget、wallTimeAndCpuTimeAreRecordedAgainstTheBaseline;再采样决定要不要扩大 -O 名单
  • +
  • 复测并更新文档 —— wholeCacheScansStayWithinTheBudget、wallTimeAndCpuTimeAreRecordedAgainstTheBaseline;原定的「xctest 峰值不超过名额」没有成立(开头约 35 秒是 Swift Testing 自身的并行);复测采样后决定不扩大 -O 名单
  • 收尾判断:预计不需要专题文章(设计来历进 FixtureTestingAndContinuousIntegration.md,Tuist 差异进 TuistDevelopment.md),不引入新术语。

    @@ -438,14 +441,24 @@

    落地步骤

    决策日志

    - 2 条,最近一条:Accepted + 12 条,最近一条:实现完成,待用户看过后收尾
    - + + + + + + + + + + +
    日期变更说明
    2026-11-21Created as DraftUltra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。
    2026-11-21Created as DraftUltra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到两个原因:四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。
    2026-11-21Accepted用户批准,开始实现。
    2026-11-21测量时临时套用另一分支的修复next 上 ./TuistScript.sh test 编不过:SwiftSectionTestingMacrosTests 报 Unable to resolve module dependency: 'SwiftSectionTestingMacros'。feature/shared-macho-testing-support 已经修了(Tuist 映射测试时把依赖宏 target 的测试也拿掉,改 Package.swift 两行),还没合进 next。本分支只在工作区里临时套用这两行来测量,不提交;改前改后在同样条件下量。
    2026-11-21基线Ultra,next 的代码,Tuist Debug,-only-testing:CrossReferenceAnalysisTests:124 个测试用时 841 秒(Swift Testing 的报告);xctest 累计 CPU 时间约 234 分钟(约 14 030 秒,平均约 17 个核心);ps 读到的 %cpu 峰值 2356%。同机另有一个会话的 swift test 占着约 4 个核心。3 个失败是新 worktree 缺 SymbolTestsCore 夹具,按 AGENTS.md 链接主检出的 DerivedData 后解决,与本提案无关。
    2026-11-21第 2 步验证入口临时换成裸 concurrentPerform 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 twoCallsAtOnceShareTheBudget 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。
    2026-11-21第 3 步验证把一处调用点临时改回 DispatchQueue.concurrentPerform 时 everyParallelScanGoesThroughTheSharedBudget 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。
    2026-11-21第 4 步验证base 里的 SWIFT_OPTIMIZATION_LEVEL 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,MachOKitExtensions.xcodeproj 里 MachOCodeReferences、ARM64InstructionDecoding 的 Debug 配置是 -O,同工程没进名单的 MachOAddressResolution 仍是 -Onone;本包 MachOSwiftSection.xcodeproj 里 CrossReferenceAnalysis 的 Debug 仍是 -Onone。
    2026-11-21第 5 步复测同一台 Ultra,同样条件(机器上没有别的测试在跑):127 个测试全部通过(3 个跳过);xctest 存活约 91 秒,累计 CPU 时间约 829 秒(基线约 14 030 秒,约 17 倍);第二次复测 93 秒、843 秒,结果一致。构建日志里 MachOCodeReferences 的编译命令带 -O。
    2026-11-21偏离:开头约 35 秒仍满核ps 读到的 %cpu 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(FileModeTests 建文件模式分析器、各种预筛测试、LargeStackThreadPool 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,后续要不要限由用户决定。
    2026-11-21不扩大 -O 名单复测时在第 61 秒采样:只剩三个 FileModeTests 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,CrossReferenceAnalysis、ObjCCodeReferences 开 -O 收益不大,维持原名单。
    2026-11-21收尾判断不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。
    2026-11-21实现完成,待用户看过后收尾功能分支已推送并在本地合进 next 的常驻检出(不推送);测量时临时套用的 Package.swift 两行没有提交。
    diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md index 8aa0d2fe..b1b7c698 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -44,7 +44,7 @@ - **开 `-O` 不会丢掉检查**:`MachOCodeReferences`、`ARM64InstructionDecoding` 里没有 `assert` / `assertionFailure`(`-O` 会去掉它们),`MachOCodeReferences` 的两处 `precondition` 在 `-O` 下保留。本包的 `CrossReferenceAnalysis` 有一处 `assert`,这也是它不进名单的原因之一。 - **Tuist 工作区里这两个模块从源码编**:TuistDevelopment.md 写明原生 workspace 里的五个上游库(含 MachOKitExtensions)在两种依赖模式下都从源码编、不进二进制缓存,`PackageSettings.targetSettings` 按 target 名对它们生效(已有先例:`restatedTraitDefinitions` 给远程包 Capstone 加设置)。 - **Tuist 生成的工程把优化级别写在每个配置里**:现有生成结果 `…/Dependencies//tuist-derived/Projects/MachOKitExtensions/MachOKitExtensions.xcodeproj/project.pbxproj` 中,每个 target 的 Debug 配置写 `SWIFT_OPTIMIZATION_LEVEL = "-Onone"`、Release 写 `"-O"`。**未验证**:`targetSettings` 的 `base` 是否覆盖这个按配置写的值。落地第 4 步先验证,不行就改用按配置的设置(见「详细设计」)。 -- **预期收益是推测**:「Debug 下这两个模块开 `-O` 后,扫描接近 Release 的速度」没有实测。落地第 1 步与第 5 步各量一次,结论写回本提案。 +- **实测收益**(落地第 1、5 步,同一台 Ultra、同样条件):`CrossReferenceAnalysisTests` 从约 14 分钟降到约 1.5 分钟,xctest 累计 CPU 时间从约 234 分钟降到约 14 分钟(约 17 倍)。开头约 35 秒仍会用满核心,那是 Swift Testing 同时跑着二十多个测试,不是这四处扫描(见决策日志)。 ## 提议方案 @@ -299,8 +299,8 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI - 行为:`debugConfigurationCompilesTheScanModulesOptimized`(重新生成后,生成的 `MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,构建日志里它们的编译命令带 `-O`) - 行为:`crossReferenceAnalysisStaysUnoptimizedInDebug` - 验证不通过就启用「详细设计」里的后备写法,再验证一次 -5. **复测并更新文档** —— 改动地图第 9–11 行 - - 行为:`cpuPeakStaysWithinTheBudget`(xctest 的 `%cpu` 峰值不超过 `maximumConcurrentScans × 100%` 加少量余量) +5. **复测并更新文档** —— 改动地图第 9–11 行(已完成) + - 行为:`wholeCacheScansStayWithinTheBudget`(采样里,四处扫描同时占用的线程不超过名额)。原先写的「xctest 的 `%cpu` 峰值不超过名额」没有成立:开头约 35 秒是 Swift Testing 自身的并行,见决策日志 - 行为:`wallTimeAndCpuTimeAreRecordedAgainstTheBaseline` - 复测时再采样一次;`CrossReferenceAnalysis` 或 `ObjCCodeReferences` 的帧占比明显时,把结论记进决策日志,再决定要不要扩大 `-O` 名单 @@ -320,3 +320,8 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI | 2026-11-21 | 第 2 步验证 | 入口临时换成裸 `concurrentPerform` 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 `twoCallsAtOnceShareTheBudget` 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。 | | 2026-11-21 | 第 3 步验证 | 把一处调用点临时改回 `DispatchQueue.concurrentPerform` 时 `everyParallelScanGoesThroughTheSharedBudget` 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。 | | 2026-11-21 | 第 4 步验证 | `base` 里的 `SWIFT_OPTIMIZATION_LEVEL` 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,`MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,同工程没进名单的 `MachOAddressResolution` 仍是 `-Onone`;本包 `MachOSwiftSection.xcodeproj` 里 `CrossReferenceAnalysis` 的 Debug 仍是 `-Onone`。 | +| 2026-11-21 | 第 5 步复测 | 同一台 Ultra,同样条件(机器上没有别的测试在跑):127 个测试全部通过(3 个跳过);xctest 存活约 91 秒,累计 CPU 时间约 829 秒(基线约 14 030 秒,约 17 倍);第二次复测 93 秒、843 秒,结果一致。构建日志里 `MachOCodeReferences` 的编译命令带 `-O`。 | +| 2026-11-21 | 偏离:开头约 35 秒仍满核 | `ps` 读到的 `%cpu` 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(`FileModeTests` 建文件模式分析器、各种预筛测试、`LargeStackThreadPool` 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,后续要不要限由用户决定。 | +| 2026-11-21 | 不扩大 `-O` 名单 | 复测时在第 61 秒采样:只剩三个 `FileModeTests` 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,`CrossReferenceAnalysis`、`ObjCCodeReferences` 开 `-O` 收益不大,维持原名单。 | +| 2026-11-21 | 收尾判断 | 不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。 | +| 2026-11-21 | 实现完成,待用户看过后收尾 | 功能分支已推送并在本地合进 `next` 的常驻检出(不推送);测量时临时套用的 `Package.swift` 两行没有提交。 | diff --git a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md index 95767cf9..c62e1155 100644 --- a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md +++ b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md @@ -201,6 +201,19 @@ GitHub 的 `macos-26` runner 是 3 核、7 GB 内存。Swift Concurrency 的 coo **排查这类卡住的办法**:`swift test` 的控制台输出是分块缓冲后才进日志的,只看日志分不清是哪个测试卡住。当时用的诊断 workflow 在 PR #128 的提交 `e473b89d` 里,可以照搬:测试放后台跑并打开 `--event-stream-output-path`(每个事件单独写一行),超过 12 分钟就列出「已开始但没结束」的测试、内存状态,并对 `swiftpm-testing-helper` 做 `sample`(它带 `get-task-allow`,不需要 sudo)。 +## 整份 cache 扫描共用一份并发名额(2026-11-21) + +`CrossReferenceAnalysisTests` 里有几处测试要把整份 dyld shared cache 的上千个镜像各扫一遍:调用者、Swift 类型、ObjC 类三种预筛的抽样复查,以及找 `__text` 之外的函数起点。它们原先各自用 `DispatchQueue.concurrentPerform` 按镜像数开满并发。Debug 构建下扫一遍要好几分钟,测试期间整台机器被占满:2026-11-21 在 28 核的 Ultra 上,xctest 持续占 2300% 以上的 CPU,这一个 target 跑了 14 分钟。 + +**规则**:这个 target 里并行扫描很多镜像,一律走 `ImageScanConcurrency.concurrentPerform(iterations:execute:)`,不直接调 `DispatchQueue.concurrentPerform`。 + +- **名额是 `max(2, 核心数 / 2)`,全进程共用**:Swift Testing 会并行跑几个套件,每次调用各自限宽的话加起来又是满核。`ImageScanConcurrencyTests.twoCallsAtOnceShareTheBudget` 钉住这一点:只按调用限宽、不共用名额的实现会让它失败。 +- **每次调用最多起「名额」个工作者**,各自从共享游标领下一个下标、扫之前取一个名额。只靠信号量的话,`concurrentPerform` 仍按核心数起线程,多出来的线程全阻塞在等名额上。 +- **不会卡住 cooperative thread**:名额只在扫一个镜像期间持有,扫描是同步的 CPU 工作、不等任何线程池,所以调用线程是 cooperative thread 也总能等到名额,不违反上一节的规则。**闭包里不能再调它**:嵌套调用在外层占着名额时再去等名额,名额全被这样占住就再也放不出来。 +- **`ParallelScanSourceTests` 拦下新的直接调用**:扫这个 target 的源码,名额之外出现 `DispatchQueue.concurrentPerform(` 就失败。例外只有 `ScanThroughputBenchmarkTests`:它要设 `CROSS_REFERENCE_BENCHMARK_OUTPUT` 才跑,量的就是全核吞吐。 + +Debug 下扫描本身为什么慢、Tuist workspace 怎么处理,见 [TuistDevelopment.md](TuistDevelopment.md) 的「扫描模块在 Debug 下也开优化」一节;设计来历与测量数据见提案 [cross-reference-test-scan-load](../Evolutions/draft-cross-reference-test-scan-load.md)。 + ## 相关文档 - [AGENTS.md](../../AGENTS.md) —— 覆盖体系的现行操作规程(invariants、regen-baselines、环境漂移排查) diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md index 1a2f934c..5a763ca4 100644 --- a/Documentations/Internal/TuistDevelopment.md +++ b/Documentations/Internal/TuistDevelopment.md @@ -105,3 +105,14 @@ Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` - **警告还给按路径声明的包**:Tuist 对所有包都关掉警告,Xcode 只关远程包的;本库(本地模式下还有五个上游库)的 target 经 `TUIST_WARNING_TARGET_NAMES` 把警告要回来。 - **预热要带 `--cache-profile development`**(脚本已经带上):`tuist cache warm` 不读 `Tuist.swift` 里的默认配置,不传就连本库与上游库也一起缓存。缓存例外按 target 名字匹配所有包,脚本读完清单会警告名字撞上的第三方 target。 - **Tuist 会往 `PrecompiledLibraries/swift-syntax/` 里写 `swift-syntax.xcodeproj`、`Derived/` 与 `.build/`**:它也是按路径声明的包。都已忽略。 + +## 扫描模块在 Debug 下也开优化 + +`Tuist/Package.swift` 的 `optimizedScanSettings` 让 MachOKitExtensions 的 `MachOCodeReferences` 与 `ARM64InstructionDecoding` 在 Debug 配置下也用 `-O` 编译。这是 Tuist workspace 与原生 workspace、`swift test` 之间一处有意的差异,后两者不受影响。 + +- **为什么**:这两个模块是交叉引用扫描的热路径。`-Onone` 下,扫描里逐条指令、逐个寄存器的区间循环走 libswiftCore 里未特化的 `IndexingIterator.next()`,每走一步都要查一次元组类型元数据,几十个线程争同一把锁;2026-11-21 在 Ultra 上采样,工作线程近一半的时间花在这上面。 +- **效果**(同一台 Ultra,Debug,`-only-testing:CrossReferenceAnalysisTests`,连同测试里的扫描限并发一起改):这个 target 从 14 分钟降到约 1.5 分钟,xctest 累计 CPU 时间从约 234 分钟降到约 14 分钟。 +- **代价**:在 Tuist workspace 里对这两个模块打断点,看到的是优化后的代码,部分局部变量看不到。要调试它们时,从 `optimizedScanSettings` 的名单里临时拿掉再 `./TuistScript.sh generate`,调完放回去。本库自己的 `CrossReferenceAnalysis` 不在名单里,照常可调试。 +- **确认生效**:重新生成后,`/Dependencies//tuist-derived/Projects/MachOKitExtensions/MachOKitExtensions.xcodeproj` 里这两个 target 的 Debug 配置是 `SWIFT_OPTIMIZATION_LEVEL = "-O"`;构建日志里它们的编译命令带 `-O`。`base` 里的设置盖得过 Tuist 按配置写的 `-Onone`。 + +测试一侧的限并发见 [FixtureTestingAndContinuousIntegration.md](FixtureTestingAndContinuousIntegration.md) 的「整份 cache 扫描共用一份并发名额」;设计来历见提案 [cross-reference-test-scan-load](../Evolutions/draft-cross-reference-test-scan-load.md)。 From 0887dff51b8feaeee5195397b179f9c930a1a36c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:29:57 +0800 Subject: [PATCH 068/175] docs: record the full test run of the cross-reference test scan load change --- .../Evolutions/draft-cross-reference-test-scan-load.html | 3 ++- .../Evolutions/draft-cross-reference-test-scan-load.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html b/Documentations/Evolutions/draft-cross-reference-test-scan-load.html index fc8e01b8..8b8ac277 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.html @@ -441,7 +441,7 @@

    落地步骤

    决策日志

    - 12 条,最近一条:实现完成,待用户看过后收尾 + 13 条,最近一条:实现完成,待用户看过后收尾
    @@ -458,6 +458,7 @@

    决策日志

    +
    2026-11-21偏离:开头约 35 秒仍满核ps 读到的 %cpu 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(FileModeTests 建文件模式分析器、各种预筛测试、LargeStackThreadPool 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,后续要不要限由用户决定。
    2026-11-21不扩大 -O 名单复测时在第 61 秒采样:只剩三个 FileModeTests 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,CrossReferenceAnalysis、ObjCCodeReferences 开 -O 收益不大,维持原名单。
    2026-11-21收尾判断不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。
    2026-11-21完整验证Tuist workspace 的 MachOSwiftSection Tests 整个 scheme(Debug,Ultra,带测量时同样临时套用的 Package.swift 两行):3005 个通过、0 失败、7 个跳过,634 秒。
    2026-11-21实现完成,待用户看过后收尾功能分支已推送并在本地合进 next 的常驻检出(不推送);测量时临时套用的 Package.swift 两行没有提交。
    diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md index b1b7c698..bbe14f4a 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -324,4 +324,5 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI | 2026-11-21 | 偏离:开头约 35 秒仍满核 | `ps` 读到的 `%cpu` 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(`FileModeTests` 建文件模式分析器、各种预筛测试、`LargeStackThreadPool` 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,后续要不要限由用户决定。 | | 2026-11-21 | 不扩大 `-O` 名单 | 复测时在第 61 秒采样:只剩三个 `FileModeTests` 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,`CrossReferenceAnalysis`、`ObjCCodeReferences` 开 `-O` 收益不大,维持原名单。 | | 2026-11-21 | 收尾判断 | 不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。 | +| 2026-11-21 | 完整验证 | Tuist workspace 的 `MachOSwiftSection Tests` 整个 scheme(Debug,Ultra,带测量时同样临时套用的 `Package.swift` 两行):3005 个通过、0 失败、7 个跳过,634 秒。 | | 2026-11-21 | 实现完成,待用户看过后收尾 | 功能分支已推送并在本地合进 `next` 的常驻检出(不推送);测量时临时套用的 `Package.swift` 两行没有提交。 | From b42118c96d75b967fdcb94c776ba0f7bab4c8a24 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 15:34:50 +0800 Subject: [PATCH 069/175] docs: record the decision to leave Swift Testing's own parallelism alone --- .../draft-cross-reference-test-scan-load.html | 11 +++++------ .../draft-cross-reference-test-scan-load.md | 3 ++- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html b/Documentations/Evolutions/draft-cross-reference-test-scan-load.html index 8b8ac277..f6a1ce5c 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.html @@ -200,10 +200,8 @@

    摘要

    要你定

    -

    已批准并实现;剩一个后续问题

    -
      -
    1. 开头约 35 秒仍会用满核心,那是 Swift Testing 同时跑着二十多个测试,不在本提案范围。要不要另外限制测试运行器的并行度?
    2. -
    +

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

    +

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

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

    @@ -441,7 +439,7 @@

    落地步骤

    决策日志

    - 13 条,最近一条:实现完成,待用户看过后收尾 + 14 条,最近一条:不限制测试运行器的并行度
    @@ -455,11 +453,12 @@

    决策日志

    - + +
    2026-11-21第 3 步验证把一处调用点临时改回 DispatchQueue.concurrentPerform 时 everyParallelScanGoesThroughTheSharedBudget 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。
    2026-11-21第 4 步验证base 里的 SWIFT_OPTIMIZATION_LEVEL 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,MachOKitExtensions.xcodeproj 里 MachOCodeReferences、ARM64InstructionDecoding 的 Debug 配置是 -O,同工程没进名单的 MachOAddressResolution 仍是 -Onone;本包 MachOSwiftSection.xcodeproj 里 CrossReferenceAnalysis 的 Debug 仍是 -Onone。
    2026-11-21第 5 步复测同一台 Ultra,同样条件(机器上没有别的测试在跑):127 个测试全部通过(3 个跳过);xctest 存活约 91 秒,累计 CPU 时间约 829 秒(基线约 14 030 秒,约 17 倍);第二次复测 93 秒、843 秒,结果一致。构建日志里 MachOCodeReferences 的编译命令带 -O。
    2026-11-21偏离:开头约 35 秒仍满核ps 读到的 %cpu 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(FileModeTests 建文件模式分析器、各种预筛测试、LargeStackThreadPool 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,后续要不要限由用户决定。
    2026-11-21偏离:开头约 35 秒仍满核ps 读到的 %cpu 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(FileModeTests 建文件模式分析器、各种预筛测试、LargeStackThreadPool 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,
    2026-11-21不扩大 -O 名单复测时在第 61 秒采样:只剩三个 FileModeTests 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,CrossReferenceAnalysis、ObjCCodeReferences 开 -O 收益不大,维持原名单。
    2026-11-21收尾判断不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。
    2026-11-21完整验证Tuist workspace 的 MachOSwiftSection Tests 整个 scheme(Debug,Ultra,带测量时同样临时套用的 Package.swift 两行):3005 个通过、0 失败、7 个跳过,634 秒。
    2026-11-21实现完成,待用户看过后收尾功能分支已推送并在本地合进 next 的常驻检出(不推送);测量时临时套用的 Package.swift 两行没有提交。
    2026-11-21不限制测试运行器的并行度用户决定保持现状:满核时间已从 14 分钟缩到开头约 35 秒,不再另写提案限制 Swift Testing 同时跑的测试数。
    diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md index bbe14f4a..df184889 100644 --- a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md +++ b/Documentations/Evolutions/draft-cross-reference-test-scan-load.md @@ -321,8 +321,9 @@ Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMI | 2026-11-21 | 第 3 步验证 | 把一处调用点临时改回 `DispatchQueue.concurrentPerform` 时 `everyParallelScanGoesThroughTheSharedBudget` 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。 | | 2026-11-21 | 第 4 步验证 | `base` 里的 `SWIFT_OPTIMIZATION_LEVEL` 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,`MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,同工程没进名单的 `MachOAddressResolution` 仍是 `-Onone`;本包 `MachOSwiftSection.xcodeproj` 里 `CrossReferenceAnalysis` 的 Debug 仍是 `-Onone`。 | | 2026-11-21 | 第 5 步复测 | 同一台 Ultra,同样条件(机器上没有别的测试在跑):127 个测试全部通过(3 个跳过);xctest 存活约 91 秒,累计 CPU 时间约 829 秒(基线约 14 030 秒,约 17 倍);第二次复测 93 秒、843 秒,结果一致。构建日志里 `MachOCodeReferences` 的编译命令带 `-O`。 | -| 2026-11-21 | 偏离:开头约 35 秒仍满核 | `ps` 读到的 `%cpu` 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(`FileModeTests` 建文件模式分析器、各种预筛测试、`LargeStackThreadPool` 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,后续要不要限由用户决定。 | +| 2026-11-21 | 偏离:开头约 35 秒仍满核 | `ps` 读到的 `%cpu` 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(`FileModeTests` 建文件模式分析器、各种预筛测试、`LargeStackThreadPool` 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」。 | | 2026-11-21 | 不扩大 `-O` 名单 | 复测时在第 61 秒采样:只剩三个 `FileModeTests` 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,`CrossReferenceAnalysis`、`ObjCCodeReferences` 开 `-O` 收益不大,维持原名单。 | | 2026-11-21 | 收尾判断 | 不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。 | | 2026-11-21 | 完整验证 | Tuist workspace 的 `MachOSwiftSection Tests` 整个 scheme(Debug,Ultra,带测量时同样临时套用的 `Package.swift` 两行):3005 个通过、0 失败、7 个跳过,634 秒。 | | 2026-11-21 | 实现完成,待用户看过后收尾 | 功能分支已推送并在本地合进 `next` 的常驻检出(不推送);测量时临时套用的 `Package.swift` 两行没有提交。 | +| 2026-11-21 | 不限制测试运行器的并行度 | 用户决定保持现状:满核时间已从 14 分钟缩到开头约 35 秒,不再另写提案限制 Swift Testing 同时跑的测试数。 | From 1c58d1c68a6b0bb1e33b6af4a2682fab298f5012 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 18:26:27 +0800 Subject: [PATCH 070/175] docs: land proposal 0103, cross-reference test scan load, as Implemented, with evolution log section 149 --- ...st-scan-load.html => 0103-cross-reference-test-scan-load.html} | 0 ...e-test-scan-load.md => 0103-cross-reference-test-scan-load.md} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Documentations/Evolutions/{draft-cross-reference-test-scan-load.html => 0103-cross-reference-test-scan-load.html} (100%) rename Documentations/Evolutions/{draft-cross-reference-test-scan-load.md => 0103-cross-reference-test-scan-load.md} (100%) diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.html b/Documentations/Evolutions/0103-cross-reference-test-scan-load.html similarity index 100% rename from Documentations/Evolutions/draft-cross-reference-test-scan-load.html rename to Documentations/Evolutions/0103-cross-reference-test-scan-load.html diff --git a/Documentations/Evolutions/draft-cross-reference-test-scan-load.md b/Documentations/Evolutions/0103-cross-reference-test-scan-load.md similarity index 100% rename from Documentations/Evolutions/draft-cross-reference-test-scan-load.md rename to Documentations/Evolutions/0103-cross-reference-test-scan-load.md From 99b9248cf6c84efb013515edf3f9015729ee3a4c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 21 Nov 2026 18:26:39 +0800 Subject: [PATCH 071/175] docs: mark proposal 0103 Implemented, point the indexes and links at its number, and add evolution log section 149 --- .../0103-cross-reference-test-scan-load.html | 13 +++++++------ .../0103-cross-reference-test-scan-load.md | 7 ++++--- Documentations/Evolutions/README.md | 2 +- .../FixtureTestingAndContinuousIntegration.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 16 ++++++++++++++++ Documentations/Internal/TuistDevelopment.md | 2 +- Documentations/README.md | 2 +- 7 files changed, 31 insertions(+), 13 deletions(-) diff --git a/Documentations/Evolutions/0103-cross-reference-test-scan-load.html b/Documentations/Evolutions/0103-cross-reference-test-scan-load.html index f6a1ce5c..72e654cc 100644 --- a/Documentations/Evolutions/0103-cross-reference-test-scan-load.html +++ b/Documentations/Evolutions/0103-cross-reference-test-scan-load.html @@ -4,7 +4,7 @@ -Draft - 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 +0103 - 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

    +
    +
    状态
    Accepted
    +
    最后更新
    2026-11-23
    +
    项目类型
    库(跨仓库唯一提案)
    +
    原文
    draft-swift-type-indexing-package.md
    +
    +
    + + + +
    + +
    +

    摘要

    +

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

    +

    搬家同时修两处错误:

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

    之后三方接入:

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

    要你定

    +
    +

    批准这份提案

    +
      +
    1. 批准后状态改为 Accepted,从第 0 步开始实现。
    2. +
    +
    +
    +

    agent 自己定的(可以推翻)

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

    架构图

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

    模块依赖:改了什么

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

    箭头从使用方指向依赖。RuntimeViewerCore 还直接依赖 ObjCTypeIndexing 与 TypeIndexing(建 TypeDatabase、取 ObjC 标注),图里省略;三个新依赖都只在 macOS 上。红色虚线是删掉的旧依赖:MachOSwiftSection 的 TypeIndexing 直接调用 ObjCIndexing。

    + +

    新包内部

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

    RuntimeViewer 的建立与刷新

    +
    + + engine connectsservice process + RuntimeTypeIndexprepare(platform) + TypeDatabaseindex(dependencies:) + RuntimeSwiftSectionresolver, clear cache + RuntimeDataChange.typeNamesResolved + ContentTextViewModelrefetch: UIKit.__X + + + + + + + unavailableReport: the reason + TypeIndex/ cache~/Library/Caches/… + + + + UI requestwaitsForTypeIndex = false + prints now__C.X until ready + MCP / CLI / export / FindwaitsForTypeIndex = true + awaits ready | unavailablethen prints + + + +
    +

    上面一行是索引建立:engine 连上后在服务进程里后台建,建好后打印器注册解析器、清掉旧缓存,再通知 App 重新取。下面一行是两类请求:界面不等,非交互的调用方等。

    +
    + +
    +

    改动地图

    +

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

    + +
    + swift-type-indexing(新仓库) +
    +
    + + + + + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    Package.swift新增product / target TypeIndexing 与测试 target;依赖 SourceKitD、swift-apinotes、FrameworkToolbox(均限 macOS);平台与 MachOSwiftSection 一致;打开三项 upcoming feature独立成包;平台声明不能高于 MachOObjCSection1
    InterfaceDeclarationNode、InterfaceTypeNameExtractor、ModuleIndexCache、ModuleInterfaceIndexer、SDKIndexer、SDKPlatform、SourceKitManager、Subprocess、SupplementaryAPINotes移入原样搬入;package 改 public(只公开需要的);日志子系统改名搬家1
    APINotesIndex移入 修改用 ImportedTypeNameCategory;改名规则修正;新增 ObjC 容器条目修正改名;给 ObjC 标注提供数据1–3
    TypeDatabase移入 修改去泛型;收 [any DeclaredTypeNameSource];构造器加 cacheDirectory:;新增 swiftImportAnnotations(…)去掉对 MachOObjCSection 的依赖;缓存位置由调用方决定1–3
    DeclaredTypeNameSource新增imagePath、declaredTypeNames()取代直接调用 ObjCInterfaceIndexer1
    ImportedTypeNameCategory新增四个 case取代 SwiftPrinting 的 CImportedTypeNameCategory1
    SourceKitLocator新增先试 Xcode 工具链,再试 <developer dir>/usr/lib/sourcekitd.framework支持 Command Line Tools2
    TypeIndexingAvailability新增SDK 路径、sourcekitd 路径、不可用原因调用方决定开不开、界面说明原因2
    SwiftImportAnnotation、ObjCContainerSwiftImportAnnotations、ObjCMemberKey新增API notes 的命名标注给 MachOObjCSection 用3
    Tests/TypeIndexingTests/*移入 修改7 个文件搬入;改用假的 DeclaredTypeNameSource;不改名的旧测试按新规则改写搬家;规则修正1–2
    四个新测试文件新增改名规则、sourcekitd 定位、缓存目录、ObjC 标注查询回归测试2–3
    README、LICENSE、AGENTS.md、文档目录、CI新增TypeIndexingPipeline.md 从 MachOSwiftSection 移入并更新新仓库的文档1、3
    +
    +
    +
    + +
    + MachOObjCSection +
    +
    + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    Package.swift修改本地候选 + 远端依赖 swift-type-indexing;新 target / product ObjCTypeIndexing 与测试 target只有新 target 依赖新包4
    ObjCDeclaredTypeNames<MachO>新增实现 DeclaredTypeNameSource,包一层 ObjCInterfaceIndexer取代 MachOSwiftSection 里那段直接调用4
    ObjCSwiftImportNotes+TypeDatabase.swift新增init(apiNotesForClassNamed:in:)、init(apiNotesForProtocolNamed:in:)API notes → 标注5
    ObjCSwiftImportNotes、Note修改swiftName、declarationNote、merging(_:);渲染 NS_SWIFT_NAME标 Swift 命名5
    ObjCClassInfo / ObjCProtocolInfo / ObjCCategoryInfo修改声明行之前打印类型一级的宏行;category 成员读标注类型一级宏5
    ObjCInterfaceBuilder 协议与 category 入口修改加 swiftImportNotes: 参数(默认空)协议与 category 也能标5
    测试新增 修改SwiftImportNotesRenderingTests 加用例;新 ObjCTypeIndexingTests回归4–5
    README、命令行指南、术语表、提案索引修改新 target、新标注、cross-repository 行文档同批4–5
    +
    +
    +
    + +
    + MachOSwiftSection(持有本提案) +
    +
    + + + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    Package.swift修改删 TypeIndexing target、product、测试 target 与 SourceKitD / swift-apinotes;加 swift-type-indexing 与 SwiftTypeNameResolution搬家后的接线6
    Sources/Declaration/TypeIndexing/(11 个文件)删除已移入新包搬家6
    TypeDatabaseTypeNameResolver新增把 TypeDatabase 适配成打印器的两个角色协议,映射分类枚举唯一的适配点,RuntimeViewer 也用它6
    SwiftInterfaceBuilderTypeNameProvider移动 修改移进 SwiftTypeNameResolution,改为建立在适配器之上名字不变,CLI 调用方不动6
    InterfaceRequest.swift修改改 import接线6
    ObjCInterfaceCommand.swift 与 SwiftSectionKit/ObjC修改新开关 --mark-sdk-swift-names;找不到 SDK 时警告并照常输出swift-section objc 的同类开关7
    Tests/TypeIndexingTests/删除已移入新包搬家6
    集成测试、命令映射测试、新的适配器测试修改 新增import 改名;新开关的映射;分类映射与打印回归6–7
    README、文档索引、补充映射指南、内部文档、术语表、SwiftSectionKit、ObjC 命令行文档、AGENTS.md、swift-section 插件 skill 与版本修改指向新包、新 target、新开关文档同批6–7
    Documentations/Evolutions/README.md修改登记本提案索引0
    +
    +
    +
    + +
    + RuntimeViewer +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    RuntimeViewerCore/Package.swift修改加 swift-type-indexing;Core 加三个 product(限 macOS)接线8
    Local workspace、.worktrees 链接、LocalDependencies.md修改加 ../swift-type-indexing本地联调8
    Tuist.swift、TuistScript.sh修改换掉 "TypeIndexing",加两个新 target 与新包Tuist 描述同批8
    AGENTS.md「Dependency floors」修改新包的版本下限与理由规则8
    TypeNames/RuntimeTypeIndex新增每进程一个;每平台一个 TypeDatabase;后台预建;状态;解析器进程级共享索引9
    TypeNames/RuntimeTypeIndexLocation新增往上找 .app 定缓存目录;不在 App 里用 runtime-viewer-cli 自己的目录所有进程共用缓存9
    TypeNames/RuntimeTypeIndexStatus、TypeIndexStatusCommand新增线上状态类型;Core 自有命令,路由为「问服务进程本身」Report 与工具栏9
    RuntimeDataChange修改新 case typeNamesResolved(platform:)通知 App 刷新9
    RuntimeSwiftSection修改两个打印器都注册解析器;每次按开关重建解析器列表;就绪时清缓存打印解析后的名字9
    RuntimeObjCSection、RuntimeEngine、RuntimeEngine+Search修改类、协议、category 都合并 API notes 标注ObjC 标注9
    SwiftGenerationOptions、GenerationOptions修改resolvesImportedTypeNames、marksSwiftNamesFromAPINotes(默认开)、waitsForTypeIndex(默认关)开关;非交互调用方等索引9
    语料 variant 与内存比较修改带上是否解析与 SDK 版本;构建前等索引语料与显示一致9
    四个服务入口与命令行 host修改配置缓存位置每个打印的进程9
    TypeIndexCoordinator、RuntimeEngineBackgroundWork新增 修改状态、进行中、App Nap、关闭Report 与后台工作10
    Report 三个文件、工具栏活动两个文件修改新类别「Imported Type Names」与活动文案可见10
    ContentTextViewModel、ViewModel修改收到 .typeNamesResolved 时重新取自动刷新10
    GenerationOptionsViewController修改两个默认勾选的开关开关10
    RuntimeDerivedDataController、RuntimeDerivedDataMaintenance修改量与删都包括 TypeIndex 目录Delete Derived Data 一起删10
    MCP、命令行执行器、导出修改置 waitsForTypeIndex = true输出稳定11
    runtime-viewer 插件 skill 与两个清单修改说明输出变化;1.3.0 → 1.4.0插件规则11
    DerivedData.md、CommandLineInterface.md、两份索引修改新缓存目录、输出变化、cross-repository 行文档同批8、11
    +
    +
    +
    +
    + +
    +

    详细设计

    + +
    + 新包的公开 API +
    +
    public protocol DeclaredTypeNameSource: Sendable {
    +    var imagePath: String { get }
    +    func declaredTypeNames() async throws -> [String]
    +}
    +
    +public enum ImportedTypeNameCategory: Sendable, Hashable {
    +    case objcClass, objcProtocol, valueType, other
    +}
    +
    +public struct TypeIndexingAvailability: Sendable, Hashable {
    +    public var sdkPath: String?
    +    public var sourceKitPath: String?        // nil: module interfaces skipped
    +    public var unavailabilityReason: UnavailabilityReason?
    +    public static func availability(for platform: SDKPlatform) -> TypeIndexingAvailability
    +}
    +
    +public struct SwiftImportAnnotation: Sendable, Hashable {
    +    public var swiftName: String?
    +    public var isSwiftPrivate: Bool
    +}
    +
    +public enum ObjCMemberKey: Sendable, Hashable {
    +    case method(selector: String, isClassMethod: Bool)
    +    case property(name: String, isClassProperty: Bool)
    +}
    +
    +public struct ObjCContainerSwiftImportAnnotations: Sendable, Hashable {
    +    public var declaration: SwiftImportAnnotation?
    +    public var members: [ObjCMemberKey: SwiftImportAnnotation]
    +}
    +
    +@available(macOS 13.0, *)
    +public actor TypeDatabase {
    +    public init(platform: SDKPlatform, cacheDirectory: URL? = nil, supplementaryAPINotesURLs: [URL] = [])
    +    public func index(dependencies: [any DeclaredTypeNameSource], moduleFilter: @Sendable (String) -> Bool) async throws
    +    public func moduleName(forTypeName typeName: String) async -> String?
    +    public func swiftName(forCName cName: String, category: ImportedTypeNameCategory) -> String?
    +    public func swiftImportAnnotations(forObjCClassNamed className: String) -> ObjCContainerSwiftImportAnnotations?
    +    public func swiftImportAnnotations(forObjCProtocolNamed protocolName: String) -> ObjCContainerSwiftImportAnnotations?
    +    public static func moduleName(forImagePath imagePath: String) -> String
    +}
    +

    所有源码仍包在 #if os(macOS) 里。协议按「是什么」命名,沿用组织里 ObjCMetadataSource 的 Source 后缀;不给 MachOKit 的类型补遵循新包的协议,由 MachOObjCSection 的包装类型实现。

    +
    +
    + +
    + 改名规则 +
    +
    let swiftName: String? = if let explicitSwiftName = entity.swiftName {
    +    explicitSwiftName                         // swift_name wins, no "__"
    +} else if entity.isSwiftPrivate == true {
    +    "__" + cName                              // swift_private alone
    +} else {
    +    nil
    +}
    +

    依据是 Clang importer:有 swift_name 时直接用它并提前返回,只有没有它时才在 swift_private 的声明前加 __。ObjC 成员按同样两条规则记录,但只保存原始的 swiftName / isSwiftPrivate,因为成员一级要打印的是宏。

    +
    +
    + +
    + 缓存目录 +
    +

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

    +
    +
    + +
    + MachOObjCSection:Swift 命名标注 +
    +
    public struct ObjCDeclaredTypeNames<MachO: ObjCMetadataSource & Sendable>: DeclaredTypeNameSource {
    +    public init(machO: MachO, imagePath: String)
    +}
    +
    +extension ObjCSwiftImportNotes {
    +    public init(apiNotesForClassNamed className: String, in typeDatabase: TypeDatabase) async
    +    public init(apiNotesForProtocolNamed protocolName: String, in typeDatabase: TypeDatabase) async
    +    public var declarationNote: Note?                 // the type itself
    +    public func merging(_ other: ObjCSwiftImportNotes) -> ObjCSwiftImportNotes
    +}
    +// Note gains `swiftName: String?`
    +

    打印效果:

    +
    NS_REFINED_FOR_SWIFT
    +@interface UICellConfigurationState : UIViewConfigurationState
    +@property (nonatomic, getter=isEditing) BOOL editing;
    +@end
    +
    +NS_SWIFT_NAME(PKDrawingReference)
    +@interface PKDrawing : NSObject <NSCopying, NSSecureCoding>
    +@end
    +

    类型一级的宏单独一行,放在 @interface / @protocol 上面(与演进视图打印可用性宏的写法相同);成员一级放在 ; 前,NS_SWIFT_NAME(...) 在 NS_REFINED_FOR_SWIFT 前。

    +
    +
    + +
    + MachOSwiftSection:适配层与命令行 +
    +
    @available(macOS 13.0, *)
    +public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameResolving {
    +    public init(typeDatabase: TypeDatabase)
    +}
    +
      +
    • SwiftInterfaceBuilderTypeNameProvider 保留名字与构造器签名,内部改用这个适配器和 ObjCDeclaredTypeNames。
    • +
    • swift-section objc interface --mark-sdk-swift-names:按镜像平台建只读 API notes 的 TypeDatabase(不碰 sourcekitd),为每个类与协议取标注;找不到 SDK 时打印 warning,输出与不加开关时相同。
    • +
    +
    +
    + +
    + RuntimeViewer +
    +
      +
    • 进程内的索引:RuntimeTypeIndex 每个服务进程一个,每个 SDKPlatform 一个 TypeDatabase。平台按镜像来源取:共享缓存镜像、文件、LC_BUILD_VERSION。Mac Catalyst 用 macOS SDK(读 iOSSupport 里的 API notes,落地时实测确认)。
    • +
    • 预建:engine 连上与加载新镜像时,把依赖模块并进过滤条件,同一平台在建时合并请求。不可用时状态记原因,打印器不注册解析器。
    • +
    • 打印:每次按当前选项重建完整的解析器列表(opaque + 类型名),不再被 removeAllTypeNameResolvers() 误删;显示与语料两个打印器都这样做。就绪时清 section 的接口缓存,再广播 .typeNamesResolved。
    • +
    • 等待:waitsForTypeIndex 为真时,打印前等该平台索引就绪或不可用。MCP、命令行、导出置真,Find 语料构建一律等待;只在磁盘缓存冷的第一次会等。
    • +
    • 兼容性:三个新选项都用 @Default;新 case 只由新版 Mac 服务发出;旧对端不回应状态命令时当作不可用。
    • +
    • 语料 variant:…-ByCategory-TypeNames<platform>-<SDK 版本-build> 或 …-UnresolvedTypeNames。
    • +
    • 界面:Generation Options 的 Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,默认勾选;Report 新类别「Imported Type Names」,每个平台一行显示建立中、就绪(缓存大小)或不可用(原因)。
    • +
    • 内存:每个打印的服务进程各一份,落地时量一次 malloc 在用量写回提案。
    • +
    +
    +
    +
    + +
    +

    调研

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

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

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

    替代方案

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

    影响

    +
    +

    源码兼容性:MachOSwiftSection 有破坏

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

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

    +

    RuntimeViewer 用户能看到的变化

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

    版本

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

    落地步骤

    +
      +
    1. 提案入库:登记草案;批准后在另外两个仓库的索引加 cross-repository 行。
    2. +
    3. 建新包并原样搬入:existingTypeIndexingTestsPassAgainstNonGenericDatabase、declaredTypeNameSourcesAreQueriedLazilyInDependencyOrder、firstImageDeclaringANameWinsTheAttribution、failingSourceIsDroppedAndNotRetried
    4. +
    5. 改名规则与 Command Line Tools(先写测试并确认修复前失败):swiftPrivateWithoutSwiftNameResolvesToDoubleUnderscorePrefix、swiftNameWinsOverSwiftPrivate、plainEntityKeepsItsCName、sourceKitIsFoundInCommandLineToolsLayout、sourceKitIsFoundInXcodeToolchainLayout、missingSourceKitSkipsModuleInterfacesButKeepsAPINotes、availabilityReportsMissingSDK、cacheEntriesAreWrittenUnderTheGivenDirectory
    6. +
    7. ObjC 容器的 API notes 查询,之后新包打 0.1.0 并推送:classAnnotationCarriesSwiftNameAndSwiftPrivate、methodAnnotationIsKeyedBySelectorAndKind、propertyAnnotationIsKeyedByNameAndKind、protocolAnnotationsAreSeparateFromClassAnnotations
    8. +
    9. MachOObjCSection 接入新包:declaredTypeNamesListFoundationClassesProtocolsAndStructs、typeDatabaseAttributesPrivateClassThroughObjCDeclaredTypeNames
    10. +
    11. ObjC 头文件的 Swift 命名标注:memberSwiftNamePrintsBeforeRefinedForSwift、classDeclarationNotePrintsOnItsOwnLineAboveInterface、protocolInterfaceTakesNotes、categoryMembersTakeNotes、mergingKeepsBothSourcesAndTheArgumentWinsPerField、apiNotesForClassBecomeNotes、markedRenderingStillProjectsToPlainRendering
    12. +
    13. MachOSwiftSection 切换到新包:resolverMapsEveryPrinterCategory、resolverPrintsResolvedModuleAndSwiftName、resolveCModuleNamesFlagStillMapsToRequest;手动端到端核对 UIKit.__UICellConfigurationState 与 PencilKit.PKDrawingReference
    14. +
    15. swift-section objc --mark-sdk-swift-names:markSDKSwiftNamesFlagMapsToRequest、missingSDKWarnsAndPrintsUnmarkedOutput;手动核对 NS_SWIFT_NAME(PKDrawingReference)
    16. +
    17. RuntimeViewer 依赖接线:./TuistScript.sh check 通过,Debug workspace 能编过
    18. +
    19. RuntimeViewer Core(实测 Catalyst 的 API notes 来源,量各服务进程的内存):typeIndexBuildsOncePerPlatformAndMergesConcurrentRequests、unavailableSDKLeavesImportedNamesUnresolved、resolverSurvivesOpaqueTypeSwitchOff、readyIndexClearsSectionInterfaceCaches、readyIndexBroadcastsTypeNamesResolved、waitingRequestPrintsResolvedNamesOnColdIndex、nonWaitingRequestPrintsImportedPlaceholderOnColdIndex、switchOffPrintsImportedPlaceholder、objcHeaderMergesAPINotesWithRefinedMembers、corpusVariantNamesTypeNameResolution、typeIndexStatusCommandRoutesToServingProcess、olderPeerDecodesOptionsWithDefaults、cacheLocationWalksUpToEnclosingApp
    20. +
    21. RuntimeViewer App:typeIndexCoordinatorReportsBuildingReadyAndUnavailable、reportListsImportedTypeNamesPerPlatform、contentRefetchesOnTypeNamesResolved、deleteDerivedDataRemovesTypeIndexDirectory、derivedDataSizeIncludesTypeIndexDirectory
    22. +
    23. MCP、命令行、导出与插件:mcpOptionsWaitForTypeIndex、commandLineOptionsWaitForTypeIndex、exportConfigurationWaitsForTypeIndex
    24. +
    +

    收尾时判断:新包的 TypeIndexingPipeline.md 承担实现说明,RuntimeViewer 的 DerivedData.md 加一节;预计新术语「类型索引」「Swift 命名标注」进各仓库的术语表。

    +
    + +
    +

    决策日志

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

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-23
    项目类型
    库(跨仓库唯一提案)
    原文
    draft-swift-type-indexing-package.md
    diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.md b/Documentations/Evolutions/draft-swift-type-indexing-package.md index 873e5b21..d5f4650b 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.md +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.md @@ -1,12 +1,12 @@ # Draft - 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-23 - **最后更新**: 2026-11-23 - **所属愿景**: 无 - **关联提案**: [0009 TypeIndexing 重启](0009-type-indexing-revival.md)、[0010 补充类型映射](0010-community-type-mapping-bundles.md)、[0096 Swift 优先的导入声明](0096-swift-first-imported-declarations.md)(`ObjCSwiftImportNotes` 的来历) -- **跨仓库范围**: 新仓库 `MxIris-Reverse-Engineering/swift-type-indexing`、MachOObjCSection、MachOSwiftSection(本仓库,持有这份唯一的提案)、RuntimeViewer。另外三个仓库的提案索引各加一行「cross-repository」链接指回这里 +- **跨仓库范围**: 新仓库 `MxIris-Reverse-Engineering/swift-type-indexing`、swift-apinotes fork(`MxIris-DeveloperTool-Forks/swift-apinotes`,实现中加入,见决策日志)、MachOObjCSection、MachOSwiftSection(本仓库,持有这份唯一的提案)、RuntimeViewer。另外三个仓库的提案索引各加一行「cross-repository」链接指回这里 - **实现分支 / PR**: 新仓库 `swift-type-indexing` 的 `main`;MachOObjCSection、MachOSwiftSection、RuntimeViewer 各自的 `feature/swift-type-indexing-package`(各从 `next` 切) - **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 - **网页版**: 同目录同名的 `.html` @@ -124,20 +124,29 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | |---|---|---|---|---| -| `Package.swift` | 新增 | 包名 `swift-type-indexing`,product / target `TypeIndexing`,测试 target `TypeIndexingTests`;依赖 SourceKitD、swift-apinotes、FrameworkToolbox(均 `.when(platforms: [.macOS])`);平台与本仓库一致(macOS 10.15 / iOS 13 / tvOS 13 / watchOS 6 / visionOS 1);打开 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` | 独立成包;平台声明不能高于 MachOObjCSection,否则 SwiftPM 拒绝解析 | 1 | +| `Package.swift` | 新增 | 包名 `swift-type-indexing`,product / target `TypeIndexing`,测试 target `TypeIndexingTests`;依赖 SourceKitD、swift-apinotes(`from: "0.3.0"`,本地候选 `../../../Fork/Library/swift-apinotes`)、FrameworkToolbox(后两者均 `.when(platforms: [.macOS])`);平台与本仓库一致(macOS 10.15 / iOS 13 / tvOS 13 / watchOS 6 / visionOS 1);打开 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` | 独立成包;平台声明不能高于 MachOObjCSection,否则 SwiftPM 拒绝解析 | 1 | | `Sources/TypeIndexing/{InterfaceDeclarationNode,InterfaceTypeNameExtractor,ModuleIndexCache,ModuleInterfaceIndexer,SDKIndexer,SDKPlatform,SourceKitManager,Subprocess,SupplementaryAPINotes}.swift` | 移入 | 从本仓库原样搬入;`package` 改 `public`(只公开调用方需要的,其余 `internal`);`@Loggable` 子系统改为 `com.mxiris.type-indexing` | 搬家 | 1 | | `Sources/TypeIndexing/APINotesIndex.swift` · `APINotesIndex` | 移入 + 修改 | 用 `ImportedTypeNameCategory`;改名规则:有 `SwiftName` 用它(不论 `SwiftPrivate`),只有 `SwiftPrivate` 时 `"__" + cName`;`cNamesBySwiftName` 同步登记;新增 ObjC 容器的方法、属性条目索引 | 修正改名;给 ObjC 标注提供数据 | 1、2、3 | -| `Sources/TypeIndexing/TypeDatabase.swift` · `TypeDatabase` | 移入 + 修改 | 去泛型;`index(dependencies:moduleFilter:)` 改收 `[any DeclaredTypeNameSource]`;`moduleName(forImagePath:)` 保持纯函数;构造器加 `cacheDirectory:`;新增 `swiftImportAnnotations(forObjCClassNamed:)` / `forObjCProtocolNamed:` | 去掉对 MachOObjCSection 的依赖;缓存位置由调用方决定;给 ObjC 标注用 | 1、2、3 | +| `Sources/TypeIndexing/TypeDatabase.swift` · `TypeDatabase` | 移入 + 修改 | 去泛型;`index(dependencies:moduleFilter:)` 改收 `[any DeclaredTypeNameSource]`,可多次调用(第一次发现 SDK、登记 API notes,之后只补新模块与新依赖);API notes、模块接口、运行时元数据三张表在查询时按优先级查,不再靠写入顺序覆盖;`moduleName(forImagePath:)` 保持纯函数;构造器加 `cacheDirectory:`;没有 sourcekitd 时只读缓存;新增 `swiftImportAnnotations(forObjCClassNamed:)` / `forObjCProtocolNamed:` | 去掉对 MachOObjCSection 的依赖;RuntimeViewer 加载新镜像时要追加模块;缓存位置由调用方决定;给 ObjC 标注用 | 1、2、3 | | `Sources/TypeIndexing/DeclaredTypeNameSource.swift` · `DeclaredTypeNameSource` | 新增 | 协议:`imagePath`、`declaredTypeNames() async throws -> [String]` | 取代直接调用 `ObjCInterfaceIndexer` | 1 | | `Sources/TypeIndexing/ImportedTypeNameCategory.swift` · `ImportedTypeNameCategory` | 新增 | `objcClass` / `objcProtocol` / `valueType` / `other` | 取代 SwiftPrinting 的 `CImportedTypeNameCategory` | 1 | | `Sources/TypeIndexing/SourceKitLocator.swift` · `SourceKitLocator` | 新增 | 依次试 `/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/sourcekitd` 与 `/usr/lib/sourcekitd.framework/sourcekitd`;`SourceKitManager` 改用它 | 支持 Command Line Tools | 2 | -| `Sources/TypeIndexing/TypeIndexingAvailability.swift` · `TypeIndexingAvailability` | 新增 | `static func availability(for: SDKPlatform) -> TypeIndexingAvailability`:SDK 路径、sourcekitd 路径、不可用原因 | 调用方决定开不开、在界面上说明原因 | 2 | +| `Sources/TypeIndexing/TypeIndexingAvailability.swift` · `TypeIndexingAvailability` | 新增 | `static func availability(for: SDKPlatform) -> TypeIndexingAvailability`:`sdkSettings`(含 SDK 路径与版本,供 RuntimeViewer 的语料 variant 用)、sourcekitd 路径、不可用原因 | 调用方决定开不开、在界面上说明原因 | 2 | +| `Sources/TypeIndexing/SDKPlatform.swift` · `SDKPlatform.macCatalyst`、`SDKSettings.macCatalystVersion`、`compilerArguments(for:)` | 修改 | 新 case `macCatalyst`:读 macOS SDK(`xcrunSDKName`),target `ios-macabi`,给 sourcekitd 显式补 `-Fsystem …/System/iOSSupport/System/Library/Frameworks`;`SDKIndexer` 的 Catalyst 搜索路径先 `System/iOSSupport/…` 再 macOS 的;缓存目录与 macOS 分开 | Mac Catalyst 的 UIKit 与其 API notes 只在 `iOSSupport` 里,原来按 `.macOS` 索引找不到 | 2、3 | | `Sources/TypeIndexing/SwiftImportAnnotation.swift` · `SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`ObjCMemberKey` | 新增 | 单个声明与一个类 / 协议的 API notes 命名标注 | 给 MachOObjCSection 用 | 3 | | `Tests/TypeIndexingTests/*` | 移入 + 修改 | 本仓库 `Tests/TypeIndexingTests/` 的 7 个文件搬入;`TypeDatabase` 改为用假的 `DeclaredTypeNameSource`;`swiftPrivateEntitiesAreAttributedButNotRenamed` 改写为新规则 | 搬家;规则修正 | 1、2 | -| `Tests/TypeIndexingTests/{SwiftNameRuleTests,SourceKitLocatorTests,CacheDirectoryTests,ObjCSwiftImportAnnotationTests}.swift` | 新增 | 见各步骤的行为清单 | 回归测试 | 2、3 | +| `Tests/TypeIndexingTests/{DeclaredTypeNameSourceTests,SwiftNameRuleTests,SourceKitLocatorTests,TypeIndexingAvailabilityTests,CacheDirectoryTests,MacCatalystPlatformTests,ObjCSwiftImportAnnotationTests}.swift` | 新增 | 见各步骤的行为清单 | 回归测试 | 1、2、3 | +| `Tests/TypeIndexingTests/SDKIntegrationTests.swift` | 新增 | 对本机真实 SDK 的核对,默认关闭:`TYPE_INDEXING_SDK_TESTS=1`(只读 API notes,约 2 秒),再加 `TYPE_INDEXING_SOURCEKIT_TESTS=1` 经 sourcekitd 冷生成 Catalyst 的 UIKit 接口(实测 126 秒) | 单测覆盖不到 SDK 布局与 sourcekitd 参数 | 2、3 | | `README.md`、`LICENSE`、`AGENTS.md` + `CLAUDE.md`(符号链接)、`Documentations/README.md`、`Documentations/Evolutions/README.md`(项目类型:库)、`Documentations/Internal/TypeIndexingPipeline.md`(从本仓库移入并更新) | 新增 / 移入 | 用法、三层数据源、改名规则、缓存布局、可用性 | 新仓库的文档 | 1、3 | | `.github/workflows/macOS.yml` | 新增 | 照本仓库 `macOS.yml` 配 macOS 构建与测试 | CI | 1 | +### swift-apinotes(fork,实现中加入) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/APINotes/TopLevelItems/ObjCContext.swift` · `ObjCContext.methods` / `properties` | 修改 | 标 `public`;打 tag `0.3.0` | 0.2.0 里是 internal,包外读不到类与协议的成员,ObjC 成员的标注没有来源 | 3 | +| `Tests/APINotesTests/ObjCContextMemberAccessTests.swift` | 新增 | 不带 `@testable` 读成员(修复前编译失败) | 回归 | 3 | + ### MachOObjCSection | 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | @@ -302,16 +311,23 @@ public struct TypeIndexingAvailability: Sendable, Hashable { case noDeveloperDirectory case sdkNotInstalled(SDKPlatform) } - public var sdkPath: String? + public let sdkSettings: SDKSettings? // path, version, build, Mac Catalyst version /// `nil` when the developer directory has no sourcekitd: API notes and /// runtime metadata still resolve names, module interfaces are skipped. - public var sourceKitPath: String? - public var unavailabilityReason: UnavailabilityReason? + public let sourceKitPath: String? + public let unavailabilityReason: UnavailabilityReason? public var isAvailable: Bool { unavailabilityReason == nil } public static func availability(for platform: SDKPlatform) -> TypeIndexingAvailability } +public enum SDKPlatform: String, CaseIterable, Hashable, Codable, Sendable { + case macOS = "macosx" + case macCatalyst = "maccatalyst" // the macOS SDK read through System/iOSSupport + case iOS = "iphoneos" + // tvOS, watchOS, visionOS, driverKit and the simulators, as before +} + /// What an API notes file says about how Swift imports one declaration. public struct SwiftImportAnnotation: Sendable, Hashable { /// `SwiftName:`; when present, it is the Swift name as is. @@ -355,7 +371,8 @@ public actor TypeDatabase { #endif ``` -- `SDKPlatform` 原样公开(它已经是 `String` raw value 的 enum)。 +- `SDKPlatform` 公开,并新增 `macCatalyst`(落地时发现,见决策日志);`SDKSettings`(`sdkPath`、`version`、`productBuildVersion`、`macCatalystVersion`、`cacheDirectoryComponent`)与 `APINotesFile(path:)` 一并公开——后者是 `swift-section` 预检 `--supplementary-apinotes` 路径用的。 +- `index(dependencies:moduleFilter:)` 可多次调用:第一次发现 SDK 并登记 API notes,之后只补新的模块与依赖镜像;因此 API notes 优先于模块接口改为查询时决定(三张表),不再靠写入顺序。 - 搬家时保留的三个 `register(...)` 测试钩子(提案 0009「与提案的差异」一节)降为 `internal`,测试用 `@testable import`。 - 命名照 `apple-style-api-design`:协议按「是什么」命名并沿用组织里 `ObjCMetadataSource` 的 `Source` 后缀;查询读成名词短语(`moduleName(forTypeName:)`);不给 MachOKit 的类型补遵循新包的协议(由 MachOObjCSection 的包装类型实现)。 @@ -445,7 +462,7 @@ public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameRe #endif ``` -`SwiftInterfaceBuilderTypeNameProvider` 保留公开名字与构造器签名,内部改为:按镜像平台建 `TypeDatabase`,依赖镜像包成 `ObjCDeclaredTypeNames`,把查询转给一个 `TypeDatabaseTypeNameResolver`。 +`SwiftInterfaceBuilderTypeNameProvider` 保留公开名字与构造器签名,内部改为:按镜像平台建 `TypeDatabase`(`LC_BUILD_VERSION` 的 macCatalyst 映射到 `.macCatalyst`,原来映射到 `.macOS`,Catalyst 镜像因此读不到 UIKit 的 API notes),依赖镜像包成 `ObjCDeclaredTypeNames`,把查询转给一个 `TypeDatabaseTypeNameResolver`。 `swift-section objc interface --mark-sdk-swift-names`:按镜像 `LC_BUILD_VERSION` 的平台建 `TypeDatabase`(只读 API notes,`moduleFilter` 返回 `false`,所以不碰 sourcekitd),对每个类与协议取 `ObjCSwiftImportNotes(apiNotesFor…:in:)` 传给 `ObjCInterfaceBuilder`。找不到 SDK 时打印一条 warning,输出与不加开关时相同。 @@ -453,7 +470,7 @@ public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameRe **进程内的索引**。`RuntimeTypeIndex` 是每个服务进程一个的 actor(经 `@Dependency` 取得,`fileprivate static let shared`),按 `SDKPlatform` 各持一个 `TypeDatabase`: -- 平台:共享缓存镜像用 `RuntimeSharedCachePartition.platform(ofImageAt:)`(macOS → `.macOS`,Mac Catalyst → `.macOS`,与 `SwiftInterfaceBuilderTypeNameProvider` 的映射一致,API notes 读 SDK 的 `iOSSupport`——落地时实测确认,见步骤 9);文件用 `RuntimeFile.platform`;其余镜像读 `LC_BUILD_VERSION`。 +- 平台:共享缓存镜像用 `RuntimeSharedCachePartition.platform(ofImageAt:)`(macOS → `.macOS`,Mac Catalyst → `.macCatalyst`);文件用 `RuntimeFile.platform`;其余镜像读 `LC_BUILD_VERSION`(`macCatalyst` 平台号映射到 `.macCatalyst`)。 - 预建:engine 连上后、以及新加载的镜像,把它们的依赖模块名并进 `moduleFilter`,依赖镜像包成 `ObjCDeclaredTypeNames` 交给 `index(dependencies:moduleFilter:)`。同一平台已在建时合并请求,不重复建。 - 不可用:`TypeIndexingAvailability` 不可用时状态记为 `.unavailable(reason)`,打印器不注册解析器,输出保持 `__C.`。 - 内存:每个打印的服务进程各有一份(本机、Catalyst、每个文件、每个框架实例),落地时量一次 `malloc` 在用量写进提案(步骤 9)。 @@ -526,12 +543,12 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` 0. **提案入库**——本仓库 `Documentations/Evolutions/README.md` 登记草案;批准后、开工前,在 MachOObjCSection 与 RuntimeViewer 的提案索引各加一行 cross-repository 链接。 - 行为:无代码。 -1. **建新包并原样搬入**——swift-type-indexing 改动地图的 Package.swift、移入的源码与测试、`DeclaredTypeNameSource`、`ImportedTypeNameCategory`、README / LICENSE / AGENTS.md / CI。 +1. ✅ **建新包并原样搬入**(2026-11-23 完成)——swift-type-indexing 改动地图的 Package.swift、移入的源码与测试、`DeclaredTypeNameSource`、`ImportedTypeNameCategory`、README / LICENSE / AGENTS.md / CI。 - 行为:`existingTypeIndexingTestsPassAgainstNonGenericDatabase` - 行为:`declaredTypeNameSourcesAreQueriedLazilyInDependencyOrder` - 行为:`firstImageDeclaringANameWinsTheAttribution` - 行为:`failingSourceIsDroppedAndNotRetried` -2. **改名规则与 Command Line Tools**——`APINotesIndex` 改名规则、`SourceKitLocator`、`TypeIndexingAvailability`、缓存目录注入。先写测试并确认修复前失败。 +2. ✅ **改名规则、Command Line Tools 与 Mac Catalyst**(2026-11-23 完成)——`APINotesIndex` 改名规则、`SourceKitLocator`、`TypeIndexingAvailability`、缓存目录注入。先写测试并确认修复前失败。 - 行为:`swiftPrivateWithoutSwiftNameResolvesToDoubleUnderscorePrefix` - 行为:`swiftNameWinsOverSwiftPrivate` - 行为:`plainEntityKeepsItsCName` @@ -540,11 +557,14 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` - 行为:`missingSourceKitSkipsModuleInterfacesButKeepsAPINotes` - 行为:`availabilityReportsMissingSDK` - 行为:`cacheEntriesAreWrittenUnderTheGivenDirectory` -3. **ObjC 容器的 API notes 查询**——`SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`TypeDatabase.swiftImportAnnotations(…)`。 + - 行为:`macCatalystSearchesIOSSupportFirst`、`macCatalystTargetTripleIsMacABI`、`macCatalystInterfaceGenerationSeesIOSSupportFrameworks`、`macCatalystCachesApartFromMacOS` + - 实测(`SDKIntegrationTests`):Catalyst 下 `UICellConfigurationState` → `UIKit` / `__UICellConfigurationState`;macOS 下 `PKDrawing` → `PencilKit` / `PKDrawingReference`;sourcekitd 冷生成 Catalyst 的 UIKit 接口后 `UIStackView` → `UIKit` +3. ✅ **ObjC 容器的 API notes 查询**(2026-11-23 在本机完成;fork 的 0.3.0 与新包的推送待用户批准公开仓库)——`SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`TypeDatabase.swiftImportAnnotations(…)`。 - 行为:`classAnnotationCarriesSwiftNameAndSwiftPrivate` - 行为:`methodAnnotationIsKeyedBySelectorAndKind` - 行为:`propertyAnnotationIsKeyedByNameAndKind` - 行为:`protocolAnnotationsAreSeparateFromClassAnnotations` + - 前置:swift-apinotes fork 把 `ObjCContext.methods` / `properties` 改成 `public`,打 `0.3.0`。 - 新包打 `0.1.0` 并推送(公开仓库)。 4. **MachOObjCSection 接入新包**——`Package.swift`、`ObjCTypeIndexing`、`ObjCDeclaredTypeNames`。 - 行为:`declaredTypeNamesListFoundationClassesProtocolsAndStructs` @@ -614,3 +634,8 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` | 2026-11-23 | 开关放 Generation Options 面板 | agent 自定,可推翻:与现有打印开关同处,随请求发出、进缓存键、命令行也读同一份 | | 2026-11-23 | 共识确认 | 用户确认以上决定,开始写提案 | | 2026-11-23 | Accepted | 用户批准,开始实现 | +| 2026-11-23 | swift-apinotes fork 加入范围 | 它的 `ObjCContext.methods` / `properties` 在 0.2.0 是 internal,ObjC 成员的标注读不到。改为 `public` 并打 0.3.0(每个字段一行),比在新包里另写一套 YAML 解析更小;推送与打 tag 和新仓库一起请用户批准 | +| 2026-11-23 | 新增 `SDKPlatform.macCatalyst` | 提案原定 Catalyst 按 `.macOS` 索引并「落地时实测确认」:实测 `SDKIndexer` 不搜 `System/iOSSupport`,Catalyst UIKit 的 API notes 找不到;sourcekitd 按前端调用解析参数,macabi target 不会自动加 iOSSupport 框架路径(报 `Could not load module: UIKit`)。新 case 读 macOS SDK、先搜 iOSSupport、显式传 `-Fsystem` | +| 2026-11-23 | `index` 可多次调用、优先级改为查询时决定 | RuntimeViewer 加载新镜像时要追加模块;原先 API notes 靠写入顺序覆盖模块接口名,追加的接口名会把名字抢回去 | +| 2026-11-23 | 可用性返回 `sdkSettings` 而非 `sdkPath` | RuntimeViewer 的语料 variant 要 SDK 版本与 build,`SDKSettings` 一并给出 | +| 2026-11-23 | 加默认关闭的 `SDKIntegrationTests` | 单测覆盖不到真实 SDK 布局与 sourcekitd 参数,上面两个 Catalyst 问题都是实测才发现的;手动开启,不进 CI | From b68aff9f31d08743db2c1ccb6071f6161f4019d2 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 23 Nov 2026 17:44:45 +0800 Subject: [PATCH 077/175] Move TypeIndexing to swift-type-indexing; keep the printer's adapter The SDK index lives in its own package now, swift-type-indexing, which MachOObjCSection's new ObjCTypeIndexing also depends on. What stays here is SwiftTypeNameResolution: - TypeDatabaseTypeNameResolver answers the printer's ModuleNameResolving and CImportedNameResolving from a TypeDatabase, mapping CImportedTypeNameCategory onto the package's ImportedTypeNameCategory. - SwiftInterfaceBuilderTypeNameProvider keeps its name and initializer and now builds on the resolver, handing dependency images over as ObjCDeclaredTypeNames. A Mac Catalyst binary maps to the new SDKPlatform.macCatalyst rather than .macOS, whose SDK search missed UIKit's API notes under System/iOSSupport. The TypeIndexing product, its tests and the direct SourceKitD and swift-apinotes dependencies are gone; nothing outside this repository depended on them. swift-section interface --resolve-c-module-names keeps its name; with the package's rename fix, SwiftPrivate types print with __ and SwiftName types under their Swift name. MachOObjCSection is pinned to its feature branch until 0.8.209 is out. Proposal: draft-swift-type-indexing-package, step 6. --- AGENTS.md | 2 +- .../swift-section/.claude-plugin/plugin.json | 2 +- .../swift-section/.codex-plugin/plugin.json | 2 +- .../skills/swift-section-cli/SKILL.md | 12 +- Documentations/Glossary.md | 6 +- Documentations/Internal/Modules/README.md | 2 +- Documentations/Internal/ProjectMap.md | 2 +- .../Internal/TypeIndexingPipeline.md | 103 ------- Documentations/README.md | 2 +- Package.swift | 75 +++-- README.md | 2 +- .../Swift/InterfaceRequest.swift | 1 + .../TypeIndexing/APINotesIndex.swift | 124 -------- .../InterfaceDeclarationNode.swift | 65 ----- .../InterfaceTypeNameExtractor.swift | 53 ---- .../TypeIndexing/ModuleIndexCache.swift | 98 ------- .../TypeIndexing/ModuleInterfaceIndexer.swift | 88 ------ .../Declaration/TypeIndexing/SDKIndexer.swift | 121 -------- .../TypeIndexing/SDKPlatform.swift | 115 -------- .../TypeIndexing/SourceKitManager.swift | 163 ----------- .../Declaration/TypeIndexing/Subprocess.swift | 54 ---- .../TypeIndexing/SupplementaryAPINotes.swift | 64 ----- ...wiftInterfaceBuilderTypeNameProvider.swift | 101 ------- .../TypeIndexing/TypeDatabase.swift | 266 ------------------ .../SwiftInterfaceBuilderDependencies.swift | 2 +- ...wiftInterfaceBuilderTypeNameProvider.swift | 66 +++++ .../TypeDatabaseTypeNameResolver.swift | 89 ++++++ .../TypeIndexing/TypeNameProviderTests.swift | 9 +- ...icDemanglerFixedShapeExtractionTests.swift | 2 +- .../TypeDatabaseTypeNameResolverTests.swift | 71 +++++ .../APINotesIndexTests.swift | 101 ------- Tests/TypeIndexingTests/ImportScanTests.swift | 55 ---- .../InterfaceTypeNameExtractorTests.swift | 113 -------- .../ModuleIndexCacheTests.swift | 55 ---- .../ModuleInterfaceIndexerTests.swift | 93 ------ .../SupplementaryAPINotesTests.swift | 200 ------------- .../TypeDatabaseMergePriorityTests.swift | 198 ------------- 37 files changed, 302 insertions(+), 2275 deletions(-) delete mode 100644 Documentations/Internal/TypeIndexingPipeline.md delete mode 100644 Sources/Declaration/TypeIndexing/APINotesIndex.swift delete mode 100644 Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift delete mode 100644 Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift delete mode 100644 Sources/Declaration/TypeIndexing/ModuleIndexCache.swift delete mode 100644 Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift delete mode 100644 Sources/Declaration/TypeIndexing/SDKIndexer.swift delete mode 100644 Sources/Declaration/TypeIndexing/SDKPlatform.swift delete mode 100644 Sources/Declaration/TypeIndexing/SourceKitManager.swift delete mode 100644 Sources/Declaration/TypeIndexing/Subprocess.swift delete mode 100644 Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift delete mode 100644 Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift delete mode 100644 Sources/Declaration/TypeIndexing/TypeDatabase.swift create mode 100644 Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift create mode 100644 Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift create mode 100644 Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift delete mode 100644 Tests/TypeIndexingTests/APINotesIndexTests.swift delete mode 100644 Tests/TypeIndexingTests/ImportScanTests.swift delete mode 100644 Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift delete mode 100644 Tests/TypeIndexingTests/ModuleIndexCacheTests.swift delete mode 100644 Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift delete mode 100644 Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift delete mode 100644 Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift diff --git a/AGENTS.md b/AGENTS.md index 3c9c0c2b..98516c1f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ One or two lines each; the linked document is the authority. - **ARM64InstructionDecoding** (MachOKitExtensions) — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). - **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. - **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). -- **TypeIndexing** — `__C` module attribution (`__C.NSString` → `Foundation.NSString`), macOS-only, via SourceKit module interfaces + APINotes + a lazy ObjC-metadata index. [TypeIndexingPipeline.md](Documentations/Internal/TypeIndexingPipeline.md). +- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index 7beeb197..f3d41ffd 100644 --- a/AgentPlugins/swift-section/.claude-plugin/plugin.json +++ b/AgentPlugins/swift-section/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.26.0", + "version": "0.27.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 a7f58228..b8095c53 100644 --- a/AgentPlugins/swift-section/.codex-plugin/plugin.json +++ b/AgentPlugins/swift-section/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.26.0", + "version": "0.27.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 8efebac2..593d9d93 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -351,10 +351,14 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 ## 8. `--resolve-c-module-names` (interface, macOS only) -Turns `__C.NSString` into `Foundation.NSString`. Needs macOS 13+ and an Xcode installation, and -the first run per SDK generates module interfaces through sourcekitd — slow once, cached after. -Attribution against a non-macOS binary is limited (it warns and degrades rather than failing). -`--supplementary-apinotes` only does anything alongside it. +Turns `__C.NSString` into `Foundation.NSString`, and applies the SDK's Swift renames: a +`SwiftPrivate` type prints with `__` (`UIKit.__UICellConfigurationState`), a `SwiftName` one under +that name (`PencilKit.PKDrawingReference`). Needs macOS 13+ and the binary's SDK in the active +developer directory — Xcode, or the Command Line Tools for macOS and Mac Catalyst binaries. The +first run per SDK generates module interfaces through sourcekitd — slow once (UIKit takes about two +minutes), cached after in `~/Library/Application Support/swift-type-indexing`. Without sourcekitd only +API notes and Objective-C metadata attribute names. A binary whose SDK is not installed warns and +prints `__C.` unresolved. `--supplementary-apinotes` only does anything alongside it. ## 9. Reading the output: things that look like bugs and are not diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index 450b7501..1f053734 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -442,10 +442,10 @@ dyld shared cache 在子缓存之间放的跳板:`bl` 只能跳 ±128 MB,跨 ### supplementary APINotes(补充映射) -TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备**类型映射文件,为 **SDK 里没有模块的私有框架**(AttributeGraph 等)提供 `__C` 类型的归属与改名——这类框架的 `swift_name` 改名在二进制里只剩类型记录里的最后一截(`Graph`),所属模块与嵌套关系都不记录,完整名字只能靠外部知识。库自身不内置任何映射(首版的内置 SPM resource bundle 因 `Bundle.module` 分发即崩问题在 review 后移除);宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes` 传入,覆盖顺序 SDK APINotes → 用户文件按传入序,后写覆盖同名。CF-bridged 类型须登记两个 C 拼写(typedef 名进 Typedefs、storage tag 名进 Tags)。描述符按 import info 里的 ABI name 打印(提案 0023),不会再出现 Swift spelling 的 `__C.Graph`;SwiftName spelling 仍会登进归属表,让改名条目所在的模块胜过只做标注的其它模块(`NSObject` 归 ObjectiveC,不归同样列出它的 Foundation)。 +类型索引(swift-type-indexing 的 `TypeIndexing`,原是本仓库的同名 target)的外部知识入口:标准 `.apinotes` 格式的**用户自备**类型映射文件,为 **SDK 里没有模块的私有框架**(AttributeGraph 等)提供 `__C` 类型的归属与改名——这类框架的 `swift_name` 改名在二进制里只剩类型记录里的最后一截(`Graph`),所属模块与嵌套关系都不记录,完整名字只能靠外部知识。库自身不内置任何映射(首版的内置 SPM resource bundle 因 `Bundle.module` 分发即崩问题在 review 后移除);宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes` 传入,覆盖顺序 SDK APINotes → 用户文件按传入序,后写覆盖同名。CF-bridged 类型须登记两个 C 拼写(typedef 名进 Typedefs、storage tag 名进 Tags)。描述符按 import info 里的 ABI name 打印(提案 0023),不会再出现 Swift spelling 的 `__C.Graph`;SwiftName spelling 仍会登进归属表,让改名条目所在的模块胜过只做标注的其它模块(`NSObject` 归 ObjectiveC,不归同样列出它的 Foundation)。 -- **主要出现在**:`Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift` -- **延伸阅读**:[提案 0010](Evolutions/0010-community-type-mapping-bundles.md)、[SupplementaryTypeMappings.md](SupplementaryTypeMappings.md)(公开使用指引)、[TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) +- **主要出现在**:swift-type-indexing 的 `Sources/TypeIndexing/SupplementaryAPINotes.swift` +- **延伸阅读**:[提案 0010](Evolutions/0010-community-type-mapping-bundles.md)、[SupplementaryTypeMappings.md](SupplementaryTypeMappings.md)(公开使用指引)、[TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md) ### sweep(构建扫描) diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index bd10797a..97cf50be 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -34,7 +34,7 @@ | SwiftObjCInterop | [SwiftObjCInterop.md](SwiftObjCInterop.md) | ✅ 已写(拆分来历:[0089-swift-objc-interop-module](../../Evolutions/0089-swift-objc-interop-module.md)) | | SwiftLayout | [SwiftLayout.md](SwiftLayout.md) | ✅ 已写(专题:[StaticLayoutEngine.md](../StaticLayoutEngine.md)、[StaticLayoutDependencyClosure.md](../StaticLayoutDependencyClosure.md)) | | SwiftDiffing | — | 待写(专题:[ABIDiffDesignAndLimitations.md](../ABIDiffDesignAndLimitations.md)、[ABIEvolutionDesign.md](../ABIEvolutionDesign.md)) | -| TypeIndexing | — | 待写(专题:[TypeIndexingPipeline.md](../TypeIndexingPipeline.md)) | +| SwiftTypeNameResolution | — | 适配层,打印器与 swift-type-indexing 之间(索引本身的说明在 [swift-type-indexing 的 TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md)) | | SwiftOutputTransformer | — | 待写(专题:[OutputTransformerMigration.md](../OutputTransformerMigration.md)) | | MachOSwiftSection | — | 待写 | | MachOFoundation | — | 由 MachOKitExtensions 提供(2.0.0 起,同名 product):再导出 `MachOBase`、`MachOSymbols`、`MachODependencies` | diff --git a/Documentations/Internal/ProjectMap.md b/Documentations/Internal/ProjectMap.md index 0ad4844e..46dc641a 100644 --- a/Documentations/Internal/ProjectMap.md +++ b/Documentations/Internal/ProjectMap.md @@ -38,7 +38,7 @@ RuntimeViewer · MachOKitUI · swift-decompiler ───┘ └── swift-section CLI wrapper └─ SwiftSectionKit one request per subcommand (+ MachOObjCSection's ObjC* products for `objc`) ├─ SwiftDump the `dump` output - ├─ TypeIndexing `__C` type → module attribution (macOS only) + ├─ SwiftTypeNameResolution `__C` type → module + Swift name via swift-type-indexing (macOS only) └─ SwiftInterface orchestrator: single version / diff / evolution ├─ SwiftIndexing image → declaration model ├─ SwiftPrinting declaration model → Swift source (a peer of SwiftIndexing) diff --git a/Documentations/Internal/TypeIndexingPipeline.md b/Documentations/Internal/TypeIndexingPipeline.md deleted file mode 100644 index abf3efb6..00000000 --- a/Documentations/Internal/TypeIndexingPipeline.md +++ /dev/null @@ -1,103 +0,0 @@ -# TypeIndexing:`__C` 模块归属索引管线实现说明 - -> 本文是 evolution 提案 [0009](../Evolutions/0009-type-indexing-revival.md)(TypeIndexing 重启)与 [0010](../Evolutions/0010-community-type-mapping-bundles.md)(补充映射包)的配套实现说明,面向维护者:记录实际落地的管线、与提案的差异、缓存布局与已知降级。 - -## 这个模块做什么 - -打印管线遇到 `__C` / `__ObjC` module 节点时(`NodePrintable.printModule`),会拿 sibling identifier 问 delegate 的 `moduleName(forTypeName:)`(带 `Ref` 后缀剥除回退)。`TypeIndexing` 提供唯一的 provider 实现 `SwiftInterfaceBuilderTypeNameProvider`:挂上它之后,`__C.NSString` 打印为 `Foundation.NSString`。CLI 入口是 `swift-section interface --resolve-c-module-names`(用户自备补充映射经 `--supplementary-apinotes` 追加);库入口是 `builder.addExtraDataProvider(SwiftInterfaceBuilderTypeNameProvider(machO:dependencies:supplementaryAPINotesURLs:))`(末参数带默认值)。 - -## 查询数据流(三源合并,优先级从高到低) - -``` -moduleName(forTypeName: "NSString") - 1. moduleNamesByTypeName ← Swift interface 类型名(低)+ APINotes C 名与 SwiftName 拼写 - (高,后写覆盖;SDK APINotes → 用户补充文件按传入序) - 2. objcModuleNamesByTypeName ← ObjC 元数据懒索引(最低,只补缺) - -swiftName(forCName: "CFStringRef", category:) ← identifier 重写(见下节) - 1. APINotes 改名表(按声明类别隔离;补充包条目同表、后写覆盖) - 2. CF `Ref` 剥除规则(剥后名必须存在于归属表;protocol 类别不适用) -``` - -## Identifier 重写:C 拼写 → Swift 拼写(用户指正驱动) - -module 名替换之外,`__C` 类型的 **identifier 本身**也可能是 Swift 里不存在的 C 拼写——首轮端到端输出的 `CoreFoundation.CFStringRef` 被用户指正:`CFStringRef` 是 C 侧 typedef 名,ClangImporter 剥 `Ref` 后缀桥接为原生 class `CFString`。落地为打印侧对 `swiftName(forCName:category:)` 的消费(该协议方法此前零消费者): - -- **只在 module 解析成功时重写**(`printModule` 返回是否命中),未解析的 `__C.CFStringRef` 绝不渲染成半吊子 `__C.CFString`。 -- **查询必须带声明类别**(`CImportedTypeNameCategory`,由 mangling 的 `Node.Kind` 映射:class / protocol / 值类型 / other)。这是第一版合并改名表当场踩出的回归:ObjC 的 class `NSObject` 与 protocol `NSObject` 同名,APINotes 只把 **protocol** 改名为 `NSObjectProtocol`——类别盲查让所有 class 继承行都被错写成 `NSObjectProtocol`(而 protocol 继承行反而是被修对的)。`APINotesIndex` 的改名表按 Classes / Protocols / 值类型(Tags + Enumerators + Typedefs)三张隔离,`.other`(typealias 等 mangling 不定类别的引用)查值类型表再查 class 表、**永不查 protocol 表**。 -- **CF `Ref` 剥除**是 APINotes miss 后的兜底规则:`Ref` 结尾且剥后名真实存在于归属表才重写(碰巧以 `Ref` 结尾的 ObjC 类不受影响),protocol 类别不适用(无 CF protocol 惯例)。 -- 归属表(`moduleNamesByCName`)不拆类别——同名实体同模块,归属无歧义。 -- **`Ref` 规则对整个 `objc_bridge`(`CF_BRIDGED_TYPE` / `CV_BRIDGED_TYPE` 等各框架宏别名)家族通用**,不是 CoreFoundation 专属——判据只是「剥后名存在于索引」。CG / CV / CM 探针实测(链 CoreGraphics + CoreVideo + libswiftCoreMedia 的 dylib):同一类型**两种 mangling 形态并存**——符号签名用 C typedef 名(`__C.CGContextRef`),字段元数据用剥后名(`__C.CGContext`)——分别由剥除规则与归属表直查覆盖(提案 0023 之后字段元数据也按描述符 import info 里的 ABI name 拼成 `__C.CGContextRef`,两种形态合一,只靠剥除规则),全部解析为 `CoreGraphics.CGContext` / `CoreVideo.CVBuffer` / `CoreMedia.CMFormatDescription`(`CVPixelBuffer` 在 mangling 层已归一为 `CVBuffer`,输出如实反映 ABI)。CoreMedia 仅以 `libswiftCoreMedia` overlay 形式出现在依赖里,`libswift` 前缀剥除使过滤命中其 SDK 模块——overlay-only 依赖场景成立。 - -- **Swift interface 类型名**:对二进制依赖命中的每个 SDK 模块,经 sourcekitd `editor.open.interface`(带 `key.enablesubstructure`)生成含 ObjC 导入声明的 Swift 视角 interface,`InterfaceTypeNameExtractor` 从结构树提取 fully-qualified 类型名。**不用 SwiftSyntax**(体积裁定,见提案 A′ 节);`.swiftinterface` 文件也不可用——它只含 Swift 声明,而本功能主要目标恰是 ObjC 导入类型。 -- **APINotes**:`.apinotes` 是编译器视角的权威归属记录,`APINotesIndex` 把**每个列出的实体**(含无 `SwiftName` 改名、含 `SwiftPrivate`)的 C 名注册到声明模块,后写覆盖 interface 名。双向改名表(`swiftName(forCName:)` / `cName(forSwiftName:)`)只收非 `SwiftPrivate` 的改名实体。 -- **ObjC 懒索引**:前两层 miss 才按依赖顺序逐 image 构造 MachOObjCSection `ObjCIndexing` 的 `ObjCInterfaceIndexer`、`prepare()`、并入 class / protocol / C struct / union 名 → image 模块名,命中即止。已索引 image 的结果缓存在 actor 内;索引失败的 image 记日志后丢弃不重试。依赖耗尽后 miss 只花一次字典探查。 - -## 补充映射:私有框架的外部知识入口(提案 0010) - -AttributeGraph 这类私有框架在 SDK 里没有任何模块(无头文件、无 swiftmodule、无 apinotes),三源全 miss;而 `AG_SWIFT_NAME(Graph)` 的改名在二进制里只剩消费方类型记录名字字段里的最后一截 `Graph`,所属模块与嵌套关系都不记录,完整的 `AttributeGraph.Graph` 原理上无法从二进制恢复。[提案 0010](../Evolutions/0010-community-type-mapping-bundles.md) 的补充映射就是这份外部知识的入口:映射用**标准 `.apinotes` 格式**表达(零新格式,直接进 `APINotesIndex` 既有管线,类别隔离天然携带),**全部由用户自备**——宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes`(可重复,文件或目录)传入;库自身不内置任何映射(首版曾内置 SPM resource bundle,review 后按用户裁定移除:`Bundle.module` accessor 在 bundle 缺失时 fatalError,而 `build-executable-product.sh` 只分发裸二进制,分发出去一用就崩——纯用户自备把整个 resource 分发问题结构性消掉)。覆盖顺序:SDK APINotes → 用户文件按传入序,`APINotesIndex.register(files:)` 的后写覆盖即优先级实现。面向用户的公开指引见 [SupplementaryTypeMappings.md](../SupplementaryTypeMappings.md)。 - -**同一个 CF-bridged 类型有两种 mangling 形态**(AG probe 实测:手造 clang module 复刻 `objc_bridge` + `swift_name` 声明,5 处引用全解析为 `AttributeGraph.Graph` / `.Subgraph`;当时还有第三种,见第 3 条),各自的覆盖机制不同: - -1. **typedef 名**(`__C.AGGraphRef`,符号签名,typealias node → `.other` 类别):`Typedefs` 条目的改名表命中。 -2. **storage / tag 名**(`__C.AGGraphStorage`,字段元数据的 foreign **class** descriptor,`.objcClass` 类别):条目按 C 语义归 `Tags`(值类型表),所以 `.objcClass` 查询在 class 表 miss 后**回退值类型表**。安全性论证:C 的 tag namespace 与 ObjC class namespace 理论上可同名共存,但 class 表先查先赢,「改名只在 tag 侧、同名 ObjC class 又真被引用」无已知真实实例;protocol 表仍绝不回退(`NSObject` 隔离不动)。系统 dyld cache 的 SwiftUI 里实测存在孤立的 `AGGraphStorage` descriptor 名,即此形态。 -3. **导入名直出**(`__C.Graph`,已不再出现):消费方二进制 emit 的 foreign descriptor,名字字段记录的是 **swift_name 之后**的拼写,而且只是最后一截。提案 0023 之前描述符就按这个名字打印,`TypeDatabase` 的归属同步(`registerAttribution(fromAPINotesIndex:)`)因此把改名反查表(`cNamesBySwiftName`)里不带点的 SwiftName spelling 也登进归属表。0023 起描述符按 import info 里的 ABI name 打印(`__C.AGGraphRef`、`__C.NSDecimal`),走第 1、2 条。2026-10-01 用 macOS 27 的 SwiftUICore 实测 `dump`:0023 之前 `__C.Graph` / `__C.Subgraph` 共 107 行,之后为 0。那段登记却不能删:它排在 C 名登记之后,还决定着几个模块的 APINotes 都列出的 C 名归谁。Foundation 与 AppKit 的 APINotes 为了标注 category 方法也列了 `NSObject`,C 名登记是后加载的文件说了算;ObjectiveC 的条目把 `NSObject` 改名为它自己,这个 SwiftName spelling 最后登记,`NSObject` 才回到 ObjectiveC。2026-10-03 试删后,AppKit 的 `--resolve-c-module-names` 输出里 `ObjectiveC.NSObject` 108 行、`ObjectiveC.NSObjectProtocol` 22 行全部变成 `Foundation.…`,于是撤回,并用 `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings` 钉住。 - -映射内容立场:**宁缺毋滥**——条目错了输出跟着错,公开指引要求每条改名都有头文件级一手证据(重建头文件声明或 OpenGraph 这类文档化项目)。 - -## 管线分层(每层一个类型,一文件) - -| 类型 | 职责 | 关键点 | -|---|---|---| -| `SDKPlatform` / `SDKSettings` | 平台 → SDK 路径、target triple、SDK 版本标识 | `SDKSettings.plist` 的 `Version` + `ProductBuildVersion` 组成缓存目录段 | -| `Subprocess` | `xcrun` / `xcode-select -p` 同步调用 | 非零退出码抛错,不再静默返回空串 | -| `SourceKitManager` | actor:sourcekitd 请求 + 响应转值类型 | dylib 路径从 active developer dir 派生(不再硬编码 `/Applications/Xcode.app`);substructure 在 actor 内转成 `InterfaceDeclarationNode` 值树;`importedModuleNames` 是行级 import 扫描 | -| `InterfaceDeclarationNode` | substructure 的值类型投影 | `other` 节点的子树在转换时即丢弃 | -| `InterfaceTypeNameExtractor` | 值树 → fully-qualified 类型名(纯函数) | extension 节点用被扩展类型名(可带点)作限定前缀、自身不入清单——旧 SwiftSyntax 解析器的 extension 嵌套键错误在此结构性消失 | -| `SDKIndexer` | SDK 文件发现(秒级,零 sourcekitd) | `.swiftmodule` 目录 `skipDescendants`;同名模块先到先得(search path 优先级) | -| `APINotesFile` / `APINotesIndex` | `.apinotes` 解析与三张名表 | 修复历史 bug:C 名 → Swift 名映射的 `moduleName` 字段曾被写成 swiftName;`register(files:)` 可追加(后写覆盖,补充包优先级的实现点) | -| `SupplementaryAPINotesLoader` | 用户自备补充映射的枚举与解析(提案 0010) | 路径可为文件或目录(目录取浅层 `.apinotes` 按文件名排序);解析失败逐文件记日志跳过;CLI 侧另有 stderr 预检警告 | -| `ModuleIndexCacheEntry` / `ModuleIndexCache` | per-module JSON 缓存 | 见下节 | -| `ModuleInterfaceIndexer` | 单模块管线:缓存 → 生成 → 提取 → 回写 | 单模块失败记日志返回 `nil`,不作废整轮索引;submodule interface 并入主模块条目(归属永远写顶层模块名);**任一 submodule 失败则本轮照常返回但不写缓存**(缓存无完整性标记,写了就把缺口固化到 SDK/generator 版本变化为止——review 发现 4);sourcekitd 调用经 `InterfaceGenerator` 闭包注入缝,缓存纪律可脱离 sourcekitd 单测 | -| `TypeDatabase` | actor:三源合并 + 懒索引 + 查询 | `register(moduleEntries:)` / `register(apiNotesIndex:)` / `register(supplementaryAPINotesFiles:)` / `register(dependencies:)` 四步公开为 package API,合并优先级因此可脱离 sourcekitd 单测;task group 结果按**完成序**到达,注册前经 `entriesInDiscoveryOrder` 重排回 SDK 发现序(后写覆盖 + 完成序 = 同名归属跨两次运行不确定——review 发现 7);`moduleName(forImagePath:)` 的扩展名剥除循环带不动点守卫(前导点名字如 `.hidden` 是剥除不动点,曾死循环——review 发现 5) | -| `SwiftInterfaceBuilderTypeNameProvider` | 对接 `SwiftInterfaceBuilder` 的 provider | 模块过滤 = 依赖 image 名集合(`TypeDatabase.moduleName(forImagePath:)`:剥全部扩展名 + `libswift` 前缀) | - -## 缓存布局 - -``` -~/Library/Application Support/MachOSwiftSection/SDKIndexer//-/.json -``` - -- 条目是**提取产物**(类型名清单 + submodule 名单),不存 interface 全文。 -- 按 SDK 精确构建分目录:Xcode 升级换目录,陈旧条目自然失效(历史实现只按 platform 分目录且要求全 SDK 索引完成的标记文件,升级后继续吃旧数据)。 -- `generatorVersion` 不匹配的条目按 miss 处理——提取行为变更时把 `ModuleIndexCacheEntry.currentGeneratorVersion` 加一。 -- 全部缓存 I/O 是 best-effort:读写失败记日志、走重新生成,不向上抛错。 - -## 性能形态 - -- SDK 扫描只做文件发现,秒级;sourcekitd 生成只对**依赖过滤命中的模块**进行(历史实现对全 SDK 数百模块逐个生成、过滤在其后,首次索引小时级——这是该 target 当年被禁用的直接原因)。 -- 首个未命中缓存的模块仍要付一次真实生成成本(大模块数秒到数十秒);同 SDK 下第二次起走缓存。 -- ObjC 懒索引把依赖 image 的解析成本压到「前两层查不到」的路径上;`ObjCInterfaceIndexer.prepare()` 解析全部成员 info,对单个大 framework 不算轻——若实测过重,未来方向是在 MachOObjCSection 加 name-only 快速路径。 - -## 降级行为(0005 事件化纪律的落点) - -TypeIndexing 内部拿不到 `SwiftIndexEvents` 的 dispatcher(provider 协议面只有 `setup()`),所以降级全部走 `@Loggable` + `#log` 地板(subsystem `com.machoswiftsection.typeindexing`):单模块 interface 生成失败、submodule 失败、`.apinotes` 解析失败、缓存读写失败、依赖 image ObjC 索引失败——都是「跳过该项 + 记日志」,绝不让一个模块的失败作废整个数据库。`setup()` 整体抛错(如 SDK 设置读不到)由 `SwiftInterfaceBuilder.prepare()` 的既有 `.renderingDegraded(source: .extraDataProvider)` 事件兜住。 - -## `@Loggable` 的形态约束(本模块特有的坑) - -TypeIndexing 的类型都标 `@available(macOS 13.0, *)`(包部署下限是 macOS 10.15)。`@Loggable` 的**直接类型形态**会展开自带 availability 标注的 static stored `logger`,在显式 `@available` 的类型里被 emit-module 拒绝("cannot be more available than enclosing scope",单 target 编译只是 warning,整包 emit-module 是 error)。因此本模块一律用 **protocol 形态**:不标 availability 的 `fileprivate protocol XxxLogging {}` + 标 `@available(macOS 13.0, *)` 的 conformance extension。泛型 `TypeDatabase` 本来就只能用 protocol 形态,非泛型类型在这里也被迫用它。 - -## 与提案的差异 - -- **swift-dependencies 未引入**:提案 E 节的依赖清单含 `Dependencies`(历史实现用 `@Dependency` 注入 `SourceKitManager`)。落地改为把 `TypeDatabase` 的三个 `register` 步骤公开为 package API,测试直接驱动合并逻辑,不需要依赖注入框架——少一个 target 依赖。 -- **兜底行级解析器未编写**:提案 A′ 允许 substructure 验证失败时退手写解析;scratchpad 探针实测 substructure 完整可用(ObjectiveC / CoreGraphics 两模块,节点带 kind + name + 嵌套 + extension),按提案「二选一定夺」条款只落主路。 -- **`MachOObjCSection` 下限抬到 0.8.105**:泛型(`ObjCMetadataSource`,支持 `MachOFile`)的 `ObjCInterfaceIndexer` 在 0.8.105 才有,0.8.104 的只接受 `MachOImage`。 -- **APINotes 归属注册比历史实现更宽**:历史实现只注册有 `SwiftName` 的实体;现在每个列出的实体(含 `SwiftPrivate`)都注册归属——`__C.X` 的 X 是 C 名,归属正确性与 Swift 侧可见性无关。改名表仍跳过 `SwiftPrivate`。 - -## 已知限制 - -- 整个 target 是 macOS-only(`#if os(macOS)` 全文件 + 依赖的 `.when(platforms: [.macOS])` 条件),且运行时要求 macOS 13+ 与本机 Xcode(sourcekitd)。 -- Identifier 重写只覆盖类型引用(`printType` 的 nominal 路径);成员级 SwiftName 改名(selector → Swift 方法名等)不在本案,另立提案。 -- 依赖 image 的模块名取自 image 文件名(`libobjc.A.dylib` → `libobjc`),与 Swift module 名在少数 dylib 上不一致;影响仅限私有类型归属的显示名。 -- CLI 的 provider 依赖集用 `.usesSystemDyldSharedCache`(被检查二进制的依赖按本机 dyld cache 解析);跨版本 / 跨平台二进制的依赖解析不在 CLI 默认路径覆盖内。 -- **声明模块完全不在依赖列表里时三层全 miss**:类型只出现在签名 / 元数据、二进制没有对该框架的任何符号引用时,链接器不会记 `LC_LOAD_DYLIB`(探针实测:只声明 `CGContext` 字段而不调 CG 函数,CoreGraphics 就不在依赖里),依赖过滤自然不会索引该模块,`__C.` 原样保留。真实二进制里用一个类型几乎必调它的函数(或至少链 overlay),所以实际影响很小;若将来遇到,可选增强是把过滤集合扩到依赖闭包(传递依赖)。用户自备的补充映射(提案 0010)不受此限:它不参与依赖过滤,条目覆盖到就能解析——SDK 里根本没有模块的私有框架(AttributeGraph)正是靠它。 diff --git a/Documentations/README.md b/Documentations/README.md index 7c4ad17c..c77082af 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -230,7 +230,7 @@ selects names using each access's offset and width. | [NodeStoreMigrationOpenIssues.md](Internal/NodeStoreMigrationOpenIssues.md) | NodeStore 迁移的遗留问题台账:每条问题记录成因、影响面、修复位置与当前状态(已修 / 裁决不修 / 仍打开),闭环的条目保留成因备回溯。大部分条目已闭环或已终审;与 `Reviews/` 下两份审查记录冲突时以后者为准。 | | [SystemFrameworkRenderingVerification.md](Internal/SystemFrameworkRenderingVerification.md) | 系统框架渲染 A/B 验证流程(大重构必跑):两个检出对同一批真实输入(归档 dyld cache → 无则当前系统 cache、模拟器 runtime → 无则现有 runtime、当前系统 MachOImage)逐字节比对 dump+interface;入口脚本 `Scripts/run-rendering-ab-verification.py`,含回退规则、踩坑清单(`-p` 消歧、fat 二进制 `-a`、同 boot 会话、scratch 隔离)与 2026-08-03 基线运行记录。 | | [TuistDevelopment.md](Internal/TuistDevelopment.md) | **使用指南:Tuist 开发 workspace**:`./TuistScript.sh` 生成的 `MachOSwiftSection-Tuist.xcworkspace`,第三方依赖走本机二进制缓存,`--local-dependencies` 改用五个上游库的本地检出;测试怎么映射进来(`Package.swift` 末尾的 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 块、手写的 `SwiftSectionCommandTests`)、与 RuntimeViewer 共用的占用记录、存放位置与 Tuist 4.210 的坑。提案 [0099-tuist-workspace](Evolutions/0099-tuist-workspace.md)。 | -| [TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) | **`__C` 模块归属索引管线**(提案 0009 + 0010 的实现说明):`__C.NSString` → `Foundation.NSString` 的三源合并(SourceKit 生成 interface 的 substructure 提取(零 SwiftSyntax)→ APINotes 权威归属覆盖 → 依赖 image ObjC 元数据懒索引兜底)、补充映射包(私有框架外部知识入口,CF-bridged 类型三种 mangling 形态与各自覆盖机制)、按 SDK 精确构建分层的 per-module JSON 缓存、过滤前移的性能形态(历史全 SDK 生成为何小时级)、`@Loggable` 在 `@available` 类型上必须走 protocol 形态的坑、与提案的差异(swift-dependencies 未引入、兜底解析器未编写、MachOObjCSection 下限 0.8.105)。 | +| [TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md)(已移到 swift-type-indexing) | **`__C` 模块归属索引管线**(提案 0009 + 0010 的实现说明,随 `TypeIndexing` 一起搬到 swift-type-indexing,本仓库只剩适配层 `SwiftTypeNameResolution`):`__C.NSString` → `Foundation.NSString` 的三源合并(SourceKit 生成 interface 的 substructure 提取(零 SwiftSyntax)→ APINotes 权威归属覆盖 → 依赖 image ObjC 元数据懒索引兜底)、补充映射包(私有框架外部知识入口,CF-bridged 类型三种 mangling 形态与各自覆盖机制)、按 SDK 精确构建分层的 per-module JSON 缓存、过滤前移的性能形态(历史全 SDK 生成为何小时级)、`@Loggable` 在 `@available` 类型上必须走 protocol 形态的坑、与提案的差异(swift-dependencies 未引入、兜底解析器未编写、MachOObjCSection 下限 0.8.105)。 | | [EventBasedDegradationReporting.md](Internal/EventBasedDegradationReporting.md) | **降级上报走事件**(提案 0005 的实现说明):库代码不写进程流,落点由宿主装的 `Handler` 决定(GUI → os_log,CLI → stderr);`Dispatcher` 零 handler 时的 os_log 地板与它为何在 dispatcher 而非调用点、`unhandledFailureDescription` 为何是白名单式穷举 switch;四条走不通的近路(`@Loggable` 的 product 与部署下限双重限制 + 泛型类型不可用、`SwiftDeclarationRendering` 因依赖方向够不到事件类型、`Handler` 非 `Sendable` 导致改注入 `Dispatcher`、fd 重定向测试会挂死整轮 `swift test` 故改源码扫描);顺带修掉的 `ConsoleEventHandler` 写 stdout 与 diff 单侧 header 失败删两侧;以及 `FileHandle.write(_:)` 为何会 abort 宿主。 | | [PrivateTypeMemberAttribution.md](Internal/PrivateTypeMemberAttribution.md) | 同名私有类型的成员归属(issue #115 修复说明):成员索引的打印名 key 剥掉了私有判别符、不是单射,「解析单个类型的成员/信息/属性」必须走带 `node:` 的重载;当时踩坑的全部位置(dump 三个 dumper、deinit/destructor、thunk 属性、`typeInfoByName`)、刻意不改 key 格式的理由、fixture 的防优化手段与回归防线。 | | [References/](Internal/References/README.md) | **外部权威资料的中译**(与 `Internal/` 其余文档相反:不描述本库,而是本库赖以成立的外部事实)。目前是 Slava Pestov《Compiling Swift Generics》**全书 24 章中译**,译自 `swift-6.4.0-RELEASE` 的 `docs/Generics/`(Apache License 2.0 with Runtime Library Exception,每篇标明出处/原作者/许可/commit)。书讲「源码怎么编成二进制」,本库做反方向的事,故书里的编码规则即本库的解码依据:generic signature 与 requirement 的 canonical 顺序(Generic Signatures / Building Generic Signatures)、`⊗` 替换代数(Substitution Maps)、conformance 三形态与 witness table(Conformances / Conformance Paths)、existential 容器布局(Existential Types)、`some P` 的完整机制(Opaque Result Types)。译文正文忠于原著,仅在确有对应处以「译注」标出本库落点;该目录 README 是分部索引与阅读约定(术语、两套记法、图的降级、原书笔误的处理)。 | diff --git a/Package.swift b/Package.swift index d9bccd57..676ac962 100644 --- a/Package.swift +++ b/Package.swift @@ -102,10 +102,20 @@ var dependencies: [Package.Dependency] = [ .package(url: "https://github.com/pointfreeco/swift-dependencies", from: "1.9.4"), - // TypeIndexing (all its sources are `#if os(macOS)`; both products carry - // a macOS-only platform condition on the target dependency) - .package(url: "https://github.com/Mx-Iris/SourceKitD", from: "0.1.0"), - .package(url: "https://github.com/MxIris-DeveloperTool/swift-apinotes", from: "0.1.0"), + // The SDK index `SwiftTypeNameResolution` resolves `__C` types with, moved + // out of this package (proposal swift-type-indexing-package). Its sources + // are all `#if os(macOS)`, so targets depend on it with a macOS-only + // condition. + .package( + local: .package( + path: "../swift-type-indexing", + isRelative: true, + ), + remote: .package( + url: "https://github.com/MxIris-Reverse-Engineering/swift-type-indexing", + from: "0.1.0", + ), + ), // CLI .package(url: "https://github.com/onevcat/Rainbow", from: "4.0.0"), @@ -225,7 +235,13 @@ extension Package.Dependency { // 0.8.208 defines `SymbolLanguage.objectiveC` and registers it when // its image loads, and takes MachOKitExtensions 3.0.0, which this // package requires (proposal split-symbol-language). - "0.8.208" ..< "0.9.0", + // 0.8.209 adds `ObjCTypeIndexing`, the bridge to swift-type-indexing + // `SwiftTypeNameResolution` hands dependency images through + // (proposal swift-type-indexing-package). + // TEMPORARY: the feature branch until MachOObjCSection 0.8.209 is + // released; the proposal's wrap-up puts the range back: + // "0.8.209" ..< "0.9.0", + branch: "feature/swift-type-indexing-package", ), ) } @@ -883,23 +899,26 @@ extension Target { path: "Sources/Output/SwiftInterface", ) - /// Module-attribution index for `__C` types (evolution proposal 0009): - /// resolves `__C.NSString` to `Foundation.NSString` via SourceKit-generated - /// module interfaces (substructure, no SwiftSyntax), APINotes renames, and - /// a lazy ObjC-metadata index over the binary's dependencies. Every source - /// file is `#if os(macOS)`. - static let TypeIndexing = Target.target( - name: "TypeIndexing", + /// The printer's side of swift-type-indexing (proposal + /// swift-type-indexing-package): `TypeDatabaseTypeNameResolver` answers the + /// printer's `ModuleNameResolving` and `CImportedNameResolving` from a + /// `TypeDatabase`, so `__C.UICellConfigurationState` prints as + /// `UIKit.__UICellConfigurationState`; `SwiftInterfaceBuilderTypeNameProvider` + /// attaches one to a `SwiftInterfaceBuilder` for a binary and its + /// dependencies. Every source file is `#if os(macOS)`. + static let SwiftTypeNameResolution = Target.target( + name: "SwiftTypeNameResolution", dependencies: [ .target(.SwiftInterface), + .target(.SwiftPrinting), + .target(.MachOSwiftSection), .product(.MachOKit), - .product(name: "ObjCIndexing", package: "MachOObjCSection"), + .product(.MachOKitExtensions), .product(name: "ObjCMetadataSource", package: "MachOObjCSection"), - .product(name: "FoundationToolbox", package: "FrameworkToolbox"), - .product(name: "SourceKitD", package: "SourceKitD", condition: .when(platforms: [.macOS])), - .product(name: "APINotes", package: "swift-apinotes", condition: .when(platforms: [.macOS])), + .product(name: "ObjCTypeIndexing", package: "MachOObjCSection", condition: .when(platforms: [.macOS])), + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), ], - path: "Sources/Declaration/TypeIndexing", + path: "Sources/Output/SwiftTypeNameResolution", ) // MARK: - Commands @@ -926,7 +945,9 @@ extension Target { .target(.SwiftDiffing), .target(.SwiftInterface), .target(.SwiftPrivateDiscriminators), - .target(.TypeIndexing), + .target(.SwiftTypeNameResolution), + // `APINotesFile`, which checks `--supplementary-apinotes` paths. + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), .target(.Utilities), // `refs` and `symbolicate`. .target(.CrossReferenceAnalysis), @@ -1222,10 +1243,13 @@ extension Target { swiftSettings: testSettings, ) - static let TypeIndexingTests = Target.testTarget( - name: "TypeIndexingTests", + static let SwiftTypeNameResolutionTests = Target.testTarget( + name: "SwiftTypeNameResolutionTests", dependencies: [ - .target(.TypeIndexing), + .target(.SwiftTypeNameResolution), + .target(.SwiftPrinting), + .product(.MachOKit), + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), ], swiftSettings: testSettings, ) @@ -1486,7 +1510,8 @@ extension Target { .target(.SwiftPrinting), .target(.SwiftInterface), .target(.SwiftDiffing), - .target(.TypeIndexing), + .target(.SwiftTypeNameResolution), + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), .target(.SwiftSectionTestingSupport), .target(.SwiftSectionFixtureSupport), .product(.MachOKit), @@ -1532,7 +1557,7 @@ let package = Package( .library(.SwiftPrinting), .library(.SwiftSpecialization), .library(.SwiftInterface), - .library(.TypeIndexing), + .library(.SwiftTypeNameResolution), .library(.SwiftSectionKit), .executable(.swift_section), ], @@ -1560,7 +1585,7 @@ let package = Package( .SwiftPrinting, .SwiftSpecialization, .SwiftInterface, - .TypeIndexing, + .SwiftTypeNameResolution, .SwiftSectionKit, .SwiftSectionMacros, .SwiftSectionTestingMacros, @@ -1584,7 +1609,7 @@ let package = Package( .SwiftOutputTransformerTests, .SwiftLayoutTests, .SwiftDumpTests, - .TypeIndexingTests, + .SwiftTypeNameResolutionTests, .SwiftPrintingTests, .SwiftDeclarationRenderingTests, .SwiftThunkAnalysisTests, diff --git a/README.md b/README.md index 6e1e59e8..180c47a6 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ Since 0.25.0 the Mach-O layer underneath — `MachOBase`, `MachOFoundation`, `Ma | `SwiftThunkAnalysis` | Reads a type stored behind a metadata accessor thunk (availability-conditional opaque types, noncopyable fields) by evaluating its ARM64 code instead of running it, and ties a class's ObjC method table to its Swift members. | | `CrossReferenceAnalysis` | What each function of a loaded arm64 image calls and references — functions, Objective-C classes, Swift types — read from its machine code. `MachOImage` only. | | `SwiftSpecialization` | Runtime specialization of generic types (`GenericSpecializer`). | -| `TypeIndexing` | Attributes `__C` types to their real module (`__C.NSString` → `Foundation.NSString`) through SDK module interfaces and APINotes. macOS only. | +| `SwiftTypeNameResolution` | Resolves `__C` types to their real module and Swift name (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`) through [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), which reads the SDK's module interfaces and API notes. macOS only. | **Declarations and output** diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index 5e5eaa1c..6c1ba2c9 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -11,6 +11,7 @@ import OutputTransformer import SwiftOutputTransformer #if os(macOS) import TypeIndexing +import SwiftTypeNameResolution import Semantic #endif diff --git a/Sources/Declaration/TypeIndexing/APINotesIndex.swift b/Sources/Declaration/TypeIndexing/APINotesIndex.swift deleted file mode 100644 index 3a5840fe..00000000 --- a/Sources/Declaration/TypeIndexing/APINotesIndex.swift +++ /dev/null @@ -1,124 +0,0 @@ -#if os(macOS) - -import APINotes -import Foundation -import SwiftPrinting - -/// The name mappings mined from a set of `.apinotes` files: C name ↔ Swift -/// name (for `SwiftName` renames) and C name → declaring module. -/// -/// Rename tables are split **per declaration category**, because a C name is -/// only unique per category: ObjC declares both a class and a protocol named -/// `NSObject`, and only the protocol carries a `SwiftName` rename -/// (`NSObjectProtocol`) — one merged table rewrote every class reference with -/// the protocol's rename. -/// -/// Built once from parsed files and immutable afterwards; the owning -/// `TypeDatabase` actor provides all synchronization. -@available(macOS 13.0, *) -package struct APINotesIndex: Sendable { - package struct Name: Sendable, Equatable { - /// The module whose APINotes file declares the mapping. - package let moduleName: String - package let name: String - - package init(moduleName: String, name: String) { - self.moduleName = moduleName - self.name = name - } - } - - /// C class name → renamed Swift name (`Classes` entries). - package private(set) var classSwiftNamesByCName: [String: Name] = [:] - - /// C protocol name → renamed Swift name (`Protocols` entries, e.g. - /// `NSObject` → `NSObjectProtocol`). - package private(set) var protocolSwiftNamesByCName: [String: Name] = [:] - - /// C tag / enumerator / typedef name → renamed Swift name, e.g. - /// `NSActivityOptions` → `ProcessInfo.ActivityOptions`. - package private(set) var valueTypeSwiftNamesByCName: [String: Name] = [:] - - /// Renamed Swift name → original C name, all categories merged (renamed - /// spellings do not collide the way C names do). - package private(set) var cNamesBySwiftName: [String: Name] = [:] - - /// C name → declaring module, for **every** listed entity, renamed or - /// not. An APINotes file is the compiler's own record of which module a C - /// declaration belongs to, so attribution registers unconditionally — - /// including `SwiftPrivate` entities, whose C name still appears in - /// manglings even though their Swift spelling is underscored. - package private(set) var moduleNamesByCName: [String: String] = [:] - - package init(files: [APINotesFile]) { - register(files: files) - } - - /// Appends more files to the index. Within every table a later entry - /// overwrites an earlier same-name one — the ordering hook the - /// supplementary-file merge priority rides on (evolution proposal 0010: - /// SDK APINotes first, then user-supplied files in caller order). - package mutating func register(files: [APINotesFile]) { - for file in files { - let module = file.apiNotesModule - registerEntities(module.classes, declaredIn: file.moduleName, into: \.classSwiftNamesByCName) - registerEntities(module.protocols, declaredIn: file.moduleName, into: \.protocolSwiftNamesByCName) - registerEntities(module.tags, declaredIn: file.moduleName, into: \.valueTypeSwiftNamesByCName) - registerEntities(module.enumerators, declaredIn: file.moduleName, into: \.valueTypeSwiftNamesByCName) - registerEntities(module.typedefs, declaredIn: file.moduleName, into: \.valueTypeSwiftNamesByCName) - } - } - - /// The rename for `cName` in `category`. `.other` (a reference whose - /// mangling does not pin the category, e.g. a typealias) consults the - /// value-type then class tables, but never the protocol table — protocol - /// references always mangle as protocols, and the `NSObject` name split - /// is exactly what that isolation protects. - /// - /// `.objcClass` falls back to the value-type table on a class-table miss: - /// a CF-bridged type reaches field metadata as a *foreign class* node - /// spelled with its C tag name (`AGGraphStorage`, `CGContext` — the - /// consuming binary emits a class-kind foreign descriptor for it), while - /// its APINotes entry sits under `Tags`/`Typedefs` per C semantics. A tag - /// and an ObjC class live in different C namespaces so they *can* share a - /// name in principle, but the class table is consulted first, and a - /// rename that exists only tag-side while a same-named distinct ObjC - /// class is being referenced has no known real-world instance. - package func swiftName(forCName cName: String, category: CImportedTypeNameCategory) -> Name? { - switch category { - case .objcClass: - return classSwiftNamesByCName[cName] ?? valueTypeSwiftNamesByCName[cName] - case .objcProtocol: - return protocolSwiftNamesByCName[cName] - case .valueType: - return valueTypeSwiftNamesByCName[cName] - case .other: - return valueTypeSwiftNamesByCName[cName] ?? classSwiftNamesByCName[cName] - } - } - - package func cName(forSwiftName swiftName: String) -> Name? { - cNamesBySwiftName[swiftName] - } - - package func moduleName(forCName cName: String) -> String? { - moduleNamesByCName[cName] - } - - private mutating func registerEntities( - _ entities: [some CommonEntity]?, - declaredIn moduleName: String, - into renameTable: WritableKeyPath - ) { - guard let entities else { return } - for entity in entities { - let cName = entity.name - moduleNamesByCName[cName] = moduleName - guard let swiftName = entity.swiftName, entity.isSwiftPrivate != true else { continue } - self[keyPath: renameTable][cName] = Name(moduleName: moduleName, name: swiftName) - cNamesBySwiftName[swiftName] = Name(moduleName: moduleName, name: cName) - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift b/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift deleted file mode 100644 index 1fcfb56b..00000000 --- a/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift +++ /dev/null @@ -1,65 +0,0 @@ -#if os(macOS) - -/// One declaration node of a SourceKit-generated module interface, converted -/// out of the `editor.open.interface` response's `key.substructure` tree into -/// a plain value so extraction is a pure, testable function over it. -/// -/// Only the declaration kinds the type-name extractor distinguishes are -/// modeled; everything else collapses to ``Kind/other`` and is never descended -/// into (nested types occur only inside type bodies and extensions). -@available(macOS 13.0, *) -package struct InterfaceDeclarationNode: Sendable, Equatable { - package enum Kind: Sendable, Equatable { - /// `struct`, `class`, `actor`, `enum`, or `protocol` — a declaration - /// whose (qualified) name enters the index. - case typeDeclaration - /// `typealias` — enters the index by name but declares no members. - case typeAlias - /// An `extension` of some type: contributes its extended type name as - /// a qualification prefix for nested declarations, but is not itself - /// an indexed type. - case `extension` - /// Anything else (functions, properties, enum cases, parameters, …). - case other - } - - package let kind: Kind - - /// The declaration's name as SourceKit reports it. For an extension this - /// is the extended type reference, which may already be dot-qualified - /// (`extension Foo.Bar`). - package let name: String? - - package let children: [InterfaceDeclarationNode] - - package init(kind: Kind, name: String?, children: [InterfaceDeclarationNode] = []) { - self.kind = kind - self.name = name - self.children = children - } - - /// Maps a SourceKit declaration-kind UID string - /// (`source.lang.swift.decl.*`) onto the extractor's kind vocabulary. - package static func kind(forUIDString uidString: String) -> Kind { - switch uidString { - case "source.lang.swift.decl.struct", - "source.lang.swift.decl.class", - "source.lang.swift.decl.actor", - "source.lang.swift.decl.enum", - "source.lang.swift.decl.protocol": - return .typeDeclaration - case "source.lang.swift.decl.typealias": - return .typeAlias - case "source.lang.swift.decl.extension", - "source.lang.swift.decl.extension.struct", - "source.lang.swift.decl.extension.class", - "source.lang.swift.decl.extension.enum", - "source.lang.swift.decl.extension.protocol": - return .extension - default: - return .other - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift b/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift deleted file mode 100644 index 3b222cfd..00000000 --- a/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift +++ /dev/null @@ -1,53 +0,0 @@ -#if os(macOS) - -/// Extracts the fully-qualified type names a SourceKit-generated module -/// interface declares, from its ``InterfaceDeclarationNode`` tree. -/// -/// Qualification follows the node parent chain: a type nested in a type -/// prefixes the outer name, and a type nested in an extension prefixes the -/// *extended* type's (possibly already dot-qualified) name — so -/// `extension Foo.Bar { public struct Baz }` yields `Foo.Bar.Baz`. The -/// extension node itself is never an indexed name. -/// -/// Only type declarations, type aliases, and extensions are descended into; -/// nothing nested in a function or accessor is reachable in a generated -/// interface, and descending into ``InterfaceDeclarationNode/Kind/other`` -/// nodes would only surface generic parameters and locals. -@available(macOS 13.0, *) -package enum InterfaceTypeNameExtractor { - package static func fullyQualifiedTypeNames(in declarations: [InterfaceDeclarationNode]) -> [String] { - var typeNames: [String] = [] - for declaration in declarations { - appendTypeNames(of: declaration, qualificationPrefix: nil, into: &typeNames) - } - return typeNames - } - - private static func appendTypeNames( - of declaration: InterfaceDeclarationNode, - qualificationPrefix: String?, - into typeNames: inout [String] - ) { - switch declaration.kind { - case .typeDeclaration, .typeAlias: - guard let name = declaration.name, !name.isEmpty else { return } - let qualifiedName = qualificationPrefix.map { "\($0).\(name)" } ?? name - typeNames.append(qualifiedName) - for child in declaration.children { - appendTypeNames(of: child, qualificationPrefix: qualifiedName, into: &typeNames) - } - case .extension: - // Not itself an indexed name; its extended-type name (already - // qualified when SourceKit prints `extension Foo.Bar`) qualifies - // the nested declarations. - guard let extendedTypeName = declaration.name, !extendedTypeName.isEmpty else { return } - for child in declaration.children { - appendTypeNames(of: child, qualificationPrefix: extendedTypeName, into: &typeNames) - } - case .other: - return - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift b/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift deleted file mode 100644 index 3e238f01..00000000 --- a/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift +++ /dev/null @@ -1,98 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox - -/// One module's cached extraction: what the indexer needs at query time, -/// without the interface text it was extracted from. -@available(macOS 13.0, *) -package struct ModuleIndexCacheEntry: Codable, Sendable { - package let moduleName: String - - /// Fully-qualified type names the module (and its indexed submodules) - /// declares, as extracted from the generated interface's substructure. - package let typeNames: [String] - - package let subModuleNames: [String] - - /// Bumped when extraction behavior changes; a mismatching entry is - /// ignored so stale semantics never survive a library update. - package let generatorVersion: Int - - package static let currentGeneratorVersion = 1 - - package init(moduleName: String, typeNames: [String], subModuleNames: [String], generatorVersion: Int = Self.currentGeneratorVersion) { - self.moduleName = moduleName - self.typeNames = typeNames - self.subModuleNames = subModuleNames - self.generatorVersion = generatorVersion - } -} - -/// Per-module JSON cache of extraction results, segmented per platform and -/// per exact SDK build so an Xcode update can never serve stale entries: -/// -/// ``` -/// Application Support/MachOSwiftSection/SDKIndexer//-/.json -/// ``` -/// -/// Every entry stands alone — there is no whole-SDK completion marker, so a -/// partially-warmed cache serves what it has and misses the rest. All cache -/// I/O is best-effort: a failure degrades to regeneration, never to an error. -@available(macOS 13.0, *) -package struct ModuleIndexCache: Sendable { - package let directoryURL: URL - - package init(platform: SDKPlatform, sdkSettings: SDKSettings) { - self.init( - directoryURL: URL.applicationSupportDirectory - .appending(component: "MachOSwiftSection") - .appending(component: "SDKIndexer") - .appending(component: platform.rawValue) - .appending(component: sdkSettings.cacheDirectoryComponent) - ) - } - - /// Direct-directory form, the seam tests use to keep cache I/O out of the - /// real Application Support tree. - package init(directoryURL: URL) { - self.directoryURL = directoryURL - } - - private func entryURL(forModuleNamed moduleName: String) -> URL { - directoryURL.appending(component: "\(moduleName).json") - } - - package func entry(forModuleNamed moduleName: String) -> ModuleIndexCacheEntry? { - let entryURL = entryURL(forModuleNamed: moduleName) - guard let entryData = try? Data(contentsOf: entryURL) else { return nil } - do { - let entry = try JSONDecoder().decode(ModuleIndexCacheEntry.self, from: entryData) - guard entry.generatorVersion == ModuleIndexCacheEntry.currentGeneratorVersion else { return nil } - return entry - } catch { - #log(.error, "Discarding undecodable cache entry at \(entryURL.path(percentEncoded: false), privacy: .public): \(String(describing: error), privacy: .public)") - return nil - } - } - - package func store(_ entry: ModuleIndexCacheEntry) { - do { - try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) - let entryData = try JSONEncoder().encode(entry) - try entryData.write(to: entryURL(forModuleNamed: entry.moduleName), options: .atomic) - } catch { - #log(.error, "Failed to store cache entry for module \(entry.moduleName, privacy: .public): \(String(describing: error), privacy: .public)") - } - } -} - -// Protocol-form `@Loggable` — see the note in SDKIndexer.swift: the direct -// type form clashes with the `@available(macOS 13.0, *)` scope. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "ModuleIndexCache") -fileprivate protocol ModuleIndexCacheLogging {} - -@available(macOS 13.0, *) -extension ModuleIndexCache: ModuleIndexCacheLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift b/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift deleted file mode 100644 index 29ecd31a..00000000 --- a/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift +++ /dev/null @@ -1,88 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox - -/// The per-module indexing pipeline: cache lookup → interface generation → -/// type-name extraction → cache store. Runs only for modules the caller's -/// dependency filter selected — this is where the expensive sourcekitd work -/// lives, deliberately downstream of the filter. -@available(macOS 13.0, *) -package struct ModuleInterfaceIndexer: Sendable { - package typealias InterfaceGenerator = @Sendable (_ moduleName: String) async throws -> SourceKitManager.GeneratedModuleInterface - - package let platform: SDKPlatform - package let sdkSettings: SDKSettings - package let cache: ModuleIndexCache - private let generateInterface: InterfaceGenerator - - package init(platform: SDKPlatform, sdkSettings: SDKSettings, cache: ModuleIndexCache, sourceKitManager: SourceKitManager) { - self.init(platform: platform, sdkSettings: sdkSettings, cache: cache) { moduleName in - try await sourceKitManager.interface(for: moduleName, platform: platform, sdkSettings: sdkSettings) - } - } - - /// Test seam: substitutes the sourcekitd-backed generation with an - /// arbitrary closure, so the cache-write discipline (partial entries are - /// never stored) is testable without sourcekitd. - package init(platform: SDKPlatform, sdkSettings: SDKSettings, cache: ModuleIndexCache, interfaceGenerator: @escaping InterfaceGenerator) { - self.platform = platform - self.sdkSettings = sdkSettings - self.cache = cache - self.generateInterface = interfaceGenerator - } - - /// Indexes one module, returning `nil` when its interface cannot be - /// generated — the caller skips that module rather than failing the whole - /// indexing run (one exotic module must not blank the entire database). - /// - /// Submodule interfaces (`Foundation.NSObject`-style imports of the - /// module's own submodules) are generated and folded into the same entry: - /// attribution always names the top-level module, which is what a - /// qualified `Foundation.NSString` spelling needs. - package func indexEntry(forModuleNamed moduleName: String) async -> ModuleIndexCacheEntry? { - if let cachedEntry = cache.entry(forModuleNamed: moduleName) { - return cachedEntry - } - do { - let interface = try await generateInterface(moduleName) - var typeNames = InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: interface.declarations) - let subModulePrefix = "\(moduleName)." - let subModuleNames = interface.importedModuleNames.filter { $0.hasPrefix(subModulePrefix) } - var allSubModulesSucceeded = true - for subModuleName in subModuleNames { - do { - let subModuleInterface = try await generateInterface(subModuleName) - typeNames.append(contentsOf: InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: subModuleInterface.declarations)) - } catch { - allSubModulesSucceeded = false - #log(.error, "Skipping submodule \(subModuleName, privacy: .public) of \(moduleName, privacy: .public): \(String(describing: error), privacy: .public)") - } - } - let entry = ModuleIndexCacheEntry(moduleName: moduleName, typeNames: typeNames, subModuleNames: subModuleNames) - // A partial entry (a submodule's generation failed, e.g. one - // sourcekitd timeout) is served for THIS run but never cached: - // the cache has no completeness marker, so storing it would - // freeze the gap until the SDK or generator version changes. - if allSubModulesSucceeded { - cache.store(entry) - } else { - #log(.error, "Not caching partial entry for \(moduleName, privacy: .public); submodule extraction will retry next run") - } - return entry - } catch { - #log(.error, "Skipping module \(moduleName, privacy: .public): interface generation failed: \(String(describing: error), privacy: .public)") - return nil - } - } -} - -// Protocol-form `@Loggable` — see the note in SDKIndexer.swift: the direct -// type form clashes with the `@available(macOS 13.0, *)` scope. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "ModuleInterfaceIndexer") -fileprivate protocol ModuleInterfaceIndexerLogging {} - -@available(macOS 13.0, *) -extension ModuleInterfaceIndexer: ModuleInterfaceIndexerLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SDKIndexer.swift b/Sources/Declaration/TypeIndexing/SDKIndexer.swift deleted file mode 100644 index 44291bc2..00000000 --- a/Sources/Declaration/TypeIndexing/SDKIndexer.swift +++ /dev/null @@ -1,121 +0,0 @@ -#if os(macOS) - -import APINotes -import Foundation -import FoundationToolbox - -/// A Swift module discovered in an SDK: just its name and on-disk location. -/// Discovery is deliberately this cheap — interface generation (the expensive -/// sourcekitd work) happens later, only for the modules a binary's dependency -/// filter selects. -@available(macOS 13.0, *) -package struct SwiftModuleDescriptor: Sendable, Hashable { - package let moduleName: String - package let path: String -} - -/// A parsed `.apinotes` file: the compiler's authoritative record of how a -/// module's C declarations surface in Swift (renames, availability). -@available(macOS 13.0, *) -package struct APINotesFile: Sendable { - package let path: String - package let moduleName: String - package let apiNotesModule: APINotes.Module - - package init(path: String) throws { - let apiNotesModule = try APINotes.Module(contentsOf: URL(fileURLWithPath: path)) - self.path = path - self.moduleName = apiNotesModule.name - self.apiNotesModule = apiNotesModule - } -} - -extension APINotes.Module: @unchecked @retroactive Sendable {} - -/// Everything one SDK scan finds: Swift modules (by name and path only) and -/// parsed APINotes files. -@available(macOS 13.0, *) -package struct SDKDiscovery: Sendable { - package let modules: [SwiftModuleDescriptor] - package let apiNotesFiles: [APINotesFile] -} - -/// Walks an SDK's module-bearing directories and reports what is there. -/// -/// This is pure file-system discovery — it never touches sourcekitd, so a full -/// SDK scan is fast. The historical design generated every discovered module's -/// interface *during* the scan, which made first-time indexing hour-scale and -/// made the caller's module filter pointless (evolution proposal 0009). -@available(macOS 13.0, *) -package struct SDKIndexer { - package let platform: SDKPlatform - - /// SDK-relative directories scanned for `.swiftmodule` and `.apinotes` - /// entries, in priority order (an earlier hit wins a module-name tie). - package let searchPaths: [String] - - package init( - platform: SDKPlatform, - searchPaths: [String] = [ - "usr/include", - "usr/lib/swift", - "System/Library/Frameworks", - "System/Library/PrivateFrameworks", - ] - ) { - self.platform = platform - self.searchPaths = searchPaths - } - - package func discover(sdkSettings: SDKSettings) -> SDKDiscovery { - var modulesByName: [String: SwiftModuleDescriptor] = [:] - var orderedModules: [SwiftModuleDescriptor] = [] - var apiNotesFiles: [APINotesFile] = [] - let fileManager = FileManager.default - - for searchPath in searchPaths { - let searchURL = URL(fileURLWithPath: sdkSettings.sdkPath).appending(path: searchPath) - guard fileManager.fileExists(atPath: searchURL.path(percentEncoded: false)) else { continue } - guard let enumerator = fileManager.enumerator(at: searchURL, includingPropertiesForKeys: nil) else { continue } - - while let entryURL = enumerator.nextObject() as? URL { - switch entryURL.pathExtension { - case "swiftmodule": - // A `.swiftmodule` is a directory of per-architecture - // binaries; nothing inside it is a further module. - enumerator.skipDescendants() - let moduleName = entryURL.deletingPathExtension().lastPathComponent - guard modulesByName[moduleName] == nil else { continue } - let descriptor = SwiftModuleDescriptor(moduleName: moduleName, path: entryURL.path(percentEncoded: false)) - modulesByName[moduleName] = descriptor - orderedModules.append(descriptor) - case "apinotes": - do { - let apiNotesFile = try APINotesFile(path: entryURL.path(percentEncoded: false)) - apiNotesFiles.append(apiNotesFile) - } catch { - #log(.error, "Skipping unparsable APINotes file at \(entryURL.path(percentEncoded: false), privacy: .public): \(String(describing: error), privacy: .public)") - } - default: - continue - } - } - } - - #log(.info, "SDK discovery (\(self.platform.rawValue, privacy: .public) \(sdkSettings.cacheDirectoryComponent, privacy: .public)): \(orderedModules.count) Swift modules, \(apiNotesFiles.count) APINotes files") - return SDKDiscovery(modules: orderedModules, apiNotesFiles: apiNotesFiles) - } -} - -// Protocol-form `@Loggable`: the macro's direct type form expands a static -// stored `logger` carrying its own availability annotation, which an -// `@available(macOS 13.0, *)` type rejects ("cannot be more available than -// enclosing scope"). The un-annotated protocol sidesteps that; the annotated -// extension scopes the conformance. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "SDKIndexer") -fileprivate protocol SDKIndexerLogging {} - -@available(macOS 13.0, *) -extension SDKIndexer: SDKIndexerLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SDKPlatform.swift b/Sources/Declaration/TypeIndexing/SDKPlatform.swift deleted file mode 100644 index 562393fd..00000000 --- a/Sources/Declaration/TypeIndexing/SDKPlatform.swift +++ /dev/null @@ -1,115 +0,0 @@ -#if os(macOS) - -import Foundation - -/// An Apple SDK the indexer can point SourceKit at, named by its -/// `xcrun --sdk` identifier. -@available(macOS 13.0, *) -package enum SDKPlatform: String, CaseIterable, Hashable, Codable, Sendable { - case macOS = "macosx" - case iOS = "iphoneos" - case tvOS = "appletvos" - case watchOS = "watchos" - case visionOS = "xros" - case driverKit = "driverkit" - case iOSSimulator = "iphonesimulator" - case tvOSSimulator = "appletvsimulator" - case watchOSSimulator = "watchsimulator" - case visionOSSimulator = "xrsimulator" - - /// The on-disk root of this platform's SDK in the active Xcode. - package func sdkPath() throws -> String { - try Subprocess.xcrun(["--show-sdk-path", "--sdk", rawValue]) - } - - /// The settings of this platform's SDK in the active Xcode. Reads - /// `SDKSettings.plist` once per call; callers cache the result. - package func sdkSettings() throws -> SDKSettings { - try SDKSettings(sdkPath: sdkPath()) - } -} - -/// The subset of an SDK's `SDKSettings.plist` the indexer consumes: enough to -/// form a compiler target triple and to version the on-disk index cache. -@available(macOS 13.0, *) -package struct SDKSettings: Sendable { - package let sdkPath: String - - /// The SDK's marketing version, e.g. `26.5`. - package let version: String - - /// The SDK's build identifier, e.g. `25F76`. Distinguishes beta builds - /// that share a marketing version. Absent from some SDKs. - package let productBuildVersion: String? - - enum Error: Swift.Error { - case malformedSDKSettings(path: String) - } - - /// Test seam: constructs settings without reading an `SDKSettings.plist`. - package init(sdkPath: String, version: String, productBuildVersion: String?) { - self.sdkPath = sdkPath - self.version = version - self.productBuildVersion = productBuildVersion - } - - package init(sdkPath: String) throws { - let settingsPlistURL = URL(fileURLWithPath: sdkPath).appending(component: "SDKSettings.plist") - let settingsPlistData = try Data(contentsOf: settingsPlistURL) - guard - let settingsPlist = try PropertyListSerialization.propertyList(from: settingsPlistData, format: nil) as? [String: Any], - let version = settingsPlist["Version"] as? String - else { - throw Error.malformedSDKSettings(path: settingsPlistURL.path(percentEncoded: false)) - } - self.sdkPath = sdkPath - self.version = version - self.productBuildVersion = settingsPlist["ProductBuildVersion"] as? String - } - - /// One path component identifying this exact SDK build, used to segment - /// the on-disk index cache so an Xcode update never serves stale entries. - package var cacheDirectoryComponent: String { - if let productBuildVersion { - return "\(version)-\(productBuildVersion)" - } - return version - } - - /// The compiler target triple for `platform` at this SDK's version, for - /// the host architecture. - package func targetTriple(for platform: SDKPlatform) -> String { - let architecture: String - #if arch(x86_64) - architecture = "x86_64" - #elseif arch(arm64) - architecture = "arm64" - #else - architecture = "unknown" - #endif - switch platform { - case .macOS: - return "\(architecture)-apple-macos\(version)" - case .iOS: - return "\(architecture)-apple-ios\(version)" - case .tvOS: - return "\(architecture)-apple-tvos\(version)" - case .watchOS: - return "\(architecture)-apple-watchos\(version)" - case .visionOS: - return "\(architecture)-apple-xros\(version)" - case .driverKit: - return "\(architecture)-apple-driverkit\(version)" - case .iOSSimulator: - return "\(architecture)-apple-ios\(version)-simulator" - case .tvOSSimulator: - return "\(architecture)-apple-tvos\(version)-simulator" - case .watchOSSimulator: - return "\(architecture)-apple-watchos\(version)-simulator" - case .visionOSSimulator: - return "\(architecture)-apple-xros\(version)-simulator" - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SourceKitManager.swift b/Sources/Declaration/TypeIndexing/SourceKitManager.swift deleted file mode 100644 index 5e5718e4..00000000 --- a/Sources/Declaration/TypeIndexing/SourceKitManager.swift +++ /dev/null @@ -1,163 +0,0 @@ -#if os(macOS) - -import Csourcekitd -import Foundation -import FoundationToolbox -import SourceKitD - -/// Generates whole-module Swift interfaces through sourcekitd's -/// `editor.open.interface` request — the same request Xcode's generated -/// interface uses, and the only ready-made way to obtain the *Swift view* of a -/// module including its ObjC-imported declarations (the SDK's -/// `.swiftinterface` files carry Swift declarations only). -/// -/// The request is sent with `key.enablesubstructure`, and the response's -/// document-structure tree is converted into plain -/// ``InterfaceDeclarationNode`` values before it leaves this actor, so -/// downstream extraction never touches sourcekitd types. -@available(macOS 13.0, *) -package actor SourceKitManager { - package struct GeneratedModuleInterface: Sendable { - package let moduleName: String - package let sourceText: String - package let declarations: [InterfaceDeclarationNode] - - /// Module names the generated interface imports, in appearance order. - /// Submodule detection (`Foundation.NSObject` inside `Foundation`) - /// filters on these. - package let importedModuleNames: [String] - - package init(moduleName: String, sourceText: String, declarations: [InterfaceDeclarationNode], importedModuleNames: [String]) { - self.moduleName = moduleName - self.sourceText = sourceText - self.declarations = declarations - self.importedModuleNames = importedModuleNames - } - } - - package enum Error: Swift.Error, CustomStringConvertible { - case missingSourceText(moduleName: String) - case missingSubstructure(moduleName: String) - - package var description: String { - switch self { - case .missingSourceText(let moduleName): - return "editor.open.interface returned no source text for module \(moduleName)" - case .missingSubstructure(let moduleName): - return "editor.open.interface returned no substructure for module \(moduleName); the type-name extraction has no input" - } - } - } - - private var cachedSourceKitD: SourceKitD? - - package init() {} - - private func sourcekitd() async throws -> SourceKitD { - if let cachedSourceKitD { - return cachedSourceKitD - } - // Derived from the active developer directory rather than hardcoding - // /Applications/Xcode.app, so Xcode-beta and multi-Xcode setups work. - let developerDirectory = try Subprocess.activeDeveloperDirectory() - let sourcekitdPath = developerDirectory + "/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/Versions/A/sourcekitd" - let sourceKitD = try await SourceKitD.getOrCreate(dylibPath: URL(fileURLWithPath: sourcekitdPath), pluginPaths: nil) - cachedSourceKitD = sourceKitD - return sourceKitD - } - - /// Generates `moduleName`'s interface against `sdkSettings`' SDK and - /// converts the structured response. One sourcekitd request per call; a - /// large module takes seconds, which is why callers index only the - /// modules a binary actually depends on and cache the extraction. - package func interface( - for moduleName: String, - platform: SDKPlatform, - sdkSettings: SDKSettings - ) async throws -> GeneratedModuleInterface { - let sourcekitd = try await sourcekitd() - let keys = sourcekitd.keys - let request = sourcekitd.dictionary([ - keys.moduleName: moduleName, - keys.name: UUID().uuidString, - keys.enableStructure: 1, - keys.compilerArgs: [ - "-sdk", sdkSettings.sdkPath, - "-target", sdkSettings.targetTriple(for: platform), - ] as [any SKDRequestValue], - ]) - let response = try await sourcekitd.send( - \.editorOpenInterface, - request, - timeout: .seconds(120), - restartTimeout: .seconds(120), - documentUrl: nil, - fileContents: nil - ) - guard let sourceText: String = response[keys.sourceText] else { - throw Error.missingSourceText(moduleName: moduleName) - } - guard let substructure: SKDResponseArray = response[keys.subStructure] else { - throw Error.missingSubstructure(moduleName: moduleName) - } - return GeneratedModuleInterface( - moduleName: moduleName, - sourceText: sourceText, - declarations: Self.declarationNodes(of: substructure, in: sourcekitd), - importedModuleNames: Self.importedModuleNames(inInterfaceSourceText: sourceText) - ) - } - - // MARK: - Response Conversion - - private static func declarationNodes(of substructure: SKDResponseArray, in sourcekitd: SourceKitD) -> [InterfaceDeclarationNode] { - var nodes: [InterfaceDeclarationNode] = [] - substructure.forEach { _, nodeDictionary in - let keys = sourcekitd.keys - let kindUID: sourcekitd_api_uid_t? = nodeDictionary[keys.kind] - let kindUIDString = kindUID.flatMap { uid in - sourcekitd.api.uid_get_string_ptr(uid).map { String(cString: $0) } - } - let kind = kindUIDString.map { InterfaceDeclarationNode.kind(forUIDString: $0) } ?? .other - let name: String? = nodeDictionary[keys.name] - // `other` nodes are never descended into by the extractor, so - // their subtrees are dropped here to keep the value tree small. - let children: [InterfaceDeclarationNode] - if kind != .other, let childSubstructure: SKDResponseArray = nodeDictionary[keys.subStructure] { - children = declarationNodes(of: childSubstructure, in: sourcekitd) - } else { - children = [] - } - nodes.append(InterfaceDeclarationNode(kind: kind, name: name, children: children)) - return true - } - return nodes - } - - // MARK: - Import Scan - - /// Line-level scan for `import Module[.Submodule]` in generated interface - /// text. Machine-generated interfaces spell imports one per line - /// (optionally attributed, e.g. `@_exported import ObjectiveC`), so no - /// syntax parsing is needed here. - package static func importedModuleNames(inInterfaceSourceText sourceText: String) -> [String] { - var importedModuleNames: [String] = [] - var seenModuleNames: Set = [] - sourceText.enumerateLines { line, _ in - let trimmedLine = line.trimmingCharacters(in: .whitespaces) - guard !trimmedLine.hasPrefix("//") else { return } - let tokens = trimmedLine.split(separator: " ") - guard let importTokenIndex = tokens.firstIndex(of: "import"), importTokenIndex + 1 < tokens.count else { return } - // Reject lines where `import` is not a keyword at clause start - // (every leading token of a real import is an attribute/modifier). - let leadingTokens = tokens[.. String { - let process = Process() - process.executableURL = URL(fileURLWithPath: executablePath) - process.arguments = arguments - let standardOutputPipe = Pipe() - process.standardOutput = standardOutputPipe - process.standardError = FileHandle.nullDevice - try process.run() - let outputData = standardOutputPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw Error.nonZeroTermination(executablePath: executablePath, arguments: arguments, terminationStatus: process.terminationStatus) - } - guard let outputString = String(data: outputData, encoding: .utf8) else { - throw Error.unreadableOutput(executablePath: executablePath, arguments: arguments) - } - return outputString.trimmingCharacters(in: .whitespacesAndNewlines) - } - - static func xcrun(_ arguments: [String]) throws -> String { - try output(of: "/usr/bin/xcrun", arguments: arguments) - } - - /// The active developer directory (`xcode-select -p`), e.g. - /// `/Applications/Xcode.app/Contents/Developer`. - static func activeDeveloperDirectory() throws -> String { - try output(of: "/usr/bin/xcode-select", arguments: ["-p"]) - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift b/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift deleted file mode 100644 index ef38b186..00000000 --- a/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift +++ /dev/null @@ -1,64 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox - -/// Loads supplementary `.apinotes` files: user-provided type mappings for -/// frameworks the SDK carries no module for (evolution proposal 0010). -/// AttributeGraph is the canonical case — its `AG_SWIFT_NAME` renames live -/// only in headers the SDK never ships, so `AttributeGraph.Graph` is -/// unrecoverable from any binary and must come from external knowledge. -/// -/// The library ships no mappings of its own: hosts supply files or -/// directories (the CLI via `--supplementary-apinotes`, library consumers via -/// the provider's `supplementaryAPINotesURLs:`), loaded in caller order so a -/// later path overwrites an earlier one inside -/// `APINotesIndex.register(files:)`. -/// -/// A file that fails to parse is skipped and logged, never fatal — the same -/// contract SDK APINotes discovery follows. -@available(macOS 13.0, *) -package enum SupplementaryAPINotesLoader { - /// The `.apinotes` files at the supplied locations. Each URL may be a - /// single file or a directory, whose immediate `.apinotes` entries are - /// loaded in file-name order; the URLs themselves keep caller order, so a - /// later path overwrites an earlier one. - package static func files(atSupplementaryLocations locationURLs: [URL]) -> [APINotesFile] { - var fileURLs: [URL] = [] - for locationURL in locationURLs { - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: locationURL.path(percentEncoded: false), isDirectory: &isDirectory) else { - #log(.error, "Skipping missing supplementary APINotes location \(locationURL.path(percentEncoded: false), privacy: .public)") - continue - } - if isDirectory.boolValue { - let entryURLs = (try? FileManager.default.contentsOfDirectory(at: locationURL, includingPropertiesForKeys: nil)) ?? [] - fileURLs.append(contentsOf: entryURLs - .filter { $0.pathExtension == "apinotes" } - .sorted { $0.lastPathComponent < $1.lastPathComponent }) - } else { - fileURLs.append(locationURL) - } - } - var parsedFiles: [APINotesFile] = [] - for fileURL in fileURLs { - do { - parsedFiles.append(try APINotesFile(path: fileURL.path(percentEncoded: false))) - } catch { - #log(.error, "Skipping unparsable supplementary APINotes file at \(fileURL.path(percentEncoded: false), privacy: .public): \(String(describing: error), privacy: .public)") - } - } - return parsedFiles - } -} - -// Protocol-form `@Loggable`: the direct type form's generated static stored -// logger is rejected inside `@available(macOS 13.0, *)` types at -// emit-module time ("cannot be more available than enclosing scope"). -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "SupplementaryAPINotes") -fileprivate protocol SupplementaryAPINotesLogging {} - -@available(macOS 13.0, *) -extension SupplementaryAPINotesLoader: SupplementaryAPINotesLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift deleted file mode 100644 index 6e2c8e52..00000000 --- a/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift +++ /dev/null @@ -1,101 +0,0 @@ -#if os(macOS) - -import Foundation -import MachOKit -import MachOSwiftSection -import ObjCMetadataSource -import SwiftInterface -import SwiftPrinting - -/// The `SwiftInterfaceBuilder` extra-data provider that restores real module -/// names for `__C` / `__ObjC` types: attach it and the printer's -/// `moduleName(forTypeName:)` delegate resolves `__C.NSString` to -/// `Foundation.NSString` through a ``TypeDatabase`` built for the indexed -/// binary's platform and dependency set. -@available(macOS 13.0, *) -public final class SwiftInterfaceBuilderTypeNameProvider: SwiftInterfaceBuilderExtraDataProvider, ModuleNameResolving, CImportedNameResolving, Sendable { - public let machO: MachO - - private let typeDatabase: TypeDatabase - - private let dependencies: SwiftInterfaceBuilderDependencies - - /// Fails when the binary carries no build-version load command mapping to - /// a known SDK platform — without a platform there is no SDK to index. - /// - /// `supplementaryAPINotesURLs` names `.apinotes` files or directories of - /// user-provided type mappings (evolution proposal 0010), loaded after - /// the SDK's own APINotes so they overwrite them. - public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, supplementaryAPINotesURLs: [URL] = []) { - guard let platform = machO.loadCommands.buildVersionCommand?.platform.sdkPlatform else { - return nil - } - self.machO = machO - self.dependencies = dependencies - self.typeDatabase = TypeDatabase(platform: platform, supplementaryAPINotesURLs: supplementaryAPINotesURLs) - } - - public func setup() async throws { - // Index only the SDK modules the binary actually links: the module - // filter is keyed on the dependency images' module names, which is - // what makes first-run indexing minutes-of-modules instead of the - // whole SDK. - let dependencyModuleNames = Set(dependencies.dependencies.map { TypeDatabase.moduleName(forImagePath: $0.imagePath) }) - try await typeDatabase.index(dependencies: dependencies.dependencies) { dependencyModuleNames.contains($0) } - } - - public func moduleName(forTypeName typeName: String) async -> String? { - await typeDatabase.moduleName(forTypeName: typeName) - } - - public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { - await typeDatabase.swiftName(forCName: cName, category: category) - } -} - -@available(macOS 13.0, *) -extension MachOKit.Platform { - var sdkPlatform: SDKPlatform? { - switch self { - case .macOS, - .macCatalyst: - return .macOS - case .driverKit: - return .driverKit - case .iOS: - return .iOS - case .tvOS: - return .tvOS - case .watchOS: - return .watchOS - case .visionOS: - return .visionOS - case .iOSSimulator: - return .iOSSimulator - case .tvOSSimulator: - return .tvOSSimulator - case .watchOSSimulator: - return .watchOSSimulator - case .visionOSSimulator: - return .visionOSSimulator - default: - return nil - } - } -} - -extension LoadCommandsProtocol { - var buildVersionCommand: BuildVersionCommand? { - for command in self { - switch command { - case .buildVersion(let buildVersionCommand): - return buildVersionCommand - default: - break - } - } - return nil - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/TypeDatabase.swift b/Sources/Declaration/TypeIndexing/TypeDatabase.swift deleted file mode 100644 index c1c16652..00000000 --- a/Sources/Declaration/TypeIndexing/TypeDatabase.swift +++ /dev/null @@ -1,266 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox -import MachOKit -import ObjCIndexing -import ObjCMetadataSource -import SwiftPrinting -import MachOKitExtensions - -/// The `__C` module-attribution database: answers "which module declares the -/// type named X" for the ObjC/C-imported types Swift manglings spell as -/// `__C.X` / `__ObjC.X`. -/// -/// Attribution merges three sources, queried in priority order: -/// -/// 1. **Public API** — type names extracted from SourceKit-generated module -/// interfaces (the Swift view of each module, ObjC-imported declarations -/// included), for the modules the indexed binary depends on. -/// 2. **APINotes** — C names registered to their declaring module, covering -/// renamed types whose C spelling never appears in any Swift interface. -/// Written after the interface names, so the compiler's own record wins a -/// conflict. -/// 3. **ObjC metadata (lazy)** — private classes/protocols and harvested C -/// struct/union names read from the binary's dependency images via -/// `ObjCIndexing`. Consulted only on a miss of the first two, one image at -/// a time, stopping at the first hit — declared-in-public-API attribution -/// always outranks "its metadata lives in this image". -@available(macOS 13.0, *) -package actor TypeDatabase { - private let platform: SDKPlatform - - /// User-supplied supplementary APINotes locations (files or directories), - /// loaded after the SDK's own APINotes so they overwrite them (evolution - /// proposal 0010). The library ships no mappings of its own. - private let supplementaryAPINotesURLs: [URL] - - private let sourceKitManager = SourceKitManager() - - /// Type name → declaring module, merged from interfaces then APINotes. - private var moduleNamesByTypeName: [String: String] = [:] - - /// Type name → image-derived module, filled lazily from `ObjCIndexing`. - private var objcModuleNamesByTypeName: [String: String] = [:] - - private var apiNotesIndex = APINotesIndex(files: []) - - /// Dependency images not yet ObjC-indexed, in dependency order. Popped - /// one at a time as misses demand; an image whose indexing fails is - /// dropped (logged), not retried. - private var unindexedDependencies: [MachO] = [] - - package init(platform: SDKPlatform, supplementaryAPINotesURLs: [URL] = []) { - self.platform = platform - self.supplementaryAPINotesURLs = supplementaryAPINotesURLs - } - - // MARK: - Indexing - - /// Builds the database: discovers the SDK (cheap), then generates and - /// extracts interfaces only for modules passing `moduleFilter` (expensive, - /// cached per module per SDK build), registers APINotes attribution, and - /// records `dependencies` for lazy ObjC indexing. - package func index(dependencies: [MachO], moduleFilter: @Sendable (String) -> Bool) async throws { - let sdkSettings = try platform.sdkSettings() - let discovery = SDKIndexer(platform: platform).discover(sdkSettings: sdkSettings) - - let filteredModules = discovery.modules.filter { moduleFilter($0.moduleName) } - let moduleInterfaceIndexer = ModuleInterfaceIndexer( - platform: platform, - sdkSettings: sdkSettings, - cache: ModuleIndexCache(platform: platform, sdkSettings: sdkSettings), - sourceKitManager: sourceKitManager - ) - let collectedEntries = await withTaskGroup(of: ModuleIndexCacheEntry?.self) { group in - for moduleDescriptor in filteredModules { - group.addTask { - await moduleInterfaceIndexer.indexEntry(forModuleNamed: moduleDescriptor.moduleName) - } - } - var entries: [ModuleIndexCacheEntry] = [] - for await entry in group { - if let entry { - entries.append(entry) - } - } - return entries - } - let orderedEntries = Self.entriesInDiscoveryOrder(collectedEntries, discoveryOrder: filteredModules.map(\.moduleName)) - - register(moduleEntries: orderedEntries) - register(apiNotesIndex: APINotesIndex(files: discovery.apiNotesFiles)) - register(supplementaryAPINotesFiles: SupplementaryAPINotesLoader.files(atSupplementaryLocations: supplementaryAPINotesURLs)) - register(dependencies: dependencies) - } - - /// Restores discovery order over task-group results: the group yields - /// entries in COMPLETION order, which varies with per-module cache hits — - /// but registration is last-writer-wins, so it must follow the discovery - /// order (SDKIndexer's search-path priority: "an earlier hit wins a - /// module-name tie"), or two runs could attribute a tied name - /// differently. - package static func entriesInDiscoveryOrder(_ collectedEntries: [ModuleIndexCacheEntry], discoveryOrder moduleNames: [String]) -> [ModuleIndexCacheEntry] { - let entriesByModuleName = Dictionary(collectedEntries.map { ($0.moduleName, $0) }, uniquingKeysWith: { firstEntry, _ in firstEntry }) - return moduleNames.compactMap { entriesByModuleName[$0] } - } - - /// Registers interface-extracted type names. Exposed as a step so merge - /// priority is unit-testable without sourcekitd. - package func register(moduleEntries: [ModuleIndexCacheEntry]) { - for entry in moduleEntries { - for typeName in entry.typeNames { - moduleNamesByTypeName[typeName] = entry.moduleName - } - } - } - - /// Registers APINotes attribution (C name → declaring module), overriding - /// any interface-derived entry for the same name. - package func register(apiNotesIndex: APINotesIndex) { - self.apiNotesIndex = apiNotesIndex - registerAttribution(fromAPINotesIndex: apiNotesIndex) - } - - /// Registers supplementary APINotes bundles (evolution proposal 0010) on - /// top of whatever is already indexed: their entries append into the same - /// `APINotesIndex`, where later files overwrite earlier same-name entries - /// — so calling this after `register(apiNotesIndex:)` gives supplementary - /// mappings the last word over SDK ones. Attribution is then re-synced - /// from the index, whose internal ordering already reflects the override. - package func register(supplementaryAPINotesFiles supplementaryFiles: [APINotesFile]) { - apiNotesIndex.register(files: supplementaryFiles) - registerAttribution(fromAPINotesIndex: apiNotesIndex) - } - - private func registerAttribution(fromAPINotesIndex attributionIndex: APINotesIndex) { - for (cName, moduleName) in attributionIndex.moduleNamesByCName { - moduleNamesByTypeName[cName] = moduleName - } - // Swift spellings too, after the C spellings. A printed `__C` name no - // longer carries one: a foreign descriptor records the imported - // spelling (`Graph` for an `AG_SWIFT_NAME(Graph)` type), but the - // demangler names it by the ABI name in its import info (evolution - // proposal `type-import-info-identity`). What this pass still decides - // is a C name several modules' APINotes list. Foundation's and - // AppKit's list `NSObject` only to annotate category methods, and the - // pass above lets whichever file came last win; ObjectiveC's entry - // renames `NSObject` to itself, so registering that spelling last - // gives the class back to ObjectiveC. Nested renames - // (`ProcessInfo.ActivityOptions`) never appear as one identifier and - // are skipped. - for (swiftName, originalCName) in attributionIndex.cNamesBySwiftName where !swiftName.contains(".") { - moduleNamesByTypeName[swiftName] = originalCName.moduleName - } - } - - /// Records the images consulted lazily for private-type attribution. - package func register(dependencies: [MachO]) { - unindexedDependencies = dependencies - } - - // MARK: - Query - - package func moduleName(forTypeName typeName: String) async -> String? { - if let moduleName = moduleNamesByTypeName[typeName] { - return moduleName - } - if let moduleName = objcModuleNamesByTypeName[typeName] { - return moduleName - } - // Lazy ObjC indexing: fold in one dependency image at a time until - // the name resolves or the images run out. Misses after exhaustion - // cost one dictionary probe, since nothing remains unindexed. - while !unindexedDependencies.isEmpty { - let machO = unindexedDependencies.removeFirst() - await indexObjCMetadata(of: machO) - if let moduleName = objcModuleNamesByTypeName[typeName] { - return moduleName - } - } - return nil - } - - /// The Swift spelling of a C-imported type name, when it differs from the - /// C one. Two sources, in order: - /// - /// 1. **APINotes renames**, per declaration category (`NSDecimal` → - /// `Decimal`; the protocol-only `NSObject` → `NSObjectProtocol` rename - /// never touches class references). - /// 2. **The CF bridge rule**: ClangImporter imports a `CF…Ref` typedef as - /// the `Ref`-stripped native class (`CFStringRef` → `CFString`), while - /// manglings record the C spelling. The stripped name qualifies only - /// when it actually exists in the attribution table — so an ObjC class - /// that merely happens to end in `Ref` is never rewritten — and never - /// applies to protocol references (there is no CF protocol convention). - package func swiftName(forCName cName: String, category: CImportedTypeNameCategory) -> String? { - if let renamedName = apiNotesIndex.swiftName(forCName: cName, category: category) { - return renamedName.name - } - if category != .objcProtocol, cName.hasSuffix("Ref") { - let strippedName = String(cName.dropLast(3)) - if !strippedName.isEmpty, moduleNamesByTypeName[strippedName] != nil { - return strippedName - } - } - return nil - } - - // MARK: - Lazy ObjC Indexing - - private func indexObjCMetadata(of machO: MachO) async { - let imagePath = machO.imagePath - let moduleName = Self.moduleName(forImagePath: imagePath) - let objcInterfaceIndexer = ObjCInterfaceIndexer(machO: machO, imagePath: imagePath) - do { - try await objcInterfaceIndexer.prepare() - } catch { - #log(.error, "Skipping ObjC metadata of \(imagePath, privacy: .public): \(String(describing: error), privacy: .public)") - return - } - let discoveredNames = objcInterfaceIndexer.classNames - + objcInterfaceIndexer.protocolNames - + objcInterfaceIndexer.structNames - + objcInterfaceIndexer.unionNames - for discoveredName in discoveredNames { - // Never overwrite: the declaring image is whichever dependency - // came first in dependency order, and interface/APINotes - // attribution is consulted before this table anyway. - if objcModuleNamesByTypeName[discoveredName] == nil { - objcModuleNamesByTypeName[discoveredName] = moduleName - } - } - } - - /// `…/Foundation.framework/Foundation` → `Foundation`, - /// `libswiftFoundation.dylib` → `Foundation`, `libobjc.A.dylib` → - /// `libobjc`: every path extension is stripped, then the `libswift` - /// overlay prefix is removed. - package static func moduleName(forImagePath imagePath: String) -> String { - var name = URL(fileURLWithPath: imagePath).lastPathComponent - while name.contains(".") { - // A leading-dot name is a fixed point of extension stripping - // (`.hidden` → `.hidden`) — without this guard the loop spins - // forever on such an install name. - let strippedName = URL(fileURLWithPath: name).deletingPathExtension().lastPathComponent - guard strippedName != name, !strippedName.isEmpty else { break } - name = strippedName - } - if name.hasPrefix("libswift") { - name = String(name.dropFirst("libswift".count)) - } - return name - } -} - -// Protocol-form `@Loggable`, required twice over: the type is generic (the -// direct form's static stored logger is illegal there) and carries an -// `@available(macOS 13.0, *)` scope the macro's own annotations would exceed. -// The protocol itself stays un-annotated for the latter reason. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "TypeDatabase") -fileprivate protocol TypeDatabaseLogging {} - -@available(macOS 13.0, *) -extension TypeDatabase: TypeDatabaseLogging {} - -#endif diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift index 98fe967e..a2ddd34a 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift @@ -7,7 +7,7 @@ import MachODependencies import MachOSwiftSection import MachOFoundation -/// The images a provider such as TypeIndexing's +/// The images a provider such as `SwiftTypeNameResolution`'s /// `SwiftInterfaceBuilderTypeNameProvider` works against: the root plus its /// **direct** dependencies only. /// diff --git a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift new file mode 100644 index 00000000..94820d4b --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift @@ -0,0 +1,66 @@ +#if os(macOS) + +import Foundation +import MachOKit +import MachOKitExtensions +import MachOSwiftSection +import ObjCMetadataSource +import ObjCTypeIndexing +import SwiftInterface +import SwiftPrinting +import TypeIndexing + +/// The `SwiftInterfaceBuilder` extra-data provider that resolves `__C` / +/// `__ObjC` types: attach it and `__C.NSString` prints as +/// `Foundation.NSString`, `__C.UICellConfigurationState` as +/// `UIKit.__UICellConfigurationState`, through a swift-type-indexing +/// `TypeDatabase` built for the indexed binary's platform and dependency set. +@available(macOS 13.0, *) +public final class SwiftInterfaceBuilderTypeNameProvider: SwiftInterfaceBuilderExtraDataProvider, ModuleNameResolving, CImportedNameResolving, Sendable { + public let machO: MachO + + private let resolver: TypeDatabaseTypeNameResolver + + private let dependencies: SwiftInterfaceBuilderDependencies + + /// Fails when the binary carries no build-version load command mapping to + /// a known SDK platform — without a platform there is no SDK to index. + /// + /// `supplementaryAPINotesURLs` names `.apinotes` files or directories of + /// user-provided type mappings (evolution proposal 0010), loaded after + /// the SDK's own APINotes so they overwrite them. + public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, supplementaryAPINotesURLs: [URL] = []) { + guard + let buildPlatform = machO.loadCommands.buildVersionCommand?.platform, + let platform = SDKPlatform(buildPlatform) + else { + return nil + } + self.machO = machO + self.dependencies = dependencies + self.resolver = TypeDatabaseTypeNameResolver(typeDatabase: TypeDatabase(platform: platform, supplementaryAPINotesURLs: supplementaryAPINotesURLs)) + } + + public func setup() async throws { + // Index only the SDK modules the binary actually links: the module + // filter is keyed on the dependency images' module names, which is + // what makes first-run indexing minutes-of-modules instead of the + // whole SDK. + let dependencyImages = dependencies.dependencies + let dependencyModuleNames = Set(dependencyImages.map { TypeDatabase.moduleName(forImagePath: $0.imagePath) }) + try await resolver.typeDatabase.index( + dependencies: dependencyImages.map { ObjCDeclaredTypeNames(machO: $0, imagePath: $0.imagePath) }, + moduleFilter: { dependencyModuleNames.contains($0) } + ) + } + + public func moduleName(forTypeName typeName: String) async -> String? { + await resolver.moduleName(forTypeName: typeName) + } + + public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { + await resolver.swiftName(forCName: cName, category: category) + } +} + +#endif diff --git a/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift new file mode 100644 index 00000000..9184e2c9 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift @@ -0,0 +1,89 @@ +#if os(macOS) + +import MachOKit +import SwiftPrinting +import TypeIndexing + +/// Answers the printer's questions about `__C` types from a swift-type-indexing +/// `TypeDatabase`: which module declares a type (`__C.UITraitCollection` → +/// `UIKit.UITraitCollection`) and what Swift calls it +/// (`__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`). +/// +/// Register it on a `SwiftDeclarationPrinter` with `addTypeNameResolver(_:)`. +/// Several printers may share one database: the database is an actor, and a +/// resolver holds nothing else. +/// +/// ```swift +/// let typeDatabase = TypeDatabase(platform: .macCatalyst) +/// try await typeDatabase.index(dependencies: [], moduleFilter: { $0 == "UIKit" }) +/// printer.addTypeNameResolver(TypeDatabaseTypeNameResolver(typeDatabase: typeDatabase)) +/// ``` +@available(macOS 13.0, *) +public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameResolving { + public let typeDatabase: TypeDatabase + + public init(typeDatabase: TypeDatabase) { + self.typeDatabase = typeDatabase + } + + public func moduleName(forTypeName typeName: String) async -> String? { + await typeDatabase.moduleName(forTypeName: typeName) + } + + public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { + await typeDatabase.swiftName(forCName: cName, category: ImportedTypeNameCategory(category)) + } +} + +extension ImportedTypeNameCategory { + /// The category swift-type-indexing looks a name up in for the printer's + /// category of a reference. The two enumerate the same namespaces. + public init(_ printerCategory: CImportedTypeNameCategory) { + switch printerCategory { + case .objcClass: + self = .objcClass + case .objcProtocol: + self = .objcProtocol + case .valueType: + self = .valueType + case .other: + self = .other + } + } +} + +extension SDKPlatform { + /// The SDK an image built for `platform` is read against, or `nil` for a + /// platform no SDK covers. Mac Catalyst has its own case: its frameworks + /// and API notes are the macOS SDK's `System/iOSSupport` ones. + public init?(_ platform: MachOKit.Platform) { + switch platform { + case .macOS: + self = .macOS + case .macCatalyst: + self = .macCatalyst + case .driverKit: + self = .driverKit + case .iOS: + self = .iOS + case .tvOS: + self = .tvOS + case .watchOS: + self = .watchOS + case .visionOS: + self = .visionOS + case .iOSSimulator: + self = .iOSSimulator + case .tvOSSimulator: + self = .tvOSSimulator + case .watchOSSimulator: + self = .watchOSSimulator + case .visionOSSimulator: + self = .visionOSSimulator + default: + return nil + } + } +} + +#endif diff --git a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift index 14d880a5..dbb26c3d 100644 --- a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift +++ b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift @@ -6,21 +6,22 @@ import MachOKit import MachOSwiftSection import SwiftInterface import Testing -import TypeIndexing +import SwiftTypeNameResolution @testable import SwiftSectionTestingSupport import MachODependencies import SwiftPrinting import SwiftIndexing import Semantic -/// Maintainer-run end-to-end for the TypeIndexing provider (evolution -/// proposal 0008): builds the fixture's interface with and without +/// Maintainer-run end-to-end for the `__C` type-name provider (evolution +/// proposal 0008, moved onto swift-type-indexing by proposal +/// swift-type-indexing-package): builds the fixture's interface with and without /// `SwiftInterfaceBuilderTypeNameProvider` attached and prints every line the /// provider changed, plus any `__C.` reference left unresolved. /// /// The first run per SDK build generates the linked modules' interfaces /// through sourcekitd (tens of seconds) and caches the extraction under -/// `Application Support/MachOSwiftSection/SDKIndexer/`. +/// `Application Support/swift-type-indexing/SDKIndexer/`. final class TypeNameProviderMachOFileTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift index 19d4d3f1..5d262944 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift @@ -241,7 +241,7 @@ struct SymbolicDemanglerFixedShapeExtractionTests { // The protocol Swift spells `NSObjectProtocol` is the ObjC protocol // `NSObject`; the reference record mangles the ObjC runtime name // (`So8NSObject_p`), and the Swift-side rename is APINotes' business - // (TypeIndexing), not the demangler's. + // (swift-type-indexing), not the demangler's. let printed = node.print(using: .default) #expect(printed == "__C.NSCopying & __C.NSObject") diff --git a/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift new file mode 100644 index 00000000..1e0e575b --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift @@ -0,0 +1,71 @@ +#if os(macOS) + +import Foundation +import MachOKit +import SwiftPrinting +import Testing +import TypeIndexing +@testable import SwiftTypeNameResolution + +/// The adapter between swift-type-indexing's `TypeDatabase` and the printer's +/// type-name resolver roles. +@Suite +struct TypeDatabaseTypeNameResolverTests { + @Test + func resolverMapsEveryPrinterCategory() { + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.objcClass) == .objcClass) + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.objcProtocol) == .objcProtocol) + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.valueType) == .valueType) + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.other) == .other) + } + + /// A Mac Catalyst binary reads the macOS SDK through `System/iOSSupport`: + /// mapped to `.macOS`, as before the index moved out, its UIKit types + /// found no API notes. + @Test + func buildPlatformsMapToTheirSDKs() { + #expect(SDKPlatform(MachOKit.Platform.macOS) == .macOS) + #expect(SDKPlatform(MachOKit.Platform.macCatalyst) == .macCatalyst) + #expect(SDKPlatform(MachOKit.Platform.iOS) == .iOS) + #expect(SDKPlatform(MachOKit.Platform.iOSSimulator) == .iOSSimulator) + } + + /// The printer's two questions, answered from API notes: the declaring + /// module, and the Swift name of a `SwiftPrivate` class and of a + /// protocol-only rename. Reads this Mac's macOS SDK (API notes only, no + /// sourcekitd) plus a supplementary file. + @Test + func resolverAnswersModuleAndSwiftName() async throws { + guard #available(macOS 13.0, *) else { return } + let temporaryDirectoryURL = FileManager.default.temporaryDirectory + .appending(component: "TypeDatabaseTypeNameResolverTests-\(UUID().uuidString)") + let apiNotesDirectoryURL = temporaryDirectoryURL.appending(component: "APINotes") + try FileManager.default.createDirectory(at: apiNotesDirectoryURL, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: temporaryDirectoryURL) } + try """ + Name: SampleKit + Classes: + - Name: SMPHiddenState + SwiftPrivate: true + Protocols: + - Name: SMPDelegate + SwiftName: SampleDelegate + """.write(to: apiNotesDirectoryURL.appending(component: "SampleKit.apinotes"), atomically: true, encoding: .utf8) + + let typeDatabase = TypeDatabase( + platform: .macOS, + cacheDirectory: temporaryDirectoryURL.appending(component: "Cache"), + supplementaryAPINotesURLs: [apiNotesDirectoryURL] + ) + try await typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + let resolver = TypeDatabaseTypeNameResolver(typeDatabase: typeDatabase) + + #expect(await resolver.moduleName(forTypeName: "SMPHiddenState") == "SampleKit") + #expect(await resolver.swiftName(forCName: "SMPHiddenState", category: .objcClass) == "__SMPHiddenState") + #expect(await resolver.swiftName(forCName: "SMPDelegate", category: .objcProtocol) == "SampleDelegate") + #expect(await resolver.swiftName(forCName: "SMPDelegate", category: .objcClass) == nil) + #expect(await resolver.moduleName(forTypeName: "NSObject") == "ObjectiveC") + } +} + +#endif diff --git a/Tests/TypeIndexingTests/APINotesIndexTests.swift b/Tests/TypeIndexingTests/APINotesIndexTests.swift deleted file mode 100644 index 93e30ee5..00000000 --- a/Tests/TypeIndexingTests/APINotesIndexTests.swift +++ /dev/null @@ -1,101 +0,0 @@ -#if os(macOS) - -import Foundation -import SwiftPrinting -import Testing -@testable import TypeIndexing - -@Suite -struct APINotesIndexTests { - /// Writes a minimal APINotes YAML to a temporary file and parses it the - /// same way SDK discovery does. - private static func makeIndex() throws -> APINotesIndex { - let apiNotesYAML = """ - Name: TestModule - Classes: - - Name: TSTRenamedThing - SwiftName: RenamedThing - - Name: TSTPlainThing - - Name: TSTPrivateThing - SwiftName: __PrivateThing - SwiftPrivate: true - Tags: - - Name: TSTOptions - SwiftName: RenamedThing.Options - Typedefs: - - Name: TSTIdentifier - """ - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "APINotesIndexTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - defer { try? FileManager.default.removeItem(at: temporaryFileURL) } - let apiNotesFile = try APINotesFile(path: temporaryFileURL.path(percentEncoded: false)) - return APINotesIndex(files: [apiNotesFile]) - } - - /// The historical implementation stored the *Swift name* into the - /// `moduleName` field of the C-name → Swift-name mapping, so the declaring - /// module was unrecoverable. The declaring module must be the module whose - /// APINotes file carries the entry. - @Test - func swiftNameLookupCarriesTheDeclaringModule() throws { - let index = try Self.makeIndex() - let swiftName = index.swiftName(forCName: "TSTRenamedThing", category: .objcClass) - #expect(swiftName?.name == "RenamedThing") - #expect(swiftName?.moduleName == "TestModule") - } - - /// ObjC declares both a class and a protocol named `NSObject`, and only - /// the protocol is renamed — the tables must be category-isolated so the - /// protocol's rename never rewrites class references. - @Test - func renameTablesAreCategoryIsolated() throws { - let apiNotesYAML = """ - Name: ObjectiveC - Classes: - - Name: NSObject - Protocols: - - Name: NSObject - SwiftName: NSObjectProtocol - """ - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "APINotesIndexTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - defer { try? FileManager.default.removeItem(at: temporaryFileURL) } - let index = try APINotesIndex(files: [APINotesFile(path: temporaryFileURL.path(percentEncoded: false))]) - - #expect(index.swiftName(forCName: "NSObject", category: .objcProtocol)?.name == "NSObjectProtocol") - #expect(index.swiftName(forCName: "NSObject", category: .objcClass) == nil) - #expect(index.swiftName(forCName: "NSObject", category: .other) == nil) - } - - @Test - func cNameLookupIsTheReverseDirection() throws { - let index = try Self.makeIndex() - let cName = index.cName(forSwiftName: "RenamedThing.Options") - #expect(cName?.name == "TSTOptions") - #expect(cName?.moduleName == "TestModule") - } - - @Test - func everyListedEntityGetsModuleAttributionRenamedOrNot() throws { - let index = try Self.makeIndex() - #expect(index.moduleName(forCName: "TSTRenamedThing") == "TestModule") - #expect(index.moduleName(forCName: "TSTPlainThing") == "TestModule") - #expect(index.moduleName(forCName: "TSTOptions") == "TestModule") - #expect(index.moduleName(forCName: "TSTIdentifier") == "TestModule") - #expect(index.moduleName(forCName: "TSTUnknown") == nil) - } - - /// `SwiftPrivate` entities keep their module attribution (their C name - /// still appears in manglings) but stay out of the rename tables. - @Test - func swiftPrivateEntitiesAreAttributedButNotRenamed() throws { - let index = try Self.makeIndex() - #expect(index.moduleName(forCName: "TSTPrivateThing") == "TestModule") - #expect(index.swiftName(forCName: "TSTPrivateThing", category: .objcClass) == nil) - #expect(index.cName(forSwiftName: "__PrivateThing") == nil) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/ImportScanTests.swift b/Tests/TypeIndexingTests/ImportScanTests.swift deleted file mode 100644 index ba45dfb5..00000000 --- a/Tests/TypeIndexingTests/ImportScanTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -#if os(macOS) - -import Testing -@testable import TypeIndexing - -@Suite -struct ImportScanTests { - @Test - func plainAndAttributedImportsAreCollectedInOrder() { - let sourceText = """ - import Foundation - @_exported import ObjectiveC - public import CoreGraphics - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText) == [ - "Foundation", - "ObjectiveC", - "CoreGraphics", - ]) - } - - @Test - func subModuleImportsKeepTheirDottedSpelling() { - let sourceText = """ - import Foundation.NSObject - import Foundation.NSString - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText) == [ - "Foundation.NSObject", - "Foundation.NSString", - ]) - } - - @Test - func duplicatesCommentsAndNonImportLinesAreIgnored() { - let sourceText = """ - // import CommentedOut - import Foundation - import Foundation - let importCount = 1 - func doSomething() { } - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText) == ["Foundation"]) - } - - @Test - func importAppearingAfterNonModifierTokensIsRejected() { - let sourceText = """ - let value = import Foundation - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText).isEmpty) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift b/Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift deleted file mode 100644 index d4e855b6..00000000 --- a/Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift +++ /dev/null @@ -1,113 +0,0 @@ -#if os(macOS) - -import Testing -@testable import TypeIndexing - -@Suite -struct InterfaceTypeNameExtractorTests { - private typealias Node = InterfaceDeclarationNode - - @Test - func topLevelTypeDeclarationsAreCollected() { - let declarations = [ - Node(kind: .typeDeclaration, name: "NSString"), - Node(kind: .typeDeclaration, name: "NSURLSession"), - Node(kind: .typeAlias, name: "NSStringEncoding"), - Node(kind: .other, name: "someGlobalFunction()"), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == [ - "NSString", - "NSURLSession", - "NSStringEncoding", - ]) - } - - @Test - func nestedTypesAreQualifiedByTheirParentChain() { - let declarations = [ - Node(kind: .typeDeclaration, name: "Outer", children: [ - Node(kind: .typeDeclaration, name: "Inner", children: [ - Node(kind: .typeDeclaration, name: "Innermost"), - ]), - Node(kind: .other, name: "someMethod()"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == [ - "Outer", - "Outer.Inner", - "Outer.Inner.Innermost", - ]) - } - - /// The historical SwiftSyntax-based parser registered a type declared in - /// an extension under its bare name — `extension Foo { struct Bar }` - /// produced a `Bar` key. The extractor must qualify through the extended - /// type instead. - @Test - func typesNestedInExtensionsAreQualifiedByTheExtendedTypeName() { - let declarations = [ - Node(kind: .extension, name: "Foo", children: [ - Node(kind: .typeDeclaration, name: "Bar"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == ["Foo.Bar"]) - } - - @Test - func dotQualifiedExtendedTypeNamesQualifyTransitively() { - let declarations = [ - Node(kind: .extension, name: "Foo.Bar", children: [ - Node(kind: .typeDeclaration, name: "Baz"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == ["Foo.Bar.Baz"]) - } - - @Test - func extensionsThemselvesAreNotIndexedNames() { - let declarations = [ - Node(kind: .extension, name: "NSString", children: [ - Node(kind: .other, name: "someMethod()"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations).isEmpty) - } - - @Test - func otherNodesAreNeverDescendedInto() { - let declarations = [ - Node(kind: .other, name: "someGlobalFunction()", children: [ - Node(kind: .typeDeclaration, name: "LocalTypeThatMustNotLeak"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations).isEmpty) - } - - @Test - func namelessDeclarationsAreSkipped() { - let declarations = [ - Node(kind: .typeDeclaration, name: nil), - Node(kind: .typeDeclaration, name: ""), - Node(kind: .typeDeclaration, name: "Survivor"), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == ["Survivor"]) - } - - @Test - func sourceKitDeclarationKindsMapOntoTheExtractorVocabulary() { - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.struct") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.class") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.actor") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.enum") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.protocol") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.typealias") == .typeAlias) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.extension") == .extension) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.extension.struct") == .extension) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.function.method.instance") == .other) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.var.instance") == .other) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.enumcase") == .other) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.associatedtype") == .other) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/ModuleIndexCacheTests.swift b/Tests/TypeIndexingTests/ModuleIndexCacheTests.swift deleted file mode 100644 index de90ab54..00000000 --- a/Tests/TypeIndexingTests/ModuleIndexCacheTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -#if os(macOS) - -import Foundation -import Testing -@testable import TypeIndexing - -@Suite -struct ModuleIndexCacheTests { - private static func makeTemporaryCache() -> ModuleIndexCache { - ModuleIndexCache( - directoryURL: FileManager.default.temporaryDirectory - .appending(component: "ModuleIndexCacheTests-\(UUID().uuidString)") - ) - } - - @Test - func storedEntriesRoundTrip() { - let cache = Self.makeTemporaryCache() - defer { try? FileManager.default.removeItem(at: cache.directoryURL) } - let entry = ModuleIndexCacheEntry( - moduleName: "Foundation", - typeNames: ["NSString", "NSURLSession.Configuration"], - subModuleNames: ["Foundation.NSObject"] - ) - cache.store(entry) - let loadedEntry = cache.entry(forModuleNamed: "Foundation") - #expect(loadedEntry?.moduleName == "Foundation") - #expect(loadedEntry?.typeNames == ["NSString", "NSURLSession.Configuration"]) - #expect(loadedEntry?.subModuleNames == ["Foundation.NSObject"]) - } - - @Test - func missingEntriesReadAsNil() { - let cache = Self.makeTemporaryCache() - #expect(cache.entry(forModuleNamed: "NeverStored") == nil) - } - - /// An entry written by an older extractor must not survive a generator - /// bump — stale extraction semantics regenerate instead of being served. - @Test - func mismatchedGeneratorVersionInvalidatesTheEntry() { - let cache = Self.makeTemporaryCache() - defer { try? FileManager.default.removeItem(at: cache.directoryURL) } - let outdatedEntry = ModuleIndexCacheEntry( - moduleName: "Foundation", - typeNames: ["NSString"], - subModuleNames: [], - generatorVersion: ModuleIndexCacheEntry.currentGeneratorVersion - 1 - ) - cache.store(outdatedEntry) - #expect(cache.entry(forModuleNamed: "Foundation") == nil) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift b/Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift deleted file mode 100644 index 5c048c80..00000000 --- a/Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift +++ /dev/null @@ -1,93 +0,0 @@ -#if os(macOS) - -import Foundation -import Testing -@testable import TypeIndexing - -/// The cache-write discipline of `ModuleInterfaceIndexer`, driven through its -/// interface-generator test seam — no sourcekitd. -@Suite -struct ModuleInterfaceIndexerTests { - private static func makeCache() throws -> ModuleIndexCache { - let directoryURL = FileManager.default.temporaryDirectory - .appending(component: "ModuleInterfaceIndexerTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) - return ModuleIndexCache(directoryURL: directoryURL) - } - - private static func makeIndexer(cache: ModuleIndexCache, interfaceGenerator: @escaping ModuleInterfaceIndexer.InterfaceGenerator) -> ModuleInterfaceIndexer { - ModuleInterfaceIndexer( - platform: .macOS, - sdkSettings: SDKSettings(sdkPath: "/nonexistent-sdk", version: "0.0", productBuildVersion: nil), - cache: cache, - interfaceGenerator: interfaceGenerator - ) - } - - private static func interface(moduleName: String, typeNames: [String], importedModuleNames: [String] = []) -> SourceKitManager.GeneratedModuleInterface { - SourceKitManager.GeneratedModuleInterface( - moduleName: moduleName, - sourceText: "", - declarations: typeNames.map { InterfaceDeclarationNode(kind: .typeDeclaration, name: $0) }, - importedModuleNames: importedModuleNames - ) - } - - enum StubError: Error { - case submoduleTimedOut - } - - /// A submodule whose generation fails degrades the entry for THIS run but - /// must not be cached: the cache has no completeness marker, so a stored - /// partial entry would freeze the gap until the SDK or generator version - /// changes (PR #110 review, finding 4). - @Test - func partialEntryIsServedButNeverCached() async throws { - let cache = try Self.makeCache() - let indexer = Self.makeIndexer(cache: cache) { moduleName in - if moduleName == "Foo" { - return Self.interface(moduleName: "Foo", typeNames: ["FooType"], importedModuleNames: ["Foo.Sub", "Unrelated"]) - } - throw StubError.submoduleTimedOut - } - - let entry = await indexer.indexEntry(forModuleNamed: "Foo") - #expect(entry?.typeNames == ["FooType"]) - #expect(cache.entry(forModuleNamed: "Foo") == nil) - } - - @Test - func completeEntryIsCached() async throws { - let cache = try Self.makeCache() - let indexer = Self.makeIndexer(cache: cache) { moduleName in - switch moduleName { - case "Foo": - return Self.interface(moduleName: "Foo", typeNames: ["FooType"], importedModuleNames: ["Foo.Sub"]) - case "Foo.Sub": - return Self.interface(moduleName: "Foo.Sub", typeNames: ["SubType"]) - default: - throw StubError.submoduleTimedOut - } - } - - let entry = await indexer.indexEntry(forModuleNamed: "Foo") - #expect(entry?.typeNames == ["FooType", "SubType"]) - #expect(cache.entry(forModuleNamed: "Foo")?.typeNames == ["FooType", "SubType"]) - } - - /// The whole module failing still returns `nil` and caches nothing — the - /// pre-existing contract, pinned alongside the partial-entry rule. - @Test - func failedModuleCachesNothing() async throws { - let cache = try Self.makeCache() - let indexer = Self.makeIndexer(cache: cache) { _ in - throw StubError.submoduleTimedOut - } - - let entry = await indexer.indexEntry(forModuleNamed: "Foo") - #expect(entry == nil) - #expect(cache.entry(forModuleNamed: "Foo") == nil) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift b/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift deleted file mode 100644 index 08036a70..00000000 --- a/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift +++ /dev/null @@ -1,200 +0,0 @@ -#if os(macOS) - -import Foundation -import MachOKit -import SwiftPrinting -import Testing -@testable import TypeIndexing - -/// Supplementary APINotes files (evolution proposal 0009): user-provided -/// mappings for frameworks with no SDK module, and the merge priority that -/// lets them override SDK entries. The library ships no mappings of its own. -@Suite -struct SupplementaryAPINotesTests { - private static func writeAPINotesFile(yaml apiNotesYAML: String, into directoryURL: URL, named fileName: String) throws -> URL { - let fileURL = directoryURL.appending(component: fileName) - try apiNotesYAML.write(to: fileURL, atomically: true, encoding: .utf8) - return fileURL - } - - private static func makeTemporaryDirectory() throws -> URL { - let directoryURL = FileManager.default.temporaryDirectory - .appending(component: "SupplementaryAPINotesTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) - return directoryURL - } - - /// The AttributeGraph-shaped mapping every example in the contribution - /// guide is written against: both C spellings of each CF-bridged type. - private static let attributeGraphYAML = """ - Name: AttributeGraph - Typedefs: - - Name: AGGraphRef - SwiftName: Graph - - Name: AGSubgraphRef - SwiftName: Subgraph - Tags: - - Name: AGGraphStorage - SwiftName: Graph - - Name: AGSubgraphStorage - SwiftName: Subgraph - """ - - /// The end-to-end data flow for a user-supplied AttributeGraph mapping, - /// in both mangling shapes a CF-bridged type reaches Swift metadata as: - /// the typedef name (`AGGraphRef`, a typealias node → `.other`) and the - /// storage/tag name (`AGGraphStorage`, a foreign *class* descriptor the - /// consuming binary emits → `.objcClass`). - /// - /// The imported Swift spelling (`Graph`) is attributed as well, though - /// no printed name carries it any more: a foreign descriptor records it, - /// but the demangler names the descriptor by the ABI name in its import - /// info (evolution proposal `type-import-info-identity`). Why the - /// spellings are still registered: - /// `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings`. - @Test - func userSuppliedMappingsResolveInAllManglingShapes() async throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - _ = try Self.writeAPINotesFile(yaml: Self.attributeGraphYAML, into: directoryURL, named: "AttributeGraph.apinotes") - - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(supplementaryAPINotesFiles: SupplementaryAPINotesLoader.files(atSupplementaryLocations: [directoryURL])) - - #expect(await typeDatabase.moduleName(forTypeName: "AGGraphRef") == "AttributeGraph") - #expect(await typeDatabase.moduleName(forTypeName: "AGGraphStorage") == "AttributeGraph") - #expect(await typeDatabase.moduleName(forTypeName: "Graph") == "AttributeGraph") - #expect(await typeDatabase.moduleName(forTypeName: "Subgraph") == "AttributeGraph") - #expect(await typeDatabase.swiftName(forCName: "AGGraphRef", category: .other) == "Graph") - #expect(await typeDatabase.swiftName(forCName: "AGGraphStorage", category: .objcClass) == "Graph") - #expect(await typeDatabase.swiftName(forCName: "Graph", category: .objcClass) == nil) - #expect(await typeDatabase.swiftName(forCName: "AGSubgraphRef", category: .other) == "Subgraph") - #expect(await typeDatabase.swiftName(forCName: "AGSubgraphStorage", category: .objcClass) == "Subgraph") - } - - /// A `Tags` rename must be visible to a class-category lookup: the - /// field-metadata shape of a CF-bridged type is a foreign *class* node - /// spelled with the C tag name, while APINotes files the entry under - /// `Tags` per C semantics. A class-table entry still wins over a - /// same-named tag entry, and the protocol table never falls back. - @Test - func classCategoryLookupFallsBackToTheValueTypeTable() throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - let fileURL = try Self.writeAPINotesFile(yaml: """ - Name: TestModule - Classes: - - Name: TSTSharedName - SwiftName: ClassSpelling - Tags: - - Name: TSTSharedName - SwiftName: TagSpelling - - Name: TSTStorage - SwiftName: Renamed - Protocols: - - Name: TSTProtocolOnly - SwiftName: ProtocolSpelling - """, into: directoryURL, named: "TestModule.apinotes") - let index = APINotesIndex(files: [try APINotesFile(path: fileURL.path(percentEncoded: false))]) - - #expect(index.swiftName(forCName: "TSTStorage", category: .objcClass)?.name == "Renamed") - #expect(index.swiftName(forCName: "TSTSharedName", category: .objcClass)?.name == "ClassSpelling") - #expect(index.swiftName(forCName: "TSTProtocolOnly", category: .objcClass) == nil) - #expect(index.swiftName(forCName: "TSTProtocolOnly", category: .other) == nil) - } - - // MARK: - Merge priority - - /// A supplementary entry overrides the SDK APINotes entry for the same C - /// name — the "hit it, replace it" contract for user-supplied files. - @Test - func supplementaryEntriesOverrideSDKAPINotesEntries() async throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - let sdkFileURL = try Self.writeAPINotesFile(yaml: """ - Name: SDKModule - Typedefs: - - Name: TSTThingRef - SwiftName: SDKSpelling - """, into: directoryURL, named: "SDKModule.apinotes") - let supplementaryFileURL = try Self.writeAPINotesFile(yaml: """ - Name: CommunityModule - Typedefs: - - Name: TSTThingRef - SwiftName: CommunitySpelling - """, into: directoryURL, named: "CommunityModule.apinotes") - - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(apiNotesIndex: APINotesIndex(files: [try APINotesFile(path: sdkFileURL.path(percentEncoded: false))])) - await typeDatabase.register(supplementaryAPINotesFiles: [try APINotesFile(path: supplementaryFileURL.path(percentEncoded: false))]) - - #expect(await typeDatabase.swiftName(forCName: "TSTThingRef", category: .other) == "CommunitySpelling") - #expect(await typeDatabase.moduleName(forTypeName: "TSTThingRef") == "CommunityModule") - } - - /// Within one supplementary registration, a later file overwrites an - /// earlier one — caller order is the override order. - @Test - func laterSupplementaryFilesOverrideEarlierOnes() async throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - let earlierFileURL = try Self.writeAPINotesFile(yaml: """ - Name: EarlierModule - Tags: - - Name: TSTStorage - SwiftName: EarlierSpelling - """, into: directoryURL, named: "EarlierModule.apinotes") - let laterFileURL = try Self.writeAPINotesFile(yaml: """ - Name: LaterModule - Tags: - - Name: TSTStorage - SwiftName: LaterSpelling - """, into: directoryURL, named: "LaterModule.apinotes") - - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(supplementaryAPINotesFiles: [ - try APINotesFile(path: earlierFileURL.path(percentEncoded: false)), - try APINotesFile(path: laterFileURL.path(percentEncoded: false)), - ]) - - #expect(await typeDatabase.swiftName(forCName: "TSTStorage", category: .valueType) == "LaterSpelling") - } - - // MARK: - Supplied locations - - /// A location may be a directory (its immediate `.apinotes` entries load - /// in file-name order) or a single file; unparsable and missing entries - /// are skipped, never fatal. - @Test - func suppliedLocationsExpandDirectoriesAndSkipBrokenEntries() throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - _ = try Self.writeAPINotesFile(yaml: """ - Name: FirstModule - Typedefs: - - Name: TSTFirstRef - SwiftName: First - """, into: directoryURL, named: "AFirst.apinotes") - _ = try Self.writeAPINotesFile(yaml: """ - Name: SecondModule - Typedefs: - - Name: TSTSecondRef - SwiftName: Second - """, into: directoryURL, named: "BSecond.apinotes") - _ = try Self.writeAPINotesFile(yaml: "{ not apinotes", into: directoryURL, named: "CBroken.apinotes") - _ = try Self.writeAPINotesFile(yaml: "ignored", into: directoryURL, named: "NotAPINotes.txt") - let standaloneFileURL = try Self.writeAPINotesFile(yaml: """ - Name: StandaloneModule - Typedefs: - - Name: TSTStandaloneRef - SwiftName: Standalone - """, into: FileManager.default.temporaryDirectory, named: "SupplementaryAPINotesTests-standalone-\(UUID().uuidString).apinotes") - defer { try? FileManager.default.removeItem(at: standaloneFileURL) } - let missingURL = directoryURL.appending(component: "Missing.apinotes") - - let loadedFiles = SupplementaryAPINotesLoader.files(atSupplementaryLocations: [directoryURL, standaloneFileURL, missingURL]) - #expect(loadedFiles.map(\.moduleName) == ["FirstModule", "SecondModule", "StandaloneModule"]) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift b/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift deleted file mode 100644 index de0f8b94..00000000 --- a/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift +++ /dev/null @@ -1,198 +0,0 @@ -#if os(macOS) - -import Foundation -import MachOKit -import SwiftPrinting -import Testing -@testable import TypeIndexing - -/// Merge-priority behavior of `TypeDatabase`, exercised through its -/// registration steps directly — no sourcekitd, no SDK scan, no Mach-O. -@Suite -struct TypeDatabaseMergePriorityTests { - private static func makeAPINotesIndex(yaml apiNotesYAML: String) throws -> APINotesIndex { - try makeAPINotesIndex(yamls: [apiNotesYAML]) - } - - /// One index over several files, registered in the order given. - private static func makeAPINotesIndex(yamls apiNotesYAMLs: [String]) throws -> APINotesIndex { - var temporaryFileURLs: [URL] = [] - defer { - for temporaryFileURL in temporaryFileURLs { - try? FileManager.default.removeItem(at: temporaryFileURL) - } - } - for apiNotesYAML in apiNotesYAMLs { - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "TypeDatabaseMergePriorityTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - temporaryFileURLs.append(temporaryFileURL) - } - return try APINotesIndex(files: temporaryFileURLs.map { try APINotesFile(path: $0.path(percentEncoded: false)) }) - } - - @Test - func interfaceExtractedNamesResolve() async { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "Foundation", typeNames: ["NSString", "NSURLSession.Configuration"], subModuleNames: []), - ModuleIndexCacheEntry(moduleName: "CoreGraphics", typeNames: ["CGRect"], subModuleNames: []), - ]) - #expect(await typeDatabase.moduleName(forTypeName: "NSString") == "Foundation") - #expect(await typeDatabase.moduleName(forTypeName: "NSURLSession.Configuration") == "Foundation") - #expect(await typeDatabase.moduleName(forTypeName: "CGRect") == "CoreGraphics") - #expect(await typeDatabase.moduleName(forTypeName: "UnknownType") == nil) - } - - /// APINotes is the compiler's own attribution record, so it overrides an - /// interface-derived entry for the same name. - @Test - func apiNotesAttributionOverridesInterfaceNames() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "WrongModule", typeNames: ["TSTThing"], subModuleNames: []), - ]) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: RightModule - Classes: - - Name: TSTThing - SwiftName: Thing - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.moduleName(forTypeName: "TSTThing") == "RightModule") - } - - /// A C name several modules' APINotes list keeps the module whose entry - /// renames it. Foundation's and AppKit's APINotes list `NSObject` only to - /// annotate category methods, and among C-name entries the last file - /// wins; ObjectiveC's entry renames `NSObject` to itself, and that - /// spelling, registered after the C names, keeps the class in - /// ObjectiveC. Without it AppKit's resolved interface printed - /// `Foundation.NSObject`. - @Test - func renamingEntryKeepsItsModuleAgainstLaterListings() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - let apiNotesIndex = try Self.makeAPINotesIndex(yamls: [ - """ - Name: DeclaringModule - Classes: - - Name: TSTBase - SwiftName: TSTBase - """, - """ - Name: AnnotatingModule - Classes: - - Name: TSTBase - """, - ]) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.moduleName(forTypeName: "TSTBase") == "DeclaringModule") - } - - @Test - func swiftNameForCNameComesFromAPINotes() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: TestModule - Tags: - - Name: TSTOptions - SwiftName: Thing.Options - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.swiftName(forCName: "TSTOptions", category: .valueType) == "Thing.Options") - #expect(await typeDatabase.swiftName(forCName: "TSTUnknown", category: .valueType) == nil) - } - - /// The category split end-to-end through the database: the protocol-only - /// `NSObject` → `NSObjectProtocol` rename applies to protocol references - /// and never to class references. - @Test - func nsObjectClassAndProtocolReferencesResolveSeparately() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: ObjectiveC - Classes: - - Name: NSObject - Protocols: - - Name: NSObject - SwiftName: NSObjectProtocol - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.swiftName(forCName: "NSObject", category: .objcProtocol) == "NSObjectProtocol") - #expect(await typeDatabase.swiftName(forCName: "NSObject", category: .objcClass) == nil) - } - - /// `CFStringRef` is the C spelling of the natively-bridged `CFString` - /// class (ClangImporter strips the CF `Ref` suffix), so the Swift-name - /// lookup must translate it whenever the stripped name really exists — - /// and must not touch a name whose stripped form is unknown. - @Test - func cfRefSpellingsTranslateToTheirStrippedSwiftNames() async { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "CoreFoundation", typeNames: ["CFString", "CFStringRef"], subModuleNames: []), - ]) - #expect(await typeDatabase.swiftName(forCName: "CFStringRef", category: .other) == "CFString") - #expect(await typeDatabase.swiftName(forCName: "CFStringRef", category: .objcClass) == "CFString") - #expect(await typeDatabase.swiftName(forCName: "CFStringRef", category: .objcProtocol) == nil) - #expect(await typeDatabase.swiftName(forCName: "SomeUnknownRef", category: .other) == nil) - #expect(await typeDatabase.swiftName(forCName: "CFString", category: .other) == nil) - #expect(await typeDatabase.swiftName(forCName: "Ref", category: .other) == nil) - } - - /// An APINotes rename outranks the CF `Ref`-stripping rule for the same - /// C name — the compiler's own record wins. - @Test - func apiNotesRenameOutranksTheCFRefRule() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "TestModule", typeNames: ["TSTThing"], subModuleNames: []), - ]) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: TestModule - Typedefs: - - Name: TSTThingRef - SwiftName: RenamedThing - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.swiftName(forCName: "TSTThingRef", category: .other) == "RenamedThing") - } - - @Test - func imagePathsReduceToModuleNames() { - #expect(TypeDatabase.moduleName(forImagePath: "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation") == "Foundation") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/swift/libswiftFoundation.dylib") == "Foundation") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/libobjc.A.dylib") == "libobjc") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/system/libsystem_c.dylib") == "libsystem_c") - } - - /// A leading-dot last path component is a fixed point of extension - /// stripping (`.hidden` → `.hidden`), which spun the strip loop forever - /// before the fixed-point guard (PR #110 review, finding 5). - @Test - func leadingDotImagePathsTerminate() { - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/.hidden") == ".hidden") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/.x.y") == ".x") - #expect(TypeDatabase.moduleName(forImagePath: ".hidden") == ".hidden") - } - - /// Task-group results arrive in completion order, but registration is - /// last-writer-wins and must follow the SDK discovery order — the re-sort - /// restores it regardless of arrival order, dropping entries discovery - /// never named (PR #110 review, finding 7). - @Test - func collectedEntriesAreReorderedToDiscoveryOrder() { - let arrivalOrderedEntries = [ - ModuleIndexCacheEntry(moduleName: "Third", typeNames: [], subModuleNames: []), - ModuleIndexCacheEntry(moduleName: "First", typeNames: [], subModuleNames: []), - ModuleIndexCacheEntry(moduleName: "Second", typeNames: [], subModuleNames: []), - ] - let orderedEntries = TypeDatabase.entriesInDiscoveryOrder( - arrivalOrderedEntries, - discoveryOrder: ["First", "Second", "Third", "NeverIndexed"] - ) - #expect(orderedEntries.map(\.moduleName) == ["First", "Second", "Third"]) - } -} - -#endif From 57db0f90d92ee063c650c5e8ad0b061a9500fb66 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 23 Nov 2026 17:49:24 +0800 Subject: [PATCH 078/175] Add swift-section objc interface --mark-sdk-swift-names The header marks the NS_SWIFT_NAME and NS_REFINED_FOR_SWIFT the API notes of the binary's SDK give the declaration and its members, read through swift-type-indexing (API notes only, no sourcekitd): the class's or protocol's on a line above @interface / @protocol, a member's ahead of its semicolon. A category takes its class's member notes. A binary no installed SDK covers warns and prints its plain interface. Also marks SDKPlatform's initializer from a build platform macOS 13+, as the type is. Proposal: draft-swift-type-indexing-package, step 7. --- .../skills/swift-section-cli/SKILL.md | 7 ++- Documentations/ObjCCommandLine.md | 25 ++++++++ Documentations/ObjCCommandLine_zh.md | 22 +++++++ Package.swift | 2 + .../ObjC/ObjCInterfaceRequest.swift | 34 ++++++++++- .../ObjC/ObjCInterfaceSession.swift | 14 +++-- .../ObjC/SDKSwiftImportNotesSource.swift | 61 +++++++++++++++++++ .../ObjC/Commands/ObjCInterfaceCommand.swift | 6 +- .../TypeDatabaseTypeNameResolver.swift | 1 + .../ObjC/ObjCSectionCommandTests.swift | 11 ++++ .../ObjCRequestTests.swift | 40 ++++++++++++ .../TypeDatabaseTypeNameResolverTests.swift | 1 + 12 files changed, 216 insertions(+), 8 deletions(-) create mode 100644 Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index 593d9d93..8b31c16f 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -51,7 +51,8 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, 0.25.0 `objc evolution --interface` / `--emit-available` / `--platform`, `objc interface --swift`, `interface --no-existential-any` / `dump --disable-existential-any`, `interface --expand-macros` and the `refs` and `symbolicate` subcommands, and after 0.26.0 -`--multiline-types` / `--maximum-line-width` on `dump` and `interface`. +`--multiline-types` / `--maximum-line-width` on `dump` and `interface`, and +`objc interface --mark-sdk-swift-names`. 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". @@ -360,6 +361,10 @@ minutes), cached after in `~/Library/Application Support/swift-type-indexing`. W API notes and Objective-C metadata attribute names. A binary whose SDK is not installed warns and prints `__C.` unresolved. `--supplementary-apinotes` only does anything alongside it. +`objc interface --mark-sdk-swift-names` reads the same SDK's API notes for an Objective-C header: +the class's or protocol's `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT` on a line above +`@interface`, a member's before its `;`. API notes only, about two seconds, no sourcekitd. + ## 9. Reading the output: things that look like bugs and are not - **`// not exported`** is an export-trie fact, not an access-level claim. A missing entry diff --git a/Documentations/ObjCCommandLine.md b/Documentations/ObjCCommandLine.md index fd5222b5..3716228f 100644 --- a/Documentations/ObjCCommandLine.md +++ b/Documentations/ObjCCommandLine.md @@ -33,6 +33,9 @@ swift-section objc interface # The same class, protocol or category as Swift imports it swift-section objc interface --swift +# The header with the NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT the SDK's API notes give it +swift-section objc interface --mark-sdk-swift-names + # Freeze a binary's Objective-C API as a baseline snapshot (JSON) swift-section objc snapshot --label 26.0 -o baseline.json @@ -121,6 +124,28 @@ class NSColor: __C.NSObject, __C.NSAccessibilityColor, __C.CAAnimatableValue, __ - A Swift class goes by its runtime name (`_TtC6AppKit11SliderModel`), as for the header. Structs and unions have no Swift view. +## SDK Swift names (`interface --mark-sdk-swift-names`) + +A binary keeps no trace of `NS_SWIFT_NAME(...)` or `NS_REFINED_FOR_SWIFT`. With +`--mark-sdk-swift-names`, `interface` reads them back from the API notes of the binary's SDK in the +active developer directory and prints them as the header did: + +``` +$ swift-section objc interface PKDrawing --uses-system-dyld-shared-cache -n PencilKit --mark-sdk-swift-names +NS_SWIFT_NAME(PKDrawingReference) +@interface PKDrawing : NSObject +… +``` + +- The class's or protocol's own macros go on a line above `@interface` / `@protocol`; a member's go + ahead of its `;`, `NS_SWIFT_NAME(...)` first. A category prints its members' macros only, taken + from the API notes of the class it extends. +- Only these two macros: nullability and the other API notes attributes are not printed. +- The SDK is the one the binary's `LC_BUILD_VERSION` names: macOS and Mac Catalyst binaries need + Xcode or the Command Line Tools, others the matching SDK in Xcode. A binary no installed SDK covers + prints a warning and its plain interface. Needs macOS 13; ignored with `--swift`. +- Reads API notes only (about two seconds); no module interface is generated. + ## Ten generation switches All of them default to off: with none given, the output is the metadata as it stands, nothing diff --git a/Documentations/ObjCCommandLine_zh.md b/Documentations/ObjCCommandLine_zh.md index 2780ba95..3c9e997f 100644 --- a/Documentations/ObjCCommandLine_zh.md +++ b/Documentations/ObjCCommandLine_zh.md @@ -30,6 +30,9 @@ swift-section objc interface # 同一个类 / 协议 / 分类,打印成 Swift 导入它的样子 swift-section objc interface --swift +# 头文件里标出 SDK 的 API notes 给它的 NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT +swift-section objc interface --mark-sdk-swift-names + # 把二进制的 Objective-C API 冻结成基线快照(JSON) swift-section objc snapshot --label 26.0 -o baseline.json @@ -103,6 +106,25 @@ class NSColor: __C.NSObject, __C.NSAccessibilityColor, __C.CAAnimatableValue, __ - Swift 类按运行时名指定(`_TtC6AppKit11SliderModel`),与头文件一样。struct 与 union 没有 Swift 视图。 +## SDK 的 Swift 命名(`interface --mark-sdk-swift-names`) + +二进制不留 `NS_SWIFT_NAME(...)` 与 `NS_REFINED_FOR_SWIFT` 的痕迹。加 `--mark-sdk-swift-names` 时,`interface` 从当前开发者目录 +里、这个二进制所属平台的 SDK 的 API notes 把它们读回来,照头文件的写法打出: + +``` +$ swift-section objc interface PKDrawing --uses-system-dyld-shared-cache -n PencilKit --mark-sdk-swift-names +NS_SWIFT_NAME(PKDrawingReference) +@interface PKDrawing : NSObject +… +``` + +- 类与协议本身的宏单独一行,在 `@interface` / `@protocol` 上面;成员的宏在分号前,`NS_SWIFT_NAME(...)` 在前。category + 只打成员的宏,取自它所扩展的类的 API notes。 +- 只打这两个宏,nullability 等其余 API notes 属性不打。 +- SDK 按二进制 `LC_BUILD_VERSION` 里的平台找:macOS 与 Mac Catalyst 的二进制有 Xcode 或 Command Line Tools 即可,其他平台要 + Xcode 里有对应 SDK。本机没有对应 SDK 时打一条警告,照常输出不带标注的头文件。要 macOS 13;与 `--swift` 同用时忽略。 +- 只读 API notes(约两秒),不生成模块接口。 + ## 十个生成开关 全部默认关闭:一个开关都不加时,输出就是元数据的原样,不删任何东西,也不加任何注释。 diff --git a/Package.swift b/Package.swift index 676ac962..8940bc7d 100644 --- a/Package.swift +++ b/Package.swift @@ -948,6 +948,8 @@ extension Target { .target(.SwiftTypeNameResolution), // `APINotesFile`, which checks `--supplementary-apinotes` paths. .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), + // `objc interface --mark-sdk-swift-names`. + .product(name: "ObjCTypeIndexing", package: "MachOObjCSection", condition: .when(platforms: [.macOS])), .target(.Utilities), // `refs` and `symbolicate`. .target(.CrossReferenceAnalysis), diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift index 7e19229b..dbb334db 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift @@ -33,6 +33,13 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { /// proposal `objc-imported-declarations`). Classes, categories and /// protocols only; the header options do not apply. public var printsSwiftImport: Bool + /// Mark the `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT` the API notes of + /// the binary's SDK give a class, protocol or category and its members, + /// read from the active developer directory (proposal + /// swift-type-indexing-package). macOS 13 and later; a binary no + /// installed SDK covers prints a warning and its plain interface. Ignored + /// with `printsSwiftImport`. + public var marksSDKSwiftNames: Bool public init( declarationName: String, @@ -43,7 +50,8 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { ivarOffsetComment: Transformer.ObjCIvarOffset? = nil, reportsIndexingProgress: Bool = false, destination: ProductDestination = .output, - printsSwiftImport: Bool = false + printsSwiftImport: Bool = false, + marksSDKSwiftNames: Bool = false ) { self.declarationName = declarationName self.kind = kind @@ -54,6 +62,7 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { self.reportsIndexingProgress = reportsIndexingProgress self.destination = destination self.printsSwiftImport = printsSwiftImport + self.marksSDKSwiftNames = marksSDKSwiftNames } public func run(output: some SwiftSectionOutput) async throws { @@ -70,11 +79,14 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { output: output ) + let swiftImportNotesForKind = await sdkSwiftImportNotesProvider(for: session.machOFile, output: output) + // Searched in declaration-kind order rather than by guessing from the // spelling: `Foo(Bar)` is unambiguous, but a bare name could be a // class, a protocol or a struct. for candidateKind in kind.map({ [$0] }) ?? ObjCDeclarationKind.allCases { - guard let interface = session.interface(of: candidateKind, named: declarationName) else { continue } + let swiftImportNotes = await swiftImportNotesForKind?(candidateKind) ?? ObjCSwiftImportNotes() + guard let interface = session.interface(of: candidateKind, named: declarationName, swiftImportNotes: swiftImportNotes) else { continue } switch destination { case .file(let path): try interface.string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) @@ -87,6 +99,24 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { throw ObjCDeclarationLookupError.declarationNotFound(declarationName) } + /// What gives the notes of a declaration kind when `marksSDKSwiftNames` + /// is on and the binary's SDK is readable; `nil` otherwise. + private func sdkSwiftImportNotesProvider(for machOFile: MachOFile, output: some SwiftSectionOutput) async -> (@Sendable (ObjCDeclarationKind) async -> ObjCSwiftImportNotes)? { + guard marksSDKSwiftNames else { return nil } + #if os(macOS) + guard #available(macOS 13.0, *) else { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names needs macOS 13 or later; printing without the SDK's Swift names")) + return nil + } + guard let notesSource = await SDKSwiftImportNotesSource.make(for: machOFile, output: output) else { return nil } + let declarationName = declarationName + return { candidateKind in await notesSource.notes(for: candidateKind, named: declarationName) } + #else + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names needs macOS; printing without the SDK's Swift names")) + return nil + #endif + } + /// The Swift side: the image's declaration index, which pairs a class or /// category Swift implements with its Swift definitions. private func runPrintingSwiftImport(output: some SwiftSectionOutput) async throws { diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift index 8fd58a93..4722d90a 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift @@ -85,28 +85,34 @@ struct ObjCInterfaceSession { // MARK: - Rendering - func interface(of kind: ObjCDeclarationKind, named name: String) -> SemanticString? { + /// The declaration of `kind` named `name`, with `swiftImportNotes` printed + /// as their macros on a class, protocol or category (structs and unions + /// take none). + func interface(of kind: ObjCDeclarationKind, named name: String, swiftImportNotes: ObjCSwiftImportNotes = ObjCSwiftImportNotes()) -> SemanticString? { switch kind { case .classes: builder.classInterface( named: name, options: options, cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder, + swiftImportNotes: swiftImportNotes ) case .protocols: builder.protocolInterface( named: name, options: options, cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder, + swiftImportNotes: swiftImportNotes ) case .categories: builder.categoryInterface( uniqueName: name, options: options, cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder, + swiftImportNotes: swiftImportNotes ) case .structs: builder.structInterface( diff --git a/Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift b/Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift new file mode 100644 index 00000000..fca87e27 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift @@ -0,0 +1,61 @@ +#if os(macOS) + +import MachOKit +import MachOKitExtensions +import ObjCDeclarationRendering +import ObjCTypeIndexing +import SwiftTypeNameResolution +import TypeIndexing + +/// The notes `objc interface --mark-sdk-swift-names` prints: what the API +/// notes of the binary's SDK say about how Swift imports a class or protocol +/// and its members, read from the active developer directory. API notes only: +/// no module interface is generated, so no sourcekitd work runs. +@available(macOS 13.0, *) +struct SDKSwiftImportNotesSource: Sendable { + let typeDatabase: TypeDatabase + + /// The source for `machOFile`'s SDK, or `nil` after a warning when the + /// binary names no platform an SDK covers, or this Mac has no SDK for it. + static func make(for machOFile: MachOFile, output: some SwiftSectionOutput) async -> SDKSwiftImportNotesSource? { + guard + let buildPlatform = machOFile.loadCommands.buildVersionCommand?.platform, + let platform = SDKPlatform(buildPlatform) + else { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names: the binary names no platform an SDK covers; printing it without the SDK's Swift names")) + return nil + } + let availability = TypeIndexingAvailability.availability(for: platform) + guard availability.isAvailable else { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names: the active developer directory has no \(platform.rawValue) SDK; printing without the SDK's Swift names")) + return nil + } + let typeDatabase = TypeDatabase(platform: platform) + do { + try await typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + } catch { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names: reading the \(platform.rawValue) SDK failed (\(error)); printing without the SDK's Swift names")) + return nil + } + return SDKSwiftImportNotesSource(typeDatabase: typeDatabase) + } + + /// The notes for the declaration of `kind` named `name`. A category takes + /// the notes of the class it extends — API notes list category methods + /// under the class — and the builder leaves out the class's own note. + func notes(for kind: ObjCDeclarationKind, named name: String) async -> ObjCSwiftImportNotes { + switch kind { + case .classes: + return await ObjCSwiftImportNotes(apiNotesForClassNamed: name, in: typeDatabase) + case .protocols: + return await ObjCSwiftImportNotes(apiNotesForProtocolNamed: name, in: typeDatabase) + case .categories: + let className = name.split(separator: "(", maxSplits: 1).first.map(String.init) ?? name + return await ObjCSwiftImportNotes(apiNotesForClassNamed: className, in: typeDatabase) + case .structs, .unions: + return ObjCSwiftImportNotes() + } + } +} + +#endif diff --git a/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift index a2850cb3..64309545 100644 --- a/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift @@ -42,6 +42,9 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { @Flag(name: .customLong("swift"), help: "Print the declaration as Swift imports it — names by the ClangImporter's rules, members Swift implements as their Swift declarations — instead of as an Objective-C header. Classes, categories and protocols only.") var printsSwiftImport: Bool = false + @Flag(name: .customLong("mark-sdk-swift-names"), help: "Mark the NS_SWIFT_NAME and NS_REFINED_FOR_SWIFT the API notes of the binary's SDK give the declaration and its members, read from the active developer directory (Xcode, or the Command Line Tools for macOS and Mac Catalyst). macOS 13 or later; ignored with --swift.") + var marksSDKSwiftNames: Bool = false + /// The library request these flags describe. func makeRequest() throws -> ObjCInterfaceRequest { ObjCInterfaceRequest( @@ -53,7 +56,8 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { ivarOffsetComment: transformerOptions.buildIvarOffsetComment(), reportsIndexingProgress: verbose, destination: outputPath.map { .file(path: $0) } ?? .output, - printsSwiftImport: printsSwiftImport + printsSwiftImport: printsSwiftImport, + marksSDKSwiftNames: marksSDKSwiftNames ) } diff --git a/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift index 9184e2c9..505ac7b3 100644 --- a/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift +++ b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift @@ -52,6 +52,7 @@ extension ImportedTypeNameCategory { } } +@available(macOS 13.0, *) extension SDKPlatform { /// The SDK an image built for `platform` is read against, or `nil` for a /// platform no SDK covers. Mac Catalyst has its own case: its frameworks diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift index 5f2b58a4..ad2b4f4b 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift @@ -258,6 +258,17 @@ struct ObjCSectionCommandTests { #expect(try swiftView.makeRequest().printsSwiftImport) } + @Test("The interface subcommand marks the SDK's Swift names only with --mark-sdk-swift-names, and the request knows") + func markSDKSwiftNamesFlagMapsToRequest() throws { + let plain = try ObjCInterfaceCommand.parse(["PKDrawing", "/tmp/Sample"]) + #expect(!plain.marksSDKSwiftNames) + #expect(try !plain.makeRequest().marksSDKSwiftNames) + + let marked = try ObjCInterfaceCommand.parse(["PKDrawing", "/tmp/Sample", "--mark-sdk-swift-names"]) + #expect(marked.marksSDKSwiftNames) + #expect(try marked.makeRequest().marksSDKSwiftNames) + } + // MARK: - Command Tree @Test("dump is the default objc subcommand") diff --git a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift index 37494397..2938c01e 100644 --- a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift +++ b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift @@ -237,4 +237,44 @@ struct ObjCRequestTests { } #expect(!output.messages(of: .progress).contains { $0.hasPrefix("Indexing") }) } + + // MARK: - SDK Swift names + + @Test("--mark-sdk-swift-names marks a class with the Swift name the SDK's API notes give it") + func markSDKSwiftNamesMarksAnSDKClass() async throws { + let output = RecordingOutput() + try await ObjCInterfaceRequest( + declarationName: "PKDrawing", + kind: .classes, + source: .systemDyldSharedCache(image: .name("PencilKit")), + marksSDKSwiftNames: true + ).run(output: output) + #expect(output.printedProduct.hasPrefix("NS_SWIFT_NAME(PKDrawingReference)\n@interface PKDrawing"), "\(output.printedProduct.prefix(200))") + #expect(output.messages(of: .warning).isEmpty) + } + + @Test("--mark-sdk-swift-names leaves a class the API notes do not mention as it was") + func markSDKSwiftNamesLeavesAnUnmentionedClassAlone() async throws { + let plain = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: Self.fixture).run(output: plain) + let marked = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: Self.fixture, marksSDKSwiftNames: true).run(output: marked) + #expect(marked.printedProduct == plain.printedProduct) + #expect(marked.messages(of: .warning).isEmpty) + } + + @Test("--mark-sdk-swift-names on a binary no SDK covers warns and prints the plain interface") + func missingSDKWarnsAndPrintsUnmarkedOutput() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let copyPath = try FixtureFiles.makeCopy(of: FixtureFiles.symbolTestsCore, buildPlatform: PLATFORM_BRIDGEOS, in: directoryURL) + let source = MachOSource.file(path: copyPath, architecture: nil) + + let plain = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: source).run(output: plain) + let marked = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: source, marksSDKSwiftNames: true).run(output: marked) + #expect(marked.printedProduct == plain.printedProduct) + #expect(marked.messages(of: .warning).contains { $0.contains("--mark-sdk-swift-names") }, "\(marked.messages(of: .warning))") + } } diff --git a/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift index 1e0e575b..33b7b7e7 100644 --- a/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift +++ b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift @@ -24,6 +24,7 @@ struct TypeDatabaseTypeNameResolverTests { /// found no API notes. @Test func buildPlatformsMapToTheirSDKs() { + guard #available(macOS 13.0, *) else { return } #expect(SDKPlatform(MachOKit.Platform.macOS) == .macOS) #expect(SDKPlatform(MachOKit.Platform.macCatalyst) == .macCatalyst) #expect(SDKPlatform(MachOKit.Platform.iOS) == .iOS) From 256466547264157ac0a10550e3f397efce2a0da8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 23 Nov 2026 18:45:04 +0800 Subject: [PATCH 079/175] docs: record how RuntimeViewer took the type index, and the verification --- .../draft-swift-type-indexing-package.html | 364 +++++++++++------- .../draft-swift-type-indexing-package.md | 93 +++-- 2 files changed, 291 insertions(+), 166 deletions(-) diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.html b/Documentations/Evolutions/draft-swift-type-indexing-package.html index 21b26c8d..370f0d47 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.html +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.html @@ -166,6 +166,7 @@

    Draft 类型索引独立成 swift
    状态
    In Progress
    最后更新
    2026-11-23
    项目类型
    库(跨仓库唯一提案)
    +
    跨仓库范围
    新仓库 swift-type-indexing、swift-apinotes fork(实现中加入)、MachOObjCSection、MachOSwiftSection(持有本提案)、RuntimeViewer
    原文
    draft-swift-type-indexing-package.md

    @@ -206,10 +207,8 @@

    摘要

    要你定

    -

    批准这份提案

    -
      -
    1. 批准后状态改为 Accepted,从第 0 步开始实现。
    2. -
    +

    没有待你决定的事

    +

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

    agent 自己定的(可以推翻)

    @@ -263,7 +262,7 @@

    模块依赖:改了什么

    third party SourceKitD - swift-apinotes + swift-apinotes (fork)0.3.0: ObjC members public @@ -277,7 +276,7 @@

    模块依赖:改了什么

    -

    箭头从使用方指向依赖。RuntimeViewerCore 还直接依赖 ObjCTypeIndexing 与 TypeIndexing(建 TypeDatabase、取 ObjC 标注),图里省略;三个新依赖都只在 macOS 上。红色虚线是删掉的旧依赖:MachOSwiftSection 的 TypeIndexing 直接调用 ObjCIndexing。

    +

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

    新包内部

    TypeDatabase                                   (actor, no longer generic)
    @@ -293,33 +292,42 @@ 

    新包内部

    RuntimeViewer 的建立与刷新

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

    上面一行是索引建立:engine 连上后在服务进程里后台建,建好后打印器注册解析器、清掉旧缓存,再通知 App 重新取。下面一行是两类请求:界面不等,非交互的调用方等。

    +

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

    @@ -333,18 +341,36 @@

    改动地图

    - - - - - - - - - - - - + + + + + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    Package.swift新增product / target TypeIndexing 与测试 target;依赖 SourceKitD、swift-apinotes、FrameworkToolbox(均限 macOS);平台与 MachOSwiftSection 一致;打开三项 upcoming feature独立成包;平台声明不能高于 MachOObjCSection1
    InterfaceDeclarationNode、InterfaceTypeNameExtractor、ModuleIndexCache、ModuleInterfaceIndexer、SDKIndexer、SDKPlatform、SourceKitManager、Subprocess、SupplementaryAPINotes移入原样搬入;package 改 public(只公开需要的);日志子系统改名搬家1
    APINotesIndex移入 修改用 ImportedTypeNameCategory;改名规则修正;新增 ObjC 容器条目修正改名;给 ObjC 标注提供数据1–3
    TypeDatabase移入 修改去泛型;收 [any DeclaredTypeNameSource];构造器加 cacheDirectory:;新增 swiftImportAnnotations(…)去掉对 MachOObjCSection 的依赖;缓存位置由调用方决定1–3
    DeclaredTypeNameSource新增imagePath、declaredTypeNames()取代直接调用 ObjCInterfaceIndexer1
    ImportedTypeNameCategory新增四个 case取代 SwiftPrinting 的 CImportedTypeNameCategory1
    SourceKitLocator新增先试 Xcode 工具链,再试 <developer dir>/usr/lib/sourcekitd.framework支持 Command Line Tools2
    TypeIndexingAvailability新增SDK 路径、sourcekitd 路径、不可用原因调用方决定开不开、界面说明原因2
    SwiftImportAnnotation、ObjCContainerSwiftImportAnnotations、ObjCMemberKey新增API notes 的命名标注给 MachOObjCSection 用3
    Tests/TypeIndexingTests/*移入 修改7 个文件搬入;改用假的 DeclaredTypeNameSource;不改名的旧测试按新规则改写搬家;规则修正1–2
    四个新测试文件新增改名规则、sourcekitd 定位、缓存目录、ObjC 标注查询回归测试2–3
    README、LICENSE、AGENTS.md、文档目录、CI新增TypeIndexingPipeline.md 从 MachOSwiftSection 移入并更新新仓库的文档1、3
    Package.swift新增包名 swift-type-indexing,product / target TypeIndexing,测试 target TypeIndexingTests;依赖 SourceKitD、swift-apinotes(from: "0.3.0",本地候选 ../../../Fork/Library/swift-apinotes)、FrameworkToolbox(后两者限 macOS);平台与 MachOSwiftSection 一致(macOS 10.15 / iOS 13 / tvOS 13 / watchOS 6 / visionOS 1);打开 ExistentialAny、MemberImportVisibility、InferIsolatedConformances独立成包;平台声明不能高于 MachOObjCSection,否则 SwiftPM 拒绝解析1
    InterfaceDeclarationNode、InterfaceTypeNameExtractor、ModuleIndexCache、ModuleInterfaceIndexer、SDKIndexer、SDKPlatform、SourceKitManager、Subprocess、SupplementaryAPINotes移入原样搬入;package 改 public(只公开调用方需要的,其余 internal);@Loggable 子系统改为 com.mxiris.type-indexing搬家1
    APINotesIndex移入 修改用 ImportedTypeNameCategory;改名规则:有 SwiftName 用它(不论 SwiftPrivate),只有 SwiftPrivate 时 "__" + cName;cNamesBySwiftName 同步登记;新增 ObjC 容器的方法、属性条目索引修正改名;给 ObjC 标注提供数据1、2、3
    TypeDatabase移入 修改去泛型;index(dependencies:moduleFilter:) 改收 [any DeclaredTypeNameSource],可多次调用(第一次发现 SDK、登记 API notes,之后只补新模块与新依赖);API notes、模块接口、运行时元数据三张表在查询时按优先级查,不再靠写入顺序覆盖;moduleName(forImagePath:) 保持纯函数;构造器加 cacheDirectory:;没有 sourcekitd 时只读缓存;新增 swiftImportAnnotations(forObjCClassNamed:) / forObjCProtocolNamed:去掉对 MachOObjCSection 的依赖;RuntimeViewer 加载新镜像时要追加模块;缓存位置由调用方决定;给 ObjC 标注用1、2、3
    DeclaredTypeNameSource新增协议:imagePath、declaredTypeNames() async throws -> [String]取代直接调用 ObjCInterfaceIndexer1
    ImportedTypeNameCategory新增objcClass / objcProtocol / valueType / other取代 SwiftPrinting 的 CImportedTypeNameCategory1
    SourceKitLocator新增依次试 <developer dir>/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/sourcekitd 与 <developer dir>/usr/lib/sourcekitd.framework/sourcekitd;SourceKitManager 改用它支持 Command Line Tools2
    TypeIndexingAvailability新增static func availability(for: SDKPlatform):sdkSettings(含 SDK 路径与版本,供 RuntimeViewer 的语料 variant 用)、sourcekitd 路径、不可用原因调用方决定开不开、在界面上说明原因2
    SDKPlatform.macCatalyst、SDKSettings.macCatalystVersion、compilerArguments(for:)修改新 case macCatalyst:读 macOS SDK(xcrunSDKName),target ios<SupportedTargets.iosmac.DefaultDeploymentTarget>-macabi,给 sourcekitd 显式补 -Fsystem …/System/iOSSupport/System/Library/Frameworks;SDKIndexer 的 Catalyst 搜索路径先 System/iOSSupport/… 再 macOS 的;缓存目录与 macOS 分开Mac Catalyst 的 UIKit 与其 API notes 只在 iOSSupport 里,原来按 .macOS 索引找不到2、3
    SwiftImportAnnotation、ObjCContainerSwiftImportAnnotations、ObjCMemberKey新增单个声明与一个类 / 协议的 API notes 命名标注给 MachOObjCSection 用3
    Tests/TypeIndexingTests/*移入 修改7 个文件搬入;TypeDatabase<MachOFile> 改为用假的 DeclaredTypeNameSource;swiftPrivateEntitiesAreAttributedButNotRenamed 改写为新规则搬家;规则修正1、2
    DeclaredTypeNameSourceTests、SwiftNameRuleTests、SourceKitLocatorTests、TypeIndexingAvailabilityTests、CacheDirectoryTests、MacCatalystPlatformTests、ObjCSwiftImportAnnotationTests新增见各步骤的行为清单回归测试1、2、3
    SDKIntegrationTests新增对本机真实 SDK 的核对,默认关闭:TYPE_INDEXING_SDK_TESTS=1(只读 API notes,约 2 秒),再加 TYPE_INDEXING_SOURCEKIT_TESTS=1 经 sourcekitd 冷生成 Catalyst 的 UIKit 接口(实测 126 秒)单测覆盖不到 SDK 布局与 sourcekitd 参数2、3
    README.md、LICENSE、AGENTS.md + CLAUDE.md(符号链接)、Documentations/README.md、提案索引(项目类型:库)、TypeIndexingPipeline.md(从 MachOSwiftSection 移入并更新)新增 移入用法、三层数据源、改名规则、缓存布局、可用性新仓库的文档1、3
    .github/workflows/macOS.yml新增照 MachOSwiftSection 的 macOS.yml 配 macOS 构建与测试CI1
    +
    +
    +
    + +
    + swift-apinotes(fork,实现中加入) +
    +
    + + + + +
    文件 / 类型动作改什么为什么步骤
    ObjCContext.swift · ObjCContext.methods / properties修改标 public;打 tag 0.3.00.2.0 里是 internal,包外读不到类与协议的成员,ObjC 成员的标注没有来源3
    Tests/APINotesTests/ObjCContextMemberAccessTests.swift新增不带 @testable 读成员(修复前编译失败)回归3
    @@ -358,14 +384,15 @@

    改动地图

    - - + + - - - - - + + + + + +
    文件 / 类型动作改什么为什么步骤
    Package.swift修改本地候选 + 远端依赖 swift-type-indexing;新 target / product ObjCTypeIndexing 与测试 target只有新 target 依赖新包4
    ObjCDeclaredTypeNames<MachO>新增实现 DeclaredTypeNameSource,包一层 ObjCInterfaceIndexer取代 MachOSwiftSection 里那段直接调用4
    Package.swift修改.package(local: ../swift-type-indexing, remote: …, from: "0.1.0"),带理由注释;新 target ObjCTypeIndexing(依赖 ObjCIndexing、ObjCDeclarationRendering、TypeIndexing 限 macOS)与同名 product;测试 target ObjCTypeIndexingTests接入新包,且只有新 target 依赖它4
    ObjCDeclaredTypeNames<MachO>新增实现 DeclaredTypeNameSource:ObjCInterfaceIndexer(machO:imagePath:) → prepare() → 类、协议、struct、union 名取代 MachOSwiftSection TypeDatabase.indexObjCMetadata(of:) 的那段4
    ObjCSwiftImportNotes+TypeDatabase.swift新增init(apiNotesForClassNamed:in:)、init(apiNotesForProtocolNamed:in:)API notes → 标注5
    ObjCSwiftImportNotes、Note修改swiftName、declarationNote、merging(_:);渲染 NS_SWIFT_NAME标 Swift 命名5
    ObjCClassInfo / ObjCProtocolInfo / ObjCCategoryInfo修改声明行之前打印类型一级的宏行;category 成员读标注类型一级宏5
    ObjCInterfaceBuilder 协议与 category 入口修改加 swiftImportNotes: 参数(默认空)协议与 category 也能标5
    测试新增 修改SwiftImportNotesRenderingTests 加用例;新 ObjCTypeIndexingTests回归4–5
    README、命令行指南、术语表、提案索引修改新 target、新标注、cross-repository 行文档同批4–5
    ObjCSwiftImportNotes、Note修改Note 加 swiftName: String?;值上加 declarationNote: Note?;加 merging(_:);渲染 NS_SWIFT_NAME(name)(在 NS_REFINED_FOR_SWIFT 前);新增类型一级的渲染函数标 Swift 命名5
    ObjCClassInfo / ObjCProtocolInfo / ObjCCategoryInfo 的 semanticString(using:)修改声明行之前打印类型一级的宏行;category 成员也读标注类型一级宏5
    ObjCInterfaceBuilder 的 protocolInterface / markedProtocolInterface / categoryInterface / markedCategoryInterface修改加 swiftImportNotes: 参数(默认空)协议与 category 也能标5
    Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift修改加 NS_SWIFT_NAME、类型一级、协议、category 的用例回归5
    Tests/ObjCTypeIndexingTests/*新增ObjCDeclaredTypeNames 对 Foundation 镜像列出 NSObject 等;API notes 转换(临时 .apinotes 驱动)回归4、5
    README.md、ObjCSectionCommandLine.md(库调用方一节)、Glossary.md、提案索引(cross-repository 行)修改新 target、新标注、指向本提案文档同批4、5
    @@ -379,15 +406,16 @@

    改动地图

    - - - - - - + + + + + + - - + + +
    文件 / 类型动作改什么为什么步骤
    Package.swift修改删 TypeIndexing target、product、测试 target 与 SourceKitD / swift-apinotes;加 swift-type-indexing 与 SwiftTypeNameResolution搬家后的接线6
    Sources/Declaration/TypeIndexing/(11 个文件)删除已移入新包搬家6
    TypeDatabaseTypeNameResolver新增把 TypeDatabase 适配成打印器的两个角色协议,映射分类枚举唯一的适配点,RuntimeViewer 也用它6
    SwiftInterfaceBuilderTypeNameProvider移动 修改移进 SwiftTypeNameResolution,改为建立在适配器之上名字不变,CLI 调用方不动6
    InterfaceRequest.swift修改改 import接线6
    ObjCInterfaceCommand.swift 与 SwiftSectionKit/ObjC修改新开关 --mark-sdk-swift-names;找不到 SDK 时警告并照常输出swift-section objc 的同类开关7
    Package.swift修改删 TypeIndexing target、product、TypeIndexingTests、SourceKitD 与 swift-apinotes 两个依赖;加 swift-type-indexing 本地候选依赖;加 target / product SwiftTypeNameResolution(依赖 SwiftPrinting、SwiftInterface、TypeIndexing 与 ObjCTypeIndexing 限 macOS);SwiftSectionKit、IntegrationTests 改依赖它搬家后的接线6
    Sources/Declaration/TypeIndexing/(除适配器外 11 个文件)删除已移入新包搬家6
    TypeDatabaseTypeNameResolver新增包一个 TypeDatabase,实现 ModuleNameResolving + CImportedNameResolving,映射 CImportedTypeNameCategory → ImportedTypeNameCategory打印器与新包之间唯一的适配点,RuntimeViewer 也用它6
    SwiftInterfaceBuilderTypeNameProvider移动 修改从 Sources/Declaration/TypeIndexing/ 移进 SwiftTypeNameResolution;依赖改为 TypeDatabaseTypeNameResolver 与 ObjCDeclaredTypeNames;buildVersionCommand 改用 MachOKitExtensions 的公开版本名字不变以免动 CLI 调用方6
    InterfaceRequest.swift修改import TypeIndexing 改为新模块;APINotesFile(path:) 预校验照旧接线6
    ObjCInterfaceCommand.swift、SwiftSectionKit/ObjC/*修改新增 --mark-sdk-swift-names:按镜像平台建 TypeDatabase,把 API notes 标注交给 ObjCInterfaceBuilder;找不到 SDK 时警告并照常输出swift-section objc 的同类开关7
    Tests/TypeIndexingTests/删除已移入新包搬家6
    集成测试、命令映射测试、新的适配器测试修改 新增import 改名;新开关的映射;分类映射与打印回归6–7
    README、文档索引、补充映射指南、内部文档、术语表、SwiftSectionKit、ObjC 命令行文档、AGENTS.md、swift-section 插件 skill 与版本修改指向新包、新 target、新开关文档同批6–7
    TypeNameProviderTests.swift、CommandRequestMappingTests.swift修改import 改名;加 --mark-sdk-swift-names 的映射用例接线6、7
    Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift新增分类映射、__C 解析经适配器到达打印器回归6
    README(product 表等)、文档索引、SupplementaryTypeMappings.md、内部文档(TypeIndexingPipeline.md 删、改为指向新包,ProjectMap.md、Modules/README.md)、术语表、SwiftSectionKit{,_zh}.md、ObjCCommandLine{,_zh}.md、AGENTS.md / CLAUDE.md、swift-section 插件 skill(加 objc 新开关)及其插件清单的 version修改指向新包、新 target、新开关文档同批6、7
    Documentations/Evolutions/README.md修改登记本提案索引0
    @@ -402,27 +430,33 @@

    改动地图

    - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    RuntimeViewerCore/Package.swift修改加 swift-type-indexing;Core 加三个 product(限 macOS)接线8
    Local workspace、.worktrees 链接、LocalDependencies.md修改加 ../swift-type-indexing本地联调8
    Tuist.swift、TuistScript.sh修改换掉 "TypeIndexing",加两个新 target 与新包Tuist 描述同批8
    AGENTS.md「Dependency floors」修改新包的版本下限与理由规则8
    TypeNames/RuntimeTypeIndex新增每进程一个;每平台一个 TypeDatabase;后台预建;状态;解析器进程级共享索引9
    TypeNames/RuntimeTypeIndexLocation新增往上找 .app 定缓存目录;不在 App 里用 runtime-viewer-cli 自己的目录所有进程共用缓存9
    TypeNames/RuntimeTypeIndexStatus、TypeIndexStatusCommand新增线上状态类型;Core 自有命令,路由为「问服务进程本身」Report 与工具栏9
    RuntimeDataChange修改新 case typeNamesResolved(platform:)通知 App 刷新9
    RuntimeSwiftSection修改两个打印器都注册解析器;每次按开关重建解析器列表;就绪时清缓存打印解析后的名字9
    RuntimeObjCSection、RuntimeEngine、RuntimeEngine+Search修改类、协议、category 都合并 API notes 标注ObjC 标注9
    SwiftGenerationOptions、GenerationOptions修改resolvesImportedTypeNames、marksSwiftNamesFromAPINotes(默认开)、waitsForTypeIndex(默认关)开关;非交互调用方等索引9
    语料 variant 与内存比较修改带上是否解析与 SDK 版本;构建前等索引语料与显示一致9
    四个服务入口与命令行 host修改配置缓存位置每个打印的进程9
    TypeIndexCoordinator、RuntimeEngineBackgroundWork新增 修改状态、进行中、App Nap、关闭Report 与后台工作10
    Report 三个文件、工具栏活动两个文件修改新类别「Imported Type Names」与活动文案可见10
    ContentTextViewModel、ViewModel修改收到 .typeNamesResolved 时重新取自动刷新10
    GenerationOptionsViewController修改两个默认勾选的开关开关10
    RuntimeDerivedDataController、RuntimeDerivedDataMaintenance修改量与删都包括 TypeIndex 目录Delete Derived Data 一起删10
    MCP、命令行执行器、导出修改置 waitsForTypeIndex = true输出稳定11
    runtime-viewer 插件 skill 与两个清单修改说明输出变化;1.3.0 → 1.4.0插件规则11
    DerivedData.md、CommandLineInterface.md、两份索引修改新缓存目录、输出变化、cross-repository 行文档同批8、11
    RuntimeViewerCore/Package.swift修改加 swift-type-indexing(本地候选 ../../swift-type-indexing + 远端,限 macOS);RuntimeViewerCore target 加 TypeIndexing、ObjCTypeIndexing、SwiftTypeNameResolution 三个 product(限 macOS)。实现期间 MachOObjCSection 与 MachOSwiftSection 临时钉 branch: "feature/swift-type-indexing-package",收尾时改回 branch: "next"接线8
    Local workspace、.worktrees/swift-type-indexing 链接、LocalDependencies.md修改加 ../swift-type-indexing本地联调8
    Tuist.swift、TuistScript.sh修改删 MachOSwiftSection 的 "TypeIndexing",加 "SwiftTypeNameResolution"、MachOObjCSection 的 "ObjCTypeIndexing";swift-type-indexing 加进 SOURCE_DEPENDENCIES 并列出它的 targetTuist 描述同批8
    AGENTS.md「Dependency floors」修改加 swift-type-indexing 的版本下限与理由规则8
    TypeNames/RuntimeTypeIndex.swift · RuntimeTypeIndex新增actor,每进程一个(static let process,不经 @Dependency);每个 SDKPlatform 一个 TypeDatabase;request(_:) 把一个镜像链接的模块和它自己的 ObjC 元数据排成一批,同平台的批次依次执行;每批完成把平台的 generation 加一并通知监听者;resolution(for:)、swiftImportNotes(forClassNamed:/forProtocolNamed:platform:)、status()进程级共享索引9
    TypeNames/RuntimeTypeNames.swift · RuntimeTypeNames新增进程开关 enableInThisProcess()(照 RuntimeDerivedData.enableInThisProcess());platformName(of:) 取镜像第一个 LC_BUILD_VERSION 的平台只有打印的服务进程建索引9
    TypeNames/RuntimeTypeIndexLocation.swift新增缓存目录:.app / Contents/XPCServices / Contents/Applications 往上找 .app → ~/Library/Caches/<bundle id>/TypeIndex;不在 App 里 → ~/Library/Caches/runtime-viewer-cli/TypeIndex;测试用临时目录所有进程共用缓存9
    TypeNames/RuntimeTypeIndexStatus.swift新增线上类型:每个平台 building(progress) / ready / unavailable(reason)、缓存字节数Report 与工具栏9
    TypeNames/RuntimeEngine+TypeNames.swift、Engine/RuntimeEngine+Commands.swift · TypeIndexStatusCommand新增Core 自有命令 typeIndexStatus,路由 .servingEngine,加进 SharedCacheRoutingDeclarationTests 的清单;typeIndexStatus() 经新的 dispatchToServingProcess(_:timeout:) 发出、连接自带 2 秒超时,旧对端答 .empty;startObservingTypeIndex() 把批次完成转成广播;RuntimeTypeNamesCorpusVariant让 App 读状态9
    Engine/RuntimeDataChange.swift修改新 case typeNamesResolved(platform: String)通知 App 刷新9
    Sections/Swift/RuntimeSwiftSection.swift修改显示打印器与语料打印器都注册 TypeDatabaseTypeNameResolver;updateConfiguration 每次按开关重建解析器列表(不再被 removeAllTypeNameResolvers() 误删);收到索引就绪时清 interfaceByObject / importedInterfaceByObject打印解析后的名字9
    RuntimeObjCSection.swift、RuntimeEngine.swift、Search/RuntimeEngine+Search.swift修改类、协议、category 都取 API notes 标注,与 objcSwiftImportNotes(for:) 合并后传入ObjC 标注9
    Interfaces/SwiftGenerationOptions.swift修改@Default(true) resolvesImportedTypeNames开关9
    Interfaces/RuntimeObjectInterface+GenerationOptions.swift · GenerationOptions修改@Default(true) marksSwiftNamesFromAPINotes(ObjC 头文件的开关,放顶层:objcHeaderOptions 是 MachOObjCSection 的 ObjCGenerationOptions,而这个开关只决定 RuntimeViewer 传不传标注);@Default(false) waitsForTypeIndex开关;非交互的调用方等索引9
    RuntimeInterfaceCorpusSnapshot.swift、RuntimeInterfaceCorpusStore.swift修改variant 加 -TypeNames<SDK build> 或 -UnresolvedTypeNames;内存比较加同一条件;语料构建前等索引语料与显示一致9
    ServicePluginEntry.swift(本机、Catalyst、文件、框架四个 service 与 Catalyst helper 五个入口)、CommandLineHostServer.start()(只在独立 host)修改进程启动时 RuntimeTypeNames.enableInThisProcess();缓存位置由 RuntimeTypeIndexLocation 从 Bundle.main 推出,不用配置每个打印的进程9
    BackgroundWork/TypeIndex/TypeIndexCoordinator.swift新增照 CrossReferencePreparationCoordinator:读状态、isWorkInProgress、close()Report 与 App Nap10
    RuntimeEngineBackgroundWork.swift修改创建协调器,并入 isWorkInProgress、activity reporter、close()接入后台工作10
    ReportNode.swift、ReportTreeBuilder.swift、ReportViewModel.swift修改新 ReportCategory.importedTypeNames 及其节点;状态、原因、缓存大小Report 可见10
    RuntimeEngineActivityReporter.swift、ToolbarActivity.swift、Presentation/SystemSymbol.swift修改新活动种类(每个批次一项,文案 Indexing Imported Type Names)与 Report 图标 shippingbox工具栏进度10
    Content/ContentTextViewModel.swift修改收到 .typeNamesResolved 时先在主线程清文档的接口缓存,再重新取当前内容(Base/ViewModel.swift 不用改)建好后自动刷新10
    GenerationOptionsViewController.swift修改Swift 组加「Resolve Imported Type Names」,ObjC 组加「Mark Swift Names From SDK」开关10
    RuntimeDerivedDataController.swift、RuntimeDerivedDataMaintenance.swift修改量与删都包括 TypeIndex 目录;确认框文案提到它Delete Derived Data 一起删10
    MCPBridgeServer.swift、CommandExecutor.swift、Export/RuntimeEngine+Export.swift修改置 waitsForTypeIndex = true输出稳定11
    runtime-viewer 插件的 SKILL.md、.claude-plugin/plugin.json、.codex-plugin/plugin.json修改说明 __C. 解析与首次等待;版本 1.3.0 → 1.4.0插件规则11
    DerivedData.md、CommandLineInterface.md、提案索引(cross-repository 行)、Documentations/README.md修改新缓存目录、输出变化、索引文档同批8、11
    测试(见各步骤的行为清单)新增RuntimeViewerCoreTests 与 RuntimeViewerAppCoreTests 中的对应套件回归9、10、11
    @@ -436,7 +470,10 @@

    详细设计

    新包的公开 API
    -
    public protocol DeclaredTypeNameSource: Sendable {
    +
    /// One dependency image whose runtime metadata lists the types it declares.
    +/// Consulted, in order, only for names the SDK's module interfaces and API
    +/// notes do not attribute; the first image that declares a name wins.
    +public protocol DeclaredTypeNameSource: Sendable {
         var imagePath: String { get }
         func declaredTypeNames() async throws -> [String]
     }
    @@ -446,15 +483,27 @@ 

    详细设计

    } public struct TypeIndexingAvailability: Sendable, Hashable { - public var sdkPath: String? - public var sourceKitPath: String? // nil: module interfaces skipped - public var unavailabilityReason: UnavailabilityReason? + public enum UnavailabilityReason: Sendable, Hashable { + case noDeveloperDirectory + case sdkNotInstalled(SDKPlatform) + } + public let sdkSettings: SDKSettings? // path, version, build, Mac Catalyst version + public let sourceKitPath: String? // nil: module interfaces skipped + public let unavailabilityReason: UnavailabilityReason? + public var isAvailable: Bool { unavailabilityReason == nil } public static func availability(for platform: SDKPlatform) -> TypeIndexingAvailability } +public enum SDKPlatform: String, CaseIterable, Hashable, Codable, Sendable { + case macOS = "macosx" + case macCatalyst = "maccatalyst" // the macOS SDK read through System/iOSSupport + case iOS = "iphoneos" + // tvOS, watchOS, visionOS, driverKit and the simulators, as before +} + public struct SwiftImportAnnotation: Sendable, Hashable { - public var swiftName: String? - public var isSwiftPrivate: Bool + public var swiftName: String? // SwiftName: the Swift name as is + public var isSwiftPrivate: Bool // without a SwiftName, Swift prefixes "__" } public enum ObjCMemberKey: Sendable, Hashable { @@ -477,45 +526,71 @@

    详细设计

    public func swiftImportAnnotations(forObjCProtocolNamed protocolName: String) -> ObjCContainerSwiftImportAnnotations? public static func moduleName(forImagePath imagePath: String) -> String }
    -

    所有源码仍包在 #if os(macOS) 里。协议按「是什么」命名,沿用组织里 ObjCMetadataSource 的 Source 后缀;不给 MachOKit 的类型补遵循新包的协议,由 MachOObjCSection 的包装类型实现。

    +
      +
    • 所有源码仍包在 #if os(macOS) 里。
    • +
    • SDKPlatform 公开,并新增 macCatalyst(落地时发现,见决策日志);SDKSettings(sdkPath、version、productBuildVersion、macCatalystVersion、cacheDirectoryComponent)与 APINotesFile(path:) 一并公开——后者是 swift-section 预检 --supplementary-apinotes 路径用的。
    • +
    • index(dependencies:moduleFilter:) 可多次调用:第一次发现 SDK 并登记 API notes,之后只补新的模块与依赖镜像;因此 API notes 优先于模块接口改为查询时决定(三张表),不再靠写入顺序。
    • +
    • 搬家时保留的三个 register(...) 测试钩子(提案 0009)降为 internal,测试用 @testable import。
    • +
    • 命名照 apple-style-api-design:协议按「是什么」命名,沿用组织里 ObjCMetadataSource 的 Source 后缀;查询读成名词短语(moduleName(forTypeName:));不给 MachOKit 的类型补遵循新包的协议,由 MachOObjCSection 的包装类型实现。
    • +
    改名规则
    -
    let swiftName: String? = if let explicitSwiftName = entity.swiftName {
    -    explicitSwiftName                         // swift_name wins, no "__"
    -} else if entity.isSwiftPrivate == true {
    -    "__" + cName                              // swift_private alone
    -} else {
    -    nil
    +
    // APINotesIndex.registerEntities(_:declaredIn:into:)
    +for entity in entities {
    +    let cName = entity.name
    +    moduleNamesByCName[cName] = moduleName
    +    let swiftName: String? = if let explicitSwiftName = entity.swiftName {
    +        explicitSwiftName                         // swift_name wins, no "__"
    +    } else if entity.isSwiftPrivate == true {
    +        "__" + cName                              // swift_private alone
    +    } else {
    +        nil
    +    }
    +    guard let swiftName, swiftName != cName else { continue }
    +    self[keyPath: renameTable][cName] = Name(moduleName: moduleName, name: swiftName)
    +    cNamesBySwiftName[swiftName] = Name(moduleName: moduleName, name: cName)
     }
    -

    依据是 Clang importer:有 swift_name 时直接用它并提前返回,只有没有它时才在 swift_private 的声明前加 __。ObjC 成员按同样两条规则记录,但只保存原始的 swiftName / isSwiftPrivate,因为成员一级要打印的是宏。

    +

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

    缓存目录
    -

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

    +

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

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

    打印效果:

    NS_REFINED_FOR_SWIFT
     @interface UICellConfigurationState : UIViewConfigurationState
    @@ -524,8 +599,13 @@ 

    详细设计

    NS_SWIFT_NAME(PKDrawingReference) @interface PKDrawing : NSObject <NSCopying, NSSecureCoding> +- (instancetype)initWithData:(NSData *)data error:(NSError **)error; @end
    -

    类型一级的宏单独一行,放在 @interface / @protocol 上面(与演进视图打印可用性宏的写法相同);成员一级放在 ; 前,NS_SWIFT_NAME(...) 在 NS_REFINED_FOR_SWIFT 前。

    +
      +
    • 类型一级的宏单独一行,放在 @interface / @protocol 上面(与演进视图打印可用性宏的写法相同);declarationNote 两个字段都有时打成一行 NS_SWIFT_NAME(X) NS_REFINED_FOR_SWIFT。
    • +
    • 成员一级放在 ; 前,NS_SWIFT_NAME(...) 在 NS_REFINED_FOR_SWIFT 前:- (void)foo NS_SWIFT_NAME(bar()) NS_REFINED_FOR_SWIFT;。
    • +
    • 标注不进可折叠区域(与现在的 NS_REFINED_FOR_SWIFT 一致:它是声明的一部分,不是注释)。
    • +
    @@ -535,10 +615,12 @@

    详细设计

    @available(macOS 13.0, *)
     public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameResolving {
         public init(typeDatabase: TypeDatabase)
    +    public func moduleName(forTypeName typeName: String) async -> String?
    +    public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String?
     }
      -
    • SwiftInterfaceBuilderTypeNameProvider 保留名字与构造器签名,内部改用这个适配器和 ObjCDeclaredTypeNames。
    • -
    • swift-section objc interface --mark-sdk-swift-names:按镜像平台建只读 API notes 的 TypeDatabase(不碰 sourcekitd),为每个类与协议取标注;找不到 SDK 时打印 warning,输出与不加开关时相同。
    • +
    • SwiftInterfaceBuilderTypeNameProvider 保留公开名字与构造器签名,内部改为:按镜像平台建 TypeDatabase(LC_BUILD_VERSION 的 macCatalyst 映射到 .macCatalyst;原来映射到 .macOS,Catalyst 镜像因此读不到 UIKit 的 API notes),依赖镜像包成 ObjCDeclaredTypeNames,把查询转给一个 TypeDatabaseTypeNameResolver。
    • +
    • swift-section objc interface --mark-sdk-swift-names:按镜像 LC_BUILD_VERSION 的平台建 TypeDatabase(只读 API notes,moduleFilter 返回 false,所以不碰 sourcekitd),对每个类与协议取 ObjCSwiftImportNotes(apiNotesFor…:in:) 传给 ObjCInterfaceBuilder;找不到 SDK 时打印 warning,输出与不加开关时相同。
    @@ -547,14 +629,21 @@

    详细设计

    RuntimeViewer
      -
    • 进程内的索引:RuntimeTypeIndex 每个服务进程一个,每个 SDKPlatform 一个 TypeDatabase。平台按镜像来源取:共享缓存镜像、文件、LC_BUILD_VERSION。Mac Catalyst 用 macOS SDK(读 iOSSupport 里的 API notes,落地时实测确认)。
    • -
    • 预建:engine 连上与加载新镜像时,把依赖模块并进过滤条件,同一平台在建时合并请求。不可用时状态记原因,打印器不注册解析器。
    • -
    • 打印:每次按当前选项重建完整的解析器列表(opaque + 类型名),不再被 removeAllTypeNameResolvers() 误删;显示与语料两个打印器都这样做。就绪时清 section 的接口缓存,再广播 .typeNamesResolved。
    • -
    • 等待:waitsForTypeIndex 为真时,打印前等该平台索引就绪或不可用。MCP、命令行、导出置真,Find 语料构建一律等待;只在磁盘缓存冷的第一次会等。
    • -
    • 兼容性:三个新选项都用 @Default;新 case 只由新版 Mac 服务发出;旧对端不回应状态命令时当作不可用。
    • -
    • 语料 variant:…-ByCategory-TypeNames<platform>-<SDK 版本-build> 或 …-UnresolvedTypeNames。
    • -
    • 界面:Generation Options 的 Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,默认勾选;Report 新类别「Imported Type Names」,每个平台一行显示建立中、就绪(缓存大小)或不可用(原因)。
    • -
    • 内存:每个打印的服务进程各一份,落地时量一次 malloc 在用量写回提案。
    • +
    • 进程开关:RuntimeTypeNames.enableInThisProcess() 照 RuntimeDerivedData.enableInThisProcess() 的样子:四个 XPC service、Catalyst helper 与独立的命令行 host(CommandLineHostServer.start(),kind == .standalone 时;App 当 host 时打印在 App 的 service 里)在入口处打开。其余进程——App 本身、注入的 payload、iOS 设备、测试——都不打开,照旧印 __C.,也从不读 SDK、不写缓存。忘了调用不会坏事,只是那个进程不解析。
    • +
    • 进程内的索引:RuntimeTypeIndex 是每个打印进程一个的 actor(static let process)。它不经 @Dependency:RuntimeViewerCore 不依赖 swift-dependencies,能碰到它的只有 engine 与 section,和 RuntimeDerivedData 一样。按 SDKPlatform 各持一个 TypeDatabase: +
        +
      • 平台:一律取镜像第一个 LC_BUILD_VERSION 的平台(RuntimeTypeNames.platformName(of:),macCatalyst 映射到 .macCatalyst),共享缓存镜像、磁盘文件与已加载镜像同一条规则。没有这个 load command 的旧镜像不解析。
      • +
      • 批次:RuntimeSwiftSection.updateConfiguration 第一次为一个镜像配置时(resolvesImportedTypeNames 开着)调 request(_:),交出这个镜像链接的模块名(machO.dependencies 的 install name 推出模块名)和它自己的 ObjCDeclaredTypeNames。新模块、新镜像才排一批;平台的第一批同时读 API notes。同一平台的批次串起来依次执行,所以不会重复建。依赖镜像里的私有类型,要等那个依赖自己被打开(后台索引迟早会开)才算进来——不为打印一个镜像去打开它全部依赖的 ObjC 元数据。
      • +
      • 不可用:TypeIndexingAvailability 不可用时记下原因,不排批次,打印器不注册解析器,输出保持 __C.。
      • +
      • 内存:每个打印的服务进程各有一份(本机、Catalyst、每个文件、每个框架实例),落地时量一次 malloc 在用量写进提案(步骤 9)。
      • +
      +
    • +
    • 打印:每批完成把平台的 generation 加一。RuntimeSwiftSection 记着自己注册解析器时的 generation,下次配置时发现变了,就按当前选项重建完整的解析器列表(opaque 解析器 + 类型名解析器,互不误删),清掉 interfaceByObject / importedInterfaceByObject;语料打印器同样按 generation 重建。批次完成时 engine 把监听回调转成 broadcast(.typeNamesResolved(platformName:))(startObservingTypeIndex(),每个 engine 一次)。ObjC 头文件在 marksSwiftNamesFromAPINotes 开着时,把 swiftImportNotes(forClassNamed:/forProtocolNamed:platform:) 的结果与 objcSwiftImportNotes(for:) 合并;category 按它的类查。
    • +
    • 等待:GenerationOptions.waitsForTypeIndex 为 true 时,updateConfiguration 等这个镜像那一批完成再打印;false(界面)时直接打印。MCP(.mcp 预设)、命令行(每种选项来源都置 true)、导出(exportGenerationOptions)等待;Find 语料打印前一律等待(waitForTypeIndex(of:))。等待只在磁盘缓存冷、第一次生成某个 SDK 版本的模块接口时明显。
    • +
    • 兼容性:三个新选项都用 @Default,旧版对端解码时取默认;RuntimeDataChange 新 case 只由新版 Mac 服务发出,旧对端不会收到也不会发出;typeIndexStatus 命令对旧对端没有处理器,XPC 上没有处理器的命令被丢弃而不是回错,所以 typeIndexStatus() 经 dispatchToServingProcess(_:timeout:) 用连接自带的 2 秒超时发出,超时或出错都答 .empty,Report 里不显示这一类。
    • +
    • 语料 variant:RuntimeInterfaceCorpusSnapshot 的 variant 加一段 RuntimeTypeNamesCorpusVariant.component:开着索引、找得到 macOS SDK 时是 TypeNames-<SDK 版本-build>(共享缓存的 macOS 与 Mac Catalyst 镜像都对着 macOS SDK 读),否则 UnresolvedTypeNames。
    • +
    • 缓存位置:RuntimeTypeIndexLocation 从进程的 Bundle.main 往上找第一个是 RuntimeViewer 的 .app(RuntimeDerivedDataLocation.enclosingApplication),用 ~/Library/Caches/<bundle id>/TypeIndex,与 DerivedData 并列;App、它的 XPC service 与内嵌的命令行工具因此共用一份。不在 App 里的命令行工具用 ~/Library/Caches/runtime-viewer-cli/TypeIndex。Delete Derived Data 一并量它、删它(先改名再后台删)。
    • +
    • 界面:Generation Options 面板的 Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,都默认勾选。Report 新类别「Imported Type Names」(排在 Cross References 之后),每个平台一行:建立中(第几批 / 共几批)、就绪(模块数)、不可用(没有开发者目录 / 没装这个平台的 SDK),类别行带缓存大小;没有平台时整类不显示,没有取消、推出、清除。TypeIndexCoordinator 照 CrossReferencePreparationCoordinator:启动时、每次 .typeNamesResolved、engine 换进程时问一次状态,建立中每 2 秒问一次;建立中算进 isWorkInProgress(防 App Nap),工具栏显示 Indexing Imported Type Names。内容区收到 .typeNamesResolved 先在主线程清文档的接口缓存再重新取,避免缓存自己的清空排在重新取之后。
    @@ -667,43 +756,58 @@

    版本

    落地步骤

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

    收尾时判断:新包的 TypeIndexingPipeline.md 承担实现说明,RuntimeViewer 的 DerivedData.md 加一节;预计新术语「类型索引」「Swift 命名标注」进各仓库的术语表。

    +

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

    决策日志

    - 12 条,最近一条:Accepted + 27 条,最近一条:实现完成,待用户看过后收尾
    - - - + + + - + - - - + + + + + + + + + + + + + + + + + +
    日期变更说明
    2026-11-23Created as DraftRuntimeViewer 把桥接类型显示成 __C.UICellConfigurationState;二进制只记 ObjC 运行时名,改名只在 SDK 里,而已有的 TypeIndexing RuntimeViewer 用不上、改名规则有误。用户决定抽成独立包,三方接入
    2026-11-23否决二进制层面的推断同名桥接 20 个里 14 个是 XReference
    2026-11-23ObjC 一侧并入本提案用户选择一并做;新包因此不能依赖 MachOObjCSection
    2026-11-23Created as DraftRuntimeViewer 把 UICellConfigurationState 的桥接类型显示成 __C.UICellConfigurationState。查明二进制只记 ObjC 运行时名、改名只在 SDK 的 API notes 里,而 MachOSwiftSection 已有的 TypeIndexing RuntimeViewer 用不上、且改名规则有误;用户决定把它抽成独立的包,三方接入
    2026-11-23否决二进制层面的推断同名又桥接的 20 个 SDK 类型里 14 个是 XReference,与 __X 在二进制里无法区分
    2026-11-23ObjC 一侧并入本提案用户选择一并做,而不是另起提案;新包因此不能依赖 MachOObjCSection,ObjC 元数据一层改为协议注入
    2026-11-23新仓库名 swift-type-indexing用户选择;模块名仍是 TypeIndexing
    2026-11-23找得到 SDK 就自动开用户选择;Command Line Tools 也带 macOS SDK 与 sourcekitd(用户指出,本机核对)
    2026-11-23RuntimeViewer 找得到 SDK 就自动开用户选择;可用条件从「装了 Xcode」改为「找得到该平台 SDK」,因为 Command Line Tools 也带 macOS SDK 与 sourcekitd(用户指出,本机核对)
    2026-11-23ObjC 只标 Swift 命名、不加 @import用户选择
    2026-11-23后台预建、先显示 __C.用户选择
    2026-11-23提案放 MachOSwiftSection用户选择;其余仓库加 cross-repository 行
    2026-11-23MCP、命令行、导出一起换用户选择;非交互调用方等索引就绪(agent 自定,可推翻)
    2026-11-23开关放 Generation Optionsagent 自定,可推翻
    2026-11-23提案放在 MachOSwiftSection用户选择;其余三个仓库的索引加 cross-repository 行
    2026-11-23MCP、命令行、导出一起换用户选择;为了输出稳定,这些非交互的调用方等索引就绪(agent 自定,可推翻)
    2026-11-23开关放 Generation Options 面板agent 自定,可推翻:与现有打印开关同处,随请求发出、进缓存键、命令行也读同一份
    2026-11-23共识确认用户确认以上决定,开始写提案
    2026-11-23Accepted用户批准,开始实现
    2026-11-23swift-apinotes fork 加入范围它的 ObjCContext.methods / properties 在 0.2.0 是 internal,ObjC 成员的标注读不到。改为 public 并打 0.3.0(每个字段一行),比在新包里另写一套 YAML 解析更小;推送与打 tag 和新仓库一起经用户批准
    2026-11-23新增 SDKPlatform.macCatalyst提案原定 Catalyst 按 .macOS 索引并「落地时实测确认」:实测 SDKIndexer 不搜 System/iOSSupport,Catalyst UIKit 的 API notes 找不到;sourcekitd 按前端调用解析参数,macabi target 不会自动加 iOSSupport 框架路径(报 Could not load module: UIKit)。新 case 读 macOS SDK、先搜 iOSSupport、显式传 -Fsystem
    2026-11-23index 可多次调用、优先级改为查询时决定RuntimeViewer 加载新镜像时要追加模块;原先 API notes 靠写入顺序覆盖模块接口名,追加的接口名会把名字抢回去
    2026-11-23可用性返回 sdkSettings 而非 sdkPathRuntimeViewer 的语料 variant 要 SDK 版本与 build,SDKSettings 一并给出
    2026-11-23加默认关闭的 SDKIntegrationTests单测覆盖不到真实 SDK 布局与 sourcekitd 参数,上面两个 Catalyst 问题都是实测才发现的;手动开启,不进 CI
    2026-11-23MachOObjCSection、MachOSwiftSection、RuntimeViewer 临时钉功能分支MachOObjCSection 0.8.209 要等收尾才发,实现期间 MachOSwiftSection 对它、RuntimeViewer 对两者都钉 branch: "feature/swift-type-indexing-package"(清单里注明 TEMPORARY);收尾时发 0.8.209,MachOSwiftSection 改回 "0.8.209" ..< "0.9.0",RuntimeViewer 改回 branch: "next"
    2026-11-23RuntimeViewer 用进程开关,不配置缓存位置原定在各入口「配置缓存位置」。改为 RuntimeTypeNames.enableInThisProcess(),照派生数据的开关:缓存位置能从 Bundle.main 推出,真正要控制的是哪些进程读 SDK、跑 sourcekitd——测试、注入的 payload、App 本身都不该。Catalyst helper 也打开(它跑的是 Catalyst 的 engine);命令行 host 只在独立运行时打开
    2026-11-23RuntimeTypeIndex 不经 @Dependency原定 @Dependency + fileprivate static let shared。RuntimeViewerCore 不依赖 swift-dependencies,项目里 RuntimeDerivedData 也是同样的 static 单例
    2026-11-23平台一律取 LC_BUILD_VERSION,批次按镜像排原定共享缓存镜像查分区、文件查 RuntimeFile.platform,engine 连上时预建。改为每个镜像第一次打印时排一批(它链接的模块 + 它自己的 ObjC 元数据):一条规则覆盖三种镜像;只为打开了的镜像建,不在连上时为整个共享缓存跑 sourcekitd。依赖镜像的私有类型等那个依赖被打开时才算入
    2026-11-23刷新靠 generation,等待放在 section 配置时原定索引就绪时主动通知各 section 清缓存、在 _interface(for:) 里等待。改为 section 下次配置时比较平台的 generation,自己重建解析器、清缓存;waitsForTypeIndex 在 updateConfiguration 里等这个镜像那一批。少一条 actor 之间的回调,也不用记哪些 section 活着
    2026-11-23旧对端的状态答 .empty,不显示原定把「无应答」当 .unavailable。旧对端(iOS 设备、注入的进程、旧版本)本来就没有索引,Report 里多一行「不可用」只是噪音;查询经连接自带的 2 秒超时发出,因为没有处理器的命令在 XPC 上被丢弃、不回错,靠任务取消收不了尾
    2026-11-23语料 variant 只带 macOS SDK 的版本原定 TypeNames<platform>-<SDK>。服务进程的共享缓存镜像——macOS 与 Mac Catalyst——都对着同一个 macOS SDK 读,一段就够
    2026-11-23内容区刷新前自己清一次接口缓存文档的接口缓存在同一事件上清空,但它和内容区的订阅各自调度,先后没有保证;内容区先在主线程清再重新取,读不到批次之前的旧结果
    2026-11-23一条既有测试的夹具换类RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 HelperCoders,它让 ISO8601DateFormatter 遵循 DateFormatConverter;镜像把一个类的遵循列成一个条目,「只采纳私有 @objc 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 EnergyFormatter,测试先断言该类只有一个遵循条目
    2026-11-23实现完成,待用户看过后收尾新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(TitleActivityIndicatorTests 一条基线必红);./TuistScript.sh check 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去
    diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.md b/Documentations/Evolutions/draft-swift-type-indexing-package.md index d5f4650b..92a62a53 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.md +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.md @@ -181,26 +181,27 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | |---|---|---|---|---| -| `RuntimeViewerCore/Package.swift` | 修改 | 加 swift-type-indexing(本地候选 `../../swift-type-indexing` + 远端,限 macOS);`RuntimeViewerCore` target 加 `TypeIndexing`、`ObjCTypeIndexing`、`SwiftTypeNameResolution` 三个 product(限 macOS) | 接线 | 8 | +| `RuntimeViewerCore/Package.swift` | 修改 | 加 swift-type-indexing(本地候选 `../../swift-type-indexing` + 远端,限 macOS);`RuntimeViewerCore` target 加 `TypeIndexing`、`ObjCTypeIndexing`、`SwiftTypeNameResolution` 三个 product(限 macOS)。**实现期间** MachOObjCSection 与 MachOSwiftSection 临时钉 `branch: "feature/swift-type-indexing-package"`,收尾时改回 `branch: "next"` | 接线 | 8 | | `RuntimeViewer-Local.xcworkspace/contents.xcworkspacedata`、`.worktrees/swift-type-indexing` 链接、`Documentations/Guides/LocalDependencies.md:37-44` | 修改 | 加 `../swift-type-indexing` | 本地联调 | 8 | | `Tuist.swift:49-110`、`TuistScript.sh:82` | 修改 | 删本仓库的 `"TypeIndexing"`,加 `"SwiftTypeNameResolution"`、MachOObjCSection 的 `"ObjCTypeIndexing"`;swift-type-indexing 加进 `SOURCE_DEPENDENCIES` 并列出它的 target | Tuist 描述同批 | 8 | | `AGENTS.md`「Dependency floors」 | 修改 | 加 swift-type-indexing 的版本下限与理由 | 规则 | 8 | -| `RuntimeViewerCore/Sources/RuntimeViewerCore/TypeNames/RuntimeTypeIndex.swift` · `RuntimeTypeIndex` | 新增 | actor,每进程一个;每个 `SDKPlatform` 一个 `TypeDatabase`;`prepare(for images:)` 后台预建;`status`;`resolver(forImageAt:)`;完成时回调 | 进程级共享索引 | 9 | +| `RuntimeViewerCore/Sources/RuntimeViewerCore/TypeNames/RuntimeTypeIndex.swift` · `RuntimeTypeIndex` | 新增 | actor,每进程一个(`static let process`,不经 `@Dependency`,见决策日志);每个 `SDKPlatform` 一个 `TypeDatabase`;`request(_:)` 把一个镜像链接的模块和它自己的 ObjC 元数据排成一批,同平台的批次依次执行;每批完成把平台的 generation 加一并通知监听者;`resolution(for:)`、`swiftImportNotes(forClassNamed:/forProtocolNamed:platform:)`、`status()` | 进程级共享索引 | 9 | +| `.../TypeNames/RuntimeTypeNames.swift` · `RuntimeTypeNames` | 新增 | 进程开关 `enableInThisProcess()`(照 `RuntimeDerivedData.enableInThisProcess()`);`platformName(of:)` 取镜像第一个 `LC_BUILD_VERSION` 的平台 | 只有打印的服务进程建索引 | 9 | | `.../TypeNames/RuntimeTypeIndexLocation.swift` | 新增 | 缓存目录:`.app` / `Contents/XPCServices` / `Contents/Applications` 往上找 `.app` → `~/Library/Caches//TypeIndex`;不在 App 里 → `~/Library/Caches/runtime-viewer-cli/TypeIndex`;测试用临时目录 | 所有进程共用缓存 | 9 | | `.../TypeNames/RuntimeTypeIndexStatus.swift` | 新增 | 线上类型:每个平台 `building(progress)` / `ready` / `unavailable(reason)`、缓存字节数 | Report 与工具栏 | 9 | -| `.../TypeNames/RuntimeEngine+TypeIndex.swift` · `TypeIndexStatusCommand` | 新增 | Core 自有命令 `typeIndexStatus`,路由属于「问服务进程本身」(neither),带说明注释;加进 `SharedCacheRoutingDeclarationTests` 的清单 | 让 App 读状态 | 9 | +| `.../TypeNames/RuntimeEngine+TypeNames.swift`、`Engine/RuntimeEngine+Commands.swift` · `TypeIndexStatusCommand` | 新增 | Core 自有命令 `typeIndexStatus`,路由 `.servingEngine`,加进 `SharedCacheRoutingDeclarationTests` 的清单;`typeIndexStatus()` 经新的 `dispatchToServingProcess(_:timeout:)` 发出、连接自带 2 秒超时,旧对端答 `.empty`;`startObservingTypeIndex()` 把批次完成转成广播;`RuntimeTypeNamesCorpusVariant` | 让 App 读状态 | 9 | | `.../Engine/RuntimeDataChange.swift` | 修改 | 新 case `typeNamesResolved(platform: String)` | 通知 App 刷新 | 9 | | `.../Sections/Swift/RuntimeSwiftSection.swift` | 修改 | 显示打印器与语料打印器都注册 `TypeDatabaseTypeNameResolver`;`updateConfiguration` 每次按开关重建解析器列表(不再被 `removeAllTypeNameResolvers()` 误删);收到索引就绪时清 `interfaceByObject` / `importedInterfaceByObject` | 打印解析后的名字 | 9 | | `.../Sections/ObjC/RuntimeObjCSection.swift:146-236`、`RuntimeEngine.swift:956-962`、`Search/RuntimeEngine+Search.swift:355-356` | 修改 | 类、协议、category 都取 API notes 标注,与 `objcSwiftImportNotes(for:)` 合并后传入 | ObjC 标注 | 9 | | `.../Interfaces/SwiftGenerationOptions.swift` | 修改 | `@Default(true) resolvesImportedTypeNames` | 开关 | 9 | | `.../Interfaces/RuntimeObjectInterface+GenerationOptions.swift` · `GenerationOptions` | 修改 | `@Default(true) marksSwiftNamesFromAPINotes`(ObjC 头文件的开关,放顶层:`objcHeaderOptions` 是 MachOObjCSection 的 `ObjCGenerationOptions`,而这个开关只决定 RuntimeViewer 传不传标注);`@Default(false) waitsForTypeIndex` | 开关;非交互的调用方等索引 | 9 | | `.../Search/Corpus/RuntimeInterfaceCorpusSnapshot.swift:29-31`、`RuntimeInterfaceCorpusStore.swift:357-369` | 修改 | variant 加 `-TypeNames` 或 `-UnresolvedTypeNames`;内存比较加同一条件;语料构建前等索引 | 语料与显示一致 | 9 | -| `ServicePluginEntry.swift`(本机、Catalyst、文件、框架四个入口)、命令行 host 入口 | 修改 | 进程启动时配置 `RuntimeTypeIndex` 的缓存位置 | 每个打印的进程 | 9 | +| `ServicePluginEntry.swift`(本机、Catalyst、文件、框架四个 service 与 Catalyst helper 五个入口)、`CommandLineHostServer.start()`(只在独立 host) | 修改 | 进程启动时 `RuntimeTypeNames.enableInThisProcess()`;缓存位置由 `RuntimeTypeIndexLocation` 从 `Bundle.main` 推出,不用配置 | 每个打印的进程 | 9 | | `RuntimeViewerAppCore/BackgroundWork/TypeIndex/TypeIndexCoordinator.swift` | 新增 | 照 `CrossReferencePreparationCoordinator`:读状态、`isWorkInProgress`、`close()` | Report 与 App Nap | 10 | | `RuntimeEngineBackgroundWork.swift:85-137` | 修改 | 创建协调器,并入 `isWorkInProgress`、activity reporter、`close()` | 接入后台工作 | 10 | | `Reports/ReportNode.swift`、`ReportTreeBuilder.swift`、`ReportViewModel.swift` | 修改 | 新 `ReportCategory.importedTypeNames` 及其节点;状态、原因、缓存大小 | Report 可见 | 10 | -| `Activity/RuntimeEngineActivityReporter.swift`、`Activity/ToolbarActivity.swift` | 修改 | 新活动种类与文案 | 工具栏进度 | 10 | -| `Content/ContentTextViewModel.swift:227-247`、`Base/ViewModel.swift:52-63` | 修改 | 收到 `.typeNamesResolved` 时重新取当前内容 | 建好后自动刷新 | 10 | +| `Activity/RuntimeEngineActivityReporter.swift`、`Activity/ToolbarActivity.swift`、`Presentation/SystemSymbol.swift` | 修改 | 新活动种类(每个批次一项,文案 Indexing Imported Type Names)与 Report 图标 `shippingbox` | 工具栏进度 | 10 | +| `Content/ContentTextViewModel.swift` | 修改 | 收到 `.typeNamesResolved` 时先在主线程清文档的接口缓存,再重新取当前内容(`Base/ViewModel.swift` 不用改) | 建好后自动刷新 | 10 | | `RuntimeViewerUsingAppKit/.../Generation Options/GenerationOptionsViewController.swift` | 修改 | Swift 组加「Resolve Imported Type Names」,ObjC 组加「Mark Swift Names From SDK」 | 开关 | 10 | | `RuntimeViewerUsingAppKit/.../App/RuntimeDerivedDataController.swift:50-93`、`DerivedDataStorage/RuntimeDerivedDataMaintenance.swift` | 修改 | 量与删都包括 `TypeIndex` 目录;确认框文案提到它 | Delete Derived Data 一起删 | 10 | | `RuntimeViewerMCPBridge/MCPBridgeServer.swift:822-834`、`RuntimeViewerCommandLineInterface/CommandExecutor.swift:444-450,578-596`、`Export/RuntimeEngine+Export.swift:44` | 修改 | 置 `waitsForTypeIndex = true` | 输出稳定 | 11 | @@ -261,19 +262,25 @@ TypeDatabase (actor, no longer generic) ### RuntimeViewer 的数据流(建立与刷新) ```text -engine connects (service process) - └─> RuntimeTypeIndex.prepare(platform, linked modules) background, Report row "Imported Type Names" - ├─> TypeIndexingAvailability.availability(for:) unavailable -> status .unavailable(reason), stop - └─> TypeDatabase.index(dependencies:moduleFilter:) reads/writes ~/Library/Caches//TypeIndex - └─> done - ├─> RuntimeSwiftSection: register TypeDatabaseTypeNameResolver, clear interface caches - └─> broadcast RuntimeDataChange.typeNamesResolved(platform:) - └─> app: RuntimeInterfaceCache.invalidateAll() - └─> ContentTextViewModel refetches -> "UIKit.__UICellConfigurationState" +service process starts (local / Catalyst / file / framework service, Catalyst helper, standalone CLI host) + └─> RuntimeTypeNames.enableInThisProcess() + +RuntimeSwiftSection.updateConfiguration(for: options) an image is printed (resolvesImportedTypeNames on) + └─> RuntimeTypeIndex.process.request(platform of LC_BUILD_VERSION, + modules the image links, the image's own ObjC metadata) + ├─> TypeIndexingAvailability.availability(for:) unavailable -> status .unavailable(reason), no batch + └─> batch, after the platform's previous one Report row "Imported Type Names", toolbar activity + └─> TypeDatabase.index(dependencies:moduleFilter:) reads/writes ~/Library/Caches//TypeIndex + └─> generation += 1, listeners called + ├─> next print: section sees a new generation -> registers TypeDatabaseTypeNameResolver, + │ drops interfaceByObject / importedInterfaceByObject + └─> engine broadcasts RuntimeDataChange.typeNamesResolved(platformName:) + └─> app: ContentTextViewModel flushes RuntimeInterfaceCache, refetches + -> "UIKit.__UICellConfigurationState" interface request - ├─ UI (waitsForTypeIndex = false) -> prints now: "__C.X" until ready - └─ MCP/CLI/export/Find corpus (waitsForTypeIndex = true) -> awaits ready | unavailable, then prints + ├─ UI (waitsForTypeIndex = false) -> prints now: "__C.X" until the image's batch is done + └─ MCP/CLI/export/Find corpus (waitsForTypeIndex = true) -> awaits the image's batch, then prints ``` ## 详细设计 @@ -468,22 +475,26 @@ public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameRe ### RuntimeViewer -**进程内的索引**。`RuntimeTypeIndex` 是每个服务进程一个的 actor(经 `@Dependency` 取得,`fileprivate static let shared`),按 `SDKPlatform` 各持一个 `TypeDatabase`: +**进程开关**。`RuntimeTypeNames.enableInThisProcess()` 照 `RuntimeDerivedData.enableInThisProcess()` 的样子:四个 XPC service、Catalyst helper 与独立的命令行 host(`CommandLineHostServer.start()`,`kind == .standalone` 时;App 当 host 时打印在 App 的 service 里)在入口处打开,其余进程——App 本身、注入的 payload、iOS 设备、测试——都不打开,照旧印 `__C.`,也从不读 SDK、不写缓存。忘了调用不会坏事,只是那个进程不解析。 -- 平台:共享缓存镜像用 `RuntimeSharedCachePartition.platform(ofImageAt:)`(macOS → `.macOS`,Mac Catalyst → `.macCatalyst`);文件用 `RuntimeFile.platform`;其余镜像读 `LC_BUILD_VERSION`(`macCatalyst` 平台号映射到 `.macCatalyst`)。 -- 预建:engine 连上后、以及新加载的镜像,把它们的依赖模块名并进 `moduleFilter`,依赖镜像包成 `ObjCDeclaredTypeNames` 交给 `index(dependencies:moduleFilter:)`。同一平台已在建时合并请求,不重复建。 -- 不可用:`TypeIndexingAvailability` 不可用时状态记为 `.unavailable(reason)`,打印器不注册解析器,输出保持 `__C.`。 +**进程内的索引**。`RuntimeTypeIndex` 是每个打印进程一个的 actor(`static let process`)。它不经 `@Dependency`:`RuntimeViewerCore` 不依赖 swift-dependencies,能碰到它的只有 engine 与 section,和 `RuntimeDerivedData` 一样。按 `SDKPlatform` 各持一个 `TypeDatabase`: + +- 平台:一律取镜像第一个 `LC_BUILD_VERSION` 的平台(`RuntimeTypeNames.platformName(of:)`,`macCatalyst` 映射到 `.macCatalyst`),共享缓存镜像、磁盘文件与已加载镜像同一条规则。没有这个 load command 的旧镜像不解析。 +- 批次:`RuntimeSwiftSection.updateConfiguration` 第一次为一个镜像配置时(`resolvesImportedTypeNames` 开着)调 `request(_:)`,交出这个镜像链接的模块名(`machO.dependencies` 的 install name 推出模块名)和它自己的 `ObjCDeclaredTypeNames`。新模块、新镜像才排一批;平台的第一批同时读 API notes。同一平台的批次串起来依次执行,所以不会重复建。依赖镜像里的私有类型,要等那个依赖自己被打开(后台索引迟早会开)才算进来——不为打印一个镜像去打开它全部依赖的 ObjC 元数据。 +- 不可用:`TypeIndexingAvailability` 不可用时记下原因,不排批次,打印器不注册解析器,输出保持 `__C.`。 - 内存:每个打印的服务进程各有一份(本机、Catalyst、每个文件、每个框架实例),落地时量一次 `malloc` 在用量写进提案(步骤 9)。 -**打印**。`RuntimeSwiftSection.updateConfiguration` 现在在 opaque 开关关闭时 `removeAllTypeNameResolvers()`;改为每次按当前选项重建完整的解析器列表(opaque 解析器 + 类型名解析器),两者互不误删。显示打印器与语料打印器都这样做。索引就绪时 `RuntimeTypeIndex` 通知各 section 清掉 `interfaceByObject` / `importedInterfaceByObject` 并重建解析器列表,然后由 engine `broadcast(.typeNamesResolved(platform:))`。 +**打印**。每批完成把平台的 generation 加一。`RuntimeSwiftSection` 记着自己注册解析器时的 generation,下次配置时发现变了,就按当前选项重建完整的解析器列表(opaque 解析器 + 类型名解析器,互不误删),清掉 `interfaceByObject` / `importedInterfaceByObject`;语料打印器同样按 generation 重建。批次完成时 engine 把监听回调转成 `broadcast(.typeNamesResolved(platformName:))`(`startObservingTypeIndex()`,每个 engine 一次)。ObjC 头文件在 `marksSwiftNamesFromAPINotes` 开着时,把 `swiftImportNotes(forClassNamed:/forProtocolNamed:platform:)` 的结果与 `objcSwiftImportNotes(for:)` 合并;category 按它的类查。 + +**等待**。`GenerationOptions.waitsForTypeIndex` 为 `true` 时,`updateConfiguration` 等这个镜像那一批完成再打印;`false`(界面)时直接打印。MCP(`.mcp` 预设)、命令行(每种选项来源都置 `true`)、导出(`exportGenerationOptions`)等待;Find 语料打印前一律等待(`waitForTypeIndex(of:)`)。等待只在磁盘缓存冷、第一次生成某个 SDK 版本的模块接口时明显。 -**等待**。`GenerationOptions.waitsForTypeIndex` 为 `true` 时,`RuntimeEngine._interface(for:options:)` 在打印前 `await` 该镜像平台的索引就绪或不可用;`false`(界面)时直接打印。MCP、命令行、导出把它置 `true`;Find 语料构建一律等待。等待只发生在第一次(磁盘缓存冷)建立某个 SDK 版本的模块时。 +**兼容性**。三个新选项都用 `@Default`,旧版对端解码时取默认;`RuntimeDataChange` 新 case 只由新版 Mac 服务发出,旧对端不会收到也不会发出;`typeIndexStatus` 命令对旧对端没有处理器,XPC 上没有处理器的命令被丢弃而不是回错,所以 `typeIndexStatus()` 经 `dispatchToServingProcess(_:timeout:)` 用连接自带的 2 秒超时发出,超时或出错都答 `.empty`,Report 里不显示这一类。 -**兼容性**。三个新选项都用 `@Default`,旧版对端解码时取默认;`RuntimeDataChange` 新 case 只由新版 Mac 服务发出,iOS 设备等旧对端不会收到也不会发出;`typeIndexStatus` 命令对旧对端没有处理器,App 把「无应答」当作 `.unavailable`。 +**语料 variant**。`RuntimeInterfaceCorpusSnapshot` 的 variant 加一段 `RuntimeTypeNamesCorpusVariant.component`:开着索引、找得到 macOS SDK 时是 `TypeNames-`(共享缓存的 macOS 与 Mac Catalyst 镜像都对着 macOS SDK 读),否则 `UnresolvedTypeNames`。 -**语料 variant**。`RuntimeInterfaceCorpusSnapshot.variant(for:)` 变为 `"\(transformer.derivedDataDigest)-ByCategory-\(typeNamesComponent)"`,`typeNamesComponent` 是 `TypeNames-`(解析了)或 `UnresolvedTypeNames`;内存里的比较加同样的条件。 +**缓存位置**。`RuntimeTypeIndexLocation` 从进程的 `Bundle.main` 往上找第一个是 RuntimeViewer 的 `.app`(`RuntimeDerivedDataLocation.enclosingApplication`),用 `~/Library/Caches//TypeIndex`,与 `DerivedData` 并列;App、它的 XPC service 与内嵌的命令行工具因此共用一份。不在 App 里的命令行工具用 `~/Library/Caches/runtime-viewer-cli/TypeIndex`。Delete Derived Data 一并量它、删它(先改名再后台删)。 -**界面**。Generation Options 面板:Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,都默认勾选。Report 新类别「Imported Type Names」,每个 engine 下每个平台一行:建立中(进度)、就绪(缓存大小)、不可用(原因:没有开发者目录 / 没装这个平台的 SDK)。 +**界面**。Generation Options 面板:Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,都默认勾选。Report 新类别「Imported Type Names」(排在 Cross References 之后),每个平台一行:建立中(第几批 / 共几批)、就绪(模块数)、不可用(没有开发者目录 / 没装这个平台的 SDK),类别行带缓存大小;没有平台时整类不显示,没有取消、推出、清除。`TypeIndexCoordinator` 照 `CrossReferencePreparationCoordinator`:启动时、每次 `.typeNamesResolved`、engine 换进程时问一次状态,建立中每 2 秒问一次;建立中算进 `isWorkInProgress`(防 App Nap),工具栏显示 Indexing Imported Type Names。内容区收到 `.typeNamesResolved` 先在主线程清文档的接口缓存再重新取,避免缓存自己的清空排在重新取之后。 ## 替代方案考量 @@ -559,17 +570,17 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` - 行为:`cacheEntriesAreWrittenUnderTheGivenDirectory` - 行为:`macCatalystSearchesIOSSupportFirst`、`macCatalystTargetTripleIsMacABI`、`macCatalystInterfaceGenerationSeesIOSSupportFrameworks`、`macCatalystCachesApartFromMacOS` - 实测(`SDKIntegrationTests`):Catalyst 下 `UICellConfigurationState` → `UIKit` / `__UICellConfigurationState`;macOS 下 `PKDrawing` → `PencilKit` / `PKDrawingReference`;sourcekitd 冷生成 Catalyst 的 UIKit 接口后 `UIStackView` → `UIKit` -3. ✅ **ObjC 容器的 API notes 查询**(2026-11-23 在本机完成;fork 的 0.3.0 与新包的推送待用户批准公开仓库)——`SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`TypeDatabase.swiftImportAnnotations(…)`。 +3. ✅ **ObjC 容器的 API notes 查询**(2026-11-23 完成;用户批准后 fork 推送并打 `0.3.0`,新仓库 `swift-type-indexing` 公开、推送并打 `0.1.0`)——`SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`TypeDatabase.swiftImportAnnotations(…)`。 - 行为:`classAnnotationCarriesSwiftNameAndSwiftPrivate` - 行为:`methodAnnotationIsKeyedBySelectorAndKind` - 行为:`propertyAnnotationIsKeyedByNameAndKind` - 行为:`protocolAnnotationsAreSeparateFromClassAnnotations` - 前置:swift-apinotes fork 把 `ObjCContext.methods` / `properties` 改成 `public`,打 `0.3.0`。 - 新包打 `0.1.0` 并推送(公开仓库)。 -4. **MachOObjCSection 接入新包**——`Package.swift`、`ObjCTypeIndexing`、`ObjCDeclaredTypeNames`。 +4. ✅ **MachOObjCSection 接入新包**(2026-11-23 完成)——`Package.swift`、`ObjCTypeIndexing`、`ObjCDeclaredTypeNames`。 - 行为:`declaredTypeNamesListFoundationClassesProtocolsAndStructs` - 行为:`typeDatabaseAttributesPrivateClassThroughObjCDeclaredTypeNames` -5. **ObjC 头文件的 Swift 命名标注**——`ObjCSwiftImportNotes` 扩展、协议与 category 入口、类型一级宏、API notes 转换。 +5. ✅ **ObjC 头文件的 Swift 命名标注**(2026-11-23 完成)——`ObjCSwiftImportNotes` 扩展、协议与 category 入口、类型一级宏、API notes 转换。 - 行为:`memberSwiftNamePrintsBeforeRefinedForSwift` - 行为:`classDeclarationNotePrintsOnItsOwnLineAboveInterface` - 行为:`protocolInterfaceTakesNotes` @@ -577,18 +588,18 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` - 行为:`mergingKeepsBothSourcesAndTheArgumentWinsPerField` - 行为:`apiNotesForClassBecomeNotes`(临时 `.apinotes` 驱动) - 行为:`markedRenderingStillProjectsToPlainRendering` -6. **本仓库切换到新包**——删 `TypeIndexing`、加 `SwiftTypeNameResolution`、CLI 接线、文档与 skill。 +6. ✅ **本仓库切换到新包**(2026-11-23 完成)——删 `TypeIndexing`、加 `SwiftTypeNameResolution`、CLI 接线、文档与 skill。 - 行为:`resolverMapsEveryPrinterCategory` - 行为:`resolverPrintsResolvedModuleAndSwiftName`(假的 `TypeDatabase` 数据驱动打印器) - 行为:`resolveCModuleNamesFlagStillMapsToRequest` - 端到端(维护者手动):`swift-section interface --resolve-c-module-names` 对 UIKitCore(Catalyst)输出 `UIKit.__UICellConfigurationState`、对 PencilKit 输出 `PencilKit.PKDrawingReference`。 -7. **`swift-section objc --mark-sdk-swift-names`**。 +7. ✅ **`swift-section objc --mark-sdk-swift-names`**(2026-11-23 完成;`ObjCRequestTests` 按 CI 的步骤先用 Xcode 26.6 编出 `SymbolTestsCore` 夹具再跑,17 条全过)。 - 行为:`markSDKSwiftNamesFlagMapsToRequest` - 行为:`missingSDKWarnsAndPrintsUnmarkedOutput` - 端到端(手动):PencilKit 的 `PKDrawing` 头文件出现 `NS_SWIFT_NAME(PKDrawingReference)`。 -8. **RuntimeViewer 依赖接线**——`RuntimeViewerCore/Package.swift`、Local workspace 与 `.worktrees` 链接、Tuist、`AGENTS.md` 依赖下限、三个 workspace 的锁文件(`UpdatePackagesScript.sh`)。 +8. ✅ **RuntimeViewer 依赖接线**(2026-11-23 完成;`Tuist.swift` 顺带补上 MachOSwiftSection 早已有的 `SwiftSectionTestingMacros`,`next` 上 `check` 本来就因它不过;`RuntimeViewerServer.xcodeproj` 自带的锁文件在 `next` 上已过时,重新解析会带进无关升级,没有动)——`RuntimeViewerCore/Package.swift`、Local workspace 与 `.worktrees` 链接、Tuist、`AGENTS.md` 依赖下限、三个 workspace 的锁文件(`UpdatePackagesScript.sh`)。 - 行为:`./TuistScript.sh check` 通过;Debug workspace 能编过。 -9. **RuntimeViewer Core**——`TypeNames/` 目录、`RuntimeDataChange` 新 case、`typeIndexStatus` 命令、打印器接线、ObjC 标注合并、三个选项、语料 variant、四个服务与命令行 host 的入口配置。实测:Catalyst 镜像的 API notes 确实来自 `iOSSupport`;记录每个服务进程多出的 `malloc` 在用量。 +9. ✅ **RuntimeViewer Core**(2026-11-23 完成;行为测试按实际做法落在 `RuntimeTypeNamesTests`、`SharedCacheRoutingDeclarationTests` 与 MachOSwiftSection、swift-type-indexing 的测试里;各服务进程多出的 `malloc` 在用量没有量,留作后续)——`TypeNames/` 目录、`RuntimeDataChange` 新 case、`typeIndexStatus` 命令、打印器接线、ObjC 标注合并、三个选项、语料 variant、四个服务与命令行 host 的入口配置。实测:Catalyst 镜像的 API notes 确实来自 `iOSSupport`;记录每个服务进程多出的 `malloc` 在用量。 - 行为:`typeIndexBuildsOncePerPlatformAndMergesConcurrentRequests` - 行为:`unavailableSDKLeavesImportedNamesUnresolved` - 行为:`resolverSurvivesOpaqueTypeSwitchOff` @@ -602,13 +613,13 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` - 行为:`typeIndexStatusCommandRoutesToServingProcess` - 行为:`olderPeerDecodesOptionsWithDefaults` - 行为:`cacheLocationWalksUpToEnclosingApp`(App、XPC service、内嵌命令行三种位置) -10. **RuntimeViewer App**——协调器、Report、工具栏活动、内容刷新、Generation Options 两个开关、Delete Derived Data。 +10. ✅ **RuntimeViewer App**(2026-11-23 完成;`contentRefetchesOnTypeNamesResolved` 即 `ContentTextPipelineTests` 的「a finished batch of the type index refetches the interface on screen」;Delete Derived Data 的两条没有单独的测试,App 一侧只是把同一个目录交给 `RuntimeTypeIndexLocation` 的量与删,后者有测试)——协调器、Report、工具栏活动、内容刷新、Generation Options 两个开关、Delete Derived Data。 - 行为:`typeIndexCoordinatorReportsBuildingReadyAndUnavailable` - 行为:`reportListsImportedTypeNamesPerPlatform` - 行为:`contentRefetchesOnTypeNamesResolved` - 行为:`deleteDerivedDataRemovesTypeIndexDirectory` - 行为:`derivedDataSizeIncludesTypeIndexDirectory` -11. **MCP、命令行、导出与插件**——`waitsForTypeIndex`、skill、两个插件清单 `1.4.0`、`CommandLineInterface.md`。 +11. ✅ **MCP、命令行、导出与插件**(2026-11-23 完成;MCP 一条由 `RuntimeTypeNamesTests` 的「An interactive print does not wait…; MCP's does」覆盖)——`waitsForTypeIndex`、skill、两个插件清单 `1.4.0`、`CommandLineInterface.md`。 - 行为:`mcpOptionsWaitForTypeIndex` - 行为:`commandLineOptionsWaitForTypeIndex` - 行为:`exportConfigurationWaitsForTypeIndex` @@ -634,8 +645,18 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` | 2026-11-23 | 开关放 Generation Options 面板 | agent 自定,可推翻:与现有打印开关同处,随请求发出、进缓存键、命令行也读同一份 | | 2026-11-23 | 共识确认 | 用户确认以上决定,开始写提案 | | 2026-11-23 | Accepted | 用户批准,开始实现 | -| 2026-11-23 | swift-apinotes fork 加入范围 | 它的 `ObjCContext.methods` / `properties` 在 0.2.0 是 internal,ObjC 成员的标注读不到。改为 `public` 并打 0.3.0(每个字段一行),比在新包里另写一套 YAML 解析更小;推送与打 tag 和新仓库一起请用户批准 | +| 2026-11-23 | swift-apinotes fork 加入范围 | 它的 `ObjCContext.methods` / `properties` 在 0.2.0 是 internal,ObjC 成员的标注读不到。改为 `public` 并打 0.3.0(每个字段一行),比在新包里另写一套 YAML 解析更小;推送与打 tag 和新仓库一起经用户批准 | | 2026-11-23 | 新增 `SDKPlatform.macCatalyst` | 提案原定 Catalyst 按 `.macOS` 索引并「落地时实测确认」:实测 `SDKIndexer` 不搜 `System/iOSSupport`,Catalyst UIKit 的 API notes 找不到;sourcekitd 按前端调用解析参数,macabi target 不会自动加 iOSSupport 框架路径(报 `Could not load module: UIKit`)。新 case 读 macOS SDK、先搜 iOSSupport、显式传 `-Fsystem` | | 2026-11-23 | `index` 可多次调用、优先级改为查询时决定 | RuntimeViewer 加载新镜像时要追加模块;原先 API notes 靠写入顺序覆盖模块接口名,追加的接口名会把名字抢回去 | | 2026-11-23 | 可用性返回 `sdkSettings` 而非 `sdkPath` | RuntimeViewer 的语料 variant 要 SDK 版本与 build,`SDKSettings` 一并给出 | | 2026-11-23 | 加默认关闭的 `SDKIntegrationTests` | 单测覆盖不到真实 SDK 布局与 sourcekitd 参数,上面两个 Catalyst 问题都是实测才发现的;手动开启,不进 CI | +| 2026-11-23 | MachOObjCSection、MachOSwiftSection、RuntimeViewer 临时钉功能分支 | MachOObjCSection 0.8.209 要等收尾才发,实现期间 MachOSwiftSection 对它、RuntimeViewer 对两者都钉 `branch: "feature/swift-type-indexing-package"`(清单里注明 TEMPORARY);收尾时发 0.8.209,MachOSwiftSection 改回 `"0.8.209" ..< "0.9.0"`,RuntimeViewer 改回 `branch: "next"` | +| 2026-11-23 | RuntimeViewer 用进程开关,不配置缓存位置 | 原定在各入口「配置缓存位置」。改为 `RuntimeTypeNames.enableInThisProcess()`,照派生数据的开关:缓存位置能从 `Bundle.main` 推出,真正要控制的是哪些进程读 SDK、跑 sourcekitd——测试、注入的 payload、App 本身都不该。Catalyst helper 也打开(它跑的是 Catalyst 的 engine);命令行 host 只在独立运行时打开 | +| 2026-11-23 | `RuntimeTypeIndex` 不经 `@Dependency` | 原定 `@Dependency` + `fileprivate static let shared`。`RuntimeViewerCore` 不依赖 swift-dependencies,项目里 `RuntimeDerivedData` 也是同样的 `static` 单例 | +| 2026-11-23 | 平台一律取 `LC_BUILD_VERSION`,批次按镜像排 | 原定共享缓存镜像查分区、文件查 `RuntimeFile.platform`,engine 连上时预建。改为每个镜像第一次打印时排一批(它链接的模块 + 它自己的 ObjC 元数据):一条规则覆盖三种镜像;只为打开了的镜像建,不在连上时为整个共享缓存跑 sourcekitd。依赖镜像的私有类型等那个依赖被打开时才算入 | +| 2026-11-23 | 刷新靠 generation,等待放在 section 配置时 | 原定索引就绪时主动通知各 section 清缓存、在 `_interface(for:)` 里等待。改为 section 下次配置时比较平台的 generation,自己重建解析器、清缓存;`waitsForTypeIndex` 在 `updateConfiguration` 里等这个镜像那一批。少一条 actor 之间的回调,也不用记哪些 section 活着 | +| 2026-11-23 | 旧对端的状态答 `.empty`,不显示 | 原定把「无应答」当 `.unavailable`。旧对端(iOS 设备、注入的进程、旧版本)本来就没有索引,Report 里多一行「不可用」只是噪音;查询经连接自带的 2 秒超时发出,因为没有处理器的命令在 XPC 上被丢弃、不回错,靠任务取消收不了尾 | +| 2026-11-23 | 语料 variant 只带 macOS SDK 的版本 | 原定 `TypeNames-`。服务进程的共享缓存镜像——macOS 与 Mac Catalyst——都对着同一个 macOS SDK 读,一段就够 | +| 2026-11-23 | 内容区刷新前自己清一次接口缓存 | 文档的接口缓存在同一事件上清空,但它和内容区的订阅各自调度,先后没有保证;内容区先在主线程清再重新取,读不到批次之前的旧结果 | +| 2026-11-23 | 一条既有测试的夹具换类 | RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 `HelperCoders`,它让 `ISO8601DateFormatter` 遵循 `DateFormatConverter`;镜像把一个类的遵循列成一个条目,「只采纳私有 `@objc` 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 `EnergyFormatter`,测试先断言该类只有一个遵循条目 | +| 2026-11-23 | 实现完成,待用户看过后收尾 | 新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(`TitleActivityIndicatorTests` 一条基线必红);`./TuistScript.sh check` 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去 | From 86a5d39da194a83d6c75b700e940107e39bc8bfe Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 23 Nov 2026 21:21:20 +0800 Subject: [PATCH 080/175] Colour macros in swift-section; record the macro colour fix in the proposal objc interface --mark-sdk-swift-names prints NS_SWIFT_NAME and NS_REFINED_FOR_SWIFT as SemanticType.macro runs now (MachOObjCSection); swift-section colours them with Xcode's Default themes' macro colours. swift-semantic-string is pinned to its feature branch until 0.7.0. The proposal records the fix, the Xcode evidence, swift-semantic-string joining the scope, and the two wrap-up steps it adds. --- .../draft-swift-type-indexing-package.html | 34 +++++++++++++++++-- .../draft-swift-type-indexing-package.md | 24 ++++++++++++- Package.swift | 5 ++- .../Output/StandardStreamOutput.swift | 8 +++++ 4 files changed, 67 insertions(+), 4 deletions(-) diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.html b/Documentations/Evolutions/draft-swift-type-indexing-package.html index 370f0d47..c12c5659 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.html +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.html @@ -166,7 +166,7 @@

    Draft 类型索引独立成 swift
    状态
    In Progress
    最后更新
    2026-11-23
    项目类型
    库(跨仓库唯一提案)
    -
    跨仓库范围
    新仓库 swift-type-indexing、swift-apinotes fork(实现中加入)、MachOObjCSection、MachOSwiftSection(持有本提案)、RuntimeViewer
    +
    跨仓库范围
    新仓库 swift-type-indexing、swift-apinotes fork(实现中加入)、swift-semantic-string(验收中加入)、MachOObjCSection、MachOSwiftSection(持有本提案)、RuntimeViewer
    原文
    draft-swift-type-indexing-package.md

    @@ -377,6 +377,21 @@

    改动地图

    +
    + swift-semantic-string(验收中加入) +
    +
    + + + + + + +
    文件 / 类型动作改什么为什么步骤
    SemanticType.swift · SemanticType.macro、Components/Macro.swift · Macro新增宏这一语义类型与它的组件;冻结编码取 22(之前的读者把它当未知编码,显示成 .other);发 0.7.0MachOObjCSection 打印的 NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 原先只能标成关键字验收
    FrozenSemanticStringTests.swift、ReviewFindingsRegressionTests.swift、README.md、AGENTS.md修改类型清单与编码总数加一,冻结与两种 Codable 的往返;文档列出新类型回归,文档同批验收
    +
    +
    +
    +
    MachOObjCSection
    @@ -393,6 +408,10 @@

    改动地图

    Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift修改加 NS_SWIFT_NAME、类型一级、协议、category 的用例回归5 Tests/ObjCTypeIndexingTests/*新增ObjCDeclaredTypeNames 对 Foundation 镜像列出 NSObject 等;API notes 转换(临时 .apinotes 驱动)回归4、5 README.md、ObjCSectionCommandLine.md(库调用方一节)、Glossary.md、提案索引(cross-repository 行)修改新 target、新标注、指向本提案文档同批4、5 + ObjCSwiftImportNotes.swift修改两个宏由 Keyword 改为 Macro;括号里的 Swift 名仍是普通文本验收时发现它们与 @interface 同为关键字色,Xcode 用宏色(见决策日志)验收 + objc-section/Utilities/SemanticString+Color.swift修改.macro 用 Xcode Default 主题的宏色(浅色 #643820、深色 #FD8F3F)命令行配色同步验收 + Package.swift(swift-semantic-string)修改临时钉 branch: "feature/swift-type-indexing-package"(注明 TEMPORARY),收尾改为 from: "0.7.0"用到 Macro验收 + SwiftImportNotesRenderingTests.swift · macrosAreMacroRuns修改两个宏是 .macro、Swift 名是 .standard(修复前失败)回归验收
    @@ -417,6 +436,8 @@

    改动地图

    Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift新增分类映射、__C 解析经适配器到达打印器回归6 README(product 表等)、文档索引、SupplementaryTypeMappings.md、内部文档(TypeIndexingPipeline.md 删、改为指向新包,ProjectMap.md、Modules/README.md)、术语表、SwiftSectionKit{,_zh}.md、ObjCCommandLine{,_zh}.md、AGENTS.md / CLAUDE.md、swift-section 插件 skill(加 objc 新开关)及其插件清单的 version修改指向新包、新 target、新开关文档同批6、7 Documentations/Evolutions/README.md修改登记本提案索引0 + swift-section/Output/StandardStreamOutput.swift修改.macro 的配色与 objc-section 相同objc interface --mark-sdk-swift-names 的宏上色验收 + Package.swift(swift-semantic-string)修改临时钉功能分支,收尾改为 from: "0.7.0"与 MachOObjCSection 的钉法一致验收 @@ -457,6 +478,14 @@

    改动地图

    runtime-viewer 插件的 SKILL.md、.claude-plugin/plugin.json、.codex-plugin/plugin.json修改说明 __C. 解析与首次等待;版本 1.3.0 → 1.4.0插件规则11 DerivedData.md、CommandLineInterface.md、提案索引(cross-repository 行)、Documentations/README.md修改新缓存目录、输出变化、索引文档同批8、11 测试(见各步骤的行为清单)新增RuntimeViewerCoreTests 与 RuntimeViewerAppCoreTests 中的对应套件回归9、10、11 + RuntimeViewerCore/Package.swift(swift-semantic-string)修改也临时钉功能分支,收尾改回 branch: "next"MachOObjCSection 的功能分支钉着它,两处不一致 SwiftPM 解析不了验收 + Settings+Theme.swift · Preset.macro、Style.xcodeMacro修改新颜色槽,@Default 是 Xcode 的宏色对、常规字重;之前存下的自定义主题照样解码主题原本只有七种文字颜色,没有宏色验收 + ThemeSettingsView.swift修改编辑器加 Macro 一行,预览加一行 NS_SWIFT_NAME,列表的色块加一格宏色可编辑验收 + ThemePreset+ThemeProfile.swift · ResolvedTheme修改.macro 取 preset.macroNSTextView 面板的着色验收 + SourceEditorThemeConversion.swift修改.macro 标成 xcode.syntax.identifier.macro.system,xcode.syntax.preprocessor 也取宏色;identifier.macro 仍借给错误色SourceEditor 面板的着色,与 Xcode 的键一致验收 + RuntimeSemanticKind.swift修改.macro 归入 .keyword这个枚举跨 engine 边界,加新 case 旧对端解码不了验收 + ThemePresetMacroSlotTests、ResolvedThemeTests、RuntimeSemanticKindTests、SemanticRetypingTests 新增一条新增旧预设解码、主题映射(去掉映射即失败)、归并、SourceEditor 把宏重新标成系统宏回归验收 + 五个锁文件(Debug、Distribution workspace 与 Core、Packages、CommandLine 包)修改三个功能分支的新提交,swift-semantic-string 改钉功能分支钉版本同批验收 @@ -775,7 +804,7 @@

    落地步骤

    决策日志

    - 27 条,最近一条:实现完成,待用户看过后收尾 + 28 条,最近一条:NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 改用宏色
    @@ -808,6 +837,7 @@

    决策日志

    +
    2026-11-23内容区刷新前自己清一次接口缓存文档的接口缓存在同一事件上清空,但它和内容区的订阅各自调度,先后没有保证;内容区先在主线程清再重新取,读不到批次之前的旧结果
    2026-11-23一条既有测试的夹具换类RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 HelperCoders,它让 ISO8601DateFormatter 遵循 DateFormatConverter;镜像把一个类的遵循列成一个条目,「只采纳私有 @objc 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 EnergyFormatter,测试先断言该类只有一个遵循条目
    2026-11-23实现完成,待用户看过后收尾新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(TitleActivityIndicatorTests 一条基线必红);./TuistScript.sh check 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去
    2026-11-23NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 改用宏色,swift-semantic-string 加入范围用户验收时发现两个宏与 @interface、@end 同为关键字色:MachOObjCSection 把它们打成了 Keyword。查证 Xcode 27.2:Objective-C 的 grammar 从 SourceModel 的 KnownMacros.plist 认出两者(NS_REFINED_FOR_SWIFT 属普通宏、NS_SWIFT_NAME 属函数宏),但只为让解析跳过它们,词法上标成 xcode.syntax.plain;SDK 头文件里的宏色来自索引给的 xcode.syntax.identifier.macro.system(Default (Light) #643820、Default (Dark) #FD8F3F,与预处理语句同色,常规字重)。用户选定完整方案:swift-semantic-string 加 SemanticType.macro 与 Macro(冻结编码 22,之前的读者当普通文本),MachOObjCSection 改用它,RuntimeViewer 主题加可编辑的宏色槽(默认取 Xcode 色,之前存下的自定义主题照样解码),SourceEditor 面板把宏标成 identifier.macro.system,搜索的 RuntimeSemanticKind 把宏归入关键字、线上格式不变;两个命令行的配色同步。收尾因此多两步,排在发 MachOObjCSection 0.8.209 之前:先发 swift-semantic-string 0.7.0,MachOObjCSection 与本仓库把它改回 from: "0.7.0";RuntimeViewer 对它改回 branch: "next"
    diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.md b/Documentations/Evolutions/draft-swift-type-indexing-package.md index 92a62a53..8f38a49a 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.md +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.md @@ -6,7 +6,7 @@ - **最后更新**: 2026-11-23 - **所属愿景**: 无 - **关联提案**: [0009 TypeIndexing 重启](0009-type-indexing-revival.md)、[0010 补充类型映射](0010-community-type-mapping-bundles.md)、[0096 Swift 优先的导入声明](0096-swift-first-imported-declarations.md)(`ObjCSwiftImportNotes` 的来历) -- **跨仓库范围**: 新仓库 `MxIris-Reverse-Engineering/swift-type-indexing`、swift-apinotes fork(`MxIris-DeveloperTool-Forks/swift-apinotes`,实现中加入,见决策日志)、MachOObjCSection、MachOSwiftSection(本仓库,持有这份唯一的提案)、RuntimeViewer。另外三个仓库的提案索引各加一行「cross-repository」链接指回这里 +- **跨仓库范围**: 新仓库 `MxIris-Reverse-Engineering/swift-type-indexing`、swift-apinotes fork(`MxIris-DeveloperTool-Forks/swift-apinotes`,实现中加入,见决策日志)、swift-semantic-string(`SemanticType.macro`,验收中加入,见决策日志)、MachOObjCSection、MachOSwiftSection(本仓库,持有这份唯一的提案)、RuntimeViewer。另外三个仓库的提案索引各加一行「cross-repository」链接指回这里 - **实现分支 / PR**: 新仓库 `swift-type-indexing` 的 `main`;MachOObjCSection、MachOSwiftSection、RuntimeViewer 各自的 `feature/swift-type-indexing-package`(各从 `next` 切) - **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 - **网页版**: 同目录同名的 `.html` @@ -147,6 +147,13 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | `Sources/APINotes/TopLevelItems/ObjCContext.swift` · `ObjCContext.methods` / `properties` | 修改 | 标 `public`;打 tag `0.3.0` | 0.2.0 里是 internal,包外读不到类与协议的成员,ObjC 成员的标注没有来源 | 3 | | `Tests/APINotesTests/ObjCContextMemberAccessTests.swift` | 新增 | 不带 `@testable` 读成员(修复前编译失败) | 回归 | 3 | +### swift-semantic-string(验收中加入) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Semantic/SemanticType.swift` · `SemanticType.macro`、`Sources/Semantic/Components/Macro.swift` · `Macro` | 新增 | 宏这一语义类型与它的组件;冻结编码取 22(之前的读者把它当未知编码,显示成 `.other`);发 `0.7.0` | MachOObjCSection 打印的 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT` 原先只能标成关键字 | 验收 | +| `Tests/SemanticTests/FrozenSemanticStringTests.swift`、`ReviewFindingsRegressionTests.swift`、`README.md`、`AGENTS.md` | 修改 | 类型清单与编码总数加一,冻结与两种 `Codable` 的往返;文档列出新类型 | 回归,文档同批 | 验收 | + ### MachOObjCSection | 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | @@ -159,6 +166,10 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | `Sources/ObjCInterface/ObjCInterfaceBuilder.swift` · `protocolInterface` / `markedProtocolInterface` / `categoryInterface` / `markedCategoryInterface` | 修改 | 加 `swiftImportNotes:` 参数(默认空) | 协议与 category 也能标 | 5 | | `Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift` | 修改 | 加 `NS_SWIFT_NAME`、类型一级、协议、category 的用例 | 回归 | 5 | | `Tests/ObjCTypeIndexingTests/*` | 新增 | `ObjCDeclaredTypeNames` 对 Foundation 镜像列出 `NSObject` 等;API notes 转换(临时 `.apinotes` 驱动) | 回归 | 4、5 | +| `Sources/ObjCDeclarationRendering/ObjCSwiftImportNotes.swift` | 修改 | 两个宏由 `Keyword` 改为 `Macro`;括号里的 Swift 名仍是普通文本 | 验收时发现它们与 `@interface` 同为关键字色,Xcode 用宏色(见决策日志) | 验收 | +| `Sources/objc-section/Utilities/SemanticString+Color.swift` | 修改 | `.macro` 用 Xcode Default 主题的宏色(浅色 `#643820`、深色 `#FD8F3F`) | 命令行配色同步 | 验收 | +| `Package.swift`(swift-semantic-string) | 修改 | 临时钉 `branch: "feature/swift-type-indexing-package"`(注明 TEMPORARY),收尾改为 `from: "0.7.0"` | 用到 `Macro` | 验收 | +| `Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift` · `macrosAreMacroRuns` | 修改 | 两个宏是 `.macro`、Swift 名是 `.standard`(修复前失败) | 回归 | 验收 | | `README.md`、`Documentations/Guides/ObjCSectionCommandLine.md`(库调用方一节)、`Documentations/Glossary.md:167-177`、`Documentations/Evolutions/README.md`(cross-repository 行) | 修改 | 新 target、新标注、指向本提案 | 文档同批 | 4、5 | ### MachOSwiftSection(本仓库) @@ -176,6 +187,8 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | `Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift` | 新增 | 分类映射、`__C` 解析经适配器到达打印器 | 回归 | 6 | | `README.md`(:76 product 表、:445-451)、`Documentations/README.md`、`Documentations/SupplementaryTypeMappings.md`、`Documentations/Internal/{TypeIndexingPipeline.md(删,改为指向新包),ProjectMap.md,Modules/README.md}`、`Documentations/Glossary.md:445-448`、`Documentations/SwiftSectionKit{,_zh}.md`、`Documentations/ObjCCommandLine{,_zh}.md`、`AGENTS.md:69` / `CLAUDE.md:69`、`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`(:46、:216-217、§8 :352-357,加 objc 新开关)及其插件清单的 `version` | 修改 | 指向新包、新 target、新开关 | 文档同批 | 6、7 | | `Documentations/Evolutions/README.md` | 修改 | 登记本提案 | 索引 | 0 | +| `Sources/Executables/swift-section/Output/StandardStreamOutput.swift` | 修改 | `.macro` 的配色与 objc-section 相同 | `objc interface --mark-sdk-swift-names` 的宏上色 | 验收 | +| `Package.swift`(swift-semantic-string) | 修改 | 临时钉功能分支,收尾改为 `from: "0.7.0"` | 与 MachOObjCSection 的钉法一致 | 验收 | ### RuntimeViewer @@ -208,6 +221,14 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md`、`.claude-plugin/plugin.json`、`.codex-plugin/plugin.json` | 修改 | 说明 `__C.` 解析与首次等待;版本 `1.3.0` → `1.4.0` | 插件规则 | 11 | | `Documentations/DerivedData.md`、`Documentations/Guides/CommandLineInterface.md`、`Documentations/Evolutions/README.md`(cross-repository 行)、`Documentations/README.md` | 修改 | 新缓存目录、输出变化、索引 | 文档同批 | 8、11 | | 测试(见各步骤的行为清单) | 新增 | `RuntimeViewerCoreTests` 与 `RuntimeViewerAppCoreTests` 中的对应套件 | 回归 | 9、10、11 | +| `RuntimeViewerCore/Package.swift`(swift-semantic-string) | 修改 | 也临时钉功能分支,收尾改回 `branch: "next"` | MachOObjCSection 的功能分支钉着它,两处不一致 SwiftPM 解析不了 | 验收 | +| `RuntimeViewerSettings/Settings+Theme.swift` · `Preset.macro`、`Style.xcodeMacro` | 修改 | 新颜色槽,`@Default` 是 Xcode 的宏色对、常规字重;之前存下的自定义主题照样解码 | 主题原本只有七种文字颜色,没有宏色 | 验收 | +| `RuntimeViewerSettingsUI/Components/ThemeSettingsView.swift` | 修改 | 编辑器加 Macro 一行,预览加一行 `NS_SWIFT_NAME`,列表的色块加一格 | 宏色可编辑 | 验收 | +| `RuntimeViewerAppUI/Theme/ThemePreset+ThemeProfile.swift` · `ResolvedTheme` | 修改 | `.macro` 取 `preset.macro` | `NSTextView` 面板的着色 | 验收 | +| `RuntimeViewerUsingAppKit/.../Content/SourceEditorThemeConversion.swift` | 修改 | `.macro` 标成 `xcode.syntax.identifier.macro.system`,`xcode.syntax.preprocessor` 也取宏色;`identifier.macro` 仍借给错误色 | SourceEditor 面板的着色,与 Xcode 的键一致 | 验收 | +| `RuntimeViewerCore/.../Search/RuntimeSemanticKind.swift` | 修改 | `.macro` 归入 `.keyword` | 这个枚举跨 engine 边界,加新 case 旧对端解码不了 | 验收 | +| `ThemePresetMacroSlotTests`、`ResolvedThemeTests`、`RuntimeSemanticKindTests`、`SemanticRetypingTests.anObjectiveCSDKMacroTakesTheSystemMacroTypeFromItsSemanticRun` | 新增 | 旧预设解码、主题映射(去掉映射即失败)、归并、SourceEditor 把宏重新标成系统宏 | 回归 | 验收 | +| 五个锁文件(Debug、Distribution workspace 与 Core、Packages、CommandLine 包) | 修改 | 三个功能分支的新提交,swift-semantic-string 改钉功能分支 | 钉版本同批 | 验收 | ## 架构图 @@ -660,3 +681,4 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` | 2026-11-23 | 内容区刷新前自己清一次接口缓存 | 文档的接口缓存在同一事件上清空,但它和内容区的订阅各自调度,先后没有保证;内容区先在主线程清再重新取,读不到批次之前的旧结果 | | 2026-11-23 | 一条既有测试的夹具换类 | RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 `HelperCoders`,它让 `ISO8601DateFormatter` 遵循 `DateFormatConverter`;镜像把一个类的遵循列成一个条目,「只采纳私有 `@objc` 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 `EnergyFormatter`,测试先断言该类只有一个遵循条目 | | 2026-11-23 | 实现完成,待用户看过后收尾 | 新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(`TitleActivityIndicatorTests` 一条基线必红);`./TuistScript.sh check` 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去 | +| 2026-11-23 | `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT` 改用宏色,swift-semantic-string 加入范围 | 用户验收时发现两个宏与 `@interface`、`@end` 同为关键字色:MachOObjCSection 把它们打成了 `Keyword`。查证 Xcode 27.2:Objective-C 的 grammar 从 SourceModel 的 `KnownMacros.plist` 认出两者(`NS_REFINED_FOR_SWIFT` 属普通宏、`NS_SWIFT_NAME` 属函数宏),但只为让解析跳过它们,词法上标成 `xcode.syntax.plain`;SDK 头文件里的宏色来自索引给的 `xcode.syntax.identifier.macro.system`(Default (Light) `#643820`、Default (Dark) `#FD8F3F`,与预处理语句同色,常规字重)。用户选定完整方案:swift-semantic-string 加 `SemanticType.macro` 与 `Macro`(冻结编码 22,之前的读者当普通文本),MachOObjCSection 改用它,RuntimeViewer 主题加可编辑的宏色槽(默认取 Xcode 色,之前存下的自定义主题照样解码),SourceEditor 面板把宏标成 `identifier.macro.system`,搜索的 `RuntimeSemanticKind` 把宏归入关键字、线上格式不变;两个命令行的配色同步。收尾因此多两步,排在发 MachOObjCSection 0.8.209 之前:先发 swift-semantic-string 0.7.0,MachOObjCSection 与本仓库把它改回 `from: "0.7.0"`;RuntimeViewer 对它改回 `branch: "next"` | diff --git a/Package.swift b/Package.swift index 8940bc7d..3b41d658 100644 --- a/Package.swift +++ b/Package.swift @@ -281,7 +281,10 @@ extension Package.Dependency { // 0.6.0 adds the annotation regions `marksCommentStructure` marks // every comment with; 0.5.0 added the definition regions // `marksNestedDefinitions` wraps each nested definition in. - from: "0.6.0", + // TEMPORARY: the feature branch, for `SemanticType.macro` + // (proposal swift-type-indexing-package), until 0.7.0 is + // released; the proposal's wrap-up puts `from: "0.7.0"` here. + branch: "feature/swift-type-indexing-package", ), ) diff --git a/Sources/Executables/swift-section/Output/StandardStreamOutput.swift b/Sources/Executables/swift-section/Output/StandardStreamOutput.swift index 4cfb5213..9e6a35c0 100644 --- a/Sources/Executables/swift-section/Output/StandardStreamOutput.swift +++ b/Sources/Executables/swift-section/Output/StandardStreamOutput.swift @@ -102,6 +102,11 @@ extension String { return "#56606B" case .keyword: return "#C33381" + case .macro: + // Xcode's Default (Light) preprocessor-macro colour, which + // `objc interface --mark-sdk-swift-names` prints its + // NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT in. + return "#643820" case .type(_, .name): return "#2E0D6E" case .type(_, .declaration): @@ -124,6 +129,9 @@ extension String { return "#6C7987" case .keyword: return "#F2248C" + case .macro: + // Xcode's Default (Dark) preprocessor-macro colour. + return "#FD8F3F" case .type(_, .name): return "#D0A8FF" case .type(_, .declaration): From f9e3e1368f3c7ed544886222961cad37ae75cc43 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 23 Nov 2026 21:46:39 +0800 Subject: [PATCH 081/175] docs: record why SourceKitService grew to 80 GB and the fix in swift-type-indexing --- .../Evolutions/draft-swift-type-indexing-package.html | 5 ++++- .../Evolutions/draft-swift-type-indexing-package.md | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.html b/Documentations/Evolutions/draft-swift-type-indexing-package.html index c12c5659..c4c5b53b 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.html +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.html @@ -356,6 +356,8 @@

    改动地图

    SDKIntegrationTests新增对本机真实 SDK 的核对,默认关闭:TYPE_INDEXING_SDK_TESTS=1(只读 API notes,约 2 秒),再加 TYPE_INDEXING_SOURCEKIT_TESTS=1 经 sourcekitd 冷生成 Catalyst 的 UIKit 接口(实测 126 秒)单测覆盖不到 SDK 布局与 sourcekitd 参数2、3 README.md、LICENSE、AGENTS.md + CLAUDE.md(符号链接)、Documentations/README.md、提案索引(项目类型:库)、TypeIndexingPipeline.md(从 MachOSwiftSection 移入并更新)新增 移入用法、三层数据源、改名规则、缓存布局、可用性新仓库的文档1、3 .github/workflows/macOS.yml新增照 MachOSwiftSection 的 macOS.yml 配 macOS 构建与测试CI1 + SourceKitManager.swift · SourceKitManager、InterfaceDocumentService、SourceKitDInterfaceDocumentService修改每个打开的接口读完就用同一文档名 editor.close(生成失败也关);同时最多生成 2 个;请求经 InterfaceDocumentService 发出;发 0.1.1验收时 SourceKitService 涨到 80 GB(见决策日志)验收 + SourceKitManagerTests.swift、TypeIndexingPipeline.md新增 修改替身核对打开与关闭配对、并发上限(去掉任一即失败);文档记下原因与量法回归,文档同批验收
    @@ -804,7 +806,7 @@

    落地步骤

    决策日志

    - 28 条,最近一条:NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 改用宏色 + 29 条,最近一条:SourceKitService 不再涨到 80 GB
    @@ -838,6 +840,7 @@

    决策日志

    +
    2026-11-23一条既有测试的夹具换类RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 HelperCoders,它让 ISO8601DateFormatter 遵循 DateFormatConverter;镜像把一个类的遵循列成一个条目,「只采纳私有 @objc 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 EnergyFormatter,测试先断言该类只有一个遵循条目
    2026-11-23实现完成,待用户看过后收尾新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(TitleActivityIndicatorTests 一条基线必红);./TuistScript.sh check 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去
    2026-11-23NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 改用宏色,swift-semantic-string 加入范围用户验收时发现两个宏与 @interface、@end 同为关键字色:MachOObjCSection 把它们打成了 Keyword。查证 Xcode 27.2:Objective-C 的 grammar 从 SourceModel 的 KnownMacros.plist 认出两者(NS_REFINED_FOR_SWIFT 属普通宏、NS_SWIFT_NAME 属函数宏),但只为让解析跳过它们,词法上标成 xcode.syntax.plain;SDK 头文件里的宏色来自索引给的 xcode.syntax.identifier.macro.system(Default (Light) #643820、Default (Dark) #FD8F3F,与预处理语句同色,常规字重)。用户选定完整方案:swift-semantic-string 加 SemanticType.macro 与 Macro(冻结编码 22,之前的读者当普通文本),MachOObjCSection 改用它,RuntimeViewer 主题加可编辑的宏色槽(默认取 Xcode 色,之前存下的自定义主题照样解码),SourceEditor 面板把宏标成 identifier.macro.system,搜索的 RuntimeSemanticKind 把宏归入关键字、线上格式不变;两个命令行的配色同步。收尾因此多两步,排在发 MachOObjCSection 0.8.209 之前:先发 swift-semantic-string 0.7.0,MachOObjCSection 与本仓库把它改回 from: "0.7.0";RuntimeViewer 对它改回 branch: "next"
    2026-11-23SourceKitService 不再涨到 80 GB:接口生成完就关闭,同时最多生成 2 个用户验收时发现 RuntimeViewer 的两个服务进程各带一个 SourceKitService,各涨到 80 GB。复现:swift-section interface --uses-system-dyld-shared-cache -n AppKit --resolve-c-module-names(缓存清空),按秒采样新起的 SourceKitService,6 秒、27 个模块时到 27 GB,被设的上限掐断。原因在 SourceKit 源码里(SwiftEditorInterfaceGen.cpp、SwiftEditor.cpp):每次 editor.open.interface 留一个 SwiftInterfaceGenContext(两个 CompilerInstance,载入模块及其全部导入),只有同名的 editor.close 才从 IFaceGenContexts 里删掉;SourceKitManager 每个模块用一个新 UUID 打开、从不关闭,TypeDatabase.index 又把一个镜像的模块一次全提交。用户选了「关闭 + 限并发」:读完响应即关(生成失败也关),同时最多 2 个。同一条复现峰值 413 MB,33 个模块 70 秒全部生成完,名字照常解析。收尾多一步:swift-type-indexing 发 0.1.1,RuntimeViewer 的下限抬到 0.1.1
    diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.md b/Documentations/Evolutions/draft-swift-type-indexing-package.md index 8f38a49a..b269a586 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.md +++ b/Documentations/Evolutions/draft-swift-type-indexing-package.md @@ -139,6 +139,8 @@ swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← Runtime | `Tests/TypeIndexingTests/SDKIntegrationTests.swift` | 新增 | 对本机真实 SDK 的核对,默认关闭:`TYPE_INDEXING_SDK_TESTS=1`(只读 API notes,约 2 秒),再加 `TYPE_INDEXING_SOURCEKIT_TESTS=1` 经 sourcekitd 冷生成 Catalyst 的 UIKit 接口(实测 126 秒) | 单测覆盖不到 SDK 布局与 sourcekitd 参数 | 2、3 | | `README.md`、`LICENSE`、`AGENTS.md` + `CLAUDE.md`(符号链接)、`Documentations/README.md`、`Documentations/Evolutions/README.md`(项目类型:库)、`Documentations/Internal/TypeIndexingPipeline.md`(从本仓库移入并更新) | 新增 / 移入 | 用法、三层数据源、改名规则、缓存布局、可用性 | 新仓库的文档 | 1、3 | | `.github/workflows/macOS.yml` | 新增 | 照本仓库 `macOS.yml` 配 macOS 构建与测试 | CI | 1 | +| `Sources/TypeIndexing/SourceKitManager.swift` · `SourceKitManager`、`InterfaceDocumentService`、`SourceKitDInterfaceDocumentService` | 修改 | 每个打开的接口读完就用同一文档名 `editor.close`(生成失败也关);同时最多生成 2 个;请求经 `InterfaceDocumentService` 发出;发 `0.1.1` | 验收时 SourceKitService 涨到 80 GB(见决策日志) | 验收 | +| `Tests/TypeIndexingTests/SourceKitManagerTests.swift`、`Documentations/Internal/TypeIndexingPipeline.md` | 新增 / 修改 | 替身核对打开与关闭配对、并发上限(去掉任一即失败);文档记下原因与量法 | 回归,文档同批 | 验收 | ### swift-apinotes(fork,实现中加入) @@ -682,3 +684,4 @@ MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` | 2026-11-23 | 一条既有测试的夹具换类 | RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 `HelperCoders`,它让 `ISO8601DateFormatter` 遵循 `DateFormatConverter`;镜像把一个类的遵循列成一个条目,「只采纳私有 `@objc` 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 `EnergyFormatter`,测试先断言该类只有一个遵循条目 | | 2026-11-23 | 实现完成,待用户看过后收尾 | 新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(`TitleActivityIndicatorTests` 一条基线必红);`./TuistScript.sh check` 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去 | | 2026-11-23 | `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT` 改用宏色,swift-semantic-string 加入范围 | 用户验收时发现两个宏与 `@interface`、`@end` 同为关键字色:MachOObjCSection 把它们打成了 `Keyword`。查证 Xcode 27.2:Objective-C 的 grammar 从 SourceModel 的 `KnownMacros.plist` 认出两者(`NS_REFINED_FOR_SWIFT` 属普通宏、`NS_SWIFT_NAME` 属函数宏),但只为让解析跳过它们,词法上标成 `xcode.syntax.plain`;SDK 头文件里的宏色来自索引给的 `xcode.syntax.identifier.macro.system`(Default (Light) `#643820`、Default (Dark) `#FD8F3F`,与预处理语句同色,常规字重)。用户选定完整方案:swift-semantic-string 加 `SemanticType.macro` 与 `Macro`(冻结编码 22,之前的读者当普通文本),MachOObjCSection 改用它,RuntimeViewer 主题加可编辑的宏色槽(默认取 Xcode 色,之前存下的自定义主题照样解码),SourceEditor 面板把宏标成 `identifier.macro.system`,搜索的 `RuntimeSemanticKind` 把宏归入关键字、线上格式不变;两个命令行的配色同步。收尾因此多两步,排在发 MachOObjCSection 0.8.209 之前:先发 swift-semantic-string 0.7.0,MachOObjCSection 与本仓库把它改回 `from: "0.7.0"`;RuntimeViewer 对它改回 `branch: "next"` | +| 2026-11-23 | SourceKitService 不再涨到 80 GB:接口生成完就关闭,同时最多生成 2 个 | 用户验收时发现 RuntimeViewer 的两个服务进程各带一个 SourceKitService,各涨到 80 GB。复现:`swift-section interface --uses-system-dyld-shared-cache -n AppKit --resolve-c-module-names`(缓存清空),按秒采样新起的 SourceKitService,6 秒、27 个模块时到 27 GB,被设的上限掐断。原因在 SourceKit 源码里(`SwiftEditorInterfaceGen.cpp`、`SwiftEditor.cpp`):每次 `editor.open.interface` 留一个 `SwiftInterfaceGenContext`(两个 `CompilerInstance`,载入模块及其全部导入),只有同名的 `editor.close` 才从 `IFaceGenContexts` 里删掉;`SourceKitManager` 每个模块用一个新 UUID 打开、从不关闭,`TypeDatabase.index` 又把一个镜像的模块一次全提交。用户选了「关闭 + 限并发」:读完响应即关(生成失败也关),同时最多 2 个。同一条复现峰值 413 MB,33 个模块 70 秒全部生成完,名字照常解析。收尾多一步:swift-type-indexing 发 0.1.1,RuntimeViewer 的下限抬到 0.1.1 | From bd388bfa071b7ea3de9b58983a25827b37fe122a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:05:15 +0800 Subject: [PATCH 082/175] docs: propose spelling C-imported type names one way, Swift or C Declarations print a C-imported type's Swift name while references and extension headers print its C name. Accepted: print both the same way, taking the Swift name from the image's own descriptors, and let RuntimeViewer switch to the C spelling from a line annotation. --- Documentations/Evolutions/README.md | 1 + .../draft-c-imported-type-name-spelling.html | 575 ++++++++++++++++++ .../draft-c-imported-type-name-spelling.md | 527 ++++++++++++++++ 3 files changed, 1103 insertions(+) create mode 100644 Documentations/Evolutions/draft-c-imported-type-name-spelling.html create mode 100644 Documentations/Evolutions/draft-c-imported-type-name-spelling.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index f1c7565d..f2d4aa5c 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -120,3 +120,4 @@ | [0103](0103-cross-reference-test-scan-load.md) | 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 | Implemented | | [0104](0104-shared-macho-testing-support.md) | 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport | Implemented | | draft | [类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer](draft-swift-type-indexing-package.md)(跨仓库唯一提案) | In Progress | +| draft | [C 导入类型的名字统一成 Swift 名,并能切换回 C 名](draft-c-imported-type-name-spelling.md)(跨仓库唯一提案,RuntimeViewer 参与) | Accepted | diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html new file mode 100644 index 00000000..6ecd98ec --- /dev/null +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html @@ -0,0 +1,575 @@ + + + + + + +Draft - C 导入类型的名字统一成 Swift 名,并能切换回 C 名 + + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

    +

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

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

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

    +

    RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一条 Xcode 式的行尾标注(Imported from C as AGWeakAttribute),点开后用里面的按钮切换。

    +
    + +
    +

    要你定

    +
    +

    已定:两次点击

    +

    用户批准按 Xcode 原生的两步做:点横幅弹出下拉框,用里面的按钮切换;右键横幅的菜单里也有同一个动作。不改 Mx-Iris/SourceEditor。

    +
    +
    + +
    +

    方案

    +

    MachOSwiftSection

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

    RuntimeViewer

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

    非目标

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

    架构图

    +
      +
    • 新增
    • +
    • 修改
    • +
    • 不变
    • +
    +
    + + + MachOSwiftSection + CImportedTypeNameSpelling.swiftName (default) | .cName + CImportedTypeSwiftNameTablemangled identity -> trusted descriptor name + AnnotationRegion.Kind.cImportedTypeName(_:)both names, when marking is on + SwiftDeclarationPrintConfiguration+ cImportedTypeNameSpelling, + marksCImportedTypeNames + SwiftDeclarationPrintermemoized name table from typeContextDescriptors + TypeNodePrintable.printTypespelling rules for __C references + +Headers: declared name, extension headerssame rules; extension headers become async + swift-section interface--c-imported-type-name-spelling swift-name|c-name + swift-type-indexing resolvers (SDK) + + + RuntimeViewer + SwiftGenerationOptions+ cImportedTypeNameSpelling (@Default .swiftName) + GenerationOptions+ marksCImportedTypeNames (internal, stored false) + RuntimeInterfaceCImportedTypeNamedeclared name's UTF-8 range + both names + RuntimeObjectInterface+ cImportedTypeNames + SourceEditorBridgingLineAnnotationrange, message, action title, identifier + SourceEditorBridging + delegate+ showLineAnnotations(_:), + didPerformActionOfLineAnnotation + ContentInterface, ContentTextViewModel+ notes, + spelling toggle input + ContentSourceEditorViewControllerline annotations, toggle relay + GenerationOptionsViewController: Imported Type Names + + + + +
    +

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

    + +
    + + click "Show C Names" in the line annotation's dropdownSourceEditorLineAnnotation.Action (or the banner's contextual menu) + navigationDelegate.didPerformActionOfLineAnnotationContentSourceEditorViewController -> toggle relay + ContentTextViewModelappDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling = .cName + appDefaults.$optionsevery content pane refetches + service: RuntimeSwiftSection.updateConfigurationprinter prints with .cName and marks declared names; cache cleared + separatingAnnotationRegions()RuntimeObjectInterface.cImportedTypeNames + setSource + showLineAnnotations"Imported to Swift as AnyWeakAttribute" [Show Swift Names] + + + + + + + +
    +

    点「Show C Names」之后:改的是全局生成选项,所有内容区经同一条重新取接口的路径刷新。

    +
    + +
    +

    改动地图

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

    详细设计

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

    kind 的编码是 "cImportedTypeName" + "\u{1F}" + swiftName + "\u{1F}" + cName;U+001F 不会出现在标识符里,Swift 名里可以照常带点号。

    +
    +
    +
    + 名字表与可信规则(模块内部) +
    +
    struct CImportedTypeSwiftNameTable: Sendable {
    +    init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext)
    +    func swiftName(forIdentity identity: Node) -> String?
    +
    +    static func trustsUserFacingName(_ userFacingName: String, importInfo: TypeImportInfo) -> Bool {
    +        guard let abiName = importInfo.abiName, abiName != userFacingName, !importInfo.isRelatedEntity else { return false }
    +        return !abiName.hasSuffix(userFacingName)
    +    }
    +}
    +
      +
    • 键是 mangled 身份节点(SymbolicDemangler.demangleContext(for:in:))的结构,照 ExtensionName 的结构化 Hashable。
    • +
    • 只遍历 C 导入的描述符,读名字与 typeImportInfo(in:);第一次需要时才建,配置怎么变都不重建;读出错的条目跳过。
    • +
    +
    +
    +
    + 打印规则的落点 +
    +
      +
    • printType(_:):.cName 写原模块名与标识符;.swiftName 先走现有路径,模块没解析出来但名字表有答案时,不写模块与分隔符,把 Swift 名写成标识符(语义仍是这个类型的 printIdentifier 上下文,跳转不受影响)。嵌套类型的父段递归回 printType,套用同一规则。
    • +
    • printModuleSelector(ofNestedType:):父段是改了名的裸名时不写模块选择器。
    • +
    • renderTypeDeclarationHeader:C 导入的描述符按方案第 5 条取名;解析器那一路用 ABI 名去问,与引用处的查询相同,声明与引用必然一致。displayParentName == true 那条路不变。
    • +
    • renderExtendedTypeName 改成 async:根在 __C 时走 typeDemangleResolver.resolve(for:) 再 .replacingTypeNameOrOtherToTypeDeclaration();其余分支原样。
    • +
    +
    +
    +
    + RuntimeViewer 的类型与 bridge 接口 +
    +
    // SwiftGenerationOptions
    +public enum CImportedTypeNameSpelling: String, Codable, Sendable, Equatable, Hashable, CaseIterable { case swiftName, cName }
    +@Default(CImportedTypeNameSpelling.swiftName)
    +public var cImportedTypeNameSpelling: CImportedTypeNameSpelling
    +
    +// RuntimeObjectInterface.GenerationOptions
    +@Default(false)
    +public var marksCImportedTypeNames: Bool
    +
    +public struct RuntimeInterfaceCImportedTypeName: Codable, Sendable, Hashable {
    +    public let nameUTF8Range: Range<Int>
    +    public let swiftName: String
    +    public let cName: String
    +}
    +// RuntimeObjectInterface
    +public let cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]?
    +
    +@objc(RuntimeViewerSourceEditorBridgingLineAnnotation)
    +public final class SourceEditorBridgingLineAnnotation: NSObject {
    +    public let characterRange: NSRange
    +    public let message: String
    +    public let actionTitle: String
    +    public let identifier: String
    +}
    +// SourceEditorBridging
    +func showLineAnnotations(_ annotations: [SourceEditorBridgingLineAnnotation])
    +// SourceEditorBridgingNavigationDelegate
    +func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAnnotationWithIdentifier identifier: String)
    +
      +
    • 线上兼容:旧版对端不认这两个选项,不带 cImportedTypeNames,内容区就没有提示;新版对端收到旧版请求时取默认值。
    • +
    • Bridge 实现照复刻版 tag 27.2.0-alpha.2 的源码:lineIdentifier 取 dataSource.identifierForLine(_:);动作进 actions,revealAction 用同一个标题;不可拖动、不可最小化、不画滚动条标记。
    • +
    • 类别的图标与颜色不凭猜:Xcode 的 note 类别在 IDESourceEditor 里、不在复刻范围,实现前读 /Volumes/RE/Xcode/26.6/ 的导出确认,没有就停下来问。
    • +
    • AppCore 按当前拼写生成文字:.swiftName 写 Imported from C as <cName> / Show C Names,.cName 写 Imported to Swift as <swiftName> / Show Swift Names;ViewModel 的新输入在主线程翻转 appDefaults.options 里的拼写。
    • +
    +
    +
    +
    + +
    +

    调研

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

    替代方案

    +
    + 6 条被否的路径 +
    +
      +
    • 模块未知时写 __C.AnyWeakAttribute:与声明行仍不一致,且是打印器以前特意避开的半翻译写法;用户选了裸名。
    • +
    • 默认按 C 名统一:读的是 Swift interface,Swift 名更贴合;C 名作为可切换的拼写保留。
    • +
    • 按前缀推断成员导入的父类型:二进制里没有父路径,前缀切分会切出 NS.Decimal 这种错误结果。
    • +
    • 类型名后面的胶囊标签:要多输出一段注释,复制与导出会带上它,还要给标签加点击;用户选了行尾标注。
    • +
    • 只切换当前编辑栏:要另存一份不进设置的状态,缓存键多一维;用户选了全局生成选项。
    • +
    • 拼写与 resolvesImportedTypeNames 合成三档:类型索引功能还在验收,合并就要改它的设置与测试;两个开关各管各的更简单。
    • +
    +
    +
    +
    + +
    +

    影响

    +

    源码兼容性

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

    ABI 兼容性

    +

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

    +

    下游影响

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

    文档与示例

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

    API 演进与废弃策略

    +

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

    +
    + +
    +

    落地步骤

    +
      +
    1. 登记草案 —— 两边的提案索引。
    2. +
    3. 名字表与可信规则 —— trustsUserFacingNameWhenABINameDiffers、refusesLeafNameOfTypeImportedAsMember、refusesRelatedEntityName、refusesNameWithoutABIName、nameTableReadsAttributeGraphDescriptors。
    4. +
    5. 打印规则 —— swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown、swiftSpellingKeepsModuleThatResolverFinds、cSpellingPrintsMangledNamesAndAsksNoResolver、untrustedDeclaredNamePrintsCName、extensionHeaderSpellsLikeMemberTypes、nonCImportedExtensionHeadersAreByteIdentical、abiDiffKeysAreUnchanged。
    6. +
    7. 标注与命令行 —— markedDeclaredNameCarriesBothSpellings、separatedMarkedPrintEqualsUnmarkedPrint、regionKindRoundTripsDottedSwiftName、sameSpellingsAreNotMarked、interfaceCommandParsesCNameSpelling;推送 MSS 功能分支,RuntimeViewer 临时按分支钉。
    8. +
    9. RuntimeViewer Core —— spellingDefaultsToSwiftNameInOlderPayload、marksCImportedTypeNamesIsNeverStoredTrue、interfaceCarriesCImportedTypeNamesWhenMarked、commentStructureIgnoresCImportedTypeNameRegions、cNameSpellingRequestsNoTypeIndex、changingSpellingClearsInterfaceCache、corpusPrintsSwiftNamesWhateverTheSpelling。
    10. +
    11. Bridge 的行尾标注 —— lineAnnotationSitsOnFirstLineOfItsRange、setSourceRemovesLineAnnotations、performingActionNotifiesDelegateWithIdentifier、contextualMenuOffersTheSameAction。
    12. +
    13. AppCore 与 App —— notesNameCDeclarationUnderSwiftSpelling、notesNameSwiftTypeUnderCSpelling、togglingFlipsStoredSpelling、mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns;用 SourceEditor 打开 AnyWeakAttribute 的目视交给用户。
    14. +
    15. 收尾 —— 插件 skill 与版本、抬 MSS pin、重解析锁文件、两边索引与提案状态;判断配套实现说明与术语。
    16. +
    +
    + +
    +

    决策日志

    +
    + 12 条,最近一条:两边都从远端的类型索引功能分支切 +
    +
    + + + + + + + + + + + + + + + + +
    日期变更说明
    2026-11-24Created as DraftRuntimeViewer 显示 AttributeGraph 的 AGWeakAttribute 时,声明行是 Swift 名,扩展头与成员类型是 C 名;用户要求统一,并在 SourceEditor 里给一个能点击切换的提示。
    2026-11-24提示用 Xcode 式的行尾标注用户选了行尾标注,不选胶囊标签:不改接口文本,复制与导出不受影响。
    2026-11-24模块未知时写裸名用户选了 AnyWeakAttribute,与声明行完全一致。
    2026-11-24切换是全局生成选项用户选了全局:存进设置、所有窗口一起变、面板里有同名开关。
    2026-11-24提案放在 MachOSwiftSection照 RuntimeViewer 索引里 cross-repository draft 的做法,由最底层的仓库维护唯一提案。
    2026-11-24导入成成员的类型不用描述符的名字实测描述符只存叶子(Key、Name);ABI 名以描述符名字结尾的一律不信,代价是 NSDecimal → Decimal 也退回 C 名。
    2026-11-24C 名模式等于 mangled 拼写不解析模块,避免与同名 Swift 结构体混淆。
    2026-11-24扩展头一并修扩展头不经解析器,和本提案改的是同一条路径;只改根在 __C 的扩展。
    2026-11-24两次点击待用户确认复刻版框架的横幅没有按钮;先按原生两步加右键菜单做,要一次点击就得改 Mx-Iris/SourceEditor。
    2026-11-24Accepted用户批准,开始实现。
    2026-11-24交互定为两次点击用户确认按 Xcode 原生的两步做(横幅 → 下拉里的按钮,右键菜单也有),不改复刻版框架。
    2026-11-24两边都从远端的 feature/swift-type-indexing-package 切远端比两边本地 next 多了验收时的修复;提案随功能分支的第一个提交走。
    +
    +
    +
    +
    + +
    +
    + + diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md new file mode 100644 index 00000000..66656a58 --- /dev/null +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md @@ -0,0 +1,527 @@ +# Draft - C 导入类型的名字统一成 Swift 名,并能切换回 C 名 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-24 +- **最后更新**: 2026-11-24 +- **所属愿景**: 无 +- **关联提案**: [`draft-swift-type-indexing-package`](draft-swift-type-indexing-package.md)(`__C` 类型名按 SDK 解析,本提案叠在它上面);RuntimeViewer 的 0064(注释结构由打印器标出、引擎分离后随 interface 下发,本提案照这条路传名字) +- **实现分支 / PR**: 两个仓库都是 `feature/c-imported-type-name-spelling`(worktree `.worktrees/MachOSwiftSection-CImportedTypeNameSpelling`、`.worktrees/RuntimeViewer-CImportedTypeNameSpelling`),叠在 `feature/swift-type-indexing-package` 上 +- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 +- **网页版**: 同目录同名的 `.html` +- **涉及仓库**: MachOSwiftSection(本仓库,打印器与 `swift-section`)、RuntimeViewer(生成选项、内容区的行尾提示)。这是跨仓库的唯一提案,RuntimeViewer 的提案索引登记为 cross-repository draft + +## 摘要 + +Swift interface 里,从 C 导入、被改了名的类型(`NS_SWIFT_NAME`、typedef、CF 的 `Ref` 去尾)现在**声明行印 Swift 名、其余地方印 C 名**:`struct AnyWeakAttribute { var _details: __C.AGWeakAttribute.__Unnamed_struct__details }`,紧跟着 `extension __C.AGWeakAttribute: Swift.Hashable {}`。原因是声明行取类型描述符里的名字,而引用处取 mangled 名,Swift 给 Clang 声明做 mangling 时一律用 C 名。描述符的导入信息(import info)里两个名字本来都存着,不需要 SDK。 + +本提案让打印器多一个拼写选项 `CImportedTypeNameSpelling`: + +- **默认 `.swiftName`**:声明、成员类型、扩展头全部用 Swift 名。查不到所属模块时写裸名(`extension AnyWeakAttribute: Swift.Hashable {}`),查得到时照旧写成 `模块.Swift名`。 +- **`.cName`**:一律按 mangled 的样子印(声明 `struct AGWeakAttribute`,引用 `__C.AGWeakAttribute`)。 + +同时修掉扩展头不经类型名解析器的问题:SDK 类型的成员已经解析成 `CoreFoundation.CGRect`,扩展头却还是 `__C.CGRect`。 + +RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一条 Xcode 式的行尾标注(`Imported from C as AGWeakAttribute`),点开后用里面的按钮切换。 + +## 动机 + +**现象**(RuntimeViewer 显示 AttributeGraph 的 `AGWeakAttribute`,2026-11-24): + +```swift +struct AnyWeakAttribute { + struct __Unnamed_struct__details { + var identifier: __C.AGAttribute + var seed: Swift.UInt32 + } + var _details: __C.AGWeakAttribute.__Unnamed_struct__details +} + +extension __C.AGWeakAttribute: Swift.Hashable {} +extension __C.AGWeakAttribute: Swift.CustomStringConvertible {} +extension __C.AGWeakAttribute: Swift.Equatable {} +``` + +同一个类型在一屏里有两个名字,扩展头看上去像是给另一个类型加的遵循。`swift-section 0.24.0 interface --show-c-imported-types` 打 AttributeGraph 得到的完全一样,还有 `struct AnyAttribute` 对 `__C.AGAttribute` 这一对(前期调研 1)。 + +**`swift-type-indexing-package` 解决不了这个**:它的改名只在模块解析成功时才生效(前期调研 5),而 AttributeGraph 这样的私有框架在 SDK 里没有模块,`__C.` 照旧。而且就算 SDK 类型解析成功了,扩展头也不经解析器(前期调研 6),`extension __C.CGRect` 与 `CoreFoundation.CGRect` 的成员并排出现。 + +**现在的声明行也会误导**:用 `NS_SWIFT_NAME(NSAttributedString.Key)` 导入成成员的 typedef,描述符里只存叶子名 `Key`(前期调研 3),于是声明行印成 `struct Key`,看不出是 `NSAttributedString.Key`。 + +用户还要能看 C 名:逆向时对照头文件、符号、IDA 里的名字都是 C 名。所以统一之后要能切回去,并且在界面上告诉读者这个类型有另一个名字。 + +## 前期调研 + +1. **复现**:本机(macOS 27.2)`swift-section 0.24.0 interface --uses-system-dyld-shared-cache --cache-image-name AttributeGraph --show-c-imported-types` 打出 `struct AnyAttribute { let rawValue: Swift.UInt32 }`、`struct AnyWeakAttribute { … var _details: __C.AGWeakAttribute.__Unnamed_struct__details }`,以及 `struct WeakAttribute { var base: __C.AGWeakAttribute }`。`dump` 则把声明也印成 `struct __C.AGWeakAttribute`(它按 mangled 身份打印)。 +2. **两套名字从哪来**: + - 声明行:`SwiftDeclarationPrinter+Headers.swift:47/56/73` 把 `descriptor.name(in:)` 交给 `renderUnboundTypeName`(`:118`),最终 `renderLeafName` 写 `TypeDeclaration(kind, bareName)`(`:137-146`)。 + - 引用处(成员类型、扩展头)来自 mangled 名。Swift 对 Clang 声明一律按 Clang 名 mangling(`swift/lib/AST/ASTMangler.cpp` 的 `tryAppendClangName`)。`SymbolicDemangler.cImportedTypeIdentity`(`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift:982`)正是把描述符换算成这个 mangled 身份的反方向映射:名字取 ABI 名,C typedef 改成 `typeAlias`,相关实体(related entity)包一层。 +3. **描述符里存的是什么**:IRGen 的 `computeIdentity`(`swift/lib/IRGen/GenMeta.cpp:1568`)写 `UserFacingName = Type->getName()`,即 Swift 名的**叶子**;Clang 声明的名字不同时,在名字后面追加 `N`(`TypeImportInfo`,`Sources/ABI/MachOSwiftSection/Models/Type/TypeImportInfo.swift`;`abiName` 只在两者不同时存在)。扫描本机 shared cache 全部子文件里「名字\0N\0」的序列: + + | 描述符的名字 | ABI 名 | 份数 | 说明 | + |---|---|---|---| + | `AnyAttribute` | `AGAttribute` | 9 | `NS_SWIFT_NAME` 改名,顶层 | + | `AnyWeakAttribute` | `AGWeakAttribute` | 4 | 同上 | + | `CGColor` | `CGColorRef` | 142 | CF 类型去 `Ref` | + | `Decimal` | `NSDecimal` | 47 | 顶层改名 | + | `Key` | `NSAttributedStringKey` | 158 | 导入成 `NSAttributedString.Key`,**只剩叶子** | + | `Name` | `NSNotificationName` | 68 | 导入成 `NSNotification.Name`,只剩叶子 | + + 结论:对顶层改名,描述符的名字就是 Swift 名;对导入成成员的类型,描述符只给叶子,父类型丢了,而且从描述符本身分不出这两种情况。 +4. **父上下文**:`IRGenModule::getAddrOfParentContextDescriptor`(`swift/lib/IRGen/GenDecl.cpp:885`)对 Clang 导入的名义类型一律挂到 `__C`(`ClangImporterContext`)下,只有真正嵌在 C 结构体里的类型(`__Unnamed_struct__details`)才以结构体为父。这一条同样说明「导入成成员」的父路径不在二进制里。 +5. **现有改名的条件**:`TypeNodePrintable.printType`(`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift:170-262`)只在 `resolvedModuleName(of:siblingIdentifier:)`(`NodePrintable.swift:179`)把 `__C` 解析成真实模块之后,才问 `CImportedNameResolving.swiftName(forCName:category:)` 改标识符。注释写明这样做是为了避免 `__C.CFString` 这种一半 C 一半 Swift 的写法。所以模块查不到时,标识符永远是 C 名。 +6. **扩展头不经解析器**(读代码得出,未实测):`renderExtendedTypeName`(`SwiftDeclarationPrinter+Headers.swift:743`)调用同步的 `ExtensionName.print(usesModuleSelectors:)`(`Sources/Declaration/SwiftDeclaration/Model/Names/ExtensionName.swift:15`),只用 `DemangleOptions` 拼字符串,不碰异步的类型名解析器。调用方有四处:`SwiftDeclarationPrinter.swift:688`、`+ObjCProtocols.swift:168`、`+ObjCImportedDefinitions.swift:101` 与 `:265`。所以即便 `swift-type-indexing` 解析成功,扩展头仍是 `__C.`。 +7. **可用的 API**:`machO.swift.typeContextDescriptors`(`Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift:54`、`MachOImage+Swift.swift:54`)、`isCImportedContextDescriptor(in:)`(`ContextDescriptorProtocol.swift:47`)、`typeImportInfo(in:)`(`TypeContextDescriptorProtocol.swift:70`)、`SymbolicDemangler.demangleContext(for:in:)`(`SymbolicDemangler.swift:342`,产出 mangled 身份节点)。打印器已有按需建一次、之后复用的状态写法(`memoizedRawLayoutBuiltinStorage`,`SwiftDeclarationPrinter.swift:115`)。 +8. **标注区域只有 kind 和内容**:swift-semantic-string 的 `AnnotationRegion`(`Sources/Semantic/AnnotationRegions/AnnotationRegion.swift:37`)没有属性字段。本仓库已有把名字编进 kind 字符串的先例:`AnnotationRegion.Kind.attachedMacroTrackedProperty(_:named:)`(`Sources/Output/SwiftPrinting/AnnotationRegionKind+AttachedMacro.swift`)。 +9. **`swift-section` 的接口参数**:`Sources/Executables/swift-section/Commands/InterfaceCommand.swift`(`--resolve-c-module-names` 在 `:34`)与 `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift`。插件 skill 在 `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`(§8 讲 `--resolve-c-module-names`),两份插件清单都是 `0.27.0`。 +10. **RuntimeViewer 现状**(`next`,含尚未推送的类型索引功能): + - 生成选项存在 `appDefaults.options`,内容区在 `appDefaults.$options` 变化时重新取接口(`RuntimeViewerAppCore/Content/ContentTextViewModel.swift`,`interfaceStream` 的 `combineLatest`);`ViewModel.currentMergedGenerationOptions`(`RuntimeViewerAppCore/Base/ViewModel.swift:51`)与它同样合并内部开关,让缓存键对齐。 + - `SwiftGenerationOptions.resolvesImportedTypeNames`(`RuntimeViewerCore/Interfaces/SwiftGenerationOptions.swift:98`,`@Default(true)`);面板的「Resolve Imported Type Names」在 `GenerationOptionsViewController.swift:64`;面板已有 `.enumOption`(`Member Sort Order` 就是),枚举写法照 `SwiftGenerationOptions.MemberSortOrder`。 + - 注释结构与宏展开都是「打印器标区域 → 引擎 `separatingAnnotationRegions()` → `RuntimeObjectInterface` 带一个可选字段」(`commentStructure`、`macroExpansions`,`RuntimeObjectInterface.swift:22/33`;`RuntimeObjectInterface+AnnotationRegions.swift`)。 + - `RuntimeSwiftSection.updateConfiguration(for:)`(`RuntimeSwiftSection.swift:1900`)在 `resolvesImportedTypeNames` 开着时请求类型索引,配置有变化就清掉接口缓存。 + - Bridge 是一个 Objective-C 协议 `SourceEditorBridging`(`RuntimeViewerSourceEditorBridge/SourceEditorBridging.swift`),点击回调走 `SourceEditorBridgingNavigationDelegate`;行内展开(`showInlineExpansion`)是「随 interface 传数据、由 bridge 放进编辑器」的先例。Bridge 从未用过行尾标注。 + - 命令行插件 skill `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md:165-172` 讲了 `__C.` 名的解析;插件版本 `1.4.0` 是类型索引功能抬的,还没发布。 +11. **复刻版 SourceEditor 的行尾标注**(`Mx-Iris/SourceEditor` tag `27.2.0-alpha.2`,RuntimeViewer 钉的版本): + - 公开入口 `SourceEditorView.insertLineAnnotation(_:)`、`removeAllLineAnnotations()`、`lineAnnotations`(`SourceEditor/macOS/SourceEditorView.swift:967-989`);`SourceEditorLineAnnotation.init(category:message:lineIdentifier:…:revealAction:…)`(`SourceEditor/Annotations/LineAnnotations/SourceEditorLineAnnotation.swift:134`);`SourceEditorLineAnnotationCategory`(同文件 `:7`);动作 `SourceEditorLineAnnotation.Action`(`SourceEditorLineAnnotationAction.swift`,`DisplayStyle` 有 `inline` / `lineItem` / `dropdown`)。 + - **横幅本身不带按钮**:点横幅时 `SourceEditorLineAnnotationManager.handleLeftMouseUpEvent`(`SourceEditorLineAnnotationManager.swift:960-977`)弹出 Xcode 那种下拉框,动作按钮在下拉框里;右键横幅弹出的菜单里只有 `revealAction` 这一项(`SourceEditorLineAnnotationView.swift:788-800`)。`SourceEditorLineAnnotationInteractionDelegate`(`SourceEditorLineAnnotationDropdownPresentation.swift:39`)没有「点了横幅」的回调。所以「点一下就切换」要么走两步(点横幅、再点下拉里的按钮),要么用右键菜单,要么去改复刻版框架。 + +## 提议方案 + +### MachOSwiftSection + +1. **拼写选项**:`SwiftDeclarationPrintConfiguration.cImportedTypeNameSpelling: CImportedTypeNameSpelling`,默认 `.swiftName`。 +2. **本镜像的名字表**:打印器第一次需要时,从本镜像所有 C 导入的类型描述符建一张表,以 mangled 身份为键、描述符的名字为值,**只收可信的条目**: + - 有 ABI 名,且与描述符的名字不同; + - 不是相关实体(`__C_Synthesized` 里的错误码结构体之类); + - ABI 名**不以**描述符的名字结尾——导入成成员的类型(`NSAttributedStringKey` → `Key`)都长这样,描述符给的只是叶子,宁可不改名。代价是 `NSDecimal` → `Decimal` 这类顶层改名也被挡掉(前期调研 3),它们照旧印 C 名,有 SDK 时由类型索引补上。 +3. **`.swiftName` 下一个 `__C` 引用怎么印**(按顺序取第一个成立的): + 1. 注册了的解析器把模块解析出来了 → 照旧写成 `模块.Swift拼写`(`swift-type-indexing-package` 的路径,不变); + 2. 名字表里有它 → **只写 Swift 名,不写模块**(`AnyWeakAttribute`,用户定的); + 3. 都没有 → 照旧 `__C.ABI名`。 + + 嵌在 C 类型里的类型,父类型那一段按同样的规则印(`AnyWeakAttribute.__Unnamed_struct__details`)。 +4. **`.cName`**:引用一律按 mangled 的样子印 `__C.ABI名`,**不问任何解析器**——模块也不解析,因为 `UIKit.UICellConfigurationState` 会和同名的 Swift 结构体混淆,这正是 `swift-type-indexing-package` 起因里的例子。 +5. **声明行与引用走同一套规则**:C 导入类型的声明名,在 `.cName` 下是 ABI 名;在 `.swiftName` 下依次取解析器给的 Swift 拼写(可以带点号,`struct NSAttributedString.Key`)、名字表里的名字、ABI 名。不可信的条目因此从 `struct Key` 变成 `struct NSAttributedStringKey`。 +6. **扩展头改走异步的类型打印路径**:只改扩展类型根在 `__C` / `__C_Synthesized` 的扩展,用打印器同一套解析与拼写印出名字,仍包成同一种 `TypeDeclaration`。其余扩展一个字节都不变。 +7. **标注**:`SwiftDeclarationPrintConfiguration.marksCImportedTypeNames`(默认关)打开时,两种拼写不同的 C 导入类型的声明名外面包一个 `AnnotationRegion`,kind 里带着两个名字。文本不变,分离之后与不标注时逐字节相同。 +8. **`swift-section interface --c-imported-type-name-spelling swift-name|c-name`**,默认 `swift-name`。 + +### RuntimeViewer + +1. **生成选项**:`SwiftGenerationOptions.cImportedTypeNameSpelling`(`@Default(.swiftName)`,旧设置读出来是 Swift 名)。Generation Options 面板的 Swift 一组加一行 `Imported Type Names: Swift | C`。它与「Resolve Imported Type Names」各管各的:后者决定要不要用 SDK 解析模块,在 C 名模式下不起作用,也不再为它建类型索引。 +2. **内部标注开关**:`GenerationOptions.marksCImportedTypeNames`,不出现在面板里,存下来的值永远是默认的 false。内容区只在 SourceEditor 可用时把它打开,`currentMergedGenerationOptions` 照同样的规则合并。 +3. **接口带回名字**:`RuntimeObjectInterface.cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]?`,每条是声明名在文本里的 UTF-8 范围和两个名字。从分离出的标注区域里取,与宏展开在同一处;注释结构不认这种 kind。 +4. **行尾标注**:bridge 新增 `showLineAnnotations(_:)` 与一个代理回调。内容区每次 `setSource` 之后,给每个改了名的声明放一条: + - Swift 名模式:`Imported from C as AGWeakAttribute`,动作 `Show C Names`; + - C 名模式:`Imported to Swift as AnyWeakAttribute`,动作 `Show Swift Names`。 + + 点横幅弹出下拉框,用里面的按钮切换;右键横幅的菜单里也有同一个动作(`revealAction`)。切换就是翻转全局的生成选项,所有内容区一起重新取接口。 +5. **其余出口跟着选项走**:MCP、App 充当 host 时的命令行、导出读的都是 `appDefaults.options`,与其他生成选项一样;独立运行的命令行 host 用默认的 Swift 名。Find 语料始终用 Swift 名打印。 + +### 交互:两次点击 + +用户选的样式里,按钮直接画在横幅上;复刻版框架的横幅没有按钮(前期调研 11)。用户批准按 Xcode 原生的两步做:点横幅弹出下拉框,用里面的按钮切换;右键横幅的菜单里也有同一个动作。不改 `Mx-Iris/SourceEditor`。 + +### 非目标 + +- **不推断导入成成员的类型的父路径**:描述符只给叶子(`Key`),没有 SDK 就保持 C 名,不按前缀去猜 `NSAttributedString.Key`。 +- **相关实体不改**:`__C_Synthesized` 里的类型(`CKError` 之类)照旧打印。 +- **只在声明行放提示**:引用处(`var base: AnyWeakAttribute`)不放,一屏里可能有几十个引用,提示会太吵。 +- **侧栏、路径栏、Find 结果里的对象名不跟着切换**:它们来自索引,不重新打印。Find 语料始终是 Swift 名,搜 C 名搜不到改了名的引用。 +- **`dump`、`diff`、`snapshot` 的键不变**:ABI diff 按 mangled 身份对比(`Sources/Output/SwiftDiffing/Keying.swift`),只有 `diff --interface` 的渲染会跟着新的默认拼写变。 +- **NSTextView 显示路径与 iOS 版不放提示**:两处都没有行尾标注;iOS 版也没有生成选项界面,只能用默认的 Swift 名。 +- **命令行工具不加对应参数**:它读 App 的生成选项,独立 host 用默认值。 + +## 改动地图 + +| 仓库 · 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| MSS · `Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift` · `CImportedTypeNameSpelling` | 新增 | `.swiftName` / `.cName` 两种拼写 | 拼写选项的类型 | 1 | +| MSS · `Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift` | 修改 | 加 `cImportedTypeNameSpelling`(默认 `.swiftName`)与 `marksCImportedTypeNames`(默认 false) | 打印配置 | 1 | +| MSS · `Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift` · `CImportedTypeSwiftNameTable` | 新增 | 从 `typeContextDescriptors` 建「mangled 身份 → 描述符名字」的表,`trustsUserFacingName(_:importInfo:)` 是可信规则 | 描述符里现成的 Swift 名 | 1 | +| MSS · `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift` | 修改 | 按需建一次名字表并复用(照 `memoizedRawLayoutBuiltinStorage`);回答节点打印器对名字表的查询;扩展头调用改成 `await` | 打印器持有名字表 | 1、2 | +| MSS · `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift` · `printType(_:)` | 修改 | `__C` 引用按方案第 3、4 条的规则印 | 统一引用处的拼写 | 2 | +| MSS · `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift` · `resolvedModuleName(of:siblingIdentifier:)` | 修改 | `.cName` 下不问解析器 | C 名模式等于 mangled 拼写 | 2 | +| MSS · 节点打印器的 delegate 协议(与 `swiftName(forCName:category:)` 同处) | 修改 | 加一个内部查询:按 mangled 身份取名字表里的 Swift 名 | 名字表不是可注册的解析器,是打印器自带的 | 2 | +| MSS · `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` · `renderTypeDeclarationHeader`、`renderExtendedTypeName` | 修改 | 声明名按同一套规则取;标注开着时包区域;扩展头根在 `__C` 时走异步类型打印 | 声明、扩展与成员一致 | 2、3 | +| MSS · `SwiftDeclarationPrinter.swift:688`、`+ObjCProtocols.swift:168`、`+ObjCImportedDefinitions.swift:101/265` | 修改 | 调用 `await renderExtendedTypeName` | 签名变成 async | 2 | +| MSS · `Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift` | 新增 | `CImportedTypeNames`(两个名字)、`AnnotationRegion.Kind.cImportedTypeName(_:)` 与解析回来的 `cImportedTypeNames` | 把两个名字交给宿主 | 3 | +| MSS · `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift`、`Sources/Executables/swift-section/Commands/InterfaceCommand.swift` | 修改 | `--c-imported-type-name-spelling swift-name\|c-name` | 命令行能切回 C 名 | 3 | +| MSS · `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift` | 新增 | 第 1–3 步的行为 | 回归 | 1–3 | +| MSS · 受新默认拼写影响的快照 / baseline 测试 | 修改 | 只更新改了名的 C 类型那几行 | 默认输出变了 | 2 | +| MSS · `README.md` 的 swift-section 一节、`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`(§4 参数表、§8、§9)、两份插件清单 | 修改 | 新参数与新默认拼写;插件版本 `0.27.0` → `0.28.0` | 文档与插件随代码 | 3 | +| MSS · `Documentations/Evolutions/README.md` | 修改 | 登记本草案 | 索引 | 0 | +| RV · `RuntimeViewerCore/Sources/RuntimeViewerCore/Interfaces/SwiftGenerationOptions.swift` | 修改 | `CImportedTypeNameSpelling` 枚举与 `cImportedTypeNameSpelling`(`@Default(.swiftName)`) | 用户选项 | 4 | +| RV · `…/Interfaces/RuntimeObjectInterface+GenerationOptions.swift` | 修改 | `marksCImportedTypeNames`(`@Default(false)`) | 只有内容区要提示 | 4 | +| RV · `…/Interfaces/SwiftDeclarationPrintConfiguration+GenerationOptions.swift` | 修改 | 把拼写映射进打印配置;**不**进 `applySwitches(of:)`,Find 语料保持 Swift 名 | 显示跟着选项,语料不跟 | 4 | +| RV · `…/Interfaces/RuntimeInterfaceCImportedTypeName.swift` | 新增 | 声明名的 UTF-8 范围与两个名字 | 接口带回提示所需的数据 | 4 | +| RV · `…/Interfaces/RuntimeObjectInterface.swift`、`RuntimeObjectInterface+AnnotationRegions.swift`、`RuntimeInterfaceCommentStructure+AnnotationRegions.swift` | 修改 | 加可选字段 `cImportedTypeNames`;分离时取出;注释结构忽略这种 kind | 照宏展开的路 | 4 | +| RV · `…/Sections/Swift/RuntimeSwiftSection.swift` · `updateConfiguration` | 修改 | 设 `marksCImportedTypeNames`;`.cName` 下不请求类型索引 | C 名用不到索引 | 4 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridge/SourceEditorBridging.swift` | 修改 | `SourceEditorBridgingLineAnnotation`、`showLineAnnotations(_:)`、代理的 `sourceEditorBridge(_:didPerformActionOfLineAnnotationWithIdentifier:)` | bridge 接口 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/SourceEditorBridge.swift`(或新的 `LineAnnotationController.swift`) | 修改 / 新增 | `setSource` 清掉旧标注;插入 `SourceEditorLineAnnotation`(类别、图标、颜色、动作、`revealAction`);动作回调代理 | 接上框架的行尾标注 | 5 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridgeTests/LineAnnotationTests.swift` | 新增 | 第 5 步的行为 | 回归 | 5 | +| RV · `RuntimeViewerPackages/Sources/RuntimeViewerAppCore/Content/ContentInterface.swift` | 修改 | 加提示的值(UTF-16 范围、消息、动作标题),按当前拼写生成文字 | AppCore 描述、AppUI / App 只画 | 6 | +| RV · `…/RuntimeViewerAppCore/Content/ContentTextViewModel.swift` | 修改 | 合并 `marksCImportedTypeNames`;新输入 `cImportedTypeNameSpellingToggled`,翻转 `appDefaults.options` 里的拼写 | 切换即改全局选项 | 6 | +| RV · `…/RuntimeViewerAppCore/Base/ViewModel.swift` · `currentMergedGenerationOptions` | 修改 | 同样合并 `marksCImportedTypeNames` | 缓存键与内容区对齐 | 6 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Content/ContentSourceEditorViewController.swift` | 修改 | `setSource` 之后 `showLineAnnotations`;代理回调进 relay | 接上 ViewModel | 6 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Generation Options/GenerationOptionsViewController.swift` | 修改 | `.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], …)` | 面板入口 | 6 | +| RV · `RuntimeViewerCore/Tests/…`、`RuntimeViewerPackages/Tests/RuntimeViewerAppCoreTests/…` | 新增 | 第 4、6 步的行为 | 回归 | 4、6 | +| RV · `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md`、两份插件清单 | 修改 | 「Imported types」一段补上描述符的 Swift 名与 C 名选项;`1.4.0` 已发布就抬到 `1.4.1`,没发布就留在 `1.4.0` | 输出变了 | 7 | +| RV · `RuntimeViewerCore/Package.swift` 与锁文件 | 修改 | 抬 MSS 的 pin | 取上游的改动 | 7 | +| RV · `Documentations/Evolutions/README.md` | 修改 | cross-repository draft 一行 | 索引 | 0 | + +## 架构图 + +**改了什么**: + +```text +MachOSwiftSection + Sources/Output/SwiftPrinting/ ++ CImportedTypeNameSpelling .swiftName (default) | .cName ++ CImportedTypeSwiftNameTable mangled identity -> descriptor's Swift name (trusted entries only) ++ AnnotationRegion.Kind.cImportedTypeName(_:) carries both names when marking is on +~ SwiftDeclarationPrintConfiguration + cImportedTypeNameSpelling, + marksCImportedTypeNames +~ SwiftDeclarationPrinter + memoized name table (machO.swift.typeContextDescriptors) +~ TypeNodePrintable.printType spelling rules for __C references +~ NodePrintable.resolvedModuleName .cName asks no resolver +~ +Headers.renderTypeDeclarationHeader declared name by the same rules; region when marked +~ +Headers.renderExtendedTypeName async; C-imported extended types through the type printer + Sources/Executables/swift-section/ +~ interface --c-imported-type-name-spelling swift-name|c-name + +RuntimeViewer + RuntimeViewerCore/Interfaces/ +~ SwiftGenerationOptions + cImportedTypeNameSpelling (@Default .swiftName) +~ GenerationOptions + marksCImportedTypeNames (internal, stored false) ++ RuntimeInterfaceCImportedTypeName declared name's UTF-8 range + both names +~ RuntimeObjectInterface + cImportedTypeNames + RuntimeViewerSourceEditorBridge/ ++ SourceEditorBridgingLineAnnotation +~ SourceEditorBridging + showLineAnnotations(_:) +~ SourceEditorBridgingNavigationDelegate + didPerformActionOfLineAnnotationWithIdentifier + RuntimeViewerAppCore/Content/ +~ ContentInterface, ContentTextViewModel + notes, + spelling toggle input + RuntimeViewerUsingAppKit/ +~ ContentSourceEditorViewController line annotations, toggle relay +~ GenerationOptionsViewController + "Imported Type Names: Swift | C" +``` + +**一个 `__C` 引用怎么印**: + +```text +printType(reference rooted in __C) +├─ spelling == .cName -> "__C." + ABI name (no resolver asked) +└─ spelling == .swiftName + ├─ a resolver resolves the module -> Module + Swift spelling (existing path) + ├─ name table has a trusted entry -> bare Swift name AnyWeakAttribute + └─ otherwise -> "__C." + ABI name __C.NSAttributedStringKey + +declared name of a C-imported descriptor +├─ .cName -> ABI name AGWeakAttribute +└─ .swiftName -> resolver's spelling ?? trusted name ?? ABI name +``` + +**点「Show C Names」之后**: + +```text +click "Show C Names" in the line annotation's dropdown + -> SourceEditorBridge: SourceEditorLineAnnotation.Action + -> navigationDelegate.sourceEditorBridge(_:didPerformActionOfLineAnnotationWithIdentifier:) + -> ContentSourceEditorViewController: cImportedTypeNameSpellingToggledRelay + -> ContentTextViewModel: appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling = .cName + -> appDefaults.$options: every content pane refetches + -> RuntimeEngine.interface(for:options:) (service process) + -> RuntimeSwiftSection.updateConfiguration printer config changed: cache cleared + -> SwiftDeclarationPrinter prints with .cName, marks declared names + -> separatingAnnotationRegions() -> RuntimeObjectInterface.cImportedTypeNames + -> ContentSourceEditorViewController.setSource + showLineAnnotations + "Imported to Swift as AnyWeakAttribute" [Show Swift Names] +``` + +## 详细设计 + +### MachOSwiftSection 的公开 API + +```swift +/// How a print spells the types a mangling places in the Clang importer's modules (`__C`, +/// `__C_Synthesized`): imported C structs, enums, typedefs, CF types and Objective-C classes. +public enum CImportedTypeNameSpelling: String, Sendable, Hashable, CaseIterable { + /// The name Swift code uses. A type whose module a registered resolver finds prints under + /// it (`CoreFoundation.CGRect`); a type the image's own descriptors rename prints under that + /// name alone (`AnyWeakAttribute`); any other keeps its mangled spelling (`__C.AGFoo`). + case swiftName + /// The C declaration's own name, exactly as the mangling spells it: `__C.AGWeakAttribute` + /// in a reference, `AGWeakAttribute` on its declaration. No resolver is asked. + case cName +} + +public struct SwiftDeclarationPrintConfiguration { + // … + /// How imported C and Objective-C type names are spelled. `.swiftName` by default. + public var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + + /// Marks the declared name of every C-imported type whose two spellings differ with a + /// `cImportedTypeName` annotation region carrying both. Off by default; separating the + /// regions gives exactly the print with it off. + public var marksCImportedTypeNames: Bool = false +} + +/// The two names of a C-imported type: what Swift code calls it and what its C declaration is called. +public struct CImportedTypeNames: Sendable, Hashable { + /// `AnyWeakAttribute`; dotted when a resolver spells a type imported as a member + /// (`NSAttributedString.Key`). + public let swiftName: String + /// `AGWeakAttribute`. + public let cName: String + + public init(swiftName: String, cName: String) +} + +extension AnnotationRegion.Kind { + /// The declared name of a C-imported type whose Swift and C names differ, marked when + /// `SwiftDeclarationPrintConfiguration.marksCImportedTypeNames` is on. The region's text is the + /// spelling printed; the kind carries both. Not a comment. + public static func cImportedTypeName(_ names: CImportedTypeNames) -> Self + + /// The names a `cImportedTypeName` kind carries; nil for any other kind. + public var cImportedTypeNames: CImportedTypeNames? { get } +} +``` + +kind 的编码是 `"cImportedTypeName" + "\u{1F}" + swiftName + "\u{1F}" + cName`。U+001F(unit separator)不会出现在 Swift 或 C 的标识符里,点号可以照常出现在 Swift 名里。解析只认这个前缀,并且要求恰好三段。 + +### 名字表(模块内部) + +```swift +/// The Swift names the image's own C-imported type descriptors give, keyed by the identity a +/// mangling spells — `SymbolicDemangler.demangleContext(for:in:)` of the descriptor. +struct CImportedTypeSwiftNameTable: Sendable { + static let empty = Self(entries: [:]) + + init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext) + + /// The trusted Swift name of the C-imported type `identity` names, or nil. + func swiftName(forIdentity identity: Node) -> String? + + /// Whether a descriptor's user-facing name is the type's whole Swift name. A type imported as + /// a member (`NS_SWIFT_NAME(NSAttributedString.Key)`) keeps only its leaf (`Key`) in the + /// descriptor, and its ABI name ends with that leaf; such a name is not trusted. + static func trustsUserFacingName(_ userFacingName: String, importInfo: TypeImportInfo) -> Bool { + guard let abiName = importInfo.abiName, abiName != userFacingName, !importInfo.isRelatedEntity else { return false } + return !abiName.hasSuffix(userFacingName) + } +} +``` + +- 键是 mangled 身份节点的**结构**(照 `ExtensionName` 的结构化 `Hashable`),所以 C typedef 的 `typeAlias` 种类、嵌套 C 类型的父路径都对得上。 +- 只遍历 `isCImportedContextDescriptor(in:) == true` 的描述符,读名字和 `typeImportInfo(in:)`,不建声明模型。表放在打印器里,第一次打印 `__C` 引用或 C 导入声明时才建;打印配置怎么变都不重建,因为表只取决于镜像。 +- 读描述符出错的条目直接跳过(表少一条只会退回 C 名),不报 degradation。 + +### 打印规则的落点 + +- `printType(_:)`:`contextNode.kind == .module` 且模块是 `__C` / `__C_Synthesized` 时: + - `.cName`:写原模块名与标识符,不调 `resolvedModuleName` 的解析分支,也不问 `swiftName(forCName:category:)`。 + - `.swiftName`:先走现有路径;模块没解析出来、但名字表对整个 `name` 节点有答案时,**不写模块与分隔符**,把 Swift 名写成标识符(语义仍是这个类型的 `printIdentifier` 上下文,RuntimeViewer 的跳转不受影响)。 + - 嵌套类型的父段经 `printName(contextNode, asPrefixContext:)` 递归回到 `printType`,自然套用同一规则。 +- `printModuleSelector(ofNestedType:)`:父段是改了名的裸名时,不写模块选择器(与第 2 条的「不写模块」一致)。 +- `renderTypeDeclarationHeader`:描述符是 C 导入的(`isCImportedContextDescriptor`)时,按方案第 5 条算出名字,替换现在的 `descriptor.name(in:)`。解析器那一路用描述符的 ABI 名去问:`moduleName(forTypeName:)` 加 `swiftName(forCName:category:)`,分类取 `CImportedTypeNameCategory(nodeKind:)`,与引用处的查询相同,所以声明与引用必然一致。`displayParentName == true`(`dump` 风格)那条路不变。 +- `renderExtendedTypeName` 改成 `async`:`extensionName.node` 根在 `__C` / `__C_Synthesized` 时,打印走 `typeDemangleResolver.resolve(for:)`,再 `.replacingTypeNameOrOtherToTypeDeclaration()`(`renderUnboundTypeName` 现成的写法);位置命名的局部类型那条分支与其余扩展保持原样。 + +### RuntimeViewer 的类型 + +```swift +extension SwiftGenerationOptions { + public enum CImportedTypeNameSpelling: String, Codable, Sendable, Equatable, Hashable, CaseIterable { + case swiftName + case cName + } +} + +// SwiftGenerationOptions +/// How imported C and Objective-C types are spelled: under their Swift name (`AnyWeakAttribute`, +/// `UIKit.UITraitCollection`), or as the binary mangles them (`__C.AGWeakAttribute`). With `.cName`, +/// `resolvesImportedTypeNames` does nothing. Swift names in settings saved before it existed. +@Default(CImportedTypeNameSpelling.swiftName) +public var cImportedTypeNameSpelling: CImportedTypeNameSpelling + +// RuntimeObjectInterface.GenerationOptions +/// Asks the Swift printer to mark the declared names of renamed C-imported types, which the +/// interface then carries as `cImportedTypeNames`. Only the content pane sets it, and only where +/// SourceEditor runs; stored values are always the default. +@Default(false) +public var marksCImportedTypeNames: Bool + +/// A declared C-imported type whose Swift and C names differ. +public struct RuntimeInterfaceCImportedTypeName: Codable, Sendable, Hashable { + /// Where the declared name is in the interface's text, in UTF-8 offsets, as the comment + /// structure counts them. + public let nameUTF8Range: Range + public let swiftName: String + public let cName: String +} + +// RuntimeObjectInterface +/// The renamed C-imported types this interface declares, when the request marked them; nil +/// otherwise, and from a peer built before them. +public let cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]? +``` + +线上兼容:旧版对端不认这两个选项,按自己的 MachOSwiftSection 打印,不带 `cImportedTypeNames`,内容区就没有提示;新版对端收到旧版请求时取默认值。 + +### Bridge + +```swift +/// A note at the end of a line, with one action — Xcode's issue annotation, used here for a +/// C-imported type's other name. A class, because `SourceEditorBridging` is an Objective-C protocol. +@objc(RuntimeViewerSourceEditorBridgingLineAnnotation) +public final class SourceEditorBridgingLineAnnotation: NSObject { + /// The UTF-16 range in the current source the note is about; it sits at the end of the + /// range's first line. + public let characterRange: NSRange + public let message: String + /// The title of the action, in the dropdown the note opens and in its contextual menu. + public let actionTitle: String + /// Handed back when the action is performed. + public let identifier: String + + public init(characterRange: NSRange, message: String, actionTitle: String, identifier: String) +} + +// SourceEditorBridging +/// Replaces the line annotations shown on the current source. `setSource` removes them all, +/// so call this after it, with ranges of that source. +func showLineAnnotations(_ annotations: [SourceEditorBridgingLineAnnotation]) + +// SourceEditorBridgingNavigationDelegate +/// The action of the line annotation shown under `identifier` was performed. +func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAnnotationWithIdentifier identifier: String) +``` + +- 实现照复刻版 tag `27.2.0-alpha.2` 的源码:`lineIdentifier` 取 `dataSource.identifierForLine(_:)`;`SourceEditorLineAnnotation` 的动作用 `Action(message:displayStyle:…)` 放进 `actions`,`revealAction` 用同一个标题,右键菜单里就有这一项;`allowsMinimization: false`、`isDraggable: false`、不画滚动条标记。 +- **类别的图标与颜色不凭猜**:Xcode 的 note 类别在 IDESourceEditor 里,不在复刻范围。实现前读 `/Volumes/RE/Xcode/26.6/` 的导出确认 note 的外观;导出里没有,就停下来问,不要按名字推断(RuntimeViewer 的 `RuntimeViewerPrecompiledLibraries/SourceEditor/AGENTS.md`)。 +- 框架里缺的东西(比如横幅上的按钮)属于 `Mx-Iris/SourceEditor` 的改动,不在 bridge 里绕。 + +### AppCore 与 App + +- `ContentInterface` 加 `cImportedTypeNameNotes: [ContentCImportedTypeNameNote]`,每条是 UTF-16 范围、消息和动作标题,由 `ContentTextViewModel` 按当前拼写生成: + - `.swiftName`:`Imported from C as ` / `Show C Names`; + - `.cName`:`Imported to Swift as ` / `Show Swift Names`。 + + 文字放在 AppCore,因为它是「描述值」(RuntimeViewerPackages 的 `Sources/AGENTS.md`)。 +- `ContentTextViewModel.Input` 加 `cImportedTypeNameSpellingToggled: Signal`,在主线程把 `appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling` 换成另一个值。之后所有内容区都经 `appDefaults.$options` 重新取接口,不需要单独通知。 +- `ContentSourceEditorViewController`:每次 `setSource` 之后 `bridge.showLineAnnotations(...)`,identifier 用提示的序号;代理回调直接 `accept` 到 relay(不管是哪一条,都是同一个全局切换)。 +- 面板:`.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], keyPath: \.swiftInterfaceOptions.cImportedTypeNameSpelling)`,放在「Resolve Imported Type Names」上面。 + +## 替代方案考量 + +- **模块未知时写 `__C.AnyWeakAttribute`**:保留「C 导入、模块未知」的信号,但与声明行 `struct AnyWeakAttribute` 仍不一致,而且是打印器以前特意避开的半翻译写法(前期调研 5)。用户选了裸名。 +- **按 C 名统一(声明行也印 `AGWeakAttribute`)作为默认**:与 mangled 一致,但读的是 Swift interface,Swift 名更贴合。C 名作为可切换的另一种拼写保留。 +- **按前缀推断成员导入的父类型**(`NSAttributedStringKey` → `NSAttributedString.Key`):二进制里没有父路径(前期调研 3、4),按前缀切分会把 `NSDecimal` 切成 `NS.Decimal` 这种错误结果。`swift-type-indexing-package` 已经否定过只靠二进制推断改名。 +- **提示做成类型名后面的胶囊标签**:要打印器多输出一段注释,复制与导出会带上它,还要给标签加点击处理。用户选了行尾标注。 +- **只切换当前编辑栏**:要在 ViewModel 里另存一份不进设置的状态,接口缓存键也要多一维;用户选了全局生成选项。 +- **把拼写和 `resolvesImportedTypeNames` 合成一个三档枚举**:类型索引功能还在验收、设置项已经写好,合并就要改它的设置与测试;两个开关各管各的更简单,C 名模式下后者不起作用即可。 + +## 影响 + +### 源码兼容性(source compatibility) + +- **纯新增**:`CImportedTypeNameSpelling`、`CImportedTypeNames`、两个配置属性、`AnnotationRegion.Kind.cImportedTypeName(_:)` / `cImportedTypeNames`。 +- `renderExtendedTypeName` 是 `package`,改成 `async` 只影响本包的四个调用点。 +- **输出有变化**(不是编译期破坏):默认拼写下,改了名的 C 类型的引用与扩展头变成 Swift 名;不可信条目的声明行从叶子名变成 C 名(`struct Key` → `struct NSAttributedStringKey`、`struct Decimal` → `struct NSDecimal`);SDK 类型的扩展头在注册了解析器时变成 `模块.名字`。依赖输出文本的下游测试要更新期望值;要旧的 C 名可以设 `.cName`,但声明行会变成 C 名,与以前的「声明 Swift、引用 C」不完全相同——那种混合正是要去掉的。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本仓库**:`SwiftInterface`(`SwiftInterfaceBuilder` 用同一个打印器)、`SwiftDiffing` 的 `--interface` 渲染、`swift-section interface` 的默认输出跟着变;ABI diff 的键不变。 +- **MachOKitUI、SymbolViewer**:经打印器显示 Swift interface,输出变化同上,不需要改代码。 +- **RuntimeViewer**(本提案的另一半): + - **用户可见**:用 SourceEditor 显示时,改了名的 C 类型的声明行末尾多一条灰色的行尾标注;Generation Options 多一行 `Imported Type Names`;默认接口里这些类型统一成 Swift 名;MCP、App 充当 host 时的命令行与导出跟着选项;Find 结果始终是 Swift 名。 + - **可发现性**:提示默认就在(只要 SourceEditor 可用),面板里有同名开关;不加首次引导。 + - **数据与配置兼容**:`appDefaults.options` 里没有这个键时取 `.swiftName`;`marksCImportedTypeNames` 存下来永远是 false。不需要迁移。 + - **平台**:提示只在 macOS 的 SourceEditor 路径;NSTextView 路径与 iOS 版只有默认的 Swift 名。 + - **发布**:不涉及权限、entitlement、公证与 Sparkle。 + - **派生数据**:Find 语料的打印变了,但代码变化本身会改变产出者身份(`Documentations/DerivedData.md`),旧语料自然失效,不必改 variant。 +- **顺序约束**:两边都叠在 `swift-type-indexing-package` 上(它的改动还在两个仓库的本地 `next` 上、没推送)。本提案要等它先收尾,或者在它的功能分支之上开分支,落地时再变基。 + +### 文档与示例 + +- 本仓库 `README.md` 的 swift-section 一节与 `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`:§4 参数表加 `--c-imported-type-name-spelling`;§8 说明默认的 Swift 名不依赖 `--resolve-c-module-names`;§9「看起来像 bug 其实不是」加一条:导入成成员的类型没有 SDK 时保持 C 名。两份插件清单抬到 `0.28.0`。 +- RuntimeViewer 的命令行插件 skill(「Imported types print under their module and Swift name」那一段)补上描述符的 Swift 名与 C 名选项。 +- 术语:落地时判断要不要在两边的术语表登记「C 导入类型名拼写」。 + +## API 演进与废弃策略 + +- 没有被替代的旧 API,不需要废弃期。 +- 默认输出变化按 minor 版本发布,在 release note 里写明「C 导入类型默认按 Swift 名打印,要旧的 C 名请设 `.cName` / `--c-imported-type-name-spelling c-name`」。 +- `CImportedTypeNameSpelling` 用 enum:只有两种拼写,调用方需要穷举(RuntimeViewer 的映射、命令行参数)。以后真要加第三种,就是一次有意的源码破坏,到时再评估。 + +## 落地步骤 + +0. **登记草案** —— 两边的提案索引 + - 行为:无(只有文档)。 +1. **名字表与可信规则** —— MSS 的 `CImportedTypeNameSpelling.swift`、配置两个属性、`CImportedTypeSwiftNameTable.swift`、打印器按需建表 + - 行为:`trustsUserFacingNameWhenABINameDiffers`(`AnyWeakAttribute` / `AGWeakAttribute`、`CGColor` / `CGColorRef`) + - 行为:`refusesLeafNameOfTypeImportedAsMember`(`Key` / `NSAttributedStringKey`) + - 行为:`refusesRelatedEntityName` + - 行为:`refusesNameWithoutABIName` + - 行为:`nameTableReadsAttributeGraphDescriptors`(读系统 shared cache 的 AttributeGraph:`AnyWeakAttribute`、`AnyAttribute` 的身份节点各对一条) +2. **打印规则** —— MSS 的 `printType`、`resolvedModuleName`、delegate 查询、声明头、扩展头与四个调用点、快照更新 + - 行为:`swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown`(`var _details: AnyWeakAttribute.__Unnamed_struct__details`、`extension AnyWeakAttribute: Swift.Hashable`) + - 行为:`swiftSpellingKeepsModuleThatResolverFinds`(测试替身解析器:`__C.CGRect` → `CoreFoundation.CGRect`,扩展头相同) + - 行为:`cSpellingPrintsMangledNamesAndAsksNoResolver`(声明 `struct AGWeakAttribute`、扩展 `extension __C.AGWeakAttribute`,替身解析器被调用 0 次) + - 行为:`untrustedDeclaredNamePrintsCName`(SwiftUICore 的 `NSAttributedStringKey` 声明行) + - 行为:`extensionHeaderSpellsLikeMemberTypes` + - 行为:`nonCImportedExtensionHeadersAreByteIdentical` + - 行为:`abiDiffKeysAreUnchanged`(现有 diff 测试照旧通过) +3. **标注与命令行** —— MSS 的 `AnnotationRegionKind+CImportedTypeName.swift`、声明头包区域、`InterfaceRequest` 与 `InterfaceCommand`、README 与插件 skill + - 行为:`markedDeclaredNameCarriesBothSpellings` + - 行为:`separatedMarkedPrintEqualsUnmarkedPrint` + - 行为:`regionKindRoundTripsDottedSwiftName`(`NSAttributedString.Key`) + - 行为:`sameSpellingsAreNotMarked` + - 行为:`interfaceCommandParsesCNameSpelling` + - 推送 MSS 的功能分支,RuntimeViewer 临时按分支钉(照 `swift-type-indexing-package` 的 TEMPORARY 写法)。 +4. **RuntimeViewer Core** —— 两个选项、`RuntimeInterfaceCImportedTypeName`、接口字段、分离、`updateConfiguration` + - 行为:`spellingDefaultsToSwiftNameInOlderPayload` + - 行为:`marksCImportedTypeNamesIsNeverStoredTrue` + - 行为:`interfaceCarriesCImportedTypeNamesWhenMarked` + - 行为:`commentStructureIgnoresCImportedTypeNameRegions` + - 行为:`cNameSpellingRequestsNoTypeIndex` + - 行为:`changingSpellingClearsInterfaceCache` + - 行为:`corpusPrintsSwiftNamesWhateverTheSpelling` +5. **Bridge 的行尾标注** —— `SourceEditorBridging.swift`、`SourceEditorBridge.swift`、`LineAnnotationTests.swift` + - 行为:`lineAnnotationSitsOnFirstLineOfItsRange` + - 行为:`setSourceRemovesLineAnnotations` + - 行为:`performingActionNotifiesDelegateWithIdentifier` + - 行为:`contextualMenuOffersTheSameAction` +6. **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 + - 行为:`notesNameCDeclarationUnderSwiftSpelling` + - 行为:`notesNameSwiftTypeUnderCSpelling` + - 行为:`togglingFlipsStoredSpelling` + - 行为:`mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` + - 编完用 SourceEditor 打开 AttributeGraph 的 `AnyWeakAttribute`,人工看一次提示与切换(交给用户目视)。 +7. **收尾** —— RuntimeViewer 插件 skill 与版本、抬 MSS pin、重解析锁文件、两边索引与本提案状态 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 可信规则与「为什么导入成成员的类型不改名」是下次维护最容易踩的,倾向写进 `Documentations/Internal/` 的一篇实现说明,或并入现有的类型名解析说明。 +- **有没有引入新术语** —— 「C 导入类型名拼写」「可信的描述符名字」是否登记术语表。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-24 | Created as Draft | RuntimeViewer 显示 AttributeGraph 的 `AGWeakAttribute` 时,声明行是 Swift 名,扩展头与成员类型是 C 名;用户要求统一,并在 SourceEditor 里给一个能点击切换 Swift 名 / C 名的提示。 | +| 2026-11-24 | 提示用 Xcode 式的行尾标注 | 用户在「行尾标注」和「类型名后的胶囊标签」之间选了前者:不改接口文本,复制与导出不受影响。 | +| 2026-11-24 | 模块未知时写裸名 | 用户选了 `AnyWeakAttribute`,不选 `__C.AnyWeakAttribute`:与声明行完全一致。 | +| 2026-11-24 | 切换是全局生成选项 | 用户选了全局:存进设置、所有窗口一起变、面板里有同名开关,不做只管当前编辑栏的临时状态。 | +| 2026-11-24 | 提案放在 MachOSwiftSection | 照 RuntimeViewer 索引里两篇 cross-repository draft 的做法,跨仓库的唯一提案由最底层的仓库维护。 | +| 2026-11-24 | 导入成成员的类型不用描述符的名字 | 实测 shared cache:`NSAttributedStringKey` 的描述符只存 `Key`、`NSNotificationName` 只存 `Name`,二进制里没有父路径;ABI 名以描述符名字结尾的一律不信,代价是 `NSDecimal` → `Decimal` 这类也退回 C 名。 | +| 2026-11-24 | C 名模式等于 mangled 拼写 | 不解析模块:`UIKit.UICellConfigurationState` 会与同名 Swift 结构体混淆。 | +| 2026-11-24 | 扩展头一并修 | 扩展头不经解析器(读代码得出),和本提案改的是同一条路径;只改根在 `__C` 的扩展,其余逐字节不变。 | +| 2026-11-24 | 两次点击待用户确认 | 复刻版框架的横幅没有按钮,点横幅弹下拉框、按钮在下拉框里;先按原生两步加右键菜单做,要一次点击就得改 `Mx-Iris/SourceEditor`。 | +| 2026-11-24 | Accepted | 用户批准,开始实现。 | +| 2026-11-24 | 交互定为两次点击 | 用户确认按 Xcode 原生的两步做(横幅 → 下拉里的按钮,右键菜单也有),不改复刻版框架。 | +| 2026-11-24 | 两边都从远端的 `feature/swift-type-indexing-package` 切 | 远端比两边本地 `next` 多了验收时的修复(宏的配色、文档);提案随功能分支的第一个提交走,因为两边本地 `next` 都有未推送的合并,不往 `next` 上单独提交提案。 | From 1e4905007a53954439604ceb79778f8570f8d0ca Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:14:27 +0800 Subject: [PATCH 083/175] WIP: spell C-imported type names one way, Swift or C The printer reads the Swift names the image's own C-imported type descriptors give (trusting only whole names), prints declarations, member types and extension headers by one rule, marks declared names with both spellings on request, and swift-section interface gains --c-imported-type-name-spelling. --- .../Swift/InterfaceRequest.swift | 9 + .../Commands/InterfaceCommand.swift | 7 + .../Models/CommandLineSupport.swift | 24 ++ ...notationRegionKind+CImportedTypeName.swift | 47 +++ .../CImportedTypeNameSpelling.swift | 25 ++ .../CImportedTypeSwiftNameTable.swift | 86 +++++ .../InterfaceNodePrintable.swift | 2 + .../NodePrintables/NodePrintable.swift | 16 +- .../NodePrintableDelegate.swift | 8 + .../NodePrintables/TypeNodePrintable.swift | 27 +- .../NodePrinter/FunctionNodePrinter.swift | 1 + .../NodePrinter/SubscriptNodePrinter.swift | 1 + .../NodePrinter/TypeNodePrinter.swift | 1 + .../NodePrinter/VariableNodePrinter.swift | 1 + .../SwiftDeclarationPrintConfiguration.swift | 20 + .../SwiftDeclarationPrinter+Headers.swift | 103 ++++- ...ationPrinter+ObjCImportedDefinitions.swift | 4 +- ...wiftDeclarationPrinter+ObjCProtocols.swift | 2 +- .../SwiftDeclarationPrinter.swift | 31 +- .../CImportedTypeNameSpellingTests.swift | 351 ++++++++++++++++++ .../CommandRequestMappingTests.swift | 10 + 21 files changed, 762 insertions(+), 14 deletions(-) create mode 100644 Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift create mode 100644 Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift create mode 100644 Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift create mode 100644 Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index 6c1ba2c9..fc50f479 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -75,6 +75,12 @@ public struct InterfaceRequest: Sendable, Equatable { /// `any P.Type`), as the compiler writes a `.swiftinterface`. On by /// default. public var usesExistentialAny: Bool + /// How the types a mangling places in `__C` spell their names: the name + /// Swift code uses (`AnyWeakAttribute`, from the image's own descriptors, + /// under the module `cModuleNameResolution` finds), or the C name every + /// mangled reference carries (`__C.AGWeakAttribute`). Swift names by + /// default (evolution proposal `c-imported-type-name-spelling`). + public var cImportedTypeNameSpelling: CImportedTypeNameSpelling /// What an attached macro generated, as the binary has it: an /// `@Observable` class's registrar, the storage and computed properties of /// its tracked properties, the generated methods and conformance. Off by @@ -114,6 +120,7 @@ public struct InterfaceRequest: Sendable, Equatable { infersObjCOverridesFromSelectorNames: Bool = false, usesModuleSelectors: Bool = false, usesExistentialAny: Bool = true, + cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName, expandsMacros: Bool = false, protocolRequirementPlacement: ProtocolRequirementPlacement = .protocolWhereClause, emitsHeader: Bool = false, @@ -138,6 +145,7 @@ public struct InterfaceRequest: Sendable, Equatable { self.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames self.usesModuleSelectors = usesModuleSelectors self.usesExistentialAny = usesExistentialAny + self.cImportedTypeNameSpelling = cImportedTypeNameSpelling self.expandsMacros = expandsMacros self.protocolRequirementPlacement = protocolRequirementPlacement self.emitsHeader = emitsHeader @@ -178,6 +186,7 @@ public struct InterfaceRequest: Sendable, Equatable { printConfiguration.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames printConfiguration.usesModuleSelectors = usesModuleSelectors printConfiguration.usesExistentialAny = usesExistentialAny + printConfiguration.cImportedTypeNameSpelling = cImportedTypeNameSpelling printConfiguration.expandsMacros = expandsMacros printConfiguration.protocolRequirementPlacement = protocolRequirementPlacement diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 79462ccb..2c208666 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -33,6 +33,9 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, and its dependencies' ObjC metadata. Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") var resolveCModuleNames: Bool = false + @Option(name: .customLong("c-imported-type-name-spelling"), help: "How imported C and Objective-C types are spelled. swift-name (the default) prints the name Swift code uses: a type the binary's own descriptors rename prints under that name (__C.AGWeakAttribute -> AnyWeakAttribute), under its module when --resolve-c-module-names finds it. c-name prints every one as the binary mangles it (__C.AGWeakAttribute), declarations included, and resolves nothing.") + var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + @Option(name: .customLong("supplementary-apinotes"), help: "A supplementary .apinotes file (or a directory of them) of user-provided type mappings for frameworks with no SDK module (e.g. AttributeGraph), loaded on top of the SDK's own APINotes. Repeatable; later paths override earlier ones. Only used with --resolve-c-module-names.", completion: .file()) var supplementaryAPINotesPaths: [String] = [] @@ -104,6 +107,7 @@ struct InterfaceCommand: AsyncParsableCommand { infersObjCOverridesFromSelectorNames: objcMemberOptions.infersOverridesFromSelectorNames, usesModuleSelectors: moduleSelectors, usesExistentialAny: existentialAny, + cImportedTypeNameSpelling: cImportedTypeNameSpelling, expandsMacros: expandMacros, protocolRequirementPlacement: requirementsOnAssociatedTypes ? .associatedTypes : .protocolWhereClause, emitsHeader: emitHeader, @@ -118,6 +122,9 @@ struct InterfaceCommand: AsyncParsableCommand { // Progress lines have always gone to stdout here, mixed into the // product unless `-o` is given. let output = StandardStreamOutput(colorScheme: colorScheme, standardOutputSeverities: [.progress]) + if resolveCModuleNames, cImportedTypeNameSpelling == .cName { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --resolve-c-module-names has no effect with --c-imported-type-name-spelling c-name")) + } if !resolveCModuleNames, !supplementaryAPINotesPaths.isEmpty { output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --supplementary-apinotes has no effect without --resolve-c-module-names")) } diff --git a/Sources/Executables/swift-section/Models/CommandLineSupport.swift b/Sources/Executables/swift-section/Models/CommandLineSupport.swift index 20e29580..b987b977 100644 --- a/Sources/Executables/swift-section/Models/CommandLineSupport.swift +++ b/Sources/Executables/swift-section/Models/CommandLineSupport.swift @@ -1,6 +1,7 @@ import ArgumentParser import Foundation import SwiftSectionKit +import SwiftPrinting // The library's enums, spelled on the command line by their raw values. The // library is in this package, so the conformances are not retroactive. @@ -9,6 +10,29 @@ extension DumpSection: ExpressibleByArgument {} extension TransformerModule: ExpressibleByArgument {} extension ObjCDeclarationKind: ExpressibleByArgument {} +// Spelled in the command line's kebab case rather than by its raw value. +extension CImportedTypeNameSpelling: ExpressibleByArgument { + public init?(argument: String) { + guard let spelling = Self.allCases.first(where: { $0.argumentValue == argument }) else { return nil } + self = spelling + } + + public var defaultValueDescription: String { + argumentValue + } + + public static var allValueStrings: [String] { + allCases.map(\.argumentValue) + } + + private var argumentValue: String { + switch self { + case .swiftName: "swift-name" + case .cName: "c-name" + } + } +} + extension SwiftSectionEnvironment { /// What the command line stamps into headers and provenance. static var commandLine: SwiftSectionEnvironment { diff --git a/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift b/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift new file mode 100644 index 00000000..98d5ba58 --- /dev/null +++ b/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift @@ -0,0 +1,47 @@ +import Semantic + +/// The two names of a C-imported type: what Swift code calls it and what its C +/// declaration is called (evolution proposal `c-imported-type-name-spelling`). +public struct CImportedTypeNames: Sendable, Hashable { + /// `AnyWeakAttribute`; dotted when a resolver spells a type imported as a + /// member (`NSAttributedString.Key`). + public let swiftName: String + + /// `AGWeakAttribute`, the name every mangled reference spells. + public let cName: String + + public init(swiftName: String, cName: String) { + self.swiftName = swiftName + self.cName = cName + } +} + +extension AnnotationRegion.Kind { + private static let cImportedTypeNamePrefix = "cImportedTypeName" + + /// U+001F, the unit separator: in no Swift or C identifier, so a dotted + /// Swift name passes through whole. + private static let cImportedTypeNameSeparator: Character = "\u{1F}" + + /// The declared name of a C-imported type whose Swift and C names differ, + /// marked when `SwiftDeclarationPrintConfiguration.marksCImportedTypeNames` + /// is on. The region's text is the spelling printed; the kind carries both + /// names, so a host can offer the other one without reading the text. Not a + /// comment: a host drawing annotation regions as comments leaves these out. + public static func cImportedTypeName(_ names: CImportedTypeNames) -> Self { + let separator = String(cImportedTypeNameSeparator) + return Self(cImportedTypeNamePrefix + separator + names.swiftName + separator + names.cName) + } + + /// The names a ``cImportedTypeName(_:)`` kind carries; nil for any other + /// kind. + public var cImportedTypeNames: CImportedTypeNames? { + let components = rawValue.split(separator: Self.cImportedTypeNameSeparator, omittingEmptySubsequences: false) + guard components.count == 3, + components[0] == Self.cImportedTypeNamePrefix, + !components[1].isEmpty, + !components[2].isEmpty + else { return nil } + return CImportedTypeNames(swiftName: String(components[1]), cName: String(components[2])) + } +} diff --git a/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift b/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift new file mode 100644 index 00000000..465aa68c --- /dev/null +++ b/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift @@ -0,0 +1,25 @@ +/// How a print spells the types a mangling places in the Clang importer's +/// modules (`__C`, `__C_Synthesized`): imported C structs, enums, typedefs, +/// CF types and Objective-C classes (evolution proposal +/// `c-imported-type-name-spelling`). +/// +/// A type imported from C has two names. Its descriptor carries the one Swift +/// code uses (`AnyWeakAttribute`), while every mangled reference to it carries +/// the C declaration's own (`__C.AGWeakAttribute`), because the compiler +/// mangles Clang declarations by their Clang names. A print picks one of the +/// two for declarations, member types and extension headers alike. +public enum CImportedTypeNameSpelling: String, Sendable, Hashable, CaseIterable { + /// The name Swift code uses. A type whose module a registered resolver + /// finds prints under it (`CoreFoundation.CGRect`, + /// `UIKit.__UICellConfigurationState`); a type the image's own + /// descriptors rename prints under that name alone (`AnyWeakAttribute`); + /// any other keeps its mangled spelling (`__C.AGFoo`). + case swiftName + + /// The C declaration's own name, exactly as the mangling spells it: + /// `__C.AGWeakAttribute` in a reference, `AGWeakAttribute` on its + /// declaration. No resolver is asked, not even for the module: a C name + /// under the Swift module (`UIKit.UICellConfigurationState`) could read as + /// a Swift type of the same name. + case cName +} diff --git a/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift b/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift new file mode 100644 index 00000000..44691378 --- /dev/null +++ b/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift @@ -0,0 +1,86 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import BinaryParseSupport + +/// The Swift names the image's own C-imported type descriptors give, keyed by +/// the identity a mangling spells for each type (evolution proposal +/// `c-imported-type-name-spelling`). +/// +/// IRGen writes a C-imported type's descriptor name as the type's Swift name +/// and, when the C declaration is called something else, appends that C name +/// as the import info's ABI name (`TypeImportInfo`). Every mangled reference +/// spells the C name, so this table is what turns `__C.AGWeakAttribute` back +/// into the `AnyWeakAttribute` its declaration prints — without an SDK, for +/// private frameworks too. +/// +/// Only names that are the type's whole Swift name are kept; see +/// ``trustsUserFacingName(_:importInfo:)``. +struct CImportedTypeSwiftNameTable: Sendable { + static let empty = Self(swiftNamesByIdentity: [:]) + + /// Keyed by the identity node with any `type` wrapper taken off. `Node` + /// hashes and compares by structure, so a reference demangled from a + /// symbol finds the entry built from the descriptor. + private let swiftNamesByIdentity: [Node: String] + + private init(swiftNamesByIdentity: [Node: String]) { + self.swiftNamesByIdentity = swiftNamesByIdentity + } + + /// Reads every C-imported type descriptor of the image. A descriptor that + /// cannot be read is left out: a missing entry only keeps that type's C + /// name. + init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext) { + var swiftNamesByIdentity: [Node: String] = [:] + for descriptorWrapper in typeContextDescriptors { + let descriptor = descriptorWrapper.typeContextDescriptor + guard descriptor.hasImportInfo, + (try? descriptor.isCImportedContextDescriptor(in: context)) == true, + let importInfo = try? descriptor.typeImportInfo(in: context), + let userFacingName = try? descriptorWrapper.namedContextDescriptor.name(in: context), + Self.trustsUserFacingName(userFacingName, importInfo: importInfo), + let identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: context) + else { continue } + swiftNamesByIdentity[Self.key(for: identity)] = userFacingName + } + self.swiftNamesByIdentity = swiftNamesByIdentity + } + + /// The trusted Swift name of the C-imported type `identity` names — a + /// nominal node as a mangling spells it, with or without a `type` wrapper + /// — or nil. + func swiftName(forIdentity identity: Node) -> String? { + guard !swiftNamesByIdentity.isEmpty else { return nil } + return swiftNamesByIdentity[Self.key(for: identity)] + } + + var isEmpty: Bool { + swiftNamesByIdentity.isEmpty + } + + /// Whether a descriptor's user-facing name is the type's whole Swift name. + /// + /// - It has to differ from the ABI name, or there is nothing to rename. + /// - An importer-synthesized related entity (the error struct of an + /// `NS_ERROR_ENUM`) is spelled through its original declaration, not + /// renamed. + /// - A type imported as a member (`NS_SWIFT_NAME(NSAttributedString.Key)`) + /// keeps only its leaf in the descriptor (`Key`), and nothing in the + /// binary names the type it is a member of. Such a C name ends with the + /// leaf (`NSAttributedStringKey`), so a name the ABI name ends with is + /// not trusted. A top-level rename shaped the same way (`NSDecimal` to + /// `Decimal`) is refused with them and keeps its C name. + static func trustsUserFacingName(_ userFacingName: String, importInfo: TypeImportInfo) -> Bool { + guard let abiName = importInfo.abiName, abiName != userFacingName, !importInfo.isRelatedEntity else { return false } + return !abiName.hasSuffix(userFacingName) + } + + private static func key(for identity: Node) -> Node { + var node = identity + while node.kind == .type, let wrapped = node.children.first { + node = wrapped + } + return node + } +} diff --git a/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift index a6ba6499..99fbaed5 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift @@ -44,6 +44,8 @@ struct InterfaceNodePrinterContext: InterfaceNodePrin var usesExistentialAny = false + var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + /// How many `repeat` patterns enclose the node being printed. `each` is /// only ever written inside one. var packExpansionDepth = 0 diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift index 3bfbe142..9b51ea94 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift @@ -29,6 +29,11 @@ protocol NodePrintableContext { /// Spell existential types with the `any` keyword. Fixed for a printer's /// lifetime, like `usesModuleSelectors`. var usesExistentialAny: Bool { get } + + /// How the types a mangling places in `__C` / `__C_Synthesized` are + /// spelled (evolution proposal `c-imported-type-name-spelling`). Fixed for + /// a printer's lifetime, like `usesModuleSelectors`. + var cImportedTypeNameSpelling: CImportedTypeNameSpelling { get } } /// Per-call hints for one `printName`. @@ -175,10 +180,13 @@ extension NodePrintable { /// The module a `module` node names, with a C-imported module spelling /// (`__C` / `__ObjC`) resolved to its real module through the delegate - /// when the sibling identifier finds one. + /// when the sibling identifier finds one. A printer spelling C names + /// (`CImportedTypeNameSpelling.cName`) asks nothing and keeps the + /// mangling's module. func resolvedModuleName(of node: Node, siblingIdentifier: String?) async -> (text: String, isResolvedCImportedModule: Bool) { let moduleName = node.text ?? "" - if moduleName == objcModule || moduleName == cModule, + if context.cImportedTypeNameSpelling == .swiftName, + moduleName == objcModule || moduleName == cModule, let identifier = siblingIdentifier, let delegate, let updatedModuleName = await or(await delegate.moduleName(forTypeName: identifier), await delegate.moduleName(forTypeName: identifier.strippedRefSuffix)) { @@ -231,7 +239,9 @@ extension NodePrintable { } extension String { - fileprivate var strippedRefSuffix: String { + /// A CF type's name without the `Ref` its C typedef carries + /// (`CFStringRef` → `CFString`), the name a module resolver knows it by. + var strippedRefSuffix: String { if hasSuffix("Ref") { return String(dropLast(3)) } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift index 7140957f..13400feb 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift @@ -22,4 +22,12 @@ protocol NodePrintableDelegate: AnyObject, Sendable { /// `SwiftDeclarationPrintConfiguration.usesExistentialAny`). A printer /// reads it once, when it is created. var usesExistentialAny: Bool { get } + /// How C-imported type names are spelled (see + /// `SwiftDeclarationPrintConfiguration.cImportedTypeNameSpelling`). A + /// printer reads it once, when it is created. + var cImportedTypeNameSpelling: CImportedTypeNameSpelling { get } + /// The Swift name the image's own descriptor gives the C-imported type + /// `identity` names, when that name is the type's whole Swift name + /// (`CImportedTypeSwiftNameTable`); nil otherwise. + func cImportedTypeSwiftName(forIdentity identity: Node) -> String? } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index ab404e14..23728994 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -184,6 +184,12 @@ extension TypeNodePrintable { var resolvedCImportedModule = false var resolvedCImportedModuleName: String? + // The Swift name the image's own descriptor gives a C-imported type + // (`AnyWeakAttribute` for `__C.AGWeakAttribute`; evolution proposal + // `c-imported-type-name-spelling`): what the identifier prints when no + // resolver spells it, with no module at all when none finds the + // module either — the name the type's declaration prints. + let descriptorSwiftName = swiftNameFromDescriptor(ofCImportedType: name) if shouldPrintContext(), !isLocalType { let writtenUnitCountBeforeContext = target.writtenUnitCount if contextNode.kind == .module { @@ -193,7 +199,9 @@ extension TypeNodePrintable { if resolvedCImportedModule { resolvedCImportedModuleName = moduleName.text } - target.write(moduleName.text, context: .context(for: contextNode, state: .printModule)) + if resolvedCImportedModule || descriptorSwiftName == nil { + target.write(moduleName.text, context: .context(for: contextNode, state: .printModule)) + } // The module→type separator stays inside this leaf's scope so // a fully-qualified top-level name (`AppKit.MenuItem`) // selects as one span. @@ -254,6 +262,8 @@ extension TypeNodePrintable { } else { target.write(swiftSpelling, context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) } + } else if let descriptorSwiftName { + target.write(descriptorSwiftName, context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) } else { await printIdentifier(declarationName, parentKind: name.kind) } @@ -267,6 +277,21 @@ extension TypeNodePrintable { } } + /// The Swift name the image's own descriptor gives the C-imported type + /// `name` refers to, when this printer spells Swift names and the type + /// sits directly in `__C` / `__C_Synthesized`; nil otherwise. A type + /// nested in a C type keeps its own name, and its parent prints through + /// this same rule when its reference is printed. + func swiftNameFromDescriptor(ofCImportedType name: Node) -> String? { + guard context.cImportedTypeNameSpelling == .swiftName, + let delegate, + let contextNode = name.children.first, + contextNode.kind == .module, + contextNode.text == objcModule || contextNode.text == cModule + else { return nil } + return delegate.cImportedTypeSwiftName(forIdentity: name) + } + /// Writes the module selector a nested type's own name carries — the /// `Foundation::` of `Swift::Duration.Foundation::TimeFormatStyle` — when /// this printer uses module selectors. The compiler writes one on every diff --git a/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift index 49ca3924..abc79a76 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift @@ -35,6 +35,7 @@ struct FunctionNodePrinter: MemberDeclarationNodePrin self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName } mutating func printDeclaration(_ node: Node) async throws { diff --git a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift index b9a356bd..53d53a7b 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift @@ -41,6 +41,7 @@ struct SubscriptNodePrinter: MemberDeclarationNodePri self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName } init(isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { diff --git a/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift index 4d86506e..447d45fa 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift @@ -18,6 +18,7 @@ struct TypeNodePrinter: InterfaceNodePrintable { self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName context.isProtocol = isProtocol } diff --git a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift index 95ef08a2..ca12e78f 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift @@ -44,6 +44,7 @@ struct VariableNodePrinter: MemberDeclarationNodePrin self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName } init(isStored: Bool, isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index 34c0398c..f1264281 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -128,6 +128,26 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { /// be written `any Collection`. public var usesExistentialAny: Bool = true + /// How the types a mangling places in `__C` / `__C_Synthesized` are + /// spelled — declarations, member types and extension headers alike + /// (evolution proposal `c-imported-type-name-spelling`). + /// + /// `.swiftName` by default: a type the image's own descriptors rename + /// prints under its Swift name (`AnyWeakAttribute`), under the module a + /// registered resolver finds for it when one does. `.cName` prints every + /// one as the mangling spells it (`__C.AGWeakAttribute`) and asks no + /// resolver. + public var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + + /// Mark the declared name of every C-imported type whose Swift and C names + /// differ with a ``AnnotationRegion/Kind/cImportedTypeName(_:)`` region + /// carrying both, so a host can say what the type's other name is. + /// + /// `FrozenSemanticString.separatingAnnotationRegions()` of the frozen + /// print gives exactly the string printed with this off. Off by default, + /// and off the output is unchanged byte for byte. + public var marksCImportedTypeNames: Bool = false + /// Print what an attached macro the type was declared with generated, as /// the binary has it, instead of the macro attribute and the /// declarations the source wrote (evolution proposal diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 85f7b755..2f8193ff 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -44,7 +44,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), declaredName: declaredTypeName(of: .struct(dumped.descriptor)), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, ownedBy: .type(.struct(dumped.descriptor)), invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .enum(let dumped): @@ -53,7 +53,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), declaredName: declaredTypeName(of: .enum(dumped.descriptor)), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, ownedBy: .type(.enum(dumped.descriptor)), invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .class(let dumped): @@ -70,7 +70,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.class, descriptorWrapper: .type(.class(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.class, descriptorWrapper: .type(.class(dumped.descriptor)), declaredName: declaredTypeName(of: .class(dumped.descriptor)), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } let superclass = try await renderClassInheritanceClause(dumped, objcProtocolNames: objcProtocolNames, resolver: resolver) if boundTypeNode == nil, let genericContext = dumped.genericContext { @@ -115,14 +115,83 @@ extension SwiftDeclarationPrinter { } @SemanticStringBuilder - private func renderUnboundTypeName(_ kind: SemanticType.TypeKind, descriptorWrapper: ContextDescriptorWrapper, name: String, displayParentName: Bool, leafNameNode: Node?, resolver: DemangleResolver) async throws -> SemanticString { + private func renderUnboundTypeName(_ kind: SemanticType.TypeKind, descriptorWrapper: ContextDescriptorWrapper, declaredName: DeclaredTypeName, displayParentName: Bool, leafNameNode: Node?, resolver: DemangleResolver) async throws -> SemanticString { if displayParentName { try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptorWrapper, in: machO.context)).replacingTypeNameOrOtherToTypeDeclaration() + } else if configuration.marksCImportedTypeNames, let cImportedTypeNames = declaredName.cImportedTypeNames { + // The declared name of a C-imported type known by two names + // (evolution proposal `c-imported-type-name-spelling`): the region + // tells a host the other one, the text stays what it prints. + AnnotationRegion(.cImportedTypeName(cImportedTypeNames)) { + renderLeafName(kind: kind, bareName: declaredName.name, leafNameNode: leafNameNode) + } } else { - renderLeafName(kind: kind, bareName: name, leafNameNode: leafNameNode) + renderLeafName(kind: kind, bareName: declaredName.name, leafNameNode: leafNameNode) } } + /// The name a type's declaration prints, and the two names of a C-imported + /// type that has two (evolution proposal `c-imported-type-name-spelling`). + struct DeclaredTypeName { + let name: String + /// Both names of a C-imported type whose Swift and C names differ and + /// are both known; nil for any other type. + let cImportedTypeNames: CImportedTypeNames? + } + + /// The name `descriptorWrapper`'s declaration prints. + /// + /// Any type but a C-imported one whose descriptor carries a C name other + /// than its own prints its descriptor name. Such a C-imported type follows + /// the rule its references follow (`TypeNodePrintable.printType`): + /// spelling C names, its C name; spelling Swift names, the Swift spelling + /// a registered resolver gives once it finds the module, else the + /// descriptor name when that is the whole Swift name + /// (`CImportedTypeSwiftNameTable.trustsUserFacingName(_:importInfo:)`), + /// else its C name — a type imported as a member keeps only its leaf + /// (`Key`) in the descriptor, which would read as a type of its own. + func declaredTypeName(of descriptorWrapper: TypeContextDescriptorWrapper) async throws -> DeclaredTypeName { + let userFacingName = try descriptorWrapper.namedContextDescriptor.name(in: machO.context) + let descriptor = descriptorWrapper.typeContextDescriptor + guard descriptor.hasImportInfo, + (try? descriptor.isCImportedContextDescriptor(in: machO.context)) == true, + let importInfo = try? descriptor.typeImportInfo(in: machO.context), + let cName = importInfo.abiName, + cName != userFacingName, + !importInfo.isRelatedEntity + else { + return DeclaredTypeName(name: userFacingName, cImportedTypeNames: nil) + } + let swiftName: String? + if let resolvedSwiftName = await resolvedSwiftName(ofCImportedDescriptor: descriptorWrapper, cName: cName) { + swiftName = resolvedSwiftName + } else if CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo) { + swiftName = userFacingName + } else { + swiftName = nil + } + let cImportedTypeNames = swiftName.map { CImportedTypeNames(swiftName: $0, cName: cName) } + switch configuration.cImportedTypeNameSpelling { + case .swiftName: + return DeclaredTypeName(name: swiftName ?? cName, cImportedTypeNames: cImportedTypeNames) + case .cName: + return DeclaredTypeName(name: cName, cImportedTypeNames: cImportedTypeNames) + } + } + + /// The Swift spelling the registered resolvers give a C-imported type, + /// asked the way a reference to it asks: only once a resolver finds its + /// module, by its C name and the category its mangling spells. + private func resolvedSwiftName(ofCImportedDescriptor descriptorWrapper: TypeContextDescriptorWrapper, cName: String) async -> String? { + guard await moduleName(forTypeName: cName) != nil || moduleName(forTypeName: cName.strippedRefSuffix) != nil, + var identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machO.context) + else { return nil } + while identity.kind == .type, let wrapped = identity.children.first { + identity = wrapped + } + return await swiftName(forCName: cName, category: CImportedTypeNameCategory(nodeKind: identity.kind)) + } + /// Renders a declaration's own leaf name. For an ordinary type this is just /// `TypeDeclaration(kind, bareName)`; for a `private`/`fileprivate` type whose /// leaf name demangles to a `.privateDeclName`, the build-specific @@ -739,16 +808,38 @@ extension SwiftDeclarationPrinter { /// would read `Holder.Visitor`, a member type the source never declared, /// and alike for every unnamed `Visitor` of `Holder`. Both spellings carry /// module selectors when the configuration asks for them. + /// + /// The extended type of an extension of a C-imported type prints through + /// the type printer, spelled the way its references and its declaration + /// are (evolution proposal `c-imported-type-name-spelling`): spelling Swift + /// names, `extension AnyWeakAttribute`, or `extension CoreFoundation.CGRect` + /// once a resolver finds the module. Spelling C names it prints as the + /// mangling spells it, which the plain spelling below already does. @SemanticStringBuilder - package func renderExtendedTypeName(_ extensionName: ExtensionName) -> SemanticString { + package func renderExtendedTypeName(_ extensionName: ExtensionName) async -> SemanticString { if spellsPositionNamedLocalType(extensionName.node) { let positionBasedNameOptions = DemangleOptions.interfaceTypeBuilderOnly.union(.showPrivateDiscriminators) TypeDeclaration(kind: extensionName.kind.semanticTypeKind, extensionName.name(using: configuration.usesModuleSelectors ? positionBasedNameOptions.union(.useModuleSelectors) : positionBasedNameOptions)) + } else if configuration.cImportedTypeNameSpelling == .swiftName, + isCImportedTypeReference(extensionName.node), + let spelledName = try? await typeDemangleResolver.resolve(for: extensionName.node) { + spelledName.replacingTypeNameOrOtherToTypeDeclaration() } else { extensionName.print(usesModuleSelectors: configuration.usesModuleSelectors) } } + /// Whether `name`, with any `type` wrapper taken off, is a nominal type + /// directly in `__C` / `__C_Synthesized`. + private func isCImportedTypeReference(_ name: NodeReference) -> Bool { + var current = name + while current.kind == .type, let wrapped = current.children.first { + current = wrapped + } + guard let contextNode = current.children.first, contextNode.kind == .module else { return false } + return contextNode.text == objcModule || contextNode.text == cModule + } + /// Whether `name` or a type it is nested in is a position-based local /// type. private func spellsPositionNamedLocalType(_ name: NodeReference) -> Bool { diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift index c6cc11b1..2f6ba015 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift @@ -98,7 +98,7 @@ extension SwiftDeclarationPrinter { await DeclarationBlock(level: level) { Keyword(.extension) Space() - renderExtendedTypeName(definition.className.extensionName) + await renderExtendedTypeName(definition.className.extensionName) } body: { await MemberList(level: level) { comment(.note("Objective-C methods of the class that no member of the Swift class answers to. Swift names follow the ClangImporter's rules for these selectors."), as: .note) @@ -262,7 +262,7 @@ extension SwiftDeclarationPrinter { try await DeclarationBlock(level: level) { Keyword(.extension) Space() - renderExtendedTypeName(definition.extendedClassName.extensionName) + await renderExtendedTypeName(definition.extendedClassName.extensionName) try await inheritanceClause(definition.protocolNames.map(\.node)) } body: { try await objcImportedMemberList(definition.members, swiftMembers: swiftMembers, leadingNote: "The Objective-C category \(definition.uniqueName).", level: level) diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift index bd8c1f4b..efdab701 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift @@ -165,7 +165,7 @@ extension SwiftDeclarationPrinter { try await DeclarationBlock(level: level) { Keyword(.extension) Space() - renderExtendedTypeName(conformance.extendedTypeName.extensionName) + await renderExtendedTypeName(conformance.extendedTypeName.extensionName) for (offset, protocolName) in conformance.protocolNames.offsetEnumerated() { Standard(offset.isStart ? ":" : ",") Space() diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 565730ea..9ec9da51 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -119,6 +119,27 @@ public final class SwiftDeclarationPrinter: S case computed([SwiftDeclaration.TypeName: RawLayoutBuiltinStorage]) } + /// The Swift names this image's own C-imported type descriptors give + /// (`CImportedTypeSwiftNameTable`), built once on first use. It depends + /// on the image alone, so no configuration change rebuilds it. + @Mutex + private var memoizedCImportedTypeSwiftNames: CImportedTypeSwiftNameTable? = nil + + func cImportedTypeSwiftNames() -> CImportedTypeSwiftNameTable { + if let table = memoizedCImportedTypeSwiftNames { + return table + } + return _memoizedCImportedTypeSwiftNames.withLock { memoizedTable in + if let table = memoizedTable { + return table + } + let typeContextDescriptors = (try? machO.swift.typeContextDescriptors) ?? [] + let table = CImportedTypeSwiftNameTable(typeContextDescriptors: typeContextDescriptors, in: machO.context) + memoizedTable = table + return table + } + } + func rawLayoutBuiltinStorageByTypeName() -> [SwiftDeclaration.TypeName: RawLayoutBuiltinStorage] { if case .computed(let storage) = memoizedRawLayoutBuiltinStorage { return storage @@ -685,7 +706,7 @@ public final class SwiftDeclarationPrinter: S } Keyword(.extension) Space() - renderExtendedTypeName(extensionDefinition.extensionName) + await renderExtendedTypeName(extensionDefinition.extensionName) // This print operation's single conformance materialization // (proposal 0002). Propagates on failure: a public entry must not @@ -1305,4 +1326,12 @@ extension SwiftDeclarationPrinter: NodePrintableDelegate { var usesExistentialAny: Bool { configuration.usesExistentialAny } + + var cImportedTypeNameSpelling: CImportedTypeNameSpelling { + configuration.cImportedTypeNameSpelling + } + + func cImportedTypeSwiftName(forIdentity identity: Node) -> String? { + cImportedTypeSwiftNames().swiftName(forIdentity: identity) + } } diff --git a/Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift b/Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift new file mode 100644 index 00000000..c6665087 --- /dev/null +++ b/Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift @@ -0,0 +1,351 @@ +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +import SwiftDeclaration +import SwiftIndexing +@_spi(Internals) import SwiftInspection +import Semantic +import SwiftSectionTestingSupport + +/// Evolution proposal `c-imported-type-name-spelling`: a C-imported type the +/// compiler knows by two names prints under one of them everywhere — +/// declaration, member types and extension headers. +/// +/// The fixture's bridging header reproduces the shapes AttributeGraph and the +/// SDK have: a struct renamed with `swift_name` (`AGWeakAttribute` → +/// `AnyWeakAttribute`) holding an anonymous struct, a `swift_wrapper` typedef +/// renamed the same way (`AGAttribute` → `AnyAttribute`), and a typedef +/// imported as a member of another type (`NSAttributedStringKey` → +/// `NSAttributedString.Key`), whose descriptor keeps only the leaf. +@Suite +struct CImportedTypeNameSpellingTests { + // MARK: - Fixture + + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private static let fixtureHeader = """ + #import + #include + + typedef uint32_t AGFooIdentifier __attribute__((swift_wrapper(struct))) __attribute__((swift_name("AnyFooIdentifier"))); + + typedef struct __attribute__((swift_name("AnyFooThing"))) AGFooThing { + struct { + AGFooIdentifier identifier; + uint32_t seed; + } _details; + } AGFooThing; + + typedef struct ProbeOwner { + int value; + } ProbeOwner; + + typedef NSString *ProbeOwnerKey __attribute__((swift_wrapper(struct))) __attribute__((swift_name("ProbeOwner.Key"))); + """ + + /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, + /// "On-the-fly-compiled fixture dylibs need a class"). The conformances + /// put the C-imported types' descriptors into this image: the Swift-side + /// `Equatable` of `AnyFooThing`, and the importer's synthesized `Hashable` + /// of the two wrappers, reached through a generic function. + private static let fixtureSource = """ + import Foundation + + public final class Anchor {} + + public struct Holder { + public var thing: AnyFooThing + public var identifier: AnyFooIdentifier + public var key: ProbeOwner.Key + + public init(thing: AnyFooThing, identifier: AnyFooIdentifier, key: ProbeOwner.Key) { + self.thing = thing + self.identifier = identifier + self.key = key + } + } + + extension AnyFooThing: Equatable { + public static func == (left: AnyFooThing, right: AnyFooThing) -> Bool { + left._details.identifier == right._details.identifier && left._details.seed == right._details.seed + } + } + + @inline(never) public func hashValue(of value: Value) -> Int { value.hashValue } + @inline(never) public func isEqual(_ left: Value, _ right: Value) -> Bool { left == right } + + public func exercise(_ holder: Holder) -> (Int, Int, Bool) { + (hashValue(of: holder.identifier), hashValue(of: holder.key), isEqual(holder.thing, holder.thing)) + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("CImportedTypeNameSpellingFixture-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let headerURL = workingDirectory.appendingPathComponent("CImportedTypeNameSpellingFixture.h") + let sourceURL = workingDirectory.appendingPathComponent("CImportedTypeNameSpellingFixture.swift") + let libraryURL = workingDirectory.appendingPathComponent("libCImportedTypeNameSpellingFixture.dylib") + try fixtureHeader.write(to: headerURL, atomically: true, encoding: .utf8) + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-emit-library", "-module-name", "CImportedTypeNameSpellingFixture", + "-target", "arm64-apple-macosx15.0", + "-import-objc-header", headerURL.path, + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "C-imported type name spelling fixture compilation failed:\n\(diagnostics)" } + } + + private func loadFixtureMachOFile() throws -> MachOFile { + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) + } + + /// Records every query, and answers the ones it was set up to answer. + private final class RecordingResolver: ModuleNameResolving, CImportedNameResolving, @unchecked Sendable { + private let lock = NSLock() + private var recordedQueryCount = 0 + private let moduleNamesByTypeName: [String: String] + private let swiftNamesByCName: [String: String] + + init(moduleNamesByTypeName: [String: String], swiftNamesByCName: [String: String] = [:]) { + self.moduleNamesByTypeName = moduleNamesByTypeName + self.swiftNamesByCName = swiftNamesByCName + } + + var queryCount: Int { + lock.withLock { recordedQueryCount } + } + + func moduleName(forTypeName typeName: String) async -> String? { + lock.withLock { recordedQueryCount += 1 } + return moduleNamesByTypeName[typeName] + } + + func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { + lock.withLock { recordedQueryCount += 1 } + return swiftNamesByCName[cName] + } + } + + private func makeBuilder(spelling: CImportedTypeNameSpelling = .swiftName, marksCImportedTypeNames: Bool = false, resolver: RecordingResolver? = nil) async throws -> SwiftInterfaceBuilder { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.cImportedTypeNameSpelling = spelling + printConfiguration.marksCImportedTypeNames = marksCImportedTypeNames + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.indexConfiguration = SwiftDeclarationIndexConfiguration(showCImportedTypes: true) + configuration.printConfiguration = printConfiguration + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: loadFixtureMachOFile()) + if let resolver { + builder.printer.addTypeNameResolver(resolver) + } + try await builder.prepare() + return builder + } + + private func buildInterface(spelling: CImportedTypeNameSpelling = .swiftName, resolver: RecordingResolver? = nil) async throws -> String { + try await makeBuilder(spelling: spelling, resolver: resolver).printRoot().string + } + + private func lines(of interface: String, startingWith prefix: String) -> [String] { + interface.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix(prefix) } + } + + // MARK: - Trusting a descriptor's name + + @Test("A descriptor name is trusted when it is the type's whole Swift name", arguments: [ + ("AnyWeakAttribute", "AGWeakAttribute"), + ("AnyAttribute", "AGAttribute"), + ("CGColor", "CGColorRef"), + ("__UIPointerShape", "UIPointerShape"), + ]) + func trustsUserFacingNameWhenABINameDiffers(userFacingName: String, abiName: String) { + let importInfo = TypeImportInfo(abiName: abiName, symbolNamespace: nil, relatedEntityName: nil) + #expect(CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo)) + } + + /// A type imported as a member keeps only its leaf; a top-level rename of + /// the same shape is refused with it. + @Test("A leaf the C name ends with is not trusted", arguments: [ + ("Key", "NSAttributedStringKey"), + ("Name", "NSNotificationName"), + ("Decimal", "NSDecimal"), + ]) + func refusesLeafNameOfTypeImportedAsMember(userFacingName: String, abiName: String) { + let importInfo = TypeImportInfo(abiName: abiName, symbolNamespace: nil, relatedEntityName: nil) + #expect(!CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo)) + } + + @Test func refusesRelatedEntityName() { + let importInfo = TypeImportInfo(abiName: "CKErrorCode", symbolNamespace: nil, relatedEntityName: "e") + #expect(!CImportedTypeSwiftNameTable.trustsUserFacingName("CKError", importInfo: importInfo)) + } + + @Test func refusesNameWithoutABIName() { + let importInfo = TypeImportInfo(abiName: nil, symbolNamespace: TypeImportInfo.cTypedefSymbolNamespace, relatedEntityName: nil) + #expect(!CImportedTypeSwiftNameTable.trustsUserFacingName("CGRect", importInfo: importInfo)) + } + + @Test func nameTableReadsTheFixturesDescriptors() throws { + let machOFile = try loadFixtureMachOFile() + let descriptors = try machOFile.swift.typeContextDescriptors + let table = CImportedTypeSwiftNameTable(typeContextDescriptors: descriptors, in: machOFile.context) + var swiftNamesByDescriptorName: [String: String?] = [:] + for descriptorWrapper in descriptors where (try? descriptorWrapper.typeContextDescriptor.isCImportedContextDescriptor(in: machOFile.context)) == true { + let descriptorName = try descriptorWrapper.namedContextDescriptor.name(in: machOFile.context) + let identity = try SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machOFile.context) + swiftNamesByDescriptorName[descriptorName] = table.swiftName(forIdentity: identity) + } + #expect(swiftNamesByDescriptorName["AnyFooThing"] == .some("AnyFooThing")) + #expect(swiftNamesByDescriptorName["AnyFooIdentifier"] == .some("AnyFooIdentifier")) + // Imported as `ProbeOwner.Key`: the descriptor says `Key`, which is not trusted. + #expect(swiftNamesByDescriptorName["Key"] == .some(nil)) + // The anonymous struct keeps its own name and has no entry. + #expect(swiftNamesByDescriptorName["__Unnamed_struct__details"] == .some(nil)) + } + + // MARK: - Spelling Swift names + + @Test func swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown() async throws { + let interface = try await buildInterface() + #expect(interface.contains("struct AnyFooThing {"), "\(interface)") + #expect(interface.contains("var _details: AnyFooThing.__Unnamed_struct__details"), "\(interface)") + #expect(interface.contains("var identifier: AnyFooIdentifier"), "\(interface)") + #expect(interface.contains("var thing: AnyFooThing"), "\(interface)") + let equatableLines = lines(of: interface, startingWith: "extension AnyFooThing: ") + #expect(equatableLines.contains { $0.contains("Swift.Equatable") }, "\(interface)") + #expect(!interface.contains("AGFooThing"), "\(interface)") + #expect(!interface.contains("AGFooIdentifier"), "\(interface)") + } + + @Test func untrustedDeclaredNamePrintsCName() async throws { + let interface = try await buildInterface() + #expect(interface.contains("struct ProbeOwnerKey {"), "\(interface)") + #expect(!interface.contains("struct Key {"), "\(interface)") + #expect(interface.contains("var key: __C.ProbeOwnerKey"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension __C.ProbeOwnerKey: ").isEmpty, "\(interface)") + } + + @Test func swiftSpellingKeepsModuleThatResolverFinds() async throws { + let resolver = RecordingResolver( + moduleNamesByTypeName: ["AGFooThing": "ProbeModule", "ProbeOwnerKey": "ProbeModule"], + swiftNamesByCName: ["ProbeOwnerKey": "ProbeOwner.Key"] + ) + let interface = try await buildInterface(resolver: resolver) + // The resolver finds the module but has no Swift name: the descriptor's. + #expect(interface.contains("var thing: ProbeModule.AnyFooThing"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension ProbeModule.AnyFooThing: ").isEmpty, "\(interface)") + #expect(interface.contains("struct AnyFooThing {"), "\(interface)") + // The resolver spells the member import whole. + #expect(interface.contains("var key: ProbeModule.ProbeOwner.Key"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension ProbeModule.ProbeOwner.Key: ").isEmpty, "\(interface)") + #expect(interface.contains("struct ProbeOwner.Key {"), "\(interface)") + // Nothing found for the wrapper: the descriptor's name, alone. + #expect(interface.contains("var identifier: AnyFooIdentifier"), "\(interface)") + } + + @Test func extensionHeaderSpellsLikeMemberTypes() async throws { + let interface = try await buildInterface() + let extensionLines = lines(of: interface, startingWith: "extension ") + #expect(!extensionLines.isEmpty, "\(interface)") + for line in extensionLines { + #expect(!line.hasPrefix("extension __C.AGFoo"), "\(line)") + } + } + + // MARK: - Spelling C names + + @Test func cSpellingPrintsMangledNamesAndAsksNoResolver() async throws { + let resolver = RecordingResolver(moduleNamesByTypeName: ["AGFooThing": "ProbeModule", "ProbeOwnerKey": "ProbeModule"]) + let interface = try await buildInterface(spelling: .cName, resolver: resolver) + #expect(interface.contains("struct AGFooThing {"), "\(interface)") + #expect(interface.contains("var _details: __C.AGFooThing.__Unnamed_struct__details"), "\(interface)") + #expect(interface.contains("var identifier: __C.AGFooIdentifier"), "\(interface)") + #expect(interface.contains("var thing: __C.AGFooThing"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension __C.AGFooThing: ").isEmpty, "\(interface)") + #expect(interface.contains("struct ProbeOwnerKey {"), "\(interface)") + #expect(!interface.contains("AnyFooThing"), "\(interface)") + #expect(!interface.contains("ProbeModule"), "\(interface)") + #expect(resolver.queryCount == 0) + } + + // MARK: - Marking declared names + + @Test func markedDeclaredNameCarriesBothSpellings() async throws { + let unmarked = try await makeBuilder().printRoot().frozen() + let marked = try await makeBuilder(marksCImportedTypeNames: true).printRoot().frozen() + let separated = marked.separatingAnnotationRegions() + #expect(separated.text == unmarked) + #expect(unmarked.separatingAnnotationRegions().annotations.isEmpty) + + let printedBytes = Array(separated.text.string.utf8) + var markedNames: [CImportedTypeNames: String] = [:] + for region in separated.annotations.regions { + guard let names = region.kind.cImportedTypeNames else { continue } + let regionStart = Int(region.utf8Offset) + markedNames[names] = String(decoding: printedBytes[regionStart ..< regionStart + Int(region.utf8Length)], as: UTF8.self) + } + #expect(markedNames == [ + CImportedTypeNames(swiftName: "AnyFooThing", cName: "AGFooThing"): "AnyFooThing", + CImportedTypeNames(swiftName: "AnyFooIdentifier", cName: "AGFooIdentifier"): "AnyFooIdentifier", + ]) + } + + @Test func markedCSpellingCarriesTheSameNames() async throws { + let marked = try await makeBuilder(spelling: .cName, marksCImportedTypeNames: true).printRoot().frozen() + let separated = marked.separatingAnnotationRegions() + let printedBytes = Array(separated.text.string.utf8) + let region = try #require(separated.annotations.regions(ofKind: .cImportedTypeName(CImportedTypeNames(swiftName: "AnyFooThing", cName: "AGFooThing"))).first) + let regionStart = Int(region.utf8Offset) + #expect(String(decoding: printedBytes[regionStart ..< regionStart + Int(region.utf8Length)], as: UTF8.self) == "AGFooThing") + } + + @Test func sameSpellingsAreNotMarked() async throws { + let marked = try await makeBuilder(marksCImportedTypeNames: true).printRoot().frozen() + let names = marked.separatingAnnotationRegions().annotations.regions.compactMap(\.kind.cImportedTypeNames) + // `ProbeOwnerKey` has no known Swift name without a resolver, and + // the anonymous struct has one name only. + #expect(!names.contains { $0.cName == "ProbeOwnerKey" || $0.cName == "__Unnamed_struct__details" }) + } + + @Test func regionKindRoundTripsDottedSwiftName() { + let names = CImportedTypeNames(swiftName: "NSAttributedString.Key", cName: "NSAttributedStringKey") + #expect(AnnotationRegion.Kind.cImportedTypeName(names).cImportedTypeNames == names) + #expect(AnnotationRegion.Kind.note.cImportedTypeNames == nil) + #expect(AnnotationRegion.Kind("cImportedTypeName").cImportedTypeNames == nil) + } +} diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index f582b006..9ed0b5ee 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -166,6 +166,16 @@ struct CommandRequestMappingTests { #expect(try InterfaceCommand.parse(["/tmp/Sample", "--no-existential-any"]).makeRequest().usesExistentialAny == false) } + @Test("interface spells C-imported types by their Swift names unless --c-imported-type-name-spelling c-name") + func interfaceCImportedTypeNameSpelling() throws { + let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.cImportedTypeNameSpelling == .swiftName) + #expect(InterfaceRequest(source: defaultRequest.source).cImportedTypeNameSpelling == .swiftName) + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--c-imported-type-name-spelling", "c-name"]).makeRequest().cImportedTypeNameSpelling == .cName) + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--c-imported-type-name-spelling", "swift-name"]).makeRequest().cImportedTypeNameSpelling == .swiftName) + #expect(throws: (any Error).self) { try InterfaceCommand.parse(["/tmp/Sample", "--c-imported-type-name-spelling", "cName"]) } + } + @Test("interface folds what an attached macro generated unless --expand-macros") func interfaceExpandMacros() throws { let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() From 7e3d61331b16f9add8fd25e7988cb29a582d82b4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:17:24 +0800 Subject: [PATCH 084/175] WIP: ask the module resolvers one after the other for a declared C-imported name --- .../SwiftPrinting/SwiftDeclarationPrinter+Headers.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 2f8193ff..92009632 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -183,7 +183,11 @@ extension SwiftDeclarationPrinter { /// asked the way a reference to it asks: only once a resolver finds its /// module, by its C name and the category its mangling spells. private func resolvedSwiftName(ofCImportedDescriptor descriptorWrapper: TypeContextDescriptorWrapper, cName: String) async -> String? { - guard await moduleName(forTypeName: cName) != nil || moduleName(forTypeName: cName.strippedRefSuffix) != nil, + var resolvedModuleName = await moduleName(forTypeName: cName) + if resolvedModuleName == nil { + resolvedModuleName = await moduleName(forTypeName: cName.strippedRefSuffix) + } + guard resolvedModuleName != nil, var identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machO.context) else { return nil } while identity.kind == .type, let wrapped = identity.children.first { From 3e7dc050a84ddb174e04d24250de3443114fdf6a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:19:45 +0800 Subject: [PATCH 085/175] WIP: separate the names in a C-imported type name kind with a bar --- .../AnnotationRegionKind+CImportedTypeName.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift b/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift index 98d5ba58..8cb8d463 100644 --- a/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift +++ b/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift @@ -19,9 +19,10 @@ public struct CImportedTypeNames: Sendable, Hashable { extension AnnotationRegion.Kind { private static let cImportedTypeNamePrefix = "cImportedTypeName" - /// U+001F, the unit separator: in no Swift or C identifier, so a dotted - /// Swift name passes through whole. - private static let cImportedTypeNameSeparator: Character = "\u{1F}" + /// In no Swift or C name, so a dotted Swift name passes through whole. Not + /// a control character: swift-semantic-string rejects those in a kind, + /// since its own markers are control characters. + private static let cImportedTypeNameSeparator: Character = "|" /// The declared name of a C-imported type whose Swift and C names differ, /// marked when `SwiftDeclarationPrintConfiguration.marksCImportedTypeNames` From 98079ba24ae475c37536df6cfc89c2fc1352f82a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:21:14 +0800 Subject: [PATCH 086/175] WIP: ask no resolver for a C-spelled declaration unless its names are marked --- .../Output/SwiftPrinting/CImportedTypeNameSpelling.swift | 8 +++++--- .../SwiftPrinting/SwiftDeclarationPrinter+Headers.swift | 5 ++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift b/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift index 465aa68c..835b8dd9 100644 --- a/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift +++ b/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift @@ -18,8 +18,10 @@ public enum CImportedTypeNameSpelling: String, Sendable, Hashable, CaseIterable /// The C declaration's own name, exactly as the mangling spells it: /// `__C.AGWeakAttribute` in a reference, `AGWeakAttribute` on its - /// declaration. No resolver is asked, not even for the module: a C name - /// under the Swift module (`UIKit.UICellConfigurationState`) could read as - /// a Swift type of the same name. + /// declaration. No resolver is asked for what it prints, not even for the + /// module: a C name under the Swift module (`UIKit.UICellConfigurationState`) + /// could read as a Swift type of the same name. A print marking declared + /// names (`marksCImportedTypeNames`) still asks for the Swift name the mark + /// carries. case cName } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 92009632..af5ca1f8 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -162,8 +162,11 @@ extension SwiftDeclarationPrinter { else { return DeclaredTypeName(name: userFacingName, cImportedTypeNames: nil) } + // Spelling C names prints the C name whatever the resolvers say; they are asked only for + // the Swift name a marked declaration carries. + let asksResolvers = configuration.cImportedTypeNameSpelling == .swiftName || configuration.marksCImportedTypeNames let swiftName: String? - if let resolvedSwiftName = await resolvedSwiftName(ofCImportedDescriptor: descriptorWrapper, cName: cName) { + if asksResolvers, let resolvedSwiftName = await resolvedSwiftName(ofCImportedDescriptor: descriptorWrapper, cName: cName) { swiftName = resolvedSwiftName } else if CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo) { swiftName = userFacingName From 6b6bafe333d3ced396fd1fe088f1856ac4a6bb41 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:27:31 +0800 Subject: [PATCH 087/175] docs: describe --c-imported-type-name-spelling and the Swift names of C types; plugin 0.28.0 --- .../swift-section/.claude-plugin/plugin.json | 2 +- .../swift-section/.codex-plugin/plugin.json | 2 +- .../skills/swift-section-cli/SKILL.md | 17 +++++++++++++++-- README.md | 5 +++++ 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index f3d41ffd..a20ee6d3 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.27.0", + "version": "0.28.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/.codex-plugin/plugin.json b/AgentPlugins/swift-section/.codex-plugin/plugin.json index b8095c53..ae02ee00 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.27.0", + "version": "0.28.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index 8b31c16f..27640470 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -215,8 +215,8 @@ switches). Only `interface` has: `--exported-only`, `--sort-members-by-offset`, `--parse-opaque-return-type`, `--show-c-imported-types`, `--resolve-c-module-names`, -`--supplementary-apinotes`, `--infer-objc-overrides`, `--requirements-on-associated-types`, -`--expand-macros`. +`--supplementary-apinotes`, `--c-imported-type-name-spelling`, `--infer-objc-overrides`, +`--requirements-on-associated-types`, `--expand-macros`. `--requirements-on-associated-types` changes where a protocol's requirements print, never which: `associatedtype Body: SwiftUI.View` instead of `protocol View where Self.Body: SwiftUI.View`, @@ -361,12 +361,25 @@ minutes), cached after in `~/Library/Application Support/swift-type-indexing`. W API notes and Objective-C metadata attribute names. A binary whose SDK is not installed warns and prints `__C.` unresolved. `--supplementary-apinotes` only does anything alongside it. +**Swift names come first, with or without the SDK.** A C type has two names: its descriptor carries +the one Swift code uses, every mangled reference the C one. `interface` prints the Swift one everywhere +— declaration, member types, extension headers — when the binary's own descriptor gives it +(`AnyWeakAttribute` for `AGWeakAttribute`, `CGColor` for `CGColorRef`), with no module when nothing +resolves it and under its module when this flag does. `--c-imported-type-name-spelling c-name` prints +every C-imported type as the binary mangles it (`struct AGWeakAttribute`, `__C.AGWeakAttribute`) and +makes this flag do nothing. + `objc interface --mark-sdk-swift-names` reads the same SDK's API notes for an Objective-C header: the class's or protocol's `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT` on a line above `@interface`, a member's before its `;`. API notes only, about two seconds, no sourcekitd. ## 9. Reading the output: things that look like bugs and are not +- **A C type imported as a member keeps its C name** (`struct NSAttributedStringKey`, + `__C.NSAttributedStringKey`) unless `--resolve-c-module-names` spells it + (`Foundation.NSAttributedString.Key`): its descriptor stores only the leaf (`Key`), and nothing + in the binary names the type it belongs to. A top-level rename shaped the same way + (`NSDecimal` → `Decimal`) keeps its C name too. - **`// not exported`** is an export-trie fact, not an access-level claim. A missing entry means "not statically callable from outside this image", which is not the same as `internal`. - **`… is declared in Enabled.swift of module SwiftUICore`** above a SwiftUI declaration is not a diff --git a/README.md b/README.md index 180c47a6..03e86d61 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,11 @@ swift-section interface --resolve-c-module-names /path/to/binary # Frameworks with no SDK module (AttributeGraph, …) take user-provided APINotes swift-section interface --resolve-c-module-names --supplementary-apinotes AttributeGraph.apinotes /path/to/binary +# A C type the binary's own descriptors rename prints under its Swift name everywhere — +# declaration, member types, extension headers (`AnyWeakAttribute`, not `__C.AGWeakAttribute`). +# c-name prints every C-imported type as the binary mangles it instead. +swift-section interface --c-imported-type-name-spelling c-name /path/to/binary + # Experimental: spell opaque result types (`some View`) from their opaque type # descriptors; complex return types may fail to parse swift-section interface --parse-opaque-return-type /path/to/binary From 6c06d2d1f6c0ec6d28c07e4975bbd8c516d7c257 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 11:50:36 +0800 Subject: [PATCH 088/175] docs: record the C-imported type name spelling's progress and the decisions made while implementing it --- Documentations/Evolutions/README.md | 2 +- .../draft-c-imported-type-name-spelling.html | 2 +- .../draft-c-imported-type-name-spelling.md | 89 +++++++++---------- 3 files changed, 46 insertions(+), 47 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index f2d4aa5c..8fec495c 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -120,4 +120,4 @@ | [0103](0103-cross-reference-test-scan-load.md) | 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 | Implemented | | [0104](0104-shared-macho-testing-support.md) | 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport | Implemented | | draft | [类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer](draft-swift-type-indexing-package.md)(跨仓库唯一提案) | In Progress | -| draft | [C 导入类型的名字统一成 Swift 名,并能切换回 C 名](draft-c-imported-type-name-spelling.md)(跨仓库唯一提案,RuntimeViewer 参与) | Accepted | +| draft | [C 导入类型的名字统一成 Swift 名,并能切换回 C 名](draft-c-imported-type-name-spelling.md)(跨仓库唯一提案,RuntimeViewer 参与) | In Progress | diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html index 6ecd98ec..c51edfb0 100644 --- a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html @@ -163,7 +163,7 @@

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-24
    项目类型
    库(跨仓库唯一提案,RuntimeViewer 参与)
    原文
    draft-c-imported-type-name-spelling.md
    diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md index 66656a58..53ea74ae 100644 --- a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md @@ -1,6 +1,6 @@ # Draft - C 导入类型的名字统一成 Swift 名,并能切换回 C 名 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-24 - **最后更新**: 2026-11-24 @@ -100,7 +100,7 @@ extension __C.AGWeakAttribute: Swift.Equatable {} 3. 都没有 → 照旧 `__C.ABI名`。 嵌在 C 类型里的类型,父类型那一段按同样的规则印(`AnyWeakAttribute.__Unnamed_struct__details`)。 -4. **`.cName`**:引用一律按 mangled 的样子印 `__C.ABI名`,**不问任何解析器**——模块也不解析,因为 `UIKit.UICellConfigurationState` 会和同名的 Swift 结构体混淆,这正是 `swift-type-indexing-package` 起因里的例子。 +4. **`.cName`**:引用一律按 mangled 的样子印 `__C.ABI名`,**打印时不问任何解析器**——模块也不解析,因为 `UIKit.UICellConfigurationState` 会和同名的 Swift 结构体混淆,这正是 `swift-type-indexing-package` 起因里的例子。只有打开了标注(第 7 条)时,声明名会去问解析器要标注里那个 Swift 名,打印出来的文字不变。 5. **声明行与引用走同一套规则**:C 导入类型的声明名,在 `.cName` 下是 ABI 名;在 `.swiftName` 下依次取解析器给的 Swift 拼写(可以带点号,`struct NSAttributedString.Key`)、名字表里的名字、ABI 名。不可信的条目因此从 `struct Key` 变成 `struct NSAttributedStringKey`。 6. **扩展头改走异步的类型打印路径**:只改扩展类型根在 `__C` / `__C_Synthesized` 的扩展,用打印器同一套解析与拼写印出名字,仍包成同一种 `TypeDeclaration`。其余扩展一个字节都不变。 7. **标注**:`SwiftDeclarationPrintConfiguration.marksCImportedTypeNames`(默认关)打开时,两种拼写不同的 C 导入类型的声明名外面包一个 `AnnotationRegion`,kind 里带着两个名字。文本不变,分离之后与不标注时逐字节相同。 @@ -288,7 +288,7 @@ extension AnnotationRegion.Kind { } ``` -kind 的编码是 `"cImportedTypeName" + "\u{1F}" + swiftName + "\u{1F}" + cName`。U+001F(unit separator)不会出现在 Swift 或 C 的标识符里,点号可以照常出现在 Swift 名里。解析只认这个前缀,并且要求恰好三段。 +kind 的编码是 `"cImportedTypeName|" + swiftName + "|" + cName`。`|` 不会出现在 Swift 或 C 的名字里,点号可以照常出现在 Swift 名里。解析只认这个前缀,并且要求恰好三段、两个名字都不为空。原先设计用 U+001F,实现时发现 swift-semantic-string 拒绝 kind 里的任何控制字符(它自己的标记就是控制字符,`AnnotationTag.validate`),改成了 `|`。 ### 名字表(模块内部) @@ -398,17 +398,20 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn ``` - 实现照复刻版 tag `27.2.0-alpha.2` 的源码:`lineIdentifier` 取 `dataSource.identifierForLine(_:)`;`SourceEditorLineAnnotation` 的动作用 `Action(message:displayStyle:…)` 放进 `actions`,`revealAction` 用同一个标题,右键菜单里就有这一项;`allowsMinimization: false`、`isDraggable: false`、不画滚动条标记。 -- **类别的图标与颜色不凭猜**:Xcode 的 note 类别在 IDESourceEditor 里,不在复刻范围。实现前读 `/Volumes/RE/Xcode/26.6/` 的导出确认 note 的外观;导出里没有,就停下来问,不要按名字推断(RuntimeViewer 的 `RuntimeViewerPrecompiledLibraries/SourceEditor/AGENTS.md`)。 +- **类别是我们自己的**:Xcode 的 issue 与 note 类别在 IDESourceEditor 里,不在复刻范围,所以外观是我们的取舍,不是复刻 Xcode:`identifier` 为 `RuntimeViewer.note`,图标 `info.circle.fill`,`annotationColor` 为 `.systemGray`,整行淡灰(`systemGray` 的 8%),不标范围、不进滚动条、不能拖动、不能最小化,`defaultViewState: .inline`。框架会怎么用这些值,读自复刻版 tag 上的源码:带标注的行按 `lineHighlightColor` 整行着色(`SourceEditorLineAnnotationManager.lineHighlightForLineIdentifier`),点横幅弹出聚合下拉框,标注那一行右侧为每个 `.inline` / `.dropdown` 动作画一个按钮、按钮文字是 `buttonMessage`(`SourceEditorLineAnnotationAggregatedDropdown`、`DropdownAnnotationView`),右键横幅的菜单只有 `revealAction`。 +- `setSource` 在换数据源之前 `removeAllLineAnnotations()`,与行内展开同一个理由:标注挂在旧数据源的行标识上。 +- 实现在 `SourceEditorBridge.swift` 末尾的一个扩展里:`sourceEditorView` 是 `private`,另起文件访问不到。 - 框架里缺的东西(比如横幅上的按钮)属于 `Mx-Iris/SourceEditor` 的改动,不在 bridge 里绕。 ### AppCore 与 App -- `ContentInterface` 加 `cImportedTypeNameNotes: [ContentCImportedTypeNameNote]`,每条是 UTF-16 范围、消息和动作标题,由 `ContentTextViewModel` 按当前拼写生成: +- `ContentInterface` 加 `cImportedTypeNameNotes: [ContentTextViewModel.CImportedTypeNameNote]`,每条是 UTF-16 范围、消息和动作标题,由 `ContentTextViewModel.cImportedTypeNameNotes(of:)` 按取接口时的拼写生成(`FetchedInterface` 带着 `cImportedTypeNames` 与 `cImportedTypeNameSpelling`): - `.swiftName`:`Imported from C as ` / `Show C Names`; - `.cName`:`Imported to Swift as ` / `Show Swift Names`。 文字放在 AppCore,因为它是「描述值」(RuntimeViewerPackages 的 `Sources/AGENTS.md`)。 -- `ContentTextViewModel.Input` 加 `cImportedTypeNameSpellingToggled: Signal`,在主线程把 `appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling` 换成另一个值。之后所有内容区都经 `appDefaults.$options` 重新取接口,不需要单独通知。 +- 内部标注开关照 `marksAttachedMacros` 的写法:`Settings.Editor.showsCImportedTypeNameNotes`(SourceEditor 可用即为真),`ContentTextViewModel` 取接口时与 `currentMergedGenerationOptions` 都合并进去。 +- `ContentTextViewModel.Input` 加 `cImportedTypeNameSpellingToggled: Signal`(`@Init(default: .empty())`,NSTextView 与 iOS 的调用点不用改),在主线程把 `appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling` 换成另一个值。之后所有内容区都经 `appDefaults.$options` 重新取接口,不需要单独通知。 - `ContentSourceEditorViewController`:每次 `setSource` 之后 `bridge.showLineAnnotations(...)`,identifier 用提示的序号;代理回调直接 `accept` 到 relay(不管是哪一条,都是同一个全局切换)。 - 面板:`.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], keyPath: \.swiftInterfaceOptions.cImportedTypeNameSpelling)`,放在「Resolve Imported Type Names」上面。 @@ -460,49 +463,39 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn ## 落地步骤 -0. **登记草案** —— 两边的提案索引 - - 行为:无(只有文档)。 -1. **名字表与可信规则** —— MSS 的 `CImportedTypeNameSpelling.swift`、配置两个属性、`CImportedTypeSwiftNameTable.swift`、打印器按需建表 - - 行为:`trustsUserFacingNameWhenABINameDiffers`(`AnyWeakAttribute` / `AGWeakAttribute`、`CGColor` / `CGColorRef`) - - 行为:`refusesLeafNameOfTypeImportedAsMember`(`Key` / `NSAttributedStringKey`) - - 行为:`refusesRelatedEntityName` - - 行为:`refusesNameWithoutABIName` - - 行为:`nameTableReadsAttributeGraphDescriptors`(读系统 shared cache 的 AttributeGraph:`AnyWeakAttribute`、`AnyAttribute` 的身份节点各对一条) -2. **打印规则** —— MSS 的 `printType`、`resolvedModuleName`、delegate 查询、声明头、扩展头与四个调用点、快照更新 - - 行为:`swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown`(`var _details: AnyWeakAttribute.__Unnamed_struct__details`、`extension AnyWeakAttribute: Swift.Hashable`) - - 行为:`swiftSpellingKeepsModuleThatResolverFinds`(测试替身解析器:`__C.CGRect` → `CoreFoundation.CGRect`,扩展头相同) - - 行为:`cSpellingPrintsMangledNamesAndAsksNoResolver`(声明 `struct AGWeakAttribute`、扩展 `extension __C.AGWeakAttribute`,替身解析器被调用 0 次) - - 行为:`untrustedDeclaredNamePrintsCName`(SwiftUICore 的 `NSAttributedStringKey` 声明行) +已完成的步骤标 ✅。测试名是实际写成的;MachOSwiftSection 的测试在 `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift`,用测试里现场编译的桥接头 fixture(`swift_name` 改名的结构体与 `swift_wrapper` typedef、匿名嵌套结构体、导入成成员的 `ProbeOwner.Key`),照 `CImportedTypeConformanceInterfaceTests` 的做法,不依赖系统镜像。 + +0. ✅ **登记草案** —— 两边的提案索引;提案随两个功能分支的第一个提交走。 +1. ✅ **名字表与可信规则** —— MSS 的 `CImportedTypeNameSpelling.swift`、配置两个属性、`CImportedTypeSwiftNameTable.swift`、打印器按需建表 + - 行为:`trustsUserFacingNameWhenABINameDiffers`(`AnyWeakAttribute` / `AGWeakAttribute`、`AnyAttribute` / `AGAttribute`、`CGColor` / `CGColorRef`、`__UIPointerShape` / `UIPointerShape`) + - 行为:`refusesLeafNameOfTypeImportedAsMember`(`Key` / `NSAttributedStringKey`、`Name` / `NSNotificationName`、`Decimal` / `NSDecimal`) + - 行为:`refusesRelatedEntityName`、`refusesNameWithoutABIName` + - 行为:`nameTableReadsTheFixturesDescriptors`(fixture 的 `AnyFooThing`、`AnyFooIdentifier` 各对一条,`Key` 与匿名结构体没有) +2. ✅ **打印规则** —— MSS 的 `printType`、`resolvedModuleName`、delegate 查询、声明头、扩展头与四个调用点 + - 行为:`swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown`(`var _details: AnyFooThing.__Unnamed_struct__details`、`extension AnyFooThing: … Swift.Equatable`,全文不出现 C 名) + - 行为:`untrustedDeclaredNamePrintsCName`(`struct ProbeOwnerKey`,没有 `struct Key`) + - 行为:`swiftSpellingKeepsModuleThatResolverFinds`(替身解析器:找到模块、没给 Swift 名时取描述符的名字 `ProbeModule.AnyFooThing`;给了 `ProbeOwner.Key` 时声明 `struct ProbeOwner.Key`、引用与扩展头 `ProbeModule.ProbeOwner.Key`) - 行为:`extensionHeaderSpellsLikeMemberTypes` - - 行为:`nonCImportedExtensionHeadersAreByteIdentical` - - 行为:`abiDiffKeysAreUnchanged`(现有 diff 测试照旧通过) -3. **标注与命令行** —— MSS 的 `AnnotationRegionKind+CImportedTypeName.swift`、声明头包区域、`InterfaceRequest` 与 `InterfaceCommand`、README 与插件 skill - - 行为:`markedDeclaredNameCarriesBothSpellings` - - 行为:`separatedMarkedPrintEqualsUnmarkedPrint` - - 行为:`regionKindRoundTripsDottedSwiftName`(`NSAttributedString.Key`) + - 行为:`cSpellingPrintsMangledNamesAndAsksNoResolver`(声明 `struct AGFooThing`、扩展 `extension __C.AGFooThing`,替身解析器被问 0 次) + - 原计划的 `nonCImportedExtensionHeadersAreByteIdentical` 与 `abiDiffKeysAreUnchanged` 不单独写:两者由 MachOSwiftSection 的全量测试覆盖(快照与 diff 测试照旧通过),见决策日志。 +3. ✅ **标注与命令行** —— MSS 的 `AnnotationRegionKind+CImportedTypeName.swift`、声明头包区域、`InterfaceRequest` 与 `InterfaceCommand`、README 与插件 skill(插件 `0.28.0`) + - 行为:`markedDeclaredNameCarriesBothSpellings`(分离后的文本与不标注时逐字节相同) + - 行为:`markedCSpellingCarriesTheSameNames` - 行为:`sameSpellingsAreNotMarked` - - 行为:`interfaceCommandParsesCNameSpelling` - - 推送 MSS 的功能分支,RuntimeViewer 临时按分支钉(照 `swift-type-indexing-package` 的 TEMPORARY 写法)。 -4. **RuntimeViewer Core** —— 两个选项、`RuntimeInterfaceCImportedTypeName`、接口字段、分离、`updateConfiguration` - - 行为:`spellingDefaultsToSwiftNameInOlderPayload` - - 行为:`marksCImportedTypeNamesIsNeverStoredTrue` - - 行为:`interfaceCarriesCImportedTypeNamesWhenMarked` - - 行为:`commentStructureIgnoresCImportedTypeNameRegions` - - 行为:`cNameSpellingRequestsNoTypeIndex` - - 行为:`changingSpellingClearsInterfaceCache` - - 行为:`corpusPrintsSwiftNamesWhateverTheSpelling` + - 行为:`regionKindRoundTripsDottedSwiftName` + - 行为:`interfaceCImportedTypeNameSpelling`(`SwiftSectionCommandTests`:默认 `swift-name`,`c-name` 映射到 `.cName`,拒绝 `cName` 这种拼法) + - MSS 功能分支已推送;RuntimeViewer 临时按分支钉(`RuntimeViewerCore/Package.swift` 的 TEMPORARY 注释)。 +4. ✅ **RuntimeViewer Core** —— 两个选项、`RuntimeInterfaceCImportedTypeName`、接口字段、分离、`updateConfiguration`、打印配置映射 + - 行为(`CImportedTypeNameSpellingEngineTests`,对系统的 AttributeGraph):`spellingDefaultsToSwiftNameInOlderPayload`、`spellingRawValuesAreStable`、`corpusPrintsSwiftNamesWhateverTheSpelling`、`swiftSpellingIsUniform`、`cSpellingIsUniform`、`interfaceCarriesCImportedTypeNamesWhenMarked`、`commentStructureIgnoresCImportedTypeNameRegions` + - 行为(`SwiftSectionPrinterConfigurationTests`):`changedSpellingReconfiguresOnce`(打印器只重配一次,接口缓存随之清掉) + - 原计划的 `cNameSpellingRequestsNoTypeIndex` 不写:测试进程不打开类型索引(`RuntimeTypeNames.enableInThisProcess()` 只在服务进程调用),无从观察,代码是 `updateConfiguration(for:)` 里一行条件。`marksCImportedTypeNamesIsNeverStoredTrue` 改由第 6 步的 `togglingFlipsStoredSpelling` 一并断言。 5. **Bridge 的行尾标注** —— `SourceEditorBridging.swift`、`SourceEditorBridge.swift`、`LineAnnotationTests.swift` - - 行为:`lineAnnotationSitsOnFirstLineOfItsRange` - - 行为:`setSourceRemovesLineAnnotations` - - 行为:`performingActionNotifiesDelegateWithIdentifier` - - 行为:`contextualMenuOffersTheSameAction` -6. **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 - - 行为:`notesNameCDeclarationUnderSwiftSpelling` - - 行为:`notesNameSwiftTypeUnderCSpelling` - - 行为:`togglingFlipsStoredSpelling` - - 行为:`mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` + - 行为:`lineAnnotationSitsOnFirstLineOfItsRange`、`showingAgainReplaces`、`setSourceRemovesLineAnnotations`、`performingActionNotifiesDelegateWithIdentifier`、`contextualMenuOffersTheSameAction` +6. **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`ViewModel.currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 + - 行为(`CImportedTypeNameNoteTests`):`notesNameCDeclarationUnderSwiftSpelling`、`notesNameSwiftTypeUnderCSpelling`、`noteRangeIsInUTF16`、`noNamesNoNotes`、`togglingFlipsStoredSpelling` + - 原计划的 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 不写:取决于 `SourceEditorFrameworks.availability`,包级测试里框架不在,写出来只是重复实现。 - 编完用 SourceEditor 打开 AttributeGraph 的 `AnyWeakAttribute`,人工看一次提示与切换(交给用户目视)。 -7. **收尾** —— RuntimeViewer 插件 skill 与版本、抬 MSS pin、重解析锁文件、两边索引与本提案状态 +7. **收尾** —— RuntimeViewer 插件 skill(版本 `1.4.0` 是类型索引功能抬的、还没发布,不再抬)、抬 MSS pin、重解析五个锁文件、两边索引与本提案状态 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -525,3 +518,9 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn | 2026-11-24 | Accepted | 用户批准,开始实现。 | | 2026-11-24 | 交互定为两次点击 | 用户确认按 Xcode 原生的两步做(横幅 → 下拉里的按钮,右键菜单也有),不改复刻版框架。 | | 2026-11-24 | 两边都从远端的 `feature/swift-type-indexing-package` 切 | 远端比两边本地 `next` 多了验收时的修复(宏的配色、文档);提案随功能分支的第一个提交走,因为两边本地 `next` 都有未推送的合并,不往 `next` 上单独提交提案。 | +| 2026-11-24 | In Progress | 第 1–4 步做完:MachOSwiftSection 的打印器、命令行与文档,RuntimeViewer Core。 | +| 2026-11-24 | kind 的分隔符改成 `\|` | 原设计的 U+001F 被 swift-semantic-string 拒绝:它不允许 kind 里出现任何控制字符(`AnnotationTag.validate`),它自己的标记就是控制字符。 | +| 2026-11-24 | C 名模式在标注时才问解析器 | C 名模式的声明名原先也去问解析器(为了标注里的 Swift 名),`cSpellingPrintsMangledNamesAndAsksNoResolver` 抓到了。改为只在 `marksCImportedTypeNames` 打开时问,打印的文字不受影响,RuntimeViewer 在 C 名模式下的提示仍能写出 SDK 给的 Swift 名。 | +| 2026-11-24 | MSS 测试用现场编译的 fixture | 原计划读系统 shared cache 的 AttributeGraph 与 SwiftUICore;改用 `CImportedTypeConformanceInterfaceTests` 那种测试里现场编译的桥接头 dylib,三种形状(顶层改名、`swift_wrapper` typedef 改名、导入成成员)都能精确构造,也不随系统版本变。RuntimeViewer Core 的引擎测试仍用系统的 AttributeGraph,那是报告的现场。 | +| 2026-11-24 | 两条行为测试并入全量与别的测试 | `nonCImportedExtensionHeadersAreByteIdentical`、`abiDiffKeysAreUnchanged` 由 MachOSwiftSection 全量测试覆盖;`marksCImportedTypeNamesIsNeverStoredTrue` 并入 `togglingFlipsStoredSpelling`;`cNameSpellingRequestsNoTypeIndex` 与 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 在测试进程里无从观察(类型索引只在服务进程打开,SourceEditor 框架只在 App 里),不写。 | +| 2026-11-24 | 行尾标注的外观是我们自己的类别 | Xcode 的 issue 与 note 类别在 IDESourceEditor 里,不在复刻范围;取灰色、`info.circle.fill`、整行 8% 的淡灰,交给用户目视验收时再调。 | From 71672f6ebde784441d69b4eeaaf21cc27a93c350 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 12:06:33 +0800 Subject: [PATCH 089/175] docs: the C-imported type name spelling is implemented, waiting for the user's look --- .../draft-c-imported-type-name-spelling.html | 30 ++++++++++++------- .../draft-c-imported-type-name-spelling.md | 8 +++-- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html index c51edfb0..a84b9dec 100644 --- a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html @@ -221,7 +221,7 @@

    MachOSwiftSection

  • .swiftName 下一个 __C 引用怎么印(按顺序取第一个成立的):解析器把模块解析出来了 → 照旧 模块.Swift拼写;名字表里有它 → 只写 Swift 名,不写模块(AnyWeakAttribute);都没有 → 照旧 __C.ABI名。嵌在 C 类型里的类型,父类型那一段按同样的规则印(AnyWeakAttribute.__Unnamed_struct__details)。
  • -
  • .cName:引用一律按 mangled 的样子印 __C.ABI名,不问任何解析器——模块也不解析,因为 UIKit.UICellConfigurationState 会和同名的 Swift 结构体混淆。
  • +
  • .cName:引用一律按 mangled 的样子印 __C.ABI名,打印时不问任何解析器——模块也不解析,因为 UIKit.UICellConfigurationState 会和同名的 Swift 结构体混淆。只有打开标注时,声明名会去问解析器要标注里的 Swift 名,打印的文字不变。
  • 声明行与引用走同一套规则:.cName 下是 ABI 名;.swiftName 下依次取解析器给的 Swift 拼写(可以带点号,struct NSAttributedString.Key)、名字表里的名字、ABI 名。不可信的条目因此从 struct Key 变成 struct NSAttributedStringKey。
  • 扩展头改走异步的类型打印路径:只改扩展类型根在 __C / __C_Synthesized 的扩展,仍包成同一种 TypeDeclaration。其余扩展一个字节都不变。
  • 标注:marksCImportedTypeNames(默认关)打开时,两种拼写不同的声明名外面包一个 AnnotationRegion,kind 里带着两个名字。文本不变,分离之后与不标注时逐字节相同。
  • @@ -388,7 +388,7 @@

    详细设计

    public static func cImportedTypeName(_ names: CImportedTypeNames) -> Self public var cImportedTypeNames: CImportedTypeNames? { get } }
    -

    kind 的编码是 "cImportedTypeName" + "\u{1F}" + swiftName + "\u{1F}" + cName;U+001F 不会出现在标识符里,Swift 名里可以照常带点号。

    +

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

    @@ -530,21 +530,21 @@

    API 演进与废弃策略

    落地步骤

      -
    1. 登记草案 —— 两边的提案索引。
    2. -
    3. 名字表与可信规则 —— trustsUserFacingNameWhenABINameDiffers、refusesLeafNameOfTypeImportedAsMember、refusesRelatedEntityName、refusesNameWithoutABIName、nameTableReadsAttributeGraphDescriptors。
    4. -
    5. 打印规则 —— swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown、swiftSpellingKeepsModuleThatResolverFinds、cSpellingPrintsMangledNamesAndAsksNoResolver、untrustedDeclaredNamePrintsCName、extensionHeaderSpellsLikeMemberTypes、nonCImportedExtensionHeadersAreByteIdentical、abiDiffKeysAreUnchanged。
    6. -
    7. 标注与命令行 —— markedDeclaredNameCarriesBothSpellings、separatedMarkedPrintEqualsUnmarkedPrint、regionKindRoundTripsDottedSwiftName、sameSpellingsAreNotMarked、interfaceCommandParsesCNameSpelling;推送 MSS 功能分支,RuntimeViewer 临时按分支钉。
    8. -
    9. RuntimeViewer Core —— spellingDefaultsToSwiftNameInOlderPayload、marksCImportedTypeNamesIsNeverStoredTrue、interfaceCarriesCImportedTypeNamesWhenMarked、commentStructureIgnoresCImportedTypeNameRegions、cNameSpellingRequestsNoTypeIndex、changingSpellingClearsInterfaceCache、corpusPrintsSwiftNamesWhateverTheSpelling。
    10. -
    11. Bridge 的行尾标注 —— lineAnnotationSitsOnFirstLineOfItsRange、setSourceRemovesLineAnnotations、performingActionNotifiesDelegateWithIdentifier、contextualMenuOffersTheSameAction。
    12. -
    13. AppCore 与 App —— notesNameCDeclarationUnderSwiftSpelling、notesNameSwiftTypeUnderCSpelling、togglingFlipsStoredSpelling、mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns;用 SourceEditor 打开 AnyWeakAttribute 的目视交给用户。
    14. -
    15. 收尾 —— 插件 skill 与版本、抬 MSS pin、重解析锁文件、两边索引与提案状态;判断配套实现说明与术语。
    16. +
    17. ✅ 登记草案 —— 两边的提案索引;提案随两个功能分支的第一个提交走。
    18. +
    19. ✅ 名字表与可信规则 —— trustsUserFacingNameWhenABINameDiffers、refusesLeafNameOfTypeImportedAsMember、refusesRelatedEntityName、refusesNameWithoutABIName、nameTableReadsTheFixturesDescriptors(测试里现场编译的桥接头 fixture)。
    20. +
    21. ✅ 打印规则 —— swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown、untrustedDeclaredNamePrintsCName、swiftSpellingKeepsModuleThatResolverFinds、extensionHeaderSpellsLikeMemberTypes、cSpellingPrintsMangledNamesAndAsksNoResolver;扩展头逐字节不变与 diff 的键由全量测试覆盖。
    22. +
    23. ✅ 标注与命令行 —— markedDeclaredNameCarriesBothSpellings、markedCSpellingCarriesTheSameNames、sameSpellingsAreNotMarked、regionKindRoundTripsDottedSwiftName、interfaceCImportedTypeNameSpelling;README 与插件 skill(0.28.0)。
    24. +
    25. ✅ RuntimeViewer Core —— 对系统 AttributeGraph 的引擎测试 7 条与 changedSpellingReconfiguresOnce;类型索引那条在测试进程里无从观察,不写。
    26. +
    27. ✅ Bridge 的行尾标注 —— lineAnnotationSitsOnFirstLineOfItsRange、showingAgainReplaces、setSourceRemovesLineAnnotations、performingActionNotifiesDelegateWithIdentifier、contextualMenuOffersTheSameAction。
    28. +
    29. ✅ AppCore 与 App —— notesNameCDeclarationUnderSwiftSpelling、notesNameSwiftTypeUnderCSpelling、noteRangeIsInUTF16、noNamesNoNotes、togglingFlipsStoredSpelling;界面目视交给用户。
    30. +
    31. ✅ 收尾的一部分 —— 五个锁文件钉到 MachOSwiftSection 功能分支的同一提交、命令行插件 skill;取号与 Implemented 留给正式收尾。

    决策日志

    - 12 条,最近一条:两边都从远端的类型索引功能分支切 + 20 条,最近一条:文档判断
    @@ -562,6 +562,14 @@

    决策日志

    + + + + + + + +
    2026-11-24Accepted用户批准,开始实现。
    2026-11-24交互定为两次点击用户确认按 Xcode 原生的两步做(横幅 → 下拉里的按钮,右键菜单也有),不改复刻版框架。
    2026-11-24两边都从远端的 feature/swift-type-indexing-package 切远端比两边本地 next 多了验收时的修复;提案随功能分支的第一个提交走。
    2026-11-24In Progress第 1–4 步做完。
    2026-11-24kind 的分隔符改成 |swift-semantic-string 不允许 kind 里出现控制字符。
    2026-11-24C 名模式在标注时才问解析器打印的文字不受影响,C 名模式下的提示仍能写出 SDK 给的 Swift 名。
    2026-11-24MSS 测试用现场编译的 fixture三种形状都能精确构造,不随系统版本变;RuntimeViewer 的引擎测试仍用系统的 AttributeGraph。
    2026-11-24两条行为测试并入全量与别的测试其余两条在测试进程里无从观察,不写。
    2026-11-24行尾标注的外观是我们自己的类别灰色、info.circle.fill、整行 8% 淡灰,交给用户目视验收时再调。
    2026-11-24实现完成,待用户看过后收尾相关测试全过;MSS 全量只有读不到本机没有的文件的 36 处,与基线同类;整个 App 编译通过;两个功能分支已在本地合进常驻 next,没推送。
    2026-11-24文档判断提案、MSS 的 README 与插件 skill、RV 的命令行插件 skill 已同步;其余不需要改。
    diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md index 53ea74ae..a6a1a7aa 100644 --- a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md @@ -489,13 +489,13 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn - 行为(`CImportedTypeNameSpellingEngineTests`,对系统的 AttributeGraph):`spellingDefaultsToSwiftNameInOlderPayload`、`spellingRawValuesAreStable`、`corpusPrintsSwiftNamesWhateverTheSpelling`、`swiftSpellingIsUniform`、`cSpellingIsUniform`、`interfaceCarriesCImportedTypeNamesWhenMarked`、`commentStructureIgnoresCImportedTypeNameRegions` - 行为(`SwiftSectionPrinterConfigurationTests`):`changedSpellingReconfiguresOnce`(打印器只重配一次,接口缓存随之清掉) - 原计划的 `cNameSpellingRequestsNoTypeIndex` 不写:测试进程不打开类型索引(`RuntimeTypeNames.enableInThisProcess()` 只在服务进程调用),无从观察,代码是 `updateConfiguration(for:)` 里一行条件。`marksCImportedTypeNamesIsNeverStoredTrue` 改由第 6 步的 `togglingFlipsStoredSpelling` 一并断言。 -5. **Bridge 的行尾标注** —— `SourceEditorBridging.swift`、`SourceEditorBridge.swift`、`LineAnnotationTests.swift` +5. ✅ **Bridge 的行尾标注** —— `SourceEditorBridging.swift`、`SourceEditorBridge.swift`、`LineAnnotationTests.swift` - 行为:`lineAnnotationSitsOnFirstLineOfItsRange`、`showingAgainReplaces`、`setSourceRemovesLineAnnotations`、`performingActionNotifiesDelegateWithIdentifier`、`contextualMenuOffersTheSameAction` -6. **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`ViewModel.currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 +6. ✅ **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`ViewModel.currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 - 行为(`CImportedTypeNameNoteTests`):`notesNameCDeclarationUnderSwiftSpelling`、`notesNameSwiftTypeUnderCSpelling`、`noteRangeIsInUTF16`、`noNamesNoNotes`、`togglingFlipsStoredSpelling` - 原计划的 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 不写:取决于 `SourceEditorFrameworks.availability`,包级测试里框架不在,写出来只是重复实现。 - 编完用 SourceEditor 打开 AttributeGraph 的 `AnyWeakAttribute`,人工看一次提示与切换(交给用户目视)。 -7. **收尾** —— RuntimeViewer 插件 skill(版本 `1.4.0` 是类型索引功能抬的、还没发布,不再抬)、抬 MSS pin、重解析五个锁文件、两边索引与本提案状态 +7. ✅(锁文件与插件 skill;取号与 Implemented 留给正式收尾)**收尾** —— RuntimeViewer 插件 skill(版本 `1.4.0` 是类型索引功能抬的、还没发布,不再抬)、抬 MSS pin、重解析五个锁文件、两边索引与本提案状态 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -524,3 +524,5 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn | 2026-11-24 | MSS 测试用现场编译的 fixture | 原计划读系统 shared cache 的 AttributeGraph 与 SwiftUICore;改用 `CImportedTypeConformanceInterfaceTests` 那种测试里现场编译的桥接头 dylib,三种形状(顶层改名、`swift_wrapper` typedef 改名、导入成成员)都能精确构造,也不随系统版本变。RuntimeViewer Core 的引擎测试仍用系统的 AttributeGraph,那是报告的现场。 | | 2026-11-24 | 两条行为测试并入全量与别的测试 | `nonCImportedExtensionHeadersAreByteIdentical`、`abiDiffKeysAreUnchanged` 由 MachOSwiftSection 全量测试覆盖;`marksCImportedTypeNamesIsNeverStoredTrue` 并入 `togglingFlipsStoredSpelling`;`cNameSpellingRequestsNoTypeIndex` 与 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 在测试进程里无从观察(类型索引只在服务进程打开,SourceEditor 框架只在 App 里),不写。 | | 2026-11-24 | 行尾标注的外观是我们自己的类别 | Xcode 的 issue 与 note 类别在 IDESourceEditor 里,不在复刻范围;取灰色、`info.circle.fill`、整行 8% 的淡灰,交给用户目视验收时再调。 | +| 2026-11-24 | 实现完成,待用户看过后收尾 | 验证(都在 Ultra):MachOSwiftSection 相关测试 43 条全过;全量 22 个目标中只有 `IntegrationTests` 报 36 处,全是读不到本机没有的文件(`Xcode-26.3.0.app`、iOS 18.5 模拟器运行时),与基线同类。RuntimeViewer Core 相关 55 条、AppCore 14 条全过;整个 App 经 Tuist 工作区编译通过;bridge 测试 78 条中 `LineAnnotation` 5 条全过,失败的是两条既有的滚动条测试,外加一条高负载下偶发的 `SymbolOccurrence`(单独重跑两次都过)。五个锁文件把 MachOSwiftSection 钉到 `feature/c-imported-type-name-spelling` 的同一提交。两个功能分支已在本地合进各自的常驻 `next`,没推送。 | +| 2026-11-24 | 文档判断 | 已同步:本提案、MachOSwiftSection 的 README 与 swift-section 插件 skill(插件 `0.28.0`)、RuntimeViewer 的命令行插件 skill。RuntimeViewer 的 `AGENTS.md` 与使用指南没有讲到这两个开关的地方,不需要改。配套实现说明与术语登记留给正式收尾时判断。 | From 60eed1db57bc9bf3f71515490cc25d6305fe99d2 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 16:29:50 +0800 Subject: [PATCH 090/175] docs: RuntimeViewer shows a C-imported type's other name in a clickable line-end tag The user turned down the line annotation, a banner that read like an issue and took two clicks. The proposal now describes the tag that replaced it: a capsule like a comment tag past the end of the declaration's line, which the bridge draws beside the text and switches the spelling on a click. --- .../draft-c-imported-type-name-spelling.html | 75 +++++----- .../draft-c-imported-type-name-spelling.md | 129 ++++++++++-------- 2 files changed, 113 insertions(+), 91 deletions(-) diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html index a84b9dec..78f3506a 100644 --- a/Documentations/Evolutions/draft-c-imported-type-name-spelling.html +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.html @@ -197,14 +197,14 @@

    摘要

  • .cName:一律按 mangled 的样子印(声明 struct AGWeakAttribute,引用 __C.AGWeakAttribute)。
  • 同时修掉扩展头不经类型名解析器的问题:SDK 类型的成员已经解析成 CoreFoundation.CGRect,扩展头却还是 __C.CGRect。

    -

    RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一条 Xcode 式的行尾标注(Imported from C as AGWeakAttribute),点开后用里面的按钮切换。

    +

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

    要你定

    -

    已定:两次点击

    -

    用户批准按 Xcode 原生的两步做:点横幅弹出下拉框,用里面的按钮切换;右键横幅的菜单里也有同一个动作。不改 Mx-Iris/SourceEditor。

    +

    已定:单击行尾标签

    +

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

    @@ -232,7 +232,7 @@

    RuntimeViewer

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

    @@ -273,10 +273,10 @@

    架构图

    GenerationOptions+ marksCImportedTypeNames (internal, stored false) RuntimeInterfaceCImportedTypeNamedeclared name's UTF-8 range + both names RuntimeObjectInterface+ cImportedTypeNames - SourceEditorBridgingLineAnnotationrange, message, action title, identifier - SourceEditorBridging + delegate+ showLineAnnotations(_:), + didPerformActionOfLineAnnotation - ContentInterface, ContentTextViewModel+ notes, + spelling toggle input - ContentSourceEditorViewControllerline annotations, toggle relay + SourceEditorBridgingLineEndTag, LineEndTagControllercapsule + text layer past the line's end; hover, click, pointing hand + SourceEditorBridging + delegate+ showLineEndTags(_:), + didClickLineEndTag + ContentInterface, ContentTextViewModel+ tags, + spelling toggle input + ContentSourceEditorViewControllerline-end tags, toggle relay GenerationOptionsViewController: Imported Type Names @@ -286,14 +286,14 @@

    架构图

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

    - - click "Show C Names" in the line annotation's dropdownSourceEditorLineAnnotation.Action (or the banner's contextual menu) - navigationDelegate.didPerformActionOfLineAnnotationContentSourceEditorViewController -> toggle relay + + click the tag "C name AGWeakAttribute"LineEndTagController, an event consumer of SourceEditorView, takes the click + navigationDelegate.didClickLineEndTagContentSourceEditorViewController -> toggle relay ContentTextViewModelappDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling = .cName appDefaults.$optionsevery content pane refetches service: RuntimeSwiftSection.updateConfigurationprinter prints with .cName and marks declared names; cache cleared separatingAnnotationRegions()RuntimeObjectInterface.cImportedTypeNames - setSource + showLineAnnotations"Imported to Swift as AnyWeakAttribute" [Show Swift Names] + setSource + showLineEndTagsstruct AGWeakAttribute { (Swift name AnyWeakAttribute) @@ -302,7 +302,7 @@

    架构图

    -

    点「Show C Names」之后:改的是全局生成选项,所有内容区经同一条重新取接口的路径刷新。

    +

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

    @@ -332,13 +332,15 @@

    改动地图

    RV · Interfaces/RuntimeInterfaceCImportedTypeName.swift新增声明名的范围与两个名字提示所需的数据4 RV · RuntimeObjectInterface.swift 及两处 +AnnotationRegions修改可选字段;分离时取出;注释结构忽略照宏展开的路4 RV · RuntimeSwiftSection.swift · updateConfiguration修改设标注开关;.cName 下不请求类型索引C 名用不到索引4 - RV · SourceEditorBridging.swift修改SourceEditorBridgingLineAnnotation、showLineAnnotations(_:)、代理回调bridge 接口5 - RV · SourceEditorBridge.swift(或新的 LineAnnotationController.swift)修改清掉旧标注、插入 SourceEditorLineAnnotation、动作回调代理接上框架的行尾标注5 - RV · RuntimeViewerSourceEditorBridgeTests/LineAnnotationTests.swift新增第 5 步的行为回归5 - RV · RuntimeViewerAppCore/Content/ContentInterface.swift修改提示的值(范围、消息、动作标题)AppCore 描述、App 只画6 + RV · SourceEditorBridging.swift修改SourceEditorBridgingLineEndTag、showLineEndTags(_:)、代理回调bridge 接口5 + RV · LineEndTagController.swift新增行尾画胶囊与文字层;悬停、工具提示、单击、手形光标画行尾标签、接点击5 + RV · SourceEditorBridge.swift修改注册控制器;换数据源前清掉标签;外观交给两个控制器接上控制器5 + RV · CommentDecorationController.swift · TagAppearance修改多存注释字体;按样式取字色;cgColor(_:in:) 模块内可见两种标签共用外观5 + RV · RuntimeViewerSourceEditorBridgeTests/LineEndTagTests.swift新增第 5 步的行为回归5 + RV · RuntimeViewerAppCore/Content/ContentInterface.swift修改标签的值(范围、标签名、另一个名字、工具提示)AppCore 描述、App 只画6 RV · RuntimeViewerAppCore/Content/ContentTextViewModel.swift修改合并标注开关;新输入翻转拼写切换即改全局选项6 RV · RuntimeViewerAppCore/Base/ViewModel.swift修改currentMergedGenerationOptions 同样合并缓存键对齐6 - RV · Content/ContentSourceEditorViewController.swift修改setSource 之后放标注;回调进 relay接上 ViewModel6 + RV · Content/ContentSourceEditorViewController.swift修改setSource 之后放标签;回调进 relay接上 ViewModel6 RV · Generation Options/GenerationOptionsViewController.swift修改Imported Type Names: Swift | C面板入口6 RV · Core 与 AppCore 测试新增第 4、6 步的行为回归4、6 RV · 命令行插件 skill 与清单修改补上描述符的 Swift 名与 C 名选项;1.4.0 已发布就抬到 1.4.1输出变了7 @@ -440,22 +442,24 @@

    详细设计

    // RuntimeObjectInterface public let cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]? -@objc(RuntimeViewerSourceEditorBridgingLineAnnotation) -public final class SourceEditorBridgingLineAnnotation: NSObject { +@objc(RuntimeViewerSourceEditorBridgingLineEndTag) +public final class SourceEditorBridgingLineEndTag: NSObject { public let characterRange: NSRange - public let message: String - public let actionTitle: String + public let label: String // "C name" + public let value: String // "AGWeakAttribute" + public let valueStyle: SourceEditorBridgingCommentRunStyle + public let toolTip: String? // "Show C Names" public let identifier: String } // SourceEditorBridging -func showLineAnnotations(_ annotations: [SourceEditorBridgingLineAnnotation]) +func showLineEndTags(_ tags: [SourceEditorBridgingLineEndTag]) // SourceEditorBridgingNavigationDelegate -func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAnnotationWithIdentifier identifier: String)
    +func sourceEditorBridge(_ bridge: SourceEditorBridging, didClickLineEndTagWithIdentifier identifier: String)
    • 线上兼容:旧版对端不认这两个选项,不带 cImportedTypeNames,内容区就没有提示;新版对端收到旧版请求时取默认值。
    • -
    • Bridge 实现照复刻版 tag 27.2.0-alpha.2 的源码:lineIdentifier 取 dataSource.identifierForLine(_:);动作进 actions,revealAction 用同一个标题;不可拖动、不可最小化、不画滚动条标记。
    • -
    • 类别的图标与颜色不凭猜:Xcode 的 note 类别在 IDESourceEditor 里、不在复刻范围,实现前读 /Volumes/RE/Xcode/26.6/ 的导出确认,没有就停下来问。
    • -
    • AppCore 按当前拼写生成文字:.swiftName 写 Imported from C as <cName> / Show C Names,.cName 写 Imported to Swift as <swiftName> / Show Swift Names;ViewModel 的新输入在主线程翻转 appDefaults.options 里的拼写。
    • +
    • LineEndTagController 是布局可视化、事件消费者(.high)与光标矩形提供者,在 bridge 的 init 里注册一次。每次布局取「选中整行时会画的矩形」里最后一行最右的那个,胶囊左边离它一个空格宽,高度与注释标签一样;胶囊是 CAShapeLayer、文字是 CATextLayer,都在 underlayLayer,外观用注释标签那一份(多存了注释字体)。
    • +
    • 左键按下(不带 ⌘、⌃)落在胶囊里就回调并吃掉这次点击与随后的抬起;移动时悬停的胶囊填充不透明度翻倍、内容视图的 toolTip 换成标签的提示(照 gutter 的做法);每个胶囊一个手形光标矩形。setSource 换数据源前清掉标签。
    • +
    • AppCore 按当前拼写生成值:.swiftName 是 C name + C 名、提示 Show C Names,.cName 是 Swift name + Swift 名、提示 Show Swift Names;ViewModel 的新输入在主线程翻转 appDefaults.options 里的拼写。
    @@ -464,7 +468,7 @@

    详细设计

    调研

    - 11 条查证过的事实 + 12 条查证过的事实
    1. 复现:swift-section 0.24.0 interface --show-c-imported-types 打 macOS 27.2 的 AttributeGraph,得到 struct AnyAttribute、struct AnyWeakAttribute { … var _details: __C.AGWeakAttribute.__Unnamed_struct__details } 与 struct WeakAttribute<A> { var base: __C.AGWeakAttribute }。
    2. @@ -478,6 +482,7 @@

      调研

    3. 命令行:InterfaceCommand.swift、InterfaceRequest.swift;插件 skill §8,清单 0.27.0。
    4. RuntimeViewer:生成选项在 appDefaults.options,内容区随它重取;面板有 .enumOption;注释结构与宏展开都是「标区域 → 分离 → 接口带可选字段」;bridge 是 Objective-C 协议,从未用过行尾标注;命令行插件 1.4.0 尚未发布。
    5. 复刻版 SourceEditor 的行尾标注(tag 27.2.0-alpha.2):insertLineAnnotation(_:) 等公开入口齐全;横幅本身不带按钮,点横幅弹下拉框(handleLeftMouseUpEvent),右键菜单只有 revealAction;交互代理没有「点了横幅」的回调。
    6. +
    7. 注释标签怎么画、能不能接点击(验收时查的):胶囊是 underlayLayer 里的 CAShapeLayer,位置取自 selectionRects,字是编辑器自己画的源码文字,所以离不开文本;SourceEditorView 把按下、抬起、移动、移出都先交给事件消费者,移动来自它自己的跟踪区域;光标矩形提供者在 I 形光标之后追加;gutter 悬停时改视图的 toolTip;positionFromInternalCharOffset、lineContentLengthForLine 都是公开的。
    @@ -486,13 +491,14 @@

    调研

    替代方案

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

    下游影响

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

    落地步骤

  • ✅ 打印规则 —— swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown、untrustedDeclaredNamePrintsCName、swiftSpellingKeepsModuleThatResolverFinds、extensionHeaderSpellsLikeMemberTypes、cSpellingPrintsMangledNamesAndAsksNoResolver;扩展头逐字节不变与 diff 的键由全量测试覆盖。
  • ✅ 标注与命令行 —— markedDeclaredNameCarriesBothSpellings、markedCSpellingCarriesTheSameNames、sameSpellingsAreNotMarked、regionKindRoundTripsDottedSwiftName、interfaceCImportedTypeNameSpelling;README 与插件 skill(0.28.0)。
  • ✅ RuntimeViewer Core —— 对系统 AttributeGraph 的引擎测试 7 条与 changedSpellingReconfiguresOnce;类型索引那条在测试进程里无从观察,不写。
  • -
  • ✅ Bridge 的行尾标注 —— lineAnnotationSitsOnFirstLineOfItsRange、showingAgainReplaces、setSourceRemovesLineAnnotations、performingActionNotifiesDelegateWithIdentifier、contextualMenuOffersTheSameAction。
  • -
  • ✅ AppCore 与 App —— notesNameCDeclarationUnderSwiftSpelling、notesNameSwiftTypeUnderCSpelling、noteRangeIsInUTF16、noNamesNoNotes、togglingFlipsStoredSpelling;界面目视交给用户。
  • +
  • ✅ Bridge 的行尾标签(最初做成行尾标注,验收时改掉) —— tagSitsPastTheEndOfTheLineItsRangeStartsOn、tagAddsNothingToTheText、showingAgainReplaces、setSourceRemovesTags、clickingNotifiesDelegateWithIdentifier、tagTakesThePointingHand、hoveringDarkensTagAndShowsToolTip。
  • +
  • ✅ AppCore 与 App —— tagHoldsCNameUnderSwiftSpelling、tagHoldsSwiftNameUnderCSpelling、tagRangeIsInUTF16、noNamesNoTags、togglingFlipsStoredSpelling;界面目视交给用户。
  • ✅ 收尾的一部分 —— 五个锁文件钉到 MachOSwiftSection 功能分支的同一提交、命令行插件 skill;取号与 Implemented 留给正式收尾。
  • @@ -544,7 +550,7 @@

    落地步骤

    决策日志

    - 20 条,最近一条:文档判断 + 21 条,最近一条:提示改成行尾标签
    @@ -570,6 +576,7 @@

    决策日志

    +
    2026-11-24行尾标注的外观是我们自己的类别灰色、info.circle.fill、整行 8% 淡灰,交给用户目视验收时再调。
    2026-11-24实现完成,待用户看过后收尾相关测试全过;MSS 全量只有读不到本机没有的文件的 36 处,与基线同类;整个 App 编译通过;两个功能分支已在本地合进常驻 next,没推送。
    2026-11-24文档判断提案、MSS 的 README 与插件 skill、RV 的命令行插件 skill 已同步;其余不需要改。
    2026-11-24提示改成行尾标签用户看过行尾标注后不要这种像报错的横幅,要标签。改为声明行末尾一个与注释标签同样的胶囊,单击即切换,悬停变深、手形指针、工具提示;由 bridge 自己画胶囊与文字层,接口文本、复制与查找都不变,打印器不动。标签写法与位置是我们定的,目视后可调。
    diff --git a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md index a6a1a7aa..14983b95 100644 --- a/Documentations/Evolutions/draft-c-imported-type-name-spelling.md +++ b/Documentations/Evolutions/draft-c-imported-type-name-spelling.md @@ -9,7 +9,7 @@ - **实现分支 / PR**: 两个仓库都是 `feature/c-imported-type-name-spelling`(worktree `.worktrees/MachOSwiftSection-CImportedTypeNameSpelling`、`.worktrees/RuntimeViewer-CImportedTypeNameSpelling`),叠在 `feature/swift-type-indexing-package` 上 - **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 - **网页版**: 同目录同名的 `.html` -- **涉及仓库**: MachOSwiftSection(本仓库,打印器与 `swift-section`)、RuntimeViewer(生成选项、内容区的行尾提示)。这是跨仓库的唯一提案,RuntimeViewer 的提案索引登记为 cross-repository draft +- **涉及仓库**: MachOSwiftSection(本仓库,打印器与 `swift-section`)、RuntimeViewer(生成选项、内容区的行尾标签)。这是跨仓库的唯一提案,RuntimeViewer 的提案索引登记为 cross-repository draft ## 摘要 @@ -22,7 +22,7 @@ Swift interface 里,从 C 导入、被改了名的类型(`NS_SWIFT_NAME`、t 同时修掉扩展头不经类型名解析器的问题:SDK 类型的成员已经解析成 `CoreFoundation.CGRect`,扩展头却还是 `__C.CGRect`。 -RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一条 Xcode 式的行尾标注(`Imported from C as AGWeakAttribute`),点开后用里面的按钮切换。 +RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一个注释标签样式的胶囊(`C name AGWeakAttribute`),单击就切换。胶囊画在文本旁边,不进接口文本。 ## 动机 @@ -84,6 +84,12 @@ extension __C.AGWeakAttribute: Swift.Equatable {} 11. **复刻版 SourceEditor 的行尾标注**(`Mx-Iris/SourceEditor` tag `27.2.0-alpha.2`,RuntimeViewer 钉的版本): - 公开入口 `SourceEditorView.insertLineAnnotation(_:)`、`removeAllLineAnnotations()`、`lineAnnotations`(`SourceEditor/macOS/SourceEditorView.swift:967-989`);`SourceEditorLineAnnotation.init(category:message:lineIdentifier:…:revealAction:…)`(`SourceEditor/Annotations/LineAnnotations/SourceEditorLineAnnotation.swift:134`);`SourceEditorLineAnnotationCategory`(同文件 `:7`);动作 `SourceEditorLineAnnotation.Action`(`SourceEditorLineAnnotationAction.swift`,`DisplayStyle` 有 `inline` / `lineItem` / `dropdown`)。 - **横幅本身不带按钮**:点横幅时 `SourceEditorLineAnnotationManager.handleLeftMouseUpEvent`(`SourceEditorLineAnnotationManager.swift:960-977`)弹出 Xcode 那种下拉框,动作按钮在下拉框里;右键横幅弹出的菜单里只有 `revealAction` 这一项(`SourceEditorLineAnnotationView.swift:788-800`)。`SourceEditorLineAnnotationInteractionDelegate`(`SourceEditorLineAnnotationDropdownPresentation.swift:39`)没有「点了横幅」的回调。所以「点一下就切换」要么走两步(点横幅、再点下拉里的按钮),要么用右键菜单,要么去改复刻版框架。 +12. **RuntimeViewer 的注释标签怎么画、能不能接点击**(验收时用户要求把行尾标注改成标签后查的): + - 注释标签(`Field offset 0x0` 那种胶囊)由 bridge 的 `CommentDecorationController` 画:胶囊是 `CAShapeLayer`,放在内容视图的 `underlayLayer` 里,位置取自「选中这几列时会画的矩形」(`SourceEditorContentView.selectionRects(for:coalesceInteriorRects:includeLineSpacing:)`),每次布局在 `LayoutVisualization.didLayoutInContentView` 里重摆;胶囊里的字是编辑器自己画的源码文字,只改了颜色。所以标签离不开文本里的一段注释,行尾没有文字可画。 + - 鼠标:复刻版 `SourceEditorView` 把按下、抬起、移动、移出都先交给事件消费者(`SourceEditorView+EventHandling.swift`),移动来自它自己的跟踪区域(`SourceEditorView.swift:285`,`mouseMoved`、`inVisibleRect`、窗口为 key 时);消费者返回 `true` 就不再进选区跟踪。折叠三角就是这样接的点击。 + - 指针:`addCursorRectOverrideProvider(_:)` 的提供者在编辑器的 I 形光标之后追加光标矩形(`SourceEditorView.resetCursorRects`)。 + - 工具提示:复刻版自己只在 gutter 用,做法是悬停时改视图的 `toolTip`(`SourceEditorGutter.swift:501`)。 + - 行信息:`SourceEditorDataSource.positionFromInternalCharOffset(_:lineHint:)`、`lineContentLengthForLine(_:)`、`lineCount` 都是公开的。 ## 提议方案 @@ -111,16 +117,16 @@ extension __C.AGWeakAttribute: Swift.Equatable {} 1. **生成选项**:`SwiftGenerationOptions.cImportedTypeNameSpelling`(`@Default(.swiftName)`,旧设置读出来是 Swift 名)。Generation Options 面板的 Swift 一组加一行 `Imported Type Names: Swift | C`。它与「Resolve Imported Type Names」各管各的:后者决定要不要用 SDK 解析模块,在 C 名模式下不起作用,也不再为它建类型索引。 2. **内部标注开关**:`GenerationOptions.marksCImportedTypeNames`,不出现在面板里,存下来的值永远是默认的 false。内容区只在 SourceEditor 可用时把它打开,`currentMergedGenerationOptions` 照同样的规则合并。 3. **接口带回名字**:`RuntimeObjectInterface.cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]?`,每条是声明名在文本里的 UTF-8 范围和两个名字。从分离出的标注区域里取,与宏展开在同一处;注释结构不认这种 kind。 -4. **行尾标注**:bridge 新增 `showLineAnnotations(_:)` 与一个代理回调。内容区每次 `setSource` 之后,给每个改了名的声明放一条: - - Swift 名模式:`Imported from C as AGWeakAttribute`,动作 `Show C Names`; - - C 名模式:`Imported to Swift as AnyWeakAttribute`,动作 `Show Swift Names`。 +4. **行尾标签**:bridge 新增 `showLineEndTags(_:)` 与一个代理回调。内容区每次 `setSource` 之后,给每个改了名的声明在行尾放一个标签,样子与注释标签一样(胶囊、标签字体与配色),写着文本没印的那个名字: + - Swift 名模式:`C name AGWeakAttribute`,提示 `Show C Names`; + - C 名模式:`Swift name AnyWeakAttribute`,提示 `Show Swift Names`。 - 点横幅弹出下拉框,用里面的按钮切换;右键横幅的菜单里也有同一个动作(`revealAction`)。切换就是翻转全局的生成选项,所有内容区一起重新取接口。 + 单击标签就切换:翻转全局的生成选项,所有内容区一起重新取接口。标签画在文本旁边,不进接口文本,复制、查找、导出都不受影响。 5. **其余出口跟着选项走**:MCP、App 充当 host 时的命令行、导出读的都是 `appDefaults.options`,与其他生成选项一样;独立运行的命令行 host 用默认的 Swift 名。Find 语料始终用 Swift 名打印。 -### 交互:两次点击 +### 交互:单击行尾标签 -用户选的样式里,按钮直接画在横幅上;复刻版框架的横幅没有按钮(前期调研 11)。用户批准按 Xcode 原生的两步做:点横幅弹出下拉框,用里面的按钮切换;右键横幅的菜单里也有同一个动作。不改 `Mx-Iris/SourceEditor`。 +最初按用户批准的 Xcode 原生两步做了行尾标注(点横幅弹下拉框,按钮在下拉框里)。用户看过之后不要这种像报错的横幅,改成标签:声明行末尾一个与注释标签同样的胶囊,单击即切换。悬停时胶囊变深、指针变成手形、显示工具提示(`Show C Names` / `Show Swift Names`)。注释标签离不开文本里的一段注释(前期调研 12),所以行尾标签由 bridge 自己画胶囊和文字,不往接口文本里加东西。不改 `Mx-Iris/SourceEditor`。 ### 非目标 @@ -129,7 +135,7 @@ extension __C.AGWeakAttribute: Swift.Equatable {} - **只在声明行放提示**:引用处(`var base: AnyWeakAttribute`)不放,一屏里可能有几十个引用,提示会太吵。 - **侧栏、路径栏、Find 结果里的对象名不跟着切换**:它们来自索引,不重新打印。Find 语料始终是 Swift 名,搜 C 名搜不到改了名的引用。 - **`dump`、`diff`、`snapshot` 的键不变**:ABI diff 按 mangled 身份对比(`Sources/Output/SwiftDiffing/Keying.swift`),只有 `diff --interface` 的渲染会跟着新的默认拼写变。 -- **NSTextView 显示路径与 iOS 版不放提示**:两处都没有行尾标注;iOS 版也没有生成选项界面,只能用默认的 Swift 名。 +- **NSTextView 显示路径与 iOS 版不放提示**:两处都没有行尾标签;iOS 版也没有生成选项界面,只能用默认的 Swift 名。 - **命令行工具不加对应参数**:它读 App 的生成选项,独立 host 用默认值。 ## 改动地图 @@ -157,13 +163,15 @@ extension __C.AGWeakAttribute: Swift.Equatable {} | RV · `…/Interfaces/RuntimeInterfaceCImportedTypeName.swift` | 新增 | 声明名的 UTF-8 范围与两个名字 | 接口带回提示所需的数据 | 4 | | RV · `…/Interfaces/RuntimeObjectInterface.swift`、`RuntimeObjectInterface+AnnotationRegions.swift`、`RuntimeInterfaceCommentStructure+AnnotationRegions.swift` | 修改 | 加可选字段 `cImportedTypeNames`;分离时取出;注释结构忽略这种 kind | 照宏展开的路 | 4 | | RV · `…/Sections/Swift/RuntimeSwiftSection.swift` · `updateConfiguration` | 修改 | 设 `marksCImportedTypeNames`;`.cName` 下不请求类型索引 | C 名用不到索引 | 4 | -| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridge/SourceEditorBridging.swift` | 修改 | `SourceEditorBridgingLineAnnotation`、`showLineAnnotations(_:)`、代理的 `sourceEditorBridge(_:didPerformActionOfLineAnnotationWithIdentifier:)` | bridge 接口 | 5 | -| RV · `…/RuntimeViewerSourceEditorBridge/SourceEditorBridge.swift`(或新的 `LineAnnotationController.swift`) | 修改 / 新增 | `setSource` 清掉旧标注;插入 `SourceEditorLineAnnotation`(类别、图标、颜色、动作、`revealAction`);动作回调代理 | 接上框架的行尾标注 | 5 | -| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridgeTests/LineAnnotationTests.swift` | 新增 | 第 5 步的行为 | 回归 | 5 | -| RV · `RuntimeViewerPackages/Sources/RuntimeViewerAppCore/Content/ContentInterface.swift` | 修改 | 加提示的值(UTF-16 范围、消息、动作标题),按当前拼写生成文字 | AppCore 描述、AppUI / App 只画 | 6 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridge/SourceEditorBridging.swift` | 修改 | `SourceEditorBridgingLineEndTag`、`showLineEndTags(_:)`、代理的 `sourceEditorBridge(_:didClickLineEndTagWithIdentifier:)` | bridge 接口 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/LineEndTagController.swift` · `LineEndTagController` | 新增 | 在行尾画胶囊与文字层;悬停变深、工具提示;单击回调;手形光标矩形 | 画行尾标签、接点击 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/SourceEditorBridge.swift` | 修改 | 注册控制器;`setSource` 换数据源前清掉标签;标签外观同时交给两个控制器 | 接上控制器 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/CommentDecorationController.swift` · `TagAppearance` | 修改 | 多存注释字体;按样式取字色的方法;`cgColor(_:in:)` 改成模块内可见 | 行尾标签与注释标签共用外观 | 5 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridgeTests/LineEndTagTests.swift` | 新增 | 第 5 步的行为(`CommentDecorationTests` 的 `CursorRectRecorder` 改成测试目标内可见) | 回归 | 5 | +| RV · `RuntimeViewerPackages/Sources/RuntimeViewerAppCore/Content/ContentInterface.swift` | 修改 | 加标签的值(UTF-16 范围、标签名、另一个名字、工具提示),按当前拼写生成文字 | AppCore 描述、AppUI / App 只画 | 6 | | RV · `…/RuntimeViewerAppCore/Content/ContentTextViewModel.swift` | 修改 | 合并 `marksCImportedTypeNames`;新输入 `cImportedTypeNameSpellingToggled`,翻转 `appDefaults.options` 里的拼写 | 切换即改全局选项 | 6 | | RV · `…/RuntimeViewerAppCore/Base/ViewModel.swift` · `currentMergedGenerationOptions` | 修改 | 同样合并 `marksCImportedTypeNames` | 缓存键与内容区对齐 | 6 | -| RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Content/ContentSourceEditorViewController.swift` | 修改 | `setSource` 之后 `showLineAnnotations`;代理回调进 relay | 接上 ViewModel | 6 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Content/ContentSourceEditorViewController.swift` | 修改 | `setSource` 之后 `showLineEndTags`;代理回调进 relay | 接上 ViewModel | 6 | | RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Generation Options/GenerationOptionsViewController.swift` | 修改 | `.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], …)` | 面板入口 | 6 | | RV · `RuntimeViewerCore/Tests/…`、`RuntimeViewerPackages/Tests/RuntimeViewerAppCoreTests/…` | 新增 | 第 4、6 步的行为 | 回归 | 4、6 | | RV · `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md`、两份插件清单 | 修改 | 「Imported types」一段补上描述符的 Swift 名与 C 名选项;`1.4.0` 已发布就抬到 `1.4.1`,没发布就留在 `1.4.0` | 输出变了 | 7 | @@ -196,13 +204,15 @@ RuntimeViewer + RuntimeInterfaceCImportedTypeName declared name's UTF-8 range + both names ~ RuntimeObjectInterface + cImportedTypeNames RuntimeViewerSourceEditorBridge/ -+ SourceEditorBridgingLineAnnotation -~ SourceEditorBridging + showLineAnnotations(_:) -~ SourceEditorBridgingNavigationDelegate + didPerformActionOfLineAnnotationWithIdentifier ++ SourceEditorBridgingLineEndTag ++ LineEndTagController capsule + text layer past the line's end; hover, click, pointing hand +~ SourceEditorBridging + showLineEndTags(_:) +~ SourceEditorBridgingNavigationDelegate + didClickLineEndTagWithIdentifier +~ CommentDecorationController.TagAppearance + commentFont, shared with the line-end tags RuntimeViewerAppCore/Content/ -~ ContentInterface, ContentTextViewModel + notes, + spelling toggle input +~ ContentInterface, ContentTextViewModel + tags, + spelling toggle input RuntimeViewerUsingAppKit/ -~ ContentSourceEditorViewController line annotations, toggle relay +~ ContentSourceEditorViewController line-end tags, toggle relay ~ GenerationOptionsViewController + "Imported Type Names: Swift | C" ``` @@ -221,12 +231,13 @@ declared name of a C-imported descriptor └─ .swiftName -> resolver's spelling ?? trusted name ?? ABI name ``` -**点「Show C Names」之后**: +**单击行尾标签之后**: ```text -click "Show C Names" in the line annotation's dropdown - -> SourceEditorBridge: SourceEditorLineAnnotation.Action - -> navigationDelegate.sourceEditorBridge(_:didPerformActionOfLineAnnotationWithIdentifier:) +click the tag "C name AGWeakAttribute" after `struct AnyWeakAttribute {` + -> SourceEditorView.mouseDown -> event consumers + -> LineEndTagController.handleMouseEvent consumes the click + -> navigationDelegate.sourceEditorBridge(_:didClickLineEndTagWithIdentifier:) -> ContentSourceEditorViewController: cImportedTypeNameSpellingToggledRelay -> ContentTextViewModel: appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling = .cName -> appDefaults.$options: every content pane refetches @@ -234,8 +245,8 @@ click "Show C Names" in the line annotation's dropdown -> RuntimeSwiftSection.updateConfiguration printer config changed: cache cleared -> SwiftDeclarationPrinter prints with .cName, marks declared names -> separatingAnnotationRegions() -> RuntimeObjectInterface.cImportedTypeNames - -> ContentSourceEditorViewController.setSource + showLineAnnotations - "Imported to Swift as AnyWeakAttribute" [Show Swift Names] + -> ContentSourceEditorViewController.setSource + showLineEndTags + struct AGWeakAttribute { (Swift name AnyWeakAttribute) ``` ## 详细设计 @@ -371,48 +382,50 @@ public let cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]? ### Bridge ```swift -/// A note at the end of a line, with one action — Xcode's issue annotation, used here for a -/// C-imported type's other name. A class, because `SourceEditorBridging` is an Objective-C protocol. -@objc(RuntimeViewerSourceEditorBridgingLineAnnotation) -public final class SourceEditorBridgingLineAnnotation: NSObject { - /// The UTF-16 range in the current source the note is about; it sits at the end of the - /// range's first line. +/// A tag a space past the end of a line that the reader can click, drawn as a comment tag is: a +/// capsule in a note's fill holding a label in a note's label colour and a value after it, in the +/// comment font. A class, because `SourceEditorBridging` is an Objective-C protocol. +@objc(RuntimeViewerSourceEditorBridgingLineEndTag) +public final class SourceEditorBridgingLineEndTag: NSObject { + /// A UTF-16 range into the current source; the tag sits after the end of the line its start lies on. public let characterRange: NSRange - public let message: String - /// The title of the action, in the dropdown the note opens and in its contextual menu. - public let actionTitle: String - /// Handed back when the action is performed. + public let label: String // "C name" + public let value: String // "AGWeakAttribute" + public let valueStyle: SourceEditorBridgingCommentRunStyle // .type + public let toolTip: String? // "Show C Names" public let identifier: String - public init(characterRange: NSRange, message: String, actionTitle: String, identifier: String) + public init(characterRange: NSRange, label: String, value: String, + valueStyle: SourceEditorBridgingCommentRunStyle, toolTip: String?, identifier: String) } // SourceEditorBridging -/// Replaces the line annotations shown on the current source. `setSource` removes them all, -/// so call this after it, with ranges of that source. -func showLineAnnotations(_ annotations: [SourceEditorBridgingLineAnnotation]) +/// Replaces the line-end tags shown on the current source. `setSource` removes them all, so call +/// this after it, with ranges of that source. Nothing is added to the text. +func showLineEndTags(_ tags: [SourceEditorBridgingLineEndTag]) // SourceEditorBridgingNavigationDelegate -/// The action of the line annotation shown under `identifier` was performed. -func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAnnotationWithIdentifier identifier: String) +/// The line-end tag shown under `identifier` was clicked. +func sourceEditorBridge(_ bridge: SourceEditorBridging, didClickLineEndTagWithIdentifier identifier: String) ``` -- 实现照复刻版 tag `27.2.0-alpha.2` 的源码:`lineIdentifier` 取 `dataSource.identifierForLine(_:)`;`SourceEditorLineAnnotation` 的动作用 `Action(message:displayStyle:…)` 放进 `actions`,`revealAction` 用同一个标题,右键菜单里就有这一项;`allowsMinimization: false`、`isDraggable: false`、不画滚动条标记。 -- **类别是我们自己的**:Xcode 的 issue 与 note 类别在 IDESourceEditor 里,不在复刻范围,所以外观是我们的取舍,不是复刻 Xcode:`identifier` 为 `RuntimeViewer.note`,图标 `info.circle.fill`,`annotationColor` 为 `.systemGray`,整行淡灰(`systemGray` 的 8%),不标范围、不进滚动条、不能拖动、不能最小化,`defaultViewState: .inline`。框架会怎么用这些值,读自复刻版 tag 上的源码:带标注的行按 `lineHighlightColor` 整行着色(`SourceEditorLineAnnotationManager.lineHighlightForLineIdentifier`),点横幅弹出聚合下拉框,标注那一行右侧为每个 `.inline` / `.dropdown` 动作画一个按钮、按钮文字是 `buttonMessage`(`SourceEditorLineAnnotationAggregatedDropdown`、`DropdownAnnotationView`),右键横幅的菜单只有 `revealAction`。 -- `setSource` 在换数据源之前 `removeAllLineAnnotations()`,与行内展开同一个理由:标注挂在旧数据源的行标识上。 -- 实现在 `SourceEditorBridge.swift` 末尾的一个扩展里:`sourceEditorView` 是 `private`,另起文件访问不到。 -- 框架里缺的东西(比如横幅上的按钮)属于 `Mx-Iris/SourceEditor` 的改动,不在 bridge 里绕。 +- `LineEndTagController` 是一个布局可视化(`LayoutVisualization`)、事件消费者(优先级 `.high`,与注释标签相同)和光标矩形提供者,在 bridge 的 `init` 里注册一次(前期调研 12)。 +- **画法**:每次布局(以及 `show` 时),对每个标签取「选中整行时会画的矩形」里最后一行最右的那个,胶囊左边离它一个空格宽,高度与注释标签一样(文字高减上下各 1 点,行被抬高时按注释字体的文字高)。胶囊是 `CAShapeLayer`,文字是 `CATextLayer`(CoreText 属性:注释字体,标签取 note 的标签色,名字取类型色),都放在 `underlayLayer`,外观用注释标签的那一份(`TagAppearance`,多存了注释字体)。被折叠进上一行的行不画。 +- **鼠标**:左键按下(不带 ⌘、⌃)落在胶囊里就回调、吃掉这次点击,连同之后的抬起;移动时更新悬停的标签:胶囊填充的不透明度翻倍,内容视图的 `toolTip` 换成标签的提示(照 gutter 的做法),移出时还原。 +- **指针**:每个胶囊上一个手形光标矩形;胶囊位置变了或滚动时让编辑器重算光标矩形(照注释标签的三角)。 +- `setSource` 在换数据源之前清掉标签:标签记的是旧文本的行号。 +- 不用复刻版的行尾标注(`SourceEditorLineAnnotation`):横幅像报错、动作要两步,用户看过后否掉了(决策日志)。 ### AppCore 与 App -- `ContentInterface` 加 `cImportedTypeNameNotes: [ContentTextViewModel.CImportedTypeNameNote]`,每条是 UTF-16 范围、消息和动作标题,由 `ContentTextViewModel.cImportedTypeNameNotes(of:)` 按取接口时的拼写生成(`FetchedInterface` 带着 `cImportedTypeNames` 与 `cImportedTypeNameSpelling`): - - `.swiftName`:`Imported from C as ` / `Show C Names`; - - `.cName`:`Imported to Swift as ` / `Show Swift Names`。 +- `ContentInterface` 加 `cImportedTypeNameTags: [ContentTextViewModel.CImportedTypeNameTag]`,每条是 UTF-16 范围、标签名、另一个名字和工具提示,由 `ContentTextViewModel.cImportedTypeNameTags(of:)` 按取接口时的拼写生成(`FetchedInterface` 带着 `cImportedTypeNames` 与 `cImportedTypeNameSpelling`): + - `.swiftName`:`C name` + ``,提示 `Show C Names`; + - `.cName`:`Swift name` + ``,提示 `Show Swift Names`。 文字放在 AppCore,因为它是「描述值」(RuntimeViewerPackages 的 `Sources/AGENTS.md`)。 -- 内部标注开关照 `marksAttachedMacros` 的写法:`Settings.Editor.showsCImportedTypeNameNotes`(SourceEditor 可用即为真),`ContentTextViewModel` 取接口时与 `currentMergedGenerationOptions` 都合并进去。 +- 内部标注开关照 `marksAttachedMacros` 的写法:`Settings.Editor.showsCImportedTypeNameTags`(SourceEditor 可用即为真),`ContentTextViewModel` 取接口时与 `currentMergedGenerationOptions` 都合并进去。 - `ContentTextViewModel.Input` 加 `cImportedTypeNameSpellingToggled: Signal`(`@Init(default: .empty())`,NSTextView 与 iOS 的调用点不用改),在主线程把 `appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling` 换成另一个值。之后所有内容区都经 `appDefaults.$options` 重新取接口,不需要单独通知。 -- `ContentSourceEditorViewController`:每次 `setSource` 之后 `bridge.showLineAnnotations(...)`,identifier 用提示的序号;代理回调直接 `accept` 到 relay(不管是哪一条,都是同一个全局切换)。 +- `ContentSourceEditorViewController`:每次 `setSource` 之后 `bridge.showLineEndTags(...)`(名字用 `.type` 的颜色),identifier 用标签的序号;代理回调直接 `accept` 到 relay(不管是哪一个,都是同一个全局切换)。 - 面板:`.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], keyPath: \.swiftInterfaceOptions.cImportedTypeNameSpelling)`,放在「Resolve Imported Type Names」上面。 ## 替代方案考量 @@ -420,7 +433,8 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn - **模块未知时写 `__C.AnyWeakAttribute`**:保留「C 导入、模块未知」的信号,但与声明行 `struct AnyWeakAttribute` 仍不一致,而且是打印器以前特意避开的半翻译写法(前期调研 5)。用户选了裸名。 - **按 C 名统一(声明行也印 `AGWeakAttribute`)作为默认**:与 mangled 一致,但读的是 Swift interface,Swift 名更贴合。C 名作为可切换的另一种拼写保留。 - **按前缀推断成员导入的父类型**(`NSAttributedStringKey` → `NSAttributedString.Key`):二进制里没有父路径(前期调研 3、4),按前缀切分会把 `NSDecimal` 切成 `NS.Decimal` 这种错误结果。`swift-type-indexing-package` 已经否定过只靠二进制推断改名。 -- **提示做成类型名后面的胶囊标签**:要打印器多输出一段注释,复制与导出会带上它,还要给标签加点击处理。用户选了行尾标注。 +- **提示做成打印器输出的一段注释,再按注释标签画**:标签的字要来自文本(前期调研 12),所以得让打印器多印一段注释,复制、查找与导出都会带上它,NSTextView 路径还会显示成普通注释。改由 bridge 在行尾自己画胶囊和文字,文本不变。 +- **复刻版的行尾标注**(最初的实现):横幅像报错,切换要先点横幅、再点下拉框里的按钮。用户看过后改成单击的行尾标签。 - **只切换当前编辑栏**:要在 ViewModel 里另存一份不进设置的状态,接口缓存键也要多一维;用户选了全局生成选项。 - **把拼写和 `resolvesImportedTypeNames` 合成一个三档枚举**:类型索引功能还在验收、设置项已经写好,合并就要改它的设置与测试;两个开关各管各的更简单,C 名模式下后者不起作用即可。 @@ -441,7 +455,7 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn - **本仓库**:`SwiftInterface`(`SwiftInterfaceBuilder` 用同一个打印器)、`SwiftDiffing` 的 `--interface` 渲染、`swift-section interface` 的默认输出跟着变;ABI diff 的键不变。 - **MachOKitUI、SymbolViewer**:经打印器显示 Swift interface,输出变化同上,不需要改代码。 - **RuntimeViewer**(本提案的另一半): - - **用户可见**:用 SourceEditor 显示时,改了名的 C 类型的声明行末尾多一条灰色的行尾标注;Generation Options 多一行 `Imported Type Names`;默认接口里这些类型统一成 Swift 名;MCP、App 充当 host 时的命令行与导出跟着选项;Find 结果始终是 Swift 名。 + - **用户可见**:用 SourceEditor 显示时,改了名的 C 类型的声明行末尾多一个注释标签样式的胶囊,写着另一个名字,单击即切换;Generation Options 多一行 `Imported Type Names`;默认接口里这些类型统一成 Swift 名;MCP、App 充当 host 时的命令行与导出跟着选项;Find 结果始终是 Swift 名。 - **可发现性**:提示默认就在(只要 SourceEditor 可用),面板里有同名开关;不加首次引导。 - **数据与配置兼容**:`appDefaults.options` 里没有这个键时取 `.swiftName`;`marksCImportedTypeNames` 存下来永远是 false。不需要迁移。 - **平台**:提示只在 macOS 的 SourceEditor 路径;NSTextView 路径与 iOS 版只有默认的 Swift 名。 @@ -489,12 +503,12 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn - 行为(`CImportedTypeNameSpellingEngineTests`,对系统的 AttributeGraph):`spellingDefaultsToSwiftNameInOlderPayload`、`spellingRawValuesAreStable`、`corpusPrintsSwiftNamesWhateverTheSpelling`、`swiftSpellingIsUniform`、`cSpellingIsUniform`、`interfaceCarriesCImportedTypeNamesWhenMarked`、`commentStructureIgnoresCImportedTypeNameRegions` - 行为(`SwiftSectionPrinterConfigurationTests`):`changedSpellingReconfiguresOnce`(打印器只重配一次,接口缓存随之清掉) - 原计划的 `cNameSpellingRequestsNoTypeIndex` 不写:测试进程不打开类型索引(`RuntimeTypeNames.enableInThisProcess()` 只在服务进程调用),无从观察,代码是 `updateConfiguration(for:)` 里一行条件。`marksCImportedTypeNamesIsNeverStoredTrue` 改由第 6 步的 `togglingFlipsStoredSpelling` 一并断言。 -5. ✅ **Bridge 的行尾标注** —— `SourceEditorBridging.swift`、`SourceEditorBridge.swift`、`LineAnnotationTests.swift` - - 行为:`lineAnnotationSitsOnFirstLineOfItsRange`、`showingAgainReplaces`、`setSourceRemovesLineAnnotations`、`performingActionNotifiesDelegateWithIdentifier`、`contextualMenuOffersTheSameAction` +5. ✅ **Bridge 的行尾标签** —— `SourceEditorBridging.swift`、`LineEndTagController.swift`、`SourceEditorBridge.swift`、`CommentDecorationController.swift`、`LineEndTagTests.swift`(最初做成行尾标注,验收时改掉,见决策日志) + - 行为:`tagSitsPastTheEndOfTheLineItsRangeStartsOn`、`tagAddsNothingToTheText`、`showingAgainReplaces`、`setSourceRemovesTags`、`clickingNotifiesDelegateWithIdentifier`、`tagTakesThePointingHand`、`hoveringDarkensTagAndShowsToolTip` 6. ✅ **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`ViewModel.currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 - - 行为(`CImportedTypeNameNoteTests`):`notesNameCDeclarationUnderSwiftSpelling`、`notesNameSwiftTypeUnderCSpelling`、`noteRangeIsInUTF16`、`noNamesNoNotes`、`togglingFlipsStoredSpelling` + - 行为(`CImportedTypeNameTagTests`):`tagHoldsCNameUnderSwiftSpelling`、`tagHoldsSwiftNameUnderCSpelling`、`tagRangeIsInUTF16`、`noNamesNoTags`、`togglingFlipsStoredSpelling` - 原计划的 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 不写:取决于 `SourceEditorFrameworks.availability`,包级测试里框架不在,写出来只是重复实现。 - - 编完用 SourceEditor 打开 AttributeGraph 的 `AnyWeakAttribute`,人工看一次提示与切换(交给用户目视)。 + - 编完用 SourceEditor 打开 AttributeGraph 的 `AnyWeakAttribute`,人工看一次标签与切换(交给用户目视)。 7. ✅(锁文件与插件 skill;取号与 Implemented 留给正式收尾)**收尾** —— RuntimeViewer 插件 skill(版本 `1.4.0` 是类型索引功能抬的、还没发布,不再抬)、抬 MSS pin、重解析五个锁文件、两边索引与本提案状态 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -526,3 +540,4 @@ func sourceEditorBridge(_ bridge: SourceEditorBridging, didPerformActionOfLineAn | 2026-11-24 | 行尾标注的外观是我们自己的类别 | Xcode 的 issue 与 note 类别在 IDESourceEditor 里,不在复刻范围;取灰色、`info.circle.fill`、整行 8% 的淡灰,交给用户目视验收时再调。 | | 2026-11-24 | 实现完成,待用户看过后收尾 | 验证(都在 Ultra):MachOSwiftSection 相关测试 43 条全过;全量 22 个目标中只有 `IntegrationTests` 报 36 处,全是读不到本机没有的文件(`Xcode-26.3.0.app`、iOS 18.5 模拟器运行时),与基线同类。RuntimeViewer Core 相关 55 条、AppCore 14 条全过;整个 App 经 Tuist 工作区编译通过;bridge 测试 78 条中 `LineAnnotation` 5 条全过,失败的是两条既有的滚动条测试,外加一条高负载下偶发的 `SymbolOccurrence`(单独重跑两次都过)。五个锁文件把 MachOSwiftSection 钉到 `feature/c-imported-type-name-spelling` 的同一提交。两个功能分支已在本地合进各自的常驻 `next`,没推送。 | | 2026-11-24 | 文档判断 | 已同步:本提案、MachOSwiftSection 的 README 与 swift-section 插件 skill(插件 `0.28.0`)、RuntimeViewer 的命令行插件 skill。RuntimeViewer 的 `AGENTS.md` 与使用指南没有讲到这两个开关的地方,不需要改。配套实现说明与术语登记留给正式收尾时判断。 | +| 2026-11-24 | 提示改成行尾标签 | 用户看过行尾标注后不要这种像报错的横幅,要标签。改为声明行末尾一个与注释标签同样的胶囊(`C name AGWeakAttribute` / `Swift name AnyWeakAttribute`),单击即切换,悬停变深、手形指针、工具提示。注释标签的字来自文本,行尾没有文字,所以由 bridge 自己画胶囊与文字层,接口文本、复制与查找都不变;打印器与 `marksCImportedTypeNames` 不动。标签写法(`C name`、放在行尾而不是紧跟类型名)是我们定的,用户目视后可调。 | From fd238c824e3419147a89170065fd73456fd02d7d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 17:57:08 +0800 Subject: [PATCH 091/175] build: take MachOObjCSection 0.8.209, swift-semantic-string 0.7.0 and swift-type-indexing 0.1.1 Puts back the version ranges the temporary feature-branch pins of proposal swift-type-indexing-package stood in for. 0.1.1 of swift-type-indexing closes each module interface it generates once read; with 0.1.0, --resolve-c-module-names grew SourceKitService to tens of GB. --- Package.swift | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/Package.swift b/Package.swift index 3b41d658..02eefa1a 100644 --- a/Package.swift +++ b/Package.swift @@ -105,7 +105,8 @@ var dependencies: [Package.Dependency] = [ // The SDK index `SwiftTypeNameResolution` resolves `__C` types with, moved // out of this package (proposal swift-type-indexing-package). Its sources // are all `#if os(macOS)`, so targets depend on it with a macOS-only - // condition. + // condition. 0.1.1 closes each module interface it generates once read: + // with 0.1.0, `--resolve-c-module-names` grew SourceKitService to tens of GB. .package( local: .package( path: "../swift-type-indexing", @@ -113,7 +114,7 @@ var dependencies: [Package.Dependency] = [ ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/swift-type-indexing", - from: "0.1.0", + from: "0.1.1", ), ), @@ -237,11 +238,9 @@ extension Package.Dependency { // package requires (proposal split-symbol-language). // 0.8.209 adds `ObjCTypeIndexing`, the bridge to swift-type-indexing // `SwiftTypeNameResolution` hands dependency images through - // (proposal swift-type-indexing-package). - // TEMPORARY: the feature branch until MachOObjCSection 0.8.209 is - // released; the proposal's wrap-up puts the range back: - // "0.8.209" ..< "0.9.0", - branch: "feature/swift-type-indexing-package", + // (proposal swift-type-indexing-package), and prints `NS_SWIFT_NAME` + // and `NS_REFINED_FOR_SWIFT` as macros. + "0.8.209" ..< "0.9.0", ), ) } @@ -280,11 +279,10 @@ extension Package.Dependency { url: "https://github.com/MxIris-Reverse-Engineering/swift-semantic-string", // 0.6.0 adds the annotation regions `marksCommentStructure` marks // every comment with; 0.5.0 added the definition regions - // `marksNestedDefinitions` wraps each nested definition in. - // TEMPORARY: the feature branch, for `SemanticType.macro` - // (proposal swift-type-indexing-package), until 0.7.0 is - // released; the proposal's wrap-up puts `from: "0.7.0"` here. - branch: "feature/swift-type-indexing-package", + // `marksNestedDefinitions` wraps each nested definition in. 0.7.0 + // adds `SemanticType.macro`, which MachOObjCSection 0.8.209 prints + // two macros with (proposal swift-type-indexing-package). + from: "0.7.0", ), ) From f7d62d0dd9f1a8211178e6ac3b5290b185686cba Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 24 Nov 2026 22:01:49 +0800 Subject: [PATCH 092/175] docs: land the swift-type-indexing package and the C-imported type name spelling proposals as 0105 and 0106 --- ... => 0105-swift-type-indexing-package.html} | 17 ++++++----- ...md => 0105-swift-type-indexing-package.md} | 11 +++++--- ...> 0106-c-imported-type-name-spelling.html} | 15 ++++++---- ... => 0106-c-imported-type-name-spelling.md} | 15 ++++++---- Documentations/Evolutions/README.md | 4 +-- Documentations/Glossary.md | 14 ++++++++++ .../Internal/ProjectEvolutionLog.md | 28 +++++++++++++++++++ Documentations/README.md | 4 ++- 8 files changed, 82 insertions(+), 26 deletions(-) rename Documentations/Evolutions/{draft-swift-type-indexing-package.html => 0105-swift-type-indexing-package.html} (97%) rename Documentations/Evolutions/{draft-swift-type-indexing-package.md => 0105-swift-type-indexing-package.md} (97%) rename Documentations/Evolutions/{draft-c-imported-type-name-spelling.html => 0106-c-imported-type-name-spelling.html} (96%) rename Documentations/Evolutions/{draft-c-imported-type-name-spelling.md => 0106-c-imported-type-name-spelling.md} (96%) diff --git a/Documentations/Evolutions/draft-swift-type-indexing-package.html b/Documentations/Evolutions/0105-swift-type-indexing-package.html similarity index 97% rename from Documentations/Evolutions/draft-swift-type-indexing-package.html rename to Documentations/Evolutions/0105-swift-type-indexing-package.html index c4c5b53b..e4a07c1e 100644 --- a/Documentations/Evolutions/draft-swift-type-indexing-package.html +++ b/Documentations/Evolutions/0105-swift-type-indexing-package.html @@ -4,7 +4,7 @@ -Draft - 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer +0105 - 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

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

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

    +
    + +
    +

    要你定

    +
    +

    两件事

    +
      +
    1. 开关做成独立的 --resolve-moved-type-modules(推荐:不需要 sourcekitd,几乎没有开销),还是并进现有的 --resolve-c-module-names?
    2. +
    3. 方案是否批准、可以开工?
    4. +
    +
    +
    +

    我自己定的(可以推翻)

    +
      +
    • 默认关闭:输出会随宿主机的 SDK 变化。
    • +
    • 按二进制的 LC_BUILD_VERSION sdk 判断,不看 minos。
    • +
    • dump、diff、snapshot、evolution 不改:dump 从不读 SDK,其余按 mangled 名比较。
    • +
    • TypeDatabaseTypeNameResolver 不变,RuntimeViewer 升级后输出不变,接入留给它自己。
    • +
    +
    +
    + +
    +

    架构图

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

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

    +

    一次查询的数据流:

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

    改动地图

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

    详细设计

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

    已知偏差

    +

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

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

    调研

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

    替代方案

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

    影响

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

    落地步骤

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

    决策日志

    +
    + 2 条,最近一条:方案取舍(待用户确认) +
    +
    + + + + + + +
    日期变更说明
    2026-11-25Created as Draft用户发现 CGFloat 在 SDK 里由 CoreFoundation 声明、二进制里却叫 CoreGraphics,问 swift-type-indexing 能否让输出与 SDK 一致;调研确认能做,用户要求写提案。
    2026-11-25方案取舍(待用户确认)独立开关、默认关闭;按二进制的 SDK 版本判断是否改写;dump 与 diff 类命令不改;RuntimeViewer 不随升级改变行为。
    +
    +
    +
    +
    + +
    +
    + + diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.md b/Documentations/Evolutions/draft-moved-swift-type-modules.md new file mode 100644 index 00000000..d36f52f0 --- /dev/null +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.md @@ -0,0 +1,404 @@ +# Draft - 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-25 +- **最后更新**: 2026-11-25 +- **所属愿景**: 无 +- **关联提案**: [0105 swift-type-indexing-package](0105-swift-type-indexing-package.md)(`TypeDatabase` 搬进独立包,本提案给它加一类数据);[0106 c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md)(`__C` 类型按 SDK 拼写,本提案把同样的思路推到原生 Swift 类型);[0082 image-group-evolution](0082-image-group-evolution.md)(evolution 把 SwiftUI 与 SwiftUICore 当一组比较,同样源于 `@_originallyDefinedIn`);[0064 module-selectors](0064-module-selectors.md)(`Module::Name` 写法) +- **实现分支 / PR**: 两个仓库都是 `feature/moved-swift-type-modules`(worktree `.worktrees/MachOSwiftSection-MovedSwiftTypeModules`、swift-type-indexing 的 `.worktrees/swift-type-indexing-MovedSwiftTypeModules`) +- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 +- **网页版**: 同目录同名的 `.html` +- **涉及仓库**: swift-type-indexing(从 SDK 读出搬家记录、提供查询)、MachOSwiftSection(本仓库:打印器、`SwiftTypeNameResolution` 适配层、`SwiftSectionKit` 请求、`swift-section interface` 开关)。这是跨仓库的唯一提案,swift-type-indexing 的提案索引在实现时登记为 cross-repository draft + +## 摘要 + +Apple 把一些 Swift 类型从一个模块搬进另一个模块时,会给声明加上 `@_originallyDefinedIn(module: "旧模块", 平台 版本)`。这个属性让 mangled name 和运行时元数据继续使用旧模块名,老二进制不用重编,所以二进制里只能读到旧名字:`CGFloat` 现在由 CoreFoundation 声明,mangling 却还是 `$s12CoreGraphics7CGFloatV`;macOS 15 起 SwiftUI 的约 370 个类型搬进了 SwiftUICore,mangling 还是 `7SwiftUI`。`swift-section interface` 因此印出 `CoreGraphics.CGFloat`、`SwiftUI.View`,而 SDK 的 `.swiftinterface` 写的是 `CoreFoundation::CGFloat`(CoreGraphics 的接口)、`SwiftUICore.View`(SwiftUI 的接口,2182 处)。 + +本提案做两件事: + +- **swift-type-indexing** 在 `TypeDatabase` 第一次 `index` 时顺带扫描 SDK 里所有模块的文本 `.swiftinterface`,把每个顶层类型声明上的 `@_originallyDefinedIn` 记成「旧模块 + 类型名 → 现在声明它的模块,以及各平台的搬家版本」。新增一个查询 `declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)`。扫描只读文本,不用 sourcekitd。 +- **MachOSwiftSection** 的打印器多一个解析器角色 `MovedTypeModuleResolving`。注册了它,原生 Swift 类型的模块名就先问它(`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`,嵌套类型跟随最外层类型)。`swift-section interface` 新增开关 `--resolve-moved-type-modules`,默认关闭。 + +是否改写按二进制自己的 SDK 版本判断(`LC_BUILD_VERSION` 的 `sdk`):用 macOS 14 SDK 编出的 SwiftUI 镜像,`View` 那时还在 SwiftUI 里,照旧印 `SwiftUI.View`。 + +## 动机 + +**现象**(本机 macOS 27.2,Xcode 27.2 的 MacOSX27.2 SDK): + +- SDK 的 `usr/lib/swift/CoreFoundation.swiftmodule/arm64e-apple-macos.swiftinterface` 第 10–16 行: + + ```swift + @available(macOS 10.0, macCatalyst 13.0, iOS 2.0, watchOS 1.0, tvOS 9.0, *) + @_originallyDefinedIn(module: "CoreGraphics", macOS 10.0) + @_originallyDefinedIn(module: "CoreGraphics", macCatalyst 13.0) + @_originallyDefinedIn(module: "CoreGraphics", iOS 2.0) + @_originallyDefinedIn(module: "CoreGraphics", watchOS 1.0) + @_originallyDefinedIn(module: "CoreGraphics", tvOS 9.0) + @frozen public struct CGFloat : Swift::Sendable { + ``` + + CoreGraphics 自己的接口里引用它时写的是 `CoreFoundation::CGFloat`(例如 `public func CGContextMoveToPoint(_ c: CoreGraphics::CGContext?, _ x: CoreFoundation::CGFloat, _ y: CoreFoundation::CGFloat)`)。 +- 二进制里:运行时 `libswiftCoreFoundation.dylib` 导出 `_$s12CoreGraphics7CGFloatVMn`(类型描述符)与 `_$s12CoreGraphics7CGFloatVN`(类型元数据),模块名仍是 CoreGraphics。 +- 因此任何引用 `CGFloat` 的二进制,`swift-section interface` 都印 `CoreGraphics.CGFloat`;SwiftUI 相关的二进制满屏是 `SwiftUI.View`、`SwiftUI.Text`,而 SDK 和 Xcode 的生成接口写的是 SwiftUICore。 + +用户在对照 SDK 阅读输出时会困惑「这个类型到底声明在哪」。现在的输出能编译过(见前期调研 6),所以问题出在跟 SDK 不一致:它照实反映了 ABI,却和源码对不上。已有的 `--resolve-c-module-names` 只处理 `__C` 类型(前期调研 3),管不到这类原生 Swift 类型。 + +**范围不只 CGFloat**(前期调研 5):macOS 27.2 SDK 里带 `@_originallyDefinedIn` 的模块有 SwiftUICore(旧模块 SwiftUI,约 370 个类型)、RealityFoundation(RealityKit)、CoreFoundation(CoreGraphics)、AVFAudio(AVFoundation)、RelevanceKit(AppIntents)、DeveloperToolsSupport 与 CoreTransferable(SwiftUI)、Foundation(`_System_Foundation`)等。一张表就能把它们全部修好。 + +## 前期调研 + +1. **编译器怎么用这个属性**(`/Volumes/SwiftProjects/swift-project/swift`): + - `include/swift/AST/Attr.h:2486` 的 `OriginallyDefinedInAttr` 存两个模块名:`ManglingModuleName`(mangling 用)与 `LinkerModuleName`(链接指令用)。源码里写成 `"Swift;CompatibilitySpan"` 时,分号前是 mangling 用的模块,分号后是链接用的库。 + - `lib/AST/Decl.cpp:1155` 的 `Decl::getAlternateModuleName()`:声明自己带有在当前平台生效的属性就用它的 `ManglingModuleName`,否则沿 `DeclContext` 往上找,所以**嵌套类型跟随外层类型的旧模块名**。`lib/AST/ASTMangler.cpp:205/970/2642/4484` 都经它取模块名。 + - 生效与否只看平台、**不看版本**:`lib/AST/Attr.cpp:2561` 的 `isActivePlatform` 只调 `isPlatformActive`。所以同一平台上,任何部署目标编出的 mangling 都用旧模块名;版本只影响链接指令(`$ld$previous`)。 + - 平台继承(`lib/AST/PlatformKindUtils.cpp:131`):`iOS` 条目在 Mac Catalyst(`ios-macabi` 三元组也是 iOS)和 visionOS(编译期)上同样生效;`macCatalyst` 条目只对 Catalyst 生效。 +2. **SDK 里的搬家记录**: + - `$ld$previous` 记录了运行时位置的变化:`libswiftCoreFoundation.tbd` 有 `$ld$previous$/usr/lib/swift/libswiftCoreGraphics.dylib$$1$10.15$13.0$_$s12CoreGraphics7CGFloatVMn$`,即部署目标在 macOS 10.15–13.0 之间时,这个符号链接到 `libswiftCoreGraphics.dylib`;Catalyst 是 13.0–16.0。现在的 `libswiftCoreGraphics.tbd` 只重新导出 CoreGraphics.framework。**属性写的是 macOS 10.0,运行时真正搬家是 macOS 13**:属性的版本不一定等于源码搬家的时间,见「已知偏差」。 + - SwiftUICore 的版本分布(`grep -o '^@_originallyDefinedIn(module: "SwiftUI", …)'`):macOS 15.0 共 1442 行,另有 15.2、26.0、27.0 等批次。**同一模块里不同声明的搬家版本不同**,表里必须逐个声明存版本。 + - `@_originallyDefinedIn` 只出现在顶层声明上,并且总是单独占一行、从第 0 列开始。SwiftUICore 里跟在它后面的声明:266 个 struct、23 个 class、33 个 enum、40 个 protocol、5 个 typealias,另有 994 个 extension、17 个 func、185 个 var、16 个 let。 +3. **现状代码怎么走**: + - 打印器只在模块名是 `__C` / `__ObjC` 时才去问解析器:`Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift:186` 的 `resolvedModuleName(of:siblingIdentifier:)`。它是全部模块名输出的唯一出口,有三个调用点:`NodePrintable.swift:176`(`printModule`)、`TypeNodePrintable.swift:197`(顶层类型的限定名,`siblingIdentifier` 是该顶层类型的标识符)、`TypeNodePrintable.swift:310`(`printModuleSelector(ofNestedType:)`,嵌套类型自己的模块选择器,`siblingIdentifier` 是嵌套类型自己的标识符)。 + - 嵌套类型的模块选择器取自 `TypeNodePrintable.swift:635` 的 `declaringModuleForModuleSelector`:沿上下文链找到根上的 `module` 节点,或最近一层 `extension` 的模块。 + - 解析器角色协议在 `Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift`(`ModuleNameResolving`、`CImportedNameResolving`、`OpaqueTypeResolving`,刻意不给默认实现);注册在 `SwiftDeclarationPrinter.swift:240` 的 `addTypeNameResolver(_:)`,按角色分发在 `SwiftDeclarationPrinter.swift:1296` 起的 `NodePrintableDelegate` 实现里。 + - 适配层:`Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift`(无状态,包一个 `TypeDatabase`)与 `SwiftInterfaceBuilderTypeNameProvider.swift`(extra-data provider,`init?` 从 `machO.loadCommands.buildVersionCommand` 取平台,`setup()` 按依赖过滤索引)。 + - `SwiftSectionKit` 的 `InterfaceRequest`(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:224`)只在 `cModuleNameResolution == .enabled` 时挂上 provider;`dump`、`diff`、`snapshot`、`evolution` 都不挂任何类型名解析器。 + - interface 头部的 `import` 行来自符号里出现的 mangling 模块名(`SwiftInterfaceBuilder.swift:357` 的 `collectModules()`),本提案不改它。 +4. **swift-type-indexing 的现状**(`../swift-type-indexing`,0.1.1):`TypeDatabase` 只回答 `__C` 类型的归属(`moduleName(forTypeName:)`)与 C 名 → Swift 名(`swiftName(forCName:category:)`)。模块接口一层经 sourcekitd `editor.open.interface` 生成,`InterfaceDeclarationNode` 只留种类、名字与嵌套,不留属性;`Documentations/Internal/TypeIndexingPipeline.md` 明确说不读文本 `.swiftinterface`,因为它只含 Swift 声明,而那一层要的是 ObjC 导入类型。本提案要的恰好是 Swift 声明。`SDKIndexer.discover` 已经列出每个 `.swiftmodule` 目录(`SwiftModuleDescriptor.path`)。第一次 `index` 在 `discoverSDK()` 里登记 API notes;只要 ObjC 标注的调用方用一个不选任何模块的 `moduleFilter` 调一次 `index`,这个用法已有先例。 +5. **成本**:macOS 27.2 SDK 有 368 个 `.swiftmodule`,`arm64e-apple-macos.swiftinterface` 共 266 份(另有 `arm64e.x1-apple-macos` 12 份、`x86_64` 与 `ios-macabi` 各一套)。`grep -A12 '^@_originallyDefinedIn'` 扫完全部 macOS 份用时 0.38 秒。Swift 逐行解析会慢一些,落地时实测并记入本节。 +6. **现在的输出能编过**:SE-0491(模块选择器)第 421 行规定 `Module::Name` 的候选包括「声明在该模块或被该模块重新导出的」声明;点号限定的写法同样会查到重新导出的声明。CoreGraphics 的接口头部有 `@_exported public import CoreFoundation`,SwiftUI 的接口第 19 行有 `@_exported import SwiftUICore`,所以 `CoreGraphics.CGFloat`、`SwiftUI.View` 都合法。本提案改的只是写法与 SDK 是否一致,不是正确性。 +7. **使用方**:RuntimeViewer 按平台共用一个 `TypeDatabase`,经 `TypeDatabaseTypeNameResolver(typeDatabase:)` 注册(`RuntimeViewerCore/Sources/RuntimeViewerCore/TypeNames/RuntimeTypeIndex.swift:145`)。本提案不改这个类型的行为,RuntimeViewer 的输出不会因为升级而悄悄改变。 + +## 提议方案 + +### swift-type-indexing + +1. 新增内部类型 `MovedTypeIndex`:输入一份 `.swiftinterface` 的文本和它所属的模块名,逐行扫描第 0 列的属性组。遇到 `@_originallyDefinedIn(module: "<名>", <平台> <版本>)` 就收集;属性组之后的第一行声明是 `struct` / `class` / `enum` / `protocol` / `actor` / `typealias`(前面可以有 `public`、`final`、`@frozen` 之类的修饰)时,记一条 `MovedTypeDeclaration`(类型名、mangling 旧模块、按平台的搬家版本)。是 extension、func、var 之类的就丢掉这组属性。模块名有分号时取分号前的部分;取出来等于本模块(例如 `Swift;CompatibilitySpan` 在 Swift 模块里)就不记。 +2. `TypeDatabase.discoverSDK()` 在登记 API notes 之后,对发现的每个模块挑一份与平台匹配的文本接口(选法见详细设计)交给 `MovedTypeIndex`,结果并进一张 `[MovedTypeKey: MovedTypeDeclaration]` 表,键是「旧模块 + 类型名」。同一个键在两个模块里都出现时,按发现顺序先到先得,并记一条日志。 +3. 新增公开查询: + + ```swift + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String, builtAgainst sdkVersion: OperatingSystemVersion) -> String? + ``` + + 当 SDK 把 `originalModuleName.typeName` 搬进了另一个模块、并且搬家版本不晚于 `sdkVersion`(数据库自身平台的版本)时,返回现在声明它的模块,否则返回 `nil`。 + +### MachOSwiftSection + +4. `SwiftPrinting` 新增角色协议 `MovedTypeModuleResolving`。`resolvedModuleName(of:siblingIdentifier:)` 在模块不是 `__C` / `__ObjC`、标识符不为空时问它;问到就印新模块,`isResolvedCImportedModule` 仍是 `false`,不触发 C 名改写。 +5. 嵌套类型的模块选择器(`printModuleSelector(ofNestedType:)`)改为按「它所在的顶层声明」查:模块节点来自上下文链的根时,键用最外层类型的标识符,`SwiftUI::Text.SwiftUI::Storage` 就整体变成 `SwiftUICore::Text.SwiftUICore::Storage`;来自某个 `extension` 时不查(非目标)。 +6. `SwiftTypeNameResolution` 新增 `TypeDatabaseMovedTypeModuleResolver`(`typeDatabase` + `sdkVersion`)。`SwiftInterfaceBuilderTypeNameProvider` 增加一个 `resolutions` 参数(选项集合:`.cImportedModules`、`.movedTypeModules`,默认只有前者,与现在一致);它从 `LC_BUILD_VERSION` 取 `sdk` 版本,开了 `.movedTypeModules` 就同时遵循新角色。只开 `.movedTypeModules` 时,`setup()` 用不选任何模块的 `moduleFilter` 调一次 `index`:不生成任何模块接口,不需要 sourcekitd。 +7. `InterfaceRequest` 新增 `resolvesMovedTypeModules: Bool = false`;`swift-section interface` 新增 `--resolve-moved-type-modules`。两个开关可以同时开,共用一个 provider 和一个数据库。 + +### 非目标 + +- **`dump`**:`dump` 按 mangled 身份打印,从不读 SDK,`__C` 类型在 dump 里也不解析(0106 前期调研 1)。搬家记录来自 SDK 而不是二进制,同样不进 dump。 +- **`diff`、`snapshot`、`evolution` 与一切查找键**:它们按 mangled 名比较,必须保持旧模块名。0082 已经用 image 分组处理了 SwiftUI → SwiftUICore 的搬家。 +- **interface 头部的 `import` 行**:旧模块总会重新导出新模块(例如 CoreGraphics 重新导出 CoreFoundation),`import CoreGraphics` 足以让 `CoreFoundation.CGFloat` 编过,不补 `import CoreFoundation`。 +- **声明在搬过家的 extension 里的嵌套类型**:SwiftUICore 有 994 个带 `@_originallyDefinedIn` 的 extension,声明在其中的嵌套类型,它自己的模块选择器仍印旧模块。这种情况很少,而且照样能编过。 +- **函数、全局变量与 extension 成员的搬家**:interface 引用它们时不带模块名。 +- **默认开启**:输出会随宿主机的 SDK 变化,同一份二进制在两台机器上印得不一样,渲染 A/B 与快照测试也会跟着漂移。 +- **RuntimeViewer 接入**:留给 RuntimeViewer 自己的后续改动,它要为每个镜像传入正确的 SDK 版本。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| swift-type-indexing `Sources/TypeIndexing/MovedTypeIndex.swift` · `MovedTypeIndex`、`MovedTypeDeclaration`、`MovedTypeKey` | 新增 | 文本扫描器(纯函数)与表的键值类型 | 搬家记录只在文本接口里 | 1 | +| swift-type-indexing `Sources/TypeIndexing/SDKPlatform.swift` · `SDKPlatform` | 修改 | 新增内部属性:本平台文本接口的文件名后缀(`-apple-macos`、`-apple-ios-macabi`、`-apple-ios-simulator`…),以及取哪个平台的搬家版本(含 Catalyst / visionOS 回退到 iOS) | 挑文件、选版本都要按平台来 | 1 | +| swift-type-indexing `Sources/TypeIndexing/TypeDatabase.swift` · `TypeDatabase` | 修改 | `discoverSDK()` 扫描并登记搬家表;新增 `declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)`;内部的 `register(movedTypeDeclarations:)` 供测试直接驱动 | 对外的唯一入口 | 2 | +| swift-type-indexing `Tests/TypeIndexingTests/MovedTypeIndexTests.swift` | 新增 | 扫描器的单元测试(手写的接口文本) | 解析规则可脱离 SDK 验证 | 1 | +| swift-type-indexing `Tests/TypeIndexingTests/TypeDatabaseMovedTypeTests.swift` | 新增 | 版本判断与平台回退 | 查询语义 | 2 | +| swift-type-indexing `Tests/TypeIndexingTests/SDKIntegrationTests.swift` | 修改 | 加 `CGFloat` 与 `SwiftUI.View` 两条,照旧默认关闭 | 对真实 SDK 的核对 | 2 | +| swift-type-indexing `Documentations/Internal/TypeIndexingPipeline.md`、`README.md`、`Documentations/Evolutions/README.md` | 修改 | 新增「搬家记录」一节;README 写查询用法;提案索引登记 cross-repository 一行 | 文档同批 | 2 | +| `Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift` · `MovedTypeModuleResolving` | 新增 | 角色协议 | 打印器侧的入口 | 3 | +| `Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift` · `NodePrintableDelegate` | 修改 | 加 `declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:)` | 节点打印器经委托提问 | 3 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift` · `TypeNameResolverRegistry`、`addTypeNameResolver(_:)`、委托实现 | 修改 | 新角色的注册与分发 | 与其他角色同一套机制 | 3 | +| `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift` · `resolvedModuleName(of:siblingIdentifier:)` | 修改 | 非 `__C` 模块问新角色 | 唯一出口 | 3 | +| `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift` · `printModuleSelector(ofNestedType:)`、`declaringModuleForModuleSelector` | 修改 | 模块节点来自根时,带回最外层类型的标识符作键 | 嵌套类型跟随外层(编译器同样如此) | 3 | +| `Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift` | 新增 | 用 `FixtureCompiler` 现编一个引用 `CGFloat` 的小库,配记录型替身解析器 | 打印器行为不依赖 SDK | 3 | +| `Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift` · `TypeDatabaseMovedTypeModuleResolver` | 新增 | 包 `TypeDatabase` + SDK 版本的适配器 | 版本按镜像固定,打印器协议不带版本 | 4 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift` · `SwiftInterfaceBuilderTypeNameProvider` | 修改 | 加 `Resolutions` 选项集合与 `resolutions:` 参数;遵循新角色;只开搬家时不生成模块接口 | 两个开关共用一个数据库 | 4 | +| `Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift` | 新增 | 适配器的版本判断,经 `@testable` 驱动 `register` | 适配层契约 | 4 | +| `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | `resolvesMovedTypeModules` 字段与 provider 接线、非 macOS 与无 build version 的警告 | 子命令逻辑在请求里 | 5 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift` · `InterfaceCommand` | 修改 | `--resolve-moved-type-modules` 及 `makeRequest()` 一行 | CLI 只是外壳 | 5 | +| `Tests/SwiftSectionKitTests/…`、`Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift` | 修改 | 请求两侧各一条 | 新开关两侧各一测(CLAUDE.md) | 5 | +| `Package.swift`、`Tuist/Package.swift` | 修改 | swift-type-indexing 升到新版本 | 用上新 API | 4 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 第 8 节旁加新开关的说明与陷阱(版本判断、默认关闭) | CLI 改动同批改 skill | 5 | +| `Documentations/Internal/Modules/SwiftInterface.md`、`Documentations/Internal/Modules/SwiftSectionKit.md`、`Documentations/Glossary.md`、`Documentations/Internal/ProjectEvolutionLog.md`、`CLAUDE.md` 的 SwiftTypeNameResolution 条 | 修改 | 新角色、新开关、术语「moved type」、账本一节 | 文档同批 | 6 | + +## 架构图 + +改了什么: + +```text +swift-type-indexing + TypeDatabase (actor) + discoverSDK() + APINotesIndex(files:) (kept) + + MovedTypeIndex.scan(interfaceText:moduleName:) for every SDK module + + movedTypeDeclarationsByKey: [MovedTypeKey: MovedTypeDeclaration] + moduleName(forTypeName:) (kept, __C only) + swiftName(forCName:category:) (kept, __C only) + + declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:) + +MachOSwiftSection + SwiftPrinting + TypeNameResolving + ModuleNameResolving / CImportedNameResolving / OpaqueTypeResolving (kept) + + MovedTypeModuleResolving + SwiftDeclarationPrinter.typeNameResolverRegistry + + movedTypeModuleResolvers + NodePrintable.resolvedModuleName(of:siblingIdentifier:) + __C / __ObjC -> ModuleNameResolving (kept) + + other module -> MovedTypeModuleResolving + TypeNodePrintable.printModuleSelector(ofNestedType:) + ~ key: outermost type's identifier when the module is the context root + SwiftTypeNameResolution + TypeDatabaseTypeNameResolver (kept, unchanged) + + TypeDatabaseMovedTypeModuleResolver(typeDatabase:sdkVersion:) + SwiftInterfaceBuilderTypeNameProvider + ~ resolutions: [.cImportedModules, .movedTypeModules] + SwiftSectionKit.InterfaceRequest + + resolvesMovedTypeModules + swift-section interface + + --resolve-moved-type-modules +``` + +一次查询的数据流: + +```text +interface print of `x: CoreGraphics.CGFloat` + TypeNodePrintable (context node = module "CoreGraphics", identifier "CGFloat") + resolvedModuleName(of: module, siblingIdentifier: "CGFloat") + not __C / __ObjC + delegate.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") + SwiftDeclarationPrinter -> first non-nil of movedTypeModuleResolvers + SwiftInterfaceBuilderTypeNameProvider + TypeDatabaseMovedTypeModuleResolver(sdkVersion: LC_BUILD_VERSION.sdk) + TypeDatabase.declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:) + movedTypeDeclarationsByKey[CoreGraphics, CGFloat] + -> declaringModule "CoreFoundation", moved macOS 10.0 + sdkVersion >= 10.0 -> "CoreFoundation" + writes "CoreFoundation" + "." (or "::") +``` + +## 详细设计 + +### 扫描器 + +```swift +struct MovedTypeKey: Hashable, Sendable { + let originalModuleName: String + let typeName: String +} + +struct MovedTypeDeclaration: Hashable, Sendable { + let typeName: String + /// The module the mangling names: the part of the attribute's module + /// argument before a `;`. + let originalModuleName: String + /// The module whose interface declares the type now. + let declaringModuleName: String + /// The version the attribute names per platform keyword (`macOS`, + /// `macCatalyst`, `iOS`, `tvOS`, `watchOS`, `visionOS`, `driverKit`). + let movedVersionsByPlatformName: [String: OperatingSystemVersion] +} + +enum MovedTypeIndex { + /// The type declarations `interfaceText` (a textual `.swiftinterface` + /// of `moduleName`) marks `@_originallyDefinedIn` another module. + static func movedTypeDeclarations(inInterfaceText interfaceText: String, moduleName: String) -> [MovedTypeDeclaration] +} +``` + +规则: + +- 只看从第 0 列开始的行。一个属性组是连续的以 `@` 开头的行;组里收集所有 `@_originallyDefinedIn(module: "M", P V)`,同一个属性写多个平台(`macOS 15.0, iOS 18.0`)时逐个拆开。 +- 属性组结束后的那一行是声明。去掉行首的属性(`@frozen`、`@MainActor`、`@preconcurrency` 等,含括号参数)和修饰词(`public`、`open`、`final`、`indirect`、`nonisolated`),第一个关键字是 `struct` / `class` / `enum` / `protocol` / `actor` / `typealias` 时取紧跟的标识符为类型名(遇到 `<`、`:`、空格、`=`、`{` 截止;反引号去掉)。其他关键字一律丢弃。 +- 平台关键字的拼写取 Swift 源码的写法:`macOS`、`macCatalyst`、`iOS`、`tvOS`、`watchOS`、`visionOS`、`driverKit`;`OSX` 视同 `macOS`,`*ApplicationExtension` 视同其基础平台。 +- `module:` 的值有 `;` 时取前半段。前半段等于 `moduleName` 时整条丢弃。 + +### 挑哪份接口文件 + +`SwiftModuleDescriptor.path` 是 `.swiftmodule` 目录。在它下面找文件名形如 `<架构>-apple-<平台后缀>.swiftinterface` 的文件,排除 `.private.swiftinterface` 与 `.package.swiftinterface`;平台后缀取自 `SDKPlatform`(`macos`、`ios-macabi`、`ios`、`ios-simulator`、`tvos`、`tvos-simulator`、`watchos`、`watchos-simulator`、`xros`、`xros-simulator`、`driverkit`)。同一模块有几种架构时按文件名排序取第一个(`arm64-` < `arm64e-` < `arm64e.x1-` < `x86_64-`,结果确定)。属性对每个平台都写全,所以选哪个架构不影响结果。目录里没有文本接口的模块(只有二进制 `.swiftmodule`)直接跳过。读文件失败记日志后跳过,不影响别的模块。 + +### 版本判断 + +```swift +extension TypeDatabase { + /// The module that declares the Swift type the mangling names + /// `originalModuleName.typeName`, when the SDK moved it there + /// (`@_originallyDefinedIn`) no later than `sdkVersion` of the database's + /// platform; nil when it never moved, or moved after that version. + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String, builtAgainst sdkVersion: OperatingSystemVersion) -> String? +} +``` + +- 用哪个平台的条目:`macOS` → `macOS`;`macCatalyst` → `macCatalyst`,没有就用 `iOS`(Catalyst 的版本号与 iOS 一致);`iOS` / `iOSSimulator` → `iOS`;`tvOS*` → `tvOS`;`watchOS*` → `watchOS`;`visionOS*` → `visionOS`,没有就用 `iOS` 并换算(iOS 17.x → visionOS 1.x,18.x → 2.x,26 起版本号相同,17 以前视为 visionOS 出现之前就已搬家);`driverKit` → `driverKit`。 +- 找不到适用条目:属性在该平台不生效,mangling 本来就是新模块,返回 `nil`。 +- `sdkVersion` 大于或等于搬家版本时返回 `declaringModuleName`。 +- 调用前没有 `index` 过:返回 `nil`(与 `moduleName(forTypeName:)` 一致)。 + +为什么用 `LC_BUILD_VERSION` 的 `sdk` 而不是 `minos`:mangling 与部署目标无关(前期调研 1),interface 想还原的是作者写代码时 SDK 里的样子,这由编译所用的 SDK 决定。系统镜像的 `sdk` 就是它所属的系统版本,所以 macOS 14 cache 里的 SwiftUI 不会被改写成 SwiftUICore。 + +**已知偏差**:属性写的版本不一定是源码真正搬家的时间。`CGFloat` 写的是 macOS 10.0,运行时却是 macOS 13 才搬进 `libswiftCoreFoundation`(前期调研 2)。用 macOS 12 SDK 编的二进制也会印成 `CoreFoundation.CGFloat`:它在当前 SDK 下成立,但不一定是当年 SDK 的写法。这里信属性,不另做修正表。 + +### 打印器 + +```swift +/// Resolves the module that declares a Swift type today when its mangling +/// names the module the type was originally defined in +/// (`@_originallyDefinedIn`): `CoreGraphics.CGFloat` → `CoreFoundation`. +public protocol MovedTypeModuleResolving: TypeNameResolving { + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? +} +``` + +`resolvedModuleName(of:siblingIdentifier:)` 的新分支: + +```swift +if moduleName != objcModule, moduleName != cModule, + let identifier = siblingIdentifier, !identifier.isEmpty, + let delegate, + let declaringModuleName = await delegate.declaringModuleName(ofMovedTypeNamed: identifier, originallyDefinedIn: moduleName) { + return (declaringModuleName, false) +} +``` + +它与 `cImportedTypeNameSpelling` 无关:`.cName` 只管 C 导入类型。`printModuleSelector(ofNestedType:)` 改为让 `declaringModuleForModuleSelector` 同时带回「模块节点的来源」:来自根时,带回最外层类型节点的标识符(根模块节点的兄弟)作为查询键;来自 `extension` 时不带,不查询。 + +### 适配层与请求 + +```swift +@available(macOS 13.0, *) +public struct TypeDatabaseMovedTypeModuleResolver: MovedTypeModuleResolving { + public let typeDatabase: TypeDatabase + /// The SDK version of the image being printed (`LC_BUILD_VERSION`'s `sdk`). + public let sdkVersion: OperatingSystemVersion + public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion) +} + +extension SwiftInterfaceBuilderTypeNameProvider { + public struct Resolutions: OptionSet, Sendable { + public static let cImportedModules: Resolutions + public static let movedTypeModules: Resolutions + } +} + +public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, resolutions: Resolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) +``` + +- `MachOKit.Version` → `OperatingSystemVersion` 的转换放在适配层(swift-type-indexing 不依赖 MachOKit)。 +- provider 未开 `.cImportedModules` 时,`moduleName(forTypeName:)` 与 `swiftName(forCName:category:)` 返回 `nil`,`setup()` 用 `moduleFilter: { _ in false }` 调一次 `index`,不传依赖;未开 `.movedTypeModules` 时,新角色的方法返回 `nil`。 +- `InterfaceRequest`:任一开关打开就构造 provider,`resolutions` 按两个开关组合。只开搬家时,现有警告的措辞里把 `--resolve-c-module-names` 换成实际打开的开关名。 + +### CLI + +```text +--resolve-moved-type-modules + Print a Swift type the SDK moved to another module (@_originallyDefinedIn) + under the module that declares it now (CoreGraphics.CGFloat -> + CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary + was built against an SDK that had already moved it. Reads the SDK's + .swiftinterface files; needs Xcode or the Command Line Tools, not + sourcekitd. macOS only. +``` + +## 替代方案考量 + +- **并进 `--resolve-c-module-names`**:用户只需要记一个「按 SDK 解析」的开关,但那个开关第一次运行要经 sourcekitd 生成模块接口(UIKit 冷生成 126 秒),只想要搬家改写的人不该为它付这笔钱;它的名字和帮助文字也说的是 `__C`。否:用独立开关,两个都开时共用数据库。 +- **从 `$ld$previous` 推导**:tbd 里有符号的旧安装路径与版本区间,但给的是库路径而不是模块名,还要逐个符号去重归并成类型;属性才是编译器自己的依据。否。 +- **经 sourcekitd 生成的接口读属性**:那一层只有依赖过滤命中的模块才生成,而且 `InterfaceDeclarationNode` 不留属性。搬家后的模块常常不是二进制的直接依赖(引用 `SwiftUI.View` 的二进制未必直接链接 SwiftUICore)。否。 +- **不做版本判断、一律按宿主 SDK 改写**:macOS 14 的 SwiftUI 镜像会印出当时还不存在的 SwiftUICore,而 `View` 恰好就声明在被打印的这个镜像里。否。 +- **按「类型定义是否在被打印的镜像里」判断**:SwiftUICore 镜像(macOS 15 起)里的定义正应改写成 SwiftUICore,这条规则会反着判。否。 +- **打印器协议带版本参数**:版本是被打印镜像的固定属性,放进适配器构造时一次给定,打印器不必知道 Mach-O。否。 +- **给 `TypeDatabaseTypeNameResolver` 直接加新角色**:RuntimeViewer 升级后输出会悄悄改变,而且它拿不到每个镜像的 SDK 版本。否:另起一个适配器。 +- **默认开启**:见非目标。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增: + +- swift-type-indexing:`TypeDatabase` 多一个公开方法。 +- MachOSwiftSection:`SwiftPrinting` 多一个公开协议;`SwiftTypeNameResolution` 多一个公开类型;`SwiftInterfaceBuilderTypeNameProvider.init` 多一个带默认值的参数(默认值保持现有行为);`InterfaceRequest` 多一个带默认值的字段;CLI 多一个开关。`NodePrintableDelegate` 是内部协议,加要求不影响外部。 + +### ABI 兼容性(条件项) + +不适用 —— 两个库都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftPrinting`、`SwiftTypeNameResolution`、`SwiftSectionKit`、`swift-section`。 +- swift-type-indexing 要先发新版本(0.2.0,新增公开 API),本库才能用上。 +- RuntimeViewer:不受影响(`TypeDatabaseTypeNameResolver` 不变);以后想要这项改写,要为每个镜像构造 `TypeDatabaseMovedTypeModuleResolver` 并传入 SDK 版本。MachOObjCSection 的 `ObjCTypeIndexing` 不受影响。 + +### 文档与示例 + +- swift-type-indexing:`TypeIndexingPipeline.md` 新增一节,README 写查询用法。 +- 本仓库:`Documentations/Internal/Modules/SwiftInterface.md`、`Documentations/Internal/Modules/SwiftSectionKit.md`、`CLAUDE.md` 的 SwiftTypeNameResolution 一条、agent 插件 skill(`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`)、`Documentations/Glossary.md`(术语 moved type)、`ProjectEvolutionLog.md`。 + +## API 演进与废弃策略 + +- 不替代任何旧 API。 +- `Resolutions` 用 `OptionSet`:以后再加别的 SDK 解析能力时只是加一个成员。 +- swift-type-indexing 0.1.x → 0.2.0;MachOSwiftSection 跟随下一个版本发布,不需要大版本跃迁。 + +## 落地步骤 + +1. **扫描器** —— 改动地图 swift-type-indexing 的 `MovedTypeIndex.swift`、`SDKPlatform.swift`、`MovedTypeIndexTests.swift` + - 行为:`structMovedFromAnotherModuleIsRecorded` + - 行为:`protocolClassEnumActorAndTypealiasAreRecorded` + - 行为:`extensionsFunctionsAndVariablesAreNotRecorded` + - 行为:`declarationModifiersAndAttributesBeforeTheKeywordAreSkipped` + - 行为:`severalPlatformsInOneAttributeAreSplit` + - 行为:`manglingModuleIsThePartBeforeTheSemicolon` + - 行为:`moveWithinTheSameModuleIsNotRecorded` + - 行为:`indentedAttributesAreIgnored` + - 行为:`interfaceFileMatchingThePlatformIsChosen` +2. **数据库与查询** —— 改动地图 swift-type-indexing 的 `TypeDatabase.swift`、`TypeDatabaseMovedTypeTests.swift`、`SDKIntegrationTests.swift` 与文档三行;完成后发 swift-type-indexing 0.2.0 + - 行为:`answersTheDeclaringModuleWhenTheSDKIsNotOlderThanTheMove` + - 行为:`answersNothingForAnSDKOlderThanTheMove` + - 行为:`answersNothingForATypeThatNeverMoved` + - 行为:`answersNothingBeforeIndexing` + - 行为:`macCatalystFallsBackToTheIOSVersion` + - 行为:`visionOSMapsTheIOSVersion` + - 行为:`firstDiscoveredModuleWinsATiedKey` + - 行为(SDK 集成,默认关闭):`cgFloatMovedFromCoreGraphicsToCoreFoundation`、`swiftUIViewMovedToSwiftUICoreInMacOS15` + - 落地时把扫描全部 SDK 模块的实测耗时写进前期调研 5。 +3. **打印器** —— 改动地图 `TypeNameResolving.swift`、`NodePrintableDelegate.swift`、`SwiftDeclarationPrinter.swift`、`NodePrintable.swift`、`TypeNodePrintable.swift`、`MovedTypeModuleTests.swift` + - 行为:`movedTopLevelTypePrintsUnderItsDeclaringModule` + - 行为:`nestedTypeFollowsItsOutermostType` + - 行为:`moduleSelectorsSpellTheDeclaringModuleOnNestedTypes` + - 行为:`extensionHeaderOfAMovedProtocolUsesTheDeclaringModule` + - 行为:`cImportedModulesAreNeverAskedAboutMoves` + - 行为:`withoutAResolverTheManglingModuleIsKept` + - 行为:`importLinesKeepTheManglingModules` +4. **适配层** —— 改动地图 `TypeDatabaseMovedTypeModuleResolver.swift`、`SwiftInterfaceBuilderTypeNameProvider.swift`、`TypeDatabaseMovedTypeModuleResolverTests.swift`、`Package.swift`、`Tuist/Package.swift` + - 行为:`resolverAnswersForTheImagesSDKVersion` + - 行为:`providerWithOnlyMovedTypesGeneratesNoModuleInterface` + - 行为:`providerWithBothResolutionsSharesOneDatabase` + - 行为:`providerDefaultKeepsTodaysResolutions` +5. **请求与 CLI** —— 改动地图 `InterfaceRequest.swift`、`InterfaceCommand.swift`、两侧测试、agent 插件 skill + - 行为:`interfaceRequestResolvesMovedTypeModulesOnlyWhenAsked` + - 行为:`resolveMovedTypeModulesFlagMapsOntoTheRequest` + - 行为:`bothResolutionFlagsCombine` + - 核对 skill 里点到的每个开关都还存在(CLAUDE.md 的 `grep -ohE` 命令)。 +6. **文档与收尾** —— 改动地图最后一行 + - 用 `swift-section interface --resolve-moved-type-modules` 打一次 macOS 27 的 SwiftUI 与 15.5 归档 cache 里的 SwiftUI,确认前者印 SwiftUICore、后者照旧印 SwiftUI,结果写进决策日志。 + - 新开关默认关闭,不开时输出逐字节不变;按 CLAUDE.md,这一改动不属于需要渲染 A/B 的大重构,以 `withoutAResolverTheManglingModuleIsKept` 与现有快照测试为准。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不单独写:调用方契约在 swift-type-indexing 的 README 与 `TypeIndexingPipeline.md` 里,打印器一侧在 `Modules/SwiftInterface.md`。 +- **有没有引入新术语** —— 有:「moved type」(被 `@_originallyDefinedIn` 搬过家的类型),登记进 `Documentations/Glossary.md`。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-25 | Created as Draft | 用户发现 `CGFloat` 在 SDK 里由 CoreFoundation 声明、二进制里却叫 CoreGraphics,问 swift-type-indexing 能否让输出与 SDK 一致;调研确认能做,用户要求写提案。 | +| 2026-11-25 | 方案取舍 | 独立开关、默认关闭;按二进制的 SDK 版本判断是否改写;`dump` 与 diff 类命令不改;RuntimeViewer 不随升级改变行为。用户确认开关做成独立的 `--resolve-moved-type-modules`。 | +| 2026-11-25 | Accepted | 用户批准,开始实现。 | diff --git a/Documentations/README.md b/Documentations/README.md index 5c72ffd5..b379d9f2 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -225,6 +225,7 @@ selects names using each access's offset and width. | [Evolutions/0104-shared-macho-testing-support.md](Evolutions/0104-shared-macho-testing-support.md) | **提案 0104(Implemented)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | | [Evolutions/0105-swift-type-indexing-package.md](Evolutions/0105-swift-type-indexing-package.md) | **提案 0105(Implemented,跨仓库)**:`TypeIndexing` 搬进独立包 swift-type-indexing(SDK 的模块接口与 API notes 索引,按 SDK 版本缓存),本仓库只留适配层 `SwiftTypeNameResolution`;同时修 API notes 改名规则与只装 Command Line Tools 时找不到 sourcekitd。MachOObjCSection 0.8.209 按 API notes 在头文件里标 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT`(swift-semantic-string 0.7.0 的宏色),RuntimeViewer 把 `__C.X` 打印成模块限定的 Swift 名 | | [Evolutions/0106-c-imported-type-name-spelling.md](Evolutions/0106-c-imported-type-name-spelling.md) | **提案 0106(Implemented,跨仓库,RuntimeViewer 参与)**:C 导入类型的名字统一成 Swift 名——声明、成员类型与扩展头一致写描述符给的 Swift 名(解析器找得到模块就带模块,否则写裸名),`CImportedTypeNameSpelling.cName` 一律写 mangled 的 C 名;ABI 名以描述符名字结尾的不信(导入成成员的类型退回 C 名)。`marksCImportedTypeNames` 在名字上标出另一种写法,RuntimeViewer 据此在声明行尾画可点击的标签、切换全局选项;`swift-section interface --c-imported-type-name-spelling` | +| [Evolutions/draft-moved-swift-type-modules.md](Evolutions/draft-moved-swift-type-modules.md) | **提案 draft(Accepted,跨仓库,swift-type-indexing 参与)**:被 SDK 用 `@_originallyDefinedIn` 搬过家的 Swift 类型(`CGFloat` 由 CoreFoundation 声明、mangling 仍是 CoreGraphics;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore),interface 按现在声明它的模块打印——swift-type-indexing 扫描 SDK 文本 `.swiftinterface` 建搬家表,打印器多一个 `MovedTypeModuleResolving` 角色,`swift-section interface --resolve-moved-type-modules` 默认关闭,按二进制的 SDK 版本判断是否改写。 | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | From ce7f395a486746742b18090ca01fccca1b2c3fe2 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:06:49 +0800 Subject: [PATCH 094/175] Print a Swift type the SDK moved under the module that declares it now The printer asks a new resolver role, MovedTypeModuleResolving, for the module declaring a Swift type whose mangling names the module it was originally defined in (@_originallyDefinedIn): CoreGraphics.CGFloat prints as CoreFoundation.CGFloat once a resolver says so. The question is asked by the top-level type's name, and a nested type's own module selector asks by its outermost type's, so SwiftUI::Text.SwiftUI::Storage moves as one. A __C or __ObjC module is never asked about a move, and without a resolver every module prints as mangled. Proposal moved-swift-type-modules, step 3; the proposal moves to In Progress. --- Documentations/Evolutions/README.md | 2 +- .../draft-moved-swift-type-modules.md | 11 +- Documentations/README.md | 2 +- ...iftInterfaceBuilderExtraDataProvider.swift | 3 +- .../NodePrintables/NodePrintable.swift | 21 ++- .../NodePrintableDelegate.swift | 1 + .../NodePrintables/TypeNameResolving.swift | 13 ++ .../NodePrintables/TypeNodePrintable.swift | 24 ++- .../SwiftDeclarationPrinter.swift | 9 + .../MovedTypeModuleTests.swift | 175 ++++++++++++++++++ 10 files changed, 245 insertions(+), 16 deletions(-) create mode 100644 Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 722fcb9b..2d4194ef 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -121,4 +121,4 @@ | [0104](0104-shared-macho-testing-support.md) | 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport | Implemented | | [0105](0105-swift-type-indexing-package.md) | 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer(跨仓库唯一提案) | Implemented | | [0106](0106-c-imported-type-name-spelling.md) | C 导入类型的名字统一成 Swift 名,并能切换回 C 名(跨仓库唯一提案,RuntimeViewer 参与) | Implemented | -| draft | [被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印(跨仓库唯一提案,swift-type-indexing 参与)](draft-moved-swift-type-modules.md) | Accepted | +| draft | [被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印(跨仓库唯一提案,swift-type-indexing 参与)](draft-moved-swift-type-modules.md) | In Progress | diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.md b/Documentations/Evolutions/draft-moved-swift-type-modules.md index d36f52f0..634166f0 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.md +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.md @@ -1,6 +1,6 @@ # Draft - 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-25 - **最后更新**: 2026-11-25 @@ -65,7 +65,7 @@ Apple 把一些 Swift 类型从一个模块搬进另一个模块时,会给声 - `SwiftSectionKit` 的 `InterfaceRequest`(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:224`)只在 `cModuleNameResolution == .enabled` 时挂上 provider;`dump`、`diff`、`snapshot`、`evolution` 都不挂任何类型名解析器。 - interface 头部的 `import` 行来自符号里出现的 mangling 模块名(`SwiftInterfaceBuilder.swift:357` 的 `collectModules()`),本提案不改它。 4. **swift-type-indexing 的现状**(`../swift-type-indexing`,0.1.1):`TypeDatabase` 只回答 `__C` 类型的归属(`moduleName(forTypeName:)`)与 C 名 → Swift 名(`swiftName(forCName:category:)`)。模块接口一层经 sourcekitd `editor.open.interface` 生成,`InterfaceDeclarationNode` 只留种类、名字与嵌套,不留属性;`Documentations/Internal/TypeIndexingPipeline.md` 明确说不读文本 `.swiftinterface`,因为它只含 Swift 声明,而那一层要的是 ObjC 导入类型。本提案要的恰好是 Swift 声明。`SDKIndexer.discover` 已经列出每个 `.swiftmodule` 目录(`SwiftModuleDescriptor.path`)。第一次 `index` 在 `discoverSDK()` 里登记 API notes;只要 ObjC 标注的调用方用一个不选任何模块的 `moduleFilter` 调一次 `index`,这个用法已有先例。 -5. **成本**:macOS 27.2 SDK 有 368 个 `.swiftmodule`,`arm64e-apple-macos.swiftinterface` 共 266 份(另有 `arm64e.x1-apple-macos` 12 份、`x86_64` 与 `ios-macabi` 各一套)。`grep -A12 '^@_originallyDefinedIn'` 扫完全部 macOS 份用时 0.38 秒。Swift 逐行解析会慢一些,落地时实测并记入本节。 +5. **成本**:macOS 27.2 SDK 有 368 个 `.swiftmodule`,`arm64e-apple-macos.swiftinterface` 共 266 份(另有 `arm64e.x1-apple-macos` 12 份、`x86_64` 与 `ios-macabi` 各一套)。`grep -A12 '^@_originallyDefinedIn'` 扫完全部 macOS 份用时 0.38 秒。实现后实测:带上扫描,一次只读 API notes 的 macOS 索引(`moduleFilter` 不选任何模块:发现 SDK、解析 API notes、扫描搬家记录)在公司那台 10 核 Mac Studio 上单独跑约 1.7 秒(`SDKIntegrationTests.cgFloatMovedFromCoreGraphicsToCoreFoundation`,两次 1.67 / 1.73 秒)。 6. **现在的输出能编过**:SE-0491(模块选择器)第 421 行规定 `Module::Name` 的候选包括「声明在该模块或被该模块重新导出的」声明;点号限定的写法同样会查到重新导出的声明。CoreGraphics 的接口头部有 `@_exported public import CoreFoundation`,SwiftUI 的接口第 19 行有 `@_exported import SwiftUICore`,所以 `CoreGraphics.CGFloat`、`SwiftUI.View` 都合法。本提案改的只是写法与 SDK 是否一致,不是正确性。 7. **使用方**:RuntimeViewer 按平台共用一个 `TypeDatabase`,经 `TypeDatabaseTypeNameResolver(typeDatabase:)` 注册(`RuntimeViewerCore/Sources/RuntimeViewerCore/TypeNames/RuntimeTypeIndex.swift:145`)。本提案不改这个类型的行为,RuntimeViewer 的输出不会因为升级而悄悄改变。 @@ -348,7 +348,7 @@ public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies (text: String, isResolvedCImportedModule: Bool) { let moduleName = node.text ?? "" + let isCImportedModule = moduleName == objcModule || moduleName == cModule if context.cImportedTypeNameSpelling == .swiftName, - moduleName == objcModule || moduleName == cModule, + isCImportedModule, let identifier = siblingIdentifier, let delegate, let updatedModuleName = await or(await delegate.moduleName(forTypeName: identifier), await delegate.moduleName(forTypeName: identifier.strippedRefSuffix)) { return (updatedModuleName, true) } + if !isCImportedModule, + !moduleName.isEmpty, + let identifier = siblingIdentifier, + !identifier.isEmpty, + let delegate, + let declaringModuleName = await delegate.declaringModuleName(ofMovedTypeNamed: identifier, originallyDefinedIn: moduleName) { + return (declaringModuleName, false) + } return (moduleName, false) } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift index 13400feb..e3392eeb 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift @@ -9,6 +9,7 @@ import Demangling protocol NodePrintableDelegate: AnyObject, Sendable { func moduleName(forTypeName typeName: String) async -> String? func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? func opaqueType(forNode node: Node, index: Int?, spellingOptions: DemangleOptions) async -> String? /// Whether what `opaqueType(forNode:index:)` supplies is to be marked as /// visible only with opaque type resolution on (see diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift index 66837bb3..14ffa632 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift @@ -44,6 +44,19 @@ public protocol CImportedNameResolving: TypeNameResolving { func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? } +/// Resolves the module that declares a Swift type now when its mangling +/// names the module the type was originally defined in +/// (`@_originallyDefinedIn`): `CoreGraphics.CGFloat` → `CoreFoundation`, +/// `SwiftUI.View` → `SwiftUICore` (evolution proposal +/// `moved-swift-type-modules`). +/// +/// The printer asks for every module other than `__C` / `__ObjC`, by the +/// top-level type's name: a nested type follows its outermost type, as the +/// compiler's mangling does. `nil` keeps the mangling's module. +public protocol MovedTypeModuleResolving: TypeNameResolving { + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? +} + /// Expands an opaque return type (`some P`) from its descriptor's generic /// requirements. public protocol OpaqueTypeResolving: TypeNameResolving { diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index 23728994..0e05a623 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -306,8 +306,16 @@ extension TypeNodePrintable { /// scopes, so the compiler writes none either), nor for a C-imported /// module spelling that does not resolve to a real module. mutating func printModuleSelector(ofNestedType name: Node) async { - guard context.usesModuleSelectors, let module = name.declaringModuleForModuleSelector else { return } - let moduleName = await resolvedModuleName(of: module, siblingIdentifier: name.children.at(1)?.text) + guard context.usesModuleSelectors, let (module, outermostTypeName) = name.declaringModuleForModuleSelector else { return } + // A C-imported module resolves by the nested type's own name; a Swift + // module by the outermost type's, the only name a move + // (`@_originallyDefinedIn`) is recorded under — a nested type moves + // with it (evolution proposal `moved-swift-type-modules`). An + // extension's module has no such name and is not asked about. + let moduleText = module.text ?? "" + let isCImportedModule = moduleText == objcModule || moduleText == cModule + let siblingIdentifier = isCImportedModule ? name.children.at(1)?.text : outermostTypeName + let moduleName = await resolvedModuleName(of: module, siblingIdentifier: siblingIdentifier) guard !moduleName.text.isEmpty, moduleName.text != objcModule, moduleName.text != cModule else { return } target.write(moduleName.text, context: .context(for: module, state: .printModule)) target.write("::") @@ -630,9 +638,13 @@ extension Node { /// of its own. The same rule as the `useModuleSelectors` option of /// swift-demangling's `NodePrinter`. /// + /// With the module at the root comes the name of the outermost type, the + /// one the module node is the context of; with an extension's module, + /// `nil`. + /// /// Iterative: the chain is as long as the nesting, and this walk sits /// outside the depth-checked `printName` recursion. - fileprivate var declaringModuleForModuleSelector: Node? { + fileprivate var declaringModuleForModuleSelector: (module: Node, outermostTypeName: String?)? { switch kind { case .class, .structure, .enum, .protocol, .otherNominalType, .typeAlias: break @@ -640,18 +652,20 @@ extension Node { return nil } var context = children.first + var contextOwner: Node = self while let current = context { switch current.kind { case .module: - return current + return (current, contextOwner.children.at(1)?.text) case .extension: guard let extensionModule = current.children.first, extensionModule.kind == .module else { return nil } - return extensionModule + return (extensionModule, nil) case .type, .class, .structure, .enum, .protocol, .otherNominalType, .typeAlias, .boundGenericClass, .boundGenericStructure, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias: // A type's first child is the type it wraps; a nominal's is its // own context; a bound generic's is its unbound type. + contextOwner = current context = current.children.first default: return nil diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 9ec9da51..6968e453 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -38,6 +38,7 @@ public final class SwiftDeclarationPrinter: S private struct TypeNameResolverRegistry: Sendable { var moduleNameResolvers: [any ModuleNameResolving] = [] var cImportedNameResolvers: [any CImportedNameResolving] = [] + var movedTypeModuleResolvers: [any MovedTypeModuleResolving] = [] var opaqueTypeResolvers: [any OpaqueTypeResolving] = [] } @@ -248,6 +249,10 @@ public final class SwiftDeclarationPrinter: S registry.cImportedNameResolvers.append(cImportedNameResolver) matchedAnyRole = true } + if let movedTypeModuleResolver = resolver as? any MovedTypeModuleResolving { + registry.movedTypeModuleResolvers.append(movedTypeModuleResolver) + matchedAnyRole = true + } if let opaqueTypeResolver = resolver as? any OpaqueTypeResolving { registry.opaqueTypeResolvers.append(opaqueTypeResolver) matchedAnyRole = true @@ -1302,6 +1307,10 @@ extension SwiftDeclarationPrinter: NodePrintableDelegate { await typeNameResolverRegistry.cImportedNameResolvers.asyncFirstNonNil { await $0.swiftName(forCName: cName, category: category) } } + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + await typeNameResolverRegistry.movedTypeModuleResolvers.asyncFirstNonNil { await $0.declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: originalModuleName) } + } + public func opaqueType(forNode node: Node, index: Int?) async -> String? { await opaqueType(forNode: node, index: index, spellingOptions: configuration.spellingOptions) } diff --git a/Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift b/Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift new file mode 100644 index 00000000..d6ebcea5 --- /dev/null +++ b/Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift @@ -0,0 +1,175 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport + +/// Evolution proposal `moved-swift-type-modules`: a Swift type the SDK moved +/// between modules (`@_originallyDefinedIn`) mangles under the module it was +/// originally defined in, and prints under the module a +/// `MovedTypeModuleResolving` resolver names — nested types with it. +/// +/// The resolver here is a table, so no SDK is involved: `CGFloat` moves from +/// CoreGraphics to CoreFoundation as the SDK says, and the fixture's own +/// `Outer` and `Drawable` move to a module named `NewHome`. +@Suite +struct MovedTypeModuleTests { + private static let fixtureModuleName = "MovedTypeModuleFixture" + + /// The class is ballast: a struct-only fixture dylib has no `__DATA` + /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. + private static let source = """ + import Foundation + + public final class FixtureAnchor {} + + public struct Outer { + public struct Inner { + public init() {} + } + public init() {} + } + + public protocol Drawable {} + + extension Drawable { + public func draw() {} + } + + public struct Holder { + public var width: CGFloat + public var inner: Outer.Inner + public var drawable: any Drawable + public var name: NSString + public init(width: CGFloat, inner: Outer.Inner, drawable: any Drawable, name: NSString) { + self.width = width + self.inner = inner + self.drawable = drawable + self.name = name + } + } + + extension CGFloat { + public var doubled: CGFloat { self * 2 } + } + """ + + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: fixtureModuleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "MovedTypeModuleFixture.swift", contents: source)], + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } + + /// Answers from a table and records every question. + private final class RecordingMovedTypeResolver: MovedTypeModuleResolving, @unchecked Sendable { + struct Question: Hashable { + let typeName: String + let originalModuleName: String + } + + private let lock = NSLock() + private var recordedQuestions: Set = [] + private let declaringModuleNames: [Question: String] + + init(declaringModuleNames: [Question: String]) { + self.declaringModuleNames = declaringModuleNames + } + + var questions: Set { + lock.withLock { recordedQuestions } + } + + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + let question = Question(typeName: typeName, originalModuleName: originalModuleName) + lock.withLock { _ = recordedQuestions.insert(question) } + return declaringModuleNames[question] + } + } + + private static func makeResolver() -> RecordingMovedTypeResolver { + RecordingMovedTypeResolver(declaringModuleNames: [ + .init(typeName: "CGFloat", originalModuleName: "CoreGraphics"): "CoreFoundation", + .init(typeName: "Outer", originalModuleName: fixtureModuleName): "NewHome", + .init(typeName: "Drawable", originalModuleName: fixtureModuleName): "NewHome", + ]) + } + + private func buildInterface(usesModuleSelectors: Bool = false, resolver: RecordingMovedTypeResolver?) async throws -> String { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.usesModuleSelectors = usesModuleSelectors + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration = printConfiguration + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: HostSlice.machOFile(at: Self.libraryURL())) + if let resolver { + builder.printer.addTypeNameResolver(resolver) + } + try await builder.prepare() + return try await builder.printRoot().string + } + + private func lines(of interface: String, startingWith prefix: String) -> [String] { + interface.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix(prefix) } + } + + @Test + func movedTopLevelTypePrintsUnderItsDeclaringModule() async throws { + let interface = try await buildInterface(resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "var width:") == ["var width: CoreFoundation.CGFloat"]) + #expect(!interface.contains("CoreGraphics.CGFloat"), "\(interface)") + } + + @Test + func nestedTypeFollowsItsOutermostType() async throws { + let interface = try await buildInterface(resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "var inner:") == ["var inner: NewHome.Outer.Inner"]) + } + + /// With module selectors a nested type writes its own, which is the + /// outermost type's declaring module too. + @Test + func moduleSelectorsSpellTheDeclaringModuleOnNestedTypes() async throws { + let interface = try await buildInterface(usesModuleSelectors: true, resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "var inner:") == ["var inner: NewHome::Outer.NewHome::Inner"]) + #expect(lines(of: interface, startingWith: "var width:") == ["var width: CoreFoundation::CGFloat"]) + } + + @Test + func extensionHeaderOfAMovedProtocolUsesTheDeclaringModule() async throws { + let interface = try await buildInterface(resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "extension NewHome.Drawable").count == 1, "\(interface)") + #expect(lines(of: interface, startingWith: "extension CoreFoundation.CGFloat").count == 1, "\(interface)") + #expect(lines(of: interface, startingWith: "var drawable:") == ["var drawable: any NewHome.Drawable"]) + } + + @Test + func cImportedModulesAreNeverAskedAboutMoves() async throws { + let resolver = Self.makeResolver() + _ = try await buildInterface(resolver: resolver) + let askedModules = Set(resolver.questions.map(\.originalModuleName)) + #expect(!askedModules.contains("__C")) + #expect(!askedModules.contains("__ObjC")) + #expect(askedModules.contains("CoreGraphics")) + } + + @Test + func withoutAResolverTheManglingModuleIsKept() async throws { + let interface = try await buildInterface(resolver: nil) + #expect(lines(of: interface, startingWith: "var width:") == ["var width: CoreGraphics.CGFloat"]) + #expect(lines(of: interface, startingWith: "var inner:") == ["var inner: \(Self.fixtureModuleName).Outer.Inner"]) + } + + /// The original module re-exports the one declaring the type now, so the + /// imports the binary's symbols name still compile the rewritten names. + @Test + func importLinesKeepTheManglingModules() async throws { + let rewrittenInterface = try await buildInterface(resolver: Self.makeResolver()) + let unresolvedInterface = try await buildInterface(resolver: nil) + #expect(lines(of: rewrittenInterface, startingWith: "import ") == lines(of: unresolvedInterface, startingWith: "import ")) + } +} From a1f3cbb0c5c0d43817588b6020f2d61b8888ccf7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:13:56 +0800 Subject: [PATCH 095/175] Print an extension of a moved Swift type under the module declaring it now An extension header spelled its extended type from the mangling directly, so extension CoreGraphics.CGFloat stayed while every reference to the type read CoreFoundation.CGFloat. When a MovedTypeModuleResolving resolver says the outermost type moved, the header prints through the type printer, as a C-imported extended type already does; any other type keeps the plain spelling. Proposal moved-swift-type-modules, step 3. --- .../SwiftDeclarationPrinter+Headers.swift | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index af5ca1f8..f799507d 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -822,6 +822,12 @@ extension SwiftDeclarationPrinter { /// names, `extension AnyWeakAttribute`, or `extension CoreFoundation.CGRect` /// once a resolver finds the module. Spelling C names it prints as the /// mangling spells it, which the plain spelling below already does. + /// + /// So does the extended type of an extension of a Swift type the SDK + /// moved between modules (evolution proposal `moved-swift-type-modules`): + /// `extension CoreFoundation.CGFloat` where the mangling says + /// `CoreGraphics`, once a `MovedTypeModuleResolving` resolver names the + /// module. Any other type keeps the plain spelling. @SemanticStringBuilder package func renderExtendedTypeName(_ extensionName: ExtensionName) async -> SemanticString { if spellsPositionNamedLocalType(extensionName.node) { @@ -831,11 +837,36 @@ extension SwiftDeclarationPrinter { isCImportedTypeReference(extensionName.node), let spelledName = try? await typeDemangleResolver.resolve(for: extensionName.node) { spelledName.replacingTypeNameOrOtherToTypeDeclaration() + } else if await isMovedTypeReference(extensionName.node), + let spelledName = try? await typeDemangleResolver.resolve(for: extensionName.node) { + spelledName.replacingTypeNameOrOtherToTypeDeclaration() } else { extensionName.print(usesModuleSelectors: configuration.usesModuleSelectors) } } + /// Whether `name`, with any `type` wrapper taken off, is a Swift type + /// — or nested in one — whose outermost type a registered + /// `MovedTypeModuleResolving` resolver says the SDK moved to another + /// module. Never asks about a `__C` / `__ObjC` type, nor about a type + /// declared in an extension or a function. + private func isMovedTypeReference(_ name: NodeReference) async -> Bool { + var current = name + while current.kind == .type, let wrapped = current.children.first { + current = wrapped + } + while current.kind.isAnyGeneric, let context = current.children.first { + if context.kind == .module { + guard let moduleName = context.text, moduleName != objcModule, moduleName != cModule, + current.children.count > 1, let typeName = current.children[1].text + else { return false } + return await declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: moduleName) != nil + } + current = context + } + return false + } + /// Whether `name`, with any `type` wrapper taken off, is a nominal type /// directly in `__C` / `__C_Synthesized`. private func isCImportedTypeReference(_ name: NodeReference) -> Bool { From e1e5277214c444816c4f0371ac158e0f7df87f11 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:13:56 +0800 Subject: [PATCH 096/175] Resolve moved Swift type modules through the SDK type-name provider TypeDatabaseMovedTypeModuleResolver answers the printer's moved-type question from a TypeDatabase for the SDK version the printed image was built with. SwiftInterfaceBuilderTypeNameProvider takes SDKTypeNameResolutions: .cImportedModules, its default and what it resolved until now, and .movedTypeModules, which alone generates no module interface. Both share one database. Proposal moved-swift-type-modules, step 4. --- Package.swift | 7 ++ ...wiftInterfaceBuilderTypeNameProvider.swift | 73 ++++++++++++--- .../TypeDatabaseMovedTypeModuleResolver.swift | 47 ++++++++++ ...DatabaseMovedTypeModuleResolverTests.swift | 89 +++++++++++++++++++ 4 files changed, 204 insertions(+), 12 deletions(-) create mode 100644 Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift create mode 100644 Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift diff --git a/Package.swift b/Package.swift index 02eefa1a..ab4ee91d 100644 --- a/Package.swift +++ b/Package.swift @@ -1251,6 +1251,10 @@ extension Target { dependencies: [ .target(.SwiftTypeNameResolution), .target(.SwiftPrinting), + // The provider's tests build a small library to read + // (proposal moved-swift-type-modules). + .target(.SwiftInterface), + .target(.SwiftSectionFixtureSupport), .product(.MachOKit), .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), ], @@ -1399,6 +1403,9 @@ extension Target { name: "SwiftSectionKitTests", dependencies: [ .target(.SwiftSectionKit), + // `FixtureCompiler`, for a library that names a moved Swift type + // (proposal moved-swift-type-modules). + .target(.SwiftSectionFixtureSupport), .product(.MachOFoundation), .target(.SwiftSymbols), // `LocalTypeFixture` and `ExclusiveImageAccess`, for the source diff --git a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift index 94820d4b..8b501181 100644 --- a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift +++ b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift @@ -10,17 +10,49 @@ import SwiftInterface import SwiftPrinting import TypeIndexing -/// The `SwiftInterfaceBuilder` extra-data provider that resolves `__C` / -/// `__ObjC` types: attach it and `__C.NSString` prints as -/// `Foundation.NSString`, `__C.UICellConfigurationState` as -/// `UIKit.__UICellConfigurationState`, through a swift-type-indexing -/// `TypeDatabase` built for the indexed binary's platform and dependency set. +/// What a `SwiftInterfaceBuilderTypeNameProvider` resolves through the SDK. @available(macOS 13.0, *) -public final class SwiftInterfaceBuilderTypeNameProvider: SwiftInterfaceBuilderExtraDataProvider, ModuleNameResolving, CImportedNameResolving, Sendable { +public struct SDKTypeNameResolutions: OptionSet, Hashable, Sendable { + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + + /// `__C` / `__ObjC` types: the module that declares them and the name + /// Swift gives them (`__C.NSString` → `Foundation.NSString`). Indexes the + /// SDK modules the binary links through sourcekitd — the first run per + /// SDK generates their interfaces. + public static let cImportedModules = SDKTypeNameResolutions(rawValue: 1 << 0) + + /// Swift types the SDK moved between modules (`@_originallyDefinedIn`): + /// the module that declares them now (`CoreGraphics.CGFloat` → + /// `CoreFoundation.CGFloat`), for the SDK version the binary was built + /// with. Reads the SDK's textual interfaces; no sourcekitd. + public static let movedTypeModules = SDKTypeNameResolutions(rawValue: 1 << 1) +} + +/// The `SwiftInterfaceBuilder` extra-data provider that resolves type names +/// through the SDK the indexed binary was built for: attach it and +/// `__C.NSString` prints as `Foundation.NSString`, +/// `__C.UICellConfigurationState` as `UIKit.__UICellConfigurationState`, and — +/// with ``SDKTypeNameResolutions/movedTypeModules`` — `CoreGraphics.CGFloat` as +/// `CoreFoundation.CGFloat`, through one swift-type-indexing `TypeDatabase` +/// built for the binary's platform and dependency set. +@available(macOS 13.0, *) +public final class SwiftInterfaceBuilderTypeNameProvider: SwiftInterfaceBuilderExtraDataProvider, ModuleNameResolving, CImportedNameResolving, MovedTypeModuleResolving, Sendable { public let machO: MachO + /// What this provider resolves; a role it was not asked for answers + /// `nil`. + public let resolutions: SDKTypeNameResolutions + private let resolver: TypeDatabaseTypeNameResolver + /// `nil` unless ``resolutions`` contains + /// ``SDKTypeNameResolutions/movedTypeModules``. + private let movedTypeModuleResolver: TypeDatabaseMovedTypeModuleResolver? + private let dependencies: SwiftInterfaceBuilderDependencies /// Fails when the binary carries no build-version load command mapping to @@ -29,19 +61,30 @@ public final class SwiftInterfaceBuilderTypeNameProvider, supplementaryAPINotesURLs: [URL] = []) { + public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, resolutions: SDKTypeNameResolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) { guard - let buildPlatform = machO.loadCommands.buildVersionCommand?.platform, - let platform = SDKPlatform(buildPlatform) + let buildVersionCommand = machO.loadCommands.buildVersionCommand, + let platform = SDKPlatform(buildVersionCommand.platform) else { return nil } self.machO = machO + self.resolutions = resolutions self.dependencies = dependencies - self.resolver = TypeDatabaseTypeNameResolver(typeDatabase: TypeDatabase(platform: platform, supplementaryAPINotesURLs: supplementaryAPINotesURLs)) + let typeDatabase = TypeDatabase(platform: platform, supplementaryAPINotesURLs: supplementaryAPINotesURLs) + self.resolver = TypeDatabaseTypeNameResolver(typeDatabase: typeDatabase) + self.movedTypeModuleResolver = resolutions.contains(.movedTypeModules) + ? TypeDatabaseMovedTypeModuleResolver(typeDatabase: typeDatabase, sdkVersion: OperatingSystemVersion(machOVersion: buildVersionCommand.sdk)) + : nil } public func setup() async throws { + guard resolutions.contains(.cImportedModules) else { + // Moved types come from the SDK discovery alone: a filter + // selecting no module generates no interface. + try await resolver.typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + return + } // Index only the SDK modules the binary actually links: the module // filter is keyed on the dependency images' module names, which is // what makes first-run indexing minutes-of-modules instead of the @@ -55,11 +98,17 @@ public final class SwiftInterfaceBuilderTypeNameProvider String? { - await resolver.moduleName(forTypeName: typeName) + guard resolutions.contains(.cImportedModules) else { return nil } + return await resolver.moduleName(forTypeName: typeName) } public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { - await resolver.swiftName(forCName: cName, category: category) + guard resolutions.contains(.cImportedModules) else { return nil } + return await resolver.swiftName(forCName: cName, category: category) + } + + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + await movedTypeModuleResolver?.declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: originalModuleName) } } diff --git a/Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift new file mode 100644 index 00000000..b3dc5c14 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift @@ -0,0 +1,47 @@ +#if os(macOS) + +import Foundation +import MachOKit +import SwiftPrinting +import TypeIndexing + +/// Answers the printer's question about a Swift type the SDK moved between +/// modules (`@_originallyDefinedIn`) from a swift-type-indexing +/// `TypeDatabase`: `CoreGraphics.CGFloat` prints as `CoreFoundation.CGFloat`, +/// and for an image built with the macOS 15 SDK or later `SwiftUI.View` as +/// `SwiftUICore.View` (evolution proposal `moved-swift-type-modules`). +/// +/// `sdkVersion` is the version of the SDK the printed image was built with — +/// its `LC_BUILD_VERSION`'s `sdk` — so an image built before a move keeps the +/// module its SDK declared the type in: the macOS 14 SwiftUI declares `View` +/// itself. The database must be built for the image's platform and indexed +/// (`index(dependencies:moduleFilter:)`, which a filter selecting no module +/// satisfies). +/// +/// Register it on a `SwiftDeclarationPrinter` with `addTypeNameResolver(_:)`. +@available(macOS 13.0, *) +public struct TypeDatabaseMovedTypeModuleResolver: MovedTypeModuleResolving { + public let typeDatabase: TypeDatabase + + /// The SDK version the printed image was built with. + public let sdkVersion: OperatingSystemVersion + + public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion) { + self.typeDatabase = typeDatabase + self.sdkVersion = sdkVersion + } + + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + await typeDatabase.declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: originalModuleName, builtAgainst: sdkVersion) + } +} + +extension OperatingSystemVersion { + /// A version a Mach-O load command records (`LC_BUILD_VERSION`'s `sdk` + /// or `minos`). + init(machOVersion: MachOKit.Version) { + self.init(majorVersion: machOVersion.major, minorVersion: machOVersion.minor, patchVersion: machOVersion.patch) + } +} + +#endif diff --git a/Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift new file mode 100644 index 00000000..2522dfca --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift @@ -0,0 +1,89 @@ +#if os(macOS) + +import Foundation +import MachOKit +import SwiftInterface +import SwiftPrinting +import SwiftSectionFixtureSupport +import Testing +import TypeIndexing +@testable import SwiftTypeNameResolution + +/// The adapters between swift-type-indexing's moved-type answers and the +/// printer (evolution proposal `moved-swift-type-modules`). Reads this Mac's +/// macOS SDK — its textual module interfaces, no sourcekitd — into a +/// temporary cache directory. +@Suite +struct TypeDatabaseMovedTypeModuleResolverTests { + private static func indexedDatabase() async throws -> (typeDatabase: TypeDatabase, cacheDirectoryURL: URL) { + let cacheDirectoryURL = FileManager.default.temporaryDirectory + .appending(component: "TypeDatabaseMovedTypeModuleResolverTests-\(UUID().uuidString)") + let typeDatabase = TypeDatabase(platform: .macOS, cacheDirectory: cacheDirectoryURL) + try await typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + return (typeDatabase, cacheDirectoryURL) + } + + /// A small library built against this Mac's SDK, so its `LC_BUILD_VERSION` + /// names an SDK every move recorded in it is in effect for. + private static func fixtureMachOFile() throws -> MachOFile { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "MovedTypeModuleResolverFixture", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "MovedTypeModuleResolverFixture.swift", contents: """ + import Foundation + public final class FixtureAnchor {} + public struct Holder { + public var width: CGFloat + public init(width: CGFloat) { self.width = width } + } + """)], + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) + } + + @Test + func resolverAnswersForTheImagesSDKVersion() async throws { + let (typeDatabase, cacheDirectoryURL) = try await Self.indexedDatabase() + defer { try? FileManager.default.removeItem(at: cacheDirectoryURL) } + let macOS15Resolver = TypeDatabaseMovedTypeModuleResolver(typeDatabase: typeDatabase, sdkVersion: OperatingSystemVersion(majorVersion: 15, minorVersion: 0, patchVersion: 0)) + let macOS14Resolver = TypeDatabaseMovedTypeModuleResolver(typeDatabase: typeDatabase, sdkVersion: OperatingSystemVersion(majorVersion: 14, minorVersion: 6, patchVersion: 0)) + + #expect(await macOS15Resolver.declaringModuleName(ofMovedTypeNamed: "View", originallyDefinedIn: "SwiftUI") == "SwiftUICore") + #expect(await macOS14Resolver.declaringModuleName(ofMovedTypeNamed: "View", originallyDefinedIn: "SwiftUI") == nil) + #expect(await macOS14Resolver.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") == "CoreFoundation") + #expect(await macOS15Resolver.declaringModuleName(ofMovedTypeNamed: "Int", originallyDefinedIn: "Swift") == nil) + } + + /// Only moved types: the setup reads the SDK's interfaces as text and + /// generates no module interface, and the `__C` questions are not + /// answered. + @Test + func providerWithOnlyMovedTypesAnswersNoCImportedQuestion() async throws { + let machOFile = try Self.fixtureMachOFile() + let provider = try #require(SwiftInterfaceBuilderTypeNameProvider( + machO: machOFile, + dependencies: SwiftInterfaceBuilderDependencies(machO: machOFile, searchPaths: []), + resolutions: .movedTypeModules + )) + try await provider.setup() + #expect(await provider.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") == "CoreFoundation") + #expect(await provider.moduleName(forTypeName: "NSObject") == nil) + #expect(await provider.swiftName(forCName: "CFStringRef", category: .other) == nil) + } + + /// The default keeps what the provider resolved before moved types + /// existed; it is not asked about moves, so nothing is indexed here. + @Test + func providerDefaultKeepsTodaysResolutions() async throws { + let machOFile = try Self.fixtureMachOFile() + let provider = try #require(SwiftInterfaceBuilderTypeNameProvider( + machO: machOFile, + dependencies: SwiftInterfaceBuilderDependencies(machO: machOFile, searchPaths: []) + )) + #expect(provider.resolutions == .cImportedModules) + #expect(await provider.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") == nil) + } +} + +#endif From d82d7b9466a101a5b95cbee9ae0a9898c9553cec Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:13:56 +0800 Subject: [PATCH 097/175] Add interface --resolve-moved-type-modules InterfaceRequest.resolvesMovedTypeModules, off by default, prints a Swift type the SDK moved between modules under the module declaring it now; with --resolve-c-module-names as well, one provider serves both. The warnings name whichever of the two flags is on. Proposal moved-swift-type-modules, step 5. --- .../Swift/InterfaceRequest.swift | 66 ++++++++++++++----- .../Commands/InterfaceCommand.swift | 4 ++ .../CommandRequestMappingTests.swift | 17 +++++ .../MovedTypeModuleRequestTests.swift | 50 ++++++++++++++ 4 files changed, 121 insertions(+), 16 deletions(-) create mode 100644 Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index fc50f479..63d4ddcc 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -39,6 +39,13 @@ public struct InterfaceRequest: Sendable, Equatable { /// Experimental: may fail to parse complex return types. public var parsesOpaqueReturnTypes: Bool public var cModuleNameResolution: CModuleNameResolution + /// Whether a Swift type the SDK moved between modules + /// (`@_originallyDefinedIn`) prints under the module that declares it + /// now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`), for the SDK + /// version the binary was built with. Reads the SDK's textual module + /// interfaces; needs Xcode or the Command Line Tools, not sourcekitd, and + /// is macOS only (evolution proposal `moved-swift-type-modules`). + public var resolvesMovedTypeModules: Bool public var fieldOffsetComments: FieldOffsetComments public var emitsMemberAddresses: Bool /// For class methods, computed properties and non-final stored @@ -108,6 +115,7 @@ public struct InterfaceRequest: Sendable, Equatable { showsCImportedTypes: Bool = false, parsesOpaqueReturnTypes: Bool = false, cModuleNameResolution: CModuleNameResolution = .disabled, + resolvesMovedTypeModules: Bool = false, fieldOffsetComments: FieldOffsetComments = .none, emitsMemberAddresses: Bool = false, emitsVTableOffsets: Bool = false, @@ -133,6 +141,7 @@ public struct InterfaceRequest: Sendable, Equatable { self.showsCImportedTypes = showsCImportedTypes self.parsesOpaqueReturnTypes = parsesOpaqueReturnTypes self.cModuleNameResolution = cModuleNameResolution + self.resolvesMovedTypeModules = resolvesMovedTypeModules self.fieldOffsetComments = fieldOffsetComments self.emitsMemberAddresses = emitsMemberAddresses self.emitsVTableOffsets = emitsVTableOffsets @@ -221,8 +230,13 @@ public struct InterfaceRequest: Sendable, Equatable { builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) } - if case .enabled(let supplementaryAPINotesPaths) = cModuleNameResolution { - addTypeNameProvider(to: builder, machOFile: machOFile, supplementaryAPINotesPaths: supplementaryAPINotesPaths, output: output) + let cImportedSupplementaryAPINotesPaths: [String]? = if case .enabled(let supplementaryAPINotesPaths) = cModuleNameResolution { + supplementaryAPINotesPaths + } else { + nil + } + if cImportedSupplementaryAPINotesPaths != nil || resolvesMovedTypeModules { + addTypeNameProvider(to: builder, machOFile: machOFile, cImportedSupplementaryAPINotesPaths: cImportedSupplementaryAPINotesPaths, output: output) } if !emitsHeader { @@ -252,30 +266,50 @@ public struct InterfaceRequest: Sendable, Equatable { } } + /// Attaches the SDK type-name provider: `__C` resolution when + /// `cImportedSupplementaryAPINotesPaths` is non-nil, moved-type + /// resolution when `resolvesMovedTypeModules` is set — one provider and + /// one SDK database for both. private func addTypeNameProvider( to builder: SwiftInterfaceBuilder, machOFile: MachOFile, - supplementaryAPINotesPaths: [String], + cImportedSupplementaryAPINotesPaths: [String]?, output: some SwiftSectionOutput ) { + let flagNames = [ + cImportedSupplementaryAPINotesPaths != nil ? "--resolve-c-module-names" : nil, + resolvesMovedTypeModules ? "--resolve-moved-type-modules" : nil, + ].compactMap(\.self).joined(separator: " and ") #if os(macOS) guard #available(macOS 13.0, *) else { - output.reportWarning("warning: --resolve-c-module-names requires macOS 13 or later") + output.reportWarning("warning: \(flagNames) requires macOS 13 or later") return } + var resolutions: SDKTypeNameResolutions = [] + if cImportedSupplementaryAPINotesPaths != nil { + resolutions.insert(.cImportedModules) + } + if resolvesMovedTypeModules { + resolutions.insert(.movedTypeModules) + } + let supplementaryAPINotesPaths = cImportedSupplementaryAPINotesPaths ?? [] + // Only `__C` resolution reads the dependency images; moved types come + // from the SDK alone. let providerDependencies = SwiftInterfaceBuilderDependencies( machO: machOFile, - searchPaths: [.systemDyldSharedCache], + searchPaths: cImportedSupplementaryAPINotesPaths != nil ? [.systemDyldSharedCache] : [], eventHandlers: output.indexEventHandlers(forInputLabeled: nil) ) - // Dependency resolution against the HOST dyld cache matches install - // names exactly, then bare names; a non-macOS binary's paths mostly - // miss both, which silently guts the SDK-interface source. Said - // aloud, misses named, instead of degrading quietly. - if providerDependencies.dependencies.isEmpty { - output.reportWarning("warning: --resolve-c-module-names resolved no dependency images against this host (non-macOS binary?); attribution will be limited to SDK APINotes and supplementary files") - } else if !providerDependencies.unresolvedLoadNames.isEmpty { - output.reportWarning("warning: --resolve-c-module-names could not resolve \(providerDependencies.unresolvedLoadNames.count) dependency image(s) against this host; their types will not be attributed: \(providerDependencies.unresolvedLoadNames.joined(separator: ", "))") + if cImportedSupplementaryAPINotesPaths != nil { + // Dependency resolution against the HOST dyld cache matches + // install names exactly, then bare names; a non-macOS binary's + // paths mostly miss both, which silently guts the SDK-interface + // source. Said aloud, misses named, instead of degrading quietly. + if providerDependencies.dependencies.isEmpty { + output.reportWarning("warning: --resolve-c-module-names resolved no dependency images against this host (non-macOS binary?); attribution will be limited to SDK APINotes and supplementary files") + } else if !providerDependencies.unresolvedLoadNames.isEmpty { + output.reportWarning("warning: --resolve-c-module-names could not resolve \(providerDependencies.unresolvedLoadNames.count) dependency image(s) against this host; their types will not be attributed: \(providerDependencies.unresolvedLoadNames.joined(separator: ", "))") + } } // A bad supplementary path is otherwise only os_log'd by the library // floor; a mistyped path or a broken YAML deserves the same warning @@ -296,13 +330,13 @@ public struct InterfaceRequest: Sendable, Equatable { } } let supplementaryAPINotesURLs = supplementaryAPINotesPaths.map { URL(fileURLWithPath: $0) } - if let typeNameProvider = SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: providerDependencies, supplementaryAPINotesURLs: supplementaryAPINotesURLs) { + if let typeNameProvider = SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: providerDependencies, resolutions: resolutions, supplementaryAPINotesURLs: supplementaryAPINotesURLs) { builder.addExtraDataProvider(typeNameProvider) } else { - output.reportWarning("warning: --resolve-c-module-names ignored: the binary carries no build-version command mapping to a known SDK platform") + output.reportWarning("warning: \(flagNames) ignored: the binary carries no build-version command mapping to a known SDK platform") } #else - output.reportWarning("warning: --resolve-c-module-names is only available on macOS") + output.reportWarning("warning: \(flagNames) is only available on macOS") #endif } } diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 2c208666..1e970f06 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -33,6 +33,9 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, and its dependencies' ObjC metadata. Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") var resolveCModuleNames: Bool = false + @Flag(help: "Print a Swift type the SDK moved to another module (@_originallyDefinedIn) under the module that declares it now (CoreGraphics.CGFloat -> CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary was built against an SDK that had already moved it. Reads the SDK's .swiftinterface files: needs Xcode or the Command Line Tools, not sourcekitd. macOS only.") + var resolveMovedTypeModules: Bool = false + @Option(name: .customLong("c-imported-type-name-spelling"), help: "How imported C and Objective-C types are spelled. swift-name (the default) prints the name Swift code uses: a type the binary's own descriptors rename prints under that name (__C.AGWeakAttribute -> AnyWeakAttribute), under its module when --resolve-c-module-names finds it. c-name prints every one as the binary mangles it (__C.AGWeakAttribute), declarations included, and resolves nothing.") var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName @@ -95,6 +98,7 @@ struct InterfaceCommand: AsyncParsableCommand { showsCImportedTypes: showCImportedTypes, parsesOpaqueReturnTypes: parseOpaqueReturnType, cModuleNameResolution: resolveCModuleNames ? .enabled(supplementaryAPINotesPaths: supplementaryAPINotesPaths) : .disabled, + resolvesMovedTypeModules: resolveMovedTypeModules, fieldOffsetComments: emitExpandedFieldOffsets ? .expanded : (emitOffsetComments ? .flat : .none), emitsMemberAddresses: emitMemberAddresses, emitsVTableOffsets: emitVtableOffsets, diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index 9ed0b5ee..2b74dd90 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -153,6 +153,23 @@ struct CommandRequestMappingTests { #expect(request.expandsMacros) } + @Test("interface resolves moved Swift types' modules only with --resolve-moved-type-modules") + func resolveMovedTypeModulesFlagMapsOntoTheRequest() throws { + let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.resolvesMovedTypeModules == false) + #expect(InterfaceRequest(source: defaultRequest.source).resolvesMovedTypeModules == false) + let request = try InterfaceCommand.parse(["/tmp/Sample", "--resolve-moved-type-modules"]).makeRequest() + #expect(request.resolvesMovedTypeModules) + #expect(request.cModuleNameResolution == .disabled) + } + + @Test("--resolve-c-module-names and --resolve-moved-type-modules combine") + func bothResolutionFlagsCombine() throws { + let request = try InterfaceCommand.parse(["/tmp/Sample", "--resolve-c-module-names", "--resolve-moved-type-modules"]).makeRequest() + #expect(request.resolvesMovedTypeModules) + #expect(request.cModuleNameResolution == .enabled(supplementaryAPINotesPaths: [])) + } + @Test("interface prints without module selectors unless asked") func interfaceModuleSelectorsDefaultOff() throws { #expect(try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest().usesModuleSelectors == false) diff --git a/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift b/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift new file mode 100644 index 00000000..a8b683bd --- /dev/null +++ b/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift @@ -0,0 +1,50 @@ +#if os(macOS) + +import Foundation +import Testing +import SwiftSectionKit +import SwiftSectionFixtureSupport + +/// `resolvesMovedTypeModules` on the `interface` request (evolution proposal +/// `moved-swift-type-modules`): off by default, the product spells a moved +/// Swift type as its mangling does; on, as this Mac's SDK declares it. Reads +/// the SDK's textual interfaces only, no sourcekitd. +@Suite +struct MovedTypeModuleRequestTests { + private static func fixture() throws -> MachOSource { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "MovedTypeModuleRequestFixture", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "MovedTypeModuleRequestFixture.swift", contents: """ + import Foundation + public final class FixtureAnchor {} + public struct Holder { + public var width: CGFloat + public init(width: CGFloat) { self.width = width } + } + """)], + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return .file(path: libraryURL.path, architecture: nil) + } + + private static func interface(resolvesMovedTypeModules: Bool) async throws -> String { + let output = RecordingOutput() + try await InterfaceRequest(source: fixture(), resolvesMovedTypeModules: resolvesMovedTypeModules).run(output: output, environment: .testing) + let declarations = output.products.compactMap { product in + if case .declarations(let semanticString) = product { semanticString.string } else { nil } + } + return try #require(declarations.only) + } + + @Test + func interfaceRequestResolvesMovedTypeModulesOnlyWhenAsked() async throws { + let unresolvedInterface = try await Self.interface(resolvesMovedTypeModules: false) + #expect(unresolvedInterface.contains("var width: CoreGraphics.CGFloat")) + let resolvedInterface = try await Self.interface(resolvesMovedTypeModules: true) + #expect(resolvedInterface.contains("var width: CoreFoundation.CGFloat")) + #expect(!resolvedInterface.contains("CoreGraphics.CGFloat")) + } +} + +#endif From c09208f3127567fb2ebaa62aed121c3f00d6600c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:15:57 +0800 Subject: [PATCH 098/175] Import Semantic and take the one interface product directly in the moved-type request test Proposal moved-swift-type-modules, step 5. --- Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift b/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift index a8b683bd..07e0b9d3 100644 --- a/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift +++ b/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift @@ -2,6 +2,7 @@ import Foundation import Testing +import Semantic import SwiftSectionKit import SwiftSectionFixtureSupport @@ -34,7 +35,8 @@ struct MovedTypeModuleRequestTests { let declarations = output.products.compactMap { product in if case .declarations(let semanticString) = product { semanticString.string } else { nil } } - return try #require(declarations.only) + try #require(declarations.count == 1) + return declarations[0] } @Test From a261058c92292e2e80c4c75b65869e8dd0e5c924 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:31:08 +0800 Subject: [PATCH 099/175] docs: document interface --resolve-moved-type-modules and moved Swift types The glossary gains moved type; the module notes, the evolution ledger, the README and the agent plugin skill describe the new flag and its version gate. The proposal records the deviations of steps 3 to 5 and the check on TipKit and DeveloperToolsSupport from the macOS 27.2 and 14.6 caches. Proposal moved-swift-type-modules, step 6. --- AGENTS.md | 2 +- .../skills/swift-section-cli/SKILL.md | 16 +++++++- .../draft-moved-swift-type-modules.html | 37 +++++++++--------- .../draft-moved-swift-type-modules.md | 39 +++++++++++-------- Documentations/Glossary.md | 9 ++++- .../Internal/Modules/SwiftInterface.md | 4 +- .../Internal/ProjectEvolutionLog.md | 14 +++++++ README.md | 6 +++ 8 files changed, 86 insertions(+), 41 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 98516c1f..b1de7cba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ One or two lines each; the linked document is the authority. - **ARM64InstructionDecoding** (MachOKitExtensions) — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). - **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. - **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). -- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. +- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([moved-swift-type-modules](Documentations/Evolutions/draft-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index 27640470..cab65124 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -215,7 +215,8 @@ switches). Only `interface` has: `--exported-only`, `--sort-members-by-offset`, `--parse-opaque-return-type`, `--show-c-imported-types`, `--resolve-c-module-names`, -`--supplementary-apinotes`, `--c-imported-type-name-spelling`, `--infer-objc-overrides`, +`--resolve-moved-type-modules`, `--supplementary-apinotes`, `--c-imported-type-name-spelling`, +`--infer-objc-overrides`, `--requirements-on-associated-types`, `--expand-macros`. `--requirements-on-associated-types` changes where a protocol's requirements print, never which: @@ -350,7 +351,7 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 one as changed. Formats 8 through 12 only ever existed on the development branch, between those changes. -## 8. `--resolve-c-module-names` (interface, macOS only) +## 8. `--resolve-c-module-names` and `--resolve-moved-type-modules` (interface, macOS only) Turns `__C.NSString` into `Foundation.NSString`, and applies the SDK's Swift renames: a `SwiftPrivate` type prints with `__` (`UIKit.__UICellConfigurationState`), a `SwiftName` one under @@ -369,6 +370,17 @@ resolves it and under its module when this flag does. `--c-imported-type-name-sp every C-imported type as the binary mangles it (`struct AGWeakAttribute`, `__C.AGWeakAttribute`) and makes this flag do nothing. +**`--resolve-moved-type-modules` is the Swift-type counterpart, and independent of it.** When the +SDK moves a Swift type to another module it marks the declaration `@_originallyDefinedIn`, and the +compiler keeps mangling the type — and every type nested in it — under the old module, so the binary +only ever says `CoreGraphics.CGFloat` and `SwiftUI.View`. This flag prints them as the SDK declares +them, `CoreFoundation.CGFloat` and `SwiftUICore.View`, references, module selectors and extension +headers alike. It reads the SDK's textual `.swiftinterface` files (about two seconds, no sourcekitd), +and only rewrites a type the binary's own SDK (`LC_BUILD_VERSION`'s `sdk`) already had moved: the +macOS 14 SwiftUI keeps `SwiftUI.View`, since `View` moved in macOS 15. Off by default, because the +result depends on the SDK installed on the machine. Both spellings compile — the old module +re-exports the new one — so the `import` lines are left as they are. + `objc interface --mark-sdk-swift-names` reads the same SDK's API notes for an Objective-C header: the class's or protocol's `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT` on a line above `@interface`, a member's before its `;`. API notes only, about two seconds, no sourcekitd. diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.html b/Documentations/Evolutions/draft-moved-swift-type-modules.html index 811926a8..b79df8d2 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.html +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.html @@ -163,7 +163,7 @@

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-25
    项目类型
    库(跨仓库:swift-type-indexing + MachOSwiftSection)
    原文
    draft-moved-swift-type-modules.md
    @@ -200,19 +200,18 @@

    摘要

    要你定

    -

    两件事

    +

    一件事

      -
    1. 开关做成独立的 --resolve-moved-type-modules(推荐:不需要 sourcekitd,几乎没有开销),还是并进现有的 --resolve-c-module-names?
    2. -
    3. 方案是否批准、可以开工?
    4. +
    5. swift-type-indexing 发 0.2.0 吗?本库的版本下限要等它发版后才能抬到 from: "0.2.0";在那之前本库只能经本地兄弟依赖构建。
    -

    我自己定的(可以推翻)

    +

    已定(用户批准)

      -
    • 默认关闭:输出会随宿主机的 SDK 变化。
    • +
    • 开关做成独立的 --resolve-moved-type-modules,默认关闭。
    • 按二进制的 LC_BUILD_VERSION sdk 判断,不看 minos。
    • -
    • dump、diff、snapshot、evolution 不改:dump 从不读 SDK,其余按 mangled 名比较。
    • -
    • TypeDatabaseTypeNameResolver 不变,RuntimeViewer 升级后输出不变,接入留给它自己。
    • +
    • dump、diff、snapshot、evolution 不改。
    • +
    • TypeDatabaseTypeNameResolver 不变,RuntimeViewer 升级后输出不变。
    @@ -240,7 +239,7 @@

    架构图

    MovedTypeModuleResolving resolvedModuleName(of:…) SwiftDeclarationPrinterregistry: movedTypeModuleResolvers - printModuleSelector(ofNestedType:)key: the outermost type's name + printModuleSelector(ofNestedType:)key: outermost type; extension headers too SwiftTypeNameResolution TypeDatabaseMovedTypeModuleResolvertypeDatabase + sdkVersion @@ -293,14 +292,15 @@

    改动地图

    SwiftPrinting/SwiftDeclarationPrinter.swift · TypeNameResolverRegistry修改新角色的注册与分发与其他角色同一套机制3 SwiftPrinting/NodePrintables/NodePrintable.swift · resolvedModuleName(of:siblingIdentifier:)修改非 __C 模块问新角色模块名输出的唯一出口3 SwiftPrinting/NodePrintables/TypeNodePrintable.swift · printModuleSelector(ofNestedType:)修改模块节点来自根时,用最外层类型的标识符作键嵌套类型跟随外层(编译器同样如此)3 + SwiftPrinting/SwiftDeclarationPrinter+Headers.swift · renderExtendedTypeName(_:)、isMovedTypeReference(_:)修改最外层类型被认作搬家时,扩展头改走类型打印器扩展头原本照 mangling 印,不经模块名出口(实现时发现)3 Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift新增FixtureCompiler 现编引用 CGFloat 的小库,配记录型替身解析器打印器行为不依赖 SDK3 SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift新增包 TypeDatabase + SDK 版本的适配器版本按镜像固定4 - SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift修改Resolutions 选项集合与 resolutions: 参数;遵循新角色;只开搬家时不生成模块接口两个开关共用一个数据库4 + SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift修改顶层选项集合 SDKTypeNameResolutions 与 resolutions: 参数;遵循新角色;只开搬家时不生成模块接口两个开关共用一个数据库4 Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift新增适配器的版本判断适配层契约4 SwiftSectionKit/Swift/InterfaceRequest.swift修改resolvesMovedTypeModules 字段、provider 接线与警告子命令逻辑在请求里5 swift-section/Commands/InterfaceCommand.swift修改--resolve-moved-type-modules 与 makeRequest() 一行CLI 只是外壳5 Tests/SwiftSectionKitTests/…、CommandRequestMappingTests.swift修改请求两侧各一条新开关两侧各一测5 - Package.swift、Tuist/Package.swift修改swift-type-indexing 升到新版本用上新 API4 + Package.swift修改两个测试目标加依赖;swift-type-indexing 版本下限待 0.2.0 发版后再抬测试要现编小库;用上新 API4 AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md修改新开关的说明与陷阱CLI 改动同批改 skill5 Modules/SwiftInterface.md、Modules/SwiftSectionKit.md、Glossary.md、ProjectEvolutionLog.md、CLAUDE.md修改新角色、新开关、术语 moved type、账本一节文档同批6 @@ -374,6 +374,7 @@

    详细设计

    • 返回的 isResolvedCImportedModule 仍是 false,不触发 C 名改写;与 cImportedTypeNameSpelling 无关。
    • declaringModuleForModuleSelector 同时带回模块节点的来源:来自根时带回最外层类型的标识符作键;来自 extension 时不查询。
    • +
    • 扩展头:renderExtendedTypeName(_:) 原本对非 C 类型直接照 mangling 印。新增 isMovedTypeReference(_:),最外层类型被解析器认作搬家时改走类型打印器;没搬家的照旧,输出逐字节不变。
    @@ -386,14 +387,12 @@

    详细设计

    public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion) } -extension SwiftInterfaceBuilderTypeNameProvider { - public struct Resolutions: OptionSet, Sendable { - public static let cImportedModules: Resolutions - public static let movedTypeModules: Resolutions - } +public struct SDKTypeNameResolutions: OptionSet, Hashable, Sendable { + public static let cImportedModules: SDKTypeNameResolutions + public static let movedTypeModules: SDKTypeNameResolutions } -public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies<MachO>, resolutions: Resolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) +public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies<MachO>, resolutions: SDKTypeNameResolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = [])
    • MachOKit.Version → OperatingSystemVersion 的转换放在适配层(swift-type-indexing 不依赖 MachOKit)。
    • 未开 .cImportedModules:两个 C 角色方法返回 nil,setup() 用 moduleFilter: { _ in false } 调一次 index;未开 .movedTypeModules:新角色返回 nil。
    • @@ -464,9 +463,9 @@

      落地步骤

    • 扫描器:structMovedFromAnotherModuleIsRecorded、protocolClassEnumActorAndTypealiasAreRecorded、extensionsFunctionsAndVariablesAreNotRecorded、declarationModifiersAndAttributesBeforeTheKeywordAreSkipped、severalPlatformsInOneAttributeAreSplit、manglingModuleIsThePartBeforeTheSemicolon、moveWithinTheSameModuleIsNotRecorded、indentedAttributesAreIgnored、interfaceFileMatchingThePlatformIsChosen
    • 数据库与查询(之后发 swift-type-indexing 0.2.0):answersTheDeclaringModuleWhenTheSDKIsNotOlderThanTheMove、answersNothingForAnSDKOlderThanTheMove、answersNothingForATypeThatNeverMoved、answersNothingBeforeIndexing、macCatalystFallsBackToTheIOSVersion、visionOSMapsTheIOSVersion、firstDiscoveredModuleWinsATiedKey;SDK 集成(默认关闭)cgFloatMovedFromCoreGraphicsToCoreFoundation、swiftUIViewMovedToSwiftUICoreInMacOS15
    • 打印器:movedTopLevelTypePrintsUnderItsDeclaringModule、nestedTypeFollowsItsOutermostType、moduleSelectorsSpellTheDeclaringModuleOnNestedTypes、extensionHeaderOfAMovedProtocolUsesTheDeclaringModule、cImportedModulesAreNeverAskedAboutMoves、withoutAResolverTheManglingModuleIsKept、importLinesKeepTheManglingModules
    • -
    • 适配层:resolverAnswersForTheImagesSDKVersion、providerWithOnlyMovedTypesGeneratesNoModuleInterface、providerWithBothResolutionsSharesOneDatabase、providerDefaultKeepsTodaysResolutions
    • +
    • 适配层:resolverAnswersForTheImagesSDKVersion、providerWithOnlyMovedTypesAnswersNoCImportedQuestion、providerDefaultKeepsTodaysResolutions(providerWithBothResolutionsSharesOneDatabase 未写,见决策日志)
    • 请求与 CLI:interfaceRequestResolvesMovedTypeModulesOnlyWhenAsked、resolveMovedTypeModulesFlagMapsOntoTheRequest、bothResolutionFlagsCombine;核对 skill 点到的开关都还存在
    • -
    • 文档与收尾:打 macOS 27 与 15.5 归档 cache 的 SwiftUI 各一次,前者印 SwiftUICore、后者照旧;默认关闭时输出逐字节不变,不需要渲染 A/B
    • +
    • 文档与收尾:打宿主 27.2 与 14.6 归档 cache 的 TipKit、DeveloperToolsSupport,前者 SwiftUI.View → SwiftUICore.View、后者照旧;默认关闭时输出逐字节不变,不需要渲染 A/B
    diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.md b/Documentations/Evolutions/draft-moved-swift-type-modules.md index 634166f0..6091f4af 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.md +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.md @@ -116,14 +116,15 @@ Apple 把一些 Swift 类型从一个模块搬进另一个模块时,会给声 | `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift` · `TypeNameResolverRegistry`、`addTypeNameResolver(_:)`、委托实现 | 修改 | 新角色的注册与分发 | 与其他角色同一套机制 | 3 | | `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift` · `resolvedModuleName(of:siblingIdentifier:)` | 修改 | 非 `__C` 模块问新角色 | 唯一出口 | 3 | | `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift` · `printModuleSelector(ofNestedType:)`、`declaringModuleForModuleSelector` | 修改 | 模块节点来自根时,带回最外层类型的标识符作键 | 嵌套类型跟随外层(编译器同样如此) | 3 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` · `renderExtendedTypeName(_:)`、`isMovedTypeReference(_:)` | 修改 | 被扩展类型的最外层类型被解析器认作搬家时,扩展头改走类型打印器 | 扩展头原本直接照 mangling 印,不经模块名出口(实现时发现,见决策日志) | 3 | | `Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift` | 新增 | 用 `FixtureCompiler` 现编一个引用 `CGFloat` 的小库,配记录型替身解析器 | 打印器行为不依赖 SDK | 3 | | `Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift` · `TypeDatabaseMovedTypeModuleResolver` | 新增 | 包 `TypeDatabase` + SDK 版本的适配器 | 版本按镜像固定,打印器协议不带版本 | 4 | -| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift` · `SwiftInterfaceBuilderTypeNameProvider` | 修改 | 加 `Resolutions` 选项集合与 `resolutions:` 参数;遵循新角色;只开搬家时不生成模块接口 | 两个开关共用一个数据库 | 4 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift` · `SwiftInterfaceBuilderTypeNameProvider` | 修改 | 加顶层选项集合 `SDKTypeNameResolutions` 与 `resolutions:` 参数;遵循新角色;只开搬家时不生成模块接口 | 两个开关共用一个数据库 | 4 | | `Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift` | 新增 | 适配器的版本判断,经 `@testable` 驱动 `register` | 适配层契约 | 4 | | `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | `resolvesMovedTypeModules` 字段与 provider 接线、非 macOS 与无 build version 的警告 | 子命令逻辑在请求里 | 5 | | `Sources/Executables/swift-section/Commands/InterfaceCommand.swift` · `InterfaceCommand` | 修改 | `--resolve-moved-type-modules` 及 `makeRequest()` 一行 | CLI 只是外壳 | 5 | | `Tests/SwiftSectionKitTests/…`、`Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift` | 修改 | 请求两侧各一条 | 新开关两侧各一测(CLAUDE.md) | 5 | -| `Package.swift`、`Tuist/Package.swift` | 修改 | swift-type-indexing 升到新版本 | 用上新 API | 4 | +| `Package.swift` | 修改 | 测试目标依赖:`SwiftTypeNameResolutionTests` 加 `SwiftInterface` 与 `SwiftSectionFixtureSupport`,`SwiftSectionKitTests` 加 `SwiftSectionFixtureSupport`;swift-type-indexing 的版本下限待它发 0.2.0 后再抬(见决策日志) | 测试要现编小库;用上新 API | 4 | | `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 第 8 节旁加新开关的说明与陷阱(版本判断、默认关闭) | CLI 改动同批改 skill | 5 | | `Documentations/Internal/Modules/SwiftInterface.md`、`Documentations/Internal/Modules/SwiftSectionKit.md`、`Documentations/Glossary.md`、`Documentations/Internal/ProjectEvolutionLog.md`、`CLAUDE.md` 的 SwiftTypeNameResolution 条 | 修改 | 新角色、新开关、术语「moved type」、账本一节 | 文档同批 | 6 | @@ -266,7 +267,9 @@ if moduleName != objcModule, moduleName != cModule, } ``` -它与 `cImportedTypeNameSpelling` 无关:`.cName` 只管 C 导入类型。`printModuleSelector(ofNestedType:)` 改为让 `declaringModuleForModuleSelector` 同时带回「模块节点的来源」:来自根时,带回最外层类型节点的标识符(根模块节点的兄弟)作为查询键;来自 `extension` 时不带,不查询。 +它与 `cImportedTypeNameSpelling` 无关:`.cName` 只管 C 导入类型。`printModuleSelector(ofNestedType:)` 改为让 `declaringModuleForModuleSelector` 同时带回「模块节点的来源」:来自根时,带回最外层类型节点的标识符(根模块节点的兄弟)作为查询键;来自 `extension` 时不带,不查询。C 导入模块照旧按嵌套类型自己的名字问 `__C` 解析器,行为不变。 + +扩展头另有一条路:`SwiftDeclarationPrinter+Headers.swift` 的 `renderExtendedTypeName(_:)` 原本对非 C 类型直接 `extensionName.print(usesModuleSelectors:)`,不经模块名出口。新增 `isMovedTypeReference(_:)`:剥掉 `type` 包装、沿上下文找到根模块,模块不是 `__C` / `__ObjC` 且解析器对最外层类型回答了搬家,才改走类型打印器(与 C 导入类型的扩展头同一条路);没搬家的类型照旧,输出逐字节不变。 ### 适配层与请求 @@ -279,14 +282,13 @@ public struct TypeDatabaseMovedTypeModuleResolver: MovedTypeModuleResolving { public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion) } -extension SwiftInterfaceBuilderTypeNameProvider { - public struct Resolutions: OptionSet, Sendable { - public static let cImportedModules: Resolutions - public static let movedTypeModules: Resolutions - } +/// What a `SwiftInterfaceBuilderTypeNameProvider` resolves through the SDK. +public struct SDKTypeNameResolutions: OptionSet, Hashable, Sendable { + public static let cImportedModules: SDKTypeNameResolutions + public static let movedTypeModules: SDKTypeNameResolutions } -public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, resolutions: Resolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) +public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, resolutions: SDKTypeNameResolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) ``` - `MachOKit.Version` → `OperatingSystemVersion` 的转换放在适配层(swift-type-indexing 不依赖 MachOKit)。 @@ -343,7 +345,7 @@ public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies`)。「anchor 在组合外」的限定是防捏造判据:anchor 协议自己在组合里时,其余同名成员写没写 sugar 无从知道(塌缩与未 pin 同形),挂了就是编造。 @@ -523,7 +530,7 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 ### type index(类型索引) -swift-type-indexing 的 `TypeIndexing`(原是本仓库的同名 target)从 SDK 建的索引:每个平台的模块接口与 API notes,回答一个 `__C` 类型属于哪个模块、Swift 里叫什么(`__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`),按 SDK 版本缓存在盘上。本仓库只留适配层 `SwiftTypeNameResolution`,`swift-section interface --resolve-c-module-names` 经它解析;MachOObjCSection 的 `ObjCTypeIndexing` 是 ObjC 一侧的接入。 +swift-type-indexing 的 `TypeIndexing`(原是本仓库的同名 target)从 SDK 建的索引:每个平台的模块接口与 API notes,回答一个 `__C` 类型属于哪个模块、Swift 里叫什么(`__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`),按 SDK 版本缓存在盘上;另外从各模块的文本 `.swiftinterface` 读出被 SDK 搬过家的 Swift 类型现在由哪个模块声明(见 moved type)。本仓库只留适配层 `SwiftTypeNameResolution`,`swift-section interface --resolve-c-module-names` 经它解析;MachOObjCSection 的 `ObjCTypeIndexing` 是 ObjC 一侧的接入。 - **主要出现在**:`Sources/Output/SwiftTypeNameResolution/`;swift-type-indexing 的 `Sources/TypeIndexing/` - **延伸阅读**:[提案 0105](Evolutions/0105-swift-type-indexing-package.md)、[TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md) diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index 80469626..a705c08f 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -52,7 +52,7 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 **宏展开的折叠**(提案 [0093-observable-macro-folding](../../Evolutions/0093-observable-macro-folding.md)):`@Observable` 展开的类默认按源码的样子打印——类型头上一行 `@Observation.Observable`,被跟踪的属性在它存储字段 `_x` 的位置印成 `var x: T`(字段的偏移与布局注释照旧;`declaredMember` 来源带上 computed `x` 的 vtable 与地址注释,`synthesized` 来源在上方加 note 写明是从哪个存储字段合成的),宏不跟踪的存储 `var` 上方加一行 `@Observation.ObservationIgnored`(单独占一行、与声明同样缩进;property wrapper 的属性也各占一行,`lazy` 留在声明行;提案 [0095-observable-nested-expansion](../../Evolutions/0095-observable-nested-expansion.md)),registrar、computed `x`、生成的方法与生成的 conformance 都不印。`expandsMacros` 打开时逐字节回到折叠之前的样子。打印器每次打印从 `TypeDefinition.observableMacroExpansion` 算一份视图(`SwiftDeclarationPrinter+ObservableMacro.swift`),接在字段块、两种成员排序、导出过滤、类型头与 `printExtensionDefinition` 上;`marksOptionalContent` 打开时两种形态都印,各自在 `SwiftVisibilityOption.expandsMacros` 的区域里,`VisibilityRegionProjectionTests` 对 fixture 的四个变体与进程内镜像验证投影。`printMacroExpansion(of:attachedTo:level:)` 用同一套逐字段、逐成员的渲染把展开单独印成一块,`printMacroExpansionParts(of:attachedTo:)` 按 Xcode 放 attached macro 展开的位置拆成几块,供宿主做内联展开。它照宏自己的分层分两层(提案 [0095-observable-nested-expansion](../../Evolutions/0095-observable-nested-expansion.md)):展开 `@Observable` 得到每个被跟踪属性一块 `@Observation.ObservationTracked`(`.trackedPropertyAttribute`,放在折叠声明上方),加上闭合括号上方的成员块与下方的 conformance 块;属性块的 `nestedExpansions` 给出这个属性在块里的 UTF-8 范围与展开它的分块,也就是 accessor 块加存储的 `.trackedProperty`,放在折叠声明下方。两层的 `anchorKind` 都是那个折叠声明的区域。两者里被跟踪属性的 computed `x` 与 accessor 块都照宏的写法印 `@storageRestrictions(initializes: _x) init`、`get`、`set` 三行(`init` 那一行与别处的 accessor 块共用 `AccessorBlockKeywords.InitAccessorLine`,提案 [0094-init-accessor-recovery](../../Evolutions/0094-init-accessor-recovery.md)),不看镜像里还剩哪些 accessor(AppKit 剥光、SwiftUI 只剩 getter 的都有);`marksAttachedMacros` 把宏属性包进 `AnnotationRegion.Kind.attachedMacro(_:)` 的区域、把每个被跟踪属性折叠出的声明包进 `attachedMacroTrackedProperty(_:named:)` 的区域,配合 `marksNestedDefinitions`,最内层的 `DefinitionRegion` 指明是哪个类型的宏。diff 与 evolution 渲染器不走这条路,始终印展开。 -**`SwiftInterfaceBuilderExtraDataProvider`**:外部数据源的注入缝,纯生命周期钩子——`Sendable` + 一个默认为空的 `setup()`(提案 0015 之前它还继承 printer 的 resolver 协议,强迫所有 provider 都是类型名解析器)。「会不会回答 printer 查询」是正交能力:provider 按需另行声明 `SwiftPrinting` 的角色协议(`ModuleNameResolving` / `CImportedNameResolving` / `OpaqueTypeResolving`,均 refine 空标记协议 `TypeNameResolving`),`addExtraDataProvider(_:)` 用 `as? any TypeNameResolving` 命中才把它转发给 printer——所以一个 resolver 型 provider 一头挂在 builder 的 prepare 生命周期上,一头挂在打印热路径上,而纯 setup 型 provider(只预热缓存之类)也是合法形态。两个已知实现:`TypeIndexing.SwiftInterfaceBuilderTypeNameProvider`(`__C` 模块归属,跨模块,声明两个名字角色)和本模块的 `SwiftInterfaceBuilderOpaqueTypeProvider`(声明 `OpaqueTypeResolving`,见子系统 2)。 +**`SwiftInterfaceBuilderExtraDataProvider`**:外部数据源的注入缝,纯生命周期钩子——`Sendable` + 一个默认为空的 `setup()`(提案 0015 之前它还继承 printer 的 resolver 协议,强迫所有 provider 都是类型名解析器)。「会不会回答 printer 查询」是正交能力:provider 按需另行声明 `SwiftPrinting` 的角色协议(`ModuleNameResolving` / `CImportedNameResolving` / `MovedTypeModuleResolving` / `OpaqueTypeResolving`,均 refine 空标记协议 `TypeNameResolving`),`addExtraDataProvider(_:)` 用 `as? any TypeNameResolving` 命中才把它转发给 printer——所以一个 resolver 型 provider 一头挂在 builder 的 prepare 生命周期上,一头挂在打印热路径上,而纯 setup 型 provider(只预热缓存之类)也是合法形态。两个已知实现:`SwiftTypeNameResolution.SwiftInterfaceBuilderTypeNameProvider`(经 SDK 解析类型名,跨模块,声明三个名字角色:`__C` 模块归属与 Swift 名,以及被 SDK 搬过家的 Swift 类型现在的声明模块——见术语表 moved type;`SDKTypeNameResolutions` 决定开哪几样,只开搬家时 `setup()` 不生成任何模块接口)和本模块的 `SwiftInterfaceBuilderOpaqueTypeProvider`(声明 `OpaqueTypeResolving`,见子系统 2)。 **`SwiftInterfaceBuilderDependencies` + `DependencyPath`**:把「主 binary + 它的依赖镜像」凑成一组,按 reader 分特化——`MachOFile` 版从 `DependencyPath`(单个 Mach-O 路径 / dyld cache 路径 / 宿主系统 cache)按 install name 匹配装载,装载失败走 `renderingDegraded` 事件(默认无 handler 也有 os_log 地板);`MachOImage` 版直接按名字向 dyld 要。消费者是 CLI 的 `InterfaceCommand` 与 `TypeIndexing`(依赖过滤 + 惰性 ObjC 元数据索引都需要依赖镜像清单)。 @@ -104,7 +104,7 @@ N ≥ 2 版本渲染成**一份**并集接口,声明尾注生命周期注解 | 入口 | 路径 | |---|---| -| `swift-section interface` | `SwiftInterfaceBuilder`(+ `--resolve-c-module-names` 挂 TypeIndexing provider,opaque provider 只在 `--parse-opaque-return-type` 下挂,默认关) | +| `swift-section interface` | `SwiftInterfaceBuilder`(+ `--resolve-c-module-names` / `--resolve-moved-type-modules` 挂 `SwiftInterfaceBuilderTypeNameProvider`,两者同开时共用一个,opaque provider 只在 `--parse-opaque-return-type` 下挂,都默认关) | | `swift-section diff --interface` | `SwiftDiffableInterfaceBuilder` ×2 + `SwiftDiffableInterfaceRenderer` | | `swift-section evolution --interface` | `AnySwiftEvolutionInterfaceBuilder`,经 SwiftSectionKit 的 `ABIEvolutionRequest`(与 `--json`/`--summary-only` 互斥;`--emit-available` 打开 `@available` 属性,即 `Report.annotatedInterface(availabilityAttributes:)`:平台名从每个输入的 `LC_BUILD_VERSION` 推断,模拟器变体按对应的设备平台算,`--platform` 可以覆盖;推断不出或输入之间互相冲突时抛 `AvailabilityPlatformInferenceError`,命令行译成 usage 错误,不会悄悄地不发属性) | | `swift-section diff` / `snapshot` / `evolution`(数据路径) | `SwiftDiffableInterfaceBuilder.abiModule()/snapshot()` → SwiftDiffing | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 5037032e..3c9fdbc9 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3579,6 +3579,20 @@ - **验证**:相关测试 43 条全过;全量 22 个目标中只有 `IntegrationTests` 报读不到本机没有的文件(`Xcode-26.3.0.app`、iOS 18.5 模拟器运行时),与基线同类。落地验证见提案决策日志最后一行。 - **对应版本**:未发布(0.26.0 之后)。 +## 2026-11-25 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 + +- **时间段**:2026-11-25,本仓库与 swift-type-indexing 的 `feature/moved-swift-type-modules`。在 JHs-Mac-Studio 上写(swift-type-indexing 在本机编译测试)、在 JHs-Mac-Studio-Ultra 上编译与测试本仓库(沙盒里带 swift-type-indexing 功能分支的拷贝)。 +- **动机**:`CGFloat` 在 SDK 里由 CoreFoundation 声明,二进制里却叫 `CoreGraphics.CGFloat`;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore,二进制仍写 `SwiftUI.View`。原因是 `@_originallyDefinedIn` 让 mangling 永远用旧模块。interface 照 ABI 印出的名字能编过,但和 SDK 对不上。 +- **关键决策**: + - 搬家记录来自 SDK 的文本 `.swiftinterface`(扫描全部模块、只看第 0 列),不经 sourcekitd:sourcekitd 的接口不留属性,也只覆盖二进制直接链接的模块。 + - 是否改写看二进制编译所用的 SDK 版本,按平台取搬家版本(Catalyst 回退 iOS,visionOS 换算 iOS 版本),macOS 14 的 SwiftUI 不改。 + - 打印器新角色 `MovedTypeModuleResolving`,按最外层类型提问,嵌套类型、模块选择器与扩展头都跟着最外层;`__C` 永不参与。 + - 独立开关 `interface --resolve-moved-type-modules`,默认关闭(输出会随宿主 SDK 变化);与 `--resolve-c-module-names` 同开时共用一个 provider 与一个数据库(`SDKTypeNameResolutions`)。dump、diff、snapshot、evolution 不改。 +- **落地模块**:swift-type-indexing 的 `MovedTypeIndex`、`TypeDatabase.declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)`;本仓库 `Sources/Output/SwiftPrinting/`(`MovedTypeModuleResolving`、`NodePrintable`、`TypeNodePrintable`、`SwiftDeclarationPrinter+Headers`)、`Sources/Output/SwiftTypeNameResolution/`(`TypeDatabaseMovedTypeModuleResolver`、`SDKTypeNameResolutions`)、`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift`、`Sources/Executables/swift-section/Commands/InterfaceCommand.swift`。 +- **文档**:提案 [moved-swift-type-modules](../Evolutions/draft-moved-swift-type-modules.md);术语表新增「moved type」;swift-type-indexing 的 `TypeIndexingPipeline.md` 新增「搬家记录」一节;插件 skill 与 `Modules/SwiftInterface.md`。 +- **验证**:见提案决策日志。 +- **对应版本**:未发布;依赖 swift-type-indexing 0.2.0(未发版)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/README.md b/README.md index 03e86d61..463dfca5 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,12 @@ swift-section interface --resolve-c-module-names /path/to/binary # Frameworks with no SDK module (AttributeGraph, …) take user-provided APINotes swift-section interface --resolve-c-module-names --supplementary-apinotes AttributeGraph.apinotes /path/to/binary +# A Swift type the SDK moved to another module (@_originallyDefinedIn) mangles under its old one; +# print it as the SDK declares it (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`, and for a +# binary built with the macOS 15 SDK or later `SwiftUI.View` → `SwiftUICore.View`). +# macOS only; reads the SDK's .swiftinterface files, no sourcekitd. +swift-section interface --resolve-moved-type-modules /path/to/binary + # A C type the binary's own descriptors rename prints under its Swift name everywhere — # declaration, member types, extension headers (`AnyWeakAttribute`, not `__C.AGWeakAttribute`). # c-name prints every C-imported type as the binary mangles it instead. From b87fd8a4026c75f21a036247b663f84cb7bb6ec0 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 15:36:36 +0800 Subject: [PATCH 100/175] docs: record the full-suite run and the finished implementation in the moved-swift-type-modules proposal --- .../Evolutions/draft-moved-swift-type-modules.html | 14 ++++++++++++-- .../Evolutions/draft-moved-swift-type-modules.md | 5 ++++- Documentations/Internal/ProjectEvolutionLog.md | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.html b/Documentations/Evolutions/draft-moved-swift-type-modules.html index b79df8d2..ee83b306 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.html +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.html @@ -474,14 +474,24 @@

    落地步骤

    决策日志

    - 2 条,最近一条:方案取舍(待用户确认) + 13 条,最近一条:实现完成,待用户看过后收尾
    - + + + + + + + + + + +
    日期变更说明
    2026-11-25Created as Draft用户发现 CGFloat 在 SDK 里由 CoreFoundation 声明、二进制里却叫 CoreGraphics,问 swift-type-indexing 能否让输出与 SDK 一致;调研确认能做,用户要求写提案。
    2026-11-25方案取舍(待用户确认)独立开关、默认关闭;按二进制的 SDK 版本判断是否改写;dump 与 diff 类命令不改;RuntimeViewer 不随升级改变行为。
    2026-11-25方案取舍独立开关、默认关闭;按二进制的 SDK 版本判断是否改写;dump 与 diff 类命令不改;RuntimeViewer 不随升级改变行为。用户确认开关做成独立的 --resolve-moved-type-modules。
    2026-11-25Accepted用户批准,开始实现。
    2026-11-25第 1–2 步完成(swift-type-indexing)扫描器与查询落地;单元测试 103 个、SDK 集成测试 7 个通过。另认 #if 指令与限定名属性;swift-type-indexing 0.2.0 未发版,本库经本地兄弟依赖构建。
    2026-11-25第 3 步:扩展头也要改扩展头原本照 mangling 印(extension CoreGraphics.CGFloat),改为最外层类型被认作搬家时走类型打印器;修复前测试红、修复后绿。
    2026-11-25第 4 步:选项集合放顶层嵌套在泛型 provider 里会逼调用方写泛型参数,改为顶层 SDKTypeNameResolutions。
    2026-11-25第 4 步:两条测试的取舍共用数据库那条要跑 sourcekitd、写真实缓存,没写;另一条改名为 providerWithOnlyMovedTypesAnswersNoCImportedQuestion。
    2026-11-25第 5 步:警告措辞只开搬家时不解析依赖镜像,警告按实际打开的开关写。
    2026-11-25第 6 步:真机核对27.2 的 TipKit:SwiftUI.View 全变 SwiftUICore.View(14 处);14.6 的 TipKit 只差 6 行 CGFloat,SwiftUI.View 原样。DeveloperToolsSupport 的 PreviewLayout 改回它自己的模块(14.0 搬家)。插件校验通过。
    2026-11-25全量验证Ultra(Xcode 26.6)2969 个测试、560 个套件全过,退出码 0。
    2026-11-25收尾判断不另写专题文章;新术语 moved type 已登记。
    2026-11-25实现完成,待用户看过后收尾两边功能分支已推送;没有在本地合进 next,因为它按远端版本下限用 swift-type-indexing 0.1.1,合进去会编不过。
    diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.md b/Documentations/Evolutions/draft-moved-swift-type-modules.md index 6091f4af..bc10141e 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.md +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.md @@ -388,7 +388,7 @@ public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies Date: Wed, 25 Nov 2026 15:43:38 +0800 Subject: [PATCH 101/175] build: take swift-type-indexing 0.2.0, the release answering moved Swift types Proposal moved-swift-type-modules. --- .../Evolutions/draft-moved-swift-type-modules.html | 13 ++++++------- .../Evolutions/draft-moved-swift-type-modules.md | 3 ++- Documentations/Internal/ProjectEvolutionLog.md | 2 +- Package.swift | 4 +++- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.html b/Documentations/Evolutions/draft-moved-swift-type-modules.html index ee83b306..88b88e57 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.html +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.html @@ -200,10 +200,8 @@

    摘要

    要你定

    -

    一件事

    -
      -
    1. swift-type-indexing 发 0.2.0 吗?本库的版本下限要等它发版后才能抬到 from: "0.2.0";在那之前本库只能经本地兄弟依赖构建。
    2. -
    +

    没有待定的事

    +

    swift-type-indexing 0.2.0 已发版,本库的版本下限已抬到 from: "0.2.0"。

    已定(用户批准)

    @@ -300,7 +298,7 @@

    改动地图

    SwiftSectionKit/Swift/InterfaceRequest.swift修改resolvesMovedTypeModules 字段、provider 接线与警告子命令逻辑在请求里5 swift-section/Commands/InterfaceCommand.swift修改--resolve-moved-type-modules 与 makeRequest() 一行CLI 只是外壳5 Tests/SwiftSectionKitTests/…、CommandRequestMappingTests.swift修改请求两侧各一条新开关两侧各一测5 - Package.swift修改两个测试目标加依赖;swift-type-indexing 版本下限待 0.2.0 发版后再抬测试要现编小库;用上新 API4 + Package.swift修改两个测试目标加依赖;swift-type-indexing 版本下限抬到 0.2.0测试要现编小库;用上新 API4 AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md修改新开关的说明与陷阱CLI 改动同批改 skill5 Modules/SwiftInterface.md、Modules/SwiftSectionKit.md、Glossary.md、ProjectEvolutionLog.md、CLAUDE.md修改新角色、新开关、术语 moved type、账本一节文档同批6 @@ -474,7 +472,7 @@

    落地步骤

    决策日志

    - 13 条,最近一条:实现完成,待用户看过后收尾 + 14 条,最近一条:swift-type-indexing 0.2.0 发版
    @@ -491,7 +489,8 @@

    决策日志

    - + +
    2026-11-25第 6 步:真机核对27.2 的 TipKit:SwiftUI.View 全变 SwiftUICore.View(14 处);14.6 的 TipKit 只差 6 行 CGFloat,SwiftUI.View 原样。DeveloperToolsSupport 的 PreviewLayout 改回它自己的模块(14.0 搬家)。插件校验通过。
    2026-11-25全量验证Ultra(Xcode 26.6)2969 个测试、560 个套件全过,退出码 0。
    2026-11-25收尾判断不另写专题文章;新术语 moved type 已登记。
    2026-11-25实现完成,待用户看过后收尾两边功能分支已推送;没有在本地合进 next,因为它按远端版本下限用 swift-type-indexing 0.1.1,合进去会编不过。
    2026-11-25实现完成,待用户看过后收尾两边功能分支已推送;当时 next 按远端版本下限用 swift-type-indexing 0.1.1,先不合。
    2026-11-25swift-type-indexing 0.2.0 发版用户同意发版;Xcode 26.6 测试与 CI 通过后打 tag,本库下限抬到 from: "0.2.0"。
    diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.md b/Documentations/Evolutions/draft-moved-swift-type-modules.md index bc10141e..f17a7676 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.md +++ b/Documentations/Evolutions/draft-moved-swift-type-modules.md @@ -124,7 +124,7 @@ Apple 把一些 Swift 类型从一个模块搬进另一个模块时,会给声 | `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | `resolvesMovedTypeModules` 字段与 provider 接线、非 macOS 与无 build version 的警告 | 子命令逻辑在请求里 | 5 | | `Sources/Executables/swift-section/Commands/InterfaceCommand.swift` · `InterfaceCommand` | 修改 | `--resolve-moved-type-modules` 及 `makeRequest()` 一行 | CLI 只是外壳 | 5 | | `Tests/SwiftSectionKitTests/…`、`Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift` | 修改 | 请求两侧各一条 | 新开关两侧各一测(CLAUDE.md) | 5 | -| `Package.swift` | 修改 | 测试目标依赖:`SwiftTypeNameResolutionTests` 加 `SwiftInterface` 与 `SwiftSectionFixtureSupport`,`SwiftSectionKitTests` 加 `SwiftSectionFixtureSupport`;swift-type-indexing 的版本下限待它发 0.2.0 后再抬(见决策日志) | 测试要现编小库;用上新 API | 4 | +| `Package.swift` | 修改 | 测试目标依赖:`SwiftTypeNameResolutionTests` 加 `SwiftInterface` 与 `SwiftSectionFixtureSupport`,`SwiftSectionKitTests` 加 `SwiftSectionFixtureSupport`;swift-type-indexing 的版本下限抬到 `from: "0.2.0"` | 测试要现编小库;用上新 API | 4 | | `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 第 8 节旁加新开关的说明与陷阱(版本判断、默认关闭) | CLI 改动同批改 skill | 5 | | `Documentations/Internal/Modules/SwiftInterface.md`、`Documentations/Internal/Modules/SwiftSectionKit.md`、`Documentations/Glossary.md`、`Documentations/Internal/ProjectEvolutionLog.md`、`CLAUDE.md` 的 SwiftTypeNameResolution 条 | 修改 | 新角色、新开关、术语「moved type」、账本一节 | 文档同批 | 6 | @@ -413,3 +413,4 @@ public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies Date: Wed, 25 Nov 2026 16:03:37 +0800 Subject: [PATCH 102/175] docs: accept the proposal to attribute private CF types to the image exporting their GetTypeID A private Core Foundation type has no SDK header, so `interface --resolve-c-module-names` finds no module for it and prints the bare Swift name its descriptor gives (`CGSVGDocument`). The proposal adds a swift-type-indexing `DeclaredTypeNameSource` that lists the CF types an image exports a `GetTypeID` function for, registered for the root and each direct dependency, so the reference prints as `CoreSVG.CGSVGDocument`. Co-Authored-By: Claude Opus 5.5 --- Documentations/Evolutions/README.md | 1 + .../draft-private-cf-type-modules.html | 438 ++++++++++++++++++ .../draft-private-cf-type-modules.md | 275 +++++++++++ Documentations/README.md | 1 + 4 files changed, 715 insertions(+) create mode 100644 Documentations/Evolutions/draft-private-cf-type-modules.html create mode 100644 Documentations/Evolutions/draft-private-cf-type-modules.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 2d4194ef..b90aa650 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -122,3 +122,4 @@ | [0105](0105-swift-type-indexing-package.md) | 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer(跨仓库唯一提案) | Implemented | | [0106](0106-c-imported-type-name-spelling.md) | C 导入类型的名字统一成 Swift 名,并能切换回 C 名(跨仓库唯一提案,RuntimeViewer 参与) | Implemented | | draft | [被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印(跨仓库唯一提案,swift-type-indexing 参与)](draft-moved-swift-type-modules.md) | In Progress | +| draft | [私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块](draft-private-cf-type-modules.md) | Accepted | diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.html b/Documentations/Evolutions/draft-private-cf-type-modules.html new file mode 100644 index 00000000..b76aa0de --- /dev/null +++ b/Documentations/Evolutions/draft-private-cf-type-modules.html @@ -0,0 +1,438 @@ + + + + + + +Draft - 私有 CF 类型按导出 GetTypeID 的镜像解析所属模块 + + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

    +

    本提案在 SwiftTypeNameResolution 里新增 CFDeclaredTypeNames,它是 swift-type-indexing 的 DeclaredTypeNameSource 的又一个实现:从镜像的导出表里找出每个 …GetTypeID 函数,列出它定义的 CF 类型(_CGSVGDocumentGetTypeID → CGSVGDocumentRef)。SwiftInterfaceBuilderTypeNameProvider 为根镜像和每个直接依赖各登记一个。之后 CGSVGDocumentRef 归到 CoreSVG,引用印成 CoreSVG.CGSVGDocument。打印器、swift-type-indexing 和 CLI 参数都不改。

    +
    + +
    +

    要你定

    +
    +

    两件事

    +
      +
    1. 实现形式:用 swift-type-indexing 现成的 DeclaredTypeNameSource 注册表(提案的做法),而不是在打印器上另注册一个解析器(讨论时最先选的方向)。理由见替代方案第 1 条。
    2. +
    3. 调研第 10 条的 IOSurfaceRef 疑似问题(可能被印成 IOSurface.IOSurface):是否先在 Ultra 上复现,再另行修复。
    4. +
    +
    +
    + +
    +

    架构图

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

    改了什么

    +
    + + + SwiftTypeNameResolution/ + SwiftInterfaceBuilderTypeNameProvider.setup()registers CF(root), then ObjC + CF for each direct dependency + CFDeclaredTypeNames<MachO>exportedSymbols: _<Name>GetTypeID -> "<Name>Ref" + + MachOObjCSection + ObjCDeclaredTypeNames<MachO> + + swift-type-indexing 0.2.0 + TypeDatabase.moduleName(forTypeName:)SDK tables first, then sources in registration order + protocol DeclaredTypeNameSourceimagePath, declaredTypeNames() + + SwiftPrinting + TypeNodePrintable.printType: module + descriptor name + + + + + asks via provider + +
    +

    实线:调用;虚线:遵循协议。swift-type-indexing 与打印器都不改,新来源只是让 moduleName(forTypeName:) 多答出一些名字。

    + +

    一个引用怎么印出来

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

    改动地图

    +
    + + + + + + + + + + + + + +
    文件 / 类型动作改什么为什么步骤
    Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift · CFDeclaredTypeNames新增DeclaredTypeNameSource 的实现:读导出表,…GetTypeID → typedef 名;内部静态函数 typedefNames(forExportedSymbolName:) 承载命名规则私有 CF 类型的模块证据1
    Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift新增命名规则的表驱动测试;现场编译的 C 动态库经 MachOFile 与 MachOImage 两种读法读出的名字规则与两种读法1
    Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98 · setup()修改来源改为「根的 CF,然后每个依赖的 ObjC、CF」;排列抽成 internal 的 static func declaredTypeNameSources(root:dependencies:)登记新来源,顺序可测2
    Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift新增来源顺序;TypeDatabase 按新来源归属模块;用现场编译的 Swift 库验证接口里的拼写端到端证明2
    Sources/Executables/swift-section/Commands/InterfaceCommand.swift:33修改--resolve-c-module-names 的帮助文字补上「依赖导出的 …GetTypeID(CF 类型)」--help 就是文档3
    AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md 第 8 节修改归属来源补上导出的 GetTypeID;加一句私有 CF 类型的效果与 XRef 退路CLI 行为变了,skill 同批更新3
    CLAUDE.md · SwiftTypeNameResolution 一条修改列出 CFDeclaredTypeNames模块清单与代码同步3
    Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案;落地时改编号与状态文档索引0、3
    Documentations/Internal/ProjectEvolutionLog.md修改落地时追加一节演进账本3
    +
    +
    + +
    +

    提议方案

    +
      +
    1. 新增 CFDeclaredTypeNames,与 ObjCDeclaredTypeNames 同形:init(machO:imagePath:),declaredTypeNames() 读 machO.exportedSymbols,每个名为 _<名字>GetTypeID 的导出给出 <名字>Ref;<名字> 以下划线开头的私有函数(__LSASNGetTypeID)同时给出去掉前导下划线的拼写(LSASNRef)。
    2. +
    3. provider 登记它:来源变成「根镜像的 CFDeclaredTypeNames,然后每个直接依赖依次是 ObjCDeclaredTypeNames、CFDeclaredTypeNames」。根镜像排第一,它自己定义的类型由它自己说了算;根镜像不进 moduleFilter,不触发 SourceKit 接口生成。
    4. +
    5. 打印器、swift-type-indexing、CLI 参数都不改,只补帮助文字和 skill 说明。
    6. +
    +

    非目标

    +
      +
    • 跟着重新导出找子框架(LSASNRef → CoreServices):ObjC 来源同样不跟,两边一起做,另开提案。
    • +
    • 间接依赖(CFPhoneNumberRef):放宽到传递闭包会让 SourceKit 接口生成回到几百个模块,另开提案。
    • +
    • 没有 GetTypeID 导出的类型,以及非 CF 的私有 C 类型:二进制里没有可靠的模块证据。
    • +
    • 没有描述符时给出 Swift 名:仍印 模块.XRef。
    • +
    • 根镜像自己的 Objective-C 类、dump、RuntimeViewer 接入(发版后在它那边加一行)、IOSurfaceRef 疑似问题。
    • +
    +
    + +
    +

    详细设计

    +
    + API +
    +
    public struct CFDeclaredTypeNames<MachO: MachORepresentable & Sendable>: DeclaredTypeNameSource {
    +    public let imagePath: String
    +
    +    private let machO: MachO
    +
    +    public init(machO: MachO, imagePath: String)
    +
    +    /// The typedef name of every CF type the image exports a `GetTypeID` function for.
    +    public func declaredTypeNames() async -> [String]
    +
    +    /// `_CGSVGDocumentGetTypeID` → ["CGSVGDocumentRef"], `__LSASNGetTypeID` → ["_LSASNRef", "LSASNRef"].
    +    static func typedefNames(forExportedSymbolName symbolName: String) -> [String]
    +}
    +
    +extension SwiftInterfaceBuilderTypeNameProvider {
    +    static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource]
    +}
    +

    形状照 ObjCDeclaredTypeNames 抄。泛型约束只要 MachORepresentable & Sendable:exportedSymbols 是 MachOKit MachORepresentable 的要求,MachOFile、MachOImage 和包装类型都有,不需要判断读取器种类。协议要求是 async throws,实现不会失败,写成不抛错的 async。

    +
    +
    +
    + 命名规则 +
    +
      +
    1. 导出名必须以一个 _ 开头,去掉它得到 C 函数名;Swift 符号和 Objective-C 符号因为不以 GetTypeID 结尾自然落选。
    2. +
    3. C 函数名以 GetTypeID 结尾,去掉后缀的部分非空、由字母数字和下划线组成、不以数字开头,记为 base。
    4. +
    5. 给出 base + "Ref";base 以下划线开头时,再给出去掉全部前导下划线后的 + "Ref"。
    6. +
    7. CFGetTypeID 给出的 CFRef 这类不是类型的名字不做过滤:只在查询恰好问到它时才命中,而那时 SDK 的归属已经先问过了。
    8. +
    +
    +
    +
    + 性能 +
    +

    TypeDatabase 只在一个名字查不到时才按顺序读下一个来源。根镜像排第一,第一次未命中就会读一遍根镜像的导出表:SwiftUICore 这样的大镜像有数十万个导出。第 3 步在 Ultra 上量一次耗时变化;明显的话,改成直接遍历导出 trie、只取以 GetTypeID 结尾的名字。

    +
    +
    +
    + +
    +

    动机

    +

    按代码推断(没有实跑 CLI):macOS 27.2 的 SwiftUICore 用到私有的 CGSVGDocumentRef,0106 之后印成没有模块的 CGSVGDocument,公开的 CGImageRef 则印成 CoreGraphics.CGImage。读者分不出它来自哪个框架。

    +

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

    +
    + + + + + + + + + + + + +
    私有 CF 类型描述符里的 Swift 名导出 GetTypeID 的镜像用到它的 Swift 镜像
    CGSVGDocumentRefCGSVGDocumentCoreSVGSwiftUICore
    CGColorTransformRef、CGContextDelegateRef去掉 RefCoreGraphicsAppKit
    AGGraphRef、AGSubgraphRefGraph、SubgraphAttributeGraphSwiftUICore、AttributeGraph
    RIOPxrSdfLayerRef 等 9 个去掉 RefCoreRealityIORealityIO
    CAXUIElementRefCAXUIElementCoreAccessibilityCoreAccessibility(自己)
    CFPhoneNumberRefCFPhoneNumberCorePhoneNumbersIDSFoundation
    LSASNRefLSASNLaunchServices(__LSASNGetTypeID)GamePolicyFoundation
    CFXGPUDeviceRef、LXEntryRef、RTIImportOperation_tCFXGPUDevice、LXEntry、ImportOperation找不到VFX、ImageGenerationServices、_USDKit_RealityKit
    +
    +
    + +
    +

    调研

    +
    + 十条查证过的事实 +
    +
      +
    1. 哪些是 CF 类、怎么枚举:ClangImporter 把指向带 objc_bridge 系列 attribute 的 struct 的指针 typedef 导入成 ForeignKind::CFType 的类,并合成 _CFObject 一致性;描述符种类是 class,import info 写着 N<typedef 名> 和 St。ipsw dyld swift --foreign 导出 dyld 预存的 __C 一致性表,按 _CFObject 筛出 66 个 CF 类。
    2. +
    3. 模块不在二进制里:描述符挂在 __C,合成的一致性在 __C_Synthesized。Swift 取顶层 Clang 模块(ClangImporter.cpp:3143-3154),LaunchServices 的类型属于 CoreServices。
    4. +
    5. GetTypeID 的镜像就是模块:46 个公开 CF 类全部一致;私有的 20 个里 17 个能找到导出;Core* 框架约有 190 个不在公开 SDK 里的 …GetTypeID。
    6. +
    7. 打印器已经会用描述符的名字:引用处模块解析后,标识符依次取解析器的 Swift 名、0106 名字表、C 名(TypeNodePrintable.swift:186-268),声明行同理(SwiftDeclarationPrinter+Headers.swift:153-183)。
    8. +
    9. swift-type-indexing 已有开放注册表:DeclaredTypeNameSource,SDK 答不上时按登记顺序读,第一个声明者胜出;这个包自己不读 Mach-O;ObjCDeclaredTypeNames 是现有唯一实现,不含 CF 类型。
    10. +
    11. 去 Ref 规则只认 SDK 里有的名字:私有 CF 类型拿不到解析器给的 Swift 名,走描述符那一档,AGGraphRef 正确地印成 Graph。
    12. +
    13. 现在谁被登记:provider 只给直接依赖登记 ObjC 来源,根镜像不登记;只有 interface --resolve-c-module-names 接上它;RuntimeViewer 自己给打开的每个镜像登记来源。
    14. +
    15. 覆盖面:直接依赖覆盖 14 个,登记根镜像后 15 个;剩下的是重新导出(1)、间接依赖(1)、没有导出(3)。
    16. +
    17. 带 Ref 的名字在 Swift 里不能用:只剩改名用的兼容别名;没有描述符时会印成 CoreSVG.CGSVGDocumentRef。IOSurfaceRef 因为和 ObjC 类 IOSurface 重名而保留 Ref。
    18. +
    19. 顺带发现、未验证:去 Ref 规则不看重名,而打印器先问解析器,__C.IOSurfaceRef 可能被印成 IOSurface.IOSurface。
    20. +
    +
    +
    +
    + +
    +

    替代方案

    +
    + 六条被否或推迟的方向 +
    +
      +
    1. 打印器上另注册一个 ModuleNameResolving:否。注册表已经在 swift-type-indexing,另写一个要么抄一遍规则,要么与 TypeDatabase 给出不同答案;RuntimeViewer 也走 DeclaredTypeNameSource。
    2. +
    3. 让 swift-type-indexing 自己读导出表:否,那个包按设计不读 Mach-O。
    4. +
    5. 从 CF 运行时类注册取名字:否,要反汇编调用点,结果与导出表等价,名字还是显示名。
    6. +
    7. 用一致性符号里的模块:否,那是声明一致性的模块,不是类型的模块。
    8. +
    9. 让去 Ref 规则也认运行时名表:否,会把 IOSurfaceRef 改成 IOSurface,还会把 Graph 改坏成 AGGraph。
    10. +
    11. 跟着重新导出算进伞框架:推迟,与 ObjC 来源一起另开提案。
    12. +
    +
    +
    +
    + +
    +

    影响

    +
      +
    • 源码兼容性:纯新增,provider 的公开接口不变;--resolve-c-module-names 下私有 CF 类型会带上模块。
    • +
    • ABI:不适用,SPM 源码分发。
    • +
    • 下游:InterfaceRequest 自动受益;没有基线开着 __C 模块解析,渲染 A/B 不受影响;RuntimeViewer 要在 RuntimeSwiftSection.swift:2013 加一行才受益;MachOKitUI、SymbolViewer 不受影响。
    • +
    • API 演进:没有被替代的旧 API,按 minor 版本发布。
    • +
    +
    + +
    +

    落地步骤

    +
      +
    1. 提案落盘、登记索引(本次)
    2. +
    3. CFDeclaredTypeNames 与测试:exportedTypeIDFunctionNamesItsTypedef、underscoredTypeIDFunctionNamesBothSpellings、otherExportsNameNothing、readsACompiledLibrarysExportsThroughBothReaders
    4. +
    5. provider 登记、端到端验证:sourcesListTheRootFirstThenEachDependencyObjCBeforeCF、typeDatabaseAttributesAnExportedCFTypeToItsImage、interfacePrintsAPrivateCFTypeUnderItsDeclaringModule、interfaceKeepsTheBareSwiftNameWithoutTheSource
    6. +
    7. 文档与系统镜像验证:在 Ultra 上对 SwiftUICore、AppKit、RealityIO 跑 interface --resolve-c-module-names,确认四个代表类型的拼写并量耗时;测试一律在 Ultra 上跑
    8. +
    +
    + +
    +

    决策日志

    +
    + 2 条,最近一条:实现放在本仓库,形式是 DeclaredTypeNameSource(待确认) +
    +
    + + + + + + +
    日期变更说明
    2026-11-25Created as Draft起因是想知道 Swift 用到的私有 CF 类能否还原原名。调研发现 Swift 名 0106 已经从描述符取得,缺的是模块;定义 CF 类型的框架都导出 GetTypeID,46 个公开类型验证全对。
    2026-11-25实现放在本仓库,形式是 DeclaredTypeNameSource用户选定放在本仓库、不改 swift-type-indexing。用户设想的开放注册表已经以 DeclaredTypeNameSource 存在,因此不再另写打印器解析器;此项待用户确认。
    +
    +
    +
    +
    + +
    +
    + + diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.md b/Documentations/Evolutions/draft-private-cf-type-modules.md new file mode 100644 index 00000000..052da42b --- /dev/null +++ b/Documentations/Evolutions/draft-private-cf-type-modules.md @@ -0,0 +1,275 @@ +# Draft - 私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-25 +- **最后更新**: 2026-11-25 +- **所属愿景**: 无 +- **关联提案**: [0105 swift-type-indexing-package](0105-swift-type-indexing-package.md)(`__C` 类型按 SDK 解析模块,`DeclaredTypeNameSource` 就是它定下的接口);[0106 c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md)(引用处改用描述符给的 Swift 名,本提案补上它缺的模块) +- **实现分支 / PR**: `feature/private-cf-type-modules`(worktree `.worktrees/MachOSwiftSection-PrivateCFTypeModules`),叠在本地 `next` 上:那里有 `feature/moved-swift-type-modules` 的本地合并、尚未推到 `origin/next`,它同样改了 `SwiftInterfaceBuilderTypeNameProvider.swift` +- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 +- **网页版**: 同目录同名的 `.html` +- **涉及仓库**: 只有 MachOSwiftSection。RuntimeViewer 自己登记类型名来源,要它也受益需要一行后续改动(见「非目标」) + +## 摘要 + +`swift-section interface --resolve-c-module-names` 能把公开的 C 导入类型写到真实模块下(`__C.CGColorRef` → `CoreGraphics.CGColor`),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(`CGSVGDocument`)。本提案在 `SwiftTypeNameResolution` 里新增 `CFDeclaredTypeNames`,它是 swift-type-indexing 的 `DeclaredTypeNameSource` 的又一个实现:从镜像的导出表里找出每个 `…GetTypeID` 函数,列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`)。`SwiftInterfaceBuilderTypeNameProvider` 为根镜像和每个直接依赖各登记一个。之后 `CGSVGDocumentRef` 归到 CoreSVG,引用印成 `CoreSVG.CGSVGDocument`。打印器、swift-type-indexing 和 CLI 参数都不改。 + +## 动机 + +**现象**(按代码推断,没有实跑 CLI):macOS 27.2 的 SwiftUICore 用到私有的 `CGSVGDocumentRef`。0106 之后,`interface --resolve-c-module-names` 把它的引用印成 `CGSVGDocument`,没有模块;公开的 `CGImageRef` 则印成 `CoreGraphics.CGImage`。同一份接口里,读者分不出 `CGSVGDocument` 来自哪个框架,也无从知道它和另一个镜像里同名的类型是不是同一个。 + +**规模**:macOS 27.2 的 dyld shared cache 里,被 Swift 代码用到的 CF 类一共 66 个,其中 20 个不在公开 SDK 的头文件里(测法见「前期调研」第 1 条): + +| 私有 CF 类型(typedef 名) | 描述符里的 Swift 名 | 导出 `GetTypeID` 的镜像 | 用到它的 Swift 镜像 | +|---|---|---|---| +| `CGSVGDocumentRef` | `CGSVGDocument` | CoreSVG | SwiftUICore | +| `CGColorTransformRef`、`CGContextDelegateRef` | 去掉 `Ref` | CoreGraphics | AppKit | +| `AGGraphRef`、`AGSubgraphRef` | `Graph`、`Subgraph` | AttributeGraph | SwiftUICore、AttributeGraph | +| `RIOPxrSdfLayerRef` 等 9 个 `RIO…Ref` | 去掉 `Ref` | CoreRealityIO | RealityIO | +| `CAXUIElementRef` | `CAXUIElement` | CoreAccessibility | CoreAccessibility(自己) | +| `CFPhoneNumberRef` | `CFPhoneNumber` | CorePhoneNumbers | IDSFoundation | +| `LSASNRef` | `LSASN` | LaunchServices(导出名 `__LSASNGetTypeID`) | GamePolicyFoundation | +| `CFXGPUDeviceRef`、`LXEntryRef`、`RTIImportOperation_t` | `CFXGPUDevice`、`LXEntry`、`ImportOperation` | 找不到 | VFX、ImageGenerationServices、_USDKit_RealityKit | + +这些类型的 Swift 名 0106 已经能从描述符里读出来,缺的只有模块。模块不在二进制里(第 2 条),但定义 CF 类型的框架几乎都会导出一个 `<名字>GetTypeID` 函数,用公开类型验证,这个对应关系 46 个全对(第 3 条)。 + +## 前期调研 + +1. **哪些是 CF 类,怎么枚举。** ClangImporter 把指向带 `objc_bridge` / `objc_bridge_mutable` / `objc_bridge_related` 的 struct 的指针 typedef 当作 CF 类型(`swift/lib/ClangImporter/CFTypeInfo.cpp:75-78`),导入成 `ForeignKind::CFType` 的类,并合成一条 `_CFObject` 一致性(`swift/lib/ClangImporter/ImportDecl.cpp` 的 `importCFClassType`,`addSynthesizedProtocolAttrs(theClass, {KnownProtocolKind::CFObject})`)。它的类型描述符种类是 class,名字后的 import info 写着 `N` 和 `St`(来自 C typedef,`swift/include/swift/ABI/TypeIdentity.h:41-55`、`swift/lib/IRGen/GenMeta.cpp:1585-1608`)。dyld 在 cache 里预存了所有 `__C` 类型一致性的表,`ipsw dyld swift --foreign ` 能导出,键是「typedef 名 + `St`」;按协议 `_$s14CoreFoundation9_CFObjectMp` 筛出的就是被 Swift 用过的全部 CF 类。macOS 27.2:66 个,20 个私有(「动机」那张表),46 个公开。 +2. **模块不在二进制里。** CF 类的描述符挂在 `__C` 模块下,`_CFObject` 等合成的一致性在 `__C_Synthesized`(mangling 里的 `SC`),都不带真实模块。Swift 给一个 Clang 声明定模块时取的是**顶层** Clang 模块(`swift/lib/ClangImporter/ClangImporter.cpp:3143-3154`,注释写明 submodule 没有自己的 `ClangModuleUnit`),所以 LaunchServices 里的类型在 Swift 里属于 CoreServices(SDK 的 `CoreServices.framework/Modules/module.modulemap:43` 把 LaunchServices 声明成 CoreServices 的 submodule)。 +3. **`GetTypeID` 的镜像就是模块。** 对 46 个公开 CF 类逐个查 `_<去掉 Ref 的名字>GetTypeID` 由 cache 里哪个镜像导出(`ipsw dyld symaddr`),再和 SDK 里声明它的框架比,46 个全部一致;其中 `IOSurfaceRef` 在 CoreGraphics 的头文件里有一份前向声明,真正的声明在 IOSurface,导出镜像也是 IOSurface。私有的 20 个里有 17 个能这样找到镜像,`CFXGPUDeviceRef`、`LXEntryRef`、`RTIImportOperation_t` 找不到对应的导出。Core* 框架一共导出约 190 个公开 SDK 里没有的 `…GetTypeID`(CoreMedia 75、CoreRealityIO 41、CoreGraphics 23、CoreSVG 16、CoreFoundation 12),并不是每个都对应 Swift 用到的类型。 +4. **打印器在模块解析出来以后已经会用描述符的名字。** 引用处 `TypeNodePrintable.printType`(`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift:186-268`):模块经 `resolvedModuleName(of:siblingIdentifier:)`(`NodePrintable.swift:186-196`,先按 C 名查,再按去掉 `Ref` 的名字查)解析;标识符依次取解析器的 `swiftName(forCName:category:)`、0106 名字表里描述符给的名字、C 名。声明行 `declaredTypeName(of:)`(`SwiftDeclarationPrinter+Headers.swift:153-183`)同样在解析器给不出 Swift 名时退回描述符的名字。所以只要模块查得到,私有 CF 类型就会印成 `CoreSVG.CGSVGDocument`,打印器不用改。 +5. **swift-type-indexing 已有开放的注册表。** 0.2.0 的 `DeclaredTypeNameSource`(`Sources/TypeIndexing/DeclaredTypeNameSource.swift`):一个依赖镜像报出它声明的类型名,`TypeDatabase.moduleName(forTypeName:)` 只在模块接口和 API notes 都没有这个名字时,才按登记顺序一个个读这些来源,第一个声明了它的镜像胜出,模块名取自 `TypeDatabase.moduleName(forImagePath:)`(镜像文件名去掉扩展名与 `libswift` 前缀)。文档写明这个包自己不读 Mach-O。MachOObjCSection 0.8.209 的 `ObjCDeclaredTypeNames`(`Sources/ObjCTypeIndexing/ObjCDeclaredTypeNames.swift`)是现在唯一的实现,报出类、协议、struct 和 union 名,不含 CF 类型。 +6. **TypeDatabase 的 CF 去 `Ref` 规则只认 SDK 里有的名字。** `TypeDatabase.swiftName(forCName:category:)` 在 API notes 没有改名时,只有去掉 `Ref` 的名字出现在模块接口或 API notes 的归属表里才返回它,运行时登记的名字不算。私有 CF 类型因此拿不到解析器给的 Swift 名,走第 4 条里描述符那一档,`AGGraphRef` 正确地印成 `Graph` 而不是 `AGGraph`。 +7. **现在谁被登记。** `SwiftInterfaceBuilderTypeNameProvider.setup()`(`Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98`)只给每个**直接**依赖登记一个 `ObjCDeclaredTypeNames`,根镜像自己不登记。只取直接依赖是有意的(`Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift:9-19`:每个依赖模块都要生成一份 SourceKit 接口,传递闭包有几百个镜像)。CLI 里只有 `interface --resolve-c-module-names` 会接上它(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:273-320`),依赖按本机 dyld cache 解析。RuntimeViewer 不经这个 provider,它在 `RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/Swift/RuntimeSwiftSection.swift:2013` 给自己打开的每个镜像登记一个 `ObjCDeclaredTypeNames`。 +8. **按这个设计能覆盖多少。** 对「动机」表里的 20 个查使用方的直接依赖(`dyld_info -dependents`):CoreSVG、CoreGraphics、AttributeGraph、CoreRealityIO 都是使用方的直接依赖,覆盖 14 个;`CAXUIElementRef` 由使用方自己定义,登记根镜像后覆盖,共 15 个。剩下 5 个:`LSASNRef` 的导出在 LaunchServices,使用方只直接链接重新导出它的 CoreServices;`CFPhoneNumberRef` 的 CorePhoneNumbers 不是 IDSFoundation 的直接依赖;另外 3 个没有对应的导出。 +9. **带 `Ref` 的名字在 Swift 里不能用。** ClangImporter 只在 Swift 3 及以后的名字里去掉 `Ref`(`swift/lib/ClangImporter/ImportName.cpp:2269-2277` 的 `swift3OrLaterName`),带 `Ref` 的拼写只剩一个改名用的兼容别名。所以一个私有 CF 类型如果在本镜像里没有描述符(只出现在符号签名里),模块解析出来以后会印成 `CoreSVG.CGSVGDocumentRef`,能读懂,但不是能编译的写法。去掉 `Ref` 时还要避开重名:`IOSurfaceRef` 的描述符名字就是 `IOSurfaceRef`,因为 IOSurface 里已有同名的 Objective-C 类 `IOSurface`(`hasNamingConflict`)。 +10. **顺带发现、未验证(推测)**:第 6 条的去 `Ref` 规则不看重名,而打印器先问解析器、后用描述符。若一个二进制链接了 IOSurface,`__C.IOSurfaceRef` 在 `--resolve-c-module-names` 下可能被印成 `IOSurface.IOSurface`,正确写法是 `IOSurface.IOSurfaceRef`。这与本提案无关,要在 Ultra 上复现后另行处理。 + +## 提议方案 + +1. **新增 `CFDeclaredTypeNames`**(`Sources/Output/SwiftTypeNameResolution/`),实现 `DeclaredTypeNameSource`,与 `ObjCDeclaredTypeNames` 同形:`init(machO:imagePath:)`,`declaredTypeNames()` 读 `machO.exportedSymbols`,每个名为 `_<名字>GetTypeID` 的导出给出 `<名字>Ref`;`<名字>` 以下划线开头的私有函数(`__LSASNGetTypeID`)同时给出去掉前导下划线的拼写(`LSASNRef`)。 +2. **provider 登记它**:`setup()` 交给 `TypeDatabase.index(dependencies:moduleFilter:)` 的来源变成「根镜像的 `CFDeclaredTypeNames`,然后每个直接依赖依次是 `ObjCDeclaredTypeNames`、`CFDeclaredTypeNames`」。根镜像排第一,因为它自己定义的类型由它自己说了算;根镜像不进 `moduleFilter`,不触发 SourceKit 接口生成。来源的排列抽成一个可测的静态函数。 +3. **打印器、swift-type-indexing、CLI 参数都不改**。效果全部经现有路径体现:`moduleName(forTypeName:)` 多答出一些名字,打印器按调研第 4 条的规则写成 `模块.描述符名`。`--resolve-c-module-names` 的帮助文字和 swift-section skill 的说明补一句来源。 + +### 非目标 + +- **跟着重新导出找子框架**(`LSASNRef` → CoreServices):`ObjCDeclaredTypeNames` 同样不跟重新导出,两种来源应该一起做;MachOKitExtensions 3.3.0 的 `DependencyTraversal` 也只有 `direct` / `transitive`(`DependencyClosure.swift:6-11`)。另开提案。 +- **间接依赖**(`CFPhoneNumberRef`):放宽到传递闭包会让 SourceKit 接口生成回到几百个模块(调研第 7 条)。要做也应该只给运行时来源放宽、不动 `moduleFilter`,另开提案。 +- **没有 `GetTypeID` 导出的类型**(`CFXGPUDeviceRef` 等 3 个),以及非 CF 的私有 C 类型(struct、enum、`swift_wrapper` typedef,如 `AGTreeElement`):二进制里没有可靠的模块证据。 +- **没有描述符时给出 Swift 名**:仍印 `模块.XRef`(调研第 9 条)。要改得让 TypeDatabase 的去 `Ref` 规则认运行时名表,会碰上重名与 `swift_name` 改名(见「替代方案」第 5 条)。 +- **根镜像自己的 Objective-C 类**:现在也没登记,是另一个问题,本提案不顺手改,免得 ObjC 输出跟着变。 +- **`dump`**:`dump` 不做 `__C` 模块解析,本提案不引入。 +- **RuntimeViewer 接入**:本库发版后,在 `RuntimeSwiftSection.swift:2013` 的 `metadataSources` 里加一个 `CFDeclaredTypeNames`,属于 RuntimeViewer 的改动。 +- **调研第 10 条的 `IOSurfaceRef` 疑似问题**:先复现,另行修复。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift` · `CFDeclaredTypeNames` | 新增 | `DeclaredTypeNameSource` 的实现:读导出表,`…GetTypeID` → typedef 名;内部静态函数 `typedefNames(forExportedSymbolName:)` 承载命名规则 | 私有 CF 类型的模块证据 | 1 | +| `Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift` | 新增 | 命名规则的表驱动测试;现场编译的 C 动态库经 `MachOFile` 与 `MachOImage` 两种读法读出的名字 | 规则与两种读法 | 1 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98` · `setup()` | 修改 | 来源改为「根的 CF,然后每个依赖的 ObjC、CF」;排列抽成 `static func declaredTypeNameSources(root:dependencies:)`(internal) | 登记新来源,顺序可测 | 2 | +| `Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift` | 新增 | 来源顺序;`TypeDatabase` 按新来源归属模块;用现场编译的 Swift 库验证接口里的拼写 | 端到端证明 | 2 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift:33` · `resolveCModuleNames` 的 `help` | 修改 | 来源列表补上「依赖导出的 `…GetTypeID`(CF 类型)」 | `--help` 就是文档 | 3 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` 第 8 节 | 修改 | 「没有 sourcekitd 时由 API notes 与 Objective-C 元数据归属」补上导出的 `GetTypeID`;加一句私有 CF 类型的效果与第 9 条的 `XRef` 退路 | CLI 行为变了,skill 同批更新 | 3 | +| `CLAUDE.md` · SwiftTypeNameResolution 一条 | 修改 | 列出 `CFDeclaredTypeNames` | 模块清单与代码同步 | 3 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案;落地时改编号与状态 | 文档索引 | 0、3 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时追加一节 | 演进账本 | 3 | + +## 架构图 + +改了什么: + +```text +SwiftTypeNameResolution/ ++ CFDeclaredTypeNames DeclaredTypeNameSource ++ declaredTypeNames() machO.exportedSymbols: _GetTypeID -> "Ref" +~ SwiftInterfaceBuilderTypeNameProvider.setup() +~ TypeDatabase.index(dependencies: ++ [CFDeclaredTypeNames(root), + ObjCDeclaredTypeNames(dependency1), ++ CFDeclaredTypeNames(dependency1), + ObjCDeclaredTypeNames(dependency2), ++ CFDeclaredTypeNames(dependency2), ...], + moduleFilter: dependency module names) unchanged: root never generates an interface + +swift-type-indexing 0.2.0 (unchanged) + TypeDatabase.moduleName(forTypeName:) + 1. module interfaces, API notes + 2. runtime declared names, folded source by source in registration order + +SwiftPrinting (unchanged) + TypeNodePrintable.printType + module <- moduleName(forTypeName: C name, then Ref-stripped) + identifier <- swiftName(forCName:) ?? descriptor name (0106) ?? C name +``` + +一个引用怎么印出来(SwiftUICore 里的 `__C.CGSVGDocumentRef`): + +```text +printType(__C.CGSVGDocumentRef) +├─ swiftNameFromDescriptor -> "CGSVGDocument" (0106 name table) +├─ resolvedModuleName(__C, "CGSVGDocumentRef") +│ └─ SwiftInterfaceBuilderTypeNameProvider.moduleName +│ └─ TypeDatabase.moduleName +│ ├─ SDK tables miss +│ ├─ CFDeclaredTypeNames(SwiftUICore) miss (+) +│ ├─ ObjCDeclaredTypeNames(AttributeGraph) miss +│ ├─ CFDeclaredTypeNames(AttributeGraph) miss (+) +│ ├─ ... +│ └─ CFDeclaredTypeNames(CoreSVG): "CGSVGDocumentRef" -> "CoreSVG" (+) +├─ swiftName(forCName: "CGSVGDocumentRef") -> nil (no API notes, not SDK-indexed) +└─ writes CoreSVG . CGSVGDocument +``` + +## 详细设计 + +### API + +```swift +#if os(macOS) + +import MachOKit +import TypeIndexing + +/// The Core Foundation types an image defines, as swift-type-indexing's `TypeDatabase` reads +/// them: one for every `…GetTypeID` function the image exports. +/// +/// A CF type's Swift metadata names the type but never its module — the descriptor sits in +/// `__C` — while the framework defining it exports the type's `GetTypeID` function. Registered +/// beside `ObjCDeclaredTypeNames`, this attributes a private CF type such as `CGSVGDocumentRef` +/// to the image exporting `CGSVGDocumentGetTypeID` (`CoreSVG`). `TypeDatabase` consults it only +/// for names neither the SDK's module interfaces nor its API notes attribute, and reads the +/// image's exports only on such a miss. +/// +/// ```swift +/// let sources: [any DeclaredTypeNameSource] = dependencyImages.flatMap { image in +/// [ +/// ObjCDeclaredTypeNames(machO: image, imagePath: image.imagePath), +/// CFDeclaredTypeNames(machO: image, imagePath: image.imagePath), +/// ] +/// } +/// ``` +public struct CFDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + private let machO: MachO + + /// - Parameters: + /// - machO: The image, in this process or in a file. + /// - imagePath: Its install path, which names the module its types are attributed to + /// (`…/CoreSVG.framework/Versions/A/CoreSVG` → `CoreSVG`). + public init(machO: MachO, imagePath: String) { + self.machO = machO + self.imagePath = imagePath + } + + /// The typedef name of every CF type the image exports a `GetTypeID` function for. + public func declaredTypeNames() async -> [String] { + machO.exportedSymbols.flatMap { exportedSymbol in + Self.typedefNames(forExportedSymbolName: exportedSymbol.name) + } + } + + /// The typedef names an exported symbol implies: `_CGSVGDocumentGetTypeID` → + /// `["CGSVGDocumentRef"]`, the private `__LSASNGetTypeID` → `["_LSASNRef", "LSASNRef"]`, + /// any other symbol → `[]`. + static func typedefNames(forExportedSymbolName symbolName: String) -> [String] +} + +#endif +``` + +形状照 `ObjCDeclaredTypeNames` 抄:同样的 `init(machO:imagePath:)`、同样的 `imagePath` 属性、同样放在 `#if os(macOS)` 里,名字按「来源 + `DeclaredTypeNames`」对称。泛型约束只要 `MachORepresentable & Sendable`:`exportedSymbols` 是 MachOKit `MachORepresentable` 的要求(`Sources/MachOKit/Protocol/MachORepresentable.swift:124-129`),`MachOFile`、`MachOImage` 和包装类型都有,不需要判断读取器种类。provider 的 `MachO` 约束经 `MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache: MachORepresentable, Sendable` 满足它。协议要求是 `async throws`,实现不会失败,所以写成不抛错的 `async`。 + +### 命名规则 + +1. 导出名必须以一个 `_` 开头(C 符号的 Mach-O 前缀),去掉它得到 C 函数名;Swift 符号(`_$s…`)和 Objective-C 符号(`_OBJC_…`)因为不以 `GetTypeID` 结尾自然落选。 +2. C 函数名以 `GetTypeID` 结尾,去掉后缀的部分非空、由字母数字和下划线组成、不以数字开头,记为 `base`。 +3. 给出 `base + "Ref"`;`base` 以下划线开头时,再给出去掉全部前导下划线后的 `+ "Ref"`(非空才给)。 +4. 会产生一些不是类型的名字,例如 `CFGetTypeID` 给出 `CFRef`。它们只在某个查询恰好问到这个名字时才会命中,而那时 SDK 的归属已经先问过了,所以无害,不做过滤。 + +### 来源的排列 + +```swift +extension SwiftInterfaceBuilderTypeNameProvider { + /// The declared-type-name sources `setup()` registers, in the order `TypeDatabase` folds + /// them: the root's CF types first — a type the root defines is its own — then each direct + /// dependency's Objective-C names and CF types, in dependency order. + static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource] +} +``` + +`setup()` 只把 `dependencies:` 参数换成这个函数的结果,`moduleFilter` 不变。 + +### 性能 + +`TypeDatabase` 只在一个名字查不到时才按顺序读下一个来源,读过的来源不再读。根镜像排第一,所以第一次未命中就会读一遍根镜像的导出表:SwiftUICore 这样的大镜像有数十万个导出,`exportedSymbols` 要建一个同样大的数组。第 3 步在 Ultra 上量一次 `interface --resolve-c-module-names` 的耗时变化;如果明显,改成直接遍历导出 trie、只取以 `GetTypeID` 结尾的名字。 + +## 替代方案考量 + +1. **在打印器上新注册一个 `ModuleNameResolving` 解析器**(讨论时最先选的方向,仍在本仓库):否。swift-type-indexing 已经有 `DeclaredTypeNameSource` 这个注册表,「SDK 优先、按依赖顺序折叠、第一个声明者胜出、镜像路径换模块名」都在那里。另写一个解析器要么把这些规则抄一遍,要么和 `TypeDatabase` 对同一个名字给出不同答案,谁胜出取决于注册顺序。RuntimeViewer 也是经 `DeclaredTypeNameSource` 接入的,走同一个接口它只需加一行。 +2. **让 swift-type-indexing 自己读导出表**:否。那个包按设计不读 Mach-O(`DeclaredTypeNameSource.swift` 的文档),读二进制的部分都由实现方提供。 +3. **从 CF 运行时类注册取类型名**(`_CFRuntimeRegisterClass` 的 `CFRuntimeClass.className`):否。要反汇编调用点才能找到参数,得到的仍然只是「哪个镜像定义了它」,和导出表等价;而且 `className` 是 `"CGSVGDocument"` 这样的显示名,不是 mangling 用的 typedef 名。 +4. **用一致性符号里的模块**(`_$sSo10AGGraphRefaSQ14AttributeGraphMc`):否。那是声明这条一致性的模块,不是类型的模块;合成的一致性在 `__C_Synthesized`;cache 里的这类本地符号大多被剥掉了。 +5. **让 TypeDatabase 的去 `Ref` 规则也认运行时名表**,好在没有描述符时也给出 Swift 名:否。它不知道重名,会把 `IOSurfaceRef` 改成 `IOSurface`(调研第 9 条);而打印器先问解析器、后用描述符,它还会把 `swift_name` 改过的 `AGGraphRef` 从 `Graph` 改坏成 `AGGraph`。 +6. **跟着 `LC_REEXPORT_DYLIB` 把子框架的导出算进伞框架**:推迟,见「非目标」第一条。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增:多一个公开类型 `CFDeclaredTypeNames`,`SwiftInterfaceBuilderTypeNameProvider` 的公开接口不变。行为上,`--resolve-c-module-names` 下原本没有模块的私有 CF 类型会带上模块。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftSectionKit` 的 `InterfaceRequest` 经 provider 自动受益,不用改代码。没有基线或快照测试开着 `__C` 模块解析(它要 SDK),渲染 A/B 校验不受影响。 +- RuntimeViewer:它不经 provider,自己在 `RuntimeSwiftSection.swift:2013` 登记来源,本提案落地不改变它的输出。要受益,等本库发版后在那里加一个 `CFDeclaredTypeNames`(见「非目标」)。 +- MachOKitUI、SymbolViewer:不用 `SwiftTypeNameResolution`,不受影响。 + +### 文档与示例 + +`swift-section interface --help` 里 `--resolve-c-module-names` 的说明、swift-section skill 第 8 节、`CLAUDE.md` 的模块清单,都在第 3 步同批更新。 + +## API 演进与废弃策略 + +- 没有被替代的旧 API,不需要废弃期。 +- 纯新增,按 minor 版本发布。 + +## 落地步骤 + +0. **提案落盘、登记索引**(本次)—— 改动地图最后两行中的索引部分 +1. **`CFDeclaredTypeNames` 与它的测试** —— 改动地图第 1、2 行 + - 行为:`exportedTypeIDFunctionNamesItsTypedef`(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`) + - 行为:`underscoredTypeIDFunctionNamesBothSpellings`(`__LSASNGetTypeID` → `_LSASNRef`、`LSASNRef`) + - 行为:`otherExportsNameNothing`(`_CGSVGDocumentCreate`、`_GetTypeID`、`_$s…`、`_OBJC_CLASS_$_…` → 空) + - 行为:`readsACompiledLibrarysExportsThroughBothReaders`(用 `FixtureCompiler` 现场编译一个导出 `ProbeWidgetGetTypeID`、`_ProbeSecretGetTypeID`、`ProbeWidgetCreate` 的 C 动态库,`MachOFile` 与 `dlopen` 后的 `MachOImage` 读出同样的名字) +2. **provider 登记新来源,端到端验证** —— 改动地图第 3、4 行 + - 行为:`sourcesListTheRootFirstThenEachDependencyObjCBeforeCF` + - 行为:`typeDatabaseAttributesAnExportedCFTypeToItsImage`(`TypeDatabase` 只登记第 1 步的 C 库、`moduleFilter` 不选任何模块,`moduleName(forTypeName: "ProbeWidgetRef") == "ProbeCF"`) + - 行为:`interfacePrintsAPrivateCFTypeUnderItsDeclaringModule`(一个用桥接头引入 `CF_BRIDGED_TYPE(id)` 的 `ProbeWidgetRef`、在公开 struct 里存它的 Swift 库,接口里的字段类型印成 `ProbeCF.ProbeWidget`;先断言这个库确实带着 `ProbeWidgetRef` 的描述符) + - 行为:`interfaceKeepsTheBareSwiftNameWithoutTheSource`(同一个库、不登记来源时仍是 0106 的 `ProbeWidget`) + - 现场编译用 `FixtureCompiler`;它给不出桥接头的路径时,照 `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift` 的写法,并把这个能力缺口记进 shared-macho-testing-support 提案 +3. **文档与系统镜像验证** —— 改动地图第 5–9 行 + - 在 Ultra 上对本机 cache 的 SwiftUICore、AppKit、RealityIO 跑 `interface --resolve-c-module-names`,确认 `CoreSVG.CGSVGDocument`、`AttributeGraph.Graph`、`CoreGraphics.CGColorTransform`、`CoreRealityIO.RIOPxrSdfLayer`,并量耗时变化(详细设计「性能」),结果记进本提案 + - 测试一律在 Ultra 上跑(公司那台不跑本库的测试),`--filter` 同时带 `--skip IntegrationTests` + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:调用方契约都在 `CFDeclaredTypeNames` 的文档注释里,维护要知道的「为什么只取直接依赖、为什么不认运行时名表去 `Ref`」在本提案里。 +- **有没有引入新术语** —— 预计没有。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-25 | Created as Draft | 起因是想知道 Swift 用到的私有 CF 类能否还原原名(`__C.CGSVGDocumentRef` → `CoreSVG.CGSVGDocument`)。调研发现 Swift 名 0106 已经从描述符取得,缺的是模块;定义 CF 类型的框架都导出 `GetTypeID`,46 个公开类型验证全对。 | +| 2026-11-25 | 实现放在本仓库,形式是 `DeclaredTypeNameSource` | 用户选定放在本仓库、不改 swift-type-indexing。调研发现用户设想的「类型索引开放注册表、各库注册自己的内容」已经以 `DeclaredTypeNameSource` 存在,ObjC 侧就是这样接入的,因此不再另写打印器解析器(替代方案第 1 条)。用户确认这个形式。 | +| 2026-11-25 | `IOSurfaceRef` 疑似问题先复现 | 用户定:先在 Ultra 上复现调研第 10 条,确认是真的再按 bug 修复另走一批,不并入本提案。 | +| 2026-11-25 | 用户批准,开始实现 | 轻量档,用户看过简报后批准。功能分支从本地 `next` 切,因为 moved-swift-type-modules 的本地合并也改了 provider 的 `setup()`,从 `origin/next` 切会在合回时冲突。 | diff --git a/Documentations/README.md b/Documentations/README.md index 98201333..7519969e 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -226,6 +226,7 @@ selects names using each access's offset and width. | [Evolutions/0105-swift-type-indexing-package.md](Evolutions/0105-swift-type-indexing-package.md) | **提案 0105(Implemented,跨仓库)**:`TypeIndexing` 搬进独立包 swift-type-indexing(SDK 的模块接口与 API notes 索引,按 SDK 版本缓存),本仓库只留适配层 `SwiftTypeNameResolution`;同时修 API notes 改名规则与只装 Command Line Tools 时找不到 sourcekitd。MachOObjCSection 0.8.209 按 API notes 在头文件里标 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT`(swift-semantic-string 0.7.0 的宏色),RuntimeViewer 把 `__C.X` 打印成模块限定的 Swift 名 | | [Evolutions/0106-c-imported-type-name-spelling.md](Evolutions/0106-c-imported-type-name-spelling.md) | **提案 0106(Implemented,跨仓库,RuntimeViewer 参与)**:C 导入类型的名字统一成 Swift 名——声明、成员类型与扩展头一致写描述符给的 Swift 名(解析器找得到模块就带模块,否则写裸名),`CImportedTypeNameSpelling.cName` 一律写 mangled 的 C 名;ABI 名以描述符名字结尾的不信(导入成成员的类型退回 C 名)。`marksCImportedTypeNames` 在名字上标出另一种写法,RuntimeViewer 据此在声明行尾画可点击的标签、切换全局选项;`swift-section interface --c-imported-type-name-spelling` | | [Evolutions/draft-moved-swift-type-modules.md](Evolutions/draft-moved-swift-type-modules.md) | **提案 draft(In Progress,跨仓库,swift-type-indexing 参与)**:被 SDK 用 `@_originallyDefinedIn` 搬过家的 Swift 类型(`CGFloat` 由 CoreFoundation 声明、mangling 仍是 CoreGraphics;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore),interface 按现在声明它的模块打印——swift-type-indexing 扫描 SDK 文本 `.swiftinterface` 建搬家表,打印器多一个 `MovedTypeModuleResolving` 角色,`swift-section interface --resolve-moved-type-modules` 默认关闭,按二进制的 SDK 版本判断是否改写。 | +| [Evolutions/draft-private-cf-type-modules.md](Evolutions/draft-private-cf-type-modules.md) | **提案 draft(Accepted)**:私有 CF 类型在 `interface --resolve-c-module-names` 下查不到模块,只印描述符给的裸名(`CGSVGDocument`)。新增 swift-type-indexing `DeclaredTypeNameSource` 的实现 `CFDeclaredTypeNames`:从镜像导出的 `…GetTypeID` 列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`),provider 为根镜像和每个直接依赖登记,引用印成 `CoreSVG.CGSVGDocument`;打印器、swift-type-indexing 与 CLI 参数不改。macOS 27.2 cache 里 Swift 用到的 20 个私有 CF 类型能覆盖 15 个。 | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | From a9ebf0b0c207830313da44abc41fbc1dba0a925e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:06:01 +0800 Subject: [PATCH 103/175] Add CFDeclaredTypeNames, the CF types an image exports a GetTypeID for A swift-type-indexing `DeclaredTypeNameSource` beside MachOObjCSection's `ObjCDeclaredTypeNames`: every exported `_GetTypeID` names the typedef `Ref`, and a private `__GetTypeID` its unprefixed spelling too. Read through `MachORepresentable.exportedSymbols`, so a file, a loaded image and a wrapper read alike. Co-Authored-By: Claude Opus 5.5 --- Documentations/Evolutions/README.md | 2 +- .../draft-private-cf-type-modules.html | 2 +- .../draft-private-cf-type-modules.md | 2 +- Documentations/README.md | 2 +- .../CFDeclaredTypeNames.swift | 88 +++++++++++++++++++ .../CFDeclaredTypeNamesTests.swift | 70 +++++++++++++++ 6 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift create mode 100644 Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index b90aa650..6120875b 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -122,4 +122,4 @@ | [0105](0105-swift-type-indexing-package.md) | 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer(跨仓库唯一提案) | Implemented | | [0106](0106-c-imported-type-name-spelling.md) | C 导入类型的名字统一成 Swift 名,并能切换回 C 名(跨仓库唯一提案,RuntimeViewer 参与) | Implemented | | draft | [被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印(跨仓库唯一提案,swift-type-indexing 参与)](draft-moved-swift-type-modules.md) | In Progress | -| draft | [私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块](draft-private-cf-type-modules.md) | Accepted | +| draft | [私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块](draft-private-cf-type-modules.md) | In Progress | diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.html b/Documentations/Evolutions/draft-private-cf-type-modules.html index b76aa0de..6dd71917 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.html +++ b/Documentations/Evolutions/draft-private-cf-type-modules.html @@ -163,7 +163,7 @@

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-25
    项目类型
    库
    原文
    draft-private-cf-type-modules.md
    diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.md b/Documentations/Evolutions/draft-private-cf-type-modules.md index 052da42b..7d33c886 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.md +++ b/Documentations/Evolutions/draft-private-cf-type-modules.md @@ -1,6 +1,6 @@ # Draft - 私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-25 - **最后更新**: 2026-11-25 diff --git a/Documentations/README.md b/Documentations/README.md index 7519969e..7973967e 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -226,7 +226,7 @@ selects names using each access's offset and width. | [Evolutions/0105-swift-type-indexing-package.md](Evolutions/0105-swift-type-indexing-package.md) | **提案 0105(Implemented,跨仓库)**:`TypeIndexing` 搬进独立包 swift-type-indexing(SDK 的模块接口与 API notes 索引,按 SDK 版本缓存),本仓库只留适配层 `SwiftTypeNameResolution`;同时修 API notes 改名规则与只装 Command Line Tools 时找不到 sourcekitd。MachOObjCSection 0.8.209 按 API notes 在头文件里标 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT`(swift-semantic-string 0.7.0 的宏色),RuntimeViewer 把 `__C.X` 打印成模块限定的 Swift 名 | | [Evolutions/0106-c-imported-type-name-spelling.md](Evolutions/0106-c-imported-type-name-spelling.md) | **提案 0106(Implemented,跨仓库,RuntimeViewer 参与)**:C 导入类型的名字统一成 Swift 名——声明、成员类型与扩展头一致写描述符给的 Swift 名(解析器找得到模块就带模块,否则写裸名),`CImportedTypeNameSpelling.cName` 一律写 mangled 的 C 名;ABI 名以描述符名字结尾的不信(导入成成员的类型退回 C 名)。`marksCImportedTypeNames` 在名字上标出另一种写法,RuntimeViewer 据此在声明行尾画可点击的标签、切换全局选项;`swift-section interface --c-imported-type-name-spelling` | | [Evolutions/draft-moved-swift-type-modules.md](Evolutions/draft-moved-swift-type-modules.md) | **提案 draft(In Progress,跨仓库,swift-type-indexing 参与)**:被 SDK 用 `@_originallyDefinedIn` 搬过家的 Swift 类型(`CGFloat` 由 CoreFoundation 声明、mangling 仍是 CoreGraphics;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore),interface 按现在声明它的模块打印——swift-type-indexing 扫描 SDK 文本 `.swiftinterface` 建搬家表,打印器多一个 `MovedTypeModuleResolving` 角色,`swift-section interface --resolve-moved-type-modules` 默认关闭,按二进制的 SDK 版本判断是否改写。 | -| [Evolutions/draft-private-cf-type-modules.md](Evolutions/draft-private-cf-type-modules.md) | **提案 draft(Accepted)**:私有 CF 类型在 `interface --resolve-c-module-names` 下查不到模块,只印描述符给的裸名(`CGSVGDocument`)。新增 swift-type-indexing `DeclaredTypeNameSource` 的实现 `CFDeclaredTypeNames`:从镜像导出的 `…GetTypeID` 列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`),provider 为根镜像和每个直接依赖登记,引用印成 `CoreSVG.CGSVGDocument`;打印器、swift-type-indexing 与 CLI 参数不改。macOS 27.2 cache 里 Swift 用到的 20 个私有 CF 类型能覆盖 15 个。 | +| [Evolutions/draft-private-cf-type-modules.md](Evolutions/draft-private-cf-type-modules.md) | **提案 draft(In Progress)**:私有 CF 类型在 `interface --resolve-c-module-names` 下查不到模块,只印描述符给的裸名(`CGSVGDocument`)。新增 swift-type-indexing `DeclaredTypeNameSource` 的实现 `CFDeclaredTypeNames`:从镜像导出的 `…GetTypeID` 列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`),provider 为根镜像和每个直接依赖登记,引用印成 `CoreSVG.CGSVGDocument`;打印器、swift-type-indexing 与 CLI 参数不改。macOS 27.2 cache 里 Swift 用到的 20 个私有 CF 类型能覆盖 15 个。 | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift new file mode 100644 index 00000000..9f1552b2 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift @@ -0,0 +1,88 @@ +#if os(macOS) + +import MachOKit +import TypeIndexing + +/// The Core Foundation types an image defines, as swift-type-indexing's +/// `TypeDatabase` reads them: one for every `…GetTypeID` function the image +/// exports. +/// +/// A CF type's Swift metadata names the type but never its module — its +/// descriptor sits in `__C` — while the framework defining it exports the +/// type's `GetTypeID` function. Registered beside `ObjCDeclaredTypeNames`, this +/// attributes a private CF type such as `CGSVGDocumentRef` to the image +/// exporting `CGSVGDocumentGetTypeID` (`CoreSVG`). `TypeDatabase` consults it +/// only for names neither the SDK's module interfaces nor its API notes +/// attribute, and reads the image's exports only on such a miss (evolution +/// proposal `private-cf-type-modules`). +/// +/// ```swift +/// let sources: [any DeclaredTypeNameSource] = dependencyImages.flatMap { image in +/// [ +/// ObjCDeclaredTypeNames(machO: image, imagePath: image.imagePath), +/// CFDeclaredTypeNames(machO: image, imagePath: image.imagePath), +/// ] +/// } +/// ``` +public struct CFDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + private let machO: MachO + + /// - Parameters: + /// - machO: The image, in this process or in a file. + /// - imagePath: Its install path, which names the module its types are + /// attributed to (`…/CoreSVG.framework/Versions/A/CoreSVG` → `CoreSVG`). + public init(machO: MachO, imagePath: String) { + self.machO = machO + self.imagePath = imagePath + } + + /// The typedef name of every CF type the image exports a `GetTypeID` + /// function for. + public func declaredTypeNames() async -> [String] { + machO.exportedSymbols.flatMap { exportedSymbol in + Self.typedefNames(forExportedSymbolName: exportedSymbol.name) + } + } + + /// The typedef names an exported symbol implies, by the CF convention that + /// `GetTypeID` returns the type ID of `Ref`: + /// `_CGSVGDocumentGetTypeID` → `["CGSVGDocumentRef"]`. A private function + /// spelled with a leading underscore also names the unprefixed typedef, + /// which is how such a type is usually declared: `__LSASNGetTypeID` → + /// `["_LSASNRef", "LSASNRef"]`. Any other symbol — a Swift or Objective-C + /// one, a function not ending in `GetTypeID` — implies none. + /// + /// A few names it gives are no type at all (`_CFGetTypeID` → `CFRef`); a + /// lookup asks for one only by coincidence, after the SDK's attribution. + static func typedefNames(forExportedSymbolName symbolName: String) -> [String] { + let typeIDFunctionSuffix = "GetTypeID" + // A C function's Mach-O symbol carries one leading underscore. + guard symbolName.hasPrefix("_"), symbolName.hasSuffix(typeIDFunctionSuffix) else { + return [] + } + let functionName = symbolName.dropFirst() + let typeNameStem = functionName.dropLast(typeIDFunctionSuffix.count) + let unprefixedTypeNameStem = typeNameStem.drop { $0 == "_" } + guard !unprefixedTypeNameStem.isEmpty, isCIdentifier(typeNameStem) else { + return [] + } + var typedefNames = [String(typeNameStem) + "Ref"] + if unprefixedTypeNameStem.count != typeNameStem.count { + typedefNames.append(String(unprefixedTypeNameStem) + "Ref") + } + return typedefNames + } + + private static func isCIdentifier(_ candidate: Substring) -> Bool { + guard let firstCharacter = candidate.first, !firstCharacter.isNumber else { + return false + } + return candidate.allSatisfy { character in + character == "_" || (character.isASCII && (character.isLetter || character.isNumber)) + } + } +} + +#endif diff --git a/Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift b/Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift new file mode 100644 index 00000000..08f2cbe2 --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift @@ -0,0 +1,70 @@ +#if os(macOS) + +import Darwin +import Foundation +import MachOKit +import SwiftSectionFixtureSupport +import SwiftTypeNameResolution +import Testing + +/// `CFDeclaredTypeNames` names the CF types an image defines after the +/// `…GetTypeID` functions it exports (evolution proposal +/// `private-cf-type-modules`). +@Suite +struct CFDeclaredTypeNamesTests { + /// Two type-ID functions — one spelled as a private function, with a + /// leading underscore — beside exports that name no type: a function of + /// the type that is not its type-ID function, and type-ID functions with + /// no type name before the suffix. + private static let fixtureSource = """ + unsigned long ProbeWidgetGetTypeID(void) { return 1; } + unsigned long _ProbeSecretGetTypeID(void) { return 2; } + void *ProbeWidgetCreate(void) { return 0; } + unsigned long GetTypeID(void) { return 3; } + unsigned long __GetTypeID(void) { return 4; } + """ + + /// What the fixture defines, written out by hand: each type-ID function's + /// typedef, and the private one's unprefixed spelling too. + private static let fixtureTypedefNames: Set = ["ProbeWidgetRef", "_ProbeSecretRef", "ProbeSecretRef"] + + private static let fixtureImagePath = "/Library/Frameworks/ProbeCF.framework/ProbeCF" + + private static func fixtureLibraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary(named: "CFDeclaredTypeNamesFixture", language: .c, source: fixtureSource) + } + + @Test + func fileNamesTheTypedefOfEveryExportedTypeIDFunction() async throws { + let machOFile = try HostSlice.machOFile(at: Self.fixtureLibraryURL()) + let declaredTypeNames = await CFDeclaredTypeNames(machO: machOFile, imagePath: Self.fixtureImagePath).declaredTypeNames() + #expect(Set(declaredTypeNames) == Self.fixtureTypedefNames) + } + + @Test + func loadedImageNamesTheSameTypedefs() async throws { + let libraryURL = try Self.fixtureLibraryURL() + let libraryHandle = try #require(dlopen(libraryURL.path, RTLD_LAZY), "the fixture library did not load") + let typeIDFunctionAddress = try #require(dlsym(libraryHandle, "ProbeWidgetGetTypeID")) + let machOImage = try #require(ProcessImages.image(containing: typeIDFunctionAddress)) + let declaredTypeNames = await CFDeclaredTypeNames(machO: machOImage, imagePath: Self.fixtureImagePath).declaredTypeNames() + #expect(Set(declaredTypeNames) == Self.fixtureTypedefNames) + } + + /// The case the source exists for: CoreSVG is a private framework, so no + /// SDK header declares `CGSVGDocumentRef`, and SwiftUICore's references to + /// it found no module until CoreSVG's export of `CGSVGDocumentGetTypeID` + /// was read. Read from this Mac's shared cache and as loaded in-process. + @Test + func coreSVGDeclaresItsPrivateDocumentType() async throws { + let coreSVGPath = "/System/Library/PrivateFrameworks/CoreSVG.framework/Versions/A/CoreSVG" + _ = try #require(dlopen(coreSVGPath, RTLD_LAZY), "CoreSVG did not load") + let (machOFile, machOImage) = try ProcessImages.cacheFileAndLoadedImage(path: coreSVGPath) + let fileTypeNames = await CFDeclaredTypeNames(machO: machOFile, imagePath: coreSVGPath).declaredTypeNames() + let imageTypeNames = await CFDeclaredTypeNames(machO: machOImage, imagePath: coreSVGPath).declaredTypeNames() + #expect(fileTypeNames.contains("CGSVGDocumentRef")) + #expect(imageTypeNames.contains("CGSVGDocumentRef")) + } +} + +#endif From d9d83274a1849e63cdddf77e8993af809178e6a4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:11:18 +0800 Subject: [PATCH 104/175] Register CFDeclaredTypeNames for the root and each direct dependency `SwiftInterfaceBuilderTypeNameProvider.setup()` now hands `TypeDatabase` the root's CF types first, then each dependency's Objective-C names and CF types, so a private CF type resolves to the image exporting its GetTypeID and prints under it (`CoreSVG.CGSVGDocument`). The root is still left out of the module filter, so it generates no SDK interface. Co-Authored-By: Claude Opus 5.5 --- .../draft-private-cf-type-modules.md | 21 ++- ...wiftInterfaceBuilderTypeNameProvider.swift | 17 ++- .../PrivateCFTypeModuleTests.swift | 127 ++++++++++++++++++ 3 files changed, 153 insertions(+), 12 deletions(-) create mode 100644 Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.md b/Documentations/Evolutions/draft-private-cf-type-modules.md index 7d33c886..3e69c9a4 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.md +++ b/Documentations/Evolutions/draft-private-cf-type-modules.md @@ -245,17 +245,15 @@ extension SwiftInterfaceBuilderTypeNameProvider { ## 落地步骤 0. **提案落盘、登记索引**(本次)—— 改动地图最后两行中的索引部分 -1. **`CFDeclaredTypeNames` 与它的测试** —— 改动地图第 1、2 行 - - 行为:`exportedTypeIDFunctionNamesItsTypedef`(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`) - - 行为:`underscoredTypeIDFunctionNamesBothSpellings`(`__LSASNGetTypeID` → `_LSASNRef`、`LSASNRef`) - - 行为:`otherExportsNameNothing`(`_CGSVGDocumentCreate`、`_GetTypeID`、`_$s…`、`_OBJC_CLASS_$_…` → 空) - - 行为:`readsACompiledLibrarysExportsThroughBothReaders`(用 `FixtureCompiler` 现场编译一个导出 `ProbeWidgetGetTypeID`、`_ProbeSecretGetTypeID`、`ProbeWidgetCreate` 的 C 动态库,`MachOFile` 与 `dlopen` 后的 `MachOImage` 读出同样的名字) -2. **provider 登记新来源,端到端验证** —— 改动地图第 3、4 行 - - 行为:`sourcesListTheRootFirstThenEachDependencyObjCBeforeCF` - - 行为:`typeDatabaseAttributesAnExportedCFTypeToItsImage`(`TypeDatabase` 只登记第 1 步的 C 库、`moduleFilter` 不选任何模块,`moduleName(forTypeName: "ProbeWidgetRef") == "ProbeCF"`) - - 行为:`interfacePrintsAPrivateCFTypeUnderItsDeclaringModule`(一个用桥接头引入 `CF_BRIDGED_TYPE(id)` 的 `ProbeWidgetRef`、在公开 struct 里存它的 Swift 库,接口里的字段类型印成 `ProbeCF.ProbeWidget`;先断言这个库确实带着 `ProbeWidgetRef` 的描述符) - - 行为:`interfaceKeepsTheBareSwiftNameWithoutTheSource`(同一个库、不登记来源时仍是 0106 的 `ProbeWidget`) - - 现场编译用 `FixtureCompiler`;它给不出桥接头的路径时,照 `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift` 的写法,并把这个能力缺口记进 shared-macho-testing-support 提案 +1. ✅ **`CFDeclaredTypeNames` 与它的测试** —— 改动地图第 1、2 行(`Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift`;Ultra,Xcode 26.6,3 个测试通过) + - 行为:`fileNamesTheTypedefOfEveryExportedTypeIDFunction`(`FixtureCompiler` 现场编译的 C 库导出 `ProbeWidgetGetTypeID`、`_ProbeSecretGetTypeID`、`ProbeWidgetCreate`、`GetTypeID`、`__GetTypeID`,经 `MachOFile` 读出的名字恰好是 `ProbeWidgetRef`、`_ProbeSecretRef`、`ProbeSecretRef`) + - 行为:`loadedImageNamesTheSameTypedefs`(同一个库 `dlopen` 后经 `MachOImage` 读出同样的名字) + - 行为:`coreSVGDeclaresItsPrivateDocumentType`(本机 cache 里的 CoreSVG,文件与进程内两种读法都给出 `CGSVGDocumentRef`) +2. **provider 登记新来源,端到端验证** —— 改动地图第 3、4 行(`Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift`) + - 夹具:C 库 `ProbeCF` 导出 `ProbeWidgetGetTypeID`;Swift 库 `ProbeKit` 用桥接头声明两个 `CF_BRIDGED_TYPE(id)` 的 typedef,链接 `ProbeCF`,并用 `@_cdecl` 自己导出 `ProbeGadgetGetTypeID`。`FixtureCompiler` 把 install name 固定成 `@rpath/lib<名字>.dylib`,所以模块名是 `libProbeCF`、`libProbeKit` + - 行为:`aPrivateCFTypePrintsUnderTheImageExportingItsTypeID`(字段类型印成 `libProbeCF.ProbeWidget`) + - 行为:`aCFTypeTheRootDefinesPrintsUnderTheRootsModule`(根镜像自己定义的印成 `libProbeKit.ProbeGadget`) + - 行为:`withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName`(不挂 provider 时仍是 0106 的 `ProbeWidget`) 3. **文档与系统镜像验证** —— 改动地图第 5–9 行 - 在 Ultra 上对本机 cache 的 SwiftUICore、AppKit、RealityIO 跑 `interface --resolve-c-module-names`,确认 `CoreSVG.CGSVGDocument`、`AttributeGraph.Graph`、`CoreGraphics.CGColorTransform`、`CoreRealityIO.RIOPxrSdfLayer`,并量耗时变化(详细设计「性能」),结果记进本提案 - 测试一律在 Ultra 上跑(公司那台不跑本库的测试),`--filter` 同时带 `--skip IntegrationTests` @@ -273,3 +271,4 @@ extension SwiftInterfaceBuilderTypeNameProvider { | 2026-11-25 | 实现放在本仓库,形式是 `DeclaredTypeNameSource` | 用户选定放在本仓库、不改 swift-type-indexing。调研发现用户设想的「类型索引开放注册表、各库注册自己的内容」已经以 `DeclaredTypeNameSource` 存在,ObjC 侧就是这样接入的,因此不再另写打印器解析器(替代方案第 1 条)。用户确认这个形式。 | | 2026-11-25 | `IOSurfaceRef` 疑似问题先复现 | 用户定:先在 Ultra 上复现调研第 10 条,确认是真的再按 bug 修复另走一批,不并入本提案。 | | 2026-11-25 | 用户批准,开始实现 | 轻量档,用户看过简报后批准。功能分支从本地 `next` 切,因为 moved-swift-type-modules 的本地合并也改了 provider 的 `setup()`,从 `origin/next` 切会在合回时冲突。 | +| 2026-11-25 | 测试都放在公开 seam 上 | 命名规则不单独测内部静态函数,改由现场编译的 C 库的导出覆盖各种写法;来源顺序不单独测内部函数,改由端到端测试证明根镜像与依赖各自归属。`declaredTypeNameSources(root:dependencies:)` 仍按设计抽成内部静态函数。 | diff --git a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift index 8b501181..dd806ab8 100644 --- a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift +++ b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift @@ -92,11 +92,26 @@ public final class SwiftInterfaceBuilderTypeNameProvider [any DeclaredTypeNameSource] { + var sources: [any DeclaredTypeNameSource] = [CFDeclaredTypeNames(machO: root, imagePath: root.imagePath)] + for dependency in dependencies { + sources.append(ObjCDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath)) + sources.append(CFDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath)) + } + return sources + } + public func moduleName(forTypeName typeName: String) async -> String? { guard resolutions.contains(.cImportedModules) else { return nil } return await resolver.moduleName(forTypeName: typeName) diff --git a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift new file mode 100644 index 00000000..e3d98771 --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift @@ -0,0 +1,127 @@ +#if os(macOS) + +import Foundation +import MachODependencies +import MachOKit +import Semantic +import SwiftInterface +import SwiftSectionFixtureSupport +import SwiftTypeNameResolution +import Testing + +/// Evolution proposal `private-cf-type-modules`, end to end: a CF type no SDK +/// header declares prints under the module of the image exporting its +/// `GetTypeID` function, through `SwiftInterfaceBuilderTypeNameProvider`. +/// +/// `ProbeCF` stands for a private framework such as CoreSVG: a C library +/// exporting `ProbeWidgetGetTypeID`. `ProbeKit` stands for SwiftUICore: a Swift +/// library whose bridging header declares the CF types, which links `ProbeCF` +/// and defines a CF type of its own, exporting `ProbeGadgetGetTypeID` through +/// `@_cdecl`. `FixtureCompiler` gives every library the install name +/// `@rpath/lib.dylib`, and `TypeDatabase` names a module after the +/// install name's file, so the two modules read `libProbeCF` and `libProbeKit`. +@Suite +struct PrivateCFTypeModuleTests { + private static let probeCFSource = """ + unsigned long ProbeWidgetGetTypeID(void) { return 1; } + """ + + private static let probeKitBridgingHeader = """ + #include + typedef struct CF_BRIDGED_TYPE(id) __ProbeWidget *ProbeWidgetRef; + typedef struct CF_BRIDGED_TYPE(id) __ProbeGadget *ProbeGadgetRef; + CFTypeID ProbeWidgetGetTypeID(void); + """ + + /// `Anchor` keeps a `__DATA` segment in the dylib. Hashing the two CF + /// types through a generic function makes the library carry their type + /// descriptors, and calling `ProbeWidgetGetTypeID` keeps `ProbeCF` among + /// its load commands. + private static let probeKitSource = """ + import Foundation + + public final class Anchor {} + + public struct Holder { + public var widget: ProbeWidget + public var gadget: ProbeGadget + + public init(widget: ProbeWidget, gadget: ProbeGadget) { + self.widget = widget + self.gadget = gadget + } + } + + @_cdecl("ProbeGadgetGetTypeID") + public func probeGadgetGetTypeID() -> UInt { + 2 + } + + @inline(never) + public func hashValue(of value: Value) -> Int { + value.hashValue + } + + public func exercise(_ holder: Holder) -> Int { + hashValue(of: holder.widget) &+ hashValue(of: holder.gadget) &+ Int(ProbeWidgetGetTypeID()) + } + """ + + private struct FixtureLibraries: Sendable { + let probeKitURL: URL + let probeCFURL: URL + } + + private static let fixtureLibraries = Result(catching: { + let probeCFURL = try FixtureCompiler.shared.dynamicLibrary(named: "ProbeCF", language: .c, source: probeCFSource) + let headerDirectoryURL = FileManager.default.temporaryDirectory + .appending(component: "PrivateCFTypeModuleTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: headerDirectoryURL, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: headerDirectoryURL) } + let headerURL = headerDirectoryURL.appending(component: "ProbeKit-Bridging-Header.h") + try probeKitBridgingHeader.write(to: headerURL, atomically: true, encoding: .utf8) + let probeKitURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeKit", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ProbeKit.swift", contents: probeKitSource)], + arguments: ["-swift-version", "5", "-import-objc-header", headerURL.path, "-Xlinker", probeCFURL.path] + ) + return FixtureLibraries(probeKitURL: probeKitURL, probeCFURL: probeCFURL) + }) + + /// `ProbeKit`'s interface; with the provider, `ProbeCF` is its one + /// resolvable dependency. + private static func probeKitInterface(attachingTypeNameProvider: Bool) async throws -> String { + let libraries = try fixtureLibraries.get() + let probeKit = try HostSlice.machOFile(at: libraries.probeKitURL) + let builder = try SwiftInterfaceBuilder(in: probeKit) + if attachingTypeNameProvider { + let dependencies = SwiftInterfaceBuilderDependencies(machO: probeKit, searchPaths: [.machOFile(path: libraries.probeCFURL.path)]) + let typeNameProvider = try #require(SwiftInterfaceBuilderTypeNameProvider(machO: probeKit, dependencies: dependencies)) + builder.addExtraDataProvider(typeNameProvider) + } + try await builder.prepare() + return try await builder.printRoot().string + } + + @Test + func aPrivateCFTypePrintsUnderTheImageExportingItsTypeID() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("widget: libProbeCF.ProbeWidget"), "\(interface)") + } + + @Test + func aCFTypeTheRootDefinesPrintsUnderTheRootsModule() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("gadget: libProbeKit.ProbeGadget"), "\(interface)") + } + + /// What 0106 alone prints: the descriptor's Swift name, with no module. + @Test + func withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: false) + #expect(interface.contains("widget: ProbeWidget"), "\(interface)") + } +} + +#endif From 6909fad22edfba135dd8007a346584a044a87fae Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:12:26 +0800 Subject: [PATCH 105/175] Spell Swift.Error in the private CF type module test, which imports Semantic Co-Authored-By: Claude Opus 5.5 --- .../SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift index e3d98771..188bc0fa 100644 --- a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift +++ b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift @@ -72,7 +72,7 @@ struct PrivateCFTypeModuleTests { let probeCFURL: URL } - private static let fixtureLibraries = Result(catching: { + private static let fixtureLibraries = Result(catching: { let probeCFURL = try FixtureCompiler.shared.dynamicLibrary(named: "ProbeCF", language: .c, source: probeCFSource) let headerDirectoryURL = FileManager.default.temporaryDirectory .appending(component: "PrivateCFTypeModuleTests-\(UUID().uuidString)") From e72a3411037f2985f92c1409f91edec358ebfdec Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:15:04 +0800 Subject: [PATCH 106/175] Register one source per dependency image, reading both its ObjC and CF names TypeDatabase keeps one declared-type-name source per image path and skips a later one with the same path, so a dependency's CFDeclaredTypeNames registered after its ObjCDeclaredTypeNames was never read: the private CF type of the end-to-end test printed bare. ImageDeclaredTypeNames reads the two as one source; the root, whose Objective-C names stay unregistered, keeps its CFDeclaredTypeNames alone. Co-Authored-By: Claude Opus 5.5 --- .../CFDeclaredTypeNames.swift | 26 +++++----- .../ImageDeclaredTypeNames.swift | 52 +++++++++++++++++++ ...wiftInterfaceBuilderTypeNameProvider.swift | 13 +++-- .../ImageDeclaredTypeNamesTests.swift | 29 +++++++++++ 4 files changed, 101 insertions(+), 19 deletions(-) create mode 100644 Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift create mode 100644 Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift diff --git a/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift index 9f1552b2..98f8e97d 100644 --- a/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift +++ b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift @@ -9,20 +9,22 @@ import TypeIndexing /// /// A CF type's Swift metadata names the type but never its module — its /// descriptor sits in `__C` — while the framework defining it exports the -/// type's `GetTypeID` function. Registered beside `ObjCDeclaredTypeNames`, this -/// attributes a private CF type such as `CGSVGDocumentRef` to the image -/// exporting `CGSVGDocumentGetTypeID` (`CoreSVG`). `TypeDatabase` consults it -/// only for names neither the SDK's module interfaces nor its API notes -/// attribute, and reads the image's exports only on such a miss (evolution -/// proposal `private-cf-type-modules`). +/// type's `GetTypeID` function. This attributes a private CF type such as +/// `CGSVGDocumentRef` to the image exporting `CGSVGDocumentGetTypeID` +/// (`CoreSVG`). `TypeDatabase` consults it only for names neither the SDK's +/// module interfaces nor its API notes attribute, and reads the image's +/// exports only on such a miss (evolution proposal `private-cf-type-modules`). +/// +/// `TypeDatabase` keeps one source per image path, so an image whose +/// Objective-C names are registered too goes in as one +/// ``ImageDeclaredTypeNames``, which reads both; this alone is for an image +/// read for its CF types only. /// /// ```swift -/// let sources: [any DeclaredTypeNameSource] = dependencyImages.flatMap { image in -/// [ -/// ObjCDeclaredTypeNames(machO: image, imagePath: image.imagePath), -/// CFDeclaredTypeNames(machO: image, imagePath: image.imagePath), -/// ] -/// } +/// try await typeDatabase.index( +/// dependencies: [CFDeclaredTypeNames(machO: coreSVG, imagePath: coreSVG.imagePath)], +/// moduleFilter: { _ in false } +/// ) /// ``` public struct CFDeclaredTypeNames: DeclaredTypeNameSource { public let imagePath: String diff --git a/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift new file mode 100644 index 00000000..603b92ba --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift @@ -0,0 +1,52 @@ +#if os(macOS) + +import ObjCMetadataSource +import ObjCTypeIndexing +import TypeIndexing + +/// Every type an image declares, as one swift-type-indexing source: the +/// classes, protocols, structs and unions its Objective-C metadata names +/// (`ObjCDeclaredTypeNames`), then the CF types it exports a `GetTypeID` +/// function for (`CFDeclaredTypeNames`). +/// +/// `TypeDatabase` keeps one source per image path and skips any later one +/// with the same path, so an image's CF types registered beside its +/// Objective-C names, as a second source, would never be read. Register this +/// instead of the two (evolution proposal `private-cf-type-modules`). +/// +/// ```swift +/// let typeDatabase = TypeDatabase(platform: .macOS) +/// try await typeDatabase.index( +/// dependencies: dependencyImages.map { ImageDeclaredTypeNames(machO: $0, imagePath: $0.imagePath) }, +/// moduleFilter: { dependencyModuleNames.contains($0) } +/// ) +/// ``` +public struct ImageDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + private let objectiveCTypeNames: ObjCDeclaredTypeNames + + private let coreFoundationTypeNames: CFDeclaredTypeNames + + /// - Parameters: + /// - machO: The image, in this process or in a file. + /// - imagePath: Its install path, which names the module its types are + /// attributed to (`…/IOSurface.framework/Versions/A/IOSurface` → + /// `IOSurface`). + public init(machO: MachO, imagePath: String) { + self.imagePath = imagePath + self.objectiveCTypeNames = ObjCDeclaredTypeNames(machO: machO, imagePath: imagePath) + self.coreFoundationTypeNames = CFDeclaredTypeNames(machO: machO, imagePath: imagePath) + } + + /// The Objective-C names, then the CF typedef names. Throws when the + /// Objective-C metadata cannot be read, as `ObjCDeclaredTypeNames` does on + /// its own: `TypeDatabase` then logs the image and skips it whole. + public func declaredTypeNames() async throws -> [String] { + let objectiveCNames = try await objectiveCTypeNames.declaredTypeNames() + let typedefNames = await coreFoundationTypeNames.declaredTypeNames() + return objectiveCNames + typedefNames + } +} + +#endif diff --git a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift index dd806ab8..0806ab8a 100644 --- a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift +++ b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift @@ -101,15 +101,14 @@ public final class SwiftInterfaceBuilderTypeNameProvider [any DeclaredTypeNameSource] { - var sources: [any DeclaredTypeNameSource] = [CFDeclaredTypeNames(machO: root, imagePath: root.imagePath)] - for dependency in dependencies { - sources.append(ObjCDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath)) - sources.append(CFDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath)) + let rootSource: any DeclaredTypeNameSource = CFDeclaredTypeNames(machO: root, imagePath: root.imagePath) + return [rootSource] + dependencies.map { dependency in + ImageDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath) } - return sources } public func moduleName(forTypeName typeName: String) async -> String? { diff --git a/Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift b/Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift new file mode 100644 index 00000000..ff6f291b --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift @@ -0,0 +1,29 @@ +#if os(macOS) + +import Darwin +import MachOKit +import ObjCMetadataSource +import SwiftSectionFixtureSupport +import SwiftTypeNameResolution +import Testing + +/// `ImageDeclaredTypeNames` lists both kinds of names one image declares, +/// because `TypeDatabase` reads only the first source registered for an image +/// path (evolution proposal `private-cf-type-modules`). +@Suite +struct ImageDeclaredTypeNamesTests { + /// IOSurface declares both under nearly one name: the Objective-C class + /// `IOSurface`, and the CF type `IOSurfaceRef`, which keeps its `Ref` in + /// Swift because the class already took the stripped name. + @Test + func listsTheObjectiveCClassAndTheCFTypeOfOneImage() async throws { + let ioSurfacePath = "/System/Library/Frameworks/IOSurface.framework/Versions/A/IOSurface" + _ = try #require(dlopen(ioSurfacePath, RTLD_LAZY), "IOSurface did not load") + let (machOFile, _) = try ProcessImages.cacheFileAndLoadedImage(path: ioSurfacePath) + let declaredTypeNames = try await ImageDeclaredTypeNames(machO: machOFile, imagePath: ioSurfacePath).declaredTypeNames() + #expect(declaredTypeNames.contains("IOSurface")) + #expect(declaredTypeNames.contains("IOSurfaceRef")) + } +} + +#endif From 35a3758076422b20f407424d4d5168f461e5c94a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:17:38 +0800 Subject: [PATCH 107/175] docs: record ImageDeclaredTypeNames and the finished second step in the private-cf-type-modules proposal Co-Authored-By: Claude Opus 5.5 --- .../draft-private-cf-type-modules.md | 86 ++++++++++++------- 1 file changed, 53 insertions(+), 33 deletions(-) diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.md b/Documentations/Evolutions/draft-private-cf-type-modules.md index 3e69c9a4..fac6e608 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.md +++ b/Documentations/Evolutions/draft-private-cf-type-modules.md @@ -13,7 +13,7 @@ ## 摘要 -`swift-section interface --resolve-c-module-names` 能把公开的 C 导入类型写到真实模块下(`__C.CGColorRef` → `CoreGraphics.CGColor`),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(`CGSVGDocument`)。本提案在 `SwiftTypeNameResolution` 里新增 `CFDeclaredTypeNames`,它是 swift-type-indexing 的 `DeclaredTypeNameSource` 的又一个实现:从镜像的导出表里找出每个 `…GetTypeID` 函数,列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`)。`SwiftInterfaceBuilderTypeNameProvider` 为根镜像和每个直接依赖各登记一个。之后 `CGSVGDocumentRef` 归到 CoreSVG,引用印成 `CoreSVG.CGSVGDocument`。打印器、swift-type-indexing 和 CLI 参数都不改。 +`swift-section interface --resolve-c-module-names` 能把公开的 C 导入类型写到真实模块下(`__C.CGColorRef` → `CoreGraphics.CGColor`),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(`CGSVGDocument`)。本提案在 `SwiftTypeNameResolution` 里新增 `CFDeclaredTypeNames`,它是 swift-type-indexing 的 `DeclaredTypeNameSource` 的又一个实现:从镜像的导出表里找出每个 `…GetTypeID` 函数,列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`)。`SwiftInterfaceBuilderTypeNameProvider` 为根镜像登记它;每个直接依赖改登记新的 `ImageDeclaredTypeNames`,把这个镜像的 Objective-C 名字和 CF 类型合成一个来源,因为 `TypeDatabase` 每个镜像路径只收一个来源。之后 `CGSVGDocumentRef` 归到 CoreSVG,引用印成 `CoreSVG.CGSVGDocument`。打印器、swift-type-indexing 和 CLI 参数都不改。 ## 动机 @@ -40,7 +40,7 @@ 2. **模块不在二进制里。** CF 类的描述符挂在 `__C` 模块下,`_CFObject` 等合成的一致性在 `__C_Synthesized`(mangling 里的 `SC`),都不带真实模块。Swift 给一个 Clang 声明定模块时取的是**顶层** Clang 模块(`swift/lib/ClangImporter/ClangImporter.cpp:3143-3154`,注释写明 submodule 没有自己的 `ClangModuleUnit`),所以 LaunchServices 里的类型在 Swift 里属于 CoreServices(SDK 的 `CoreServices.framework/Modules/module.modulemap:43` 把 LaunchServices 声明成 CoreServices 的 submodule)。 3. **`GetTypeID` 的镜像就是模块。** 对 46 个公开 CF 类逐个查 `_<去掉 Ref 的名字>GetTypeID` 由 cache 里哪个镜像导出(`ipsw dyld symaddr`),再和 SDK 里声明它的框架比,46 个全部一致;其中 `IOSurfaceRef` 在 CoreGraphics 的头文件里有一份前向声明,真正的声明在 IOSurface,导出镜像也是 IOSurface。私有的 20 个里有 17 个能这样找到镜像,`CFXGPUDeviceRef`、`LXEntryRef`、`RTIImportOperation_t` 找不到对应的导出。Core* 框架一共导出约 190 个公开 SDK 里没有的 `…GetTypeID`(CoreMedia 75、CoreRealityIO 41、CoreGraphics 23、CoreSVG 16、CoreFoundation 12),并不是每个都对应 Swift 用到的类型。 4. **打印器在模块解析出来以后已经会用描述符的名字。** 引用处 `TypeNodePrintable.printType`(`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift:186-268`):模块经 `resolvedModuleName(of:siblingIdentifier:)`(`NodePrintable.swift:186-196`,先按 C 名查,再按去掉 `Ref` 的名字查)解析;标识符依次取解析器的 `swiftName(forCName:category:)`、0106 名字表里描述符给的名字、C 名。声明行 `declaredTypeName(of:)`(`SwiftDeclarationPrinter+Headers.swift:153-183`)同样在解析器给不出 Swift 名时退回描述符的名字。所以只要模块查得到,私有 CF 类型就会印成 `CoreSVG.CGSVGDocument`,打印器不用改。 -5. **swift-type-indexing 已有开放的注册表。** 0.2.0 的 `DeclaredTypeNameSource`(`Sources/TypeIndexing/DeclaredTypeNameSource.swift`):一个依赖镜像报出它声明的类型名,`TypeDatabase.moduleName(forTypeName:)` 只在模块接口和 API notes 都没有这个名字时,才按登记顺序一个个读这些来源,第一个声明了它的镜像胜出,模块名取自 `TypeDatabase.moduleName(forImagePath:)`(镜像文件名去掉扩展名与 `libswift` 前缀)。文档写明这个包自己不读 Mach-O。MachOObjCSection 0.8.209 的 `ObjCDeclaredTypeNames`(`Sources/ObjCTypeIndexing/ObjCDeclaredTypeNames.swift`)是现在唯一的实现,报出类、协议、struct 和 union 名,不含 CF 类型。 +5. **swift-type-indexing 已有开放的注册表。** 0.2.0 的 `DeclaredTypeNameSource`(`Sources/TypeIndexing/DeclaredTypeNameSource.swift`):一个依赖镜像报出它声明的类型名,`TypeDatabase.moduleName(forTypeName:)` 只在模块接口和 API notes 都没有这个名字时,才按登记顺序一个个读这些来源,第一个声明了它的镜像胜出,模块名取自 `TypeDatabase.moduleName(forImagePath:)`(镜像文件名去掉扩展名与 `libswift` 前缀)。文档写明这个包自己不读 Mach-O。MachOObjCSection 0.8.209 的 `ObjCDeclaredTypeNames`(`Sources/ObjCTypeIndexing/ObjCDeclaredTypeNames.swift`)是现在唯一的实现,报出类、协议、struct 和 union 名,不含 CF 类型。`TypeDatabase.register(dependencies:)` 按镜像路径去重(`Sources/TypeIndexing/TypeDatabase.swift:237-243`):同一路径的第二个来源直接丢掉,所以一个镜像的几种名字必须放进同一个来源。这一条是实现时由端到端测试发现的,见决策日志。 6. **TypeDatabase 的 CF 去 `Ref` 规则只认 SDK 里有的名字。** `TypeDatabase.swiftName(forCName:category:)` 在 API notes 没有改名时,只有去掉 `Ref` 的名字出现在模块接口或 API notes 的归属表里才返回它,运行时登记的名字不算。私有 CF 类型因此拿不到解析器给的 Swift 名,走第 4 条里描述符那一档,`AGGraphRef` 正确地印成 `Graph` 而不是 `AGGraph`。 7. **现在谁被登记。** `SwiftInterfaceBuilderTypeNameProvider.setup()`(`Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98`)只给每个**直接**依赖登记一个 `ObjCDeclaredTypeNames`,根镜像自己不登记。只取直接依赖是有意的(`Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift:9-19`:每个依赖模块都要生成一份 SourceKit 接口,传递闭包有几百个镜像)。CLI 里只有 `interface --resolve-c-module-names` 会接上它(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:273-320`),依赖按本机 dyld cache 解析。RuntimeViewer 不经这个 provider,它在 `RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/Swift/RuntimeSwiftSection.swift:2013` 给自己打开的每个镜像登记一个 `ObjCDeclaredTypeNames`。 8. **按这个设计能覆盖多少。** 对「动机」表里的 20 个查使用方的直接依赖(`dyld_info -dependents`):CoreSVG、CoreGraphics、AttributeGraph、CoreRealityIO 都是使用方的直接依赖,覆盖 14 个;`CAXUIElementRef` 由使用方自己定义,登记根镜像后覆盖,共 15 个。剩下 5 个:`LSASNRef` 的导出在 LaunchServices,使用方只直接链接重新导出它的 CoreServices;`CFPhoneNumberRef` 的 CorePhoneNumbers 不是 IDSFoundation 的直接依赖;另外 3 个没有对应的导出。 @@ -50,8 +50,9 @@ ## 提议方案 1. **新增 `CFDeclaredTypeNames`**(`Sources/Output/SwiftTypeNameResolution/`),实现 `DeclaredTypeNameSource`,与 `ObjCDeclaredTypeNames` 同形:`init(machO:imagePath:)`,`declaredTypeNames()` 读 `machO.exportedSymbols`,每个名为 `_<名字>GetTypeID` 的导出给出 `<名字>Ref`;`<名字>` 以下划线开头的私有函数(`__LSASNGetTypeID`)同时给出去掉前导下划线的拼写(`LSASNRef`)。 -2. **provider 登记它**:`setup()` 交给 `TypeDatabase.index(dependencies:moduleFilter:)` 的来源变成「根镜像的 `CFDeclaredTypeNames`,然后每个直接依赖依次是 `ObjCDeclaredTypeNames`、`CFDeclaredTypeNames`」。根镜像排第一,因为它自己定义的类型由它自己说了算;根镜像不进 `moduleFilter`,不触发 SourceKit 接口生成。来源的排列抽成一个可测的静态函数。 -3. **打印器、swift-type-indexing、CLI 参数都不改**。效果全部经现有路径体现:`moduleName(forTypeName:)` 多答出一些名字,打印器按调研第 4 条的规则写成 `模块.描述符名`。`--resolve-c-module-names` 的帮助文字和 swift-section skill 的说明补一句来源。 +2. **新增 `ImageDeclaredTypeNames`**(同一目录),也实现 `DeclaredTypeNameSource`:一个镜像的 `ObjCDeclaredTypeNames` 名字在前、`CFDeclaredTypeNames` 名字在后,合成一个来源。`TypeDatabase` 每个镜像路径只收第一个来源(调研第 5 条),把两种来源分开登记,后登记的那个永远读不到。 +3. **provider 登记它们**:`setup()` 交给 `TypeDatabase.index(dependencies:moduleFilter:)` 的来源变成「根镜像的 `CFDeclaredTypeNames`,然后每个直接依赖一个 `ImageDeclaredTypeNames`」,取代原来每个依赖一个 `ObjCDeclaredTypeNames`。根镜像排第一,因为它自己定义的类型由它自己说了算;根镜像不进 `moduleFilter`,不触发 SourceKit 接口生成,它的 Objective-C 名字照旧不登记。来源的排列抽成一个内部静态函数。 +4. **打印器、swift-type-indexing、CLI 参数都不改**。效果全部经现有路径体现:`moduleName(forTypeName:)` 多答出一些名字,打印器按调研第 4 条的规则写成 `模块.描述符名`。`--resolve-c-module-names` 的帮助文字和 swift-section skill 的说明补一句来源。 ### 非目标 @@ -61,7 +62,7 @@ - **没有描述符时给出 Swift 名**:仍印 `模块.XRef`(调研第 9 条)。要改得让 TypeDatabase 的去 `Ref` 规则认运行时名表,会碰上重名与 `swift_name` 改名(见「替代方案」第 5 条)。 - **根镜像自己的 Objective-C 类**:现在也没登记,是另一个问题,本提案不顺手改,免得 ObjC 输出跟着变。 - **`dump`**:`dump` 不做 `__C` 模块解析,本提案不引入。 -- **RuntimeViewer 接入**:本库发版后,在 `RuntimeSwiftSection.swift:2013` 的 `metadataSources` 里加一个 `CFDeclaredTypeNames`,属于 RuntimeViewer 的改动。 +- **RuntimeViewer 接入**:本库发版后,把 `RuntimeSwiftSection.swift:2013` 的 `metadataSources` 里的 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`,属于 RuntimeViewer 的改动。不能另加一个 `CFDeclaredTypeNames`:同一路径的第二个来源会被丢掉。 - **调研第 10 条的 `IOSurfaceRef` 疑似问题**:先复现,另行修复。 ## 改动地图 @@ -69,12 +70,14 @@ | 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | |---|---|---|---|---| | `Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift` · `CFDeclaredTypeNames` | 新增 | `DeclaredTypeNameSource` 的实现:读导出表,`…GetTypeID` → typedef 名;内部静态函数 `typedefNames(forExportedSymbolName:)` 承载命名规则 | 私有 CF 类型的模块证据 | 1 | -| `Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift` | 新增 | 命名规则的表驱动测试;现场编译的 C 动态库经 `MachOFile` 与 `MachOImage` 两种读法读出的名字 | 规则与两种读法 | 1 | -| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98` · `setup()` | 修改 | 来源改为「根的 CF,然后每个依赖的 ObjC、CF」;排列抽成 `static func declaredTypeNameSources(root:dependencies:)`(internal) | 登记新来源,顺序可测 | 2 | -| `Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift` | 新增 | 来源顺序;`TypeDatabase` 按新来源归属模块;用现场编译的 Swift 库验证接口里的拼写 | 端到端证明 | 2 | +| `Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift` | 新增 | 现场编译的 C 动态库经 `MachOFile` 与 `MachOImage` 两种读法读出的名字(覆盖命名规则的各种写法);本机 cache 的 CoreSVG | 规则与两种读法 | 1 | +| `Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift` · `ImageDeclaredTypeNames` | 新增 | 一个镜像的 ObjC 名字与 CF 类型合成一个 `DeclaredTypeNameSource` | `TypeDatabase` 每个镜像路径只收一个来源 | 2 | +| `Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift` | 新增 | IOSurface 一个镜像里同时列出 ObjC 类 `IOSurface` 与 CF 类型 `IOSurfaceRef` | 合成来源两种名字都在 | 2 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-113` · `setup()` | 修改 | 来源改为「根的 `CFDeclaredTypeNames`,然后每个依赖一个 `ImageDeclaredTypeNames`」;排列抽成 `static func declaredTypeNameSources(root:dependencies:)`(internal) | 登记新来源 | 2 | +| `Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift` | 新增 | 用现场编译的 C 库与 Swift 库验证接口里的拼写:依赖定义的、根镜像定义的、不挂 provider 时的 | 端到端证明 | 2 | | `Sources/Executables/swift-section/Commands/InterfaceCommand.swift:33` · `resolveCModuleNames` 的 `help` | 修改 | 来源列表补上「依赖导出的 `…GetTypeID`(CF 类型)」 | `--help` 就是文档 | 3 | | `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` 第 8 节 | 修改 | 「没有 sourcekitd 时由 API notes 与 Objective-C 元数据归属」补上导出的 `GetTypeID`;加一句私有 CF 类型的效果与第 9 条的 `XRef` 退路 | CLI 行为变了,skill 同批更新 | 3 | -| `CLAUDE.md` · SwiftTypeNameResolution 一条 | 修改 | 列出 `CFDeclaredTypeNames` | 模块清单与代码同步 | 3 | +| `CLAUDE.md` · SwiftTypeNameResolution 一条 | 修改 | 列出 `CFDeclaredTypeNames` 与 `ImageDeclaredTypeNames` | 模块清单与代码同步 | 3 | | `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案;落地时改编号与状态 | 文档索引 | 0、3 | | `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时追加一节 | 演进账本 | 3 | @@ -86,16 +89,19 @@ SwiftTypeNameResolution/ + CFDeclaredTypeNames DeclaredTypeNameSource + declaredTypeNames() machO.exportedSymbols: _GetTypeID -> "Ref" ++ ImageDeclaredTypeNames DeclaredTypeNameSource, one per image ++ declaredTypeNames() ObjCDeclaredTypeNames names + CFDeclaredTypeNames names ~ SwiftInterfaceBuilderTypeNameProvider.setup() ~ TypeDatabase.index(dependencies: + [CFDeclaredTypeNames(root), - ObjCDeclaredTypeNames(dependency1), -+ CFDeclaredTypeNames(dependency1), - ObjCDeclaredTypeNames(dependency2), -+ CFDeclaredTypeNames(dependency2), ...], +- ObjCDeclaredTypeNames(dependency1), ++ ImageDeclaredTypeNames(dependency1), +- ObjCDeclaredTypeNames(dependency2), ++ ImageDeclaredTypeNames(dependency2), ...], moduleFilter: dependency module names) unchanged: root never generates an interface swift-type-indexing 0.2.0 (unchanged) + TypeDatabase.register(dependencies:) keeps the first source per image path TypeDatabase.moduleName(forTypeName:) 1. module interfaces, API notes 2. runtime declared names, folded source by source in registration order @@ -116,10 +122,9 @@ printType(__C.CGSVGDocumentRef) │ └─ TypeDatabase.moduleName │ ├─ SDK tables miss │ ├─ CFDeclaredTypeNames(SwiftUICore) miss (+) -│ ├─ ObjCDeclaredTypeNames(AttributeGraph) miss -│ ├─ CFDeclaredTypeNames(AttributeGraph) miss (+) +│ ├─ ImageDeclaredTypeNames(AttributeGraph) miss (~ was ObjC only) │ ├─ ... -│ └─ CFDeclaredTypeNames(CoreSVG): "CGSVGDocumentRef" -> "CoreSVG" (+) +│ └─ ImageDeclaredTypeNames(CoreSVG): "CGSVGDocumentRef" -> "CoreSVG" (~) ├─ swiftName(forCName: "CGSVGDocumentRef") -> nil (no API notes, not SDK-indexed) └─ writes CoreSVG . CGSVGDocument ``` @@ -138,20 +143,15 @@ import TypeIndexing /// them: one for every `…GetTypeID` function the image exports. /// /// A CF type's Swift metadata names the type but never its module — the descriptor sits in -/// `__C` — while the framework defining it exports the type's `GetTypeID` function. Registered -/// beside `ObjCDeclaredTypeNames`, this attributes a private CF type such as `CGSVGDocumentRef` -/// to the image exporting `CGSVGDocumentGetTypeID` (`CoreSVG`). `TypeDatabase` consults it only -/// for names neither the SDK's module interfaces nor its API notes attribute, and reads the -/// image's exports only on such a miss. +/// `__C` — while the framework defining it exports the type's `GetTypeID` function. This +/// attributes a private CF type such as `CGSVGDocumentRef` to the image exporting +/// `CGSVGDocumentGetTypeID` (`CoreSVG`). `TypeDatabase` consults it only for names neither the +/// SDK's module interfaces nor its API notes attribute, and reads the image's exports only on +/// such a miss. /// -/// ```swift -/// let sources: [any DeclaredTypeNameSource] = dependencyImages.flatMap { image in -/// [ -/// ObjCDeclaredTypeNames(machO: image, imagePath: image.imagePath), -/// CFDeclaredTypeNames(machO: image, imagePath: image.imagePath), -/// ] -/// } -/// ``` +/// `TypeDatabase` keeps one source per image path, so an image whose Objective-C names are +/// registered too goes in as one `ImageDeclaredTypeNames`, which reads both; this alone is for +/// an image read for its CF types only. public struct CFDeclaredTypeNames: DeclaredTypeNameSource { public let imagePath: String @@ -179,9 +179,25 @@ public struct CFDeclaredTypeNames: Declare static func typedefNames(forExportedSymbolName symbolName: String) -> [String] } +/// Every type an image declares, as one swift-type-indexing source: the classes, protocols, +/// structs and unions its Objective-C metadata names (`ObjCDeclaredTypeNames`), then the CF +/// types it exports a `GetTypeID` function for (`CFDeclaredTypeNames`). +public struct ImageDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + public init(machO: MachO, imagePath: String) + + /// The Objective-C names, then the CF typedef names. Throws when the Objective-C metadata + /// cannot be read, as `ObjCDeclaredTypeNames` does on its own: `TypeDatabase` then logs + /// the image and skips it whole. + public func declaredTypeNames() async throws -> [String] +} + #endif ``` +`ImageDeclaredTypeNames` 只要 `ObjCMetadataSource` 一个约束:它经 `MachORepresentableWithCache` 继承 `MachORepresentable` 与 `Sendable`,正好满足两种来源。Objective-C 元数据读不出来时整个来源抛错,与只登记 `ObjCDeclaredTypeNames` 时一样,由 `TypeDatabase` 记日志并跳过这个镜像;不为保住 CF 名字而吞掉这个错误。 + 形状照 `ObjCDeclaredTypeNames` 抄:同样的 `init(machO:imagePath:)`、同样的 `imagePath` 属性、同样放在 `#if os(macOS)` 里,名字按「来源 + `DeclaredTypeNames`」对称。泛型约束只要 `MachORepresentable & Sendable`:`exportedSymbols` 是 MachOKit `MachORepresentable` 的要求(`Sources/MachOKit/Protocol/MachORepresentable.swift:124-129`),`MachOFile`、`MachOImage` 和包装类型都有,不需要判断读取器种类。provider 的 `MachO` 约束经 `MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache: MachORepresentable, Sendable` 满足它。协议要求是 `async throws`,实现不会失败,所以写成不抛错的 `async`。 ### 命名规则 @@ -197,7 +213,8 @@ public struct CFDeclaredTypeNames: Declare extension SwiftInterfaceBuilderTypeNameProvider { /// The declared-type-name sources `setup()` registers, in the order `TypeDatabase` folds /// them: the root's CF types first — a type the root defines is its own — then each direct - /// dependency's Objective-C names and CF types, in dependency order. + /// dependency's Objective-C names and CF types, one `ImageDeclaredTypeNames` per image, in + /// dependency order. static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource] } ``` @@ -216,12 +233,13 @@ extension SwiftInterfaceBuilderTypeNameProvider { 4. **用一致性符号里的模块**(`_$sSo10AGGraphRefaSQ14AttributeGraphMc`):否。那是声明这条一致性的模块,不是类型的模块;合成的一致性在 `__C_Synthesized`;cache 里的这类本地符号大多被剥掉了。 5. **让 TypeDatabase 的去 `Ref` 规则也认运行时名表**,好在没有描述符时也给出 Swift 名:否。它不知道重名,会把 `IOSurfaceRef` 改成 `IOSurface`(调研第 9 条);而打印器先问解析器、后用描述符,它还会把 `swift_name` 改过的 `AGGraphRef` 从 `Graph` 改坏成 `AGGraph`。 6. **跟着 `LC_REEXPORT_DYLIB` 把子框架的导出算进伞框架**:推迟,见「非目标」第一条。 +7. **让 swift-type-indexing 允许一个镜像路径登记多个来源**(不合成 `ImageDeclaredTypeNames`):否。「一个来源代表一个镜像」是那个包按镜像路径去重时的模型,改它要动 swift-type-indexing 并发版,而本提案定下不改那个包;在本仓库合成一个来源就够了。 ## 影响 ### 源码兼容性(source compatibility) -纯新增:多一个公开类型 `CFDeclaredTypeNames`,`SwiftInterfaceBuilderTypeNameProvider` 的公开接口不变。行为上,`--resolve-c-module-names` 下原本没有模块的私有 CF 类型会带上模块。 +纯新增:多两个公开类型 `CFDeclaredTypeNames` 与 `ImageDeclaredTypeNames`,`SwiftInterfaceBuilderTypeNameProvider` 的公开接口不变。行为上,`--resolve-c-module-names` 下原本没有模块的私有 CF 类型会带上模块。 ### ABI 兼容性(条件项) @@ -230,7 +248,7 @@ extension SwiftInterfaceBuilderTypeNameProvider { ### 下游影响 - 本仓库:`SwiftSectionKit` 的 `InterfaceRequest` 经 provider 自动受益,不用改代码。没有基线或快照测试开着 `__C` 模块解析(它要 SDK),渲染 A/B 校验不受影响。 -- RuntimeViewer:它不经 provider,自己在 `RuntimeSwiftSection.swift:2013` 登记来源,本提案落地不改变它的输出。要受益,等本库发版后在那里加一个 `CFDeclaredTypeNames`(见「非目标」)。 +- RuntimeViewer:它不经 provider,自己在 `RuntimeSwiftSection.swift:2013` 登记来源,本提案落地不改变它的输出。要受益,等本库发版后把那里的 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`(见「非目标」)。 - MachOKitUI、SymbolViewer:不用 `SwiftTypeNameResolution`,不受影响。 ### 文档与示例 @@ -249,7 +267,8 @@ extension SwiftInterfaceBuilderTypeNameProvider { - 行为:`fileNamesTheTypedefOfEveryExportedTypeIDFunction`(`FixtureCompiler` 现场编译的 C 库导出 `ProbeWidgetGetTypeID`、`_ProbeSecretGetTypeID`、`ProbeWidgetCreate`、`GetTypeID`、`__GetTypeID`,经 `MachOFile` 读出的名字恰好是 `ProbeWidgetRef`、`_ProbeSecretRef`、`ProbeSecretRef`) - 行为:`loadedImageNamesTheSameTypedefs`(同一个库 `dlopen` 后经 `MachOImage` 读出同样的名字) - 行为:`coreSVGDeclaresItsPrivateDocumentType`(本机 cache 里的 CoreSVG,文件与进程内两种读法都给出 `CGSVGDocumentRef`) -2. **provider 登记新来源,端到端验证** —— 改动地图第 3、4 行(`Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift`) +2. ✅ **合成来源、provider 登记新来源,端到端验证** —— 改动地图第 3–6 行(`ImageDeclaredTypeNamesTests.swift`、`PrivateCFTypeModuleTests.swift`;Ultra,Xcode 26.6,`SwiftTypeNameResolutionTests` 13 个测试通过。`aPrivateCFTypePrintsUnderTheImageExportingItsTypeID` 在合成来源之前是红的,见决策日志) + - 行为:`listsTheObjectiveCClassAndTheCFTypeOfOneImage`(本机 cache 的 IOSurface 一个来源里同时有 ObjC 类 `IOSurface` 与 CF 类型 `IOSurfaceRef`) - 夹具:C 库 `ProbeCF` 导出 `ProbeWidgetGetTypeID`;Swift 库 `ProbeKit` 用桥接头声明两个 `CF_BRIDGED_TYPE(id)` 的 typedef,链接 `ProbeCF`,并用 `@_cdecl` 自己导出 `ProbeGadgetGetTypeID`。`FixtureCompiler` 把 install name 固定成 `@rpath/lib<名字>.dylib`,所以模块名是 `libProbeCF`、`libProbeKit` - 行为:`aPrivateCFTypePrintsUnderTheImageExportingItsTypeID`(字段类型印成 `libProbeCF.ProbeWidget`) - 行为:`aCFTypeTheRootDefinesPrintsUnderTheRootsModule`(根镜像自己定义的印成 `libProbeKit.ProbeGadget`) @@ -272,3 +291,4 @@ extension SwiftInterfaceBuilderTypeNameProvider { | 2026-11-25 | `IOSurfaceRef` 疑似问题先复现 | 用户定:先在 Ultra 上复现调研第 10 条,确认是真的再按 bug 修复另走一批,不并入本提案。 | | 2026-11-25 | 用户批准,开始实现 | 轻量档,用户看过简报后批准。功能分支从本地 `next` 切,因为 moved-swift-type-modules 的本地合并也改了 provider 的 `setup()`,从 `origin/next` 切会在合回时冲突。 | | 2026-11-25 | 测试都放在公开 seam 上 | 命名规则不单独测内部静态函数,改由现场编译的 C 库的导出覆盖各种写法;来源顺序不单独测内部函数,改由端到端测试证明根镜像与依赖各自归属。`declaredTypeNameSources(root:dependencies:)` 仍按设计抽成内部静态函数。 | +| 2026-11-25 | 新增 `ImageDeclaredTypeNames`,一个依赖只登记一个来源 | 偏离原方案。端到端测试发现依赖定义的私有 CF 类型仍印裸名:`TypeDatabase.register(dependencies:)` 按镜像路径去重,同一依赖先登记的 `ObjCDeclaredTypeNames` 占了位置,随后的 `CFDeclaredTypeNames` 被丢掉;根镜像只有一个来源,所以那条通过了。改为每个依赖登记一个合成两种名字的 `ImageDeclaredTypeNames`,方案方向不变,多一个纯新增的公开类型;RuntimeViewer 的后续接入也要用它。 | From 403cd9d2341056deff897274a99721785deb073b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:18:35 +0800 Subject: [PATCH 108/175] docs: say --resolve-c-module-names attributes a private CF type to the image exporting its GetTypeID The interface command's help, the swift-section skill and the module list name the new sources, and the skill spells out what stays unresolved: a re-exported sub-framework, a transitive dependency, and a reference with no descriptor in the binary, which keeps its `Ref` spelling under the module. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../swift-section/skills/swift-section-cli/SKILL.md | 13 +++++++++++-- .../swift-section/Commands/InterfaceCommand.swift | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b1de7cba..9001a203 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ One or two lines each; the linked document is the authority. - **ARM64InstructionDecoding** (MachOKitExtensions) — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). - **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. - **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). -- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([moved-swift-type-modules](Documentations/Evolutions/draft-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. +- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. A private CF type (no SDK header) is attributed to the image exporting its `…GetTypeID` through `CFDeclaredTypeNames` — registered alone for the root, and for each direct dependency inside an `ImageDeclaredTypeNames` with its ObjC names, because `TypeDatabase` keeps only the first source per image path and silently drops a second ([private-cf-type-modules](Documentations/Evolutions/draft-private-cf-type-modules.md)). Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([moved-swift-type-modules](Documentations/Evolutions/draft-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index cab65124..19797d13 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -359,8 +359,17 @@ that name (`PencilKit.PKDrawingReference`). Needs macOS 13+ and the binary's SDK developer directory — Xcode, or the Command Line Tools for macOS and Mac Catalyst binaries. The first run per SDK generates module interfaces through sourcekitd — slow once (UIKit takes about two minutes), cached after in `~/Library/Application Support/swift-type-indexing`. Without sourcekitd only -API notes and Objective-C metadata attribute names. A binary whose SDK is not installed warns and -prints `__C.` unresolved. `--supplementary-apinotes` only does anything alongside it. +API notes, Objective-C metadata and exported `GetTypeID` functions attribute names. A binary whose SDK +is not installed warns and prints `__C.` unresolved. `--supplementary-apinotes` only does anything +alongside it. + +**A private CF type is attributed to the image exporting its `GetTypeID`.** No SDK header declares +`CGSVGDocumentRef`, but CoreSVG exports `CGSVGDocumentGetTypeID`, so SwiftUICore's reference prints +as `CoreSVG.CGSVGDocument`. Only the binary itself and its direct dependencies are read: a type whose +function lives in a re-exported sub-framework (LaunchServices under CoreServices) or a transitive +dependency keeps the bare Swift name. A reference with no descriptor in the binary keeps the C +spelling under the module (`CoreSVG.CGSVGDocumentRef`) — readable, though Swift spells it without +`Ref`. **Swift names come first, with or without the SDK.** A C type has two names: its descriptor carries the one Swift code uses, every mangled reference the C one. `interface` prints the Swift one everywhere diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 1e970f06..6ec69999 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -30,7 +30,7 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Parse opaque return value, this option is an experimental feature and may result in parsing errors for complex return types.") var parseOpaqueReturnType: Bool = false - @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, and its dependencies' ObjC metadata. Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") + @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, its dependencies' ObjC metadata, and the CF types the binary and its dependencies export a GetTypeID function for (a private CF type: __C.CGSVGDocumentRef -> CoreSVG.CGSVGDocument). Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") var resolveCModuleNames: Bool = false @Flag(help: "Print a Swift type the SDK moved to another module (@_originallyDefinedIn) under the module that declares it now (CoreGraphics.CGFloat -> CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary was built against an SDK that had already moved it. Reads the SDK's .swiftinterface files: needs Xcode or the Command Line Tools, not sourcekitd. macOS only.") From 6b74b731a41fbab464a0ba7ff10d14e9fff0425e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:28:31 +0800 Subject: [PATCH 109/175] Pin that a bridged CF type without a GetTypeID function keeps its bare Swift name Co-Authored-By: Claude Opus 5.5 --- .../PrivateCFTypeModuleTests.swift | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift index 188bc0fa..b05c8b34 100644 --- a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift +++ b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift @@ -17,7 +17,9 @@ import Testing /// exporting `ProbeWidgetGetTypeID`. `ProbeKit` stands for SwiftUICore: a Swift /// library whose bridging header declares the CF types, which links `ProbeCF` /// and defines a CF type of its own, exporting `ProbeGadgetGetTypeID` through -/// `@_cdecl`. `FixtureCompiler` gives every library the install name +/// `@_cdecl`, and declares a third, `ProbeLonelyRef`, that no image exports a +/// `GetTypeID` for — a bridged type made up without the CF convention. +/// `FixtureCompiler` gives every library the install name /// `@rpath/lib.dylib`, and `TypeDatabase` names a module after the /// install name's file, so the two modules read `libProbeCF` and `libProbeKit`. @Suite @@ -30,10 +32,11 @@ struct PrivateCFTypeModuleTests { #include typedef struct CF_BRIDGED_TYPE(id) __ProbeWidget *ProbeWidgetRef; typedef struct CF_BRIDGED_TYPE(id) __ProbeGadget *ProbeGadgetRef; + typedef struct CF_BRIDGED_TYPE(id) __ProbeLonely *ProbeLonelyRef; CFTypeID ProbeWidgetGetTypeID(void); """ - /// `Anchor` keeps a `__DATA` segment in the dylib. Hashing the two CF + /// `Anchor` keeps a `__DATA` segment in the dylib. Hashing the CF /// types through a generic function makes the library carry their type /// descriptors, and calling `ProbeWidgetGetTypeID` keeps `ProbeCF` among /// its load commands. @@ -45,10 +48,12 @@ struct PrivateCFTypeModuleTests { public struct Holder { public var widget: ProbeWidget public var gadget: ProbeGadget + public var lonely: ProbeLonely - public init(widget: ProbeWidget, gadget: ProbeGadget) { + public init(widget: ProbeWidget, gadget: ProbeGadget, lonely: ProbeLonely) { self.widget = widget self.gadget = gadget + self.lonely = lonely } } @@ -63,7 +68,7 @@ struct PrivateCFTypeModuleTests { } public func exercise(_ holder: Holder) -> Int { - hashValue(of: holder.widget) &+ hashValue(of: holder.gadget) &+ Int(ProbeWidgetGetTypeID()) + hashValue(of: holder.widget) &+ hashValue(of: holder.gadget) &+ hashValue(of: holder.lonely) &+ Int(ProbeWidgetGetTypeID()) } """ @@ -116,6 +121,15 @@ struct PrivateCFTypeModuleTests { #expect(interface.contains("gadget: libProbeKit.ProbeGadget"), "\(interface)") } + /// No image exports `ProbeLonelyGetTypeID`, and nothing else in the binaries + /// names the module that declares `ProbeLonelyRef` — the class it is + /// bridged to is not recorded — so it keeps the descriptor's bare name. + @Test + func aBridgedTypeWithoutATypeIDFunctionKeepsItsBareSwiftName() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("lonely: ProbeLonely\n"), "\(interface)") + } + /// What 0106 alone prints: the descriptor's Swift name, with no module. @Test func withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName() async throws { From b63d180ccf37d4ad802f77e54e8e5242b9cc11a1 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:31:07 +0800 Subject: [PATCH 110/175] Test that a GetTypeID export does not claim a C typedef that is no CF class Co-Authored-By: Claude Opus 5.5 --- .../PrivateCFTypeModuleTests.swift | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift index b05c8b34..1253c722 100644 --- a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift +++ b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift @@ -18,7 +18,9 @@ import Testing /// library whose bridging header declares the CF types, which links `ProbeCF` /// and defines a CF type of its own, exporting `ProbeGadgetGetTypeID` through /// `@_cdecl`, and declares a third, `ProbeLonelyRef`, that no image exports a -/// `GetTypeID` for — a bridged type made up without the CF convention. +/// `GetTypeID` for — a bridged type made up without the CF convention. `ProbeCF` +/// also exports `ProbeDecoyGetTypeID` while `ProbeKit`'s `ProbeDecoyRef` is a +/// `swift_wrapper` struct, no CF class: a `GetTypeID` export alone must not claim it. /// `FixtureCompiler` gives every library the install name /// `@rpath/lib.dylib`, and `TypeDatabase` names a module after the /// install name's file, so the two modules read `libProbeCF` and `libProbeKit`. @@ -26,6 +28,7 @@ import Testing struct PrivateCFTypeModuleTests { private static let probeCFSource = """ unsigned long ProbeWidgetGetTypeID(void) { return 1; } + unsigned long ProbeDecoyGetTypeID(void) { return 3; } """ private static let probeKitBridgingHeader = """ @@ -33,6 +36,7 @@ struct PrivateCFTypeModuleTests { typedef struct CF_BRIDGED_TYPE(id) __ProbeWidget *ProbeWidgetRef; typedef struct CF_BRIDGED_TYPE(id) __ProbeGadget *ProbeGadgetRef; typedef struct CF_BRIDGED_TYPE(id) __ProbeLonely *ProbeLonelyRef; + typedef unsigned int ProbeDecoyRef __attribute__((swift_wrapper(struct))); CFTypeID ProbeWidgetGetTypeID(void); """ @@ -49,11 +53,13 @@ struct PrivateCFTypeModuleTests { public var widget: ProbeWidget public var gadget: ProbeGadget public var lonely: ProbeLonely + public var decoy: ProbeDecoyRef - public init(widget: ProbeWidget, gadget: ProbeGadget, lonely: ProbeLonely) { + public init(widget: ProbeWidget, gadget: ProbeGadget, lonely: ProbeLonely, decoy: ProbeDecoyRef) { self.widget = widget self.gadget = gadget self.lonely = lonely + self.decoy = decoy } } @@ -68,7 +74,7 @@ struct PrivateCFTypeModuleTests { } public func exercise(_ holder: Holder) -> Int { - hashValue(of: holder.widget) &+ hashValue(of: holder.gadget) &+ hashValue(of: holder.lonely) &+ Int(ProbeWidgetGetTypeID()) + hashValue(of: holder.widget) &+ hashValue(of: holder.gadget) &+ hashValue(of: holder.lonely) &+ hashValue(of: holder.decoy) &+ Int(ProbeWidgetGetTypeID()) } """ @@ -130,6 +136,16 @@ struct PrivateCFTypeModuleTests { #expect(interface.contains("lonely: ProbeLonely\n"), "\(interface)") } + /// The decoy's descriptor is a struct promoted from a C typedef, not the + /// foreign class ClangImporter gives a CF type, so `ProbeCF`'s + /// `ProbeDecoyGetTypeID` says nothing about it. + @Test + func aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("var decoy: "), "\(interface)") + #expect(!interface.contains("libProbeCF.ProbeDecoyRef"), "\(interface)") + } + /// What 0106 alone prints: the descriptor's Swift name, with no module. @Test func withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName() async throws { From e8c2ccc9a170ca177a62a9bdf313924d8ad35aee Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:32:08 +0800 Subject: [PATCH 111/175] Let a GetTypeID export claim only the CF types the root's foreign class descriptors name The export says where a type lives; whether a name is a CF type at all is the root's own Swift metadata to say: a C-imported class descriptor promoted from a typedef is the foreign class ClangImporter makes of a CF type. Without that check `ProbeCF`'s `ProbeDecoyGetTypeID` claimed a `swift_wrapper` struct named `ProbeDecoyRef`, and `CFGetTypeID` the non-type `CFRef`. Co-Authored-By: Claude Opus 5.5 --- .../CFDeclaredTypeNames.swift | 19 +++++++++- .../ImageDeclaredTypeNames.swift | 9 ++++- ...wiftInterfaceBuilderTypeNameProvider.swift | 37 ++++++++++++++++++- 3 files changed, 61 insertions(+), 4 deletions(-) diff --git a/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift index 98f8e97d..f5ced784 100644 --- a/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift +++ b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift @@ -31,21 +31,38 @@ public struct CFDeclaredTypeNames: Declare private let machO: MachO + /// The only typedef names this source may give, or `nil` for every one the + /// exports imply. + private let admittedTypedefNames: Set? + /// - Parameters: /// - machO: The image, in this process or in a file. /// - imagePath: Its install path, which names the module its types are /// attributed to (`…/CoreSVG.framework/Versions/A/CoreSVG` → `CoreSVG`). public init(machO: MachO, imagePath: String) { + self.init(machO: machO, imagePath: imagePath, restrictedTo: nil) + } + + /// A source giving only the names in `admittedTypedefNames` — the CF types + /// a binary's foreign class descriptors confirm, so that an export whose + /// name only looks like the convention (`CFGetTypeID`) or meets a typedef + /// that is no CF class claims nothing. + init(machO: MachO, imagePath: String, restrictedTo admittedTypedefNames: Set?) { self.machO = machO self.imagePath = imagePath + self.admittedTypedefNames = admittedTypedefNames } /// The typedef name of every CF type the image exports a `GetTypeID` /// function for. public func declaredTypeNames() async -> [String] { - machO.exportedSymbols.flatMap { exportedSymbol in + let typedefNames = machO.exportedSymbols.flatMap { exportedSymbol in Self.typedefNames(forExportedSymbolName: exportedSymbol.name) } + guard let admittedTypedefNames else { + return typedefNames + } + return typedefNames.filter { admittedTypedefNames.contains($0) } } /// The typedef names an exported symbol implies, by the CF convention that diff --git a/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift index 603b92ba..916e7812 100644 --- a/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift +++ b/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift @@ -34,9 +34,16 @@ public struct ImageDeclaredTypeNames: DeclaredTypeNam /// attributed to (`…/IOSurface.framework/Versions/A/IOSurface` → /// `IOSurface`). public init(machO: MachO, imagePath: String) { + self.init(machO: machO, imagePath: imagePath, restrictingCFTypesTo: nil) + } + + /// A source whose CF part gives only the names in `admittedTypedefNames` + /// (`CFDeclaredTypeNames.init(machO:imagePath:restrictedTo:)`); the + /// Objective-C names are all given. + init(machO: MachO, imagePath: String, restrictingCFTypesTo admittedTypedefNames: Set?) { self.imagePath = imagePath self.objectiveCTypeNames = ObjCDeclaredTypeNames(machO: machO, imagePath: imagePath) - self.coreFoundationTypeNames = CFDeclaredTypeNames(machO: machO, imagePath: imagePath) + self.coreFoundationTypeNames = CFDeclaredTypeNames(machO: machO, imagePath: imagePath, restrictedTo: admittedTypedefNames) } /// The Objective-C names, then the CF typedef names. Throws when the diff --git a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift index 0806ab8a..59f54255 100644 --- a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift +++ b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift @@ -104,11 +104,44 @@ public final class SwiftInterfaceBuilderTypeNameProvider [any DeclaredTypeNameSource] { - let rootSource: any DeclaredTypeNameSource = CFDeclaredTypeNames(machO: root, imagePath: root.imagePath) + let referencedCFTypedefNames = cfTypedefNames(referencedBy: root) + let rootSource: any DeclaredTypeNameSource = CFDeclaredTypeNames(machO: root, imagePath: root.imagePath, restrictedTo: referencedCFTypedefNames) return [rootSource] + dependencies.map { dependency in - ImageDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath) + ImageDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath, restrictingCFTypesTo: referencedCFTypedefNames) + } + } + + /// The typedef names of the CF types `image`'s Swift metadata refers to: + /// its C-imported class descriptors promoted from a C typedef — the + /// foreign class ClangImporter makes of a CF type (a struct or enum from + /// a `swift_wrapper` typedef shares the import info, not the kind). Named + /// by the ABI name a mangling spells, or by the descriptor's own name when + /// ClangImporter kept the C spelling (`IOSurfaceRef`, whose stripped name + /// the Objective-C class `IOSurface` took). + static func cfTypedefNames(referencedBy image: MachO) -> Set { + let context = image.context + var typedefNames: Set = [] + for descriptorWrapper in (try? image.swift.typeContextDescriptors) ?? [] { + guard case .class = descriptorWrapper else { continue } + let descriptor = descriptorWrapper.typeContextDescriptor + guard descriptor.hasImportInfo, + (try? descriptor.isCImportedContextDescriptor(in: context)) == true, + let importInfo = try? descriptor.typeImportInfo(in: context), + importInfo.isCTypedef, + !importInfo.isRelatedEntity + else { continue } + if let abiName = importInfo.abiName { + typedefNames.insert(abiName) + } else if let descriptorName = try? descriptorWrapper.namedContextDescriptor.name(in: context) { + typedefNames.insert(descriptorName) + } } + return typedefNames } public func moduleName(forTypeName typeName: String) async -> String? { From 418dea5f819339eb5788ef573d6df489ae8f1033 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:32:58 +0800 Subject: [PATCH 112/175] docs: say a GetTypeID export only locates a CF type the binary's own metadata names Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../swift-section/skills/swift-section-cli/SKILL.md | 7 ++++--- .../swift-section/Commands/InterfaceCommand.swift | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9001a203..178cc766 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ One or two lines each; the linked document is the authority. - **ARM64InstructionDecoding** (MachOKitExtensions) — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). - **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. - **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). -- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. A private CF type (no SDK header) is attributed to the image exporting its `…GetTypeID` through `CFDeclaredTypeNames` — registered alone for the root, and for each direct dependency inside an `ImageDeclaredTypeNames` with its ObjC names, because `TypeDatabase` keeps only the first source per image path and silently drops a second ([private-cf-type-modules](Documentations/Evolutions/draft-private-cf-type-modules.md)). Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([moved-swift-type-modules](Documentations/Evolutions/draft-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. +- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. A private CF type (no SDK header) is attributed to the image exporting its `…GetTypeID` through `CFDeclaredTypeNames` — registered alone for the root, and for each direct dependency inside an `ImageDeclaredTypeNames` with its ObjC names, because `TypeDatabase` keeps only the first source per image path and silently drops a second. The export only locates a type: it claims a name only when the root's foreign class descriptors confirm a CF class (`cfTypedefNames(referencedBy:)`) ([private-cf-type-modules](Documentations/Evolutions/draft-private-cf-type-modules.md)). Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([moved-swift-type-modules](Documentations/Evolutions/draft-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index 19797d13..3e974739 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -367,9 +367,10 @@ alongside it. `CGSVGDocumentRef`, but CoreSVG exports `CGSVGDocumentGetTypeID`, so SwiftUICore's reference prints as `CoreSVG.CGSVGDocument`. Only the binary itself and its direct dependencies are read: a type whose function lives in a re-exported sub-framework (LaunchServices under CoreServices) or a transitive -dependency keeps the bare Swift name. A reference with no descriptor in the binary keeps the C -spelling under the module (`CoreSVG.CGSVGDocumentRef`) — readable, though Swift spells it without -`Ref`. +dependency keeps the bare Swift name. The export only says where a type lives: a name is attributed +this way only when the binary's own metadata shows it is a CF class (a C-imported class descriptor +promoted from a typedef), so a reference with no such descriptor stays `__C.CGSVGDocumentRef`, and a +bridged type nobody exports a `GetTypeID` for keeps its bare name. **Swift names come first, with or without the SDK.** A C type has two names: its descriptor carries the one Swift code uses, every mangled reference the C one. `interface` prints the Swift one everywhere diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index 6ec69999..623778ed 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -30,7 +30,7 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Parse opaque return value, this option is an experimental feature and may result in parsing errors for complex return types.") var parseOpaqueReturnType: Bool = false - @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, its dependencies' ObjC metadata, and the CF types the binary and its dependencies export a GetTypeID function for (a private CF type: __C.CGSVGDocumentRef -> CoreSVG.CGSVGDocument). Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") + @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, its dependencies' ObjC metadata, and, for a CF class the binary's own metadata names, the image among the binary and its dependencies that exports its GetTypeID function (a private CF type: __C.CGSVGDocumentRef -> CoreSVG.CGSVGDocument). Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") var resolveCModuleNames: Bool = false @Flag(help: "Print a Swift type the SDK moved to another module (@_originallyDefinedIn) under the module that declares it now (CoreGraphics.CGFloat -> CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary was built against an SDK that had already moved it. Reads the SDK's .swiftinterface files: needs Xcode or the Command Line Tools, not sourcekitd. macOS only.") From 2ebcbb0fbe87cd7597ca23b10fcf4ecd9b51153b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:37:20 +0800 Subject: [PATCH 113/175] docs: record the foreign-descriptor gate and the system-image results in the private-cf-type-modules proposal Co-Authored-By: Claude Opus 5.5 --- .../draft-private-cf-type-modules.html | 187 ++++++++++-------- .../draft-private-cf-type-modules.md | 54 ++++- 2 files changed, 149 insertions(+), 92 deletions(-) diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.html b/Documentations/Evolutions/draft-private-cf-type-modules.html index 6dd71917..2e1cd49d 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.html +++ b/Documentations/Evolutions/draft-private-cf-type-modules.html @@ -192,17 +192,14 @@

    Draft 私有 CF 类型按导出 G

    摘要

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

    -

    本提案在 SwiftTypeNameResolution 里新增 CFDeclaredTypeNames,它是 swift-type-indexing 的 DeclaredTypeNameSource 的又一个实现:从镜像的导出表里找出每个 …GetTypeID 函数,列出它定义的 CF 类型(_CGSVGDocumentGetTypeID → CGSVGDocumentRef)。SwiftInterfaceBuilderTypeNameProvider 为根镜像和每个直接依赖各登记一个。之后 CGSVGDocumentRef 归到 CoreSVG,引用印成 CoreSVG.CGSVGDocument。打印器、swift-type-indexing 和 CLI 参数都不改。

    +

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

    要你定

    -

    两件事

    -
      -
    1. 实现形式:用 swift-type-indexing 现成的 DeclaredTypeNameSource 注册表(提案的做法),而不是在打印器上另注册一个解析器(讨论时最先选的方向)。理由见替代方案第 1 条。
    2. -
    3. 调研第 10 条的 IOSurfaceRef 疑似问题(可能被印成 IOSurface.IOSurface):是否先在 Ultra 上复现,再另行修复。
    4. -
    +

    没有悬而未决的事

    +

    实现已完成,在本地合进常驻检出后可以就地看效果;看过后用 finish-feature 收尾。后续项(RuntimeViewer 接入、模块名与类型同名时用模块选择器)见「非目标」。

    @@ -215,29 +212,31 @@

    架构图

    改了什么

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

    实线:调用;虚线:遵循协议。swift-type-indexing 与打印器都不改,新来源只是让 moduleName(forTypeName:) 多答出一些名字。

    +

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

    一个引用怎么印出来

    @@ -245,8 +244,8 @@

    一个引用怎么印出来

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

    改动地图

    - - - - - - - + + + + + + + + + @@ -277,17 +278,19 @@

    改动地图

    提议方案

      -
    1. 新增 CFDeclaredTypeNames,与 ObjCDeclaredTypeNames 同形:init(machO:imagePath:),declaredTypeNames() 读 machO.exportedSymbols,每个名为 _<名字>GetTypeID 的导出给出 <名字>Ref;<名字> 以下划线开头的私有函数(__LSASNGetTypeID)同时给出去掉前导下划线的拼写(LSASNRef)。
    2. -
    3. provider 登记它:来源变成「根镜像的 CFDeclaredTypeNames,然后每个直接依赖依次是 ObjCDeclaredTypeNames、CFDeclaredTypeNames」。根镜像排第一,它自己定义的类型由它自己说了算;根镜像不进 moduleFilter,不触发 SourceKit 接口生成。
    4. +
    5. CFDeclaredTypeNames:每个 _<名字>GetTypeID 导出给出 <名字>Ref;以下划线开头的私有函数(__LSASNGetTypeID)同时给出去掉前导下划线的拼写。
    6. +
    7. ImageDeclaredTypeNames:一个镜像的 ObjC 名字在前、CF 名字在后,合成一个来源。分开登记的话,后登记的那个永远读不到。
    8. +
    9. provider 登记它们:根镜像的 CFDeclaredTypeNames,然后每个直接依赖一个 ImageDeclaredTypeNames。GetTypeID 只负责定位,「是不是 CF 类型」由 foreign 描述符决定:CF 来源只给出根镜像的 foreign class 描述符证实的名字。
    10. 打印器、swift-type-indexing、CLI 参数都不改,只补帮助文字和 skill 说明。

    非目标

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

    详细设计

    public struct CFDeclaredTypeNames<MachO: MachORepresentable & Sendable>: DeclaredTypeNameSource {
         public let imagePath: String
    -
    -    private let machO: MachO
    -
         public init(machO: MachO, imagePath: String)
    -
    -    /// The typedef name of every CF type the image exports a `GetTypeID` function for.
    +    init(machO: MachO, imagePath: String, restrictedTo admittedTypedefNames: Set<String>?)   // internal
         public func declaredTypeNames() async -> [String]
    +}
     
    -    /// `_CGSVGDocumentGetTypeID` → ["CGSVGDocumentRef"], `__LSASNGetTypeID` → ["_LSASNRef", "LSASNRef"].
    -    static func typedefNames(forExportedSymbolName symbolName: String) -> [String]
    +public struct ImageDeclaredTypeNames<MachO: ObjCMetadataSource>: DeclaredTypeNameSource {
    +    public let imagePath: String
    +    public init(machO: MachO, imagePath: String)
    +    init(machO: MachO, imagePath: String, restrictingCFTypesTo admittedTypedefNames: Set<String>?)   // internal
    +    public func declaredTypeNames() async throws -> [String]
     }
     
     extension SwiftInterfaceBuilderTypeNameProvider {
         static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource]
    +    static func cfTypedefNames(referencedBy image: MachO) -> Set<String>
     }
    -

    形状照 ObjCDeclaredTypeNames 抄。泛型约束只要 MachORepresentable & Sendable:exportedSymbols 是 MachOKit MachORepresentable 的要求,MachOFile、MachOImage 和包装类型都有,不需要判断读取器种类。协议要求是 async throws,实现不会失败,写成不抛错的 async。

    +

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

    命名规则
      -
    1. 导出名必须以一个 _ 开头,去掉它得到 C 函数名;Swift 符号和 Objective-C 符号因为不以 GetTypeID 结尾自然落选。
    2. -
    3. C 函数名以 GetTypeID 结尾,去掉后缀的部分非空、由字母数字和下划线组成、不以数字开头,记为 base。
    4. -
    5. 给出 base + "Ref";base 以下划线开头时,再给出去掉全部前导下划线后的 + "Ref"。
    6. -
    7. CFGetTypeID 给出的 CFRef 这类不是类型的名字不做过滤:只在查询恰好问到它时才命中,而那时 SDK 的归属已经先问过了。
    8. +
    9. 导出名以一个 _ 开头,去掉它得到 C 函数名。
    10. +
    11. C 函数名以 GetTypeID 结尾,去掉后缀的部分是合法 C 标识符且不全是下划线,记为 base。
    12. +
    13. 给出 base + "Ref";base 以下划线开头时再给出去掉前导下划线的拼写。
    14. +
    15. 规则会产生 CFRef 这类非类型名字;provider 登记的来源都带闸门,只留根镜像证实的名字。
    性能
    -

    TypeDatabase 只在一个名字查不到时才按顺序读下一个来源。根镜像排第一,第一次未命中就会读一遍根镜像的导出表:SwiftUICore 这样的大镜像有数十万个导出。第 3 步在 Ultra 上量一次耗时变化;明显的话,改成直接遍历导出 trie、只取以 GetTypeID 结尾的名字。

    +

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

    动机

    -

    按代码推断(没有实跑 CLI):macOS 27.2 的 SwiftUICore 用到私有的 CGSVGDocumentRef,0106 之后印成没有模块的 CGSVGDocument,公开的 CGImageRef 则印成 CoreGraphics.CGImage。读者分不出它来自哪个框架。

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

    文件 / 类型动作改什么为什么步骤
    Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift · CFDeclaredTypeNames新增DeclaredTypeNameSource 的实现:读导出表,…GetTypeID → typedef 名;内部静态函数 typedefNames(forExportedSymbolName:) 承载命名规则私有 CF 类型的模块证据1
    Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift新增命名规则的表驱动测试;现场编译的 C 动态库经 MachOFile 与 MachOImage 两种读法读出的名字规则与两种读法1
    Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98 · setup()修改来源改为「根的 CF,然后每个依赖的 ObjC、CF」;排列抽成 internal 的 static func declaredTypeNameSources(root:dependencies:)登记新来源,顺序可测2
    Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift新增来源顺序;TypeDatabase 按新来源归属模块;用现场编译的 Swift 库验证接口里的拼写端到端证明2
    Sources/Executables/swift-section/Commands/InterfaceCommand.swift:33修改--resolve-c-module-names 的帮助文字补上「依赖导出的 …GetTypeID(CF 类型)」--help 就是文档3
    AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md 第 8 节修改归属来源补上导出的 GetTypeID;加一句私有 CF 类型的效果与 XRef 退路CLI 行为变了,skill 同批更新3
    CLAUDE.md · SwiftTypeNameResolution 一条修改列出 CFDeclaredTypeNames模块清单与代码同步3
    Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift新增DeclaredTypeNameSource:读导出表,…GetTypeID → typedef 名;internal 的带闸门构造器私有 CF 类型的模块证据1
    Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift新增现场编译的 C 库经两种读法读出的名字;本机 cache 的 CoreSVG规则与两种读法1
    Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift新增一个镜像的 ObjC 名字与 CF 类型合成一个来源TypeDatabase 每个镜像路径只收一个来源2
    Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift新增IOSurface 同时列出 IOSurface 与 IOSurfaceRef合成来源两种名字都在2
    Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift · setup()修改来源改为「根的 CF,然后每个依赖一个 ImageDeclaredTypeNames」;cfTypedefNames(referencedBy:) 从根镜像的 foreign 描述符收集闸门集合登记新来源,判定靠描述符2
    Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift新增端到端:依赖定义的、根镜像定义的、不导出 GetTypeID 的、诱饵 swift_wrapper、不挂 provider 的端到端证明2
    Sources/Executables/swift-section/Commands/InterfaceCommand.swift修改--resolve-c-module-names 的帮助文字--help 就是文档3
    AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md 第 8 节修改私有 CF 类型的归属、哪些情况仍不解析CLI 行为变了3
    CLAUDE.md(AGENTS.md)修改模块清单列出两个新类型、闸门与去重的坑模块清单与代码同步3
    Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案;落地时改编号与状态文档索引0、3
    Documentations/Internal/ProjectEvolutionLog.md修改落地时追加一节演进账本3
    - + @@ -349,8 +352,8 @@

    动机

    - - + +
    私有 CF 类型描述符里的 Swift 名导出 GetTypeID 的镜像用到它的 Swift 镜像
    私有 CF 类型Swift 名导出 GetTypeID 的镜像用到它的 Swift 镜像
    CGSVGDocumentRefCGSVGDocumentCoreSVGSwiftUICore
    CGColorTransformRef、CGContextDelegateRef去掉 RefCoreGraphicsAppKit
    RIOPxrSdfLayerRef 等 9 个去掉 RefCoreRealityIORealityIO
    CAXUIElementRefCAXUIElementCoreAccessibilityCoreAccessibility(自己)
    CFPhoneNumberRefCFPhoneNumberCorePhoneNumbersIDSFoundation
    LSASNRefLSASNLaunchServices(__LSASNGetTypeID)GamePolicyFoundation
    CFXGPUDeviceRef、LXEntryRef、RTIImportOperation_tCFXGPUDevice、LXEntry、ImportOperation找不到VFX、ImageGenerationServices、_USDKit_RealityKit
    LSASNRefLSASNLaunchServicesGamePolicyFoundation
    CFXGPUDeviceRef、LXEntryRef、RTIImportOperation_t…找不到VFX 等
    @@ -362,16 +365,16 @@

    调研

    十条查证过的事实
      -
    1. 哪些是 CF 类、怎么枚举:ClangImporter 把指向带 objc_bridge 系列 attribute 的 struct 的指针 typedef 导入成 ForeignKind::CFType 的类,并合成 _CFObject 一致性;描述符种类是 class,import info 写着 N<typedef 名> 和 St。ipsw dyld swift --foreign 导出 dyld 预存的 __C 一致性表,按 _CFObject 筛出 66 个 CF 类。
    2. -
    3. 模块不在二进制里:描述符挂在 __C,合成的一致性在 __C_Synthesized。Swift 取顶层 Clang 模块(ClangImporter.cpp:3143-3154),LaunchServices 的类型属于 CoreServices。
    4. -
    5. GetTypeID 的镜像就是模块:46 个公开 CF 类全部一致;私有的 20 个里 17 个能找到导出;Core* 框架约有 190 个不在公开 SDK 里的 …GetTypeID。
    6. -
    7. 打印器已经会用描述符的名字:引用处模块解析后,标识符依次取解析器的 Swift 名、0106 名字表、C 名(TypeNodePrintable.swift:186-268),声明行同理(SwiftDeclarationPrinter+Headers.swift:153-183)。
    8. -
    9. swift-type-indexing 已有开放注册表:DeclaredTypeNameSource,SDK 答不上时按登记顺序读,第一个声明者胜出;这个包自己不读 Mach-O;ObjCDeclaredTypeNames 是现有唯一实现,不含 CF 类型。
    10. -
    11. 去 Ref 规则只认 SDK 里有的名字:私有 CF 类型拿不到解析器给的 Swift 名,走描述符那一档,AGGraphRef 正确地印成 Graph。
    12. -
    13. 现在谁被登记:provider 只给直接依赖登记 ObjC 来源,根镜像不登记;只有 interface --resolve-c-module-names 接上它;RuntimeViewer 自己给打开的每个镜像登记来源。
    14. -
    15. 覆盖面:直接依赖覆盖 14 个,登记根镜像后 15 个;剩下的是重新导出(1)、间接依赖(1)、没有导出(3)。
    16. -
    17. 带 Ref 的名字在 Swift 里不能用:只剩改名用的兼容别名;没有描述符时会印成 CoreSVG.CGSVGDocumentRef。IOSurfaceRef 因为和 ObjC 类 IOSurface 重名而保留 Ref。
    18. -
    19. 顺带发现、未验证:去 Ref 规则不看重名,而打印器先问解析器,__C.IOSurfaceRef 可能被印成 IOSurface.IOSurface。
    20. +
    21. CF 类导入成 ForeignKind::CFType 的类并合成 _CFObject;描述符种类 class,import info 写着 N<typedef 名> 与 St。
    22. +
    23. 模块不在二进制里;Swift 取顶层 Clang 模块。
    24. +
    25. GetTypeID 的镜像就是模块:46 个公开 CF 类全部一致。
    26. +
    27. 打印器在模块解析出来以后已经会用描述符的名字。
    28. +
    29. swift-type-indexing 已有 DeclaredTypeNameSource 注册表;TypeDatabase 按镜像路径去重,同一路径的第二个来源被丢掉(实现时由端到端测试发现)。
    30. +
    31. 去 Ref 规则只认 SDK 里有的名字,私有类型走描述符名(AGGraphRef → Graph)。
    32. +
    33. provider 只读直接依赖;RuntimeViewer 自己给每个镜像登记来源。
    34. +
    35. 按设计 20 个里覆盖 15 个;实测覆盖更多(有描述符但没有一致性记录的也算上)。
    36. +
    37. 带 Ref 的拼写在 Swift 里不能用;IOSurfaceRef 因为和 ObjC 类 IOSurface 重名而保留 Ref。
    38. +
    39. IOSurfaceRef 疑似问题未复现:TextRecognition 印 CoreGraphics.IOSurfaceRef,能编过;IOSurface.IOSurfaceRef 因模块名被同名类遮住编不过,要写 IOSurface::IOSurfaceRef。

    @@ -380,15 +383,16 @@

    调研

    替代方案

    - 六条被否或推迟的方向 + 七条被否或推迟的方向
      -
    1. 打印器上另注册一个 ModuleNameResolving:否。注册表已经在 swift-type-indexing,另写一个要么抄一遍规则,要么与 TypeDatabase 给出不同答案;RuntimeViewer 也走 DeclaredTypeNameSource。
    2. -
    3. 让 swift-type-indexing 自己读导出表:否,那个包按设计不读 Mach-O。
    4. -
    5. 从 CF 运行时类注册取名字:否,要反汇编调用点,结果与导出表等价,名字还是显示名。
    6. -
    7. 用一致性符号里的模块:否,那是声明一致性的模块,不是类型的模块。
    8. -
    9. 让去 Ref 规则也认运行时名表:否,会把 IOSurfaceRef 改成 IOSurface,还会把 Graph 改坏成 AGGraph。
    10. -
    11. 跟着重新导出算进伞框架:推迟,与 ObjC 来源一起另开提案。
    12. +
    13. 打印器上另注册一个 ModuleNameResolving:否,注册表已经在 swift-type-indexing。
    14. +
    15. 让 swift-type-indexing 自己读导出表:否,那个包按设计不读 Mach-O。
    16. +
    17. 从 CF 运行时类注册取名字:否,要反汇编调用点,结果与导出表等价。
    18. +
    19. 用一致性符号里的模块:否,那是声明一致性的模块。
    20. +
    21. 让去 Ref 规则也认运行时名表:否,会改错 IOSurfaceRef 与 Graph。
    22. +
    23. 跟着重新导出算进伞框架:推迟。
    24. +
    25. 让 swift-type-indexing 允许一个镜像路径登记多个来源:否,本提案不改那个包。
    @@ -397,9 +401,9 @@

    替代方案

    影响

      -
    • 源码兼容性:纯新增,provider 的公开接口不变;--resolve-c-module-names 下私有 CF 类型会带上模块。
    • +
    • 源码兼容性:纯新增两个公开类型,provider 的公开接口不变;--resolve-c-module-names 下私有 CF 类型带上模块。
    • ABI:不适用,SPM 源码分发。
    • -
    • 下游:InterfaceRequest 自动受益;没有基线开着 __C 模块解析,渲染 A/B 不受影响;RuntimeViewer 要在 RuntimeSwiftSection.swift:2013 加一行才受益;MachOKitUI、SymbolViewer 不受影响。
    • +
    • 下游:InterfaceRequest 自动受益;RuntimeViewer 发版后把 ObjCDeclaredTypeNames 换成 ImageDeclaredTypeNames 才受益。
    • API 演进:没有被替代的旧 API,按 minor 版本发布。
    @@ -407,24 +411,43 @@

    影响

    落地步骤

      -
    1. 提案落盘、登记索引(本次)
    2. -
    3. CFDeclaredTypeNames 与测试:exportedTypeIDFunctionNamesItsTypedef、underscoredTypeIDFunctionNamesBothSpellings、otherExportsNameNothing、readsACompiledLibrarysExportsThroughBothReaders
    4. -
    5. provider 登记、端到端验证:sourcesListTheRootFirstThenEachDependencyObjCBeforeCF、typeDatabaseAttributesAnExportedCFTypeToItsImage、interfacePrintsAPrivateCFTypeUnderItsDeclaringModule、interfaceKeepsTheBareSwiftNameWithoutTheSource
    6. -
    7. 文档与系统镜像验证:在 Ultra 上对 SwiftUICore、AppKit、RealityIO 跑 interface --resolve-c-module-names,确认四个代表类型的拼写并量耗时;测试一律在 Ultra 上跑
    8. +
    9. 提案落盘、登记索引 ✅
    10. +
    11. CFDeclaredTypeNames 与测试 ✅:fileNamesTheTypedefOfEveryExportedTypeIDFunction、loadedImageNamesTheSameTypedefs、coreSVGDeclaresItsPrivateDocumentType
    12. +
    13. 合成来源、provider 登记、端到端验证 ✅:listsTheObjectiveCClassAndTheCFTypeOfOneImage、aPrivateCFTypePrintsUnderTheImageExportingItsTypeID、aCFTypeTheRootDefinesPrintsUnderTheRootsModule、aBridgedTypeWithoutATypeIDFunctionKeepsItsBareSwiftName、aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass、withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName
    14. +
    15. 文档与系统镜像验证 ✅:
    +
    + + + + + + + + +
    镜像改动前后不同的行新增的模块限定改动后耗时
    SwiftUICore300AttributeGraph.Subgraph 134、AttributeGraph.Graph 13、CoreSVG.CGSVGDocument 717.28 秒(改动前 17.22)
    AppKit16CoreGraphics.CGColorTransform 4、CGContextDelegate 3、CGDisplayList 18.17 秒
    RealityIO976CoreRealityIO.RIOPxrUsdObject 等二十多种2.24 秒
    TextRecognition0无2.62 秒
    +

    决策日志

    - 2 条,最近一条:实现放在本仓库,形式是 DeclaredTypeNameSource(待确认) + 10 条,最近一条:不改成遍历导出 trie
    - - + + + + + + + + + +
    日期变更说明
    2026-11-25Created as Draft起因是想知道 Swift 用到的私有 CF 类能否还原原名。调研发现 Swift 名 0106 已经从描述符取得,缺的是模块;定义 CF 类型的框架都导出 GetTypeID,46 个公开类型验证全对。
    2026-11-25实现放在本仓库,形式是 DeclaredTypeNameSource用户选定放在本仓库、不改 swift-type-indexing。用户设想的开放注册表已经以 DeclaredTypeNameSource 存在,因此不再另写打印器解析器;此项待用户确认。
    2026-11-25Created as DraftSwift 名 0106 已从描述符取得,缺的是模块;GetTypeID 定位模块,46 个公开类型验证全对。
    2026-11-25形式是 DeclaredTypeNameSource用户设想的开放注册表已经存在;用户确认。
    2026-11-25IOSurfaceRef 疑似问题先复现用户定:先复现,不并入本提案。
    2026-11-25用户批准,开始实现功能分支从本地 next 切。
    2026-11-25测试都放在公开 seam 上命名规则与来源顺序都经公开接口测。
    2026-11-25新增 ImageDeclaredTypeNames偏离原方案:TypeDatabase 按镜像路径去重,分开登记的 CF 来源被丢掉。
    2026-11-25加 foreign 描述符闸门用户指出判断 CF 类型要靠 foreign metadata;诱饵测试加闸前红、加闸后绿。
    2026-11-25不导出 GetTypeID 的桥接类型印裸名应用户要求实测并写成测试。
    2026-11-25IOSurfaceRef 疑似问题未复现印 CoreGraphics.IOSurfaceRef,能编过;模块选择器问题记为后续项。
    2026-11-25不改成遍历导出 trie耗时测不出差别。
    diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.md b/Documentations/Evolutions/draft-private-cf-type-modules.md index fac6e608..19c555d5 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.md +++ b/Documentations/Evolutions/draft-private-cf-type-modules.md @@ -13,7 +13,7 @@ ## 摘要 -`swift-section interface --resolve-c-module-names` 能把公开的 C 导入类型写到真实模块下(`__C.CGColorRef` → `CoreGraphics.CGColor`),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(`CGSVGDocument`)。本提案在 `SwiftTypeNameResolution` 里新增 `CFDeclaredTypeNames`,它是 swift-type-indexing 的 `DeclaredTypeNameSource` 的又一个实现:从镜像的导出表里找出每个 `…GetTypeID` 函数,列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`)。`SwiftInterfaceBuilderTypeNameProvider` 为根镜像登记它;每个直接依赖改登记新的 `ImageDeclaredTypeNames`,把这个镜像的 Objective-C 名字和 CF 类型合成一个来源,因为 `TypeDatabase` 每个镜像路径只收一个来源。之后 `CGSVGDocumentRef` 归到 CoreSVG,引用印成 `CoreSVG.CGSVGDocument`。打印器、swift-type-indexing 和 CLI 参数都不改。 +`swift-section interface --resolve-c-module-names` 能把公开的 C 导入类型写到真实模块下(`__C.CGColorRef` → `CoreGraphics.CGColor`),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(`CGSVGDocument`)。本提案在 `SwiftTypeNameResolution` 里新增 `CFDeclaredTypeNames`,它是 swift-type-indexing 的 `DeclaredTypeNameSource` 的又一个实现:从镜像的导出表里找出每个 `…GetTypeID` 函数,列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`)。`SwiftInterfaceBuilderTypeNameProvider` 为根镜像登记它;每个直接依赖改登记新的 `ImageDeclaredTypeNames`,把这个镜像的 Objective-C 名字和 CF 类型合成一个来源,因为 `TypeDatabase` 每个镜像路径只收一个来源。`GetTypeID` 只负责定位:一个名字是不是 CF 类型,由根镜像自己的 foreign class 描述符决定,CF 来源只给出被它证实的名字。之后 `CGSVGDocumentRef` 归到 CoreSVG,引用印成 `CoreSVG.CGSVGDocument`。打印器、swift-type-indexing 和 CLI 参数都不改。 ## 动机 @@ -44,14 +44,14 @@ 6. **TypeDatabase 的 CF 去 `Ref` 规则只认 SDK 里有的名字。** `TypeDatabase.swiftName(forCName:category:)` 在 API notes 没有改名时,只有去掉 `Ref` 的名字出现在模块接口或 API notes 的归属表里才返回它,运行时登记的名字不算。私有 CF 类型因此拿不到解析器给的 Swift 名,走第 4 条里描述符那一档,`AGGraphRef` 正确地印成 `Graph` 而不是 `AGGraph`。 7. **现在谁被登记。** `SwiftInterfaceBuilderTypeNameProvider.setup()`(`Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98`)只给每个**直接**依赖登记一个 `ObjCDeclaredTypeNames`,根镜像自己不登记。只取直接依赖是有意的(`Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift:9-19`:每个依赖模块都要生成一份 SourceKit 接口,传递闭包有几百个镜像)。CLI 里只有 `interface --resolve-c-module-names` 会接上它(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:273-320`),依赖按本机 dyld cache 解析。RuntimeViewer 不经这个 provider,它在 `RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/Swift/RuntimeSwiftSection.swift:2013` 给自己打开的每个镜像登记一个 `ObjCDeclaredTypeNames`。 8. **按这个设计能覆盖多少。** 对「动机」表里的 20 个查使用方的直接依赖(`dyld_info -dependents`):CoreSVG、CoreGraphics、AttributeGraph、CoreRealityIO 都是使用方的直接依赖,覆盖 14 个;`CAXUIElementRef` 由使用方自己定义,登记根镜像后覆盖,共 15 个。剩下 5 个:`LSASNRef` 的导出在 LaunchServices,使用方只直接链接重新导出它的 CoreServices;`CFPhoneNumberRef` 的 CorePhoneNumbers 不是 IDSFoundation 的直接依赖;另外 3 个没有对应的导出。 -9. **带 `Ref` 的名字在 Swift 里不能用。** ClangImporter 只在 Swift 3 及以后的名字里去掉 `Ref`(`swift/lib/ClangImporter/ImportName.cpp:2269-2277` 的 `swift3OrLaterName`),带 `Ref` 的拼写只剩一个改名用的兼容别名。所以一个私有 CF 类型如果在本镜像里没有描述符(只出现在符号签名里),模块解析出来以后会印成 `CoreSVG.CGSVGDocumentRef`,能读懂,但不是能编译的写法。去掉 `Ref` 时还要避开重名:`IOSurfaceRef` 的描述符名字就是 `IOSurfaceRef`,因为 IOSurface 里已有同名的 Objective-C 类 `IOSurface`(`hasNamingConflict`)。 -10. **顺带发现、未验证(推测)**:第 6 条的去 `Ref` 规则不看重名,而打印器先问解析器、后用描述符。若一个二进制链接了 IOSurface,`__C.IOSurfaceRef` 在 `--resolve-c-module-names` 下可能被印成 `IOSurface.IOSurface`,正确写法是 `IOSurface.IOSurfaceRef`。这与本提案无关,要在 Ultra 上复现后另行处理。 +9. **带 `Ref` 的名字在 Swift 里不能用。** ClangImporter 只在 Swift 3 及以后的名字里去掉 `Ref`(`swift/lib/ClangImporter/ImportName.cpp:2269-2277` 的 `swift3OrLaterName`),带 `Ref` 的拼写只剩一个改名用的兼容别名。所以一个私有 CF 类型如果在本镜像里没有描述符(只出现在符号签名里),即使模块解析出来,也只能印成 `CoreSVG.CGSVGDocumentRef`,能读懂,但不是能编译的写法;加了 foreign 描述符闸门以后(提议方案第 3 条),这种引用不再认领模块,保持 `__C.CGSVGDocumentRef`。去掉 `Ref` 时还要避开重名:`IOSurfaceRef` 的描述符名字就是 `IOSurfaceRef`,因为 IOSurface 里已有同名的 Objective-C 类 `IOSurface`(`hasNamingConflict`)。 +10. **顺带怀疑过、复现后没有出现**:曾推测第 6 条的去 `Ref` 规则不看重名,会把 `__C.IOSurfaceRef` 印成 `IOSurface.IOSurface`。在 Ultra 上对直接链接 IOSurface、用到 `IOSurfaceRef` 的 TextRecognition 跑 `interface --resolve-c-module-names`,改动前后都印成 `CoreGraphics.IOSurfaceRef`(9 处),名字没被改。模块落在 CoreGraphics,是因为 CoreGraphics 的头文件里也有一份 `IOSurfaceRef` 的 typedef;swiftc 6.4.2 探针确认 `CoreGraphics.IOSurfaceRef` 能编过。同一探针还确认 `IOSurface.IOSurfaceRef` 与 `IOSurface.IOSurface` 都编不过(模块名 `IOSurface` 被同名的 Objective-C 类遮住,报 `'IOSurfaceRef' is not a member type of class 'IOSurface.IOSurface'`),要写成模块选择器 `IOSurface::IOSurfaceRef`、`IOSurface::IOSurface`;`--module-selectors` 下 TextRecognition 印成 `CoreGraphics::IOSurfaceRef`。后者是打印器在「模块名与它里面的类型同名」时的通用问题,不属于本提案。 ## 提议方案 1. **新增 `CFDeclaredTypeNames`**(`Sources/Output/SwiftTypeNameResolution/`),实现 `DeclaredTypeNameSource`,与 `ObjCDeclaredTypeNames` 同形:`init(machO:imagePath:)`,`declaredTypeNames()` 读 `machO.exportedSymbols`,每个名为 `_<名字>GetTypeID` 的导出给出 `<名字>Ref`;`<名字>` 以下划线开头的私有函数(`__LSASNGetTypeID`)同时给出去掉前导下划线的拼写(`LSASNRef`)。 2. **新增 `ImageDeclaredTypeNames`**(同一目录),也实现 `DeclaredTypeNameSource`:一个镜像的 `ObjCDeclaredTypeNames` 名字在前、`CFDeclaredTypeNames` 名字在后,合成一个来源。`TypeDatabase` 每个镜像路径只收第一个来源(调研第 5 条),把两种来源分开登记,后登记的那个永远读不到。 -3. **provider 登记它们**:`setup()` 交给 `TypeDatabase.index(dependencies:moduleFilter:)` 的来源变成「根镜像的 `CFDeclaredTypeNames`,然后每个直接依赖一个 `ImageDeclaredTypeNames`」,取代原来每个依赖一个 `ObjCDeclaredTypeNames`。根镜像排第一,因为它自己定义的类型由它自己说了算;根镜像不进 `moduleFilter`,不触发 SourceKit 接口生成,它的 Objective-C 名字照旧不登记。来源的排列抽成一个内部静态函数。 +3. **provider 登记它们**:`setup()` 交给 `TypeDatabase.index(dependencies:moduleFilter:)` 的来源变成「根镜像的 `CFDeclaredTypeNames`,然后每个直接依赖一个 `ImageDeclaredTypeNames`」,取代原来每个依赖一个 `ObjCDeclaredTypeNames`。根镜像排第一,因为它自己定义的类型由它自己说了算;根镜像不进 `moduleFilter`,不触发 SourceKit 接口生成,它的 Objective-C 名字照旧不登记。来源的排列抽成一个内部静态函数。**`GetTypeID` 只负责定位,「是不是 CF 类型」由 foreign 描述符决定**:provider 先从根镜像收集 C 导入、从 C typedef 升格来的 class 描述符(ClangImporter 给 CF 类型生成的 foreign class)的 typedef 名,所有 CF 来源只给出这个集合里的名字。这样 `CFGetTypeID` 给出的 `CFRef` 这类非类型名字,以及恰好与某个导出同名的 `swift_wrapper` typedef,都不会被认领。 4. **打印器、swift-type-indexing、CLI 参数都不改**。效果全部经现有路径体现:`moduleName(forTypeName:)` 多答出一些名字,打印器按调研第 4 条的规则写成 `模块.描述符名`。`--resolve-c-module-names` 的帮助文字和 swift-section skill 的说明补一句来源。 ### 非目标 @@ -59,7 +59,8 @@ - **跟着重新导出找子框架**(`LSASNRef` → CoreServices):`ObjCDeclaredTypeNames` 同样不跟重新导出,两种来源应该一起做;MachOKitExtensions 3.3.0 的 `DependencyTraversal` 也只有 `direct` / `transitive`(`DependencyClosure.swift:6-11`)。另开提案。 - **间接依赖**(`CFPhoneNumberRef`):放宽到传递闭包会让 SourceKit 接口生成回到几百个模块(调研第 7 条)。要做也应该只给运行时来源放宽、不动 `moduleFilter`,另开提案。 - **没有 `GetTypeID` 导出的类型**(`CFXGPUDeviceRef` 等 3 个),以及非 CF 的私有 C 类型(struct、enum、`swift_wrapper` typedef,如 `AGTreeElement`):二进制里没有可靠的模块证据。 -- **没有描述符时给出 Swift 名**:仍印 `模块.XRef`(调研第 9 条)。要改得让 TypeDatabase 的去 `Ref` 规则认运行时名表,会碰上重名与 `swift_name` 改名(见「替代方案」第 5 条)。 +- **本镜像没有描述符的引用**:foreign 描述符闸门把它挡在外面,仍印 `__C.XRef`(调研第 9 条)。要在没有描述符时也给出模块和 Swift 名,就得让 TypeDatabase 的去 `Ref` 规则认运行时名表,会碰上重名与 `swift_name` 改名(见「替代方案」第 5 条)。 +- **自己定义、却没导出 `GetTypeID` 的 CF 桥接类型**:foreign 描述符能证实它是 CF 类,但没有任何二进制证据说明它属于哪个模块(桥接到哪个类不进二进制),印描述符给的裸名。端到端测试里的 `ProbeLonelyRef` 钉住了这一点。 - **根镜像自己的 Objective-C 类**:现在也没登记,是另一个问题,本提案不顺手改,免得 ObjC 输出跟着变。 - **`dump`**:`dump` 不做 `__C` 模块解析,本提案不引入。 - **RuntimeViewer 接入**:本库发版后,把 `RuntimeSwiftSection.swift:2013` 的 `metadataSources` 里的 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`,属于 RuntimeViewer 的改动。不能另加一个 `CFDeclaredTypeNames`:同一路径的第二个来源会被丢掉。 @@ -92,6 +93,8 @@ SwiftTypeNameResolution/ + ImageDeclaredTypeNames DeclaredTypeNameSource, one per image + declaredTypeNames() ObjCDeclaredTypeNames names + CFDeclaredTypeNames names ~ SwiftInterfaceBuilderTypeNameProvider.setup() ++ cfTypedefNames(referencedBy: root) root's foreign class descriptors -> the CF typedef names it uses ++ every CF source below gives only these names ~ TypeDatabase.index(dependencies: + [CFDeclaredTypeNames(root), - ObjCDeclaredTypeNames(dependency1), @@ -205,7 +208,7 @@ public struct ImageDeclaredTypeNames: DeclaredTypeNam 1. 导出名必须以一个 `_` 开头(C 符号的 Mach-O 前缀),去掉它得到 C 函数名;Swift 符号(`_$s…`)和 Objective-C 符号(`_OBJC_…`)因为不以 `GetTypeID` 结尾自然落选。 2. C 函数名以 `GetTypeID` 结尾,去掉后缀的部分非空、由字母数字和下划线组成、不以数字开头,记为 `base`。 3. 给出 `base + "Ref"`;`base` 以下划线开头时,再给出去掉全部前导下划线后的 `+ "Ref"`(非空才给)。 -4. 会产生一些不是类型的名字,例如 `CFGetTypeID` 给出 `CFRef`。它们只在某个查询恰好问到这个名字时才会命中,而那时 SDK 的归属已经先问过了,所以无害,不做过滤。 +4. 规则本身会产生一些不是类型的名字,例如 `CFGetTypeID` 给出 `CFRef`。provider 登记的来源都带 foreign 描述符闸门(下一节),只给出根镜像证实是 CF 类的名字;公开的 `init(machO:imagePath:)` 不带闸门,给需要全部名字的调用方(RuntimeViewer 那种为整个进程登记镜像、没有单一根镜像的场合)。 ### 来源的排列 @@ -216,14 +219,30 @@ extension SwiftInterfaceBuilderTypeNameProvider { /// dependency's Objective-C names and CF types, one `ImageDeclaredTypeNames` per image, in /// dependency order. static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource] + + /// The typedef names of the CF types `image`'s Swift metadata refers to: its C-imported + /// class descriptors promoted from a C typedef — the foreign class ClangImporter makes of a + /// CF type. Named by the ABI name, or by the descriptor's own name when ClangImporter kept + /// the C spelling (`IOSurfaceRef`). + static func cfTypedefNames(referencedBy image: MachO) -> Set +} + +extension CFDeclaredTypeNames { + /// A source giving only the names in `admittedTypedefNames`. + init(machO: MachO, imagePath: String, restrictedTo admittedTypedefNames: Set?) +} + +extension ImageDeclaredTypeNames { + /// A source whose CF part gives only the names in `admittedTypedefNames`. + init(machO: MachO, imagePath: String, restrictingCFTypesTo admittedTypedefNames: Set?) } ``` -`setup()` 只把 `dependencies:` 参数换成这个函数的结果,`moduleFilter` 不变。 +`setup()` 只把 `dependencies:` 参数换成这个函数的结果,`moduleFilter` 不变。带闸门的两个构造器是 internal:闸门的集合取决于一个根镜像,只有 provider 这种「为一个根镜像登记依赖」的调用方有它;公开接口因此不变。判定只看描述符:种类是 class、`isCImportedContextDescriptor` 为真、import info 的 `isCTypedef` 为真且不是相关实体。只有 CF 类型会被升格成 class 而又来自 C typedef(`swift_wrapper` 给的是 struct / enum,C++ 的 foreign reference type 来自 tag namespace),所以这四条合起来就是「ClangImporter 给 CF 类型生成的 foreign class」。 ### 性能 -`TypeDatabase` 只在一个名字查不到时才按顺序读下一个来源,读过的来源不再读。根镜像排第一,所以第一次未命中就会读一遍根镜像的导出表:SwiftUICore 这样的大镜像有数十万个导出,`exportedSymbols` 要建一个同样大的数组。第 3 步在 Ultra 上量一次 `interface --resolve-c-module-names` 的耗时变化;如果明显,改成直接遍历导出 trie、只取以 `GetTypeID` 结尾的名字。 +`TypeDatabase` 只在一个名字查不到时才按顺序读下一个来源,读过的来源不再读。根镜像排第一,所以第一次未命中就会读一遍根镜像的导出表:SwiftUICore 这样的大镜像有数十万个导出,`exportedSymbols` 要建一个同样大的数组。第 3 步在 Ultra 上量了 `interface --resolve-c-module-names` 的耗时:SwiftUICore 热缓存下 17.22 → 17.28 秒,测不出差别,所以不改成直接遍历导出 trie。 ## 替代方案考量 @@ -272,9 +291,20 @@ extension SwiftInterfaceBuilderTypeNameProvider { - 夹具:C 库 `ProbeCF` 导出 `ProbeWidgetGetTypeID`;Swift 库 `ProbeKit` 用桥接头声明两个 `CF_BRIDGED_TYPE(id)` 的 typedef,链接 `ProbeCF`,并用 `@_cdecl` 自己导出 `ProbeGadgetGetTypeID`。`FixtureCompiler` 把 install name 固定成 `@rpath/lib<名字>.dylib`,所以模块名是 `libProbeCF`、`libProbeKit` - 行为:`aPrivateCFTypePrintsUnderTheImageExportingItsTypeID`(字段类型印成 `libProbeCF.ProbeWidget`) - 行为:`aCFTypeTheRootDefinesPrintsUnderTheRootsModule`(根镜像自己定义的印成 `libProbeKit.ProbeGadget`) + - 行为:`aBridgedTypeWithoutATypeIDFunctionKeepsItsBareSwiftName`(`ProbeLonelyRef` 只有 `CF_BRIDGED_TYPE(id)`、没有任何镜像导出它的 `GetTypeID`,印裸名 `ProbeLonely`) + - 行为:`aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass`(`ProbeCF` 导出 `ProbeDecoyGetTypeID`,`ProbeKit` 的 `ProbeDecoyRef` 却是 `swift_wrapper` 结构体,不被印成 `libProbeCF.ProbeDecoyRef`;加 foreign 描述符闸门之前它是红的) - 行为:`withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName`(不挂 provider 时仍是 0106 的 `ProbeWidget`) -3. **文档与系统镜像验证** —— 改动地图第 5–9 行 - - 在 Ultra 上对本机 cache 的 SwiftUICore、AppKit、RealityIO 跑 `interface --resolve-c-module-names`,确认 `CoreSVG.CGSVGDocument`、`AttributeGraph.Graph`、`CoreGraphics.CGColorTransform`、`CoreRealityIO.RIOPxrSdfLayer`,并量耗时变化(详细设计「性能」),结果记进本提案 +3. ✅ **文档与系统镜像验证** —— 改动地图第 7–11 行 + - 在 Ultra(macOS 27.2 26B131,Xcode 26.6 release 构建)上,对本机 cache 的四个镜像各跑一遍 `interface --resolve-c-module-names`,改动前用第 1 步那个提交(provider 还没改)编出的 `swift-section`,改动后用最终提交编出的: + + | 镜像 | 改动前后不同的行 | 新增的模块限定(出现次数) | 改动后耗时 | + |---|---|---|---| + | SwiftUICore | 300 | `AttributeGraph.Subgraph` 134、`AttributeGraph.Graph` 13、`CoreSVG.CGSVGDocument` 7 | 17.28 秒(改动前热缓存 17.22 秒) | + | AppKit | 16 | `CoreGraphics.CGColorTransform` 4、`CoreGraphics.CGContextDelegate` 3、`CoreGraphics.CGDisplayList` 1 | 8.17 秒 | + | RealityIO | 976 | `CoreRealityIO.RIOPxrUsdObject`、`RIOPxrVtValue`、`RIOBuilder…` 等二十多种 | 2.24 秒 | + | TextRecognition | 0 | 无(只用公开的 CF 类型) | 2.62 秒 | + + - 所有变化都是原本没有模块的私有 CF 类型带上了定义它的模块,没有归错的;实际覆盖比「动机」里按一致性表估计的多(AppKit 的 `CGDisplayList`、RealityIO 的 `RIOBuilder…` 一批不在那张表里,它们有描述符但没有一致性记录)。加 foreign 描述符闸门前后,这四个镜像的输出逐字节相同。耗时看 SwiftUICore 的热缓存对比,没有可测出的变化,所以「性能」一节说的「改成遍历导出 trie」不做 - 测试一律在 Ultra 上跑(公司那台不跑本库的测试),`--filter` 同时带 `--skip IntegrationTests` **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -292,3 +322,7 @@ extension SwiftInterfaceBuilderTypeNameProvider { | 2026-11-25 | 用户批准,开始实现 | 轻量档,用户看过简报后批准。功能分支从本地 `next` 切,因为 moved-swift-type-modules 的本地合并也改了 provider 的 `setup()`,从 `origin/next` 切会在合回时冲突。 | | 2026-11-25 | 测试都放在公开 seam 上 | 命名规则不单独测内部静态函数,改由现场编译的 C 库的导出覆盖各种写法;来源顺序不单独测内部函数,改由端到端测试证明根镜像与依赖各自归属。`declaredTypeNameSources(root:dependencies:)` 仍按设计抽成内部静态函数。 | | 2026-11-25 | 新增 `ImageDeclaredTypeNames`,一个依赖只登记一个来源 | 偏离原方案。端到端测试发现依赖定义的私有 CF 类型仍印裸名:`TypeDatabase.register(dependencies:)` 按镜像路径去重,同一依赖先登记的 `ObjCDeclaredTypeNames` 占了位置,随后的 `CFDeclaredTypeNames` 被丢掉;根镜像只有一个来源,所以那条通过了。改为每个依赖登记一个合成两种名字的 `ImageDeclaredTypeNames`,方案方向不变,多一个纯新增的公开类型;RuntimeViewer 的后续接入也要用它。 | +| 2026-11-25 | 加 foreign 描述符闸门 | 用户指出判断「是不是 CF 类型」要靠 foreign metadata 才可靠。改为:`GetTypeID` 只负责定位,provider 先从根镜像的 foreign class 描述符(C 导入、从 C typedef 升格来的 class)收集 CF typedef 名,CF 来源只给出这些名字。诱饵测试 `aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass` 加闸前红、加闸后绿。代价是本镜像没有描述符的引用不再认领模块,保持 `__C.XRef`(原来会印成不能编译的 `模块.XRef`)。带闸门的构造器是 internal,公开接口不变。 | +| 2026-11-25 | 自己定义、不导出 `GetTypeID` 的 CF 桥接类型印裸名 | 应用户要求实测:`ProbeLonelyRef` 只有 `CF_BRIDGED_TYPE(id)`,foreign 描述符证实它是 CF 类,但没有模块证据,印 `ProbeLonely`。写成测试钉住,列入非目标。 | +| 2026-11-25 | `IOSurfaceRef` 疑似问题未复现 | TextRecognition 改动前后都印 `CoreGraphics.IOSurfaceRef`,能编过;没有被改成 `IOSurface`。复现中确认的另一件事——`IOSurface.IOSurfaceRef` / `IOSurface.IOSurface` 因模块名被同名类遮住而编不过、要用 `IOSurface::…`——是打印器的通用拼写问题,记为后续项。 | +| 2026-11-25 | 不改成遍历导出 trie | 第 3 步实测 SwiftUICore 热缓存下耗时 17.22 → 17.28 秒,`exportedSymbols` 的开销测不出来。 | From 26ee901a5bf82626c03ca2d9e576c848bb74e32f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 16:54:23 +0800 Subject: [PATCH 114/175] docs: record the green full suite and the finished implementation in the private-cf-type-modules proposal Co-Authored-By: Claude Opus 5.5 --- Documentations/Evolutions/draft-private-cf-type-modules.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Documentations/Evolutions/draft-private-cf-type-modules.md b/Documentations/Evolutions/draft-private-cf-type-modules.md index 19c555d5..2ce1e696 100644 --- a/Documentations/Evolutions/draft-private-cf-type-modules.md +++ b/Documentations/Evolutions/draft-private-cf-type-modules.md @@ -326,3 +326,5 @@ extension ImageDeclaredTypeNames { | 2026-11-25 | 自己定义、不导出 `GetTypeID` 的 CF 桥接类型印裸名 | 应用户要求实测:`ProbeLonelyRef` 只有 `CF_BRIDGED_TYPE(id)`,foreign 描述符证实它是 CF 类,但没有模块证据,印 `ProbeLonely`。写成测试钉住,列入非目标。 | | 2026-11-25 | `IOSurfaceRef` 疑似问题未复现 | TextRecognition 改动前后都印 `CoreGraphics.IOSurfaceRef`,能编过;没有被改成 `IOSurface`。复现中确认的另一件事——`IOSurface.IOSurfaceRef` / `IOSurface.IOSurface` 因模块名被同名类遮住而编不过、要用 `IOSurface::…`——是打印器的通用拼写问题,记为后续项。 | | 2026-11-25 | 不改成遍历导出 trie | 第 3 步实测 SwiftUICore 热缓存下耗时 17.22 → 17.28 秒,`exportedSymbols` 的开销测不出来。 | +| 2026-11-25 | 全量测试通过 | Ultra(macOS 27.2,Xcode 26.6),`swift test --skip IntegrationTests`:2978 个测试、563 个套件全部通过,退出码 0。 | +| 2026-11-25 | 实现完成,待用户看过后收尾 | 文档判断:CLI 帮助文字、swift-section skill、`CLAUDE.md` 模块清单、两处索引已同批更新;不写单独的使用指南或实现说明,调用方契约在两个类型的文档注释里,「为什么一个镜像只登记一个来源、为什么判定靠 foreign 描述符」记在本提案;没有新术语。演进账本一节留到正式收尾。 | From 48132f7dcdef14a3df6fb4eb4f3a203dba06629a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 25 Nov 2026 17:21:00 +0800 Subject: [PATCH 115/175] docs: mark proposal 0107 Implemented, point the indexes and links at its number, and number its evolution log section 153 --- AGENTS.md | 2 +- ...ules.html => 0107-moved-swift-type-modules.html} | 13 +++++++------ ...-modules.md => 0107-moved-swift-type-modules.md} | 11 ++++++----- Documentations/Evolutions/README.md | 2 +- Documentations/Glossary.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 4 ++-- Documentations/README.md | 2 +- 7 files changed, 19 insertions(+), 17 deletions(-) rename Documentations/Evolutions/{draft-moved-swift-type-modules.html => 0107-moved-swift-type-modules.html} (97%) rename Documentations/Evolutions/{draft-moved-swift-type-modules.md => 0107-moved-swift-type-modules.md} (97%) diff --git a/AGENTS.md b/AGENTS.md index 178cc766..96c15084 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ One or two lines each; the linked document is the authority. - **ARM64InstructionDecoding** (MachOKitExtensions) — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). - **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. - **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). -- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. A private CF type (no SDK header) is attributed to the image exporting its `…GetTypeID` through `CFDeclaredTypeNames` — registered alone for the root, and for each direct dependency inside an `ImageDeclaredTypeNames` with its ObjC names, because `TypeDatabase` keeps only the first source per image path and silently drops a second. The export only locates a type: it claims a name only when the root's foreign class descriptors confirm a CF class (`cfTypedefNames(referencedBy:)`) ([private-cf-type-modules](Documentations/Evolutions/draft-private-cf-type-modules.md)). Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([moved-swift-type-modules](Documentations/Evolutions/draft-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. +- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. A private CF type (no SDK header) is attributed to the image exporting its `…GetTypeID` through `CFDeclaredTypeNames` — registered alone for the root, and for each direct dependency inside an `ImageDeclaredTypeNames` with its ObjC names, because `TypeDatabase` keeps only the first source per image path and silently drops a second. The export only locates a type: it claims a name only when the root's foreign class descriptors confirm a CF class (`cfTypedefNames(referencedBy:)`) ([private-cf-type-modules](Documentations/Evolutions/draft-private-cf-type-modules.md)). Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([0107-moved-swift-type-modules](Documentations/Evolutions/0107-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. diff --git a/Documentations/Evolutions/draft-moved-swift-type-modules.html b/Documentations/Evolutions/0107-moved-swift-type-modules.html similarity index 97% rename from Documentations/Evolutions/draft-moved-swift-type-modules.html rename to Documentations/Evolutions/0107-moved-swift-type-modules.html index 88b88e57..50ab0dda 100644 --- a/Documentations/Evolutions/draft-moved-swift-type-modules.html +++ b/Documentations/Evolutions/0107-moved-swift-type-modules.html @@ -4,7 +4,7 @@ -Draft - 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 +0107 - 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

    +

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

    +
    +

    动机里的复现

    +

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

    +
    +
    + +
    +

    架构图

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

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

    +
    + +
    +

    改动地图

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

    提议方案

    +

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

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

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

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

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

    +
    +

    没有询问就采用的假设

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

    非目标

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

    详细设计

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

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

    +
    +
    +
    + 两条后端 +
    +

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

    +

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

    +
    +
    +
    + +
    +

    调研

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

    替代方案

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

    影响

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

    落地步骤

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

    后续项

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

    决策日志

    +
    + 16 条,最近一条:实现完成,待用户看过后收尾 +
    +
    + + + + + + + + + + + + + + + + + + + + +
    日期变更说明
    2026-11-25Created as Draft同名 C 类型的声明写裸名、扩展头写 __C::,布局注释用 C 名且不带模块选择器;补齐 0106 留下的这两处
    2026-11-25范围用户选定只做二进制能证明的部分;跨镜像查找另开提案
    2026-11-25批准用户调用 implement-feature 即批准,提案由 agent 起草、用户事前未审阅
    2026-11-25开始实现功能分支 feature/consistent-c-imported-type-spelling,从 next 切出
    2026-11-25调研更正AGTreeValue、AGTypeSignature 实际改了名但不可信,照旧 __C::
    2026-11-25两条后端一起改对照测试要求两条路径逐字节一致
    2026-11-25进程内缓存存节点渲染时重算会带回 0067 去掉的成本
    2026-11-25第 1 步审查修正文档里「只有没有 descriptor 的保留 __C.」;锁内 demangle 归入 A61;索引缺登记是误报
    2026-11-25第 2 步审查补强两条测试;注释行不带判别符、带语法糖是有意的一致
    2026-11-25进程内测试改在渲染器接缝上进程内建索引撞上 next 上的符号索引死锁;对照后来改为逐行相同
    2026-11-25第 3 步审查补三条测试;改 SpecializedRuntimeTypeNameTests 的期望;几种嵌套形状记为后续项
    2026-11-26自审9 条:耗时与内存实测后不修(A91);被排除的描述符先判定、不 demangle(A86);A87–A90 登记;skill 补布局注释与 dump 的区别
    2026-11-26真实镜像对照AttributeGraph 的 __C 从 73 处降到 60 处,剩下的都是没有 descriptor 或改名不可信的类型
    2026-11-26全量验证2997 个测试只有一条已知的负载超时,单独重跑全过;第一次的 SIGSEGV 是加存储属性后的旧目标文件,clean 后消失
    2026-11-26收尾判断不另写使用指南或实现说明;没有新术语,更新了既有词条
    2026-11-26实现完成,待用户看过后收尾在本地合进 next 的常驻检出,不推送
    +
    +
    +
    +
    + +
    +
    + + diff --git a/Documentations/Evolutions/draft-consistent-c-imported-type-spelling.md b/Documentations/Evolutions/draft-consistent-c-imported-type-spelling.md index f23af7a2..835a45d9 100644 --- a/Documentations/Evolutions/draft-consistent-c-imported-type-spelling.md +++ b/Documentations/Evolutions/draft-consistent-c-imported-type-spelling.md @@ -3,11 +3,11 @@ - **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-25 -- **最后更新**: 2026-11-25 +- **最后更新**: 2026-11-26 - **所属愿景**: 无 - **关联提案**: [0106-c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md)(本提案补齐它留下的两处:没改名的 C 类型、字段布局注释);[0067-nested-field-offset-memoization](0067-nested-field-offset-memoization.md)(进程内每层展开的缓存,本提案往缓存的行里多存一个类型节点);[0064-module-selectors](0064-module-selectors.md)、[0092-existential-any](0092-existential-any.md)(布局注释由此也带上模块选择器与 `any`) - **实现分支 / PR**: `feature/consistent-c-imported-type-spelling`(worktree `.worktrees/MachOSwiftSection-ConsistentCImportedTypeSpelling`) -- **配套文档**: 待定 —— 落地时判断 +- **配套文档**: 无单独文档(见决策日志「收尾判断」);规则在 [术语表](../Glossary.md)「C-imported type name spelling」,裁决在 [ReviewAdjudications](../Internal/ReviewAdjudications.md) A86–A91 - **网页版**: 同目录同名的 `.html` ## 摘要 @@ -121,11 +121,13 @@ struct WeakAttribute { | `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` · `modelFieldBlock` | 修改 | 渲染配置加 `.spellingFieldLayoutTypeNamesThroughResolver(true)` | interface 打开开关 | 2 | | `Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift` · `StructField` / `EnumPayload` | 修改 | 新增 `typeNode: Node?` | 进程内缓存带节点 | 3 | | `Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` · `RuntimeFieldLayoutBackend` | 修改 | `nestedTypeName` 拆出 `nestedTypeNode`;建层时存节点;`expandedFieldOffsets(of:…)` 与 `walkNestedExpandedFieldOffsets` 改成 async,每行经 `fieldLayoutTypeName` 取名字 | 进程内路径的注释跟拼写,与离线逐字节一致 | 3 | -| `Tests/SwiftDeclarationRenderingTests/…` | 视情况修改 | 调用点随 async 化补 `await` | 编译 | 2、3 | +| `Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift` | 修改 | 加一轮开关打开、用 `.interface` 拼写的「带缓存与不带缓存逐字相同」 | 缓存里存的节点也要证明冷热一致 | 3 | +| `Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift` | 修改 | 布局注释的期望从 `(RuntimeNamedPrivateArgument in _…)` 改成和字段声明一样的 `SwiftSpecializationTests.RuntimeNamedPrivateArgument` | 注释行跟着声明拼写 | 3 | | `Documentations/Glossary.md` · C-imported type name spelling | 修改 | 补同名类型、布局注释 | 术语表跟上行为 | 4 | -| `Documentations/Internal/Modules/SwiftLayout.md` | 修改 | `NestedFieldOffset` 多了 `typeNode` | 模块参考 | 4 | -| `Documentations/Internal/Modules/SwiftDeclarationRendering.md`(若有相关段落)、`Documentations/Internal/Modules/SwiftPrinting.md` | 视情况修改 | 布局注释的拼写来源、名字表的收录规则 | 模块参考 | 4 | -| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 新增一节(节号落地时取) | 演进账本 | 4 | +| `Documentations/Internal/Modules/SwiftLayout.md` | 修改 | 关键契约补一条:`typeName` 与 `typeNode` 两份,本模块不换拼写 | 模块参考 | 4 | +| `Documentations/Internal/FieldLayoutRendererReaderSpecialization.md` | 修改 | 两条后端经同一个入口取行的类型名 | 渲染分叉的说明(`SwiftDeclarationRendering`、`SwiftPrinting` 没有单独的模块文档) | 4 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 新增一节(落地前标题写日期,节号落地时取) | 演进账本 | 4 | +| `Documentations/Internal/ReviewAdjudications.md` | 修改 | 登记 A86–A91(审查与自审判为不修、误报或有意的发现) | 「不修」与「误报」的裁决留档 | 4 | | `Documentations/Evolutions/README.md` | 修改 | 登记本提案(编号 `draft`);`Documentations/README.md` 照项目惯例在落地取号时登记(进行中的 draft 都不在那里) | 索引 | 0 | ## 架构图 @@ -290,7 +292,7 @@ private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors ### 下游影响 -- 本仓库:`SwiftPrinting`、`SwiftDeclarationRendering`、`SwiftLayout`;interface 输出变化:同名 C 类型的引用与扩展头少了 `__C.`;开了展开字段偏移时注释的类型名与声明写法一致(C 类型 Swift 名、模块选择器、`any`、语法糖、私有类型不带判别符、局部类型只写名字)。每一行多一次经打印器的异步打印,开销在交付前实测。dump、diff 键、snapshot 不变。 +- 本仓库:`SwiftPrinting`、`SwiftDeclarationRendering`、`SwiftLayout`;interface 输出变化:同名 C 类型的引用与扩展头少了 `__C.`;开了展开字段偏移时注释的类型名与声明写法一致(C 类型 Swift 名、模块选择器、`any`、语法糖、私有类型不带判别符、局部类型只写名字)。每一行多一次经打印器的异步打印:SwiftUICore 打开展开字段偏移的 interface 从 7.10 秒到 7.39 秒(+4%);进程内缓存每行多存一个节点,SwiftUICore 全部展开后多占约 2.1 MB(实测见 [A91](../Internal/ReviewAdjudications.md))。没开 `--resolve-c-module-names` 时,镜像里有描述符的 SDK 类型(`CGRect`、`CGPoint`、RenderBox 的 `RBColor`)也从 `__C::CGRect` 变成裸的 `CGRect`。dump、diff 键、snapshot 不变。 - RuntimeViewer:用同一个打印器,内容区的接口文本跟着变;Imported Type Names 切到 C 名时注释也写 C 名。它的 `ExpandedFieldOffsetTransformer` 模板收到的 `typeName` 变成打印器拼写。不需要改 RuntimeViewer 代码。 ### 文档与示例 @@ -321,7 +323,7 @@ private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors - 行为:进程内路径的布局注释同样写 Swift 名与模块选择器 - 行为:进程内与离线两条路径对非泛型字段的布局注释逐行相同(且进程内的行里必须出现只有打印器才写的 `::`,防止两边都退回 `.default` 时空过) - 行为:带缓存与不带缓存的进程内展开逐字相同,开关关着(既有测试)与开着、用另一种拼写(新增)都一样 -4. **文档** —— 改动地图第 15–19 行,以及第 4、5 行在第 3 步之后的补全 +4. **文档**(已完成:术语表、插件 skill 第 8 节、`--c-imported-type-name-spelling` 帮助、SwiftLayout 模块文档、`FieldLayoutRendererReaderSpecialization.md`、演进账本、已裁决清单 A86–A91) —— 改动地图第 15–19 行,以及第 4、5 行在第 3 步之后的补全 **收尾时必须判断两件事**:要不要配套专题文章;有没有引入新术语。结论写进决策日志。 @@ -349,6 +351,11 @@ private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors | 2026-11-25 | 两条后端一起改 | `OfflineSpecializationParityTests` 要求两条路径逐字节一致 | | 2026-11-25 | 进程内缓存存节点 | 渲染时重算会带回 0067 去掉的 demangle 成本 | | 2026-11-25 | 第 1 步审查(两个审查 agent) | 文档里「只有没有 descriptor 的保留 `__C.`」说错了:改名不可信的(`ProbeOwnerKey`、`AGTreeValue`)也保留,CLI 帮助、插件 skill 与 `CImportedTypeNameSpelling` 的注释已改。名字表在锁内 demangle:A61 第一处已裁决「打印器的一次性建表不改锁」,理由(入口已切到大栈)对 0106 的名字表同样成立,不改,第 5 步登记。`Code` 枚举与 C++ 模板特化记为后续项。`Documentations/README.md` 缺登记是误报:项目惯例是 draft 落地时才登记 | -| 2026-11-25 | 进程内测试改在渲染器接缝上 | 最初用进程内 `SwiftInterfaceBuilder` 打 dlopen 进来的 fixture,撞上符号索引的建索引死锁(后续项有详情,是 `next` 上的旧问题)。改为用打印器自己的 `typeDemangleResolver` 直接驱动 `FieldLayoutRenderer`,与打印器构造渲染配置的方式相同、但不建索引;离线与进程内的逐行对照照样做,以进程内的行是离线行的子集为准(进程内从活的 metadata 读偏移,可能更早停下) | -| 2026-11-25 | 第 3 步审查(两个审查 agent) | 测试有三处证明力不够,已补(见落地步骤 3)。`SpecializedRuntimeTypeNameTests` 改了期望:注释行和字段声明一样写 `SwiftSpecializationTests.RuntimeNamedPrivateArgument`,测试要证明的「保留模块」不变;运行时名字里判别符的恢复另有 `RuntimeTypeNamePrivateDiscriminatorTests` 守着,不另加 dump 侧的孪生测试。pack、整数泛型参数、关联类型成员这几种嵌套行的两条路径对照、位置命名的局部类型在两条路径地址不同,都是改前就没覆盖的,记为后续项。进程内缓存多存节点的内存成本,交付前实测 | | 2026-11-25 | 第 2 步审查(两个审查 agent) | 两条测试证明不了它声称的:dump 守护测试改成用一个把所有类型都印成固定字样的解析器,开关关着不生效、开着才生效;C 名测试加开模块选择器。注释行跟着声明不带私有判别符、带语法糖,是这次有意的一致,写进「提议方案」与「影响」;opaque 行记为后续项。每行一次异步打印的开销,交付前在大框架上实测 | +| 2026-11-25 | 进程内测试改在渲染器接缝上 | 最初用进程内 `SwiftInterfaceBuilder` 打 dlopen 进来的 fixture,撞上符号索引的建索引死锁(后续项有详情,是 `next` 上的旧问题)。改为用打印器自己的 `typeDemangleResolver` 直接驱动 `FieldLayoutRenderer`,与打印器构造渲染配置的方式相同、但不建索引。离线与进程内的对照起初按「进程内的行是离线行的子集」比,第 3 步审查后改为逐行相同 | +| 2026-11-25 | 第 3 步审查(两个审查 agent) | 测试有三处证明力不够,已补(见落地步骤 3)。`SpecializedRuntimeTypeNameTests` 改了期望:注释行和字段声明一样写 `SwiftSpecializationTests.RuntimeNamedPrivateArgument`,测试要证明的「保留模块」不变;运行时名字里判别符的恢复另有 `RuntimeTypeNamePrivateDiscriminatorTests` 守着,不另加 dump 侧的孪生测试。pack、整数泛型参数、关联类型成员这几种嵌套行的两条路径对照、位置命名的局部类型在两条路径地址不同,都是改前就没覆盖的,记为后续项。进程内缓存多存节点的内存成本,交付前实测 | +| 2026-11-26 | 自审(`code-review` medium,整条分支) | 9 条:耗时与内存实测后不修(+4%、+2.1 MB,A91);名字表在锁内 demangle 归入 A61,锁不改,但被 import info 排除的描述符改为先判定、不 demangle(A86);同名 C 类型与同名 Swift 类型混淆是误报(A87);注释行不带私有判别符是有意的(A88);解析失败静默退回 `.default` 不修(A89);依赖镜像的 C 类型按根镜像的名字表拼是已知限制,插件 skill 写明(A90);插件 skill 补上布局注释与 dump 的区别;网页版随交付生成 | +| 2026-11-26 | 真实镜像对照 | macOS 27.2 的 AttributeGraph(显示 C 导入类型、模块选择器、展开字段偏移、`--resolve-c-module-names`):`__C` 从 73 处降到 60 处,`AGDescriptionOption` 的 6 个扩展头去掉 `__C::`,注释行改为 `AnyWeakAttribute.__Unnamed_struct__details`、`AnyAttribute`、`Swift::UInt32`。剩下的 60 处都是镜像里没有描述符的类型,或改名不可信的 `AGTreeElement`、`AGTreeValue`、`AGTypeSignature` | +| 2026-11-26 | 全量验证 | JHs-Mac-Studio-Ultra,Xcode 26.6,`swift test --skip IntegrationTests`:2997 个测试只有 `BoundedConcurrentMapTests.cancellationStopsSubmittingPendingElements` 超时(全量时线程池满载的已知偶发),单独重跑该套件 9 个全过。第一次全量在 `DumpRequest` 里复制 `DeclarationRenderConfiguration` 时 SIGSEGV:给这个结构体加了存储属性后增量构建链接了旧目标文件,`swift package clean` 后重编即消失 | +| 2026-11-26 | 收尾判断 | 不另写使用指南或实现说明:拼写规则写在术语表「C-imported type name spelling」,两份类型名的契约写在 SwiftLayout 模块文档,渲染入口写在 `FieldLayoutRendererReaderSpecialization.md`。没有新术语,更新了既有词条 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 三步与文档都已提交到功能分支;在本地合进 `next` 的常驻检出,不推送 | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 4bbcfdaa..7c152f40 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3618,7 +3618,7 @@ - **落地模块**:`Sources/Output/SwiftPrinting/`(`CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)`、`SwiftDeclarationPrinter+Headers` 打开开关)、`Sources/Output/SwiftDeclarationRendering/`(`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`、两条后端改成异步渲染、`NestedFieldOffsetLevel` 带节点)、`Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift`(`NestedFieldOffset.typeNode`)、`swift-section interface --c-imported-type-name-spelling` 的帮助文字。 - **文档**:提案 [draft-consistent-c-imported-type-spelling](../Evolutions/draft-consistent-c-imported-type-spelling.md);术语表「C-imported type name spelling」;插件 skill 第 8 节;SwiftLayout 模块文档的关键契约、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md)。 - **顺带发现**:符号索引的建索引死锁(同一镜像 15 个以上并发建索引时占满大栈线程池),`next` 上就有,记在提案后续项,没在本分支修。 -- **验证**:见提案决策日志最后几行。 +- **验证**:Ultra(Xcode 26.6)全量 `swift test --skip IntegrationTests` 2997 个测试,只有已知的负载偶发 `BoundedConcurrentMapTests` 一条超时,单独重跑全过;每步的行为测试先红后绿。macOS 27.2 的 AttributeGraph 前后对照 `__C` 从 73 处降到 60 处;SwiftUICore 打开展开字段偏移的 interface 慢 4%(7.10 → 7.39 秒),进程内缓存多占约 2.1 MB([ReviewAdjudications](ReviewAdjudications.md) A91)。 - **对应版本**:未发布。 ## 维护约定 diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 4220fbbf..fa89d5af 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -1028,3 +1028,81 @@ - **既往修复**:无。 - **代码锚点**:`Sources/Executables/reader-benchmark/ReaderBenchmark.swift`;体检报告 [CodebaseAudit20261116](Reviews/CodebaseAudits/CodebaseAudit20261116.md)。 - **复审条件**:它被并进 `swift-section`,或开始输出诊断与进度信息。 + +--- + +## A86 — C 导入类型的名字表在锁内 demangle(提案 `consistent-c-imported-type-spelling` 的审查,归入 A61 第一处) + +- **裁决**:锁不改(2026-11-26)。本分支只把被 import info 排除的条目挪到 demangle 之前判定。 +- **发现**:`SwiftDeclarationPrinter.cImportedTypeSwiftNames()`(`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:129`)第一次用到时在 `@Mutex` 里建 `CImportedTypeSwiftNameTable`,每个收进表的描述符要 `SymbolicDemangler.demangleContext` 一次。本提案让没有 ABI 名的描述符也进表,持锁 demangle 的次数随之变多。 +- **复现 / 是否误报**:写法属实。结果不会错,只有「调用方在 512 KB 栈上、且另有线程在等这把锁」时多等;复现不出输出层面的问题。 +- **与 main 基线对比**:建表与锁来自提案 0106(`1e490500`,2026-11-24),main 上没有;本分支增加的是进表的条目数。 +- **为什么不修**:与 A61 第一处(打印器的另外两次一次性建表)同一种写法、同一个理由:建表只发生在打印入口里,入口已包 `LargeStackTaskExecution.run`,持锁期间不切线程。被相关实体、不可信改名排除的描述符现在先判定、不 demangle,持锁的工作只多出真正进表的那些。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift` 的 `init(typeContextDescriptors:in:)`。 +- **复审条件**:与 A61 相同;另外,有宿主在没包执行器的同步入口上第一次打印 C 导入类型。 + +--- + +## A87 — 同名 C 类型写裸名,会不会和同名的 Swift 类型混淆(提案 `consistent-c-imported-type-spelling` 的自审,**误报**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:本镜像有描述符、Swift 名就是 C 名的 C 导入类型(`CMTime`、`CGRect`、`std` 这类 C++ 命名空间)现在写裸名;镜像里若另有同名的 Swift 类型,审查担心两者在声明、扩展头与布局注释里无法区分。 +- **复现 / 是否误报**:误报。Swift 类型的引用与扩展头一律带模块(`M.CMTime`、`M::CMTime`),C 类型现在是裸的 `CMTime`,两者照样分得开;声明行本来就不带模块,C 导入类型的声明在 0106 之前就是裸名。改了名的 C 类型(`AnyWeakAttribute`)从 0106 起就是这种写法。 +- **与 main 基线对比**:同名类型写裸名是本分支引入的;改名类型的同样写法来自 0106,main 上没有。 +- **为什么不修**:见上,没有实际的歧义。 +- **既往修复**:无。 +- **代码锚点**:`CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)`。 +- **复审条件**:引用或扩展头里出现不带模块的 Swift 类型。 + +--- + +## A88 — interface 的布局注释行不带私有判别符、局部类型只写名字(提案 `consistent-c-imported-type-spelling` 的审查与自审,**有意设计**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:展开字段偏移树的行改用 interface 打印器的拼写后,`M.(Foo in _ABC…)` 变成 `M.Foo`,局部类型只写自己的名字;同一个类型里两个字段分别是两个文件里同名的私有 `Foo` 时,注释行分不出哪棵子树属于哪个。 +- **复现 / 是否误报**:属实。 +- **与 main 基线对比**:本分支引入;main 上注释行按 `.default` 打印,带判别符。 +- **为什么不修**:这正是要的一致:这些行描述的字段声明(`let element: M.Foo`)本身也不带判别符,注释与声明写法相同才是这次改动的目的。要区分同名私有类型,看声明上方 `--emit-private-source-files` 印的源文件注释;dump 的注释行照旧带判别符。`SpecializedRuntimeTypeNameTests` 的期望随之改写,它要证明的「保留模块」不变。 +- **既往修复**:无。 +- **代码锚点**:`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`。 +- **复审条件**:interface 的字段声明开始带判别符,或有宿主依赖注释行区分同名私有类型。 + +--- + +## A89 — 布局注释行的拼写失败时静默退回 `.default`(提案 `consistent-c-imported-type-spelling` 的自审,**不修**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:`fieldLayoutTypeName(printedName:typeNode:)` 用 `try?` 调解析器,抛错或得到空串时退回 `.default` 拼写,不发事件、不打日志;那一行会是 `__C.AGAttribute`,旁边的行是 `AnyAttribute`。 +- **复现 / 是否误报**:机制属实,没有构造出会抛错的节点:interface 打印器的 `typeDemangleResolver` 只在打印器已释放时什么都不印。 +- **与 main 基线对比**:本分支引入。 +- **为什么不修**:退回的仍是正确的类型名,只是拼写不同;同一个类型在字段声明处由打印器自己印,出错会走它自己的报告路径。逐行打日志会在大框架上刷出几万行。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift` 的 `fieldLayoutTypeName(printedName:typeNode:)`。 +- **复审条件**:发现某类节点会让 interface 打印器抛错。 + +--- + +## A90 — 布局注释里来自依赖镜像的 C 类型按根镜像的名字表拼(提案 `consistent-c-imported-type-spelling` 的自审,**已知限制**) + +- **裁决**:不修,文档写明(2026-11-26)。 +- **发现**:展开树里某一行的类型来自依赖镜像时,打印器只认根镜像自己的描述符;依赖镜像带着那个 C 类型的描述符、根镜像没有时,这一行写 `__C.Bar`,而依赖镜像自己的 interface 写 `Bar`。 +- **复现 / 是否误报**:属实,按机制推断,没有专门造 fixture。 +- **与 main 基线对比**:main 上这一行永远是 `__C.Bar`,本分支没有让它变坏。 +- **为什么不修**:要从别的镜像的描述符取名字,正是另开提案的跨镜像查找(`AGSubgraphRef` 在 SwiftUICore 里记作 `Subgraph` 那条)要解决的事;插件 skill 第 8 节写明了这个限制。 +- **既往修复**:无。 +- **代码锚点**:`SwiftDeclarationPrinter.cImportedTypeSwiftNames()`。 +- **复审条件**:跨镜像查找的提案落地。 + +--- + +## A91 — 布局注释每行一次异步打印,进程内缓存每行多存一个节点(提案 `consistent-c-imported-type-spelling` 的自审,**实测后不修**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:interface 的每一行展开字段偏移注释都经打印器的 `typeDemangleResolver` 印一次,没有跨行的结果缓存;进程内全进程缓存 `NestedFieldOffsetLevel` 的每一行多存一棵节点树,只有 `RuntimeFieldLayoutMemo.removeAll()` 能释放。 +- **复现 / 是否误报**:成本属实,实测都很小(JHs-Mac-Studio-Ultra,Xcode 26.6,release CLI 交替各跑 3 次):`swift-section interface --uses-system-dyld-shared-cache --cache-image-name SwiftUICore --module-selectors --emit-expanded-field-offsets` 从 7.10 秒到 7.39 秒(+4%,42,559 行注释,约每行 7 微秒);进程内把 SwiftUICore 每个非泛型类型的字段都展开一遍(34,755 行),渲染后的内存增量从 6.72 MB 到 8.85 MB(+2.1 MB)。 +- **与 main 基线对比**:本分支引入。 +- **为什么不修**:按 `.default` 文字做跨行缓存能省掉一部分打印,但收益只有那 4%;节点在建层时本来就算出来了,存下来避免渲染时重新 demangle(提案 0067 去掉的正是这部分成本)。 +- **既往修复**:无。 +- **代码锚点**:`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`、`NestedFieldOffsetLevel.StructField.typeNode`。 +- **复审条件**:有宿主实测到这部分耗时或内存成为瓶颈(RuntimeViewer 建搜索语料时会把镜像的全部类型都展开一遍)。 diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index fe310bb3..05d7d549 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -36,7 +36,7 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Print a Swift type the SDK moved to another module (@_originallyDefinedIn) under the module that declares it now (CoreGraphics.CGFloat -> CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary was built against an SDK that had already moved it. Reads the SDK's .swiftinterface files: needs Xcode or the Command Line Tools, not sourcekitd. macOS only.") var resolveMovedTypeModules: Bool = false - @Option(name: .customLong("c-imported-type-name-spelling"), help: "How imported C and Objective-C types are spelled. swift-name (the default) prints the name Swift code uses: a type the binary's own descriptors name prints under that name, renamed (__C.AGWeakAttribute -> AnyWeakAttribute) or imported under its C name (__C.AGDescriptionOption -> AGDescriptionOption), under its module when --resolve-c-module-names finds it. Any other keeps __C: a type the binary has no descriptor for, or one whose descriptor may name only the leaf of a member import (__C.NSAttributedStringKey). c-name prints every one as the binary mangles it (__C.AGWeakAttribute), declarations included, and resolves nothing.") + @Option(name: .customLong("c-imported-type-name-spelling"), help: "How imported C and Objective-C types are spelled. swift-name (the default) prints the name Swift code uses: a type the binary's own descriptors name prints under that name, renamed (__C.AGWeakAttribute -> AnyWeakAttribute) or imported under its C name (__C.AGDescriptionOption -> AGDescriptionOption), under its module when --resolve-c-module-names finds it. Any other keeps __C: a type the binary has no descriptor for, or one whose descriptor may name only the leaf of a member import (__C.NSAttributedStringKey). c-name prints every one as the binary mangles it (__C.AGWeakAttribute), declarations included, and resolves nothing. The expanded field-offset comments follow the same spelling.") var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName @Option(name: .customLong("supplementary-apinotes"), help: "A supplementary .apinotes file (or a directory of them) of user-provided type mappings for frameworks with no SDK module (e.g. AttributeGraph), loaded on top of the SDK's own APINotes. Repeatable; later paths override earlier ones. Only used with --resolve-c-module-names.", completion: .file()) diff --git a/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift b/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift index 6b7aaac1..24128b11 100644 --- a/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift +++ b/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift @@ -49,7 +49,12 @@ struct CImportedTypeSwiftNameTable: Sendable { } else { importInfo = nil } - guard let identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: context) else { continue } + // What the import info rules out — a related entity, a rename + // that is not trusted — is ruled out wherever the type sits, so it + // is settled before the demangle the key needs. + guard Self.knownSwiftName(ofDescriptorNamed: userFacingName, importInfo: importInfo, isDirectlyInImportedModule: true) != nil, + let identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: context) + else { continue } let identityKey = Self.key(for: identity) let isDirectlyInImportedModule = identityKey.children.first?.kind == .module guard let swiftName = Self.knownSwiftName(ofDescriptorNamed: userFacingName, importInfo: importInfo, isDirectlyInImportedModule: isDirectlyInImportedModule) else { continue } From c575a7b6a686547c566bf69a4818d412ac4bbc56 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 11:36:14 +0800 Subject: [PATCH 121/175] docs: propose unifying the evolution integration suites The Swift report, Swift interface, ObjC report and ObjC header suites each define the same version axes again and borrow one another's class properties. The proposal merges them into one set of axis suites under Tests/IntegrationTests/Evolution/. --- Documentations/Evolutions/README.md | 1 + ...ft-unify-evolution-integration-suites.html | 666 ++++++++++++++++++ ...raft-unify-evolution-integration-suites.md | 482 +++++++++++++ Documentations/README.md | 1 + 4 files changed, 1150 insertions(+) create mode 100644 Documentations/Evolutions/draft-unify-evolution-integration-suites.html create mode 100644 Documentations/Evolutions/draft-unify-evolution-integration-suites.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 2ab8382a..65ad8ec4 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -124,3 +124,4 @@ | [0107](0107-moved-swift-type-modules.md) | 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印(跨仓库唯一提案,swift-type-indexing 参与) | Implemented | | [0108](0108-private-cf-type-modules.md) | 私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块 | Implemented | | draft | [C 导入类型的拼写补齐:同名类型去掉 `__C`,布局注释跟着打印器的拼写](draft-consistent-c-imported-type-spelling.md) | In Progress | +| draft | [IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴](draft-unify-evolution-integration-suites.md) | Accepted | diff --git a/Documentations/Evolutions/draft-unify-evolution-integration-suites.html b/Documentations/Evolutions/draft-unify-evolution-integration-suites.html new file mode 100644 index 00000000..7a055841 --- /dev/null +++ b/Documentations/Evolutions/draft-unify-evolution-integration-suites.html @@ -0,0 +1,666 @@ + + + + + + +Draft - IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 + + + + +
    + +
    +

    MachOSwiftSectionEvolutionsDraft

    +

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

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

    摘要

    +

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

    +

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

    +
    + +
    +

    要你定

    +
    +

    批准后开工。以下是没问你就采用的假设,可以推翻:

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

    架构图

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

    改了什么:文件与类型

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

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

    + +

    套件之间的引用

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

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

    + +

    一次测试的调用链

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

    改动地图

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

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

    +
    + +
    +

    提议方案

    +

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

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

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

    +

    非目标

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

    详细设计

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

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

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

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

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

    动机

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

    调研

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

    替代方案

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

    影响

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

    落地步骤

    +
    +

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

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

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

    +
    + +
    +

    决策日志

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

    MachOSwiftSectionEvolutionsDraft

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

    -
    状态
    Accepted
    +
    状态
    In Progress
    最后更新
    2026-11-26
    项目类型
    库
    原文
    draft-unify-evolution-integration-suites.md
    diff --git a/Documentations/Evolutions/draft-unify-evolution-integration-suites.md b/Documentations/Evolutions/draft-unify-evolution-integration-suites.md index e7f70281..ec729bb3 100644 --- a/Documentations/Evolutions/draft-unify-evolution-integration-suites.md +++ b/Documentations/Evolutions/draft-unify-evolution-integration-suites.md @@ -1,6 +1,6 @@ # Draft - IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-26 - **最后更新**: 2026-11-26 @@ -480,3 +480,4 @@ enum EvolutionTestSuite { |------|------|------| | 2026-11-26 | Created as Draft | 用户要求把 IntegrationTests 里重复的演进测试抽出来,Swift 与 ObjC 各有一套套件,统一成一套。澄清一轮:范围只做演进(不顺带合并 diff 基类与 MachOSymbols 的重复);每种输出保留一对显式测试,不用参数化测试;按规则写轻量档提案。 | | 2026-11-26 | Accepted | 用户看过简报后批准,开始实现。 | +| 2026-11-26 | In Progress:第 1 步开工 | 功能分支从本地 `next` 切出,按 `create-worktree` 的基线规则。本地 `next` 上还有一次未推送、待用户验收的合并(C 导入类型拼写),因此推送功能分支时它作为祖先一并上了远端功能分支,`next` 本身未推送。`MultiVersionDyldCacheImageTests` 用两个 `let`(`swiftAxis`、`objcAxis`)加 `switch` 存两条轴,不用字典加强制解包(详细设计里留的退路)。 | diff --git a/Documentations/README.md b/Documentations/README.md index 1066ef1d..14090ac3 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -227,7 +227,7 @@ selects names using each access's offset and width. | [Evolutions/0106-c-imported-type-name-spelling.md](Evolutions/0106-c-imported-type-name-spelling.md) | **提案 0106(Implemented,跨仓库,RuntimeViewer 参与)**:C 导入类型的名字统一成 Swift 名——声明、成员类型与扩展头一致写描述符给的 Swift 名(解析器找得到模块就带模块,否则写裸名),`CImportedTypeNameSpelling.cName` 一律写 mangled 的 C 名;ABI 名以描述符名字结尾的不信(导入成成员的类型退回 C 名)。`marksCImportedTypeNames` 在名字上标出另一种写法,RuntimeViewer 据此在声明行尾画可点击的标签、切换全局选项;`swift-section interface --c-imported-type-name-spelling` | | [Evolutions/0107-moved-swift-type-modules.md](Evolutions/0107-moved-swift-type-modules.md) | **提案 0107(Implemented,跨仓库,swift-type-indexing 参与)**:被 SDK 用 `@_originallyDefinedIn` 搬过家的 Swift 类型(`CGFloat` 由 CoreFoundation 声明、mangling 仍是 CoreGraphics;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore),interface 按现在声明它的模块打印——swift-type-indexing 扫描 SDK 文本 `.swiftinterface` 建搬家表,打印器多一个 `MovedTypeModuleResolving` 角色,`swift-section interface --resolve-moved-type-modules` 默认关闭,按二进制的 SDK 版本判断是否改写。 | | [Evolutions/0108-private-cf-type-modules.md](Evolutions/0108-private-cf-type-modules.md) | **提案 0108(Implemented)**:私有 CF 类型在 `interface --resolve-c-module-names` 下查不到模块,只印描述符给的裸名(`CGSVGDocument`)。新增 swift-type-indexing `DeclaredTypeNameSource` 的实现 `CFDeclaredTypeNames`:从镜像导出的 `…GetTypeID` 列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`),provider 为根镜像和每个直接依赖登记,引用印成 `CoreSVG.CGSVGDocument`;打印器、swift-type-indexing 与 CLI 参数不改。macOS 27.2 cache 里 Swift 用到的 20 个私有 CF 类型能覆盖 15 个。 | -| [Evolutions/draft-unify-evolution-integration-suites.md](Evolutions/draft-unify-evolution-integration-suites.md) | **提案 draft(Accepted)**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自重复定义同几条版本轴、互相借用对方的类属性,每条管线又把单镜像与镜像组写两遍。合成一套:`Tests/IntegrationTests/Evolution/` 下版本轴只定义一次、按读的元数据(`__swift5_*` / `__objc_*`)筛版本,四条管线收进一个协议,21 个套件类变成 10 个轴套件,43 个「轴 × 输出」组合与输出文件名不变。 | +| [Evolutions/draft-unify-evolution-integration-suites.md](Evolutions/draft-unify-evolution-integration-suites.md) | **提案 draft(In Progress)**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自重复定义同几条版本轴、互相借用对方的类属性,每条管线又把单镜像与镜像组写两遍。合成一套:`Tests/IntegrationTests/Evolution/` 下版本轴只定义一次、按读的元数据(`__swift5_*` / `__objc_*`)筛版本,四条管线收进一个协议,21 个套件类变成 10 个轴套件,43 个「轴 × 输出」组合与输出文件名不变。 | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Tests/IntegrationTests/Evolution/EvolutionAxis.swift b/Tests/IntegrationTests/Evolution/EvolutionAxis.swift new file mode 100644 index 00000000..39cd304a --- /dev/null +++ b/Tests/IntegrationTests/Evolution/EvolutionAxis.swift @@ -0,0 +1,247 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection + +/// The metadata an evolution pipeline reads, and so which images join its +/// axis: an image without it has nothing to index, and indexing it anyway +/// only logs extraction failures. +enum EvolutionMetadataLanguage: Sendable { + /// `__swift5_*` sections. AppKit kept its Swift API in + /// `libswiftAppKit.dylib` until macOS 14, so a Swift axis of AppKit + /// reaching further back starts at 14.0. + case swift + /// `__objc_*` sections, which AppKit carries in every cache. + case objc + + func isCarried(by machOFile: MachOFile) -> Bool { + let sectionNamePrefix = switch self { + case .swift: "__swift5_" + case .objc: "__objc_" + } + return machOFile.sections.contains(where: { $0.sectionName.hasPrefix(sectionNamePrefix) }) + } +} + +/// The platform an evolution interface spells availability for — what +/// `evolution --interface --emit-available --platform` passes — each +/// pipeline in its own spelling. +enum EvolutionAvailabilityPlatform: Sendable { + case macOS + + /// The platform of `@available(macOS, …)`. + var swiftSpelling: String { + switch self { + case .macOS: "macOS" + } + } + + /// The platform of `API_AVAILABLE(macos(…))`. + var objcSpelling: String { + switch self { + case .macOS: "macos" + } + } +} + +/// One image of one version on an evolution axis. +struct EvolutionImage: Sendable { + let imageName: String + let machOFile: MachOFile +} + +/// One version on an evolution axis: its label and the images whose +/// declarations make it up, the primary image first. +struct EvolutionVersion: Sendable { + let label: String + let images: [EvolutionImage] + + var primaryImage: EvolutionImage { images[0] } + + /// This version as a pipeline reading `language` sees it: only the + /// images carrying that metadata, or `nil` — off the axis — when the + /// primary image does not. + func keepingImages(carrying language: EvolutionMetadataLanguage) -> EvolutionVersion? { + guard language.isCarried(by: primaryImage.machOFile) else { return nil } + return EvolutionVersion(label: label, images: images.filter { language.isCarried(by: $0.machOFile) }) + } +} + +/// One ordered series of versions (oldest first), as one pipeline reads it. +struct EvolutionAxis: Sendable { + let versions: [EvolutionVersion] + /// Whether every version is a group of images (evolution proposal + /// `image-group-evolution`). It picks the builders' image-group entry + /// points, which name each version's images and record moves between + /// them, so a version of one image still reads differently from a group + /// of one. + let comparesImageGroups: Bool + /// Set when every label is a version number, so the interfaces also + /// spell each lifecycle one attribute or macro can express. + let availabilityPlatform: EvolutionAvailabilityPlatform? +} + +/// Extracts the same images from an *ordered series* of dyld shared caches — +/// the N-version counterpart of +/// `SwiftDiffableInterfaceBuilderTestSuite.CrossVersionDyldCacheImageTests`. +/// The caches are retained because the extracted `MachOFile`s resolve +/// cross-image references through them while indexing. +/// +/// One instance serves every pipeline: it keeps, per cache, every image of +/// `cacheImageNames` the cache holds, and each language's axis then keeps +/// the images carrying that language's metadata. A version whose primary +/// image is missing, or lacks the metadata, is off that axis — there is +/// nothing to index. A cache that cannot be opened still throws. +/// +/// Each cache is opened whole, the way `swift-section --dyld-shared-cache` +/// opens it, so the dumps match what the command line prints. Opened from +/// its main file alone, every read into another sub-cache file mapped that +/// file once more until MachOObjCSection 0.8.109, and an evolution over +/// every archived macOS minor ran past 5 GB. +/// +/// A suite comparing a group of images per version (evolution proposal +/// `image-group-evolution`) lists them in `cacheImageNames`, the primary +/// image first: AppKit with the frameworks Apple moved its classes into, +/// SwiftUI with SwiftUICore. Each other image joins its group where the +/// cache has it with the metadata — CollectionViewCore is in the macOS +/// caches from 13.0 on, SwiftUICore from 15.0 on. +@TestActor +class MultiVersionDyldCacheImageTests: Sendable { + let caches: [FullDyldCache] + private let swiftAxis: EvolutionAxis + private let objcAxis: EvolutionAxis + + /// Oldest first; each cache's `versionLabel` labels it on the axis. + class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } + + class var cacheImageName: MachOImageName { .SwiftUI } + + /// The images whose declarations make up one version, the primary + /// image first; by default the primary image alone. + class var cacheImageNames: [MachOImageName] { [cacheImageName] } + + /// Set on an axis whose every label is a version number. + class var availabilityPlatform: EvolutionAvailabilityPlatform? { nil } + + /// The three macOS caches most suites read: 15.5 → 26.5.2 → 27.0. + static var defaultMacOSCachePaths: [DyldSharedCachePath] { + [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] + } + + /// One archived cache per macOS minor, oldest first: the directories + /// under `/Volumes/DyldSharedCaches/macOS` that hold a cache. A cache is + /// labeled with its version, or with the major release + /// `archivedMacOSVersionLabelsByCacheVersion` names for it, so every label + /// is a version number. + static var archivedMacOSCachePaths: [DyldSharedCachePath] { + archivedMacOSCacheVersions.map { cacheVersion in + let cachePath = DyldSharedCachePath.macOS(cacheVersion) + guard let versionLabel = archivedMacOSVersionLabelsByCacheVersion[cacheVersion] else { return cachePath } + return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) + } + } + + static var archivedMacOSCacheVersions: [String] { [ + "11.0.1", + "11.1", + "11.2", + "11.3", + "11.4", + "11.5", + "11.6", + "11.7", + "12.0.1", + "12.1", + "12.2", + "12.3", + "12.4", + "12.5", + "12.6", + "12.7", + "13.0", + "13.1", + "13.2", + "13.3", + "13.4", + "13.5", + "13.6", + "13.7", + "14.0", + "14.1", + "14.2", + "14.3", + "14.4", + "14.5", + "14.6", + "14.7", + "14.8", + "15.0", + "15.1", + "15.2", + "15.3", + "15.4", + "15.5", + "15.6", + "15.7", + "15.8", + "26.0", + "26.1", + "26.2", + "26.3", + "26.4", + "26.5", + "26.6", + "26.7", + "27.0", + ] } + + /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and 12.0.1, + /// so those are the directories the volume has; the axis still labels + /// them 11.0 and 12.0, the versions an SDK's availability attributes name. + static var archivedMacOSVersionLabelsByCacheVersion: [String: String] { + ["11.0.1": "11.0", "12.0.1": "12.0"] + } + + init() async throws { + let primaryImageName = Self.cacheImageNames.first?.name + var caches: [FullDyldCache] = [] + var versions: [EvolutionVersion] = [] + for cachePath in Self.cachePaths { + let cache = try FullDyldCache(path: cachePath) + let images = Self.cacheImageNames.compactMap { imageName -> EvolutionImage? in + guard let machOFile = cache.machOFile(named: imageName) else { return nil } + return EvolutionImage(imageName: imageName.name, machOFile: machOFile) + } + guard let primaryImage = images.first, primaryImage.imageName == primaryImageName else { + continue + } + caches.append(cache) + versions.append(EvolutionVersion(label: cachePath.versionLabel, images: images)) + } + let comparesImageGroups = Self.cacheImageNames.count > 1 + let availabilityPlatform = Self.availabilityPlatform + self.caches = caches + self.swiftAxis = EvolutionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: .swift) }, + comparesImageGroups: comparesImageGroups, + availabilityPlatform: availabilityPlatform + ) + self.objcAxis = EvolutionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: .objc) }, + comparesImageGroups: comparesImageGroups, + availabilityPlatform: availabilityPlatform + ) + } + + /// The axis a pipeline reading `language` runs over. Computed at + /// initialization: the class properties it derives from are isolated to + /// the test actor, the pipelines are not. + nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis { + switch language { + case .swift: swiftAxis + case .objc: objcAxis + } + } +} diff --git a/Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift b/Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift new file mode 100644 index 00000000..d10e8f3d --- /dev/null +++ b/Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift @@ -0,0 +1,326 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import SwiftDiffing +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDiffing +import Semantic + +/// The four evolution outputs `swift-section` produces, each the pipeline of +/// one subcommand. +enum EvolutionDumpKind: Sendable { + /// `swift-section evolution`: the lineage report (`-Evolution.txt`) and + /// its machine-readable form (`-Evolution.json`). + case swiftReport + /// `swift-section evolution --interface`: the union interface with + /// lifecycle annotations (`-EvolutionInterface.swiftinterface`). + case swiftInterface + /// `swift-section objc evolution`: the lineage report + /// (`-ObjCEvolution.txt`) and its JSON (`-ObjCEvolution.json`). + case objcReport + /// `swift-section objc evolution --interface`: the union header with + /// lifecycle annotations (`-ObjCEvolutionInterface.h`). + case objcInterface + + var language: EvolutionMetadataLanguage { + switch self { + case .swiftReport, .swiftInterface: .swift + case .objcReport, .objcInterface: .objc + } + } +} + +/// Where a dump goes: printed for a quick look, or written next to the +/// other dumps for inspection. +enum EvolutionDumpDestination: Sendable { + case console + case file +} + +/// What one pipeline produced. +struct EvolutionDumpOutput: Sendable { + /// The file-name suffix, after the build version and the image names. + let suffix: String + /// What a maintainer reads: the report, or the annotated interface. + let text: String + let textFileExtension: String + /// The machine-readable form a report also writes; `nil` for an + /// interface. + let json: String? +} + +/// The evolution dumps: an *ordered series* of versions of one image — or +/// of one group of images per version (evolution proposal +/// `image-group-evolution`) — run through the pipelines of `swift-section +/// evolution` and `swift-section objc evolution`, with and without +/// `--interface`. +/// +/// The report pipelines freeze every version into a snapshot document +/// round-tripped through the persisted JSON form, so the codec and the +/// format-version gate run on real-world data. The interface pipelines +/// render the versions merged into one interface, each declaration's +/// lifecycle annotated; read one against the report of the same axis — the +/// annotations are the same lineages. +/// +/// A conforming suite supplies the axis each pipeline runs over. Like its +/// siblings this is a maintainer-inspection dump: it prints / writes results +/// without assertions. +protocol EvolutionDumpTests: SwiftInterfaceDumpTests { + func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension EvolutionDumpTests { + var indexConfiguration: SwiftDeclarationIndexConfiguration { + .init(showCImportedTypes: false) + } + + /// Runs one pipeline over this suite's axis for the pipeline's language, + /// then prints the text, or writes the text — and a report's JSON — + /// named after the newest version's images. + func dump(_ kind: EvolutionDumpKind, to destination: EvolutionDumpDestination) async throws { + let axis = evolutionAxis(for: kind.language) + let output: EvolutionDumpOutput + switch kind { + case .swiftReport: + output = try await swiftReport(over: axis) + case .swiftInterface: + output = try await swiftInterface(over: axis) + case .objcReport: + output = try await objcReport(over: axis) + case .objcInterface: + output = try await objcInterface(over: axis) + } + switch destination { + case .console: + printResult(output.text) + case .file: + guard let newestVersion = axis.versions.last else { return } + try write(output.text, forImageGroup: newestVersion.images, suffix: output.suffix, fileExtension: output.textFileExtension) + if let json = output.json { + try write(json, forImageGroup: newestVersion.images, suffix: output.suffix, fileExtension: "json") + } + } + } + + // MARK: - Swift + + /// One image indexed the way `swift-section snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form: what the evolution consumes is exactly what a saved + /// baseline would decode to. + private func swiftSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ABISnapshotDocument { + let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: image.machOFile) + try await builder.prepare() + let document = ABISnapshotDocument( + provenance: ABIProvenance( + label: label, + binaryPath: image.machOFile.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: builder.snapshot() + ) + return try ABISnapshotDocument.decode(from: document.encoded()) + } + + /// The lineage report and its JSON. The timed step covers indexing every + /// image of every version — the real cost; the lineage math afterwards + /// is milliseconds. + private func swiftReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + var documentsByVersion: [[ABISnapshotDocument]] = [] + try await measuringPreparation { + for version in axis.versions { + var documents: [ABISnapshotDocument] = [] + for image in version.images { + documents.append(try await swiftSnapshotDocument(of: image, label: version.label)) + } + documentsByVersion.append(documents) + } + } + let evolution: ABIEvolution + var report: String + if axis.comparesImageGroups { + let imageGroups = zip(axis.versions, documentsByVersion).map { version, documents in + zip(version.images, documents).map { image, document in + ABIImageSnapshot(imageName: image.imageName, snapshot: document.snapshot) + } + } + evolution = try ABIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: axis.versions.map { ABIVersionDescriptor(label: $0.label) } + ) + report = ABIEvolutionReporter().report(evolution) + } else { + let documents = documentsByVersion.flatMap { $0 } + evolution = try ABIEvolutionBuilder().evolution(of: documents) + report = ABIEvolutionReporter().report(evolution) + // For a two-version series the lineage events must match the + // two-sided differ verbatim — print both verdicts so the manual + // inspection can eyeball the consistency on real-world data. + if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { + let diff = ABIDiffer().diff(old: oldDocument, new: newDocument) + report += "\n\nPairwise cross-check — evolution ABI-breaking: \(evolution.hasBreakingChange) · diff ABI-breaking: \(diff.hasBreakingChange)" + } + } + return EvolutionDumpOutput( + suffix: "Evolution", + text: report, + textFileExtension: "txt", + json: String(decoding: try ABIJSON.encoder().encode(evolution), as: UTF8.self) + ) + } + + /// The annotated union interface plus the per-axis verdict line, so the + /// manual inspection can eyeball the CI-gate input next to the + /// rendering. The timed step covers indexing every version; the lineage + /// join and rendering afterwards are cheap by comparison. + private func swiftInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + let labels = axis.versions.map(\.label) + let availabilityAnnotationPlatform = axis.availabilityPlatform?.swiftSpelling + let builder: AnySwiftEvolutionInterfaceBuilder + if axis.comparesImageGroups { + // Each version's images render as one interface, every + // declaration through the image that indexed it. + builder = try AnySwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + imageGroups: axis.versions.map { version in + version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName, machO: $0.machOFile) } + }, + labels: labels, + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) + } else { + builder = try AnySwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + versions: axis.versions.map(\.primaryImage.machOFile), + labels: labels, + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) + } + try await measuringPreparation { + try await builder.prepare() + } + var report = try await builder.printAnnotatedInterface().string + if let evolution = builder.evolution { + report += "\n\n// ABI-breaking on this axis: \(evolution.hasBreakingChange)" + } + return EvolutionDumpOutput(suffix: "EvolutionInterface", text: report, textFileExtension: "swiftinterface", json: nil) + } + + // MARK: - Objective-C + + /// One image indexed the way `swift-section objc snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form. + private func objcSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ObjCAPISnapshotDocument { + let indexer = try await preparedObjCIndexer(of: image.machOFile) + let document = ObjCAPISnapshotDocument( + provenance: ObjCAPIProvenance( + label: label, + binaryPath: image.machOFile.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() + ) + return try ObjCAPISnapshotDocument.decode(from: document.encoded()) + } + + /// The lineage report and its JSON, as `swiftReport(over:)` builds the + /// Swift ones. + private func objcReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + var documentsByVersion: [[ObjCAPISnapshotDocument]] = [] + try await measuringPreparation { + for version in axis.versions { + var documents: [ObjCAPISnapshotDocument] = [] + for image in version.images { + documents.append(try await objcSnapshotDocument(of: image, label: version.label)) + } + documentsByVersion.append(documents) + } + } + let evolution: ObjCAPIEvolution + var report: String + if axis.comparesImageGroups { + let imageGroups = zip(axis.versions, documentsByVersion).map { version, documents in + zip(version.images, documents).map { image, document in + ObjCAPIImageSnapshot(imageName: image.imageName, snapshot: document.snapshot) + } + } + evolution = try ObjCAPIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: axis.versions.map { ObjCAPIVersionDescriptor(label: $0.label) } + ) + report = ObjCAPIEvolutionReporter().report(evolution) + } else { + let documents = documentsByVersion.flatMap { $0 } + evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) + report = ObjCAPIEvolutionReporter().report(evolution) + if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { + let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) + report += "\n\nPairwise cross-check — evolution API-breaking: \(evolution.hasBreakingChange) · diff API-breaking: \(diff.hasBreakingChange)" + } + } + return EvolutionDumpOutput( + suffix: "ObjCEvolution", + text: report, + textFileExtension: "txt", + json: String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self) + ) + } + + /// The annotated union header plus the per-axis verdict line. Every + /// version is indexed the way `objc evolution --interface` indexes it and + /// handed to the builder, which keeps what it rendered and snapshotted, + /// never the indexer; a group's images go in together, the primary image + /// first, so a class that moved between them stays one declaration. + private func objcInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + var builder = ObjCEvolutionInterfaceBuilder() + try await measuringPreparation { + for version in axis.versions { + let versionDescriptor = ObjCAPIVersionDescriptor(label: version.label) + if axis.comparesImageGroups { + var images: [ObjCEvolutionInterfaceImage] = [] + for image in version.images { + let indexer = try await preparedObjCIndexer(of: image.machOFile) + images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName, indexer: indexer, machO: image.machOFile)) + } + builder.addVersion(images: images, version: versionDescriptor) + } else { + let image = version.primaryImage + let indexer = try await preparedObjCIndexer(of: image.machOFile) + builder.addVersion(indexer: indexer, machO: image.machOFile, version: versionDescriptor) + } + } + } + let evolutionInterface = try builder.build(availabilityPlatform: axis.availabilityPlatform?.objcSpelling) + return EvolutionDumpOutput( + suffix: "ObjCEvolutionInterface", + text: evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)", + textFileExtension: "h", + json: nil + ) + } +} + +/// One image indexed the way the `objc` subcommands index it: the Swift +/// classes that keep no class object supplied from Swift metadata. +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +private func preparedObjCIndexer(of machO: MachOFile) async throws -> ObjCInterfaceIndexer { + let indexer = ObjCInterfaceIndexer( + machO: machO, + imagePath: machO.imagePath, + suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) + ) + try await indexer.prepare() + return indexer +} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift index edd2b785..fa6c8ac2 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift @@ -70,6 +70,23 @@ extension SwiftInterfaceDumpTests { let fileName = "\(primaryImage.machO.loadCommands.buildVersionCommand!)-\(imageGroupName)-\(suffix).\(fileExtension)" try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) } + + /// `write(_:for:suffix:fileExtension:)` for one version of an evolution + /// axis: named after the primary image's build version and every image + /// of the version, joined by `+` (`…-SwiftUI+SwiftUICore-Evolution.txt`). + /// A version of one image gets the name `write(_:for:…)` gives it. + func write( + _ string: String, + forImageGroup images: [EvolutionImage], + suffix: String, + fileExtension: String = "swiftinterface" + ) throws { + guard let primaryImage = images.first else { return } + try rootDirectory.createDirectoryIfNeeded() + let imageGroupName = images.map { $0.machOFile.imagePath.lastPathComponent }.joined(separator: "+") + let fileName = "\(primaryImage.machOFile.loadCommands.buildVersionCommand!)-\(imageGroupName)-\(suffix).\(fileExtension)" + try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) + } } extension BuildVersionCommand: @retroactive CustomStringConvertible { From cd2901d94cdc3675f0e99023bebcf72ef5da73c2 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 11:43:54 +0800 Subject: [PATCH 123/175] test(IntegrationTests): run every evolution output from one set of axis suites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit EvolutionTestSuite declares each version axis once — ten suites in place of twenty-one — and runs on it the Swift and Objective-C reports and interfaces it is read for, one line per test. The four old suite families and their files go, along with the tuple form of write(_:forImageGroup:). The tests and the names of the files they write are the same as before; only the test names change. --- ...ft-unify-evolution-integration-suites.html | 4 +- ...raft-unify-evolution-integration-suites.md | 6 +- Documentations/Internal/ABIEvolutionDesign.md | 9 +- .../Evolution/EvolutionTests.swift | 352 +++++++++++++ .../ObjCDiffing/ObjCAPIEvolutionTests.swift | 497 ------------------ .../SwiftDiffing/ABIEvolutionTests.swift | 293 ----------- .../SwiftEvolutionInterfaceBuilderTests.swift | 321 ----------- .../SwiftInterfaceTestSupport.swift | 25 +- 8 files changed, 363 insertions(+), 1144 deletions(-) create mode 100644 Tests/IntegrationTests/Evolution/EvolutionTests.swift delete mode 100644 Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift delete mode 100644 Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift delete mode 100644 Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift diff --git a/Documentations/Evolutions/draft-unify-evolution-integration-suites.html b/Documentations/Evolutions/draft-unify-evolution-integration-suites.html index f0d80781..36ca8d08 100644 --- a/Documentations/Evolutions/draft-unify-evolution-integration-suites.html +++ b/Documentations/Evolutions/draft-unify-evolution-integration-suites.html @@ -367,7 +367,7 @@

    改动地图

    同上 · EvolutionDumpKind / EvolutionDumpDestination / EvolutionDumpOutput新增四种输出、两种去处、一次输出的内容测试体缩成一行1 SwiftInterface/SwiftInterfaceTestSupport.swift · write(_:forImageGroup:suffix:fileExtension:)修改第 1 步加一个收 [EvolutionImage] 的重载,第 2 步删掉收元组的旧重载镜像组命名改用新值类型;分两步保证每步都能编1、2 Evolution/EvolutionTests.swift · EvolutionTestSuite新增十个轴套件,43 个一行测试,沿用旧套件里仍成立的注释合并后的套件2 - SwiftDiffing/ABIEvolutionTests.swift删除整个文件被合并2 + SwiftDiffing/ABIEvolutionTests.swift删除整个文件(SwiftDiffing/ 目录随之为空、删除)被合并2 SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift删除整个文件被合并2 ObjCDiffing/ObjCAPIEvolutionTests.swift删除整个文件(ObjCDiffing/ 目录随之为空、删除)被合并2 Documentations/Internal/ABIEvolutionDesign.md:235-243修改集成套件的路径与套件名改成新的这段是现行说明,引用了被删的文件3 @@ -631,7 +631,7 @@

    落地步骤

  • interfaceSpellsAvailabilityInItsOwnLanguagesSpelling
  • -
  • 十个轴套件取代旧文件:EvolutionTests.swift;删三个旧文件与空的 ObjCDiffing/;删旧重载。 +
  • 十个轴套件取代旧文件:EvolutionTests.swift;删三个旧文件与随之变空的 SwiftDiffing/、ObjCDiffing/;删旧重载。
    • everyAxisPipelinePairOfTheOldSuitesHasOneTestNow(43 个)
    • noSuiteReadsAnotherSuitesClassProperties
    • diff --git a/Documentations/Evolutions/draft-unify-evolution-integration-suites.md b/Documentations/Evolutions/draft-unify-evolution-integration-suites.md index ec729bb3..4a5cd583 100644 --- a/Documentations/Evolutions/draft-unify-evolution-integration-suites.md +++ b/Documentations/Evolutions/draft-unify-evolution-integration-suites.md @@ -98,7 +98,7 @@ | 同上 · `EvolutionDumpKind` / `EvolutionDumpDestination` / `EvolutionDumpOutput` | 新增 | 四种输出、两种去处、一次输出的内容 | 测试体缩成一行 | 1 | | `Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift` · `write(_:forImageGroup:suffix:fileExtension:)` | 修改 | 第 1 步加一个收 `[EvolutionImage]` 的重载,第 2 步删掉收元组的旧重载 | 镜像组命名改用新值类型;分两步保证每步都能编 | 1、2 | | `Tests/IntegrationTests/Evolution/EvolutionTests.swift` · `EvolutionTestSuite` | 新增 | 十个轴套件,43 个一行测试,沿用旧套件里仍成立的注释(11.x 方法名、镜像何时加入组等) | 合并后的套件 | 2 | -| `Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift` | 删除 | 整个文件 | 被合并 | 2 | +| `Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift` | 删除 | 整个文件(`SwiftDiffing/` 目录随之为空、删除) | 被合并 | 2 | | `Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift` | 删除 | 整个文件 | 被合并 | 2 | | `Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift` | 删除 | 整个文件(`ObjCDiffing/` 目录随之为空、删除) | 被合并 | 2 | | `Documentations/Internal/ABIEvolutionDesign.md:235-243` | 修改 | 集成套件的路径与套件名改成新的 | 这段是现行说明,引用了被删的文件 | 3 | @@ -453,7 +453,7 @@ enum EvolutionTestSuite { 验证一律在 Ultra 上做(本机是公司那台,不编大工程):`queued-build swift build --build-tests`,scratch 用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection`,默认 Xcode 编一遍,再用 `DEVELOPER_DIR=…/Xcode-26.6.0.app`(CI 的版本)编一遍。不运行 IntegrationTests。 -1. **新骨架与四条管线** —— 改动地图里 `EvolutionAxis.swift` 全部、`EvolutionDumpTests.swift` 全部、`SwiftInterfaceTestSupport.swift` 的新重载。旧的三个文件还在,与新代码并存,名字不冲突(旧基类嵌在 `ABIEvolutionTestSuite` 里)。 +1. **新骨架与四条管线**(已完成,Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过)—— 改动地图里 `EvolutionAxis.swift` 全部、`EvolutionDumpTests.swift` 全部、`SwiftInterfaceTestSupport.swift` 的新重载。旧的三个文件还在,与新代码并存,名字不冲突(旧基类嵌在 `ABIEvolutionTestSuite` 里)。 - 行为:`evolutionAxisForSwiftDropsVersionsWhosePrimaryImageHasNoSwiftSection` - 行为:`evolutionAxisForObjCKeepsEveryCacheHoldingAppKit` - 行为:`imageGroupAxisKeepsAnImageOnlyWhereItsCacheCarriesTheMetadata` @@ -461,7 +461,7 @@ enum EvolutionTestSuite { - 行为:`reportWritesTextAndJSONNamedAfterTheNewestVersionsImages` - 行为:`interfaceSpellsAvailabilityInItsOwnLanguagesSpelling` - 本步只编译,测试目标能编过即可。 -2. **十个轴套件取代旧文件** —— `EvolutionTests.swift`;删除三个旧文件与空的 `ObjCDiffing/` 目录;删除 `write(_:forImageGroup:)` 收元组的旧重载。 +2. **十个轴套件取代旧文件** —— `EvolutionTests.swift`;删除三个旧文件与随之变空的 `SwiftDiffing/`、`ObjCDiffing/` 目录;删除 `write(_:forImageGroup:)` 收元组的旧重载。 - 行为:`everyAxisPipelinePairOfTheOldSuitesHasOneTestNow`(43 个,逐一对照「提议方案」的表) - 行为:`noSuiteReadsAnotherSuitesClassProperties` - 行为:`archivedAxesTakeTheCacheListFromTheBaseClass` diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index c7621664..15ee4357 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -232,14 +232,7 @@ swift-section evolution ... \ 8. **兼容性推广**:逐转换 additive/breaking 与 `firstBreakingTransitionIndex`。 9. **reporter**:小型 evolution 的整段文本断言(确定性输出)。 -另有**维护者手检集成套件** `Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift` -(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行): -`ABIEvolutionTestSuite.DyldCacheTests` 对三份 macOS dyld cache(15.5 → 26.5.1 → -27.0-beta.1)提取同一 image(AppKit)跑完整 pipeline——逐版本索引 → 冻结 → -**经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → -timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘); -`SwiftUICoreTests`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 -diff 的 verdict 交叉核对行。 +另有**维护者手检集成套件**,在 `Tests/IntegrationTests/Evolution/`(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行;Swift 与 ObjC 的报告和联合接口共用这一套,见提案 [unify-evolution-integration-suites](../Evolutions/draft-unify-evolution-integration-suites.md)):每条版本轴一个套件,挂在 `EvolutionTestSuite` 下,各按读的元数据筛版本。报告的 `swiftReportFile` / `swiftReportString` 跑完整 pipeline——逐版本索引 → 冻结 → **经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘)。`SwiftUIDyldCacheTests` 对三份 macOS dyld cache(15.5 → 26.5.2 → 27.0)提取 SwiftUI;`SwiftUICoreSimulatorTests`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 diff 的 verdict 交叉核对行。 ## 后续项(不在首轮范围) diff --git a/Tests/IntegrationTests/Evolution/EvolutionTests.swift b/Tests/IntegrationTests/Evolution/EvolutionTests.swift new file mode 100644 index 00000000..b22462ea --- /dev/null +++ b/Tests/IntegrationTests/Evolution/EvolutionTests.swift @@ -0,0 +1,352 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import Semantic + +/// Every evolution axis the maintainer inspects, one suite per axis. A suite +/// declares its caches and images once and runs on them each evolution +/// output it is read for — the Swift and Objective-C reports and interfaces +/// alike — with one test per output and destination. Each language's +/// pipelines see only the versions whose images carry their metadata (see +/// `MultiVersionDyldCacheImageTests`). +/// +/// Read an interface against the report of the same axis: the two views +/// must tell one story. An annotated interface is worth reading only from +/// three versions up — introduced mid-axis, removed mid-axis, modified +/// twice, gone-and-back bitmaps; for two, `diff --interface` already covers +/// it. +enum EvolutionTestSuite { + /// SwiftUI across the default three caches (15.5 → 26.5.2 → 27.0) — the + /// flagship N == 3 lineage: introduced / modified / removed / re-added + /// stories only visible with more than two versions. + final class SwiftUIDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cacheImageName: MachOImageName { .SwiftUI } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + /// The pack-generic façade on the same three images: the axis + /// through `SwiftEvolutionInterfaceBuilder` (compile-time arity), dumped for eyeball comparison + /// against `swiftInterfaceString()` — the two must be + /// byte-identical. + @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) + @Test func swiftInterfaceStringViaPackFacade() async throws { + let versions = evolutionAxis(for: .swift).versions + let builder = try SwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + versions: versions[0].primaryImage.machOFile, versions[1].primaryImage.machOFile, versions[2].primaryImage.machOFile, + labels: versions.map(\.label) + ) + // No `measuringPreparation` here: this @Test runs on the suite's + // @TestActor, and handing it an actor-isolated closure trips + // region-isolation checking (the extension helpers avoid this by + // being nonisolated themselves). + try await builder.prepare() + printResult(try await builder.printAnnotatedInterface().string) + } + } + + /// SwiftUICore across the default three caches — the Swift-rich axis, + /// exercising the union interface over heavy generics, opaque returns + /// and extension blocks. + final class SwiftUICoreDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cacheImageName: MachOImageName { .SwiftUICore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + } + + /// AppKit's Objective-C metadata across the default three caches. + final class AppKitDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// SwiftUI across every archived macOS cache, 11.0 → 27.0. Every label + /// is a version number, so the interface also spells each lifecycle one + /// attribute can express as `@available(macOS, …)`. + final class SwiftUIArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } + override class var cacheImageName: MachOImageName { .SwiftUI } + override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + } + + /// AppKit's Objective-C metadata across every archived macOS cache, with + /// the header's `API_AVAILABLE` / `API_OBSOLETED` macros. + /// + /// The method names of a macOS 11 cache read correctly only from + /// MachOObjCSection 0.8.202. Its relative method lists count a selector + /// from the name field itself, where later caches count it from a + /// selector base, and an earlier reader made every class and category + /// method of 11.x garbage — 11.7 → 12.0.1 then reported about 47,000 + /// removals and 53,000 additions instead of about 1,200 and 1,400. + final class AppKitArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } + override class var cacheImageName: MachOImageName { .AppKit } + override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// SwiftUI together with SwiftUICore across the default three caches, + /// each version one group of images (evolution proposal + /// `image-group-evolution`): what moved between the two images after the + /// split reads as moved, not as removed and added. + final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// The same group across every archived macOS cache: SwiftUI alone until + /// 14.8, SwiftUICore joining it in 15.0 — where an evolution of SwiftUI + /// alone reads every declaration moved into SwiftUICore as removed. Every + /// label is a version number, so both interfaces spell availability. + final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// AppKit together with the frameworks Apple moved its classes into — + /// UIFoundation, CollectionViewCore, CoreAutoLayout — across the default + /// three caches, each version one group of images. + final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// The same group across every archived macOS cache: the classes that + /// moved between AppKit, UIFoundation and CollectionViewCore in 13.0 and + /// 15.0 — where an evolution of AppKit alone reads them as removed or + /// added — read as moved. CollectionViewCore joins the group in 13.0. + final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } + override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } + override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the + /// N == 2 case, whose printed pairwise cross-check line must agree with + /// the two-sided differ. + final class SwiftUICoreSimulatorTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } + override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } + + nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis { + let versions = [ + EvolutionVersion(label: "18.5", images: [EvolutionImage(imageName: "SwiftUICore", machOFile: oldMachOFile)]), + EvolutionVersion(label: "26.5", images: [EvolutionImage(imageName: "SwiftUICore", machOFile: newMachOFile)]), + ] + return EvolutionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: language) }, + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + } +} diff --git a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift deleted file mode 100644 index 4ffe7019..00000000 --- a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift +++ /dev/null @@ -1,497 +0,0 @@ -import Foundation -import Testing -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -import SwiftIndexing -import ObjCMetadataSource -import ObjCIndexing -import ObjCInterface -import ObjCDiffing -import Semantic - -/// One image indexed the way the `objc` subcommands index it: the Swift -/// classes that keep no class object supplied from Swift metadata. -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -private func preparedObjCIndexer(of machO: MachOFile) async throws -> ObjCInterfaceIndexer { - let indexer = ObjCInterfaceIndexer( - machO: machO, - imagePath: machO.imagePath, - suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) - ) - try await indexer.prepare() - return indexer -} - -/// The Objective-C counterpart of ``ABIEvolutionDumpTests``. -/// -/// These index an *ordered series* of versions of one image — or of one -/// group of images per version (evolution proposal `image-group-evolution`) -/// — with MachOObjCSection's `ObjCInterfaceIndexer`, freeze each into an -/// `ObjCAPISnapshotDocument` (round-tripping through the persisted JSON form -/// so the codec and the format-version gate run on real-world data), and run -/// the series through `ObjCAPIEvolutionBuilder` + `ObjCAPIEvolutionReporter` — -/// the `swift-section objc evolution` pipeline. The annotated union header of -/// the same axis is ``ObjCEvolutionInterfaceDumpTests``, below. Like its -/// siblings it is a maintainer-inspection dump: it prints / writes results -/// without assertions. -protocol ObjCAPIEvolutionDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension ObjCAPIEvolutionDumpTests { - /// One image indexed the way `swift-section objc snapshot` indexes it and - /// frozen into a labeled snapshot document, round-tripped through the - /// persisted form: what the evolution consumes is exactly what a saved - /// baseline would decode to. - private func snapshotDocument(of machO: MachOFile, label: String) async throws -> ObjCAPISnapshotDocument { - let indexer = try await preparedObjCIndexer(of: machO) - let document = ObjCAPISnapshotDocument( - provenance: ObjCAPIProvenance( - label: label, - binaryPath: machO.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() - ) - return try ObjCAPISnapshotDocument.decode(from: document.encoded()) - } - - /// Every version (oldest first) as `snapshotDocument(of:label:)`. The - /// timed step covers the whole preparation; the lineage math afterwards - /// takes seconds at most. - private func snapshotDocuments(of versions: [(label: String, machO: MachOFile)]) async throws -> [ObjCAPISnapshotDocument] { - var documents: [ObjCAPISnapshotDocument] = [] - try await measuringPreparation { - for version in versions { - documents.append(try await snapshotDocument(of: version.machO, label: version.label)) - } - } - return documents - } - - private func timelineReport(of evolution: ObjCAPIEvolution, documents: [ObjCAPISnapshotDocument]) -> String { - var report = ObjCAPIEvolutionReporter().report(evolution) - // For a two-version series the lineage events must match the - // two-sided differ verbatim — print both verdicts so the manual - // inspection can eyeball the consistency on real-world data. - if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { - let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) - report += "\n\nPairwise cross-check — evolution API-breaking: \(evolution.hasBreakingChange) · diff API-breaking: \(diff.hasBreakingChange)" - } - return report - } - - /// Console analogue of `evolutionFile`: prepares every version, then - /// prints the timeline report. - func evolutionString(versions: [(label: String, machO: MachOFile)]) async throws { - let documents = try await snapshotDocuments(of: versions) - let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) - printResult(timelineReport(of: evolution, documents: documents)) - } - - /// Writes the timeline report (`-ObjCEvolution.txt`) and the - /// machine-readable form (`-ObjCEvolution.json`) next to the Swift - /// evolution dumps, both named after the *newest* version. - func evolutionFile(versions: [(label: String, machO: MachOFile)]) async throws { - let documents = try await snapshotDocuments(of: versions) - guard let newestVersion = versions.last else { return } - let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) - try write(timelineReport(of: evolution, documents: documents), for: newestVersion.machO, suffix: "ObjCEvolution", fileExtension: "txt") - try write(String(decoding: ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self), for: newestVersion.machO, suffix: "ObjCEvolution", fileExtension: "json") - } - - // MARK: - Groups of images - - /// Versions made up of groups of images (evolution proposal - /// `image-group-evolution`): every image of every version frozen as - /// `snapshotDocument(of:label:)` freezes one, under its image name. - private func imageGroupEvolution( - of imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] - ) async throws -> ObjCAPIEvolution { - var imageGroups: [[ObjCAPIImageSnapshot]] = [] - try await measuringPreparation { - for version in imageGroupVersions { - var imageSnapshots: [ObjCAPIImageSnapshot] = [] - for image in version.images { - let document = try await snapshotDocument(of: image.machO, label: version.label) - imageSnapshots.append(ObjCAPIImageSnapshot(imageName: image.imageName.name, snapshot: document.snapshot)) - } - imageGroups.append(imageSnapshots) - } - } - return try ObjCAPIEvolutionBuilder().evolution( - ofImageGroups: imageGroups, - versions: imageGroupVersions.map { ObjCAPIVersionDescriptor(label: $0.label) } - ) - } - - /// Console analogue of `evolutionFile(imageGroupVersions:)`. - func evolutionString(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - printResult(ObjCAPIEvolutionReporter().report(try await imageGroupEvolution(of: imageGroupVersions))) - } - - /// Writes the timeline report and the JSON of an evolution over groups of - /// images, named after the newest version's group - /// (`…-AppKit+UIFoundation+CollectionViewCore+CoreAutoLayout-ObjCEvolution.txt` - /// / `.json`). - func evolutionFile(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - let evolution = try await imageGroupEvolution(of: imageGroupVersions) - guard let newestVersion = imageGroupVersions.last else { return } - try write(ObjCAPIEvolutionReporter().report(evolution), forImageGroup: newestVersion.images, suffix: "ObjCEvolution", fileExtension: "txt") - try write(String(decoding: ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self), forImageGroup: newestVersion.images, suffix: "ObjCEvolution", fileExtension: "json") - } -} - -enum ObjCAPIEvolutionTestSuite { - /// AppKit's Objective-C metadata across an ordered series of dyld shared - /// caches. A version joins the axis when its image carries an `__objc_*` - /// section, which AppKit does in every cache — unlike its Swift sections, - /// which the Swift suites need and which only appear from macOS 14. - class MultiVersionDyldCacheImageTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .AppKit } - - override class func isOnAxis(_ machOFile: MachOFile) -> Bool { - machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__objc_") }) - } - } - - /// AppKit across the three macOS caches the Swift evolution suites - /// default to (15.5 → 26.5.2 → 27.0), so the Objective-C report can be - /// read beside theirs. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: versions) - } - } - - /// AppKit across every archived macOS cache, on the axis of the Swift - /// `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests`: the - /// same versions under the same labels, listed there once for both. - /// - /// The method names of a macOS 11 cache read correctly only from - /// MachOObjCSection 0.8.202. Its relative method lists count a selector - /// from the name field itself, where later caches count it from a - /// selector base, and an earlier reader made every class and category - /// method of 11.x garbage — 11.7 → 12.0.1 then reported about 47,000 - /// removals and 53,000 additions instead of about 1,200 and 1,400. - final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: versions) - } - } - - /// AppKit together with the frameworks Apple moved its classes into — - /// UIFoundation, CollectionViewCore, CoreAutoLayout — across the default - /// three caches (15.5 → 26.5.2 → 27.0), each version one group of images - /// (evolution proposal `image-group-evolution`). - final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, on the axis of - /// ``ArchivedDyldCacheTests``: the classes that moved between AppKit, - /// UIFoundation and CollectionViewCore in 13.0 and 15.0 — where an - /// evolution of AppKit alone reads them as removed or added — read as - /// moved. CollectionViewCore joins the group in 13.0. - final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { AppKitImageGroupDyldCacheTests.cacheImageNames } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// SwiftUI together with SwiftUICore across the default three caches — - /// the Objective-C side of `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache: SwiftUI alone until - /// 14.8, SwiftUICore joining it in 15.0. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { SwiftUIImageGroupDyldCacheTests.cacheImageNames } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } -} - -/// The annotated-union-header analogue of ``ObjCAPIEvolutionDumpTests``, and -/// the Objective-C counterpart of ``SwiftEvolutionInterfaceDumpTests``. -/// -/// These run the same series through MachOObjCSection's -/// `ObjCEvolutionInterfaceBuilder` — the `swift-section objc evolution -/// --interface` pipeline: every declaration rendered the way `objc dump` -/// renders it, the versions merged into one header, and each declaration's -/// lifecycle annotated. Read the header against the lineage report of the -/// same axis — the annotations are the same lineages. Like its siblings it is -/// a maintainer-inspection dump: it prints / writes results without -/// assertions. -protocol ObjCEvolutionInterfaceDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension ObjCEvolutionInterfaceDumpTests { - /// Indexes every version (oldest first) the way `objc evolution - /// --interface` does and hands it to the builder, which keeps what it - /// rendered and snapshotted, never the indexer. The timed step covers the - /// indexing and rendering of every version. - private func evolutionInterface( - of versions: [(label: String, machO: MachOFile)], - availabilityPlatform: String? - ) async throws -> ObjCEvolutionInterface { - var builder = ObjCEvolutionInterfaceBuilder() - try await measuringPreparation { - for version in versions { - let indexer = try await preparedObjCIndexer(of: version.machO) - builder.addVersion(indexer: indexer, machO: version.machO, version: ObjCAPIVersionDescriptor(label: version.label)) - } - } - return try builder.build(availabilityPlatform: availabilityPlatform) - } - - /// `evolutionInterface(of:availabilityPlatform:)` over versions made up - /// of groups of images (evolution proposal `image-group-evolution`): each - /// version's images handed to the builder together, the primary image - /// first, so a class that moved between them stays one declaration. - private func evolutionInterface( - ofImageGroups imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityPlatform: String? - ) async throws -> ObjCEvolutionInterface { - var builder = ObjCEvolutionInterfaceBuilder() - try await measuringPreparation { - for version in imageGroupVersions { - var images: [ObjCEvolutionInterfaceImage] = [] - for image in version.images { - let indexer = try await preparedObjCIndexer(of: image.machO) - images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName.name, indexer: indexer, machO: image.machO)) - } - builder.addVersion(images: images, version: ObjCAPIVersionDescriptor(label: version.label)) - } - } - return try builder.build(availabilityPlatform: availabilityPlatform) - } - - /// The annotated header plus the per-axis verdict line, so the manual - /// inspection can eyeball the CI-gate input next to the rendering. - private func annotatedHeaderReport(of evolutionInterface: ObjCEvolutionInterface) -> String { - evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)" - } - - /// Console analogue of `evolutionInterfaceFile`. A platform adds the - /// availability macros, as `objc evolution --interface --emit-available - /// --platform` does. - func evolutionInterfaceString(versions: [(label: String, machO: MachOFile)], availabilityPlatform: String? = nil) async throws { - let evolutionInterface = try await evolutionInterface(of: versions, availabilityPlatform: availabilityPlatform) - printResult(annotatedHeaderReport(of: evolutionInterface)) - } - - /// Writes the annotated header (`-ObjCEvolutionInterface.h`) next to the - /// lineage report, named after the *newest* version. - func evolutionInterfaceFile(versions: [(label: String, machO: MachOFile)], availabilityPlatform: String? = nil) async throws { - let evolutionInterface = try await evolutionInterface(of: versions, availabilityPlatform: availabilityPlatform) - guard let newestVersion = versions.last else { return } - try write(annotatedHeaderReport(of: evolutionInterface), for: newestVersion.machO, suffix: "ObjCEvolutionInterface", fileExtension: "h") - } - - /// Console analogue of - /// `evolutionInterfaceFile(imageGroupVersions:availabilityPlatform:)`. - func evolutionInterfaceString( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityPlatform: String? = nil - ) async throws { - let evolutionInterface = try await evolutionInterface(ofImageGroups: imageGroupVersions, availabilityPlatform: availabilityPlatform) - printResult(annotatedHeaderReport(of: evolutionInterface)) - } - - /// Writes the annotated header of versions made up of groups of images, - /// named after the newest version's group - /// (`…-AppKit+UIFoundation+CollectionViewCore+CoreAutoLayout-ObjCEvolutionInterface.h`). - func evolutionInterfaceFile( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityPlatform: String? = nil - ) async throws { - let evolutionInterface = try await evolutionInterface(ofImageGroups: imageGroupVersions, availabilityPlatform: availabilityPlatform) - guard let newestVersion = imageGroupVersions.last else { return } - try write(annotatedHeaderReport(of: evolutionInterface), forImageGroup: newestVersion.images, suffix: "ObjCEvolutionInterface", fileExtension: "h") - } -} - -enum ObjCEvolutionInterfaceTestSuite { - /// AppKit across the three macOS caches the evolution suites default to - /// (15.5 → 26.5.2 → 27.0) — the axis of - /// `ObjCAPIEvolutionTestSuite.DyldCacheTests`, so the header and the - /// report can be read side by side. - final class DyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions) - } - } - - /// AppKit across every archived macOS cache, on the axis of - /// `ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests`. Every label is a - /// version number, so the header also spells each lifecycle one macro can - /// express as `API_AVAILABLE` / `API_OBSOLETED`. - final class ArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions, availabilityPlatform: "macos") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions, availabilityPlatform: "macos") - } - } - - /// AppKit with UIFoundation, CollectionViewCore and CoreAutoLayout across - /// the default three caches — the axis of - /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests`. - final class AppKitImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, on the axis of - /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupArchivedDyldCacheTests`, - /// with the availability macros. - final class AppKitImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - } - - /// SwiftUI with SwiftUICore across the default three caches — the axis - /// of `ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. - final class SwiftUIImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, with the - /// availability macros. - final class SwiftUIImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - } -} diff --git a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift deleted file mode 100644 index 1a555bd1..00000000 --- a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift +++ /dev/null @@ -1,293 +0,0 @@ -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -@testable import SwiftInterface -@_spi(Support) @testable import SwiftIndexing -import SwiftDiffing - -/// The N-version analogue of ``SwiftDiffableInterfaceBuilderTests``. -/// -/// Where the diffable-interface tests index a *pair* of binaries and diff -/// them, these index an *ordered series* of versions of one module, freeze -/// each into an `ABISnapshotDocument` (round-tripping through the persisted -/// JSON form so the codec and the format-version gate run on real-world -/// data), and run the series through `ABIEvolutionBuilder` + -/// `ABIEvolutionReporter` — the `swift-section evolution` pipeline. Like its -/// siblings it is a maintainer-inspection dump: it prints / writes results -/// without assertions. -protocol ABIEvolutionDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension ABIEvolutionDumpTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - - /// Indexes every version (oldest first) and freezes it into a labeled, - /// persistence-round-tripped snapshot document. The timed step covers the - /// whole preparation — indexing N binaries is the real cost; the lineage - /// math afterwards is milliseconds. - private func snapshotDocuments( - of versions: [(label: String, machO: some MachOFieldLayoutRenderable)] - ) async throws -> [ABISnapshotDocument] { - var documents: [ABISnapshotDocument] = [] - try await measuringPreparation { - for version in versions { - let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: version.machO) - try await builder.prepare() - let document = ABISnapshotDocument( - provenance: ABIProvenance( - label: version.label, - binaryPath: version.machO.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: builder.snapshot() - ) - // Round-trip through the persisted form: what the evolution - // consumes is exactly what a saved baseline would decode to. - documents.append(try ABISnapshotDocument.decode(from: document.encoded())) - } - } - return documents - } - - private func timelineReport(of documents: [ABISnapshotDocument]) throws -> String { - let evolution = try ABIEvolutionBuilder().evolution(of: documents) - var report = ABIEvolutionReporter().report(evolution) - // For a two-version series the lineage events must match the - // two-sided differ verbatim — print both verdicts so the manual - // inspection can eyeball the consistency on real-world data. - if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { - let diff = ABIDiffer().diff(old: oldDocument, new: newDocument) - report += "\n\nPairwise cross-check — evolution ABI-breaking: \(evolution.hasBreakingChange) · diff ABI-breaking: \(diff.hasBreakingChange)" - } - return report - } - - /// Console analogue of `diffString`: prepares every version, then prints - /// the timeline report. - func evolutionString(versions: [(label: String, machO: some MachOFieldLayoutRenderable)]) async throws { - let documents = try await snapshotDocuments(of: versions) - printResult(try timelineReport(of: documents)) - } - - /// File analogue of `diffFile`: writes the timeline report - /// (`-Evolution.txt`) and the machine-readable form (`-Evolution.json`) - /// next to the interface/diff dumps, both named after the *newest* - /// version. - func evolutionFile(versions: [(label: String, machO: some MachOFieldLayoutRenderable)]) async throws { - let documents = try await snapshotDocuments(of: versions) - guard let newestVersion = versions.last else { return } - try write(try timelineReport(of: documents), for: newestVersion.machO, suffix: "Evolution", fileExtension: "txt") - let evolution = try ABIEvolutionBuilder().evolution(of: documents) - try write(String(decoding: ABIJSON.encoder().encode(evolution), as: UTF8.self), for: newestVersion.machO, suffix: "Evolution", fileExtension: "json") - } - - // MARK: - Groups of images - - /// Versions made up of groups of images (evolution proposal - /// `image-group-evolution`): every image of every version indexed and - /// frozen as `snapshotDocuments(of:)` freezes one, round-tripped through - /// the persisted form, under its image name. - private func imageGroupEvolution( - of imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] - ) async throws -> ABIEvolution { - var imageGroups: [[ABIImageSnapshot]] = [] - try await measuringPreparation { - for version in imageGroupVersions { - var imageSnapshots: [ABIImageSnapshot] = [] - for image in version.images { - let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: image.machO) - try await builder.prepare() - let document = ABISnapshotDocument( - provenance: ABIProvenance( - label: version.label, - binaryPath: image.machO.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: builder.snapshot() - ) - imageSnapshots.append(ABIImageSnapshot( - imageName: image.imageName.name, - snapshot: try ABISnapshotDocument.decode(from: document.encoded()).snapshot - )) - } - imageGroups.append(imageSnapshots) - } - } - return try ABIEvolutionBuilder().evolution( - ofImageGroups: imageGroups, - versions: imageGroupVersions.map { ABIVersionDescriptor(label: $0.label) } - ) - } - - /// Console analogue of `evolutionFile(imageGroupVersions:)`. - func evolutionString(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - printResult(ABIEvolutionReporter().report(try await imageGroupEvolution(of: imageGroupVersions))) - } - - /// Writes the timeline report and the JSON of an evolution over groups of - /// images, named after the newest version's group - /// (`…-SwiftUI+SwiftUICore-Evolution.txt` / `.json`). - func evolutionFile(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - let evolution = try await imageGroupEvolution(of: imageGroupVersions) - guard let newestVersion = imageGroupVersions.last else { return } - try write(ABIEvolutionReporter().report(evolution), forImageGroup: newestVersion.images, suffix: "Evolution", fileExtension: "txt") - try write(String(decoding: ABIJSON.encoder().encode(evolution), as: UTF8.self), forImageGroup: newestVersion.images, suffix: "Evolution", fileExtension: "json") - } -} - -enum ABIEvolutionTestSuite { - /// Extracts the same image from an *ordered series* of dyld shared caches — - /// the N-version counterpart of - /// `SwiftDiffableInterfaceBuilderTestSuite.CrossVersionDyldCacheImageTests`. - /// The caches are retained because the extracted `MachOFile`s resolve - /// cross-image references through them while indexing. - /// - /// A version whose cache lacks the image, or whose image lacks the metadata - /// a suite reads (`isOnAxis(_:)`), is left off the axis: there is nothing - /// to index. For the Swift suites that is an image with no `__swift5_*` - /// section, and indexing it anyway logs four extraction failures. AppKit - /// kept its Swift API in `libswiftAppKit.dylib` until macOS 14, so a Swift - /// AppKit axis reaching further back starts at 14.0. A cache that cannot - /// be opened still throws. - /// - /// Each cache is opened whole, the way `swift-section --dyld-shared-cache` - /// opens it, so the dumps match what the command line prints. Opened from - /// its main file alone, every read into another sub-cache file mapped that - /// file once more until MachOObjCSection 0.8.109, and an evolution over - /// every archived macOS minor ran past 5 GB. - /// - /// A suite comparing a group of images per version (evolution proposal - /// `image-group-evolution`) lists them in `cacheImageNames`, the primary - /// image first: AppKit with the frameworks Apple moved its classes into, - /// SwiftUI with SwiftUICore. A version joins the axis when its cache has - /// the primary image on the axis; each other image joins its group where - /// the cache has it on the axis — CollectionViewCore is in the macOS - /// caches from 13.0 on, SwiftUICore from 15.0 on. - @TestActor - class MultiVersionDyldCacheImageTests: Sendable { - let caches: [FullDyldCache] - /// Each version's primary image. - let versions: [(label: String, machO: MachOFile)] - /// Each version's group of images, the primary image first. - let imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] - - /// Oldest first; each cache's `versionLabel` labels it on the axis. - class var cachePaths: [DyldSharedCachePath] { [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] } - class var cacheImageName: MachOImageName { .SwiftUI } - - /// The images whose declarations make up one version, the primary - /// image first; by default the primary image alone. - class var cacheImageNames: [MachOImageName] { [cacheImageName] } - - /// Whether a version's image belongs on the axis: it must carry the - /// metadata the suite indexes, which for the Swift suites is a - /// `__swift5_*` section. - class func isOnAxis(_ machOFile: MachOFile) -> Bool { - machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__swift5_") }) - } - - init() async throws { - var caches: [FullDyldCache] = [] - var versions: [(label: String, machO: MachOFile)] = [] - var imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] = [] - for cachePath in Self.cachePaths { - let cache = try FullDyldCache(path: cachePath) - let images = Self.cacheImageNames.compactMap { imageName -> (imageName: MachOImageName, machO: MachOFile)? in - guard let machOFile = cache.machOFile(named: imageName), Self.isOnAxis(machOFile) else { return nil } - return (imageName, machOFile) - } - guard let primaryImage = images.first, primaryImage.imageName == Self.cacheImageNames.first else { - continue - } - caches.append(cache) - versions.append((cachePath.versionLabel, primaryImage.machO)) - imageGroupVersions.append((cachePath.versionLabel, images)) - } - self.caches = caches - self.versions = versions - self.imageGroupVersions = imageGroupVersions - } - } - - /// AppKit across three macOS caches (15.5 → 26.5.1 → 27.0 beta 1) — the - /// flagship N == 3 lineage: introduced/modified/removed/re-added stories - /// only visible with more than two versions. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: versions) - } - } - - /// SwiftUI together with SwiftUICore across the default three caches - /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution - /// proposal `image-group-evolution`): what moved between the two images - /// after the split reads as moved, not as removed and added. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, on the axis of - /// `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests`: - /// SwiftUI alone until 14.8, SwiftUICore joining it in 15.0 — where an - /// evolution of SwiftUI alone reads every declaration moved into - /// SwiftUICore as removed. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the - /// N == 2 case, whose printed pairwise cross-check line must agree with - /// the two-sided differ. - final class SwiftUICoreTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, nonisolated ABIEvolutionDumpTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: [("18.5", oldMachOFile), ("26.5", newMachOFile)]) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: [("18.5", oldMachOFile), ("26.5", newMachOFile)]) - } - } -} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift deleted file mode 100644 index f8a0ade3..00000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ /dev/null @@ -1,321 +0,0 @@ -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -@_spi(Support) @testable import SwiftInterface -@_spi(Support) @testable import SwiftIndexing -import SwiftDiffing -import Semantic - -/// The annotated-union-interface analogue of ``ABIEvolutionDumpTests``. -/// -/// Where the evolution dump tests run an ordered series of versions through -/// the lineage-report pipeline (`ABIEvolutionBuilder` + `ABIEvolutionReporter`), -/// these run the same series through `AnySwiftEvolutionInterfaceBuilder` — -/// the `swift-section evolution --interface` pipeline — and dump the union -/// interface with lifecycle annotations. Like its siblings it is a -/// maintainer-inspection dump: it prints / writes results without assertions. -/// Inspect the output against the lineage report the `ABIEvolutionTests` -/// dumps produce for the same axis — the two views must tell one story -/// (annotation facts are the same lineages). -/// -/// Every axis here has three versions or more, on -/// `MultiVersionDyldCacheImageTests`: an evolution over fewer than three -/// images is what `diff --interface` already covers, and the stories this -/// view exists for — introduced mid-axis, removed mid-axis, modified twice, -/// gone-and-back bitmaps — only appear from three versions up. -protocol SwiftEvolutionInterfaceDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftEvolutionInterfaceDumpTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - - /// Builds and `prepare()`s the whole axis in one timed step — indexing N - /// binaries is the real cost; the lineage join and rendering afterwards - /// are cheap by comparison. - private func preparedBuilder( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)], - availabilityAnnotationPlatform: String? - ) async throws -> AnySwiftEvolutionInterfaceBuilder { - let builder = try AnySwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - versions: versions.map(\.machO), - labels: versions.map(\.label), - availabilityAnnotationPlatform: availabilityAnnotationPlatform - ) - try await measuringPreparation { - try await builder.prepare() - } - return builder - } - - /// The annotated union interface plus the per-axis verdict line, so the - /// manual inspection can eyeball the CI-gate input next to the rendering. - private func annotatedInterfaceReport(of builder: AnySwiftEvolutionInterfaceBuilder) async throws -> String { - var report = try await builder.printAnnotatedInterface().string - if let evolution = builder.evolution { - report += "\n\n// ABI-breaking on this axis: \(evolution.hasBreakingChange)" - } - return report - } - - /// Console analogue of `evolutionString`: prepares every version, then - /// prints the annotated union interface. A platform adds the genuine - /// `@available` lines, as `evolution --interface --emit-available - /// --platform` does. - func evolutionInterfaceString( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(versions: versions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - printResult(try await annotatedInterfaceReport(of: builder)) - } - - /// File analogue of `evolutionFile`: writes the annotated union interface - /// (`-EvolutionInterface.swiftinterface`) next to the lineage-report and - /// diff dumps, named after the *newest* version. - func evolutionInterfaceFile( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(versions: versions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - guard let newestVersion = versions.last else { return } - try await write(annotatedInterfaceReport(of: builder), for: newestVersion.machO, suffix: "EvolutionInterface") - } - - // MARK: - Groups of images - - /// Versions made up of groups of images (evolution proposal - /// `image-group-evolution`): each version's images render as one - /// interface, every declaration through the image that indexed it. - private func preparedBuilder( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityAnnotationPlatform: String? - ) async throws -> AnySwiftEvolutionInterfaceBuilder { - let builder = try AnySwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - imageGroups: imageGroupVersions.map { version in - version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName.name, machO: $0.machO) } - }, - labels: imageGroupVersions.map(\.label), - availabilityAnnotationPlatform: availabilityAnnotationPlatform - ) - try await measuringPreparation { - try await builder.prepare() - } - return builder - } - - /// Console analogue of `evolutionInterfaceFile(imageGroupVersions:availabilityAnnotationPlatform:)`. - func evolutionInterfaceString( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - printResult(try await annotatedInterfaceReport(of: builder)) - } - - /// Writes the annotated union interface of an evolution over groups of - /// images, named after the newest version's group - /// (`…-SwiftUI+SwiftUICore-EvolutionInterface.swiftinterface`). - func evolutionInterfaceFile( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - guard let newestVersion = imageGroupVersions.last else { return } - try await write(annotatedInterfaceReport(of: builder), forImageGroup: newestVersion.images, suffix: "EvolutionInterface") - } -} - -enum SwiftEvolutionInterfaceBuilderTestSuite { - /// AppKit across three macOS caches (15.5 → 26.5.1 → 27.0 beta 1) — the - /// same axis as `ABIEvolutionTestSuite.DyldCacheTests`' lineage dumps, so - /// the interface and the report can be inspected side by side. - final class DyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions) - } - - /// The pack-generic façade on the same three real images: the axis - /// through `SwiftEvolutionInterfaceBuilder` (compile-time arity), dumped for eyeball comparison - /// against the erased builder's output above — the two must be - /// byte-identical. - @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) - @Test func evolutionInterfaceStringViaPackFacade() async throws { - let builder = try SwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - versions: versions[0].machO, versions[1].machO, versions[2].machO, - labels: versions.map(\.label) - ) - // No `measuringPreparation` here: this @Test runs on the suite's - // @TestActor, and handing it an actor-isolated closure trips - // region-isolation checking (the extension helpers avoid this by - // being nonisolated themselves). - try await builder.prepare() - printResult(try await builder.printAnnotatedInterface().string) - } - } - - /// SwiftUICore across the same three macOS caches — the Swift-rich axis - /// (AppKit's Swift section is comparatively thin), exercising the union - /// interface over heavy generics, opaque returns, and extension blocks. - final class SwiftUICoreDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions) - } - } - - /// The same image across archived macOS caches, picked by version: list - /// in `cacheVersions` the directories under - /// `/Volumes/DyldSharedCaches/macOS` that hold a cache, oldest first. A - /// cache is labeled with its version, or with the major release - /// `versionLabelsByCacheVersion` names for it, so every label is a - /// version number and the union interface also spells each lifecycle one - /// attribute can express as `@available(macOS, …)`. A version whose image - /// carries no Swift metadata drops off the axis (see - /// `MultiVersionDyldCacheImageTests`). - final class ArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - - class var cacheVersions: [String] { [ - "11.0.1", - "11.1", - "11.2", - "11.3", - "11.4", - "11.5", - "11.6", - "11.7", - "12.0.1", - "12.1", - "12.2", - "12.3", - "12.4", - "12.5", - "12.6", - "12.7", - "13.0", - "13.1", - "13.2", - "13.3", - "13.4", - "13.5", - "13.6", - "13.7", - "14.0", - "14.1", - "14.2", - "14.3", - "14.4", - "14.5", - "14.6", - "14.7", - "14.8", - "15.0", - "15.1", - "15.2", - "15.3", - "15.4", - "15.5", - "15.6", - "15.7", - "15.8", - "26.0", - "26.1", - "26.2", - "26.3", - "26.4", - "26.5", - "26.6", - "26.7", - "27.0", - ] } - - /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and - /// 12.0.1, so those are the directories the volume has; the axis - /// still labels them 11.0 and 12.0, the versions an SDK's - /// `@available` attributes name. - class var versionLabelsByCacheVersion: [String: String] { ["11.0.1": "11.0", "12.0.1": "12.0"] } - - override class var cachePaths: [DyldSharedCachePath] { - cacheVersions.map { cacheVersion in - let cachePath = DyldSharedCachePath.macOS(cacheVersion) - guard let versionLabel = versionLabelsByCacheVersion[cacheVersion] else { return cachePath } - return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) - } - } - - override class var cacheImageName: MachOImageName { .SwiftUI } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions, availabilityAnnotationPlatform: "macOS") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions, availabilityAnnotationPlatform: "macOS") - } - } - - /// SwiftUI together with SwiftUICore across the default three caches - /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution - /// proposal `image-group-evolution`) — the axis of - /// `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`, so the - /// interface and the report can be read side by side. - final class SwiftUIImageGroupDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache (`ArchivedDyldCacheTests`' - /// axis): SwiftUI alone until 14.8, SwiftUICore joining it in 15.0. Every - /// label is a version number, so the interface also spells each - /// lifecycle one attribute can express as `@available(macOS, …)`. - final class SwiftUIImageGroupArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, nonisolated SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: "macOS") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: "macOS") - } - } -} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift index fa6c8ac2..063bf267 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift @@ -54,27 +54,12 @@ extension SwiftInterfaceDumpTests { try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) } - /// `write(_:for:suffix:fileExtension:)` for a version made up of a group - /// of images (evolution proposal `image-group-evolution`): named after - /// the primary image's build version and every image of the group, - /// joined by `+` (`…-SwiftUI+SwiftUICore-Evolution.txt`). - func write( - _ string: String, - forImageGroup images: [(imageName: MachOImageName, machO: MachOFile)], - suffix: String, - fileExtension: String = "swiftinterface" - ) throws { - guard let primaryImage = images.first else { return } - try rootDirectory.createDirectoryIfNeeded() - let imageGroupName = images.map { $0.machO.imagePath.lastPathComponent }.joined(separator: "+") - let fileName = "\(primaryImage.machO.loadCommands.buildVersionCommand!)-\(imageGroupName)-\(suffix).\(fileExtension)" - try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) - } - /// `write(_:for:suffix:fileExtension:)` for one version of an evolution - /// axis: named after the primary image's build version and every image - /// of the version, joined by `+` (`…-SwiftUI+SwiftUICore-Evolution.txt`). - /// A version of one image gets the name `write(_:for:…)` gives it. + /// axis, which may be a group of images (evolution proposal + /// `image-group-evolution`): named after the primary image's build + /// version and every image of the version, joined by `+` + /// (`…-SwiftUI+SwiftUICore-Evolution.txt`). A version of one image gets + /// the name `write(_:for:…)` gives it. func write( _ string: String, forImageGroup images: [EvolutionImage], From 74ee5726c5b9cf880081d1e8b5337c997b3bf74b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 11:45:10 +0800 Subject: [PATCH 124/175] docs: record the evolution suite merge in the ledger and the proposal --- .../draft-unify-evolution-integration-suites.md | 7 +++++-- Documentations/Internal/ProjectEvolutionLog.md | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-unify-evolution-integration-suites.md b/Documentations/Evolutions/draft-unify-evolution-integration-suites.md index 4a5cd583..6672f5ca 100644 --- a/Documentations/Evolutions/draft-unify-evolution-integration-suites.md +++ b/Documentations/Evolutions/draft-unify-evolution-integration-suites.md @@ -461,12 +461,12 @@ enum EvolutionTestSuite { - 行为:`reportWritesTextAndJSONNamedAfterTheNewestVersionsImages` - 行为:`interfaceSpellsAvailabilityInItsOwnLanguagesSpelling` - 本步只编译,测试目标能编过即可。 -2. **十个轴套件取代旧文件** —— `EvolutionTests.swift`;删除三个旧文件与随之变空的 `SwiftDiffing/`、`ObjCDiffing/` 目录;删除 `write(_:forImageGroup:)` 收元组的旧重载。 +2. **十个轴套件取代旧文件**(已完成,Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过,新文件没有警告)—— `EvolutionTests.swift`;删除三个旧文件与随之变空的 `SwiftDiffing/`、`ObjCDiffing/` 目录;删除 `write(_:forImageGroup:)` 收元组的旧重载。 - 行为:`everyAxisPipelinePairOfTheOldSuitesHasOneTestNow`(43 个,逐一对照「提议方案」的表) - 行为:`noSuiteReadsAnotherSuitesClassProperties` - 行为:`archivedAxesTakeTheCacheListFromTheBaseClass` - 两个 Xcode 版本各编一遍。 -3. **文档** —— `ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 +3. **文档**(已完成;维护者比对待做)—— `ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 - 维护者比对:挑 `SwiftUIImageGroupDyldCacheTests`(四种输出都有、只开三份 cache)前后各跑一次 file 测试,`diff` 两次的输出(JSON 忽略 `createdAt`)。结果记进决策日志。 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -481,3 +481,6 @@ enum EvolutionTestSuite { | 2026-11-26 | Created as Draft | 用户要求把 IntegrationTests 里重复的演进测试抽出来,Swift 与 ObjC 各有一套套件,统一成一套。澄清一轮:范围只做演进(不顺带合并 diff 基类与 MachOSymbols 的重复);每种输出保留一对显式测试,不用参数化测试;按规则写轻量档提案。 | | 2026-11-26 | Accepted | 用户看过简报后批准,开始实现。 | | 2026-11-26 | In Progress:第 1 步开工 | 功能分支从本地 `next` 切出,按 `create-worktree` 的基线规则。本地 `next` 上还有一次未推送、待用户验收的合并(C 导入类型拼写),因此推送功能分支时它作为祖先一并上了远端功能分支,`next` 本身未推送。`MultiVersionDyldCacheImageTests` 用两个 `let`(`swiftAxis`、`objcAxis`)加 `switch` 存两条轴,不用字典加强制解包(详细设计里留的退路)。 | +| 2026-11-26 | 第 2、3 步完成 | 十个轴套件取代旧的三个文件;`SwiftDiffing/` 也随之变空、删除(改动地图原先只写了 `ObjCDiffing/`)。`ABIEvolutionDesign.md` 的集成套件一段改成新路径与套件名,账本追加一节。只编译、没运行 IntegrationTests。 | +| 2026-11-26 | 收尾判断 | 不配使用指南或实现说明:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。没有新术语:「版本轴」是描述性说法,已在多份提案里直接使用,不登记术语表。 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 功能分支已推送,并在本地以 `--no-ff` 合进 `.worktrees/MachOSwiftSection` 的 `next`(不推送)。改前改后的输出比对由维护者做。 | diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 7c152f40..525cd8dd 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3621,6 +3621,20 @@ - **验证**:Ultra(Xcode 26.6)全量 `swift test --skip IntegrationTests` 2997 个测试,只有已知的负载偶发 `BoundedConcurrentMapTests` 一条超时,单独重跑全过;每步的行为测试先红后绿。macOS 27.2 的 AttributeGraph 前后对照 `__C` 从 73 处降到 60 处;SwiftUICore 打开展开字段偏移的 interface 慢 4%(7.10 → 7.39 秒),进程内缓存多占约 2.1 MB([ReviewAdjudications](ReviewAdjudications.md) A91)。 - **对应版本**:未发布。 +## 2026-11-26 IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 + +- **时间段**:2026-11-26,本仓库的 `feature/unify-evolution-integration-suites`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译。 +- **动机**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自把同几条版本轴再定义一遍:SwiftUI 加 SwiftUICore 的两条轴各写了四次,51 份归档 cache 的清单挂在 Swift 接口套件上、别的套件去借它的类属性,ObjC 侧为了把 `__swift5_*` 换成 `__objc_*` 多出一层基类;四条管线又各把单镜像与镜像组写两遍。两个 Swift 侧 `DyldCacheTests` 的注释写着读 AppKit,实际读的是 SwiftUI。 +- **关键决策**: + - 一个套件实例为 Swift 与 ObjC 各存一条轴,按镜像带不带该语言的元数据筛版本,主镜像不带的版本不上这条轴。 + - 单镜像与镜像组仍走构建器的两个入口(`comparesImageGroups`):镜像组入口给版本描述写镜像名、不带 provenance,一律走它会改变输出。 + - 每种输出保留一对显式的一行测试,不用参数化测试:51 版归档轴一点就跑全部管线要几个小时。 + - 默认三版本轴上 Swift 一侧沿用实际读的 SwiftUI、ObjC 一侧沿用 AppKit,拆成两个套件,改正过时的注释。原有 43 个「轴 × 输出」组合与输出文件名不变,只改测试名。 +- **落地模块**:`Tests/IntegrationTests/Evolution/`(`EvolutionAxis.swift`、`EvolutionDumpTests.swift`、`EvolutionTests.swift`)与 `SwiftInterfaceTestSupport.swift` 的 `write(_:forImageGroup:)`;删去 `SwiftDiffing/ABIEvolutionTests.swift`、`SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift`、`ObjCDiffing/ObjCAPIEvolutionTests.swift`。 +- **文档**:提案 [draft-unify-evolution-integration-suites](../Evolutions/draft-unify-evolution-integration-suites.md);[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段。没有新术语,不另写使用指南或实现说明。 +- **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过。改前改后的输出是否逐字一致,待维护者挑一条轴比对。 +- **对应版本**:未发布(只改测试目标)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 From 6330ef31d81c830f71569a9f14c8fc76867fa236 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 12:11:46 +0800 Subject: [PATCH 125/175] docs: land consistent C-imported type spelling as proposal 0109 and the evolution suite merge as 0110 --- ...-consistent-c-imported-type-spelling.html} | 13 +++++----- ...09-consistent-c-imported-type-spelling.md} | 5 ++-- ...0-unify-evolution-integration-suites.html} | 26 ++++++++++++------- ...110-unify-evolution-integration-suites.md} | 9 ++++--- Documentations/Evolutions/README.md | 4 +-- Documentations/Glossary.md | 2 +- Documentations/Internal/ABIEvolutionDesign.md | 2 +- ...FieldLayoutRendererReaderSpecialization.md | 2 +- .../Internal/Modules/SwiftLayout.md | 2 +- .../Internal/ProjectEvolutionLog.md | 8 +++--- Documentations/README.md | 3 ++- 11 files changed, 43 insertions(+), 33 deletions(-) rename Documentations/Evolutions/{draft-consistent-c-imported-type-spelling.html => 0109-consistent-c-imported-type-spelling.html} (97%) rename Documentations/Evolutions/{draft-consistent-c-imported-type-spelling.md => 0109-consistent-c-imported-type-spelling.md} (99%) rename Documentations/Evolutions/{draft-unify-evolution-integration-suites.html => 0110-unify-evolution-integration-suites.html} (93%) rename Documentations/Evolutions/{draft-unify-evolution-integration-suites.md => 0110-unify-evolution-integration-suites.md} (98%) diff --git a/Documentations/Evolutions/draft-consistent-c-imported-type-spelling.html b/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.html similarity index 97% rename from Documentations/Evolutions/draft-consistent-c-imported-type-spelling.html rename to Documentations/Evolutions/0109-consistent-c-imported-type-spelling.html index 32e5a32d..b656bc62 100644 --- a/Documentations/Evolutions/draft-consistent-c-imported-type-spelling.html +++ b/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.html @@ -4,7 +4,7 @@ -Draft - C 导入类型的拼写补齐:同名类型去掉 __C,布局注释跟着打印器的拼写 +0109 - C 导入类型的拼写补齐:同名类型去掉 __C,布局注释跟着打印器的拼写 + + + +
      + +
      +

      MachOSwiftSectionEvolutionsDraft

      +

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

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

      摘要

      +

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

      +

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

      +

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

      +
      + +
      +

      要你定

      +
      +

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

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

      架构图

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

      改了什么:文件与类型

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

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

      + +

      协议与基类

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

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

      + +

      一个 diff 测试的调用链

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

      改动地图

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

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

      +
      + +
      +

      提议方案

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

      采用的假设

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

      非目标

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

      详细设计

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

      动机

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

      调研

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

      替代方案

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

      影响

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

      落地步骤

      +

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

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

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

      +
      + +
      +

      决策日志

      +
      + 2 条,最近一条:Accepted +
      +
      + + + + + + +
      日期变更说明
      2026-11-26Created as Draft0110 合并演进套件后,用户要求把 diff 与单版本接口两类手检套件也按同样的结构统一。澄清一轮:两类都加上 ObjC 输出;diff 改用演进套件的版本轴(cache 对因此整份打开,与 CLI 一致);维护者未提交的接口套件实验不碰,照提交版重构,由维护者自己收掉。
      2026-11-26Accepted用户看过简报后批准,开始实现。
      +
      +
      +
      +
      + +
      +
      + + diff --git a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md b/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md new file mode 100644 index 00000000..85143968 --- /dev/null +++ b/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md @@ -0,0 +1,438 @@ +# Draft - IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-26 +- **最后更新**: 2026-11-26 +- **所属愿景**: 无 +- **关联提案**: [0110-unify-evolution-integration-suites](0110-unify-evolution-integration-suites.md)(演进套件的合并;本提案把同样的结构推到 diff 与单版本接口,并让 diff 与演进共用它的版本轴);[0061-dyld-shared-cache-path-versions](0061-dyld-shared-cache-path-versions.md)(按版本号取归档 cache、`versionLabel`) +- **实现分支 / PR**: `feature/unify-diff-and-interface-integration-suites`(worktree `.worktrees/MachOSwiftSection-UnifyDiffAndInterfaceIntegrationSuites`) +- **配套文档**: 无 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +`Tests/IntegrationTests/` 里维护者手检的输出有三类:单版本接口(`SwiftInterfaceBuilderTests.swift`)、两版本 diff(`SwiftDiffableInterfaceBuilderTests.swift`)、N 版本演进(`Evolution/`,0110 刚合并过)。演进那一类已经是「一个套件声明一次镜像、`dump(.kind, to: .file / .console)` 一行一个测试、Swift 与 ObjC 都出」;另两类还是各写各的:diff 自带三个「新旧两版」基类,读 cache 只开主文件,和演进套件、CLI 都不一样;接口套件为了多开一个选项把整份配置抄一遍;两类都只出 Swift。 + +本提案把三类放进同一个目录 `Tests/IntegrationTests/InspectionDumps/`,共用一套骨架: + +- **一个公共协议 `InspectionDumpTests`**(原 `SwiftInterfaceDumpTests`):输出目录、计时、打印、写文件,以及三类共用的输出形状 `DumpOutput` / `DumpDestination`、元数据语言 `MetadataLanguage`、准备 ObjC 索引的函数。 +- **diff 与演进共用版本轴**:diff 就是只有两个版本的轴。`MultiVersionDyldCacheImageTests`(整份打开每个 cache)给 diff 的 cache 对用;模拟器文件对、Xcode 框架对的两个基类搬到顶层,也各自给出轴。原 `Evolution*` 前缀的轴类型去掉前缀(`VersionAxis`、`AxisVersion`、`AxisImage`、`AvailabilityPlatform`)。 +- **每类一个「输出种类」枚举 + 一个 `dump` 入口**:`InterfaceDumpKind`(`swiftInterface` / `objcInterface`)、`DiffDumpKind`(`swiftReport` / `swiftInterface` / `objcReport`)、`EvolutionDumpKind`(不变)。 +- **新增 ObjC 输出**:AppKit 的两个接口套件多出整镜像的 ObjC 头文件(`objc dump` 的管线),AppKit 的两个 diff 套件多出 ObjC 变更列表与 JSON(`objc diff` 的管线);Swift diff 报告也多写一份 JSON(`diff --json`)。 + +测试从 20 个(接口 10、diff 10)变成 38 个(接口 14、diff 24),演进的 43 个不变。只动 IntegrationTests 与它在 `Package.swift` 里的依赖表,不碰库代码。 + +## 动机 + +0110 合并演进套件时把 diff 与接口划在范围外。现在三类并排,差异本身就成了要维护的东西: + +1. **diff 有自己的一套「新旧两版」基类,和演进的版本轴是同一件事的两种写法**。`SwiftDiffableInterfaceBuilderTestSuite` 里的 `CrossVersionMachOFileTests`(`Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift:95`)、`CrossVersionDyldCacheImageTests`(`:113`)、`CrossVersionXcodeFrameworkTests`(`:138`)各自持有一对 `MachOFile`;演进套件 `EvolutionTestSuite.SwiftUICoreSimulatorTests` 还得借 diff 的 `CrossVersionMachOFileTests`(`Tests/IntegrationTests/Evolution/EvolutionTests.swift:326`),再自己把这一对包成 `EvolutionAxis`(`:330-339`)。 +2. **diff 读 cache 的方式和演进、CLI 都不同**。`CrossVersionDyldCacheImageTests` 用 `DyldCache(path:)` 只打开主文件(`:124-125`),从主 cache 取镜像;`MultiVersionDyldCacheImageTests` 与 `swift-section --dyld-shared-cache` 都整份打开(`FullDyldCache`,见 `Tests/IntegrationTests/Evolution/EvolutionAxis.swift:92-96` 的注释)。同一个 AppKit,在 diff 与演进两个手检输出里经两条读路径。 +3. **注释和代码对不上**。diff 的 `DyldCacheTests` 注释写「The same macOS image (SwiftUI) extracted from two dyld shared caches (macOS 15.5 → current)」(`:190-191`),实际读 AppKit,26.5.1 → 27.0(`:193-195`)。0110 在演进套件里修过同一类问题。 +4. **接口套件为一个选项抄整份配置**。`XcodeMachOFileTests` 只想开 `printExportedDeclarationsOnly`,却把 `builderConfiguration` 的十几个参数整段重写(提交版 `SwiftInterfaceBuilderTests.swift:151-173`),以后改默认配置要改两处。 +5. **接口套件用类型转换判读取器**。`buildFile` 用 `machO is MachOImage` 决定文件后缀(提交版 `:66`)。项目规则要求问 `asMachOImage`,不转具体类型(`CLAUDE.md`「you need to know whether a reader is a MachOImage or a MachOFile」一节);这里是测试代码,扫描不到,但同样会把包装类型认错。 +6. **只有演进出 ObjC**。AppKit 的 ObjC 部分远大于 Swift,维护者却只能在演进套件里看到它;看单个 cache 的 AppKit 头文件、两版之间的 ObjC 变化,得另跑 CLI。 +7. **三类的 `indexConfiguration` 各写一份**(`SwiftDiffableInterfaceBuilderTests.swift:25`、`EvolutionDumpTests.swift:82`、接口配置里的 `indexConfiguration:`),值都是 `.init(showCImportedTypes: false)`。 + +## 前期调研 + +1. **CLI 里对应的管线**(测试要复现的就是它们): + - Swift 单版本接口:`SwiftInterfaceBuilder` + `SwiftInterfaceBuilderOpaqueTypeProvider`,`prepare()` 后 `printRoot()`。现状测试照此做,打印配置开满(字段偏移、地址、vtable/PWT 偏移、布局、按偏移排序等)。 + - ObjC 整镜像头文件:`swift-section objc dump`(`Sources/Commands/SwiftSectionKit/ObjC/ObjCDumpRequest.swift`)。`ObjCInterfaceSession.make` 建 `ObjCInterfaceIndexer(machO:imagePath:suppliedClasses:)`(`suppliedClasses` 用 `ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)`)、`prepare()`,再用 `ObjCInterfaceBuilder(indexer:machO:)` 按 `classes, protocols, categories, structs, unions` 的顺序、每种名字排序后逐个取 `classInterface(named:…)` / `protocolInterface` / `categoryInterface(uniqueName:…)` / `structInterface` / `unionInterface`,写文件时每段后接一个空行。`ObjCDeclarationKind` 在 SwiftSectionKit 里,IntegrationTests 不依赖 SwiftSectionKit,测试里照这个顺序自己写五个分支。 + - Swift diff:变更列表是 `ABIDiffer().diff(old:new:)` + `ABIDiffReporter().report(_:)` + 一行 `ABI-breaking: … · backward-compatible: …`;`--json` 是 `ABIJSON.encoder().encode(diff)`;`--interface` 是 `SwiftDiffableInterfaceRenderer(old:new:).printAnnotatedInterface(format:)`(`Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift:67-150`)。现状测试的变更列表直接用两个 builder 的 `abiModule()`,不经快照文档。 + - ObjC diff:`ObjCAPIDiffRequest`(`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:56-108`)把两边各读成 `ObjCAPISnapshotDocument`,`ObjCAPIDiffer().diff(old:new:)`,变更列表 `ObjCAPIDiffReporter().report(_:)` + 一行 `API-breaking: … · backward-compatible: …`,`--json` 是 `ObjCAPIJSON.encoder().encode(diff)`。ObjC diff **没有**带标注的头文件。 +2. **用到的 ObjC 接口在锁定版本里都有**。`Package.resolved` 锁 MachOObjCSection 0.8.209;在这个 tag 上 `ObjCInterfaceBuilder` 的五个 `…Interface` 方法、`ObjCInterfaceIndexer` 的五个 `…Names`、`ObjCGenerationOptions.printExportedDeclarationsOnly` 都在,`MachOImage` 与 `MachOFile` 都遵循 `ObjCMetadataSource`。`ObjCGenerationOptions` 在 `ObjCDeclarationRendering` 这个 product 里,IntegrationTests 目前没依赖它,要在 `Package.swift` 加一行;`Tuist/Package.swift` 不逐个列 MachOObjCSection 的 product,不用改。 +3. **`swiftClassesWithoutClassObjects(in:)` 收 `some MachORepresentableWithCache`**(`Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift:26`),`ObjCInterfaceIndexer` 对 `MachO: ObjCMetadataSource` 泛型,所以准备 ObjC 索引的函数可以改成泛型,接口套件的进程内镜像也能用。 +4. **测试支撑的基类**(MachOKitExtensions 的 `MachOTestingSupport`):`DyldCacheTests` 在 `cachePath == .current` 时用 `FullDyldCache.cachedHost`,否则 `FullDyldCache(path:)`,`machOFileInCache` 取自整份 cache;`MachOFileTests`、`MachOImageTests` 是 `@MainActor`;`XcodeMachOFileTests` 没有隔离。接口套件继续用这些基类,不需要版本轴。 +5. **文件命名**:`write(_:for:…)` 与 `write(_:forImageGroup:…)` 在单镜像时逐字相同(0110 调研第 3 条),所以 diff 改用轴之后输出文件名不变。 +6. **IntegrationTests 外引用这些名字的地方**:`Documentations/Internal/ABIEvolutionDesign.md:235` 写着 `Tests/IntegrationTests/Evolution/`;账本、任务报告、已落地提案里的 `SwiftInterfaceBuilderTestSuite` 等旧名是历史记录。`Scripts/`、`Sources/`、别的测试目标都不引用。 + +## 提议方案 + +### 三类的分工 + +| 类 | 协议 | 输入 | 输出种类(CLI 对应) | 文件后缀 | +|---|---|---|---|---| +| 接口 | `InterfaceDumpTests` | 一个镜像,任意读取器(文件、cache 里的文件、进程内镜像) | `swiftInterface`(`interface`)、`objcInterface`(`objc dump`) | `-FileDump.swiftinterface` / `-ImageDump.swiftinterface`;`-ObjCFileDump.h` / `-ObjCImageDump.h` | +| diff | `DiffDumpTests` | 版本轴的第一个与最后一个版本(主镜像) | `swiftReport`(`diff` + `diff --json`)、`swiftInterface`(`diff --interface`,inline 与 unified)、`objcReport`(`objc diff` + `--json`) | `-Diff.txt` / `.json`;`-AnnotatedInterface-Inline` / `-Unified.swiftinterface`;`-ObjCDiff.txt` / `.json` | +| 演进 | `EvolutionDumpTests` | 整条版本轴 | 不变 | 不变 | + +diff 与演进都是 `VersionAxisDumpTests`(要求 `versionAxis(for:)`),都由三个轴基类之一供轴: + +| 轴基类 | 版本来自 | 谁用 | +|---|---|---| +| `MultiVersionDyldCacheImageTests` | `cachePaths` 列出的 cache,整份打开 | 演进的九个 cache 套件;diff 的两个 AppKit 套件 | +| `CrossVersionMachOFileTests` | 两个模拟器运行时里的同一个文件 | 演进的 `SwiftUICoreSimulatorTests`;diff 的 `SwiftUICoreTests`、`SwiftUITests` | +| `CrossVersionXcodeFrameworkTests` | 两个已安装的 Xcode 里同一个共享框架 | diff 的 `XcodeFrameworkTests` | + +### 套件与测试 + +套件类名保留现状(接口与 diff 的套件是「指向任意镜像」的探针,维护者常临时改读别的镜像,按来源命名比按镜像命名更不易过时);外层的枚举改名,测试函数改成「种类 + 去向」: + +| 套件 | 读什么 | 测试 | +|---|---|---| +| `InterfaceTestSuite.DyldCacheTests` | 本机 cache 的 AppKit | `swiftInterfaceFile/String`、`objcInterfaceFile/String` | +| `InterfaceTestSuite.ArchivedDyldCacheTests` | 归档 26.6 cache 的 AppKit | 同上 4 个 | +| `InterfaceTestSuite.MachOFileTests` | SymbolTestsCore fixture | `swiftInterfaceFile/String` | +| `InterfaceTestSuite.MachOImageTests` | 进程内 SwiftUICore | `swiftInterfaceFile/String` | +| `InterfaceTestSuite.XcodeMachOFileTests` | Xcode 的 SourceEditor,只印导出声明 | `swiftInterfaceFile/String` | +| `DiffTestSuite.SwiftUICoreTests` | 模拟器 18.5 → 26.5 的 SwiftUICore | `swiftReportFile/String`、`swiftInterfaceFile/String` | +| `DiffTestSuite.SwiftUITests` | 模拟器 18.5 → 26.5 的 SwiftUI | 同上 4 个 | +| `DiffTestSuite.DyldCacheTests` | cache 26.5.1 → 27.0 的 AppKit | 同上 4 个 + `objcReportFile/String` | +| `DiffTestSuite.ArchivedDyldCacheTests` | 归档 cache 26.6 → 27.0 的 AppKit | 同上 6 个 | +| `DiffTestSuite.XcodeFrameworkTests` | Xcode 26.3.0 → 26.4.0 的 DVTProductsUI | `swiftReportFile/String`、`swiftInterfaceFile/String` | + +ObjC 输出只加在 AppKit 套件上(ObjC 是 AppKit 的大头;别的套件要看 ObjC,加一对一行测试即可)。 + +### 采用的假设 + +- **diff 的 cache 对改为整份打开**(用户在澄清时选定)。输出可能与现状有出入,以与 CLI 一致为准。 +- **ObjC 头文件开满注释**:ivar 偏移、属性特性、方法 IMP 地址、访问器地址四种注释都开。Swift 接口这边本来就开满了字段偏移与成员地址,手检输出以信息最多为目标。 +- **Swift diff 报告多写一份 `-Diff.json`**,与演进报告、ObjC diff 报告对齐;变更列表照旧用两个 builder 的 `abiModule()`,不改成快照文档往返(不改变现有输出)。 +- **diff 比较轴上第一个与最后一个版本的主镜像**。diff 套件只声明两个版本、一个镜像;轴筛掉版本后不足两个时,打印一行说明、不写文件(与演进轴为空时直接返回一致,IntegrationTests 不设断言)。 +- **控制台只打印一份**:diff 的 `swiftInterface` 写文件时出 inline 与 unified 两份,打到控制台只出 inline(现状 `diffString` 也只印 inline);为此这条管线按去向决定要不要渲染 unified,省一次完整渲染。 +- **Xcode 对按版本号取**:`CrossVersionXcodeFrameworkTests` 的类属性从 `oldXcodeApplicationPath` / `newXcodeApplicationPath` 改为 `oldXcodeVersion` / `newXcodeVersion`(`"26.3.0"` / `"26.4.0"`),路径拼成 `/Applications/Xcode-<版本>.app`,版本号也当轴标签,与归档 cache 按版本号取一致。 +- **旧测试名直接删除,不留别名**:IntegrationTests 没有调用方,测试名只在维护者手动运行时用到。 +- **维护者在公司那台 `next` 检出里未提交的 `SwiftInterfaceBuilderTests.swift` 实验不碰**(用户在澄清时选定):本提案照提交版重构;合回那个检出前,由维护者自己提交或丢弃那份实验,否则合并会被它挡住。实验里的「改读 AttributeGraph」在新结构里是给 `InterfaceTestSuite.DyldCacheTests` 改 `cacheImageName`。 + +### 非目标 + +- 不动 `SwiftDump/` 的 `DumpableTests` 一族(`dump` 子命令的手检,结构另成一套)。 +- 不动 `RenderingVerificationTests`(渲染 A/B 验证的 MachOImage 腿,有自己的约定)与 `SwiftInterfaceIndexerTests`。 +- 不给 diff 加镜像组:`ABIDiffer` 与 `ObjCAPIDiffer` 没有镜像组入口。 +- 不改库代码、不改 CLI。 + +## 改动地图 + +| 文件 · 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Tests/IntegrationTests/InspectionDumps/` | 新增目录 | 三类手检输出的家 | 三类共用骨架,放一处 | 1 | +| `InspectionDumps/InspectionDumpTests.swift`(`git mv` 自 `SwiftInterface/SwiftInterfaceTestSupport.swift`) | 移动 + 修改 | 协议改名 `InspectionDumpTests`;加 `indexConfiguration`、`MetadataLanguage`(自 `EvolutionMetadataLanguage`)、`DumpDestination`、`DumpFile`、`DumpOutput`、`deliver(_:to:writingFile:)`、泛型的 `preparedObjCIndexer(of:)`;`write(_:forImageGroup:)` 收 `[AxisImage]` | 三类共用的部分只写一次 | 1 | +| `InspectionDumps/VersionAxis.swift`(`git mv` 自 `Evolution/EvolutionAxis.swift`) | 移动 + 修改 | 去掉 `Evolution` 前缀:`AvailabilityPlatform`、`AxisImage`、`AxisVersion`、`VersionAxis`;新增 `VersionAxes`(两种语言各一条轴)与协议 `VersionAxisDumpTests`(含共享的 `objcSnapshotDocument(of:label:)`);`MultiVersionDyldCacheImageTests` 改存 `VersionAxes`;`CrossVersionMachOFileTests`、`CrossVersionXcodeFrameworkTests` 从 diff 文件搬来,加版本标签与轴 | diff 与演进共用版本轴 | 1 | +| `InspectionDumps/EvolutionDumpTests.swift`(`git mv` 自 `Evolution/`) | 移动 + 修改 | 改继承 `VersionAxisDumpTests`;`EvolutionDumpOutput` 换成 `DumpOutput`;`evolutionAxis(for:)` 改名 `versionAxis(for:)`;删自己的 `indexConfiguration`、`preparedObjCIndexer`、`objcSnapshotDocument` | 共用骨架 | 1 | +| `InspectionDumps/EvolutionTests.swift`(`git mv` 自 `Evolution/`) | 移动 + 修改 | 换新类型名;`SwiftUICoreSimulatorTests` 改继承顶层 `CrossVersionMachOFileTests`,删掉自己拼轴的那段 | 轴由基类给 | 1 | +| `SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift` | 修改(第 1 步)→ 删除(第 3 步) | 第 1 步只把协议名改成 `InspectionDumpTests`、删自己的 `indexConfiguration`,保证能编 | 分步可编 | 1、3 | +| `SwiftInterface/SwiftInterfaceBuilderTests.swift` | 修改(第 1 步)→ 删除(第 2 步) | 第 1 步只改协议名 | 分步可编 | 1、2 | +| `InspectionDumps/InterfaceDumpTests.swift` | 新增 | `InterfaceDumpKind`;协议 `InterfaceDumpTests`(`printsExportedDeclarationsOnly`);`builderConfiguration`、`objcGenerationOptions`;`dump(_:of:to:)` 与两条管线 | 接口一类的管线 | 2 | +| `InspectionDumps/InterfaceTests.swift` | 新增 | `enum InterfaceTestSuite`,五个套件、14 个测试 | 取代旧接口套件 | 2 | +| `InspectionDumps/DiffDumpTests.swift` | 新增 | `DiffDumpKind`;协议 `DiffDumpTests: VersionAxisDumpTests`;`dump(_:to:)` 与三条管线 | diff 一类的管线 | 3 | +| `InspectionDumps/DiffTests.swift` | 新增 | `enum DiffTestSuite`,五个套件、24 个测试 | 取代旧 diff 套件 | 3 | +| `Tests/IntegrationTests/Evolution/` | 删除(目录) | 三个文件移走后为空 | — | 1 | +| `Package.swift` · `IntegrationTests` 目标 | 修改 | 加 `.product(name: "ObjCDeclarationRendering", package: "MachOObjCSection")`;注释从「ObjC API evolution dumps」改为三类 ObjC 输出 | `ObjCGenerationOptions` 在这个 product 里 | 2 | +| `Documentations/Internal/ABIEvolutionDesign.md:235` | 修改 | 目录改 `Tests/IntegrationTests/InspectionDumps/` | 路径变了 | 4 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 追加一节 | 账本 | 4 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案 | 索引 | 起草时 / 4 | + +## 架构图 + +改了什么(文件与类型): + +``` +Tests/IntegrationTests/ +- SwiftInterface/SwiftInterfaceTestSupport.swift protocol SwiftInterfaceDumpTests +- SwiftInterface/SwiftInterfaceBuilderTests.swift protocol SwiftInterfaceBuilderTests + enum SwiftInterfaceBuilderTestSuite (5) +- SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +- protocol SwiftDiffableInterfaceBuilderTests +- enum SwiftDiffableInterfaceBuilderTestSuite +- CrossVersionMachOFileTests / CrossVersionDyldCacheImageTests (DyldCache, main file only) / CrossVersionXcodeFrameworkTests +- 5 suites +- Evolution/EvolutionAxis.swift / EvolutionDumpTests.swift / EvolutionTests.swift + SwiftInterface/SwiftInterfaceIndexerTests.swift, RenderingVerificationTests.swift (unchanged) ++ InspectionDumps/ ++ InspectionDumpTests.swift protocol InspectionDumpTests ++ MetadataLanguage, DumpDestination, DumpFile, DumpOutput, preparedObjCIndexer(of:) ++ VersionAxis.swift AvailabilityPlatform, AxisImage, AxisVersion, VersionAxis, VersionAxes ++ protocol VersionAxisDumpTests: InspectionDumpTests ++ MultiVersionDyldCacheImageTests (FullDyldCache) ++ CrossVersionMachOFileTests, CrossVersionXcodeFrameworkTests ++ InterfaceDumpTests.swift InterfaceDumpKind { swiftInterface, objcInterface } ++ protocol InterfaceDumpTests: InspectionDumpTests ++ InterfaceTests.swift enum InterfaceTestSuite (5 suites, 14 tests) ++ DiffDumpTests.swift DiffDumpKind { swiftReport, swiftInterface, objcReport } ++ protocol DiffDumpTests: VersionAxisDumpTests ++ DiffTests.swift enum DiffTestSuite (5 suites, 24 tests) +~ EvolutionDumpTests.swift protocol EvolutionDumpTests: VersionAxisDumpTests +~ EvolutionTests.swift enum EvolutionTestSuite (10 suites, 43 tests) +``` + +协议与基类的关系: + +``` +InspectionDumpTests (rootDirectory, indexConfiguration, measuringPreparation, printResult, write, deliver) +├── InterfaceDumpTests dump(_: InterfaceDumpKind, of: machO, to:) +│ suites inherit MachOTestingSupport bases: DyldCacheTests / MachOFileTests / MachOImageTests / XcodeMachOFileTests +└── VersionAxisDumpTests versionAxis(for: MetadataLanguage) -> VersionAxis + ├── DiffDumpTests dump(_: DiffDumpKind, to:) reads versions.first / versions.last + └── EvolutionDumpTests dump(_: EvolutionDumpKind, to:) reads every version + axis providers: MultiVersionDyldCacheImageTests | CrossVersionMachOFileTests | CrossVersionXcodeFrameworkTests + each stores VersionAxes (swift axis, objc axis) built in init +``` + +一个 diff 测试的调用链: + +``` +DiffTestSuite.DyldCacheTests.objcReportFile() + └─ dump(.objcReport, to: .file) DiffDumpTests + ├─ versionAxis(for: .objc) MultiVersionDyldCacheImageTests (26.5.1, 27.0 / AppKit) + ├─ old = versions.first, new = versions.last + ├─ objcReport(old:new:) + │ ├─ measuringPreparation { objcSnapshotDocument(of: old.primaryImage) ; … new … } + │ │ └─ preparedObjCIndexer(of:) → ObjCAPISnapshotBuilder.snapshot() → JSON round trip + │ ├─ ObjCAPIDiffer().diff(old:new:) + │ └─ DumpOutput(console: report, files: [ObjCDiff.txt, ObjCDiff.json]) + └─ deliver(output, to: .file) → write(_:forImageGroup: new.images, …) +``` + +## 详细设计 + +### `InspectionDumpTests.swift` + +```swift +/// Shared scaffolding for the maintainer-inspection dumps: the single-version +/// interfaces, the two-version diffs and the N-version evolutions. +protocol InspectionDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InspectionDumpTests { + var rootDirectory: URL // unchanged: Documents/SwiftInterfaceTests + var indexConfiguration: SwiftDeclarationIndexConfiguration { .init(showCImportedTypes: false) } + func measuringPreparation(_ prepare: () async throws -> Void) async rethrows // unchanged + func printResult(_ string: String) // unchanged + func write(_:for:suffix:fileExtension:) throws // unchanged + func write(_:forImageGroup images: [AxisImage], suffix:fileExtension:) throws + + /// Prints the console text, or writes every file through `writeFile`. + func deliver(_ output: DumpOutput, to destination: DumpDestination, writingFile writeFile: (DumpFile) throws -> Void) rethrows +} + +enum MetadataLanguage: Sendable { case swift, objc; func isCarried(by machOFile: MachOFile) -> Bool } +enum DumpDestination: Sendable { case console, file } + +/// One file a dump writes: named `--.`. +struct DumpFile: Sendable { let suffix: String; let fileExtension: String; let text: String } + +/// What one pipeline produced: what the console destination prints, and +/// what the file destination writes. +struct DumpOutput: Sendable { let consoleText: String; let files: [DumpFile] } + +/// One image indexed the way the `objc` subcommands index it. +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +func preparedObjCIndexer(of machO: MachO) async throws -> ObjCInterfaceIndexer +``` + +`BuildVersionCommand` 与 `Platform.stringValue` 的扩展原样搬来。`deliver` 让三类各自决定文件名怎么起:接口按 `write(_:for: machO…)`,diff 与演进按 `write(_:forImageGroup: newest.images…)`。 + +### `VersionAxis.swift` + +`AvailabilityPlatform`、`AxisImage`、`AxisVersion`(含 `keepingImages(carrying:)`)、`VersionAxis` 只改名,语义不变。新增: + +```swift +/// One axis per metadata language, each keeping the versions whose primary +/// image carries that language's metadata. Built once at initialization: +/// the class properties it derives from are isolated to the test actor, +/// the pipelines are not. +struct VersionAxes: Sendable { + init(versions: [AxisVersion], comparesImageGroups: Bool, availabilityPlatform: AvailabilityPlatform?) + func axis(for language: MetadataLanguage) -> VersionAxis +} + +/// A dump over an ordered series of versions: a diff reads its first and +/// last version, an evolution every version. +protocol VersionAxisDumpTests: InspectionDumpTests { + func versionAxis(for language: MetadataLanguage) -> VersionAxis +} + +extension VersionAxisDumpTests { + /// moved from EvolutionDumpTests (was private); the diff's ObjC report uses it too + func objcSnapshotDocument(of image: AxisImage, label: String) async throws -> ObjCAPISnapshotDocument +} +``` + +`VersionAxes` 存成两个 `let`(`swiftAxis`、`objcAxis`)加 `switch`,与 0110 落地时的写法一致。三个轴基类都 `@TestActor`,都存一个 `let axes: VersionAxes`,都实现 `nonisolated func versionAxis(for:) -> VersionAxis { axes.axis(for: language) }`: + +- `MultiVersionDyldCacheImageTests`:类属性(`cachePaths`、`cacheImageName`、`cacheImageNames`、`availabilityPlatform`、`defaultMacOSCachePaths`、`archivedMacOSCachePaths` 与 51 个版本)与 `init` 的取镜像逻辑原样保留,最后一步改成 `self.axes = VersionAxes(versions:comparesImageGroups:availabilityPlatform:)`。文档注释里指向 diff 基类的那句改掉。 +- `CrossVersionMachOFileTests`:保留 `oldMachOFile` / `newMachOFile`、`oldFileName` / `newFileName`(默认 SwiftUICore 18.5 / 26.5);新增 `oldVersionLabel` / `newVersionLabel`(默认 `"18.5"` / `"26.5"`)。轴的镜像名取 `machOFile.imagePath.lastPathComponent`(单镜像轴的管线不读这个名字,演进输出不变)。`comparesImageGroups: false`、`availabilityPlatform: nil`。 +- `CrossVersionXcodeFrameworkTests`:`oldXcodeVersion` / `newXcodeVersion`(`"26.3.0"` / `"26.4.0"`)、`sharedFrameworkName`(`"DVTProductsUI"`);路径 `/Applications/Xcode-<版本>.app/Contents/SharedFrameworks/<名>.framework/Versions/A/<名>`;轴标签就是版本号。 + +### `InterfaceDumpTests.swift` + +```swift +/// The two single-version outputs, each the pipeline of one subcommand. +enum InterfaceDumpKind: Sendable { + /// `swift-section interface`: `-FileDump.swiftinterface` / `-ImageDump.swiftinterface`. + case swiftInterface + /// `swift-section objc dump`: every Objective-C declaration of the image, + /// `-ObjCFileDump.h` / `-ObjCImageDump.h`. + case objcInterface +} + +protocol InterfaceDumpTests: InspectionDumpTests { + /// Whether both interfaces print only what the image exports — what + /// `interface --exported-only` and `objc dump --exported-only` do. + var printsExportedDeclarationsOnly: Bool { get } +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InterfaceDumpTests { + var printsExportedDeclarationsOnly: Bool { false } + var builderConfiguration: SwiftInterfaceBuilderConfiguration // today's configuration + printExportedDeclarationsOnly: printsExportedDeclarationsOnly + var objcGenerationOptions: ObjCGenerationOptions // .default + the four comment options + printExportedDeclarationsOnly + + func dump( + _ kind: InterfaceDumpKind, of machO: MachO, to destination: DumpDestination + ) async throws +} +``` + +- 读取器后缀:`machO.asMachOImage != nil ? "ImageDump" : "FileDump"`,ObjC 加前缀 `ObjC`。 +- `swiftInterface`:`SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO)` + `addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO:))`,`measuringPreparation { prepare() }`,`printRoot().string`。与现状逐字相同。 +- `objcInterface`:`measuringPreparation` 里 `preparedObjCIndexer(of: machO)`;`ObjCInterfaceBuilder(indexer:machO:)`;按 classes、protocols、categories、structs、unions 的顺序,名字排序,逐个取接口(类别用 `categoryInterface(uniqueName:)`),每段后接 `"\n\n"`,与 `objc dump --file` 的拼法一致。 +- 套件若要改 `printsExportedDeclarationsOnly`,在 `@MainActor` 的基类上要写 `nonisolated var`;`XcodeMachOFileTests` 的基类不隔离,直接写 `var`。 + +### `DiffDumpTests.swift` + +```swift +enum DiffDumpKind: Sendable { + /// `swift-section diff` and `diff --json`: `-Diff.txt` / `-Diff.json`. + case swiftReport + /// `swift-section diff --interface`: `-AnnotatedInterface-Inline.swiftinterface` + /// and `-AnnotatedInterface-Unified.swiftinterface`; the console prints the inline one. + case swiftInterface + /// `swift-section objc diff` and `objc diff --json`: `-ObjCDiff.txt` / `-ObjCDiff.json`. + case objcReport + var language: MetadataLanguage +} + +protocol DiffDumpTests: VersionAxisDumpTests {} + +extension DiffDumpTests { + func dump(_ kind: DiffDumpKind, to destination: DumpDestination) async throws { + let axis = versionAxis(for: kind.language) + guard axis.versions.count >= 2, let oldVersion = axis.versions.first, let newVersion = axis.versions.last else { + printResult("No diff: \(axis.versions.count) version(s) carry \(kind.language) metadata") + return + } + let output: DumpOutput = switch kind { … } + try deliver(output, to: destination) { file in + try write(file.text, forImageGroup: newVersion.images, suffix: file.suffix, fileExtension: file.fileExtension) + } + } +} +``` + +- `swiftReport`:两个 `SwiftDiffableInterfaceBuilder` 在一个 `measuringPreparation` 里各 `prepare()`(与现状同);`ABIDiffer().diff(old: abiModule(), new: abiModule())`;正文 = 报告 + `\n\n` + 结论行;JSON = `ABIJSON.encoder().encode(diff)`。 +- `swiftInterface`:同样准备两个 builder;inline 必出,unified(`.unified()`,与现状相同的默认标签)只在去向是文件时渲染。 +- `objcReport`:两边 `objcSnapshotDocument(of: version.primaryImage, label: version.label)`,`ObjCAPIDiffer().diff(old:new:)`,正文 = `ObjCAPIDiffReporter().report(diff)` + 结论行(`API-breaking: … · backward-compatible: …`,与 CLI 同),JSON = `ObjCAPIJSON.encoder().encode(diff)`。 + +### 套件的样子 + +```swift +enum DiffTestSuite { + /// AppKit extracted from two dyld shared caches (macOS 26.5.1 → 27.0), each + /// opened whole the way `swift-section --dyld-shared-cache` opens it. + final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { [.macOS_26_5_1, .macOS_27_0] } + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + // swiftReportString, swiftInterfaceFile/String, objcReportFile/String: the same shape + } +} + +enum InterfaceTestSuite { + class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, InterfaceDumpTests { + override class var fileName: XcodeMachOFileName { .sharedFrameworks(.SourceEditor) } + var printsExportedDeclarationsOnly: Bool { true } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFile, to: .file) + } + // swiftInterfaceString: the same shape + } +} +``` + +### 与现状的行为差异 + +| 方面 | 现状 | 之后 | +|---|---|---| +| diff 的 cache 对 | `DyldCache(path:)` 只开主文件,从主 cache 取镜像 | `FullDyldCache(path:)` 整份打开,与演进、CLI 一致;输出可能有出入 | +| diff 的输出 | `diffFile` 写三个文件;`diffString` 印变更列表与 inline | `swiftReport` 写 `-Diff.txt` 与新增的 `-Diff.json`,印变更列表;`swiftInterface` 写 inline 与 unified,印 inline | +| 新增 ObjC 输出 | 无 | AppKit 接口套件:`-ObjCFileDump.h`;AppKit diff 套件:`-ObjCDiff.txt` / `.json` | +| 接口的文件名 | `-FileDump` / `-ImageDump`,按 `is MachOImage` | 文件名不变,按 `asMachOImage` | +| Xcode diff 的类属性 | 两个 `.app` 路径 | 两个版本号 | +| 测试标识 | `SwiftInterfaceBuilderTestSuite.*/buildFile()` 等、`SwiftDiffableInterfaceBuilderTestSuite.*/diffFile()` 等 | `InterfaceTestSuite.*/swiftInterfaceFile()` 等、`DiffTestSuite.*/swiftReportFile()` 等;演进的不变 | +| 演进 | — | 输出与测试标识都不变;只换类型名与目录 | + +## 替代方案考量 + +1. **单版本接口也走版本轴(一个版本的轴)**:放弃。接口套件要读进程内的 `MachOImage`(SwiftUICore),而轴里的镜像是 `MachOFile`,演进构建器也只收 `MachOFile`;为接口把 `AxisImage` 泛型化,会让 diff 与演进的每条管线都背上它用不到的泛型。接口套件继续用 MachOKitExtensions 的四个基类,`dump` 直接收这个镜像。 +2. **三类合成一个大的 `DumpKind` 枚举、一个协议**:放弃。三类的输入不同(一个镜像 / 两个版本 / N 个版本),合成一个就得让每个种类在运行时检查自己拿到的输入形状对不对;分三个枚举,编译期就排除了「对单个镜像跑 diff」这类组合。 +3. **diff 保留自己的两版基类**:用户在澄清时否掉——两套写法表达同一件事,读 cache 的方式还和 CLI 不一致。 +4. **只统一结构、不加 ObjC**:用户在澄清时否掉——三类都能一处声明镜像、同时看两种语言,才算统一。 +5. **ObjC 输出加在每个套件上**:暂不。SymbolTestsCore、SwiftUICore、SourceEditor、DVTProductsUI 的 ObjC 部分不是维护者常看的;需要时加一对一行测试即可。 +6. **套件按镜像改名(如 `AppKitDyldCacheTests`)**:放弃。接口与 diff 的套件是维护者临时指向别的镜像的探针(任务报告里出现过改读 SnippetUI,未提交的实验在改读 AttributeGraph),按镜像命名会随手变得名不副实。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯测试改动,不涉及任何公开 API:IntegrationTests 不是 product,没有调用方。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译;本提案也只改测试目标。 + +### 下游影响 + +本仓库只有 IntegrationTests 目标受影响,`Package.swift` 只为它多列一个已有的 MachOObjCSection product。下游仓库不依赖 IntegrationTests,无影响。维护者手动运行时用的测试名会变(见行为差异表)。 + +### 文档与示例 + +`Documentations/Internal/ABIEvolutionDesign.md:235` 的目录改成 `Tests/IntegrationTests/InspectionDumps/`。账本、任务报告与已落地提案里的旧套件名是历史记录,不改。 + +## API 演进与废弃策略 + +不适用 —— 没有公开 API 变化;旧测试名直接删除,不留别名。 + +## 落地步骤 + +验证一律在 Ultra 上做(本机是公司那台,不编大工程):`queued-build swift build --build-tests`,scratch 用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-UnifyDiffAndInterfaceIntegrationSuites`,默认 Xcode 编一遍,再用 `DEVELOPER_DIR=…/Xcode-26.6.0.app`(CI 的版本)编一遍。第一次 26.6 构建若报 `no such module 'swift_section'`,是已知的构建顺序竞态,原样重跑。不运行 IntegrationTests。 + +1. **公共骨架与版本轴**——`InspectionDumps/` 目录;`InspectionDumpTests.swift`、`VersionAxis.swift`、`EvolutionDumpTests.swift`、`EvolutionTests.swift` 移入并改名;两个旧文件只做机械改名以保持能编。 + - 行为:`evolutionSuitesKeepTheirFortyThreeTestsAndOutputs` + - 行为:`multiVersionCacheAxisStoresOneAxisPerLanguage` + - 行为:`simulatorFilePairGivesItsOwnAxisLabeledByVersion` + - 行为:`objcSnapshotDocumentIsSharedByDiffAndEvolution` +2. **接口一类**——`InterfaceDumpTests.swift`、`InterfaceTests.swift`;删除 `SwiftInterface/SwiftInterfaceBuilderTests.swift`;`Package.swift` 加 `ObjCDeclarationRendering`。 + - 行为:`swiftInterfaceMatchesTodaysConfigurationAndFileName` + - 行为:`exportedOnlySuiteOverridesOneFlagInsteadOfTheWholeConfiguration` + - 行为:`objcInterfaceConcatenatesEveryKindInObjcDumpOrder` + - 行为:`readerSuffixComesFromAsMachOImage` + - 行为:`appKitInterfaceSuitesWriteBothLanguages` +3. **diff 一类**——`DiffDumpTests.swift`、`DiffTests.swift`;删除 `SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift`。 + - 行为:`diffCachePairOpensEachCacheWhole` + - 行为:`swiftReportWritesChangeListAndJSON` + - 行为:`swiftInterfaceRendersUnifiedOnlyForFiles` + - 行为:`objcReportUsesTheObjCDifferAndVerdictLine` + - 行为:`diffWithFewerThanTwoVersionsPrintsANoteAndWritesNothing` + - 行为:`xcodePairIsPickedByVersion` +4. **文档**——`ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 + - 维护者比对(可选):挑 `InterfaceTestSuite.MachOFileTests.swiftInterfaceFile` 与 `DiffTestSuite.SwiftUICoreTests` 的两个 file 测试前后各跑一次,`diff` 输出;cache 对的 diff 预期可能因整份打开而不同。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。 +- **有没有引入新术语** —— 「版本轴」0110 已判断不登记;本提案不新增术语。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-26 | Created as Draft | 0110 合并演进套件后,用户要求把 diff 与单版本接口两类手检套件也按同样的结构统一。澄清一轮:两类都加上 ObjC 输出;diff 改用演进套件的版本轴(cache 对因此整份打开,与 CLI 一致);维护者未提交的接口套件实验不碰,照提交版重构,由维护者自己收掉。 | +| 2026-11-26 | Accepted | 用户看过简报后批准,开始实现。 | diff --git a/Documentations/README.md b/Documentations/README.md index 1e5d2591..98cd2c46 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -229,6 +229,7 @@ selects names using each access's offset and width. | [Evolutions/0108-private-cf-type-modules.md](Evolutions/0108-private-cf-type-modules.md) | **提案 0108(Implemented)**:私有 CF 类型在 `interface --resolve-c-module-names` 下查不到模块,只印描述符给的裸名(`CGSVGDocument`)。新增 swift-type-indexing `DeclaredTypeNameSource` 的实现 `CFDeclaredTypeNames`:从镜像导出的 `…GetTypeID` 列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`),provider 为根镜像和每个直接依赖登记,引用印成 `CoreSVG.CGSVGDocument`;打印器、swift-type-indexing 与 CLI 参数不改。macOS 27.2 cache 里 Swift 用到的 20 个私有 CF 类型能覆盖 15 个。 | | [Evolutions/0109-consistent-c-imported-type-spelling.md](Evolutions/0109-consistent-c-imported-type-spelling.md) | **提案 0109(Implemented)**:C 导入类型的拼写补齐——0106 之后还剩两处混用:镜像里有描述符、Swift 名与 C 名相同的类型,声明写裸名而引用与扩展头写 `__C::`;展开字段偏移树的注释用固定的 `.default` 印类型名(C 名、点号限定、不带模块选择器与 `any`)。名字表收下没有 ABI 名的描述符(编译器只在两个名字不同时才写 ABI 名),引用改写裸名;interface 的布局注释经打印器自己的类型拼写印类型名,离线与进程内两条后端一起改,dump 不变。本镜像没有描述符的类型照旧写 `__C::`。 | | [Evolutions/0110-unify-evolution-integration-suites.md](Evolutions/0110-unify-evolution-integration-suites.md) | **提案 0110(Implemented)**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自重复定义同几条版本轴、互相借用对方的类属性,每条管线又把单镜像与镜像组写两遍。合成一套:`Tests/IntegrationTests/Evolution/` 下版本轴只定义一次、按读的元数据(`__swift5_*` / `__objc_*`)筛版本,四条管线收进一个协议,21 个套件类变成 10 个轴套件,43 个「轴 × 输出」组合与输出文件名不变。 | +| [Evolutions/draft-unify-diff-and-interface-integration-suites.md](Evolutions/draft-unify-diff-and-interface-integration-suites.md) | **提案 draft(Accepted)**:IntegrationTests 的 diff 与单版本接口两类手检套件按 0110 的结构统一,三类输出(接口、diff、演进)进同一个目录 `Tests/IntegrationTests/InspectionDumps/`、共用一个公共协议;diff 改用演进的版本轴(cache 对因此整份打开,与 CLI 一致),每类一个「输出种类」枚举加一个 `dump` 入口;AppKit 的接口与 diff 套件多出 ObjC 头文件与 ObjC 变更列表。测试 20 个变 38 个,演进的 43 个不变。 | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | From 94de6c3a45be7b022ea65a283b75aebb37d0fe5e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:42:15 +0800 Subject: [PATCH 127/175] test(IntegrationTests): move the dump scaffolding and version axes into InspectionDumps The shared support and the evolution suites move into one directory with neutral names: InspectionDumpTests, MetadataLanguage, DumpOutput and the VersionAxis types. The two-version base classes join the axis file and supply axes too, so the simulator evolution suite no longer builds its own. The two older suite files only follow the protocol rename for now. --- .../Evolution/EvolutionAxis.swift | 247 ------------ .../EvolutionDumpTests.swift | 127 ++----- .../EvolutionTests.swift | 24 +- .../InspectionDumpTests.swift} | 105 +++++- .../InspectionDumps/VersionAxis.swift | 354 ++++++++++++++++++ .../SwiftDiffableInterfaceBuilderTests.swift | 6 +- .../SwiftInterfaceBuilderTests.swift | 2 +- 7 files changed, 489 insertions(+), 376 deletions(-) delete mode 100644 Tests/IntegrationTests/Evolution/EvolutionAxis.swift rename Tests/IntegrationTests/{Evolution => InspectionDumps}/EvolutionDumpTests.swift (71%) rename Tests/IntegrationTests/{Evolution => InspectionDumps}/EvolutionTests.swift (92%) rename Tests/IntegrationTests/{SwiftInterface/SwiftInterfaceTestSupport.swift => InspectionDumps/InspectionDumpTests.swift} (54%) create mode 100644 Tests/IntegrationTests/InspectionDumps/VersionAxis.swift diff --git a/Tests/IntegrationTests/Evolution/EvolutionAxis.swift b/Tests/IntegrationTests/Evolution/EvolutionAxis.swift deleted file mode 100644 index 39cd304a..00000000 --- a/Tests/IntegrationTests/Evolution/EvolutionAxis.swift +++ /dev/null @@ -1,247 +0,0 @@ -import Foundation -import Testing -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection - -/// The metadata an evolution pipeline reads, and so which images join its -/// axis: an image without it has nothing to index, and indexing it anyway -/// only logs extraction failures. -enum EvolutionMetadataLanguage: Sendable { - /// `__swift5_*` sections. AppKit kept its Swift API in - /// `libswiftAppKit.dylib` until macOS 14, so a Swift axis of AppKit - /// reaching further back starts at 14.0. - case swift - /// `__objc_*` sections, which AppKit carries in every cache. - case objc - - func isCarried(by machOFile: MachOFile) -> Bool { - let sectionNamePrefix = switch self { - case .swift: "__swift5_" - case .objc: "__objc_" - } - return machOFile.sections.contains(where: { $0.sectionName.hasPrefix(sectionNamePrefix) }) - } -} - -/// The platform an evolution interface spells availability for — what -/// `evolution --interface --emit-available --platform` passes — each -/// pipeline in its own spelling. -enum EvolutionAvailabilityPlatform: Sendable { - case macOS - - /// The platform of `@available(macOS, …)`. - var swiftSpelling: String { - switch self { - case .macOS: "macOS" - } - } - - /// The platform of `API_AVAILABLE(macos(…))`. - var objcSpelling: String { - switch self { - case .macOS: "macos" - } - } -} - -/// One image of one version on an evolution axis. -struct EvolutionImage: Sendable { - let imageName: String - let machOFile: MachOFile -} - -/// One version on an evolution axis: its label and the images whose -/// declarations make it up, the primary image first. -struct EvolutionVersion: Sendable { - let label: String - let images: [EvolutionImage] - - var primaryImage: EvolutionImage { images[0] } - - /// This version as a pipeline reading `language` sees it: only the - /// images carrying that metadata, or `nil` — off the axis — when the - /// primary image does not. - func keepingImages(carrying language: EvolutionMetadataLanguage) -> EvolutionVersion? { - guard language.isCarried(by: primaryImage.machOFile) else { return nil } - return EvolutionVersion(label: label, images: images.filter { language.isCarried(by: $0.machOFile) }) - } -} - -/// One ordered series of versions (oldest first), as one pipeline reads it. -struct EvolutionAxis: Sendable { - let versions: [EvolutionVersion] - /// Whether every version is a group of images (evolution proposal - /// `image-group-evolution`). It picks the builders' image-group entry - /// points, which name each version's images and record moves between - /// them, so a version of one image still reads differently from a group - /// of one. - let comparesImageGroups: Bool - /// Set when every label is a version number, so the interfaces also - /// spell each lifecycle one attribute or macro can express. - let availabilityPlatform: EvolutionAvailabilityPlatform? -} - -/// Extracts the same images from an *ordered series* of dyld shared caches — -/// the N-version counterpart of -/// `SwiftDiffableInterfaceBuilderTestSuite.CrossVersionDyldCacheImageTests`. -/// The caches are retained because the extracted `MachOFile`s resolve -/// cross-image references through them while indexing. -/// -/// One instance serves every pipeline: it keeps, per cache, every image of -/// `cacheImageNames` the cache holds, and each language's axis then keeps -/// the images carrying that language's metadata. A version whose primary -/// image is missing, or lacks the metadata, is off that axis — there is -/// nothing to index. A cache that cannot be opened still throws. -/// -/// Each cache is opened whole, the way `swift-section --dyld-shared-cache` -/// opens it, so the dumps match what the command line prints. Opened from -/// its main file alone, every read into another sub-cache file mapped that -/// file once more until MachOObjCSection 0.8.109, and an evolution over -/// every archived macOS minor ran past 5 GB. -/// -/// A suite comparing a group of images per version (evolution proposal -/// `image-group-evolution`) lists them in `cacheImageNames`, the primary -/// image first: AppKit with the frameworks Apple moved its classes into, -/// SwiftUI with SwiftUICore. Each other image joins its group where the -/// cache has it with the metadata — CollectionViewCore is in the macOS -/// caches from 13.0 on, SwiftUICore from 15.0 on. -@TestActor -class MultiVersionDyldCacheImageTests: Sendable { - let caches: [FullDyldCache] - private let swiftAxis: EvolutionAxis - private let objcAxis: EvolutionAxis - - /// Oldest first; each cache's `versionLabel` labels it on the axis. - class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } - - class var cacheImageName: MachOImageName { .SwiftUI } - - /// The images whose declarations make up one version, the primary - /// image first; by default the primary image alone. - class var cacheImageNames: [MachOImageName] { [cacheImageName] } - - /// Set on an axis whose every label is a version number. - class var availabilityPlatform: EvolutionAvailabilityPlatform? { nil } - - /// The three macOS caches most suites read: 15.5 → 26.5.2 → 27.0. - static var defaultMacOSCachePaths: [DyldSharedCachePath] { - [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] - } - - /// One archived cache per macOS minor, oldest first: the directories - /// under `/Volumes/DyldSharedCaches/macOS` that hold a cache. A cache is - /// labeled with its version, or with the major release - /// `archivedMacOSVersionLabelsByCacheVersion` names for it, so every label - /// is a version number. - static var archivedMacOSCachePaths: [DyldSharedCachePath] { - archivedMacOSCacheVersions.map { cacheVersion in - let cachePath = DyldSharedCachePath.macOS(cacheVersion) - guard let versionLabel = archivedMacOSVersionLabelsByCacheVersion[cacheVersion] else { return cachePath } - return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) - } - } - - static var archivedMacOSCacheVersions: [String] { [ - "11.0.1", - "11.1", - "11.2", - "11.3", - "11.4", - "11.5", - "11.6", - "11.7", - "12.0.1", - "12.1", - "12.2", - "12.3", - "12.4", - "12.5", - "12.6", - "12.7", - "13.0", - "13.1", - "13.2", - "13.3", - "13.4", - "13.5", - "13.6", - "13.7", - "14.0", - "14.1", - "14.2", - "14.3", - "14.4", - "14.5", - "14.6", - "14.7", - "14.8", - "15.0", - "15.1", - "15.2", - "15.3", - "15.4", - "15.5", - "15.6", - "15.7", - "15.8", - "26.0", - "26.1", - "26.2", - "26.3", - "26.4", - "26.5", - "26.6", - "26.7", - "27.0", - ] } - - /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and 12.0.1, - /// so those are the directories the volume has; the axis still labels - /// them 11.0 and 12.0, the versions an SDK's availability attributes name. - static var archivedMacOSVersionLabelsByCacheVersion: [String: String] { - ["11.0.1": "11.0", "12.0.1": "12.0"] - } - - init() async throws { - let primaryImageName = Self.cacheImageNames.first?.name - var caches: [FullDyldCache] = [] - var versions: [EvolutionVersion] = [] - for cachePath in Self.cachePaths { - let cache = try FullDyldCache(path: cachePath) - let images = Self.cacheImageNames.compactMap { imageName -> EvolutionImage? in - guard let machOFile = cache.machOFile(named: imageName) else { return nil } - return EvolutionImage(imageName: imageName.name, machOFile: machOFile) - } - guard let primaryImage = images.first, primaryImage.imageName == primaryImageName else { - continue - } - caches.append(cache) - versions.append(EvolutionVersion(label: cachePath.versionLabel, images: images)) - } - let comparesImageGroups = Self.cacheImageNames.count > 1 - let availabilityPlatform = Self.availabilityPlatform - self.caches = caches - self.swiftAxis = EvolutionAxis( - versions: versions.compactMap { $0.keepingImages(carrying: .swift) }, - comparesImageGroups: comparesImageGroups, - availabilityPlatform: availabilityPlatform - ) - self.objcAxis = EvolutionAxis( - versions: versions.compactMap { $0.keepingImages(carrying: .objc) }, - comparesImageGroups: comparesImageGroups, - availabilityPlatform: availabilityPlatform - ) - } - - /// The axis a pipeline reading `language` runs over. Computed at - /// initialization: the class properties it derives from are isolated to - /// the test actor, the pipelines are not. - nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis { - switch language { - case .swift: swiftAxis - case .objc: objcAxis - } - } -} diff --git a/Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/EvolutionDumpTests.swift similarity index 71% rename from Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift rename to Tests/IntegrationTests/InspectionDumps/EvolutionDumpTests.swift index d10e8f3d..73a1c6d4 100644 --- a/Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/EvolutionDumpTests.swift @@ -30,7 +30,7 @@ enum EvolutionDumpKind: Sendable { /// lifecycle annotations (`-ObjCEvolutionInterface.h`). case objcInterface - var language: EvolutionMetadataLanguage { + var language: MetadataLanguage { switch self { case .swiftReport, .swiftInterface: .swift case .objcReport, .objcInterface: .objc @@ -38,25 +38,6 @@ enum EvolutionDumpKind: Sendable { } } -/// Where a dump goes: printed for a quick look, or written next to the -/// other dumps for inspection. -enum EvolutionDumpDestination: Sendable { - case console - case file -} - -/// What one pipeline produced. -struct EvolutionDumpOutput: Sendable { - /// The file-name suffix, after the build version and the image names. - let suffix: String - /// What a maintainer reads: the report, or the annotated interface. - let text: String - let textFileExtension: String - /// The machine-readable form a report also writes; `nil` for an - /// interface. - let json: String? -} - /// The evolution dumps: an *ordered series* of versions of one image — or /// of one group of images per version (evolution proposal /// `image-group-evolution`) — run through the pipelines of `swift-section @@ -70,25 +51,19 @@ struct EvolutionDumpOutput: Sendable { /// lifecycle annotated; read one against the report of the same axis — the /// annotations are the same lineages. /// -/// A conforming suite supplies the axis each pipeline runs over. Like its -/// siblings this is a maintainer-inspection dump: it prints / writes results -/// without assertions. -protocol EvolutionDumpTests: SwiftInterfaceDumpTests { - func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis -} +/// A conforming suite supplies the axis each pipeline runs over +/// (`VersionAxisDumpTests`). Like its siblings this is a maintainer-inspection +/// dump: it prints / writes results without assertions. +protocol EvolutionDumpTests: VersionAxisDumpTests {} @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) extension EvolutionDumpTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - /// Runs one pipeline over this suite's axis for the pipeline's language, /// then prints the text, or writes the text — and a report's JSON — /// named after the newest version's images. - func dump(_ kind: EvolutionDumpKind, to destination: EvolutionDumpDestination) async throws { - let axis = evolutionAxis(for: kind.language) - let output: EvolutionDumpOutput + func dump(_ kind: EvolutionDumpKind, to destination: DumpDestination) async throws { + let axis = versionAxis(for: kind.language) + let output: DumpOutput switch kind { case .swiftReport: output = try await swiftReport(over: axis) @@ -99,15 +74,9 @@ extension EvolutionDumpTests { case .objcInterface: output = try await objcInterface(over: axis) } - switch destination { - case .console: - printResult(output.text) - case .file: + try deliver(output, to: destination) { file in guard let newestVersion = axis.versions.last else { return } - try write(output.text, forImageGroup: newestVersion.images, suffix: output.suffix, fileExtension: output.textFileExtension) - if let json = output.json { - try write(json, forImageGroup: newestVersion.images, suffix: output.suffix, fileExtension: "json") - } + try write(file.text, forImageGroup: newestVersion.images, suffix: file.suffix, fileExtension: file.fileExtension) } } @@ -117,7 +86,7 @@ extension EvolutionDumpTests { /// frozen into a labeled snapshot document, round-tripped through the /// persisted form: what the evolution consumes is exactly what a saved /// baseline would decode to. - private func swiftSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ABISnapshotDocument { + private func swiftSnapshotDocument(of image: AxisImage, label: String) async throws -> ABISnapshotDocument { let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: image.machOFile) try await builder.prepare() let document = ABISnapshotDocument( @@ -135,7 +104,7 @@ extension EvolutionDumpTests { /// The lineage report and its JSON. The timed step covers indexing every /// image of every version — the real cost; the lineage math afterwards /// is milliseconds. - private func swiftReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + private func swiftReport(over axis: VersionAxis) async throws -> DumpOutput { var documentsByVersion: [[ABISnapshotDocument]] = [] try await measuringPreparation { for version in axis.versions { @@ -171,11 +140,12 @@ extension EvolutionDumpTests { report += "\n\nPairwise cross-check — evolution ABI-breaking: \(evolution.hasBreakingChange) · diff ABI-breaking: \(diff.hasBreakingChange)" } } - return EvolutionDumpOutput( - suffix: "Evolution", - text: report, - textFileExtension: "txt", - json: String(decoding: try ABIJSON.encoder().encode(evolution), as: UTF8.self) + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "Evolution", fileExtension: "txt", text: report), + DumpFile(suffix: "Evolution", fileExtension: "json", text: String(decoding: try ABIJSON.encoder().encode(evolution), as: UTF8.self)), + ] ) } @@ -183,7 +153,7 @@ extension EvolutionDumpTests { /// manual inspection can eyeball the CI-gate input next to the /// rendering. The timed step covers indexing every version; the lineage /// join and rendering afterwards are cheap by comparison. - private func swiftInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + private func swiftInterface(over axis: VersionAxis) async throws -> DumpOutput { let labels = axis.versions.map(\.label) let availabilityAnnotationPlatform = axis.availabilityPlatform?.swiftSpelling let builder: AnySwiftEvolutionInterfaceBuilder @@ -213,31 +183,17 @@ extension EvolutionDumpTests { if let evolution = builder.evolution { report += "\n\n// ABI-breaking on this axis: \(evolution.hasBreakingChange)" } - return EvolutionDumpOutput(suffix: "EvolutionInterface", text: report, textFileExtension: "swiftinterface", json: nil) + return DumpOutput( + consoleText: report, + files: [DumpFile(suffix: "EvolutionInterface", fileExtension: "swiftinterface", text: report)] + ) } // MARK: - Objective-C - /// One image indexed the way `swift-section objc snapshot` indexes it and - /// frozen into a labeled snapshot document, round-tripped through the - /// persisted form. - private func objcSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ObjCAPISnapshotDocument { - let indexer = try await preparedObjCIndexer(of: image.machOFile) - let document = ObjCAPISnapshotDocument( - provenance: ObjCAPIProvenance( - label: label, - binaryPath: image.machOFile.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() - ) - return try ObjCAPISnapshotDocument.decode(from: document.encoded()) - } - /// The lineage report and its JSON, as `swiftReport(over:)` builds the /// Swift ones. - private func objcReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + private func objcReport(over axis: VersionAxis) async throws -> DumpOutput { var documentsByVersion: [[ObjCAPISnapshotDocument]] = [] try await measuringPreparation { for version in axis.versions { @@ -270,11 +226,12 @@ extension EvolutionDumpTests { report += "\n\nPairwise cross-check — evolution API-breaking: \(evolution.hasBreakingChange) · diff API-breaking: \(diff.hasBreakingChange)" } } - return EvolutionDumpOutput( - suffix: "ObjCEvolution", - text: report, - textFileExtension: "txt", - json: String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self) + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "ObjCEvolution", fileExtension: "txt", text: report), + DumpFile(suffix: "ObjCEvolution", fileExtension: "json", text: String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self)), + ] ) } @@ -283,7 +240,7 @@ extension EvolutionDumpTests { /// handed to the builder, which keeps what it rendered and snapshotted, /// never the indexer; a group's images go in together, the primary image /// first, so a class that moved between them stays one declaration. - private func objcInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput { + private func objcInterface(over axis: VersionAxis) async throws -> DumpOutput { var builder = ObjCEvolutionInterfaceBuilder() try await measuringPreparation { for version in axis.versions { @@ -303,24 +260,10 @@ extension EvolutionDumpTests { } } let evolutionInterface = try builder.build(availabilityPlatform: axis.availabilityPlatform?.objcSpelling) - return EvolutionDumpOutput( - suffix: "ObjCEvolutionInterface", - text: evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)", - textFileExtension: "h", - json: nil + let header = evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)" + return DumpOutput( + consoleText: header, + files: [DumpFile(suffix: "ObjCEvolutionInterface", fileExtension: "h", text: header)] ) } } - -/// One image indexed the way the `objc` subcommands index it: the Swift -/// classes that keep no class object supplied from Swift metadata. -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -private func preparedObjCIndexer(of machO: MachOFile) async throws -> ObjCInterfaceIndexer { - let indexer = ObjCInterfaceIndexer( - machO: machO, - imagePath: machO.imagePath, - suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) - ) - try await indexer.prepare() - return indexer -} diff --git a/Tests/IntegrationTests/Evolution/EvolutionTests.swift b/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift similarity index 92% rename from Tests/IntegrationTests/Evolution/EvolutionTests.swift rename to Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift index b22462ea..4ab75336 100644 --- a/Tests/IntegrationTests/Evolution/EvolutionTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift @@ -54,7 +54,7 @@ enum EvolutionTestSuite { /// byte-identical. @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) @Test func swiftInterfaceStringViaPackFacade() async throws { - let versions = evolutionAxis(for: .swift).versions + let versions = versionAxis(for: .swift).versions let builder = try SwiftEvolutionInterfaceBuilder( configuration: indexConfiguration, versions: versions[0].primaryImage.machOFile, versions[1].primaryImage.machOFile, versions[2].primaryImage.machOFile, @@ -117,7 +117,7 @@ enum EvolutionTestSuite { final class SwiftUIArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } override class var cacheImageName: MachOImageName { .SwiftUI } - override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + override class var availabilityPlatform: AvailabilityPlatform? { .macOS } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftInterfaceFile() async throws { @@ -142,7 +142,7 @@ enum EvolutionTestSuite { final class AppKitArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } override class var cacheImageName: MachOImageName { .AppKit } - override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + override class var availabilityPlatform: AvailabilityPlatform? { .macOS } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func objcReportFile() async throws { @@ -220,7 +220,7 @@ enum EvolutionTestSuite { final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + override class var availabilityPlatform: AvailabilityPlatform? { .macOS } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -297,7 +297,7 @@ enum EvolutionTestSuite { final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } - override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + override class var availabilityPlatform: AvailabilityPlatform? { .macOS } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func objcReportFile() async throws { @@ -323,22 +323,10 @@ enum EvolutionTestSuite { /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the /// N == 2 case, whose printed pairwise cross-check line must agree with /// the two-sided differ. - final class SwiftUICoreSimulatorTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + final class SwiftUICoreSimulatorTests: CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis { - let versions = [ - EvolutionVersion(label: "18.5", images: [EvolutionImage(imageName: "SwiftUICore", machOFile: oldMachOFile)]), - EvolutionVersion(label: "26.5", images: [EvolutionImage(imageName: "SwiftUICore", machOFile: newMachOFile)]), - ] - return EvolutionAxis( - versions: versions.compactMap { $0.keepingImages(carrying: language) }, - comparesImageGroups: false, - availabilityPlatform: nil - ) - } - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { try await dump(.swiftReport, to: .file) diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift b/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift similarity index 54% rename from Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift rename to Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift index 063bf267..3a5f1e61 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift +++ b/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift @@ -2,28 +2,81 @@ import Foundation import MachOKit import SwiftSectionFixtureSupport @testable import MachOSwiftSection +@_spi(Support) @testable import SwiftIndexing +import ObjCMetadataSource +import ObjCIndexing import FoundationToolbox import SwiftStdlibToolbox -/// Shared scaffolding for the `SwiftInterface`-level integration dumps. +/// Shared scaffolding for the maintainer-inspection dumps: the +/// single-version interfaces (`InterfaceDumpTests`), the two-version diffs +/// (`DiffDumpTests`) and the N-version evolutions (`EvolutionDumpTests`). /// -/// Both the single-binary interface builder tests and the two-binary diffable -/// builder tests follow the same shape — index a binary (timed), render it to a -/// `String`, then either print it or write it next to the others — so that -/// common machinery (the output directory, the `prepare()` timer, the -/// console/file sinks, and the binary-identifying file name) lives here once. -protocol SwiftInterfaceDumpTests {} +/// Every dump has the same shape — index the images (timed), run one +/// `swift-section` pipeline over them, then print the result or write it +/// next to the others — so the common machinery lives here once: the output +/// directory, the index configuration every pipeline shares, the +/// `prepare()` timer, the console and file sinks, and the file names that +/// identify the images. Like the dumps themselves, nothing here asserts. +protocol InspectionDumpTests {} + +/// The metadata a pipeline reads: an image without it has nothing to index, +/// and indexing it anyway only logs extraction failures. +enum MetadataLanguage: Sendable { + /// `__swift5_*` sections. AppKit kept its Swift API in + /// `libswiftAppKit.dylib` until macOS 14, so a Swift axis of AppKit + /// reaching further back starts at 14.0. + case swift + /// `__objc_*` sections, which AppKit carries in every cache. + case objc + + func isCarried(by machOFile: MachOFile) -> Bool { + let sectionNamePrefix = switch self { + case .swift: "__swift5_" + case .objc: "__objc_" + } + return machOFile.sections.contains(where: { $0.sectionName.hasPrefix(sectionNamePrefix) }) + } +} + +/// Where a dump goes: printed for a quick look, or written next to the +/// other dumps for inspection. +enum DumpDestination: Sendable { + case console + case file +} + +/// One file a dump writes, named +/// `--.`. +struct DumpFile: Sendable { + let suffix: String + let fileExtension: String + let text: String +} + +/// What one pipeline produced: the text the console destination prints, +/// and the files the file destination writes. +struct DumpOutput: Sendable { + let consoleText: String + let files: [DumpFile] +} @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftInterfaceDumpTests { - /// The directory every dump is written under, shared so the interface and - /// diff artifacts of the same binary co-locate for manual inspection. +extension InspectionDumpTests { + /// The directory every dump is written under, shared so the interface, + /// diff and evolution artifacts of the same binary co-locate for manual + /// inspection. var rootDirectory: URL { .documentsDirectory.appending(path: "SwiftInterfaceTests") } + /// How every pipeline indexes Swift metadata. + var indexConfiguration: SwiftDeclarationIndexConfiguration { + .init(showCImportedTypes: false) + } + /// Runs `prepare` and prints how long it took (unless running silently). - /// Callers pass the whole preparation step — for the differ that means + /// Callers pass the whole preparation step — for a diff that means /// preparing *both* binaries — so the printed duration covers the real work. func measuringPreparation(_ prepare: () async throws -> Void) async rethrows { let clock = ContinuousClock() @@ -40,6 +93,19 @@ extension SwiftInterfaceDumpTests { #endif } + /// Prints `output`'s console text, or hands each of its files to + /// `writeFile`, which names it after the images the dump read. + func deliver(_ output: DumpOutput, to destination: DumpDestination, writingFile writeFile: (DumpFile) throws -> Void) rethrows { + switch destination { + case .console: + printResult(output.consoleText) + case .file: + for file in output.files { + try writeFile(file) + } + } + } + /// Writes a rendered dump into `rootDirectory` under a name that identifies /// the binary by its build version and file name, so repeated runs overwrite /// in place and different binaries never collide. @@ -54,7 +120,7 @@ extension SwiftInterfaceDumpTests { try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) } - /// `write(_:for:suffix:fileExtension:)` for one version of an evolution + /// `write(_:for:suffix:fileExtension:)` for one version of a version /// axis, which may be a group of images (evolution proposal /// `image-group-evolution`): named after the primary image's build /// version and every image of the version, joined by `+` @@ -62,7 +128,7 @@ extension SwiftInterfaceDumpTests { /// the name `write(_:for:…)` gives it. func write( _ string: String, - forImageGroup images: [EvolutionImage], + forImageGroup images: [AxisImage], suffix: String, fileExtension: String = "swiftinterface" ) throws { @@ -74,6 +140,19 @@ extension SwiftInterfaceDumpTests { } } +/// One image indexed the way the `objc` subcommands index it: the Swift +/// classes that keep no class object supplied from Swift metadata. +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +func preparedObjCIndexer(of machO: MachO) async throws -> ObjCInterfaceIndexer { + let indexer = ObjCInterfaceIndexer( + machO: machO, + imagePath: machO.imagePath, + suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) + ) + try await indexer.prepare() + return indexer +} + extension BuildVersionCommand: @retroactive CustomStringConvertible { public var description: String { "\(platform.stringValue)-\(sdk)" diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift new file mode 100644 index 00000000..5e8ed630 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift @@ -0,0 +1,354 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDiffing + +/// The platform a version axis spells availability for — what +/// `evolution --interface --emit-available --platform` passes — each +/// pipeline in its own spelling. +enum AvailabilityPlatform: Sendable { + case macOS + + /// The platform of `@available(macOS, …)`. + var swiftSpelling: String { + switch self { + case .macOS: "macOS" + } + } + + /// The platform of `API_AVAILABLE(macos(…))`. + var objcSpelling: String { + switch self { + case .macOS: "macos" + } + } +} + +/// One image of one version on a version axis. +struct AxisImage: Sendable { + let imageName: String + let machOFile: MachOFile +} + +/// One version on a version axis: its label and the images whose +/// declarations make it up, the primary image first. +struct AxisVersion: Sendable { + let label: String + let images: [AxisImage] + + var primaryImage: AxisImage { images[0] } + + /// This version as a pipeline reading `language` sees it: only the + /// images carrying that metadata, or `nil` — off the axis — when the + /// primary image does not. + func keepingImages(carrying language: MetadataLanguage) -> AxisVersion? { + guard language.isCarried(by: primaryImage.machOFile) else { return nil } + return AxisVersion(label: label, images: images.filter { language.isCarried(by: $0.machOFile) }) + } +} + +/// One ordered series of versions (oldest first), as one pipeline reads it: +/// a diff reads its first and last version, an evolution every version. +struct VersionAxis: Sendable { + let versions: [AxisVersion] + /// Whether every version is a group of images (evolution proposal + /// `image-group-evolution`). It picks the evolution builders' + /// image-group entry points, which name each version's images and + /// record moves between them, so a version of one image still reads + /// differently from a group of one. + let comparesImageGroups: Bool + /// Set when every label is a version number, so the evolution + /// interfaces also spell each lifecycle one attribute or macro can + /// express. + let availabilityPlatform: AvailabilityPlatform? +} + +/// The axis of each metadata language over one series of versions: each +/// keeps the versions whose primary image carries that language's metadata. +struct VersionAxes: Sendable { + private let swiftAxis: VersionAxis + private let objcAxis: VersionAxis + + init(versions: [AxisVersion], comparesImageGroups: Bool, availabilityPlatform: AvailabilityPlatform?) { + self.swiftAxis = VersionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: .swift) }, + comparesImageGroups: comparesImageGroups, + availabilityPlatform: availabilityPlatform + ) + self.objcAxis = VersionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: .objc) }, + comparesImageGroups: comparesImageGroups, + availabilityPlatform: availabilityPlatform + ) + } + + func axis(for language: MetadataLanguage) -> VersionAxis { + switch language { + case .swift: swiftAxis + case .objc: objcAxis + } + } +} + +/// A dump over an ordered series of versions — a diff or an evolution. A +/// conforming suite supplies the axis each pipeline runs over, usually by +/// inheriting one of the axis base classes below. +protocol VersionAxisDumpTests: InspectionDumpTests { + func versionAxis(for language: MetadataLanguage) -> VersionAxis +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension VersionAxisDumpTests { + /// One image indexed the way `swift-section objc snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form: what a diff or an evolution consumes is exactly what a + /// saved baseline would decode to. + func objcSnapshotDocument(of image: AxisImage, label: String) async throws -> ObjCAPISnapshotDocument { + let indexer = try await preparedObjCIndexer(of: image.machOFile) + let document = ObjCAPISnapshotDocument( + provenance: ObjCAPIProvenance( + label: label, + binaryPath: image.machOFile.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() + ) + return try ObjCAPISnapshotDocument.decode(from: document.encoded()) + } +} + +/// Extracts the same images from an *ordered series* of dyld shared caches: +/// N versions for an evolution, two for a diff. The caches are retained +/// because the extracted `MachOFile`s resolve cross-image references through +/// them while indexing. +/// +/// One instance serves every pipeline: it keeps, per cache, every image of +/// `cacheImageNames` the cache holds, and each language's axis then keeps +/// the images carrying that language's metadata. A version whose primary +/// image is missing, or lacks the metadata, is off that axis — there is +/// nothing to index. A cache that cannot be opened still throws. +/// +/// Each cache is opened whole, the way `swift-section --dyld-shared-cache` +/// opens it, so the dumps match what the command line prints. Opened from +/// its main file alone, every read into another sub-cache file mapped that +/// file once more until MachOObjCSection 0.8.109, and an evolution over +/// every archived macOS minor ran past 5 GB. +/// +/// A suite comparing a group of images per version (evolution proposal +/// `image-group-evolution`) lists them in `cacheImageNames`, the primary +/// image first: AppKit with the frameworks Apple moved its classes into, +/// SwiftUI with SwiftUICore. Each other image joins its group where the +/// cache has it with the metadata — CollectionViewCore is in the macOS +/// caches from 13.0 on, SwiftUICore from 15.0 on. A diff reads the primary +/// image of each version only. +@TestActor +class MultiVersionDyldCacheImageTests: Sendable { + let caches: [FullDyldCache] + private let axes: VersionAxes + + /// Oldest first; each cache's `versionLabel` labels it on the axis. + class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } + + class var cacheImageName: MachOImageName { .SwiftUI } + + /// The images whose declarations make up one version, the primary + /// image first; by default the primary image alone. + class var cacheImageNames: [MachOImageName] { [cacheImageName] } + + /// Set on an axis whose every label is a version number. + class var availabilityPlatform: AvailabilityPlatform? { nil } + + /// The three macOS caches most evolution suites read: 15.5 → 26.5.2 → 27.0. + static var defaultMacOSCachePaths: [DyldSharedCachePath] { + [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] + } + + /// One archived cache per macOS minor, oldest first: the directories + /// under `/Volumes/DyldSharedCaches/macOS` that hold a cache. A cache is + /// labeled with its version, or with the major release + /// `archivedMacOSVersionLabelsByCacheVersion` names for it, so every label + /// is a version number. + static var archivedMacOSCachePaths: [DyldSharedCachePath] { + archivedMacOSCacheVersions.map { cacheVersion in + let cachePath = DyldSharedCachePath.macOS(cacheVersion) + guard let versionLabel = archivedMacOSVersionLabelsByCacheVersion[cacheVersion] else { return cachePath } + return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) + } + } + + static var archivedMacOSCacheVersions: [String] { [ + "11.0.1", + "11.1", + "11.2", + "11.3", + "11.4", + "11.5", + "11.6", + "11.7", + "12.0.1", + "12.1", + "12.2", + "12.3", + "12.4", + "12.5", + "12.6", + "12.7", + "13.0", + "13.1", + "13.2", + "13.3", + "13.4", + "13.5", + "13.6", + "13.7", + "14.0", + "14.1", + "14.2", + "14.3", + "14.4", + "14.5", + "14.6", + "14.7", + "14.8", + "15.0", + "15.1", + "15.2", + "15.3", + "15.4", + "15.5", + "15.6", + "15.7", + "15.8", + "26.0", + "26.1", + "26.2", + "26.3", + "26.4", + "26.5", + "26.6", + "26.7", + "27.0", + ] } + + /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and 12.0.1, + /// so those are the directories the volume has; the axis still labels + /// them 11.0 and 12.0, the versions an SDK's availability attributes name. + static var archivedMacOSVersionLabelsByCacheVersion: [String: String] { + ["11.0.1": "11.0", "12.0.1": "12.0"] + } + + init() async throws { + let primaryImageName = Self.cacheImageNames.first?.name + var caches: [FullDyldCache] = [] + var versions: [AxisVersion] = [] + for cachePath in Self.cachePaths { + let cache = try FullDyldCache(path: cachePath) + let images = Self.cacheImageNames.compactMap { imageName -> AxisImage? in + guard let machOFile = cache.machOFile(named: imageName) else { return nil } + return AxisImage(imageName: imageName.name, machOFile: machOFile) + } + guard let primaryImage = images.first, primaryImage.imageName == primaryImageName else { + continue + } + caches.append(cache) + versions.append(AxisVersion(label: cachePath.versionLabel, images: images)) + } + self.caches = caches + self.axes = VersionAxes( + versions: versions, + comparesImageGroups: Self.cacheImageNames.count > 1, + availabilityPlatform: Self.availabilityPlatform + ) + } + + /// The axis a pipeline reading `language` runs over. Computed at + /// initialization: the class properties it derives from are isolated to + /// the test actor, the pipelines are not. + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } +} + +/// The same file from two simulator runtimes, by fixture name — the +/// two-version counterpart of `SwiftSectionTestingSupport.MachOFileTests`, +/// which loads one. +@TestActor +class CrossVersionMachOFileTests: Sendable { + let oldMachOFile: MachOFile + let newMachOFile: MachOFile + private let axes: VersionAxes + + class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } + class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } + + /// The runtime versions the two files come from, which label them on the axis. + class var oldVersionLabel: String { "18.5" } + class var newVersionLabel: String { "26.5" } + + init() async throws { + let oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.oldFileName)) + let newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.newFileName)) + self.oldMachOFile = oldMachOFile + self.newMachOFile = newMachOFile + self.axes = VersionAxes( + versions: [ + AxisVersion(label: Self.oldVersionLabel, images: [AxisImage(imageName: oldMachOFile.imagePath.lastPathComponent, machOFile: oldMachOFile)]), + AxisVersion(label: Self.newVersionLabel, images: [AxisImage(imageName: newMachOFile.imagePath.lastPathComponent, machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } +} + +/// The same shared framework from two installed Xcode applications, picked +/// by version: `/Applications/Xcode-.app`. The shared +/// `XcodeMachOFileName` fixture names a single Xcode, so this loads by path. +@TestActor +class CrossVersionXcodeFrameworkTests: Sendable { + let oldMachOFile: MachOFile + let newMachOFile: MachOFile + private let axes: VersionAxes + + /// The two Xcode versions, which also label them on the axis. + class var oldXcodeVersion: String { "26.3.0" } + class var newXcodeVersion: String { "26.4.0" } + class var sharedFrameworkName: String { "DVTProductsUI" } + + init() async throws { + let oldMachOFile = try Self.loadSharedFramework(fromXcodeVersion: Self.oldXcodeVersion) + let newMachOFile = try Self.loadSharedFramework(fromXcodeVersion: Self.newXcodeVersion) + self.oldMachOFile = oldMachOFile + self.newMachOFile = newMachOFile + let imageName = Self.sharedFrameworkName + self.axes = VersionAxes( + versions: [ + AxisVersion(label: Self.oldXcodeVersion, images: [AxisImage(imageName: imageName, machOFile: oldMachOFile)]), + AxisVersion(label: Self.newXcodeVersion, images: [AxisImage(imageName: imageName, machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } + + private class func loadSharedFramework(fromXcodeVersion xcodeVersion: String) throws -> MachOFile { + let name = sharedFrameworkName + let binaryPath = "/Applications/Xcode-\(xcodeVersion).app/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" + return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) + } +} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift index e560e2c7..38d05b6e 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift @@ -18,14 +18,10 @@ import Semantic /// `SwiftDiffableInterfaceRenderer` (the full interface annotated with inline /// `+`/`-` markers). Like its sibling it is a maintainer-inspection dump — it /// prints / writes results without assertions. -protocol SwiftDiffableInterfaceBuilderTests: SwiftInterfaceDumpTests {} +protocol SwiftDiffableInterfaceBuilderTests: InspectionDumpTests {} @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) extension SwiftDiffableInterfaceBuilderTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - /// Builds and `prepare()`s both binaries in one timed step — the differ needs /// both sides indexed before it can compare them, so the printed duration /// covers the whole preparation. diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift index 4d033d39..8ad70c2f 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift @@ -14,7 +14,7 @@ import SwiftSectionFixtureSupport @_spi(Internals) @testable import MachOCaches import Semantic -protocol SwiftInterfaceBuilderTests: SwiftInterfaceDumpTests { +protocol SwiftInterfaceBuilderTests: InspectionDumpTests { var builderConfiguration: SwiftInterfaceBuilderConfiguration { get } } From 8f2b258cffafdc980e5b983a7e225ce74302b219 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:43:59 +0800 Subject: [PATCH 128/175] test(IntegrationTests): import the toolbox modules the version axis file reads through --- Tests/IntegrationTests/InspectionDumps/VersionAxis.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift index 5e8ed630..8246f8da 100644 --- a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift @@ -8,6 +8,8 @@ import ObjCMetadataSource import ObjCIndexing import ObjCInterface import ObjCDiffing +import FoundationToolbox +import SwiftStdlibToolbox /// The platform a version axis spells availability for — what /// `evolution --interface --emit-available --platform` passes — each From 0037cf76e73239f1be49b6f05b99698ac3dd28fd Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:45:33 +0800 Subject: [PATCH 129/175] test(IntegrationTests): run the single-version interfaces through one interface dump InterfaceTestSuite replaces SwiftInterfaceBuilderTestSuite: each suite names its image and calls dump(.swiftInterface or .objcInterface, of:to:). The exported-only Xcode suite overrides one flag instead of restating the whole configuration, the reader suffix comes from asMachOImage, and AppKit's two suites also print the image's Objective-C header the way objc dump does. --- Package.swift | 6 +- .../InspectionDumps/InspectionDumpTests.swift | 15 +- .../InspectionDumps/InterfaceDumpTests.swift | 148 ++++++++++++++ .../InspectionDumps/InterfaceTests.swift | 120 +++++++++++ .../SwiftInterfaceBuilderTests.swift | 189 ------------------ 5 files changed, 281 insertions(+), 197 deletions(-) create mode 100644 Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift create mode 100644 Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift delete mode 100644 Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift diff --git a/Package.swift b/Package.swift index 4ee7eca5..a96a4e77 100644 --- a/Package.swift +++ b/Package.swift @@ -1528,8 +1528,10 @@ extension Target { .target(.SwiftSectionFixtureSupport), .product(.MachOKit), .product(.MachOObjCSection), - // The ObjC API evolution dumps run the `swift-section objc - // evolution` pipeline on MachOObjCSection's own modules. + // The Objective-C inspection dumps run the `swift-section objc + // dump`, `objc diff` and `objc evolution` pipelines on + // MachOObjCSection's own modules. + .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), .product(name: "ObjCDiffing", package: "MachOObjCSection"), .product(name: "ObjCIndexing", package: "MachOObjCSection"), .product(name: "ObjCInterface", package: "MachOObjCSection"), diff --git a/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift index 3a5f1e61..da06ec86 100644 --- a/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift @@ -75,15 +75,18 @@ extension InspectionDumpTests { .init(showCImportedTypes: false) } - /// Runs `prepare` and prints how long it took (unless running silently). - /// Callers pass the whole preparation step — for a diff that means - /// preparing *both* binaries — so the printed duration covers the real work. - func measuringPreparation(_ prepare: () async throws -> Void) async rethrows { + /// Runs `prepare`, prints how long it took (unless running silently) and + /// returns what it prepared. Callers pass the whole preparation step — + /// for a diff that means preparing *both* binaries — so the printed + /// duration covers the real work. + func measuringPreparation(_ prepare: () async throws -> Prepared) async rethrows -> Prepared { let clock = ContinuousClock() - let duration = try await clock.measure { try await prepare() } + let start = clock.now + let prepared = try await prepare() #if !SILENT_TEST - print(duration) + print(clock.now - start) #endif + return prepared } /// Prints a rendered dump to the console, unless running silently. diff --git a/Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift new file mode 100644 index 00000000..70bf2f77 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift @@ -0,0 +1,148 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDeclarationRendering +import Semantic + +/// The two single-version outputs, each the pipeline of one subcommand. +enum InterfaceDumpKind: Sendable { + /// `swift-section interface`: the image's Swift interface + /// (`-FileDump.swiftinterface`, or `-ImageDump.swiftinterface` for an + /// image read in process). + case swiftInterface + /// `swift-section objc dump`: every Objective-C declaration of the image + /// (`-ObjCFileDump.h` / `-ObjCImageDump.h`). + case objcInterface +} + +/// The single-version dumps: one image — a file, an image of a dyld shared +/// cache, or an image this process loaded — run through the pipelines of +/// `swift-section interface` and `swift-section objc dump`. +/// +/// A conforming suite inherits the `MachOTestingSupport` base class that +/// loads its image and passes that image to `dump(_:of:to:)`. Both outputs +/// print every comment the binary supports, so the dump carries as much as +/// the binary tells. Like its siblings this is a maintainer-inspection dump: +/// it prints / writes results without assertions. +protocol InterfaceDumpTests: InspectionDumpTests { + /// Whether both outputs print only what the image exports — what + /// `interface --exported-only` does, and the Objective-C header's + /// `printExportedDeclarationsOnly` option. A suite isolated to an actor + /// overrides it `nonisolated`. + var printsExportedDeclarationsOnly: Bool { get } +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InterfaceDumpTests { + var printsExportedDeclarationsOnly: Bool { false } + + var builderConfiguration: SwiftInterfaceBuilderConfiguration { + SwiftInterfaceBuilderConfiguration( + indexConfiguration: indexConfiguration, + printConfiguration: .init( + printStrippedSymbolicItem: true, + printFieldOffset: true, + printExpandedFieldOffsets: true, + printMemberAddress: true, + printVTableOffset: true, + printPWTOffset: true, + printExportedDeclarationsOnly: printsExportedDeclarationsOnly, + infersObjCOverridesFromSelectorNames: true, + usesModuleSelectors: true, + protocolRequirementPlacement: .associatedTypes, + memberSortOrder: .byOffset, + printTypeLayout: true, + printEnumLayout: true, + ), + ) + } + + /// Every comment an Objective-C declaration can carry: ivar offsets, + /// property attributes, method and accessor addresses. + var objcGenerationOptions: ObjCGenerationOptions { + var options = ObjCGenerationOptions.default + options.addIvarOffsetComments = true + options.addPropertyAttributesComments = true + options.addMethodIMPAddressComments = true + options.addPropertyAccessorAddressComments = true + options.printExportedDeclarationsOnly = printsExportedDeclarationsOnly + return options + } + + /// Runs one pipeline over `machO`, then prints the result, or writes it + /// named after the image and the reader that read it. + func dump( + _ kind: InterfaceDumpKind, + of machO: MachO, + to destination: DumpDestination + ) async throws { + let output: DumpOutput + switch kind { + case .swiftInterface: + output = try await swiftInterface(of: machO) + case .objcInterface: + output = try await objcInterface(of: machO) + } + try deliver(output, to: destination) { file in + try write(file.text, for: machO, suffix: file.suffix, fileExtension: file.fileExtension) + } + } + + /// `ImageDump` for an image read in process, `FileDump` for a file, so + /// the file name tells which reader produced it. + private func readerSuffix(of machO: some MachORepresentableWithCache) -> String { + machO.asMachOImage != nil ? "ImageDump" : "FileDump" + } + + /// The interface `swift-section interface` prints. The timed step is the + /// indexing; printing afterwards is not timed. + private func swiftInterface(of machO: MachO) async throws -> DumpOutput { + let builder = try SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + try await measuringPreparation { try await builder.prepare() } + let interface = try await builder.printRoot().string + return DumpOutput( + consoleText: interface, + files: [DumpFile(suffix: readerSuffix(of: machO), fileExtension: "swiftinterface", text: interface)] + ) + } + + /// Every Objective-C declaration of the image, the way `objc dump` + /// writes them to a file: classes, protocols, categories, structs and + /// unions in that order, each kind sorted by name — the index keeps its + /// names in dictionaries, whose order is not stable across runs — and a + /// blank line after each. + private func objcInterface(of machO: MachO) async throws -> DumpOutput { + let indexer = try await measuringPreparation { try await preparedObjCIndexer(of: machO) } + let builder = ObjCInterfaceBuilder(indexer: indexer, machO: machO) + let options = objcGenerationOptions + let declarationKinds: [(names: [String], interface: (String) -> SemanticString?)] = [ + (indexer.classNames.sorted(), { builder.classInterface(named: $0, options: options) }), + (indexer.protocolNames.sorted(), { builder.protocolInterface(named: $0, options: options) }), + (indexer.categoryNames.sorted(), { builder.categoryInterface(uniqueName: $0, options: options) }), + (indexer.structNames.sorted(), { builder.structInterface(named: $0, options: options) }), + (indexer.unionNames.sorted(), { builder.unionInterface(named: $0, options: options) }), + ] + var header = "" + for declarationKind in declarationKinds { + for name in declarationKind.names { + guard let interface = declarationKind.interface(name) else { continue } + header.append(interface.string) + header.append("\n\n") + } + } + return DumpOutput( + consoleText: header, + files: [DumpFile(suffix: "ObjC" + readerSuffix(of: machO), fileExtension: "h", text: header)] + ) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift b/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift new file mode 100644 index 00000000..50bf2423 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift @@ -0,0 +1,120 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import SwiftSectionTestingSupport +@testable import MachOSwiftSection + +/// Every single-version interface the maintainer inspects, one suite per +/// image source. A suite names its image once and dumps it through each +/// output it is read for, one test per output and destination. +/// +/// The suites are probes: point `cacheImageName`, `fileName` or `imageName` +/// at any image to look at it. AppKit's suites also print its Objective-C +/// header, the larger half of its API. +enum InterfaceTestSuite { + /// An image of this Mac's dyld shared cache. + class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + override class var cacheImageName: MachOImageName { .AppKit } + + override class var cachePath: DyldSharedCachePath { .current } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .console) + } + } + + /// The same image from an archived macOS cache, picked by version: point + /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` + /// that holds a cache. + class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + class var cacheVersion: String { "26.6" } + + override class var cachePath: DyldSharedCachePath { .macOS(cacheVersion) } + + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .console) + } + } + + /// A file on disk: by default the SymbolTestsCore fixture. + class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFile, to: .console) + } + } + + /// An image this process loaded, read in process. + class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + override class var imageName: MachOImageName { .SwiftUICore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOImage, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOImage, to: .console) + } + } + + /// A file inside Xcode, printed with only what it exports. + class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, InterfaceDumpTests { + override class var fileName: XcodeMachOFileName { .sharedFrameworks(.SourceEditor) } + + var printsExportedDeclarationsOnly: Bool { true } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFile, to: .console) + } + } +} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift deleted file mode 100644 index 8ad70c2f..00000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ /dev/null @@ -1,189 +0,0 @@ -@_spi(Support) @testable import SwiftDeclaration -@_spi(Support) @testable import SwiftIndexing -@_spi(Support) @testable import SwiftPrinting -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import Dependencies -@testable import MachOSwiftSection -@testable import SwiftSectionTestingSupport -import SwiftSectionFixtureSupport -@testable import SwiftInterface -@_spi(Internals) @testable import SwiftSymbols -@_spi(Internals) @testable import MachOCaches -import Semantic - -protocol SwiftInterfaceBuilderTests: InspectionDumpTests { - var builderConfiguration: SwiftInterfaceBuilderConfiguration { get } -} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftInterfaceBuilderTests { - var builderConfiguration: SwiftInterfaceBuilderConfiguration { - SwiftInterfaceBuilderConfiguration( - indexConfiguration: .init( - showCImportedTypes: false, - ), - printConfiguration: .init( - printStrippedSymbolicItem: true, - printFieldOffset: true, - printExpandedFieldOffsets: true, - printMemberAddress: true, - printVTableOffset: true, - printPWTOffset: true, - infersObjCOverridesFromSelectorNames: true, - usesModuleSelectors: true, - protocolRequirementPlacement: .associatedTypes, - memberSortOrder: .byOffset, - printTypeLayout: true, - printEnumLayout: true, - ), - ) - } - - private func makeBuilder(in machO: MachO) throws -> SwiftInterfaceBuilder { - let builder = try SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO) - builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) - return builder - } - - /// Builds the interface (timed) and returns the rendered source. The two - /// `@Test` entry points below only differ in where they send this string. - private func buildInterfaceString(in machO: some MachOFieldLayoutRenderable) async throws -> String { - let builder = try makeBuilder(in: machO) - try await measuringPreparation { try await builder.prepare() } - return try await builder.printRoot().string - } - - func buildString(in machO: some MachOFieldLayoutRenderable) async throws { - try await printResult(buildInterfaceString(in: machO)) - } - - func buildFile(in machO: some MachOFieldLayoutRenderable) async throws { - // Preserve the historical `-FileDump` / `-ImageDump` naming so the file - // tells you which reader produced it. - let suffix = machO is MachOImage ? "ImageDump" : "FileDump" - try await write(buildInterfaceString(in: machO), for: machO, suffix: suffix) - } -} - -enum SwiftInterfaceBuilderTestSuite { - class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { - .AppKit - } - - override class var cachePath: DyldSharedCachePath { - .current - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFileInCache) - } - } - - /// The same image from an archived macOS cache, picked by version: point - /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` - /// that holds a cache. - class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { - class var cacheVersion: String { - "26.6" - } - - override class var cachePath: DyldSharedCachePath { - .macOS(cacheVersion) - } - - override class var cacheImageName: MachOImageName { - .AppKit - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFileInCache) - } - } - - class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { - override class var fileName: MachOFileName { - .SymbolTestsCore - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFile) - } - } - - class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { - override class var imageName: MachOImageName { - .SwiftUICore - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOImage) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOImage) - } - } - - class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, SwiftInterfaceBuilderTests { - var builderConfiguration: SwiftInterfaceBuilderConfiguration { - SwiftInterfaceBuilderConfiguration( - indexConfiguration: .init( - showCImportedTypes: false, - ), - printConfiguration: .init( - printStrippedSymbolicItem: true, - printFieldOffset: true, - printExpandedFieldOffsets: true, - printMemberAddress: true, - printVTableOffset: true, - printPWTOffset: true, - printExportedDeclarationsOnly: true, - infersObjCOverridesFromSelectorNames: true, - usesModuleSelectors: true, - protocolRequirementPlacement: .associatedTypes, - memberSortOrder: .byOffset, - printTypeLayout: true, - printEnumLayout: true, - ), - ) - } - - override class var fileName: XcodeMachOFileName { - .sharedFrameworks(.SourceEditor) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFile) - } - } -} From 7ad356f5d52b5d47c1c87262ec0ce85219642b9e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:47:25 +0800 Subject: [PATCH 130/175] test(IntegrationTests): run the diffs over the shared version axes DiffTestSuite replaces SwiftDiffableInterfaceBuilderTestSuite. A diff reads the first and last version of the axis its base class supplies, so the two cache pairs now open each cache whole, the way the command line does. The Swift report also writes its JSON, and AppKit's two suites diff the Objective-C API through the objc diff pipeline. --- .../InspectionDumps/DiffDumpTests.swift | 157 +++++++++++ .../InspectionDumps/DiffTests.swift | 172 +++++++++++++ .../SwiftDiffableInterfaceBuilderTests.swift | 243 ------------------ 3 files changed, 329 insertions(+), 243 deletions(-) create mode 100644 Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift create mode 100644 Tests/IntegrationTests/InspectionDumps/DiffTests.swift delete mode 100644 Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift diff --git a/Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift new file mode 100644 index 00000000..b3bf6b86 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift @@ -0,0 +1,157 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import SwiftDiffing +import ObjCDiffing +import Semantic + +/// The three two-version outputs, each the pipeline of one subcommand. +enum DiffDumpKind: Sendable { + /// `swift-section diff` and `diff --json`: the change list with the + /// verdict line (`-Diff.txt`) and its machine-readable form + /// (`-Diff.json`). + case swiftReport + /// `swift-section diff --interface`: the new interface annotated with + /// inline `+`/`-` markers (`-AnnotatedInterface-Inline.swiftinterface`) + /// and as a unified diff (`-AnnotatedInterface-Unified.swiftinterface`); + /// the console prints the inline one. + case swiftInterface + /// `swift-section objc diff` and `objc diff --json`: the change list + /// with the verdict line (`-ObjCDiff.txt`) and its JSON + /// (`-ObjCDiff.json`). Objective-C has no annotated header for a diff. + case objcReport + + var language: MetadataLanguage { + switch self { + case .swiftReport, .swiftInterface: .swift + case .objcReport: .objc + } + } +} + +/// The diff dumps: the first and last version of a version axis — two +/// simulator runtimes, two dyld shared caches, two Xcodes — run through the +/// pipelines of `swift-section diff` and `swift-section objc diff`. A diff +/// reads each version's primary image: neither differ compares groups of +/// images. +/// +/// A conforming suite supplies the axis (`VersionAxisDumpTests`), usually by +/// inheriting one of the axis base classes and naming two versions. Like its +/// siblings this is a maintainer-inspection dump: it prints / writes results +/// without assertions. +protocol DiffDumpTests: VersionAxisDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension DiffDumpTests { + /// Runs one pipeline over the first and last version of this suite's + /// axis for the pipeline's language, then prints the result, or writes + /// it named after the new version's image. An axis left with fewer than + /// two versions carrying the metadata has nothing to compare: the dump + /// says so and writes nothing. + func dump(_ kind: DiffDumpKind, to destination: DumpDestination) async throws { + let axis = versionAxis(for: kind.language) + guard axis.versions.count >= 2, let oldVersion = axis.versions.first, let newVersion = axis.versions.last else { + printResult("No diff: \(axis.versions.count) version(s) carry the \(kind.language) metadata") + return + } + let output: DumpOutput + switch kind { + case .swiftReport: + output = try await swiftReport(old: oldVersion, new: newVersion) + case .swiftInterface: + output = try await swiftInterface(old: oldVersion, new: newVersion, rendersUnifiedDiff: destination == .file) + case .objcReport: + output = try await objcReport(old: oldVersion, new: newVersion) + } + try deliver(output, to: destination) { file in + try write(file.text, forImageGroup: [newVersion.primaryImage], suffix: file.suffix, fileExtension: file.fileExtension) + } + } + + // MARK: - Swift + + /// Both primary images indexed in one timed step — the differ needs both + /// sides before it can compare them, so the printed duration covers the + /// whole preparation. + private func preparedBuilders( + old oldVersion: AxisVersion, + new newVersion: AxisVersion + ) async throws -> (old: SwiftDiffableInterfaceBuilder, new: SwiftDiffableInterfaceBuilder) { + let oldBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: oldVersion.primaryImage.machOFile) + let newBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: newVersion.primaryImage.machOFile) + try await measuringPreparation { + try await oldBuilder.prepare() + try await newBuilder.prepare() + } + return (oldBuilder, newBuilder) + } + + /// The change list plus the one-line compatibility verdict, as + /// `swift-section diff` prints it, and the diff as `diff --json` writes + /// it. + private func swiftReport(old oldVersion: AxisVersion, new newVersion: AxisVersion) async throws -> DumpOutput { + let builders = try await preparedBuilders(old: oldVersion, new: newVersion) + let diff = ABIDiffer().diff(old: builders.old.abiModule(), new: builders.new.abiModule()) + let verdict = "ABI-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" + let report = ABIDiffReporter().report(diff) + "\n\n" + verdict + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "Diff", fileExtension: "txt", text: report), + DumpFile(suffix: "Diff", fileExtension: "json", text: String(decoding: try ABIJSON.encoder().encode(diff), as: UTF8.self)), + ] + ) + } + + /// The new interface annotated against the old, as `diff --interface` + /// prints it: with inline markers always, as a unified diff only when it + /// goes to a file — each form is a full print of its own. + private func swiftInterface( + old oldVersion: AxisVersion, + new newVersion: AxisVersion, + rendersUnifiedDiff: Bool + ) async throws -> DumpOutput { + let builders = try await preparedBuilders(old: oldVersion, new: newVersion) + let inlineInterface = await SwiftDiffableInterfaceRenderer(old: builders.old, new: builders.new) + .printAnnotatedInterface(format: .inline) + .string + var files = [DumpFile(suffix: "AnnotatedInterface-Inline", fileExtension: "swiftinterface", text: inlineInterface)] + if rendersUnifiedDiff { + let unifiedInterface = await SwiftDiffableInterfaceRenderer(old: builders.old, new: builders.new) + .printAnnotatedInterface(format: .unified()) + .string + files.append(DumpFile(suffix: "AnnotatedInterface-Unified", fileExtension: "swiftinterface", text: unifiedInterface)) + } + return DumpOutput(consoleText: inlineInterface, files: files) + } + + // MARK: - Objective-C + + /// The change list plus the verdict line, as `swift-section objc diff` + /// prints it, and the diff as `objc diff --json` writes it. Both sides + /// go through the persisted snapshot form, the way the command line reads + /// a binary. + private func objcReport(old oldVersion: AxisVersion, new newVersion: AxisVersion) async throws -> DumpOutput { + let documents = try await measuringPreparation { + let oldDocument = try await objcSnapshotDocument(of: oldVersion.primaryImage, label: oldVersion.label) + let newDocument = try await objcSnapshotDocument(of: newVersion.primaryImage, label: newVersion.label) + return (old: oldDocument, new: newDocument) + } + let diff = ObjCAPIDiffer().diff(old: documents.old, new: documents.new) + let verdict = "API-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" + let report = ObjCAPIDiffReporter().report(diff) + "\n\n" + verdict + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "ObjCDiff", fileExtension: "txt", text: report), + DumpFile(suffix: "ObjCDiff", fileExtension: "json", text: String(decoding: try ObjCAPIJSON.encoder().encode(diff), as: UTF8.self)), + ] + ) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/DiffTests.swift b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift new file mode 100644 index 00000000..028e4e38 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift @@ -0,0 +1,172 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection + +/// Every diff the maintainer inspects, one suite per pair of versions. A +/// suite names its two versions once and diffs them through each output it +/// is read for, one test per output and destination. The pairs come from the +/// version axis base classes the evolution suites read too (see +/// `VersionAxis.swift`); AppKit's suites also diff its Objective-C API, the +/// larger half of it. +enum DiffTestSuite { + /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5). + final class SwiftUICoreTests: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } + override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + } + + /// SwiftUI across two simulator runtimes (iOS 18.5 → 26.5). + final class SwiftUITests: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } + override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUI } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + } + + /// AppKit from two dyld shared caches (macOS 26.5.1 → 27.0), each opened + /// whole the way `swift-section --dyld-shared-cache` opens it. + /// Cross-image references resolve through each cache. + final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { [.macOS_26_5_1, .macOS_27_0] } + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + } + + /// The same image from two archived macOS caches, picked by version: + /// point the two versions at any directories under + /// `/Volumes/DyldSharedCaches/macOS` that hold a cache. + final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + class var oldCacheVersion: String { "26.6" } + class var newCacheVersion: String { "27.0" } + override class var cachePaths: [DyldSharedCachePath] { [.macOS(oldCacheVersion), .macOS(newCacheVersion)] } + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + } + + /// The DVTProductsUI shared framework across two installed Xcodes + /// (26.3.0 → 26.4.0). + final class XcodeFrameworkTests: CrossVersionXcodeFrameworkTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var oldXcodeVersion: String { "26.3.0" } + override class var newXcodeVersion: String { "26.4.0" } + override class var sharedFrameworkName: String { "DVTProductsUI" } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + } +} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift deleted file mode 100644 index 38d05b6e..00000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ /dev/null @@ -1,243 +0,0 @@ -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -@testable import SwiftInterface -@_spi(Support) @testable import SwiftIndexing -import SwiftDiffing -import Semantic - -/// The ABI-diff analogue of ``SwiftInterfaceBuilderTests``. -/// -/// Where the interface builder tests index *one* binary and render it, these -/// index a *pair* of binaries and run them through the diff pipeline: -/// `ABIDiffer` (the machine-readable change list) and -/// `SwiftDiffableInterfaceRenderer` (the full interface annotated with inline -/// `+`/`-` markers). Like its sibling it is a maintainer-inspection dump — it -/// prints / writes results without assertions. -protocol SwiftDiffableInterfaceBuilderTests: InspectionDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftDiffableInterfaceBuilderTests { - /// Builds and `prepare()`s both binaries in one timed step — the differ needs - /// both sides indexed before it can compare them, so the printed duration - /// covers the whole preparation. - private func preparedBuilders( - old: Old, - new: New, - ) async throws -> (old: SwiftDiffableInterfaceBuilder, new: SwiftDiffableInterfaceBuilder) { - let oldBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: old) - let newBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: new) - try await measuringPreparation { - try await oldBuilder.prepare() - try await newBuilder.prepare() - } - return (oldBuilder, newBuilder) - } - - /// The machine-readable change list plus the one-line compatibility verdict, - /// mirroring `swift-section diff`'s text report. - private func changeListReport( - old: SwiftDiffableInterfaceBuilder, - new: SwiftDiffableInterfaceBuilder, - ) -> String { - let diff = ABIDiffer().diff(old: old.abiModule(), new: new.abiModule()) - let verdict = "ABI-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" - return ABIDiffReporter().report(diff) + "\n\n" + verdict - } - - /// The full interface annotated with inline `+`/`-` markers, mirroring - /// `swift-section diff --interface`. - private func annotatedInterface( - old: SwiftDiffableInterfaceBuilder, - new: SwiftDiffableInterfaceBuilder, - format: DiffFormat = .inline, - ) async -> String { - await SwiftDiffableInterfaceRenderer(old: old, new: new).printAnnotatedInterface(format: format).string - } - - /// Console analogue of `buildString`: prepares both binaries, then prints the - /// change list and the annotated interface. - func diffString( - old: some MachOFieldLayoutRenderable, - new: some MachOFieldLayoutRenderable, - ) async throws { - let (oldBuilder, newBuilder) = try await preparedBuilders(old: old, new: new) - printResult(changeListReport(old: oldBuilder, new: newBuilder)) - await printResult(annotatedInterface(old: oldBuilder, new: newBuilder)) - } - - /// File analogue of `buildFile`: writes the change list (`-Diff.txt`) and the - /// annotated interface (`-AnnotatedInterface.swiftinterface`) next to the - /// single-binary interface dumps, both named after the *new* binary. - func diffFile( - old: some MachOFieldLayoutRenderable, - new: some MachOFieldLayoutRenderable, - ) async throws { - let (oldBuilder, newBuilder) = try await preparedBuilders(old: old, new: new) - try write(changeListReport(old: oldBuilder, new: newBuilder), for: newBuilder.machO, suffix: "Diff", fileExtension: "txt") - try await write(annotatedInterface(old: oldBuilder, new: newBuilder, format: .inline), for: newBuilder.machO, suffix: "AnnotatedInterface-Inline") - try await write(annotatedInterface(old: oldBuilder, new: newBuilder, format: .unified()), for: newBuilder.machO, suffix: "AnnotatedInterface-Unified") - } -} - -enum SwiftDiffableInterfaceBuilderTestSuite { - /// Loads a fixed `(old, new)` pair of `MachOFile`s by name — the two-binary - /// counterpart of `SwiftSectionTestingSupport.MachOFileTests`, which only loads one. - @TestActor - class CrossVersionMachOFileTests: Sendable { - let oldMachOFile: MachOFile - let newMachOFile: MachOFile - - class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - init() async throws { - self.oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.oldFileName)) - self.newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.newFileName)) - } - } - - /// Extracts the same image from two dyld shared caches — the two-binary, - /// two-cache counterpart of `SwiftSectionTestingSupport.DyldCacheTests`. The caches are - /// retained because the extracted `MachOFile`s resolve cross-image references - /// (into Foundation, libswiftCore, …) through them while indexing. - @TestActor - class CrossVersionDyldCacheImageTests: Sendable { - let oldCache: DyldCache - let newCache: DyldCache - let oldMachOFileInCache: MachOFile - let newMachOFileInCache: MachOFile - - class var oldCachePath: DyldSharedCachePath { .macOS_26_5_1 } - class var newCachePath: DyldSharedCachePath { .macOS_27_0 } - class var cacheImageName: MachOImageName { .AppKit } - - init() async throws { - let oldCache = try DyldCache(path: Self.oldCachePath) - let newCache = try DyldCache(path: Self.newCachePath) - self.oldCache = oldCache - self.newCache = newCache - self.oldMachOFileInCache = try #require(oldCache.machOFile(named: Self.cacheImageName)) - self.newMachOFileInCache = try #require(newCache.machOFile(named: Self.cacheImageName)) - } - } - - /// Loads the same shared framework from two installed Xcode applications. The - /// shared `XcodeMachOFileName` fixture hardcodes a single Xcode, so this loads - /// by path directly — the local-loading counterpart that lets the diff compare - /// two Xcode versions without changing the fixture. - @TestActor - class CrossVersionXcodeFrameworkTests: Sendable { - let oldMachOFile: MachOFile - let newMachOFile: MachOFile - - class var oldXcodeApplicationPath: String { "/Applications/Xcode-26.3.0.app" } - class var newXcodeApplicationPath: String { "/Applications/Xcode-26.4.0.app" } - class var sharedFrameworkName: String { "DVTProductsUI" } - - init() async throws { - self.oldMachOFile = try Self.loadSharedFramework(inXcodeAt: Self.oldXcodeApplicationPath) - self.newMachOFile = try Self.loadSharedFramework(inXcodeAt: Self.newXcodeApplicationPath) - } - - private class func loadSharedFramework(inXcodeAt xcodeApplicationPath: String) throws -> MachOFile { - let name = sharedFrameworkName - let binaryPath = "\(xcodeApplicationPath)/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" - return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) - } - } - - /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.2). - final class SwiftUICoreTests: CrossVersionMachOFileTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func `diff file`() async throws { - try await diffFile(old: oldMachOFile, new: newMachOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func `diff string`() async throws { - try await diffString(old: oldMachOFile, new: newMachOFile) - } - } - - /// SwiftUI across two simulator runtimes (iOS 18.5 → 26.2). - final class SwiftUITests: CrossVersionMachOFileTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUI } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFile, new: newMachOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFile, new: newMachOFile) - } - } - - /// The same macOS image (SwiftUI) extracted from two dyld shared caches - /// (macOS 15.5 → current). Cross-image references resolve through each cache. - final class DyldCacheTests: CrossVersionDyldCacheImageTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldCachePath: DyldSharedCachePath { .macOS_26_5_1 } - override class var newCachePath: DyldSharedCachePath { .macOS_27_0 } - override class var cacheImageName: MachOImageName { .AppKit } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFileInCache, new: newMachOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFileInCache, new: newMachOFileInCache) - } - } - - /// The same image from two archived macOS caches, picked by version: point - /// the two versions at any directories under `/Volumes/DyldSharedCaches/macOS` - /// that hold a cache. - final class ArchivedDyldCacheTests: CrossVersionDyldCacheImageTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - class var oldCacheVersion: String { "26.6" } - class var newCacheVersion: String { "27.0" } - override class var oldCachePath: DyldSharedCachePath { .macOS(oldCacheVersion) } - override class var newCachePath: DyldSharedCachePath { .macOS(newCacheVersion) } - override class var cacheImageName: MachOImageName { .AppKit } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFileInCache, new: newMachOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFileInCache, new: newMachOFileInCache) - } - } - - /// The DVTProductsUI shared framework across two installed Xcode versions - /// (26.3 → 26.4) — mirrors the framework the interface builder tests use, - /// loaded by path so the diff can compare two Xcodes. - final class XcodeFrameworkTests: CrossVersionXcodeFrameworkTests, nonisolated SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldXcodeApplicationPath: String { "/Applications/Xcode-26.3.0.app" } - override class var newXcodeApplicationPath: String { "/Applications/Xcode-26.4.0.app" } - override class var sharedFrameworkName: String { "DVTProductsUI" } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFile, new: newMachOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFile, new: newMachOFile) - } - } -} From ece64457c8adb1c1e92f07f6cf12e00bace93e32 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:49:18 +0800 Subject: [PATCH 131/175] docs: record the diff and interface suite merge in the ledger and the proposal --- ...diff-and-interface-integration-suites.html | 21 ++++++++++------ ...y-diff-and-interface-integration-suites.md | 25 +++++++++++-------- Documentations/Internal/ABIEvolutionDesign.md | 2 +- .../Internal/ProjectEvolutionLog.md | 14 +++++++++++ 4 files changed, 43 insertions(+), 19 deletions(-) diff --git a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html b/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html index 3ea77417..a0971f88 100644 --- a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html +++ b/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html @@ -163,7 +163,7 @@

      MachOSwiftSectionEvolutionsDraft

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

      -
      状态
      Accepted
      +
      状态
      In Progress
      最后更新
      2026-11-26
      项目类型
      库
      原文
      draft-unify-diff-and-interface-integration-suites.md
      @@ -199,7 +199,7 @@

      摘要

      要你定

      -

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

      +

      实现完成,待看过后收尾。以下是没问用户就采用的假设:

      1. ObjC 输出只加在 AppKit 的四个套件上;别的套件要看 ObjC,加一对一行测试即可。
      2. ObjC 头文件开满注释(ivar 偏移、属性特性、方法 IMP 地址、访问器地址),与 Swift 接口开满字段偏移、成员地址对齐。
      3. @@ -343,7 +343,7 @@

        一个 diff 测试的调用链

        objcReport — objcSnapshotDocument ×2 → ObjCAPIDiffer - deliver → write(forImageGroup: new.images) → -ObjCDiff.txt / .json + deliver → write(forImageGroup: [new.primaryImage]) → -ObjCDiff.txt / .json @@ -524,10 +524,10 @@

        影响

        落地步骤

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

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

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

      @@ -535,7 +535,7 @@

      落地步骤

      决策日志

      - 2 条,最近一条:Accepted + 7 条,最近一条:实现完成,待用户看过后收尾
      @@ -543,6 +543,11 @@

      决策日志

      + + + + +
      2026-11-26Created as Draft0110 合并演进套件后,用户要求把 diff 与单版本接口两类手检套件也按同样的结构统一。澄清一轮:两类都加上 ObjC 输出;diff 改用演进套件的版本轴(cache 对因此整份打开,与 CLI 一致);维护者未提交的接口套件实验不碰,照提交版重构,由维护者自己收掉。
      2026-11-26Accepted用户看过简报后批准,开始实现。
      2026-11-26In Progress:第 1 步开工功能分支从 next 切出,next 上已有本提案的 Accepted 提交。第 1 步首次在 Xcode 27.2 上编译时,VersionAxis.swift 缺 FoundationToolbox 与 SwiftStdlibToolbox 的导入(成员导入可见性检查),补了一个提交;Xcode 26.6 首次撞上已知的 no such module 'swift_section' 构建顺序竞态,第 2 步重跑通过。
      2026-11-26第 2、3 步完成measuringPreparation 改成泛型、返回准备好的值(详细设计原写不变):ObjC 头文件要在计时的一步里拿回索引器,ObjC diff 要拿回两份快照文档。diff 的文件名按新版本的主镜像起([newVersion.primaryImage]),不按整组镜像:diff 只读主镜像,单镜像时文件名与原来相同。带标注的接口两种格式各建一个渲染器,与现状一致。
      2026-11-26第 4 步完成ABIEvolutionDesign.md 的集成套件一段改成新目录并链接本提案;账本追加一节(节号落地时取)。只编译、没运行 IntegrationTests。
      2026-11-26收尾判断不配使用指南或实现说明:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。没有新术语:「版本轴」0110 已判断不登记。
      2026-11-26实现完成,待用户看过后收尾功能分支已推送,待在本地合进 .worktrees/MachOSwiftSection 的 next(不推送)。
      diff --git a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md b/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md index 85143968..e3dd6182 100644 --- a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md +++ b/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.md @@ -1,6 +1,6 @@ # Draft - IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-26 - **最后更新**: 2026-11-26 @@ -181,7 +181,7 @@ DiffTestSuite.DyldCacheTests.objcReportFile() │ │ └─ preparedObjCIndexer(of:) → ObjCAPISnapshotBuilder.snapshot() → JSON round trip │ ├─ ObjCAPIDiffer().diff(old:new:) │ └─ DumpOutput(console: report, files: [ObjCDiff.txt, ObjCDiff.json]) - └─ deliver(output, to: .file) → write(_:forImageGroup: new.images, …) + └─ deliver(output, to: .file) → write(_:forImageGroup: [new.primaryImage], …) ``` ## 详细设计 @@ -197,7 +197,7 @@ protocol InspectionDumpTests {} extension InspectionDumpTests { var rootDirectory: URL // unchanged: Documents/SwiftInterfaceTests var indexConfiguration: SwiftDeclarationIndexConfiguration { .init(showCImportedTypes: false) } - func measuringPreparation(_ prepare: () async throws -> Void) async rethrows // unchanged + func measuringPreparation(_ prepare: () async throws -> Prepared) async rethrows -> Prepared // now returns what it prepared func printResult(_ string: String) // unchanged func write(_:for:suffix:fileExtension:) throws // unchanged func write(_:forImageGroup images: [AxisImage], suffix:fileExtension:) throws @@ -221,7 +221,7 @@ struct DumpOutput: Sendable { let consoleText: String; let files: [DumpFile] } func preparedObjCIndexer(of machO: MachO) async throws -> ObjCInterfaceIndexer ``` -`BuildVersionCommand` 与 `Platform.stringValue` 的扩展原样搬来。`deliver` 让三类各自决定文件名怎么起:接口按 `write(_:for: machO…)`,diff 与演进按 `write(_:forImageGroup: newest.images…)`。 +`BuildVersionCommand` 与 `Platform.stringValue` 的扩展原样搬来。`deliver` 让三类各自决定文件名怎么起:接口按 `write(_:for: machO…)`,演进按 `write(_:forImageGroup: newest.images…)`,diff 按 `write(_:forImageGroup: [newVersion.primaryImage]…)`(diff 只读主镜像;单镜像时三种写法得到同一个文件名)。`measuringPreparation` 改成泛型、返回准备好的值:ObjC 头文件与 ObjC diff 要在计时的那一步里拿回索引器或快照文档。 ### `VersionAxis.swift` @@ -315,14 +315,14 @@ extension DiffDumpTests { } let output: DumpOutput = switch kind { … } try deliver(output, to: destination) { file in - try write(file.text, forImageGroup: newVersion.images, suffix: file.suffix, fileExtension: file.fileExtension) + try write(file.text, forImageGroup: [newVersion.primaryImage], suffix: file.suffix, fileExtension: file.fileExtension) } } } ``` - `swiftReport`:两个 `SwiftDiffableInterfaceBuilder` 在一个 `measuringPreparation` 里各 `prepare()`(与现状同);`ABIDiffer().diff(old: abiModule(), new: abiModule())`;正文 = 报告 + `\n\n` + 结论行;JSON = `ABIJSON.encoder().encode(diff)`。 -- `swiftInterface`:同样准备两个 builder;inline 必出,unified(`.unified()`,与现状相同的默认标签)只在去向是文件时渲染。 +- `swiftInterface`:同样准备两个 builder;inline 必出,unified(`.unified()`,与现状相同的默认标签)只在去向是文件时渲染。两种格式各建一个 `SwiftDiffableInterfaceRenderer`,与现状相同。 - `objcReport`:两边 `objcSnapshotDocument(of: version.primaryImage, label: version.label)`,`ObjCAPIDiffer().diff(old:new:)`,正文 = `ObjCAPIDiffReporter().report(diff)` + 结论行(`API-breaking: … · backward-compatible: …`,与 CLI 同),JSON = `ObjCAPIJSON.encoder().encode(diff)`。 ### 套件的样子 @@ -404,25 +404,25 @@ enum InterfaceTestSuite { 验证一律在 Ultra 上做(本机是公司那台,不编大工程):`queued-build swift build --build-tests`,scratch 用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-UnifyDiffAndInterfaceIntegrationSuites`,默认 Xcode 编一遍,再用 `DEVELOPER_DIR=…/Xcode-26.6.0.app`(CI 的版本)编一遍。第一次 26.6 构建若报 `no such module 'swift_section'`,是已知的构建顺序竞态,原样重跑。不运行 IntegrationTests。 -1. **公共骨架与版本轴**——`InspectionDumps/` 目录;`InspectionDumpTests.swift`、`VersionAxis.swift`、`EvolutionDumpTests.swift`、`EvolutionTests.swift` 移入并改名;两个旧文件只做机械改名以保持能编。 +1. **公共骨架与版本轴**(已完成,Ultra 上 Xcode 27.2 编过;26.6 首次撞上已知的构建顺序竞态,随第 2 步重跑通过)——`InspectionDumps/` 目录;`InspectionDumpTests.swift`、`VersionAxis.swift`、`EvolutionDumpTests.swift`、`EvolutionTests.swift` 移入并改名;两个旧文件只做机械改名以保持能编。 - 行为:`evolutionSuitesKeepTheirFortyThreeTestsAndOutputs` - 行为:`multiVersionCacheAxisStoresOneAxisPerLanguage` - 行为:`simulatorFilePairGivesItsOwnAxisLabeledByVersion` - 行为:`objcSnapshotDocumentIsSharedByDiffAndEvolution` -2. **接口一类**——`InterfaceDumpTests.swift`、`InterfaceTests.swift`;删除 `SwiftInterface/SwiftInterfaceBuilderTests.swift`;`Package.swift` 加 `ObjCDeclarationRendering`。 +2. **接口一类**(已完成,Ultra 上 Xcode 26.6 与 27.2 都编过,新文件没有警告)——`InterfaceDumpTests.swift`、`InterfaceTests.swift`;删除 `SwiftInterface/SwiftInterfaceBuilderTests.swift`;`Package.swift` 加 `ObjCDeclarationRendering`。 - 行为:`swiftInterfaceMatchesTodaysConfigurationAndFileName` - 行为:`exportedOnlySuiteOverridesOneFlagInsteadOfTheWholeConfiguration` - 行为:`objcInterfaceConcatenatesEveryKindInObjcDumpOrder` - 行为:`readerSuffixComesFromAsMachOImage` - 行为:`appKitInterfaceSuitesWriteBothLanguages` -3. **diff 一类**——`DiffDumpTests.swift`、`DiffTests.swift`;删除 `SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift`。 +3. **diff 一类**(已完成,Ultra 上 Xcode 26.6 与 27.2 都编过,新文件没有警告)——`DiffDumpTests.swift`、`DiffTests.swift`;删除 `SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift`。 - 行为:`diffCachePairOpensEachCacheWhole` - 行为:`swiftReportWritesChangeListAndJSON` - 行为:`swiftInterfaceRendersUnifiedOnlyForFiles` - 行为:`objcReportUsesTheObjCDifferAndVerdictLine` - 行为:`diffWithFewerThanTwoVersionsPrintsANoteAndWritesNothing` - 行为:`xcodePairIsPickedByVersion` -4. **文档**——`ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 +4. **文档**(已完成)——`ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 - 维护者比对(可选):挑 `InterfaceTestSuite.MachOFileTests.swiftInterfaceFile` 与 `DiffTestSuite.SwiftUICoreTests` 的两个 file 测试前后各跑一次,`diff` 输出;cache 对的 diff 预期可能因整份打开而不同。 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -436,3 +436,8 @@ enum InterfaceTestSuite { |------|------|------| | 2026-11-26 | Created as Draft | 0110 合并演进套件后,用户要求把 diff 与单版本接口两类手检套件也按同样的结构统一。澄清一轮:两类都加上 ObjC 输出;diff 改用演进套件的版本轴(cache 对因此整份打开,与 CLI 一致);维护者未提交的接口套件实验不碰,照提交版重构,由维护者自己收掉。 | | 2026-11-26 | Accepted | 用户看过简报后批准,开始实现。 | +| 2026-11-26 | In Progress:第 1 步开工 | 功能分支从 `next` 切出,`next` 上已有本提案的 Accepted 提交。第 1 步首次在 Xcode 27.2 上编译时,`VersionAxis.swift` 缺 `FoundationToolbox` 与 `SwiftStdlibToolbox` 的导入(成员导入可见性检查),补了一个提交;Xcode 26.6 首次撞上已知的 `no such module 'swift_section'` 构建顺序竞态,第 2 步重跑通过。 | +| 2026-11-26 | 第 2、3 步完成 | `measuringPreparation` 改成泛型、返回准备好的值(详细设计原写不变):ObjC 头文件要在计时的一步里拿回索引器,ObjC diff 要拿回两份快照文档。diff 的文件名按新版本的主镜像起(`[newVersion.primaryImage]`),不按整组镜像:diff 只读主镜像,单镜像时文件名与原来相同。带标注的接口两种格式各建一个渲染器,与现状一致。 | +| 2026-11-26 | 第 4 步完成 | `ABIEvolutionDesign.md` 的集成套件一段改成新目录并链接本提案;账本追加一节(节号落地时取)。只编译、没运行 IntegrationTests。 | +| 2026-11-26 | 收尾判断 | 不配使用指南或实现说明:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。没有新术语:「版本轴」0110 已判断不登记。 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 功能分支已推送,待在本地合进 `.worktrees/MachOSwiftSection` 的 `next`(不推送)。 | diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index d6393037..5f9db8c4 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -232,7 +232,7 @@ swift-section evolution ... \ 8. **兼容性推广**:逐转换 additive/breaking 与 `firstBreakingTransitionIndex`。 9. **reporter**:小型 evolution 的整段文本断言(确定性输出)。 -另有**维护者手检集成套件**,在 `Tests/IntegrationTests/Evolution/`(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行;Swift 与 ObjC 的报告和联合接口共用这一套,见提案 [0110-unify-evolution-integration-suites](../Evolutions/0110-unify-evolution-integration-suites.md)):每条版本轴一个套件,挂在 `EvolutionTestSuite` 下,各按读的元数据筛版本。报告的 `swiftReportFile` / `swiftReportString` 跑完整 pipeline——逐版本索引 → 冻结 → **经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘)。`SwiftUIDyldCacheTests` 对三份 macOS dyld cache(15.5 → 26.5.2 → 27.0)提取 SwiftUI;`SwiftUICoreSimulatorTests`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 diff 的 verdict 交叉核对行。 +另有**维护者手检集成套件**,在 `Tests/IntegrationTests/InspectionDumps/`(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行;Swift 与 ObjC 的报告和联合接口共用这一套,见提案 [0110-unify-evolution-integration-suites](../Evolutions/0110-unify-evolution-integration-suites.md);与单版本接口、两版本 diff 的手检套件同在一个目录、共用版本轴,见提案 [draft-unify-diff-and-interface-integration-suites](../Evolutions/draft-unify-diff-and-interface-integration-suites.md)):每条版本轴一个套件,挂在 `EvolutionTestSuite` 下,各按读的元数据筛版本。报告的 `swiftReportFile` / `swiftReportString` 跑完整 pipeline——逐版本索引 → 冻结 → **经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘)。`SwiftUIDyldCacheTests` 对三份 macOS dyld cache(15.5 → 26.5.2 → 27.0)提取 SwiftUI;`SwiftUICoreSimulatorTests`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 diff 的 verdict 交叉核对行。 ## 后续项(不在首轮范围) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 046c0bd4..0e580804 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3635,6 +3635,20 @@ - **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过。改前改后的输出是否逐字一致,待维护者挑一条轴比对。 - **对应版本**:未发布(只改测试目标)。 +## 2026-11-26 IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 + +- **时间段**:2026-11-26,本仓库的 `feature/unify-diff-and-interface-integration-suites`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译。 +- **动机**:0110 合并演进套件之后,单版本接口与两版本 diff 两类手检套件还各写各的。diff 自带三个「新旧两版」基类,读 cache 只开主文件,和演进套件、CLI 都不一样,`DyldCacheTests` 的注释写 SwiftUI、实际读 AppKit;接口套件为了开一个「只印导出声明」把整份配置抄了一遍,还用 `machO is MachOImage` 判读取器;两类都只出 Swift,AppKit 的 ObjC 部分只有演进套件看得到。 +- **关键决策**: + - 三类输出进同一个目录 `Tests/IntegrationTests/InspectionDumps/`,共用 `InspectionDumpTests`:输出目录、索引配置、计时、`DumpOutput` 与 `deliver`、泛型的 `preparedObjCIndexer`。 + - diff 与演进共用版本轴:diff 读轴上首尾两个版本的主镜像;cache 对改用 `MultiVersionDyldCacheImageTests`,整份打开;模拟器与 Xcode 两个两版基类搬进轴文件、各自给出轴;轴类型去掉 `Evolution` 前缀。 + - 单版本接口不走版本轴:它要读进程内的 `MachOImage`,而轴与演进构建器只收 `MachOFile`。 + - 每类一个输出种类枚举加一个 `dump` 入口。AppKit 的接口套件加整镜像的 ObjC 头文件(`objc dump` 的管线,四种注释全开),AppKit 的 diff 套件加 ObjC 变更列表与 JSON,Swift diff 报告加 JSON。套件类名保留(它们是维护者临时改读别的镜像的探针),测试名改成「种类 + 去向」;接口 14 个、diff 24 个,演进 43 个不变。 +- **落地模块**:`Tests/IntegrationTests/InspectionDumps/`(`InspectionDumpTests.swift`、`VersionAxis.swift`、`InterfaceDumpTests.swift`、`InterfaceTests.swift`、`DiffDumpTests.swift`、`DiffTests.swift`,以及从 `Evolution/` 移来的 `EvolutionDumpTests.swift`、`EvolutionTests.swift`);`Package.swift` 给 IntegrationTests 加 `ObjCDeclarationRendering`。删去 `SwiftInterface/SwiftInterfaceBuilderTests.swift`、`SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift`,`SwiftInterface/SwiftInterfaceTestSupport.swift` 移成 `InspectionDumpTests.swift`。 +- **文档**:提案 [draft-unify-diff-and-interface-integration-suites](../Evolutions/draft-unify-diff-and-interface-integration-suites.md);[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段改了目录。没有新术语,不另写使用指南或实现说明。 +- **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过,新文件没有警告。diff 的 cache 对改为整份打开,输出可能与改前不同;改前改后的比对待维护者做。 +- **对应版本**:未发布(只改测试目标)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 From 85e91fe14333cb09f718736a2fda80dfdbec7ded Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:53:36 +0800 Subject: [PATCH 132/175] test(IntegrationTests): read AttributeGraph with C-imported types and type-name resolution in the interface dump The interface dump suites print C-imported types and only exported declarations, register SwiftInterfaceBuilderTypeNameProvider for files (resolving dependencies through the system dyld shared cache), and the dyld cache suite reads AttributeGraph. --- .../SwiftInterface/SwiftInterfaceBuilderTests.swift | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift index 4d033d39..818402bf 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift @@ -1,4 +1,5 @@ @_spi(Support) @testable import SwiftDeclaration +import SwiftTypeNameResolution @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting import Foundation @@ -13,6 +14,7 @@ import SwiftSectionFixtureSupport @_spi(Internals) @testable import SwiftSymbols @_spi(Internals) @testable import MachOCaches import Semantic +import MachODependencies protocol SwiftInterfaceBuilderTests: SwiftInterfaceDumpTests { var builderConfiguration: SwiftInterfaceBuilderConfiguration { get } @@ -23,7 +25,7 @@ extension SwiftInterfaceBuilderTests { var builderConfiguration: SwiftInterfaceBuilderConfiguration { SwiftInterfaceBuilderConfiguration( indexConfiguration: .init( - showCImportedTypes: false, + showCImportedTypes: true, ), printConfiguration: .init( printStrippedSymbolicItem: true, @@ -32,12 +34,14 @@ extension SwiftInterfaceBuilderTests { printMemberAddress: true, printVTableOffset: true, printPWTOffset: true, + printExportedDeclarationsOnly: true, infersObjCOverridesFromSelectorNames: true, usesModuleSelectors: true, protocolRequirementPlacement: .associatedTypes, memberSortOrder: .byOffset, printTypeLayout: true, printEnumLayout: true, + ), ) } @@ -45,6 +49,9 @@ extension SwiftInterfaceBuilderTests { private func makeBuilder(in machO: MachO) throws -> SwiftInterfaceBuilder { let builder = try SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + if let machOFile = machO.asMachOFile { + builder.addExtraDataProvider(try #require(SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: .init(machO: machOFile, searchPaths: [.systemDyldSharedCache])))) + } return builder } @@ -71,7 +78,7 @@ extension SwiftInterfaceBuilderTests { enum SwiftInterfaceBuilderTestSuite { class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated SwiftInterfaceBuilderTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { - .AppKit + .AttributeGraph } override class var cachePath: DyldSharedCachePath { From 7fd4d0eb9a513bccd685f50702f1184044a6d020 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:53:36 +0800 Subject: [PATCH 133/175] chore(project): let Xcode autocreate scheme contexts in both workspaces --- .../xcshareddata/WorkspaceSettings.xcsettings | 8 ++++++++ .../xcshareddata/WorkspaceSettings.xcsettings | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 .swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings diff --git a/.swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/.swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..54782e32 --- /dev/null +++ b/.swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded + + + diff --git a/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings index 08de0be8..54782e32 100644 --- a/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ b/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -3,6 +3,6 @@ IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded - + From 2db688a1b1df131e6f9d6db303c1d0c97e6c04e4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 14:54:27 +0800 Subject: [PATCH 134/175] docs: land the diff and interface suite merge as proposal 0111 --- ...diff-and-interface-integration-suites.html} | 18 ++++++++++-------- ...y-diff-and-interface-integration-suites.md} | 10 ++++++---- Documentations/Evolutions/README.md | 2 +- Documentations/Internal/ABIEvolutionDesign.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 6 +++--- Documentations/README.md | 2 +- 6 files changed, 22 insertions(+), 18 deletions(-) rename Documentations/Evolutions/{draft-unify-diff-and-interface-integration-suites.html => 0111-unify-diff-and-interface-integration-suites.html} (95%) rename Documentations/Evolutions/{draft-unify-diff-and-interface-integration-suites.md => 0111-unify-diff-and-interface-integration-suites.md} (97%) diff --git a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html b/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.html similarity index 95% rename from Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html rename to Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.html index a0971f88..879ea606 100644 --- a/Documentations/Evolutions/draft-unify-diff-and-interface-integration-suites.html +++ b/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.html @@ -4,7 +4,7 @@ -Draft - IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 +0111 - IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 + + + +
      + +
      +

      MachOSwiftSectionEvolutionsDraft

      +

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

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

      摘要

      +

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

      +

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

      +

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

      +
      + +
      +

      要你定

      +
      +

      没有待定的事

      +

      第 5 步已由用户决定并入;提案已批准,正在实现。

      +
      +
      + +
      +

      提议方案

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

      架构图

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

      扫描一个函数时的分派

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

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

      + +

      CLI 的查询分支

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

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

      +
      + +
      +

      改动地图

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

      详细设计

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

      调研

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

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

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

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

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

      替代方案

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

      影响

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

      落地步骤

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

      收尾时要判断的两件事

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

      决策日志

      +
      + 4 条,最近一条:Accepted +
      +
      + + + + + + + + +
      日期变更说明
      2026-11-26Created as Draft按 2026-11-18 的方法补做 0097 落地时没做的全面核对:本库 90.3%、IDA 一次查询 97.0%。用户批准写一份提案修复测出的四处缺口,并把结果写进愿景
      2026-11-26第 5 步列为待定「取函数地址」不在这次测量的类别里,但决定调用链能不能穿过 block 与闭包;是否并入本提案由用户定
      2026-11-26第 5 步并入用户决定把「取函数地址记成对函数的引用」并入本提案,同批实现
      2026-11-26Accepted用户批准,开始实现。四个仓库各开 feature/cross-reference-recall-gaps,按依赖顺序 MachOKitExtensions → MachOObjCSection → 本库 → RuntimeViewer 提交;构建与测试都在 Ultra 上跑(四个工程都在公司那台不编译的清单里),用 /Volumes/DerivedData/Agents.noindex/claude/LocalDependencies/CrossReferenceRecallGaps/ 下按仓库名放的功能分支拷贝解析本地依赖
      +
      +
      +
      +
      + +
      +
      + + diff --git a/Documentations/Evolutions/draft-cross-reference-recall-gaps.md b/Documentations/Evolutions/draft-cross-reference-recall-gaps.md new file mode 100644 index 00000000..ef4c68c5 --- /dev/null +++ b/Documentations/Evolutions/draft-cross-reference-recall-gaps.md @@ -0,0 +1,392 @@ +# Draft - 交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-26 +- **最后更新**: 2026-11-26 +- **所属愿景**: [不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)(第 1 阶段的补漏) +- **关联提案**: [0097-offline-cross-references-and-symbolication](0097-offline-cross-references-and-symbolication.md)(离线交叉引用与这次复测的对象)、[0098-move-cross-reference-layers](0098-move-cross-reference-layers.md)(三层的归属)、RuntimeViewer [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)(界面与查询层) +- **实现分支 / PR**: `feature/cross-reference-recall-gaps`(MachOKitExtensions、MachOObjCSection、本库、RuntimeViewer 同名分支;worktree 为各仓库的 `.worktrees/<项目名>-CrossReferenceRecallGaps`) +- **配套文档**: 待定 —— 落地时判断;预计只更新三份模块文档,不另写 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +2026-11-26 在 Finder 26.5.2 与 ControlCenter 26.7 上按 2026-11-18 的方法复测交叉引用的召回:`swift-section refs` 0.25.0 找到 527 条代码引用里的 476 条(90.3%),IDA 一次查询 97.0%、两跳 99.4%。漏掉的 51 条里,13 条是按设计不报的 `__objc_superrefs` 载入,其余 38 条来自四处缺口:CLI 没有按 Swift 类型查的入口(27 条)、Swift 代码把 ObjC 类的 GOT 槽地址交给编译器生成的元数据辅助函数时不认类引用(8 条)、selector 只被当作参数用时不报(2 条)、一种 ivar 偏移的读法漏记(1 条)。本提案补齐这四处,改动跨 MachOKitExtensions(核心层)、MachOObjCSection(ObjC 层)、本库(Swift 层、门面与 CLI)和 RuntimeViewer(两处穷尽 switch),并把这次的测量脚本收进本库当验收工具:补完后同一组样本应到 514/527(97.5%),剩下的 13 条就是 `super` 的载入。第 5 步还把「取函数地址」记成对函数的引用——它不在这次测量的类别里,但决定了调用链能不能穿过 block 与闭包。 + +## 动机 + +完整动机见愿景《[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)》。这一步特有的部分: + +- **0097 落地时没有做全面核对。** 0097 决策日志 2026-11-19「第 4 步完成」一行只抽样了 ControlCenter 的 3 个函数,「全面核对没有重做」一段说明生成标准答案的脚本已经不在卷上。2026-11-26 从 2026-11-18 那次对比的对话记录里原样取回了标准答案与选目标的代码,复现出同一批 120 个目标,补做了这次核对(方法与数字见「前期调研」,结论写进了愿景「我们选的方向」第 1 条的复测段)。 +- **差距集中在几处可以修的地方,而不是扫描整体不行。** 导入函数、内部 `bl`、字符串三类与 IDA 一样全中;selector 发送(95/97)与类引用里的页对齐类对象还比 IDA 一次查询多中几条。漏报按原因归成五组,每组都有具体地址(见「前期调研」)。 +- **影响面比样本里的条数大。** + - GOT 槽地址那一组:ControlCenter 里有 554 处 `bl 0x10000b4a8`,每一处都把一个 ObjC 类的 GOT 槽地址放进 `x2`。这是 Swift 代码取 ObjC 类元数据的通用写法,Swift 为主的镜像里按类查引用会整批漏掉这一类。 + - Swift 类型那一组:经 CLI 工作的 agent 现在根本问不了「哪些代码用到了 Swift 类型 X」,只有 RuntimeViewer 的界面能问(Find 导航页的 Type References)。 + - selector 那一组:`respondsToSelector:` 的参数、返回 selector 的函数;`performSelector:`、target-action 的 `setAction:` 也是同一形态(推测,样本里没有抽到)。逆向时「谁把这个方法设成了按钮的 action」是常见问题。 + +## 前期调研 + +### 测量方法与复现 + +- **样本**:`/Volumes/RE/Finder/26.5.2/Finder`(ObjC 为主)与 `/Volumes/RE/ControlCenter/26.7/ControlCenter`(Swift 为主)的 arm64e 切片,UUID 分别是 `1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0`、`5782ED6B-471B-3CAC-9258-93734B6009C3`,与卷上两个 `.i64` 相同。 +- **标准答案**:不依赖任何一个被测工具,由 `otool -tV` 加独立的 `adrp` 寄存器跟踪、`dyld_info -fixups`、相对方法列表与 `__swift5_types` 解码生成。代码从 2026-11-18 那次对比的子 agent 对话记录(`~/.claude/projects/-Users-JH/4cad8a68-…/subagents/agent-a43f33e89a2f7bb07.jsonl` 的第 24、31、51、56 次工具调用)原样取回,只换了临时目录。 +- **复现核对**:两份标准答案的引用总数(511,138 与 359,773)、`__objc_stubs` 数(8,809 与 1,363)、各类目标列表与 2026-11-18 的输出逐项一致;按原打分规则(第 69 次工具调用)重算 IDA 一列,仍是 97.0% / 99.4%。所以这次的数字可以直接与那次比。 +- **查询**:每个目标调一次 `swift-section refs <文件> --json`(`--selector`、`--class`、`--symbol`、`--function`、`--string`、`--ivar`),共 128 次,零报错;Finder 单次中位 0.31 秒、ControlCenter 0.13 秒,都含建分析器的时间。外部类另加一次 `--symbol _OBJC_CLASS_$_<类>`,结果与只查 `--class` 相同,说明 `--class` 已经覆盖导入的类。 +- **脚本**:在 `/tmp/claude-xref-2026-11-26/scripts/`(`run_all.sh` 一条命令跑完,约 30 秒)。`/tmp` 会被系统清理,所以落地步骤第 0 步先把它们收进本库;万一已被清掉,可从 2026-11-26 那次会话的对话记录里取回(脚本都是用 Write 工具写的)。 + +### 分类别结果(两个镜像合计,代码引用) + +| 类别 | 标准答案 | IDA 一次 | IDA 两跳 | 本库 0.25.0 | +|---|---|---|---|---| +| A selector 发送 | 97 | 92 | 97 | 95 | +| B ObjC 类引用 | 87 | 76 | 84 | 66 | +| C 导入函数 | 91 | 91 | 91 | 91 | +| D 内部函数 `bl` | 70 | 70 | 70 | 70 | +| E 字符串 | 46 | 46 | 46 | 46 | +| F ivar(仅 Finder) | 32 | 32 | 32 | 31 | +| G Swift 元数据访问器(仅 ControlCenter) | 104 | 104 | 104 | 77 | +| 合计 | 527 | 97.0% | 99.4% | 90.3% | + +另有 49 条数据引用(方法表的 IMP、只在 vtable / 见证表里出现的函数、GOT 槽本身等),IDA 全中,本库按 0097 的非目标不做,记 0。本库多报 1 条:`0x1005273f8 ldr x0, [x20]`,是先 `adrp; add x20, ` 再经 `x20` 载入,标准答案的线性跟踪把这条引用记在 `add` 上,核对后是真引用。 + +### 51 条漏报的五组原因 + +1. **取访问器地址当函数指针用(27 条,G 类)。** 形如 ControlCenter `0x1000cd564`:`adrp x16, …; add x16, x16, #0xd38`(访问器 `0x1003e3d38`)→ `mov x17, #0x882f; pacia x16, x17; mov x1, x16`,把签过名的访问器地址交给调用方。分析器其实记下了:`refs --function=0x1000cd568 --callees` 显示 `0x1000cd568 reference addressMaterialization swiftType`(Swift 会话把访问器地址认领为类型引用,见 `CrossReferenceAnalysis.md`「Swift 类型引用」第 2 种来源)。漏在 CLI:`--function` 只返回调用者,而 `ReferencesRequest`(`Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift:262-310`)的六种主体里没有 Swift 类型。Swift 类型的引用表按描述符位置归档(`CodeReferenceTable.Key.swiftTypeDescriptor`),查询要经比对器 `references(toSwiftType:inImageAt:)`(`Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+SwiftTypes.swift:57`),不能像其它主体那样换成表键。 +2. **`__objc_superrefs` 的载入(13 条,B 类,按设计)。** Finder `0x1006604a0 ldr x8, [x8, #0x358]` 读的是 `__objc_superrefs` 的 `0x100b4b358`,随后 `stp x0, x8, [sp]` 拼出 `objc_super` 交给 `_objc_msgSendSuper2`。13 条全是这种。`CrossReferenceAnalysis.md`「类引用(第二批)」写明这一载入不算类引用(「报出来只会让每个调 `super` 的方法都『引用』了自己的类」),引用记成带类名的 `superMessageSend`。标准答案把 `__objc_superrefs` 算作类引用的槽(2026-11-18 的报告「经 `__objc_superrefs` 加载类对象,这类已并入 ground truth」)。 +3. **GOT 槽地址交给元数据辅助函数(8 条,B 类)。** ControlCenter `0x1006455c8`:`adrp x2, …; add x2, x2, #0x2a0`(`_OBJC_CLASS_$_OS_os_log` 的 GOT 槽 `0x10083a2a0`)→ `mov x0, #0; bl 0x10000b4a8`。`0x10000b4a8` 是编译器生成的共用辅助函数:`ldr x0, [x1]; cbnz …; ldr x0, [x2]; bl _objc_opt_self; bl _swift_getObjCClassMetadata; stlr x0, [x19]`——`x1` 是缓存变量,`x2` 是类的 GOT 槽。ControlCenter 里有 554 处调用它。核心层 `ReferenceScanner.noteAddress`(MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Scanning/ReferenceScanner.swift:366`)把数据段里的地址交给会话的 `recordAddressReference`,ObjC 会话只认类对象本身(MachOObjCSection `Sources/ObjCCodeReferences/ObjCCodeReferenceRecognizer.swift:305`),GOT 槽的地址不是类对象,于是什么都不记。读槽的入口 `noteSlotReference(fromSlot:at:)`(`ReferenceScanner.swift:441`)已经能解本镜像的 GOT、classref、cache 的共用 GOT 池与独立文件的 bind,只是取槽地址的路径没有走到它。IDA 也要两跳(2026-11-18 报告的 IDA 漏报第 2 条,同一个 `0x1006455cc`)。 +4. **selector 只当参数用(2 条,A 类)。** Finder `0x1003ee048`:`adrp x8, …; ldr x1, [x8, #0x6d0]`(`coalescingNodeObserver:openSyncCompleted:` 的 selref)→ `mov x0, x19; bl _objc_opt_respondsToSelector`;ControlCenter `0x100674e00`:`adrp x8, …; ldr x0, [x8, #0x378]; ret`,一个返回 selector `name` 的函数。ObjC 会话只在发送时从 `x1` 的来源槽读出 selector(`selectorInSelectorRegister`),它观察的槽只有 `__objc_superrefs` 与 `__objc_ivar`(`ObjCCodeReferenceRecognizer.swift:209`),没被发送用掉的 selref 载入什么都不留。`objc_opt_respondsToSelector` 作为 libobjc 的发送入口记成一次 `respondsToSelector:` 发送(`recordCallStandIn` 的 `.entryPoint`),`x1` 里那个作参数的 selector 被丢掉。 +5. **`adrp; add` 之后 `ldrsw [xN]` 读 ivar 偏移(1 条,F 类,原因待查)。** Finder `-[TTaskErrorOrConflictViewController setResolutionsForKind:]` 的 `0x1002bbb14`:`adrp x9, …; add x9, x9, #0x28; ldrsw x9, [x9]; str w8, [x0, x9]`(ivar `_rightResolution`)。同一个 ivar 在别的函数里的两处 `adrp; ldrsw [x8, #imm]` 都找到了,同一函数里别的 ivar 的 11 处也都找到了。读代码排除了几种可能:机器码 `d00047a9 9100a129 b9800129` 都在解码器覆盖内(`ARM64InstructionWord.wordLoad` 认 `0xB980_0000`,`addImmediate` 认 `0x9100_0000`);函数起点表里 `0x1002bba08`–`0x1002bbb28` 是一个函数;`RegisterFile.add` 对 `.address` 状态的源寄存器给出 `.address`。`0x1002bbb14` 是三条 `b` 的共同目标、又从上一条顺序落下,是汇合点——推测问题与汇合处的寄存器状态有关,未证实。第 4 步先写复现测试再定位。 + +### 赢过 IDA 的地方 + +- Finder 的三个页对齐类对象(`adrp; add #0x0`,如 `0x100131f8c`)IDA 漏,本库一次查到。 +- 经 `ldr` 读 selref 的经典发送,本库一次查到;IDA 要再查 selref 一跳(A 类 IDA 一次 92、本库 95)。 +- 不需要先建 IDA 库;单次查询 0.1–0.3 秒。 + +### 相关的现成能力 + +- RuntimeViewer 按类型查引用时用类型的 mangling(`RuntimeObject.name`,如 `7SwiftUI4TextV`)找描述符:`swiftTypeDescriptorLocations(withKey:inImageAt:)` → `swiftTypeIdentity(ofDescriptorAt:)` → 预筛 `imageIndices(referencingSwiftType:among:)` → 每个候选镜像 `references(toSwiftType:inImageAt:)`(RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift:300-380`)。CLI 照搬这条路即可,写法也与它一致。 +- 按名字定位符号:`locations(ofSymbolNamed:among:)`(`CrossReferenceAnalyzer+Linkage.swift:11`),查 `$s…Mn` 比逐镜像算 key 快得多。 +- 核心层的读槽、槽认领缓存(`slotClaims`)与导入名(`importedSlotNames`)都现成。寄存器表有按寄存器的标记(`RegisterFile.setTag` / `tag(of:)`,ObjC 会话用它标方法接收者),但打标记会把寄存器改成 `.tagged` 状态、丢掉地址(`RegisterFile.swift:83`),不能拿来标「已记过」;按寄存器的位掩码(`constantMask`、`blendedMask`)是现成的另一种写法。 +- 下游穷尽 switch:RuntimeViewer `CrossReferenceQuery.swift` 的 `switch reference.target`(`:92`、`:727`)与 `switch target`(`:949`)。0097 加三种新目标时的做法是在 RuntimeViewer 里补 case、先不显示(0097「源码兼容性」一节与决策日志 2026-11-19「第 8 步完成」)。 + +## 提议方案 + +1. **CLI 加 `--type`。** `swift-section refs --type ` 列出对一个 Swift 结构体、枚举或类的全部引用,写法与 RuntimeViewer 相同:类型的 mangling(`7SwiftUI4TextV`),也收它的描述符、访问器或元数据符号(`$s…Mn`、`$s…Ma`、`$s…N`,前面的 `_` 可有可无),去掉前后缀得到 mangling。定义它的镜像先按 `$sMn` 符号在全部镜像里找;找不到(缓存里的内部类型没有这个符号)时,独立文件逐个镜像按 key 找,dyld cache 要求用 `--type-image` 指定镜像,否则报错并提示。结果是这些身份在各候选镜像里的 `references(toSwiftType:inImageAt:)` 之并。 +2. **取到引用槽地址也算一次槽引用(核心层)。** `adrp; add` 或 `adr` 算出的地址如果正好落在引用槽上(本镜像的 GOT 与会话报的引用节,或 cache 的共用 GOT 池),就在这条指令上按读槽处理:走 `noteSlotReference(fromSlot:at:)`,路线记 `.pointerSlot`,由会话认出类,或在独立文件里记成导入符号。寄存器记下「已作为槽引用记过」,之后经它做零位移载入时不再重记,免得 `adrp; add; ldr [x]` 在同一处用法上记两行;寄存器里的地址照常保留,后面的发送仍能认出类字面量接收者。与语言无关,不写任何运行时名字。 +3. **selector 引用(ObjC 层)。** 查询里含 selector 键时,ObjC 会话也观察 `__objc_selrefs` 的载入:每次载入先记为待定;经典发送或 `super` 发送用 `x1` 里这个 selector 发送时,把它消掉;离开函数时,没被消掉的记成 selector 引用(新目标 `CodeReferenceTarget.selector(String)`,种类 `.reference`),归在已有的 `.selector` 表键下,`--selector` 因此同时返回发送与引用。libobjc 的发送入口(`objc_opt_respondsToSelector` 等)不消掉它,那里的 `x1` 是参数。核心层的会话协议加一个 `leaveFunction()`,默认什么都不做。经 `__objc_stubs` 的发送在代码里不载入 selref,不受影响。 +4. **ivar 读法(核心层)。** 先用夹具编出这段指令写复现测试,确认修复前失败,再定位、修复。 +5. **取函数地址记成对函数的引用(核心层)。** `adrp; add` 或 `adr` 算出的地址正好是本镜像函数表里的一个函数起点时,记一条 `.reference`,目标是 `.function(location)`,路线 `.addressMaterialization`;会话同时认领它(Swift 访问器)时两条都记。只在查询含函数键或建整表时找。`--function` 和 RuntimeViewer 的调用层级因此会列出取了它地址的代码:建栈上 block 的函数、把回调传给 `dispatch_async` / `CFRunLoop` 的函数、返回闭包的函数。这一步不在这次测量的类别里,用户决定并入(见决策日志)。 +6. **测量脚本进仓库,作为验收。** 收进 `Scripts/CrossReferenceRecall/`,`03_query_swift_section.py` 对 G 类改用 `--type`(mangling 取自访问器的符号名);落地时重跑,结果写回愿景。 + +### 非目标 + +- **`__objc_superrefs` 的载入不算类引用**:0097 定下的理由不变(见「替代方案考量」)。这 13 条是验收目标与 100% 之间的差。 +- **数据引用**(方法表的 IMP、vtable 与见证表里的函数、函数指针表、GOT 槽本身作为被引用者):愿景第 3 阶段。 +- **按点分隔的 Swift 名字查类型**(`ControlCenter.Foo`):要知道每一层的种类(结构体、类、枚举)才能拼出 mangling,先只收 mangling 与符号。 +- **RuntimeViewer 显示 selector 引用**:先在两处 switch 里补 case 并过滤掉,与 0097 处理新目标的做法一致;界面上怎么显示另提。第 5 步若并入,调用层级里取地址的行会和调用行一样显示,区分显示也另提。 +- **按辅助函数形状认 ObjC 类**(见「替代方案考量」)。 +- **x86_64**;**Binary Ninja 一列不重测**(2026-11-18 的结论是它经 MCP 只有 67.6%,不作参照)。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| 本库 `Scripts/CrossReferenceRecall/`(`01_prepare.sh`、`02a`–`02e`、`03_query_swift_section.py`、`04_score.py`、`run_all.sh`、`README.md`) | 新增 | 2026-11-26 的测量脚本;README 写样本路径、怎么跑、怎么读结果、基线数字 | 验收工具不能再丢 | 0 | +| 本库 `Scripts/CrossReferenceRecall/03_query_swift_section.py` | 修改 | G 类访问器改用 `--type`;可选 `--swift-section` 参数指定被测的二进制 | 第 1 步之后 G 类该走类型查询 | 1 | +| 本库 `Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift` · `CrossReferenceSubject` | 修改 | 加 `.swiftType(String, imageName: String?)`;`ResolvedQuery` 加按类型的查询分支;写法归一与定义镜像的查找 | `--type` 的库侧 | 1 | +| 本库 `Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift` · `CrossReferenceRequestError` | 修改 | 加 `swiftTypeNotFound(String)`、`swiftTypeNeedsImage(String)` | 找不到类型、缓存里的内部类型 | 1 | +| 本库 `Sources/Executables/swift-section/Commands/ReferencesCommand.swift` | 修改 | `--type`、`--type-image`;`validate()` 计入新主体;`--selector` 的帮助文字改成「发送与引用」 | CLI 入口 | 1、3 | +| 本库 `Sources/Executables/swift-section/…/CommandLineErrorTranslation` | 修改 | 两个新错误的措辞 | 用法错误照旧是退出码 64 | 1 | +| 本库 `Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift` | 修改 | `.selector` 目标的文字(`selector <名字>`)与 JSON(`{"selector": …}`) | 新目标的输出 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift` · `CodeReferenceTarget` | 修改 | 加 `case selector(String)` | selector 引用的目标 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift` | 修改 | `.selector` 目标归 `.selector` 键 | `--selector` 与 RuntimeViewer 的 selector 查询都能取到 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift` · `Target` | 修改 | 常驻索引加 `.selector` 组 | RuntimeViewer 常驻用的紧凑索引要能存 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift` · `ReferenceCollector` | 修改 | 实现 `recordSelectorReference`;`findsSelectorReferences`(键含 `.selector` 或建整表)传给 ObjC 会话;第 5 步实现 `recordFunctionAddressReference` 与开关 | 门面拼装 | 3、5 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Symbolication/AddressSymbolication.swift` | 修改 | selref 槽的含义从 `.messageSend(selector:receiver: .unknown)` 改为 `.selector` | 0097 第 6 步留的说明「目标类型里没有单独的 selector」不再成立 | 3 | +| 本库 `AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md`(及 `SKILL.md` 里列到 `refs` 选项的地方) | 修改 | `--type`、`--type-image`、selector 引用、取槽地址的类引用;第 5 步的取地址行 | 项目规定:改 CLI 同批改 skill | 1、3、5 | +| 本库 `README.md` 的 `refs` 一节 | 修改 | 加 `--type` 的例子 | 对外文档 | 1 | +| 本库 `Tests/SwiftSectionKitTests/…`(新文件 `ReferencesRequestSwiftTypeTests.swift`) | 新增 | `--type` 的解析、写法、错误 | 第 1 步行为 | 1 | +| 本库 `Tests/CrossReferenceAnalysisTests/…`(新文件 `SelectorReferenceTests.swift`、`SlotAddressReferenceTests.swift`,第 5 步 `FunctionAddressReferenceTests.swift`) | 新增 | 经门面的行为测试 | 各步行为 | 2、3、5 | +| 本库 `Documentations/Internal/Modules/CrossReferenceAnalysis.md` | 修改 | 引用种类、类引用、selector、`--type`、测试锚点;召回一节指向愿景 | 总说明 | 1–5 | +| 本库 `Documentations/Visions/ReverseEngineeringWithoutIDA.md` | 修改 | 复测段(本批已写);落地后补上修复后的数字 | 愿景是活文档 | 6 | +| MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Scanning/ReferenceScanner.swift` · `noteAddress` | 修改 | 落在引用槽上的地址改走 `noteSlotReference`;需要知道目标寄存器,签名加 `destination` | 第 2 步 | 2 | +| MachOKitExtensions `ReferenceScanner.swift` · `scanFunction` 的载入分支 | 修改 | 经已记过槽引用的寄存器做零位移载入时不重记 | 防重复 | 2 | +| MachOKitExtensions `ReferenceScanner.swift`(具体位置待第 4 步的测试定位) | 修改 | 修 ivar 漏记 | 第 4 步 | 4 | +| MachOKitExtensions `ReferenceScanner.swift` · `noteAddress` | 修改 | 落在函数起点的地址记成对函数的引用 | 第 5 步 | 5 | +| MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Scanning/RegisterFile.swift` | 修改 | 加一个按寄存器的位 `recordedSlotMask`:这个地址已作为槽引用记过;改写寄存器时清掉,汇合时比较 | 防重复,且不丢地址(现成的 `setTag` 会把地址状态覆盖掉) | 2 | +| MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Recognition/CodeReferenceRecognition.swift` · `CodeReferenceRecognitionSession` | 修改 | 加 `func leaveFunction()`,协议扩展给空实现;扫描器在每个函数扫完时调用 | selector 待定载入的冲刷点 | 3 | +| MachOKitExtensions `CodeReferenceRecognition.swift` · `CodeReferenceRecording` | 修改 | 加 `recordFunctionAddressReference(toFunctionAt:at:)` | 第 5 步 | 5 | +| MachOKitExtensions `Tests/MachOCodeReferencesTests/…`(新文件 `SlotAddressScanTests.swift`、`InstanceVariableMergePointTests.swift`) | 新增 | 用 `FixtureCompiler` 编带内联汇编的夹具,钉住指令序列 | 复现测试 | 2、4 | +| MachOKitExtensions `Documentations/Internal/MachOCodeReferences.md` | 修改 | 新契约与测试 | 实现说明 | 2、4、5 | +| MachOObjCSection `Sources/ObjCCodeReferences/ObjCCodeReferenceRecognizer.swift` · `ObjCCodeReferenceRecording` | 修改 | 加 `recordSelectorReference(selector:at:)` | 第 3 步 | 3 | +| MachOObjCSection `ObjCCodeReferenceRecognizer.swift` · 会话 | 修改 | `findsSelectorReferences` 开关;`watchedSlotRanges` 加 `selectorReferenceRange`;待定载入、发送消掉、`leaveFunction` 冲刷 | 第 3 步 | 3 | +| MachOObjCSection `Tests/ObjCCodeReferencesTests/…`(新文件 `SelectorReferenceRecognitionTests.swift`) | 新增 | ObjC 夹具:`respondsToSelector:`、`setAction:`、经典发送不重复 | 第 3 步 | 3 | +| MachOObjCSection `Documentations/Internal/ObjCCodeReferences.md` | 修改 | selector 引用的认法 | 实现说明 | 3 | +| RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift` | 修改 | `:92`、`:727`、`:949` 三处 switch 补 `.selector`(不显示);selector 查询结果滤掉 `.selector` 目标 | 穷尽 switch 会编译失败;界面先不变 | 3 | + +## 架构图 + +改了什么(扫描一个函数时的分派,`+` 新增,`~` 修改): + +```text +ReferenceScanner.scanFunction (MachOCodeReferences) +├── adrp/add/adr → noteAddress(address, destination) ~ takes the register +│ ├── + address in a reference slot (own GOT, classrefs, cache GOT pool) +│ │ → noteSlotReference(fromSlot:) → ObjC session: class │ file mode: imported symbol +│ │ → mark the register: slot address recorded (address kept) +│ ├── + address == a function start → recording.recordFunctionAddressReference (step 5) +│ └── other data → sessions.recordAddressReference (unchanged) +├── ldr/ldrsw [base, #d] → noteLoad / noteWatchedLoad +│ ├── + base marked as recorded slot address and d == 0 → skip (no second row) +│ └── ObjC session.noteWatchedSlotLoad +│ ├── __objc_ivar → ivar reference ~ step 4 fixes a miss +│ └── + __objc_selrefs → pending selector load +├── bl → ObjC session.recordCallStandIn +│ ├── classic / super send → messageSend + consumes the pending load behind x1 +│ └── entry point (objc_opt_respondsToSelector …) → send (x1 stays pending: an argument) +└── + function scanned → session.leaveFunction() + → ObjC: each pending load left → recordSelectorReference → target .selector(name), key .selector +``` + +CLI 的查询分支(`+` 新增): + +```text +swift-section refs (ReferencesCommand → SwiftSectionKit.ReferencesRequest) +├── --selector S → keys [.selector(S)] → sends + selector references (step 3) +├── --function A → keys [.function(loc), imported names] → calls (+ address-taking, step 5) +├── --class / --symbol / --ivar / --string (unchanged) +└── + --type T [--type-image I] + → normalize T: strip _ / $s prefix, Mn / Ma / N suffix → mangling key + → defining images: locations(ofSymbolNamed: "_$s" + key + "Mn") + else every image (files) │ else --type-image required (cache) + → swiftTypeDescriptorLocations(withKey:inImageAt:) → swiftTypeIdentity(ofDescriptorAt:) + → candidates: imageIndices(referencingSwiftType:among: scope) + → per candidate image: references(toSwiftType:inImageAt:) (union over identities) +``` + +## 详细设计 + +### 第 1 步:`--type` + +```swift +public enum CrossReferenceSubject: Sendable, Hashable { + // … the six existing cases … + /// A Swift struct, enum or class by its mangling — `7SwiftUI4TextV` — or a + /// `$s…Mn`, `$s…Ma` or `$s…N` symbol of it, defined in the image + /// `imageName` names, or in whichever image exports its descriptor. + case swiftType(String, imageName: String?) +} +``` + +```swift +// ReferencesCommand +@Option(name: .customLong("type"), help: "Every reference to the Swift struct, enum or class with this mangling (7SwiftUI4TextV), or to the one a $s…Mn, $s…Ma or $s…N symbol names.") +var swiftType: String? + +@Option(name: .customLong("type-image"), help: "The image that defines --type's type, by path or file name: needed in a dyld shared cache for a type no image exports.") +var swiftTypeImage: String? +``` + +- `validate()`:`--type` 计入「恰好一个主体」;`--type-image` 只能和 `--type` 一起用(与 `--function-image` 同样的报错写法)。 +- 写法归一:去掉前导 `_`,去掉前导 `$s`;末尾依次试 `Mn`、`Ma`、`N`,去掉后剩下的部分能 demangle 成一个名义类型才算数,否则当作原样的 mangling。名义类型的 mangling 以种类字母(`V`、`C`、`O`,`__C` 类型的 `a` 等)结尾,不会被误剥。 +- 找定义镜像:`--type-image` 给了就只在它里面找;否则 `locations(ofSymbolNamed: "_$s" + key + "Mn", among: 全部镜像)`;仍然没有时,独立文件逐个镜像 `swiftTypeDescriptorLocations(withKey:inImageAt:)`,dyld cache 抛 `swiftTypeNeedsImage`(逐镜像算 key 要几分钟)。macOS 与 Mac Catalyst 两个变体都定义时,两个身份都查,结果取并集。 +- 查询:`ResolvedQuery.Search` 加 `case swiftTypes([SwiftTypeIdentity], candidates: [Int])`;`run(output:)` 在候选镜像上并发调 `references(toSwiftType:inImageAt:)`,与 `.callers` 的并发写法相同(`ReferencesRequest.swift:142`)。`--in-image` 照旧限定扫描范围。 +- 输出:目标照已有的 `swiftType` / `swiftTypeName` / `objectiveCClass`(Swift 类也比它的 ObjC 类对象位置)格式输出,不新增格式。 + +### 第 2 步:取到引用槽地址 + +```swift +// ReferenceScanner (MachOCodeReferences) +private mutating func noteAddress(_ address: UInt64, builtInto destination: Int, at site: ScanSite, mayNameAString: Bool) { + if isReferenceSlot(address) { + noteSlotReference(fromSlot: address, at: site.reached(by: .pointerSlot)) + registers.markRecordedSlotAddress(of: destination) + return + } + // … unchanged … +} + +/// A slot of this image's GOT or of a session's reference sections, or one +/// of the GOT pool the shared cache keeps outside every image. +private func isReferenceSlot(_ address: UInt64) -> Bool +``` + +- `isReferenceSlot` 复用 `noteSlotReference` 开头的判断(`referenceSlotRanges` 与 `images.isSlotOutsideEveryImage`),两处共用一个私有函数,免得以后只改一处。 +- 载入分支:`load.displacement == 0` 且 `registers.isRecordedSlotAddress(load.base)` 时不调 `noteLoad`,寄存器照常更新(目标寄存器仍是 `.loadedFromSlot`,类字面量接收者照认)。 +- `RegisterFile` 的 `Contents` 加 `recordedSlotMask`,与 `constantMask` 同样处理:`overwrite` 清位,`Snapshot.agrees` 比较它,`meet` 不一致时清掉。不用现成的 `setTag`:它把寄存器改成 `.tagged` 状态,地址就没了(`RegisterFile.swift:83`)。 +- 只在 `looksForAddressReferences` 为真时做,与现状一致:只查 selector 或函数时不付这份代价。 + +### 第 3 步:selector 引用 + +```swift +// MachOObjCSection, ObjCCodeReferences +@_spi(Internals) public protocol ObjCCodeReferenceRecording: CodeReferenceRecording { + // … existing … + /// A load of the selector reference to `selector` that no send used: + /// the selector handed on as data — to `respondsToSelector:`, + /// `performSelector:`, a control's action. + func recordSelectorReference(selector: String, at site: ScanSite) +} +``` + +```swift +// MachOKitExtensions, MachOCodeReferences +@_spi(Internals) public protocol CodeReferenceRecognitionSession: AnyObject { + // … existing … + /// The scan is done with the function it last entered. + func leaveFunction() +} + +extension CodeReferenceRecognitionSession { + @_spi(Internals) public func leaveFunction() {} +} +``` + +```swift +// MachOSwiftSection, CrossReferenceAnalysis +public enum CodeReferenceTarget: Hashable, Sendable { + // … existing … + /// A selector the code loads but sends no message with: it hands the + /// selector on — to `respondsToSelector:`, `performSelector:`, a + /// control's action. + case selector(String) +} +``` + +- ObjC 会话:`findsSelectorReferences` 为真时 `watchedSlotRanges` 加上 `sections.selectorReferenceRange`(`ObjCImageSections` 已有这个字段)。`noteWatchedSlotLoad` 落在它上面时读出 selector 名,追加到 `pendingSelectorLoads: [(slot: UInt64, site: ScanSite)]`。 +- 消掉:`recordCallStandIn` 的 `.classicSend` 与 `.superSend` 分支取 `registers.slotAddress(of: 1)`,从 `pendingSelectorLoads` 末尾往前删掉第一个同槽的条目。`.entryPoint` 与 `.selector`(`__objc_stubs`)不删。 +- 冲刷:`leaveFunction()` 把剩下的逐条交给 `recordSelectorReference`,清空数组。`enterFunction` 也清一次,防扫描器提前返回时漏冲刷(`scanFunction` 的 `guard` 早退)。 +- 顺序:冲刷发生在函数末尾,所以一个函数里 selector 引用排在该函数的其它引用之后;收集器按地址排序后输出,不影响结果顺序(实现时核对 `ReferenceCollector` 是否排序,若不排则在冲刷前按地址插入)。 +- 门面:`ReferenceCollector.findsSelectorReferences` = 查询键含 `.selector`,或建整表。`recordSelectorReference` → `keep(.selector(selector), at: site)`;`CodeReferenceTable` 把它归在 `.selector(selector)` 键下。 +- 符号化:selref 槽的含义改为 `.selector(name)`(`AddressSymbolication.swift`),`swift-section symbolicate` 对 selref 槽的输出从 `send <名字>` 变成 `selector <名字>`。 + +### 第 4 步:ivar + +- 夹具:一个 ObjC 类,三个 ivar;一个方法用 `__asm__` 写出与 Finder `0x1002bba08` 同构的序列——前面几个分支 `b` 到同一个标签,标签处 `adrp x9, _OBJC_IVAR_$_…@PAGE; add x9, x9, _OBJC_IVAR_$_…@PAGEOFF; ldrsw x9, [x9]; str w8, [x0, x9]`。另写一个不经汇合点的对照方法。 +- 测试先红(经汇合点的那条找不到、对照那条找到),由此确认是汇合还是别的原因,再修。 + +### 第 5 步:取函数地址 + +```swift +// MachOKitExtensions, CodeReferenceRecording +/// Code built the address of the function at the unslid `address` — to call +/// it later, sign it and hand it on, or put it in a block. +func recordFunctionAddressReference(toFunctionAt address: UInt64, at site: ScanSite) +``` + +- `noteAddress` 里 `isCode` 且这个地址是函数起点时记一条;会话随后照常被问(Swift 会话认领访问器,两条都记)。开关 `recordsFunctionAddressReferences` 由门面按查询键(含 `.function`)或建整表给出。 +- 判断是不是函数起点:`ImageFunctionTable.functionIndex(containing:)`(`ImageFunctionTable.swift:249`)取到的函数起点等于这个地址。 +- 门面把它记成 `kind == .reference`、目标 `.function(location)`,归 `.function` 键。 + +## 替代方案考量 + +- **只让 `--function` 查访问器时也返回类型引用,不加 `--type`**:能补上这 27 条,但只覆盖访问器;泛型实例的访问器、按 mangled name 实例化、元数据地址这几种类型引用仍然问不到,而 RuntimeViewer 早已按类型查。否。 +- **GOT 槽地址按辅助函数的形状认**:在 Swift 层认出 `ldr x0, [x2]; bl objc_opt_self; bl swift_getObjCClassMetadata` 这种函数,在调用点从 `x2` 取类。更准,但只覆盖这一个辅助函数,还要 Swift 层认 libobjc 的名字;核心层按「地址落在引用槽」处理与语言无关,覆盖一切先取槽地址再用的写法。否。 +- **每次 selref 载入都记一条引用**:实现最简单,但经典发送(不走 `__objc_stubs` 的二进制)每次发送都会多一条同位置的引用行。否。 +- **selector 引用另开一个表键**:`--selector` 就要查两个键,RuntimeViewer 的 selector 查询也要改;归在同一键下、靠目标区分更省事,下游想只要发送时按目标过滤即可。否。 +- **把 `__objc_superrefs` 的载入报成类引用**:召回能到 100%、与 IDA 对齐,但每个调 `super` 的方法都会「引用」自己的类,按类查引用的结果会被这些行淹没(Foundation 1,803 处、AppKit 8,336 处 super 发送,见 `CrossReferenceAnalysis.md`「类引用」)。0097 的理由仍然成立。否。 +- **测量脚本放在 `/Volumes/RE` 或个人目录**:2026-11-18 那次就是这样丢的。进仓库、跟着交叉引用的代码走。否。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏**: + +- `CodeReferenceTarget` 加 `case selector(String)`:下游对它的穷尽 switch 编译失败。已知调用点是 RuntimeViewer `CrossReferenceQuery.swift` 的 `:92`、`:727`、`:949`。改法: + + ```swift + // before + switch reference.target { + case .function(let location): … + // … every case … + case .constantString(let characters): … + } + // after: one more case, shown as nothing for now + case .selector: + return nil + ``` + +- `CrossReferenceSubject`(SwiftSectionKit)加 `case swiftType`:本库以外没有使用方(RuntimeViewer 用自己的查询层)。 +- MachOKitExtensions 与 MachOObjCSection 的改动全在 `@_spi(Internals)` 接口上(`CodeReferenceRecognitionSession.leaveFunction` 有默认实现;`ObjCCodeReferenceRecording` 与 `CodeReferenceRecording` 各加一个要求,实现方只有本库的 `ReferenceCollector` 与 MachOKitExtensions 测试里的识别器)。SPI 不承诺稳定(`MachOCodeReferences.md`「接口只给 MachOSwiftSection 用」)。 +- 行为变化(不是编译错误):`--selector` 与 RuntimeViewer 按 selector 的查询多出 `.selector` 目标的行(RuntimeViewer 先滤掉);按类查引用多出取槽地址的行;`symbolicate` 对 selref 槽的说法变了;第 5 步若并入,`--function` 与调用层级多出取地址的行。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`CrossReferenceAnalysis`、`SwiftSectionKit`、`swift-section` 可执行文件,以及 `CrossReferenceAnalysisTests`、`SwiftSectionKitTests`。整表变大(多出取槽地址、selector 引用,第 5 步再多出取函数地址),`ScanThroughputBenchmarkTests` 要重量。 +- MachOKitExtensions(核心层)、MachOObjCSection(ObjC 层):同批改、同批发版。依赖顺序 MachOKitExtensions → MachOObjCSection → 本库。 +- RuntimeViewer:三处 switch;按 0097 的经验,本库 `next` 一合进新 case,RuntimeViewer 的 `next` 要同批跟上(它按本地路径依赖本库)。 +- MachOKitUI、REAgent:不用交叉引用(`grep` 过 `CrossReferenceAnalysis`、`ObjCCodeReferences`),不受影响。 + +### 文档与示例 + +- `README.md` 的 `refs` 一节、`AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md`。 +- 三份模块文档:本库 `Documentations/Internal/Modules/CrossReferenceAnalysis.md`、MachOKitExtensions `Documentations/Internal/MachOCodeReferences.md`、MachOObjCSection `Documentations/Internal/ObjCCodeReferences.md`。 +- 愿景的复测段,落地后补修复后的数字。 + +## API 演进与废弃策略 + +- 没有被替代的 API,不废弃任何东西。 +- 版本:本库 0.x 的下一个 minor(`CodeReferenceTarget` 新 case 按 0.x 惯例走 minor,0097 同样处理);MachOKitExtensions 下一个 minor(SPI 变化,但 MachOObjCSection 要求它的新版本);MachOObjCSection 下一个 minor。 + +## 落地步骤 + +0. **测量脚本进仓库** —— 改动地图第 1 行 + - 行为:`run_all.sh` 对 0.25.0 复现 476/527(90.3%),IDA 列 97.0% / 99.4%,复现核对通过 + - 行为:README 记下基线数字与每类的漏报原因,供以后对照 +1. **`--type`** —— 改动地图第 2–7、13–15 行 + - 行为:`typeSubjectFindsTheReferencesTheAnalyzersSwiftTypeQueryFinds`(与直接调 `references(toSwiftType:)` 的结果逐条相同,在进程内的 SwiftUICore 上) + - 行为:`typeSubjectAcceptsTheManglingAndItsDescriptorAccessorAndMetadataSymbols` + - 行为:`typeSubjectLooksForAnUnexportedTypeInEveryStandaloneFile` + - 行为:`typeSubjectInACacheNeedsTheTypeImageForAnUnexportedType`(报 `swiftTypeNeedsImage`,CLI 退出码 64) + - 行为:`typeImageWithoutTypeIsAUsageError` + - 行为:测量脚本 G 类改用 `--type` 后 104/104 +2. **取到引用槽地址也算槽引用** —— 改动地图第 19–20、22、26 行 + - 行为:`slotAddressHandedToAHelperIsAClassReference`(Swift 夹具引用一个 ObjC 类的元类型,生成同形的辅助函数调用) + - 行为:`slotAddressInAStandaloneFileIsAnImportedSymbolReference` + - 行为:`aLoadThroughARecordedSlotAddressIsNotRecordedAgain` + - 行为:`slotAddressesAddOnlySlotReferencesToTheWholeImageTable`(AppKit、SwiftUICore、Foundation 整表与改前比,多出的只有取槽地址的类引用) + - 行为:测量脚本 B 类 74/87(剩下的 13 条是 `super`) +3. **selector 引用** —— 改动地图第 6、8–12、23、25、28–32 行 + - 行为:`respondsToSelectorArgumentIsASelectorReference` + - 行为:`anActionSelectorHandedToSetActionIsASelectorReference` + - 行为:`aClassicSendLeavesNoSelectorReferenceBehind` + - 行为:`stubSendsLeaveNoSelectorReference` + - 行为:`selectorQueriesReturnSendsAndSelectorReferences` + - 行为:`selectorReferencesSurviveTheCompactIndex` + - 行为:`symbolicationCallsASelectorReferenceSlotASelector` + - 行为:RuntimeViewer `selectorReferencesAreNotShownYet` + - 行为:测量脚本 A 类 97/97 +4. **ivar 读法** —— 改动地图第 21、26–27 行 + - 行为:`instanceVariableLoadThroughAnAddedAddressAtAMergePoint`(修复前失败) + - 行为:`instanceVariableLoadThroughAnAddedAddressOutsideAMergePoint`(对照) + - 行为:测量脚本 F 类 32/32 +5. **取函数地址** —— 改动地图第 23–24 行及第 11、16 行的第 5 步部分 + - 行为:`takingAFunctionsAddressIsAReferenceToIt` + - 行为:`aSignedAccessorAddressIsBothAFunctionAndATypeReference` + - 行为:`aStackBlockIsReferencedByTheFunctionThatBuildsIt` + - 行为:`functionQueriesReturnCallsAndAddressTakingSites` +6. **验收与文档** —— 改动地图第 17–18 行与三份模块文档 + - 行为:测量脚本代码引用 ≥ 514/527(97.5%),多报为 0,或逐条核对为真引用 + - 行为:`ScanThroughputBenchmarkTests` 各项比改前慢不超过 5%(超过就把数字和原因写进模块文档,由用户定) + - 行为:愿景复测段补上修复后的数字 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不另写:调用方契约写进 CLI 的 skill 与 README,实现细节写进三份模块文档。 +- **有没有引入新术语** —— 「selector 引用」(selector 被载入但没有用来发送)可能要登记进 `Documentations/Glossary.md`;落地时判断。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-26 | Created as Draft | 按 2026-11-18 的方法补做 0097 落地时没做的全面核对:本库 90.3%、IDA 一次查询 97.0%。用户批准写一份提案修复测出的四处缺口,并把结果写进愿景 | +| 2026-11-26 | 第 5 步列为待定 | 「取函数地址」不在这次测量的类别里,但决定调用链能不能穿过 block 与闭包;是否并入本提案由用户定 | +| 2026-11-26 | 第 5 步并入 | 用户决定把「取函数地址记成对函数的引用」并入本提案,同批实现 | +| 2026-11-26 | Accepted | 用户批准,开始实现。四个仓库各开 `feature/cross-reference-recall-gaps`,按依赖顺序 MachOKitExtensions → MachOObjCSection → 本库 → RuntimeViewer 提交;构建与测试都在 Ultra 上跑(四个工程都在公司那台不编译的清单里),用 `/Volumes/DerivedData/Agents.noindex/claude/LocalDependencies/CrossReferenceRecallGaps/` 下按仓库名放的功能分支拷贝解析本地依赖 | diff --git a/Documentations/README.md b/Documentations/README.md index 0c1772bf..4c92560c 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -230,6 +230,7 @@ selects names using each access's offset and width. | [Evolutions/0109-consistent-c-imported-type-spelling.md](Evolutions/0109-consistent-c-imported-type-spelling.md) | **提案 0109(Implemented)**:C 导入类型的拼写补齐——0106 之后还剩两处混用:镜像里有描述符、Swift 名与 C 名相同的类型,声明写裸名而引用与扩展头写 `__C::`;展开字段偏移树的注释用固定的 `.default` 印类型名(C 名、点号限定、不带模块选择器与 `any`)。名字表收下没有 ABI 名的描述符(编译器只在两个名字不同时才写 ABI 名),引用改写裸名;interface 的布局注释经打印器自己的类型拼写印类型名,离线与进程内两条后端一起改,dump 不变。本镜像没有描述符的类型照旧写 `__C::`。 | | [Evolutions/0110-unify-evolution-integration-suites.md](Evolutions/0110-unify-evolution-integration-suites.md) | **提案 0110(Implemented)**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自重复定义同几条版本轴、互相借用对方的类属性,每条管线又把单镜像与镜像组写两遍。合成一套:`Tests/IntegrationTests/Evolution/` 下版本轴只定义一次、按读的元数据(`__swift5_*` / `__objc_*`)筛版本,四条管线收进一个协议,21 个套件类变成 10 个轴套件,43 个「轴 × 输出」组合与输出文件名不变。 | | [Evolutions/0111-unify-diff-and-interface-integration-suites.md](Evolutions/0111-unify-diff-and-interface-integration-suites.md) | **提案 0111(Implemented)**:IntegrationTests 的 diff 与单版本接口两类手检套件按 0110 的结构统一,三类输出(接口、diff、演进)进同一个目录 `Tests/IntegrationTests/InspectionDumps/`、共用一个公共协议;diff 改用演进的版本轴(cache 对因此整份打开,与 CLI 一致),每类一个「输出种类」枚举加一个 `dump` 入口;AppKit 的接口与 diff 套件多出 ObjC 头文件与 ObjC 变更列表。测试 20 个变 38 个,演进的 43 个不变。 | +| [Evolutions/draft-cross-reference-recall-gaps.md](Evolutions/draft-cross-reference-recall-gaps.md) | **提案 draft(Accepted)**:交叉引用召回补漏——2026-11-26 按 2026-11-18 的方法复测,`swift-section refs` 0.25.0 代码引用召回 90.3%(476/527),IDA 一次查询 97.0%;补四处缺口:CLI 加 `--type` 按 Swift 类型查询、取到 GOT 槽地址也算类引用、没被发送用掉的 selref 载入记成 selector 引用、一种 `adrp; add; ldrsw [xN]` 的 ivar 读法;第 5 步把取函数地址记成对函数的引用;测量脚本进 `Scripts/CrossReferenceRecall/` 作验收。跨 MachOKitExtensions、MachOObjCSection 与 RuntimeViewer | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Documentations/Visions/ReverseEngineeringWithoutIDA.md b/Documentations/Visions/ReverseEngineeringWithoutIDA.md index 3593fa4b..c47d8599 100644 --- a/Documentations/Visions/ReverseEngineeringWithoutIDA.md +++ b/Documentations/Visions/ReverseEngineeringWithoutIDA.md @@ -1,8 +1,8 @@ # 愿景:不依赖 IDA 的逆向 - **状态**: Active -- **最后更新**: 2026-11-19 -- **相关提案**: [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) +- **最后更新**: 2026-11-26 +- **相关提案**: [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md)、[draft-cross-reference-recall-gaps](../Evolutions/draft-cross-reference-recall-gaps.md)(召回补漏) 愿景**不做具体决定**,它划定一个方向的边界与取舍原则,让后续每个提案不必重新论证一遍。 具体怎么做写在各自的提案里。 @@ -135,6 +135,23 @@ (建库时间未计)。 - 没测到的:dyld shared cache 里的跨镜像引用。IDA 的弱点主要在这里(一个库只装得下几个镜像),而 Binary Ninja 的 MCP 又没法加载 cache 镜像,这一场景要用户在界面里手动加载后才能比。 + - **复测(2026-11-26):本方向的工具在同一组样本上,代码引用召回 90.3%(476/527);IDA 一次查询 97.0%、 + 两跳 99.4%。** + - 被测的是 `swift-section refs` 0.25.0(0097 之后交叉引用只有重构,行为与 `next` 相同),每个目标查一次。 + 标准答案与选目标的代码从 2026-11-18 那次的对话记录原样取回,复现出同一批 120 个目标;引用总数、目标列表与 + 当时逐项一致,IDA 一列按原规则重算仍是 97.0% / 99.4%,所以两次的数字可以直接比。 + - 分类别:导入函数(91)、内部 `bl`(70)、字符串(46)全中,与 IDA 持平;selector 发送 95/97(IDA 一次 + 92);ivar 31/32;ObjC 类引用 66/87(IDA 一次 76、两跳 84);Swift 元数据访问器 77/104(IDA 104)。 + 49 条数据引用按 0097 的非目标不做,记 0。多报 1 条,核对后是真引用。单次查询 0.1–0.3 秒,不用建库。 + - 漏掉的 51 条分五组:27 条是代码取了访问器的地址当函数指针用——分析器记成了 Swift 类型引用,但 CLI 没有 + 按类型查的入口;13 条是 `__objc_superrefs` 的载入,按设计不算类引用;8 条是 Swift 代码把 ObjC 类的 GOT + 槽地址交给编译器生成的元数据辅助函数(ControlCenter 里有 554 处这种调用);2 条是 selector 只当参数用 + (`respondsToSelector:`、返回 selector 的函数);1 条是 `adrp; add` 之后 `ldrsw [xN]` 读 ivar 偏移, + 原因待查。 + - 比 IDA 强的地方:页对齐的类对象、经 `ldr` 读 selref 的经典发送都一次查到。 + - 后四组缺口的修复是提案 + [draft-cross-reference-recall-gaps](../Evolutions/draft-cross-reference-recall-gaps.md),修完的目标是 + 514/527(97.5%),剩下的就是 `super` 的那 13 条。测量脚本随那份提案进仓库,以后改交叉引用就拿它验收。 2. **两个解码器分工。** 扫描整个 cache 的热路径用手写的 `ARM64InstructionDecoding`;给人和 agent 读的反汇编 文本、需要完整操作数语义的地方(跳转表、寄存器追踪)用 swift-capstone。两者之间用对拍测试保持一致: 同一批函数两边解码,结果逐条比。swift-capstone 因此要加大维护——拿 `otool -tV` 整镜像对拍正确性(重点是 @@ -197,6 +214,7 @@ |------|------|------------------------| | [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) | Implemented | 第 1 阶段:交叉引用与地址符号化扩展到磁盘文件和归档 cache,并接到 `swift-section` 与 RuntimeViewer 的 CLI / MCP;顺带把交叉引用按「我们选的方向」第 6 条拆成核心、ObjC、Swift 三层(真正迁出本库另写提案) | | [0098 move-cross-reference-layers](../Evolutions/0098-move-cross-reference-layers.md) | Accepted | 「我们选的方向」第 6 条:把 0097 拆出的核心层与地址解析、ARM64 解码搬进 MachOKitExtensions,ObjC 层搬进 MachOObjCSection,随本库 0.25.0 落地 | +| [draft-cross-reference-recall-gaps](../Evolutions/draft-cross-reference-recall-gaps.md) | Accepted | 第 1 阶段的补漏:按「我们选的方向」第 1 条的复测(2026-11-26,90.3% 对 IDA 97.0%)补上四处缺口——CLI 按 Swift 类型查询、取 GOT 槽地址的类引用、selector 引用、一种 ivar 读法,并把取函数地址记成对函数的引用;测量脚本进仓库作为第 7 条「标准答案」的验收工具 | --- From 5833eb9409be85c52d31614c30d2ba93bb80f3f8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:31:12 +0800 Subject: [PATCH 139/175] Expect a weak property's ivar to say ? Its weak storage is no type Objective-C represents as it is, so the compiler marks the ivar ? even for a class; the premise test now says so. --- .../ObjCImplementationInstanceVariableFactsTests.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift index 34b8eed3..6457f80a 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift @@ -30,7 +30,9 @@ struct ObjCImplementationInstanceVariableFactsTests { "buffer": "@\"NSMutableString\"", "previousLayout": "@\"\"", "identifier": "?", - "observer": "@\"NSObject\"", + // A `weak` property's storage is no type Objective-C represents + // as it is, so its ivar says `?` even for a class. + "observer": "?", "isAnimated": "B", "interactiveProgress": "d", "stepCount": "q", From d84944a2b10ee06b9eb0971a1943515c1fe22b34 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:31:27 +0800 Subject: [PATCH 140/175] Recover a stripped stored property's type from a complete ivar encoding An @objc @implementation stored property whose field-offset symbol is gone now prints as a declaration when its ivar carries a complete encoding, which the compiler only writes for a type Objective-C represents as it is: a class stays that class (implicitly unwrapped), a protocol is the existential, B/d/q are Bool/Double/Int, a structure keeps its name, and a readonly Objective-C property makes it a let. Blocks, pointers to structures, bit fields and unnamed structures stay comments, as does an ivar with no encoding. --- .../draft-objc-ivar-type-recovery.md | 8 +- .../SwiftObjCInterop/ObjCImportedTypes.swift | 78 +++++++++++++++++-- .../ObjCInstanceVariableSwiftType.swift | 15 +++- ...eclarationPrinter+ObjCImplementation.swift | 38 +++++++++ ...CImplementationClassRecognitionTests.swift | 74 +++++++++++++++++- .../ObjCInstanceVariableSwiftTypeTests.swift | 78 +++++++++++++++++++ 6 files changed, 276 insertions(+), 15 deletions(-) create mode 100644 Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index ddd924a8..14ccde1d 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -35,7 +35,7 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti 在 `SwiftObjCInterop` 加一个只依赖 ivar 事实与 ObjC 属性的还原函数,interface 与 dump 共用: 1. **encoding 完整**(非空、非 `?`):`ObjCTypeEncoding.type(from:)` 解析后按「原样表示」规则转成 `Type` 节点——与导入规则只差三处:桥接类保持类本身(`NSString` 还是 `NSString`),`id` 是 `AnyObject`,block / 位域 / 不认识的类型 / 无名结构体还原不出(返回 `nil`,保持注释)。 -2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);没有 ObjC 属性、或 `T` 是 block 等还原不出的类型,保持注释。 +2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);没有 ObjC 属性、或 `T` 是 block 等还原不出的类型,保持注释。`weak` 属性例外:`weak` 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 `?`,而 `weak` 只能是类,所以按「原样表示」规则读它的 `T` 特性,不桥接。 3. **空 encoding**:保持注释,二进制里没有任何类型信息。 4. **可空性**:可空的类型写 `T!`(ClangImporter 对无可空性标注的声明的写法,Generated Interface 也这样写);ObjC 属性是 `weak` 时写 `weak var x: T?`(`weak` 必为可选)。 5. **`var` / `let`**:有 ObjC 属性且是 `readonly` 写 `let`,否则 `var`——与已有的「存储属性按 setter 判 `var` / `let`」同一规则(`printThrowingObjCImplementationStoredProperty`)。 @@ -182,17 +182,18 @@ package struct ObjCInstanceVariableSwiftType { 1. **骨架**(已完成):`ObjCInstanceVariableSwiftType`(恒返回 `nil`)、`cTypeReplacements`、`SwiftPrinting` 依赖 `ObjCOutputTransformer`;夹具加 `AdaptiveTransitionWidget`,类集合断言跟上;前提测试。 - 行为:夹具的 `@objc @implementation` 类集合多出 `AdaptiveTransitionWidget`,其余输出不变。 - 行为:剥过符号后新类的 ivar 仍有名字与编译器写的 encoding,`@objc` 的都能对上 ObjC 属性。 -2. **完整 encoding 还原**:`triviallyRepresentedTypeNode`,interface 接入。 +2. **完整 encoding 还原**(已完成):`triviallyRepresentedTypeNode`,interface 接入。 - 行为:剥过符号的类类型 ivar 打成 `var x: Class!`。 - 行为:协议存在类型打成 `var x: (any P)!`。 - 行为:`B` / `d` / `q` 打成 `Bool` / `Double` / `Int`,结构体按结构体名。 - - 行为:`readonly` 的 ObjC 属性打 `let`,`weak` 的打 `weak var x: T?`。 + - 行为:`readonly` 的 ObjC 属性打 `let`。 - 行为:完整 encoding 的 `NSString` 不桥接成 `String`、`@` 是 `AnyObject`(单元测试;夹具造不出,见改动地图);夹具里不桥接的类用 `NSMutableString` 验。 - 行为:block、指向结构体的指针、位域、无名结构体还原不出。 - 行为:空 encoding 仍是注释。 3. **`?` 按 ObjC 属性还原**:`bridgedTypeNode`。 - 行为:`?` 且有 `NSString` 属性的打成 `String!`,`NSArray` 的打成 `[Any]!`,`id` 的打成 `Any!`。 - 行为:`?` 且没有 ObjC 属性的仍是注释。 + - 行为:`weak` 的 ObjC 属性打 `weak var x: T?`,类不桥接(`weak` 的存储让 ivar 写 `?`)。 4. **C 类型替换**:`applyTransformers(_: Transformer.ObjCConfiguration)`,打印时替换。 - 行为:配置 `double → CGFloat` 时 `d` 打成 `CGFloat`。 - 行为:没有配置或模块关闭时仍是 `Double`。 @@ -217,4 +218,5 @@ package struct ObjCInstanceVariableSwiftType { | 2026-11-26 | 开始实现 | 在 `feature/objc-ivar-type-recovery` 上按落地步骤做 | | 2026-11-26 | 还原结果存 `ObjCEncodedType`,不另设 `ObjCPrimitiveType` | `ObjCEncodedType` 在同一个包内可见,打印器直接对到 `Transformer.CType.Pattern`,少一个只为转一手的类型 | | 2026-11-26 | 夹具的 `CGFloat` 属性在 Swift 一侧写 `Double` | 夹具只 `import Foundation`,头文件的 `CGFloat` 导入成 `Double`,写 `CGFloat` 时 `@implementation` 的类型匹配报错 | +| 2026-11-26 | `weak` 属性挪到第 3 步,按 ObjC 属性读、不桥接 | 前提测试实测:`weak var observer: NSObject?` 的 ivar encoding 是 `?`,不是 `@"NSObject"` | | 2026-11-26 | 加前提测试 | 第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(`ObjCImplementationClassFacts.InstanceVariable.name` 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实 | diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift index bd7ee698..d5631622 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift @@ -20,6 +20,20 @@ package struct ObjCImportedTypes case closureComponent /// A result the error convention proves non-nil. case nonOptional + /// A `weak` property: `T?`, as `weak` requires an optional. + case weakStorage + } + + /// How an Objective-C type maps to a Swift one. + private enum Mapping { + /// As the importer imports a declaration: Foundation's bridged + /// classes become their Swift value types and `id` is `Any`. + case imported + /// As the Swift type behind an `@objc @implementation` ivar's complete + /// encoding, which the compiler only writes for a type Objective-C + /// represents as it is (evolution proposal `objc-ivar-type-recovery`): + /// no class is bridged and `id` is `AnyObject`. + case triviallyRepresented } /// The image the names are resolved in: a Swift class or protocol is @@ -32,15 +46,54 @@ package struct ObjCImportedTypes /// A `Type` node for `type` in `position`. package func typeNode(_ type: ObjCEncodedType, position: Position) -> Node { - let base = Self.type(bareTypeNode(type)) + typeNode(type, position: position, mapping: .imported) + } + + /// The Swift type of an `@objc @implementation` stored property whose + /// ivar carries the complete encoding `type` (evolution proposal + /// `objc-ivar-type-recovery`): the compiler writes one only for a type + /// Objective-C represents as it is, so `NSString` stays `NSString` and + /// `id` is `AnyObject`. `nil` for a type the encoding does not + /// determine: a block, whose signature no ivar encoding carries, a + /// pointer to a structure (a CF type reads the same), a bit field, an + /// unnamed structure, an array the importer cannot represent, or one the + /// reader does not know. + package func triviallyRepresentedTypeNode(_ type: ObjCEncodedType, position: Position) -> Node? { + guard Self.determinesStoredPropertyType(type) else { return nil } + return typeNode(type, position: position, mapping: .triviallyRepresented) + } + + private func typeNode(_ type: ObjCEncodedType, position: Position, mapping: Mapping) -> Node { + let base = Self.type(bareTypeNode(type, mapping: mapping)) guard Self.isNullable(type) else { return base } switch position { case .topLevel: return Self.implicitlyUnwrapped(base) - case .closureComponent: return Self.optional(base) + case .closureComponent, .weakStorage: return Self.optional(base) case .nonOptional: return base } } + /// Whether `type` names one Swift type a stored property can have. A + /// pointer does only to `void` or a scalar: the importer gives a pointer + /// to an object, a pointer or a structure a type of its own + /// (`AutoreleasingUnsafeMutablePointer`, an optional pointee, a CF class). + private static func determinesStoredPropertyType(_ type: ObjCEncodedType) -> Bool { + switch type { + case .void, .block, .bitField, .unknown: false + case .structure(let name), .union(let name): name != nil + case .array(_, let element): flattenedElementCount(of: type) != nil && determinesStoredPropertyType(element) + case .pointer(let pointee, _): pointee == .void || isScalar(pointee) + default: true + } + } + + private static func isScalar(_ type: ObjCEncodedType) -> Bool { + switch type { + case .bool, .character, .unsignedCharacter, .short, .unsignedShort, .int, .unsignedInt, .long, .unsignedLong, .longLong, .unsignedLongLong, .float, .double, .longDouble: true + default: false + } + } + /// `instancetype`, of unknown nullability, as an initializer's result: /// `Self!`. package static var initializerResultTypeNode: Node { @@ -59,7 +112,7 @@ package struct ObjCImportedTypes } /// The type itself, unwrapped: what a `Type` node holds. - private func bareTypeNode(_ type: ObjCEncodedType) -> Node { + private func bareTypeNode(_ type: ObjCEncodedType, mapping: Mapping = .imported) -> Node { switch type { case .void: return Node.createTransient(kind: .tuple) case .bool: return Self.swiftStructure("Bool") @@ -76,7 +129,7 @@ package struct ObjCImportedTypes case .characterString(let isConst): return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [Self.swiftStructure("Int8")]) case .selector: return Self.structure(module: "ObjectiveC", name: "Selector") case .objectClass: return Node.createTransient(kind: .typeAlias, children: [Self.module("Swift"), Node.createTransient(kind: .identifier, text: "AnyClass")]) - case .object(let className, let protocolNames): return objectNode(className: className, protocolNames: protocolNames) + case .object(let className, let protocolNames): return objectNode(className: className, protocolNames: protocolNames, mapping: mapping) case .block(let signature): guard let signature else { return Self.anyNode } return Node.createTransient(kind: .functionType, children: [ @@ -92,7 +145,7 @@ package struct ObjCImportedTypes // ClangImporter imports a pointer to what it cannot represent as // `OpaquePointer`. case .array where Self.flattenedElementCount(of: pointee) == nil: return Self.swiftStructure("OpaquePointer") - default: return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [bareTypeNode(pointee)]) + default: return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [bareTypeNode(pointee, mapping: mapping)]) } case .structure(let name), .union(let name): guard let name else { return Self.swiftStructure("OpaquePointer") } @@ -101,9 +154,9 @@ package struct ObjCImportedTypes // A C array imports as a tuple of its elements, a single element // as the element itself; one it cannot represent, as nothing. guard Self.flattenedElementCount(of: type) != nil else { return Self.anyNode } - if count == 1 { return bareTypeNode(element) } + if count == 1 { return bareTypeNode(element, mapping: mapping) } return Node.createTransient(kind: .tuple, children: (0 ..< count).map { _ in - Node.createTransient(kind: .tupleElement, child: Self.type(bareTypeNode(element))) + Node.createTransient(kind: .tupleElement, child: Self.type(bareTypeNode(element, mapping: mapping))) }) case .bitField, .unknown: return Self.anyNode @@ -132,9 +185,14 @@ package struct ObjCImportedTypes return flattenedCount } - private func objectNode(className: String?, protocolNames: [String]) -> Node { + private func objectNode(className: String?, protocolNames: [String], mapping: Mapping) -> Node { let protocols = protocolNames.map { Self.type(ObjCRuntimeNames.protocolNode(forRuntimeName: $0, in: machO)) } guard let className else { + // A bare `id` a Swift type represents as it is is `AnyObject`; + // the importer gives `Any`. + if mapping == .triviallyRepresented, protocols.isEmpty { + return Node.createTransient(kind: .protocolListWithAnyObject, child: Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList))) + } // `id`, `id

      `, `id`. return Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList, children: protocols)) } @@ -145,6 +203,10 @@ package struct ObjCImportedTypes Self.type(ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO)), ]) } + // A class a Swift type represents as it is is that class. + if mapping == .triviallyRepresented { + return ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO) + } if let bridged = ObjCBridgedStructures.structuresByClassName[className] { return Self.structure(module: bridged.module, name: bridged.name) } diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift index 06e25168..3b913099 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift @@ -41,6 +41,19 @@ package struct ObjCInstanceVariableSwiftType { /// synthesized on it (`ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`); /// `nil` when the Objective-C side does not say. package init?(instanceVariable: ObjCImplementationClassFacts.InstanceVariable, objcProperty: ObjCImplementationClassFacts.Property?, in machO: some MachOSwiftSectionRepresentableWithCache) { - return nil + let importedTypes = ObjCImportedTypes(machO: machO) + let isWeak = objcProperty?.isWeak ?? false + // An empty encoding: the property is not `@objc`, and nothing in the + // binary says what its type is. + guard instanceVariable.isObjCVisible else { return nil } + guard instanceVariable.typeEncoding != "?" else { return nil } + guard let encodedType = ObjCTypeEncoding.type(from: instanceVariable.typeEncoding), + let typeNode = importedTypes.triviallyRepresentedTypeNode(encodedType, position: isWeak ? .weakStorage : .topLevel) + else { return nil } + self.typeNode = typeNode + self.source = .instanceVariableEncoding + self.encodedType = encodedType + self.isReadOnly = objcProperty?.isReadOnly ?? false + self.isWeak = isWeak } } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift index 9042c736..85ac1e60 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift @@ -88,6 +88,12 @@ extension SwiftDeclarationPrinter { /// without renders as an honest comment naming what the binary does say /// (ObjC name, offset, size, encoding) rather than a fabricated type. /// + /// Before falling back to the comment, the Objective-C side is asked for + /// the Swift type: a complete ivar encoding is the Swift type itself, and + /// a `?` one the bridged form of the Objective-C property synthesized on + /// the ivar (`ObjCInstanceVariableSwiftType`, evolution proposal + /// `objc-ivar-type-recovery`). + /// /// `standIns` replace that comment with a declaration the Objective-C side /// gives, keyed by the ivar's identity: the Generated Interface prints the /// Objective-C property synthesized on the ivar as Swift imports it, @@ -126,6 +132,23 @@ extension SwiftDeclarationPrinter { Space() } await printType(typeNode.materialize(), isProtocol: false, level: level) + } else if let recoveredType = recoveredSwiftType(of: instanceVariable, in: extensionDefinition) { + SemanticString { + if recoveredType.isWeak { + Keyword(.weak) + Space() + Keyword(.var) + } else { + // A `readonly` Objective-C property over + // stored Swift storage was declared `let`. + Keyword(recoveredType.isReadOnly ? .let : .var) + } + Space() + MemberDeclaration(instanceVariable.name) + Standard(":") + Space() + } + await printRecoveredType(recoveredType, level: level) } else { comment(.note(Self.unrecoverableStoredPropertyComment(for: instanceVariable)), as: .note) } @@ -135,6 +158,21 @@ extension SwiftDeclarationPrinter { } } + /// The Swift type the Objective-C side gives `instanceVariable`, or `nil` + /// when it gives none. An unnamed ivar names no property to declare. + private func recoveredSwiftType(of instanceVariable: ObjCImplementationClassFacts.InstanceVariable, in extensionDefinition: ExtensionDefinition) -> ObjCInstanceVariableSwiftType? { + guard !instanceVariable.name.isEmpty, let facts = extensionDefinition.objcImplementation else { return nil } + let objcProperty = facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.name) + return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable, objcProperty: objcProperty, in: machO) + } + + /// A recovered type, through the configuration's C type replacements when + /// it is a C primitive one of them names. + @SemanticStringBuilder + private func printRecoveredType(_ recoveredType: ObjCInstanceVariableSwiftType, level: Int) async -> SemanticString { + await printType(recoveredType.typeNode, isProtocol: false, level: level) + } + static func unrecoverableStoredPropertyComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> String { let name = instanceVariable.name.isEmpty ? "" : instanceVariable.name return "stored property \(name): Swift type not recoverable (ObjC ivar, offset 0x\(String(instanceVariable.offset, radix: 16)), size \(instanceVariable.size), encoding \"\(instanceVariable.typeEncoding)\")" diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 5f79d958..1f27436e 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -111,15 +111,83 @@ struct ObjCImplementationClassRecognitionTests { let interface = try await interface(of: .strippedLocals) let widget = try #require(block(named: "@objc @implementation extension __C.Widget {", in: interface)) #expect(!widget.contains("inferred from ObjC class data")) - // No field-offset symbol survived, so the ivars render as honest - // comments — ObjC facts, no fabricated Swift type. + // No field-offset symbol survived. An ivar with a complete encoding + // takes the type Objective-C represents as it is (evolution proposal + // `objc-ivar-type-recovery`); the others render as honest comments — + // ObjC facts, no fabricated Swift type. #expect(widget.contains("// stored property title: Swift type not recoverable (ObjC ivar, offset 0x8, size 16, encoding \"?\")")) - #expect(widget.contains("// stored property count: Swift type not recoverable (ObjC ivar, offset 0x18, size 8, encoding \"q\")")) + #expect(widget.contains(" var count: Swift.Int\n")) + #expect(!widget.contains("stored property count")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable (ObjC ivar, offset 0x20, size 8, encoding \"\")")) #expect(widget.contains("// stored property hiddenTally: Swift type not recoverable (ObjC ivar, offset 0x28, size 8, encoding \"\")")) #expect(widget.contains("// stored property $__lazy_storage_$_summary: Swift type not recoverable (ObjC ivar, offset 0x30, size 16, encoding \"\")")) } + // MARK: - Stored property types the Objective-C side gives + + // Evolution proposal `objc-ivar-type-recovery`: `AdaptiveTransitionWidget`'s + // members are internal, so `strip -x` leaves only its ivar list and + // Objective-C properties. + + private func adaptiveTransitionWidget(of variant: ObjCImplementationFixture.Variant) async throws -> String { + let interface = try await interface(of: variant) + return try #require(block(named: "@objc @implementation extension __C.AdaptiveTransitionWidget {", in: interface)) + } + + /// What follows `var : ` or `let : ` on its line in `block`. + private func declaredType(of propertyName: String, in block: String) -> String? { + for line in block.split(separator: "\n") { + for introducer in ["var ", "let "] { + guard let range = line.range(of: "\(introducer)\(propertyName): ") else { continue } + return String(line[range.upperBound...]) + } + } + return nil + } + + @Test func strippedClassTypedIvarsRecoverTheClassImplicitlyUnwrapped() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" var containerView: __C.NSObject!\n"), "\(widget)") + // `NSMutableString` is no class Swift bridges. + #expect(widget.contains(" var buffer: __C.NSMutableString!\n"), "\(widget)") + #expect(!widget.contains("stored property containerView")) + } + + @Test func strippedProtocolTypedIvarRecoversTheExistentialImplicitlyUnwrapped() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" var previousLayout: (any __C.AdaptiveLayout)!\n"), "\(widget)") + } + + @Test func strippedScalarIvarsRecoverTheTypesTheirEncodingsName() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") + // `CGFloat` and `Double` encode alike; with no C type replacement the + // encoding's own type prints. + #expect(widget.contains(" var interactiveProgress: Swift.Double\n"), "\(widget)") + #expect(widget.contains(" var stepCount: Swift.Int\n"), "\(widget)") + // A structure prints as the field-offset symbol spells it. + let full = try await adaptiveTransitionWidget(of: .full) + let structureType = try #require(declaredType(of: "selectedRange", in: full)) + #expect(declaredType(of: "selectedRange", in: widget) == structureType, "\(widget)") + } + + @Test func readOnlyObjCPropertyRecoversAsALet() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" let revision: Swift.Int\n"), "\(widget)") + } + + @Test func ivarWithNoEncodingStaysAComment() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains("// stored property transitionAnimations: Swift type not recoverable (ObjC ivar, offset 0x"), "\(widget)") + #expect(!widget.contains("var transitionAnimations")) + } + + @Test func recoveredTypesHoldWithEveryObjCImplementationSymbolGone() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedEverything) + #expect(widget.contains(" var containerView: __C.NSObject!\n"), "\(widget)") + #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") + } + // MARK: - Inferred tier: no Swift symbol at all @Test func fullyStrippedImageIsRecognizedFromIvarEncodingsAndSaysSo() async throws { diff --git a/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift new file mode 100644 index 00000000..0621b092 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift @@ -0,0 +1,78 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import SwiftSectionFixtureSupport +@_spi(Internals) import Demangling +@testable import MachOSwiftSection +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// The Swift type behind an `@objc @implementation` ivar's encoding +/// (evolution proposal `objc-ivar-type-recovery`), checked encoding by +/// encoding against AppKit loaded into the test process, which only serves as +/// the image class names are looked up in. +@Suite +struct ObjCInstanceVariableSwiftTypeTests { + private static func appKit() throws -> MachOImage { + _ = dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", RTLD_NOW) + return try #require(MachOImage(named: .AppKit)) + } + + private static func instanceVariable(encoding: String) -> ObjCImplementationClassFacts.InstanceVariable { + ObjCImplementationClassFacts.InstanceVariable(name: "storage", offset: 8, size: 8, alignment: 8, typeEncoding: encoding, swiftFieldOffsetSymbolName: nil, swiftPropertyName: nil, swiftTypeNode: nil) + } + + /// The printed type recovered from an ivar with `encoding`, or `nil`. + private static func recoveredType(encoding: String, propertyAttributes: String? = nil) throws -> String? { + let objcProperty = propertyAttributes.map { ObjCImplementationClassFacts.Property(name: "storage", attributes: $0) } + return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable(encoding: encoding), objcProperty: objcProperty, in: try appKit()) + .map { $0.typeNode.print(using: .interface) } + } + + @Test func completeEncodingOfABridgeableClassKeepsTheClass() throws { + // A Swift `NSString` property: the compiler writes `@"NSString"` only + // because the type is the class itself, never for a `String`. + #expect(try Self.recoveredType(encoding: "@\"NSString\"") == "__C.NSString!") + #expect(try Self.recoveredType(encoding: "@\"NSArray\"") == "__C.NSArray!") + } + + @Test func completeEncodingOfABareIdIsAnyObject() throws { + #expect(try Self.recoveredType(encoding: "@") == "Swift.AnyObject!") + } + + @Test func completeEncodingOfAProtocolIsTheExistential() throws { + #expect(try Self.recoveredType(encoding: "@\"\"") == "(any __C.NSCopying)!") + } + + @Test func scalarEncodingsNameTheirSwiftTypes() throws { + #expect(try Self.recoveredType(encoding: "B") == "Swift.Bool") + #expect(try Self.recoveredType(encoding: "d") == "Swift.Double") + #expect(try Self.recoveredType(encoding: "q") == "Swift.Int") + #expect(try Self.recoveredType(encoding: "^d") == "Swift.UnsafeMutablePointer!") + } + + @Test func encodingsThatDoNotDetermineATypeRecoverNothing() throws { + // A block's signature is in no ivar encoding. + #expect(try Self.recoveredType(encoding: "@?") == nil) + // A CF type and a pointer to a structure encode alike. + #expect(try Self.recoveredType(encoding: "^{CGColor=}") == nil) + #expect(try Self.recoveredType(encoding: "{?=ii}") == nil) + #expect(try Self.recoveredType(encoding: "b3") == nil) + #expect(try Self.recoveredType(encoding: "") == nil) + } + + @Test func weakPropertyIsOptional() throws { + #expect(try Self.recoveredType(encoding: "@\"NSObject\"", propertyAttributes: "T@\"NSObject\",W,N,Vstorage") == "__C.NSObject?") + } + + @Test func readOnlyAndWeakAreReadOffTheObjCProperty() throws { + let appKit = try Self.appKit() + let readOnly = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "q"), objcProperty: .init(name: "storage", attributes: "Tq,R,N,Vstorage"), in: appKit)) + #expect(readOnly.isReadOnly) + #expect(!readOnly.isWeak) + #expect(readOnly.source == .instanceVariableEncoding) + let settable = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "q"), objcProperty: nil, in: appKit)) + #expect(!settable.isReadOnly) + } +} From efd6c54012f989b009c848582e99f3bb3e31b370 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:32:52 +0800 Subject: [PATCH 141/175] Call the encoding parser by its name --- .../Evolutions/draft-objc-ivar-type-recovery.md | 8 ++++---- .../SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index 14ccde1d..0ffc4d81 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -25,7 +25,7 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti - **编译器怎么写 ivar 的 encoding**:`swift/lib/IRGen/GenClass.cpp` 的 `buildIvar`(约 2083–2096 行):只有 `varDecl->isObjC() && varDecl->hasStorage()` 才写 encoding;类型 `isTriviallyRepresentableIn(ForeignLanguage::ObjectiveC, …)` 时调 `getObjCEncodingForPropertyType`,否则写 `"?"`(注释原文:「"Unknown type" - used when ObjC classes are bridged to separate Swift types」);不是 `@objc` 的存储属性 encoding 为空串。`isTriviallyRepresentableIn`(`lib/AST/Type.cpp` 3481 行)对 `Trivial` 与 `Object` 返回 true,对 `Bridged` / `BridgedError` / `StaticBridged` / `None` 返回 false。 - **encoding 与 ObjC 属性的 `T` 特性是同一个函数算的**:`getObjCEncodingForPropertyType`(`lib/IRGen/GenObjC.cpp` 1267 行)取 getter 的 foreign 结果类型对应的 clang 类型,交给 clang 的 `getObjCEncodingForPropertyType`;属性表的 `T` 特性也走它(`GenClass.cpp` 2192 行)。所以 encoding 为 `?` 的 ivar,它的 ObjC 属性 `T` 特性给的是桥接后的 ObjC 类型(`T@"NSString"`)。 - **encoding 不带的信息**:可空性(`UIView` / `UIView?` / `UIView!` 都是 `@"UIView"`)、typedef(`CGFloat`、`NSTimeInterval` 都是 `d`,`NSInteger` 与 `Int` 都是 `q`)、`NSArray` 等的泛型参数(`T@"NSArray"`)、block 的签名(ivar 与属性都只写 `@?`)。 -- **已有的转换**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift` 的 `ObjCImportedTypes.typeNode(_:position:)` 按 ClangImporter 的规则把 `ObjCEncodedType` 转成 `Type` 节点:桥接类(`ObjCBridgedStructures`、`NSArray` / `NSDictionary` / `NSSet` / `NSError`)转值类型,`id` 转 `Any`,可空的对象类型转 `T!`,类名经 `ObjCRuntimeNames.classNode(forRuntimeName:in:)` 找 Swift 类、找不到就是 `__C.`;`__C` 名在打印时经 C 导入类型名改写(0106,接 swift-type-indexing 的 SDK 索引)换成 Swift 名。`ObjCTypeEncoding.type(from:)` 与 `propertyType(fromAttributes:)` 解析 encoding 与 `T` 特性(`ObjCTypeEncoding.swift` 115–132 行)。 +- **已有的转换**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift` 的 `ObjCImportedTypes.typeNode(_:position:)` 按 ClangImporter 的规则把 `ObjCEncodedType` 转成 `Type` 节点:桥接类(`ObjCBridgedStructures`、`NSArray` / `NSDictionary` / `NSSet` / `NSError`)转值类型,`id` 转 `Any`,可空的对象类型转 `T!`,类名经 `ObjCRuntimeNames.classNode(forRuntimeName:in:)` 找 Swift 类、找不到就是 `__C.`;`__C` 名在打印时经 C 导入类型名改写(0106,接 swift-type-indexing 的 SDK 索引)换成 Swift 名。`ObjCTypeEncodingParser.type(from:)` 与 `propertyType(fromAttributes:)` 解析 encoding 与 `T` 特性(`ObjCTypeEncoding.swift` 115–132 行)。 - **现状的渲染路径**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift` 的 `renderUnrepresentedObjCImplementationInstanceVariables`:有 `Wvd` 符号的 ivar 打 `var name: Type`,否则(Generated Interface 有 stand-in 时打 stand-in)打 `unrecoverableStoredPropertyComment`。`dump` 一侧在 `Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift` 约 142–160 行,注释部分写 `Swift type not recoverable`。ObjC 属性与 ivar 的对应:`ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`(先认 `V`,再认同名)。 - **ObjC 一侧的 C 类型替换**:MachOObjCSection 的 `Transformer.CType`(`ObjCOutputTransformer`,`Pattern` 13 种 C 基本类型)。RuntimeViewer 在 `RuntimeObjCSection.builderInputs(for:)` 里把它转成 `[ObjCPrimitiveTypePattern: String]` 交给 ObjC 渲染;Swift 打印目前拿不到这份替换表。`ObjCOutputTransformer` 只依赖 `OutputTransformer` 与 `Semantic`。 - **实例**:UIKitCore(macOS 27.2 的 iOSSupport)`_UISplitViewControllerAdaptiveLayoutTransition` 的 24 个 ivar:12 个空 encoding、1 个 `?`(`identifier`,ObjC 属性 `NSString *`)、11 个完整 encoding(`@"UIView"`、`@"<_UISplitViewControllerAdaptiveLayout>"`、`B`、`d` 等)。 @@ -34,7 +34,7 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti 在 `SwiftObjCInterop` 加一个只依赖 ivar 事实与 ObjC 属性的还原函数,interface 与 dump 共用: -1. **encoding 完整**(非空、非 `?`):`ObjCTypeEncoding.type(from:)` 解析后按「原样表示」规则转成 `Type` 节点——与导入规则只差三处:桥接类保持类本身(`NSString` 还是 `NSString`),`id` 是 `AnyObject`,block / 位域 / 不认识的类型 / 无名结构体还原不出(返回 `nil`,保持注释)。 +1. **encoding 完整**(非空、非 `?`):`ObjCTypeEncodingParser.type(from:)` 解析后按「原样表示」规则转成 `Type` 节点——与导入规则只差三处:桥接类保持类本身(`NSString` 还是 `NSString`),`id` 是 `AnyObject`,block / 位域 / 不认识的类型 / 无名结构体还原不出(返回 `nil`,保持注释)。 2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);没有 ObjC 属性、或 `T` 是 block 等还原不出的类型,保持注释。`weak` 属性例外:`weak` 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 `?`,而 `weak` 只能是类,所以按「原样表示」规则读它的 `T` 特性,不桥接。 3. **空 encoding**:保持注释,二进制里没有任何类型信息。 4. **可空性**:可空的类型写 `T!`(ClangImporter 对无可空性标注的声明的写法,Generated Interface 也这样写);ObjC 属性是 `weak` 时写 `weak var x: T?`(`weak` 必为可选)。 @@ -81,8 +81,8 @@ SwiftObjCInterop ObjCImplementationClassFacts.InstanceVariable (typeEncoding, swiftTypeNode?) ObjCImplementationClassFacts.Property (attributes: T…,R,W,V…) + ObjCInstanceVariableSwiftType(instanceVariable:objcProperty:in:) -+ encoding complete -> ObjCTypeEncoding.type(from:) -> ObjCImportedTypes.triviallyRepresentedTypeNode -+ encoding "?" -> ObjCTypeEncoding.propertyType(fromAttributes:) -> ObjCImportedTypes.bridgedTypeNode ++ encoding complete -> ObjCTypeEncodingParser.type(from:) -> ObjCImportedTypes.triviallyRepresentedTypeNode ++ encoding "?" -> ObjCTypeEncodingParser.propertyType(fromAttributes:) -> ObjCImportedTypes.bridgedTypeNode + encoding "" -> nil ObjCImportedTypes typeNode(_:position:) (unchanged: imported declarations) diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift index 3b913099..f3a3000f 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift @@ -47,7 +47,7 @@ package struct ObjCInstanceVariableSwiftType { // binary says what its type is. guard instanceVariable.isObjCVisible else { return nil } guard instanceVariable.typeEncoding != "?" else { return nil } - guard let encodedType = ObjCTypeEncoding.type(from: instanceVariable.typeEncoding), + guard let encodedType = ObjCTypeEncodingParser.type(from: instanceVariable.typeEncoding), let typeNode = importedTypes.triviallyRepresentedTypeNode(encodedType, position: isWeak ? .weakStorage : .topLevel) else { return nil } self.typeNode = typeNode From 42d1c48a774b8858d006bfcab076cf1bc51196af Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:36:52 +0800 Subject: [PATCH 142/175] Recover bridged and weak stored properties from their Objective-C property An ivar the compiler marked ? takes the type the importer gives the T attribute of the Objective-C property synthesized on it (NSString is String!, NSArray [Any]!, id Any!), and a weak one its class unbridged as T?, since weak storage makes the compiler write ? for any class. Also prints each recovered declaration on one row (Rows had split the type onto a line of its own) and looks the property up by the same name the Generated Interface's stand-ins use. --- .../draft-objc-ivar-type-recovery.md | 15 ++++-- .../SwiftObjCInterop/ObjCImportedTypes.swift | 13 +++++ .../ObjCInstanceVariableSwiftType.swift | 28 +++++++++-- ...eclarationPrinter+ObjCImplementation.swift | 38 +++++++------- ...CImplementationClassRecognitionTests.swift | 33 +++++++++--- .../ObjCInstanceVariableSwiftTypeTests.swift | 50 +++++++++++++++++-- 6 files changed, 136 insertions(+), 41 deletions(-) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index 0ffc4d81..774b567b 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -24,7 +24,8 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti - **编译器怎么写 ivar 的 encoding**:`swift/lib/IRGen/GenClass.cpp` 的 `buildIvar`(约 2083–2096 行):只有 `varDecl->isObjC() && varDecl->hasStorage()` 才写 encoding;类型 `isTriviallyRepresentableIn(ForeignLanguage::ObjectiveC, …)` 时调 `getObjCEncodingForPropertyType`,否则写 `"?"`(注释原文:「"Unknown type" - used when ObjC classes are bridged to separate Swift types」);不是 `@objc` 的存储属性 encoding 为空串。`isTriviallyRepresentableIn`(`lib/AST/Type.cpp` 3481 行)对 `Trivial` 与 `Object` 返回 true,对 `Bridged` / `BridgedError` / `StaticBridged` / `None` 返回 false。 - **encoding 与 ObjC 属性的 `T` 特性是同一个函数算的**:`getObjCEncodingForPropertyType`(`lib/IRGen/GenObjC.cpp` 1267 行)取 getter 的 foreign 结果类型对应的 clang 类型,交给 clang 的 `getObjCEncodingForPropertyType`;属性表的 `T` 特性也走它(`GenClass.cpp` 2192 行)。所以 encoding 为 `?` 的 ivar,它的 ObjC 属性 `T` 特性给的是桥接后的 ObjC 类型(`T@"NSString"`)。 -- **encoding 不带的信息**:可空性(`UIView` / `UIView?` / `UIView!` 都是 `@"UIView"`)、typedef(`CGFloat`、`NSTimeInterval` 都是 `d`,`NSInteger` 与 `Int` 都是 `q`)、`NSArray` 等的泛型参数(`T@"NSArray"`)、block 的签名(ivar 与属性都只写 `@?`)。 +- **encoding 不带的信息**:可空性(`UIView` / `UIView?` / `UIView!` 都是 `@"UIView"`)、typedef 与枚举(`CGFloat`、`NSTimeInterval` 都是 `d`;`NSInteger`、`Int` 与 `NS_ENUM(NSInteger)` 的枚举都是 `q`,`NS_OPTIONS` 是 `Q`)、`NSArray` 等的泛型参数(`T@"NSArray"`)、block 的签名(ivar 与属性都只写 `@?`),以及几处同码异型:`^v` 是 `UnsafeMutableRawPointer` 也可能是 `OpaquePointer`,`#` 是 `AnyClass` 也可能是某个类的 `.Type`,`*` 是任何 char 类指针,arm64 上 `B` 也可能是 `ObjCBool`,`:` 不分 `Selector` 与 `Selector?`。 +- **`weak` 的 ivar 写 `?`**(本提案的前提测试实测):`weak var observer: NSObject?` 的存储类型不能原样表示成 ObjC 类型,ivar encoding 是 `?`;ObjC 属性的 `T` 特性仍是 `@"NSObject"`、带 `W`。 - **已有的转换**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift` 的 `ObjCImportedTypes.typeNode(_:position:)` 按 ClangImporter 的规则把 `ObjCEncodedType` 转成 `Type` 节点:桥接类(`ObjCBridgedStructures`、`NSArray` / `NSDictionary` / `NSSet` / `NSError`)转值类型,`id` 转 `Any`,可空的对象类型转 `T!`,类名经 `ObjCRuntimeNames.classNode(forRuntimeName:in:)` 找 Swift 类、找不到就是 `__C.`;`__C` 名在打印时经 C 导入类型名改写(0106,接 swift-type-indexing 的 SDK 索引)换成 Swift 名。`ObjCTypeEncodingParser.type(from:)` 与 `propertyType(fromAttributes:)` 解析 encoding 与 `T` 特性(`ObjCTypeEncoding.swift` 115–132 行)。 - **现状的渲染路径**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift` 的 `renderUnrepresentedObjCImplementationInstanceVariables`:有 `Wvd` 符号的 ivar 打 `var name: Type`,否则(Generated Interface 有 stand-in 时打 stand-in)打 `unrecoverableStoredPropertyComment`。`dump` 一侧在 `Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift` 约 142–160 行,注释部分写 `Swift type not recoverable`。ObjC 属性与 ivar 的对应:`ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`(先认 `V`,再认同名)。 - **ObjC 一侧的 C 类型替换**:MachOObjCSection 的 `Transformer.CType`(`ObjCOutputTransformer`,`Pattern` 13 种 C 基本类型)。RuntimeViewer 在 `RuntimeObjCSection.builderInputs(for:)` 里把它转成 `[ObjCPrimitiveTypePattern: String]` 交给 ObjC 渲染;Swift 打印目前拿不到这份替换表。`ObjCOutputTransformer` 只依赖 `OutputTransformer` 与 `Semantic`。 @@ -38,13 +39,15 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti 2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);没有 ObjC 属性、或 `T` 是 block 等还原不出的类型,保持注释。`weak` 属性例外:`weak` 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 `?`,而 `weak` 只能是类,所以按「原样表示」规则读它的 `T` 特性,不桥接。 3. **空 encoding**:保持注释,二进制里没有任何类型信息。 4. **可空性**:可空的类型写 `T!`(ClangImporter 对无可空性标注的声明的写法,Generated Interface 也这样写);ObjC 属性是 `weak` 时写 `weak var x: T?`(`weak` 必为可选)。 -5. **`var` / `let`**:有 ObjC 属性且是 `readonly` 写 `let`,否则 `var`——与已有的「存储属性按 setter 判 `var` / `let`」同一规则(`printThrowingObjCImplementationStoredProperty`)。 +5. **`var` / `let`**:有 ObjC 属性且是 `readonly` 写 `let`,否则 `var`。 6. **C 类型替换**:`SwiftDeclarationPrintConfiguration` 新增 `cTypeReplacements: [Transformer.CType.Pattern: String]`(默认空)与 `applyTransformers(_: Transformer.ObjCConfiguration)`;还原出的类型本身是 C 基本类型、且表里有替换时,打替换的名字(`var interactiveProgress: CGFloat`)。调用方(RuntimeViewer)把 ObjC 一侧的 C Type Replacement 设置原样交进来,两侧显示一致。 7. **dump**:同一个还原函数,ivar 行打成 `var name: Type`,注释里的 `Swift type not recoverable` 换成类型来源(`Swift type from the ObjC type encoding` / `Swift type from the ObjC property`)。 **没有询问就采用的假设**(用户可以推翻): -- 还原出的声明不加「类型来自 encoding」的逐行标注:完整 encoding 的类型除可空性外是精确的,`!` 已经说明可空性未知;`dump` 的注释写明来源。 +- 还原出的声明不加「类型来自 encoding」的逐行标注,也不加 `@objc`(与已有的「只有 `Wvd` 符号」分支一致)。打出的是 ClangImporter 给这个 C 类型的 Swift 类型;上面「encoding 不带的信息」列出的那些情况(typedef、枚举、`^v`、`#` 等)是已知近似,与 ObjC 头文件一侧显示的一致;`!` 说明可空性未知;`dump` 的注释写明来源。 +- 没有 ObjC 属性时写 `var`:只有 ivar 时没有任何信息说它不可写。已有的 `printThrowingObjCImplementationStoredProperty` 在「没有 setter 符号也没有 ObjC 属性」时写 `let`,那里有 accessor 符号可依,这里没有。 +- Generated Interface 里没有 stand-in 的 ivar 也走这条还原:它的类体本来就是 Swift 一侧的实现。 - C 类型替换只作用于「类型本身就是 C 基本类型」的情况,不改指针参数、元组里的基本类型;`dump` 不接替换表。 - `copy` 特性不还原成 `@NSCopying`:对桥接值类型没有意义,对类类型也无从确认源码写了它。 - Generated Interface 已有的 stand-in(0096)不变:它的定位是「ObjC 一侧如何导入」,与本提案的 Swift 一侧不同。 @@ -190,7 +193,7 @@ package struct ObjCInstanceVariableSwiftType { - 行为:完整 encoding 的 `NSString` 不桥接成 `String`、`@` 是 `AnyObject`(单元测试;夹具造不出,见改动地图);夹具里不桥接的类用 `NSMutableString` 验。 - 行为:block、指向结构体的指针、位域、无名结构体还原不出。 - 行为:空 encoding 仍是注释。 -3. **`?` 按 ObjC 属性还原**:`bridgedTypeNode`。 +3. **`?` 按 ObjC 属性还原**(已完成):`bridgedTypeNode`。 - 行为:`?` 且有 `NSString` 属性的打成 `String!`,`NSArray` 的打成 `[Any]!`,`id` 的打成 `Any!`。 - 行为:`?` 且没有 ObjC 属性的仍是注释。 - 行为:`weak` 的 ObjC 属性打 `weak var x: T?`,类不桥接(`weak` 的存储让 ivar 写 `?`)。 @@ -205,6 +208,8 @@ package struct ObjCInstanceVariableSwiftType { ## 后续项 +- 已有问题(基线上就有):`renderUnrepresentedObjCImplementationInstanceVariables` 里「只有 `Wvd` 符号」那条分支把 `var name: ` 与类型放成 `Rows` 的两个子项,打出来分成两行。本提案的新分支踩过同一个坑,改成了一个子项;那条旧分支要配一个「`Wvd` 在、accessor 已剥」的夹具才能复现,留到之后。 + - RuntimeViewer:`RuntimeSwiftSection` 把 `transformer.objc.cType` 交给 Swift 打印配置(`applyTransformers(_: Transformer.ObjCConfiguration)`),C Type Replacement 改动时让 Swift 输出重印;随 MachOSwiftSection 依赖版本一起抬。 - `swift-section interface` 的 `--c-type-replacement`。 - Generated Interface 的 stand-in 对完整 encoding 的 ivar 是否改用本提案的 Swift 类型(`NSString` 不桥接)。 @@ -219,4 +224,6 @@ package struct ObjCInstanceVariableSwiftType { | 2026-11-26 | 还原结果存 `ObjCEncodedType`,不另设 `ObjCPrimitiveType` | `ObjCEncodedType` 在同一个包内可见,打印器直接对到 `Transformer.CType.Pattern`,少一个只为转一手的类型 | | 2026-11-26 | 夹具的 `CGFloat` 属性在 Swift 一侧写 `Double` | 夹具只 `import Foundation`,头文件的 `CGFloat` 导入成 `Double`,写 `CGFloat` 时 `@implementation` 的类型匹配报错 | | 2026-11-26 | `weak` 属性挪到第 3 步,按 ObjC 属性读、不桥接 | 前提测试实测:`weak var observer: NSObject?` 的 ivar encoding 是 `?`,不是 `@"NSObject"` | +| 2026-11-26 | 第 2 步的修正与第 3 步同一个提交 | 第 2 步的首个提交在 Ultra 上编不过(解析器名写错)、修好后又发现声明被 `Rows` 拆成两行,两处修正与第 3 步的改动落在同几个文件里 | +| 2026-11-26 | 完整 encoding 的近似(枚举、`^v`、`#` 等)照打,写进假设 | 第 2 步审查指出;与 `CGFloat` / `Double` 同性质,ObjC 头文件一侧显示的也是同一个 C 类型 | | 2026-11-26 | 加前提测试 | 第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(`ObjCImplementationClassFacts.InstanceVariable.name` 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实 | diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift index d5631622..c6abd3d7 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift @@ -63,6 +63,19 @@ package struct ObjCImportedTypes return typeNode(type, position: position, mapping: .triviallyRepresented) } + /// The Swift type of an `@objc @implementation` stored property whose + /// ivar the compiler marked `?` — a type bridged to a separate + /// Objective-C one — read off the `T` attribute of the Objective-C + /// property synthesized on it (evolution proposal + /// `objc-ivar-type-recovery`): the type the importer gives that + /// Objective-C type, `NSString` as `String`, `NSArray` as `[Any]` (the + /// attribute names no element type), `id` as `Any`. `nil` for a type + /// that determines none, as for `triviallyRepresentedTypeNode(_:position:)`. + package func bridgedTypeNode(_ type: ObjCEncodedType, position: Position) -> Node? { + guard Self.determinesStoredPropertyType(type) else { return nil } + return typeNode(type, position: position, mapping: .imported) + } + private func typeNode(_ type: ObjCEncodedType, position: Position, mapping: Mapping) -> Node { let base = Self.type(bareTypeNode(type, mapping: mapping)) guard Self.isNullable(type) else { return base } diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift index f3a3000f..ef859644 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift @@ -43,15 +43,33 @@ package struct ObjCInstanceVariableSwiftType { package init?(instanceVariable: ObjCImplementationClassFacts.InstanceVariable, objcProperty: ObjCImplementationClassFacts.Property?, in machO: some MachOSwiftSectionRepresentableWithCache) { let importedTypes = ObjCImportedTypes(machO: machO) let isWeak = objcProperty?.isWeak ?? false + let encodedType: ObjCEncodedType + let typeNode: Node // An empty encoding: the property is not `@objc`, and nothing in the // binary says what its type is. guard instanceVariable.isObjCVisible else { return nil } - guard instanceVariable.typeEncoding != "?" else { return nil } - guard let encodedType = ObjCTypeEncodingParser.type(from: instanceVariable.typeEncoding), - let typeNode = importedTypes.triviallyRepresentedTypeNode(encodedType, position: isWeak ? .weakStorage : .topLevel) - else { return nil } + if instanceVariable.typeEncoding == "?" { + // Bridged: the Objective-C property says to what. A `weak` + // property's storage is marked `?` whatever its class, and + // `weak` holds only a class, which no bridging changes. + guard let objcProperty, + let propertyType = ObjCTypeEncodingParser.propertyType(fromAttributes: objcProperty.attributes), + let propertyTypeNode = isWeak + ? importedTypes.triviallyRepresentedTypeNode(propertyType, position: .weakStorage) + : importedTypes.bridgedTypeNode(propertyType, position: .topLevel) + else { return nil } + encodedType = propertyType + typeNode = propertyTypeNode + self.source = .objcProperty + } else { + guard let instanceVariableType = ObjCTypeEncodingParser.type(from: instanceVariable.typeEncoding), + let instanceVariableTypeNode = importedTypes.triviallyRepresentedTypeNode(instanceVariableType, position: isWeak ? .weakStorage : .topLevel) + else { return nil } + encodedType = instanceVariableType + typeNode = instanceVariableTypeNode + self.source = .instanceVariableEncoding + } self.typeNode = typeNode - self.source = .instanceVariableEncoding self.encodedType = encodedType self.isReadOnly = objcProperty?.isReadOnly ?? false self.isWeak = isWeak diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift index 85ac1e60..b2f9a796 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift @@ -133,22 +133,8 @@ extension SwiftDeclarationPrinter { } await printType(typeNode.materialize(), isProtocol: false, level: level) } else if let recoveredType = recoveredSwiftType(of: instanceVariable, in: extensionDefinition) { - SemanticString { - if recoveredType.isWeak { - Keyword(.weak) - Space() - Keyword(.var) - } else { - // A `readonly` Objective-C property over - // stored Swift storage was declared `let`. - Keyword(recoveredType.isReadOnly ? .let : .var) - } - Space() - MemberDeclaration(instanceVariable.name) - Standard(":") - Space() - } - await printRecoveredType(recoveredType, level: level) + // One row: `Rows` puts each component on a line of its own. + await recoveredStoredPropertyDeclaration(named: instanceVariable.name, type: recoveredType, level: level) } else { comment(.note(Self.unrecoverableStoredPropertyComment(for: instanceVariable)), as: .note) } @@ -162,14 +148,26 @@ extension SwiftDeclarationPrinter { /// when it gives none. An unnamed ivar names no property to declare. private func recoveredSwiftType(of instanceVariable: ObjCImplementationClassFacts.InstanceVariable, in extensionDefinition: ExtensionDefinition) -> ObjCInstanceVariableSwiftType? { guard !instanceVariable.name.isEmpty, let facts = extensionDefinition.objcImplementation else { return nil } - let objcProperty = facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.name) + let objcProperty = facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.swiftPropertyName ?? instanceVariable.name) return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable, objcProperty: objcProperty, in: machO) } - /// A recovered type, through the configuration's C type replacements when - /// it is a C primitive one of them names. + /// `[weak] var|let name: Type` for a stored property whose type the + /// Objective-C side gave. With an Objective-C property, `readonly` makes + /// it a `let`; with none, nothing says it cannot be set. @SemanticStringBuilder - private func printRecoveredType(_ recoveredType: ObjCInstanceVariableSwiftType, level: Int) async -> SemanticString { + private func recoveredStoredPropertyDeclaration(named name: String, type recoveredType: ObjCInstanceVariableSwiftType, level: Int) async -> SemanticString { + if recoveredType.isWeak { + Keyword(.weak) + Space() + Keyword(.var) + } else { + Keyword(recoveredType.isReadOnly ? .let : .var) + } + Space() + MemberDeclaration(name) + Standard(":") + Space() await printType(recoveredType.typeNode, isProtocol: false, level: level) } diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 1f27436e..3a442ac7 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -111,11 +111,13 @@ struct ObjCImplementationClassRecognitionTests { let interface = try await interface(of: .strippedLocals) let widget = try #require(block(named: "@objc @implementation extension __C.Widget {", in: interface)) #expect(!widget.contains("inferred from ObjC class data")) - // No field-offset symbol survived. An ivar with a complete encoding - // takes the type Objective-C represents as it is (evolution proposal - // `objc-ivar-type-recovery`); the others render as honest comments — - // ObjC facts, no fabricated Swift type. - #expect(widget.contains("// stored property title: Swift type not recoverable (ObjC ivar, offset 0x8, size 16, encoding \"?\")")) + // No field-offset symbol survived. The Objective-C side still gives + // the types of the `@objc` ones (evolution proposal + // `objc-ivar-type-recovery`): a complete encoding is the type itself, + // a `?` one the bridged form of its Objective-C property. The others + // render as honest comments — ObjC facts, no fabricated Swift type. + #expect(widget.contains(" var title: Swift.String!\n")) + #expect(!widget.contains("stored property title")) #expect(widget.contains(" var count: Swift.Int\n")) #expect(!widget.contains("stored property count")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable (ObjC ivar, offset 0x20, size 8, encoding \"\")")) @@ -131,7 +133,9 @@ struct ObjCImplementationClassRecognitionTests { private func adaptiveTransitionWidget(of variant: ObjCImplementationFixture.Variant) async throws -> String { let interface = try await interface(of: variant) - return try #require(block(named: "@objc @implementation extension __C.AdaptiveTransitionWidget {", in: interface)) + // The fully stripped variant's header carries the inferred evidence + // between `@implementation` and `extension`. + return try #require(block(named: "extension __C.AdaptiveTransitionWidget {", in: interface)) } /// What follows `var : ` or `let : ` on its line in `block`. @@ -176,6 +180,21 @@ struct ObjCImplementationClassRecognitionTests { #expect(widget.contains(" let revision: Swift.Int\n"), "\(widget)") } + @Test func bridgedIvarsRecoverTheImportedTypeOfTheirObjCProperty() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + // `readonly` over stored storage: a `let`. + #expect(widget.contains(" let identifier: Swift.String!\n"), "\(widget)") + // The `T` attribute names no element type. + #expect(widget.contains(" var names: [Any]!\n"), "\(widget)") + #expect(widget.contains(" var payload: Any!\n"), "\(widget)") + #expect(!widget.contains("stored property identifier")) + } + + @Test func weakObjCPropertyRecoversAsAWeakOptionalOfItsClass() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" weak var observer: __C.NSObject?\n"), "\(widget)") + } + @Test func ivarWithNoEncodingStaysAComment() async throws { let widget = try await adaptiveTransitionWidget(of: .strippedLocals) #expect(widget.contains("// stored property transitionAnimations: Swift type not recoverable (ObjC ivar, offset 0x"), "\(widget)") @@ -195,7 +214,7 @@ struct ObjCImplementationClassRecognitionTests { // The class has no member symbol left, so the extension is synthesized // from the ObjC side alone — and labelled as an inference. let widget = try #require(block(named: "@objc @implementation /* inferred from ObjC class data: 4 ivars carry Swift-style type encodings */ extension __C.Widget {", in: interface)) - #expect(widget.contains("// stored property title: Swift type not recoverable")) + #expect(widget.contains(" var title: Swift.String!\n")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable")) // The clang class has complete encodings and no Swift symbols: silent // (it still appears as the SUPERCLASS of the fixture's Swift subclasses). diff --git a/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift index 0621b092..7de4bb59 100644 --- a/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift +++ b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift @@ -30,11 +30,27 @@ struct ObjCInstanceVariableSwiftTypeTests { .map { $0.typeNode.print(using: .interface) } } + /// How the fixed print preset spells the class named `runtimeName`, which + /// is how a class the recovery keeps prints, whatever the spelling of + /// imported names. + private static func printedClass(_ runtimeName: String) throws -> String { + ObjCRuntimeNames.classNode(forRuntimeName: runtimeName, in: try appKit()).print(using: .interface) + } + + /// The importer's type for an Objective-C type, as a declaration imports it. + private static func importedType(_ encoding: String) throws -> String { + let type = try #require(ObjCTypeEncodingParser.type(from: encoding)) + return ObjCImportedTypes(machO: try appKit()).typeNode(type, position: .topLevel).print(using: .interface) + } + @Test func completeEncodingOfABridgeableClassKeepsTheClass() throws { // A Swift `NSString` property: the compiler writes `@"NSString"` only // because the type is the class itself, never for a `String`. - #expect(try Self.recoveredType(encoding: "@\"NSString\"") == "__C.NSString!") - #expect(try Self.recoveredType(encoding: "@\"NSArray\"") == "__C.NSArray!") + let string = try Self.recoveredType(encoding: "@\"NSString\"") + #expect(string == (try Self.printedClass("NSString")) + "!") + #expect(string != (try Self.importedType("@\"NSString\""))) + let array = try Self.recoveredType(encoding: "@\"NSArray\"") + #expect(array == (try Self.printedClass("NSArray")) + "!") } @Test func completeEncodingOfABareIdIsAnyObject() throws { @@ -42,7 +58,10 @@ struct ObjCInstanceVariableSwiftTypeTests { } @Test func completeEncodingOfAProtocolIsTheExistential() throws { - #expect(try Self.recoveredType(encoding: "@\"\"") == "(any __C.NSCopying)!") + // As the importer gives it: no bridging touches a protocol. + let existential = try Self.recoveredType(encoding: "@\"\"") + #expect(existential == (try Self.importedType("@\"\""))) + #expect(existential?.hasSuffix("!") == true) } @Test func scalarEncodingsNameTheirSwiftTypes() throws { @@ -62,8 +81,26 @@ struct ObjCInstanceVariableSwiftTypeTests { #expect(try Self.recoveredType(encoding: "") == nil) } - @Test func weakPropertyIsOptional() throws { - #expect(try Self.recoveredType(encoding: "@\"NSObject\"", propertyAttributes: "T@\"NSObject\",W,N,Vstorage") == "__C.NSObject?") + @Test func bridgedEncodingTakesTheImportedTypeOfTheObjCProperty() throws { + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSString\",C,N,Vstorage") == "Swift.String!") + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSArray\",C,N,Vstorage") == (try Self.importedType("@\"NSArray\""))) + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@,&,N,Vstorage") == (try Self.importedType("@"))) + let appKit = try Self.appKit() + let bridged = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "?"), objcProperty: .init(name: "storage", attributes: "T@\"NSString\",C,N,Vstorage"), in: appKit)) + #expect(bridged.source == .objcProperty) + } + + @Test func bridgedEncodingWithoutATypedObjCPropertyRecoversNothing() throws { + #expect(try Self.recoveredType(encoding: "?") == nil) + // A Swift closure bridges to a block, whose attribute has no signature. + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@?,C,N,Vstorage") == nil) + } + + @Test func weakStorageReadsItsClassUnbridged() throws { + // `weak` makes the compiler write `?` for any class, and holds no + // value type: `NSString` stays a class. + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSObject\",W,N,Vstorage") == (try Self.printedClass("NSObject")) + "?") + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSString\",W,N,Vstorage") == (try Self.printedClass("NSString")) + "?") } @Test func readOnlyAndWeakAreReadOffTheObjCProperty() throws { @@ -74,5 +111,8 @@ struct ObjCInstanceVariableSwiftTypeTests { #expect(readOnly.source == .instanceVariableEncoding) let settable = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "q"), objcProperty: nil, in: appKit)) #expect(!settable.isReadOnly) + let weak = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "?"), objcProperty: .init(name: "storage", attributes: "T@\"NSObject\",W,N,Vstorage"), in: appKit)) + #expect(weak.isWeak) + #expect(!weak.isReadOnly) } } From ed8c5a01e6ea685a62f85d9d1539d97d766ad1eb Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:38:27 +0800 Subject: [PATCH 143/175] Spell a recovered C primitive type through the C type replacements SwiftDeclarationPrintConfiguration.cTypeReplacements, filled from an Objective-C configuration's enabled cType module by the new applyTransformers(_: Transformer.ObjCConfiguration), now spells a recovered stored property whose type is a C primitive (double as CGFloat), as the Objective-C header does with the same replacements. An empty spelling or a disabled module leaves the importer's type. --- .../draft-objc-ivar-type-recovery.md | 2 +- Package.swift | 4 ++ ...ationPrintConfiguration+Transformers.swift | 10 +++++ ...eclarationPrinter+ObjCImplementation.swift | 32 +++++++++++++++- ...CImplementationClassRecognitionTests.swift | 37 ++++++++++++++++--- 5 files changed, 78 insertions(+), 7 deletions(-) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index 774b567b..828a6575 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -197,7 +197,7 @@ package struct ObjCInstanceVariableSwiftType { - 行为:`?` 且有 `NSString` 属性的打成 `String!`,`NSArray` 的打成 `[Any]!`,`id` 的打成 `Any!`。 - 行为:`?` 且没有 ObjC 属性的仍是注释。 - 行为:`weak` 的 ObjC 属性打 `weak var x: T?`,类不桥接(`weak` 的存储让 ivar 写 `?`)。 -4. **C 类型替换**:`applyTransformers(_: Transformer.ObjCConfiguration)`,打印时替换。 +4. **C 类型替换**(已完成):`applyTransformers(_: Transformer.ObjCConfiguration)`,打印时替换;`SwiftInterfaceTests` 为此依赖 `ObjCOutputTransformer` 与 `OutputTransformer`。 - 行为:配置 `double → CGFloat` 时 `d` 打成 `CGFloat`。 - 行为:没有配置或模块关闭时仍是 `Double`。 5. **dump 与文档**:`ObjCImplementationClassDumper` 接入;模块说明与演进账本。 diff --git a/Package.swift b/Package.swift index 63c0d763..d7cb0564 100644 --- a/Package.swift +++ b/Package.swift @@ -1281,6 +1281,10 @@ extension Target { .target(.SwiftInterface), // The nested-definition contract with source-file comments on. .target(.SwiftPrivateDiscriminators), + // `Transformer.CType`, the C type replacements of a recovered + // `@objc @implementation` stored property's type. + .product(.OutputTransformer), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), .product(.MachOKitExtensions), .target(.SwiftSectionTestingSupport), .target(.SwiftSectionFixtureSupport), diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift index e423bc1f..16faedda 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift @@ -1,6 +1,7 @@ import Foundation import OutputTransformer import SwiftOutputTransformer +import ObjCOutputTransformer import SwiftDeclarationRendering extension SwiftDeclarationPrintConfiguration { @@ -15,4 +16,13 @@ extension SwiftDeclarationPrintConfiguration { typeLayoutTransformer = transformers.makeTypeLayoutTransformer() (enumLayoutTransformer, enumLayoutCaseTransformer) = transformers.makeEnumLayoutTransformers() } + + /// Installs what the Objective-C transformer modules change in a Swift + /// print: the replacements of an enabled `cType` module, for the types + /// the interface reads off the Objective-C side (evolution proposal + /// `objc-ivar-type-recovery`), so both sides of a class spell a C + /// primitive alike. A disabled module clears them. + public mutating func applyTransformers(_ transformers: Transformer.ObjCConfiguration) { + cTypeReplacements = transformers.cType.isEnabled ? transformers.cType.replacements.filter { !$0.value.isEmpty } : [:] + } } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift index b2f9a796..f48f304f 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift @@ -4,6 +4,8 @@ import Demangling import Semantic @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import OutputTransformer +import ObjCOutputTransformer // The interface-side rendering of an `@objc @implementation` class's stored // properties (evolution proposal `objc-implementation-class-recognition`). @@ -168,7 +170,35 @@ extension SwiftDeclarationPrinter { MemberDeclaration(name) Standard(":") Space() - await printType(recoveredType.typeNode, isProtocol: false, level: level) + if let replacement = cTypeReplacement(for: recoveredType.encodedType) { + TypeName(kind: .other, replacement) + } else { + await printType(recoveredType.typeNode, isProtocol: false, level: level) + } + } + + /// The configuration's spelling for `type` when it is a C primitive one + /// of its C type replacements names (`double` → `CGFloat`), as an + /// Objective-C header spells it with the same replacements. + private func cTypeReplacement(for type: ObjCEncodedType) -> String? { + let pattern: Transformer.CType.Pattern? = switch type { + case .character: .char + case .unsignedCharacter: .uchar + case .short: .short + case .unsignedShort: .ushort + case .int: .int + case .unsignedInt: .uint + case .long: .long + case .unsignedLong: .ulong + case .longLong: .longLong + case .unsignedLongLong: .ulongLong + case .float: .float + case .double: .double + case .longDouble: .longDouble + default: nil + } + guard let pattern, let replacement = configuration.cTypeReplacements[pattern], !replacement.isEmpty else { return nil } + return replacement } static func unrecoverableStoredPropertyComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> String { diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 3a442ac7..9bb41102 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -11,6 +11,8 @@ import Semantic @testable import SwiftSectionTestingSupport import SwiftPrinting import SwiftSectionFixtureSupport +import OutputTransformer +import ObjCOutputTransformer /// `@objc @implementation` recognition on the interface path (evolution /// proposal `objc-implementation-class-recognition`), over the on-the-fly @@ -19,15 +21,16 @@ import SwiftSectionFixtureSupport /// adds to, and a plain Swift class with ObjC ancestry. @Suite(.serialized, ExclusiveImageAccess(ObjCImplementationFixture.moduleName)) struct ObjCImplementationClassRecognitionTests { - private func interface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool = false) async throws -> String { - try await printInterface(of: variant, printFieldOffset: printFieldOffset, marksCommentStructure: false).string + private func interface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool = false, configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> String { + try await printInterface(of: variant, printFieldOffset: printFieldOffset, marksCommentStructure: false, configure: configure).string } - private func printInterface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool, marksCommentStructure: Bool) async throws -> SemanticString { + private func printInterface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool, marksCommentStructure: Bool, configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> SemanticString { let machOFile = try ObjCImplementationFixture.machOFile(variant) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.printFieldOffset = printFieldOffset configuration.printConfiguration.marksCommentStructure = marksCommentStructure + configure(&configuration.printConfiguration) let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) try await builder.prepare() return try await builder.printRoot() @@ -131,8 +134,8 @@ struct ObjCImplementationClassRecognitionTests { // members are internal, so `strip -x` leaves only its ivar list and // Objective-C properties. - private func adaptiveTransitionWidget(of variant: ObjCImplementationFixture.Variant) async throws -> String { - let interface = try await interface(of: variant) + private func adaptiveTransitionWidget(of variant: ObjCImplementationFixture.Variant, configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> String { + let interface = try await interface(of: variant, configure: configure) // The fully stripped variant's header carries the inferred evidence // between `@implementation` and `extension`. return try #require(block(named: "extension __C.AdaptiveTransitionWidget {", in: interface)) @@ -195,6 +198,30 @@ struct ObjCImplementationClassRecognitionTests { #expect(widget.contains(" weak var observer: __C.NSObject?\n"), "\(widget)") } + @Test func cTypeReplacementsSpellARecoveredPrimitiveType() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in + configuration.cTypeReplacements = [.double: "CGFloat", .longLong: "NSInteger"] + } + #expect(widget.contains(" var interactiveProgress: CGFloat\n"), "\(widget)") + #expect(widget.contains(" var stepCount: NSInteger\n"), "\(widget)") + // Only a primitive type is replaced. + #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") + } + + @Test func objcTransformersInstallTheirCTypeReplacementsOnlyWhenEnabled() async throws { + let enabled = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in + configuration.applyTransformers(Transformer.ObjCConfiguration(cType: .init(isEnabled: true, replacements: [.double: "CGFloat", .longLong: ""]))) + } + #expect(enabled.contains(" var interactiveProgress: CGFloat\n"), "\(enabled)") + // An empty spelling replaces nothing. + #expect(enabled.contains(" var stepCount: Swift.Int\n"), "\(enabled)") + let disabled = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in + configuration.cTypeReplacements = [.double: "Float64"] + configuration.applyTransformers(Transformer.ObjCConfiguration(cType: .init(isEnabled: false, replacements: [.double: "CGFloat"]))) + } + #expect(disabled.contains(" var interactiveProgress: Swift.Double\n"), "\(disabled)") + } + @Test func ivarWithNoEncodingStaysAComment() async throws { let widget = try await adaptiveTransitionWidget(of: .strippedLocals) #expect(widget.contains("// stored property transitionAnimations: Swift type not recoverable (ObjC ivar, offset 0x"), "\(widget)") From 1ffe58b6682f3f1b403896c3e6b0a3ac50f21142 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:40:36 +0800 Subject: [PATCH 144/175] Print the recovered stored property types in the dump too swift-section dump now prints an @objc @implementation ivar with no field-offset symbol as a declaration when the Objective-C side gives its type, and its comment says whether the type came from the ivar's encoding or from its Objective-C property. Documents the recovery in the SwiftObjCInterop module notes and the recognition write-up. --- .../draft-objc-ivar-type-recovery.md | 5 +-- .../Internal/Modules/SwiftObjCInterop.md | 4 +-- .../ObjCImplementationClassRecognition.md | 2 +- .../ObjCImplementationClassDumper.swift | 35 +++++++++++++++++-- .../ObjCImplementationClassDumpTests.swift | 7 +++- 5 files changed, 44 insertions(+), 9 deletions(-) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index 828a6575..905569c4 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -75,7 +75,8 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti | `Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift` | 新增 | 逐个 encoding 检查还原结果,含夹具造不出的形状(`@"NSString"`、`@`、`@?`、`^{CGColor=}`) | `@objc @implementation` 的匹配规则不允许实现里把头文件的 `NSString *` 写成 `NSString` | 2–3 | | `Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift` | 修改 | 类集合断言加新类;`count` 的断言改成还原后的声明;新增还原的测试 | 行为清单 | 1–4 | | `Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift` | 修改 | dump 的还原断言 | 行为清单 | 5 | -| `Documentations/Internal/Modules/SwiftObjCInterop.md` 等模块说明、`ProjectEvolutionLog.md` | 修改 | 记录还原规则 | 文档同批 | 5 | +| `Documentations/Internal/Modules/SwiftObjCInterop.md`、`Documentations/Internal/ObjCImplementationClassRecognition.md` | 修改 | 记录还原规则与新入口 | 文档同批 | 5 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 一节记录本次改动 | 节号落地时取 | 收尾 | ## 架构图 @@ -200,7 +201,7 @@ package struct ObjCInstanceVariableSwiftType { 4. **C 类型替换**(已完成):`applyTransformers(_: Transformer.ObjCConfiguration)`,打印时替换;`SwiftInterfaceTests` 为此依赖 `ObjCOutputTransformer` 与 `OutputTransformer`。 - 行为:配置 `double → CGFloat` 时 `d` 打成 `CGFloat`。 - 行为:没有配置或模块关闭时仍是 `Double`。 -5. **dump 与文档**:`ObjCImplementationClassDumper` 接入;模块说明与演进账本。 +5. **dump 与文档**(已完成):`ObjCImplementationClassDumper` 接入;模块说明 `Internal/Modules/SwiftObjCInterop.md` 与实现说明 `Internal/ObjCImplementationClassRecognition.md`。演进账本的节号按项目规则在落地时取,由收尾时补。 - 行为:dump 的 ivar 行打出还原的类型,注释写明来源。 - 行为:还原不出的 ivar 注释仍写 `Swift type not recoverable`。 diff --git a/Documentations/Internal/Modules/SwiftObjCInterop.md b/Documentations/Internal/Modules/SwiftObjCInterop.md index 5b6c5065..350b9d62 100644 --- a/Documentations/Internal/Modules/SwiftObjCInterop.md +++ b/Documentations/Internal/Modules/SwiftObjCInterop.md @@ -38,7 +38,7 @@ ### 2:`@objc @implementation` 类 -SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没有 Swift 的 nominal type descriptor 与 field descriptor。`ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表认出它们,给出 `ObjCImplementationClassFacts`:证据分 definitive 与 inferred 两档,ivar 按偏移值与 `Wvd` 符号配对,还有方法表。见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 +SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没有 Swift 的 nominal type descriptor 与 field descriptor。`ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表认出它们,给出 `ObjCImplementationClassFacts`:证据分 definitive 与 inferred 两档,ivar 按偏移值与 `Wvd` 符号配对,还有方法表。`Wvd` 被剥掉的存储属性由 `ObjCInstanceVariableSwiftType` 从 ivar 的 encoding 或 ObjC 属性还原 Swift 类型(提案 `objc-ivar-type-recovery`)。见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 ### 3:ObjC 协议 @@ -73,7 +73,7 @@ SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没 - `ObjCImportedMemberNodes`:方法、属性、subscript 的 demangle 树,0079 的协议要求也经它建。 - `ObjCSwiftTypeCompatibility`:按名字把 ObjC 成员配给 Swift 成员时的类型核对(提案 [0096](../../Evolutions/0096-swift-first-imported-declarations.md))。只认明显对不上的两种:对象(`@`)对实现它的模块自己定义的 struct / enum,标量对类或 existential;别的模块的值类型可能桥接(`String`、`Data`、`UTType`),不判。它也是「同名的 Swift 属性是另一个声明」的证据——头文件标了 `NS_REFINED_FOR_SWIFT` 的属性,Swift 里叫 `__name`,原名留给一个纯 Swift 的属性。`ObjCMemberShape.removingRefinedForSwiftPrefix` 去掉这个 `__`(属性名、方法基名、初始化器第一个标签)再比 selector。 - `ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`:存储属性对应的 ObjC 属性(`V`)。`-O` 下 setter 常被内联进 thunk、不留符号,可写与否、是否 `weak` 要看它的特性串,interface 不再把这样的属性打成 `let`。 -- `ObjCImportedTypes`:编码里的类型换成 Swift 的类型树(对象是 `T!`,`NSString` 这类桥接成值类型;`r*` 即 `const char *` 是 `UnsafePointer`,`*` 是 `UnsafeMutablePointer`;C 数组照 ClangImporter 导入成元组,单元素的是元素本身,超过 4,096 个元素的导入不了、指针指向它时是 `OpaquePointer`,嵌套数组展开超过 65,536 个元素也按导入不了处理);`ObjCBridgedStructures` 记哪些类导入成值类型,`@NSCopying` 据此判断。 +- `ObjCImportedTypes`:编码里的类型换成 Swift 的类型树(对象是 `T!`,`NSString` 这类桥接成值类型;另有两个入口给 `@objc @implementation` 的存储属性用——`triviallyRepresentedTypeNode` 按「原样表示」读完整的 ivar encoding,不桥接、`id` 是 `AnyObject`,`bridgedTypeNode` 按导入规则读 `?` 的 ivar 对应的 ObjC 属性类型,两者对 block、指向结构体的指针、位域等给不出确定类型的返回 `nil`;`r*` 即 `const char *` 是 `UnsafePointer`,`*` 是 `UnsafeMutablePointer`;C 数组照 ClangImporter 导入成元组,单元素的是元素本身,超过 4,096 个元素的导入不了、指针指向它时是 `OpaquePointer`,嵌套数组展开超过 65,536 个元素也按导入不了处理);`ObjCBridgedStructures` 记哪些类导入成值类型,`@NSCopying` 据此判断。 ## 关键契约 diff --git a/Documentations/Internal/ObjCImplementationClassRecognition.md b/Documentations/Internal/ObjCImplementationClassRecognition.md index e1f73c32..7f9f5bea 100644 --- a/Documentations/Internal/ObjCImplementationClassRecognition.md +++ b/Documentations/Internal/ObjCImplementationClassRecognition.md @@ -33,7 +33,7 @@ SE-0436 的 `@objc @implementation extension` 让 ObjC 头文件里声明的类 ## 两个 join 是怎么做的 - **ivar ↔ `Wvd` 符号**:按**偏移值**。ivar_t 的 `offset` 字段指向的就是 `Wvd` 符号命名的那个全局变量,索引读出该全局变量的值(一个 word)与 `ivar.offset(in:)` 相等即配对。之所以不按名字:即时编译的 fixture 里头文件声明的 `title` 属性其 ivar name 字段是空指针;名字只作兜底。`Wvi`(间接字段偏移)不参与,`@implementation` 类没有 field offset vector,编译器也不会给它发 `Wvi`。符号里 `variable` 节点的名字有两种形状:普通属性是 `identifier`;`private` / `fileprivate` 属性和**每个 `lazy var` 的合成存储**(编译器总把它设为 private,不管属性本身写的什么访问级别)是 `privateDeclName`(鉴别符 + 名字)。第一版只认前者,这两类 ivar 在符号齐全的二进制里也拿不到类型,打出「Swift type not recoverable」注释,对应的成员还被打成 `{ get set }` 的计算属性(2026-09-29 修复)。 -- **存储属性 ↔ 成员定义**:按 Swift 属性名。`attachObjCImplementation(_:)` 用 `ObjCImplementationClassFacts.storageInstanceVariable(forPropertyNamed:)` 把 `VariableDefinition.objcImplementationStorage` 填上,打印器据此改打存储形态;没对上的 ivar 由 `unrepresentedObjCImplementationInstanceVariables` 单独渲染,有 `Wvd` 的打 `var name: Type`,没有的打一行诚实注释。`lazy var x` 的存储名是 `$__lazy_storage_$_x`,永远对不上属性自己的名字,所以查询先按原名找、找不到再找 `lazyPropertyName == x` 的 ivar。`lazyPropertyName` 读 Swift 名,`Wvd` 被剥掉后读 ObjC ivar 名,两者拼法相同(macOS 27.0 AppKit 的 `_NSTextFormattingViewController.campoTextSuggestionsViewController` 就是后一种:访问器导出,存储的 `Wvd` 是 local 符号、被剥掉了);只靠 ObjC 名连上的存储没有 Swift 名,所以「已有成员代表」的判断除按 Swift 名外还按对象身份。渲染规则照抄 Swift 类型自己的 lazy 字段:interface 打 `lazy var x: `,没有 getter 可连时打存储类型 `Optional<…>`;dump 与 `ClassDumper` 一样打 `lazy var x: <存储类型>`。 +- **存储属性 ↔ 成员定义**:按 Swift 属性名。`attachObjCImplementation(_:)` 用 `ObjCImplementationClassFacts.storageInstanceVariable(forPropertyNamed:)` 把 `VariableDefinition.objcImplementationStorage` 填上,打印器据此改打存储形态;没对上的 ivar 由 `unrepresentedObjCImplementationInstanceVariables` 单独渲染,有 `Wvd` 的打 `var name: Type`;没有的先问 ObjC 一侧(`ObjCInstanceVariableSwiftType`,提案 `objc-ivar-type-recovery`):encoding 完整的,Swift 类型就是这个 ObjC 类型本身(编译器只给能原样表示成 ObjC 的类型写完整 encoding);encoding 是 `?` 的,Swift 类型是它的 ObjC 属性 `T` 特性的桥接形态(`NSString` → `String`);`weak` 的存储让编译器对类也写 `?`,按 ObjC 属性读、不桥接。对象类型可空性未知写 `T!`,`readonly` 写 `let`,C 基本类型按打印配置的 `cTypeReplacements` 改写。都给不出的(空 encoding、block、指向结构体的指针等)才打一行诚实注释。dump 同样打出还原的类型,注释写明来自 encoding 还是 ObjC 属性。`lazy var x` 的存储名是 `$__lazy_storage_$_x`,永远对不上属性自己的名字,所以查询先按原名找、找不到再找 `lazyPropertyName == x` 的 ivar。`lazyPropertyName` 读 Swift 名,`Wvd` 被剥掉后读 ObjC ivar 名,两者拼法相同(macOS 27.0 AppKit 的 `_NSTextFormattingViewController.campoTextSuggestionsViewController` 就是后一种:访问器导出,存储的 `Wvd` 是 local 符号、被剥掉了);只靠 ObjC 名连上的存储没有 Swift 名,所以「已有成员代表」的判断除按 Swift 名外还按对象身份。渲染规则照抄 Swift 类型自己的 lazy 字段:interface 打 `lazy var x: `,没有 getter 可连时打存储类型 `Optional<…>`;dump 与 `ClassDumper` 一样打 `lazy var x: <存储类型>`。 ## 边界与已知限制 diff --git a/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift index 9166d3e5..2f17311f 100644 --- a/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift @@ -17,7 +17,9 @@ import SwiftDeclarationRendering /// the Swift symbols found there, the property list, the protocol list, then /// the Swift member symbols the way `ClassDumper` lists a class's. Nothing /// is guessed: an IMP with no symbol prints as an address, an ivar with no -/// field-offset symbol prints its ObjC facts and no Swift type. +/// field-offset symbol prints its ObjC facts, and the Swift type only when the +/// Objective-C side gives it, saying which part did (evolution proposal +/// `objc-ivar-type-recovery`). package struct ObjCImplementationClassDumper: NamedDumper { package typealias Dumped = ObjCImplementationClass @@ -139,6 +141,7 @@ package struct ObjCImplementationClassDumper: configuration.fieldOffsetComment(startOffset: instanceVariable.offset, endOffset: instanceVariable.offset + instanceVariable.size) } Indent(level: 1) + let recoveredType = instanceVariable.swiftTypeNode == nil ? recoveredSwiftType(of: instanceVariable) : nil if let typeNode = instanceVariable.swiftTypeNode, let propertyName = instanceVariable.swiftPropertyName { // A `lazy var`'s storage prints under the property's name with // its storage type, as `ClassDumper` prints a Swift type's own @@ -157,11 +160,24 @@ package struct ObjCImplementationClassDumper: Standard(":") Space() try await demangleResolver.resolve(for: typeNode.materialize()) + } else if let recoveredType { + if recoveredType.isWeak { + Keyword(.weak) + Space() + Keyword(.var) + } else { + Keyword(recoveredType.isReadOnly ? .let : .var) + } + Space() + MemberDeclaration(instanceVariable.name) + Standard(":") + Space() + try await demangleResolver.resolve(for: recoveredType.typeNode) } else { MemberDeclaration(instanceVariable.name.isEmpty ? "" : instanceVariable.name) } Space() - Comment(instanceVariableComment(for: instanceVariable)) + Comment(instanceVariableComment(for: instanceVariable, recoveredType: recoveredType)) if offset.isEnd { BreakLine() } @@ -169,13 +185,26 @@ package struct ObjCImplementationClassDumper: } } - private func instanceVariableComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> String { + /// The Swift type the Objective-C side gives an ivar with no + /// field-offset symbol, as the interface prints it. + private func recoveredSwiftType(of instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> ObjCInstanceVariableSwiftType? { + guard !instanceVariable.name.isEmpty else { return nil } + let objcProperty = facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.swiftPropertyName ?? instanceVariable.name) + return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable, objcProperty: objcProperty, in: machO) + } + + private func instanceVariableComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable, recoveredType: ObjCInstanceVariableSwiftType?) -> String { var parts = ["offset 0x\(String(instanceVariable.offset, radix: 16))", "size \(instanceVariable.size)", "alignment \(instanceVariable.alignment)", "encoding \"\(instanceVariable.typeEncoding)\""] if !instanceVariable.name.isEmpty, instanceVariable.swiftPropertyName != nil, instanceVariable.name != instanceVariable.swiftPropertyName { parts.append("ivar \(instanceVariable.name)") } if let symbolName = instanceVariable.swiftFieldOffsetSymbolName { parts.append(symbolName) + } else if let recoveredType { + switch recoveredType.source { + case .instanceVariableEncoding: parts.append("Swift type from the ObjC type encoding") + case .objcProperty: parts.append("Swift type from the ObjC property") + } } else { parts.append("Swift type not recoverable") } diff --git a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift index 29078a91..3e8ac3ef 100644 --- a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift @@ -68,7 +68,12 @@ struct ObjCImplementationClassDumpTests { let output = try await dump(.strippedEverything) #expect(output.hasPrefix("@objc @implementation /* inferred from ObjC class data: 4 ivars carry Swift-style type encodings */ extension Widget {")) #expect(output.contains("// Evidence: inferred from ObjC class data: 4 ivars carry Swift-style type encodings")) - #expect(output.contains("title // offset 0x8, size 16, alignment 8, encoding \"?\", Swift type not recoverable")) + // The Objective-C side still gives the `@objc` ivars' types, and the + // comment says which part did (evolution proposal + // `objc-ivar-type-recovery`). + #expect(output.contains("var title: Swift.String! // offset 0x8, size 16, alignment 8, encoding \"?\", Swift type from the ObjC property"), "\(output)") + #expect(output.contains("var count: Swift.Int // offset 0x18, size 8, alignment 8, encoding \"q\", Swift type from the ObjC type encoding"), "\(output)") + #expect(output.contains("swiftOnlyCache // offset 0x20, size 8, alignment 8, encoding \"\", Swift type not recoverable, not exposed to ObjC"), "\(output)") // IMPs with no symbol print as addresses only. #expect(output.contains("-[Widget refresh] // types \"v16@0:8\", imp 0x")) #expect(!output.contains("To\n")) From c31ecdaf90bf7df73c72ceebb27d1b5ff926719c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:44:58 +0800 Subject: [PATCH 145/175] Trust a ? ivar's Objective-C property only for a bridged class or a bare id A ? proves the Swift type is no class Objective-C has, so a property type the importer keeps as a class (an unowned property's storage is also marked ?) or a protocol says nothing reliable and stays a comment. Tightens the tests the step 3 and 4 review found too weak. --- .../Evolutions/draft-objc-ivar-type-recovery.md | 5 ++++- .../Analysis/SwiftObjCInterop/ObjCImportedTypes.swift | 11 ++++++++--- .../SwiftDeclarationPrintConfiguration.swift | 7 +++++-- .../ObjCImplementationClassRecognitionTests.swift | 7 +++++-- .../ObjCInstanceVariableSwiftTypeTests.swift | 6 ++++++ 5 files changed, 28 insertions(+), 8 deletions(-) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index 905569c4..eee18201 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -36,7 +36,7 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti 在 `SwiftObjCInterop` 加一个只依赖 ivar 事实与 ObjC 属性的还原函数,interface 与 dump 共用: 1. **encoding 完整**(非空、非 `?`):`ObjCTypeEncodingParser.type(from:)` 解析后按「原样表示」规则转成 `Type` 节点——与导入规则只差三处:桥接类保持类本身(`NSString` 还是 `NSString`),`id` 是 `AnyObject`,block / 位域 / 不认识的类型 / 无名结构体还原不出(返回 `nil`,保持注释)。 -2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);没有 ObjC 属性、或 `T` 是 block 等还原不出的类型,保持注释。`weak` 属性例外:`weak` 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 `?`,而 `weak` 只能是类,所以按「原样表示」规则读它的 `T` 特性,不桥接。 +2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);只认桥接表里的类与裸 `id`——`?` 证明 Swift 类型不是 ObjC 的类本身,导入成类自己的(`unowned` 属性的存储也写 `?`)、表外的桥接类都不可信。没有 ObjC 属性、或 `T` 不是这几种,保持注释。`weak` 属性例外:`weak` 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 `?`,而 `weak` 只能是类,所以按「原样表示」规则读它的 `T` 特性,不桥接。 3. **空 encoding**:保持注释,二进制里没有任何类型信息。 4. **可空性**:可空的类型写 `T!`(ClangImporter 对无可空性标注的声明的写法,Generated Interface 也这样写);ObjC 属性是 `weak` 时写 `weak var x: T?`(`weak` 必为可选)。 5. **`var` / `let`**:有 ObjC 属性且是 `readonly` 写 `let`,否则 `var`。 @@ -227,4 +227,7 @@ package struct ObjCInstanceVariableSwiftType { | 2026-11-26 | `weak` 属性挪到第 3 步,按 ObjC 属性读、不桥接 | 前提测试实测:`weak var observer: NSObject?` 的 ivar encoding 是 `?`,不是 `@"NSObject"` | | 2026-11-26 | 第 2 步的修正与第 3 步同一个提交 | 第 2 步的首个提交在 Ultra 上编不过(解析器名写错)、修好后又发现声明被 `Rows` 拆成两行,两处修正与第 3 步的改动落在同几个文件里 | | 2026-11-26 | 完整 encoding 的近似(枚举、`^v`、`#` 等)照打,写进假设 | 第 2 步审查指出;与 `CGFloat` / `Double` 同性质,ObjC 头文件一侧显示的也是同一个 C 类型 | +| 2026-11-26 | `?` 只认桥接表里的类与裸 `id` | 第 3、4 步审查指出:`?` 证明 Swift 类型不是那个类本身,按导入规则照单全收会把 `unowned` 属性的存储(也写 `?`、特性里没有 `W`)和表外的桥接类(`NSAffineTransform` → `AffineTransform`)打成错的类 | +| 2026-11-26 | `weak` 与 `readonly` 同时出现时仍写 `weak var` | `weak let`(SE-0481)要 Swift 6.2,源码更常见的是 `weak private(set) var`;无从区分时取更常见的写法 | +| 2026-11-26 | C 类型替换只换类型本身,替换名照原样打印 | 与假设一致;替换表的文档写明只收不带模块的名字。ObjC 一侧会递归替换指针里的类型,Swift 一侧不跟 | | 2026-11-26 | 加前提测试 | 第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(`ObjCImplementationClassFacts.InstanceVariable.name` 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实 | diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift index c6abd3d7..27010394 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift @@ -69,10 +69,15 @@ package struct ObjCImportedTypes /// property synthesized on it (evolution proposal /// `objc-ivar-type-recovery`): the type the importer gives that /// Objective-C type, `NSString` as `String`, `NSArray` as `[Any]` (the - /// attribute names no element type), `id` as `Any`. `nil` for a type - /// that determines none, as for `triviallyRepresentedTypeNode(_:position:)`. + /// attribute names no element type), `id` as `Any`. The `?` proves the + /// Swift type is no class Objective-C has, so only a class the importer + /// bridges and a bare `id` qualify; anything else — a class imported as + /// itself, which an `unowned` property's storage also marks `?`, a + /// Foundation class bridged to a value type the table does not list — + /// returns `nil`. package func bridgedTypeNode(_ type: ObjCEncodedType, position: Position) -> Node? { - guard Self.determinesStoredPropertyType(type) else { return nil } + guard case .object(let className, let protocolNames) = type, protocolNames.isEmpty else { return nil } + if let className, !ObjCBridgedStructures.importsAsNonClassType(className) { return nil } return typeNode(type, position: position, mapping: .imported) } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index 92fef3c4..4ce33c8d 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -304,8 +304,11 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { /// off the Objective-C side: an `@objc @implementation` stored property /// recovered from its ivar (evolution proposal `objc-ivar-type-recovery`). /// A replacement stands in for the whole type, as `Transformer.CType` does - /// in an Objective-C header; an empty spelling is no replacement. Empty by - /// default, which prints the type the importer gives (`Swift.Double`). + /// in an Objective-C header, but only for the property's type itself, not + /// for a pointee or an element; it prints as written, so give the name + /// Swift code writes (`CGFloat`), no module. An empty spelling is no + /// replacement. Empty by default, which prints the type the importer + /// gives (`Swift.Double`). public var cTypeReplacements: [Transformer.CType.Pattern: String] = [:] } diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 9bb41102..59c2a284 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -138,6 +138,7 @@ struct ObjCImplementationClassRecognitionTests { let interface = try await interface(of: variant, configure: configure) // The fully stripped variant's header carries the inferred evidence // between `@implementation` and `extension`. + #expect(variant == .strippedEverything || interface.contains("@objc @implementation extension __C.AdaptiveTransitionWidget {")) return try #require(block(named: "extension __C.AdaptiveTransitionWidget {", in: interface)) } @@ -200,11 +201,13 @@ struct ObjCImplementationClassRecognitionTests { @Test func cTypeReplacementsSpellARecoveredPrimitiveType() async throws { let widget = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in - configuration.cTypeReplacements = [.double: "CGFloat", .longLong: "NSInteger"] + configuration.cTypeReplacements = [.double: "CGFloat", .longLong: "NSInteger", .ulongLong: "NSUInteger"] } #expect(widget.contains(" var interactiveProgress: CGFloat\n"), "\(widget)") #expect(widget.contains(" var stepCount: NSInteger\n"), "\(widget)") - // Only a primitive type is replaced. + // Only the type itself is replaced: `NSRange`'s `QQ` fields are not. + let unreplaced = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(declaredType(of: "selectedRange", in: widget) == declaredType(of: "selectedRange", in: unreplaced), "\(widget)") #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") } diff --git a/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift index 7de4bb59..3233e84e 100644 --- a/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift +++ b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift @@ -92,6 +92,12 @@ struct ObjCInstanceVariableSwiftTypeTests { @Test func bridgedEncodingWithoutATypedObjCPropertyRecoversNothing() throws { #expect(try Self.recoveredType(encoding: "?") == nil) + // The `?` proves the type is no Objective-C class: a class imported as + // itself is an `unowned` property's storage or a bridging the table + // does not know, and says nothing reliable. + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSObject\",&,N,Vstorage") == nil) + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"\",&,N,Vstorage") == nil) + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "Tq,N,Vstorage") == nil) // A Swift closure bridges to a block, whose attribute has no signature. #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@?,C,N,Vstorage") == nil) } From d16dfcfad284579797b715302b90a67a2213be3f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:45:24 +0800 Subject: [PATCH 146/175] docs: correct the ivar type recovery proposal's log and change map --- Documentations/Evolutions/draft-objc-ivar-type-recovery.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index eee18201..e8bb1985 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -68,6 +68,7 @@ RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdapti | `Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift` | 修改 | 新增 `cTypeReplacements` | 调用方传 C 类型替换表 | 1 | | `Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift` | 修改 | 新增 `applyTransformers(_: Transformer.ObjCConfiguration)` | 与 Swift 一侧的 `applyTransformers` 对称 | 4 | | `Package.swift`(`SwiftPrinting` target) | 修改 | 依赖 `ObjCOutputTransformer` 与 `OutputTransformer` | `Transformer.CType.Pattern` 在前者,`Transformer` 命名空间在后者 | 1 | +| `Package.swift`(`SwiftInterfaceTests` target) | 修改 | 同样两个依赖 | 测试要写 `cTypeReplacements` 与 `Transformer.ObjCConfiguration`;两者都是图里已有包的 product,Tuist 清单不用改 | 4 | | `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift` | 修改 | `renderUnrepresentedObjCImplementationInstanceVariables` 先试还原,还原不出才打注释 | 行为本身 | 2–4 | | `Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift` | 修改 | ivar 行用同一还原,注释写来源 | dump 与 interface 一致 | 5 | | `Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift` | 修改 | 新增 ObjC 协议 `AdaptiveLayout`、遵循它的 Swift 类 `StandInAdaptiveLayout`(给协议属性一个初值)与 `AdaptiveTransitionWidget`(照 `_UISplitViewControllerAdaptiveLayoutTransition`):`NSObject`、`NSMutableString`(不桥接的类)、协议存在类型、`BOOL`、`CGFloat`(夹具里导入成 `Double`)、`NSInteger`、`readonly NSInteger`、`NSRange`、`readonly NSString`、`weak`、`NSArray`、`id`、纯 Swift 属性 | 覆盖每种 encoding | 1 | @@ -224,10 +225,11 @@ package struct ObjCInstanceVariableSwiftType { | 2026-11-26 | 开始实现 | 在 `feature/objc-ivar-type-recovery` 上按落地步骤做 | | 2026-11-26 | 还原结果存 `ObjCEncodedType`,不另设 `ObjCPrimitiveType` | `ObjCEncodedType` 在同一个包内可见,打印器直接对到 `Transformer.CType.Pattern`,少一个只为转一手的类型 | | 2026-11-26 | 夹具的 `CGFloat` 属性在 Swift 一侧写 `Double` | 夹具只 `import Foundation`,头文件的 `CGFloat` 导入成 `Double`,写 `CGFloat` 时 `@implementation` 的类型匹配报错 | +| 2026-11-26 | 加前提测试 | 第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(`ObjCImplementationClassFacts.InstanceVariable.name` 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实 | | 2026-11-26 | `weak` 属性挪到第 3 步,按 ObjC 属性读、不桥接 | 前提测试实测:`weak var observer: NSObject?` 的 ivar encoding 是 `?`,不是 `@"NSObject"` | -| 2026-11-26 | 第 2 步的修正与第 3 步同一个提交 | 第 2 步的首个提交在 Ultra 上编不过(解析器名写错)、修好后又发现声明被 `Rows` 拆成两行,两处修正与第 3 步的改动落在同几个文件里 | +| 2026-11-26 | 第 2 步的两处修正与第 3 步同一个提交 | 第 2 步的首个提交在 Ultra 上编不过(解析器名写错,单独一个提交修好);之后又发现声明被 `Rows` 拆成两行、ObjC 属性的查找名与 stand-in 不一致,这两处修正与第 3 步的改动落在同几个文件里 | | 2026-11-26 | 完整 encoding 的近似(枚举、`^v`、`#` 等)照打,写进假设 | 第 2 步审查指出;与 `CGFloat` / `Double` 同性质,ObjC 头文件一侧显示的也是同一个 C 类型 | | 2026-11-26 | `?` 只认桥接表里的类与裸 `id` | 第 3、4 步审查指出:`?` 证明 Swift 类型不是那个类本身,按导入规则照单全收会把 `unowned` 属性的存储(也写 `?`、特性里没有 `W`)和表外的桥接类(`NSAffineTransform` → `AffineTransform`)打成错的类 | | 2026-11-26 | `weak` 与 `readonly` 同时出现时仍写 `weak var` | `weak let`(SE-0481)要 Swift 6.2,源码更常见的是 `weak private(set) var`;无从区分时取更常见的写法 | +| 2026-11-26 | `applyTransformers(_: Transformer.ObjCConfiguration)` 与 Swift 一侧同名重载 | 调用点传的都是有类型的值(`transformer.objc`),不会歧义;只装 `cType`,`ivarOffset` 是 ObjC 头文件的 ivar 注释,Swift 一侧的偏移注释仍走 `fieldOffsetTransformer` | | 2026-11-26 | C 类型替换只换类型本身,替换名照原样打印 | 与假设一致;替换表的文档写明只收不带模块的名字。ObjC 一侧会递归替换指针里的类型,Swift 一侧不跟 | -| 2026-11-26 | 加前提测试 | 第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(`ObjCImplementationClassFacts.InstanceVariable.name` 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实 | From 807102cceaefda59ab7e85ca27a18bfacade885e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:47:15 +0800 Subject: [PATCH 147/175] docs: add the web page of the ivar type recovery proposal --- .../draft-objc-ivar-type-recovery.html | 388 ++++++++++++++++++ .../draft-objc-ivar-type-recovery.md | 1 + 2 files changed, 389 insertions(+) create mode 100644 Documentations/Evolutions/draft-objc-ivar-type-recovery.html diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.html b/Documentations/Evolutions/draft-objc-ivar-type-recovery.html new file mode 100644 index 00000000..87ce1fd9 --- /dev/null +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.html @@ -0,0 +1,388 @@ + + + + + + +Draft - @objc @implementation 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型 + + + + +

      + +
      +

      MachOSwiftSectionEvolutionsDraft

      +

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

      +
      +
      状态
      In Progress
      +
      最后更新
      2026-11-26
      +
      项目类型
      库
      +
      原文
      draft-objc-ivar-type-recovery.md
      +
      +
      + + + +
      + +
      +

      摘要

      +

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

      +
      + +
      +

      提议方案

      +

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

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

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

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

      非目标

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

      架构图

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

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

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

      改动地图

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

      落地步骤

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

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

      +
      + +
      +

      动机

      +
      + 为什么要做 +
      +

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

      +

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

      +
      +
      +
      +
      +

      前期调研

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

      详细设计

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

      替代方案

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

      影响

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

      源码兼容性(source compatibility)

      +

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

      +

      ABI 兼容性(条件项)

      +

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

      +

      下游影响

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

      文档与示例

      +

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

      +

      API 演进与废弃策略

      +

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

      +
      +
      +
      +
      +

      后续项

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

      决策日志

      +
      + 14 条 +
      +
      日期变更说明
      2026-11-26Created as Draft用户在 RuntimeViewer 里看到 UIKitCore 一个 @objc @implementation 类的存储属性大半只有注释,而 ObjC 一侧已显示出类型,要求能还原的都还原,类名经 type indexing 转 Swift 名
      2026-11-26用户经 implement-feature 批准,提案由 agent 起草、用户事前未审阅用户事先定了四点:对象类型写 T!;d 走 C 类型替换表;桥接集合也还原([Any]);方案照此开工
      2026-11-26开始实现在 feature/objc-ivar-type-recovery 上按落地步骤做
      2026-11-26还原结果存 ObjCEncodedType,不另设 ObjCPrimitiveTypeObjCEncodedType 在同一个包内可见,打印器直接对到 Transformer.CType.Pattern,少一个只为转一手的类型
      2026-11-26夹具的 CGFloat 属性在 Swift 一侧写 Double夹具只 import Foundation,头文件的 CGFloat 导入成 Double,写 CGFloat 时 @implementation 的类型匹配报错
      2026-11-26加前提测试第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(ObjCImplementationClassFacts.InstanceVariable.name 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实
      2026-11-26weak 属性挪到第 3 步,按 ObjC 属性读、不桥接前提测试实测:weak var observer: NSObject? 的 ivar encoding 是 ?,不是 @"NSObject"
      2026-11-26第 2 步的两处修正与第 3 步同一个提交第 2 步的首个提交在 Ultra 上编不过(解析器名写错,单独一个提交修好);之后又发现声明被 Rows 拆成两行、ObjC 属性的查找名与 stand-in 不一致,这两处修正与第 3 步的改动落在同几个文件里
      2026-11-26完整 encoding 的近似(枚举、^v、# 等)照打,写进假设第 2 步审查指出;与 CGFloat / Double 同性质,ObjC 头文件一侧显示的也是同一个 C 类型
      2026-11-26? 只认桥接表里的类与裸 id第 3、4 步审查指出:? 证明 Swift 类型不是那个类本身,按导入规则照单全收会把 unowned 属性的存储(也写 ?、特性里没有 W)和表外的桥接类(NSAffineTransform → AffineTransform)打成错的类
      2026-11-26weak 与 readonly 同时出现时仍写 weak varweak let(SE-0481)要 Swift 6.2,源码更常见的是 weak private(set) var;无从区分时取更常见的写法
      2026-11-26applyTransformers(_: Transformer.ObjCConfiguration) 与 Swift 一侧同名重载调用点传的都是有类型的值(transformer.objc),不会歧义;只装 cType,ivarOffset 是 ObjC 头文件的 ivar 注释,Swift 一侧的偏移注释仍走 fieldOffsetTransformer
      2026-11-26C 类型替换只换类型本身,替换名照原样打印与假设一致;替换表的文档写明只收不带模块的名字。ObjC 一侧会递归替换指针里的类型,Swift 一侧不跟
      2026-11-26实现完成,待用户看过后收尾五步都在 Ultra 上过了针对性测试;整套测试结果见收尾;RuntimeViewer 的接入随依赖版本一起做(后续项)
      +
      +
      +
      + +
      +
      + + diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md index e8bb1985..3fd786d2 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.md +++ b/Documentations/Evolutions/draft-objc-ivar-type-recovery.md @@ -233,3 +233,4 @@ package struct ObjCInstanceVariableSwiftType { | 2026-11-26 | `weak` 与 `readonly` 同时出现时仍写 `weak var` | `weak let`(SE-0481)要 Swift 6.2,源码更常见的是 `weak private(set) var`;无从区分时取更常见的写法 | | 2026-11-26 | `applyTransformers(_: Transformer.ObjCConfiguration)` 与 Swift 一侧同名重载 | 调用点传的都是有类型的值(`transformer.objc`),不会歧义;只装 `cType`,`ivarOffset` 是 ObjC 头文件的 ivar 注释,Swift 一侧的偏移注释仍走 `fieldOffsetTransformer` | | 2026-11-26 | C 类型替换只换类型本身,替换名照原样打印 | 与假设一致;替换表的文档写明只收不带模块的名字。ObjC 一侧会递归替换指针里的类型,Swift 一侧不跟 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 五步都在 Ultra 上过了针对性测试;整套测试结果见收尾;RuntimeViewer 的接入随依赖版本一起做(后续项) | From b8a383dee1703475f7d185fef1d8c5214b60cb8a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:55:25 +0800 Subject: [PATCH 148/175] feat(cross-reference-analysis): query a Swift type from the CLI, record selector and function address references MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - refs --type takes a Swift type's mangling (7SwiftUI4TextV) or a $s…Mn, $s…Ma or $s…N symbol of it, with --type-image for a type a dyld cache exports no descriptor of, and lists what the analyzer's type query finds. - CodeReferenceTarget.selector: a selector loaded but sent nothing with, filed under the selector's key beside its sends; the compact index keeps it, and symbolication now calls a selector reference slot a selector. - The collector records function address references for whole tables and function queries, and puts a selector reference back in its function's instruction order. - Tests: SelectorReferenceTests, SlotAddressReferenceTests, FunctionAddressReferenceTests, ReferencesRequestSwiftTypeTests; the selector request tests accept a selector reference as a use. Evolution proposal cross-reference-recall-gaps, now In Progress. --- Documentations/Evolutions/README.md | 2 +- .../draft-cross-reference-recall-gaps.html | 2 +- .../draft-cross-reference-recall-gaps.md | 2 +- Documentations/README.md | 2 +- .../Visions/ReverseEngineeringWithoutIDA.md | 2 +- ...CrossReferenceAnalyzer+Symbolication.swift | 2 +- .../CrossReferenceAnalyzer.swift | 50 ++++++++-- .../Models/CodeReference.swift | 7 ++ .../Models/CodeReferenceIndex.swift | 9 +- .../Models/CodeReferenceTable.swift | 2 +- .../CrossReferenceFormatting.swift | 4 + .../CrossReferences/CrossReferenceInput.swift | 11 +++ .../CrossReferences/ReferencesRequest.swift | 96 ++++++++++++++++++- .../Commands/ReferencesCommand.swift | 19 +++- .../Models/CommandLineSupport.swift | 2 + .../FunctionAddressReferenceTests.swift | 67 +++++++++++++ .../SelectorReferenceTests.swift | 89 +++++++++++++++++ .../SlotAddressReferenceTests.swift | 44 +++++++++ .../StandaloneFileReferenceDumpTests.swift | 2 + .../CrossReferenceCommandTests.swift | 7 ++ .../CrossReferenceRequestTests.swift | 19 ++-- .../ReferencesRequestSwiftTypeTests.swift | 74 ++++++++++++++ 22 files changed, 485 insertions(+), 29 deletions(-) create mode 100644 Tests/CrossReferenceAnalysisTests/FunctionAddressReferenceTests.swift create mode 100644 Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift create mode 100644 Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift create mode 100644 Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 021d6f1b..117ffee1 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -126,4 +126,4 @@ | [0109](0109-consistent-c-imported-type-spelling.md) | C 导入类型的拼写补齐:同名类型去掉 `__C`,布局注释跟着打印器的拼写 | Implemented | | [0110](0110-unify-evolution-integration-suites.md) | IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 | Implemented | | [0111](0111-unify-diff-and-interface-integration-suites.md) | IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 | Implemented | -| draft | [交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法](draft-cross-reference-recall-gaps.md)(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Accepted | +| draft | [交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法](draft-cross-reference-recall-gaps.md)(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | In Progress | diff --git a/Documentations/Evolutions/draft-cross-reference-recall-gaps.html b/Documentations/Evolutions/draft-cross-reference-recall-gaps.html index 41fe2b84..abd8ed6a 100644 --- a/Documentations/Evolutions/draft-cross-reference-recall-gaps.html +++ b/Documentations/Evolutions/draft-cross-reference-recall-gaps.html @@ -163,7 +163,7 @@

      MachOSwiftSectionEvolutionsDraft

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

      -
      状态
      Accepted
      +
      状态
      In Progress
      最后更新
      2026-11-26
      项目类型
      库
      原文
      draft-cross-reference-recall-gaps.md
      diff --git a/Documentations/Evolutions/draft-cross-reference-recall-gaps.md b/Documentations/Evolutions/draft-cross-reference-recall-gaps.md index ef4c68c5..939cb02b 100644 --- a/Documentations/Evolutions/draft-cross-reference-recall-gaps.md +++ b/Documentations/Evolutions/draft-cross-reference-recall-gaps.md @@ -1,6 +1,6 @@ # Draft - 交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-26 - **最后更新**: 2026-11-26 diff --git a/Documentations/README.md b/Documentations/README.md index 4c92560c..efd26df0 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -230,7 +230,7 @@ selects names using each access's offset and width. | [Evolutions/0109-consistent-c-imported-type-spelling.md](Evolutions/0109-consistent-c-imported-type-spelling.md) | **提案 0109(Implemented)**:C 导入类型的拼写补齐——0106 之后还剩两处混用:镜像里有描述符、Swift 名与 C 名相同的类型,声明写裸名而引用与扩展头写 `__C::`;展开字段偏移树的注释用固定的 `.default` 印类型名(C 名、点号限定、不带模块选择器与 `any`)。名字表收下没有 ABI 名的描述符(编译器只在两个名字不同时才写 ABI 名),引用改写裸名;interface 的布局注释经打印器自己的类型拼写印类型名,离线与进程内两条后端一起改,dump 不变。本镜像没有描述符的类型照旧写 `__C::`。 | | [Evolutions/0110-unify-evolution-integration-suites.md](Evolutions/0110-unify-evolution-integration-suites.md) | **提案 0110(Implemented)**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自重复定义同几条版本轴、互相借用对方的类属性,每条管线又把单镜像与镜像组写两遍。合成一套:`Tests/IntegrationTests/Evolution/` 下版本轴只定义一次、按读的元数据(`__swift5_*` / `__objc_*`)筛版本,四条管线收进一个协议,21 个套件类变成 10 个轴套件,43 个「轴 × 输出」组合与输出文件名不变。 | | [Evolutions/0111-unify-diff-and-interface-integration-suites.md](Evolutions/0111-unify-diff-and-interface-integration-suites.md) | **提案 0111(Implemented)**:IntegrationTests 的 diff 与单版本接口两类手检套件按 0110 的结构统一,三类输出(接口、diff、演进)进同一个目录 `Tests/IntegrationTests/InspectionDumps/`、共用一个公共协议;diff 改用演进的版本轴(cache 对因此整份打开,与 CLI 一致),每类一个「输出种类」枚举加一个 `dump` 入口;AppKit 的接口与 diff 套件多出 ObjC 头文件与 ObjC 变更列表。测试 20 个变 38 个,演进的 43 个不变。 | -| [Evolutions/draft-cross-reference-recall-gaps.md](Evolutions/draft-cross-reference-recall-gaps.md) | **提案 draft(Accepted)**:交叉引用召回补漏——2026-11-26 按 2026-11-18 的方法复测,`swift-section refs` 0.25.0 代码引用召回 90.3%(476/527),IDA 一次查询 97.0%;补四处缺口:CLI 加 `--type` 按 Swift 类型查询、取到 GOT 槽地址也算类引用、没被发送用掉的 selref 载入记成 selector 引用、一种 `adrp; add; ldrsw [xN]` 的 ivar 读法;第 5 步把取函数地址记成对函数的引用;测量脚本进 `Scripts/CrossReferenceRecall/` 作验收。跨 MachOKitExtensions、MachOObjCSection 与 RuntimeViewer | +| [Evolutions/draft-cross-reference-recall-gaps.md](Evolutions/draft-cross-reference-recall-gaps.md) | **提案 draft(In Progress)**:交叉引用召回补漏——2026-11-26 按 2026-11-18 的方法复测,`swift-section refs` 0.25.0 代码引用召回 90.3%(476/527),IDA 一次查询 97.0%;补四处缺口:CLI 加 `--type` 按 Swift 类型查询、取到 GOT 槽地址也算类引用、没被发送用掉的 selref 载入记成 selector 引用、一种 `adrp; add; ldrsw [xN]` 的 ivar 读法;第 5 步把取函数地址记成对函数的引用;测量脚本进 `Scripts/CrossReferenceRecall/` 作验收。跨 MachOKitExtensions、MachOObjCSection 与 RuntimeViewer | | [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Documentations/Visions/ReverseEngineeringWithoutIDA.md b/Documentations/Visions/ReverseEngineeringWithoutIDA.md index c47d8599..24abf2a9 100644 --- a/Documentations/Visions/ReverseEngineeringWithoutIDA.md +++ b/Documentations/Visions/ReverseEngineeringWithoutIDA.md @@ -214,7 +214,7 @@ |------|------|------------------------| | [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) | Implemented | 第 1 阶段:交叉引用与地址符号化扩展到磁盘文件和归档 cache,并接到 `swift-section` 与 RuntimeViewer 的 CLI / MCP;顺带把交叉引用按「我们选的方向」第 6 条拆成核心、ObjC、Swift 三层(真正迁出本库另写提案) | | [0098 move-cross-reference-layers](../Evolutions/0098-move-cross-reference-layers.md) | Accepted | 「我们选的方向」第 6 条:把 0097 拆出的核心层与地址解析、ARM64 解码搬进 MachOKitExtensions,ObjC 层搬进 MachOObjCSection,随本库 0.25.0 落地 | -| [draft-cross-reference-recall-gaps](../Evolutions/draft-cross-reference-recall-gaps.md) | Accepted | 第 1 阶段的补漏:按「我们选的方向」第 1 条的复测(2026-11-26,90.3% 对 IDA 97.0%)补上四处缺口——CLI 按 Swift 类型查询、取 GOT 槽地址的类引用、selector 引用、一种 ivar 读法,并把取函数地址记成对函数的引用;测量脚本进仓库作为第 7 条「标准答案」的验收工具 | +| [draft-cross-reference-recall-gaps](../Evolutions/draft-cross-reference-recall-gaps.md) | In Progress | 第 1 阶段的补漏:按「我们选的方向」第 1 条的复测(2026-11-26,90.3% 对 IDA 97.0%)补上四处缺口——CLI 按 Swift 类型查询、取 GOT 槽地址的类引用、selector 引用、一种 ivar 读法,并把取函数地址记成对函数的引用;测量脚本进仓库作为第 7 条「标准答案」的验收工具 | --- diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift index 9b00fb67..50f7c1e0 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift @@ -129,7 +129,7 @@ extension CrossReferenceAnalyzer { case .address(let value)?: switch kind { case .selectorReference: - if let selector = cString(atRuntimeAddress: value) { return .messageSend(selector: selector, receiver: .unknown) } + if let selector = cString(atRuntimeAddress: value) { return .selector(selector) } case .protocolReference: // `protocol_t`: `isa`, then the name. if let nameAddress = memory.pointer(at: value &+ 8), let name = cString(atRuntimeAddress: nameAddress) { return .cString(name) } diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift index df4cd8a7..1a9b2ad9 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift @@ -390,7 +390,7 @@ public final class CrossReferenceAnalyzer: @unchecked Sendable { ) -> [CodeReference] { let collector = ReferenceCollector(keeping: keys, matching: query) let sessions: [any CodeReferenceRecognitionSession] = [ - objectiveC.makeSession(table: table, recording: collector, findsClassReferences: collector.findsTypeReferences), + objectiveC.makeSession(table: table, recording: collector, findsClassReferences: collector.findsTypeReferences, findsSelectorReferences: collector.findsSelectorReferences), swift.makeSession(table: table, recording: collector, findsTypeReferences: collector.findsTypeReferences), ] var scanner = ReferenceScanner( @@ -400,7 +400,8 @@ public final class CrossReferenceAnalyzer: @unchecked Sendable { recording: collector, followsBranches: followsBranches, recordsStringReferences: collector.findsStrings(whenWholeImage: recordsStringReferences), - recordsImportedSymbolReferences: collector.findsImportedSymbolReferences + recordsImportedSymbolReferences: collector.findsImportedSymbolReferences, + recordsFunctionAddressReferences: collector.findsFunctionAddressReferences ) body(&scanner, collector) return collector.references @@ -511,8 +512,23 @@ final class ReferenceCollector: ObjCCodeReferenceRecording, SwiftCodeReferenceRe self.findsImportedSymbolReferences = keptKeys.map { keys in keys.contains { if case .importedSymbol = $0 { true } else { false } } } ?? true + self.findsSelectorReferences = keptKeys.map { keys in + keys.contains { if case .selector = $0 { true } else { false } } + } ?? true + self.findsFunctionAddressReferences = keptKeys.map { keys in + keys.contains { if case .function = $0 { true } else { false } } + } ?? true } + /// Whether the selectors code loads but sends nothing with are recorded: + /// for a whole image, or for a query for a selector. + let findsSelectorReferences: Bool + + /// Whether the addresses code builds of a function's start are recorded + /// as references to the function: for a whole image, or for a query for + /// a function's callers. + let findsFunctionAddressReferences: Bool + /// Whether loads from slots that bind to another image's symbol are /// recorded: for a whole image, or for a query for an imported name. let findsImportedSymbolReferences: Bool @@ -530,13 +546,16 @@ final class ReferenceCollector: ObjCCodeReferenceRecording, SwiftCodeReferenceRe } private func keep(_ target: CodeReferenceTarget, at site: ScanSite, isRuntimeHelperCall: Bool = false) { - if let keptKeys { - let isFiled = if let key = target.tableKey { keptKeys.contains(key) } else { false } - guard isFiled || swiftTypeQuery?.matches(target) == true else { return } - } + guard isKept(target) else { return } references.append(CodeReference(function: site.function, instructionAddress: site.instructionAddress, kind: site.kind, target: target, route: site.route, isRuntimeHelperCall: isRuntimeHelperCall)) } + private func isKept(_ target: CodeReferenceTarget) -> Bool { + guard let keptKeys else { return true } + let isFiled = if let key = target.tableKey { keptKeys.contains(key) } else { false } + return isFiled || swiftTypeQuery?.matches(target) == true + } + func recordCall(to target: ResolvedCallTarget, targetAddress: UInt64, at site: ScanSite, isRuntimeHelperCall: Bool) { switch target { case .function(let location): @@ -568,6 +587,25 @@ final class ReferenceCollector: ObjCCodeReferenceRecording, SwiftCodeReferenceRe keep(.objectiveCInstanceVariable(className: className, name: name), at: site) } + /// Recorded when the scan leaves the function that loads the selector, + /// after the function's later references: put back in instruction order, + /// which a function's references are listed in. + func recordSelectorReference(selector: String, at site: ScanSite) { + let target = CodeReferenceTarget.selector(selector) + guard isKept(target) else { return } + var insertionIndex = references.endIndex + while insertionIndex > references.startIndex, + references[insertionIndex - 1].function == site.function, + references[insertionIndex - 1].instructionAddress > site.instructionAddress { + insertionIndex -= 1 + } + references.insert(CodeReference(function: site.function, instructionAddress: site.instructionAddress, kind: site.kind, target: target, route: site.route, isRuntimeHelperCall: false), at: insertionIndex) + } + + func recordFunctionAddressReference(to function: CodeLocation, at site: ScanSite) { + keep(.function(function), at: site) + } + func recordString(_ string: StringLiteralReference, at site: ScanSite) { switch string { case .cString(let characters): diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift index b3f134da..aee7e6bd 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift @@ -41,6 +41,13 @@ public enum CodeReferenceTarget: Hashable, Sendable { /// (`_OBJC_IVAR_$_.`): the class that declares it, by /// its runtime name, and the variable's name. case objectiveCInstanceVariable(className: String, name: String) + /// A selector the code loads but sends no message with: it hands the + /// selector on — to `respondsToSelector:` or `performSelector:`, as a + /// return value, as a control's action. Filed under the same table key as + /// the selector's sends. Found only where code loads the selector from + /// the image's `__objc_selrefs`: a dyld shared cache's builder rewrites + /// those loads into the selector string's address. + case selector(String) /// A C string literal whose address the code takes, by its characters. /// Recorded only when string references are: see /// ``CrossReferenceAnalyzer/recordsStringReferences``. diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift index a5bc7600..505e58cd 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift @@ -43,6 +43,7 @@ public struct CodeReferenceIndex: Sendable { case importedSymbol(name: String) case messageSend(selector: String) case superMessageSend(selector: String) + case selector(String) case objectiveCClass(name: String, location: CodeLocation) case swiftType(descriptor: CodeLocation) case swiftTypeName(SwiftTypeName) @@ -161,6 +162,8 @@ public struct CodeReferenceIndex: Sendable { return .messageSend(selector: selector, receiver: receiver) case .superMessageSend(let selector): return .superMessageSend(selector: selector, className: className) + case .selector(let selector): + return .selector(selector) case .objectiveCClass(let name, let location): return .objectiveCClass(name: name, location: location) case .swiftType(let descriptor): @@ -228,6 +231,8 @@ public struct CodeReferenceIndex: Sendable { case .superMessageSend(let selector, let superclassName): target = .superMessageSend(selector: selector) className = superclassName + case .selector(let selector): + target = .selector(selector) case .objectiveCClass(let name, let location): target = .objectiveCClass(name: name, location: location) case .swiftType(let descriptor): @@ -287,7 +292,7 @@ public struct CodeReferenceIndex: Sendable { keyedTargets[.function(location), default: []].append(target) case .importedSymbol(let name): keyedTargets[.importedSymbol(name), default: []].append(target) - case .messageSend(let selector), .superMessageSend(let selector): + case .messageSend(let selector), .superMessageSend(let selector), .selector(let selector): keyedTargets[.selector(selector), default: []].append(target) case .objectiveCClass(let name, _): keyedTargets[.objectiveCClass(name), default: []].append(target) @@ -360,7 +365,7 @@ public struct CodeReferenceIndex: Sendable { private static func heapByteCount(of target: Target) -> Int { switch target { - case .importedSymbol(let name), .messageSend(let name), .superMessageSend(let name), .objectiveCClass(let name, _), .cString(let name), .constantString(let name): + case .importedSymbol(let name), .messageSend(let name), .superMessageSend(let name), .selector(let name), .objectiveCClass(let name, _), .cString(let name), .constantString(let name): return heapByteCount(of: name) case .objectiveCInstanceVariable(let className, let name): return heapByteCount(of: className) + heapByteCount(of: name) diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift index 7b3cab31..6bcc1de8 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift @@ -74,7 +74,7 @@ extension CodeReferenceTarget { switch self { case .function(let location): return .function(location) - case .messageSend(let selector, _), .superMessageSend(let selector, _): + case .messageSend(let selector, _), .superMessageSend(let selector, _), .selector(let selector): return .selector(selector) case .importedSymbol(let name): return .importedSymbol(name) diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift index 2521db51..5bcd1e77 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift @@ -190,6 +190,8 @@ final class CrossReferenceTargetNaming { return .object(["objectiveCClass": .object(members)]) case .objectiveCInstanceVariable(let className, let name): return .object(["instanceVariable": .object(["class": .string(className), "name": .string(name)])]) + case .selector(let selector): + return .object(["selector": .string(selector)]) case .cString(let characters): return .object(["cString": .string(characters)]) case .constantString(let characters): @@ -230,6 +232,8 @@ final class CrossReferenceTargetNaming { return "class \(name) (\(CrossReferenceFormatting.imageName(ofPath: imagePath(of: location))))" case .objectiveCInstanceVariable(let className, let name): return "ivar \(className).\(name)" + case .selector(let selector): + return "selector \(selector)" case .cString(let characters): return "C string \(CrossReferenceFormatting.quoted(characters))" case .constantString(let characters): diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift index 7b350a79..8404a408 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift @@ -32,6 +32,13 @@ public enum CrossReferenceRequestError: Error, LocalizedError, Sendable, Equatab case symbolIsNoFunction(name: String) /// No analyzed image defines or imports a class of this name. case classNotFound(name: String) + /// No analyzed image — or none of the one named — defines a Swift type + /// with this mangling. + case swiftTypeNotFound(mangling: String) + /// A dyld shared cache's images export no descriptor of a Swift type + /// with this mangling: the image that defines it must be named, since + /// working out every image's type keys takes minutes. + case swiftTypeNeedsImage(mangling: String) /// No function of the image the address was looked up in holds it. case noFunction(address: UInt64) /// Several of the files hold a function at the address; the image must @@ -54,6 +61,10 @@ public enum CrossReferenceRequestError: Error, LocalizedError, Sendable, Equatab "The symbol '\(name)' does not name the start of a function." case .classNotFound(let name): "No analyzed image defines or imports an Objective-C class named '\(name)'." + case .swiftTypeNotFound(let mangling): + "No analyzed image defines a Swift type whose mangling is '\(mangling)'." + case .swiftTypeNeedsImage(let mangling): + "No image of the dyld shared cache exports a descriptor of '\(mangling)'; name the image that defines it." case .noFunction(let address): "No function holds the address \(CrossReferenceFormatting.hexadecimal(address))." case .ambiguousFunction(let address, let imagePaths): diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift index 445981e2..65a886f3 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift @@ -22,6 +22,12 @@ public enum CrossReferenceSubject: Sendable, Hashable { case instanceVariable(className: String, name: String) /// A C string or constant `CFString` literal with these characters. case string(String) + /// A Swift struct, enum or class by its mangling — `7SwiftUI4TextV` — or + /// by a `$s…Mn`, `$s…Ma` or `$s…N` symbol of it (its descriptor, its + /// metadata accessor, its metadata), defined in the image `imageName` + /// names, or in whichever image exports its descriptor. A Swift class is + /// also referenced as the Objective-C class it is. + case swiftType(String, imageName: String?) } /// Which way `refs` follows a function. @@ -40,8 +46,9 @@ public enum CrossReferenceOutputFormat: Sendable, Hashable { } /// `swift-section refs`: the code that references a selector, a symbol, a -/// class, a function, an instance variable or a string — or, for a function, -/// what it references — across a dyld shared cache or a set of files. +/// class, a function, an instance variable, a string or a Swift type — or, +/// for a function, what it references — across a dyld shared cache or a set +/// of files. /// /// The images that can reference the subject are found first, from their /// symbol tables, selector references and linkage; only those are scanned, @@ -91,6 +98,9 @@ public struct ReferencesRequest: Sendable, Equatable { case .callers(let keys, let candidates): references = await Self.references(to: keys, inImagesAt: candidates, analyzer: analyzer).filter(query.acceptsReference) scannedImageCount = candidates.count + case .swiftTypes(let identities, let candidates): + references = await Self.references(toSwiftTypes: identities, inImagesAt: candidates, analyzer: analyzer) + scannedImageCount = candidates.count } let referenceCount = references.count let referencingImageCount = Set(references.map(\.function.imageIndex)).count @@ -151,6 +161,32 @@ public struct ReferencesRequest: Sendable, Equatable { } } + /// The references to any of `identities` in each candidate image, + /// concurrently, in candidate order. A type defined by two variants of a + /// framework has an identity each; a reference matching both is listed + /// once. + private static func references(toSwiftTypes identities: [SwiftTypeIdentity], inImagesAt candidates: [Int], analyzer: CrossReferenceAnalyzer) async -> [CodeReference] { + await withCheckedContinuation { continuation in + scanQueue.async { + let results = ImageResults(count: candidates.count) + DispatchQueue.concurrentPerform(iterations: candidates.count) { position in + var seen = Set() + var references: [CodeReference] = [] + for identity in identities { + for reference in analyzer.references(toSwiftType: identity, inImageAt: candidates[position]) where seen.insert(reference).inserted { + references.append(reference) + } + } + if identities.count > 1 { + references.sort { ($0.instructionAddress, $0.function.address) < ($1.instructionAddress, $1.function.address) } + } + results.store(references, at: position) + } + continuation.resume(returning: results.joined()) + } + } + } + /// One slot an image, each written by one iteration alone. private final class ImageResults: @unchecked Sendable { private var slots: [[CodeReference]] @@ -241,6 +277,10 @@ private struct ResolvedQuery { enum Search { case callers(keys: Set, candidates: [Int]) case callees(CodeFunction) + /// A Swift type's references, matched by the analyzer's type query + /// rather than by table keys: they are filed by descriptor, and a + /// mangled name may spell the type. + case swiftTypes([SwiftTypeIdentity], candidates: [Int]) } var search: Search @@ -309,7 +349,59 @@ private struct ResolvedQuery { // Any image can hold the literal; none is ruled out. search = .callers(keys: [.cString(characters), .constantString(characters)], candidates: scope) jsonDescription = ["string": .string(characters)] + case .swiftType(let spelling, let imageName): + let mangling = Self.swiftTypeMangling(spelledAs: spelling) + let identities = try Self.swiftTypeIdentities(mangling: mangling, imageName: imageName, input: input, analyzer: analyzer) + var candidates = Set() + for identity in identities { + candidates.formUnion(analyzer.imageIndices(referencingSwiftType: identity, among: scope)) + } + search = .swiftTypes(identities, candidates: candidates.sorted()) + jsonDescription = ["swiftType": .string(mangling)] + } + } + + /// The nominal mangling `spelling` names: itself, or — for a symbol, + /// `$s` first and `_` before it optionally — the symbol without its + /// prefix and its descriptor (`Mn`), accessor (`Ma`) or metadata (`N`) + /// suffix. A mangling on its own ends with its kind (`V`, `C`, `O`, `a` + /// for a C type), never with one of those suffixes. + static func swiftTypeMangling(spelledAs spelling: String) -> String { + var mangling = Substring(spelling) + if mangling.hasPrefix("_") { mangling = mangling.dropFirst() } + guard mangling.hasPrefix("$s") else { return spelling } + mangling = mangling.dropFirst(2) + for suffix in ["Mn", "Ma", "N"] where mangling.hasSuffix(suffix) && mangling.count > suffix.count { + return String(mangling.dropLast(suffix.count)) + } + return String(mangling) + } + + /// The Swift types with `mangling`: in the image `imageName` names, or + /// wherever a `$s…Mn` symbol puts the descriptor, or — for a set of + /// files, which are few — in whichever file defines one. + private static func swiftTypeIdentities(mangling: String, imageName: String?, input: CrossReferenceInput, analyzer: CrossReferenceAnalyzer) throws -> [SwiftTypeIdentity] { + let allImages = 0 ..< analyzer.imageCount + let descriptors: [CodeLocation] + if let imageName { + descriptors = try analyzer.imageIndices(named: [imageName]).flatMap { analyzer.swiftTypeDescriptorLocations(withKey: mangling, inImageAt: $0) } + } else { + let exported = analyzer.locations(ofSymbolNamed: "_$s" + mangling + "Mn", among: allImages) + if !exported.isEmpty { + descriptors = exported + } else if case .files = input { + descriptors = allImages.flatMap { analyzer.swiftTypeDescriptorLocations(withKey: mangling, inImageAt: $0) } + } else { + throw CrossReferenceRequestError.swiftTypeNeedsImage(mangling: mangling) + } + } + var identities: [SwiftTypeIdentity] = [] + for descriptor in descriptors { + guard let identity = analyzer.swiftTypeIdentity(ofDescriptorAt: descriptor), !identities.contains(identity) else { continue } + identities.append(identity) } + guard !identities.isEmpty else { throw CrossReferenceRequestError.swiftTypeNotFound(mangling: mangling) } + return identities } private init(search: Search, acceptsReference: @escaping (CodeReference) -> Bool, jsonDescription: [String: CrossReferenceJSONValue]) { diff --git a/Sources/Executables/swift-section/Commands/ReferencesCommand.swift b/Sources/Executables/swift-section/Commands/ReferencesCommand.swift index 14bf059b..71234280 100644 --- a/Sources/Executables/swift-section/Commands/ReferencesCommand.swift +++ b/Sources/Executables/swift-section/Commands/ReferencesCommand.swift @@ -5,7 +5,7 @@ import SwiftSectionKit struct ReferencesCommand: AsyncParsableCommand { static let configuration: CommandConfiguration = .init( commandName: "refs", - abstract: "List the code that references a selector, a symbol, a class, a function, an instance variable or a string — or what a function references — across a dyld shared cache or a set of arm64 Mach-O files.", + abstract: "List the code that references a selector, a symbol, a class, a function, an instance variable, a string or a Swift type — or what a function references — across a dyld shared cache or a set of arm64 Mach-O files.", discussion: "Addresses in and out are unslid, as IDA, ipsw and dyld_info show them. Each line is a reference: the referencing instruction's address, its image, its function and the offset into it, the reference's kind and route, and what it references." ) @@ -14,7 +14,7 @@ struct ReferencesCommand: AsyncParsableCommand { @OptionGroup var inputOptions: CrossReferenceInputOptionGroup - @Option(help: "Every send of this selector, super sends included (makeKeyAndOrderFront:).") + @Option(help: "Every send of this selector, super sends included (makeKeyAndOrderFront:), and every other use of it: an argument of respondsToSelector: or performSelector:, a returned selector, an action.") var selector: String? @Option(help: "The callers of the function this symbol names, with its leading underscore: a C function, a Swift mangled name, _OBJC_CLASS_$_ or _OBJC_IVAR_$_.. A function no analyzed image defines is looked for as the imported symbol it is.") @@ -38,6 +38,12 @@ struct ReferencesCommand: AsyncParsableCommand { @Option(help: "Every reference to a C string or constant CFString literal with these characters.") var string: String? + @Option(name: .customLong("type"), help: "Every reference to the Swift struct, enum or class with this mangling (7SwiftUI4TextV), or to the one a $s…Mn, $s…Ma or $s…N symbol names: its metadata accessor called or its address taken, its metadata, a mangled name spelling it.") + var swiftType: String? + + @Option(name: .customLong("type-image"), help: "The image that defines --type's type, by path or file name: needed in a dyld shared cache for a type no image exports.") + var swiftTypeImage: String? + @Option(help: "Report at most this many references, the first in image and address order.") var limit: Int? @@ -45,10 +51,11 @@ struct ReferencesCommand: AsyncParsableCommand { var json: Bool = false func validate() throws { - let queryCount = [selector, symbol, className, function, instanceVariable, string].compactMap { $0 }.count + let queryCount = [selector, symbol, className, function, instanceVariable, string, swiftType].compactMap { $0 }.count guard queryCount == 1 else { - throw ValidationError("Name exactly one of --selector, --symbol, --class, --function, --ivar and --string.") + throw ValidationError("Name exactly one of --selector, --symbol, --class, --function, --ivar, --string and --type.") } + if swiftTypeImage != nil, swiftType == nil { throw ValidationError("--type-image names the image that defines --type's type; it needs --type.") } if callees, function == nil { throw ValidationError("--callees lists a function's references; it needs --function.") } if functionImage != nil, function == nil { throw ValidationError("--function-image names the image of --function's address; it needs --function.") } if let instanceVariable, !Self.isQualifiedInstanceVariableName(instanceVariable) { @@ -79,8 +86,10 @@ struct ReferencesCommand: AsyncParsableCommand { subject = .instanceVariable(className: String(instanceVariable[.. + extern void consume(int value); + __attribute__((noinline)) void work(void *context) { consume((int)(long)context); } + void scheduleWork(void) { dispatch_async_f(dispatch_get_main_queue(), 0, work); } + void callWork(void) { work(0); } + void scheduleBlock(int value) { dispatch_async(dispatch_get_main_queue(), ^{ consume(value); }); } + """ + + private static func analyzer() throws -> CrossReferenceAnalyzer { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "FunctionAddressReferences", + language: .c, + sourceFiles: [FixtureSourceFile(name: "FunctionAddressReferences.c", contents: source)], + arguments: ["-arch", "arm64", "-O2", "-fblocks", "-Wl,-undefined,dynamic_lookup"] + ) + return try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) + } + + private static func function(where matches: (String) -> Bool, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: 0).first { if case .symbol(let symbol)? = $0.name { matches(symbol) } else { false } }) + } + + @Test func functionQueriesReturnCallsAndAddressTakingSites() throws { + let analyzer = try Self.analyzer() + let work = try Self.function(where: { $0 == "_work" }, in: analyzer) + let scheduleWork = try Self.function(where: { $0 == "_scheduleWork" }, in: analyzer) + let callWork = try Self.function(where: { $0 == "_callWork" }, in: analyzer) + let references = analyzer.references(to: [.function(work.location)], inImageAt: 0) + // `callWork` calls it, or branches to it. + #expect(references.contains { $0.function == callWork.location && $0.kind != .reference }) + // `scheduleWork` builds its address for `dispatch_async_f`. + let taken = references.filter { $0.function == scheduleWork.location } + #expect(taken.count == 1) + #expect(taken.first?.kind == .reference) + #expect(taken.first?.route == .addressMaterialization) + } + + @Test func aStackBlockIsReferencedByTheFunctionThatBuildsIt() throws { + let analyzer = try Self.analyzer() + let scheduleBlock = try Self.function(where: { $0 == "_scheduleBlock" }, in: analyzer) + let invoke = try Self.function(where: { $0.hasPrefix("___scheduleBlock_block_invoke") }, in: analyzer) + let references = analyzer.references(to: [.function(invoke.location)], inImageAt: 0) + #expect(references.contains { $0.function == scheduleBlock.location && $0.kind == .reference }) + } + + /// The whole image's table carries them too. + @Test func theWholeTableHoldsFunctionAddressReferences() throws { + let analyzer = try Self.analyzer() + let work = try Self.function(where: { $0 == "_work" }, in: analyzer) + let table = analyzer.referenceTable(ofImageAt: 0) + #expect(table.references(to: .function(work.location)).contains { $0.kind == .reference }) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift new file mode 100644 index 00000000..1ca3d6f9 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift @@ -0,0 +1,89 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@testable import CrossReferenceAnalysis + +/// A selector code loads but sends nothing with is a selector reference, +/// filed under the selector's key beside its sends (evolution proposal +/// `cross-reference-recall-gaps`): an argument of `respondsToSelector:` or +/// `performSelector:`, a returned selector. +@Suite +struct SelectorReferenceTests { + private static let source = """ + #import + BOOL probeResponds(id object) { + return [object respondsToSelector:@selector(coalescingNodeObserver:openSyncCompleted:)]; + } + SEL probeReturnsSelector(void) { + return @selector(name); + } + id probePerforms(id object) { + return [object performSelector:@selector(copy)]; + } + """ + + /// Classic sends: the selector references are loaded in the functions + /// themselves, the shape a selector stub hides. + private static func analyzer() throws -> CrossReferenceAnalyzer { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SelectorReferences", + language: .c, + sourceFiles: [FixtureSourceFile(name: "SelectorReferences.m", contents: source)], + arguments: ["-arch", "arm64", "-O2", "-fno-objc-msgsend-selector-stubs", "-framework", "Foundation"] + ) + return try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) + } + + private static func function(named name: String, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: 0).first { if case .symbol(name)? = $0.name { true } else { false } }) + } + + @Test func selectorQueriesReturnSendsAndSelectorReferences() throws { + let analyzer = try Self.analyzer() + let performs = try Self.function(named: "_probePerforms", in: analyzer) + let copies = analyzer.references(to: [.selector("copy")], inImageAt: 0) + #expect(copies.map(\.target) == [.selector("copy")]) + #expect(copies.allSatisfy { $0.function == performs.location && $0.kind == .reference }) + let performSelectors = analyzer.references(to: [.selector("performSelector:")], inImageAt: 0) + #expect(performSelectors.contains { if case .messageSend("performSelector:", _) = $0.target { true } else { false } }) + #expect(!performSelectors.contains { $0.target == .selector("performSelector:") }) + #expect(analyzer.references(to: [.selector("name")], inImageAt: 0).map(\.target) == [.selector("name")]) + #expect(analyzer.references(to: [.selector("coalescingNodeObserver:openSyncCompleted:")], inImageAt: 0).map(\.target) == [.selector("coalescingNodeObserver:openSyncCompleted:")]) + } + + @Test func selectorReferencesSurviveTheCompactIndex() throws { + let analyzer = try Self.analyzer() + let index = analyzer.referenceIndex(ofImageAt: 0) + for selector in ["copy", "name", "performSelector:"] { + #expect(Set(index.references(to: [.selector(selector)])) == Set(analyzer.references(to: [.selector(selector)], inImageAt: 0)), "\(selector)") + } + } + + /// Recorded when the scan leaves the function, a selector reference is + /// listed where its instruction lies among the function's references. + @Test func aFunctionsReferencesStayInInstructionOrder() throws { + let analyzer = try Self.analyzer() + let references = try analyzer.references(madeBy: Self.function(named: "_probePerforms", in: analyzer)) + #expect(references.contains { $0.target == .selector("copy") }) + #expect(references.map(\.instructionAddress) == references.map(\.instructionAddress).sorted()) + } + + @Test func symbolicationCallsASelectorReferenceSlotASelector() throws { + let analyzer = try Self.analyzer() + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SelectorReferences", + language: .c, + sourceFiles: [FixtureSourceFile(name: "SelectorReferences.m", contents: Self.source)], + arguments: ["-arch", "arm64", "-O2", "-fno-objc-msgsend-selector-stubs", "-framework", "Foundation"] + ) + let machO = try MachOFile(url: library) + let selectorReferences = try #require(machO.sections64.first { $0.segmentName == "__DATA" && $0.sectionName == "__objc_selrefs" }) + let meaning = analyzer.symbolication(of: UInt64(selectorReferences.address), inImageAt: 0).meaning + guard case .pointerSlot(.selectorReference, let target) = meaning, case .selector = target else { + Issue.record("\(meaning)") + return + } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift new file mode 100644 index 00000000..38c921f1 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift @@ -0,0 +1,44 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@testable import CrossReferenceAnalysis + +/// Optimized Swift code hands an Objective-C class's GOT slot to the merged +/// helper that makes the class's metadata (`$sSo…CMaTm`), building only the +/// slot's address: `adrp x2; add x2, ; bl`. That `add` references the +/// class (evolution proposal `cross-reference-recall-gaps`; ControlCenter +/// 26.7 has 554 such calls). +@Suite +struct SlotAddressReferenceTests { + private static func analyzer() throws -> (analyzer: CrossReferenceAnalyzer, machO: MachOFile) { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SlotAddressReferences", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "SlotAddressReferences.swift", contents: """ + import Foundation + public func descriptorClass() -> Any.Type { NSAppleEventDescriptor.self } + public func timerClass() -> Any.Type { Timer.self } + """)], + arguments: ["-O", "-swift-version", "5"] + ) + let machO = try MachOFile(url: library) + return (try CrossReferenceAnalyzer(machOFiles: [machO]), machO) + } + + /// In a file analyzed without Foundation, the slot binds to an imported + /// class: the reference a `refs --class NSTimer` query also takes. + @Test func slotAddressHandedToAHelperIsAClassReference() throws { + let (analyzer, _) = try Self.analyzer() + let timerClass = try #require(analyzer.functions(inImageAt: 0).first { function in + if case .symbol(let symbol)? = function.name { symbol.hasPrefix("_$s21SlotAddressReferences10timerClass") } else { false } + }) + let references = analyzer.references(to: [.objectiveCClass("NSTimer"), .importedSymbol("_OBJC_CLASS_$_NSTimer")], inImageAt: 0) + let inTimerClass = references.filter { $0.function == timerClass.location } + #expect(inTimerClass.count == 1) + #expect(inTimerClass.first?.target == .importedSymbol(name: "_OBJC_CLASS_$_NSTimer")) + #expect(inTimerClass.first?.kind == .reference) + #expect(inTimerClass.first?.route == .pointerSlot) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift b/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift index 68084ab8..834b4689 100644 --- a/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift +++ b/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift @@ -71,6 +71,8 @@ struct StandaloneFileReferenceDumpTests { "class \(name) 0x\(String(location.address, radix: 16))" case .objectiveCInstanceVariable(let className, let name): "ivar \(className).\(name)" + case .selector(let selector): + "selector \(selector)" case .cString(let characters): "cString \(characters.debugDescription)" case .constantString(let characters): diff --git a/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift b/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift index 026f3a32..1c50f8a1 100644 --- a/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift @@ -50,6 +50,8 @@ struct CrossReferenceCommandTests { (["--function", "4096", "--function-image", "Foo"], .function(address: 4096, imageName: "Foo")), (["--ivar", "NSWindow._frame"], .instanceVariable(className: "NSWindow", name: "_frame")), (["--string", "NSWindowDidBecomeKeyNotification"], .string("NSWindowDidBecomeKeyNotification")), + (["--type", "7SwiftUI4TextV"], .swiftType("7SwiftUI4TextV", imageName: nil)), + (["--type", "$s7SwiftUI4TextVMa", "--type-image", "SwiftUICore"], .swiftType("$s7SwiftUI4TextVMa", imageName: "SwiftUICore")), ]) func refsMapsEachQuery(arguments: [String], subject: CrossReferenceSubject) throws { let request = try ReferencesCommand.parse(arguments + ["--uses-system-dyld-shared-cache"]).makeRequest() @@ -70,6 +72,8 @@ struct CrossReferenceCommandTests { ["--ivar", "Trailing."], ["--function", "nowhere"], ["--selector", "init", "--limit", "0"], + ["--selector", "init", "--type-image", "Foo"], + ["--selector", "init", "--type", "7SwiftUI4TextV"], ]) func refsRefusesIncompleteFlags(arguments: [String]) { #expect(throws: (any Error).self) { try ReferencesCommand.parse(arguments + ["--uses-system-dyld-shared-cache"]) } @@ -103,5 +107,8 @@ struct CrossReferenceCommandTests { let ambiguous = CommandLineErrorTranslation.translated(CrossReferenceRequestError.ambiguousFunction(address: 0x10, imagePaths: ["/tmp/A", "/tmp/B"])) #expect((ambiguous as? ValidationError)?.message.contains("--function-image") == true) #expect(CommandLineErrorTranslation.translated(CrossReferenceRequestError.noFunction(address: 0x10)) is CrossReferenceRequestError) + let unexportedType = CommandLineErrorTranslation.translated(CrossReferenceRequestError.swiftTypeNeedsImage(mangling: "7SwiftUI13PinnedBarViewC")) + #expect((unexportedType as? ValidationError)?.message.contains("--type-image") == true) + #expect(CommandLineErrorTranslation.translated(CrossReferenceRequestError.swiftTypeNotFound(mangling: "3Foo3BarV")) is CrossReferenceRequestError) } } diff --git a/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift b/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift index f650cff4..59f345bf 100644 --- a/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift +++ b/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift @@ -13,9 +13,11 @@ struct CrossReferenceRequestTests { static let archivedCachePath = "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e" static let selector = "makeKeyAndOrderFront:" - private static func isSend(_ target: CodeReferenceTarget, of selector: String) -> Bool { + /// A send of `selector`, or another use of it — an argument, a returned + /// selector (evolution proposal `cross-reference-recall-gaps`). + private static func isUse(_ target: CodeReferenceTarget, of selector: String) -> Bool { switch target { - case .messageSend(selector, _), .superMessageSend(selector, _): true + case .messageSend(selector, _), .superMessageSend(selector, _), .selector(selector): true default: false } } @@ -26,7 +28,7 @@ struct CrossReferenceRequestTests { let result = try await ReferencesRequest(input: .dyldSharedCache(path: Self.archivedCachePath), subject: .selector(Self.selector)).run(output: output) #expect(result.rows.count > 100) #expect(!result.isTruncated) - #expect(result.rows.allSatisfy { Self.isSend($0.reference.target, of: Self.selector) }) + #expect(result.rows.allSatisfy { Self.isUse($0.reference.target, of: Self.selector) }) #expect(result.rows.contains { $0.imagePath.hasSuffix("/AppKit.framework/Versions/C/AppKit") }) let lines = output.printedProduct.split(separator: "\n") #expect(lines.count == result.rows.count) @@ -54,10 +56,13 @@ struct CrossReferenceRequestTests { let function = try #require(reference["function"] as? [String: Any]) #expect((function["address"] as? String)?.hasPrefix("0x") == true) #expect((reference["image"] as? String)?.hasSuffix("/AppKit") == true) - #expect(["call", "tailCall"].contains(reference["kind"] as? String)) + #expect(["call", "tailCall", "reference"].contains(reference["kind"] as? String)) let target = try #require(reference["target"] as? [String: Any]) - let send = (target["messageSend"] ?? target["superMessageSend"]) as? [String: Any] - #expect(send?["selector"] as? String == Self.selector) + if let send = (target["messageSend"] ?? target["superMessageSend"]) as? [String: Any] { + #expect(send["selector"] as? String == Self.selector) + } else { + #expect(target["selector"] as? String == Self.selector) + } } } @@ -141,7 +146,7 @@ struct CrossReferenceRequestTests { let result = try await ReferencesRequest(input: .files(paths: [path], architecture: .arm64e), subject: .selector("init")).run(output: RecordingOutput()) #expect(!result.rows.isEmpty) #expect(result.scannedImageCount == 1) - #expect(result.rows.allSatisfy { $0.imagePath == path && Self.isSend($0.reference.target, of: "init") }) + #expect(result.rows.allSatisfy { $0.imagePath == path && Self.isUse($0.reference.target, of: "init") }) await #expect(performing: { try await ReferencesRequest(input: .files(paths: [path], architecture: nil), subject: .selector("init")).run(output: RecordingOutput()) }, throws: { error in diff --git a/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift new file mode 100644 index 00000000..6c56a8a4 --- /dev/null +++ b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift @@ -0,0 +1,74 @@ +#if os(macOS) + +import Foundation +import Testing +import MachOKitExtensions +import CrossReferenceAnalysis +import SwiftSectionKit +import SwiftSectionFixtureSupport + +/// `refs --type`: the references to a Swift type, by its mangling or by a +/// symbol of it (evolution proposal `cross-reference-recall-gaps`). +@Suite +struct ReferencesRequestSwiftTypeTests { + private static func isTypeReference(_ target: CodeReferenceTarget) -> Bool { + switch target { + case .swiftType, .swiftTypeName, .objectiveCClass: true + default: false + } + } + + /// SwiftUICore's `Text`, whichever of its manglings or symbols names it. + @Test(.enabled(if: FullDyldCache.cachedHost != nil, "needs the running system's dyld shared cache")) + func typeSubjectFindsTheSameReferencesWhateverNamesTheType() async throws { + let byMangling = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("7SwiftUI4TextV", imageName: nil), imageNames: ["SwiftUICore"]).run(output: RecordingOutput()) + #expect(!byMangling.rows.isEmpty) + #expect(byMangling.rows.allSatisfy { Self.isTypeReference($0.reference.target) }) + // Calls to the metadata accessor, and its address taken. + #expect(byMangling.rows.contains { $0.reference.kind == .call }) + for spelling in ["$s7SwiftUI4TextVMn", "_$s7SwiftUI4TextVMa", "$s7SwiftUI4TextVN"] { + let bySymbol = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType(spelling, imageName: nil), imageNames: ["SwiftUICore"]).run(output: RecordingOutput()) + #expect(bySymbol.rows == byMangling.rows, "\(spelling)") + } + } + + @Test(.enabled(if: FullDyldCache.cachedHost != nil, "needs the running system's dyld shared cache")) + func typeSubjectInACacheNeedsTheImageOfATypeNoImageExports() async throws { + await #expect(throws: CrossReferenceRequestError.swiftTypeNeedsImage(mangling: "11NoSuchTypes7NothingV")) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("$s11NoSuchTypes7NothingVMn", imageName: nil)).run(output: RecordingOutput()) + } + await #expect(throws: CrossReferenceRequestError.swiftTypeNotFound(mangling: "11NoSuchTypes7NothingV")) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("11NoSuchTypes7NothingV", imageName: "SwiftUICore")).run(output: RecordingOutput()) + } + } + + /// A type no symbol names — its descriptor symbol stripped — is looked + /// for in every file of a set of files, which are few. + @Test func typeSubjectLooksForAnUnexportedTypeInEveryStandaloneFile() async throws { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "HiddenTypeReferences", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "HiddenTypeReferences.swift", contents: """ + struct Hidden { + var value: Int + } + + public func makeHidden() -> Any { + Hidden(value: 1) + } + """)], + arguments: ["-swift-version", "5", "-Xlinker", "-x"] + ) + let input = CrossReferenceInput.files(paths: [libraryURL.path], architecture: nil) + let byMangling = try await ReferencesRequest(input: input, subject: .swiftType("20HiddenTypeReferences6HiddenV", imageName: nil)).run(output: RecordingOutput()) + #expect(!byMangling.rows.isEmpty) + #expect(byMangling.rows.allSatisfy { Self.isTypeReference($0.reference.target) }) + // A symbol of the type names it too, its prefix and suffix taken off. + for spelling in ["$s20HiddenTypeReferences6HiddenVMn", "_$s20HiddenTypeReferences6HiddenVMa", "$s20HiddenTypeReferences6HiddenVN"] { + let bySymbol = try await ReferencesRequest(input: input, subject: .swiftType(spelling, imageName: nil)).run(output: RecordingOutput()) + #expect(bySymbol.rows == byMangling.rows, "\(spelling)") + } + } +} + +#endif From c125ad2260d575d2f059425340884d83883ece6d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 17:56:21 +0800 Subject: [PATCH 149/175] test(IntegrationTests): split the inspection dump suites by source and name what they read Interface, Diff and Evolution each hold one suite per place their images come from, and every suite runs all of its family's outputs. Which framework a suite reads is a named configuration (CacheImagesConfiguration, SimulatorFilePairConfiguration, XcodeFrameworkPairConfiguration) instead of one suite class per framework: an image group is a configuration listing several images. --- Documentations/Internal/ABIEvolutionDesign.md | 2 +- .../Internal/ProjectEvolutionLog.md | 14 + .../InspectionDumps/DiffTests.swift | 83 +++--- .../InspectionDumps/EvolutionTests.swift | 246 ++++-------------- .../InspectionDumps/InterfaceTests.swift | 55 +++- .../InspectionDumps/VersionAxis.swift | 120 ++++++--- 6 files changed, 226 insertions(+), 294 deletions(-) diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index d02c7cb9..d5f9c78e 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -232,7 +232,7 @@ swift-section evolution ... \ 8. **兼容性推广**:逐转换 additive/breaking 与 `firstBreakingTransitionIndex`。 9. **reporter**:小型 evolution 的整段文本断言(确定性输出)。 -另有**维护者手检集成套件**,在 `Tests/IntegrationTests/InspectionDumps/`(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行;Swift 与 ObjC 的报告和联合接口共用这一套,见提案 [0110-unify-evolution-integration-suites](../Evolutions/0110-unify-evolution-integration-suites.md);与单版本接口、两版本 diff 的手检套件同在一个目录、共用版本轴,见提案 [0111-unify-diff-and-interface-integration-suites](../Evolutions/0111-unify-diff-and-interface-integration-suites.md)):每条版本轴一个套件,挂在 `EvolutionTestSuite` 下,各按读的元数据筛版本。报告的 `swiftReportFile` / `swiftReportString` 跑完整 pipeline——逐版本索引 → 冻结 → **经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘)。`SwiftUIDyldCacheTests` 对三份 macOS dyld cache(15.5 → 26.5.2 → 27.0)提取 SwiftUI;`SwiftUICoreSimulatorTests`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 diff 的 verdict 交叉核对行。 +另有**维护者手检集成套件**,在 `Tests/IntegrationTests/InspectionDumps/`(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行;Swift 与 ObjC 的报告和联合接口共用这一套,见提案 [0110-unify-evolution-integration-suites](../Evolutions/0110-unify-evolution-integration-suites.md);与单版本接口、两版本 diff 的手检套件同在一个目录、共用版本轴,见提案 [0111-unify-diff-and-interface-integration-suites](../Evolutions/0111-unify-diff-and-interface-integration-suites.md)):每种版本来源一个套件,挂在 `Evolution` 下(`Caches`、`ArchivedCaches`、`SimulatorFiles`),读哪些镜像由套件指向的具名配置决定(`CacheImagesConfiguration.swiftUIGroup`、`.appKit` 等,要看别的框架就加一份配置),各按读的元数据筛版本。报告的 `swiftReportFile` / `swiftReportString` 跑完整 pipeline——逐版本索引 → 冻结 → **经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘)。`Evolution.Caches` 默认对三份 macOS dyld cache(15.5 → 26.5.2 → 27.0)提取 SwiftUI 与 SwiftUICore;`Evolution.SimulatorFiles`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 diff 的 verdict 交叉核对行。 ## 后续项(不在首轮范围) diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index d39fcc51..72d2a5c4 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3649,6 +3649,20 @@ - **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过,新文件没有警告。diff 的 cache 对改为整份打开,输出可能与改前不同;改前改后的比对待维护者做。维护者在接口套件里未提交的实验(读 AttributeGraph、显示 C 导入类型、类型名解析)落地前先单独提交,合并时按新结构处理,只留在历史里。 - **对应版本**:未发布(只改测试目标)。 +## 2026-11-26 IntegrationTests 手检套件按来源分,框架交给具名配置 + +- **时间段**:2026-11-26,本仓库的 `feature/source-based-inspection-dump-suites`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译。0111 的后续,按用户要求直接做、不写提案。 +- **动机**:0111 之后,手检套件的类型名还是很长(`EvolutionTestSuite.SwiftUIImageGroupArchivedDyldCacheTests`),而且按框架开套件:同一种版本来源,SwiftUI、AppKit、镜像组各一个类,测试在每个类里重写一遍。 +- **关键决策**: + - 套件只按版本或镜像的来源分,挂在三个短命名空间下:`Interface.SystemCache` / `ArchivedCache` / `File` / `InProcessImage` / `XcodeFile`,`Diff.SimulatorFiles` / `Caches` / `ArchivedCaches` / `XcodeFrameworks`,`Evolution.Caches` / `ArchivedCaches` / `SimulatorFiles`。不写限定某个框架的套件。 + - 读哪个框架交给具名配置:`CacheImagesConfiguration`(`.swiftUI`、`.swiftUICore`、`.appKit`、`.swiftUIGroup`、`.appKitGroup`;列多个镜像就是镜像组,不再单开套件)、`SimulatorFilePairConfiguration`(`.swiftUICore`、`.swiftUI`)、`XcodeFrameworkPairConfiguration`(`.dvtProductsUI`)。三个轴基类各读一个 `configuration` 类属性,原来的 `cacheImageName(s)`、`oldFileName` 一类属性删掉。接口套件的镜像本来就是基类的一个类属性,照旧。要看别的框架,加一份配置、把套件指过去。 + - 每个套件把这一类的输出各写一遍,Swift 与 ObjC 都写:接口 20 个、diff 24 个、演进 25 个测试;测试函数名与输出文件名不变。默认配置取覆盖面最广的:演进的两个 cache 套件读 SwiftUI 加 SwiftUICore,diff 与接口的 cache 套件读 AppKit。AppKit 的演进、SwiftUI 的模拟器 diff 不再默认跑,要看时改配置。 + - pack 门面那个测试改成取前三个版本、不足三个时打印一行说明;配置是镜像组时,它只印各版本的主镜像,不再与 `swiftInterfaceString` 逐字相同。 +- **落地模块**:`Tests/IntegrationTests/InspectionDumps/`(`VersionAxis.swift`、`InterfaceTests.swift`、`DiffTests.swift`、`EvolutionTests.swift`)。 +- **文档**:[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段改用新的套件与配置名。没有新术语,不另写使用指南或实现说明;提案 0111 是落地时的快照,不改。 +- **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests`。 +- **对应版本**:未发布(只改测试目标)。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Tests/IntegrationTests/InspectionDumps/DiffTests.swift b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift index 028e4e38..b7ecd840 100644 --- a/Tests/IntegrationTests/InspectionDumps/DiffTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift @@ -2,20 +2,18 @@ import Foundation import Testing import MachOKit import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport +@testable import SwiftSectionTestingSupport @testable import MachOSwiftSection -/// Every diff the maintainer inspects, one suite per pair of versions. A -/// suite names its two versions once and diffs them through each output it -/// is read for, one test per output and destination. The pairs come from the -/// version axis base classes the evolution suites read too (see -/// `VersionAxis.swift`); AppKit's suites also diff its Objective-C API, the -/// larger half of it. -enum DiffTestSuite { - /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5). - final class SwiftUICoreTests: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } +/// Every diff the maintainer inspects, one suite per place the two versions +/// come from. Each suite runs every diff output on one pair, which its +/// `configuration` names — the version axis base classes the evolution +/// suites read too (see `VersionAxis.swift`). To diff another framework, add +/// a configuration and point the suite at it. +enum Diff { + /// The same file in two simulator runtimes (iOS 18.5 → 26.5). + final class SimulatorFiles: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var configuration: SimulatorFilePairConfiguration { .swiftUICore } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -36,40 +34,25 @@ enum DiffTestSuite { @Test func swiftInterfaceString() async throws { try await dump(.swiftInterface, to: .console) } - } - - /// SwiftUI across two simulator runtimes (iOS 18.5 → 26.5). - final class SwiftUITests: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUI } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftReportFile() async throws { - try await dump(.swiftReport, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftReportString() async throws { - try await dump(.swiftReport, to: .console) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftInterfaceFile() async throws { - try await dump(.swiftInterface, to: .file) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftInterfaceString() async throws { - try await dump(.swiftInterface, to: .console) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) } } - /// AppKit from two dyld shared caches (macOS 26.5.1 → 27.0), each opened - /// whole the way `swift-section --dyld-shared-cache` opens it. - /// Cross-image references resolve through each cache. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + /// The same image from two dyld shared caches (macOS 26.5.1 → 27.0), + /// each opened whole the way `swift-section --dyld-shared-cache` opens + /// it. Cross-image references resolve through each cache. + final class Caches: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { [.macOS_26_5_1, .macOS_27_0] } - override class var cacheImageName: MachOImageName { .AppKit } + + override class var configuration: CacheImagesConfiguration { .appKit } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -105,11 +88,14 @@ enum DiffTestSuite { /// The same image from two archived macOS caches, picked by version: /// point the two versions at any directories under /// `/Volumes/DyldSharedCaches/macOS` that hold a cache. - final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + final class ArchivedCaches: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { class var oldCacheVersion: String { "26.6" } + class var newCacheVersion: String { "27.0" } + override class var cachePaths: [DyldSharedCachePath] { [.macOS(oldCacheVersion), .macOS(newCacheVersion)] } - override class var cacheImageName: MachOImageName { .AppKit } + + override class var configuration: CacheImagesConfiguration { .appKit } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -142,12 +128,9 @@ enum DiffTestSuite { } } - /// The DVTProductsUI shared framework across two installed Xcodes - /// (26.3.0 → 26.4.0). - final class XcodeFrameworkTests: CrossVersionXcodeFrameworkTests, nonisolated DiffDumpTests, @unchecked Sendable { - override class var oldXcodeVersion: String { "26.3.0" } - override class var newXcodeVersion: String { "26.4.0" } - override class var sharedFrameworkName: String { "DVTProductsUI" } + /// The same shared framework in two installed Xcodes (26.3.0 → 26.4.0). + final class XcodeFrameworks: CrossVersionXcodeFrameworkTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var configuration: XcodeFrameworkPairConfiguration { .dvtProductsUI } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -168,5 +151,15 @@ enum DiffTestSuite { @Test func swiftInterfaceString() async throws { try await dump(.swiftInterface, to: .console) } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } } } diff --git a/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift b/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift index 4ab75336..9336b2a5 100644 --- a/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift @@ -2,30 +2,31 @@ import Foundation import Testing import MachOKit import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport +@testable import SwiftSectionTestingSupport @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface @_spi(Support) @testable import SwiftIndexing import Semantic -/// Every evolution axis the maintainer inspects, one suite per axis. A suite -/// declares its caches and images once and runs on them each evolution -/// output it is read for — the Swift and Objective-C reports and interfaces -/// alike — with one test per output and destination. Each language's -/// pipelines see only the versions whose images carry their metadata (see -/// `MultiVersionDyldCacheImageTests`). +/// Every evolution the maintainer inspects, one suite per place the versions +/// come from. Each suite runs every evolution output — the Swift and +/// Objective-C reports and interfaces alike — on one series of versions, +/// which its `configuration` names; each language's pipelines see only the +/// versions whose images carry their metadata (see +/// `MultiVersionDyldCacheImageTests`). To follow another framework or group +/// of images, add a configuration and point the suite at it. /// /// Read an interface against the report of the same axis: the two views /// must tell one story. An annotated interface is worth reading only from /// three versions up — introduced mid-axis, removed mid-axis, modified /// twice, gone-and-back bitmaps; for two, `diff --interface` already covers /// it. -enum EvolutionTestSuite { - /// SwiftUI across the default three caches (15.5 → 26.5.2 → 27.0) — the - /// flagship N == 3 lineage: introduced / modified / removed / re-added - /// stories only visible with more than two versions. - final class SwiftUIDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .SwiftUI } +enum Evolution { + /// The default three macOS caches (15.5 → 26.5.2 → 27.0) — the N == 3 + /// lineage: introduced / modified / removed / re-added stories only + /// visible with more than two versions. + final class Caches: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var configuration: CacheImagesConfiguration { .swiftUIGroup } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -47,49 +48,6 @@ enum EvolutionTestSuite { try await dump(.swiftInterface, to: .console) } - /// The pack-generic façade on the same three images: the axis - /// through `SwiftEvolutionInterfaceBuilder` (compile-time arity), dumped for eyeball comparison - /// against `swiftInterfaceString()` — the two must be - /// byte-identical. - @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) - @Test func swiftInterfaceStringViaPackFacade() async throws { - let versions = versionAxis(for: .swift).versions - let builder = try SwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - versions: versions[0].primaryImage.machOFile, versions[1].primaryImage.machOFile, versions[2].primaryImage.machOFile, - labels: versions.map(\.label) - ) - // No `measuringPreparation` here: this @Test runs on the suite's - // @TestActor, and handing it an actor-isolated closure trips - // region-isolation checking (the extension helpers avoid this by - // being nonisolated themselves). - try await builder.prepare() - printResult(try await builder.printAnnotatedInterface().string) - } - } - - /// SwiftUICore across the default three caches — the Swift-rich axis, - /// exercising the union interface over heavy generics, opaque returns - /// and extension blocks. - final class SwiftUICoreDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftInterfaceFile() async throws { - try await dump(.swiftInterface, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftInterfaceString() async throws { - try await dump(.swiftInterface, to: .console) - } - } - - /// AppKit's Objective-C metadata across the default three caches. - final class AppKitDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .AppKit } - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func objcReportFile() async throws { try await dump(.objcReport, to: .file) @@ -109,68 +67,46 @@ enum EvolutionTestSuite { @Test func objcInterfaceString() async throws { try await dump(.objcInterface, to: .console) } - } - - /// SwiftUI across every archived macOS cache, 11.0 → 27.0. Every label - /// is a version number, so the interface also spells each lifecycle one - /// attribute can express as `@available(macOS, …)`. - final class SwiftUIArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } - override class var cacheImageName: MachOImageName { .SwiftUI } - override class var availabilityPlatform: AvailabilityPlatform? { .macOS } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftInterfaceFile() async throws { - try await dump(.swiftInterface, to: .file) - } - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftInterfaceString() async throws { - try await dump(.swiftInterface, to: .console) + /// The pack-generic façade on the first three versions' primary + /// images: the axis through `SwiftEvolutionInterfaceBuilder` (compile-time arity), dumped for eyeball + /// comparison against `swiftInterfaceString()` — byte-identical when + /// the configuration reads one image per version. + @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) + @Test func swiftInterfaceStringViaPackFacade() async throws { + let versions = versionAxis(for: .swift).versions + guard versions.count >= 3 else { + printResult("No pack façade dump: \(versions.count) version(s) carry Swift metadata") + return + } + let builder = try SwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + versions: versions[0].primaryImage.machOFile, versions[1].primaryImage.machOFile, versions[2].primaryImage.machOFile, + labels: versions.prefix(3).map(\.label) + ) + // No `measuringPreparation` here: this @Test runs on the suite's + // @TestActor, and handing it an actor-isolated closure trips + // region-isolation checking (the extension helpers avoid this by + // being nonisolated themselves). + try await builder.prepare() + printResult(try await builder.printAnnotatedInterface().string) } } - /// AppKit's Objective-C metadata across every archived macOS cache, with - /// the header's `API_AVAILABLE` / `API_OBSOLETED` macros. - /// - /// The method names of a macOS 11 cache read correctly only from - /// MachOObjCSection 0.8.202. Its relative method lists count a selector - /// from the name field itself, where later caches count it from a - /// selector base, and an earlier reader made every class and category - /// method of 11.x garbage — 11.7 → 12.0.1 then reported about 47,000 - /// removals and 53,000 additions instead of about 1,200 and 1,400. - final class AppKitArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + /// Every archived macOS cache, 11.0 → 27.0. Every label is a version + /// number, so both interfaces also spell each lifecycle one attribute or + /// macro can express (`@available(macOS, …)`, `API_AVAILABLE(macos(…))`). + /// A group whose other images join late reads them from where they + /// appear: SwiftUICore joins SwiftUI in 15.0, where an evolution of + /// SwiftUI alone reads every declaration moved into SwiftUICore as + /// removed. + final class ArchivedCaches: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } - override class var cacheImageName: MachOImageName { .AppKit } - override class var availabilityPlatform: AvailabilityPlatform? { .macOS } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcReportFile() async throws { - try await dump(.objcReport, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcReportString() async throws { - try await dump(.objcReport, to: .console) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcInterfaceFile() async throws { - try await dump(.objcInterface, to: .file) - } - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcInterfaceString() async throws { - try await dump(.objcInterface, to: .console) - } - } + override class var availabilityPlatform: AvailabilityPlatform? { .macOS } - /// SwiftUI together with SwiftUICore across the default three caches, - /// each version one group of images (evolution proposal - /// `image-group-evolution`): what moved between the two images after the - /// split reads as moved, not as removed and added. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + override class var configuration: CacheImagesConfiguration { .swiftUIGroup } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -213,14 +149,11 @@ enum EvolutionTestSuite { } } - /// The same group across every archived macOS cache: SwiftUI alone until - /// 14.8, SwiftUICore joining it in 15.0 — where an evolution of SwiftUI - /// alone reads every declaration moved into SwiftUICore as removed. Every - /// label is a version number, so both interfaces spell availability. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - override class var availabilityPlatform: AvailabilityPlatform? { .macOS } + /// The same file in two simulator runtimes (iOS 18.5 → 26.5) — the + /// N == 2 case, whose printed pairwise cross-check line must agree with + /// the two-sided differ. + final class SimulatorFiles: CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var configuration: SimulatorFilePairConfiguration { .swiftUICore } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @Test func swiftReportFile() async throws { @@ -262,79 +195,4 @@ enum EvolutionTestSuite { try await dump(.objcInterface, to: .console) } } - - /// AppKit together with the frameworks Apple moved its classes into — - /// UIFoundation, CollectionViewCore, CoreAutoLayout — across the default - /// three caches, each version one group of images. - final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcReportFile() async throws { - try await dump(.objcReport, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcReportString() async throws { - try await dump(.objcReport, to: .console) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcInterfaceFile() async throws { - try await dump(.objcInterface, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcInterfaceString() async throws { - try await dump(.objcInterface, to: .console) - } - } - - /// The same group across every archived macOS cache: the classes that - /// moved between AppKit, UIFoundation and CollectionViewCore in 13.0 and - /// 15.0 — where an evolution of AppKit alone reads them as removed or - /// added — read as moved. CollectionViewCore joins the group in 13.0. - final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } - override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } - override class var availabilityPlatform: AvailabilityPlatform? { .macOS } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcReportFile() async throws { - try await dump(.objcReport, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcReportString() async throws { - try await dump(.objcReport, to: .console) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcInterfaceFile() async throws { - try await dump(.objcInterface, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func objcInterfaceString() async throws { - try await dump(.objcInterface, to: .console) - } - } - - /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the - /// N == 2 case, whose printed pairwise cross-check line must agree with - /// the two-sided differ. - final class SwiftUICoreSimulatorTests: CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftReportFile() async throws { - try await dump(.swiftReport, to: .file) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func swiftReportString() async throws { - try await dump(.swiftReport, to: .console) - } - } } diff --git a/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift b/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift index 50bf2423..09e7cf7a 100644 --- a/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift @@ -6,15 +6,12 @@ import SwiftSectionFixtureSupport @testable import MachOSwiftSection /// Every single-version interface the maintainer inspects, one suite per -/// image source. A suite names its image once and dumps it through each -/// output it is read for, one test per output and destination. -/// -/// The suites are probes: point `cacheImageName`, `fileName` or `imageName` -/// at any image to look at it. AppKit's suites also print its Objective-C -/// header, the larger half of its API. -enum InterfaceTestSuite { +/// place an image is read from. Each suite runs both outputs on one image, +/// which is its configuration: point `cacheImageName`, `fileName` or +/// `imageName` at any image to look at it. +enum Interface { /// An image of this Mac's dyld shared cache. - class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + class SystemCache: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { .AppKit } override class var cachePath: DyldSharedCachePath { .current } @@ -40,10 +37,10 @@ enum InterfaceTestSuite { } } - /// The same image from an archived macOS cache, picked by version: point + /// An image of an archived macOS cache, picked by version: point /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` /// that holds a cache. - class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + class ArchivedCache: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { class var cacheVersion: String { "26.6" } override class var cachePath: DyldSharedCachePath { .macOS(cacheVersion) } @@ -71,8 +68,8 @@ enum InterfaceTestSuite { } } - /// A file on disk: by default the SymbolTestsCore fixture. - class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + /// A file on disk. + class File: SwiftSectionTestingSupport.MachOFileTests, nonisolated InterfaceDumpTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -84,10 +81,20 @@ enum InterfaceTestSuite { @Test func swiftInterfaceString() async throws { try await dump(.swiftInterface, of: machOFile, to: .console) } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFile, to: .console) + } } /// An image this process loaded, read in process. - class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + class InProcessImage: SwiftSectionTestingSupport.MachOImageTests, nonisolated InterfaceDumpTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -99,10 +106,20 @@ enum InterfaceTestSuite { @Test func swiftInterfaceString() async throws { try await dump(.swiftInterface, of: machOImage, to: .console) } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOImage, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOImage, to: .console) + } } /// A file inside Xcode, printed with only what it exports. - class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, InterfaceDumpTests { + class XcodeFile: SwiftSectionTestingSupport.XcodeMachOFileTests, InterfaceDumpTests { override class var fileName: XcodeMachOFileName { .sharedFrameworks(.SourceEditor) } var printsExportedDeclarationsOnly: Bool { true } @@ -116,5 +133,15 @@ enum InterfaceTestSuite { @Test func swiftInterfaceString() async throws { try await dump(.swiftInterface, of: machOFile, to: .console) } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFile, to: .console) + } } } diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift index 8246f8da..a429e0c8 100644 --- a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift @@ -126,13 +126,68 @@ extension VersionAxisDumpTests { } } +/// The images a dyld shared cache suite reads out of each cache, the +/// primary image first. More than one makes every version a group of images +/// (evolution proposal `image-group-evolution`): AppKit with the frameworks +/// Apple moved its classes into, SwiftUI with SwiftUICore. Each other image +/// joins its group where the cache has it with the metadata — +/// CollectionViewCore is in the macOS caches from 13.0 on, SwiftUICore from +/// 15.0 on. +/// +/// A suite points at one of these; to look at another framework, add one and +/// point the suite at it. +struct CacheImagesConfiguration: Sendable { + let imageNames: [MachOImageName] + + static var swiftUI: Self { Self(imageNames: [.SwiftUI]) } + static var swiftUICore: Self { Self(imageNames: [.SwiftUICore]) } + /// AppKit kept its Swift API in `libswiftAppKit.dylib` until macOS 14, + /// so its Swift axis starts at 14.0; its Objective-C metadata is in every + /// cache. + static var appKit: Self { Self(imageNames: [.AppKit]) } + static var swiftUIGroup: Self { Self(imageNames: [.SwiftUI, .SwiftUICore]) } + static var appKitGroup: Self { Self(imageNames: [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout]) } +} + +/// The same file in two simulator runtimes, and the runtime versions that +/// label them on the axis. A suite points at one of these; to look at +/// another file, add one. +struct SimulatorFilePairConfiguration: Sendable { + let oldFileName: MachOFileName + let newFileName: MachOFileName + let oldVersionLabel: String + let newVersionLabel: String + + static var swiftUICore: Self { + Self(oldFileName: .iOS_18_5_Simulator_SwiftUICore, newFileName: .iOS_26_5_Simulator_SwiftUICore, oldVersionLabel: "18.5", newVersionLabel: "26.5") + } + + static var swiftUI: Self { + Self(oldFileName: .iOS_18_5_Simulator_SwiftUI, newFileName: .iOS_26_5_Simulator_SwiftUI, oldVersionLabel: "18.5", newVersionLabel: "26.5") + } +} + +/// A shared framework of two installed Xcode applications, picked by +/// version — `/Applications/Xcode-.app` — which also labels it on +/// the axis. A suite points at one of these; to look at another framework or +/// other Xcodes, add one. +struct XcodeFrameworkPairConfiguration: Sendable { + let frameworkName: String + let oldXcodeVersion: String + let newXcodeVersion: String + + static var dvtProductsUI: Self { + Self(frameworkName: "DVTProductsUI", oldXcodeVersion: "26.3.0", newXcodeVersion: "26.4.0") + } +} + /// Extracts the same images from an *ordered series* of dyld shared caches: /// N versions for an evolution, two for a diff. The caches are retained /// because the extracted `MachOFile`s resolve cross-image references through /// them while indexing. /// /// One instance serves every pipeline: it keeps, per cache, every image of -/// `cacheImageNames` the cache holds, and each language's axis then keeps +/// `configuration` the cache holds, and each language's axis then keeps /// the images carrying that language's metadata. A version whose primary /// image is missing, or lacks the metadata, is off that axis — there is /// nothing to index. A cache that cannot be opened still throws. @@ -141,15 +196,8 @@ extension VersionAxisDumpTests { /// opens it, so the dumps match what the command line prints. Opened from /// its main file alone, every read into another sub-cache file mapped that /// file once more until MachOObjCSection 0.8.109, and an evolution over -/// every archived macOS minor ran past 5 GB. -/// -/// A suite comparing a group of images per version (evolution proposal -/// `image-group-evolution`) lists them in `cacheImageNames`, the primary -/// image first: AppKit with the frameworks Apple moved its classes into, -/// SwiftUI with SwiftUICore. Each other image joins its group where the -/// cache has it with the metadata — CollectionViewCore is in the macOS -/// caches from 13.0 on, SwiftUICore from 15.0 on. A diff reads the primary -/// image of each version only. +/// every archived macOS minor ran past 5 GB. A diff reads the primary image +/// of each version only. @TestActor class MultiVersionDyldCacheImageTests: Sendable { let caches: [FullDyldCache] @@ -158,11 +206,8 @@ class MultiVersionDyldCacheImageTests: Sendable { /// Oldest first; each cache's `versionLabel` labels it on the axis. class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } - class var cacheImageName: MachOImageName { .SwiftUI } - - /// The images whose declarations make up one version, the primary - /// image first; by default the primary image alone. - class var cacheImageNames: [MachOImageName] { [cacheImageName] } + /// The images whose declarations make up one version. + class var configuration: CacheImagesConfiguration { .swiftUI } /// Set on an axis whose every label is a version number. class var availabilityPlatform: AvailabilityPlatform? { nil } @@ -247,12 +292,13 @@ class MultiVersionDyldCacheImageTests: Sendable { } init() async throws { - let primaryImageName = Self.cacheImageNames.first?.name + let imageNames = Self.configuration.imageNames + let primaryImageName = imageNames.first?.name var caches: [FullDyldCache] = [] var versions: [AxisVersion] = [] for cachePath in Self.cachePaths { let cache = try FullDyldCache(path: cachePath) - let images = Self.cacheImageNames.compactMap { imageName -> AxisImage? in + let images = imageNames.compactMap { imageName -> AxisImage? in guard let machOFile = cache.machOFile(named: imageName) else { return nil } return AxisImage(imageName: imageName.name, machOFile: machOFile) } @@ -265,7 +311,7 @@ class MultiVersionDyldCacheImageTests: Sendable { self.caches = caches self.axes = VersionAxes( versions: versions, - comparesImageGroups: Self.cacheImageNames.count > 1, + comparesImageGroups: imageNames.count > 1, availabilityPlatform: Self.availabilityPlatform ) } @@ -280,29 +326,25 @@ class MultiVersionDyldCacheImageTests: Sendable { /// The same file from two simulator runtimes, by fixture name — the /// two-version counterpart of `SwiftSectionTestingSupport.MachOFileTests`, -/// which loads one. +/// which loads one. `configuration` names the pair. @TestActor class CrossVersionMachOFileTests: Sendable { let oldMachOFile: MachOFile let newMachOFile: MachOFile private let axes: VersionAxes - class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - /// The runtime versions the two files come from, which label them on the axis. - class var oldVersionLabel: String { "18.5" } - class var newVersionLabel: String { "26.5" } + class var configuration: SimulatorFilePairConfiguration { .swiftUICore } init() async throws { - let oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.oldFileName)) - let newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: Self.newFileName)) + let configuration = Self.configuration + let oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.oldFileName)) + let newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.newFileName)) self.oldMachOFile = oldMachOFile self.newMachOFile = newMachOFile self.axes = VersionAxes( versions: [ - AxisVersion(label: Self.oldVersionLabel, images: [AxisImage(imageName: oldMachOFile.imagePath.lastPathComponent, machOFile: oldMachOFile)]), - AxisVersion(label: Self.newVersionLabel, images: [AxisImage(imageName: newMachOFile.imagePath.lastPathComponent, machOFile: newMachOFile)]), + AxisVersion(label: configuration.oldVersionLabel, images: [AxisImage(imageName: oldMachOFile.imagePath.lastPathComponent, machOFile: oldMachOFile)]), + AxisVersion(label: configuration.newVersionLabel, images: [AxisImage(imageName: newMachOFile.imagePath.lastPathComponent, machOFile: newMachOFile)]), ], comparesImageGroups: false, availabilityPlatform: nil @@ -317,27 +359,26 @@ class CrossVersionMachOFileTests: Sendable { /// The same shared framework from two installed Xcode applications, picked /// by version: `/Applications/Xcode-.app`. The shared /// `XcodeMachOFileName` fixture names a single Xcode, so this loads by path. +/// `configuration` names the framework and the two versions. @TestActor class CrossVersionXcodeFrameworkTests: Sendable { let oldMachOFile: MachOFile let newMachOFile: MachOFile private let axes: VersionAxes - /// The two Xcode versions, which also label them on the axis. - class var oldXcodeVersion: String { "26.3.0" } - class var newXcodeVersion: String { "26.4.0" } - class var sharedFrameworkName: String { "DVTProductsUI" } + class var configuration: XcodeFrameworkPairConfiguration { .dvtProductsUI } init() async throws { - let oldMachOFile = try Self.loadSharedFramework(fromXcodeVersion: Self.oldXcodeVersion) - let newMachOFile = try Self.loadSharedFramework(fromXcodeVersion: Self.newXcodeVersion) + let configuration = Self.configuration + let frameworkName = configuration.frameworkName + let oldMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.oldXcodeVersion) + let newMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.newXcodeVersion) self.oldMachOFile = oldMachOFile self.newMachOFile = newMachOFile - let imageName = Self.sharedFrameworkName self.axes = VersionAxes( versions: [ - AxisVersion(label: Self.oldXcodeVersion, images: [AxisImage(imageName: imageName, machOFile: oldMachOFile)]), - AxisVersion(label: Self.newXcodeVersion, images: [AxisImage(imageName: imageName, machOFile: newMachOFile)]), + AxisVersion(label: configuration.oldXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: oldMachOFile)]), + AxisVersion(label: configuration.newXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: newMachOFile)]), ], comparesImageGroups: false, availabilityPlatform: nil @@ -348,8 +389,7 @@ class CrossVersionXcodeFrameworkTests: Sendable { axes.axis(for: language) } - private class func loadSharedFramework(fromXcodeVersion xcodeVersion: String) throws -> MachOFile { - let name = sharedFrameworkName + private static func loadSharedFramework(named name: String, fromXcodeVersion xcodeVersion: String) throws -> MachOFile { let binaryPath = "/Applications/Xcode-\(xcodeVersion).app/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) } From 7ef1b4f22f5d606b4a2b92832617732d7199ee8e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 18:01:33 +0800 Subject: [PATCH 150/175] build: add the cross-reference recall benchmark, and import MachOKit where a test names FullDyldCache Scripts/CrossReferenceRecall measures swift-section refs against the ground truth of the 2026-11-18 IDA / Binary Ninja benchmark, recovered from that session's transcript and rewritten with full names; it reproduces that run's totals and targets exactly, and 0.25.0 scores 476 of 527 (90.3%) as on 2026-11-26. Step 0 of proposal cross-reference-recall-gaps. --- Scripts/CrossReferenceRecall/README.md | 44 ++ Scripts/CrossReferenceRecall/ground_truth.py | 403 ++++++++++++++++++ .../CrossReferenceRecall/ida-2026-11-18.txt | 60 +++ Scripts/CrossReferenceRecall/prepare.sh | 22 + .../query_swift_section.py | 240 +++++++++++ Scripts/CrossReferenceRecall/run_all.sh | 13 + Scripts/CrossReferenceRecall/score.py | 141 ++++++ .../verify_reproduction.py | 52 +++ .../ReferencesRequestSwiftTypeTests.swift | 1 + 9 files changed, 976 insertions(+) create mode 100644 Scripts/CrossReferenceRecall/README.md create mode 100644 Scripts/CrossReferenceRecall/ground_truth.py create mode 100644 Scripts/CrossReferenceRecall/ida-2026-11-18.txt create mode 100644 Scripts/CrossReferenceRecall/prepare.sh create mode 100644 Scripts/CrossReferenceRecall/query_swift_section.py create mode 100644 Scripts/CrossReferenceRecall/run_all.sh create mode 100644 Scripts/CrossReferenceRecall/score.py create mode 100644 Scripts/CrossReferenceRecall/verify_reproduction.py diff --git a/Scripts/CrossReferenceRecall/README.md b/Scripts/CrossReferenceRecall/README.md new file mode 100644 index 00000000..e59f908f --- /dev/null +++ b/Scripts/CrossReferenceRecall/README.md @@ -0,0 +1,44 @@ +# Cross-reference recall benchmark + +Measures how many of the code references in two real Apple binaries `swift-section refs` finds, against a ground truth built without any of the tools measured, and puts the result next to IDA's on the same targets. It is the acceptance gate of evolution proposal [`cross-reference-recall-gaps`](../../Documentations/Evolutions/draft-cross-reference-recall-gaps.md), and the numbers are kept in the vision [Reverse engineering without IDA](../../Documentations/Visions/ReverseEngineeringWithoutIDA.md). + +## Samples + +| Binary | Path (default) | arm64e UUID | +|---|---|---| +| Finder 26.5.2 (mostly Objective-C) | `/Volumes/RE/Finder/26.5.2/Finder` | `1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0` | +| ControlCenter 26.7 (mostly Swift) | `/Volumes/RE/ControlCenter/26.7/ControlCenter` | `5782ED6B-471B-3CAC-9258-93734B6009C3` | + +Override the paths with `CROSS_REFERENCE_RECALL_FINDER` and `CROSS_REFERENCE_RECALL_CONTROL_CENTER`; the slices must have these UUIDs, or the targets and the IDA baseline no longer apply. + +## Running + +```sh +SWIFT_SECTION=/path/to/swift-section Scripts/CrossReferenceRecall/run_all.sh +``` + +About 30 seconds. Everything is written to `CROSS_REFERENCE_RECALL_WORK` (default `/tmp/cross-reference-recall`). Needs `otool`, `dyld_info`, `lipo` and `dwarfdump` from the Xcode command-line tools, and the system `python3`. + +| Script | What it does | +|---|---| +| `prepare.sh` | Thins both binaries to arm64e and writes their `otool -tV`, section and `dyld_info -fixups` listings. | +| `ground_truth.py` | Builds the ground truth — `otool -tV` plus a linear `adrp` register tracker, the fixups, the relative method lists and `__swift5_types` — and picks the 120 targets, seeded, in the order the 2026-11-18 run did. | +| `verify_reproduction.py` | Checks the totals and target lists against that run's printed output; fails when they differ. | +| `query_swift_section.py` | Asks `$SWIFT_SECTION refs` once per target, as an agent would. | +| `score.py` | Scores with the 2026-11-18 rules and prints the table beside `ida-2026-11-18.txt`; every miss and extra goes to `swift-section.details.txt` with its disassembly line. | + +`ground_truth.py` is the 2026-11-18 run's code, recovered from that session's transcript and rewritten with full names; `verify_reproduction.py` is what shows the rewrite changed nothing. `ida-2026-11-18.txt` is that run's scoring output (`ida1` one query, `ida2` two hops; the `bn` rows are Binary Ninja through its MCP server). + +## Categories + +A selector sends · B Objective-C class references · C imported functions through stubs · D internal functions called with `bl` · E string literals · F instance variable offsets (Finder only) · G Swift metadata accessors, and functions only Swift tables point at (ControlCenter only) · H method implementations and function pointers. G-tableonly and H are data references, which `refs` does not report. + +## Results + +| Date | Tool | Code references found (of 527) | +|---|---|---| +| 2026-11-18 | IDA, one query / two hops | 97.0% / 99.4% | +| 2026-11-18 | Binary Ninja 6 through its MCP server | 67.6% | +| 2026-11-26 | `swift-section` 0.25.0 | 90.3% (476) | + +0.25.0's 51 misses: 27 Swift metadata accessors whose address is taken rather than called, 13 loads from `__objc_superrefs` (not class references by design), 8 class GOT slots whose address Swift code hands to the metadata helper, 2 selectors used as arguments, 1 instance variable offset whose address two paths build differently before one load. The proposal fixes all but the 13. diff --git a/Scripts/CrossReferenceRecall/ground_truth.py b/Scripts/CrossReferenceRecall/ground_truth.py new file mode 100644 index 00000000..ed0aa715 --- /dev/null +++ b/Scripts/CrossReferenceRecall/ground_truth.py @@ -0,0 +1,403 @@ +"""Builds the independent ground truth of the cross-reference recall +benchmark and picks its targets, exactly as the 2026-11-18 IDA / Binary Ninja +benchmark did (see README.md): from `otool -tV`, a linear `adrp` register +tracker, `dyld_info -fixups`, the relative method lists and `__swift5_types` — +none of the tools measured. + +The order matters and is kept: a first ground truth with a 64-instruction +window between `adrp` and its use, the Finder targets picked from it, then +the final ground truth without the window, and the ControlCenter targets +picked from that. Both pickings are seeded, so the targets come out the same +every time; `verify_reproduction.py` checks that they do. + +Reads `.otool`, `.sections` and `.fixups` +(`prepare.sh`) from the work directory; writes `.ground-truth.json`, +`.pairs.json` and `.targets.json` there. +""" +import collections +import json +import os +import random +import re +import struct +import subprocess + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" +BINARIES = ("Finder", "ControlCenter") +INSTRUCTION_PATTERN = re.compile(r'^([0-9a-f]{16})\t(\S+)\t?([^;]*)') +ADD_PATTERN = re.compile(r'(\w+), (\w+), #(0x[0-9a-f]+|\d+)$') +MEMORY_PATTERN = re.compile(r'(\w+)(?:, (\w+))?, \[(\w+)(?:, #(-?0x[0-9a-f]+|-?\d+))?\]$') +NOT_WRITING_PREFIXES = ("st", "cmp", "cmn", "tst", "b", "cb", "tb", "ret", "pac", "aut", "brk", "fcmp", "prfm") +POINTER_SECTIONS = ("__got", "__auth_got", "__objc_superrefs", "__objc_classrefs") + + +def function_starts(binary_name): + output = subprocess.run(["dyld_info", "-function_starts", WORK + binary_name], capture_output=True, text=True).stdout + return [int(line.split()[0], 16) for line in output.splitlines()[2:] if line.strip().startswith("0x")] + + +def file_bytes_reader(binary_name): + """A reader of the bytes at a virtual address, through the segments' + file offsets.""" + file_bytes = open(WORK + binary_name, "rb").read() + load_commands = subprocess.run(["otool", "-l", WORK + binary_name], capture_output=True, text=True).stdout + segments = [] + current = {} + for line in load_commands.splitlines(): + tokens = line.split() + if not tokens: + continue + if tokens[0] == "cmd": + current = {"cmd": tokens[1]} + if tokens[0] in ("segname", "vmaddr", "vmsize", "fileoff", "filesize") and current.get("cmd") == "LC_SEGMENT_64" and tokens[0] not in current: + current[tokens[0]] = tokens[1] if tokens[0] == "segname" else int(tokens[1], 0) + if tokens[0] == "filesize": + segments.append(dict(current)) + + def read_bytes(address, count): + for segment in segments: + if segment["vmaddr"] <= address < segment["vmaddr"] + segment["filesize"]: + offset = segment["fileoff"] + address - segment["vmaddr"] + return file_bytes[offset:offset + count] + return None + + return read_bytes + + +def read_sections(binary_name): + sections = {} + for line in open(WORK + binary_name + ".sections"): + segment, section, address, size = line.split() + sections[section if section not in sections else segment + "," + section] = (int(address, 16), int(size, 16)) + return sections + + +def read_fixups(binary_name): + fixups = {} + for line in open(WORK + binary_name + ".fixups"): + tokens = line.split() + if len(tokens) >= 5 and tokens[2].startswith("0x"): + address = int(tokens[2], 16) + if tokens[3] in ("rebase", "auth-rebase"): + fixups[address] = ("r", int(tokens[4], 16)) + else: + fixups[address] = ("b", tokens[4]) + return fixups + + +def track_references(binary_name, window): + """Every address an instruction reaches: a branch target, an `adr`, or an + `adrp` page plus the immediate of an `add` or a load / store that uses + it — no further than `window` instructions apart when a window is given. + Also which `adrp` each such use pairs with.""" + starts = set(function_starts(binary_name)) + references = collections.defaultdict(list) + pairs = {} + registers = {} + instruction_number = 0 + for line in open(WORK + binary_name + ".otool"): + match = INSTRUCTION_PATTERN.match(line) + if not match: + continue + instruction_address = int(match.group(1), 16) + mnemonic = match.group(2) + operands = match.group(3).strip() + if instruction_address in starts: + registers = {} + instruction_number += 1 + if mnemonic == "adrp": + registers[operands.split(",", 1)[0].strip()] = (int(line.split(";")[1].strip(), 16), instruction_number, instruction_address) + continue + if mnemonic in ("bl", "b") and operands.startswith("0x"): + references[int(operands, 16)].append((instruction_address, "call" if mnemonic == "bl" else "jump")) + continue + if mnemonic == "adr": + register, immediate = [operand.strip() for operand in operands.split(",")] + references[instruction_address + int(immediate.lstrip("#"), 0)].append((instruction_address, "adr")) + registers.pop(register, None) + continue + add_match = ADD_PATTERN.match(operands) if mnemonic == "add" else None + if add_match: + destination, source, immediate = add_match.groups() + if source in registers and (window is None or instruction_number - registers[source][1] < window): + references[registers[source][0] + int(immediate, 0)].append((instruction_address, "add")) + pairs[instruction_address] = registers[source][2] + registers.pop(destination, None) + continue + memory_match = MEMORY_PATTERN.match(operands) + if memory_match and (mnemonic.startswith("ld") or mnemonic.startswith("st") or mnemonic == "prfm"): + destination, second_destination, base, immediate = memory_match.groups() + if base in registers and (window is None or instruction_number - registers[base][1] < window): + references[registers[base][0] + int(immediate or "0", 0)].append((instruction_address, mnemonic)) + pairs[instruction_address] = registers[base][2] + if mnemonic.startswith("ld"): + registers.pop(destination, None) + if second_destination: + registers.pop(second_destination, None) + continue + if operands and not mnemonic.startswith(NOT_WRITING_PREFIXES): + destination = operands.split(",")[0].strip() + registers.pop(destination, None) + if destination.startswith("w"): + registers.pop("x" + destination[1:], None) + return references, pairs + + +def objective_c_stubs(sections, fixups, read_bytes): + """Each `__objc_stubs` stub: its selector reference and selector.""" + def c_string(address): + bytes_read = read_bytes(address, 512) + return bytes_read.split(b"\0")[0].decode("utf8", "replace") if bytes_read else None + + stubs = {} + if "__objc_stubs" not in sections: + return stubs + start, size = sections["__objc_stubs"] + address = start + while address < start + size: + first_word, second_word = struct.unpack("> 29) & 3 + immediate_high = (first_word >> 5) & 0x7FFFF + immediate = (immediate_high << 2) | immediate_low + if immediate & (1 << 20): + immediate -= 1 << 21 + page = (address & ~0xFFF) + (immediate << 12) + offset = ((second_word >> 10) & 0xFFF) * 8 + selector_reference = page + offset + fixup = fixups.get(selector_reference) + selector = c_string(fixup[1]) if fixup and fixup[0] == "r" else None + stubs[address] = (selector_reference, selector) + address += 32 + return stubs + + +def save_ground_truth(binary_name, sections, stubs, references, fixups): + json.dump({ + "sections": sections, + "stubs": {str(key): value for key, value in stubs.items()}, + "references": {str(key): value for key, value in references.items()}, + "fixups": {str(key): value for key, value in fixups.items()}, + }, open(WORK + binary_name + ".ground-truth.json", "w")) + + +def load_ground_truth(binary_name): + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + return ( + ground_truth["sections"], + {int(key): value for key, value in ground_truth["stubs"].items()}, + {int(key): value for key, value in ground_truth["references"].items()}, + {int(key): value for key, value in ground_truth["fixups"].items()}, + ) + + +def method_list_references(sections, read_bytes): + """Each method implementation's address, and the method list fields + that point at it: relative method lists, 12-byte entries.""" + method_lists_start, method_lists_size = sections["__objc_methlist"] + references = {} + lists = 0 + address = method_lists_start + while address < method_lists_start + method_lists_size - 8: + entry_size_and_flags, count = struct.unpack(" 5000: + print("bad method list", hex(address), hex(entry_size_and_flags), count) + break + lists += 1 + for index in range(count): + field = address + 8 + index * 12 + 8 + implementation = field + struct.unpack(" 0] + chosen = random.sample(candidates, 6) + random.sample(with_direct_loads, 2) + targets["A"] = [dict(stub=candidate[0], selector_reference=candidate[1], selector=candidate[2]) for candidate in chosen] + global_offset_table = section_range("__got") + authenticated_global_offset_table = section_range("__auth_got") + class_list = section_range("__objc_classlist") + external = [ + (address, value) for address, (kind, value) in fixups.items() + if (global_offset_table[0] <= address < global_offset_table[1] or authenticated_global_offset_table[0] <= address < authenticated_global_offset_table[1]) + and kind == "b" and "_OBJC_CLASS_$_" in value and 2 <= len(code_references(address)) <= 50 + ] + classes = [value for address, (kind, value) in fixups.items() if class_list[0] <= address < class_list[1] and kind == "r"] + own = [class_address for class_address in classes if 2 <= len(code_references(class_address)) <= 50] + targets["B"] = [dict(kind="ext", slot=address, symbol=value) for address, value in random.sample(external, 4)] + [dict(kind="own", class_address=class_address) for class_address in random.sample(own, 4)] + authenticated_stubs = section_range("__auth_stubs") + targets["C"] = random.sample([address for address in range(authenticated_stubs[0], authenticated_stubs[1], 16) if 2 <= len(code_references(address)) <= 50], 8) + starts = function_starts(binary_name) + start_set = set(starts) + targets["D"] = random.sample([start for start in starts if 2 <= len([instruction for instruction, kind in references.get(start, []) if kind == "call"]) <= 50], 8) + constant_strings = section_range("__cfstring") + c_strings = section_range("__cstring") + constant_string_targets = [address for address in range(constant_strings[0], constant_strings[1], 32) if 2 <= len(code_references(address)) <= 50] + c_string_targets = sorted(target for target in references if c_strings[0] <= target < c_strings[1] and 2 <= len(code_references(target)) <= 50) + targets["E"] = [dict(kind="cfstr", address=address) for address in random.sample(constant_string_targets, 4)] + [dict(kind="cstr", address=address) for address in random.sample(c_string_targets, 4)] + instance_variables = section_range("__objc_ivar") + targets["F"] = random.sample([address for address in range(instance_variables[0], instance_variables[1], 8) if 2 <= len(code_references(address)) <= 50], 8) + implementations, lists = method_list_references(sections, file_bytes_reader(binary_name)) + print("lists", lists, "imps", len(implementations)) + rebase_targets_in_text = {} + for fixup_address, (kind, value) in fixups.items(): + if kind == "r" and is_in_text(value): + rebase_targets_in_text.setdefault(value, []).append(fixup_address) + method_implementations = [start for start in implementations if start in start_set] + pointed_functions = [start for start in rebase_targets_in_text if start in start_set and start not in implementations] + print("H1", len(method_implementations), "H2", len(pointed_functions)) + targets["H"] = [dict(kind="imp", function=start) for start in random.sample(method_implementations, 4)] + [dict(kind="ptr", function=start) for start in random.sample(pointed_functions, 4)] + json.dump({ + "targets": targets, + "method_list_references": {str(key): value for key, value in implementations.items()}, + }, open(WORK + binary_name + ".targets.json", "w")) + + +def pick_control_center_targets(): + binary_name = "ControlCenter" + sections, stubs, references, fixups = load_ground_truth(binary_name) + read_bytes = file_bytes_reader(binary_name) + + def section_range(name): + start, size = sections[name] + return start, start + size + + text = section_range("__text") + + def is_in_text(address): + return text[0] <= address < text[1] + + def section_name(address): + for name, (start, size) in sections.items(): + if start <= address < start + size: + return name + return "?" + + def code_references(target): + return sorted(set(instruction for instruction, kind in references.get(target, []) if is_in_text(instruction))) + + random.seed(11) + targets = {} + candidates = [ + (stub_address, selector_reference, selector, len([instruction for instruction, kind in references.get(stub_address, []) if kind == "call" and is_in_text(instruction)]), len(code_references(selector_reference))) + for stub_address, (selector_reference, selector) in stubs.items() + ] + candidates = [candidate for candidate in candidates if 2 <= candidate[3] <= 50] + with_direct_loads = [candidate for candidate in candidates if candidate[4] > 0] + print("A", len(candidates), len(with_direct_loads)) + chosen = random.sample(candidates, 8 - min(2, len(with_direct_loads))) + random.sample(with_direct_loads, min(2, len(with_direct_loads))) + targets["A"] = [dict(stub=candidate[0], selector_reference=candidate[1], selector=candidate[2]) for candidate in chosen] + binds_by_symbol = collections.defaultdict(list) + rebases_by_target = collections.defaultdict(list) + for address, (kind, value) in fixups.items(): + if kind == "b": + binds_by_symbol[value.split("/")[-1].split()[0]].append(address) + else: + rebases_by_target[value].append(address) + external = [ + symbol for symbol, slots in binds_by_symbol.items() + if "_OBJC_CLASS_$_" in symbol and 2 <= sum(len(code_references(slot)) for slot in slots if section_name(slot) in POINTER_SECTIONS) <= 50 + ] + class_list = section_range("__objc_classlist") + classes = [value for address, (kind, value) in fixups.items() if class_list[0] <= address < class_list[1] and kind == "r"] + + def class_references(class_address): + return set(code_references(class_address)).union(*[set(code_references(slot)) for slot in rebases_by_target.get(class_address, []) if section_name(slot) in POINTER_SECTIONS]) + + own = [class_address for class_address in classes if 2 <= len(class_references(class_address)) <= 50] + print("B ext", len(external), "own", len(own), "of", len(classes)) + targets["B"] = [dict(kind="ext", symbol="x/" + symbol) for symbol in random.sample(external, 4)] + [dict(kind="own", class_address=class_address) for class_address in random.sample(own, min(4, len(own)))] + authenticated_stubs = section_range("__auth_stubs") + targets["C"] = random.sample([address for address in range(authenticated_stubs[0], authenticated_stubs[1], 16) if 2 <= len(code_references(address)) <= 50], 8) + starts = function_starts(binary_name) + start_set = set(starts) + types = section_range("__swift5_types") + accessors = {} + for address in range(types[0], types[1], 4): + descriptor = address + struct.unpack("= 1] + print("F", [(hex(address), len(code_references(address))) for address in targets["F"]]) + implementations, _ = method_list_references(sections, read_bytes) + rebase_targets_in_text = {} + for fixup_address, (kind, value) in fixups.items(): + if kind == "r" and is_in_text(value): + rebase_targets_in_text.setdefault(value, []).append(fixup_address) + method_implementations = [start for start in implementations if start in start_set] + # Functions referenced only from Swift metadata and witness tables: data, + # and no code. + table_only = [ + start for start, slots in rebase_targets_in_text.items() + if start in start_set and start not in implementations and not code_references(start) and all(section_name(slot) in ("__data", "__const") for slot in slots) + ] + pointed_functions = [start for start in rebase_targets_in_text if start in start_set and start not in implementations and start not in table_only] + print("H1", len(method_implementations), "H2", len(pointed_functions), "G2", len(table_only)) + targets["H"] = [dict(kind="imp", function=start) for start in random.sample(method_implementations, 4)] + [dict(kind="ptr", function=start) for start in random.sample(pointed_functions, 4)] + targets["G"] = [dict(category="G", kind="accessor", function=start) for start in random.sample(accessor_candidates, 8)] + [dict(category="G", kind="tableonly", function=start) for start in random.sample(table_only, 8)] + json.dump({ + "targets": targets, + "method_list_references": {str(key): value for key, value in implementations.items()}, + }, open(WORK + binary_name + ".targets.json", "w")) + + +def main(): + for binary_name in BINARIES: + read_bytes = file_bytes_reader(binary_name) + sections = read_sections(binary_name) + fixups = read_fixups(binary_name) + stubs = objective_c_stubs(sections, fixups, read_bytes) + references, _ = track_references(binary_name, window=64) + save_ground_truth(binary_name, sections, stubs, references, fixups) + print(binary_name, "stubs", len(stubs), "targets", len(references), "refs", sum(len(value) for value in references.values())) + pick_finder_targets() + for binary_name in BINARIES: + sections, stubs, first_references, fixups = load_ground_truth(binary_name) + references, pairs = track_references(binary_name, window=None) + save_ground_truth(binary_name, sections, stubs, references, fixups) + json.dump({str(key): value for key, value in pairs.items()}, open(WORK + binary_name + ".pairs.json", "w")) + print(binary_name, "refs old", sum(len(value) for value in first_references.values()), "new", sum(len(value) for value in references.values())) + pick_control_center_targets() + + +main() diff --git a/Scripts/CrossReferenceRecall/ida-2026-11-18.txt b/Scripts/CrossReferenceRecall/ida-2026-11-18.txt new file mode 100644 index 00000000..bf5ae684 --- /dev/null +++ b/Scripts/CrossReferenceRecall/ida-2026-11-18.txt @@ -0,0 +1,60 @@ +Finder A bn1 code 20/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder A bn2 code 22/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder A ida1 code 20/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder A ida2 code 22/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder B bn1 code 0/57 data 8/13 extra 0 {} internal 0 2hop 0 +Finder B bn2 code 57/57 data 8/13 extra 0 {} internal 0 2hop 0 +Finder B ida1 code 54/57 data 13/13 extra 0 {} internal 0 2hop 0 +Finder B ida2 code 54/57 data 13/13 extra 1 {'__objc_classlist': 1} internal 0 2hop 0 +Finder C bn1 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder C bn2 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder C ida1 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder C ida2 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder D bn1 code 27/28 data 0/0 extra 0 {} internal 226 2hop 0 +Finder D bn2 code 27/28 data 0/0 extra 0 {} internal 226 2hop 0 +Finder D ida1 code 28/28 data 0/0 extra 0 {} internal 2 2hop 0 +Finder D ida2 code 28/28 data 0/0 extra 0 {} internal 2 2hop 0 +Finder E bn1 code 0/28 data 2/2 extra 0 {} internal 0 2hop 0 +Finder E bn2 code 26/28 data 2/2 extra 0 {} internal 0 2hop 0 +Finder E ida1 code 28/28 data 2/2 extra 0 {} internal 0 2hop 0 +Finder E ida2 code 28/28 data 2/2 extra 0 {} internal 0 2hop 6 +Finder F bn1 code 0/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder F bn2 code 32/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder F ida1 code 32/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder F ida2 code 32/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder H bn1 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 13 2hop 0 +Finder H bn2 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 13 2hop 0 +Finder H ida1 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 +Finder H ida2 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 +ControlCenter A bn1 code 72/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter A bn2 code 75/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter A ida1 code 72/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter A ida2 code 75/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter B bn1 code 0/30 data 5/9 extra 0 {} internal 0 2hop 0 +ControlCenter B bn2 code 30/30 data 5/9 extra 0 {} internal 0 2hop 0 +ControlCenter B ida1 code 22/30 data 9/9 extra 2 {'text:ldr': 1, '?': 1} internal 0 2hop 0 +ControlCenter B ida2 code 30/30 data 9/9 extra 3 {'text:ldr': 1, '?': 2} internal 0 2hop 0 +ControlCenter C bn1 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter C bn2 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter C ida1 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter C ida2 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter D bn1 code 42/42 data 0/0 extra 0 {} internal 21 2hop 0 +ControlCenter D bn2 code 42/42 data 0/0 extra 0 {} internal 21 2hop 0 +ControlCenter D ida1 code 42/42 data 0/0 extra 1 {'__data': 1} internal 0 2hop 0 +ControlCenter D ida2 code 42/42 data 0/0 extra 1 {'__data': 1} internal 0 2hop 0 +ControlCenter E bn1 code 0/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter E bn2 code 9/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter E ida1 code 18/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter E ida2 code 18/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter G-accessor bn1 code 104/104 data 0/0 extra 5 {'text:adrp': 5} internal 3 2hop 0 +ControlCenter G-accessor bn2 code 104/104 data 0/0 extra 5 {'text:adrp': 5} internal 3 2hop 0 +ControlCenter G-accessor ida1 code 104/104 data 0/0 extra 8 {'__constg_swiftt': 8} internal 0 2hop 0 +ControlCenter G-accessor ida2 code 104/104 data 0/0 extra 8 {'__constg_swiftt': 8} internal 0 2hop 0 +ControlCenter G-tableonly bn1 code 0/0 data 11/11 extra 17 {'text:adrp': 17} internal 4 2hop 0 +ControlCenter G-tableonly bn2 code 0/0 data 11/11 extra 17 {'text:adrp': 17} internal 4 2hop 0 +ControlCenter G-tableonly ida1 code 0/0 data 11/11 extra 0 {} internal 0 2hop 0 +ControlCenter G-tableonly ida2 code 0/0 data 11/11 extra 0 {} internal 0 2hop 0 +ControlCenter H bn1 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 7 2hop 0 +ControlCenter H bn2 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 7 2hop 0 +ControlCenter H ida1 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 +ControlCenter H ida2 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 \ No newline at end of file diff --git a/Scripts/CrossReferenceRecall/prepare.sh b/Scripts/CrossReferenceRecall/prepare.sh new file mode 100644 index 00000000..f0cccc23 --- /dev/null +++ b/Scripts/CrossReferenceRecall/prepare.sh @@ -0,0 +1,22 @@ +#!/bin/zsh +# Thins the two samples to the arm64e slice both IDA databases hold, and +# writes the disassembly, load-command and fixup listings ground_truth.py +# reads. The samples are the ones the 2026-11-18 benchmark used. +set -euo pipefail +WORK=${CROSS_REFERENCE_RECALL_WORK:-/tmp/cross-reference-recall} +FINDER=${CROSS_REFERENCE_RECALL_FINDER:-/Volumes/RE/Finder/26.5.2/Finder} +CONTROL_CENTER=${CROSS_REFERENCE_RECALL_CONTROL_CENTER:-/Volumes/RE/ControlCenter/26.7/ControlCenter} +mkdir -p $WORK +cd $WORK + +lipo -thin arm64e $FINDER -output Finder +lipo -thin arm64e $CONTROL_CENTER -output ControlCenter +# 1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0 and 5782ED6B-471B-3CAC-9258-93734B6009C3. +dwarfdump --uuid Finder ControlCenter + +for binary in Finder ControlCenter; do + otool -arch arm64e -tV $WORK/$binary > $binary.otool + otool -arch arm64e -l $WORK/$binary | awk '/sectname/{s=$2} /segname/{g=$2} /^ *addr /{a=$2} /^ *size /{if(s!=""){print g, s, a, $2; s=""}}' > $binary.sections + dyld_info -fixups $WORK/$binary > $binary.fixups + wc -l $binary.otool $binary.sections $binary.fixups +done diff --git a/Scripts/CrossReferenceRecall/query_swift_section.py b/Scripts/CrossReferenceRecall/query_swift_section.py new file mode 100644 index 00000000..e6730af2 --- /dev/null +++ b/Scripts/CrossReferenceRecall/query_swift_section.py @@ -0,0 +1,240 @@ +"""Asks `swift-section refs` about every target of the benchmark. + +The per-target ground truth is built exactly as the 2026-11-18 harness built +it for IDA and Binary Ninja; only the tool asked changes. Each target gets +one query, as an agent would ask it ("one_query"). An external class also +gets the by-symbol query the documentation tells callers to add +("with_symbol_query"); for every other target the two are the same. + +The binary asked is `$SWIFT_SECTION`, `swift-section` on the `PATH` when it +is unset. Writes `.swift-section.results.json`. +""" +import bisect +import collections +import json +import os +import struct +import subprocess +import time + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" +SWIFT_SECTION = os.environ.get("SWIFT_SECTION", "swift-section") +POINTER_SECTIONS = ("__got", "__auth_got", "__objc_superrefs", "__objc_classrefs") + + +def run_binary(binary_name): + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + references_by_target = {int(key): value for key, value in ground_truth["references"].items()} + fixups = {int(key): value for key, value in ground_truth["fixups"].items()} + sections = ground_truth["sections"] + targets_document = json.load(open(WORK + binary_name + ".targets.json")) + targets = targets_document["targets"] + method_list_references = {int(key): value for key, value in targets_document.get("method_list_references", {}).items()} + + text_range = (sections["__text"][0], sections["__text"][0] + sections["__text"][1]) + + def is_in_text(address): + return text_range[0] <= address < text_range[1] + + def section_name(address): + for name, (start, size) in sections.items(): + if start <= address < start + size: + return name + return "?" + + def code_references(target_address): + return set(instruction for instruction, kind in references_by_target.get(target_address, []) if is_in_text(instruction)) + + rebases_by_target = collections.defaultdict(list) + binds_by_symbol = collections.defaultdict(list) + for slot_address, (fixup_kind, value) in fixups.items(): + if fixup_kind == "r": + rebases_by_target[value].append(slot_address) + else: + binds_by_symbol[value.split("/")[-1].split()[0]].append(slot_address) + + function_starts_output = subprocess.run(["dyld_info", "-function_starts", WORK + binary_name], capture_output=True, text=True).stdout + function_starts = sorted(int(line.split()[0], 16) for line in function_starts_output.splitlines()[2:] if line.strip().startswith("0x")) + + def function_end(function_start): + index = bisect.bisect_right(function_starts, function_start) + return function_starts[index] if index < len(function_starts) else text_range[1] + + file_bytes = open(WORK + binary_name, "rb").read() + + def read_bytes(address, count): + offset = address - 0x100000000 + return file_bytes[offset:offset + count] + + def stub_slot(stub_address): + words = struct.unpack("> 5) & 0x7FFFF) << 2) | ((words[0] >> 29) & 3) + if immediate & (1 << 20): + immediate -= 1 << 21 + return (stub_address & ~0xFFF) + (immediate << 12) + ((words[1] >> 10) & 0xFFF) + + # Names the queries need. Finder and ControlCenter keep no local symbols, so + # class and instance variable names are read from the Objective-C metadata. + def rebase_target(slot_address): + fixup = fixups.get(slot_address) + return fixup[1] if fixup and fixup[0] == "r" else None + + def read_c_string(address): + if address is None: + return None + raw = read_bytes(address, 4096).split(b"\0")[0] + try: + return raw.decode("utf-8") + except UnicodeDecodeError: + return None + + def class_read_only_data(class_address): + data_pointer = rebase_target(class_address + 32) + return data_pointer & ~7 if data_pointer is not None else None + + def class_runtime_name(class_address): + read_only_data = class_read_only_data(class_address) + return read_c_string(rebase_target(read_only_data + 24)) if read_only_data is not None else None + + def constant_string_characters(constant_string_address): + flags = struct.unpack(" ./run_all.sh +set -euo pipefail +SCRIPTS=${0:A:h} +export CROSS_REFERENCE_RECALL_WORK=${CROSS_REFERENCE_RECALL_WORK:-/tmp/cross-reference-recall} + +zsh $SCRIPTS/prepare.sh +python3 -I $SCRIPTS/ground_truth.py +python3 -I $SCRIPTS/verify_reproduction.py +python3 -I $SCRIPTS/query_swift_section.py +python3 -I $SCRIPTS/score.py diff --git a/Scripts/CrossReferenceRecall/score.py b/Scripts/CrossReferenceRecall/score.py new file mode 100644 index 00000000..2110ec8f --- /dev/null +++ b/Scripts/CrossReferenceRecall/score.py @@ -0,0 +1,141 @@ +"""Scores swift-section's answers with the 2026-11-18 scoring rules, puts +them next to that run's IDA rows (ida-2026-11-18.txt), and lists every miss +and extra with its disassembly line in `swift-section.details.txt`. + +A reference found counts when the tool's instruction is the ground truth's, +the `adrp` it pairs with, or up to 16 bytes after it; a hit inside the +target function itself, a data reference, or a reference through a +constant string to its characters is set aside rather than counted extra. +""" +import bisect +import collections +import json +import os +import re +import subprocess + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" +IDA_ROWS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ida-2026-11-18.txt") +TOOLS = ("one_query", "with_symbol_query") + +summary = {} +details = [] +for binary_name in ("Finder", "ControlCenter"): + results = json.load(open(WORK + binary_name + ".swift-section.results.json"))["results"] + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + sections = ground_truth["sections"] + pairs = {int(key): value for key, value in json.load(open(WORK + binary_name + ".pairs.json")).items()} + mnemonics = {} + lines = {} + for line in open(WORK + binary_name + ".otool"): + parts = line.split("\t") + if len(parts) > 1 and len(parts[0]) == 16: + address = int(parts[0], 16) + mnemonics[address] = parts[1] + lines[address] = line.rstrip("\n") + text_range = (sections["__text"][0], sections["__text"][0] + sections["__text"][1]) + + def is_in_text(address): + return text_range[0] <= address < text_range[1] + + def section_name(address): + for name, (start, size) in sections.items(): + if start <= address < start + size: + return name + return "?" + + function_starts_output = subprocess.run(["dyld_info", "-function_starts", WORK + binary_name], capture_output=True, text=True).stdout + function_starts = sorted(int(line.split()[0], 16) for line in function_starts_output.splitlines()[2:] if line.strip().startswith("0x")) + + def function_end(function_start): + index = bisect.bisect_right(function_starts, function_start) + return function_starts[index] if index < len(function_starts) else text_range[1] + + counters = collections.defaultdict(collections.Counter) + extra_kinds = collections.defaultdict(collections.Counter) + for result in results: + category = result["category"] + ("-" + result["label"].split("@")[0] if result["category"] == "G" else "") + target = result["target"] + ground_truth_code = set(result["ground_truth_code"]) + ground_truth_data = set(result["ground_truth_data"]) + legitimate = set(result["legitimate"]) + if category in ("C", "D"): + ground_truth_data = set() + legitimate_addresses = set() + for address in legitimate: + legitimate_addresses.update({address, pairs.get(address, -1)}) + low, high = (target, function_end(target)) if (target and is_in_text(target)) else (0, 0) + for tool in TOOLS: + counter = counters[(category, tool)] + counter["targets"] += 1 + answer = set(result["tools"][tool] or []) + found = set() + data_found = set() + for site in sorted(answer): + hits = [expected for expected in ground_truth_code if site == expected or site == pairs.get(expected) or (is_in_text(site) and 0 < site - expected <= 16)] + if hits: + found |= set(hits) + counter["matched"] += 1 + continue + if low <= site < high: + counter["inside_target"] += 1 + continue + matched_data = [expected for expected in ground_truth_data if not is_in_text(site) and 0 <= expected - site < 32] + if matched_data: + data_found |= set(matched_data) + continue + if site in legitimate_addresses: + counter["through_constant_string"] += 1 + continue + kind = "text:" + mnemonics.get(site, "?") if is_in_text(site) else section_name(site) + extra_kinds[(category, tool)][kind] += 1 + counter["extra"] += 1 + if tool == "with_symbol_query": + details.append(("EXTRA", binary_name, category, result["label"], hex(site), lines.get(site, kind))) + counter["ground_truth_code"] += len(ground_truth_code) + counter["found"] += len(found) + counter["ground_truth_data"] += len(ground_truth_data) + counter["data_found"] += len(data_found) + if tool == "with_symbol_query": + for missed in sorted(ground_truth_code - found): + details.append(("MISS", binary_name, category, result["label"], hex(missed), lines.get(missed, "?"))) + summary[binary_name] = {"%s|%s" % key: counter for key, counter in counters.items()} + +# The 2026-11-18 IDA rows, e.g. "Finder A ida1 code 20/22 data 0/0 extra 0 ..." +ida_rows = {} +for line in open(IDA_ROWS): + match = re.match(r"(\w+) (\S+) (ida1|ida2) code (\d+)/(\d+) data (\d+)/(\d+) extra (\d+)", line) + if match: + binary_name, category, tool, found, total, data_found, data_total, extra = match.groups() + ida_rows[(binary_name, category, "one_query" if tool == "ida1" else "two_hops")] = tuple(int(value) for value in (found, total, data_found, data_total, extra)) + +print("binary category GT IDA-1 IDA-2 ours-1 ours-2 | data GT IDA ours | extras IDA-2 ours-2") +totals = collections.Counter() +for binary_name in ("Finder", "ControlCenter"): + for category in sorted({key.split("|")[0] for key in summary[binary_name]}): + one_query = summary[binary_name][category + "|one_query"] + with_symbol_query = summary[binary_name][category + "|with_symbol_query"] + ida_one_query = ida_rows.get((binary_name, category, "one_query")) + ida_two_hops = ida_rows.get((binary_name, category, "two_hops")) + if ida_one_query and ida_one_query[1] != one_query["ground_truth_code"]: + print(" GROUND TRUTH DIFFERS from 2026-11-18:", binary_name, category, ida_one_query[1], one_query["ground_truth_code"]) + print("%-14s %-14s %4d %5s %5s %6d %6d | %7d %3s %4d | %12s %6d" % ( + binary_name, category, one_query["ground_truth_code"], + ida_one_query[0] if ida_one_query else "-", ida_two_hops[0] if ida_two_hops else "-", + one_query["found"], with_symbol_query["found"], + one_query["ground_truth_data"], ida_two_hops[2] if ida_two_hops else "-", with_symbol_query["data_found"], + ida_two_hops[4] if ida_two_hops else "-", with_symbol_query["extra"])) + totals["ground_truth"] += one_query["ground_truth_code"] + totals["one_query"] += one_query["found"] + totals["with_symbol_query"] += with_symbol_query["found"] + totals["ida_one_query"] += ida_one_query[0] if ida_one_query else 0 + totals["ida_two_hops"] += ida_two_hops[0] if ida_two_hops else 0 +print() +print("code references %d: IDA one query %.1f%%, two hops %.1f%%; swift-section one query %.1f%%, with the by-symbol query %.1f%%" % ( + totals["ground_truth"], 100 * totals["ida_one_query"] / totals["ground_truth"], 100 * totals["ida_two_hops"] / totals["ground_truth"], + 100 * totals["one_query"] / totals["ground_truth"], 100 * totals["with_symbol_query"] / totals["ground_truth"])) + +with open(WORK + "swift-section.details.txt", "w") as details_file: + for entry in details: + details_file.write("\t".join(str(field) for field in entry) + "\n") +print("misses", sum(1 for entry in details if entry[0] == "MISS"), "extras", sum(1 for entry in details if entry[0] == "EXTRA"), "->", WORK + "swift-section.details.txt") diff --git a/Scripts/CrossReferenceRecall/verify_reproduction.py b/Scripts/CrossReferenceRecall/verify_reproduction.py new file mode 100644 index 00000000..3deaf1d7 --- /dev/null +++ b/Scripts/CrossReferenceRecall/verify_reproduction.py @@ -0,0 +1,52 @@ +"""Checks that ground_truth.py reproduced the 2026-11-18 run: the totals and +target lists below are copied from that run's printed output. Exits with 1 +when anything differs — the numbers would no longer compare with the IDA +baseline in ida-2026-11-18.txt.""" +import json +import os +import sys + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" + +expected_reference_totals = {"Finder": 511138, "ControlCenter": 359773} +expected_stub_counts = {"Finder": 8809, "ControlCenter": 1363} +expected_targets = { + "Finder": { + "C": [4303335148, 4303340684, 4303335740, 4303349948, 4303345276, 4303334844, 4303359708, 4303350588], + "D": [4296493604, 4297114024, 4302277612, 4302218044, 4301417104, 4295793096, 4301308772, 4301449572], + "F": [4307227568, 4307236272, 4307226952, 4307236864, 4307231160, 4307236592, 4307228448, 4307226664], + "first selectors": ["propertiesToUpdate", "fiDomain"], + }, + "ControlCenter": { + "C": [4301922220, 4301907948, 4301911132, 4301927564, 4301924412, 4301927388, 4301895132, 4301924860], + "D": [4295169504, 4301400024, 4295515008, 4295483488, 4295324396, 4296870092, 4297616600, 4295299536], + "F": [], + "first selectors": ["sfSymbolNameCase", "ssidData"], + }, +} + +failures = [] +for binary_name, expectation in expected_targets.items(): + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + reference_total = sum(len(entries) for entries in ground_truth["references"].values()) + stub_count = len(ground_truth["stubs"]) + print(binary_name, "references", reference_total, "expected", expected_reference_totals[binary_name], "stubs", stub_count, "expected", expected_stub_counts[binary_name]) + if reference_total != expected_reference_totals[binary_name] or stub_count != expected_stub_counts[binary_name]: + failures.append(binary_name + " ground truth totals") + targets = json.load(open(WORK + binary_name + ".targets.json"))["targets"] + for category in ("C", "D", "F"): + matches = targets.get(category, []) == expectation[category] + print(binary_name, category, "matches" if matches else "DIFFERS") + if not matches: + failures.append(binary_name + " " + category) + first_selectors = [target["selector"] for target in targets["A"][:2]] + matches = first_selectors == expectation["first selectors"] + print(binary_name, "A", first_selectors, "matches" if matches else "DIFFERS") + if not matches: + failures.append(binary_name + " A") + print(binary_name, {category: len(entries) for category, entries in targets.items()}) + +if failures: + print("NOT REPRODUCED:", failures) + sys.exit(1) +print("reproduced") diff --git a/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift index 6c56a8a4..6e847fc6 100644 --- a/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift +++ b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift @@ -2,6 +2,7 @@ import Foundation import Testing +import MachOKit import MachOKitExtensions import CrossReferenceAnalysis import SwiftSectionKit From 88e9c535f1712ed504f5ac743e646acda90e7a3c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 18:13:59 +0800 Subject: [PATCH 151/175] test(IntegrationTests): give each version axis base class its own file VersionAxis.swift keeps the axis value types; the dump protocol and each axis base class, next to the configuration type it reads, move into files of their own. --- .../Internal/ProjectEvolutionLog.md | 2 +- .../CrossVersionMachOFileTests.swift | 58 ++++ .../CrossVersionXcodeFrameworkTests.swift | 61 ++++ .../InspectionDumps/DiffTests.swift | 7 +- .../MultiVersionDyldCacheImageTests.swift | 174 ++++++++++ .../InspectionDumps/VersionAxis.swift | 306 ------------------ .../VersionAxisDumpTests.swift | 35 ++ 7 files changed, 333 insertions(+), 310 deletions(-) create mode 100644 Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift create mode 100644 Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift create mode 100644 Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift create mode 100644 Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 72d2a5c4..e5be67ba 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -3658,7 +3658,7 @@ - 读哪个框架交给具名配置:`CacheImagesConfiguration`(`.swiftUI`、`.swiftUICore`、`.appKit`、`.swiftUIGroup`、`.appKitGroup`;列多个镜像就是镜像组,不再单开套件)、`SimulatorFilePairConfiguration`(`.swiftUICore`、`.swiftUI`)、`XcodeFrameworkPairConfiguration`(`.dvtProductsUI`)。三个轴基类各读一个 `configuration` 类属性,原来的 `cacheImageName(s)`、`oldFileName` 一类属性删掉。接口套件的镜像本来就是基类的一个类属性,照旧。要看别的框架,加一份配置、把套件指过去。 - 每个套件把这一类的输出各写一遍,Swift 与 ObjC 都写:接口 20 个、diff 24 个、演进 25 个测试;测试函数名与输出文件名不变。默认配置取覆盖面最广的:演进的两个 cache 套件读 SwiftUI 加 SwiftUICore,diff 与接口的 cache 套件读 AppKit。AppKit 的演进、SwiftUI 的模拟器 diff 不再默认跑,要看时改配置。 - pack 门面那个测试改成取前三个版本、不足三个时打印一行说明;配置是镜像组时,它只印各版本的主镜像,不再与 `swiftInterfaceString` 逐字相同。 -- **落地模块**:`Tests/IntegrationTests/InspectionDumps/`(`VersionAxis.swift`、`InterfaceTests.swift`、`DiffTests.swift`、`EvolutionTests.swift`)。 +- **落地模块**:`Tests/IntegrationTests/InspectionDumps/`:`InterfaceTests.swift`、`DiffTests.swift`、`EvolutionTests.swift`;原来的 `VersionAxis.swift` 按职责拆成五个文件——`VersionAxis.swift`(轴的值类型)、`VersionAxisDumpTests.swift`(协议与共享的 ObjC 快照)、`MultiVersionDyldCacheImageTests.swift`、`CrossVersionMachOFileTests.swift`、`CrossVersionXcodeFrameworkTests.swift`(每个轴基类与它的配置类型一个文件)。 - **文档**:[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段改用新的套件与配置名。没有新术语,不另写使用指南或实现说明;提案 0111 是落地时的快照,不改。 - **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests`。 - **对应版本**:未发布(只改测试目标)。 diff --git a/Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift b/Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift new file mode 100644 index 00000000..4ea327f2 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox + +/// The same file in two simulator runtimes, and the runtime versions that +/// label them on the axis. A suite points at one of these; to look at +/// another file, add one. +struct SimulatorFilePairConfiguration: Sendable { + let oldFileName: MachOFileName + let newFileName: MachOFileName + let oldVersionLabel: String + let newVersionLabel: String + + static var swiftUICore: Self { + Self(oldFileName: .iOS_18_5_Simulator_SwiftUICore, newFileName: .iOS_26_5_Simulator_SwiftUICore, oldVersionLabel: "18.5", newVersionLabel: "26.5") + } + + static var swiftUI: Self { + Self(oldFileName: .iOS_18_5_Simulator_SwiftUI, newFileName: .iOS_26_5_Simulator_SwiftUI, oldVersionLabel: "18.5", newVersionLabel: "26.5") + } +} + +/// The same file from two simulator runtimes, by fixture name — the +/// two-version counterpart of `SwiftSectionTestingSupport.MachOFileTests`, +/// which loads one. `configuration` names the pair. +@TestActor +class CrossVersionMachOFileTests: Sendable { + let oldMachOFile: MachOFile + let newMachOFile: MachOFile + private let axes: VersionAxes + + class var configuration: SimulatorFilePairConfiguration { .swiftUICore } + + init() async throws { + let configuration = Self.configuration + let oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.oldFileName)) + let newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.newFileName)) + self.oldMachOFile = oldMachOFile + self.newMachOFile = newMachOFile + self.axes = VersionAxes( + versions: [ + AxisVersion(label: configuration.oldVersionLabel, images: [AxisImage(imageName: oldMachOFile.imagePath.lastPathComponent, machOFile: oldMachOFile)]), + AxisVersion(label: configuration.newVersionLabel, images: [AxisImage(imageName: newMachOFile.imagePath.lastPathComponent, machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift b/Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift new file mode 100644 index 00000000..0a7b8c01 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift @@ -0,0 +1,61 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox + +/// A shared framework of two installed Xcode applications, picked by +/// version — `/Applications/Xcode-.app` — which also labels it on +/// the axis. A suite points at one of these; to look at another framework or +/// other Xcodes, add one. +struct XcodeFrameworkPairConfiguration: Sendable { + let frameworkName: String + let oldXcodeVersion: String + let newXcodeVersion: String + + static var dvtProductsUI: Self { + Self(frameworkName: "DVTProductsUI", oldXcodeVersion: "26.3.0", newXcodeVersion: "26.4.0") + } +} + +/// The same shared framework from two installed Xcode applications, picked +/// by version: `/Applications/Xcode-.app`. The shared +/// `XcodeMachOFileName` fixture names a single Xcode, so this loads by path. +/// `configuration` names the framework and the two versions. +@TestActor +class CrossVersionXcodeFrameworkTests: Sendable { + let oldMachOFile: MachOFile + let newMachOFile: MachOFile + private let axes: VersionAxes + + class var configuration: XcodeFrameworkPairConfiguration { .dvtProductsUI } + + init() async throws { + let configuration = Self.configuration + let frameworkName = configuration.frameworkName + let oldMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.oldXcodeVersion) + let newMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.newXcodeVersion) + self.oldMachOFile = oldMachOFile + self.newMachOFile = newMachOFile + self.axes = VersionAxes( + versions: [ + AxisVersion(label: configuration.oldXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: oldMachOFile)]), + AxisVersion(label: configuration.newXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } + + private static func loadSharedFramework(named name: String, fromXcodeVersion xcodeVersion: String) throws -> MachOFile { + let binaryPath = "/Applications/Xcode-\(xcodeVersion).app/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" + return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/DiffTests.swift b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift index b7ecd840..4fc00375 100644 --- a/Tests/IntegrationTests/InspectionDumps/DiffTests.swift +++ b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift @@ -7,9 +7,10 @@ import SwiftSectionFixtureSupport /// Every diff the maintainer inspects, one suite per place the two versions /// come from. Each suite runs every diff output on one pair, which its -/// `configuration` names — the version axis base classes the evolution -/// suites read too (see `VersionAxis.swift`). To diff another framework, add -/// a configuration and point the suite at it. +/// `configuration` names; the pairs come from the version axis base classes +/// the evolution suites read too (`MultiVersionDyldCacheImageTests`, +/// `CrossVersionMachOFileTests`, `CrossVersionXcodeFrameworkTests`). To diff +/// another framework, add a configuration and point the suite at it. enum Diff { /// The same file in two simulator runtimes (iOS 18.5 → 26.5). final class SimulatorFiles: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { diff --git a/Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift b/Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift new file mode 100644 index 00000000..2974db01 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift @@ -0,0 +1,174 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox + +/// The images a dyld shared cache suite reads out of each cache, the +/// primary image first. More than one makes every version a group of images +/// (evolution proposal `image-group-evolution`): AppKit with the frameworks +/// Apple moved its classes into, SwiftUI with SwiftUICore. Each other image +/// joins its group where the cache has it with the metadata — +/// CollectionViewCore is in the macOS caches from 13.0 on, SwiftUICore from +/// 15.0 on. +/// +/// A suite points at one of these; to look at another framework, add one and +/// point the suite at it. +struct CacheImagesConfiguration: Sendable { + let imageNames: [MachOImageName] + + static var swiftUI: Self { Self(imageNames: [.SwiftUI]) } + static var swiftUICore: Self { Self(imageNames: [.SwiftUICore]) } + /// AppKit kept its Swift API in `libswiftAppKit.dylib` until macOS 14, + /// so its Swift axis starts at 14.0; its Objective-C metadata is in every + /// cache. + static var appKit: Self { Self(imageNames: [.AppKit]) } + static var swiftUIGroup: Self { Self(imageNames: [.SwiftUI, .SwiftUICore]) } + static var appKitGroup: Self { Self(imageNames: [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout]) } +} + +/// Extracts the same images from an *ordered series* of dyld shared caches: +/// N versions for an evolution, two for a diff. The caches are retained +/// because the extracted `MachOFile`s resolve cross-image references through +/// them while indexing. +/// +/// One instance serves every pipeline: it keeps, per cache, every image of +/// `configuration` the cache holds, and each language's axis then keeps +/// the images carrying that language's metadata. A version whose primary +/// image is missing, or lacks the metadata, is off that axis — there is +/// nothing to index. A cache that cannot be opened still throws. +/// +/// Each cache is opened whole, the way `swift-section --dyld-shared-cache` +/// opens it, so the dumps match what the command line prints. Opened from +/// its main file alone, every read into another sub-cache file mapped that +/// file once more until MachOObjCSection 0.8.109, and an evolution over +/// every archived macOS minor ran past 5 GB. A diff reads the primary image +/// of each version only. +@TestActor +class MultiVersionDyldCacheImageTests: Sendable { + let caches: [FullDyldCache] + private let axes: VersionAxes + + /// Oldest first; each cache's `versionLabel` labels it on the axis. + class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } + + /// The images whose declarations make up one version. + class var configuration: CacheImagesConfiguration { .swiftUI } + + /// Set on an axis whose every label is a version number. + class var availabilityPlatform: AvailabilityPlatform? { nil } + + /// The three macOS caches most evolution suites read: 15.5 → 26.5.2 → 27.0. + static var defaultMacOSCachePaths: [DyldSharedCachePath] { + [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] + } + + /// One archived cache per macOS minor, oldest first: the directories + /// under `/Volumes/DyldSharedCaches/macOS` that hold a cache. A cache is + /// labeled with its version, or with the major release + /// `archivedMacOSVersionLabelsByCacheVersion` names for it, so every label + /// is a version number. + static var archivedMacOSCachePaths: [DyldSharedCachePath] { + archivedMacOSCacheVersions.map { cacheVersion in + let cachePath = DyldSharedCachePath.macOS(cacheVersion) + guard let versionLabel = archivedMacOSVersionLabelsByCacheVersion[cacheVersion] else { return cachePath } + return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) + } + } + + static var archivedMacOSCacheVersions: [String] { [ + "11.0.1", + "11.1", + "11.2", + "11.3", + "11.4", + "11.5", + "11.6", + "11.7", + "12.0.1", + "12.1", + "12.2", + "12.3", + "12.4", + "12.5", + "12.6", + "12.7", + "13.0", + "13.1", + "13.2", + "13.3", + "13.4", + "13.5", + "13.6", + "13.7", + "14.0", + "14.1", + "14.2", + "14.3", + "14.4", + "14.5", + "14.6", + "14.7", + "14.8", + "15.0", + "15.1", + "15.2", + "15.3", + "15.4", + "15.5", + "15.6", + "15.7", + "15.8", + "26.0", + "26.1", + "26.2", + "26.3", + "26.4", + "26.5", + "26.6", + "26.7", + "27.0", + ] } + + /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and 12.0.1, + /// so those are the directories the volume has; the axis still labels + /// them 11.0 and 12.0, the versions an SDK's availability attributes name. + static var archivedMacOSVersionLabelsByCacheVersion: [String: String] { + ["11.0.1": "11.0", "12.0.1": "12.0"] + } + + init() async throws { + let imageNames = Self.configuration.imageNames + let primaryImageName = imageNames.first?.name + var caches: [FullDyldCache] = [] + var versions: [AxisVersion] = [] + for cachePath in Self.cachePaths { + let cache = try FullDyldCache(path: cachePath) + let images = imageNames.compactMap { imageName -> AxisImage? in + guard let machOFile = cache.machOFile(named: imageName) else { return nil } + return AxisImage(imageName: imageName.name, machOFile: machOFile) + } + guard let primaryImage = images.first, primaryImage.imageName == primaryImageName else { + continue + } + caches.append(cache) + versions.append(AxisVersion(label: cachePath.versionLabel, images: images)) + } + self.caches = caches + self.axes = VersionAxes( + versions: versions, + comparesImageGroups: imageNames.count > 1, + availabilityPlatform: Self.availabilityPlatform + ) + } + + /// The axis a pipeline reading `language` runs over. Computed at + /// initialization: the class properties it derives from are isolated to + /// the test actor, the pipelines are not. + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift index a429e0c8..e9fb0aee 100644 --- a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift @@ -1,15 +1,6 @@ import Foundation -import Testing import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport @testable import MachOSwiftSection -import ObjCMetadataSource -import ObjCIndexing -import ObjCInterface -import ObjCDiffing -import FoundationToolbox -import SwiftStdlibToolbox /// The platform a version axis spells availability for — what /// `evolution --interface --emit-available --platform` passes — each @@ -97,300 +88,3 @@ struct VersionAxes: Sendable { } } } - -/// A dump over an ordered series of versions — a diff or an evolution. A -/// conforming suite supplies the axis each pipeline runs over, usually by -/// inheriting one of the axis base classes below. -protocol VersionAxisDumpTests: InspectionDumpTests { - func versionAxis(for language: MetadataLanguage) -> VersionAxis -} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension VersionAxisDumpTests { - /// One image indexed the way `swift-section objc snapshot` indexes it and - /// frozen into a labeled snapshot document, round-tripped through the - /// persisted form: what a diff or an evolution consumes is exactly what a - /// saved baseline would decode to. - func objcSnapshotDocument(of image: AxisImage, label: String) async throws -> ObjCAPISnapshotDocument { - let indexer = try await preparedObjCIndexer(of: image.machOFile) - let document = ObjCAPISnapshotDocument( - provenance: ObjCAPIProvenance( - label: label, - binaryPath: image.machOFile.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() - ) - return try ObjCAPISnapshotDocument.decode(from: document.encoded()) - } -} - -/// The images a dyld shared cache suite reads out of each cache, the -/// primary image first. More than one makes every version a group of images -/// (evolution proposal `image-group-evolution`): AppKit with the frameworks -/// Apple moved its classes into, SwiftUI with SwiftUICore. Each other image -/// joins its group where the cache has it with the metadata — -/// CollectionViewCore is in the macOS caches from 13.0 on, SwiftUICore from -/// 15.0 on. -/// -/// A suite points at one of these; to look at another framework, add one and -/// point the suite at it. -struct CacheImagesConfiguration: Sendable { - let imageNames: [MachOImageName] - - static var swiftUI: Self { Self(imageNames: [.SwiftUI]) } - static var swiftUICore: Self { Self(imageNames: [.SwiftUICore]) } - /// AppKit kept its Swift API in `libswiftAppKit.dylib` until macOS 14, - /// so its Swift axis starts at 14.0; its Objective-C metadata is in every - /// cache. - static var appKit: Self { Self(imageNames: [.AppKit]) } - static var swiftUIGroup: Self { Self(imageNames: [.SwiftUI, .SwiftUICore]) } - static var appKitGroup: Self { Self(imageNames: [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout]) } -} - -/// The same file in two simulator runtimes, and the runtime versions that -/// label them on the axis. A suite points at one of these; to look at -/// another file, add one. -struct SimulatorFilePairConfiguration: Sendable { - let oldFileName: MachOFileName - let newFileName: MachOFileName - let oldVersionLabel: String - let newVersionLabel: String - - static var swiftUICore: Self { - Self(oldFileName: .iOS_18_5_Simulator_SwiftUICore, newFileName: .iOS_26_5_Simulator_SwiftUICore, oldVersionLabel: "18.5", newVersionLabel: "26.5") - } - - static var swiftUI: Self { - Self(oldFileName: .iOS_18_5_Simulator_SwiftUI, newFileName: .iOS_26_5_Simulator_SwiftUI, oldVersionLabel: "18.5", newVersionLabel: "26.5") - } -} - -/// A shared framework of two installed Xcode applications, picked by -/// version — `/Applications/Xcode-.app` — which also labels it on -/// the axis. A suite points at one of these; to look at another framework or -/// other Xcodes, add one. -struct XcodeFrameworkPairConfiguration: Sendable { - let frameworkName: String - let oldXcodeVersion: String - let newXcodeVersion: String - - static var dvtProductsUI: Self { - Self(frameworkName: "DVTProductsUI", oldXcodeVersion: "26.3.0", newXcodeVersion: "26.4.0") - } -} - -/// Extracts the same images from an *ordered series* of dyld shared caches: -/// N versions for an evolution, two for a diff. The caches are retained -/// because the extracted `MachOFile`s resolve cross-image references through -/// them while indexing. -/// -/// One instance serves every pipeline: it keeps, per cache, every image of -/// `configuration` the cache holds, and each language's axis then keeps -/// the images carrying that language's metadata. A version whose primary -/// image is missing, or lacks the metadata, is off that axis — there is -/// nothing to index. A cache that cannot be opened still throws. -/// -/// Each cache is opened whole, the way `swift-section --dyld-shared-cache` -/// opens it, so the dumps match what the command line prints. Opened from -/// its main file alone, every read into another sub-cache file mapped that -/// file once more until MachOObjCSection 0.8.109, and an evolution over -/// every archived macOS minor ran past 5 GB. A diff reads the primary image -/// of each version only. -@TestActor -class MultiVersionDyldCacheImageTests: Sendable { - let caches: [FullDyldCache] - private let axes: VersionAxes - - /// Oldest first; each cache's `versionLabel` labels it on the axis. - class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } - - /// The images whose declarations make up one version. - class var configuration: CacheImagesConfiguration { .swiftUI } - - /// Set on an axis whose every label is a version number. - class var availabilityPlatform: AvailabilityPlatform? { nil } - - /// The three macOS caches most evolution suites read: 15.5 → 26.5.2 → 27.0. - static var defaultMacOSCachePaths: [DyldSharedCachePath] { - [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] - } - - /// One archived cache per macOS minor, oldest first: the directories - /// under `/Volumes/DyldSharedCaches/macOS` that hold a cache. A cache is - /// labeled with its version, or with the major release - /// `archivedMacOSVersionLabelsByCacheVersion` names for it, so every label - /// is a version number. - static var archivedMacOSCachePaths: [DyldSharedCachePath] { - archivedMacOSCacheVersions.map { cacheVersion in - let cachePath = DyldSharedCachePath.macOS(cacheVersion) - guard let versionLabel = archivedMacOSVersionLabelsByCacheVersion[cacheVersion] else { return cachePath } - return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) - } - } - - static var archivedMacOSCacheVersions: [String] { [ - "11.0.1", - "11.1", - "11.2", - "11.3", - "11.4", - "11.5", - "11.6", - "11.7", - "12.0.1", - "12.1", - "12.2", - "12.3", - "12.4", - "12.5", - "12.6", - "12.7", - "13.0", - "13.1", - "13.2", - "13.3", - "13.4", - "13.5", - "13.6", - "13.7", - "14.0", - "14.1", - "14.2", - "14.3", - "14.4", - "14.5", - "14.6", - "14.7", - "14.8", - "15.0", - "15.1", - "15.2", - "15.3", - "15.4", - "15.5", - "15.6", - "15.7", - "15.8", - "26.0", - "26.1", - "26.2", - "26.3", - "26.4", - "26.5", - "26.6", - "26.7", - "27.0", - ] } - - /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and 12.0.1, - /// so those are the directories the volume has; the axis still labels - /// them 11.0 and 12.0, the versions an SDK's availability attributes name. - static var archivedMacOSVersionLabelsByCacheVersion: [String: String] { - ["11.0.1": "11.0", "12.0.1": "12.0"] - } - - init() async throws { - let imageNames = Self.configuration.imageNames - let primaryImageName = imageNames.first?.name - var caches: [FullDyldCache] = [] - var versions: [AxisVersion] = [] - for cachePath in Self.cachePaths { - let cache = try FullDyldCache(path: cachePath) - let images = imageNames.compactMap { imageName -> AxisImage? in - guard let machOFile = cache.machOFile(named: imageName) else { return nil } - return AxisImage(imageName: imageName.name, machOFile: machOFile) - } - guard let primaryImage = images.first, primaryImage.imageName == primaryImageName else { - continue - } - caches.append(cache) - versions.append(AxisVersion(label: cachePath.versionLabel, images: images)) - } - self.caches = caches - self.axes = VersionAxes( - versions: versions, - comparesImageGroups: imageNames.count > 1, - availabilityPlatform: Self.availabilityPlatform - ) - } - - /// The axis a pipeline reading `language` runs over. Computed at - /// initialization: the class properties it derives from are isolated to - /// the test actor, the pipelines are not. - nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { - axes.axis(for: language) - } -} - -/// The same file from two simulator runtimes, by fixture name — the -/// two-version counterpart of `SwiftSectionTestingSupport.MachOFileTests`, -/// which loads one. `configuration` names the pair. -@TestActor -class CrossVersionMachOFileTests: Sendable { - let oldMachOFile: MachOFile - let newMachOFile: MachOFile - private let axes: VersionAxes - - class var configuration: SimulatorFilePairConfiguration { .swiftUICore } - - init() async throws { - let configuration = Self.configuration - let oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.oldFileName)) - let newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.newFileName)) - self.oldMachOFile = oldMachOFile - self.newMachOFile = newMachOFile - self.axes = VersionAxes( - versions: [ - AxisVersion(label: configuration.oldVersionLabel, images: [AxisImage(imageName: oldMachOFile.imagePath.lastPathComponent, machOFile: oldMachOFile)]), - AxisVersion(label: configuration.newVersionLabel, images: [AxisImage(imageName: newMachOFile.imagePath.lastPathComponent, machOFile: newMachOFile)]), - ], - comparesImageGroups: false, - availabilityPlatform: nil - ) - } - - nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { - axes.axis(for: language) - } -} - -/// The same shared framework from two installed Xcode applications, picked -/// by version: `/Applications/Xcode-.app`. The shared -/// `XcodeMachOFileName` fixture names a single Xcode, so this loads by path. -/// `configuration` names the framework and the two versions. -@TestActor -class CrossVersionXcodeFrameworkTests: Sendable { - let oldMachOFile: MachOFile - let newMachOFile: MachOFile - private let axes: VersionAxes - - class var configuration: XcodeFrameworkPairConfiguration { .dvtProductsUI } - - init() async throws { - let configuration = Self.configuration - let frameworkName = configuration.frameworkName - let oldMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.oldXcodeVersion) - let newMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.newXcodeVersion) - self.oldMachOFile = oldMachOFile - self.newMachOFile = newMachOFile - self.axes = VersionAxes( - versions: [ - AxisVersion(label: configuration.oldXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: oldMachOFile)]), - AxisVersion(label: configuration.newXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: newMachOFile)]), - ], - comparesImageGroups: false, - availabilityPlatform: nil - ) - } - - nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { - axes.axis(for: language) - } - - private static func loadSharedFramework(named name: String, fromXcodeVersion xcodeVersion: String) throws -> MachOFile { - let binaryPath = "/Applications/Xcode-\(xcodeVersion).app/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" - return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) - } -} diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift new file mode 100644 index 00000000..9476c092 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift @@ -0,0 +1,35 @@ +import Foundation +import MachOKit +@testable import MachOSwiftSection +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDiffing + +/// A dump over an ordered series of versions — a diff or an evolution. A +/// conforming suite supplies the axis each pipeline runs over, usually by +/// inheriting one of the axis base classes below. +protocol VersionAxisDumpTests: InspectionDumpTests { + func versionAxis(for language: MetadataLanguage) -> VersionAxis +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension VersionAxisDumpTests { + /// One image indexed the way `swift-section objc snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form: what a diff or an evolution consumes is exactly what a + /// saved baseline would decode to. + func objcSnapshotDocument(of image: AxisImage, label: String) async throws -> ObjCAPISnapshotDocument { + let indexer = try await preparedObjCIndexer(of: image.machOFile) + let document = ObjCAPISnapshotDocument( + provenance: ObjCAPIProvenance( + label: label, + binaryPath: image.machOFile.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() + ) + return try ObjCAPISnapshotDocument.decode(from: document.encoded()) + } +} From e5b5568fd201f6063caaec3f97da4f8612c22d6e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 18:19:07 +0800 Subject: [PATCH 152/175] docs: document refs --type, selector and function address references; fix the --type tests The module document, the CLI skill and the README describe --type and --type-image, selector references, function address references and the class reference a GOT slot's address makes; the benchmark's prepare.sh takes a sample already thinned. The stripped-type test names a module and a type that share no word, since a shared one is mangled as a substitution, and the Text test no longer expects a call: the type reference a metadata accessor call adds is a reference. --- .../skills/swift-section-cli/SKILL.md | 7 ++-- .../references/cross-references.md | 36 ++++++++++++++++--- .../Modules/CrossReferenceAnalysis.md | 5 +++ README.md | 6 +++- Scripts/CrossReferenceRecall/prepare.sh | 8 +++-- .../ReferencesRequestSwiftTypeTests.swift | 20 +++++------ 6 files changed, 61 insertions(+), 21 deletions(-) diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index f7c2376f..6c45bb79 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -51,8 +51,9 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, 0.25.0 `objc evolution --interface` / `--emit-available` / `--platform`, `objc interface --swift`, `interface --no-existential-any` / `dump --disable-existential-any`, `interface --expand-macros` and the `refs` and `symbolicate` subcommands, and after 0.26.0 -`--multiline-types` / `--maximum-line-width` on `dump` and `interface`, and -`objc interface --mark-sdk-swift-names`. +`--multiline-types` / `--maximum-line-width` on `dump` and `interface`, +`objc interface --mark-sdk-swift-names`, and `refs --type` / `--type-image` (with `refs` +listing selector references and function address references). When one is missing, say so rather than silently producing a weaker answer — the alternative is usually "upgrade (`brew upgrade swift-section`), or do without that annotation". @@ -68,7 +69,7 @@ missing, say so rather than silently producing a weaker answer — the alternati | How did this API evolve across N OS versions? | `evolution` | | Reformat the memory-layout comments the two above emit | `transformer` | | Objective-C headers, IMP addresses, or an Objective-C API diff (0.20.0+, formerly the separate `objc-section` executable) | `objc` — read `references/objc.md` first | -| Who calls this selector / symbol / function, who references this class, ivar or string — across a whole dyld shared cache or an app's files | `refs` — read `references/cross-references.md` first | +| Who calls this selector / symbol / function, who references this class, ivar, string or Swift type — across a whole dyld shared cache or an app's files | `refs` — read `references/cross-references.md` first | | What is this address: which function and how far into it, a stub and where it leads, a slot and what it holds | `symbolicate` — same reference | `dump` is the default subcommand: `swift-section ` is `swift-section dump `. diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md b/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md index 9f84b70b..d85a4443 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md @@ -1,7 +1,8 @@ # `refs` and `symbolicate` Two subcommands that read arm64 machine code rather than metadata: who references a selector, -a symbol, a class, a function, an instance variable or a string — and what an address is. They +a symbol, a class, a function, an instance variable, a string or a Swift type — and what an +address is. They work on a whole dyld shared cache (an archived one, another device's, or the running system's, read from its files) or on a set of standalone Mach-O files read together, without IDA and without loading anything into a process. @@ -17,6 +18,9 @@ swift-section refs --class NSWindow --uses-system-dyld-shared-cache --in-image A # What one function calls, in instruction order swift-section refs --function 0x1880a1000 --callees --uses-system-dyld-shared-cache +# Every reference to a Swift type, by its mangling or a $s…Mn / $s…Ma / $s…N symbol of it +swift-section refs --type 7SwiftUI4TextV --uses-system-dyld-shared-cache --in-image SwiftUICore + # An app's executable and its frameworks, read together; a fat file needs -a swift-section refs --symbol _objc_msgSend Foo.app/Contents/MacOS/Foo \ Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e @@ -35,13 +39,17 @@ swift-section symbolicate 0x19012345 0x1e1226590 --uses-system-dyld-shared-cache by its symbol, or, where the symbol table names none, by the export trie, the Objective-C method lists or the Swift metadata (`-[NSWindow …]`, `…Ma`); its address when nothing names it. - **kind** — `call`, `tailCall` (a branch out that does not return), or `reference` (an - address taken: a class object, a type's metadata, a string, an ivar offset). + address taken: a class object, a type's metadata, a string, an ivar offset, a function's + start, a selector handed on). - **route** — how the code got there: `direct`, `imageStub`, `stubIsland`, `cacheSharedStub` (macOS / iOS 27's selector and GOT stubs outside every image), `pointerSlot`, `addressMaterialization`, `literalLoad`, `indirect`. A reference that went through a stub is as real as a direct one; the route is what to check before trusting it. -- **target** — `send sel:` (`to self`, `to NSWindow` when the receiver is known), a function - and its image, a class, `ivar Class._name`, a string, `type …`, `indirect` (`at offset …` when the callee was loaded from memory). +- **target** — `send sel:` (`to self`, `to NSWindow` when the receiver is known), `selector + sel:` (loaded but sent nothing with: an argument of `respondsToSelector:` or + `performSelector:`, a returned selector, an action), a function and its image, a class, + `ivar Class._name`, a string, `type …`, `indirect` (`at offset …` when the callee was loaded + from memory). A one-line summary goes to stderr: how many references, in how many images, and how many images were scanned. @@ -64,12 +72,30 @@ were scanned. whole cache, name the images. - **`--class` on a class no symbol exports** (most private classes in a cache) reads every image's class list first; the first such query takes a few seconds longer. +- **`--selector` lists more than sends**: a `selector` row is the selector loaded from the + image's `__objc_selrefs` and handed on. A dyld cache's builder rewrites those loads into the + selector string's address, so inside a cache only the sends show; in an app's files both do. +- **`--function` lists the code that takes the function's address too** (`kind reference`, + route `addressMaterialization`): a block's invoke function shows the function that builds the + block, a callback the function that hands it to `dispatch_async_f`. A call-hierarchy walk can + go through blocks and closures this way; data that points at a function (a method list, a + vtable) still does not show. +- **`--type` takes a mangling, not a Swift name**: `7SwiftUI4TextV`, or a symbol of the type + (`$s7SwiftUI4TextVMn`, `_$s…Ma`, `$s…N`). In a dyld cache, a type no image exports a + descriptor of (an internal one) needs `--type-image `, the image that defines it; a set + of files is searched whole. A Swift class is also listed as the Objective-C class it is. +- **A class reference can sit at an `add`**: optimized Swift code builds the address of a + class's GOT slot and hands it to the helper that makes the class's metadata, so the reference + is where the slot's address is built, not where it is loaded. - **`--json`** prints one document whose every address is a hexadecimal string, never a number. Its field names are a contract. `--limit` keeps the first references in image and address order and sets `isTruncated`. - **Not reported, by design or not yet**: a call through a vtable, a witness table or any register says `indirect` with what the call site shows (the offset of the load, the pointer- - authentication discriminator) but no callee — never which table it was; a Swift class's stored-property offset variables are not + authentication discriminator) but no callee — never which table it was; a load from + `__objc_superrefs` is the start of a super send, reported as `send super …`, never as a + reference to the class; data references (a method list's IMP, a pointer in `__const`); a + Swift class's stored-property offset variables are not reported as ivar references; an app read together with the running system's cache is not supported — read the app's files alone, and a call into a system library stays the imported symbol it is. diff --git a/Documentations/Internal/Modules/CrossReferenceAnalysis.md b/Documentations/Internal/Modules/CrossReferenceAnalysis.md index f484071b..267fa006 100644 --- a/Documentations/Internal/Modules/CrossReferenceAnalysis.md +++ b/Documentations/Internal/Modules/CrossReferenceAnalysis.md @@ -35,6 +35,8 @@ - **ivar**:`.objectiveCInstanceVariable(className:name:)`。代码经 `adrp; ldrsw`(或 ld64 改写出的字面量 `ldrsw`、Swift 的 64 位 `ldr`)读 `__objc_ivar` 里的偏移变量;ObjC 会话把这个节作为「观察的槽」,核心在 32 位与 64 位载入时都问它。名字先取 `_OBJC_IVAR_$_<类>.<变量>` 符号,没有符号再从类的 ivar 列表反查(列表项的第一个字段指向偏移变量,第二个是名字),在 ObjC 层的附件 `ObjCInstanceVariableNames` 里,第一次碰到时读。父类是 `NSObject` 的类,clang 直接用常量偏移,不经偏移变量;Swift 类经 ObjC ivar 列表登记的偏移变量是 `__data` 里的 Swift 字段偏移全局量,不在 `__objc_ivar`,眼下不收。 - **字符串**:`.cString(String)`(`adrp; add` 或 `adr` 落进 C 字符串节——`__cstring`、`__objc_methname`、`__oslogstring` 等 `S_CSTRING_LITERALS` 节)与 `.constantString(String)`(落进 `__cfstring`,按 `{ isa, flags, characters, length }` 读,`flags & 0x10` 是 UTF-16)。核心层认,默认不记:分析器用 `recordingStringReferences: true` 打开(`recordsStringReferences`),查询里含 `.cString` / `.constantString` 键时那次扫描也会找。减法算出的地址从不当作字符串:Swift 的大字符串字面量是 `adrp; add; sub #0x20`,`add` 已经指到字符串起点,`sub` 之后的地址会落进前一个字符串中间。 - **对导入符号的数据引用**:从引用槽(GOT 等)读到一个 bind,而它绑到的符号不在分析器覆盖的镜像里——只给一个 app 时读 `_OBJC_CLASS_$_CALayer`、ivar、全局量都是这样——记成 `.importedSymbol(name:)`、`kind == .reference`。进程内槽里都是地址,不会出现。查一个类的全部引用时,调用方还要查 `_OBJC_CLASS_$_<类>` 这个导入名。 +- **selector 引用**(提案 [cross-reference-recall-gaps](../../Evolutions/draft-cross-reference-recall-gaps.md)):`.selector(String)`、`kind == .reference`——从 `__objc_selrefs` 载入、却没有用来发送的 selector:`respondsToSelector:` 与 `performSelector:` 的参数、返回的 selector、控件的 action。ObjC 会话把载入先记为待定,经典发送与 `super` 发送用 `x1` 里的它发送时消掉,离开函数时把剩下的记下(实现见 MachOObjCSection 的 `ObjCCodeReferences.md`)。归在与发送相同的 `.selector` 键下,`--selector` 和 RuntimeViewer 的 selector 查询都取得到(RuntimeViewer 暂不显示)。收集器把它按指令地址插回所在函数的引用之间,被调仍按指令顺序。dyld cache 的构建器把 selref 载入改写成取 selector 字符串的地址,所以只在独立文件里有;符号化把 selref 槽说成 `.selector`,不再说成一次发送。 +- **取函数地址**(同一提案):`adrp; add` 或 `adr` 算出本镜像某个函数的起点,记一条 `kind == .reference`、路线 `addressMaterialization`、目标 `.function(location)` 的引用,归 `.function` 键:`--function` 与调用层级因此列出建栈上 block、把回调交给 `dispatch_async_f`、返回闭包的函数。只在查询含函数键或建整表时找(`ReferenceCollector.findsFunctionAddressReferences`)。指向函数的数据(方法表的 IMP、vtable)仍不算。 - **路线**:`CodeReference.route`(`CodeReferenceRoute`,核心层定义)说明这条引用是怎么到达目标的,不说明目标是什么。`direct`(`bl` / `b` 直达)、`imageStub`(本镜像的 `__stubs`、`__auth_stubs`、`__objc_stubs`)、`stubIsland`(cache 镜像之间的 stub island,可多跳)、`cacheSharedStub`(macOS / iOS 27 整个 cache 共用的 selector 桩与 GOT 桩)、`pointerSlot`(经指针槽载入:GOT、ObjC 引用节、ivar 偏移变量)、`addressMaterialization`(`adrp; add` 或 `adr` 算地址)、`literalLoad`(字面量 `ldr`)、`indirect`(经寄存器的调用与跳转,认证与否看证据)。调用的路线由 `CallTargetResolver.resolveWithRoute(_:)` 给出,经多跳时取第一种跳板;会话认领的目标按地址落在哪定(本镜像代码直达、本镜像其他节经本镜像桩、镜像之外经 cache 共用桩)。常驻索引把路线存在每条记录 `flags` 的第 5–7 位。 ## 地址符号化 @@ -147,6 +149,8 @@ SwiftThunkAnalysis 自己的 Capstone 解码器原先也把字面量 `ldr` 当 按字符串取类(`objc_getClass("NSFoo")`,AppKit 183 处)不算类引用。 +**取到类的 GOT 槽地址也是类引用**(提案 [cross-reference-recall-gaps](../../Evolutions/draft-cross-reference-recall-gaps.md))。优化过的 Swift 代码取 ObjC 类的元数据时,先 `adrp x2; add x2, <类的 GOT 槽>`,再调合并后的访问器(`$sSo22NSAppleEventDescriptorCMaTm` 这类),由它载入槽、`objc_opt_self`、`swift_getObjCClassMetadata`;ControlCenter 26.7 有 554 处这种调用,2026-11-26 以前全部漏掉。核心层把落在引用槽上的地址当作在这条 `add` 上读槽,之后经同一寄存器的零位移载入不再重记(MachOKitExtensions 的 `MachOCodeReferences.md`)。 + **代价**(release,28 核,与只有分支跟踪的那次提交交替跑三轮取最好):全缓存整表 2.03 → 2.40 秒(引用多了 326 万条,+17%),查 `init` 的调用者 1.54 → 1.70 秒,`makeKeyAndOrderFront:` 0.29 → 0.33 秒。扫描器自己缓存类索引,查类不抢分析器的锁;地址落在本镜像 `__TEXT`、或载入的槽是本镜像的非类槽时,在任何查表之前就排除。 ### Swift 类型引用(第二批) @@ -266,6 +270,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` - `ObjectiveCClassReferenceTests`:AppKit 里三种取法都有(取本镜像类的地址、载入本镜像的类、载入别的镜像的类,`NSString` 在其中);`+[NSThread currentThread]` 发给类字面量 `NSNotificationCenter`;`_BenchmarkHost._started(test:)` 经 `objc_opt_self` 发给 `NSApplication`;分类方法与类方法的 super 类;Block 里的 super 发送按 `__objc_superrefs` 得到所在方法的类(Block 的符号不是方法名,只有槽位能给出类;分类方法那个测试里槽位与符号给出的类相同,分辨不出);Matter 里没有符号的方法,super 类与方法表一致;两个 SwiftUI 的同名类各自指向自己;类预筛(`NSWindow`、`NSUUID`、`__NSStackBlock__`、`OS_xpc_dictionary`)丢掉的镜像里抽样一处引用也没有。其中三个在去掉对应做法时变红过:经 `objc_opt_self` 不保留 `x0`、不读 `__objc_superrefs`、预筛只认 `_OBJC_CLASS_$_`。 - `SwiftTypeReferenceTests`:SwiftUICore 里访问器调用报出的类型与访问器符号全部一致(一万处以上);紧邻的 `adrp` / `add` 取出的地址上若有符号,报出的类型与符号一致;Foundation 的名字取自 `x1` 的记录、落在 `__swift5_typeref`、能解开;Foundation 与 SwiftData 里,查询保留的名字恰是解开后提到该类型的名字(40 个最常被符号引用的类型;另四个标准库类型,查询退回的正是同一套解开,所以它们只守着符号引用不指错描述符);两个 SwiftUI 的同名类型按位置分开;类型预筛(Foundation 的 `URL` 与 `JSONEncoder`、SwiftUICore 的 `Text`)丢掉的镜像里抽样一处引用也没有——按导入符号预筛时三者都漏;Foundation 与 AppKit 的每一个类型,按名字先筛再比 key 的查找与比每个类型的 key 结果相同(`typeLookupsCompareSameNamedTypesOnly`),按名字查导出表与读整个导出表判断导出与否相同(`exportLookupsAgreeWithTheWholeTrie`);查导入类型时不从不透明类型的描述符读名字,子进程里拿一页末尾的假描述符核对(`importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs`,修复前子进程 SIGBUS)。 - `FallbackNamingTests`:导出表给的名字落在导出的地址上(SiriAppIntents);AppKit 里方法表给的名字与 `-[C sel]` 符号一致(去掉分类名后 99.9% 以上);SwiftUICore 里从元数据重建的名字与真实的 `…Ma`、`…Mr`、方法符号一致(99% 以上);Matter 的方法在没有符号时由方法表起名;SiriAppIntents 几乎每个类型的访问器都有名字,重建的名字 demangle 出来是元数据访问器。 +- 召回补漏(提案 [cross-reference-recall-gaps](../../Evolutions/draft-cross-reference-recall-gaps.md)):`SelectorReferenceTests`(经典发送的 ObjC 库里,`copy`、`name` 与 `respondsToSelector:` 的参数是 selector 引用、发送不重复、常驻索引存得下、被调按指令顺序、selref 槽符号化成 selector)、`SlotAddressReferenceTests`(`-O` 编的 Swift 库里,`Timer.self` 在 `add x2` 上引用 `_OBJC_CLASS_$_NSTimer`)、`FunctionAddressReferenceTests`(`dispatch_async_f` 的回调与栈上 block 的 invoke 函数被取地址处引用、整表也有);SwiftSectionKit 的 `ReferencesRequestSwiftTypeTests`(`--type` 的三种符号写法与 mangling 结果相同、cache 里没导出的类型要给镜像、独立文件里去掉符号的类型逐个文件找)。召回的数字与测量办法在愿景《[不依赖 IDA 的逆向](../../Visions/ReverseEngineeringWithoutIDA.md)》「我们选的方向」第 1 条,脚本在 `Scripts/CrossReferenceRecall/`。 - `StandaloneImageTests`:SymbolTestsCore fixture 经自己的桩调用 libswiftCore,没有一条停在只有名字的导入上;它的路径是加载路径而不是 `@rpath/…`,安装名也能查回它;测试包(`MH_BUNDLE`,没有安装名)的路径等于 `dladdr` 给的;测试包算作主程序的依赖方。 - `RegisterFileTests`:48 条汇编器编出的指令,每条写的寄存器都被作废,Capstone 的寄存器访问表独立核对这张表;普通读写只作废目标寄存器。 - `RenamedReexportTests`:AppKit 按 `_strlen`、`_CGSMainConnectionID` 调用 `__platform_strlen`、`_SLSMainConnectionID`,CharacterPicker 按 `NSEmojiImageAsset` 引用 CoreText 的类,三者的预筛都留住了它们;别名经伞形框架的那一种(`_xkMDConfigErase`)。 diff --git a/README.md b/README.md index 463dfca5..25a4785c 100644 --- a/README.md +++ b/README.md @@ -753,7 +753,7 @@ superclass chain, why pure-Swift classes' ivar records do not line up, and the r #### refs - Find Cross References -Who sends a selector, calls a function, or references a class, an instance variable or a string — across every image of a dyld shared cache (an archived one, another device's, or the running system's, read from its files) or across a set of Mach-O files read together, such as an app's executable and its frameworks. No disassembler and no process: the code is read from the files, through image stubs, the stub islands between a cache's images, and the selector and GOT stubs macOS 27 shares across a cache. Only the images that can reference the subject are scanned — the ones whose selector references, imports or linkage allow it. +Who sends a selector, calls a function or takes its address, or references a class, an instance variable, a string or a Swift type — across every image of a dyld shared cache (an archived one, another device's, or the running system's, read from its files) or across a set of Mach-O files read together, such as an app's executable and its frameworks. No disassembler and no process: the code is read from the files, through image stubs, the stub islands between a cache's images, and the selector and GOT stubs macOS 27 shares across a cache. Only the images that can reference the subject are scanned — the ones whose selector references, imports or linkage allow it. ```bash # Every send of a selector across a whole cache @@ -770,6 +770,10 @@ swift-section refs --symbol _objc_autoreleasePoolPush --uses-system-dyld-shared- # What one function references, in instruction order swift-section refs --function 0x18a403858 --callees --uses-system-dyld-shared-cache +# Every reference to a Swift type, by its mangling or a $s…Mn / $s…Ma / $s…N symbol of it; +# --type-image names the image of a type no image of a cache exports +swift-section refs --type 7SwiftUI4TextV --uses-system-dyld-shared-cache --in-image SwiftUICore + # An app's files; a fat file needs --architecture, as everywhere swift-section refs --string NSWindowDidBecomeKeyNotification \ Foo.app/Contents/MacOS/Foo Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e diff --git a/Scripts/CrossReferenceRecall/prepare.sh b/Scripts/CrossReferenceRecall/prepare.sh index f0cccc23..5dd156c2 100644 --- a/Scripts/CrossReferenceRecall/prepare.sh +++ b/Scripts/CrossReferenceRecall/prepare.sh @@ -9,8 +9,12 @@ CONTROL_CENTER=${CROSS_REFERENCE_RECALL_CONTROL_CENTER:-/Volumes/RE/ControlCente mkdir -p $WORK cd $WORK -lipo -thin arm64e $FINDER -output Finder -lipo -thin arm64e $CONTROL_CENTER -output ControlCenter +# A sample already thinned to arm64e is taken as it is. +thin() { + if lipo -info $1 | grep -q '^Non-fat'; then cp $1 $2; else lipo -thin arm64e $1 -output $2; fi +} +thin $FINDER Finder +thin $CONTROL_CENTER ControlCenter # 1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0 and 5782ED6B-471B-3CAC-9258-93734B6009C3. dwarfdump --uuid Finder ControlCenter diff --git a/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift index 6e847fc6..50f891b3 100644 --- a/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift +++ b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift @@ -25,8 +25,6 @@ struct ReferencesRequestSwiftTypeTests { let byMangling = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("7SwiftUI4TextV", imageName: nil), imageNames: ["SwiftUICore"]).run(output: RecordingOutput()) #expect(!byMangling.rows.isEmpty) #expect(byMangling.rows.allSatisfy { Self.isTypeReference($0.reference.target) }) - // Calls to the metadata accessor, and its address taken. - #expect(byMangling.rows.contains { $0.reference.kind == .call }) for spelling in ["$s7SwiftUI4TextVMn", "_$s7SwiftUI4TextVMa", "$s7SwiftUI4TextVN"] { let bySymbol = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType(spelling, imageName: nil), imageNames: ["SwiftUICore"]).run(output: RecordingOutput()) #expect(bySymbol.rows == byMangling.rows, "\(spelling)") @@ -44,28 +42,30 @@ struct ReferencesRequestSwiftTypeTests { } /// A type no symbol names — its descriptor symbol stripped — is looked - /// for in every file of a set of files, which are few. + /// for in every file of a set of files, which are few. The module and + /// the type share no word: a shared one would be spelled as a + /// substitution in the mangling. @Test func typeSubjectLooksForAnUnexportedTypeInEveryStandaloneFile() async throws { let libraryURL = try FixtureCompiler.shared.dynamicLibrary( - named: "HiddenTypeReferences", + named: "StrippedTypes", language: .swift, - sourceFiles: [FixtureSourceFile(name: "HiddenTypeReferences.swift", contents: """ - struct Hidden { + sourceFiles: [FixtureSourceFile(name: "StrippedTypes.swift", contents: """ + struct Concealed { var value: Int } - public func makeHidden() -> Any { - Hidden(value: 1) + public func makeConcealed() -> Any { + Concealed(value: 1) } """)], arguments: ["-swift-version", "5", "-Xlinker", "-x"] ) let input = CrossReferenceInput.files(paths: [libraryURL.path], architecture: nil) - let byMangling = try await ReferencesRequest(input: input, subject: .swiftType("20HiddenTypeReferences6HiddenV", imageName: nil)).run(output: RecordingOutput()) + let byMangling = try await ReferencesRequest(input: input, subject: .swiftType("13StrippedTypes9ConcealedV", imageName: nil)).run(output: RecordingOutput()) #expect(!byMangling.rows.isEmpty) #expect(byMangling.rows.allSatisfy { Self.isTypeReference($0.reference.target) }) // A symbol of the type names it too, its prefix and suffix taken off. - for spelling in ["$s20HiddenTypeReferences6HiddenVMn", "_$s20HiddenTypeReferences6HiddenVMa", "$s20HiddenTypeReferences6HiddenVN"] { + for spelling in ["$s13StrippedTypes9ConcealedVMn", "_$s13StrippedTypes9ConcealedVMa", "$s13StrippedTypes9ConcealedVN"] { let bySymbol = try await ReferencesRequest(input: input, subject: .swiftType(spelling, imageName: nil)).run(output: RecordingOutput()) #expect(bySymbol.rows == byMangling.rows, "\(spelling)") } From aed3353d61fe2127ce7ba85e9989cffc455bfe69 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 26 Nov 2026 18:29:42 +0800 Subject: [PATCH 153/175] docs: land the ObjC ivar type recovery proposal as 0112 --- ...very.html => 0112-objc-ivar-type-recovery.html} | 14 +++++++------- ...recovery.md => 0112-objc-ivar-type-recovery.md} | 9 ++++++--- Documentations/Evolutions/README.md | 2 +- Documentations/Internal/ProjectEvolutionLog.md | 13 +++++++++++++ Documentations/README.md | 1 + 5 files changed, 28 insertions(+), 11 deletions(-) rename Documentations/Evolutions/{draft-objc-ivar-type-recovery.html => 0112-objc-ivar-type-recovery.html} (96%) rename Documentations/Evolutions/{draft-objc-ivar-type-recovery.md => 0112-objc-ivar-type-recovery.md} (94%) diff --git a/Documentations/Evolutions/draft-objc-ivar-type-recovery.html b/Documentations/Evolutions/0112-objc-ivar-type-recovery.html similarity index 96% rename from Documentations/Evolutions/draft-objc-ivar-type-recovery.html rename to Documentations/Evolutions/0112-objc-ivar-type-recovery.html index 87ce1fd9..847213e7 100644 --- a/Documentations/Evolutions/draft-objc-ivar-type-recovery.html +++ b/Documentations/Evolutions/0112-objc-ivar-type-recovery.html @@ -4,7 +4,7 @@ -Draft - @objc @implementation 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型 +0112 - @objc @implementation 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型