From 03c2c3ed4fb61200cf4e7ed1689f9eadffab8ae6 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 00:09:51 +0900 Subject: [PATCH 01/18] e2e graph/834 runs in a home of its own: a replay holds only while nothing else writes the home --- tests/e2e/workspace/graph.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/e2e/workspace/graph.cpp b/tests/e2e/workspace/graph.cpp index 93c644a6b..a01753039 100644 --- a/tests/e2e/workspace/graph.cpp +++ b/tests/e2e/workspace/graph.cpp @@ -229,7 +229,10 @@ E2E graph{"graph", s::home_fixture, [] { "834 a workspace plans once and replays in one check"_test[s::unix_shell][s::python3] = [] { // P1 P2: --workspace and -p resolve the toolchain once; P3: an unchanged build replays - // without planning, in under a second, for --workspace, -p and from inside a member. + // without planning, in under a second, for --workspace, -p and from inside a member. A + // replay holds only while nothing else writes the home: in the shared one, an install beside + // the case rewrote the runtime environment's description and the replay planned (CI, 2026-12-06). + s::own_home(); s::project ws({{"mcpp.toml", "[workspace]\nmembers = [\"lib1\", \"lib2\", \"lib3\", \"lib4\", \"lib5\", \"app\"]\n"}, {"lib1/mcpp.toml", "[package]\nname = \"lib1\"\nversion = \"0.1.0\"\n\n[targets.lib1]\nkind = \"lib\"\n"}, {"lib1/src/lib1.cppm", "export module lib1;\nexport int v1() { return 1; }\n"}, From 91049e94807a67772a7de35cfda58b3490108ddc Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:29:04 +0900 Subject: [PATCH 02/18] Design: the uses of a path, one table of roots, and tools named by their address --- ...th-uses-roots-and-tool-addresses-design.md | 383 ++++++++++++++++++ .github/tools/path-identity.baseline | 30 -- 2 files changed, 383 insertions(+), 30 deletions(-) create mode 100644 .agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md delete mode 100644 .github/tools/path-identity.baseline diff --git a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md new file mode 100644 index 000000000..05791effc --- /dev/null +++ b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md @@ -0,0 +1,383 @@ +--- +subject: design +status: active +--- + +# 路径的四种用途、根目录表与工具的地址:受限视图下的一致性 + +**日期:** 2026-12-07 · **版本:** v2(v1 的五项决定按建议确定,见 §9;实施任务见 §11) · +**基线:** mcpp main `7c0b9f06`(2026.12.6.2 之后;附录 A 的行号以 `a2f99fba` 为准,二者在所列文件上相同)、 +mcpplibs.os 0.4.10、openkal-windows 0.23.3、LLVM 22.1.8 的驱动源码 · +**相关规范:** SPEC-006(工具链管理)、SPEC-007(构建插件)、SPEC-010(home)、 +docs/05、docs/07、docs/20、docs/25 · +**相关 issue:** mcpp#1024、#1032、#1048 至 #1053 · +**前序:** [2026-11-27 陈述的闭包、单一读者与六项功能](2026-11-27-stated-closure-single-reader-and-feature-designs.md) §4.6(路径的拼写:home 保留给定的拼写)。 + +## 1. 范围 + +本文回答七个问题。它们属于同一件事:一个路径在 mcpp 中承担的用途不止一种,而一个值同时承担几种用途时, +在只授予部分目录的环境中必有一种用途失败。 + +| 编号 | 问题 | 所在 | +|---|---|---| +| 1 | 路径的用途有几种,每种由什么机制回答 | §3、§4.1 | +| 2 | 其余 65 处解析物理路径的调用如何归类与迁移 | §4.2、附录 A | +| 3 | 编译器运行状态与编译器注册使用哪个拼写 | §4.3 | +| 4 | 链接器如何交给驱动,驱动如何看待自身的位置 | §4.4 | +| 5 | 根目录在四处各自枚举,如何收敛为一张表 | §4.5 | +| 6 | `--verbose` 如何到达每一次构建 | §4.6 | +| 7 | 规则与文档如何各只写在一处 | §8 | + +不在本文内:MSVC ABI 上不带 CRT 的程序(§4.7,不在目标侧模型内);openkal-windows 在很长的授权路径下建立 +IPC 端点(§4.8,属于 openkal)。本设计不改动 openkal,也不改动 mcpplibs.os。 + +## 2. 现状(实测与源码) + +### 2.1 规则已有,机制未收敛 + +自 2026.11.27.1 起,docs/25 陈述:home 以给定的拼写打开并交给程序,物理路径只判断两个路径是否为一个对象, +不能判定时退回拼写并报告降级;由路径构成的键也用拼写。`modules/libs/src/path_identity.cppm` 提供 +`given`、`identity`、`same` 三个函数,`.github/tools/check_path_identity.sh` 以只降不升的基线约束其余调用。 + +实测:基线仍为 30 个文件、65 处 `canonical`/`weakly_canonical`;使用该模块的文件为 5 个。`identity()` 的返回类型 +为 `std::optional`,即身份本身是一个可以打开的路径,类型不阻止它流向文件操作。#1024、 +#1032 之后同类缺陷在编译器运行子系统再次出现(§2.2),原因在此。 + +### 2.2 编译器运行子系统的两处 + +- `src/build/schedule/detach_codegen.cppm:841`:`at.work = weakly_canonical(...)`,`owner.lock` 与运行状态在其下创建; + 同文件 `:835` 以物理输出目录的哈希命名运行目录,与 docs/25 的“键用拼写”不一致。 +- `src/build/schedule/compiler_transaction.cppm:203`:注册监听目录取 `weakly_canonical(os::dirs::runtime())`,并写入 + 传输记录,编译器进程据此连接。 + +在以 `Z:` 授予工作目录、未授予其物理祖先的 AppContainer 中,Windows 把别名解析为物理卷路径,mcpplibs.os 的定位 +拒绝它(`beneath no directory this program was given`)。 + +### 2.3 mcpplibs.os 已经提供所需的原语 + +mcpplibs.os 0.4.10 的 `mcpplibs.os.fs` 导出: + +- 词法的 `generic`、`native`、`is_absolute`、`same`(按主机规则比较拼写,Windows 上不分大小写)、`within` + (按路径组成部分判断包含); +- `struct identity { volume, index }` 与 `identity_of(node)`:“两个名字是同一节点,当且仅当其标识相等”。它经 openkal 的 + `field::identity` 取得;openkal-windows 以卷序列号与文件索引实现(其 `src/fs.cpp:420-458`),POSIX 为设备号与 inode; +- `canonical(name)`:询问文件系统,跟随链接并展开 8.3 短名。 + +mcpp 未使用 `identity_of`、`same`、`within` 中的任何一个。对象标识经句柄取得,不读祖先目录,因此在受限视图中可用; +它是两个整数,不是路径,不可能被用于打开文件。 + +### 2.4 驱动的事实(LLVM 22.1.8) + +- MSVC 链接(`clang/lib/Driver/ToolChains/MSVC.cpp:282-288、421`)只从 `-fuse-ld` 取链接器(`lld` 映射为 `lld-link`), + 以 `GetProgramPath` 查找;`--ld-path` 只由通用的 `ToolChain::GetLinkerPath` 读取(`ToolChain.cpp:1103-1150`),MSVC 路线 + 不调用它,驱动报告该参数未使用。 +- `Driver::GetProgramPath`(`Driver.cpp:6604-6644`)依次查找 `-B` 前缀、工具链的程序目录(驱动的安装目录)、`PATH`; + 每一处先试 `<三元组>-<名字>`,再试 `<名字>`(`generatePrefixedToolNames`,`:6588`)。`findProgramByName` 对含路径分隔符 + 的名字原样返回且不检查存在(`llvm/lib/Support/Windows/Program.inc:41`)。因此单独的 `-fuse-ld=<绝对路径>` 在 MSVC + 路线上得到 `<三元组>-<绝对路径>`,链接失败。 +- 驱动的安装目录由 `getMainExecutable` 经 `real_path` 求得(`llvm/lib/Support/Windows/Path.inc:207-235`),别名、`subst` + 盘与符号链接都被解析为物理路径;`-no-canonical-prefixes` 使驱动以启动它的路径为准(`clang/tools/driver/driver.cpp:63-76`)。 +- 先例:Bazel 的 `tools/cpp/unix_cc_configure.bzl:293-305` 为其符号链接沙箱传 `-fno-canonical-system-headers`,对 clang + 传 `-no-canonical-prefixes`。 + +### 2.5 链接器的选择分在三处 + +- `tools.ld`:`src/build/flags.cppm:2866-2869` 与 `src/toolchain/hostflags.cppm:669` 各写一次 `--ld-path=`; +- 树自带的 lld:`Toolchain::treeLinkWords`(`modules/toolchain-model/src/model.cppm:304`、 + `src/build/prepare/local_toolchain.cpp:432-473`)给出 `-fuse-ld=lld`,由驱动搜索; +- freestanding:`src/freestanding/linkline.cppm:254` 的 `resolve_lld` 以绝对路径指名 lld。 + +### 2.6 根目录在四处各自枚举 + +| 所在 | 枚举的根 | 用途 | +|---|---|---| +| `src/ui.cppm:408-420、1650-1680` | 项目、home、用户目录 | 输出中缩短路径(`x/y`、`@mcpp/…`、`~/…`) | +| `src/build/plan.cppm:1044、2244` `trim_map` | 包、工具链、输出目录、store | `-ffile-prefix-map`(`src/build/flags.cppm:1392-1414`) | +| `src/build/prepare/plan.cpp:1277-1290` | 输出目录、bin、编译数据库、契约、引擎 | 构建程序的 `${mcpp.*}` 占位符(SPEC-007) | +| `src/build/hermetic.cppm:154-170` | store、上游 store、基座、配对 sysroot、图的根 | 链接的自足性检查 | + +### 2.7 构建的详细输出 + +`BuildOptions::verbose` 缺省为假(`src/build/backend.cppm:14`),由驱动构建的各调用点各自决定。13 处中,`build` +(`src/build/execute.cppm:2354`)、`configure` 与 `pack` 的 5 处(`src/pack/pipeline.cppm`、`src/pack/library_pipeline.cppm`) +取命令的详细程度,两处构建程序的构建由 `MCPP_TOOL_BUILD_VERBOSE` 决定,`test` 的 4 处不设置。实测(`7c0b9f06` 之前): +同一工程冷构建,`mcpp build --verbose` 打印 6 行 ninja 命令,`mcpp pack --verbose` 打印 0 行;`pack` 已补上,`test` 仍缺。 +`tests/e2e/pack/verbosity.cpp` 以“冷构建、源文件名与编译开关同在一行”为判据断言 `pack` 的这一行为。 + +## 3. 原则 + +**P1 路径有四种用途,每种只有一个机制。** + +| 用途 | 例 | 机制 | +|---|---|---| +| 地址:打开、交给程序、写入记录 | 锁文件、监听目录、链接器、build.ninja | 给定的拼写:绝对化与词法规范化(`given`) | +| 保存的键:缓存条目、记录中的键 | 计划的工作目录、缓存条目的使用者 | 给定拼写的文本(`key`,docs/25 已定) | +| 对象:是否同一、是否在某目录下、内存中的路径集合与映射 | home 借用上游、成员匹配、遍历去环、编译器运行的槽 | 一对路径的问题:`same`、`within`、`beneath`;已存在节点的集合:对象标识(`object`);内存中以路径为键:跟随链接的拼写(`resolved`) | +| 有意跟随链接:要的是链接指向的文件 | soname 链、加载器、被链接的锁文件 | 路径上每个符号链接与目录联接都替换为其目标,卷的拼写保留(`resolved`) | + +物理路径字符串不属于任何一种用途;它只出现在诊断文本中(`describe`)。 + +`resolved` 只读链接本身(`read_link` 经给定的路线),从不经物理路径打开祖先,因此在受限视图中可用;它与物理路径的差别 +只在卷一级的别名(`subst` 盘、映射盘、AppContainer 的盘符),后者由对象标识回答。名字是否在某目录下(不问对象)是 +纯词法的问题,由 mcpplibs.os 的 `fs::within` 回答;`path_identity::within` 回答的是对象:目录内一个指向外部的链接不在 +目录内。 + +**P2 身份不是路径。** 同一性由 mcpplibs.os 的对象标识回答。持久键不用对象标识:inode 会被复用,部分文件系统的 +设备号在重启后改变。 + +**P3 正确性不依赖同一性。** 互斥由对象内部的锁文件保证,经地址打开,同一对象的任何拼写打开的是同一文件。同一性 +只用于识别共享(缓存命中、借用、去重);不能判定时按拼写决定,并经 `diag::degraded()` 报告,代价至多是多一个条目。 + +**P4 派生只做词法。** 根只有三个来源:给定的(参数、环境变量、清单)、操作系统报告的(当前目录、临时目录、运行时 +目录,按报告原样)、mcpp 自己写的记录(只含地址)。一切派生路径为“根 / 相对部分”的词法结果。 + +**P5 工具由地址指名,驱动以给定的拼写看待自身。** 这是“hermetic 缺省”的延伸:mcpp 已以 `--no-default-config`、 +`-nostdlibinc`、显式 sysroot 封闭搜索,链接器是剩下的一处。 + +**P6 每层负责自己的部分。** + +| 层 | 负责 | 不负责 | +|---|---|---| +| 外层环境(AppContainer、容器、Nix、CI) | 授予哪些根、以何拼写、权限、临时目录与 profile | — | +| openkal、mcpplibs.os | 地址的到达(按授权定位)、对象标识、按授权启动进程、以“目录 + 名字”寻址的 IPC | 路径的用途 | +| mcpp | 四种用途的规则、根目录表、记录只含地址、以地址指名工具、降级可见 | 创建沙箱、识别 AppContainer、扩大授权、特判盘符 | +| 驱动与工具 | 自身的内部行为 | mcpp 只以有文档的参数约束它,不修补、不包装 | +| 工程 | 以模型内的声明表达需求 | 以原始参数绕过模型(§4.7) | + +## 4. 设计 + +### 4.1 路径模块 + +`mcpp.libs.path_identity` 保留为一个薄层,只导入 `std` 与 `mcpplibs.os`,导出: + +```cpp +std::filesystem::path given(const std::filesystem::path& p); // 地址 +std::string key(const std::filesystem::path& p); // 保存的键:given 的 UTF-8 文本 +std::filesystem::path resolved(const std::filesystem::path& p); // 链接跟随,卷的拼写保留 +bool same(const std::filesystem::path& a, const std::filesystem::path& b); +std::optional beneath(const std::filesystem::path& p, const std::filesystem::path& dir); +bool within(const std::filesystem::path& p, const std::filesystem::path& dir); +struct Object { std::uint64_t volume, index; }; // 已存在节点的标识,可作集合的键 +std::optional object(const std::filesystem::path& p); +std::string describe(const std::filesystem::path& p); // 物理拼写,只用于诊断 +void on_undecided(void (*report)(std::string_view question)); +``` + +- `resolved`:自根逐个组成部分读链接(mcpplibs.os `read_link`,含 Windows 的目录联接),绝对目标从其根重来,相对目标 + 接在链接所在目录之后;不存在的部分原样附加;链接环在 40 跳截断,回答地址本身。 +- `same`:给定拼写相同即真;跟随链接后拼写相同即真;否则比较两侧最深的存在部分的对象标识,且其后的部分拼写相同。 +- `beneath`/`within`:跟随链接后按组成部分包含即真;否则取 `dir` 的对象标识,沿 `resolved(p)` 的祖先逐级比较,相等即真。 +- 取不到标识时按拼写决定,并经 `on_undecided` 报告;该处理由 mcpp 在命令入口安装一次,报告为 + `diag::degraded("path", …)`(本包不导入 mcpp)。调用点不各自处理降级。 +- 原 `identity()` 删去:调用者需要的是对象的问题,不是一个物理路径。 + +`std::filesystem::canonical`、`weakly_canonical` 与 `os::fs::canonical` 只出现在本模块的 `describe`; +`check_path_identity.sh` 由“只降不升”改为“为零”,基线文件删去。 + +`std::filesystem::canonical`、`weakly_canonical` 与 `os::fs::canonical` 只允许出现在诊断文本的生成处,经本模块的 +一个 `describe()` 取得;`check_path_identity.sh` 由“只降不升”改为“为零”,基线文件删去。 + +### 4.2 迁移 + +65 处按 P1 归类迁移(附录 A 为最终归类),另有三处经原 `identity()` 的调用者(cps 的使用说明、配置的借用判断、包 +说明的读取)一并迁移。`src/project.cppm:433` 同时去掉 `.string()` 的收窄(AGENTS.md §4)。 + +### 4.3 编译器运行状态与注册 + +- 工作目录是地址:`given(...)`,锁文件与运行状态在其下创建。 +- 输出目录是对象:编译器按其工作目录给出输出,POSIX 报告的工作目录跟随了链接,而 mcpp 按构建目录给出;二者须相等, + 因此运行目录的键与输出标识(`compiler_transaction.cppm:416`)都用 `resolved`。POSIX 上它与原物理路径相同,现有运行 + 目录的键不变;Windows 上它保留卷的拼写,在 AppContainer 中可达。卷别名不同的两种拼写得到两组运行状态,其构建仍由 + 输出目录内的构建目录锁互斥(P3),这与 docs/25 的“两种拼写两个条目”同属一类代价。 +- 注册目录是地址:`Witnesses::start(generation, runtime)` 由调用者传入 `os::dirs::runtime()`,监听、传输记录、连接与 + 停止的唤醒都用 `given(runtime)`。 + +### 4.4 链接器与驱动 + +**一项工具链事实。** `Toolchain::linker { path, flavour, source }`,在解析工具链时确定一次: + +1. 声明的 `tools.ld`; +2. 树或载荷中与目标格式对应的 lld(ELF `ld.lld`,PE `lld-link`,Mach-O `ld64.lld`,wasm `wasm-ld`;格式取自目标行, + 与 `LinkShape` 同源); +3. 否则为空,由驱动的缺省决定,不加任何链接器词。 + +`path` 是给定的拼写(P4)。在规划时检查其存在;缺失沿用现有对 `tools` 程序缺失的拒绝。`mcpp why toolchain` 列出 +它与来源。 + +**一个生成函数。** 按路线给出词,项目的 C 与 C++ 链接、构建程序的链接、freestanding 链接三处共用, +`resolve_lld` 并入: + +| 路线 | 词 | 依据 | +|---|---|---| +| 通用(ELF、Mach-O、wasm) | `-fuse-ld=lld --ld-path=`(lld 形态);其他链接器 `--ld-path=` | `GetLinkerPath` 读取 `--ld-path` | +| MSVC ABI | `-B -fuse-ld=` | `GetProgramPath` 先查 `-B`,以不含目录的名字查找,避开三元组前缀 | + +MSVC 路线上 `-B` 目录中的查找经 LLVM 的 `can_execute`,它在 Windows 上依次试 `<名字>` 与 `<名字>.exe` +(`llvm/lib/Support/Windows/Path.inc:746-749`)。因此该路线上的链接器须为可执行文件(`.exe`),主名即去掉 `.exe` 的 +文件名;`tools.ld` 指向其他形式的文件(如 `.cmd`)时在规划时拒绝,与 gcc 树声明 `ld` 时的拒绝同理:驱动按名字在目录中 +选择程序,以别的形式无法选中。 + +MSVC 路线的另两种写法不采用:单独的 `-fuse-ld=<绝对路径>` 得到 `<三元组>-<绝对路径>`(§2.4);`-B "" -fuse-ld=<绝对路径>` +在 22.1.8 上成立,但空前缀同时进入驱动的文件查找(相对当前目录),且依赖一个内部细节(决定 D1)。 + +**驱动看待自身的位置。** mcpp 启动的每个 clang 驱动(编译、链接、探测与查询,如 `-print-resource-dir`)都传 +`-no-canonical-prefixes`,驱动的安装目录、资源目录与程序目录都以给定的拼写派生;`hermetic.cppm:165` 为“驱动经物理 +路径报告资源目录”所加的上游 store 例外随之删去(决定 D2)。探测结果因此可能改变,按工具链身份记录的探测在升级后 +重做一次。 + +### 4.5 根目录表 + +一个模块 `mcpp.build.roots`:一张在规划时建立的表,每项为 `{ kind, name, path }`,`path` 为给定的拼写。 + +| kind | 来源 | +|---|---| +| `project`、`workspace` | 工程与工作区的根 | +| `package` | 图中每个包的根 | +| `home`、`user` | `MCPP_HOME`、用户目录 | +| `store` | 每个 xpkgs store(含上游) | +| `toolchain`、`base` | 工具链的根、基座或 sysroot | +| `output`、`runtime` | 输出目录、运行时目录 | + +表只回答两个问题:一个路径落在哪个根下(最具体者优先,经 `within`),一个根的给定拼写是什么。§2.6 的四处改为读表: + +- 输出中的路径缩短:规则不变(项目内相对、`@mcpp/…`、`~/…`),根取自表;无规划的命令(如 `self env`)建立只含 + `home`、`user` 的表。 +- `trim_map`:以表中属于该包闭包的根生成 `-ffile-prefix-map`。 +- 构建程序占位符:名字与取值取自表,SPEC-007 的定义不变。 +- 自足性检查的允许集合:表中 `store`、`toolchain`、`base` 与图的根;上游 store 由编译器路径的 `resolved` 得到(D2 之后删去)。 + +记录的格式与缓存键不变:键用拼写(docs/25),本设计不引入可迁移的键。 + +### 4.6 构建的详细输出 + +`BuildOptions::verbose` 改为 `std::optional`;未设置时由 ninja 后端取命令的详细程度(`mcpp::log::is_verbose()`)。 +`build`、`configure`、`pack`、`test` 与其余驱动构建的调用点不写它,`pack` 的 5 处现有的设置删去;只有构建程序的内层 +构建显式设置(`MCPP_TOOL_BUILD_VERBOSE`),在这两处写明理由。`tests/e2e/pack/verbosity.cpp` 的判据移入测试工具集 +(“输出中有一行同时含该源文件名与编译开关”),供 `pack` 与 `test` 的用例共用。一条文档:`--verbose` 作用于命令运行的 +每一次构建。 + +### 4.7 不在本设计内:MSVC ABI 上不带 CRT 的程序 + +每个 MSVC ABI 构建声明其 CRT 模型(#718,`modules/toolchain-model/src/dialect.cppm:185-206`),自由书写的 CRT 词作为 +第二次声明检查。“没有 C 库”在目标侧由 `sysroot = ""` 陈述(零 libc 档位),而 MSVC 行上 `sysroot` 键指 MSVC 工具集 +(`src/build/prepare/target_side.cpp:295-305`),该档位不存在。`[build] ldflags` 中原样的 `-nostdlib` 不改变模型, +据此加 `-fms-omit-default-lib` 是对原始参数的推断,不采用;mcpp 给出一条提示,说明 CRT 模型的默认库指令仍写入 +目标文件(决定 D4)。 + +### 4.8 下层的部分 + +AppContainer 中长授权路径下 IPC 端点建立失败(`invalid argument`)属于 openkal-windows 的端点实现;mcpplibs.os 已以 +“目录 + 名字”调用它。本设计不改动 openkal;§4.3 之后,该错误报告的是给定的拼写。 + +## 5. 各仓库的改动与次序 + +只改 mcpp,一个带版本号的 PR。mcpplibs.os 0.4.10 已含 `identity_of`、`same`、`within`,openkal 已实现标识字段,二者不改。 + +```text +路径模块(§4.1)── 65 处迁移(§4.2,附录 A)── CI 规则为零 + └── 编译器运行状态与注册(§4.3) + └── 根目录表(§4.5)── 路径缩短 / trim_map / 占位符 / 自足性检查 +Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no-canonical-prefixes +详细输出(§4.6) +规范与文档(§8)、CHANGELOG +``` + +## 6. 兼容性与无感升级 + +- 无别名的路径上,地址与键与此前相同;有别名时,编译器运行目录换键一次(§4.3),`path` 依赖与成员的比较结果不变, + 取不到标识时按拼写并报告降级。 +- 链接器词改变,链接命令改变:每个使用 clang 的工程重新链接一次。 +- `-no-canonical-prefixes` 改变编译命令:使用 clang 的工程重新编译一次(决定 D2 的代价)。 +- 记录格式、缓存键、构建程序占位符的名字与值、输出中的路径缩短形式不变。 +- `--verbose` 下 `pack`、`test` 多出 ninja 命令行;缺省输出不变。 + +## 7. 测试 + +- 单元(`modules/libs/tests/`):`given`、`key`、`resolved`、`same`、`beneath`/`within`、`describe` 在符号链接、相对 + 链接、链接环、不存在的尾部、目录内指向外部的链接下的回答;`tests/unit/` 中注册经链接给出的运行时目录、输出经链接的同一。 +- 测试工具集新增两项,供各用例复用:以别名运行(Linux 上工程、home、工具链与临时目录经符号链接给出;Windows 上用 + CI 已有的 `subst` 盘),与一个断言“mcpp 写出的产物中不出现物理前缀”(build.ninja、编译数据库、链接命令、运行目录、 + 传输记录、各记录)。 +- e2e:别名下的 `build`、`test`、`pack`;编译器运行目录与传输记录的拼写;`path` 依赖与成员在两种拼写下的同一。 +- 链接器:Linux 上由符号链接组成、物理目录中有另一 lld 的树,断言用的是树中的;`tools.ld` 为追踪程序(非 lld 的名字) + 时在 Windows clang 任务的 MSVC 行与 Linux 行都被调用;缺失时被拒绝。 +- 详细输出:冷构建的 `pack --verbose` 与 `test --verbose` 显示编译命令;缺省不显示。 +- CI:`check_path_identity.sh` 为零。 + +## 8. 规范与文档的收敛 + +每条规则只写在一处,其余处引用它。 + +| 规则 | 唯一所在 | 其余处 | +|---|---|---| +| 路径的四种用途、根目录表、降级 | 新 SPEC-020《路径》(规范性条款,RFC 2119) | docs/25 的“home 保留拼写”一段改为用户视角的一段并引用;docs/05 中 `path` 依赖“按规范化后的绝对目录比较”改为“按跟随链接后的绝对目录”并引用;AGENTS.md 的规范编号范围更正为 SPEC-001 至 SPEC-020 | +| 代码中的判断 | AGENTS.md §4 一行并链接 SPEC-020 | mcpp-contributing skill 写判断步骤与 CI 规则,不重述规则 | +| 链接器如何到达驱动 | SPEC-006 一条(各路线的词) | docs/20 的表与 `tools.ld` 一段改为用户视角并引用;删去“经 `--ld-path`”这一在 MSVC 路线上不成立的陈述 | +| 构建程序占位符 | SPEC-007(不变) | 一句:取值来自根目录表 | +| `--verbose` 的范围 | docs/09 一句 | — | + +各条在 docs/ 中英文同步,CHANGELOG 每项行为一条。 + +## 9. 决定 + +| 编号 | 问题 | 决定 | 未采用 | +|---|---|---|---| +| D1 | MSVC 路线的链接器词 | `-B<目录> -fuse-ld=<主名>`,链接器须为 `.exe`(§4.4) | `-B "" -fuse-ld=<绝对路径>` | +| D2 | `-no-canonical-prefixes` 的范围 | mcpp 启动的全部 clang 驱动;使用 clang 的工程升级后重编译一次 | 只用于按路径指定的树(`hermetic.cppm:165` 的例外保留) | +| D3 | 路径规则的所在 | 新 SPEC-020《路径》 | 并入 SPEC-010 | +| D4 | §4.7 | MSVC ABI 行的 `ldflags` 含 `-nostdlib` 时给出一条提示:CRT 模型的默认库指令仍写入目标文件;不改变行为 | 不提示 | +| D5 | 路径模块的位置 | 保留 `modules/libs/src/path_identity.cppm` 的薄层 | 调用点直接用 mcpplibs.os | + +## 10. 自我评审 + +- 对象标识在 openkal 的托管目标上可能不提供(`present` 不含标识):`same`/`within` 为 `nullopt`,按拼写决定并报告; + 正确性由 P3 保证。 +- 代价:`same` 至多两次 stat;`within` 每级祖先一次,深度有界;遍历去环由路径集合改为标识集合,次数不变。 +- Windows 的大小写与 8.3 短名:拼写比较由 `os::fs::same` 折叠大小写,短名由对象标识识别。 +- 43 处同一与包含的迁移改变的是判断方式,不改变回答:两种拼写原先经物理路径相等的,现经标识相等。 +- MSVC 路线的链接器词依赖 `GetProgramPath` 先查 `-B` 的行为,该行为在 LLVM 中长期稳定,以 Windows CI 的追踪程序断言 + 守住。 +- 本设计不新造机制:对象标识、词法比较来自 mcpplibs.os;降级报告、CI 守卫、工具链事实、占位符均为现有机制的收敛。 + +## 11. 实施任务 + +一个带版本号的 PR(2026.12.7.1)。提交按任务组织,英文陈述句;在三个检查点推送,不逐提交运行全量 CI。 + +```text +T0 e2e graph/834 在自己的 home 中运行(已提交) +T1 路径模块 ─┬─ T2 65 处迁移,CI 为零 ───────────┐ + ├─ T3 编译器运行状态与注册 ─────────┤ + └─ T4 根目录表 ─┐ ├─ T9 别名下的测试 ─ T10 规范与文档 ─ T11 版本 +T5 链接器事实与生成函数 ──────┴─ T6 -no-canonical-prefixes ─┤ +T7 详细输出单一来源 ──────────────────────────────────────────┤ +T8 MSVC 行 -nostdlib 的提示 ──────────────────────────────────┘ +``` + +| 任务 | 内容 | 依赖 | 完成判据 | +|---|---|---|---| +| T0 | e2e `graph/834` 以 `s::own_home()` 运行:重放的断言只在无人写其 home 时成立 | — | 已提交;workspace/graph 9 例通过 | +| T1 | §4.1:路径模块的 `given`、`key`、`resolved`、`same`、`beneath`、`within`、`object`、`describe`、`on_undecided`,基于 mcpplibs.os 的 `same`、`within`、`read_link`、`identity_of`、`canonical`;删去 `identity()`;入口安装 `on_undecided` | — | 单元:符号链接、相对链接、链接环、不存在的尾部、指向外部的链接;Linux、macOS、Windows 通过 | +| T2 | §4.2:附录 A 中除 T3 所属 4 处外的 61 处,与原 `identity()` 的 4 个调用者;`check_path_identity.sh` 改为零,删去基线文件;`project.cppm:433` 去掉 `.string()` | T1 | 脚本为零;现有单元与 e2e 通过 | +| T3 | §4.3:工作目录与注册目录为 `given`,运行目录的键与输出标识为 `resolved`;`Witnesses::start` 由调用者传入运行时目录 | T1 | 单元:注册经链接给出的运行时目录时传输记录为给定拼写,往返、拒绝与停止不变;经链接的输出与经实路径的输出同一 | +| T4 | §4.5:`mcpp.build.roots`;路径缩短、`trim_map`、构建程序占位符、自足性检查的允许集合改为读表 | T1 | 路径缩短、`-ffile-prefix-map`、占位符的输出与改前逐字节相同;自足性检查结果不变 | +| T5 | §4.4:`Toolchain::linker` 与生成函数,项目、构建程序、freestanding 三处共用,`resolve_lld` 并入;`mcpp why toolchain` 列出;缺失与 MSVC 路线上的非 `.exe` 在规划时拒绝 | T1 | 单元(toolchain-model):四条路线 × 声明、树、载荷、无;e2e:Linux 上物理目录另有 lld 的符号链接树用树中的;`tools.ld` 的追踪程序在 Linux 行与 Windows MSVC 行被调用;缺失被拒绝 | +| T6 | §4.4:mcpp 启动的全部 clang 驱动加 `-no-canonical-prefixes`;删去 `hermetic.cppm:165` 的例外 | T4、T5 | 载荷工具链(含借用上游的链接项)编译、链接与自足性检查通过;e2e 875(符号链接树)与 Windows `subst` 任务通过;资源目录以给定拼写报告 | +| T7 | §4.6:`verbose` 为 `std::optional`;删去 `pack` 5 处的设置;判据移入测试工具集;`test --verbose` 的用例 | — | e2e:`pack` 与 `test` 的冷构建在 `--verbose` 下显示编译命令,缺省不显示 | +| T8 | D4:MSVC ABI 行 `ldflags` 含 `-nostdlib` 时的提示,登记为一个 notice | — | 一个 C++ e2e 用例使该 notice 出现(面的账本);其他行不出现 | +| T9 | §7:测试工具集的“以别名运行”与“产物中无物理前缀”;别名下的 `build`、`test`、`pack`,运行目录与传输记录,`path` 依赖与成员的同一 | T2、T3、T4 | Linux 符号链接与 Windows `subst` 两种别名下通过 | +| T10 | §8:SPEC-020;SPEC-006、SPEC-007;docs/05、09、20、25(中英文);AGENTS.md §4;mcpp-contributing;规范索引 | T1–T8 | 每条规则只在 §8 所列一处陈述;索引生成与文档检查通过 | +| T11 | `mcpp.toml` 与 `modules/versioning/src/version.cppm` 一个提交;CHANGELOG 2026.12.7.1 一节,并入 main 上已有的 `[Unreleased]` 条目;GCC 与 LLVM 23.1.3 本地构建;面的账本增量核对;PR 描述 | T0–T10 | 全部检查通过;生态级自我评审 | + +检查点:T1、T2、T3 之后推送一次;T4 至 T8 之后一次;T9 至 T11 之后一次。 + +## 附录 A:65 处调用的归类(最终) + +| 用途 | 位置 | +|---|---| +| 地址,`given`(7) | `detach_codegen.cppm:841`(工作目录);`compiler_transaction.cppm:203`(注册目录);`prepare/graph.cpp:1410`(path 依赖的根);`project.cppm:433`(工作区的 path 依赖,`key`);`prepare/features.cpp:1555`;`provider/xlings/xlings.cpp:1171`(锁在目录内);`toolchain/clang.cppm:171` | +| 对象,一对路径的问题(`same`、`within`、`beneath`;27) | `prepare/features.cpp:2038–2039`;`prepare/platform.cpp:908`;`prepare/plan.cpp:197、203`;`prepare/windows_resources.cpp:684–685`;`project.cppm:479、482`;`prepare/graph.cpp:438`;`engine_package.cppm:127–128`;`build/plan.cppm:1961–1962`;`pack/pack.cppm:1302、1305、1315、1318`;`pack/distribution.cppm:908、911`;`runtime_validation.cppm:1225`;`toolchain/registry.cppm:1089`;`toolchain/post_install.cppm:234、242`;`runtime/binding.cppm:345、347`;`toolchain/base_probe.cppm:241、244` | +| 对象,集合或映射的键(`object`、`resolved`;17) | `manifest/src/glob.cppm` ×5(遍历去环、子模块);`modgraph/scanner.cppm:545`;`prepare/features.cpp:1541`;`prepare/state.cppm:563`;`prepare/manifest.cpp:239`;`prepare/graph.cpp:320`;`config.cppm:453`;`runtime/elf.cppm:506、1685`;`detach_codegen.cppm:835`;`compiler_transaction.cppm:416`;`toolchain/base_probe.cppm:162`(指纹) | +| 有意跟随链接,`resolved`(14) | `pm/lock_io.cppm:396`;`home/files.cppm:605`;`runtime/binding.cppm:514、535`;`toolchain/post_install.cppm:325`;`pack/pack.cppm:3785`;`build/hermetic.cppm:165`;`pm/patch.cppm:338`;`toolchain/base_probe.cppm:272`;`toolchain/clang.cppm:207`;`build/resources.cppm:213`;`runtime_validation.cppm:1024、1218`;`toolchain/registry.cppm:1087` | + +另:原 `identity()` 的调用者——`modules/cps/src/cps.cppm`、`modules/cps/src/usage.cppm`、`src/toolchain/probe.cppm` +改用 `resolved`、`within`;`src/config.cppm` 的借用判断与 `src/pm/package_info.cppm` 的说明读取改用 `within`。 diff --git a/.github/tools/path-identity.baseline b/.github/tools/path-identity.baseline deleted file mode 100644 index 03b95fb3e..000000000 --- a/.github/tools/path-identity.baseline +++ /dev/null @@ -1,30 +0,0 @@ -modules/manifest/src/glob.cppm 5 -src/build/engine_package.cppm 2 -src/build/hermetic.cppm 1 -src/build/plan.cppm 2 -src/build/prepare/features.cpp 4 -src/build/prepare/graph.cpp 3 -src/build/prepare/manifest.cpp 1 -src/build/prepare/plan.cpp 2 -src/build/prepare/platform.cpp 1 -src/build/prepare/state.cppm 1 -src/build/prepare/windows_resources.cpp 2 -src/build/resources.cppm 1 -src/build/runtime_validation.cppm 3 -src/build/schedule/compiler_transaction.cppm 2 -src/build/schedule/detach_codegen.cppm 2 -src/config.cppm 1 -src/home/files.cppm 1 -src/modgraph/scanner.cppm 1 -src/pack/distribution.cppm 2 -src/pack/pack.cppm 5 -src/pm/lock_io.cppm 1 -src/pm/patch.cppm 1 -src/project.cppm 3 -src/provider/xlings/xlings.cpp 1 -src/runtime/binding.cppm 4 -src/runtime/elf.cppm 2 -src/toolchain/base_probe.cppm 4 -src/toolchain/clang.cppm 2 -src/toolchain/post_install.cppm 3 -src/toolchain/registry.cppm 2 From ea95be973fc0e561b784b93815a14e0589c6f5fb Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:29:04 +0900 Subject: [PATCH 03/18] The path module answers each use of a path: an address, a key, an object, a link followed; an undecided question is reported once --- modules/libs/mcpp.toml | 8 +- modules/libs/src/path_identity.cppm | 224 +++++++++++++++++----- modules/libs/tests/test_path_identity.cpp | 111 +++++++++-- src/cli.cppm | 9 + 4 files changed, 291 insertions(+), 61 deletions(-) diff --git a/modules/libs/mcpp.toml b/modules/libs/mcpp.toml index 05b1ae0c3..84b7efe13 100644 --- a/modules/libs/mcpp.toml +++ b/modules/libs/mcpp.toml @@ -1,6 +1,7 @@ # libs — the readers and small primitives every other package of mcpp may -# import: the TOML parser (`toml`) and what of a C++ source is code -# (`code_text`). It imports nothing from mcpp. JSON is nlohmann.json from the +# import: the TOML parser (`toml`), what of a C++ source is code (`code_text`) +# and the uses of a path (`path_identity`, over mcpplibs.os's names and +# identities). It imports nothing from mcpp. JSON is nlohmann.json from the # index (2026.11.7.1): no third-party source is copied into this tree. [package] name = "libs" @@ -9,5 +10,8 @@ version = "0.1.0" description = "Readers and primitives below every other package of mcpp" license = "Apache-2.0" +[dependencies] +mcpplibs.os = "0.4.9" + [dev-dependencies] mcpplibs.mtest = "0.11.3" diff --git a/modules/libs/src/path_identity.cppm b/modules/libs/src/path_identity.cppm index 816dce119..411011bbf 100644 --- a/modules/libs/src/path_identity.cppm +++ b/modules/libs/src/path_identity.cppm @@ -1,24 +1,25 @@ -// mcpp.libs.path_identity — whether two paths name one object, kept apart from -// the paths a program opens. +// mcpp.libs.path_identity — the uses of a path, each answered by one function (SPEC-020). // -// A path the user or the environment gives (`MCPP_HOME`, `MCPP_TOOLCHAIN`, an -// argument, the working directory) is opened and handed to a program as it is -// spelled, made absolute and lexically normal and no more. Its canonical form -// is an identity: what two spellings have in common when they name one object. -// The two were one value: the home was resolved to its canonical form and every -// path derived from it was opened under that form. Under a sandbox that grants -// a tree through a drive alias (an AppContainer whose `Z:` names a directory -// whose ancestors it may not open), the canonical form leads through those -// ancestors, and the home could not be opened (mcpp#1024). On Linux the same -// conversion turned a home given through a symbolic link into its target. +// A path the user, the environment or the system gives (`MCPP_HOME`, `MCPP_TOOLCHAIN`, an +// argument, the working directory, the runtime directory) is an ADDRESS: it is opened and +// handed to a program as it is spelled, made absolute and lexically normal and no more +// (`given`), and a key built from it is that spelling (`key`). Whether two paths name one +// object, or one lies within a directory, is a question of IDENTITY (`same`, `within`, +// `beneath`): it is answered by the spellings, then by the spellings with their links +// followed, then by the objects' identities, which the system reads through a handle opened +// by the given spelling (mcpplibs.os `identity_of`). No ancestor is opened by any other +// spelling, so a process granted a tree through a drive alias -- an AppContainer whose `Z:` +// names a directory whose ancestors it may not open -- asks these questions as any other +// process does (mcpp#1024). A path whose links are to be followed -- a library's soname +// chain, a link a package carries -- is `resolved`: every symbolic link and junction along it +// is replaced by its target, and the volume's own spelling (a drive alias, a `subst` drive, a +// mapped drive) is kept. The physical spelling of a path serves none of these uses; a +// diagnostic prints it (`describe`). // -// Identity is asked here. Resolving it reads every ancestor of the path, which -// a restricted process may not do; the answer is then absent, and the caller -// decides with the spelling and says that it did (`diag::degraded`). -// `.github/tools/check_path_identity.sh` counts the resolutions made anywhere -// else, against a baseline that only falls. -// -// It imports nothing of mcpp. +// When an identity cannot be read, the question is decided by the spellings, and the +// decision is reported through the handler the program installs (`on_undecided`): this +// package imports nothing of mcpp. `.github/tools/check_path_identity.sh` holds the +// resolutions of a path to its canonical form outside this file at zero. export module mcpp.libs.path_identity; @@ -26,48 +27,183 @@ import std; export namespace mcpp::libs::path_identity { -// The spelling a given path is opened under: absolute, lexically normal, every -// link and alias kept. +// The address of a given path: absolute, lexically normal, every link and alias kept. std::filesystem::path given(const std::filesystem::path& p); -// The object `p` names, whatever its spelling: links resolved, and for a path -// whose last components do not exist yet, the existing part resolved and the -// rest appended. nullopt when it cannot be resolved (an ancestor this process -// may not read). -std::optional identity(const std::filesystem::path& p); +// A key built from a path: the UTF-8 text of its address, with `/` separators. Two +// spellings of one object make two keys, which costs one more entry and gives no wrong +// result. +std::string key(const std::filesystem::path& p); + +// The address with every symbolic link and junction along it followed, relative targets +// joined to the link's directory; the volume's spelling kept, and a part that does not exist +// appended as it is. A loop of links answers the address itself. +std::filesystem::path resolved(const std::filesystem::path& p); + +// Whether `a` and `b` name one object. A part that does not exist yet is compared as +// spelled beneath the deepest part that does. +bool same(const std::filesystem::path& a, const std::filesystem::path& b); + +// beneath: where the object `p` reaches lies beneath the object `dir` reaches: the path from `dir` +// to it with links followed (`.` for `dir` itself), or nullopt when it does not lie there. +// A link beneath `dir` that leads out of it is not within it. Whether a NAME lies beneath a +// directory is a question of spelling alone: mcpplibs.os `fs::within`. +std::optional beneath(const std::filesystem::path& p, const std::filesystem::path& dir); + +// Whether the object `p` reaches is the object `dir` reaches or lies beneath it. +bool within(const std::filesystem::path& p, const std::filesystem::path& dir); -// Whether `a` and `b` name one object. nullopt when either identity cannot be -// resolved; the caller compares the given spellings then, and says so. -std::optional same(const std::filesystem::path& a, const std::filesystem::path& b); +// The identity of the object a path reaches, as the system reads it through a handle: a key +// of a set of objects -- the directories of a walk, files met twice. Not a key of anything +// kept: an index is reused once its file is gone. +struct Object { + std::uint64_t volume = 0; + std::uint64_t index = 0; + auto operator<=>(const Object&) const = default; +}; +// nullopt when `p` does not exist or its identity cannot be read. +std::optional object(const std::filesystem::path& p); + +// The physical spelling of a path, for a diagnostic only; the address when it cannot be read. +std::string describe(const std::filesystem::path& p); + +// The report of a question decided by the spellings because an identity could not be read. +// One handler for the process, installed before any question is asked. +void on_undecided(void (*report)(std::string_view question)); } // namespace mcpp::libs::path_identity module :private; +import mcpplibs.os.fs; + namespace mcpp::libs::path_identity { +namespace { -std::filesystem::path given(const std::filesystem::path& p) { - std::error_code ec; - auto abs = std::filesystem::absolute(p, ec); - return (ec ? p : abs).lexically_normal(); +namespace fs = std::filesystem; +namespace ofs = mcpplibs::os::fs; + +std::atomic g_report{nullptr}; + +// A loop of links is cut at the bound the POSIX systems use for one lookup. +constexpr int kLinkHops = 40; + +std::string text(const fs::path& p) { return ofs::generic_utf8(p); } + +void undecided(std::string_view question) { + if (auto* report = g_report.load(std::memory_order_acquire)) report(question); } -std::optional identity(const std::filesystem::path& p) { +bool present(const fs::path& p) { std::error_code ec; - auto resolved = std::filesystem::weakly_canonical(given(p), ec); - if (ec) return std::nullopt; - return resolved; + return fs::exists(p, ec); +} + +// The deepest part of `p` that exists, and what follows it. +std::pair existing_part(const fs::path& p) { + fs::path node = p, tail; + while (!node.empty() && !present(node)) { + const auto parent = node.parent_path(); + if (parent == node) break; + tail = tail.empty() ? node.filename() : node.filename() / tail; + node = parent; + } + return {node, tail}; } -std::optional same(const std::filesystem::path& a, const std::filesystem::path& b) { +} // namespace + +fs::path given(const fs::path& p) { std::error_code ec; - if (std::filesystem::exists(a, ec) && std::filesystem::exists(b, ec)) { - const bool eq = std::filesystem::equivalent(a, b, ec); - if (!ec) return eq; + auto abs = fs::absolute(p, ec); + return (ec ? p : abs).lexically_normal(); +} + +std::string key(const fs::path& p) { return text(given(p)); } + +fs::path resolved(const fs::path& p) { + const auto start = given(p); + fs::path out = start.root_path(); + std::deque rest; + for (auto const& c : start.relative_path()) rest.push_back(c); + int hops = 0; + while (!rest.empty()) { + const auto c = std::move(rest.front()); + rest.pop_front(); + if (c.empty() || c == ".") continue; + if (c == "..") { out = out.parent_path(); continue; } + auto next = out / c; + auto link = ofs::read_link(next); + if (!link) { + out = std::move(next); + // Nothing beneath a missing part can be a link: the rest is appended as spelled. + if (link.error().code == mcpplibs::os::errc::not_found) + for (; !rest.empty(); rest.pop_front()) out /= rest.front(); + continue; + } + if (++hops > kLinkHops) return start; + const auto target = ofs::from_utf8(*link); + const auto rel = target.relative_path(); + rest.insert(rest.begin(), rel.begin(), rel.end()); + if (target.has_root_path()) out = target.root_path(); } - auto ia = identity(a), ib = identity(b); - if (!ia || !ib) return std::nullopt; - return *ia == *ib; + return out.lexically_normal(); +} + +bool same(const fs::path& a, const fs::path& b) { + const auto ga = given(a), gb = given(b); + if (ofs::same(ga, gb)) return true; + const auto ra = resolved(ga), rb = resolved(gb); + if (ofs::same(ra, rb)) return true; + const auto [na, ta] = existing_part(ra); + const auto [nb, tb] = existing_part(rb); + if (!ofs::same(ta, tb)) return false; + const auto ia = ofs::identity_of(na), ib = ofs::identity_of(nb); + if (ia && ib) return *ia == *ib; + undecided(std::format("whether {} and {} are one object", text(ga), text(gb))); + return false; +} + +std::optional beneath(const fs::path& p, const fs::path& dir) { + // The object, not the name: a link beneath `dir` may lead out of it, so the spellings are + // compared with their links followed. Whether a NAME lies beneath a directory is + // mcpplibs.os's lexical `within`. + const auto gp = given(p), gd = given(dir); + const auto rp = resolved(gp), rd = resolved(gd); + if (ofs::within(rp, rd)) return rp.lexically_relative(rd); + if (!present(rd)) return std::nullopt; + const auto id = ofs::identity_of(rd); + bool unread = !id; + if (id) { + for (auto at = rp;; at = at.parent_path()) { + if (present(at)) { + const auto here = ofs::identity_of(at); + if (here && *here == *id) return rp.lexically_relative(at); + if (!here) unread = true; + } + if (at.parent_path() == at || at.empty()) break; + } + } + if (unread) undecided(std::format("whether {} lies within {}", text(gp), text(gd))); + return std::nullopt; +} + +bool within(const fs::path& p, const fs::path& dir) { return beneath(p, dir).has_value(); } + +std::optional object(const fs::path& p) { + const auto id = ofs::identity_of(given(p)); + if (!id) return std::nullopt; + return Object{id->volume, id->index}; +} + +std::string describe(const fs::path& p) { + const auto at = given(p); + if (!present(at)) return text(at); + return text(ofs::canonical(at)); +} + +void on_undecided(void (*report)(std::string_view question)) { + g_report.store(report, std::memory_order_release); } } // namespace mcpp::libs::path_identity diff --git a/modules/libs/tests/test_path_identity.cpp b/modules/libs/tests/test_path_identity.cpp index fb146a8bb..4768d7043 100644 --- a/modules/libs/tests/test_path_identity.cpp +++ b/modules/libs/tests/test_path_identity.cpp @@ -4,24 +4,105 @@ import mcpp.libs.path_identity; using namespace mcpplibs::mtest; -// SUBSYSTEM-LEVEL: a given path keeps its spelling, and identity is a question of its own -// (design 2026-11-27 §4.6, mcpp#1024). +// SUBSYSTEM-LEVEL: the uses of a path (SPEC-020). An address keeps its spelling; whether two +// paths are one object, or one lies within a directory, is answered without opening any +// ancestor by another spelling; links are followed only where a use asks for it. namespace pi = mcpp::libs::path_identity; +namespace fs = std::filesystem; + +namespace { + +int g_undecided = 0; +void count_undecided(std::string_view) { ++g_undecided; } + +// A directory of the case, removed when the case ends; empty when this host gives no +// privilege to make a directory link, which the cases below need. +struct Tree { + fs::path base = fs::temp_directory_path() / std::format("mcpp-path-identity-{:08x}", std::random_device{}()); + bool links = true; + Tree() { + fs::create_directories(base / "real" / "x"); + std::error_code ec; + fs::create_directory_symlink(base / "real", base / "link", ec); + links = !ec; + } + ~Tree() { std::error_code ec; fs::remove_all(base, ec); } +}; + +} // namespace UTest the_given_spelling_keeps_a_link{"PathIdentity/TheGivenSpellingKeepsALink", [] { - const auto base = std::filesystem::temp_directory_path() / std::format("mcpp-path-identity-{}", std::random_device{}()); - std::filesystem::create_directories(base / "real" / "x"); + Tree t; + if (!t.links) skip("no privilege for a directory link here"); + const auto viaLink = t.base / "link" / "." / "x"; + expect(eq(pi::given(viaLink), (t.base / "link" / "x").lexically_normal())); + expect(eq(pi::key(viaLink), pi::given(viaLink).generic_string())); + expect(ne(pi::key(viaLink), pi::key(t.base / "real" / "x"))); +}}; + +UTest a_link_along_the_path_is_followed{"PathIdentity/ALinkAlongThePathIsFollowed", [] { + Tree t; + if (!t.links) skip("no privilege for a directory link here"); + expect(eq(pi::resolved(t.base / "link" / "x"), pi::resolved(t.base / "real" / "x"))); + // A relative target is joined to the link's directory. + std::error_code ec; + fs::create_directory_symlink(fs::path("real") / "x", t.base / "rel", ec); + expect(fatal(!ec)); + expect(eq(pi::resolved(t.base / "rel"), pi::resolved(t.base / "real" / "x"))); + // A part that does not exist is appended as spelled. + expect(eq(pi::resolved(t.base / "link" / "new" / "deeper"), + pi::resolved(t.base / "real") / "new" / "deeper")); +}}; + +UTest a_loop_of_links_answers_the_address{"PathIdentity/ALoopOfLinksAnswersTheAddress", [] { + Tree t; + if (!t.links) skip("no privilege for a directory link here"); + std::error_code ec; + fs::create_directory_symlink(t.base / "b", t.base / "a", ec); + fs::create_directory_symlink(t.base / "a", t.base / "b", ec); + expect(fatal(!ec)); + expect(eq(pi::resolved(t.base / "a" / "y"), pi::given(t.base / "a" / "y"))); +}}; + +UTest one_object_by_two_spellings{"PathIdentity/OneObjectByTwoSpellings", [] { + Tree t; + if (!t.links) skip("no privilege for a directory link here"); + pi::on_undecided(count_undecided); + g_undecided = 0; + expect(pi::same(t.base / "link" / "x", t.base / "real" / "x")); + expect(!pi::same(t.base / "link" / "x", t.base / "real")); + // A path that does not exist yet is compared beneath the deepest part that does. + expect(pi::same(t.base / "link" / "new", t.base / "real" / "new")); + expect(!pi::same(t.base / "link" / "new", t.base / "real" / "other")); + expect(eq(g_undecided, 0)); +}}; + +UTest a_path_within_a_directory{"PathIdentity/APathWithinADirectory", [] { + Tree t; + if (!t.links) skip("no privilege for a directory link here"); + pi::on_undecided(count_undecided); + g_undecided = 0; + // By the spellings, by the links followed, and for the directory itself. + expect(eq(pi::beneath(t.base / "real" / "x", t.base / "real"), std::optional{"x"})); + expect(eq(pi::beneath(t.base / "link" / "x", t.base / "real"), std::optional{"x"})); + expect(eq(pi::beneath(t.base / "real", t.base / "link"), std::optional{"."})); + expect(pi::within(t.base / "link" / "x" / "new", t.base / "real")); + expect(!pi::within(t.base / "real", t.base / "real" / "x")); + // A link inside the directory that leads out of it does not lie within it. + fs::create_directories(t.base / "outside"); std::error_code ec; - std::filesystem::create_directory_symlink(base / "real", base / "link", ec); - if (ec) { std::filesystem::remove_all(base); return; } // no privilege for a link here - const auto viaLink = base / "link" / "." / "x"; - expect(eq(pi::given(viaLink), (base / "link" / "x").lexically_normal())); - expect(fatal(pi::identity(viaLink).has_value())); - expect(eq(*pi::identity(viaLink), *pi::identity(base / "real" / "x"))); - expect(eq(pi::same(viaLink, base / "real" / "x"), std::optional{true})); - expect(eq(pi::same(viaLink, base / "real"), std::optional{false})); - // A path that does not exist yet is resolved as far as it exists. - expect(eq(pi::same(base / "link" / "new", base / "real" / "new"), std::optional{true})); - std::filesystem::remove_all(base); + fs::create_directory_symlink(t.base / "outside", t.base / "real" / "x" / "escape", ec); + expect(fatal(!ec)); + expect(!pi::within(t.base / "real" / "x" / "escape", t.base / "real")); + // Nothing lies within a directory that does not exist. + expect(!pi::within(t.base / "real", t.base / "absent")); + expect(eq(g_undecided, 0)); +}}; + +UTest a_physical_spelling_is_for_a_diagnostic{"PathIdentity/APhysicalSpellingIsForADiagnostic", [] { + Tree t; + if (!t.links) skip("no privilege for a directory link here"); + expect(eq(pi::describe(t.base / "link" / "x"), pi::describe(t.base / "real" / "x"))); + expect(eq(pi::describe(t.base / "absent"), pi::key(t.base / "absent"))); }}; diff --git a/src/cli.cppm b/src/cli.cppm index fd724b6d4..f40c6993c 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -65,6 +65,7 @@ import mcpp.ui; import mcpp.log; import mcpp.home; // --system: the system home import mcpp.diag; // the single sink for the report below +import mcpp.libs.path_identity; import mcpp.modgraph.glob; // take_unnarrowable_paths() namespace libc = mcpplibs::mwrap::libc::macros; @@ -1228,6 +1229,14 @@ mcpplibs::cmdline::App command_tree(const std::vector& passthrough, int run(int argc, char** argv) { namespace cl = mcpplibs::cmdline; + // A question of identity the system could not answer is decided by the spellings, and + // said, for every package that asks one (SPEC-020): the path package imports nothing of + // mcpp, so the report is installed here. + mcpp::libs::path_identity::on_undecided(+[](std::string_view question) { + mcpp::diag::degraded("path", std::format("{} could not be read", question), + "it was decided by the paths as they are spelled"); + }); + // Internal split-schedule executor. Everything after `--` is the // compiler's argv, including flags with the same names as these options. // Dispatch before global option scans: child words never configure mcpp. From 735d80f4bb409173bac9f6c7630af54c866826c7 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:29:11 +0900 Subject: [PATCH 04/18] Every resolution of a path to its physical spelling moves to the path module, and the CI check holds the rest at zero; compiler-run state and registration keep the given spelling --- .github/tools/check_path_identity.sh | 45 +++++++----------- modules/cps/src/cps.cppm | 3 +- modules/cps/src/usage.cppm | 2 +- modules/manifest/src/glob.cppm | 49 +++++++++----------- src/build/engine_package.cppm | 6 +-- src/build/hermetic.cppm | 9 ++-- src/build/plan.cppm | 8 ++-- src/build/prepare/features.cpp | 11 ++--- src/build/prepare/graph.cpp | 15 +++--- src/build/prepare/manifest.cpp | 5 +- src/build/prepare/plan.cpp | 10 ++-- src/build/prepare/platform.cpp | 3 +- src/build/prepare/state.cppm | 9 ++-- src/build/prepare/windows_resources.cpp | 10 ++-- src/build/resources.cppm | 4 +- src/build/runtime_validation.cppm | 26 ++++------- src/build/schedule/compiler_transaction.cppm | 20 ++++---- src/build/schedule/detach_codegen.cppm | 33 ++++++------- src/config.cppm | 19 ++------ src/home/files.cppm | 4 +- src/modgraph/scanner.cppm | 8 ++-- src/pack/distribution.cppm | 8 ++-- src/pack/pack.cppm | 28 +++-------- src/pm/lock_io.cppm | 7 +-- src/pm/package_info.cppm | 7 +-- src/pm/patch.cppm | 8 ++-- src/project.cppm | 14 ++---- src/provider/xlings/xlings.cpp | 8 ++-- src/runtime/binding.cppm | 19 +++----- src/runtime/elf.cppm | 8 ++-- src/toolchain/base_probe.cppm | 16 +++---- src/toolchain/clang.cppm | 13 ++---- src/toolchain/post_install.cppm | 18 ++++--- src/toolchain/probe.cppm | 20 +++----- src/toolchain/registry.cppm | 20 ++++---- tests/unit/test_compiler_transaction.cpp | 42 +++++++++++++++++ 36 files changed, 234 insertions(+), 301 deletions(-) diff --git a/.github/tools/check_path_identity.sh b/.github/tools/check_path_identity.sh index 939a73a2a..5f94fc104 100755 --- a/.github/tools/check_path_identity.sh +++ b/.github/tools/check_path_identity.sh @@ -1,35 +1,22 @@ #!/usr/bin/env bash -# The resolutions of a path to its canonical form only fall (design 2026-11-27 §4.6, mcpp#1024). +# No path is resolved to its canonical form outside mcpp.libs.path_identity (SPEC-020). # -# A path the user or the environment gives is opened and handed to a program as it is spelled; its -# canonical form is an identity, asked of mcpp.libs.path_identity, which reports when it cannot be -# read. Each file's count of `canonical(` and `weakly_canonical(` called on std::filesystem is at -# most its line in path-identity.baseline; a file not listed has none. A line falls as its calls -# move to the identity module (an identity) or to the given spelling (an address). +# A path the user, the environment or the system gives is an address, opened and handed to a +# program as it is spelled; whether two paths name one object is answered by the path package +# (`same`, `within`, `beneath`, `object`), and a path whose links are to be followed is its +# `resolved` form. The physical spelling serves none of these uses: a call of `canonical(` or +# `weakly_canonical(` on std::filesystem or on mcpplibs.os's fs anywhere else is an error. set -u cd "$(dirname "$0")/../.." -baseline=.github/tools/path-identity.baseline -[ -f "$baseline" ] || { echo "::error::missing $baseline"; exit 1; } +found=$(grep -rnE '(filesystem|fs)::(weakly_)?canonical\(' src modules \ + --include='*.cpp' --include='*.cppm' 2>/dev/null \ + | grep -v '^modules/libs/src/path_identity.cppm:' | grep -v '/tests/') -current=$(grep -rcE '(filesystem|fs)::(weakly_)?canonical\(' src modules \ - --include='*.cpp' --include='*.cppm' 2>/dev/null \ - | grep -v ':0$' | grep -v '^modules/libs/src/path_identity.cppm:' | grep -v '/tests/' \ - | sed 's/:/ /' | sort) - -rc=0 -while read -r file n; do - [ -n "$file" ] || continue - allowed=$(awk -v f="$file" '$1 == f { print $2 }' "$baseline") - if [ -z "$allowed" ]; then - echo "::error::$file resolves a path to its canonical form $n time(s); ask mcpp.libs.path_identity, or open the given spelling" - rc=1 - elif [ "$n" -gt "$allowed" ]; then - echo "::error::$file resolves a path to its canonical form $n times, more than the $allowed of $baseline" - rc=1 - elif [ "$n" -lt "$allowed" ]; then - echo "note: $file resolves $n times, fewer than the $allowed of $baseline; lower its line" - fi -done <<< "$current" -[ "$rc" = 0 ] && echo "OK: no file resolves a path to its canonical form more often than $baseline states" -exit "$rc" +if [ -n "$found" ]; then + echo "::error::a path is resolved to its canonical form outside mcpp.libs.path_identity:" + echo "$found" + echo "an address is given(p); an object is same/within/beneath/object; links are followed by resolved(p)" + exit 1 +fi +echo "OK: no path is resolved to its canonical form outside mcpp.libs.path_identity" diff --git a/modules/cps/src/cps.cppm b/modules/cps/src/cps.cppm index dab72f74a..506db94e5 100644 --- a/modules/cps/src/cps.cppm +++ b/modules/cps/src/cps.cppm @@ -582,8 +582,7 @@ std::expected prefix_of(const Package& p) { const auto dir = fs::absolute(p.file, ec).parent_path(); if (auto d = strip(dir)) return *d; // A file reached through a link: its own directory, as CMake retries with the real path. - if (auto real = mcpp::libs::path_identity::identity(p.file)) - if (auto d = strip(real->parent_path())) return *d; + if (auto d = strip(mcpp::libs::path_identity::resolved(p.file).parent_path())) return *d; return std::unexpected(std::format("its `cps_path` {} is not the tail of the directory {}", p.cpsPath, dir.generic_string())); } diff --git a/modules/cps/src/usage.cppm b/modules/cps/src/usage.cppm index 5fde0612d..89f03709f 100644 --- a/modules/cps/src/usage.cppm +++ b/modules/cps/src/usage.cppm @@ -366,7 +366,7 @@ std::vector candidates(const std::vector take_unnarrowable_paths(); // cannot hold a file that one sees and the other does not (#766). // // From `start`, directory symlinks are followed (vendored trees are often -// symlink farms). A directory whose canonical path is already on the current -// recursion chain is a link cycle and is not entered; the same real directory +// symlink farms). A directory that is the same object as one already on the +// current recursion chain is a link cycle and is not entered; the same real directory // reached through a second lexical path still is, because matching is lexical. // is_excluded_walk_dir's directories are not entered. `onDir` sees every other // directory below `start` and may refuse to enter it; `onFile` sees every @@ -397,20 +398,19 @@ std::string_view trim_ws(std::string_view s) { return s; } -// The submodule paths `.gitmodules` registers under `root`, canonical and -// absolute, read once per root for the process. Glob walks run on several -// threads at once (a workspace's build programs), hence the lock. An entry is -// never erased, so the reference stays valid after the lock is released; this -// runs once per directory entry of a walk, where a copy would be paid each time. -const std::set& submodule_paths(const std::filesystem::path& root) { +// The directories `.gitmodules` registers under `root`, as objects (SPEC-020: a +// set of objects is a set of identities), read once per root for the process. +// Glob walks run on several threads at once (a workspace's build programs), +// hence the lock. An entry is never erased, so the reference stays valid after +// the lock is released; this runs once per directory entry of a walk, where a +// copy would be paid each time. +const std::set& submodule_paths(const std::filesystem::path& root) { static std::mutex m; - static std::map> cache; - std::error_code kec; - auto key = std::filesystem::canonical(root, kec); - if (kec) key = root; + static std::map> cache; + const auto key = mcpp::libs::path_identity::key(root); std::lock_guard lock(m); if (auto it = cache.find(key); it != cache.end()) return it->second; - std::set paths; + std::set paths; std::ifstream f(root / ".gitmodules"); std::string line; while (f && std::getline(f, line)) { @@ -420,9 +420,8 @@ const std::set& submodule_paths(const std::filesystem::pa if (k != "path") continue; std::string_view v = trim_ws(std::string_view(line).substr(eq + 1)); if (v.empty()) continue; - std::error_code pec; - auto abs = std::filesystem::canonical(root / std::filesystem::path(std::string(v)), pec); - paths.insert(pec ? (root / std::filesystem::path(std::string(v))) : abs); + if (auto o = mcpp::libs::path_identity::object(root / std::filesystem::path(std::string(v)))) + paths.insert(*o); } return cache.emplace(key, std::move(paths)).first->second; } @@ -441,21 +440,17 @@ bool is_excluded_walk_dir(const std::filesystem::path& dir, if (name == kMcppDir || name == kGitDir || name == kTargetDir) return true; auto const& submodules = submodule_paths(root); if (submodules.empty()) return false; - std::error_code ec; - auto c = std::filesystem::canonical(dir, ec); - return submodules.contains(ec ? dir : c); + const auto o = mcpp::libs::path_identity::object(dir); + return o && submodules.contains(*o); } bool walk_glob_tree(const std::filesystem::path& root, const std::filesystem::path& start, const std::function& onDir, const std::function& onFile) { namespace fs = std::filesystem; - std::vector chain; // canonical directories of the recursion stack + // The directories of the recursion stack, as objects: a link back to one of them is a cycle. + std::vector> chain{mcpp::libs::path_identity::object(start)}; std::error_code ec, eec; // ec: iteration; eec: per-entry probes - { - auto c = fs::canonical(start, eec); - chain.push_back(eec ? start : c); - } fs::recursive_directory_iterator it(start, fs::directory_options::follow_directory_symlink, ec); for (fs::recursive_directory_iterator end; !ec && it != end; it.increment(ec)) { auto& e = *it; @@ -466,12 +461,12 @@ bool walk_glob_tree(const std::filesystem::path& root, const std::filesystem::pa } auto depth = static_cast(it.depth()); chain.resize(std::min(chain.size(), depth + 1)); - auto c = fs::canonical(e.path(), eec); - if (!eec && std::find(chain.begin(), chain.end(), c) != chain.end()) { + auto o = mcpp::libs::path_identity::object(e.path()); + if (o && std::find(chain.begin(), chain.end(), o) != chain.end()) { it.disable_recursion_pending(); // link cycle continue; } - chain.push_back(eec ? e.path() : c); + chain.push_back(o); if (!onDir(e.path())) it.disable_recursion_pending(); continue; } diff --git a/src/build/engine_package.cppm b/src/build/engine_package.cppm index a2311b605..2a2b1ab54 100644 --- a/src/build/engine_package.cppm +++ b/src/build/engine_package.cppm @@ -65,6 +65,7 @@ module :private; import mcpp.build.directives; // kProtocolVersion -- the announced value has ONE source import mcpp.build.hostprogram; // the interface text import mcpp.version; +import mcpp.libs.path_identity; namespace mcpp::build::engine { @@ -123,10 +124,7 @@ bool is_engine_package(const fs::path& dir) { if (inside(dir, root())) return true; // One directory has more than one spelling: `/var` is `/private/var` on // macOS, and Windows has HOME and USERPROFILE, drive-letter case, 8.3 names. - std::error_code e1, e2; - const auto cd = fs::weakly_canonical(dir, e1); - const auto cr = fs::weakly_canonical(root(), e2); - return !e1 && !e2 && inside(cd, cr); + return mcpp::libs::path_identity::within(dir, root()); } std::pair module_texts() { diff --git a/src/build/hermetic.cppm b/src/build/hermetic.cppm index b99d2c4db..7aec584ea 100644 --- a/src/build/hermetic.cppm +++ b/src/build/hermetic.cppm @@ -57,6 +57,7 @@ import mcpp.provider.select; import mcpp.toolchain.fingerprint; import mcpp.toolchain.triple; import mcpp.invocation; +import mcpp.libs.path_identity; namespace mcpp::build { @@ -160,12 +161,8 @@ std::expected verify_hermetic_link( // 2026-10-16 §8): mcpp passes the link's paths on the command line, but // the driver reports its own resource dir (clang_rt.crt*) through the // path the link names. That store is allowed too. - { - std::error_code ec; - auto real = std::filesystem::weakly_canonical(tc.binaryPath, ec); - if (!ec) - if (auto upstream = mcpp::provider::store_of(real)) allowed.push_back(*upstream); - } + if (auto upstream = mcpp::provider::store_of(mcpp::libs::path_identity::resolved(tc.binaryPath))) + allowed.push_back(*upstream); if (!tc.base.root.empty()) allowed.push_back(tc.base.root); if (!tc.pairedSysroot.empty()) allowed.push_back(tc.pairedSysroot); diff --git a/src/build/plan.cppm b/src/build/plan.cppm index 0f3b41a13..05201b564 100644 --- a/src/build/plan.cppm +++ b/src/build/plan.cppm @@ -1062,6 +1062,7 @@ import mcpp.pack.prebuilt; // is_distribution_package — a shipped shared lib import mcpp.runtime.env_contract; import mcpp.provider.select; import mcpp.diag; +import mcpp.libs.path_identity; namespace mcpp::build { @@ -1949,7 +1950,7 @@ bool path_is_under_any(const std::filesystem::path& p, for (auto const& root : roots) { if (root.empty()) continue; if (inside(p, root)) return true; - // Retry on canonicalized paths. Lexical is the PRIMARY answer (it is + // Retry as objects (SPEC-020). Lexical is the PRIMARY answer (it is // the only one that survives a symlinked store), but it also requires // the two paths to be spelled the same way, and mcpp's home is reached // through more than one spelling on Windows (HOME vs USERPROFILE, drive @@ -1957,10 +1958,7 @@ bool path_is_under_any(const std::filesystem::path& p, // under different equivalence relations, and either "yes" is sufficient // evidence that the payload was installed into a store — so a spelling // difference degrades to a slower build, never to a wrong one. - std::error_code e1, e2; - auto cp = std::filesystem::weakly_canonical(p, e1); - auto cr = std::filesystem::weakly_canonical(root, e2); - if (!e1 && !e2 && inside(cp, cr)) return true; + if (mcpp::libs::path_identity::within(p, root)) return true; } return false; } diff --git a/src/build/prepare/features.cpp b/src/build/prepare/features.cpp index a8b198f5a..93643668b 100644 --- a/src/build/prepare/features.cpp +++ b/src/build/prepare/features.cpp @@ -3,6 +3,7 @@ module mcpp.build.prepare; import :state; +import mcpp.libs.path_identity; import mcpp.build.prepare_inputs; @@ -1537,8 +1538,7 @@ static std::vector tool_upstream_keys(PrepareState& state, const st const mcpp::manifest::Manifest& manifest) { namespace fs = std::filesystem; std::vector keys; - std::error_code ec; - std::set seen{fs::weakly_canonical(root, ec)}; + std::set seen{mcpp::libs::path_identity::resolved(root)}; std::vector> work{{root, manifest}}; while (!work.empty()) { auto [dir, m] = std::move(work.back()); @@ -1552,11 +1552,11 @@ static std::vector tool_upstream_keys(PrepareState& state, const st keys.push_back(std::format("{}@{}", name, spec.version)); continue; } - const auto at = fs::weakly_canonical(dir / spec.path, ec); + const auto at = mcpp::libs::path_identity::given(dir / spec.path); auto dm = mcpp::manifest::load(at / "mcpp.toml", {.insideWorkspace = true}); keys.push_back(std::format("{}@{}+path.{}", name, dm ? dm->package.version : std::string{}, tree_content_digest(state, at).substr(0, 16))); - if (dm && seen.insert(at).second) work.emplace_back(at, std::move(*dm)); + if (dm && seen.insert(mcpp::libs::path_identity::resolved(at)).second) work.emplace_back(at, std::move(*dm)); } } std::ranges::sort(keys); @@ -2035,8 +2035,7 @@ static std::expected step6_dependency_build_programs(PrepareS // program runs in the `platform` phase, and states only the // platform's build, link and runner fields. const bool platformPhase = state.platform.active && state.platformData.plugin.set - && std::filesystem::weakly_canonical(pkg.root) - == std::filesystem::weakly_canonical(state.platform.root); + && mcpp::libs::path_identity::same(pkg.root, state.platform.root); if (platformPhase) bpEnv.phase = "platform"; bpEnv.languageModules = pkg.manifest.language.modules; bpEnv.ruleModules = pkg.manifest.buildConfig.ruleModules; diff --git a/src/build/prepare/graph.cpp b/src/build/prepare/graph.cpp index 699669d50..f4902b66d 100644 --- a/src/build/prepare/graph.cpp +++ b/src/build/prepare/graph.cpp @@ -3,6 +3,7 @@ module mcpp.build.prepare; import :state; +import mcpp.libs.path_identity; import mcpp.build.prepare_inputs; @@ -316,9 +317,7 @@ static std::string sourceRefOf( std::filesystem::path p = s.path; auto base = resolveRoot.empty() ? *state.root : resolveRoot; if (p.is_relative()) p = base / p; - std::error_code ec; - auto canon = std::filesystem::weakly_canonical(p, ec); - return (ec ? p : canon).lexically_normal().generic_string(); + return mcpp::libs::path_identity::key(mcpp::libs::path_identity::resolved(p)); } // "version": the constraint as authored; empty means unconstrained, // matching `addrset::unify`'s treatment of a bare-name claim. @@ -434,12 +433,10 @@ step4b_resolve_identity(PrepareState& state, WorklistItemCtx& ctx) { std::filesystem::path p = spec.path; auto base = item.resolveRoot.empty() ? *state.root : item.resolveRoot; if (p.is_relative()) p = base / p; - std::error_code ec; - auto canon = std::filesystem::weakly_canonical(p, ec); - if (ec) canon = p.lexically_normal(); for (auto const& [src, clone] : state.gitCloneBySource) { - auto rel = canon.lexically_relative(clone.root).generic_string(); - if (rel.empty() || rel.starts_with("..")) continue; + const auto beneath = mcpp::libs::path_identity::beneath(p, clone.root); + if (!beneath) continue; + const auto rel = beneath->generic_string(); bool mapped = rel == "."; if (!mapped) { if (auto rm = mcpp::manifest::load(clone.root / "mcpp.toml"); @@ -1407,7 +1404,7 @@ step4b_acquire_dependency_source(PrepareState& state, WorklistItemCtx& ctx) { dep_root = spec.path; auto base = item.resolveRoot.empty() ? *state.root : item.resolveRoot; if (dep_root.is_relative()) dep_root = base / dep_root; - dep_root = std::filesystem::weakly_canonical(dep_root); + dep_root = mcpp::libs::path_identity::given(dep_root); } else if (spec.isGit()) { // Git-based (M4 #5): clone into ~/.mcpp/git// and treat // as a path dep from there. diff --git a/src/build/prepare/manifest.cpp b/src/build/prepare/manifest.cpp index 0f01e9867..20372e06c 100644 --- a/src/build/prepare/manifest.cpp +++ b/src/build/prepare/manifest.cpp @@ -3,6 +3,7 @@ module mcpp.build.prepare; import :state; +import mcpp.libs.path_identity; import mcpp.build.prepare_inputs; @@ -235,9 +236,7 @@ select_workspace_members(PrepareState& state, const std::filesystem::path& wsRoo for (auto const& mp : selection) { const auto dir = (wsRoot / mp).lexically_normal(); - std::error_code canonEc; - auto canonical = std::filesystem::weakly_canonical(dir, canonEc); - if (canonEc) canonical = dir; + const auto canonical = mcpp::libs::path_identity::resolved(dir); state.selectedMembers[canonical] = mcpp::project::product_directory_name(all, mp); if (auto t = state.overrides.member_targets.find(mp); t != state.overrides.member_targets.end()) state.memberTargets[canonical] = t->second; diff --git a/src/build/prepare/plan.cpp b/src/build/prepare/plan.cpp index 52c0c9bcc..91722dd6e 100644 --- a/src/build/prepare/plan.cpp +++ b/src/build/prepare/plan.cpp @@ -4,6 +4,7 @@ module mcpp.build.prepare; import :state; +import mcpp.libs.path_identity; import mcpp.build.prepare_inputs; @@ -193,16 +194,11 @@ static std::expected step13_source_packages(PrepareState& sta // The selected members, in selection order (§15). if (state.workspacePlan()) { for (auto const& mp : state.selectedMemberPaths) { - std::error_code ec; - auto dir = std::filesystem::weakly_canonical(state.runtimeWorkspaceRoot / mp, ec); - if (ec) dir = (state.runtimeWorkspaceRoot / mp).lexically_normal(); + const auto dir = state.runtimeWorkspaceRoot / mp; for (std::size_t i = 1; i < state.packages.size(); ++i) { auto const& pkg = state.packages[i]; if (!pkg.selectedMember) continue; - std::error_code pec; - auto root = std::filesystem::weakly_canonical(pkg.root, pec); - if (pec) root = pkg.root.lexically_normal(); - if (root != dir) continue; + if (!mcpp::libs::path_identity::same(pkg.root, dir)) continue; ctx.workspaceMembers.push_back({ .name = pkg.manifest.package.namespace_.empty() ? pkg.manifest.package.name diff --git a/src/build/prepare/platform.cpp b/src/build/prepare/platform.cpp index dbd3750e7..0d2294135 100644 --- a/src/build/prepare/platform.cpp +++ b/src/build/prepare/platform.cpp @@ -17,6 +17,7 @@ module mcpp.build.prepare; import :state; +import mcpp.libs.path_identity; import std; import mcpp.build.prepare_inputs; @@ -905,7 +906,7 @@ std::expected step4b_apply_platform(PrepareState& state) { auto n = mcpp::pm::compat::resolve_package_name(pr.manifest.package.name, pr.manifest.package.namespace_); const bool byPath = !ref.spec.path.empty() - && fs::weakly_canonical(pr.root) == fs::weakly_canonical(fs::path(ref.spec.path)); + && mcpp::libs::path_identity::same(pr.root, fs::path(ref.spec.path)); if (byPath || n.shortName == state.platformPackageShortName) { found = ≺ break; } } if (!found) diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index dd2b56627..6a7b31e62 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -12,6 +12,7 @@ module mcpp.build.prepare:state; // primary interface. PrepareState needs BuildOverrides, BuildContext, // PlanNote, CacheMode, TcOrigin and ToolPurpose, all exported from there. import mcpp.build.prepare; +import mcpp.libs.path_identity; import mcpp.build.prepare_inputs; @@ -555,13 +556,11 @@ struct PrepareState { // included): its build program runs where a root's does (§15). std::function isWorkspaceMemberPackage; // The selected member whose directory is `dir`, when there is one: the - // key into `selectedMembers` and `memberCliForwards` (weakly canonical, - // so a symbolic link in the path names the same member). + // key into `selectedMembers` and `memberCliForwards` (its links followed, + // so a symbolic link in the path names the same member; SPEC-020). std::optional selectedMemberAt(const std::filesystem::path& dir) const { if (selectedMembers.empty()) return std::nullopt; - std::error_code ec; - auto key = std::filesystem::weakly_canonical(dir, ec); - if (ec) key = dir.lexically_normal(); + const auto key = mcpp::libs::path_identity::resolved(dir); if (selectedMembers.contains(key)) return key; return std::nullopt; } diff --git a/src/build/prepare/windows_resources.cpp b/src/build/prepare/windows_resources.cpp index c299b2e63..994899773 100644 --- a/src/build/prepare/windows_resources.cpp +++ b/src/build/prepare/windows_resources.cpp @@ -71,6 +71,7 @@ import mcpp.version_req; import mcpp.ui; import mcpp.log; import mcpp.bmi_cache; +import mcpp.libs.path_identity; namespace mcpp::build { @@ -679,12 +680,9 @@ std::string workspace_member_of(const PrepareState& state, const std::filesystem // One directory has more than one spelling (`/var` is `/private/var` on // macOS; a symlinked home; HOME and USERPROFILE on Windows): a member // reached through the other spelling is the same member. - if (rel.empty() || rel.starts_with("..")) { - std::error_code e1, e2; - const auto cr = std::filesystem::weakly_canonical(root, e1); - const auto cw = std::filesystem::weakly_canonical(state.runtimeWorkspaceRoot, e2); - if (!e1 && !e2) rel = relative(cr, cw); - } + if (rel.empty() || rel.starts_with("..")) + if (const auto beneath = mcpp::libs::path_identity::beneath(root, state.runtimeWorkspaceRoot)) + rel = beneath->generic_string(); if (rel.empty() || rel == "." || rel.starts_with("..")) return {}; for (auto const& m : state.wsManifest->workspace.members) { if (m == rel) return rel; diff --git a/src/build/resources.cppm b/src/build/resources.cppm index 2f143367a..bb8007f25 100644 --- a/src/build/resources.cppm +++ b/src/build/resources.cppm @@ -199,6 +199,7 @@ module :private; import mcpp.toolchain.triple; import mcpp.version_req; import mcpp.run; +import mcpp.libs.path_identity; namespace mcpp::build::resources { @@ -210,8 +211,7 @@ bool is_llvm_windres(const std::filesystem::path& p) { }; if (named(p)) return true; std::error_code ec; - const auto real = std::filesystem::canonical(p, ec); - return !ec && named(real); + return std::filesystem::exists(p, ec) && named(mcpp::libs::path_identity::resolved(p)); } std::vector system_include_dirs(const mcpp::toolchain::Toolchain& tc, diff --git a/src/build/runtime_validation.cppm b/src/build/runtime_validation.cppm index b051d617b..f953ec43a 100644 --- a/src/build/runtime_validation.cppm +++ b/src/build/runtime_validation.cppm @@ -584,7 +584,7 @@ std::vector linked_and_loaded_apart(const mcpp::build::BuildPlan& p return o.soname == facts->soname || o.artifact.filename() == facts->soname; }); if (loaded == resolution.objects.end() || under_binding(loaded->artifact) || under_binding(file)) continue; - if (mcpp::libs::path_identity::same(file, loaded->artifact).value_or(false)) continue; + if (mcpp::libs::path_identity::same(file, loaded->artifact)) continue; const auto a = digest(file), b = digest(loaded->artifact); if (a && b && *a == *b) continue; mcpp::build::refusal::record(mcpp::build::refusal::Code::RuntimeClosure); @@ -1021,8 +1021,7 @@ ArtifactVerdict artifact_identity_verdict( // the loader will reach, and a payload directory is normally reached // through a symlink that some later install can silently repoint. Reading // the declared path alone would confirm the promise against itself. - auto real = std::filesystem::weakly_canonical(artifact.path, ec); - if (ec) real = artifact.path; + const auto real = mcpp::libs::path_identity::resolved(artifact.path); // A path COMPONENT, not a substring: `0.1.1` must not satisfy `0.1.11`, // and a version appearing inside a file name is not the store directory @@ -1209,23 +1208,14 @@ check_symbol_provision(const mcpp::build::BuildPlan& plan, names = std::move(*symbols); return objectSymbolCache.emplace(object, std::move(names)).first->second; }; - // The installation the toolchain's compiler belongs to, canonical, for - // the second rule below: `/bin/`, whose C++ runtime - // library and module source both live under ``. + // The installation the toolchain's compiler belongs to, its links + // followed, for the second rule below: `/bin/`, whose C++ + // runtime library and module source both live under ``. std::filesystem::path toolchainRoot; - { - std::error_code ec; - auto compiler = std::filesystem::weakly_canonical(plan.toolchain.binaryPath, ec); - if (!ec && compiler.has_parent_path()) - toolchainRoot = compiler.parent_path().parent_path(); - } + if (!plan.toolchain.binaryPath.empty()) + toolchainRoot = mcpp::libs::path_identity::resolved(plan.toolchain.binaryPath).parent_path().parent_path(); auto in_toolchain = [&](const std::filesystem::path& file) { - if (toolchainRoot.empty()) return false; - std::error_code ec; - auto canonical = std::filesystem::weakly_canonical(file, ec); - if (ec) return false; - auto rel = canonical.lexically_relative(toolchainRoot); - return !rel.empty() && *rel.begin() != ".."; + return !toolchainRoot.empty() && mcpp::libs::path_identity::within(file, toolchainRoot); }; // For each provider in `resolution` that is a shared library of this // plan: the names defined by objects linked into both it and `image`. diff --git a/src/build/schedule/compiler_transaction.cppm b/src/build/schedule/compiler_transaction.cppm index f13b9ddc2..752526898 100644 --- a/src/build/schedule/compiler_transaction.cppm +++ b/src/build/schedule/compiler_transaction.cppm @@ -11,6 +11,7 @@ import mcpp.home; import mcpp.buildopt.keep; import mcpp.toolchain.fingerprint; import mcpp.home.files; // contention_point (SPEC-017 O12) +import mcpp.libs.path_identity; export namespace mcpp::build::schedule::transaction { namespace fs = std::filesystem; @@ -197,11 +198,13 @@ bool send(os::ipc::connection& connection,std::string_view bytes); class Witnesses { public: - static std::expected,std::string> start(const fs::path& generation) { - auto runtime=os::dirs::runtime();if(!runtime)return std::unexpected("no local directory for compiler registration"); + // `runtime` is the local directory the system gives for endpoints (mcpplibs.os + // `dirs::runtime`), an address (SPEC-020): the listener, the transport record, a + // controller's connection and the stop's wakeup reach it as the system gave it. + static std::expected,std::string> start(const fs::path& generation, + const fs::path& runtime) { auto result=std::unique_ptr(new Witnesses);result->generation_=generation; - std::error_code ec;result->directory_=fs::weakly_canonical(*runtime,ec); - if(ec)return std::unexpected("cannot identify the compiler registration directory"); + result->directory_=mcpp::libs::path_identity::given(runtime); result->name_="mc-"+mcpp::toolchain::hash_string(spelling(generation)); auto listener=os::ipc::listener::listen(result->directory_,result->name_); if(!listener)return std::unexpected("cannot create a compiler registration endpoint: "+listener.error().message()); @@ -411,11 +414,10 @@ Record read(const fs::path& path, std::string_view tag) { std::expected output_identity(const fs::path& path) { if(path.empty())return fs::path{}; - std::error_code ec;const auto absolute=fs::absolute(path,ec).lexically_normal(); - if(ec)return std::unexpected("cannot resolve a compiler output identity"); - const auto parent=fs::weakly_canonical(absolute.parent_path(),ec); - if(ec)return std::unexpected("cannot resolve a compiler output directory"); - return parent/absolute.filename(); + // An object (SPEC-020): a compiler names its output from its working directory, which a + // POSIX system reports with its links followed, and mcpp names it from its build directory. + const auto absolute=mcpp::libs::path_identity::given(path); + return mcpp::libs::path_identity::resolved(absolute.parent_path())/absolute.filename(); } std::string spelling(const fs::path& path) { return mcpp::home::spelling(path); } diff --git a/src/build/schedule/detach_codegen.cppm b/src/build/schedule/detach_codegen.cppm index 581dfeabf..ef1236b81 100644 --- a/src/build/schedule/detach_codegen.cppm +++ b/src/build/schedule/detach_codegen.cppm @@ -228,6 +228,8 @@ import mcpp.diag; import mcpp.home; import mcpp.invocation; import mcpp.toolchain.fingerprint; +import mcpp.libs.path_identity; +import mcpplibs.os.dirs; // --------------------------------------------------------------------------- @@ -819,28 +821,25 @@ RunScope::~RunScope() = default; namespace { // Where a configuration's compiler-run state lies: -// `/.mcpp/compiler-runs//`. -// The runs of an output directory, beside the project's target/, named after -// the directory's canonical spelling. -std::filesystem::path runs_root(const std::filesystem::path& work, const std::filesystem::path& canonical) { - return work / ".mcpp" / "compiler-runs" / mcpp::toolchain::hash_string(mcpp::home::spelling(canonical)); +// `/.mcpp/compiler-runs//`, +// beside the project's target/ (SPEC-020). The work directory is an address: it is +// opened as it was given. The output directory is an object: the slots of every +// spelling of it, and the outputs a compiler reports from its working directory, +// compare with links followed and the volume's spelling kept. +std::filesystem::path runs_root(const std::filesystem::path& work, const std::filesystem::path& output) { + return work / ".mcpp" / "compiler-runs" / mcpp::toolchain::hash_string(mcpp::home::spelling(output)); } struct RunsLocation { std::filesystem::path canonical, work, root; }; std::expected locate_runs(const std::filesystem::path& outputDir) { - std::error_code ec; - const auto spelled = std::filesystem::absolute(outputDir, ec).lexically_normal(); - if (ec) return std::unexpected("cannot identify the compiler-run output directory"); + const auto spelled = mcpp::libs::path_identity::given(outputDir); RunsLocation at; - at.canonical = std::filesystem::weakly_canonical(spelled, ec); - if (ec) return std::unexpected("cannot identify the compiler-run output directory"); - // Locate work BEFORE resolving output symlinks: target/ may point + at.canonical = mcpp::libs::path_identity::resolved(spelled); + // Locate work BEFORE following output symlinks: target/ may point // at a disposable cache. Locks remain beside target/, independently of - // clean and MCPP_HOME; the canonical output still identifies the slots. + // clean and MCPP_HOME; the output, links followed, still identifies the slots. const auto target = spelled.parent_path().parent_path(); - at.work = std::filesystem::weakly_canonical( - target.filename() == "target" ? target.parent_path() : spelled.parent_path(), ec); - if (ec) return std::unexpected("cannot identify the compiler-run work directory"); + at.work = target.filename() == "target" ? target.parent_path() : spelled.parent_path(); at.root = runs_root(at.work, at.canonical); return at; } @@ -987,7 +986,9 @@ std::expected RunScope::begin(const std::filesystem::path mcpplibs::os::fs::lock::kind::exclusive, false); if (!owner) return std::unexpected("cannot lock the compiler-run owner: " + owner.error().message()); state->owner.emplace(std::move(*owner)); - auto witnesses = transactions::Witnesses::start(state->generation); + const auto runtime = mcpplibs::os::dirs::runtime(); + if (!runtime) return std::unexpected("no local directory for compiler registration"); + auto witnesses = transactions::Witnesses::start(state->generation, *runtime); if (!witnesses) return std::unexpected(witnesses.error()); state->witnesses = std::move(*witnesses); const auto record = std::format("mcpp-compiler-run-v1\n{} {} {}\n", self->id, self->started_ns, compilerCap); diff --git a/src/config.cppm b/src/config.cppm index f50c1a000..b3833d60e 100644 --- a/src/config.cppm +++ b/src/config.cppm @@ -449,11 +449,8 @@ std::string index_location_named_twice(const std::filesystem::path& projectDir, std::string first, where; if (spec.is_local()) { const auto written = resolve_project_index_path(projectDir, spec); - std::error_code ec; - auto dir = std::filesystem::weakly_canonical(written, ec); - if (ec) dir = written; - // `/..` normalises to `/`, and a directory not yet - // present keeps that spelling through weakly_canonical. + auto dir = mcpp::libs::path_identity::resolved(written); + // `/..` normalises to `/`. if (!dir.has_filename() && dir.has_relative_path()) dir = dir.parent_path(); auto [it, fresh] = dirs.try_emplace(dir, name); if (fresh) continue; @@ -1463,17 +1460,7 @@ std::expected load_or_init( if (!std::filesystem::exists(mcpp::provider::open(make_xlings_env(cfg))->config_file(), ec)) return false; if (!cfg.xlingsHomeOverride.empty()) return !std::filesystem::equivalent(cfg.xlingsHomeOverride, cfg.registryDir, ec); - const auto real = mcpp::libs::path_identity::identity(cfg.registryDir); - const auto home = mcpp::libs::path_identity::identity(cfg.mcppHome); - if (!real || !home) { - mcpp::diag::degraded("config", std::format( - "whether the registry {} is a link to another home's could not be read", - mcpp::home::spelling(cfg.registryDir)), - "it is taken as this home's own, as its spelling says"); - return false; - } - const auto rel = real->lexically_relative(*home); - return rel.empty() || *rel.begin() == ".."; + return !mcpp::libs::path_identity::within(cfg.registryDir, cfg.mcppHome); }(); for (auto& r : cfg.indexRepos) { if (cfg.registryBorrowed || mcpp::provider::layout().is_provider_index(r.name)) continue; diff --git a/src/home/files.cppm b/src/home/files.cppm index 4452b6abd..add210e19 100644 --- a/src/home/files.cppm +++ b/src/home/files.cppm @@ -8,6 +8,7 @@ import std; import mcpplibs.os.fs; import mcpplibs.os.env; import mcpplibs.os.process; +import mcpp.libs.path_identity; export namespace mcpp::home { @@ -601,8 +602,7 @@ bool write_replacing(const std::filesystem::path& path, std::string_view text) { // A link (a config.toml a dotfile manager keeps elsewhere) is written // through: the file it names is replaced, and the link stays. auto file = path; - if (std::filesystem::is_symlink(path, ec)) - if (auto target = std::filesystem::canonical(path, ec); !ec) file = std::move(target); + if (std::filesystem::is_symlink(path, ec)) file = mcpp::libs::path_identity::resolved(path); std::filesystem::create_directories(file.parent_path(), ec); auto tmp = file; tmp += std::format(".{:x}.tmp", std::random_device{}()); diff --git a/src/modgraph/scanner.cppm b/src/modgraph/scanner.cppm index bd527df9d..4ec40916e 100644 --- a/src/modgraph/scanner.cppm +++ b/src/modgraph/scanner.cppm @@ -228,6 +228,7 @@ module :private; import mcpp.libs.code_text; import mcpp.modgraph.glob; +import mcpp.libs.path_identity; namespace mcpp::modgraph { @@ -539,11 +540,10 @@ std::vector expand_glob_one(const std::filesystem::path& std::sort(out.begin(), out.end()); // Dedup files reachable through more than one directory link (first // lexical occurrence wins). - std::error_code eec; - std::set seenFiles; + std::set seenFiles; out.erase(std::remove_if(out.begin(), out.end(), [&](const fs::path& p) { - auto c = fs::canonical(p, eec); - return !eec && !seenFiles.insert(c).second; + const auto o = mcpp::libs::path_identity::object(p); + return o && !seenFiles.insert(*o).second; }), out.end()); return out; } diff --git a/src/pack/distribution.cppm b/src/pack/distribution.cppm index bd974a365..0a4864e5a 100644 --- a/src/pack/distribution.cppm +++ b/src/pack/distribution.cppm @@ -245,6 +245,7 @@ import mcpp.pack.polyglot; // a polyglot file is refused by name (§8) import mcpp.toolchain.triple; // the system of a package's leg (§8) import mcpp.libs.toml; // a generated manifest quotes its keys (mcpp#911 B1) import mcpp.diag; // emit: a note about a package of two legs for one system +import mcpp.libs.path_identity; namespace mcpp::pack::distribution { @@ -904,13 +905,10 @@ std::expected place(const std::vector& members, const fs::create_symlink(fs::path(m.target), link, ec); if (ec) return std::unexpected(std::format("cannot link '{}': {}", link.string(), ec.message())); } - // And as the file system resolves them: every link ends under the root. - const auto root = fs::weakly_canonical(into, ec); + // And as objects, links followed: every link ends under the root. for (auto const& m : members) { if (m.kind != 'l') continue; - const auto real = fs::weakly_canonical(into / fs::path(m.path), ec); - const auto [r, _] = std::mismatch(root.begin(), root.end(), real.begin(), real.end()); - if (ec || r != root.end()) + if (!mcpp::libs::path_identity::within(into / fs::path(m.path), into)) return std::unexpected(std::format("the link '{}' points to '{}', outside the package", m.path, m.target)); } diff --git a/src/pack/pack.cppm b/src/pack/pack.cppm index 300053cc0..8c52b2bdd 100644 --- a/src/pack/pack.cppm +++ b/src/pack/pack.cppm @@ -672,6 +672,7 @@ import mcpp.toolchain.target_schema; import mcpp.toolchain.base; import mcpp.diag; import mcpp.runtime.elf; +import mcpp.libs.path_identity; namespace mcpp::pack { @@ -1292,33 +1293,19 @@ strip_program(const Plan& plan, const std::filesystem::path& staged) return {}; } -// IS `file` ONE OF `set`? Compared as file-system identity (after `..` and -// symbolic links are resolved), so the loader's spelling of a path and the -// plan's spelling of the same file agree. +// IS `file` ONE OF `set`? Compared as objects (SPEC-020), so the loader's +// spelling of a path and the plan's spelling of the same file agree. bool path_in(const std::filesystem::path& file, const std::vector& set) { - std::error_code ec; - const auto want = std::filesystem::weakly_canonical(file, ec); - for (auto const& p : set) { - std::error_code pec; - if (std::filesystem::weakly_canonical(p, pec) == want) return true; - } - return false; + return std::ranges::any_of(set, [&](auto const& p) { return mcpp::libs::path_identity::same(p, file); }); } // DOES `file` LIE UNDER ONE OF `dirs`? bool path_under(const std::filesystem::path& file, const std::vector& dirs) { - std::error_code ec; - const auto f = std::filesystem::weakly_canonical(file, ec); - for (auto const& d : dirs) { - std::error_code dec; - const auto rel = f.lexically_relative(std::filesystem::weakly_canonical(d, dec)); - if (!rel.empty() && *rel.begin() != "..") return true; - } - return false; + return std::ranges::any_of(dirs, [&](auto const& d) { return mcpp::libs::path_identity::within(file, d); }); } // SHOULD THE STAGED COPY OF `source` BE STRIPPED? (#649 E5) @@ -3781,9 +3768,8 @@ run(const Plan& plan, const mcpp::config::GlobalConfig& cfg) for (auto const& d : toBundle) { if (d.soname != loader) continue; std::error_code dec; - const auto payload = - std::filesystem::canonical(d.path, dec).parent_path().parent_path(); - if (dec) break; + if (!std::filesystem::exists(d.path, dec)) break; + const auto payload = mcpp::libs::path_identity::resolved(d.path).parent_path().parent_path(); auto copy_dir = [&](std::string_view sub) { const auto from = payload / "lib" / std::string(sub); std::error_code cec; diff --git a/src/pm/lock_io.cppm b/src/pm/lock_io.cppm index ba8c1c2f4..a11f32685 100644 --- a/src/pm/lock_io.cppm +++ b/src/pm/lock_io.cppm @@ -165,6 +165,7 @@ std::string index_package_digest(std::string_view indexNamespace, module :private; import mcpp.toolchain.fingerprint; // hash_string — the cross-platform FNV-1a +import mcpp.libs.path_identity; namespace mcpp::pm { @@ -392,11 +393,7 @@ std::expected write(const Lockfile& lock, const std::filesystem } // A linked lock stays a link: the file it names is the one replaced. auto file = path; - if (std::filesystem::is_symlink(path, ec)) { - auto resolved = std::filesystem::weakly_canonical(path, ec); - if (ec) return std::unexpected(LockError{std::format("cannot resolve '{}'", path.string())}); - file = resolved; - } + if (std::filesystem::is_symlink(path, ec)) file = mcpp::libs::path_identity::resolved(path); // A read-only lock is refused as writing it in place was: the rename below // would otherwise replace a file its owner made read-only. if (*prior) { diff --git a/src/pm/package_info.cppm b/src/pm/package_info.cppm index a4cc1de2e..b14c7673e 100644 --- a/src/pm/package_info.cppm +++ b/src/pm/package_info.cppm @@ -269,14 +269,11 @@ Sheet read_sheet(const fs::path& root, const mcpp::manifest::Manifest& m) { s.path = s.file.filename().generic_string(); } // The objects the root and the file name, links resolved: the file is read when it is inside. - const auto realRoot = mcpp::libs::path_identity::identity(root); - const auto resolved = mcpp::libs::path_identity::identity(s.file); - const auto rel = realRoot && resolved ? resolved->lexically_relative(*realRoot) : fs::path{}; - if (rel.empty() || *rel.begin() == ".." || !fs::is_regular_file(*resolved, ec)) { + if (!mcpp::libs::path_identity::within(s.file, root) || !fs::is_regular_file(s.file, ec)) { s.state = "absent"; return s; } - const auto& real = *resolved; + const auto& real = s.file; std::ifstream in(real, std::ios::binary); std::string bytes(static_cast(std::min(fs::file_size(real, ec), kSheetBytes)), '\0'); in.read(bytes.data(), static_cast(bytes.size())); diff --git a/src/pm/patch.cppm b/src/pm/patch.cppm index e996b7e33..59b3c49b6 100644 --- a/src/pm/patch.cppm +++ b/src/pm/patch.cppm @@ -58,6 +58,7 @@ std::string variant_dir_name(std::string_view version, std::string_view digest); module :private; import mcpp.pack.distribution; // sha256 +import mcpp.libs.path_identity; namespace mcpp::pm::patch { @@ -335,10 +336,9 @@ std::expected materialize(const fs::path& source, // directory, or files in it, as links into another store; a link copied as // a link would have the patch written through it into the source every // other build reads. Links are followed, so the variant's tree is its own. - const auto real = fs::weakly_canonical(source, ec); - if (ec) return std::unexpected(std::format("the source '{}' cannot be resolved: {}", - source.string(), ec.message())); - fs::copy(real, work, fs::copy_options::recursive, ec); + if (!fs::exists(source, ec)) + return std::unexpected(std::format("the source '{}' cannot be resolved: it does not exist", source.string())); + fs::copy(mcpp::libs::path_identity::resolved(source), work, fs::copy_options::recursive, ec); if (ec) return std::unexpected(std::format("the source '{}' cannot be copied for its variant: {}", source.string(), ec.message())); for (auto const& p : patches) { diff --git a/src/project.cppm b/src/project.cppm index 4c1caa6b4..b1f53045c 100644 --- a/src/project.cppm +++ b/src/project.cppm @@ -368,6 +368,7 @@ module :private; import mcpp.ui; import mcpp.diag; +import mcpp.libs.path_identity; namespace mcpp::project { @@ -430,7 +431,7 @@ void merge_workspace_deps(mcpp::manifest::Manifest& member, if (!spec.path.empty() && !wsRoot.empty()) { std::filesystem::path p(spec.path); if (p.is_relative()) { - spec.path = std::filesystem::weakly_canonical(wsRoot / p).string(); + spec.path = mcpp::libs::path_identity::key(wsRoot / p); } } spec.inheritWorkspace = false; @@ -475,15 +476,8 @@ bool is_workspace_member(const mcpp::manifest::Manifest& workspace, const std::filesystem::path& wsRoot, const std::filesystem::path& candidate) { if (!workspace.workspace.present) return false; - std::error_code ec; - auto want = std::filesystem::weakly_canonical(candidate, ec); - if (ec) { ec.clear(); want = candidate.lexically_normal(); } - for (auto const& m : workspace.workspace.members) { - auto member = std::filesystem::weakly_canonical(wsRoot / m, ec); - if (ec) { ec.clear(); member = (wsRoot / m).lexically_normal(); } - if (member == want) return true; - } - return false; + return std::ranges::any_of(workspace.workspace.members, + [&](auto const& m) { return mcpp::libs::path_identity::same(wsRoot / m, candidate); }); } void inherit_workspace_package(mcpp::manifest::Manifest& member, diff --git a/src/provider/xlings/xlings.cpp b/src/provider/xlings/xlings.cpp index edecb58fd..41326c95e 100644 --- a/src/provider/xlings/xlings.cpp +++ b/src/provider/xlings/xlings.cpp @@ -26,6 +26,7 @@ import mcpp.toolchain.platform; // ...for this host import nlohmann.json; import mcpplibs.os.fs; import mcpplibs.os.env; +import mcpp.libs.path_identity; namespace libc = mcpplibs::mwrap::libc::macros; @@ -1166,10 +1167,9 @@ std::filesystem::path state_dir(const Env& env) { // in the project's directory let it collide with an install of another // project, or of none, on Windows (e2e images/1033, run 43632995462). One // turn per home orders every writer of either state. - const auto dir = env.home / "subos"; - std::error_code ec; - auto real = std::filesystem::weakly_canonical(dir, ec); - return ec ? dir : real; + // The lock lies in the directory, so every spelling of one home takes the + // same lock (SPEC-020): the address is the given spelling. + return mcpp::libs::path_identity::given(env.home / "subos"); } namespace { diff --git a/src/runtime/binding.cppm b/src/runtime/binding.cppm index f6f21f96b..97e1fd706 100644 --- a/src/runtime/binding.cppm +++ b/src/runtime/binding.cppm @@ -223,6 +223,7 @@ module :private; import nlohmann.json; import mcpp.toolchain.platform; import mcpp.provider.select; +import mcpp.libs.path_identity; namespace mcpp::runtime { @@ -340,15 +341,10 @@ std::filesystem::path subos_path( std::optional managed_glibc_identity( const std::filesystem::path& libraryDir, const std::filesystem::path& xlingsRoot) { - std::error_code bec, lec; const auto& layout = mcpp::provider::layout(); - auto base = std::filesystem::weakly_canonical( - layout.tool_in(layout.store_of_home(xlingsRoot), "glibc"), bec); - auto real = std::filesystem::weakly_canonical(libraryDir, lec); - if (bec || lec || base.empty() || real.empty()) return std::nullopt; - - auto relative = real.lexically_relative(base); - if (relative.empty() || relative.is_absolute()) return std::nullopt; + const auto beneath = mcpp::libs::path_identity::beneath(libraryDir, layout.tool_in(layout.store_of_home(xlingsRoot), "glibc")); + if (!beneath) return std::nullopt; + const auto& relative = *beneath; std::vector parts; for (auto const& part : relative) parts.push_back(part.string()); if (parts.size() != 2 || (parts[1] != "lib" && parts[1] != "lib64")) @@ -511,9 +507,7 @@ resolve_runtime_binding( std::error_code lec; auto libc = candidate / "libc.so.6"; if (!std::filesystem::is_regular_file(libc, lec)) continue; - auto realLibc = std::filesystem::canonical(libc, lec); - auto libDir = lec ? candidate.lexically_normal() - : realLibc.parent_path(); + auto libDir = mcpp::libs::path_identity::resolved(libc).parent_path(); out.libraryDirs.push_back(libDir); if (auto physical = detail::managed_glibc_identity( libDir, out.subosDir.parent_path().parent_path())) { @@ -532,8 +526,7 @@ resolve_runtime_binding( } std::sort(loaders.begin(), loaders.end()); if (loaders.size() == 1) { - auto realLoader = std::filesystem::canonical(loaders.front(), lec); - out.loader = lec ? loaders.front().lexically_normal() : realLoader; + out.loader = mcpp::libs::path_identity::resolved(loaders.front()); } break; } diff --git a/src/runtime/elf.cppm b/src/runtime/elf.cppm index 90d8b0b63..3221101fc 100644 --- a/src/runtime/elf.cppm +++ b/src/runtime/elf.cppm @@ -11,6 +11,7 @@ import std; import mcpplibs.os.platform; import mcpp.toolchain.platform; import mcpp.runtime.binding; +import mcpp.libs.path_identity; export namespace mcpp::runtime::elf { @@ -502,9 +503,7 @@ void append_path_list(std::vector& out, std::string_view value) { std::filesystem::path comparable_path(const std::filesystem::path& path) { if (path.empty()) return {}; - std::error_code ec; - auto canonical = std::filesystem::weakly_canonical(path, ec); - return ec ? path.lexically_normal() : canonical; + return mcpp::libs::path_identity::resolved(path); } bool same_path(const std::filesystem::path& lhs, @@ -1682,8 +1681,7 @@ DlopenSurfaceReport inspect_dlopen_surface( std::map> libraries; for (auto const& [name, path] : entries) { - auto real = std::filesystem::weakly_canonical(path, ec); - if (ec) { real = path; ec.clear(); } + const auto real = mcpp::libs::path_identity::resolved(path); auto it = libraries.find(real); if (it == libraries.end()) libraries.emplace(real, std::pair{name, path}); else if (name.size() < it->second.first.size()) diff --git a/src/toolchain/base_probe.cppm b/src/toolchain/base_probe.cppm index 5764d7ba4..b7da283d0 100644 --- a/src/toolchain/base_probe.cppm +++ b/src/toolchain/base_probe.cppm @@ -102,6 +102,7 @@ import mcpp.toolchain.linkmodel; import mcpp.runtime.elf; import mcpp.toolchain.apple_sdk; import mcpp.invocation; +import mcpp.libs.path_identity; namespace mcpp::toolchain::base { @@ -159,8 +160,9 @@ void mix(std::uint64_t& h, std::string_view s) { void stamp(std::uint64_t& h, const fs::path& p) { std::error_code ec; mix(h, p.generic_string()); - auto real = fs::canonical(p, ec); - if (ec) { mix(h, "absent"); return; } + if (!fs::exists(p, ec)) { mix(h, "absent"); return; } + // The file a link names is evidence too: a loader link moved to another file is another base. + const auto real = mcpp::libs::path_identity::resolved(p); mix(h, real.generic_string()); mix(h, std::format("{}", static_cast(fs::file_size(real, ec)))); auto t = fs::last_write_time(real, ec); @@ -238,10 +240,7 @@ GnuMeasurement measure_gnu(const std::vector& driverBase, : (fs::exists(d / "libc.so", ec) || fs::exists(d / "libc.a", ec)); if (hasLibc && std::ranges::find(m.runtimeDirs, d) == m.runtimeDirs.end()) { // A symlinked `lib64 -> usr/lib64` is one directory. - auto real = fs::canonical(d, ec); - bool dup = false; - for (auto const& seen : m.runtimeDirs) - if (!ec && fs::canonical(seen, ec) == real) dup = true; + const bool dup = std::ranges::any_of(m.runtimeDirs, [&](auto const& seen) { return mcpp::libs::path_identity::same(seen, d); }); if (!dup) m.runtimeDirs.push_back(d); } } @@ -269,9 +268,8 @@ RuntimeFloor compiler_runtime_glibc_floor(const std::vector& driver auto p = detail::print_file_name(driverBase, name); if (p.empty()) continue; std::error_code ec; - auto real = fs::canonical(p, ec); - if (ec) continue; - auto facts = mcpp::runtime::elf::inspect_elf_runtime(real); + if (!fs::exists(p, ec)) continue; + auto facts = mcpp::runtime::elf::inspect_elf_runtime(mcpp::libs::path_identity::resolved(p)); if (!facts) continue; auto v = highest_glibc(facts->requiredGlibcVersions); if (!v.empty() && (best.version.empty() || compare_versions(v, best.version) > 0)) diff --git a/src/toolchain/clang.cppm b/src/toolchain/clang.cppm index b76bd330a..71f29f91b 100644 --- a/src/toolchain/clang.cppm +++ b/src/toolchain/clang.cppm @@ -167,9 +167,7 @@ std::optional find_libcxx_std_module_source( std::filesystem::path p = *src; if (p.is_relative()) p = manifestPath.parent_path() / p; - std::error_code ec; - auto canon = std::filesystem::weakly_canonical(p, ec); - if (!ec) p = canon; + p = mcpp::libs::path_identity::given(p); if (std::filesystem::exists(p) && take(p, "-print-library-module-manifest-path")) return p; } } @@ -203,9 +201,7 @@ std::optional find_libcxx_std_module_source( !answer.empty()) { std::filesystem::path lib(answer); if (take(lib, "--print-file-name=libc++.a")) { - std::error_code ec; - auto dir = std::filesystem::weakly_canonical(lib.parent_path(), ec); - if (ec) dir = lib.parent_path(); + auto dir = mcpp::libs::path_identity::resolved(lib.parent_path()); for (int up = 0; up < 4 && !dir.empty(); ++up) { auto cand = dir / "share" / "libc++" / "v1" / "std.cppm"; if (std::filesystem::exists(cand) && mcpp::toolchain::inside_roots(cand, roots)) return cand; @@ -228,8 +224,9 @@ std::vector tree_roots(const Toolchain& tc) { std::vector roots{tree}; const auto rel = tc.binaryPath.lexically_normal().lexically_relative(tree.lexically_normal()); if (!rel.empty() && *rel.begin() != "..") - if (auto real = mcpp::libs::path_identity::identity(tc.binaryPath)) - if (auto resolved = real->parent_path().parent_path(); resolved != tree) roots.push_back(resolved); + if (auto resolved = mcpp::libs::path_identity::resolved(tc.binaryPath).parent_path().parent_path(); + resolved != tree) + roots.push_back(resolved); return roots; } diff --git a/src/toolchain/post_install.cppm b/src/toolchain/post_install.cppm index ec28c5c15..280160ca0 100644 --- a/src/toolchain/post_install.cppm +++ b/src/toolchain/post_install.cppm @@ -139,6 +139,7 @@ import mcpp.toolchain.linkmodel; import mcpp.ui; import mcpp.provider; import mcpp.provider.select; +import mcpp.libs.path_identity; namespace mcpp::toolchain { @@ -228,20 +229,17 @@ bool starts_through_its_home(const std::filesystem::path& root) { const auto& layout = mcpp::provider::layout(); const auto store = layout.store_of(root); if (store.empty()) return false; - // Both sides as the filesystem resolves them: a home reached through a - // link (a borrowed registry) names its loader by either spelling. + // Both sides as objects: a home reached through a link (a borrowed + // registry) names its loader by either spelling. + const auto home = layout.home_of_store(store); + if (home.empty()) return false; std::error_code ec; - const auto home = std::filesystem::weakly_canonical(layout.home_of_store(store), ec); - if (ec || home.empty()) return false; for (auto it = std::filesystem::directory_iterator(root / "bin", ec); !ec && it != std::filesystem::directory_iterator(); it.increment(ec)) { if (it->is_symlink(ec) || !it->is_regular_file(ec)) continue; const auto interp = read_elf_interp(it->path()); if (interp.empty()) continue; - std::error_code iec; - const auto loader = std::filesystem::weakly_canonical(std::filesystem::path(interp), iec); - const auto rel = (iec ? std::filesystem::path(interp) : loader).lexically_relative(home); - return !rel.empty() && *rel.begin() != ".."; + return mcpp::libs::path_identity::within(std::filesystem::path(interp), home); } return false; } @@ -322,8 +320,8 @@ std::string baked_runtime_binding(const std::filesystem::path& compilerBin) { // payload before reading a version off it. A view path has no version // component at all, and parsing one yields nothing. std::error_code cec; - if (auto real = std::filesystem::canonical(loader, cec); !cec) - loader = real.string(); + if (std::filesystem::exists(loader, cec)) + loader = mcpp::libs::path_identity::resolved(loader).string(); // .../xim-x-glibc//lib64/ld-linux-... — the version is the // grandparent of the lib dir. auto dir = std::filesystem::path(loader).parent_path(); // lib64 diff --git a/src/toolchain/probe.cppm b/src/toolchain/probe.cppm index 65e39dc24..7d36cd4fb 100644 --- a/src/toolchain/probe.cppm +++ b/src/toolchain/probe.cppm @@ -484,19 +484,13 @@ std::string ask_driver(const std::filesystem::path& compiler, const std::vector< bool inside_roots(const std::filesystem::path& file, const std::vector& roots) { if (roots.empty()) return true; namespace pi = mcpp::libs::path_identity; - auto spelled = [](const std::filesystem::path& p) { return pi::given(p); }; - // An identity that cannot be read (an ancestor this process may not open) - // is compared as spelled. - auto resolved = [](const std::filesystem::path& p) { return pi::identity(p).value_or(pi::given(p)); }; - auto under = [](const std::filesystem::path& f, const std::filesystem::path& r) { - const auto rel = f.lexically_relative(r); - return !rel.empty() && *rel.begin() != ".."; - }; - const auto fileSpelled = spelled(file), fileResolved = resolved(file); - for (auto const& root : roots) - if (!root.empty() && (under(fileSpelled, spelled(root)) || under(fileResolved, resolved(root)))) - return true; - return false; + // By name, then as objects (SPEC-020): a driver may name its file by either spelling. + const auto spelled = pi::given(file); + return std::ranges::any_of(roots, [&](auto const& root) { + if (root.empty()) return false; + const auto rel = spelled.lexically_relative(pi::given(root)); + return (!rel.empty() && *rel.begin() != "..") || pi::within(file, root); + }); } std::expected run_capture(const std::vector& argv, diff --git a/src/toolchain/registry.cppm b/src/toolchain/registry.cppm index 9df2fc2c2..2a53bd3f8 100644 --- a/src/toolchain/registry.cppm +++ b/src/toolchain/registry.cppm @@ -466,6 +466,7 @@ import mcpp.toolchain.target_schema; import mcpp.toolchain.target_rows; import mcpp.toolchain.payloads; import mcpp.toolchain.target_select; +import mcpp.libs.path_identity; namespace mcpp::toolchain { @@ -1078,20 +1079,17 @@ payload_default_runner(const std::filesystem::path& compilerPath) { // PAYLOAD. The layout is `//`, so the store is // the root's grandparent, and a dependency's program lives beside it. // - // Compared on canonical paths, because a store reached through a symbolic - // link is still that store; and IGNORED rather than refused when it is + // Compared as objects (SPEC-020), because a store reached through a + // symbolic link is still that store; and IGNORED rather than refused when it is // outside, because where a store lives is a property of this machine and // not a defect in the file. What the rule removes is the one case that // matters: a payload choosing a host interpreter. - std::error_code rootEc, runnerEc; - const auto store = std::filesystem::weakly_canonical(d.root, rootEc) - .parent_path().parent_path(); - const auto program = std::filesystem::weakly_canonical( - std::filesystem::path(d.runner), runnerEc); - if (rootEc || runnerEc || store.empty()) return {}; - const auto rel = program.lexically_relative(store); - if (rel.empty() || rel == "." || *rel.begin() == "..") return {}; - return { program.string() }; + const auto store = mcpp::libs::path_identity::resolved(d.root).parent_path().parent_path(); + if (store.empty()) return {}; + const auto program = std::filesystem::path(d.runner); + const auto rel = mcpp::libs::path_identity::beneath(program, store); + if (!rel || *rel == ".") return {}; + return { mcpp::libs::path_identity::given(program).string() }; } std::filesystem::path payload_frontend_dir(const std::filesystem::path& payloadRoot, diff --git a/tests/unit/test_compiler_transaction.cpp b/tests/unit/test_compiler_transaction.cpp index d5ec6a84d..941c332be 100644 --- a/tests/unit/test_compiler_transaction.cpp +++ b/tests/unit/test_compiler_transaction.cpp @@ -498,3 +498,45 @@ UTest a_closed_channel_ends_the_wait{"CompilerTransaction/AClosedChannelEndsTheW expect(!answer); owner.join(); }}; + +// THE REGISTRATION DIRECTORY IS AN ADDRESS (SPEC-020, mcpp#1049): given through a link, the +// listener, the transport record, a controller's connection and the stop reach it by that +// spelling, not by the link's target. The directory is short: a local endpoint's name has a +// length limit of its own, which this case does not measure. +UTest registration_keeps_the_given_runtime_spelling{"CompilerTransaction/RegistrationKeepsTheGivenRuntimeSpelling", [] { + const auto root=fs::temp_directory_path()/std::format("mcr-{:08x}",std::random_device{}()); + fs::create_directories(root/"generation");fs::create_directories(root/"r"); + std::error_code ec;fs::create_directory_symlink(root/"r",root/"a",ec); + if(ec){fs::remove_all(root,ec);skip("no privilege for a directory link here");} + const auto given=(root/"a").lexically_normal(); + { + auto witnesses=tx::Witnesses::start(root/"generation",given); + if(auto&& ok=expect(fatal(bool(witnesses)));!ok)ok<has_value()&&(**transport).size()==2u)); + expect(eq(tx::named((**transport)[0]),given)); + auto connection=mcpplibs::os::ipc::connection::connect(tx::named((**transport)[0]),(**transport)[1]); + if(auto&& ok=expect(fatal(bool(connection)));!ok)ok<stop(); + expect(!(*witnesses)->failed()); + } + fs::remove_all(root,ec); +}}; + +// A COMPILER'S OUTPUT IS AN OBJECT (SPEC-020): named through a linked directory -- a POSIX +// working directory is reported with its links followed -- it is the output mcpp names. +UTest an_output_through_a_link_is_the_same_output{"CompilerTransaction/AnOutputThroughALinkIsTheSameOutput", [] { + const auto root=fs::temp_directory_path()/std::format("mco-{:08x}",std::random_device{}()); + fs::create_directories(root/"real"/"obj"); + std::error_code ec;fs::create_directory_symlink(root/"real",root/"link",ec); + if(ec){fs::remove_all(root,ec);skip("no privilege for a directory link here");} + const auto viaLink=tx::output_identity(root/"link"/"obj"/"x.o"); + const auto viaReal=tx::output_identity(root/"real"/"obj"/"x.o"); + expect(fatal(viaLink&&viaReal)); + expect(eq(*viaLink,*viaReal)); + fs::remove_all(root,ec); +}}; From 0c9d13006b35f68d4353ddcddc2de852e6adb8cf Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:29:11 +0900 Subject: [PATCH 05/18] SPEC-020 states the uses of a path; docs/25 and docs/05 describe every path by its given spelling --- AGENTS.md | 5 +- docs/05-dependencies.md | 2 +- docs/25-home-indices-and-store.md | 33 +++++----- docs/specs/README.md | 1 + docs/specs/paths.md | 94 ++++++++++++++++++++++++++++ docs/zh/05-dependencies.md | 2 +- docs/zh/25-home-indices-and-store.md | 14 +++-- 7 files changed, 128 insertions(+), 23 deletions(-) create mode 100644 docs/specs/paths.md diff --git a/AGENTS.md b/AGENTS.md index 5b5589200..be2cdeefb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ linked document holds. | Tree | States | Rule | |---|---|---| | [`docs/`](docs/README.md), [`docs/zh/`](docs/zh/README.md) | how to use what mcpp implements | describes the current implementation only; English and Chinese stay in parity | -| [`docs/specs/`](docs/specs/README.md) | semantics and constraints (SPEC-001 to SPEC-016) | RFC 2119 wording; every clause carries its implementation status and the version it holds from | +| [`docs/specs/`](docs/specs/README.md) | semantics and constraints (SPEC-001 to SPEC-020) | RFC 2119 wording; every clause carries its implementation status and the version it holds from | | [`.agents/docs/`](.agents/docs/README.md) | design records: measurements, decisions, what was refuted | front matter `subject`, `status`; the index is generated (`.github/tools/gen_agents_index.py`) | | [`.agents/skills/`](.agents/skills/) | procedures: [contributing](.agents/skills/mcpp-contributing/SKILL.md), [docs style](.agents/skills/mcpp-docs-style/SKILL.md), [release](.agents/skills/mcpp-release/SKILL.md), [usage](.agents/skills/mcpp-usage/SKILL.md) (a pointer to [`docs/mcpp-skills/`](docs/mcpp-skills/mcpp/SKILL.md), the sheets `--agent-skill-doc` prints) | ordered steps with criteria | | [`CHANGELOG.md`](CHANGELOG.md) | one section per release; release.yml publishes it as the release notes | English, Keep a Changelog | @@ -69,6 +69,9 @@ CHANGELOG in the same pull request. - A comment states why, from what was measured, not what the next line does. - A path from a directory walk is never narrowed with `.string()`: compare as `path`, hash `u8string()`, hand to tools through `try_narrow` ([contributing](.agents/skills/mcpp-contributing/SKILL.md)). +- A path is opened and handed on under the spelling it was given; whether two paths are one + object, and links followed, are asked of `mcpp.libs.path_identity`, and a physical spelling + is printed in a diagnostic only ([SPEC-020](docs/specs/paths.md); `check_path_identity.sh`). ## 5. Build and test diff --git a/docs/05-dependencies.md b/docs/05-dependencies.md index ec79185a0..d845742b1 100644 --- a/docs/05-dependencies.md +++ b/docs/05-dependencies.md @@ -221,7 +221,7 @@ requester of the same identity gets. | any | same kind, same reference | Unchanged: the second declaration becomes an edge to the identity already resolved. Nothing is reported. | | `version` | `version`, a different constraint | The two constraints are AND-combined by SemVer, as above; an unsatisfiable pair is refused, naming both constraints and both requesters. | | `git` | `git`, a different `rev`/`tag`/`branch` | The root's declaration wins when the root is one of the two requesters; otherwise the declaration resolved first wins. A `dependency/source-override` warning names both requesters and both references, states which one is used and why, and how to take the other. This is never silent. | -| `path` | `path`, a different directory | The same rule and the same warning as the row above, compared by canonical absolute directory rather than by git reference. | +| `path` | `path`, a different directory | The same rule and the same warning as the row above, compared by the absolute directory with its links followed rather than by git reference ([SPEC-020](specs/paths.md) §4). | | a root `path` or `git` declaration | a dependency's `git` or `version` declaration (a kind clash) | The root's declaration wins, with the same warning. When the losing declaration is a `version` requirement, it is checked against the `[package] version` of the root's resolved checkout; a violated requirement is refused, naming the pin, the requester and the requirement. The index is not asked to select or pin a request the root has answered, so the root's checkout serves a version no index carries yet (2026.10.26.2+). | | a dependency's `path`/`git` declaration | another dependency's declaration of a different kind (a kind clash, and neither party is the root) | Refused: "requested as both a … dep … and a … dep …. Pick one." The message adds one sentence: declare the identity in the root to settle it. | diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index 5bf6f80f6..3c45152a7 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -98,20 +98,25 @@ For a redirected home it names the effective target before resetting it. `--system self init --home` is refused. The exact selection and persistence rules are in [SPEC-010](specs/home-initialization.md). -**The home keeps the spelling it is given (2026.11.27.1+).** A home named -through a symbolic link is used under that name: mcpp makes the path absolute -and lexically normal, and opens files and starts programs under it, so `mcpp -self env` and every path handed to a tool show the directory the user named. -The physical path decides only whether two paths are one object -- a home -borrowed from an upstream, a project inside the home. When that cannot be -decided, because a parent directory is not accessible, the comparison falls -back to the spelling and the build reports it as degraded, naming the -decision. A key built from a path (a cache entry's user, a plan's work -directory) uses the spelling too: two spellings of one tree make two keys, -which costs one more entry and gives no wrong result. Before, the home was -resolved to its physical path when it was read (mcpp#1024). A check in CI holds -the number of physical-path calls outside the one identity function to a -baseline that only shrinks. +**A path keeps the spelling it is given (home 2026.11.27.1+, every path +2026.12.7.1+).** A home, a project, a path dependency, a toolchain tree or a +directory the system reports (the temporary and runtime directories) named +through a symbolic link, a junction, a `subst` drive or an AppContainer's +drive letter is used under that name: mcpp makes the path absolute and +lexically normal, and opens files and starts programs under it, so `mcpp self +env` and every path handed to a tool show the directory the user named. Whether +two paths are one object -- a home borrowed from an upstream, a project inside +the home, two declarations of one path dependency -- is answered with their +links followed and then by the objects' identities, which the system reads +without opening any parent directory by another spelling. When an identity +cannot be read, the question is decided by the spelling and the build reports +it as degraded, naming the question. A key built from a path (a cache entry's +user, a plan's work directory) uses the spelling: two spellings of one tree +make two keys, which costs one more entry and gives no wrong result. A process +granted a tree through a drive alias whose parents it may not open builds as +any other process does. [SPEC-020](specs/paths.md) states the rules; a check in +CI holds the calls that resolve a path to its physical spelling to the one +module that prints it in a diagnostic. ### Initialization and network diagnosis (2026.10.19.1+) diff --git a/docs/specs/README.md b/docs/specs/README.md index 34f4f7d71..e0945abfa 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -49,6 +49,7 @@ | [SPEC-017](test.md) | mcpp 测试规范:测试程序、测试协议、记录、存储、启动描述与框架声明;基础能力 B1–B6 与可选能力 O1–O12 | 评审中 v2.7 | 2026-12-04 | mcpp >= 2026.11.8.1;逐条标注;B5、B6 的新键、O3 的运行器一侧、O8 mcpp >= 2026.11.10.1;O9 mtest >= 0.6.0;O10 mcpp >= 2026.11.13.1;O11、O12 与 P5.6 mcpp >= 2026.11.21.1;B1 第 8 条 mcpp >= 2026.12.4.1 | | [SPEC-018](module-rebuilds.md) | 模块的重编译:按 BMI 内容截断,GCC 的时间戳与行映射,`bmi_cutoff`,构建目录的记录 | 评审中 v1.2 | 2026-11-27 | mcpp >= 2026.11.17.2;§1 第 6 条 mcpp >= 2026.11.27.1 | | [SPEC-019](build-optimizations.md) | 构建优化:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | 评审中 v1.4 | 2026-12-06 | mcpp >= 2026.11.17.2;§5、§9 的新增自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.1;`batch-fetch`、`plan-locks` 与 §9 R4 自 2026.12.4.1;§5 第 9 条自 2026.12.6.1 | +| [SPEC-020](paths.md) | 路径:地址、保存的键、对象、跟随链接;根目录表;工具由地址指名 | 评审中 v1.0 | 2026-12-07 | mcpp >= 2026.12.7.1 | ## 文档约定 diff --git a/docs/specs/paths.md b/docs/specs/paths.md new file mode 100644 index 000000000..33444d111 --- /dev/null +++ b/docs/specs/paths.md @@ -0,0 +1,94 @@ +# SPEC-020: 路径 + +| 项 | 值 | +|---|---| +| 规范编号 | SPEC-020 | +| 标题 | 路径的用途:地址、保存的键、对象、跟随链接;根目录表;工具由地址指名 | +| 状态 | 评审中 v1.0 | +| 版本 | 1.0 | +| 最后修改 | 2026-12-07 | +| 对应实现 | mcpp >= 2026.12.7.1;§2 的 home 部分 mcpp >= 2026.11.27.1 | +| 相关设计文档 | `.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md`;`.agents/docs/2026-11-27-stated-closure-single-reader-and-feature-designs.md` §4.6 | +| 相关 issue | #1024、#1032、#1048、#1049、#1050、#1053 | +| 使用文档 | [25 — home、索引与 store](../zh/25-home-indices-and-store.md) 的路径一节;[20 — 工具链](../zh/20-toolchains.md) 的链接器一节 | + +用语按 RFC 2119:**必须 / 禁止**为强制,**应当**为建议,**可以**为可选。 + +## 0. 这份规范存在的原因 + +同一个目录可以有多种拼写:符号链接与目录联接、`subst` 盘与映射盘、AppContainer 中的盘符、macOS 的 `/var` 与 +`/private/var`、Windows 的 8.3 短名。在进程可以读一切祖先目录的环境中,把路径解析为物理路径不会出错;在只授予 +部分目录的环境中(openkal 的 preopen、AppContainer 与 LPAC、以符号链接拼成的沙箱),授权附着在路线上而不在对象上, +物理路径打不开。一个值同时承担几种用途时,这种环境中必有一种用途失败。本规范为路径的每种用途规定一个机制。 + +## 1. 四种用途 + +| 用途 | 含义 | 机制 | +|---|---|---| +| 地址 | 打开一个文件、交给一个程序、写入一条记录 | 给定的拼写(§2) | +| 保存的键 | 缓存条目、记录中的键 | 给定拼写的文本(§3) | +| 对象 | 两个路径是否同一个对象;一个对象是否在某目录下;内存中的路径集合与映射 | §4 | +| 跟随链接 | 所要的是链接指向的文件 | §5 | + +1. 每一处路径的使用**必须**属于上表的一种用途,并使用该用途的机制。 +2. 路径的物理拼写不属于任何一种用途;它**只能**出现在诊断文本中(§7)。 + +## 2. 地址 + +1. 用户、环境或系统给出的路径(参数、环境变量、清单、当前目录、系统报告的临时目录与运行时目录)**必须**以给定的 + 拼写打开并交给程序:绝对化与词法规范化,不解析链接与别名。 +2. 派生路径**必须**是“根 / 相对部分”的词法结果;根只有三种来源:给定的、系统报告的、mcpp 自己写的记录。 +3. mcpp 写入的记录**必须**只含地址。 +4. 互斥**必须**由对象内部的文件锁保证,经地址打开;同一对象的任何拼写打开的是同一个锁文件,正确性因此不依赖 + §4 的判断。 + +## 3. 保存的键 + +1. 以路径构成的保存的键(缓存条目的使用者、计划的工作目录)**必须**是地址的 UTF-8 文本。 +2. 同一对象的两种拼写得到两个键:多一个条目,不产生错误的结果。 + +## 4. 对象 + +1. 两个路径是否为同一对象:给定拼写相同,或跟随链接(§5)后拼写相同,或两侧最深的存在部分的对象标识相等且其后的 + 部分拼写相同。对象标识由系统经地址打开的句柄读出(卷与文件索引;POSIX 为设备号与 inode),**禁止**经物理拼写 + 打开任何祖先。 +2. 一个对象是否在某目录下:跟随链接后按路径组成部分包含,或目录的对象标识等于该对象跟随链接后的某个祖先的标识。 + 目录内一个指向目录外的链接**不在**目录内。 +3. 一个名字是否在某目录下(不问对象)是词法问题,按主机的大小写规则比较组成部分。 +4. 已存在节点的集合(遍历去环、去重)**必须**以对象标识为键;内存中以路径为键的映射**必须**以跟随链接的拼写(§5) + 为键。对象标识**禁止**作为保存的键:文件删除后其索引会被复用,部分文件系统的设备号在重启后改变。 + +## 5. 跟随链接 + +1. 跟随链接的拼写:自根逐个组成部分读链接(含 Windows 的目录联接),绝对目标从其根重来,相对目标接在链接所在目录 + 之后;不存在的部分原样附加;链接环在 40 跳截断,其拼写为地址本身。 +2. 卷一级的别名(`subst` 盘、映射盘、AppContainer 的盘符)**必须**保留;跟随链接只读链接本身,经给定的路线。 + +## 6. 不能判定 + +1. 对象标识读不出时,问题**必须**按拼写判定,并报告为降级(`path`),说明所判定的问题;`--strict` 下降级为错误。 + +## 7. 物理拼写 + +1. 物理拼写**只能**由路径模块的诊断函数取得;其他代码**禁止**调用 `canonical` 与 `weakly_canonical` + (`std::filesystem` 与 mcpplibs.os)。CI 检查此条:除路径模块外为零处。 + +## 8. 根目录表 + +1. 一次构建的路径位于少数根之下:home、每个 store、工具链、基座(sysroot)、构建目录、每个包。规划**必须**建立一张 + 根目录表,每项为种类、地址与构建给它的名字(`/mcpp/home`、`/mcpp/store`、`/mcpp/toolchain`、`/mcpp/sysroot`、 + `/mcpp/build`、`<包名>@<版本>`)。 +2. `trim_paths` 的前缀映射与链接自足性检查的允许集合**必须**读同一张表。 + +## 9. 工具由地址指名 + +1. 一次链接使用的链接器**必须**由工具链事实确定一次(声明的 `tools.ld`、树或载荷中与目标格式对应的 lld、驱动的 + 缺省),并以地址交给驱动;各路线所用的参数由 [SPEC-006](toolchain-management.md) 规定。 +2. mcpp 启动的 clang 驱动**必须**以给定的拼写看待自身的位置(`-no-canonical-prefixes`):安装目录、资源目录与程序 + 目录由启动它的路径派生。 + +## 版本历史 + +| 版本 | 日期 | 变化 | +|---|---|---| +| 1.0 | 2026-12-07 | 初版:四种用途、对象标识、跟随链接、不能判定时的降级、物理拼写为零处、根目录表、工具由地址指名。 | diff --git a/docs/zh/05-dependencies.md b/docs/zh/05-dependencies.md index c2f3c1b45..1ec06bc19 100644 --- a/docs/zh/05-dependencies.md +++ b/docs/zh/05-dependencies.md @@ -194,7 +194,7 @@ sdk = { version = "1.0", visibility = "private" } | 任意 | 同种类、同引用 | 不变:第二条声明成为指向已解析身份的一条边,不报告任何信息。 | | `version` | `version`,不同的约束 | 按上文所述,用 SemVer 对两个约束做 AND 合并;无法满足的一对被拒绝,并点名两个约束与两个请求方。 | | `git` | `git`,不同的 `rev`/`tag`/`branch` | 根是两个请求方之一时,根的声明胜出;否则先解析出来的声明胜出。`dependency/source-override` 警告点名两个请求方与两个引用,说明哪一个被采用、原因是什么,以及如何取用另一个。这个警告绝不会被吞掉。 | -| `path` | `path`,不同的目录 | 规则与警告同上一行,只是比较的是规范化后的绝对目录,而不是 git 引用。 | +| `path` | `path`,不同的目录 | 规则与警告同上一行,只是比较的是跟随链接后的绝对目录([SPEC-020](../specs/paths.md) §4),而不是 git 引用。 | | 根的 `path` 或 `git` 声明 | 某个依赖的 `git` 或 `version` 声明(种类冲突) | 根的声明胜出,警告同上。若败下阵的声明是一条 `version` 需求,它会被拿去与根已解析出的那份 checkout 的 `[package] version` 核对;需求被违反就拒绝,并点名那个 pin、请求方与需求本身。根已回答的请求不再交给索引选择与固定,因此根的 checkout 也能满足索引尚未收录的版本(2026.10.26.2+)。 | | 某个依赖的 `path`/`git` 声明 | 另一个依赖的不同种类的声明(种类冲突,且双方都不是根) | 拒绝:"requested as both a … dep … and a … dep …. Pick one."。消息多出一句:在根里声明该身份即可解决。 | diff --git a/docs/zh/25-home-indices-and-store.md b/docs/zh/25-home-indices-and-store.md index 404ae3157..3d527fbd5 100644 --- a/docs/zh/25-home-indices-and-store.md +++ b/docs/zh/25-home-indices-and-store.md @@ -77,12 +77,14 @@ Windows 首次显式 `self init` 时,若 D 是可写的本地固定磁盘, 重定向场景会先标明实际目标。`--system self init --home` 被拒绝。 完整选择与持久化规则见 [SPEC-010](../specs/home-initialization.md)。 -**home 保持给定的拼写(2026.11.27.1+)。** 经符号链接给出的 home 按这个名字使用:mcpp 把路径绝对化并做词法归一, -在它之下打开文件、启动程序,因此 `mcpp self env` 与交给工具的每个路径显示的都是用户给出的目录。物理路径只用来判断 -两个路径是不是同一个对象——从上游借用的 home、位于 home 之内的工程。上级目录不可访问而无法判断时,比较退回到拼写, -构建以降级报告并指名这项判断。以路径为输入的键(缓存条目的使用者、计划的工作目录)同样用拼写:同一棵树的两种拼写 -得到两个键,多一个条目,不产生错误结果。此前 home 在读取时被解析为物理路径(mcpp#1024)。CI 中的一项检查把身份函数 -之外的物理路径调用数限制在一份只减不增的基线以内。 +**路径保持给定的拼写(home 自 2026.11.27.1,全部路径自 2026.12.7.1)。** 经符号链接、目录联接、`subst` 盘或 +AppContainer 的盘符给出的 home、工程、`path` 依赖、工具链目录,以及系统报告的目录(临时目录、运行时目录),都按这个 +名字使用:mcpp 把路径绝对化并做词法归一,在它之下打开文件、启动程序,因此 `mcpp self env` 与交给工具的每个路径显示的 +都是用户给出的目录。两个路径是不是同一个对象——从上游借用的 home、位于 home 之内的工程、同一 `path` 依赖的两处声明—— +先跟随链接比较,再比较对象标识;系统读出标识时不经其他拼写打开任何上级目录。标识读不出时,问题按拼写判定,构建以 +降级报告并指名这个问题。以路径为输入的键(缓存条目的使用者、计划的工作目录)用拼写:同一棵树的两种拼写得到两个键, +多一个条目,不产生错误结果。经盘符别名授予目录、而不能打开其上级目录的进程,与其他进程一样构建。规则见 +[SPEC-020](../specs/paths.md);CI 中的一项检查把解析物理拼写的调用限制在只为诊断打印它的那一个模块之内。 ### 初始化与网络诊断(2026.10.19.1+) From 13cfc24236b43f27f22b41924a32b89fe1bd681e Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:40:53 +0900 Subject: [PATCH 06/18] The roots of a build are one table: the trim_paths map and the link's hermetic check read it --- src/build/hermetic.cppm | 21 +++++-- src/build/ninja_backend.cppm | 8 +-- src/build/plan.cppm | 31 +++------ src/build/roots.cppm | 84 +++++++++++++++++++++++++ tests/unit/test_hermetic_graph_link.cpp | 26 +++++--- 5 files changed, 130 insertions(+), 40 deletions(-) create mode 100644 src/build/roots.cppm diff --git a/src/build/hermetic.cppm b/src/build/hermetic.cppm index 7aec584ea..b33b95efb 100644 --- a/src/build/hermetic.cppm +++ b/src/build/hermetic.cppm @@ -22,6 +22,7 @@ export module mcpp.build.hermetic; import std; import mcpp.toolchain.model; +import mcpp.build.roots; export namespace mcpp::build { @@ -36,13 +37,14 @@ export namespace mcpp::build { // package may add a package-relative `-L`, and a path dependency's root can be // anywhere): the C library comes from the graph, so a host library directory // would answer a `-l` the graph does not. +// `roots` is the build's table (SPEC-020 §8): its build directory, its stores +// and, for an isolated graph link, its packages. std::expected verify_hermetic_link( const mcpp::toolchain::Toolchain& tc, const std::string& ldflagsNinja, - const std::filesystem::path& outputDir, + const std::vector& roots, bool allowHostLibs, - bool isolatedGraphLink = false, - const std::vector& graphRoots = {}); + bool isolatedGraphLink = false); } // namespace mcpp::build @@ -144,12 +146,15 @@ std::string expand_response_files(const std::string& flags) { std::expected verify_hermetic_link( const mcpp::toolchain::Toolchain& tc, const std::string& ldflagsNinja, - const std::filesystem::path& outputDir, + const std::vector& roots, bool allowHostLibs, - bool isolatedGraphLink, - const std::vector& graphRoots) + bool isolatedGraphLink) { if constexpr (!mcpplibs::os::is_linux) return {}; + namespace rt = mcpp::build::roots; + const auto outputs = rt::paths(roots, rt::Kind::output); + const auto outputDir = outputs.empty() ? std::filesystem::path{} : outputs.front(); + const auto graphRoots = rt::paths(roots, rt::Kind::package); // Provider toolchains only: the compiler must live in a store. A // host/system compiler is the user's explicit opt-in to the host world. @@ -163,6 +168,10 @@ std::expected verify_hermetic_link( // path the link names. That store is allowed too. if (auto upstream = mcpp::provider::store_of(mcpp::libs::path_identity::resolved(tc.binaryPath))) allowed.push_back(*upstream); + // Every store of the build, and its stated base, as the table names them. + for (auto const& s : rt::paths(roots, rt::Kind::store)) allowed.push_back(s); + for (auto const& b : rt::paths(roots, rt::Kind::base)) allowed.push_back(b); + // The toolchain's own facts: a base it carries unstated, the sysroot it is paired with. if (!tc.base.root.empty()) allowed.push_back(tc.base.root); if (!tc.pairedSysroot.empty()) allowed.push_back(tc.pairedSysroot); diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 343acc018..e7e73d87f 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -5440,9 +5440,9 @@ std::expected NinjaBackend::build(const BuildPlan& plan std::error_code sec; std::filesystem::create_directories(graph_link_sysroot(plan.outputDir), sec); } - if (auto h = verify_hermetic_link(plan.toolchain, flags.ld, plan.outputDir, + if (auto h = verify_hermetic_link(plan.toolchain, flags.ld, plan.roots, plan.manifest.buildConfig.allowHostLibs, - flags.graphLinkIsolated, plan.packageRoots); !h) { + flags.graphLinkIsolated); !h) { return std::unexpected(BuildError{h.error(), {}}); } // A workspace member's units link with their group's line (§15), which @@ -5455,9 +5455,9 @@ std::expected NinjaBackend::build(const BuildPlan& plan const auto gf = compute_flags(view); swap_link_group(view, g); if (!checked.insert(gf.ld).second) continue; - if (auto h = verify_hermetic_link(plan.toolchain, gf.ld, plan.outputDir, + if (auto h = verify_hermetic_link(plan.toolchain, gf.ld, plan.roots, plan.manifest.buildConfig.allowHostLibs, - gf.graphLinkIsolated, plan.packageRoots); !h) + gf.graphLinkIsolated); !h) return std::unexpected(BuildError{h.error(), {}}); } } diff --git a/src/build/plan.cppm b/src/build/plan.cppm index 05201b564..475050e6f 100644 --- a/src/build/plan.cppm +++ b/src/build/plan.cppm @@ -13,6 +13,7 @@ import mcpp.manifest; import mcpp.source_kind; import mcpp.modgraph.graph; import mcpp.modgraph.scanner; +import mcpp.build.roots; import mcpp.toolchain.detect; import mcpp.toolchain.fingerprint; import mcpp.toolchain.target_rows; // a row's fixed executable suffix (N48) @@ -503,6 +504,11 @@ struct BuildPlan { // a driver that tries the last-given mapping first takes the longest // match. Empty unless the profile trims. std::vector> trimMap; + // THE ROOTS OF THE BUILD (SPEC-020 §8): the home, every store, the + // toolchain, its stated base, the build directory and every package, each + // once with the name an output gives it. `trimMap` and the link's hermetic + // check read them; filled by `make_plan`. + std::vector roots; // THE SAME MAP, PER PACKAGE (mcpp#844, design 2026-10-26 part 2 §10.4), // by `CompileUnit::packageName`: the fixed roots and the roots of the // package and its dependency closure -- every prefix the package's units @@ -2245,28 +2251,8 @@ trim_map(const std::vector& packages, const std::vector& storeRoots, const std::vector& keep) { std::vector> out; - auto add = [&](std::filesystem::path from, std::string to) { - if (from.empty() || !from.is_absolute()) return; - from = from.lexically_normal(); - while (from.has_relative_path() && from.filename().empty()) from = from.parent_path(); - if (from == from.root_path()) return; // never map `/` itself - if (std::ranges::any_of(out, [&](auto const& e) { return e.first == from; })) return; - out.emplace_back(std::move(from), std::move(to)); - }; - add(mcpp::home::root(), "/mcpp/home"); - for (auto const& s : storeRoots) add(s, "/mcpp/store"); - add(tc.localRoot.empty() ? tc.binaryPath.parent_path().parent_path() - : std::filesystem::path(tc.localRoot), "/mcpp/toolchain"); - if (tc.base.stated()) add(tc.base.root, "/mcpp/sysroot"); - add(outputDir, "/mcpp/build"); - for (std::size_t i = 0; i < packages.size(); ++i) { - auto const& p = packages[i]; - if (!keep.empty() && (i >= keep.size() || !keep[i])) continue; - if (!p.manifest.package.name.empty()) - add(p.root, std::format("{}@{}", p.manifest.package.name, - p.manifest.package.version.empty() ? std::string("0") - : p.manifest.package.version)); - } + for (auto& r : mcpp::build::roots::of_build(packages, tc, outputDir, storeRoots, keep)) + out.emplace_back(std::move(r.path), std::move(r.name)); std::ranges::stable_sort(out, {}, [](auto const& e) { return e.first.native().size(); }); return out; } @@ -2301,6 +2287,7 @@ make_plan(const mcpp::manifest::Manifest& manifest, pkg.licenseFiles.value_or(mcpp::manifest::default_license_files()), pkg.licenseFiles.has_value()}); } + plan.roots = mcpp::build::roots::of_build(packages, tc, outputDir, storeRoots); if (manifest.buildConfig.trimPaths) plan.trimMap = trim_map(packages, tc, outputDir, storeRoots); diff --git a/src/build/roots.cppm b/src/build/roots.cppm new file mode 100644 index 000000000..6ea55630d --- /dev/null +++ b/src/build/roots.cppm @@ -0,0 +1,84 @@ +// mcpp.build.roots — the directories a build lies beneath, named once (SPEC-020 §8). +// +// A path of a build lies beneath one of a few roots: the home, a store, the toolchain, its +// base, the build directory, a package. The `trim_paths` map renamed them and the link's +// hermetic check allowed them, each from a list of its own, and the two lists disagreed: the +// check knew the compiler's store and, through a link the driver followed, an upstream's, +// where the map knew every store of the home. The table names each root once -- its kind, +// its address (SPEC-020 §2) and the name an output gives it -- and both read it. + +export module mcpp.build.roots; + +import std; +import mcpp.modgraph.scanner; // PackageRoot +import mcpp.toolchain.model; + +export namespace mcpp::build::roots { + +enum class Kind { home, store, toolchain, base, output, package }; + +struct Root { + Kind kind; + std::filesystem::path path; // the address, absolute and lexically normal + std::string name; // `/mcpp/home`, `/mcpp/store`, ..., `@` +}; + +// The roots of a build, each once (a later root a path already names is not added): the home, +// every store, the toolchain, its base when one is stated, the build directory, and each +// package `keep` marks -- every package when `keep` is empty. `/` is never a root. +std::vector of_build(const std::vector& packages, + const mcpp::toolchain::Toolchain& tc, + const std::filesystem::path& outputDir, + const std::vector& storeRoots, + const std::vector& keep = {}); + +// The addresses of the roots of one kind, in the table's order. +std::vector paths(const std::vector& roots, Kind kind); + +} // namespace mcpp::build::roots + +module :private; + +import mcpp.home; + +namespace mcpp::build::roots { + +std::vector of_build(const std::vector& packages, + const mcpp::toolchain::Toolchain& tc, + const std::filesystem::path& outputDir, + const std::vector& storeRoots, + const std::vector& keep) { + std::vector out; + auto add = [&](Kind kind, std::filesystem::path from, std::string name) { + if (from.empty() || !from.is_absolute()) return; + from = from.lexically_normal(); + while (from.has_relative_path() && from.filename().empty()) from = from.parent_path(); + if (from == from.root_path()) return; // never `/` itself + if (std::ranges::any_of(out, [&](auto const& r) { return r.path == from; })) return; + out.push_back({kind, std::move(from), std::move(name)}); + }; + add(Kind::home, mcpp::home::root(), "/mcpp/home"); + for (auto const& s : storeRoots) add(Kind::store, s, "/mcpp/store"); + add(Kind::toolchain, tc.localRoot.empty() ? tc.binaryPath.parent_path().parent_path() + : std::filesystem::path(tc.localRoot), "/mcpp/toolchain"); + if (tc.base.stated()) add(Kind::base, tc.base.root, "/mcpp/sysroot"); + add(Kind::output, outputDir, "/mcpp/build"); + for (std::size_t i = 0; i < packages.size(); ++i) { + auto const& p = packages[i]; + if (!keep.empty() && (i >= keep.size() || !keep[i])) continue; + if (!p.manifest.package.name.empty()) + add(Kind::package, p.root, std::format("{}@{}", p.manifest.package.name, + p.manifest.package.version.empty() ? std::string("0") + : p.manifest.package.version)); + } + return out; +} + +std::vector paths(const std::vector& roots, Kind kind) { + std::vector out; + for (auto const& r : roots) + if (r.kind == kind) out.push_back(r.path); + return out; +} + +} // namespace mcpp::build::roots diff --git a/tests/unit/test_hermetic_graph_link.cpp b/tests/unit/test_hermetic_graph_link.cpp index 96ee6e5b1..5bcf5091a 100644 --- a/tests/unit/test_hermetic_graph_link.cpp +++ b/tests/unit/test_hermetic_graph_link.cpp @@ -10,6 +10,7 @@ import std; import mcpplibs.mtest; import mcpp.build.hermetic; +import mcpp.build.roots; import mcpplibs.os.platform; import mcpp.toolchain.model; @@ -52,14 +53,23 @@ mcpp::toolchain::Toolchain fake_driver(const std::filesystem::path& root, return tc; } +// The build's table of roots (SPEC-020 §8): its build directory and its packages. +std::vector table(const std::filesystem::path& out, + const std::vector& packages = {}) { + namespace rt = mcpp::build::roots; + std::vector roots{{rt::Kind::output, out, "/mcpp/build"}}; + for (auto const& p : packages) roots.push_back({rt::Kind::package, p, "pkg@0"}); + return roots; +} + } // namespace UTest a_host_search_directory_is_refused_and_named{"HermeticGraphLink/AHostSearchDirectoryIsRefusedAndNamed", [] { if constexpr (!mcpplibs::os::is_linux) skip("the check runs on Linux hosts"); Tmp t; auto tc = fake_driver(t.path, {"/usr/lib", (t.path / "xpkgs" / "musl" / "lib").string()}); - auto r = mcpp::build::verify_hermetic_link(tc, "", t.path / "out", false, - /*isolatedGraphLink=*/true, {}); + auto r = mcpp::build::verify_hermetic_link(tc, "", table(t.path / "out"), false, + /*isolatedGraphLink=*/true); expect(fatal(!r.has_value())); if (auto&& failed = expect(ne(r.error().find("/usr/lib"), std::string::npos)); !failed) failed << r.error(); if (auto&& failed = expect(ne(r.error().find("mcpp#696"), std::string::npos)); !failed) failed << r.error(); @@ -70,8 +80,8 @@ UTest allow_host_libs_downgrades_the_refusal{"HermeticGraphLink/AllowHostLibsDow if constexpr (!mcpplibs::os::is_linux) skip("the check runs on Linux hosts"); Tmp t; auto tc = fake_driver(t.path, {"/usr/lib"}); - auto r = mcpp::build::verify_hermetic_link(tc, "", t.path / "out", true, - /*isolatedGraphLink=*/true, {}); + auto r = mcpp::build::verify_hermetic_link(tc, "", table(t.path / "out"), true, + /*isolatedGraphLink=*/true); if (auto&& failed = expect(r.has_value()); !failed) failed << (r ? "" : r.error()); }}; @@ -85,8 +95,8 @@ UTest the_build_and_the_graphs_packages_are_allowed{"HermeticGraphLink/TheBuildA auto tc = fake_driver(t.path, {(out / "graph-sysroot" / "lib").string(), (pathDep / "lib" / "empty").string(), (t.path / "xpkgs" / "musl" / "lib").string()}); - auto r = mcpp::build::verify_hermetic_link(tc, "", out, false, - /*isolatedGraphLink=*/true, {pathDep}); + auto r = mcpp::build::verify_hermetic_link(tc, "", table(out, {pathDep}), false, + /*isolatedGraphLink=*/true); if (auto&& failed = expect(r.has_value()); !failed) failed << (r ? "" : r.error()); }}; @@ -96,7 +106,7 @@ UTest a_payload_link_is_not_held_to_the_graph_rule{"HermeticGraphLink/APayloadLi if constexpr (!mcpplibs::os::is_linux) skip("the check runs on Linux hosts"); Tmp t; auto tc = fake_driver(t.path, {"/usr/lib"}); - auto r = mcpp::build::verify_hermetic_link(tc, "", t.path / "out", false, - /*isolatedGraphLink=*/false, {}); + auto r = mcpp::build::verify_hermetic_link(tc, "", table(t.path / "out"), false, + /*isolatedGraphLink=*/false); if (auto&& failed = expect(r.has_value()); !failed) failed << (r ? "" : r.error()); }}; From be42c7fe905e63e12da6c6e80feb4d87914750ae Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:40:53 +0900 Subject: [PATCH 07/18] Every build a command runs follows the command's verbosity; a build program's inner build alone states its own --- src/build/backend.cppm | 7 ++++++- src/build/configure.cppm | 5 ++--- src/build/execute.cppm | 13 ++++++------- src/build/prepare/features.cpp | 5 +++-- src/build/prepare/host_graph.cpp | 5 +++-- src/cli/cmd_build.cppm | 8 ++++---- src/pack/library_pipeline.cppm | 1 - src/pack/pipeline.cppm | 6 +----- 8 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/build/backend.cppm b/src/build/backend.cppm index 41cf45e5b..00205a6a1 100644 --- a/src/build/backend.cppm +++ b/src/build/backend.cppm @@ -3,6 +3,7 @@ export module mcpp.build.backend; import std; +import mcpp.log; import mcpp.build.plan; import mcpp.build.progress; @@ -11,7 +12,11 @@ export namespace mcpp::build { enum class BackendKind { Ninja, Native }; struct BuildOptions { - bool verbose = false; + // Ninja's own lines and the commands it runs: by default the command's + // verbosity (`--verbose`), so every build a command runs follows it. Set + // only where a drive deliberately differs -- a build program's inner + // build, whose lines are filtered unless MCPP_TOOL_BUILD_VERBOSE asks. + bool verbose = mcpp::log::is_verbose(); bool dryRun = false; bool requireCompileDatabase = false; // Explicit ninja goal targets (LinkUnit::output paths, relative to the diff --git a/src/build/configure.cppm b/src/build/configure.cppm index 8e56f1548..4f162c41d 100644 --- a/src/build/configure.cppm +++ b/src/build/configure.cppm @@ -11,7 +11,7 @@ export namespace mcpp::build { std::expected stage_configure_prerequisites(const BuildPlan& plan); -int run_configure_plan(BuildContext& ctx, bool verbose); +int run_configure_plan(BuildContext& ctx); } // namespace mcpp::build @@ -90,7 +90,7 @@ stage_configure_prerequisites(const BuildPlan& plan) { return staged; } -int run_configure_plan(BuildContext& ctx, bool verbose) { +int run_configure_plan(BuildContext& ctx) { auto staged = stage_configure_prerequisites(ctx.plan); if (!staged) { mcpp::ui::error(staged.error()); @@ -99,7 +99,6 @@ int run_configure_plan(BuildContext& ctx, bool verbose) { auto backend = mcpp::build::make_ninja_backend(); BuildOptions options; - options.verbose = verbose; options.dryRun = true; options.requireCompileDatabase = true; diff --git a/src/build/execute.cppm b/src/build/execute.cppm index 7599d7e12..236f57cae 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -2244,7 +2244,7 @@ std::optional verify_cxx_island(const BuildContext& ctx) { return std::nullopt; } -export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache, +export int run_build_plan(BuildContext& ctx, bool no_cache, std::string_view targetOverride = "") { // `--cache=off` means a cold build: no global cache, and target/ cleared — // which is exactly what `--no-cache` has always done, hence the alias. @@ -2351,7 +2351,6 @@ export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache, // (pack drive and selection design 2026-10-01, A1, A2): every command's // drive takes them from the plan and the open report. mcpp::build::BuildOptions opts; - opts.verbose = verbose; auto record = start_record(ctx); auto r = be->build(ctx.plan, opts); if (!r) { @@ -4508,7 +4507,7 @@ export int build_run_target(const std::optional& targetName, auto ctx2 = prepare_build(/*print_fp=*/false, /*includeDevDeps=*/false, /*extraTargets=*/{}, ov2); if (!ctx2) { mcpp::ui::error(std::format("{}", ctx2.error())); return kRunBuildFailed; } - if (run_build_plan(*ctx2, /*verbose=*/false, no_cache, target) != 0) + if (run_build_plan(*ctx2, no_cache, target) != 0) return kRunBuildFailed; // ONE DISTRIBUTABLE, OR A SENTENCE. The pack pipeline reports the // terminal artifacts of the request (outputs no other introduced @@ -4582,7 +4581,7 @@ export int build_run_target(const std::optional& targetName, // The comment on `try_fast_run` records the same defect reached through the // MANIFEST's default target, and guards that door alone. This is the other // door: the flag. Measured on 2026.8.24.3, from a clean `target/`. - if (run_build_plan(*ctx, /*verbose=*/false, no_cache, target) != 0) + if (run_build_plan(*ctx, no_cache, target) != 0) return kRunBuildFailed; // The program run is the selected member's (workspace design 2026-09-29 // §15), with its closure's runtime. @@ -7821,7 +7820,7 @@ export int run_tests(std::span passthrough, // bare `mcpp run` warned "fingerprint changed" and rebuilt. // `--no-programs`: planned for their names, not built. if (!testOpts.noPrograms) - if (int rc = run_build_plan(*binCtx, mcpp::log::is_verbose(), false, + if (int rc = run_build_plan(*binCtx, false, overrides.target_triple); rc != 0) return rc; for (auto const& lu : binCtx->plan.linkUnits) { @@ -8091,7 +8090,7 @@ export int run_test_legs(std::span passthrough, if (l.programs) { // `--no-programs`: planned for their names, not built. if (!testOpts.noPrograms - && run_build_plan(*l.programs, mcpp::log::is_verbose(), false, l.triple) != 0) { + && run_build_plan(*l.programs, false, l.triple) != 0) { l.programsFailed = true; return 1; } @@ -8451,7 +8450,7 @@ export void run_workspace_tests(std::span passthrough, if (!binCtx) { why = binCtx.error(); return false; } // `--no-programs`: planned for their names, and the environment's. if (!testOpts.noPrograms - && run_build_plan(*binCtx, mcpp::log::is_verbose(), false, base.target_triple) != 0) { + && run_build_plan(*binCtx, false, base.target_triple) != 0) { why.clear(); return false; } diff --git a/src/build/prepare/features.cpp b/src/build/prepare/features.cpp index 93643668b..b25d23925 100644 --- a/src/build/prepare/features.cpp +++ b/src/build/prepare/features.cpp @@ -1817,8 +1817,9 @@ step6_build_tool(PrepareState& state, HostToolCtx& ctx) { // ninja's own progress and command echoes, which is right // for a normal build and wrong when the question is "what // did the inner build actually do". - if (auto v = mcpp::invocation::get("MCPP_TOOL_BUILD_VERBOSE"); v && *v != "0") - bopt.verbose = true; + // A build program's inner build is filtered whatever the command's + // verbosity: its lines are the program's, not the user's build. + bopt.verbose = mcpp::invocation::get("MCPP_TOOL_BUILD_VERBOSE").value_or("0") != "0"; auto br = be->build(subCtx->plan, bopt); if (!br) { auto diag = br.error().diagnosticOutput; diff --git a/src/build/prepare/host_graph.cpp b/src/build/prepare/host_graph.cpp index ef25cfff8..a0e6a3a8c 100644 --- a/src/build/prepare/host_graph.cpp +++ b/src/build/prepare/host_graph.cpp @@ -1028,8 +1028,9 @@ build_group(PrepareState& state, const fs::path& dir, const std::vector mcpp::build::BuildOptions bopt; bopt.ninjaTargets = ninjaGoals; bopt.report = mcpp::build::BuildOptions::Report::Caller; - if (auto v = mcpp::invocation::get("MCPP_TOOL_BUILD_VERBOSE"); v && *v != "0") - bopt.verbose = true; + // A build program's inner build is filtered whatever the command's + // verbosity: its lines are the program's, not the user's build. + bopt.verbose = mcpp::invocation::get("MCPP_TOOL_BUILD_VERBOSE").value_or("0") != "0"; auto br = be->build(ctx->plan, bopt); timer.mark("built"); // What an index package and the engine interface compiled to is kept in diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index 5cc1ca5b4..4197bbedb 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -307,7 +307,7 @@ int run_build_with_hooks(mcpp::build::BuildContext& ctx, bool verbose, if (!invoke(*sub.hooks, mcpp::hooks::Event::BuildStart, sub.root)) return 1; - int rc = mcpp::build::run_build_plan(ctx, verbose, no_cache, targetOverride); + int rc = mcpp::build::run_build_plan(ctx, no_cache, targetOverride); // Closed BEFORE the terminal hook. A "build finished" sound competing with // the background music it replaces is the ordering this line settles. @@ -624,7 +624,7 @@ int build_several_legs(const mcpplibs::cmdline::ParsedArgs& parsed, if (configure_only) { for (auto* c : contexts) { c->plan.publishRootCompileDb = false; - if (int r = mcpp::build::run_configure_plan(*c, verbose); r != 0 && rc == 0) rc = r; + if (int r = mcpp::build::run_configure_plan(*c); r != 0 && rc == 0) rc = r; } } else { std::map tripleOf; @@ -718,7 +718,7 @@ int cmd_build_body(const mcpplibs::cmdline::ParsedArgs& parsed, BodyMode mode) { rootCompileDb = ctx->plan.rootCompileDb; configured->push_back(ctx->outputDir); } - return mcpp::build::run_configure_plan(*ctx, verbose); + return mcpp::build::run_configure_plan(*ctx); }; // A workspace: the selected members, planned by configuration group @@ -775,7 +775,7 @@ int cmd_build_body(const mcpplibs::cmdline::ParsedArgs& parsed, BodyMode mode) { if (fetch_only) continue; ctx->plan.publishRootCompileDb = false; rootCompileDb = ctx->plan.rootCompileDb; - if (int r = mcpp::build::run_configure_plan(*ctx, verbose); r != 0) rc = r; + if (int r = mcpp::build::run_configure_plan(*ctx); r != 0) rc = r; configured.push_back(ctx->outputDir); } if (!configured.empty()) diff --git a/src/pack/library_pipeline.cppm b/src/pack/library_pipeline.cppm index 77b3d0189..909a94a9c 100644 --- a/src/pack/library_pipeline.cppm +++ b/src/pack/library_pipeline.cppm @@ -217,7 +217,6 @@ int build_and_pack_library(const std::string& targetName, auto built = mcpp::build::legs::build(contexts, [&](mcpp::build::BuildContext& c) { auto be = mcpp::build::make_ninja_backend(); mcpp::build::BuildOptions bo; - bo.verbose = mcpp::log::is_verbose(); if (auto br = be->build(c.plan, bo); !br) { // The compiler's own output, not just "build failed". `mcpp // build` has always printed this; `mcpp pack` dropped it, so a diff --git a/src/pack/pipeline.cppm b/src/pack/pipeline.cppm index 6427c0316..f3afc2097 100644 --- a/src/pack/pipeline.cppm +++ b/src/pack/pipeline.cppm @@ -269,7 +269,6 @@ build_extra_android_legs(const std::string& targetName, auto built = mcpp::build::legs::build(contexts, [](mcpp::build::BuildContext& c) { auto be = mcpp::build::make_ninja_backend(); mcpp::build::BuildOptions bo; - bo.verbose = mcpp::log::is_verbose(); if (auto br = be->build(c.plan, bo); !br) { mcpp::build::report_failed_drive(br.error()); return 1; @@ -811,8 +810,7 @@ std::optional member_plan(PackRun& run, GroupJob& g, MemberJob& m) { auto built = mcpp::build::legs::build(contexts, [](mcpp::build::BuildContext& c) { auto be = mcpp::build::make_ninja_backend(); mcpp::build::BuildOptions bo; - bo.verbose = mcpp::log::is_verbose(); - if (auto br = be->build(c.plan, bo); !br) { + if (auto br = be->build(c.plan, bo); !br) { mcpp::build::report_failed_drive(br.error()); return 1; } @@ -1665,7 +1663,6 @@ std::optional dispatch_group(PackRun& run, GroupJob& g, mcpp::build::Ba } mcpp::build::progress::programs_done(); mcpp::build::BuildOptions dbo; - dbo.verbose = mcpp::log::is_verbose(); dbo.keepGoing = run.several; auto dr = be.build(distCtx->plan, dbo); const bool driveFailed = !dr.has_value(); @@ -1903,7 +1900,6 @@ PackOutcome run_pack(PackRun run) { for (auto& g : groups) { if (g.rc != 0) continue; mcpp::build::BuildOptions bo; - bo.verbose = mcpp::log::is_verbose(); auto br = be->build(g.ctx->plan, bo); if (!br) { mcpp::build::report_failed_drive(br.error()); From a2619f40f7111f97383688932f5733937fe8b9d6 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:40:53 +0900 Subject: [PATCH 08/18] The documentation indices list SPEC-020, and SPEC-020 keeps a change record --- .agents/docs/README.md | 4 +++- docs/README.md | 1 + docs/specs/paths.md | 4 ++-- docs/zh/README.md | 1 + 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.agents/docs/README.md b/.agents/docs/README.md index 2c79b1cac..e7ea16a66 100644 --- a/.agents/docs/README.md +++ b/.agents/docs/README.md @@ -18,7 +18,7 @@ superseded_by: 2026-09-07-....md # when status is superseded --- ``` -377 records. +378 records. ## By subject @@ -61,6 +61,7 @@ Records that declare one. Everything else is listed by date below. ### design +- [路径的四种用途、根目录表与工具的地址:受限视图下的一致性](2026-12-07-path-uses-roots-and-tool-addresses-design.md) — active - [陈述的闭包、单一读者与六项功能:十四项缺陷的收敛设计](2026-11-27-stated-closure-single-reader-and-feature-designs.md) — landed - [生态级方案:内核接口的供给与能力,派生状态的核对,存储的引用](2026-11-22-kernel-interface-and-derived-state-ecosystem-design.md) — active - [程序起点模型:启动者、两层入口与 `main` 的三种陈述(mcpp#845、mcpp#981)](2026-11-20-program-start-model.md) — landed @@ -219,6 +220,7 @@ Records that declare one. Everything else is listed by date below. ### 2026-12 +- [路径的四种用途、根目录表与工具的地址:受限视图下的一致性](2026-12-07-path-uses-roots-and-tool-addresses-design.md) — active - [命令行表面的两种读者:帮助与固定输出的版式和样式、包的种类与信息、包自带的 agent 说明](2026-12-06-cli-surface-people-and-agents-design.md) — active ### 2026-11 diff --git a/docs/README.md b/docs/README.md index af5040142..8ed143ede 100644 --- a/docs/README.md +++ b/docs/README.md @@ -186,3 +186,4 @@ downstream tooling. - [SPEC-017 — The mcpp test spec: test programs, the test protocol, records, the store, launch descriptions and framework declarations; base and optional capabilities](specs/test.md) - [SPEC-018 — The rebuild of modules: the cutoff by BMI content, GCC's stamps and line maps, `bmi_cutoff`, the build directory's record](specs/module-rebuilds.md) - [SPEC-019 — Build optimizations: the register, levels, seams, the statement that turns all of it off, the private module fragment as a unit, the advice after a build](specs/build-optimizations.md) + - [SPEC-020 — Paths: the uses of a path (an address, a kept key, an object, a link followed), the table of roots, tools named by their address](specs/paths.md) diff --git a/docs/specs/paths.md b/docs/specs/paths.md index 33444d111..43ba5c9be 100644 --- a/docs/specs/paths.md +++ b/docs/specs/paths.md @@ -87,8 +87,8 @@ 2. mcpp 启动的 clang 驱动**必须**以给定的拼写看待自身的位置(`-no-canonical-prefixes`):安装目录、资源目录与程序 目录由启动它的路径派生。 -## 版本历史 +## 变更记录 -| 版本 | 日期 | 变化 | +| 版本 | 日期 | 变更 | |---|---|---| | 1.0 | 2026-12-07 | 初版:四种用途、对象标识、跟随链接、不能判定时的降级、物理拼写为零处、根目录表、工具由地址指名。 | diff --git a/docs/zh/README.md b/docs/zh/README.md index e15489876..c566013c8 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -181,3 +181,4 @@ - [SPEC-017 —— mcpp 测试规范:测试程序、测试协议、记录、存储、启动描述与框架声明;基础能力与可选能力](../specs/test.md) - [SPEC-018 —— 模块的重编译:按 BMI 内容截断、GCC 的时间戳与行映射、`bmi_cutoff`、构建目录的记录](../specs/module-rebuilds.md) - [SPEC-019 —— 构建优化:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议](../specs/build-optimizations.md) + - [SPEC-020 —— 路径:路径的用途(地址、保存的键、对象、跟随链接),根目录表,工具由地址指名](../specs/paths.md) From 0ba5b1bda0ea9124d4f625726355d385047af009 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 01:54:11 +0900 Subject: [PATCH 09/18] A clang tree's linker is one fact named by its address, handed to the driver in the form each link route reads --- modules/toolchain-model/src/linkmodel.cppm | 69 +++++++++++++++++++ modules/toolchain-model/src/model.cppm | 11 ++- .../tests/test_linker_words.cpp | 67 ++++++++++++++++++ src/build/flags.cppm | 31 +++++---- src/build/prepare/local_toolchain.cpp | 60 ++++++++++------ src/build/prepare/state.cppm | 2 +- src/build/prepare/toolchain_resolver.cpp | 2 +- src/toolchain/hostflags.cppm | 8 +-- tests/e2e/toolchain/custom.cpp | 68 +++++++++++++++++- 9 files changed, 275 insertions(+), 43 deletions(-) create mode 100644 modules/toolchain-model/tests/test_linker_words.cpp diff --git a/modules/toolchain-model/src/linkmodel.cppm b/modules/toolchain-model/src/linkmodel.cppm index e22f31b7b..e037bfcd6 100644 --- a/modules/toolchain-model/src/linkmodel.cppm +++ b/modules/toolchain-model/src/linkmodel.cppm @@ -353,6 +353,29 @@ std::filesystem::path payload_lib_dir_with_loader( ClangDriverModel resolve_clang_driver(const Toolchain& tc); +// THE NAME lld RUNS UNDER FOR A LINK OF `tc`'s TARGET: `lld-link` on the MSVC +// ABI, `ld64.lld` for Mach-O, `wasm-ld` for wasm, `ld.lld` otherwise (the MinGW +// driver runs the ELF name too). Without the host's executable suffix. +std::string_view lld_name(const Toolchain& tc); + +// THE WORDS THAT HAND `tc.linker` TO A CLANG DRIVER, by the route each driver +// reads it (SPEC-006 §2.10; measured with `-###` on LLVM 23.1.3): +// ELF, Mach-O, MinGW `--ld-path=`, after `-fuse-ld=lld` when the +// program is an lld, which tells the driver so +// wasm `-fuse-ld=`: the wasm linker reads no `--ld-path` +// MSVC ABI `-B -fuse-ld=`: this route reads no +// `--ld-path`, and prefixes a name that holds a directory +// with the triple; it finds `` or `.exe` in a +// `-B` directory before any other +// Empty when no linker is named. +std::vector linker_words(const Toolchain& tc, const PathEscape& esc); + +// A linker's file name without a trailing `.exe`: the name the MSVC route +// selects it by, and the name that tells an lld. On that route `link` and `lld` +// name programs the driver finds by its own rules, so a linker of either name +// cannot be selected by address. +std::string linker_name(const std::filesystem::path& linker); + ToolchainLinkModel resolve_link_model(const Toolchain& tc); } // namespace mcpp::toolchain @@ -369,6 +392,52 @@ namespace mcpp::toolchain { std::string no_escape(const std::filesystem::path& p) { return p.string(); } +namespace { + +// The target's object format, with the architecture's word for a triple the +// vocabulary does not parse (`wasm32-wasip1`): the driver chooses its link by it. +bool links_wasm(const Toolchain& tc) { + if (auto t = triple::parse(tc.targetTriple)) return t->is_wasm(); + return tc.targetTriple.starts_with("wasm"); +} +bool links_mach_o(const Toolchain& tc) { + if (auto t = triple::parse(tc.targetTriple)) return t->is_mach_o(); + return tc.targetTriple.contains("-apple-"); +} + +} // namespace + +std::string_view lld_name(const Toolchain& tc) { + if (is_msvc_target(tc)) return "lld-link"; + if (links_mach_o(tc)) return "ld64.lld"; + if (links_wasm(tc)) return "wasm-ld"; + return "ld.lld"; +} + +std::string linker_name(const std::filesystem::path& linker) { + auto name = linker.filename().string(); + if (name.size() > 4) { + auto ext = name.substr(name.size() - 4); + std::ranges::transform(ext, ext.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (ext == ".exe") name.resize(name.size() - 4); + } + return name; +} + +std::vector linker_words(const Toolchain& tc, const PathEscape& esc) { + if (tc.linker.empty()) return {}; + if (is_msvc_target(tc)) + return {"-B" + esc(tc.linker.parent_path()), "-fuse-ld=" + linker_name(tc.linker)}; + if (links_wasm(tc)) return {"-fuse-ld=" + esc(tc.linker)}; + // An lld, by the names lld answers to: the driver then passes what only lld takes. + const auto name = linker_name(tc.linker); + const bool lld = name == "ld.lld" || name == "ld64.lld" || name == "lld-link" || name == "wasm-ld"; + std::vector out; + if (lld) out.push_back("-fuse-ld=lld"); + out.push_back("--ld-path=" + esc(tc.linker)); + return out; +} + std::string render_tokens(const std::vector& tokens) { std::string out; for (auto const& t : tokens) { out += ' '; out += t; } diff --git a/modules/toolchain-model/src/model.cppm b/modules/toolchain-model/src/model.cppm index 4c6780189..78ab02988 100644 --- a/modules/toolchain-model/src/model.cppm +++ b/modules/toolchain-model/src/model.cppm @@ -294,14 +294,21 @@ struct Toolchain { // and none of these is set for it. // treeLinkWords the clang link words in place of the payload's fixed // `-fuse-ld=lld --rtlib=compiler-rt --unwindlib=libunwind`: - // `-fuse-ld=lld` when the tree has lld and no `tools.ld` - // is stated, a runtime word when the driver has the library + // a runtime word when the driver has the library (the + // linker is `linker`, below) // archiverTakesResponseFiles false: mcpp expands the response file and // archives in batches (`mcpp __archive`) // compilesModules false: the driver refused a module unit; the build // takes the path of a compiler without C++ modules // treeFacts each fact with its source, for `mcpp why toolchain` std::optional> treeLinkWords; + // THE LINKER, NAMED BY ITS ADDRESS (SPEC-020 §9, SPEC-006 §2.10): the + // stated `tools.ld`, else the lld of the link's flavour in a clang tree + // named by path. A driver that finds lld by name finds it beside its + // resolved self, and a tree of links resolves elsewhere. Empty: the + // driver's own choice -- a managed payload's lld lies beside its driver. + // Every clang link takes it through `linker_words` (linkmodel). + std::filesystem::path linker; bool archiverTakesResponseFiles = true; bool compilesModules = true; // A named struct for the reason `ToolOverride` is one (below). diff --git a/modules/toolchain-model/tests/test_linker_words.cpp b/modules/toolchain-model/tests/test_linker_words.cpp new file mode 100644 index 000000000..624c714bd --- /dev/null +++ b/modules/toolchain-model/tests/test_linker_words.cpp @@ -0,0 +1,67 @@ +import std; +import mcpplibs.mtest; +import mcpp.toolchain.model; +import mcpp.toolchain.linkmodel; + +using namespace mcpplibs::mtest; + +// SUBSYSTEM-LEVEL: the linker named by its address (SPEC-020 §9, SPEC-006 §2.10). One fact, +// handed to the driver in the form the target's route reads; measured with `-###` on LLVM +// 23.1.3: `--ld-path` reaches the ELF, Mach-O and MinGW links, the wasm link reads only an +// absolute `-fuse-ld`, and the MSVC link reads only `-fuse-ld`, by a name it looks up in `-B`. + +namespace tc = mcpp::toolchain; + +namespace { + +tc::Toolchain clang_for(std::string triple, std::filesystem::path linker) { + tc::Toolchain t; + t.compiler = tc::CompilerId::Clang; + t.targetTriple = std::move(triple); + t.linker = std::move(linker); + return t; +} + +std::vector words(const tc::Toolchain& t) { return tc::linker_words(t, tc::no_escape); } + +using W = std::vector; + +} // namespace + +UTest the_lld_of_each_flavour{"LinkerWords/TheLldOfEachFlavour", [] { + expect(eq(tc::lld_name(clang_for("x86_64-linux-gnu", {})), std::string_view{"ld.lld"})); + expect(eq(tc::lld_name(clang_for("x86_64-w64-mingw32", {})), std::string_view{"ld.lld"})); + expect(eq(tc::lld_name(clang_for("aarch64-apple-darwin", {})), std::string_view{"ld64.lld"})); + expect(eq(tc::lld_name(clang_for("wasm32-emscripten", {})), std::string_view{"wasm-ld"})); + expect(eq(tc::lld_name(clang_for("wasm32-wasip1", {})), std::string_view{"wasm-ld"})); + expect(eq(tc::lld_name(clang_for("x86_64-pc-windows-msvc", {})), std::string_view{"lld-link"})); +}}; + +UTest a_path_route_takes_ld_path{"LinkerWords/APathRouteTakesLdPath", [] { + // An lld is said to be one, so the driver passes what only lld takes; another program is + // named and nothing more. + expect(eq(words(clang_for("x86_64-linux-gnu", "/t/bin/ld.lld")), W{"-fuse-ld=lld", "--ld-path=/t/bin/ld.lld"})); + expect(eq(words(clang_for("aarch64-apple-darwin", "/t/bin/ld64.lld")), W{"-fuse-ld=lld", "--ld-path=/t/bin/ld64.lld"})); + expect(eq(words(clang_for("x86_64-w64-mingw32", "/t/bin/ld.lld.exe")), W{"-fuse-ld=lld", "--ld-path=/t/bin/ld.lld.exe"})); + expect(eq(words(clang_for("x86_64-linux-gnu", "/w/trace-ld")), W{"--ld-path=/w/trace-ld"})); +}}; + +UTest the_wasm_route_takes_an_absolute_fuse_ld{"LinkerWords/TheWasmRouteTakesAnAbsoluteFuseLd", [] { + expect(eq(words(clang_for("wasm32-emscripten", "/t/bin/wasm-ld")), W{"-fuse-ld=/t/bin/wasm-ld"})); + expect(eq(words(clang_for("wasm32-wasip1", "/t/bin/wasm-ld")), W{"-fuse-ld=/t/bin/wasm-ld"})); +}}; + +UTest the_msvc_route_takes_a_name_in_a_b_directory{"LinkerWords/TheMsvcRouteTakesANameInABDirectory", [] { + // A name that holds a directory is prefixed with the triple on this route, so the program is + // named by its file name, found in the `-B` directory before anywhere else. + expect(eq(words(clang_for("x86_64-pc-windows-msvc", "C:/t/bin/lld-link.exe")), W{"-BC:/t/bin", "-fuse-ld=lld-link"})); + expect(eq(words(clang_for("x86_64-pc-windows-msvc", "C:/w/Trace-Link.EXE")), W{"-BC:/w", "-fuse-ld=Trace-Link"})); + expect(eq(words(clang_for("x86_64-pc-windows-msvc", "/w/trace-link")), W{"-B/w", "-fuse-ld=trace-link"})); + expect(eq(tc::linker_name("C:/w/link.exe"), std::string{"link"})); +}}; + +UTest no_linker_no_words{"LinkerWords/NoLinkerNoWords", [] { + // A managed payload's lld lies beside its driver; the driver's own choice is not restated. + expect(words(clang_for("x86_64-linux-gnu", {})).empty()); + expect(words(clang_for("x86_64-pc-windows-msvc", {})).empty()); +}}; diff --git a/src/build/flags.cppm b/src/build/flags.cppm index edd1896b5..3ff92d2b9 100644 --- a/src/build/flags.cppm +++ b/src/build/flags.cppm @@ -2848,26 +2848,31 @@ CompileFlags compute_flags_impl(const BuildPlan& plan, bool packageLinkFlags) { f.ld += base_link_words(true); f.ldC += base_link_words(false); - // A LINKER STATED BY ROLE (mcpp#755, `tools = { ld = ... }`), AFTER EVERY - // SHAPE HAS BUILT ITS LINE. + // THE LINKER NAMED BY ITS ADDRESS (SPEC-020 §9; mcpp#755, `tools = { ld = + // ... }`), AFTER EVERY SHAPE HAS BUILT ITS LINE. // // It was appended inside the Linux clang branch, the only one that consumes // `link_toolchain_flags`: on macOS the stated linker entered the fingerprint // -- the fast path declined when the wrapper changed -- and took no part in // the link, with nothing said (measured in the toolchain lab on macos-15, - // where `build.ninja` held no `--ld-path`). The flag belongs to the driver, - // not to a platform, so it is added once here, for every shape. + // where `build.ninja` held no `--ld-path`). The words belong to the driver, + // not to a platform, so they are added once here, for every shape, in the + // form the target's route reads (`linker_words`): `--ld-path` alone reached + // neither the MSVC route nor wasm, which reported it unused. // - // Clang only: `--ld-path` is clang's. GCC chooses its linker by name inside a - // `-B` directory, so a program named anything else could not be selected that - // way, and a silent `-B` would be the same defect in the other direction. A - // gcc toolchain that states `ld` is refused where the declaration is read. - if (plan.toolchain.compiler == mcpp::toolchain::CompilerId::Clang) - if (auto* ld = plan.toolchain.tool_override("ld")) { - const auto opt = " --ld-path=" + escape_path(*ld); - if (f.ld.find("--ld-path=") == std::string::npos) f.ld += opt; - if (f.ldC.find("--ld-path=") == std::string::npos) f.ldC += opt; + // Clang only: the fact is set for a clang tree (a gcc toolchain that states + // `ld` is refused where the declaration is read). A line that runs the + // linker itself (`ldDriver`, a platform's direct link) is run by it. + if (plan.toolchain.compiler == mcpp::toolchain::CompilerId::Clang && !plan.toolchain.linker.empty()) { + if (!f.ldDriver.empty()) { + f.ldDriver = plan.toolchain.linker; + } else { + std::string words; + for (auto const& w : mcpp::toolchain::linker_words(plan.toolchain, escape_path)) words += " " + w; + f.ld += words; + f.ldC += words; } + } // THE LINKER'S OWN REPORT (SPEC-004 §8.1, mcpp#931). What the flags name // is known when the graph is written; what the linker finds by searching diff --git a/src/build/prepare/local_toolchain.cpp b/src/build/prepare/local_toolchain.cpp index 06d16279a..e9410b9cf 100644 --- a/src/build/prepare/local_toolchain.cpp +++ b/src/build/prepare/local_toolchain.cpp @@ -25,6 +25,7 @@ import mcpp.toolchain.triple; import mcpp.toolchain.post_install; import mcpp.toolchain.probe; // the tree's probes, `ask_driver` import mcpp.toolchain.model; +import mcpp.toolchain.linkmodel; // lld_name, linker_name import mcpp.diag; import mcpp.ui; @@ -337,9 +338,10 @@ step2_use_local_toolchain(PrepareState& state, const mcpp::toolchain::ToolchainS for (auto const& [role, p] : lt.tools) if (!fs::exists(p, ec)) return refuse(std::format("tools.{} names '{}', which does not exist", role, p)); - // A STATED LINKER REACHES THE LINK THROUGH CLANG'S `--ld-path`, which gcc - // does not have: gcc selects a linker by the name `ld` inside a `-B` - // directory, so a program named anything else cannot be chosen that way. + // A STATED LINKER REACHES THE LINK BY ITS ADDRESS, WHICH CLANG TAKES AND + // GCC DOES NOT (SPEC-006 §2.10): gcc selects a linker by the name `ld` + // inside a `-B` directory, so a program named anything else cannot be + // chosen that way. // Refused here rather than ignored in the link: the alternative is a stated // tool that enters the fingerprint and takes no part in the build, which is // what this mechanism exists to prevent. @@ -347,8 +349,8 @@ step2_use_local_toolchain(PrepareState& state, const mcpp::toolchain::ToolchainS for (auto const& [role, p] : lt.tools) if (role == "ld") return refuse(std::format( - "tools.ld names '{}', and this is a gcc toolchain: a linker is stated " - "through clang's `--ld-path`, which gcc has no counterpart for. Either " + "tools.ld names '{}', and this is a gcc toolchain: a stated linker is " + "handed to clang by its address, which gcc has no counterpart for. Either " "name an llvm toolchain, or place a program called `ld` in the tree " "gcc searches", p)); state.explicit_compiler = driver; @@ -426,31 +428,48 @@ std::expected step2_apply_local_toolchain(PrepareState& state // WHAT A CLANG TREE NAMED BY PATH LINKS WITH, AND WHETHER IT COMPILES MODULES // (design 2026-11-27 §3.1.2), asked once the build's target is known and with -// its words. The linker: `tools.ld` (through `--ld-path`, flags.cppm and -// hostflags.cppm), else lld in the tree, else the driver's default; a runtime -// word only when the driver has that library. One rule for the project's -// links and the build programs': both read `Toolchain::treeLinkWords`. -void step2_tree_capabilities(PrepareState& state) { - if (!state.tc || state.tc->localRoot.empty()) return; +// its words. The linker (SPEC-020 §9): `tools.ld`, else the tree's lld of the +// link's flavour, else the driver's default -- named by its address, because a +// driver that searches by name searches beside its resolved self, and the +// driver of a tree of links resolves into another tree. A runtime word only +// when the driver has that library. One rule for the project's links and the +// build programs': both read `Toolchain::linker` and `Toolchain::treeLinkWords`. +std::expected step2_tree_capabilities(PrepareState& state) { + if (!state.tc || state.tc->localRoot.empty()) return {}; auto& tc = *state.tc; using Fact = mcpp::toolchain::Toolchain::TreeFact; - if (tc.compiler != mcpp::toolchain::CompilerId::Clang) return; + if (tc.compiler != mcpp::toolchain::CompilerId::Clang) return {}; std::vector base; if (!tc.crossTargetFlag.empty()) base.push_back(tc.crossTargetFlag); const auto env = mcpp::toolchain::compiler_env(tc); std::vector words; std::error_code ec; if (auto* ld = tc.tool_override("ld")) { - tc.treeFacts.push_back(Fact{"linker", std::format("{} (stated, --ld-path)", ld->generic_string())}); + // On the MSVC ABI clang selects a linker by its name in a `-B` directory + // (SPEC-006 §2.10) and takes `link` and `lld` for programs it finds by + // its own rules: a stated linker of either name would not be the one + // that runs. + if (mcpp::toolchain::is_msvc_target(tc)) { + const auto name = mcpp::toolchain::linker_name(*ld); + auto lower = name; + std::ranges::transform(lower, lower.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (lower == "link" || lower == "lld") { + refusal::record(refusal::Code::LocalToolchain); + return std::unexpected(std::format( + "tools.ld names '{}'; on the MSVC ABI clang takes the name `{}` for a program it " + "finds by its own rules, so this one would not be the linker that runs. Give the " + "program another file name, such as `{}-ld.exe`", ld->generic_string(), name, name)); + } + } + tc.linker = *ld; + tc.treeFacts.push_back(Fact{"linker", std::format("{} (stated)", ld->generic_string())}); } else { - fs::path lld; + const auto name = std::string(mcpp::toolchain::lld_name(tc)) + std::string(mcpplibs::os::exe_suffix); for (auto const& dir : {tc.localRoot / "bin", tc.binaryPath.parent_path()}) - for (std::string n : {"ld.lld", "ld64.lld", "lld-link", "lld"}) - if (lld.empty() && fs::exists(dir / (n + std::string(mcpplibs::os::exe_suffix)), ec)) - lld = dir / (n + std::string(mcpplibs::os::exe_suffix)); - if (!lld.empty()) words.push_back("-fuse-ld=lld"); - tc.treeFacts.push_back(Fact{"linker", lld.empty() ? std::string("the driver's default (no lld in the tree)") - : std::format("lld in the tree ({})", lld.generic_string())}); + if (tc.linker.empty() && fs::exists(dir / name, ec)) tc.linker = dir / name; + tc.treeFacts.push_back(Fact{"linker", tc.linker.empty() + ? std::format("the driver's default (no {} in the tree)", name) + : std::format("lld in the tree ({})", tc.linker.generic_string())}); } auto has = [&](std::vector w, std::string_view question) { w.insert(w.begin(), base.begin(), base.end()); @@ -475,6 +494,7 @@ void step2_tree_capabilities(PrepareState& state) { tc.compilesModules = mcpp::toolchain::driver_compiles_modules(tc.binaryPath, base, env, &why); tc.treeFacts.push_back(Fact{"C++ modules", tc.compilesModules ? std::string("a module unit compiles (probed)") : std::format("refused a module unit (probed: {})", why)}); + return {}; } // ONE PACKAGE AT TWO VERSIONS, ONE FOR EACH PURPOSE (design 2026-11-27 D8): diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index 6a7b31e62..a7aa854b0 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -1619,7 +1619,7 @@ void step2_ask_std_module_with_words(PrepareState& state); // local_toolchain.cpp: what a clang tree named by path links with and whether // it compiles modules; and a toolchain package [xlings.workspace] names at // another version (design 2026-11-27 §3.1.2, D8). -void step2_tree_capabilities(PrepareState& state); +std::expected step2_tree_capabilities(PrepareState& state); void step2_toolchain_in_workspace(PrepareState& state); // The system a paired provider supplies to the declared compiler (SPEC-016 §6). std::expected step2_paired_system(PrepareState& state); diff --git a/src/build/prepare/toolchain_resolver.cpp b/src/build/prepare/toolchain_resolver.cpp index 0b3b8f18f..01f25558a 100644 --- a/src/build/prepare/toolchain_resolver.cpp +++ b/src/build/prepare/toolchain_resolver.cpp @@ -1047,7 +1047,7 @@ std::expected phase2_define_toolchain_resolver(PrepareState& if (auto r = step2_bind_msvc_toolset(state); !r) return std::unexpected(r.error()); if (auto r = step2_resolve_base(state); !r) return std::unexpected(r.error()); step2_ask_std_module_with_words(state); - step2_tree_capabilities(state); + if (auto r = step2_tree_capabilities(state); !r) return std::unexpected(r.error()); step2_toolchain_in_workspace(state); if (auto r = step2_resolve_run_under(state); !r) return std::unexpected(r.error()); step2_windows_runtime_identity(state); diff --git a/src/toolchain/hostflags.cppm b/src/toolchain/hostflags.cppm index 7c594aac6..9b35b1a85 100644 --- a/src/toolchain/hostflags.cppm +++ b/src/toolchain/hostflags.cppm @@ -662,11 +662,11 @@ std::vector host_link_tokens(const Toolchain& tc, // and the SDK's library directories from these, not from the machine. for (auto& t : lm.msvc_driver_tokens(esc)) out.push_back(t); - // A stated linker reaches the build programs' links as it reaches the - // project's (flags.cppm): through clang's `--ld-path` (design 2026-11-27 - // §3.1.2, one rule for both kinds of link). + // The linker named by its address reaches the build programs' links as it + // reaches the project's (flags.cppm, SPEC-020 §9): one rule for both kinds + // of link. if (is_clang(tc)) - if (auto* ld = tc.tool_override("ld")) out.push_back("--ld-path=" + esc(*ld)); + for (auto& w : linker_words(tc, esc)) out.push_back(std::move(w)); const bool bypassCfg = dm.hasCfg && (opt.cfgBypass == HostFlagOptions::CfgBypass::Always diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index 8c27a775e..bdb010655 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -47,7 +47,9 @@ E2E custom{"custom", s::home_fixture, [] { const auto T = work / "llvm"; llvm_tree(T); const auto wrapper = work / "ld-wrapper"; - s::write_executable(wrapper, std::format("#!/bin/sh\nexec \"{}/bin/ld.lld\" \"$@\"\n", llvm_root.string())); + const auto linked = work / "ld-wrapper.log"; + s::write_executable(wrapper, std::format("#!/bin/sh\necho \"$@\" >> '{}'\nexec \"{}/bin/ld.lld\" \"$@\"\n", + linked.string(), llvm_root.string())); const s::options o{.env = {{"NO_COLOR", "1"}}}; s::project app(work / "app", {{"src/main.cpp", "#include \nint main() { std::puts(\"built by a toolchain named by path\"); return 0; }\n"}}); auto write_manifest = [&](const fs::path& root, std::string_view extra) { @@ -68,7 +70,8 @@ E2E custom{"custom", s::home_fixture, [] { std::string ninja; for (const auto& n : s::glob(app.at("target"), "*/*/build.ninja")) ninja += s::read_file(n); expect(fatal(s::has_line(ninja, std::format(R"(^cxx *= /usr/bin/env {}/bin/clang\+\+)", literal(T.string()))))) << "FAIL: the launcher does not prefix the compiler"; - expect(fatal(e2e::contains(ninja, "--ld-path=" + wrapper.string()))) << "FAIL: the stated linker is not used"; + expect(fatal(e2e::contains(ninja, "--ld-path=" + wrapper.string()))) << "FAIL: the stated linker is not named"; + expect(fatal(fs::exists(linked) && !s::read_file(linked).empty())) << "FAIL: the stated linker did not run"; bool cfg = false; for (const auto& e : fs::directory_iterator(T)) { if (e.path().extension() == ".cfg") cfg = true; @@ -231,6 +234,67 @@ E2E custom{"custom", s::home_fixture, [] { expect(s::lacks(out, "another library was taken")) << out; }; + "a tree's lld is named by its address"_test[s::llvm][s::unix_shell][s::symlink] = [] { + // SPEC-020 §9: the linker of a tree named by path is the tree's lld of the link's + // flavour, handed to the driver by its address. The tree's driver is a link into the + // payload, so a driver that searched by name beside its resolved self would run the + // payload's lld; the tree's own `ld.lld` here records each call. + const auto llvm_root = s::payload_root("xim-x-llvm", s::llvm_version()); + if (!fs::exists(llvm_root / "bin/clang++")) skip(std::format("no llvm payload installed ({})", llvm_root.string())); + const auto work = s::case_dir(); + const auto T = work / "llvm"; + llvm_tree(T); + const auto linked = work / "tree-lld.log"; + fs::remove(T / "bin/ld.lld"); + s::write_executable(T / "bin/ld.lld", std::format("#!/bin/sh\necho \"$@\" >> '{}'\nexec '{}/bin/ld.lld' \"$@\"\n", + linked.string(), llvm_root.string())); + s::project app(work / "app", {{"src/main.cpp", "int main() { return 0; }\n"}}); + app.write("mcpp.toml", std::format("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[toolchain]\ndefault = {{ path = \"{}\" }}\n", T.string())); + const s::options o{.env = {{"NO_COLOR", "1"}}}; + auto r = app.mcpp({"build"}, o); + expect(fatal(e2e::succeeded(r))) << s::text(r); + std::string ninja; + for (const auto& n : s::glob(app.at("target"), "*/*/build.ninja")) ninja += s::read_file(n); + expect(e2e::contains(ninja, "--ld-path=" + (T / "bin/ld.lld").string())) << "the tree's lld is not named by its address"; + expect(fatal(fs::exists(linked) && !s::read_file(linked).empty())) << "the tree's lld did not run"; + r = app.mcpp({"why", "toolchain"}, o); + expect(e2e::contains(s::text(r), "linker: lld in the tree (" + (T / "bin/ld.lld").generic_string() + ")")) << s::text(r); + }; + + "a stated linker runs on the msvc abi"_test[s::windows] = [] { + // SPEC-006 §2.10: the MSVC route of clang reads no `--ld-path`; a stated linker is named + // in a `-B` directory by its file name, and the driver runs it. Shown by the driver's own + // account of the link (`-v`), which prints the program it starts in quotes. + const auto llvm_root = s::payload_root("xim-x-llvm", s::llvm_version()); + if (!fs::exists(llvm_root / "bin/lld-link.exe")) skip(std::format("no llvm payload installed ({})", llvm_root.string())); + const auto work = s::case_dir(); + fs::create_directories(work / "tools"); + const auto tracer = work / "tools" / "trace-link.exe"; + std::error_code ec; + fs::create_hard_link(llvm_root / "bin/lld-link.exe", tracer, ec); + if (ec) fs::copy_file(llvm_root / "bin/lld-link.exe", tracer); + s::project app(work / "app", {{"src/main.cpp", "int main() { return 0; }\n"}}); + app.write("mcpp.toml", std::format("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[build]\nldflags = [\"-v\"]\n\n" + "[toolchain]\ndefault = {{ path = '{}', tools = {{ ld = '{}' }} }}\n", + llvm_root.generic_string(), tracer.generic_string())); + const s::options o{.env = {{"NO_COLOR", "1"}}}; + auto r = app.mcpp({"build", "--verbose"}, o); + const auto out = s::text(r); + expect(fatal(e2e::succeeded(r))) << out; + expect(s::has_line(out, R"(trace-link(\.exe)?")")) << "the driver did not start the stated linker:\n" << out; + expect(s::lacks(out, "argument unused during compilation: '--ld-path")) << out; + // A linker the MSVC route takes by its own rules cannot be named by address. + const auto named_link = work / "named" / "link.exe"; + fs::create_directories(named_link.parent_path()); + fs::copy_file(tracer, named_link, ec); + app.write("mcpp.toml", std::format("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n" + "[toolchain]\ndefault = {{ path = '{}', tools = {{ ld = '{}' }} }}\n", + llvm_root.generic_string(), named_link.generic_string())); + r = app.mcpp({"build"}, o); + expect(!e2e::succeeded(r)) << "a linker named link was accepted: " << s::text(r); + expect(e2e::contains(s::text(r), "Give the program another file name")) << s::text(r); + }; + "a tree's linker, archiver and modules are taken from its statement or a probe"_test[s::llvm][s::unix_shell][s::symlink] = [] { // Design 2026-11-27 §3.1.2: a tree without lld links with its driver's default linker; a // stated archiver that reads `@file` as a member's name is given the expanded words; `mcpp From f1016e42a0a64f3ce696b4a04b2b81381ff9c0ec Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:22:09 +0900 Subject: [PATCH 10/18] Every clang driver mcpp starts sees itself by the path it was started by; the hermetic check compares its directories by components --- modules/toolchain-model/src/linkmodel.cppm | 2 +- modules/toolchain-model/src/model.cppm | 22 ++++++++++++- .../tests/test_linker_words.cpp | 2 +- src/build/flags.cppm | 16 +++++++++- src/build/hermetic.cppm | 21 ++++++------ src/build/ninja_backend.cppm | 4 ++- src/build/prepare/base.cpp | 1 + src/build/prepare/local_toolchain.cpp | 6 ++-- src/build/prepare/retarget.cpp | 2 +- src/pack/pipeline.cppm | 1 + src/toolchain/clang.cppm | 32 +++++++++---------- src/toolchain/hostflags.cppm | 4 +++ src/toolchain/msvc_coroutines.cppm | 5 +-- src/toolchain/probe.cppm | 2 +- tests/e2e/toolchain/custom.cpp | 8 +++-- tests/unit/test_hostflags.cpp | 4 ++- 16 files changed, 91 insertions(+), 41 deletions(-) diff --git a/modules/toolchain-model/src/linkmodel.cppm b/modules/toolchain-model/src/linkmodel.cppm index e037bfcd6..58d7f5f39 100644 --- a/modules/toolchain-model/src/linkmodel.cppm +++ b/modules/toolchain-model/src/linkmodel.cppm @@ -359,7 +359,7 @@ ClangDriverModel resolve_clang_driver(const Toolchain& tc); std::string_view lld_name(const Toolchain& tc); // THE WORDS THAT HAND `tc.linker` TO A CLANG DRIVER, by the route each driver -// reads it (SPEC-006 §2.10; measured with `-###` on LLVM 23.1.3): +// reads it (SPEC-006 §3.12; measured with `-###` on LLVM 23.1.3): // ELF, Mach-O, MinGW `--ld-path=`, after `-fuse-ld=lld` when the // program is an lld, which tells the driver so // wasm `-fuse-ld=`: the wasm linker reads no `--ld-path` diff --git a/modules/toolchain-model/src/model.cppm b/modules/toolchain-model/src/model.cppm index 78ab02988..21a4847d1 100644 --- a/modules/toolchain-model/src/model.cppm +++ b/modules/toolchain-model/src/model.cppm @@ -302,7 +302,7 @@ struct Toolchain { // takes the path of a compiler without C++ modules // treeFacts each fact with its source, for `mcpp why toolchain` std::optional> treeLinkWords; - // THE LINKER, NAMED BY ITS ADDRESS (SPEC-020 §9, SPEC-006 §2.10): the + // THE LINKER, NAMED BY ITS ADDRESS (SPEC-020 §9, SPEC-006 §3.12): the // stated `tools.ld`, else the lld of the link's flavour in a clang tree // named by path. A driver that finds lld by name finds it beside its // resolved self, and a tree of links resolves elsewhere. Empty: the @@ -366,6 +366,20 @@ bool is_musl_target(const Toolchain& tc); bool is_msvc_target(const Toolchain& tc); bool is_mingw_target(const Toolchain& tc); +// THE WORD THAT HAS A CLANG DRIVER SEE ITSELF BY THE PATH IT WAS STARTED BY +// (SPEC-020 §9). Without it the driver resolves its own path to the physical +// one (`getMainExecutable`, `real_path`) and derives its installation, resource +// and program directories from that: a tree of links resolves into the tree it +// links to, and a drive alias into a path a process granted only the alias +// cannot open. Measured on LLVM 23.1.3 with a tree of links: `-print-resource- +// dir` and `-print-prog-name=ld.lld` answer the payload's directories without +// it and the tree's with it. +inline constexpr std::string_view kDriverSelfWord = "-no-canonical-prefixes"; +// The word for `tc`'s driver on every command mcpp starts: clang's, unless the +// toolchain ships its own sysroot (`em++` is a wrapper whose configuration is +// its own, and is told nothing it does not need); none for any other driver. +std::vector driver_self_words(const Toolchain& tc); + // THE FLAGS A WHOLE GRAPH HAS TO AGREE ON WHEN THE RUNTIME COMES FROM IT. // // An ordinary flag is a package's business. These two are not: they change what @@ -618,6 +632,12 @@ bool is_clang(const Toolchain& tc) { return tc.compiler == CompilerId::Clang; } +std::vector driver_self_words(const Toolchain& tc) { + if (!is_clang(tc)) return {}; + if (auto t = triple::parse(tc.targetTriple); t && t->has_own_sysroot()) return {}; + return {std::string(kDriverSelfWord)}; +} + // Target-shape predicates read the parsed canonical Triple (triple.cppm is // the single triple parser), with the old substring heuristics kept only as // a fallback for triples outside the language. This makes them spelling- diff --git a/modules/toolchain-model/tests/test_linker_words.cpp b/modules/toolchain-model/tests/test_linker_words.cpp index 624c714bd..851096e73 100644 --- a/modules/toolchain-model/tests/test_linker_words.cpp +++ b/modules/toolchain-model/tests/test_linker_words.cpp @@ -5,7 +5,7 @@ import mcpp.toolchain.linkmodel; using namespace mcpplibs::mtest; -// SUBSYSTEM-LEVEL: the linker named by its address (SPEC-020 §9, SPEC-006 §2.10). One fact, +// SUBSYSTEM-LEVEL: the linker named by its address (SPEC-020 §9, SPEC-006 §3.12). One fact, // handed to the driver in the form the target's route reads; measured with `-###` on LLVM // 23.1.3: `--ld-path` reaches the ELF, Mach-O and MinGW links, the wasm link reads only an // absolute `-fuse-ld`, and the MSVC link reads only `-fuse-ld`, by a name it looks up in `-B`. diff --git a/src/build/flags.cppm b/src/build/flags.cppm index 3ff92d2b9..3cc06cd5a 100644 --- a/src/build/flags.cppm +++ b/src/build/flags.cppm @@ -1790,7 +1790,7 @@ CompileFlags compute_flags_impl(const BuildPlan& plan, bool packageLinkFlags) { const bool driverPlacesArchives = (format == dist::Format::Elf || format == dist::Format::MachO) && !mi.freestanding && !mi.graphCxxRuntime && !mi.appleCrossTarget; - std::vector driverFlags; + std::vector driverFlags = mcpp::toolchain::driver_self_words(plan.toolchain); if (!plan.toolchain.crossTargetFlag.empty()) driverFlags.push_back(plan.toolchain.crossTargetFlag); if (isClangWithCfg) driverFlags.push_back("--no-default-config"); auto find_archive = [&](std::string_view name) -> std::filesystem::path { @@ -2873,6 +2873,20 @@ CompileFlags compute_flags_impl(const BuildPlan& plan, bool packageLinkFlags) { f.ldC += words; } } + // THE DRIVER SEES ITSELF BY THE PATH IT WAS STARTED BY (SPEC-020 §9), on + // every line it runs, whichever shape built the line: the compile words + // carry it from `host_compile_tokens` where a shape reads them, and a + // shape that builds its own line (freestanding, a graph-supplied target + // side) is given it here. A line the linker runs itself takes no driver + // word. + for (auto const& w : mcpp::toolchain::driver_self_words(plan.toolchain)) { + const auto word = " " + w; + for (auto* line : {&f.cxx, &f.cc, &f.as}) + if (!line->contains(word)) *line += word; + if (f.ldDriver.empty()) + for (auto* line : {&f.ld, &f.ldC}) + if (!line->contains(word)) *line += word; + } // THE LINKER'S OWN REPORT (SPEC-004 §8.1, mcpp#931). What the flags name // is known when the graph is written; what the linker finds by searching diff --git a/src/build/hermetic.cppm b/src/build/hermetic.cppm index b33b95efb..8ffecf872 100644 --- a/src/build/hermetic.cppm +++ b/src/build/hermetic.cppm @@ -52,6 +52,7 @@ module :private; import mcpp.log; import mcpplibs.os.platform; +import mcpplibs.os.fs; import mcpp.build.command_line; import mcpp.run; import mcpp.provider; @@ -86,14 +87,14 @@ bool is_crt_object(std::string_view base) { || base.find("clang_rt.crt") != std::string_view::npos; } +// Whether the name `p` lies within one of `prefixes`, by its components +// (SPEC-020 §4.3): the driver's answer is a name, as it spelled it. bool under_any(const std::filesystem::path& p, const std::vector& prefixes) { - auto s = p.lexically_normal().string(); - for (auto& pre : prefixes) { - if (pre.empty()) continue; - if (s.starts_with(pre.lexically_normal().string())) return true; - } - return false; + const auto name = p.lexically_normal(); + return std::ranges::any_of(prefixes, [&](const std::filesystem::path& pre) { + return !pre.empty() && mcpplibs::os::fs::within(name, pre.lexically_normal()); + }); } // Split a `-###` output line into tokens; the driver quotes each argument @@ -163,9 +164,11 @@ std::expected verify_hermetic_link( std::vector allowed; allowed.push_back(*store); // A toolchain borrowed from an upstream is a link entry (design - // 2026-10-16 §8): mcpp passes the link's paths on the command line, but - // the driver reports its own resource dir (clang_rt.crt*) through the - // path the link names. That store is allowed too. + // 2026-10-16 §8). A clang driver reports its resource directory through + // the path it was started by (`-no-canonical-prefixes`, SPEC-020 §9), + // which lies in this store; gcc resolves its own path and reports its + // runtime (crtbegin.o) through the store the link leads to, which is + // allowed too (measured: e2e layers/201 under a home that borrows gcc). if (auto upstream = mcpp::provider::store_of(mcpp::libs::path_identity::resolved(tc.binaryPath))) allowed.push_back(*upstream); // Every store of the build, and its stated base, as the table names them. diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index e7e73d87f..87106b420 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -2094,7 +2094,9 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, append(" command = $mcpp platform-step capture --out $out -- $argv\n"); append(" description = GEN $out\n\n"); append("rule platform_asm\n"); - append(std::format(" command = $cc {}-c $in -o $out\n", + std::string self; + for (auto const& w : mcpp::toolchain::driver_self_words(plan.toolchain)) self += w + " "; + append(std::format(" command = $cc {}{}-c $in -o $out\n", self, clangDriver && tt ? std::format("--target={} --no-default-config ", tt->llvm_triple()) : std::string{})); diff --git a/src/build/prepare/base.cpp b/src/build/prepare/base.cpp index f5b2350ce..e4cd9a749 100644 --- a/src/build/prepare/base.cpp +++ b/src/build/prepare/base.cpp @@ -243,6 +243,7 @@ namespace { // a measurement asks. std::vector driver_base(const mcpp::toolchain::Toolchain& tc) { std::vector v{tc.binaryPath.string()}; + for (auto& w : mcpp::toolchain::driver_self_words(tc)) v.push_back(std::move(w)); if (mcpp::toolchain::is_clang(tc)) v.push_back("--no-default-config"); if (!tc.crossTargetFlag.empty()) v.push_back(tc.crossTargetFlag); return v; diff --git a/src/build/prepare/local_toolchain.cpp b/src/build/prepare/local_toolchain.cpp index e9410b9cf..cae639dff 100644 --- a/src/build/prepare/local_toolchain.cpp +++ b/src/build/prepare/local_toolchain.cpp @@ -339,7 +339,7 @@ step2_use_local_toolchain(PrepareState& state, const mcpp::toolchain::ToolchainS if (!fs::exists(p, ec)) return refuse(std::format("tools.{} names '{}', which does not exist", role, p)); // A STATED LINKER REACHES THE LINK BY ITS ADDRESS, WHICH CLANG TAKES AND - // GCC DOES NOT (SPEC-006 §2.10): gcc selects a linker by the name `ld` + // GCC DOES NOT (SPEC-006 §3.12): gcc selects a linker by the name `ld` // inside a `-B` directory, so a program named anything else cannot be // chosen that way. // Refused here rather than ignored in the link: the alternative is a stated @@ -439,14 +439,14 @@ std::expected step2_tree_capabilities(PrepareState& state) { auto& tc = *state.tc; using Fact = mcpp::toolchain::Toolchain::TreeFact; if (tc.compiler != mcpp::toolchain::CompilerId::Clang) return {}; - std::vector base; + std::vector base = mcpp::toolchain::driver_self_words(tc); if (!tc.crossTargetFlag.empty()) base.push_back(tc.crossTargetFlag); const auto env = mcpp::toolchain::compiler_env(tc); std::vector words; std::error_code ec; if (auto* ld = tc.tool_override("ld")) { // On the MSVC ABI clang selects a linker by its name in a `-B` directory - // (SPEC-006 §2.10) and takes `link` and `lld` for programs it finds by + // (SPEC-006 §3.12) and takes `link` and `lld` for programs it finds by // its own rules: a stated linker of either name would not be the one // that runs. if (mcpp::toolchain::is_msvc_target(tc)) { diff --git a/src/build/prepare/retarget.cpp b/src/build/prepare/retarget.cpp index 0643f802a..a934d61e7 100644 --- a/src/build/prepare/retarget.cpp +++ b/src/build/prepare/retarget.cpp @@ -488,7 +488,7 @@ void step2_ask_std_module_with_words(PrepareState& state) { if (!cross && mcpp::toolchain::inside_roots(tc.stdModuleSource, roots)) return; // The words the std module's precompile is given (mcpp.toolchain.stdmod): // the target, the base, the library the cfg bypass selects. - std::vector words; + std::vector words = mcpp::toolchain::driver_self_words(tc); if (cross) { mcpp::toolchain::HostFlagOptions hopt; hopt.cfgBypass = mcpp::toolchain::HostFlagOptions::CfgBypass::Always; diff --git a/src/pack/pipeline.cppm b/src/pack/pipeline.cppm index f3afc2097..e3c1d532a 100644 --- a/src/pack/pipeline.cppm +++ b/src/pack/pipeline.cppm @@ -207,6 +207,7 @@ DriverLibraryDirs driver_library_dirs(const mcpp::toolchain::Toolchain& tc) DriverLibraryDirs out; auto query = [&](std::string_view flag) { std::vector argv{ tc.binaryPath.string() }; + for (auto& w : mcpp::toolchain::driver_self_words(tc)) argv.push_back(std::move(w)); if (!tc.crossTargetFlag.empty()) argv.push_back(tc.crossTargetFlag); argv.emplace_back(flag); return mcpp::toolchain::run_capture(argv, mcpp::toolchain::compiler_env(tc)); diff --git a/src/toolchain/clang.cppm b/src/toolchain/clang.cppm index 71f29f91b..1d117bde1 100644 --- a/src/toolchain/clang.cppm +++ b/src/toolchain/clang.cppm @@ -49,9 +49,8 @@ std::vector std_module_build_commands(const Toolchain& tc, std::string_view cppStandardFlag, std::string_view crtFlag = {}); -std::optional find_libcxx_std_compat_source( - const std::filesystem::path& cxx_binary, - const mcpp::run::Env& env); +// `std.compat.cppm` beside the std module source `stdSource`, when it is there. +std::optional find_libcxx_std_compat_source(const std::filesystem::path& stdSource); std::filesystem::path std_compat_bmi_path(const std::filesystem::path& cacheDir); std::filesystem::path staged_std_compat_bmi_path(const std::filesystem::path& outputDir); @@ -246,10 +245,11 @@ void enrich_toolchain(Toolchain& tc, const mcpp::run::Env& env) { // host without one (mcpp#1039: an NDK clang named the host GCC's // `libstdc++.modules.json`); the next probe finds its own. A build asks // again with its words (prepare, `step2_ask_std_module_with_words`). + // The driver sees itself by the path it was started by (SPEC-020 §9). + const auto self = mcpp::toolchain::driver_self_words(tc); std::vector rejected; - if (auto p = find_libcxx_std_module_source(tc.binaryPath, env, {}, tree_roots(tc), &rejected)) { - tc.set_std_modules(*p, find_libcxx_std_compat_source(tc.binaryPath, env) - .value_or(std::filesystem::path{})); + if (auto p = find_libcxx_std_module_source(tc.binaryPath, env, self, tree_roots(tc), &rejected)) { + tc.set_std_modules(*p, find_libcxx_std_compat_source(*p).value_or(std::filesystem::path{})); // libc++ documents the std module for C++20 and later, and its // std.cppm carries no __cplusplus guard. Verified on clang 22.1.8 + // libc++ (std and std.compat) at -std=c++20 (design §2.2). @@ -260,8 +260,10 @@ void enrich_toolchain(Toolchain& tc, const mcpp::run::Env& env) { // the refusal of `import std`, which otherwise names only its absence. // A driver for the MSVC ABI is not asked: its std module is the STL's, // looked for below. - if (auto r = mcpp::toolchain::run_capture( - { tc.binaryPath.string(), "--print-file-name=libc++.a" }, env, /*withErrors=*/true); !r) + std::vector argv{tc.binaryPath.string()}; + argv.insert(argv.end(), self.begin(), self.end()); + argv.push_back("--print-file-name=libc++.a"); + if (auto r = mcpp::toolchain::run_capture(argv, env, /*withErrors=*/true); !r) tc.stdModuleUnanswered = r.error().message; } for (auto const& r : rejected) @@ -549,9 +551,7 @@ std::filesystem::path runtime_archive_path(const Toolchain& tc, return out; } -std::optional find_libcxx_std_compat_source( - const std::filesystem::path& cxx_binary, - const mcpp::run::Env& env) +std::optional find_libcxx_std_compat_source(const std::filesystem::path& stdSource) { // DERIVED FROM THE SIBLING, NOT SEARCHED FOR SEPARATELY. // @@ -564,11 +564,11 @@ std::optional find_libcxx_std_compat_source( // `std.compat.cppm` sits beside `std.cppm` in every libc++ layout, because // the same install rule places both. Deriving it makes the two answers // structurally consistent rather than two searches that can disagree, - // which is what the comment claimed all along. - if (auto std_src = find_libcxx_std_module_source(cxx_binary, env)) { - auto p = std_src->parent_path() / "std.compat.cppm"; - if (std::filesystem::exists(p)) return p; - } + // which is what the comment claimed all along. The sibling of the answer + // already taken, so it is asked by the same words and held to the same roots. + std::error_code ec; + auto p = stdSource.parent_path() / "std.compat.cppm"; + if (std::filesystem::exists(p, ec)) return p; return std::nullopt; } diff --git a/src/toolchain/hostflags.cppm b/src/toolchain/hostflags.cppm index 9b35b1a85..8554bc2ee 100644 --- a/src/toolchain/hostflags.cppm +++ b/src/toolchain/hostflags.cppm @@ -324,6 +324,9 @@ std::vector host_compile_tokens(const Toolchain& tc, // produce a string of unknown options and then LNK1181. if (tc.compiler == CompilerId::MSVC) return out; + // The driver sees itself by the path it was started by (SPEC-020 §9). + for (auto& w : driver_self_words(tc)) out.push_back(std::move(w)); + const auto dm = resolve_clang_driver(tc); const auto lm = resolve_link_model(tc); @@ -654,6 +657,7 @@ std::vector host_link_tokens(const Toolchain& tc, const PathEscape& esc) { std::vector out; if (tc.compiler == CompilerId::MSVC) return out; + for (auto& w : driver_self_words(tc)) out.push_back(std::move(w)); const auto dm = resolve_clang_driver(tc); const auto lm = resolve_link_model(tc); diff --git a/src/toolchain/msvc_coroutines.cppm b/src/toolchain/msvc_coroutines.cppm index 95dee9164..f20c8b99e 100644 --- a/src/toolchain/msvc_coroutines.cppm +++ b/src/toolchain/msvc_coroutines.cppm @@ -89,6 +89,7 @@ std::string advice(std::string_view output); module :private; import mcpp.run; +import mcpp.toolchain.model; // kDriverSelfWord import mcpp.toolchain.triple; namespace mcpp::toolchain::msvc_coroutines { @@ -308,8 +309,8 @@ std::optional run_probe(const FailedCommand& cmd) { / std::format("mcpp-coroutine-probe-{}.cpp", std::random_device{}()); if (ec) return std::nullopt; { std::ofstream touch(empty); if (!touch) return std::nullopt; } - std::vector argv{cmd.compiler, "--no-default-config", - "--target=" + cmd.target}; + std::vector argv{cmd.compiler, std::string(mcpp::toolchain::kDriverSelfWord), + "--no-default-config", "--target=" + cmd.target}; if (!cmd.standard.empty()) argv.push_back("-std=" + cmd.standard); for (std::string_view a : {"-dM", "-E", "-x", "c++"}) argv.emplace_back(a); argv.push_back(empty.string()); diff --git a/src/toolchain/probe.cppm b/src/toolchain/probe.cppm index 7d36cd4fb..42451d2d5 100644 --- a/src/toolchain/probe.cppm +++ b/src/toolchain/probe.cppm @@ -235,7 +235,7 @@ bool compresses_debug_sections(const std::filesystem::path& compiler, const mcpp // of its own, and its driver runs the one on PATH -- on a CI image, // another LLVM's, built without zlib. std::filesystem::path lld; - if (auto r = run_capture({compiler.string(), "-print-prog-name=ld.lld"}, env)) { + if (auto r = run_capture({compiler.string(), std::string(kDriverSelfWord), "-print-prog-name=ld.lld"}, env)) { const auto named = std::filesystem::path(trim_line(first_line_of(*r))); std::error_code fec; if (named.is_absolute() && std::filesystem::exists(named, fec)) lld = named; diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index bdb010655..64f06ee94 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -262,7 +262,7 @@ E2E custom{"custom", s::home_fixture, [] { }; "a stated linker runs on the msvc abi"_test[s::windows] = [] { - // SPEC-006 §2.10: the MSVC route of clang reads no `--ld-path`; a stated linker is named + // SPEC-006 §3.12: the MSVC route of clang reads no `--ld-path`; a stated linker is named // in a `-B` directory by its file name, and the driver runs it. Shown by the driver's own // account of the link (`-v`), which prints the program it starts in quotes. const auto llvm_root = s::payload_root("xim-x-llvm", s::llvm_version()); @@ -345,12 +345,14 @@ E2E custom{"custom", s::home_fixture, [] { expect(e2e::contains(out, "takes its arguments directly")) << out; expect(e2e::contains(out, "C++ modules: a module unit compiles")) << out; - // A driver that refuses a module unit. + // A driver that refuses a module unit. It runs the payload's own driver, which reads its own + // configuration: the tree holds no `.cfg`, and a driver started from it sees itself there + // (SPEC-020 §9), so the tree's driver would find no C++ library of its own. const auto driver = work / "driver" / "clang++"; s::write_executable(driver, std::format( "#!/bin/sh\nfor a in \"$@\"; do case \"$a\" in c++-module|--precompile) " "echo \"error: this driver takes no module unit\" >&2; exit 1;; esac; done\nexec '{}/bin/clang++' \"$@\"\n", - T.string())); + llvm_root.string())); s::project plain(work / "plain", {{"src/main.cpp", "#include \nint main() { std::puts(\"no modules\"); }\n"}}); plain.write("mcpp.toml", std::format( "[package]\nname = \"plain\"\nversion = \"0.1.0\"\n\n[toolchain]\n" diff --git a/tests/unit/test_hostflags.cpp b/tests/unit/test_hostflags.cpp index d52dca926..ac75d2d46 100644 --- a/tests/unit/test_hostflags.cpp +++ b/tests/unit/test_hostflags.cpp @@ -945,8 +945,10 @@ UTest payload_served_command_line_is_unchanged{"HostFlags/PayloadServedCommandLi const auto toks = mcpp::toolchain::host_compile_tokens( tc, opt, mcpp::toolchain::no_escape); + // The driver's word for itself leads (SPEC-020 §9); the rest is the + // sequence this guard has always held. const std::vector expected{ - "--no-default-config", "-nostdinc++", + "-no-canonical-prefixes", "--no-default-config", "-nostdinc++", "-isystem" + (fx.root / "include" / "c++" / "v1").string(), }; expect(eq(toks, expected)); From 5b36f478cbe3dad696d4687b096b534c31e3b83f Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:22:09 +0900 Subject: [PATCH 11/18] On the MSVC ABI, -nostdlib in [build] ldflags is noted once: each object still names the default libraries of the CRT model --- modules/notice/src/notice.cppm | 1 + src/build/prepare/scan.cpp | 11 +++++++++++ tests/e2e/golden/surface.txt | 1 + tests/e2e/windows/crt.cpp | 12 ++++++++++++ 4 files changed, 25 insertions(+) diff --git a/modules/notice/src/notice.cppm b/modules/notice/src/notice.cppm index 8cc893420..157feb667 100644 --- a/modules/notice/src/notice.cppm +++ b/modules/notice/src/notice.cppm @@ -29,6 +29,7 @@ inline constexpr Kind kKinds[] = { {"toolchain/tree-holds-two-families", Policy::Once, "docs/20-toolchains.md, \"`{ path = … }`\""}, {"xlings/package-at-two-versions", Policy::Once, "docs/23-the-project-environment.md, \"`[xlings]`\""}, {"bundle-lacks-target", Policy::Always, "docs/05-dependencies.md, \"Offline builds and mcpp fetch\""}, + {"build/msvc-nostdlib", Policy::Once, "docs/20-toolchains.md, \"On the MSVC runtime\""}, }; // The row of `domain`, or none. diff --git a/src/build/prepare/scan.cpp b/src/build/prepare/scan.cpp index 08a29881d..aff03dddb 100644 --- a/src/build/prepare/scan.cpp +++ b/src/build/prepare/scan.cpp @@ -682,6 +682,17 @@ step11_msvc_crt_word_check(PrepareState& state) { if (auto r = check_words(pkg.manifest.buildConfig.dialectCxxflags, "[build] dialect_cxxflags", "dialect_cxxflags"); !r) return std::unexpected(r.error()); + // `-nostdlib` IN THE LINK FLAGS DOES NOT TAKE THE CRT AWAY HERE + // (design 2026-12-07 §4.7, D4): it drops the driver's `-defaultlib:` + // words, and each object still names the CRT model's default + // libraries. The build is unchanged; the reader is told once. + if (isRoot && std::ranges::contains(mcpp::manifest::flag_words(pkg.manifest.buildConfig.ldflags), + std::string("-nostdlib"))) + mcpp::diag::notice(mcpp::diag::Severity::Note, "build/msvc-nostdlib", pkg.manifest.package.name, + "[build] ldflags states -nostdlib on the MSVC ABI, and each object still names the " + "default libraries of the CRT model", + "a program without the CRT states `-fms-omit-default-lib` (clang) or `/Zl` (cl) in " + "its compile flags as well; docs/20, \"On the MSVC runtime\""); } } return {}; diff --git a/tests/e2e/golden/surface.txt b/tests/e2e/golden/surface.txt index 16a8ac25f..b4aae6847 100644 --- a/tests/e2e/golden/surface.txt +++ b/tests/e2e/golden/surface.txt @@ -432,6 +432,7 @@ reason vcs-unavailable reason version-floor-unmet notice build-program/includes-header notice build-program/reads-outside +notice build/msvc-nostdlib notice bundle-lacks-target notice host-input notice machine-path-in-manifest diff --git a/tests/e2e/windows/crt.cpp b/tests/e2e/windows/crt.cpp index 6689783cb..729e24cf0 100644 --- a/tests/e2e/windows/crt.cpp +++ b/tests/e2e/windows/crt.cpp @@ -163,6 +163,18 @@ E2E crt{"crt", s::home_fixture, [] { expect(fatal(e2e::succeeded(r))) << "a dependency's agreeing CRT word was refused: " << s::text(r); expect(fatal(!e2e::contains(s::text(r), "agrees with the CRT model"))) << "a dependency's agreeing CRT word was warned: " << s::text(r); }; + "a -nostdlib link on the msvc abi is noted"_test[s::windows] = [] { + // Design 2026-12-07 §4.7 (D4): on the MSVC ABI `-nostdlib` in `[build] ldflags` drops the + // driver's `-defaultlib:` words, and each object still names the default libraries of the + // CRT model; a note says so (`build/msvc-nostdlib`), and nothing else changes. + s::project p{{"src/main.cpp", "int main() { return 0; }\n"}, {"mcpp.toml", app_manifest("", false)}}; + default_build_on_llvm_row(p); + p.write("mcpp.toml", app_manifest("ldflags = [\"-nostdlib\"]", false)); + const auto r = p.mcpp({"build"}); + expect(e2e::contains(s::text(r), "[build] ldflags states -nostdlib on the MSVC ABI")) << s::text(r); + expect(e2e::contains(s::text(r), "-fms-omit-default-lib")) << s::text(r); + }; + "888 the llvm row in a developer environment"_test[s::windows] = [] { // vcvars exports WindowsSdkDir with a trailing backslash; rendered as "...\Windows Kits\10\" // the closing quote was escaped under the Windows argv rules and the std module's precompile From a2371ea8acd916622f2106bf64efd068c205e111 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:22:09 +0900 Subject: [PATCH 12/18] The test kit gives a directory a second spelling and reads a compile command; a test run under --verbose and a home named through an alias are cases --- tests/e2e/build/alias.cpp | 62 ++++++++++++++++++++++++++++++++++ tests/e2e/pack/verbosity.cpp | 12 +------ tests/e2e/test/verbosity.cpp | 33 ++++++++++++++++++ tests/support/src/support.cpp | 25 ++++++++++++++ tests/support/src/support.cppm | 19 +++++++++++ 5 files changed, 140 insertions(+), 11 deletions(-) create mode 100644 tests/e2e/build/alias.cpp create mode 100644 tests/e2e/test/verbosity.cpp diff --git a/tests/e2e/build/alias.cpp b/tests/e2e/build/alias.cpp new file mode 100644 index 000000000..c5cd2974d --- /dev/null +++ b/tests/e2e/build/alias.cpp @@ -0,0 +1,62 @@ +// A path given through an alias is kept as it is given (SPEC-020 §2, design 2026-12-07 §7): a home +// initialized and named through a link is named so in the graph and the compile database of a +// build, a test run and a pack, never by its physical spelling; a path dependency named by two +// spellings of one directory is one package. +import std; +import mcpplibs.mtest; +import mcpp.test.support; + +using namespace mcpplibs::mtest; +namespace s = mcpp::test::support; +namespace fs = std::filesystem; + +namespace { + +// The graph and the compile database of every build under `target`. +std::string graphs_of(const s::project& p) { + std::string text; + for (const auto& n : s::glob(p.at("target"), "*/*/build.ninja")) text += s::read_file(n); + for (const auto& n : s::find_files(p.at("target"), "compile_commands\\.json")) text += s::read_file(n); + return text; +} + +E2E alias{"alias", s::home_fixture, [] { + "a home given through an alias is named by the alias"_test[s::symlink] = [] { + const auto [via, home] = s::aliased_home(); + const s::options o{.env = {{"MCPP_HOME", via.string()}}}; + s::project p{{"mcpp.toml", "[package]\nname = \"aliased\"\nversion = \"0.1.0\"\n"}, + {"src/main.cpp", "int main() { return 0; }\n"}, + {"tests/t_aliased.cpp", "int main() { return 0; }\n"}}; + for (std::vector args : {std::vector{"build"}, {"test"}, {"pack", "--mode", "system"}}) { + const auto r = p.mcpp(args, o); + expect(fatal(e2e::succeeded(r))) << args.front() << ": " << s::text(r); + } + const auto text = graphs_of(p); + expect(e2e::contains(text, via.generic_string() + "/")) << "the graph does not name the home as it was given"; + expect(s::lacks(text, s::physical(home) + "/")) << "the graph names the home by its physical spelling"; + }; + + "a path dependency named by two spellings is one package"_test[s::symlink] = [] { + const auto work = s::case_dir(); + s::project lib(work / "lib", { + {"mcpp.toml", "[package]\nname = \"twolib\"\nversion = \"0.1.0\"\n\n[targets.twolib]\nkind = \"lib\"\n"}, + {"src/twolib.cppm", "export module twolib;\nexport int two() { return 2; }\n"}}); + const auto via = s::alias_of(work / "lib"); + s::project mid(work / "mid", { + {"mcpp.toml", std::format("[package]\nname = \"mid\"\nversion = \"0.1.0\"\n\n[targets.mid]\nkind = \"lib\"\n\n" + "[dependencies]\ntwolib = {{ path = \"{}\" }}\n", (work / "lib").generic_string())}, + {"src/mid.cppm", "export module mid;\nimport twolib;\nexport int mid() { return two() + 1; }\n"}}); + s::project app(work / "app", { + {"mcpp.toml", std::format("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\n" + "mid = {{ path = \"{}\" }}\ntwolib = {{ path = \"{}\" }}\n", + (work / "mid").generic_string(), via.generic_string())}, + {"src/main.cpp", "import mid;\nimport twolib;\nint main() { return mid() + two() == 5 ? 0 : 1; }\n"}}); + const auto r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + const auto bins = s::glob(app.at("target"), "*/*/bin/app"); + expect(fatal(!bins.empty())) << "no app"; + expect(eq(s::run(bins.front()).status, 0)) << "the program did not run"; + }; +}}; + +} // namespace diff --git a/tests/e2e/pack/verbosity.cpp b/tests/e2e/pack/verbosity.cpp index 690651a13..47c1c31c3 100644 --- a/tests/e2e/pack/verbosity.cpp +++ b/tests/e2e/pack/verbosity.cpp @@ -11,16 +11,6 @@ namespace s = mcpp::test::support; namespace { -bool shows_compile(std::string_view text, std::string_view source) { - std::istringstream lines{std::string(text)}; - for (std::string line; std::getline(lines, line);) { - if (line.find(source) != std::string::npos - && (line.find(" -c ") != std::string::npos || line.find(" /c ") != std::string::npos)) - return true; - } - return false; -} - void cold_pack(bool library, bool verbose) { s::own_home(); const std::string source = library ? "pack_verbose_interface.cppm" : "pack_verbose_translation.cpp"; @@ -36,7 +26,7 @@ void cold_pack(bool library, bool verbose) { const auto r = p.mcpp(std::move(args)); expect(fatal(e2e::succeeded(r))) << s::text(r); expect(fatal(e2e::contains(s::text(r), "Packed"))) << s::text(r); - expect(eq(shows_compile(s::text(r), source), verbose)) << s::text(r); + expect(eq(s::shows_compile(s::text(r), source), verbose)) << s::text(r); } E2E verbosity{"verbosity", s::home_fixture, [] { diff --git a/tests/e2e/test/verbosity.cpp b/tests/e2e/test/verbosity.cpp new file mode 100644 index 000000000..8276d099b --- /dev/null +++ b/tests/e2e/test/verbosity.cpp @@ -0,0 +1,33 @@ +// `mcpp test --verbose` prints the commands of the builds it runs, as `mcpp build --verbose` and +// `mcpp pack --verbose` do (design 2026-12-07 §4.6): every build a command runs follows the +// command's verbosity. The run is cold, in a home of the case's own, so the test program's compile +// is one the run performs rather than one a cache answers. +import std; +import mcpplibs.mtest; +import mcpp.test.support; + +using namespace mcpplibs::mtest; +namespace s = mcpp::test::support; + +namespace { + +void cold_test(bool verbose) { + s::own_home(); + const std::string source = "test_verbose_translation.cpp"; + s::project p{s::files{ + {"mcpp.toml", "[package]\nname = \"testverbosity\"\nversion = \"0.1.0\"\n"}, + {"src/main.cpp", "int main() { return 0; }\n"}, + {"tests/" + source, "int main() { return 0; }\n"}}}; + std::vector args{"test"}; + if (verbose) args.emplace_back("--verbose"); + const auto r = p.mcpp(std::move(args)); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(eq(s::shows_compile(s::text(r), source), verbose)) << s::text(r); +} + +E2E verbosity{"verbosity", s::home_fixture, [] { + "a test run under --verbose prints its compile commands"_test = [] { cold_test(true); }; + "a test run prints no compile command by default"_test = [] { cold_test(false); }; +}}; + +} // namespace diff --git a/tests/support/src/support.cpp b/tests/support/src/support.cpp index aa559073f..c8306425a 100644 --- a/tests/support/src/support.cpp +++ b/tests/support/src/support.cpp @@ -594,6 +594,26 @@ std::optional own_home_of_case() { return std::nullopt; } +fs::path alias_of(const fs::path& dir) { + const auto at = case_dir() / std::format("alias-{:08x}", std::random_device{}()); + fs::create_directory_symlink(dir, at); + return at; +} + +std::string physical(const fs::path& dir) { return fs::canonical(dir).generic_string(); } + +aliased_home_t aliased_home(home kind) { + fs::path h; + { + auto& all = registry_of_cases(); + std::scoped_lock lock(all.m); + h = all.make("mcpp-e2e-home"); + } + const auto a = alias_of(h); + populate_home(a, kind); + return {a, h}; +} + fs::path another_home(home kind) { auto& all = registry_of_cases(); std::scoped_lock lock(all.m); @@ -856,6 +876,11 @@ mcpplibs::mtest::comparison contains_nocase(std::string_view text, std::string_v return {lower(text).contains(lower(needle)), "contains_nocase", std::format("text containing \"{}\" (any case)", needle), tail_of(text)}; } +bool shows_compile(std::string_view text, std::string_view source) { + for (auto l : split_lines(text)) + if (l.contains(source) && (l.contains(" -c ") || l.contains(" /c "))) return true; + return false; +} mcpplibs::mtest::comparison has_line_nocase(std::string_view text, std::string_view pattern) { const std::regex re{std::string(pattern), std::regex::ECMAScript | std::regex::icase}; bool held = false; diff --git a/tests/support/src/support.cppm b/tests/support/src/support.cppm index 29edf3813..ffcbb6f65 100644 --- a/tests/support/src/support.cppm +++ b/tests/support/src/support.cppm @@ -175,6 +175,21 @@ fs::path another_home(home kind = home::fresh); void own_home(home kind = home::inherited); // The shared home: `MCPP_HOME`, else `~/.mcpp`. fs::path shared_home(); +// A SECOND SPELLING OF A DIRECTORY (design 2026-12-07 §7): a link to `dir` in the case's directory, +// on a host that makes directory links (`s::symlink`). A path given through it is an address mcpp +// keeps (SPEC-020 §2); `physical(dir)` is the spelling an artefact must not hold in its place. +fs::path alias_of(const fs::path& dir); +// The physical spelling of `dir`, every link along it followed, as text. +std::string physical(const fs::path& dir); +// A further home of the case named through an alias from its start: made, then initialized and used +// through a link to it, so each record it holds is written with the alias, as a home a sandbox +// grants by one spelling is (a record keeps the address it was written with, SPEC-020 §2). mcpp runs +// in it with `options::env` setting MCPP_HOME to `alias`. +struct aliased_home_t { + fs::path alias; + fs::path dir; +}; +aliased_home_t aliased_home(home kind = home::inherited); // The command that runs `program` with `args` through `wine` and returns when every process wine // started has ended (`wineserver -w`), with the program's status. Wine starts its services with @@ -418,6 +433,10 @@ mcpplibs::mtest::comparison lacks(std::string_view text, std::string_view needle mcpplibs::mtest::comparison contains_nocase(std::string_view text, std::string_view needle); // some line of `text` matches `pattern`, ignoring ASCII case (`grep -iE`). mcpplibs::mtest::comparison has_line_nocase(std::string_view text, std::string_view pattern); +// some line of `text` is the compile command of `source`: it names the file and a compile switch +// (` -c ` or ` /c `), which tells a command from a path a planning message mentions. A cold build +// under `--verbose` prints one (design 2026-12-07 §4.6). +bool shows_compile(std::string_view text, std::string_view source); // The last line of `text` that is not empty (`| tail -1` of a program's output). std::string last_line(std::string_view text); // The last line of `text` that starts with `prefix` (`grep '^' | tail -1`), or "". From 4725ed2a52bc02260cb59ec569ca54d8720773d6 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:22:09 +0900 Subject: [PATCH 13/18] =?UTF-8?q?SPEC-006=20=C2=A73.12=20states=20the=20li?= =?UTF-8?q?nker=20named=20by=20its=20address;=20SPEC-020=20=C2=A79,=20docs?= =?UTF-8?q?/09=20and=20docs/20=20state=20the=20driver's=20view=20of=20itse?= =?UTF-8?q?lf,=20the=20scope=20of=20--verbose=20and=20-nostdlib=20on=20the?= =?UTF-8?q?=20MSVC=20ABI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...th-uses-roots-and-tool-addresses-design.md | 143 ++++++++++-------- .agents/skills/mcpp-contributing/SKILL.md | 17 +++ docs/09-commands-by-scenario.md | 6 +- docs/20-toolchains.md | 29 +++- docs/specs/paths.md | 10 +- docs/specs/toolchain-management.md | 26 +++- docs/zh/09-commands-by-scenario.md | 2 +- docs/zh/20-toolchains.md | 19 ++- 8 files changed, 163 insertions(+), 89 deletions(-) diff --git a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md index 05791effc..933fa4ab5 100644 --- a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md +++ b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md @@ -174,9 +174,6 @@ void on_undecided(void (*report)(std::string_view question)); `std::filesystem::canonical`、`weakly_canonical` 与 `os::fs::canonical` 只出现在本模块的 `describe`; `check_path_identity.sh` 由“只降不升”改为“为零”,基线文件删去。 -`std::filesystem::canonical`、`weakly_canonical` 与 `os::fs::canonical` 只允许出现在诊断文本的生成处,经本模块的 -一个 `describe()` 取得;`check_path_identity.sh` 由“只降不升”改为“为零”,基线文件删去。 - ### 4.2 迁移 65 处按 P1 归类迁移(附录 A 为最终归类),另有三处经原 `identity()` 的调用者(cps 的使用说明、配置的借用判断、包 @@ -194,67 +191,72 @@ void on_undecided(void (*report)(std::string_view question)); ### 4.4 链接器与驱动 -**一项工具链事实。** `Toolchain::linker { path, flavour, source }`,在解析工具链时确定一次: +**一项工具链事实。** `Toolchain::linker` 是一个路径,在解析 clang 树时确定一次: 1. 声明的 `tools.ld`; -2. 树或载荷中与目标格式对应的 lld(ELF `ld.lld`,PE `lld-link`,Mach-O `ld64.lld`,wasm `wasm-ld`;格式取自目标行, - 与 `LinkShape` 同源); -3. 否则为空,由驱动的缺省决定,不加任何链接器词。 +2. 树中与链接格式对应的 lld(MSVC ABI `lld-link`,Mach-O `ld64.lld`,wasm `wasm-ld`,其余含 MinGW `ld.lld`;在 + `/bin` 与驱动所在目录中查找); +3. 否则为空,由驱动决定。托管载荷的 lld 位于其驱动旁,驱动以给定的拼写看待自身之后(下文)在该处找到它,不另行 + 指名。 -`path` 是给定的拼写(P4)。在规划时检查其存在;缺失沿用现有对 `tools` 程序缺失的拒绝。`mcpp why toolchain` 列出 -它与来源。 +`path` 是给定的拼写(P4)。`mcpp why toolchain` 列出它与来源。 -**一个生成函数。** 按路线给出词,项目的 C 与 C++ 链接、构建程序的链接、freestanding 链接三处共用, -`resolve_lld` 并入: +**一个生成函数。** `linker_words` 按路线给出词。实测(LLVM 23.1.3,`-###`): -| 路线 | 词 | 依据 | +| 路线 | 读取 | 词 | |---|---|---| -| 通用(ELF、Mach-O、wasm) | `-fuse-ld=lld --ld-path=`(lld 形态);其他链接器 `--ld-path=` | `GetLinkerPath` 读取 `--ld-path` | -| MSVC ABI | `-B -fuse-ld=` | `GetProgramPath` 先查 `-B`,以不含目录的名字查找,避开三元组前缀 | +| ELF、Mach-O、MinGW | `--ld-path` | `--ld-path=`;文件名是 lld 的名字时前加 `-fuse-ld=lld` | +| wasm | 绝对路径的 `-fuse-ld`;`--ld-path` 报告为未使用 | `-fuse-ld=` | +| MSVC ABI | `-fuse-ld`,以 `GetProgramPath` 查找;`--ld-path` 报告为未使用 | `-B -fuse-ld=<文件名去掉末尾的 .exe>` | -MSVC 路线上 `-B` 目录中的查找经 LLVM 的 `can_execute`,它在 Windows 上依次试 `<名字>` 与 `<名字>.exe` -(`llvm/lib/Support/Windows/Path.inc:746-749`)。因此该路线上的链接器须为可执行文件(`.exe`),主名即去掉 `.exe` 的 -文件名;`tools.ld` 指向其他形式的文件(如 `.cmd`)时在规划时拒绝,与 gcc 树声明 `ld` 时的拒绝同理:驱动按名字在目录中 -选择程序,以别的形式无法选中。 +此前的 `--ld-path` 在 wasm 与 MSVC 路线上不起作用:声明的链接器进入指纹而不参与链接。MSVC 路线上 `-B` 目录中的 +查找先试 `<名字>` 再试 `<名字>.exe`(`can_execute`),因此任何文件名都可选中,无须限定 `.exe`;只有 `link` 与 `lld` +两个名字由驱动按自己的规则另找程序(`link` 取 Visual Studio 的 `link.exe`,`lld` 映射为 `lld-link`),声明为这两个 +名字的链接器在规划时拒绝,并提示改名。 -MSVC 路线的另两种写法不采用:单独的 `-fuse-ld=<绝对路径>` 得到 `<三元组>-<绝对路径>`(§2.4);`-B "" -fuse-ld=<绝对路径>` -在 22.1.8 上成立,但空前缀同时进入驱动的文件查找(相对当前目录),且依赖一个内部细节(决定 D1)。 +词在项目链接行的最终处加入,每种形态一次;构建程序由同一 `compute_flags` 生成链接行,`host_link_tokens` 给出同样 +的词。平台直接运行链接器的链接(`link.driver = "lld"`)由该事实运行。freestanding 链接以 `resolve_lld` 按地址指名 +载荷的 lld,事实的词在其后且指向同一树。 -**驱动看待自身的位置。** mcpp 启动的每个 clang 驱动(编译、链接、探测与查询,如 `-print-resource-dir`)都传 -`-no-canonical-prefixes`,驱动的安装目录、资源目录与程序目录都以给定的拼写派生;`hermetic.cppm:165` 为“驱动经物理 -路径报告资源目录”所加的上游 store 例外随之删去(决定 D2)。探测结果因此可能改变,按工具链身份记录的探测在升级后 -重做一次。 +**驱动看待自身的位置。** `driver_self_words` 对 clang 给出 `-no-canonical-prefixes`,自带 sysroot 的工具链(其驱动 +是包装程序)除外。实测:由符号链接组成的树,`-print-resource-dir` 与 `-print-prog-name=ld.lld` 不带该词时回答链接 +所指向的载荷目录,带该词时回答树中的目录。它进入 `host_compile_tokens`(项目、标准库模块、扫描与构建程序的编译词)、 +`host_link_tokens`、项目每条编译与链接行的最终处,以及每个探测:树的能力、标准库模块源、运行时归档、基座测量、 +打包的库目录、压缩调试段、MSVC 协程探测、平台汇编规则(决定 D2)。 -### 4.5 根目录表 +`hermetic.cppm` 为上游 store 所加的允许保留:gcc 不带该词,按解析后的路径报告其运行时(`crtbegin.o`),借用上游 +gcc 的 home 中该路径位于上游 store(实测:e2e `layers/201`)。允许集合的比较改为按路径组成部分(`os::fs::within`), +不再按字符串前缀。 -一个模块 `mcpp.build.roots`:一张在规划时建立的表,每项为 `{ kind, name, path }`,`path` 为给定的拼写。 +以包装程序作为 `tools.cxx` 时,被包装的驱动以包装程序给出的路径看待自身:读取该路径旁的配置文件,而不是链接所 +指向的目录中的配置文件。 -| kind | 来源 | -|---|---| -| `project`、`workspace` | 工程与工作区的根 | -| `package` | 图中每个包的根 | -| `home`、`user` | `MCPP_HOME`、用户目录 | -| `store` | 每个 xpkgs store(含上游) | -| `toolchain`、`base` | 工具链的根、基座或 sysroot | -| `output`、`runtime` | 输出目录、运行时目录 | +### 4.5 根目录表 + +一个模块 `mcpp.build.roots`:一张在规划时建立的表,每项为 `{ kind, path, name }`,`path` 为给定的拼写。 -表只回答两个问题:一个路径落在哪个根下(最具体者优先,经 `within`),一个根的给定拼写是什么。§2.6 的四处改为读表: +| kind | 来源 | 名字 | +|---|---|---| +| `home` | `MCPP_HOME` | `/mcpp/home` | +| `store` | 每个 xpkgs store | `/mcpp/store` | +| `toolchain` | 树的根或驱动的上两级 | `/mcpp/toolchain` | +| `base` | 陈述的基座 | `/mcpp/sysroot` | +| `output` | 构建目录 | `/mcpp/build` | +| `package` | 图中每个包的根 | `<包名>@<版本>` | -- 输出中的路径缩短:规则不变(项目内相对、`@mcpp/…`、`~/…`),根取自表;无规划的命令(如 `self env`)建立只含 - `home`、`user` 的表。 -- `trim_map`:以表中属于该包闭包的根生成 `-ffile-prefix-map`。 -- 构建程序占位符:名字与取值取自表,SPEC-007 的定义不变。 -- 自足性检查的允许集合:表中 `store`、`toolchain`、`base` 与图的根;上游 store 由编译器路径的 `resolved` 得到(D2 之后删去)。 +`trim_map`(`-ffile-prefix-map`)与链接自足性检查的允许集合读这张表,此前二者各有一份枚举且不一致:检查只知道 +编译器所在的 store,映射知道 home 的每个 store。输出中的路径缩短(项目、home、用户目录)与构建程序占位符 +(SPEC-007,输出目录下的名字)不是这一组根的枚举,各自保留。 记录的格式与缓存键不变:键用拼写(docs/25),本设计不引入可迁移的键。 ### 4.6 构建的详细输出 -`BuildOptions::verbose` 改为 `std::optional`;未设置时由 ninja 后端取命令的详细程度(`mcpp::log::is_verbose()`)。 -`build`、`configure`、`pack`、`test` 与其余驱动构建的调用点不写它,`pack` 的 5 处现有的设置删去;只有构建程序的内层 -构建显式设置(`MCPP_TOOL_BUILD_VERBOSE`),在这两处写明理由。`tests/e2e/pack/verbosity.cpp` 的判据移入测试工具集 -(“输出中有一行同时含该源文件名与编译开关”),供 `pack` 与 `test` 的用例共用。一条文档:`--verbose` 作用于命令运行的 -每一次构建。 +`BuildOptions::verbose` 的缺省成员初始化为 `mcpp::log::is_verbose()`:每次驱动构建在构造选项时取命令的详细程度。 +`build`、`configure`、`pack`、`test` 与其余驱动构建的调用点不写它,`pack` 的 5 处现有设置删去;只有构建程序的 +内层构建显式设置(`MCPP_TOOL_BUILD_VERBOSE`),在这两处写明理由。最初的形式 `std::optional` 使 GCC 16 读 +`mcpp.build.backend` 的 BMI 时报告 `Bad file data`,缺省成员初始化表达同一语义且不改变成员类型。一条文档: +`--verbose` 作用于命令运行的每一次构建。 ### 4.7 不在本设计内:MSVC ABI 上不带 CRT 的程序 @@ -276,8 +278,8 @@ AppContainer 中长授权路径下 IPC 端点建立失败(`invalid argument` ```text 路径模块(§4.1)── 65 处迁移(§4.2,附录 A)── CI 规则为零 └── 编译器运行状态与注册(§4.3) - └── 根目录表(§4.5)── 路径缩短 / trim_map / 占位符 / 自足性检查 -Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no-canonical-prefixes + └── 根目录表(§4.5)── trim_map / 自足性检查 +Toolchain::linker + 生成函数(§4.4)── 项目与构建程序的链接 ── -no-canonical-prefixes 详细输出(§4.6) 规范与文档(§8)、CHANGELOG ``` @@ -286,8 +288,10 @@ Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no- - 无别名的路径上,地址与键与此前相同;有别名时,编译器运行目录换键一次(§4.3),`path` 依赖与成员的比较结果不变, 取不到标识时按拼写并报告降级。 -- 链接器词改变,链接命令改变:每个使用 clang 的工程重新链接一次。 -- `-no-canonical-prefixes` 改变编译命令:使用 clang 的工程重新编译一次(决定 D2 的代价)。 +- 链接器词只在按路径命名的 clang 树上改变,这样的工程重新链接一次;托管载荷的链接器词不变。 +- `-no-canonical-prefixes` 改变 clang 的编译与链接命令:使用 clang 的工程重新编译一次,标准库模块重建一次(决定 D2 + 的代价)。 +- 由符号链接组成的树,其驱动在树中读取配置文件与资源目录,而不再在链接所指向的目录中读取。 - 记录格式、缓存键、构建程序占位符的名字与值、输出中的路径缩短形式不变。 - `--verbose` 下 `pack`、`test` 多出 ninja 命令行;缺省输出不变。 @@ -295,13 +299,16 @@ Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no- - 单元(`modules/libs/tests/`):`given`、`key`、`resolved`、`same`、`beneath`/`within`、`describe` 在符号链接、相对 链接、链接环、不存在的尾部、目录内指向外部的链接下的回答;`tests/unit/` 中注册经链接给出的运行时目录、输出经链接的同一。 -- 测试工具集新增两项,供各用例复用:以别名运行(Linux 上工程、home、工具链与临时目录经符号链接给出;Windows 上用 - CI 已有的 `subst` 盘),与一个断言“mcpp 写出的产物中不出现物理前缀”(build.ninja、编译数据库、链接命令、运行目录、 - 传输记录、各记录)。 -- e2e:别名下的 `build`、`test`、`pack`;编译器运行目录与传输记录的拼写;`path` 依赖与成员在两种拼写下的同一。 -- 链接器:Linux 上由符号链接组成、物理目录中有另一 lld 的树,断言用的是树中的;`tools.ld` 为追踪程序(非 lld 的名字) - 时在 Windows clang 任务的 MSVC 行与 Linux 行都被调用;缺失时被拒绝。 +- 测试工具集新增:`alias_of`(目录的第二种拼写,一个符号链接)、`physical`(物理拼写)与 `shows_compile`(输出中 + 某行是某源文件的编译命令)。POSIX 的 `getcwd` 回答物理路径,工程目录因此由系统报告;别名经 `MCPP_HOME` 与 + 清单中的 `path` 给出。 +- e2e:经别名给出的 home 下 `build`、`test`、`pack` 的图与编译数据库以别名指名 home,不含其物理拼写;以两种拼写 + 指名的 `path` 依赖为同一个包。 +- 链接器:Linux 上由符号链接组成的树,其 `ld.lld` 为记录调用的程序,断言它被调用且以地址指名;`tools.ld` 为追踪 + 程序时在 Linux 被调用;Windows 的 MSVC 行上,`tools.ld` 为 `lld-link` 的另一名字,驱动的 `-v` 输出显示它被启动, + 名为 `link.exe` 时被拒绝;单元覆盖四条路线。 - 详细输出:冷构建的 `pack --verbose` 与 `test --verbose` 显示编译命令;缺省不显示。 +- MSVC 行 `-nostdlib` 的提示由 Windows 的一个 C++ 用例触发(面的账本)。 - CI:`check_path_identity.sh` 为零。 ## 8. 规范与文档的收敛 @@ -312,8 +319,9 @@ Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no- |---|---|---| | 路径的四种用途、根目录表、降级 | 新 SPEC-020《路径》(规范性条款,RFC 2119) | docs/25 的“home 保留拼写”一段改为用户视角的一段并引用;docs/05 中 `path` 依赖“按规范化后的绝对目录比较”改为“按跟随链接后的绝对目录”并引用;AGENTS.md 的规范编号范围更正为 SPEC-001 至 SPEC-020 | | 代码中的判断 | AGENTS.md §4 一行并链接 SPEC-020 | mcpp-contributing skill 写判断步骤与 CI 规则,不重述规则 | -| 链接器如何到达驱动 | SPEC-006 一条(各路线的词) | docs/20 的表与 `tools.ld` 一段改为用户视角并引用;删去“经 `--ld-path`”这一在 MSVC 路线上不成立的陈述 | -| 构建程序占位符 | SPEC-007(不变) | 一句:取值来自根目录表 | +| 链接器如何到达驱动 | SPEC-006 §3.12(各路线的词) | docs/20 的表与 `tools.ld` 一段改为用户视角并引用;删去“经 `--ld-path`”这一在 MSVC 与 wasm 路线上不成立的陈述 | +| 驱动以给定的拼写看待自身 | SPEC-020 §9 | docs/20 一句 | +| MSVC ABI 上的 `-nostdlib` | docs/20“On the MSVC runtime”一段 | — | | `--verbose` 的范围 | docs/09 一句 | — | 各条在 docs/ 中英文同步,CHANGELOG 每项行为一条。 @@ -322,8 +330,8 @@ Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no- | 编号 | 问题 | 决定 | 未采用 | |---|---|---|---| -| D1 | MSVC 路线的链接器词 | `-B<目录> -fuse-ld=<主名>`,链接器须为 `.exe`(§4.4) | `-B "" -fuse-ld=<绝对路径>` | -| D2 | `-no-canonical-prefixes` 的范围 | mcpp 启动的全部 clang 驱动;使用 clang 的工程升级后重编译一次 | 只用于按路径指定的树(`hermetic.cppm:165` 的例外保留) | +| D1 | MSVC 路线的链接器词 | `-B<目录> -fuse-ld=<文件名去掉 .exe>`;名为 `link` 或 `lld` 时拒绝(§4.4) | `-B "" -fuse-ld=<绝对路径>`;限定 `.exe` | +| D2 | `-no-canonical-prefixes` 的范围 | mcpp 启动的全部 clang 驱动,自带 sysroot 的包装驱动除外;使用 clang 的工程升级后重编译一次;`hermetic.cppm` 的上游 store 允许为 gcc 保留 | 只用于按路径指定的树 | | D3 | 路径规则的所在 | 新 SPEC-020《路径》 | 并入 SPEC-010 | | D4 | §4.7 | MSVC ABI 行的 `ldflags` 含 `-nostdlib` 时给出一条提示:CRT 模型的默认库指令仍写入目标文件;不改变行为 | 不提示 | | D5 | 路径模块的位置 | 保留 `modules/libs/src/path_identity.cppm` 的薄层 | 调用点直接用 mcpplibs.os | @@ -335,8 +343,9 @@ Toolchain::linker + 生成函数(§4.4)── 三处链接共用 ── -no- - 代价:`same` 至多两次 stat;`within` 每级祖先一次,深度有界;遍历去环由路径集合改为标识集合,次数不变。 - Windows 的大小写与 8.3 短名:拼写比较由 `os::fs::same` 折叠大小写,短名由对象标识识别。 - 43 处同一与包含的迁移改变的是判断方式,不改变回答:两种拼写原先经物理路径相等的,现经标识相等。 -- MSVC 路线的链接器词依赖 `GetProgramPath` 先查 `-B` 的行为,该行为在 LLVM 中长期稳定,以 Windows CI 的追踪程序断言 - 守住。 +- MSVC 路线的链接器词依赖 `GetProgramPath` 先查 `-B` 的行为,该行为在 LLVM 中长期稳定,以 Windows CI 的用例(驱动 + `-v` 输出中的被启动程序)守住。 +- 实测否定了原设想的两处:wasm 路线同样不读 `--ld-path`;gcc 解析自身路径,上游 store 的允许不能删去。 - 本设计不新造机制:对象标识、词法比较来自 mcpplibs.os;降级报告、CI 守卫、工具链事实、占位符均为现有机制的收敛。 ## 11. 实施任务 @@ -359,13 +368,13 @@ T8 MSVC 行 -nostdlib 的提示 ─────────────── | T1 | §4.1:路径模块的 `given`、`key`、`resolved`、`same`、`beneath`、`within`、`object`、`describe`、`on_undecided`,基于 mcpplibs.os 的 `same`、`within`、`read_link`、`identity_of`、`canonical`;删去 `identity()`;入口安装 `on_undecided` | — | 单元:符号链接、相对链接、链接环、不存在的尾部、指向外部的链接;Linux、macOS、Windows 通过 | | T2 | §4.2:附录 A 中除 T3 所属 4 处外的 61 处,与原 `identity()` 的 4 个调用者;`check_path_identity.sh` 改为零,删去基线文件;`project.cppm:433` 去掉 `.string()` | T1 | 脚本为零;现有单元与 e2e 通过 | | T3 | §4.3:工作目录与注册目录为 `given`,运行目录的键与输出标识为 `resolved`;`Witnesses::start` 由调用者传入运行时目录 | T1 | 单元:注册经链接给出的运行时目录时传输记录为给定拼写,往返、拒绝与停止不变;经链接的输出与经实路径的输出同一 | -| T4 | §4.5:`mcpp.build.roots`;路径缩短、`trim_map`、构建程序占位符、自足性检查的允许集合改为读表 | T1 | 路径缩短、`-ffile-prefix-map`、占位符的输出与改前逐字节相同;自足性检查结果不变 | -| T5 | §4.4:`Toolchain::linker` 与生成函数,项目、构建程序、freestanding 三处共用,`resolve_lld` 并入;`mcpp why toolchain` 列出;缺失与 MSVC 路线上的非 `.exe` 在规划时拒绝 | T1 | 单元(toolchain-model):四条路线 × 声明、树、载荷、无;e2e:Linux 上物理目录另有 lld 的符号链接树用树中的;`tools.ld` 的追踪程序在 Linux 行与 Windows MSVC 行被调用;缺失被拒绝 | -| T6 | §4.4:mcpp 启动的全部 clang 驱动加 `-no-canonical-prefixes`;删去 `hermetic.cppm:165` 的例外 | T4、T5 | 载荷工具链(含借用上游的链接项)编译、链接与自足性检查通过;e2e 875(符号链接树)与 Windows `subst` 任务通过;资源目录以给定拼写报告 | -| T7 | §4.6:`verbose` 为 `std::optional`;删去 `pack` 5 处的设置;判据移入测试工具集;`test --verbose` 的用例 | — | e2e:`pack` 与 `test` 的冷构建在 `--verbose` 下显示编译命令,缺省不显示 | +| T4 | §4.5:`mcpp.build.roots`;`trim_map` 与自足性检查的允许集合读表 | T1 | `-ffile-prefix-map` 的输出与改前相同;自足性检查结果不变 | +| T5 | §4.4:`Toolchain::linker` 与 `linker_words`,项目与构建程序的链接共用;`mcpp why toolchain` 列出;MSVC 路线上名为 `link`、`lld` 的链接器在规划时拒绝 | T1 | 单元(toolchain-model):四条路线 × 声明、树、无;e2e:符号链接树的 `ld.lld` 被调用;`tools.ld` 的追踪程序在 Linux 与 Windows MSVC 行被调用;`link.exe` 被拒绝 | +| T6 | §4.4:mcpp 启动的全部 clang 驱动加 `-no-canonical-prefixes` | T4、T5 | 载荷工具链(含借用上游的链接项)编译、链接与自足性检查通过;e2e 875(符号链接树)通过 | +| T7 | §4.6:`verbose` 的缺省成员初始化取命令的详细程度;删去 `pack` 5 处的设置;判据移入测试工具集;`test --verbose` 的用例 | — | e2e:`pack` 与 `test` 的冷构建在 `--verbose` 下显示编译命令,缺省不显示 | | T8 | D4:MSVC ABI 行 `ldflags` 含 `-nostdlib` 时的提示,登记为一个 notice | — | 一个 C++ e2e 用例使该 notice 出现(面的账本);其他行不出现 | -| T9 | §7:测试工具集的“以别名运行”与“产物中无物理前缀”;别名下的 `build`、`test`、`pack`,运行目录与传输记录,`path` 依赖与成员的同一 | T2、T3、T4 | Linux 符号链接与 Windows `subst` 两种别名下通过 | -| T10 | §8:SPEC-020;SPEC-006、SPEC-007;docs/05、09、20、25(中英文);AGENTS.md §4;mcpp-contributing;规范索引 | T1–T8 | 每条规则只在 §8 所列一处陈述;索引生成与文档检查通过 | +| T9 | §7:测试工具集的 `alias_of`、`physical`;别名下的 `build`、`test`、`pack` 的图与编译数据库,`path` 依赖在两种拼写下的同一 | T2、T3、T4 | Linux 与 macOS 上通过 | +| T10 | §8:SPEC-020;SPEC-006 §3.12;docs/05、09、20、25(中英文);AGENTS.md §4;mcpp-contributing;规范索引 | T1–T8 | 每条规则只在 §8 所列一处陈述;索引生成与文档检查通过 | | T11 | `mcpp.toml` 与 `modules/versioning/src/version.cppm` 一个提交;CHANGELOG 2026.12.7.1 一节,并入 main 上已有的 `[Unreleased]` 条目;GCC 与 LLVM 23.1.3 本地构建;面的账本增量核对;PR 描述 | T0–T10 | 全部检查通过;生态级自我评审 | 检查点:T1、T2、T3 之后推送一次;T4 至 T8 之后一次;T9 至 T11 之后一次。 diff --git a/.agents/skills/mcpp-contributing/SKILL.md b/.agents/skills/mcpp-contributing/SKILL.md index 65e487184..eceb2a30f 100644 --- a/.agents/skills/mcpp-contributing/SKILL.md +++ b/.agents/skills/mcpp-contributing/SKILL.md @@ -366,6 +366,23 @@ Windows 上 `std::filesystem::path::string()` 会把 native(宽)名经**进 UTF-8 ACP(65001),这类用例会静默变成永远绿的装饰品。参见 `tests/unit/test_modgraph.cpp` 的 `Scanner.GlobWalkSurvivesNamesTheCodePageCannotSpell`。 +## 路径的用途(SPEC-020) + +写下一个路径的用法之前,先判定它属于哪一种用途,再用 `mcpp.libs.path_identity` 中对应的函数;规则本身见 +[SPEC-020](../../../docs/specs/paths.md),此处只列判断的步骤。 + +1. 打开它、交给程序、写进记录:地址,`given(p)`。 +2. 作为缓存条目或记录中的键:`key(p)`。 +3. 问两个路径是否同一对象、一个对象是否在某目录下:`same`、`within`、`beneath`;问一个**名字**是否在某目录下 + (不问对象):`mcpplibs::os::fs::within`。 +4. 遍历时去环、去重:`object(p)` 作集合的键;内存中以路径为键的映射:`resolved(p)`。 +5. 要的是链接指向的文件(soname 链、加载器):`resolved(p)`。 +6. 只为在诊断中给出物理路径:`describe(p)`。 + +`canonical` 与 `weakly_canonical`(`std::filesystem` 与 mcpplibs.os)只出现在路径模块中: +`.github/tools/check_path_identity.sh` 在其他位置为零,没有基线。clang 驱动的每条命令带上 +`driver_self_words(tc)`(`-no-canonical-prefixes`);新增一处探测时一并加上。 + ## 注意事项 - C++23 模块项目,修改模块时注意 import 依赖顺序 diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index 98ec43de8..612935727 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -504,8 +504,10 @@ proceeds. `--verbose` names every package: `Fresh` for those with nothing to do, and `Compiled` with the steps and span of each that did work. It also states each build program's compile and run times, and prints every step as ninja reports -it (`[f/t] ` and its output). `--quiet` prints none of this. Machine -output (`--message-format json`) is unchanged. +it (`[f/t] ` and its output). It applies to every build a command +runs: `build`, `run`, `test` and `pack` alike. A build program's own inner build +prints its steps only when `MCPP_TOOL_BUILD_VERBOSE` is set. `--quiet` prints +none of this. Machine output (`--message-format json`) is unchanged. ## Output streams diff --git a/docs/20-toolchains.md b/docs/20-toolchains.md index eec0d422b..73b24bd09 100644 --- a/docs/20-toolchains.md +++ b/docs/20-toolchains.md @@ -598,11 +598,14 @@ whether `import std` is available are read from the driver itself. The tools beside them are found as ``, then `llvm-`, then ``; `tools` names any the tree does not have. -`tools = { ld = … }` is read by a clang tree, where the linker reaches the link -as `--ld-path`. A gcc tree that states `ld` is refused: gcc chooses its linker by -the name `ld` inside a directory it is given with `-B`, so a program under any -other name could not be selected, and a stated tool that took no part in the -build is what this mechanism exists to prevent. +`tools = { ld = … }` is read by a clang tree, which hands the linker to the +driver by its address, in the form the target's link reads +([SPEC-006 §3.12](specs/toolchain-management.md)). On the MSVC ABI a linker whose +file name is `link` or `lld` is refused: the driver takes those two names for +programs it finds by its own rules. A gcc tree that states `ld` is refused: gcc +chooses its linker by the name `ld` inside a directory it is given with `-B`, so +a program under any other name could not be selected, and a stated tool that +took no part in the build is what this mechanism exists to prevent. **What the tree can do is stated or probed (2026.12.4.1+).** A managed payload's shape is the index's data; a tree's is read from the tree: @@ -611,12 +614,15 @@ shape is the index's data; a tree's is read from the tree: |---|---| | archiver | `tools.ar`; else the tree (`ar`, `llvm-ar`, `ar`); else the same names on `PATH`, reported as `build/archiver-from-host` (a degradation, refused under `--strict`); none anywhere is refused with `[toolchain-has-no-archiver]` | | response files | asked of the archiver once; one that reads `@file` as a member's name is given the expanded words, in batches when they exceed the host's command line | -| linker (clang) | `tools.ld` through `--ld-path`; else `-fuse-ld=lld` when the tree has lld; else the driver's default | +| linker (clang) | `tools.ld`; else the tree's lld of the link's flavour (`ld.lld`, `ld64.lld`, `wasm-ld`, `lld-link`), named by its address; else the driver's default | | compiler runtime, unwinder (clang) | `--rtlib=compiler-rt` and `--unwindlib=libunwind` only when the driver names the library | | C++ modules (clang) | a two-line module unit compiled once; a driver that refuses it builds the units that use no module, and a unit that declares or imports one is refused with `[compiler-without-modules]`, naming the file | -The project's links and the build programs' links take the same words. Each -answer is kept under the program's identity, and `mcpp why toolchain` lists each +The project's links and the build programs' links take the same words. Every +command mcpp starts gives a clang driver `-no-canonical-prefixes`, so the driver +of a tree of links finds its resource directory and programs in the tree it was +started from, not in the tree its links lead to +([SPEC-020 §9](specs/paths.md)). Each answer is kept under the program's identity, and `mcpp why toolchain` lists each fact with its source; the layer report writes `custom` for the layers the tree supplies. A tree that holds both `clang++` and `g++` with no `family` stated is noted once (`toolchain/tree-holds-two-families`), naming the one used. @@ -1937,6 +1943,13 @@ not warned, because `cxx_runtime` is the root's key. A debug word (`/MTd`, axis, and the standard library module and the link use the release CRT. The engine never lets the last word on the command line decide silently. +**`-nostdlib` does not remove the CRT on the MSVC ABI.** In `[build] ldflags` it +drops the `-defaultlib:` words the driver adds to the link, and each object +still names the default libraries of the CRT model, which the linker reads. A +note says so once (`build/msvc-nostdlib`); the build is otherwise unchanged. A +program built without the CRT also states `-fms-omit-default-lib` (clang) or +`/Zl` (cl) in its compile flags. + > **Upgrading to 2026.9.28.2?** A program whose runtime search directories > hold an older copy of the MSVC C++ runtime now receives the toolset's copy, > where it received the directory's; the difference is stated once as a note diff --git a/docs/specs/paths.md b/docs/specs/paths.md index 43ba5c9be..24a60744a 100644 --- a/docs/specs/paths.md +++ b/docs/specs/paths.md @@ -82,10 +82,12 @@ ## 9. 工具由地址指名 -1. 一次链接使用的链接器**必须**由工具链事实确定一次(声明的 `tools.ld`、树或载荷中与目标格式对应的 lld、驱动的 - 缺省),并以地址交给驱动;各路线所用的参数由 [SPEC-006](toolchain-management.md) 规定。 -2. mcpp 启动的 clang 驱动**必须**以给定的拼写看待自身的位置(`-no-canonical-prefixes`):安装目录、资源目录与程序 - 目录由启动它的路径派生。 +1. 一次链接使用的链接器**必须**由工具链事实确定一次(声明的 `tools.ld`;否则按路径命名的树中与链接格式对应的 + lld;否则驱动的缺省,托管载荷的 lld 位于其驱动旁),并以地址交给驱动;各路线所用的参数由 + [SPEC-006 §3.12](toolchain-management.md) 规定。 +2. mcpp 启动的 clang 驱动(编译、链接、探测与查询)**必须**以给定的拼写看待自身的位置(`-no-canonical-prefixes`): + 安装目录、资源目录与程序目录由启动它的路径派生。自带 sysroot 的工具链(其驱动是一个包装程序,配置由它自己 + 给出)除外。 ## 变更记录 diff --git a/docs/specs/toolchain-management.md b/docs/specs/toolchain-management.md index 9748e710d..5bb0e41d3 100644 --- a/docs/specs/toolchain-management.md +++ b/docs/specs/toolchain-management.md @@ -4,8 +4,8 @@ |---|---| | 规范编号 | SPEC-006 | | 标题 | 工具链管理:身份、来源、选择与载荷契约 | -| 状态 | 草案 v0.14 | -| 最后修改 | 2026-11-23 | +| 状态 | 草案 v0.15 | +| 最后修改 | 2026-12-07 | | 对应实现 | 逐条标注;标为「已实现」的条款对应 mcpp >= 2026.9.24.1。标为「未实现」的条款计划与下一批 LLVM 工具链一同落地,届时按实测修订本规范 | | 相关设计文档 | `.agents/docs/2026-10-23-target-base-and-execution-host-design.md`、`.agents/docs/2026-09-24-toolchain-selection-and-payload-trust-design.md`、`.agents/docs/2026-09-24-685-687-msvc-stl-and-toolchain-payloads.md`、`.agents/docs/2026-09-28-ecosystem-design-and-optimisation-plan.md`、`.agents/docs/2026-10-02-pr-ci-acceleration-and-the-toolchain-specification-design.md`、`.agents/docs/2026-11-21-offline-host-inputs-and-toolchain-defaults-design.md` | | 相关 issue | mcpp#685、mcpp#687、mcpp#718、mcpp#755、mcpp#832、mcpp#988 | @@ -333,6 +333,27 @@ loader,基座是下限。静态产物与裸机为 `none`。被陈述基座的内 Apple 的 `SDKROOT` 与 `xcrun`、微软的 vswhere 与 `/winsysroot` 布局)。第三方生态与工具的知识(例如 Swift SDK 包、`QEMU_LD_PREFIX`)**禁止**进入引擎,由包与插件经 §3.9 与 SPEC-002 §6 的通用接口接入。 +### 3.12 链接器由地址指名 已实现(2026.12.7.1 起) + +1. clang 工具链的链接器**必须**在解析工具链时确定一次:按路径命名的工具链所陈述的 `tools.ld`;否则该树 + 中与链接格式对应的 lld(MSVC ABI 为 `lld-link`,Mach-O 为 `ld64.lld`,wasm 为 `wasm-ld`,其余含 MinGW + 为 `ld.lld`;在 `/bin` 与驱动所在目录中查找);否则由驱动决定。托管载荷的 lld 位于其驱动旁, + 不另行指名。 +2. 链接器**必须**以地址交给驱动,参数取目标的链接路线所读的形式: + + | 路线 | 参数 | + |---|---| + | ELF、Mach-O、MinGW | `--ld-path=<地址>`;链接器的文件名为 lld 的名字时前加 `-fuse-ld=lld` | + | wasm | `-fuse-ld=<地址>` | + | MSVC ABI | `-B<目录> -fuse-ld=<文件名,去掉末尾的 .exe>` | + + 依据(LLVM 23.1.3,以 `-###` 实测):wasm 与 MSVC 路线不读 `--ld-path`,驱动报告该参数未使用;MSVC + 路线给含目录的名字加三元组前缀,并在 `-B` 目录中先于其他位置查找 `<名字>` 与 `<名字>.exe`。 +3. MSVC ABI 上,文件名(去掉 `.exe`)为 `link` 或 `lld` 的被陈述链接器**必须**在规划时被拒绝:驱动按 + 自己的规则为这两个名字另找程序。 +4. 平台直接运行链接器的链接(`link.driver = "lld"`)由该链接器运行。 +5. 链接器及其来源**必须**由 `mcpp why toolchain` 陈述。 + ## 4. 载荷契约 ### 4.1 可重定位 部分实现 @@ -464,6 +485,7 @@ doctor 如实报告这一点。它同时报告 mcpp 的包 home 中指向不存 | v0.11 | 2026-11-10 | 随 mcpp 2026.11.10.1:§3.9.2 引擎默认档为所选提供者的 `sysroot` 列,为包时按工程陈述的规则解析;附录 A 的 `*-windows-gnu` 接受基座包与 `{ path }`,新增 `*-freebsd` 行(基座包见 SPEC-002 §2.5)。 | | v0.13 | 2026-11-22 | 随 mcpp 2026.11.22.1:§2.9 配套载荷的声明依次取自载荷安装时的描述文件与索引的描述文件,取 store 持有的第一个。 | | v0.14 | 2026-11-23 | 随 mcpp 2026.11.23.1(设计 2026-11-22 内核接口与派生状态 §3.3、§3.11):§2.9 内核头文件是目标的 `kernel-abi` 层;基座不带时缺省取工具链载荷的声明,没有声明时拒绝;引擎不向共享视图写入内核头文件。新增 §2.10 存储的根。 | +| v0.15 | 2026-12-07 | 随 mcpp 2026.12.7.1(设计 2026-12-07 路径的用途 §4.4):新增 §3.12,clang 工具链的链接器是一项事实,以地址交给驱动,参数按链接路线;MSVC ABI 上名为 `link` 或 `lld` 的被陈述链接器被拒绝。 | | v0.9 | 2026-10-17 | 随 mcpp 2026.10.17.1:新增 §4.7,已安装的修订在构建中继续使用,`floor` 决定是否必须替换,`toolchain install` 取当前修订;§6.4 doctor 只读,报告构建实际使用的工具链与包 home 的一致性。 | --- diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index e15bbe04c..4edcde7c4 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -393,7 +393,7 @@ $ mcpp build --play-game=snake - **终端模式**:构建结束或被中断时,终端模式会恢复;被强制杀死的进程无法恢复,此时可执行 `stty sane`。 - **使用条件**:游戏要求标准输入和标准错误(点阵屏画在其上)都是终端,且 mcpp 位于该终端的前台(不是后台作业);否则写出一行说明原因,构建照常进行。 -`--verbose` 列出每个包:无事可做的包记为 `Fresh`,做了事的包记为 `Compiled`,并给出其步骤数和耗时跨度。它还给出每个构建程序的编译与运行时间,并按 ninja 的报告打印每个步骤(`[f/t] <命令>` 及其输出)。`--quiet` 不输出以上内容。机器输出(`--message-format json`)不变。 +`--verbose` 列出每个包:无事可做的包记为 `Fresh`,做了事的包记为 `Compiled`,并给出其步骤数和耗时跨度。它还给出每个构建程序的编译与运行时间,并按 ninja 的报告打印每个步骤(`[f/t] <命令>` 及其输出)。它作用于命令运行的每一次构建:`build`、`run`、`test` 与 `pack` 相同;构建程序内部的构建只在设置 `MCPP_TOOL_BUILD_VERBOSE` 时打印其步骤。`--quiet` 不输出以上内容。机器输出(`--message-format json`)不变。 ## 输出流 diff --git a/docs/zh/20-toolchains.md b/docs/zh/20-toolchains.md index 6324c993b..dcc6dc4e0 100644 --- a/docs/zh/20-toolchains.md +++ b/docs/zh/20-toolchains.md @@ -517,9 +517,11 @@ MCPP_TOOLCHAIN=path:/opt/llvm-trunk mcpp build 得到。旁边的工具按 ``、`llvm-`、`` 查找;`tools` 点名树里没有的 那些。 -`tools = { ld = … }` 只对 clang 的树成立——被陈述的链接器以 `--ld-path` 进入链接。gcc 的树 -陈述 `ld` 会被拒绝:gcc 按 `-B` 给出的目录里的名字 `ld` 选链接器,叫别的名字的程序无法那样 -被选中,而一个进了声明却不参与构建的工具,正是这套机制要防的事。 +`tools = { ld = … }` 只对 clang 的树成立:被陈述的链接器以地址交给驱动,写法取目标的链接所 +读的形式([SPEC-006 §3.12](../specs/toolchain-management.md))。MSVC ABI 上文件名为 `link` 或 +`lld` 的链接器会被拒绝:驱动按自己的规则为这两个名字另找程序。gcc 的树陈述 `ld` 会被拒绝: +gcc 按 `-B` 给出的目录里的名字 `ld` 选链接器,叫别的名字的程序无法那样被选中,而一个进了 +声明却不参与构建的工具,正是这套机制要防的事。 **树能做什么,取自陈述或探测(2026.12.4.1+)。** 托管载荷的形状是索引的数据;树的形状从树中读取: @@ -527,11 +529,13 @@ MCPP_TOOLCHAIN=path:/opt/llvm-trunk mcpp build |---|---| | 归档器 | `tools.ar`;否则树中的(`ar`、`llvm-ar`、`ar`);否则 `PATH` 上的同名程序,报告为 `build/archiver-from-host`(降级,`--strict` 下拒绝);处处都没有时以 `[toolchain-has-no-archiver]` 拒绝 | | 响应文件 | 向归档器询问一次;把 `@file` 当作成员名的归档器得到展开后的词,超出宿主命令行上限时分批 | -| 链接器(clang) | `tools.ld`,经 `--ld-path`;否则树中有 lld 时写 `-fuse-ld=lld`;否则用驱动的默认链接器 | +| 链接器(clang) | `tools.ld`;否则树中与链接格式对应的 lld(`ld.lld`、`ld64.lld`、`wasm-ld`、`lld-link`),以地址指名;否则用驱动的默认链接器 | | 编译器运行库、展开库(clang) | 只在驱动给出该库时写 `--rtlib=compiler-rt` 与 `--unwindlib=libunwind` | | C++ 模块(clang) | 编译一次两行的模块单元;拒绝它的驱动构建不用模块的单元,声明或导入模块的单元以 `[compiler-without-modules]` 拒绝,并指出文件 | -工程的链接与构建程序的链接用同样的词。每个答案按程序的身份保存,`mcpp why toolchain` 列出每一项及其来源; +工程的链接与构建程序的链接用同样的词。mcpp 启动的每条命令都给 clang 驱动 +`-no-canonical-prefixes`:由符号链接组成的树,其驱动在启动它的那棵树中找资源目录与程序, +而不在链接所指向的树中([SPEC-020 §9](../specs/paths.md))。每个答案按程序的身份保存,`mcpp why toolchain` 列出每一项及其来源; 层报告对树供给的层写 `custom`。一棵树同时有 `clang++` 与 `g++` 而未陈述 `family` 时,说明一次 (`toolchain/tree-holds-two-families`),写出用的是哪一个。 @@ -1707,6 +1711,11 @@ profile 表达的是调试信息,不是另一个 CRT。这根轴留待有消 `-fms-runtime-lib=*_dbg`)总被拒绝:模型没有调试这一轴,标准库模块与链接 使用的是发布版 CRT。引擎绝不让命令行上最后一个词静默胜出。 +**MSVC ABI 上 `-nostdlib` 不去掉 CRT。** `[build] ldflags` 中的 `-nostdlib` 去掉驱动加到链接上的 +`-defaultlib:`,而每个目标文件仍写着 CRT 模型的默认库,链接器照样读取。mcpp 对此说明一次 +(`build/msvc-nostdlib`),构建的其余部分不变。不带 CRT 的程序还需在编译参数中写 +`-fms-omit-default-lib`(clang)或 `/Zl`(cl)。 + > **升级到 2026.9.28.2?** 运行时搜索目录中带有较旧 MSVC C++ 运行时副本的 > 程序,现在得到工具集的副本,此前得到的是该目录的副本;这一差异以一条 > 说明陈述一次,不再在每次链接时警告。在 `host-coupled` 下声明运行时文件 From 32ce837476b5dd01d49c570c4c49f0160ffba601 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:22:19 +0900 Subject: [PATCH 14/18] 2026.12.7.1: the uses of a path, one table of roots, and tools named by their address --- CHANGELOG.md | 42 ++++++++++++++++++++++++++++- mcpp.toml | 2 +- modules/versioning/src/version.cppm | 2 +- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07368c7f6..137bb907b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,53 @@ > Each `## []` section is that release's notes. Entries are written in English > from 2026.9.28.3 on; earlier entries remain as written. -## [Unreleased] +## [2026.12.7.1] - 2026-12-07 + +### Changed + +- A path the user, the environment or the system gives is kept in the spelling it was given: an + address is made absolute and lexically normal, and no link or drive alias along it is resolved. + Whether two paths are one object is answered by their spellings, then by their spellings with + every link followed, then by the identity the system reads for the deepest part that exists + (mcpplibs.os); a question whose identity cannot be read is decided by the spellings and reported + once as a degradation (`path`). A path's physical spelling appears in diagnostics only, and a CI + check holds every other resolution of a path to its canonical form at zero (SPEC-020). +- The working directory of a compiler run and its lock are opened by the given spelling, and a + compiler registration publishes its endpoint and transport record under the runtime directory as + the system reports it; before, both were resolved to physical paths, which a process granted + only the given spelling cannot open (mcpp#1048, mcpp#1049). +- The linker of a clang toolchain named by path is one fact, decided once: `tools.ld`, else the + tree's lld of the link's flavour, named by its address. It reaches the driver in the form each + link route reads: `--ld-path` for ELF, Mach-O and MinGW, an absolute `-fuse-ld` for wasm, and + `-B -fuse-ld=` on the MSVC ABI, where `--ld-path` was reported unused and a + stated linker took no part in the link. On the MSVC ABI a stated linker named `link` or `lld` is + refused, since the driver finds those names by its own rules (SPEC-006 §3.12; mcpp#1050, + mcpp#1053). +- Every clang driver mcpp starts, for a compile, a link or a probe, is given + `-no-canonical-prefixes`: it derives its installation, resource and program directories from + the path it was started by. A tree of links finds its resource directory and programs in itself, + not in the tree its links lead to. A project built with clang compiles once more after the + upgrade, its std module included (SPEC-020 §9). +- The roots of a build are one table: the `trim_paths` prefix map and the link's hermetic check + read it, and the check allows every store of the home, as the map names them (SPEC-020 §8). +- `--verbose` applies to every build a command runs: `mcpp test --verbose` prints its compile + commands, as `mcpp build --verbose` and `mcpp pack --verbose` do. A build program's inner build + prints them only under `MCPP_TOOL_BUILD_VERBOSE` (docs/09). + +### Added + +- On the MSVC ABI, `-nostdlib` in `[build] ldflags` is noted once (`build/msvc-nostdlib`): it drops + the driver's `-defaultlib:` words, and each object still names the default libraries of the CRT + model. A program without the CRT also states `-fms-omit-default-lib` (clang) or `/Zl` (cl) in its + compile flags; the build is otherwise unchanged (mcpp#1051). ### Fixed - `mcpp pack --verbose` forwards verbosity to every pack-owned build, including library packages, additional legs and distribution-format builds (mcpp#1052). Builds without `--verbose` retain their normal output. +- The link's hermetic check compares its allowed directories by path components; before, a + directory whose name extended an allowed one (`store2` beside `store`) was taken as inside it. ## [2026.12.6.2] - 2026-12-06 diff --git a/mcpp.toml b/mcpp.toml index 30924393e..7fa1205e4 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,6 +1,6 @@ [package] name = "mcpp" -version = "2026.12.6.2" +version = "2026.12.7.1" description = "Modern C++ build & package management tool" license = "Apache-2.0" authors = ["mcpp-community"] diff --git a/modules/versioning/src/version.cppm b/modules/versioning/src/version.cppm index 8841d8ea8..14941dce6 100644 --- a/modules/versioning/src/version.cppm +++ b/modules/versioning/src/version.cppm @@ -31,6 +31,6 @@ import std; export namespace mcpp { -inline constexpr std::string_view MCPP_VERSION = "2026.12.6.2"; +inline constexpr std::string_view MCPP_VERSION = "2026.12.7.1"; } // namespace mcpp From 86e71dd355baeade364fa153526e1be5f4076580 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:52:59 +0900 Subject: [PATCH 15/18] A directory's address carries no trailing separator; the root of the directory's own volume is not asked for its identity, and an undecided question names the node it could not read --- modules/libs/src/path_identity.cppm | 41 ++++++++++++++--------- modules/libs/tests/test_path_identity.cpp | 4 +++ src/cli.cppm | 3 +- 3 files changed, 31 insertions(+), 17 deletions(-) diff --git a/modules/libs/src/path_identity.cppm b/modules/libs/src/path_identity.cppm index 411011bbf..f90c76aaf 100644 --- a/modules/libs/src/path_identity.cppm +++ b/modules/libs/src/path_identity.cppm @@ -27,7 +27,8 @@ import std; export namespace mcpp::libs::path_identity { -// The address of a given path: absolute, lexically normal, every link and alias kept. +// The address of a given path: absolute, lexically normal, every link and alias kept; a +// directory's address carries no trailing separator (`a/b/.` and `a/b` are one address). std::filesystem::path given(const std::filesystem::path& p); // A key built from a path: the UTF-8 text of its address, with `/` separators. Two @@ -67,8 +68,9 @@ std::optional object(const std::filesystem::path& p); // The physical spelling of a path, for a diagnostic only; the address when it cannot be read. std::string describe(const std::filesystem::path& p); -// The report of a question decided by the spellings because an identity could not be read. -// One handler for the process, installed before any question is asked. +// The report of a question decided by the spellings because an identity could not be read: +// the question and the node whose identity was not read, as one sentence. One handler for +// the process, installed before any question is asked. void on_undecided(void (*report)(std::string_view question)); } // namespace mcpp::libs::path_identity @@ -116,7 +118,12 @@ std::pair existing_part(const fs::path& p) { fs::path given(const fs::path& p) { std::error_code ec; auto abs = fs::absolute(p, ec); - return (ec ? p : abs).lexically_normal(); + auto out = (ec ? p : abs).lexically_normal(); + // `lexically_normal` keeps a trailing separator (`a/b/.` is `a/b/`), which a tool that + // reads its own escapes takes for one (llvm-windres: `-IC:\a\b\` is an unterminated + // escape, measured on windows-2022). + if (out.has_relative_path() && out.filename().empty()) out = out.parent_path(); + return out; } std::string key(const fs::path& p) { return text(given(p)); } @@ -160,7 +167,8 @@ bool same(const fs::path& a, const fs::path& b) { if (!ofs::same(ta, tb)) return false; const auto ia = ofs::identity_of(na), ib = ofs::identity_of(nb); if (ia && ib) return *ia == *ib; - undecided(std::format("whether {} and {} are one object", text(ga), text(gb))); + undecided(std::format("whether {} and {} are one object could not be read: {}", text(ga), text(gb), + ia ? ib.error().message() : ia.error().message())); return false; } @@ -173,18 +181,21 @@ std::optional beneath(const fs::path& p, const fs::path& dir) { if (ofs::within(rp, rd)) return rp.lexically_relative(rd); if (!present(rd)) return std::nullopt; const auto id = ofs::identity_of(rd); - bool unread = !id; - if (id) { - for (auto at = rp;; at = at.parent_path()) { - if (present(at)) { - const auto here = ofs::identity_of(at); - if (here && *here == *id) return rp.lexically_relative(at); - if (!here) unread = true; - } - if (at.parent_path() == at || at.empty()) break; + std::string unread = id ? std::string{} : id.error().message(); + // The root of the volume `dir` is spelled on is `dir` only when `dir` is that root, which + // the spellings answered above; a root spelled otherwise (a drive alias, a mount) may name + // `dir`, and only its identity is asked. + const auto own_root = [&](const fs::path& at) { return at == at.root_path() && ofs::same(at, rd.root_path()); }; + for (auto at = rp; id && !at.empty(); at = at.parent_path()) { + if (!own_root(at) && present(at)) { + const auto here = ofs::identity_of(at); + if (here && *here == *id) return rp.lexically_relative(at); + if (!here && unread.empty()) unread = here.error().message(); } + if (at.parent_path() == at) break; } - if (unread) undecided(std::format("whether {} lies within {}", text(gp), text(gd))); + if (!unread.empty()) + undecided(std::format("whether {} lies within {} could not be read: {}", text(gp), text(gd), unread)); return std::nullopt; } diff --git a/modules/libs/tests/test_path_identity.cpp b/modules/libs/tests/test_path_identity.cpp index 4768d7043..1972b74c5 100644 --- a/modules/libs/tests/test_path_identity.cpp +++ b/modules/libs/tests/test_path_identity.cpp @@ -37,6 +37,10 @@ UTest the_given_spelling_keeps_a_link{"PathIdentity/TheGivenSpellingKeepsALink", if (!t.links) skip("no privilege for a directory link here"); const auto viaLink = t.base / "link" / "." / "x"; expect(eq(pi::given(viaLink), (t.base / "link" / "x").lexically_normal())); + // A directory's address carries no trailing separator. + expect(eq(pi::given(t.base / "real" / "."), (t.base / "real").lexically_normal())); + expect(eq(pi::key(t.base / "real" / ""), pi::key(t.base / "real"))); + expect(eq(pi::given(t.base / "real" / "x" / ".."), (t.base / "real").lexically_normal())); expect(eq(pi::key(viaLink), pi::given(viaLink).generic_string())); expect(ne(pi::key(viaLink), pi::key(t.base / "real" / "x"))); }}; diff --git a/src/cli.cppm b/src/cli.cppm index f40c6993c..25294fdef 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -1233,8 +1233,7 @@ int run(int argc, char** argv) { // said, for every package that asks one (SPEC-020): the path package imports nothing of // mcpp, so the report is installed here. mcpp::libs::path_identity::on_undecided(+[](std::string_view question) { - mcpp::diag::degraded("path", std::format("{} could not be read", question), - "it was decided by the paths as they are spelled"); + mcpp::diag::degraded("path", std::string(question), "it was decided by the paths as they are spelled"); }); // Internal split-schedule executor. Everything after `--` is the From 25c9262a896c44f7219c57ce11f9e308025e365e Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 02:53:21 +0900 Subject: [PATCH 16/18] SPEC-020 states that a directory's address has no trailing separator and when a root is asked for its identity --- ...2026-12-07-path-uses-roots-and-tool-addresses-design.md | 4 ++++ docs/specs/paths.md | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md index 933fa4ab5..e744aaa82 100644 --- a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md +++ b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md @@ -166,7 +166,11 @@ void on_undecided(void (*report)(std::string_view question)); - `resolved`:自根逐个组成部分读链接(mcpplibs.os `read_link`,含 Windows 的目录联接),绝对目标从其根重来,相对目标 接在链接所在目录之后;不存在的部分原样附加;链接环在 40 跳截断,回答地址本身。 - `same`:给定拼写相同即真;跟随链接后拼写相同即真;否则比较两侧最深的存在部分的对象标识,且其后的部分拼写相同。 +- `given`:目录的地址不带结尾分隔符(`lexically_normal` 保留 `a/b/..` 的结尾分隔符,`llvm-windres` 把 `-IC:\a\b\` + 读作未终止的转义,windows-2022 实测)。 - `beneath`/`within`:跟随链接后按组成部分包含即真;否则取 `dir` 的对象标识,沿 `resolved(p)` 的祖先逐级比较,相等即真。 + 与 `dir` 同一卷拼写的根不读标识:它只在 `dir` 就是该根时与之同一,拼写已回答;Windows 上按名字读盘符根的标识取不到, + 读它使每个不在目录下的回答都报告为不能判定(windows-2022 实测)。 - 取不到标识时按拼写决定,并经 `on_undecided` 报告;该处理由 mcpp 在命令入口安装一次,报告为 `diag::degraded("path", …)`(本包不导入 mcpp)。调用点不各自处理降级。 - 原 `identity()` 删去:调用者需要的是对象的问题,不是一个物理路径。 diff --git a/docs/specs/paths.md b/docs/specs/paths.md index 24a60744a..12529ecdb 100644 --- a/docs/specs/paths.md +++ b/docs/specs/paths.md @@ -36,7 +36,7 @@ ## 2. 地址 1. 用户、环境或系统给出的路径(参数、环境变量、清单、当前目录、系统报告的临时目录与运行时目录)**必须**以给定的 - 拼写打开并交给程序:绝对化与词法规范化,不解析链接与别名。 + 拼写打开并交给程序:绝对化与词法规范化,不解析链接与别名;目录的地址不带结尾分隔符。 2. 派生路径**必须**是“根 / 相对部分”的词法结果;根只有三种来源:给定的、系统报告的、mcpp 自己写的记录。 3. mcpp 写入的记录**必须**只含地址。 4. 互斥**必须**由对象内部的文件锁保证,经地址打开;同一对象的任何拼写打开的是同一个锁文件,正确性因此不依赖 @@ -66,7 +66,10 @@ ## 6. 不能判定 -1. 对象标识读不出时,问题**必须**按拼写判定,并报告为降级(`path`),说明所判定的问题;`--strict` 下降级为错误。 +1. 对象标识读不出时,问题**必须**按拼写判定,并报告为降级(`path`),说明所判定的问题与读不出标识的节点;`--strict` + 下降级为错误。 +2. 与目录同一卷拼写的根只在目录就是该根时与目录同一,拼写已回答这一点,因此不为此读取根的标识;拼写不同的根 + (盘符别名、挂载)才读取。 ## 7. 物理拼写 From a1002e9e1efdfccc16f53a257dfdb4f3bac9a522 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 04:05:42 +0900 Subject: [PATCH 17/18] A drive alias is asked through the entry beneath its root, since a root gives no identity by its name; two unit cases expect the given spelling --- modules/libs/src/path_identity.cppm | 23 +++++++++++++++++------ modules/libs/tests/test_path_identity.cpp | 18 ++++++++++++++++++ tests/unit/test_toolchain_descriptor.cpp | 3 ++- tests/unit/test_xlings.cpp | 5 +++-- 4 files changed, 40 insertions(+), 9 deletions(-) diff --git a/modules/libs/src/path_identity.cppm b/modules/libs/src/path_identity.cppm index f90c76aaf..37291dae8 100644 --- a/modules/libs/src/path_identity.cppm +++ b/modules/libs/src/path_identity.cppm @@ -182,17 +182,28 @@ std::optional beneath(const fs::path& p, const fs::path& dir) { if (!present(rd)) return std::nullopt; const auto id = ofs::identity_of(rd); std::string unread = id ? std::string{} : id.error().message(); - // The root of the volume `dir` is spelled on is `dir` only when `dir` is that root, which - // the spellings answered above; a root spelled otherwise (a drive alias, a mount) may name - // `dir`, and only its identity is asked. - const auto own_root = [&](const fs::path& at) { return at == at.root_path() && ofs::same(at, rd.root_path()); }; + // A volume's root is not asked for its identity: the system gives none for a root by its + // name (measured on windows-2022: `asking about D:/: invalid argument`). The root `dir` is + // spelled on is `dir` only when `dir` is that root, which the spellings answered above. A + // root spelled otherwise (a drive alias) names `dir` when the entry beneath it on the way + // to `p` is the entry of that name beneath `dir`. + fs::path below; for (auto at = rp; id && !at.empty(); at = at.parent_path()) { - if (!own_root(at) && present(at)) { + if (at == at.root_path() || at.parent_path() == at) { + const auto twin = rd / below.filename(); + if (!below.empty() && !ofs::same(at, rd.root_path()) && present(twin)) { + const auto a = ofs::identity_of(below), b = ofs::identity_of(twin); + if (a && b && *a == *b) return rp.lexically_relative(at); + if ((!a || !b) && unread.empty()) unread = (a ? b : a).error().message(); + } + break; + } + if (present(at)) { const auto here = ofs::identity_of(at); if (here && *here == *id) return rp.lexically_relative(at); if (!here && unread.empty()) unread = here.error().message(); } - if (at.parent_path() == at) break; + below = at; } if (!unread.empty()) undecided(std::format("whether {} lies within {} could not be read: {}", text(gp), text(gd), unread)); diff --git a/modules/libs/tests/test_path_identity.cpp b/modules/libs/tests/test_path_identity.cpp index 1972b74c5..cb07fbee1 100644 --- a/modules/libs/tests/test_path_identity.cpp +++ b/modules/libs/tests/test_path_identity.cpp @@ -110,3 +110,21 @@ UTest a_physical_spelling_is_for_a_diagnostic{"PathIdentity/APhysicalSpellingIsF expect(eq(pi::describe(t.base / "link" / "x"), pi::describe(t.base / "real" / "x"))); expect(eq(pi::describe(t.base / "absent"), pi::key(t.base / "absent"))); }}; + +UTest a_path_outside_is_decided_without_a_report{"PathIdentity/APathOutsideIsDecidedWithoutAReport", [] { + // No link is needed, so this holds on every host: a path outside a directory is answered + // without a report, on one volume and across two (the working directory and the temporary + // one are on different drives on a Windows runner). No volume's root is asked for its + // identity, which a root does not give by its name on Windows. + const auto base = fs::temp_directory_path() / std::format("mcpp-path-outside-{:08x}", std::random_device{}()); + fs::create_directories(base / "a" / "deep"); + fs::create_directories(base / "b"); + pi::on_undecided(count_undecided); + g_undecided = 0; + expect(!pi::within(base / "a" / "deep", base / "b")); + expect(!pi::within(fs::current_path(), base / "b")); + expect(!pi::within(base / "a", fs::current_path() / "no-such-directory")); + expect(eq(g_undecided, 0)); + std::error_code ec; + fs::remove_all(base, ec); +}}; diff --git a/tests/unit/test_toolchain_descriptor.cpp b/tests/unit/test_toolchain_descriptor.cpp index c8db62734..b98bb7dfc 100644 --- a/tests/unit/test_toolchain_descriptor.cpp +++ b/tests/unit/test_toolchain_descriptor.cpp @@ -330,7 +330,8 @@ UTest a_runner_in_the_same_store_is_the_default_for_its_compiler{"PayloadDescrip auto argv = payload_default_runner(compiler); expect(fatal(eq(argv.size(), 1u))); - expect(eq(std::filesystem::path(argv[0]), std::filesystem::weakly_canonical(node))); + // The runner's address as the descriptor states it (SPEC-020 §2). + expect(eq(std::filesystem::path(argv[0]), node.lexically_normal())); // The relative form resolves against the root the descriptor came from. FakeStore::describe(emsdk, R"({"schema": 1, "runner": "bin/node"})"); diff --git a/tests/unit/test_xlings.cpp b/tests/unit/test_xlings.cpp index 1aff14290..7617e5d09 100644 --- a/tests/unit/test_xlings.cpp +++ b/tests/unit/test_xlings.cpp @@ -881,8 +881,9 @@ UTest a_projects_install_takes_the_homes_turn{"XlingsState/AProjectsInstallTakes const mcpp::provider::xlings::Env global{.home = home}; const mcpp::provider::xlings::Env scoped{.home = home, .projectDir = project / ".mcpp"}; expect(eq(mcpp::provider::xlings::state_dir(scoped), mcpp::provider::xlings::state_dir(global))); - expect(eq(mcpp::provider::xlings::state_dir(global), - std::filesystem::weakly_canonical(home / "subos"))); + // The address, as the home was given (SPEC-020 §2): a temporary directory a runner names by + // its short (8.3) spelling keeps it. + expect(eq(mcpp::provider::xlings::state_dir(global), (home / "subos").lexically_normal())); std::filesystem::remove_all(home); std::filesystem::remove_all(project); }}; From a9914b1c197ac3075bdda0b615e4ea199b41feba Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 7 Dec 2026 04:07:03 +0900 Subject: [PATCH 18/18] =?UTF-8?q?SPEC-020=20=C2=A76=20states=20that=20a=20?= =?UTF-8?q?volume's=20root=20is=20asked=20through=20the=20entry=20beneath?= =?UTF-8?q?=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-12-07-path-uses-roots-and-tool-addresses-design.md | 5 +++-- docs/specs/paths.md | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md index e744aaa82..a2571934d 100644 --- a/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md +++ b/.agents/docs/2026-12-07-path-uses-roots-and-tool-addresses-design.md @@ -169,8 +169,9 @@ void on_undecided(void (*report)(std::string_view question)); - `given`:目录的地址不带结尾分隔符(`lexically_normal` 保留 `a/b/..` 的结尾分隔符,`llvm-windres` 把 `-IC:\a\b\` 读作未终止的转义,windows-2022 实测)。 - `beneath`/`within`:跟随链接后按组成部分包含即真;否则取 `dir` 的对象标识,沿 `resolved(p)` 的祖先逐级比较,相等即真。 - 与 `dir` 同一卷拼写的根不读标识:它只在 `dir` 就是该根时与之同一,拼写已回答;Windows 上按名字读盘符根的标识取不到, - 读它使每个不在目录下的回答都报告为不能判定(windows-2022 实测)。 + 卷的根不读标识:Windows 上按名字读盘符根的标识回答 `invalid argument`,读它使每个不在目录下的回答都报告为不能判定 + (windows-2022 实测)。与 `dir` 同一卷拼写的根只在 `dir` 就是该根时与之同一,拼写已回答;拼写不同的根(盘符别名) + 经其下一层的项回答:该项与 `dir` 下同名的项为同一对象时,根指名 `dir`。 - 取不到标识时按拼写决定,并经 `on_undecided` 报告;该处理由 mcpp 在命令入口安装一次,报告为 `diag::degraded("path", …)`(本包不导入 mcpp)。调用点不各自处理降级。 - 原 `identity()` 删去:调用者需要的是对象的问题,不是一个物理路径。 diff --git a/docs/specs/paths.md b/docs/specs/paths.md index 12529ecdb..e4d508a24 100644 --- a/docs/specs/paths.md +++ b/docs/specs/paths.md @@ -68,8 +68,9 @@ 1. 对象标识读不出时,问题**必须**按拼写判定,并报告为降级(`path`),说明所判定的问题与读不出标识的节点;`--strict` 下降级为错误。 -2. 与目录同一卷拼写的根只在目录就是该根时与目录同一,拼写已回答这一点,因此不为此读取根的标识;拼写不同的根 - (盘符别名、挂载)才读取。 +2. 卷的根不读取标识:系统不按名字给出根的标识(Windows 上为 `invalid argument`)。与目录同一卷拼写的根只在目录 + 就是该根时与目录同一,拼写已回答这一点;拼写不同的根(盘符别名)在其下一层的项与目录下同名的项为同一对象时 + 指名该目录。 ## 7. 物理拼写