From 0dd1fba7d7837b99789cb743184e44746f5fd7c2 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 4 Dec 2026 23:06:12 +0900 Subject: [PATCH 01/36] Fetching dependencies: the version table read as the installer reads it, one writer of standard error, one line per dependency, waves A version stated through a local table and a platform reference (`ref`, `inherits`) are read as libxpkg resolves them; a form not read has no revision, `mcpp xpkg parse` refuses it, and a revision read differently from the installer's record is reported once (fetch/revision-misread). The provider's lines go through mcpp.ui, checked by check_stderr_writers.sh against a shrinking baseline. A dependency is one line under its manifest name, with no announcement before the provider downloads, `Updating` when its revision changes. The dependencies known at a step are asked of the provider in one call (batch-fetch). --- .../2026-11-27-ecosystem-boundary-design.md | 1468 +++++++++++++++++ .github/tools/check_stderr_writers.sh | 49 + .github/tools/stderr-writers.baseline | 21 + .github/workflows/ci.yml | 3 + CHANGELOG.md | 15 + docs/11-publishing-a-library.md | 38 +- docs/specs/README.md | 2 +- docs/specs/package-identity.md | 26 +- docs/zh/11-publishing-a-library.md | 25 +- modules/buildopt/src/registry.cppm | 42 +- modules/manifest/src/key_registry.cppm | 6 + modules/manifest/src/toml.cppm | 3 + modules/manifest/src/types.cppm | 9 + modules/manifest/src/xpkg.cppm | 277 +++- src/build/prepare/graph.cpp | 1 + src/build/prepare/graph_load.cpp | 188 ++- src/build/prepare/state.cppm | 8 + src/cli/cmd_xpkg.cppm | 35 + src/fetcher/progress.cppm | 20 +- src/project.cppm | 8 + src/provider/xlings/xlings.cpp | 79 +- src/ui.cppm | 17 +- tests/unit/test_manifest.cpp | 87 + 23 files changed, 2296 insertions(+), 131 deletions(-) create mode 100644 .agents/docs/2026-11-27-ecosystem-boundary-design.md create mode 100755 .github/tools/check_stderr_writers.sh create mode 100644 .github/tools/stderr-writers.baseline diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md new file mode 100644 index 000000000..d4356f6bc --- /dev/null +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -0,0 +1,1468 @@ +--- +subject: ecosystem +status: active +--- + +# 生态与外部的交界:工具链的事实、二进制库交付物、被启动的外部程序、名字的拼写与共享的状态 + +**日期:** 2026-11-27,2026-12-04 修订 · **版本:** v8(待评审;决定全部作出,见 §7;五轮自查的结论见 §11) · +**基线:** mcpp main `30fcd5a0`(2026.11.27.1 之后,含 #1036)、xlings 2026.11.23.1、openkal 0.26.0、openkal-linux 0.27.2、 +openkal-windows 0.23、openkal-musl 0.30.3、mcpplibs.os 0.4.8、mcpplibs.cmdline 0.1.0(mcpp 所钉为 0.0.6)、 +mcpp-index `9788068b` · +**相关规范:** SPEC-002(目标侧)、SPEC-004(清单语义)、SPEC-006(工具链管理)、SPEC-011(并发运行)、SPEC-014(打包)、 +SPEC-017(测试)、SPEC-019(构建优化)、docs/50 的原因码表,openkal 规范 7.1、7.2、7.13、7.17,xlings 的 payload-rules、bundle、xlings-json · +**相关 issue:** mcpp#1029、#1031、#1032、#1034、#1038、#1039、#1040,openkal-musl#93(openkal-linux#30 为其前史); +mcpp#1028 已由 #1036 合入,余下的补全在本文 · +**测量:** 探针 PR mcpp#1035,运行 45997639603(Windows、Linux、macOS 运行器,2026-11-27);本机测量与观察(2026-12-04) + +本文把仍开着的八项报告放在一起设计。它们分属 mcpp、openkal-windows、openkal-musl 与 openkal-linux,另涉及 openkal +规范、mcpp-index、mcpplibs.cmdline 与 xlings。其中七项出在同一处:生态自己的模型与它不拥有、或看不全的东西相接的地方——别人安装的 +工具链、别的构建系统、被启动的外部程序、按拼写授权的环境、看不见彼此的进程。本文把它们抽象为六个通用问题,给出 +六条规则、各仓库改动的性质与最佳方案(§4)、每个仓库一个 PR 的次序(§6)。第八项(#1038)是一项新功能,它使 +mcpp 的一个命令默认运行宿主的程序,按同一组规则设计。评审中另加入四件事:锁的粒度(同一工作区里不同成员同时 +构建)、命令行以人与 agent 同为直接使用者、索引的一次回归的修复、取得依赖时的显示与安装的锁。决定在 §7,已全部作出。 + +## 0. 结论 + +**六个通用问题。** + +- **问题一(工具链的事实)。** 一个工程必须用 mcpp 没有安装的工具链构建,因为它的产物要与那套工具链的使用者链接, + 或者它要链接宿主上已经按宿主 C 库构建的库。它的反面是同一个问题:一套由生态安装的工具链,在被问到自己的事实时 + 回答了宿主的(#1039)。 +- **问题二(二进制库交付物)。** 一个库以二进制形式交付给不使用 mcpp 的构建系统。C++ 静态库没有跨标准库实现的稳定 + ABI,所以交付物的 ABI 由构建它的那套环境决定。 +- **问题三(被启动的外部程序)。** 生态内的程序启动生态外的程序(版本控制工具、命令解释器、自建沙箱的包装程序)。 + 调用者需要确切知道被启动的程序持有什么。 +- **问题四(名字的拼写)。** 生态的工具运行在按拼写授权的环境里(替换出的盘符、经符号链接到达的目录、只对某个 + 名字授权的沙箱)。同一个文件的两个名字在那里不等价。 +- **问题五(共享的状态)。** 一个 home 由许多进程共用,其中一些互相看不见(另一个进程命名空间、另一个容器、经网络 + 文件系统的另一台机器)。「谁持有这个条目」在那里不能由一个进程的所见来判定(#1040)。一把锁保护的范围大于它要保护的对象时,互不相干的 + 工作互相等待。 +- **问题六(直接使用者)。** 一个命令行工具有两种直接使用者:人与 agent。二者起步时手里都只有这个二进制,没有仓库, + 未必有网络;都从 `--help` 与报错往下走。 + +**六条规则。** + +- **规则一(陈述到达它管辖的每一条通道)。** 一条陈述的作用域由它的含义决定,不由首先实现它的那条通道决定。 + 工具链的表管辖一次命令里的每一次编译;ABI 成员管辖依赖图的每一个单元与链接;到达一个单元编译的接口,也到达它的 + 链接;调用者对「被启动的程序持有什么」的陈述,在每一层接口上都能说出。 +- **规则二(交界处的事实取自陈述或探测,探测带着构建的词)。** 归档器、链接器、运行库、标准库模块的源文件、是否接受 + 模块语法,是树的陈述或对树的探测结果,不按生态自己的载荷的形状假设。向驱动提出的每一个问题带着这次构建调用它时 + 的词(目标、基底、标准库的选择);答案落在构建所声明的根之外时不被采用。取自宿主的工具被点名并报告,不沉默。 +- **规则三(拼写与身份分开)。** 打开文件与启动程序使用给定的拼写;物理路径只用于判定两个名字是不是同一个对象。 + mcpp 已于 2026.11.27.1 对 home 实行(mcpp#1024,§8 的 M5 证实它在替换盘符与符号链接下成立),本文把它下推到 + openkal-windows。 +- **规则四(交付物带着它的环境)。** 二进制交付物陈述构建它的环境;该环境由生态供给时,消费者经同一个机制—— + xlings 的工程环境,在 `mcpp.toml` 中是 `[xlings]`——取得它;不由生态供给时,交付物用一棵具名的树构建,并在记录中说明。 +- **规则五(持有由系统的锁判定,记录只用于称呼)。** 一个共享条目是否被持有,是系统的锁的事实;持有者留下的记录 + 只用来告诉等待者,不用来判定,也不用来回收。完整的条目不加锁地读;等待从不沉默。它与规则三同形:称呼用给出的 + 名字,判定用系统的事实。锁的粒度与它保护的对象一致:单元、计划、配置各有各的保护。 +- **规则六(工具自己说明自己)。** 使用它所需的一切都能从二进制得到;帮助、补全、解析与用法说明读同一份命令树, + 说明与二进制的一致由测试保证;每一个出口给出下一步。没有专为某一种使用者的行为分支。 + +**一张图。** + +| 问题 | 规则 | 改动 | 仓库 | 报告 | +|---|---|---|---|---| +| 一 工具链的事实 | 一、二 | 1、2、3 | mcpp | mcpp#1034、#1039 | +| (同一规则下的缺陷) | 一 | 4、5、6 | mcpp | mcpp#1031、#1029、#1028 | +| 二 二进制库交付物 | 四 | 7 | mcpp;索引与 xlings 的既有机制 | — | +| 三 被启动的外部程序 | 一 | 13、14 | openkal-musl、openkal 规范与三个实现 | openkal-musl#93 | +| 四 名字的拼写 | 三 | 12 | openkal-windows | mcpp#1032 | +| 五 共享的状态 | 五 | 8、11、19 | mcpp;xlings(登记 issue) | mcpp#1040 | +| 六 直接使用者 | 六 | 9、10、11、18 | mcpp、mcpplibs.cmdline | mcpp#1038 | +| (生态的数据) | 二 | 15、16、17 | mcpp-index | — | + +**改动(按仓库;性质与理由见 §4)。** + +*mcpp* + +1. 表形式的 `[toolchain]` 的全部字段到达构建程序的子构建;子构建的身份包含这些字段(#1034,§3.1.1)。 +2. 一棵具名的树的四项能力取自陈述或探测:归档器(宿主的被点名并报告)、归档器是否接受响应文件、链接器与运行库、 + 是否接受模块语法(§3.1.2)。 +3. 向驱动提出的每一个问题带着构建的词,经同一个函数;标准库模块的源文件在预编译的词已知之处询问;答案落在构建 + 所声明的根之外时不被采用,并在规划时说明(#1039,§3.1.3)。 +4. 链接跟随编译:向一个单元的编译供给接口(BMI 或包含目录)的每一个包,其共享镜像在该单元所属镜像的链接行上 + (#1031,§3.2.1)。 +5. 三个 ABI 成员(`threads`、`exceptions`、`longjmp`)由同一个函数渲染到根包与每一个依赖包的 C 与 C++ 单元和链接; + 显式陈述 `exceptions = "wasm"` 与行的默认值得到同一结果(#1029,§3.2.2)。 +6. 测试程序与本包的可执行目标写同一个文件时在规划时拒绝(#1028,已由 #1036 合入)。本文补全它:原因码进入 docs/50 + 与 `mcpp explain`,消息点名目录与可以照抄的补救,命令一级的测试,在不区分大小写的文件系统上的判同(§3.2.3)。 +7. 库包的索引条目由命令写出:`mcpp pack ` 写出包的描述,`mcpp emit xpkg --package` 据此写出完整的条目 + (§3.3.2)。带头文件接口的库包的每条腿另带 `lib//pkgconfig/<包的身份>.pc`,条目经索引已有的函数把它 + 声明进工程环境的 pkg-config 视图,其他构建系统由此读到它(§3.3.3)。 +8. home 与构建目录的锁(#1040,§3.7):完整的条目不加锁地读,只有要写它的构建才取锁;所有的等待经同一个原语,它把 + 「被持有」与「不能加锁」分开,报告锁的路径与记录的可见性并周期性重复,可由 `--lock-wait` 陈述上限;不按记录回收锁。 + 锁的粒度与被保护的对象一致:单元由发布协议保护,计划的锁属于选择,配置的锁只在整体操作时排他——同一个工作区里 + 选择不同成员的两个命令因此同时构建(决定 D12)。 +9. `mcpp new` 默认把新建的工程初始化为一个 git 仓库,有显式的覆盖(`--vcs none` 与 `config.toml`);位于另一个工程或 + 仓库之内的子工程不带自己的版本库;不提交、不选分支名;没有 git 时工程照常创建并报告(#1038,§3.8)。 +10. 命令行以人与 agent 同为直接使用者(§3.9):升级 mcpplibs.cmdline 并启用它的 `--agent-skill-doc`,每个命令的用法 + 随二进制携带;根帮助由命令树生成;每一个出口给出下一步(相近的名字、应运行的那一行);`mcpp explain` 覆盖全部 + 三类代码。 +11. 取得依赖(§3.11):索引条目的修订读对,读不懂时是「未知」而不是 0,已装好的依赖不再每次构建都回到安装器; + 写到标准错误的每一行经界面模块,进度条不再残留;每个依赖一行、一种写法,不预告没有发生的下载;依赖按波次在 + 一次安装器调用里取得;`--lock-wait` 传给安装器。mcpp 自己的安装轮次本轮不动,它的去留随改动 19 的收尾。 + +*openkal-windows* + +12. 启动程序时,目录按三步称呼:预开目录用预开时的名字;位于本进程当前目录之内的目录用当前目录的名字加余下的 + 部分;其余用系统报告的路径。前两步的结果与句柄核对为同一对象(mcpp#1032,§3.5)。 + +*openkal-musl、openkal 规范与三个实现(openkal-linux、openkal-macos、openkal-windows)* + +13. C 库一层能够陈述「被启动的程序不持有 3 号及以上的任何描述符」,该陈述使启动不传递授权(openkal-musl#93,§3.4.1)。 +14. 一次没有陈述资源偏好的启动不写入自己的变量,环境按调用者给出的原样到达。规范 7.17 补一句说明继承的途径, + 规范的测试集增加一例;三个实现改为与其余五个实现已有的行为一致(§3.4.2)。 + +*mcpp-index* + +15. 补齐显示栈的缺包:D-Bus、XCB 的扩展库与工具库、xkbcommon 的 X11 部分、无障碍总线客户端、两个矢量图形库 + (§3.6)。 +16. 修复 `mcpplibs.cmdline` 条目的安装钩子(它使该包的 0.0.1 无法安装,mcpp 的每个 PR 的 CI 因此失败),并增加一项 + 检查:一个被改动的条目所列的每个版本都被安装一次(§3.10)。 +17. 把 28 个经局部表引用来陈述版本的条目改写为内联的表,并由索引的检查固定这一写法,直到每个仍受支持的 mcpp + 版本都读得懂引用的写法(§3.11.2 第 3 条)。它使已经发布的 mcpp 立即停止对这些包的重复安装。 + +*mcpplibs.cmdline* + +18. 用法错误带上相近的名字与适用的帮助;提供把 skill 文档与命令树相互核对的函数;合并两处重复的索引实现(§3.9.3)。 + +*xlings* + +19. 本方案不改 xlings 的代码。安装的锁的粒度(一个包的载荷在这个包的锁之下,状态的读改写在状态锁之下且只在 + 那一小段持有)登记为 xlings 的一个 issue,由 xlings 实现;mcpp 另登记一个备注 issue,记下 xlings 发布之后 + 收尾的那个 PR 要做的事(§3.11.2 第 10 至 13 条,D14)。名字的拼写不改:测量表明别名本身不导致失败 + (§8 M5),报告中另两项观察在没有那种沙箱的运行器上没有重现。 + +**不做的事(§9)。** 不放开对 `"system"` 的拒绝;不在引擎内加入任何厂商工具链的名字或专有开关;不增加面向全图的 +C flags 通用键;不为追随旧发行版而增加旧版编译器载荷;不改变授权随启动传递的默认值;不按记录中的进程标识回收锁; +不把删除锁文件作为补救;不让 `mcpp new` 的版本库初始化成为没有覆盖的行为;不设「agent 模式」;不向新建的工程写入 +面向 agent 的说明文件。 + +## 1. 证据的状态 + +**实测**指在基线上运行并观察(本机或探针运行 45997639603);**读码**指读源码得出,未运行;**报告**指 issue 中的观察。 + +| 事实 | 来源 | +|---|---| +| 表形式工具链的 `launcher` 与 `tools.cxx` 对工程自己的单元生效,对构建程序不生效;子构建只收到 `path:` | 实测(Linux,本机) | +| Linux 运行器上 `{ path = "/usr", family = "gcc", sysroot = "/" }`:工程由 gcc 13.3.0 编译并链接宿主 C 库;它的构建程序由 clang 18.1.3 规划,并因「基底没有内核头」被拒绝。`family` 与 `sysroot` 都没有到达 | 实测(M4) | +| macOS 运行器上陈述了 `tools.ld` 的树:工程链接成功,构建程序的链接是 `-fuse-ld=lld` 并失败 | 实测(M4) | +| 没有陈述 `tools.ld`、树中也没有 lld 的 clang 树,工程自己的链接同样失败(`invalid linker name in argument '-fuse-ld=lld'`) | 实测(M4) | +| 运行器自带的归档器不接受响应文件(`ar: @…rsp: No such file or directory`) | 实测(M4) | +| 该运行器的 clang 17 在 `-std=c++23` 下不接受 `export module`,加上厂商的开关也不接受;mcpp 把这个错误留给了编译器 | 实测(M4) | +| 驱动能回答自己有没有编译器运行库与展开库:前者给出文件,后者原样回显名字 | 实测(M4) | +| 以路径点名一个没有 `ar` 的树时,子构建的 `build.ninja` 写的是裸名字 `ar = ar` | 实测(Linux,本机) | +| 共享镜像只取直接依赖包的共享库上链接行 | 读码;报告含复现 | +| `wasm32-emscripten`:C 单元在根包时,行默认值与「两者都陈述」成功,只陈述 `exceptions = "wasm"` 失败;C 单元在依赖包时,行默认值、只陈述异常、两者都陈述三种都失败(`undefined symbol: emscripten_longjmp`),`exceptions = "js"` 成功 | 实测(M3,七个变体) | +| 测试程序与本包可执行目标同路径时的规划拒绝已合入(#1036):检查在测试模式的入口,根包与成员两条路径;两例单元测试,没有命令一级的测试;原因码未列入 docs/50;路径比较区分大小写 | 读提交 | +| 本机 5253 份清单按「可执行目标的名字等于 `tests/` 下的目录或文件名」粗筛,命中 1 份 | 实测(本机,2026-12-04) | +| 替换盘符 `Z:` 下,直接启动的程序读到的模块路径是 `Z:\…`;经 mcpp 启动的同一程序读到物理路径,命令行仍是 `Z:/…`;工作目录同样变为物理路径;系统的盘符表包含 `Z:` | 实测(M1) | +| 物理映像名在只对别名授权的沙箱里使被启动的编译器失败 | 报告(含四格对照);机制已由 M1 证实 | +| openkal-musl 0.30.3 的 `posix_spawn` 无条件传递授权;未列入的属性标志返回 `ENOSYS`;3 号以上的 `addclose` 被接受且不产生效果;预开变量带接收者的进程标识,采用者把这些描述符标为执行时关闭 | 读码 | +| mcpplibs.os 的授权是可选项,mcpp 启动编译器时不传授权 | 读码 | +| mcpp 的 home 在替换盘符(Windows)与符号链接(Linux)之下:构建成功,命令行、产物的解释器与搜索路径只出现给定的拼写 | 实测(M5) | +| xlings 向一个经符号链接到达的 home 从离线包安装成功 | 实测(M5) | +| 一个依赖 `xim:gcc@16.1.0` 的载荷装入声明 gcc 15.1.0 的工程环境:16.1.0 被装在旁边且不激活,环境的编译器仍是 15.1.0,没有任何提示 | 实测(M2) | +| mcpp 中 `[toolchain] gcc@15.1.0` 与 `[xlings.workspace] "xim:gcc" = "16.1.0"` 并存:两个版本都被供给,构建用 15.1.0,没有任何提示 | 实测(M2) | +| 索引中的库载荷以下界陈述运行时(`xim:glibc@>=2.38`);`gcc-runtime` 的说明是一个版本覆盖用相同或更旧 GCC 构建的二进制 | 读索引 | +| 索引中 85 个库载荷的配方带 `.pc` 文件,并经配方库的 `sysroot.declare_pkgconfig` 把它声明进环境的 pkg-config 视图;mcpp 的构建程序经 `pkg_config_libdir()` 读同一个视图 | 读索引;docs/30 | +| `mcpp pack --pkg-format tar` 写出的归档含 `mcpp.toml`、`include/`、`interface/`、`lib//`,不含 `mcpp-package.json` | 实测(Linux,本机) | +| `mcpp emit xpkg --package <库包归档>` 以 `'/…' has no mcpp-package.json` 失败,退出 2;消息不说明这是库包,也不给补救 | 实测(Linux,本机) | +| 在解包后的库包目录中运行不带 `--package` 的 `mcpp emit xpkg`,得到源码包形状的条目:地址与摘要是占位符,并列出三个系统,而包中只有一条 Linux 的腿 | 实测(Linux,本机) | +| 库包的测试只覆盖以 `path` 消费;docs/12 列出的「索引条目」这一写法没有测试 | 读测试 | +| mcpp-index 的 `freedesktop.libxkbcommon` 只编核心,源码树中的 X11 部分未列入;`compat.xcb` 只构建核心协议 | 读索引(M6) | +| 询问标准库模块源文件的两次探测只带驱动的路径,不带目标;询问运行库归档的函数带链接行的 flag,其注释记录了不带接口级别时回答宿主归档的测量 | 读码 | +| 同一个驱动不带目标回答宿主 GCC 的模块清单,带上目标回答「没有」;预编译因找不到宿主标准库的头文件而失败 | 报告(含两次对照);本机没有该载荷与带模块清单的宿主 GCC,未复现(M8) | +| home 的锁是系统的建议锁,描述符带执行时关闭;`.owner` 记录从不删除 | 读码 | +| 本机 44 个标准库模块条目的记录全部指向已不存在的进程;系统没有报告其中任何一把锁被持有 | 实测(本机,2026-12-04) | +| 标准库模块的条目在命中时也取排他锁,发生在规划段;它的记录每次原地重写 | 读码 | +| 加锁的原语对任何失败返回同一个值;等待的循环把「文件存在」时的任何失败当作被持有,无限等待,并报告记录中的进程 | 读码 | +| 等待在 300 毫秒时报告一次;另有两处等待不报告,一处的阈值是一小时 | 读码 | +| 分析所在的会话处于非初始的进程命名空间,宿主与其他沙箱的进程在其中不可见 | 实测(本机) | +| #1040 所报告的那一次等待的直接原因 | 未确定:现场的文件已删除 | +| `mcpp new` 的三条创建路径不运行任何版本控制工具;内置模板与平台模板写出 `.gitignore` | 读码 | +| mcpp 已为 git 依赖、发布与离线包运行 `PATH` 中的 `git` | 读码 | +| 一个工作区的两个互不依赖的成员:`build -p a` 运行时启动 `build -p b`,二者规划进同一个配置目录,后者等待 4.5 秒(前者共 6.1 秒)后才编译 | 实测(本机,2026.11.27.1) | +| 每一次编译经编译执行器,按命令、编译器与源文件内容在 home 的单元缓存中查找,命中时放置而不启动编译器;可重定向的工具链上编译写私有路径后改名发布 | 读文档(docs/26)与规范(SPEC-011 §5.1 第 8 条) | +| SPEC-011 §2 第 5 条写 `mcpp test` 持锁到测试结束;实现在构建完成后释放,docs/07 与实现一致 | 读三处 | +| 2026-10-26 的设计 §4.2 曾决定不新增「等待或失败」的参数 | 读设计记录 | +| 根帮助是手写的文本,与命令树是两份,缺若干命令;未知命令打印整份帮助且没有相近的名字;未知选项与没有工程时各只有一行;`mcpp explain` 只认识 `E0001` 至 `E0006`;`mcpp help <命令>` 打印根帮助 | 实测(本机,2026.11.27.1) | +| mcpp 钉的 mcpplibs.cmdline 是 0.0.6;0.0.7 提供分组与帮助的尾段,0.1.0 提供动作之前应答的选项与 `--agent-skill-doc`(构建时渲染进二进制) | 读清单与该库的源码 | +| 该库的 `install_default` 与 `install_runtime` 各含一份逐行相同的索引实现;用法错误不带相近的名字 | 读源码 | +| mcpp-index 的 `mcpplibs.cmdline` 条目自 2026-12-03 起带一个安装钩子,它在安装目录里找解包出的树而树尚未放入;0.0.1 的安装失败;条目的测试成员只依赖最新版本 | 读提交与 mcpp 的 CI 日志 | +| 上述失败出现在 mcpp 一个 PR 的四个失败作业中(单元测试两个分片、Linux 与 macOS 的 e2e);另两个失败作业(示例、Windows 集成)未见同样的行,原因未确认 | 读 CI 日志 | +| cargo 1.99:独立的新工程建立仓库;已有仓库之内不建立;尚未纳入版本控制的工作区之内的成员建立;仓库之内显式 `--vcs git` 建立。`go mod init`、`npm init` 不建立 | 实测(本机) | +| 已装好的依赖每次构建都回到安装器:mcpp 读到的条目修订是 0,安装器记录的是 1;进度条的第一帧残留:安装器一层的一行直接写标准错误;一次构建等待另一个工程的安装:两层各有一把以 home 为范围、贯穿整个安装的锁 | 实测与读码,细目在 §3.11.1 | + +## 2. 已有的机制 + +本方案不新增机制的地方,都落在下表的某一行上。 + +| 机制 | 所在 | 与本文的关系 | +|---|---|---| +| `[toolchain]

= { path, prefix, sysroot, family, launcher, tools }` | mcpp,docs/20 | 问题一的唯一入口;改动 1、2、3 使它在每条通道上成立 | +| `msvc@system`、被定位而不安装的 Apple SDK | mcpp,docs/20 | 不可再分发的厂商部件的既有处理;本文不增加同类 | +| `[toolchain] bootstrap` | mcpp,docs/20 | 构建程序需要另一套工具链时的陈述 | +| 目标基底 `sysroot`、`allow_host_libs`、运行阶段的能力要求与 `HOST-REQUIREMENTS` | mcpp,docs/20、docs/10 | 链接宿主库与宿主驱动的既有通道 | +| 宿主工具的报告:取自宿主的汇编器被点名并写进构建报告 | mcpp,docs/20 的宿主面一节 | 改动 2 对归档器沿用这一做法 | +| 没有 C++ 模块的编译器:不含模块的单元照常构建,模块单元在规划时拒绝并指出文件 | mcpp,docs/20 | 改动 2 把探测结果接到这条已有的路径上 | +| 库包:`mcpp pack ` 写出接口、二进制与带兼容标签的清单,消费侧核对标签 | mcpp,docs/12 | 问题二在 mcpp 消费者一侧已解决 | +| `[xlings]`:`[xlings.workspace]`(宿主轴)与 `[target.<选择器>.xlings.workspace]`(目标轴),原样物化为工程的 `.xlings.json`;一个包一个版本的裁决 | mcpp,docs/23 | 规则四的机制:交付物的环境在这里陈述,也在这里被消费 | +| 工程环境:`.xlings.json` 的 `workspace` 在工程自己的 SubOS 里给出工具链,任何构建系统在其中运行 | xlings,docs/04 | 同一机制面向其他构建系统的一面 | +| `mcpp emit xpkg`:为打包出的程序写索引条目 | mcpp,docs/10 | 改动 7 把它用于库包 | +| 载荷规则 A、B、D、E、M、P;离线包 `bundle.toml` | xlings 规范 | 库包作为载荷须满足规则 P;无网络的宿主走离线包 | +| 形状 F(共享库兼容包)与形状 G(宿主运行时适配) | mcpp-index,package-types | 显示栈从源码构建,驱动来自宿主 | +| 输出路径的冲突在规划时拒绝:测试重名、一个测试是另一个的目录、成员的目标与另一个目标同路径 | mcpp,SPEC-017 | 改动 6 属于这一类,处理与它们相同 | +| 询问运行库归档的函数:接收链接行的 flag,答案按「驱动加词」缓存 | mcpp,工具链模块 | 改动 3 把它推广为向驱动提问的唯一入口 | +| home 的锁(系统的建议锁加一份记录)、写临时文件后改名替换的函数;读者不加锁、规划段不持锁 | mcpp,SPEC-011 | 改动 8 使标准库模块的条目遵循它,并把等待收到一个原语 | +| 编译执行器与 home 的单元缓存;私有路径写出、改名发布;链接产物的原子发布 | mcpp,docs/26、SPEC-011 §3、§5.1 | 改动 8 的粒度依靠它们:单元由此自己保护自己 | +| 各选择共用构建目录,同一个单元在每个选择里是同一条命令;`.build_cache` 按选择记录 | mcpp,docs/07 | 改动 8 保留它,只把计划与 ninja 的状态归于选择 | +| mcpplibs.cmdline:命令树、分组、帮助的尾段、动作之前应答的选项、补全、`--agent-skill-doc` 与构建时的渲染 | mcpplibs.cmdline 0.0.7、0.1.0 | 改动 10 启用它们;改动 18 补上相近的名字与核对的函数 | +| 非终端下的人读输出、`--message-format json`、调用方标签、副作用的陈述(`--offline`、`--deny`) | mcpp,docs/50、docs/52 | 改动 10 不设第二套语义,说明只是把它们讲给只有二进制的读者 | +| 安装钩子的契约:把解包出的树放到 mcpp 会去找的地方 | mcpp,docs/32 | 改动 16 修的正是违反它的一个钩子 | +| 界面模块的实时区域:一个写者,记着自己画了几行,非终端下每项完成时一行 | mcpp,界面模块 | 改动 11 使它成为叙述流唯一的写者 | +| xlings 的状态锁:以 home 为范围,只有改变状态的命令取它,记录是提示而不是事实,等待有上限 | xlings | 改动 19 把持有的时段缩到状态的读改写,载荷另有包的锁 | +| docs/51 的受支持版本 | mcpp | 改动 17 的依据:条目须处在每个受支持版本的读者读得懂的范围内 | +| 对 `git` 的查找与运行 | mcpp,git 依赖 | 改动 9 复用,不另设查找 | +| 「被启动的程序得到三个流与调用者授予的目录,别无其他句柄」 | openkal 规范 7.13 | 问题三的规则已在;缺的是 C 库一层说出它的词 | +| 一个实现不维护名字解析器 | openkal 规范 7.1 | 改动 12 去掉的正是启动路径上的那一次解析 | + +## 3. 设计 + +### 3.1 工具链的事实(mcpp) + +`{ path = … }` 是 mcpp 对「这台机器已有的一棵工具链树」的陈述方式:树由工程点名,mcpp 识别并记录它。它与被拒绝的 +`"system"` 的区别在于后者没有被点名。问题一的全部需求由这一个入口承担,本文不增加第二个入口;这条路受支持, +它放弃的保证(另一台机器上的同一次构建)由 mcpp 在构建报告中写明,文档不把它作为首选。 + +#### 3.1.1 表到达构建程序 + +**现状。** 构建程序由一次子构建编译。主构建把工具链交给它时只交一个字符串,表形式在那个字符串里是 +`path:

`;子构建把来自上层的规格当作没有表的路径读取。实测的后果:同一个工程的两类编译由两个不同的编译器进行, +构建程序因缺少工程已陈述的基底而被拒绝,或因缺少工程已陈述的链接器而链接失败。 + +**设计。** 为构建程序写出的工作空间清单带上同一张表:`[workspace.toolchain]` 下宿主平台的条目(主构建为宿主解析出 +的那一张,不是某个目标条件下的),各路径写成绝对路径。 +子构建不再从上层接收 `path:` 规格,而是像任何工程一样从自己的清单读表,读表的实现只有清单这一个。托管规格 +(`gcc@…`、`llvm@…`、`msvc@…`)仍以字符串交付,它们没有表。 + +子构建的身份(决定构建程序是否重用的键)包含表的每个字段与 `tools` 各项的路径、大小与修改时间,与主构建的指纹用同一 +份输入。 + +**结果。** 文档已有的一句话成为事实:没有 `bootstrap` 时,本机构建用自己的工具链编译构建程序。需要驱动带固定词的树 +用 `tools.cxx` 指向一个驱动脚本即可,该脚本此后对两类编译同样生效;工程不需要镜像一个工具目录。 + +#### 3.1.2 树的能力取自陈述或探测 + +四项事实目前按生态载荷的形状假设,对别的树不成立(均已实测)。 + +| 事实 | 现状 | 设计 | +|---|---|---| +| 归档器 | 取 `tools.ar`,否则在树中找;找不到写裸名字 `ar` | 找不到时在 `PATH` 中解析为绝对路径,记入指纹,并像宿主的汇编器那样报告:`the archiver for this build is the host's ('')`,补救是 `tools.ar`;`--strict` 拒绝。`PATH` 中也没有即拒绝。裸名字不再写入。查找的名字取自该族的数据行,引擎不写死 | +| 归档器接受响应文件 | 假设接受 | 识别时探测一次:经响应文件归档一个文本文件并列出它(归档器接受任意文件,不需要先编译),结果记入工具链记录;不接受的归档器由 mcpp 展开响应文件后调用,超出宿主命令行上限时分批追加再建索引 | +| clang 树的链接器与运行库 | 主构建:`tools.ld` 经 `--ld-path`,否则 `-fuse-ld=lld`;宿主程序:固定 `-fuse-ld=lld --rtlib=compiler-rt --unwindlib=libunwind` | 两类链接同一规则:`tools.ld` 优先;否则树中有 lld 才写 `-fuse-ld=lld`;否则不写,用驱动的默认链接器。运行库与展开库的词只在驱动回答它有该库时写 | +| 是否接受模块语法 | GCC 按版本判断;clang 树假设接受 | 识别时用一个两行的模块单元探测;不接受的树进入已有的「没有 C++ 模块的编译器」路径:不含模块的单元照常构建,模块单元在规划时拒绝并指出文件。需要一个词才接受的驱动,由 `tools.cxx` 指向带上该词的驱动脚本 | + +四项探测都经 §3.1.3 的提问函数进行,带着这次构建的词;结果按「驱动加词」记入工具链记录,进入指纹;`mcpp why toolchain` 列出每一项及其来源(陈述、探测、宿主)。 +目标侧的五层报告对具名的树写 `custom` 而不是 `payload`(实测现在写的是后者)。 + +托管载荷不经过这条路径:它们的形状是索引的数据,行为不变。 + +#### 3.1.3 每一个问题带着构建的词(#1039) + +**现状(读码;报告含两次对照)。** mcpp 向驱动提出若干问题:标准库模块的清单在哪里、链接用的标准库归档在哪里、 +运行库与展开库在哪里。其中两个——标准库模块的源文件的两次探测——在识别工具链时提出,只带驱动的路径,不带目标。 +一个为多个目标服务的驱动(一个 `clang++` 编译两种架构,由 `--target` 告知是哪一个)在不带目标时回答的是宿主: +报告中,同一个驱动不带目标回答宿主 GCC 的 `libstdc++.modules.json`,带上目标回答「没有」。mcpp 于是把宿主的标准库 +模块源文件交给一次以另一个 C 库和另一个标准库为目标的预编译,失败的消息来自编译器(找不到宿主标准库的头文件)。 +这只在宿主装有带模块清单的 GCC 时出现,所以运行器上没有暴露。 + +同一个缺陷在另一个问题上已经修过一次:询问运行库归档的函数接收链接行的 flag,它的注释写明「问题中的目标就是 +链接所指的目标」,并记录了同一个驱动不带接口级别时回答宿主归档的测量。那一次只改了那一个问题。 + +**设计。** 两条,对托管载荷与具名的树同样成立。 + +1. **一个提问的函数。** 向驱动提出的问题(`-print-…`、`--print-file-name=…`,以及 §3.1.2 的探测编译与探测链接) + 都经同一个函数,它接收驱动与这次构建调用它时的词(目标、基底、标准库的选择、「不读默认配置」),答案按 + 「驱动加词」缓存,并随工具链记录保存(键中含驱动的身份),一次构建不为已经回答过的问题再启动驱动。没有词的提问 + 不再存在:识别阶段只回答与目标无关的事实(族、版本);标准库模块的源文件在预编译 + 的词已知之处询问,与询问运行库归档的时机相同。 +2. **答案须落在声明的根之内。** 一次构建声明了它的根:工具链的树、目标基底、被陈述的宿主许可(`allow_host_libs`、 + 数据行陈述取自宿主的部件)。驱动的答案指向这些根之外的文件时不被采用,提问转向下一个探测;所有探测都没有可采用 + 的答案时,沿用已有的「没有标准库模块」的拒绝,并列出每个未被采用的答案及其原因。这条判据不点名任何标准库实现; + 它是「默认封闭」对探测结果的陈述。以路径点名的树声明的根就是那棵树,它的驱动回答树内的文件,结果不变。 + +**结果。** 报告中的构建在规划时得到驱动自带的标准库模块(第一个探测带上目标后回答「没有」,其后的探测在载荷内 +找到它)。即使将来某个驱动在带词时仍回答宿主的文件,第 2 条使它在规划时被说明,而不是在编译时由编译器报错。 + +报告的两条建议中,第一条(带上目标)就是第 1 条;第二条(标准库为某一实现时拒绝另一实现的清单)不采用:它按实现的 +名字判定,而第 2 条按根判定,对任何标准库成立,也覆盖归档与运行库的同类答案。 + +报告另记一个上游事实:该载荷自带的模块清单里相对路径多了一层,按它找不到文件。mcpp 已对「清单指向不存在的文件」 +转向下一个探测,行为不变;这个事实登记进上游缺陷登记表(mcpp#1027)。 + +#### 3.1.4 这条路的测试 + +e2e 四例,按 AGENTS.md §5 的写法(第二行陈述所需能力,缺能力时 `SKIP` 并以 77 退出): + +- 以路径点名一个已安装的托管载荷,表中带 `launcher` 与 `tools.cxx` 两个记录参数的脚本;断言构建程序与工程单元都 + 经过二者。不需要宿主编译器,三个平台都运行。 +- 以路径点名 Linux 运行器自带的树(`{ path = "/usr", family = "gcc", sysroot = "/" }`),带一个构建程序;断言二者由 + 同一驱动编译并链接同一个 C 库。`requires: system-gcc`。 +- 以路径点名 macOS 运行器自带的树,带一个静态库目标、一个构建程序与一个模块单元;断言前两者构建成功、归档器的 + 响应文件由 mcpp 展开,模块单元在规划时被拒绝并指出文件。`requires: system-clang`。 +- 以 `tools.cxx` 指向一个驱动脚本,它对不带目标的提问回答声明的根之外的一个文件,对带目标的提问回答根之内的; + 断言 mcpp 的每一次提问都带着目标,根之外的答案没有进入任何命令,`mcpp why toolchain` 列出标准库模块源文件的来源。 + 不需要宿主编译器,三个平台都运行;它固定 §3.1.3 的两条。 + +### 3.2 同一条规则下的三项缺陷(mcpp) + +#### 3.2.1 链接跟随编译(#1031) + +**现状。** 共享链接时,一个镜像的链接行只有它直接依赖的包的共享库。经由依赖的接口到达的包——模块的再导出、接口 +中的内联函数与模板、头文件互相包含——其符号被消费者的目标文件直接引用,而库不在行上。静态链接时图中每个归档都在 +行上,所以只在共享链接时出现。 + +**设计。** 一个单元的编译收到了哪些包的接口,规划是知道的:模块一侧是扫描得出的导入闭包,头文件一侧是使用要求的 +不动点传给它的包含目录。规则是:**向一个镜像的任一单元的编译供给 BMI 或包含目录的每一个包,若它有共享镜像, +该镜像在这个镜像的链接行上。** 这比「再导出的模块」宽:接口中的内联函数调用另一个包时,没有再导出也产生直接引用。 + +顺序与 `link_line` 的槽位不变,新增的库进入依赖槽,位于直接依赖之后。 + +**范围的上界。** 包含目录按使用要求的作用域传递,私有依赖的不传给消费者,所以新增的库只来自公开依赖的闭包与模块的 +导入闭包,不是整张图。这与静态链接已有的结果同向(那里图中每个归档都在行上)。mcpp 不对这些库使用「按需」一类的 +链接器开关(该开关不是每个链接器都有),所以闭包中未被引用的共享库也成为镜像的装载依赖;`mcpp why flags` 给出每一个 +的来源。 + +#### 3.2.2 ABI 成员的一处渲染(#1029) + +**现状(实测)。** 两个独立的缺口。其一,行的默认值 `exceptions = "wasm"` 会同时设定长跳转模型,工程显式写出同一个值 +时走另一分支,不设定。其二,长跳转的 flag 只加入根包的 `cflags`;`threads` 的 `-pthread` 在每个依赖包加载时补入, +长跳转没有对应的补入。第二个缺口使默认配置失败:什么都不写的工程,只要依赖图里有一个调用 `setjmp` 的 C 包, +链接即失败,消费者一侧没有任何写法能补救。 + +**设计。** 「根包陈述的 ABI」解析为一个记录(线程、异常模型、长跳转模型),解析只做一次:未陈述长跳转时它跟随 +异常模型,无论异常模型来自行还是来自工程。一个函数把这个记录渲染到四处:全图的方言 flag 集合、根包的 C flags、 +每个依赖包的 C flags、链接。现有两处各自为 `-pthread` 写的补入改为调用它。 + +`-fexceptions` 仍不进入 C 单元;`-sSUPPORT_LONGJMP=` 进入每一个 C 单元,因为它改变编译器为 `setjmp` 生成的代码。 +e2e 取 M3 的七个变体,预期全部成功。 + +另加一个按表驱动的单元测试:对每一个 ABI 成员,在「根包、依赖包」乘「C 单元、C++ 单元、链接」的六个位置上断言 +构建数据库中的 flag。增加一个成员而漏掉一个位置时,这个测试失败;它把规则一对 ABI 成员固定下来。 + +issue 末尾关于「`cflags` 到不了索引包」的部分不改:SPEC-004 §9 规定 `cflags` 的作用域是根包与被选中的成员, +ABI 成员是全图事实的通道。 + +#### 3.2.3 测试程序与可执行目标写同一个文件(#1028,已由 #1036 合入) + +**已合入的行为。** 测试的名字就是它的程序在 `bin/` 下的路径;与本包的可执行目标(`bin`,以及形式为可执行文件的 +`app`)得到同一路径时,`mcpp test` 在规划时拒绝,消息带 `[test-output-collision]`,点名包、测试程序、目标与共同的 +路径。检查复用目标的输出路径与工作区成员的放置函数,所以根包与成员两条路径都覆盖,逐文件、按目录、按包三种粒度 +都覆盖。`mcpp build` 不受影响;被拒绝发生在写出构建文件之前,已构建的程序不被覆盖。 + +**决定的修订(D1)。** v4 的决定是先经弃用表报告、到期后拒绝。合入的实现是立即拒绝,本文改取它,理由三条: + +- docs/51 管辖的是清单的拼写与读法。这里被拒绝的不是一种读法,而是两个产物写同一个文件,其结果此前没有定义 + (后运行的命令决定这个文件是什么)。 +- 同一类冲突引擎一律在规划时拒绝:测试重名、一个测试是另一个的目录、成员的目标与本次构建的另一个目标同路径。 + 这一项与它们同类,处理也应相同。 +- 影响面经过测量:本机 5253 份清单按「可执行目标的名字等于 `tests/` 下的目录或文件名」粗筛,命中 1 份。警告期内 + 报告所述的后果(按路径取用程序的工具得到的是测试程序)照样发生。 + +代价写明:处于冲突中的工程升级后 `mcpp test` 被拒绝,没有过渡期;补救是改一个目录或文件的名字。 + +**本文补全的五处。** + +1. **原因码进入表。** `test-output-collision` 列入 docs/50「出现在消息中的标记」一表(两种语言),`mcpp explain` 有它的 + 条目。 +2. **消息点名使用者能改的对象。** 测试的名字取自目录时点名目录,取自文件时点名文件;补救写成可以照抄的一行 + (把 `tests/<名字>/` 改为什么都可以,例子给出一个)。目标一侧点名清单中的键,机器输出带 `path` 与 `range`。 +3. **命令一级的测试。** e2e 两例:根包(构建、测试被拒绝、原来的程序仍在且内容不变、改名后测试通过)与工作区成员。 + 合入的 PR 的描述提到这两例,但提交中只有单元测试。 +4. **判同按文件系统。** 路径的比较现在区分大小写;在不区分大小写的文件系统上,只差大小写的两个名字是同一个文件。 + 判同的函数向输出目录所在的文件系统询问一次它是否区分大小写(探测,不点名系统),不区分时按折叠后的名字比较。 + 同一个函数用于既有的测试重名检查,使这一类检查只有一个判同的实现。 +5. **CHANGELOG 的归类。** 条目移到 Changed,写明处于冲突中的工程的 `mcpp test` 自该版本起被拒绝及其补救。 + +### 3.3 二进制库交付物(mcpp;xlings 与索引的既有机制) + +问题二有两种环境,答案不同。 + +| 环境 | 交付物如何构建 | 消费者如何得到同一环境 | +|---|---|---| +| 生态供给的环境 | 托管工具链 | mcpp 消费者:依赖解析与兼容标签的核对(已有)。其他构建系统:xlings 的工程环境(本节) | +| 生态不供给的环境 | 具名的树(§3.1) | 消费者自己已有那套工具链;mcpp 只记录交付物是用哪棵树构建的 | + +**交付物经生态的运行时环境交付。** 可以,条件是消费者从生态取得编译器。环境的陈述与消费是同一个机制的两面: + +- **陈述。** 构建交付物的工程在 `mcpp.toml` 中已经陈述了它的环境:`[toolchain]`,以及目标轴的 + `[target.<选择器>.xlings.workspace]`(产物编译与链接所依据的载荷)。mcpp 解析后的目标侧记录与锁文件就是这份环境。 +- **消费。** mcpp 消费者把库写进 `[dependencies]`,标签由消费侧核对;它需要的宿主工具写进 `[xlings.workspace]`。 + 使用其他构建系统的消费者在工程的 `.xlings.json` 的 `workspace` 中声明这个库与编译器,`xlings install` 把它们装进 + 工程自己的 SubOS,构建系统在其中运行。`mcpp.toml` 的 `[xlings]` 原样物化为这同一个文件,所以两类消费者用的是 + 一个机制。 + +这条路覆盖 Linux 的全部目标,以及 macOS 上使用生态的 LLVM 与被定位的 Apple SDK 的消费者。Windows 的 MSVC ABI +由平台自己保持稳定,`msvc@system` 与托管的 `msvc@` 已覆盖。它不覆盖的只有一种消费者:坚持使用一套不来自 +生态的编译器。对这种消费者,交付物只能用那套编译器构建,这就是 §3.1 的用途。 + +#### 3.3.1 现状(实测) + +程序与库在这条路上的完成度不同。 + +| | 程序(`kind = "bin"`) | 库(`kind = "lib"`、`"shared"`) | +|---|---|---| +| `mcpp pack` 写出包的描述 `mcpp-package.json` | 是 | 否 | +| `mcpp emit xpkg --package <归档>` 写出完整条目(地址、摘要、覆盖的系统与架构) | 是,全自动 | 否:以 `has no mcpp-package.json` 失败,消息点名的是 mcpp 的临时目录,不说明原因与补救 | +| 条目经索引被消费 | `xlings install` | docs/12 列为一种写法;没有命令能写出正确的条目,也没有测试 | +| 其他构建系统能读的描述 | 不适用 | 没有;包的描述只有 `mcpp.toml` | + +在库包目录里运行不带 `--package` 的 `mcpp emit xpkg` 会得到一个条目,但它是按源码包写的:地址与摘要是占位符, +并声称覆盖三个系统。手工改正后 mcpp 消费者可以用它,这不是一条受支持的路。所以对库而言,这个机制现在是 +不完整的:消费侧的核对(接口摘要、兼容标签)已经实现并有测试,发布侧缺最后一步。 + +#### 3.3.2 条目由命令写出(面向 mcpp 消费者) + +1. `mcpp pack ` 与程序一样写出 `mcpp-package.json`:包的身份、每条腿的三元组与兼容标签、每个文件的角色 + (`library`、`interface`、`metadata`)与摘要。docs/10 已有「每次打包都写出这个文件」的陈述,库包此前是例外。 +2. `mcpp emit xpkg --package <库包归档> [--package …] --url <前缀>` 读它并写出条目:地址与 sha256 取自归档本身; + 只列出各条腿实际覆盖的系统与架构;`mcpp = "*/mcpp.toml"`(指针形式,与源码包相同,消费者的构建从包内的清单读 + 其余一切)。一个包的多条腿各是一个 `--package`,合成一个条目。 +3. 不带 `--package` 而在库包目录中运行的 `mcpp emit xpkg` 被拒绝,并指出应运行的命令(§10)。 + +这一步不引入新概念:条目的形状、指针形式、消费侧的核对都已存在。它使 docs/12 的第三种写法成为可以照做的步骤, +并补上该写法的 e2e:打包、写条目、经工程的 `[indices]` 消费、兼容标签不匹配时被拒绝。 + +#### 3.3.3 其他构建系统读到它 + +库包交给不使用 mcpp 的构建系统时,对方需要四件事:包含目录、库文件的位置与名字、静态归档不携带的依赖闭包与 +系统库及其顺序、这份二进制是为哪个 ABI 构建的。前两件可以从目录布局猜出;后两件只存在于 `mcpp.toml`,而那是 +只有 mcpp 读的格式。 + +采用 pkg-config 描述(`.pc`)的理由: + +- **它是索引中库载荷的既有约定,不是新选的格式。** 索引的库载荷带 `.pc`,配方把它声明进环境的 pkg-config 视图; + mcpp 自己的构建程序读的也是这个视图。mcpp 打出的库包带上它,就与索引中其他库载荷同形,消费者不必区分一个库 + 是谁构建的。 +- **它是声明式的,并被各构建系统直接读取**(CMake 的 `pkg_check_modules`、Meson 的 `dependency()`、xmake 的 + `pkgconfig::`、Makefile 的 `pkg-config --cflags --libs`)。另一类候选是某个构建系统自己的包描述,那是可执行的 + 脚本,只有该构建系统能读,且每多支持一个就多一份生成器。 +- **它能表达静态库的闭包**:`Requires` 指向依赖包的同名描述,`Libs.private` 给出系统库。 + +**位置与名字各一条规则。** 每条腿一份,位于 `lib//pkgconfig/`,与库文件按三元组分开的既有布局一致, +一条腿与多条腿没有两种写法。文件以包的身份命名(有命名空间时为 `..pc`),与归档的命名用同一个 +函数:环境的 pkg-config 视图是一个平面的名字空间,两个命名空间下同名的包不能相撞。 + +**内容全部取自库包清单已有的链接意图,不新增陈述:** `Cflags` 为 `include/`,`Libs` 为本腿的库目录与库名, +`Libs.private` 为系统库,`Requires.private` 为依赖包(以它们的身份为名),另有变量 `mcpp_abi` 给出兼容标签。 +`prefix` 相对该文件自身的位置给出(`${pcfiledir}`),满足载荷规则 P;以路径直接使用库包的消费者不需要任何改写。 + +它的边界写明而不掩盖: + +- **它描述头文件接口,不描述模块接口。** 模块接口单元必须由消费者的编译器编译,各构建系统对此没有共同的描述。 + 只有模块接口、没有 `include/` 的库包不写 `.pc`,`mcpp pack` 报告这一点(§10);它仍是完整的 mcpp 库包。 +- **它不核对 ABI。** `pkg-config` 没有这个概念。`mcpp_abi` 让消费者能读到并自行比较;核对只存在于 mcpp 消费者一侧, + 这一点写进 docs/12 与条目的说明。 +- **它描述这个包自己,不携带闭包。** 静态归档不含依赖的代码,库包按 docs/12 的既有规则声明依赖而不捆绑。mcpp 消费者 + 由依赖解析取得它们;其他构建系统的消费者须在环境中另有这些依赖的二进制与同名描述,否则 `pkg-config` 以包名报告 + 缺失。带依赖的静态库包在打包时报告这一点(§10)。把依赖静态链接进自身的共享库包没有这个问题,它是面向其他构建 + 系统交付时闭包最简单的形状。 + +**条目面向环境的一面,以及各自的职责。** mcpp 写出的是数据:`.pc`、包的描述、条目。把一个 `.pc` 放进环境的视图是 +索引与 xlings 的机制——索引的库载荷经索引自带的函数做两件事:把 `prefix` 改写为安装位置(视图中的文件不在载荷 +目录里,相对自身的前缀在那里不成立),再把文件声明为环境的资产。mcpp 不重写这个机制:条目只调用这两个函数,与 +索引自己的库配方写的是同样的两行。只有一条腿对应该系统与架构时才写;同一系统与架构有两条腿(两个 C 库、两种 +ABI)的包不写这一面,`emit xpkg` 报告这一点,补救是按 docs/12 的既有规则每种 ABI 发布一个包。头文件与库目录不另行 +导出到环境:`.pc` 已经给出它们的位置。 + +`deps` 按索引中库载荷的既有约定写成**运行时的下界**:C 库的下界由 `pack` 对库的二进制用程序包已有的读法测得 +(所引用的最高符号版本),C++ 运行时取构建时的版本;标签只有三元组的库(接口全部为 `extern "C"`)不带 C++ 运行时的 +依赖。 + +条目于是有两个读者:mcpp 读 `mcpp` 字段,xlings 读安装步骤。实现前在探针 PR 中测量三件事(§8 的 M7):mcpp 自己 +取包时这两步的效果(它们把 `.pc` 放进 mcpp 的构建程序经 `pkg_config_libdir()` 读的那个视图,与载荷的既有行为 +一致,须证实);这两个函数在 mcpp 为之写条目的索引中是否可用;不可用时条目以一行消息给出 `.pc` 所在的目录而 +不失败。 + +**编译器不写进 `deps`。** 实测(M2)表明载荷对编译器某个版本的依赖只会把那个版本装在旁边,不改变环境在用的 +编译器,也不产生提示;写进去是一条不起作用的陈述。编译器由消费者在自己的环境中声明,条目的说明与 `.pc` 的 +`mcpp_abi` 给出应声明的版本。 + +用具名的树构建的库包,其描述写明工具链是一棵具名的树以及驱动的身份;`mcpp emit xpkg` 拒绝它,原因码 +`package-built-outside-the-ecosystem`,因为它的环境不是索引能供给的。它以 `path` 或 `git` 交付。 + +xlings 一侧不需要改动:库包作为载荷已在规则之内。 + +### 3.4 被启动的外部程序(openkal-musl、规范的一句与三个实现) + +openkal 规范 7.13 已规定被启动的程序得到三个流与调用者授予的目录,别无其他句柄。接口有三层,调用者在其中两层 +已经能说出「不授予」:内核抽象层的 `grants` 为空,以及 mcpplibs.os 的可选项。C 库一层说不出:`posix_spawn` 与 +`execve` 无条件把调用者自己的预开目录作为授权传下去。移植来的程序用的正是这一层。 + +被启动的程序不是 openkal 程序时,这些授权对它没有用处:它不读取预开目录的变量;变量中带有预定接收者的进程 +标识,它再启动的程序也不会采用;openkal 程序在采用时把这些描述符标为执行时关闭,外部程序不会。留下的只是它 +不知情地持有并继续传递的描述符。这与 openkal-linux#30 是同一类事实;那一次的结论没有成为一条受测试保护的 +不变量,授权特性后来把描述符的继承按设计带了回来。 + +#### 3.4.1 C 库一层的陈述 + +**设计。** 采用 C 库世界已有的词:`posix_spawn_file_actions_addclosefrom_np(fa, lowfd)`。它在其他 C 库中的含义是 +「被启动的程序不持有 `lowfd` 及以上的任何描述符」,本端口保持这个含义:`lowfd <= 3` 时这次启动不传递授权(内核 +抽象层的 `grants` 为空),`lowfd` 小于 3 时 `lowfd` 至 2 的流另按对各自的 `addclose` 处理。`lowfd > 3` 被拒绝 +(`ENOSYS`,本端口对「此处不提供」的既有返回值),因为授权占用的位置从 3 开始,保留其中一段没有调用者能说出的 +含义。 + +对单个描述符的 `addclose`(3 号及以上)保持被接受:调用者自己的描述符本来就不会被继承,这个动作对它们是成立的。 + +默认值不变。一个持有受限授权的 openkal 程序启动另一个 openkal 程序时,后者不应得到比前者更多,这是授权默认传递 +的理由,本文不动它。 + +`execve` 不带属性。它用新映像替换本程序,授权是本程序自己的预开目录传给它的后继;本文不为它设计进程级的开关。 + +#### 3.4.2 环境按给出的原样到达 + +**现状(读码)。** 规范 7.17 只说偏好「未陈述则继承」,没有说经由什么。八个实现因此分成两种行为: + +| 行为 | 实现 | +|---|---| +| 未陈述时不写入,也不去掉调用者给出的同名变量;偏好经由给出的环境继承 | openkal-posix、openkal-freebsd、openkal-svr4、openkal-dos、openkal-uefi | +| 调用者给出的同名变量一律去掉;未陈述时写入本进程的偏好(非默认值时) | openkal-linux、openkal-macos、openkal-windows | + +第二种行为下,没有任何一种启动能让被启动的程序得到与给出的完全相同的环境。两种行为在「把自己的环境原样传下去」 +这一常见情形下结果相同,所以规范的测试集没有分辨出它们。 + +**设计。** 取第一种行为为规范的含义:没有陈述偏好的启动不写入变量,也不去掉调用者给出的同名变量。把自己的环境 +传下去的调用者,其偏好照常继承;构造了一份新环境的调用者,得到的就是那份环境。陈述了偏好的启动行为不变。规范 +7.17 的「未陈述则继承」补上「经由调用者给出的环境」;规范的测试集增加一例(以一份不含该变量的环境启动,被启动的 +程序读到默认偏好,且其环境与给出的相同),三个实现改为第一种行为。这是一次收敛:改动之后八个实现只有一种行为。 + +#### 3.4.3 不变量的测试 + +openkal-musl 的测试启动一个不属于本生态的程序,分别在默认启动与带上述陈述的启动下读取它的描述符表与环境。 +带陈述的启动必须只有 0、1、2,且环境与给出的逐字节相同。这条测试同时固定了 openkal-linux#30 的结论。 + +### 3.5 名字的拼写(openkal-windows) + +**现状(实测)。** 接口以「目录句柄加相对名」称呼被启动的程序与它的工作目录。系统的进程创建函数要一个名字,实现向 +系统询问句柄的最终路径并拼接。最终路径是物理路径:替换盘符下,被启动的程序读到的模块路径与工作目录都是物理的, +而同一程序被直接启动时读到的是别名。实现自己的文件系统部分已经写明,这种询问正是规范 7.1 排除的名字解析。 + +**两个目录到达实现时带着的信息不同(读码)。** 映像所在的目录由 mcpplibs.os 以「名字的最长预开前缀」交来,就是一个 +预开目录,余下的部分是相对名;预开目录的名字是实现在启动时按给定拼写记下的,实测系统的盘符表包含替换出的盘符, +所以它有自己的预开目录。工作目录则不同:它不恰好是预开目录时,由调用者相对某个预开目录打开后以句柄交来, +它被给出时的拼写没有越过接口。实现不为句柄保存名字(它自己的文件说明了这是规范 7.1 排除的表),所以这个拼写在 +实现一侧无从恢复。 + +**设计(D9 已决定)。** 启动时,一个目录按三步称呼,映像的目录与工作目录用同一个函数: + +1. 它是预开目录:用预开时记下的名字。 +2. 否则,它位于本进程当前目录之内(当前目录的预开项的最终路径是它的最终路径的前缀):用当前目录的名字加余下的 + 部分。这是本系统上一个程序相对自己的当前目录进入子目录时得到的名字;当前目录的拼写是使用者进入它时给出的。 +3. 否则:用系统报告的最终路径,即现在的行为。 + +前两步得到的名字在使用前与句柄核对:按该名字打开,比较卷序列号与文件标识;不同(目录在预开之后被改名或移走)则 +退到第 3 步。物理路径由此只用于定位与判同,不用于称呼。句柄表不增加任何状态,规范不改。 + +**这个设计的边界。** 既不是预开目录、也不在本进程当前目录之内的工作目录,仍以物理路径称呼。在那里可供选择的 +名字(物理盘符下的,或某个别名盘符下的)没有一个是调用者给出的,选哪一个都是猜测,猜错的方向同样会使按拼写授权 +的环境拒绝它。要在这种情形下也准确,启动须以「目录加相对名」称呼工作目录,与映像同形;那是规范的启动结构的 +变化,涉及每一个实现。按规范 7.1 自己的判据,这个形状取自以句柄进入目录的环境。本文不改它(决定 D9),并把这一 +观察登记在 openkal 规范的仓库。 + +**其他系统。** 在 POSIX 系统上,被启动的程序读到的自身路径与工作目录本来就是系统解析后的,直接启动时也是如此; +规则三的判据是「被启动的程序读到的与它被直接启动时相同」,在那里已经成立(M5 证实命令行只含给定的拼写)。 + +测试即 M1 的形状,两例:替换盘符下从工程目录内启动,被启动的程序读到的模块路径与工作目录以别名开头;从工程 +目录之外启动,模块路径以别名开头,工作目录为系统报告的路径。 + +### 3.6 索引的缺包(mcpp-index) + +一个图形库或应用要从索引取得整套显示栈,目前缺下列包。命名与形状沿用索引的既有规则:层级在 `namespace`,名字是 +单段;与生态载荷共用同一 soname 的库用形状 F(共享、规范 soname);其余从源码构建。 + +| 包 | 内容 | 形状与依赖 | +|---|---|---| +| `freedesktop.dbus` | libdbus-1 | E;依赖 `compat.expat` | +| `compat.xcb-render`、`compat.xcb-shm`、`compat.xcb-xfixes`、`compat.xcb-xkb` | XCB 的四个扩展库 | F,与 `compat.xcb` 同一来源与生成步骤 | +| `compat.xcb-util-renderutil`、`compat.xcb-util-image`、`compat.xcb-util-cursor` | XCB 工具库 | F;依赖上面的扩展库 | +| `freedesktop.libxkbcommon-x11` | xkbcommon 的 X11 部分(现有包的源码树中已有,未列入构建) | 同一上游仓库的第二个成员;依赖 `freedesktop.libxkbcommon` 与 `compat.xcb-xkb` | +| `gnome.atspi` | 无障碍总线客户端库 | 依赖 `gnome.glib`、`gnome.gio`、`freedesktop.dbus`(决定 D7) | +| `compat.plutovg`、`compat.lunasvg` | 矢量图形与 SVG | A 与 E;后者依赖前者 | + +每个包带 `tests/examples/` 下的一个成员与一条可失败的断言。驱动与会话服务不进索引,仍由形状 G 的包与运行阶段的 +能力要求陈述。 + +### 3.7 共享的条目、锁的粒度与等待(mcpp,#1040) + +**现状(读码;本机观察)。** + +- home 中的锁已经是系统的建议锁(POSIX 上 `flock`,Windows 上 `LockFileEx`),描述符带执行时关闭。进程结束时系统 + 释放它。旁边的 `.owner` 是持有者留下的记录,按设计从不删除。所以「记录里的进程已不存在」是每个条目的常态,不是 + 锁残留的证据:本机 44 个标准库模块条目的记录全部指向已不存在的进程,系统没有报告其中任何一把锁被持有。 +- 报告建议的第一条(改用建议锁,记录只作诊断)描述的正是现有的实现。报告观察到的等待因而意味着:系统认为这把锁 + 被持有,或者加锁因别的原因失败。两种情况现在都呈现为同一行 `Waiting … compiled by pid N`,其中的 N 取自记录。 +- 加锁的原语对任何失败返回同一个值(打不开文件、文件系统不支持锁、锁被持有),等待的循环只区分「文件不存在」与 + 「其余」,其余一律当作被持有而无限等待。 +- 标准库模块的条目在每次构建时取排他锁,命中时也取:检查「条目是否完整」在锁内进行。这发生在规划段。SPEC-011 §1 + 规定规划段不持锁,§3 规定读者不加锁;这个条目是例外。后果是一个不释放锁的持有者挡住的不只是要构建这个条目的 + 进程,而是 home 中使用同一工具链的每一次构建,包括条目早已完整的。 +- 条目的记录 `std-module.json` 在每次构建结束时原地重写(截断后写入),命中时也写。 +- 等待在 300 毫秒时报告一次,此后不再有任何输出。另有两处等待用自己的循环,完全不报告;一处的报告阈值是一小时。 +- 报告以 `ps -p ` 没有输出来判定持有者已死。分析所在的会话处于一个非初始的进程命名空间:宿主与其他沙箱里的 + 进程在其中不可见,而它们与该会话共用同一个 home。在这样的环境里,「看不到这个进程」不能推出「它不存在」。 +- 报告中那一次的直接原因没有确定:现场的文件已被删除。两个候选是「持有者在另一个进程命名空间里,被挂起或卡住」 + 与「加锁失败被读作被持有」。本设计使二者以后都能被分辨,并去掉常见情形下的暴露。 + +**设计。** 五条。 + +1. **完整的条目不加锁地读。** 条目的记录是它的完成标记:由构建它的进程在全部文件写完之后写出,写临时文件后改名 + 替换(home 已有这个函数),此后不再重写。记录列出已完成的部分(`std`、`std.compat`)。一次构建读到相符的记录且 + 文件齐全时直接使用,不取锁。不相符、缺文件或需要一个尚未完成的部分时才取锁,取得后再看一次,然后构建;重建一个 + 已有的条目时先移除记录。SPEC-011 增加一条:home 的条目遵循 §3 的读者规则,规划段只在要写一个条目时持有它的锁。 + 没有「部分」字段的旧记录按未完成处理一次:取锁、核对文件、补写记录,不重新编译。 +2. **一个等待的原语。** 所有等待经同一个函数(`FileLock::acquire`);三处自己的循环改为调用它。报告的形状、周期与 + 事件由此只有一份。 +3. **「被持有」与「不能加锁」分开。** 每个系统的原语返回原因:系统回答「已被锁定」是被持有;其余(没有权限、 + 只读、文件系统不支持锁、描述符耗尽)是不能加锁。后者立即返回错误,不等待,消息点名锁的路径、系统的原因与按原因 + 给出的补救。打开文件时的瞬时拒绝沿用读文件已有的两秒重试。 +4. **等待的报告。** 一行说四件事:等的是什么(哪个条目或哪个构建目录);锁文件的路径,按给出的拼写;最后一份记录 + (进程标识、命令、调用方标签、距今多久),措辞是「最后记录的持有者」;该进程标识在本进程看来是否可见。不可见时 + 加一行说明它的两种含义——持有者在本进程看不见的地方(另一个进程命名空间、容器,或经网络文件系统共用这个 home 的 + 另一台机器),或者是一个继承了这个文件的进程——以及在这个系统上列出持有者的那条命令(平台模块的数据)。报告在 + 300 毫秒、10 秒、30 秒、60 秒时重复,此后每 60 秒一次,每次带已等待的时间。`waiting` 事件增加 `path`、`resource`、 + `holderVisible` 三个字段并同样重复;已有字段不变。 +5. **不按记录回收,也不建议删除锁文件。** 进程标识在命名空间之间不通用,会被重用,在另一台机器上没有意义;按它 + 回收会让两个进程同时写一个条目,这正是这把锁所防止的(两个编译器同时写同一个模块文件;代码所记的测量是读方的总线错误)。 + 删除锁文件同样如此:新文件是另一个对象,原持有者仍然持有旧的。锁被持有时,补救是找到并结束持有者;没有进程 + 持有时,按定义不会等待。`mcpp explain` 的条目写明这一点。 + +#### 3.7.1 锁的粒度:单元、计划、配置 + +**现状(实测;读码)。** mcpp 的锁与各自保护的对象如下。 + +| 对象 | 锁 | 持有的时段 | 判断 | +|---|---|---|---| +| home:索引数据、安装状态、工具链版本目录 | 各自的一把(`Turn`) | 一次读改写 | 粒度合适 | +| home:标准库模块的条目 | 条目的锁 | 每次构建,命中时也取 | 过粗:读者不应取锁(上文第 1 条) | +| home:依赖的 BMI 缓存 | 目录的锁,只尝试不等待 | 一次写入 | 粒度合适:取不到就不写入缓存 | +| home:构建程序的输出目录 | 目录的锁 | 程序运行期间 | 粒度合适:第二个工程等待后重放其指令 | +| 工程:`target/.build_cache` | 文件的锁 | 一次读改写 | 粒度合适 | +| 工程:一个配置的构建目录 | 目录的锁 | 准备的收尾加 ninja | **过粗**(见下) | +| 工程:`mcpp.lock` | 无锁,乐观写入 | — | 粒度合适 | + +配置目录的锁过粗,实测如下:一个工作区,两个互不依赖的成员 `a`、`b`;`mcpp build -p a` 运行时启动 `mcpp build -p b`。 +两个命令规划进同一个配置目录,后者等待 4.5 秒(前者共 6.1 秒)之后才开始编译,而它们没有任何共同的单元。 + +这把锁属于配置而不属于成员,原因是 ninja:每个命令把自己那个选择的 `build.ninja` 写进共享的目录,而一个目录只有 +一份 ninja 的状态,两个 ninja 不能同时写它(mcpp#839)。在这把锁设计之后,引擎增加了两样东西,使单元可以自己保护 +自己,不再需要它: + +- 每一次编译都经编译执行器。它按「命令、编译器、源文件的内容」在 home 的单元缓存里查找,命中时放置目标文件与 BMI, + 不启动编译器(2026.11.21.1 起;`cl.exe` 的编译不缓存)。 +- 输出可重定向的工具链上,编译只写这次尝试私有的路径,结束后以改名发布;与已发布者相同的文件保留已发布者 + (SPEC-011 §5.1 第 8 条)。 + +另查出一处文档不一致:SPEC-011 §2 第 5 条写 `mcpp test` 持锁到测试结束;实现自 mcpp#915 起在全部构建完成后即释放, +docs/07 的陈述与实现一致。规范的这一条随本轮改正。 + +**设计。** 配置目录里有三种对象,各有自己的粒度。 + +| 对象 | 属于 | 怎样保护 | +|---|---|---| +| 单元:目标文件、BMI、扫描的结果 | 它的命令。同一个单元在每个选择里是同一条命令(docs/07 的既有保证) | 不持锁。发布协议保护写入(私有路径、改名发布、相同则保留);单元缓存按命令去重 | +| 计划:`build.ninja`、ninja 的状态、运行状态 | 选择 | 计划的锁,排他。位于 `<配置目录>/plans/<选择>/`,选择的键与 `.build_cache` 已用的相同 | +| 成员的产物:`bin/<成员>/` 下的程序与库 | 成员 | 链接与归档写临时名后改名。归档此前不在原子发布之列,本轮补上 | +| 配置目录整体:创建、接替前代目录、更新、`mcpp clean`、回收 | 配置 | 配置的锁。构建以**共享**方式持有,整体操作以**排他**方式持有 | + +结果:选择不同成员的两个命令持有不同的计划锁,同时构建;二者都到达的单元由先编译的一方发布,另一方的执行器 +放置它。选择相同的两个命令照旧排队,后到者取得锁后发现无事可做。 + +**条件是数据。** 上述粒度成立的前提是单元能保护自己:工具链的输出可重定向(工具链模型的 `OutputRelocation`), +并且这次构建使用 home 的单元缓存。两者任一不成立时(`cl.exe`,或 `--cache off`),构建以排他方式持有配置的锁, +即现在的行为;`mcpp why` 写明这次构建用的是哪一种及其原因。引擎不点名编译器。 + +**它是构建优化表的一个条目(SPEC-019)。** 条目 `plan-locks`,默认开;参数 `[build] plan_locks`(`selection` 为默认, +`configuration` 为现在的行为)与 `MCPP_PLAN_LOCKS`,`MCPP_BUILDOPT=off` 同样关掉它。两个计划同时进行时,一个构建在 +二者共有的单元上失败,它以该表既有的 `tip:` 结束,点名这个条目与检查它的那一次调用。这是 docs/26 对每一项优化的 +既有要求,不是为它新设的。 + +**写进文档的路径不变。** docs/50 与 docs/52 陈述的文件(配置的结果记录、`target/.last-result.json`、配置一级与根目录的 +编译数据库、解析记录)留在原处,照旧以原子替换写出;计划的目录只收纳没有写进文档的文件。读这些路径的程序(编辑器 +的插件、驱动 mcpp 的程序)不需要改。 + +有一处读法要写明。结果记录描述的是一个命令:两个命令同时构建一个配置时,配置的那一份是最后写它的那个命令的, +其中的 `pid` 与 `command` 说明是哪一个;所以一个命令结束时写下的 `ok`,可以盖住另一个仍在进行的命令的 `running`。 +每个命令自己的记录另有两处读得到,都不受别的命令影响:它的 `--message-format json` 的结尾,与它的计划目录里的 +`result.json`(同一种记录)。docs/50 的这一节补上这句话;记录的字段不变。这不是新的不确定:两个命令先后构建时, +配置的那一份本来就是后一个的。 + +**与早先发布的 mcpp 共用一个目录。** 锁文件与原语不变。新版本的共享持有与旧版本的排他持有互相排斥,所以旧版本 +在场时退回到串行,没有两种版本同时写一个状态的情形。 + +**代价写明。** 一个选择第一次构建时,它的 ninja 状态是空的,它的每条边都经过执行器一次;别的选择已经构建过的 +单元被放置而不是被编译。docs/07 的保证「`build --workspace` 之后 `build -p X` 不编译任何东西」仍然成立;它不再是 +「什么都不做」,而是每个单元一次查找(实测量级为每单元十几毫秒:288 个单元 4.1 秒)。此后该选择的再次构建与现在 +相同。两个同时进行的构建各用自己的 `--jobs`,与两个工程同时构建时一样。 + +**这个代价有上限,超过时用快路径。** 上限是:一个选择的首次构建,在别的选择已经构建过它的全部单元时,每个单元 +的开销不超过两毫秒(M10 测量)。超过时,执行器在发布一个单元时另记下它读过的文件的大小与修改时间;查找时先比对 +它们,全部相符即采用已发布的文件,不相符才按内容查找。这与 ninja 判断一条边是否过期用的是同一种依据,只是记在 +单元旁边而不是某一个计划的日志里,所以每个计划都读得到。测量低于上限时不加这一层。 + +实现前须读码与测量(§8 的 M10):逐一列出现在在配置锁之下写入的路径并归入上表的四行;在两种可重定向的工具链上 +让两个计划同时编译同一个单元;测量一个选择首次构建的放置开销;归档的原子发布;在网络文件系统上的共享持有。有一条路径归不进任何一行时, +它所属的配置保持排他,而不是为它开一个例外。 + +#### 3.7.2 等待的上限与提示(D10 已决定) + +默认仍然等待:SPEC-011 §2 第 3 条规定后到者等待而不是失败,而一次正当的等待有多长,mcpp 无从得知。上限作为显式的 +覆盖提供:全局选项 `--lock-wait <时长>`、环境变量 `MCPP_LOCK_WAIT`、`config.toml` 的 `[build] lock_wait`;`0` 表示 +不等待。超过上限时拒绝,原因码 `lock-wait-exceeded`。 + +2026-10-26 的设计 §4.2 曾决定「不新增等待或失败的参数,调用方取消即可」。本文推翻它,理由是 #1040:调用方无从分辨 +一次正当的等待与一次不会结束的等待,「取消」要求每个调用方各自实现一套超时;而 agent 与 CI 正是没有人盯着的调用方。 + +等待的那几行(第 4 条)的样子,以计划的锁为例: + +``` + Waiting for the plan of member 'a' (target/x86_64-linux-gnu/54a5c9ff/plans/a) + last recorded holder: pid 311530 (mcpp build -p a, started 2s ago), a process visible here + help: it ends when that command does; to stop waiting after a limit, --lock-wait + Waiting 30s for the plan of member 'a', held by pid 311530 (mcpp build -p a) +``` + +第一次报告带全部要素与 `help:` 一行;其后的重复只有一行。持有者不可见时,第二行改为 +`last recorded holder: pid N (…), not a process visible here`,并加上它的两种含义与列出持有者的命令。等待结束后 +`Finished` 行照旧写出等待了多久。 + +#### 3.7.3 不变量与测试 + +与 §3.4.3 同一做法,把一条写在规范里的不变量固定为测试:由 mcpp 启动的程序(编译器、构建程序、`mcpp run` 的程序)的 +描述符表中没有任何锁文件。SPEC-011 §2 第 5 条已作此规定,此前没有测试。规则五在规范中已有先例:SPEC-011 §5.1 +第 6 条规定「原单元从当前进程空间不可观察」时不得把名字消失解释为空单元;本节把同一条判据用于锁的记录。 + +e2e 八例:条目完整而它的锁被另一个进程持有,构建不等待;条目不完整而锁被持有,报告点名路径并重复,带上限时以 +原因码拒绝;锁文件不可打开,立即报错而不等待;持有者位于另一个进程命名空间(`requires: unshare`),报告写明不可见, +不回收,持有者结束后构建继续;上述不变量;同一工作区里选择两个不相交成员的命令同时进行,谁也不等待谁;两个选择 +共有一个依赖时,它的每个单元只被编译一次;条件不成立的配置(`--cache off`)退回排他并在 `mcpp why` 中说明。 + +### 3.8 新建工程的版本库(mcpp,#1038;D11 已决定) + +**现状。** `mcpp new` 的三条创建路径(内置模板、包模板、平台模板)写出工程的文件,其中内置模板与平台模板带一份 +`.gitignore`;都不建立版本库。这不是一个缺陷,是一项可以加入的便利;它值得按规范设计,是因为它使一个不属于构建的 +命令默认运行宿主的程序。 + +**同类工具的做法(实测除注明外)。** + +| 情形 | cargo 1.99 | 其他 | +|---|---|---| +| 独立的新工程 | 建立仓库 | `go mod init`、`npm init`:不建立 | +| 在一个已有的仓库之内新建 | 不建立 | 各语言的单仓多包(工作区)里,成员都不带自己的仓库 | +| 在一个尚未纳入版本控制的工作区之内新建成员 | **建立**:成员得到自己的仓库 | — | +| 在已有的仓库之内显式要求 `--vcs git` | 建立(嵌套的仓库) | — | + +第三行是那个工具的一个已知的不便:工作区的根以后成为仓库时,成员成了嵌套的仓库。行业的习惯因此是两条:子工程不带 +自己的版本库;显式的要求被照做。 + +**报告的七条建议逐条的处理。** + +| 建议 | 处理 | 理由 | +|---|---|---| +| 默认初始化,不引入任何开关 | 默认初始化;**有覆盖** | AGENTS.md §2:每个默认值都是数据,都有显式的覆盖 | +| 只初始化,不添加、不提交 | 采用 | 第一个提交的内容与作者属于使用者 | +| 不写死分支名 | 采用 | 分支名是使用者的 git 配置 | +| 已在某个工作树之内时不嵌套 | 采用,并推广为「子工程」的规则(见下) | 行业习惯;并避免上表第三行的情形 | +| 没有 git 或初始化失败时不失败 | 采用,区分两种情形 | 「做得更少决不沉默」;被显式陈述的请求不能满足时是错误 | +| 在事务提交之后进行;三条路径一致 | 采用:一个函数,三处调用 | 不改变「失败不留半成品目录」的既有保证 | +| 一行叙述写到标准错误 | 采用 | 人读输出的规范:叙述在标准错误,结果在标准输出 | + +**设计。** + +1. **键与覆盖。** 一个概念 `vcs`,两个值:`git`(引擎的默认值)与 `none`。命令行 `mcpp new --vcs <值>`;机器一层 + `config.toml` 的 `[new] vcs`。没有工程一层,因为工程此时还不存在。名字取自 Cargo 的同义选项。 +2. **子工程不带自己的版本库。** 子工程指新建的目录位于另一个工程或仓库之内:它的某个上级目录是一个版本库的工作树, + 或者持有一份 `mcpp.toml`(工作区的根,或任何一个工程)。值来自默认或 `config.toml` 时,子工程不初始化,也不报告: + 这是创建在别人的树里的工程应有的结果,版本库属于那棵树的根。`.gitignore` 照常写出,它在上级的仓库里同样生效。 +3. **显式的要求被照做。** 命令行写了 `--vcs git` 时,子工程也初始化,并用一行说明它位于哪个仓库或工程之内。命令行是 + 最高的一层;不嵌套是默认的行为,默认的行为有覆盖。 +4. **怎样运行。** `git` 按 git 依赖已有的方式取得(同一个查找),以 `init --quiet <目录>` 运行,目录用给出的拼写。 + 子进程的环境去掉指向别处仓库的变量(`GIT_DIR`、`GIT_WORK_TREE` 等):带着它们,`git init` 会把仓库建在别处, + 从钩子里运行 `mcpp new` 时正是如此。判断「是否在工作树之内」的那次询问同样去掉它们。不传分支名,不添加,不提交。 +5. **时机。** 在脚手架事务提交(改名到最终路径)之后;`.git` 不参与事务。三条创建路径在提交之后调用同一个函数。 +6. **做不到时。** 值来自默认或 `config.toml`:工程照常创建,退出 0,经 `diag::degraded` 报告,带影响(该目录不是 + 仓库,`.gitignore` 在 `git init` 之前不起作用)与补救(那一行命令)。值来自命令行的 `--vcs git`:工程保留,命令以 + 非零退出,消息写明工程已创建、失败的是初始化这一步及其原因。 +7. **叙述。** 成功时一行写到标准错误;标准输出不变。 + +**与「默认封闭」的关系。** 该规则管辖构建取用什么。`.git` 不是工程的内容,不被跟踪,不进入任何构建的输入;两台机器上 +`mcpp new` 的结果只在有无 `.git` 上不同。这是 mcpp 默认运行宿主程序的唯一一处,所以它有覆盖,做不到时有报告。 + +**可见的变化。** 脚本化调用 `mcpp new` 的输出目录里多出 `.git`;把这样的目录复制进另一个仓库会带上它。CHANGELOG 在 +Changed 下写明,并给出 `--vcs none` 与 `config.toml` 的写法。mcpp 自己的 e2e 在隔离的 home 的 `config.toml` 里写 +`vcs = "none"`,验证本功能的各例除外。 + +e2e(`requires: git`):独立的新工程得到一个没有提交的仓库,分支名取自配置;在工作树之内、在工作区之内、在另一个 +工程的目录之内都不初始化;同样三处带 `--vcs git` 时初始化并说明;`--vcs none` 与 `config.toml` 的覆盖;`PATH` 中没有 +git 时退出 0 并报告,`--vcs git` 时非零;环境中带 `GIT_DIR` 时仓库仍建在工程里。 + +### 3.9 命令行:人与 agent 同为直接使用者(mcpp、mcpplibs.cmdline) + +一个 agent 拿到 `mcpp` 这个命令时,手里只有这个二进制:没有仓库,未必有网络,读不到 docs/。它的做法与一个第一次 +使用的人相同——运行 `mcpp --help`,照着报错往下走。所以判据只有一条,对两种读者相同:**只凭这个二进制,能不能学会 +用它。** + +#### 3.9.1 现状(实测,2026.11.27.1) + +| 做什么 | 得到什么 | 缺什么 | +|---|---|---| +| `mcpp --help` | 一份手写的用法文本,与解析所用的命令树是两份;`why`、根上的 `explain`、`self completion` 等命令不在其中 | 帮助与命令树可以不一致,已经不一致 | +| `mcpp help build` | 根的用法文本 | 没有这个入口 | +| `mcpp buidl` | `error: unknown command 'buidl'`,随后是整份用法文本(七十行) | 没有相近的名字;一屏与原因无关的文字 | +| `mcpp build --jbos 3` | `error: unknown option: --jbos` | 没有相近的选项,没有指向 `mcpp build --help` | +| 在没有工程的目录里 `mcpp build` | `error: no mcpp.toml found in current directory or any parent` | 没有下一步 | +| `mcpp explain layer-cycle` | `unknown error code 'layer-cycle'`,`known codes: E0001..E0006` | docs/50 的原因码与 `MCPP_*` 的诊断代码都查不到;本文 §10 的 G4 此前假设它们查得到 | +| 找「怎样使用 mcpp」的说明 | 仓库里的 `.agents/skills/mcpp-usage`(189 行)与 docs/;二进制里没有 | 只有二进制的读者得不到 | + +mcpp 依赖的 mcpplibs.cmdline 是 0.0.6。它此后的三个版本提供了:子命令的分组与一致的次序、帮助之后的一段文字(0.0.7); +在动作之前应答的选项,以及 Agent Skills 的约定——`--agent-skill-doc` 在命令树的每一层应答,文档在构建时由构建程序的 +一个模块渲染进二进制,没有运行时的文件读取(0.1.0)。 + +#### 3.9.2 设计:六条 + +1. **一份命令树。** 根帮助由命令树生成,手写的用法文本删去。分组(工程、资源、mcpp 自身)用 cmdline 的分组陈述。 + 帮助、补全、缺子命令时的报错与 skill 的索引读同一份列表,所以不会再有一个命令存在而帮助里没有。`mcpp help <命令>` + 与 `mcpp <命令> --help` 同义。 +2. **用法随二进制携带。** 启用 `--agent-skill-doc`:`mcpp --agent-skill-doc` 给出根说明与各命令说明的索引, + `mcpp <命令> --agent-skill-doc` 给出该命令的说明,没有自己说明的子命令应答最近的上级的。文档位于 + `docs/mcpp-skills/`(`mcpp/SKILL.md` 与 `mcpp-<命令>/SKILL.md`),由仓库根的构建程序渲染为一个模块。每份不超过 + 一百行(一次应答对 agent 是一次读取,长度就是它的开销),用英文并只含 ASCII,与 mcpp 的消息一致,在任何终端的 + 代码页下都原样显示。根帮助的末尾有一行指向它,这是 agent 发现它的地方: + `Agents: mcpp --agent-skill-doc prints how to use mcpp; every command takes the flag.` +3. **说明的内容有固定的骨架。** 每份回答同样的五个问题:何时用这个命令;可以照抄的例子;它读什么、写什么、是否联网 + (取自命令已有的副作用数据,`--offline` 与 `--deny` 的写法);常见的拒绝与补救(原因码);它可能等待什么 + (`--lock-wait`)。根说明另有:五个命令构成的日常循环、消息怎样读(括号里的原因码与 `mcpp explain`)、机器输出 + (`--message-format json`、调用方标签)、退出码。 +4. **说明与二进制不可能不一致。** 两道检查,都是测试:说明里每一行以 `mcpp ` 开头的例子都经命令树解析,一个不存在 + 的命令或选项使测试失败;命令树里每个顶层命令都有自己的说明。检查的函数由 cmdline 提供(§3.9.3),不是每个使用 + 它的程序各写一份。 +5. **每一个出口给出下一步。** 用法错误不再打印整份帮助,而是一行原因加至多两行 `help:`:未知的命令给出名字相近的 + 命令与 `mcpp --help`;未知的选项给出该命令名字相近的选项与 `mcpp <命令> --help`;没有工程时给出 `mcpp new ` + 与「在工程的目录里运行」。这是 §10 的 G2 用于用法错误。退出码不变。 + `--message-format json` 下,同一条错误是一条带稳定代码的诊断,相近的名字是其中的一个数组,读它的程序不需要解析句子。 +6. **代码都查得到。** `mcpp explain` 接受三类代码:`E` 开头的错误码、`MCPP_*` 的诊断代码、docs/50 的原因码。三者登记 + 在一处,docs/50 的表由这一处生成;查不到时给出名字相近的代码。§10.3 的验收「每个新的原因码在 `mcpp explain` 中有 + 条目」由此才可能。 + +**不做的区分。** 没有「agent 模式」。mcpp 不探测调用者是谁,同一条命令对人与 agent 的含义相同;差别只在已有的、由 +调用者陈述的通道上(输出是否为终端、`--message-format json`、`MCPP_CLIENT`)。一个专为 agent 的行为分支会成为第二份 +要维护的语义,并且在探测出错时无从发现。 + +**与既有文档的关系。** 2026-10-26 的设计 §5.10 把面向具体 agent 的封装放在 mcpp-ide 仓库。二进制里的说明是与 agent +无关的那一层,具体的封装可以只是「运行 `mcpp --agent-skill-doc`」。仓库的 `.agents/skills/mcpp-usage` 的内容移入 +`docs/mcpp-skills/`,原处留一行指向它:同一个事实只在一处。docs/52(由程序驱动 mcpp)陈述这个入口。 + +#### 3.9.3 mcpplibs.cmdline 的改动 + +mcpp 升级到 cmdline 的新版本,启用它的 `agent-skills` 特性。这次升级跨过四个版本,其间有两处行为变化(快照中子命令的 +次序、应答选项先于动作);mcpp 的命令行 e2e 与补全的快照测试覆盖它们,不一致之处在这个 PR 里改正而不是绕过。下面三项属于命令行库而不属于 mcpp,在 cmdline 里做, +使用它的每个程序都得到: + +| 改动 | 性质 | 理由 | +|---|---|---| +| 用法错误带上相近的名字(取自帮助所用的同一份列表)与适用的那一级帮助 | 新功能 | 命令树在库里,相近的名字只有库能给;mcpp 自己做一份就有两份 | +| 把 skill 文档与命令树相互核对的函数:例子经解析,顶层命令有说明 | 新功能 | 「说明与二进制一致」对每个使用这个约定的程序都是同一道检查 | +| `install_default` 与 `install_runtime` 中重复的两段索引实现合为一个 | 优化 | 两份逐行相同的代码,改一处漏一处 | + +mcpp 的自举版本须能读懂 cmdline 新版本的清单(它用到构建依赖的再导出);`.xlings.json` 所钉的版本是否满足在探针中 +核实(§8 的 M11),不满足时按发布规则改钉一个已发布的版本。 + +e2e:`mcpp --agent-skill-doc` 与一个子命令的应答在没有网络、当前目录为空的环境里可用;根帮助列出命令树的每个非隐藏 +命令并含指向 skill 的那一行;三种用法错误各自的 `help:` 行;`mcpp explain` 对三类代码各一例。 + +### 3.10 索引条目的每个版本都可安装(mcpp-index) + +**现状(读 CI 日志与索引的提交)。** 2026-12-03 收录 `mcpplibs.cmdline` 0.1.0 时,条目由内联的构建描述改为指向包内 +清单,并为唯一不带清单的 0.0.1 加了一个安装钩子,在安装目录下的源码树里写出一份清单。钩子在 `安装目录/cmdline-0.0.1/` +下找 `src/cmdline.cppm`;钩子运行时解包出的树还在钩子的工作目录里,尚未被放进安装目录——安装钩子的契约正是「把解包 +出的树放到 mcpp 会去找的地方」(docs/32)。于是 0.0.1 的安装以 `no src/cmdline.cppm under …` 失败,其余版本因钩子提前 +返回而不受影响。 + +该条目的测试成员只依赖最新的版本,所以索引自己的 CI 通过。mcpp 的 e2e 有若干例依赖 0.0.1(多版本合并、版本名字 +的修饰等),因此自该提交起 mcpp 的每个 PR 的 CI 都失败,与 PR 的内容无关。 + +**设计。** + +1. **修复钩子。** 0.0.1 的分支在解包出的树所在之处(钩子的工作目录)写出清单,然后与索引中其他带钩子的条目一样把树 + 放进安装目录;其余版本不变。条目开头的注释称 0.0.1「已被移除」,与条目仍列出它不符,一并改正。 +2. **一项检查,使这一类回归不能再合入。** 索引的 CI 对一个被改动的条目所列的**每个**版本各安装一次(下载、钩子、 + mcpp 读到清单),不只是测试成员所依赖的那一个。一个条目的钩子按版本分支时,每条分支由此都被执行。 + +这是一次修复,与改动 15 的补包无关,并且挡住包括探针在内的每个 mcpp PR,所以它单独、最先进行(决定 D13)。 + +### 3.11 取得依赖:读者、显示与安装的锁(mcpp、xlings、mcpp-index) + +三个现象出自取得依赖的同一段路径:已经装好的依赖每次构建都打印 `Downloading`;首次拉取时每个依赖留下三行,其中 +一行是停在 `connecting… 0s` 的进度条;一次构建在 `Waiting for another mcpp of this home, installing …` 上等待另一个 +工程的安装。 + +#### 3.11.1 现状(实测;读码) + +| 现象 | 原因 | 来源 | +|---|---|---| +| 已安装的依赖每次构建都打印 `Downloading <包> v<版本>` | mcpp 以文本扫描读索引条目,只在一个版本的值是内联的表时读它的 `revision`;条目把各版本的表放在一个局部变量里再按名字引用时,读到的是 0,而安装器(它执行条目)记录的是 1。`-v` 下可见 `installed revision 1, descriptor revision 0; reinstalling`。于是每次构建都回到安装器 | 实测(两个工程,共四个包);读码 | +| 同上,代价不只是一行字 | 每个这样的依赖每次构建启动一次安装器(本机约 0.35 秒),并取得 home 的安装锁;另一个正在安装的进程因此被它挡住,它也被别人挡住 | 实测 | +| 索引中这种写法的条目 | 392 个条目中粗筛 28 个 | 读索引 | +| `Downloading` 这一行是在询问安装器之前打印的 | 它是一句预告而不是一个事实;安装器随后什么都不下载时,这一行就是假的 | 读码 | +| 首次拉取时,进度条的第一帧(`[=== ] connecting… 0s`)留在屏幕上不被擦除 | 实时区域由界面模块统一重绘,它记着自己画了几行。安装器一层的 `Source <包> <主机> (attempt N)` 一行不经界面模块,直接写标准错误;每次下载开始时它恰好出现一次,光标因此多下移一行,下一帧少上移一行,区域最上面的那一行(进度条)成为孤行 | 实测:在伪终端中抓取原始字节并在一个虚拟终端上重放;读码 | +| 不经界面模块而直接写标准错误的调用 | 约二百三十处,分布在二十余个文件 | 读码 | +| 同一个依赖在三行里有三种写法 | 预告用使用者在清单里写的身份(`compat.pugixml v1.16`);进度条与完成行用发给安装器的地址(`compat:pugixml@1.16`);窄终端上进度条里的名字被截成 `compat:p…`,因为宽度先给了进度条 | 实测(64 列) | +| 四个各几百 KB 的依赖首次拉取用了约 27 秒 | 依赖逐个取得,每个一次安装器的启动与一次连接(每次约 6 秒停在 `connecting…`) | 实测 | +| 一次构建等待另一个工程的安装 | 两层各有一把以 home 为范围的锁:mcpp 的安装轮次,xlings 的状态锁。二者都在整个安装期间持有——下载、解包与钩子都在锁内(实测单个包的下载可达一分钟) | 实测;读两处源码 | +| 非终端下的输出 | 每个下载在完成时一行,没有重绘 | 实测;这一面是正确的 | + +最后一项之前的那一项回答「这是锁的粒度问题还是正常」:二者都是。一个 home 一次只做一个安装是两层现在的设计, +等待是按设计发生的;而它的粒度过粗——它保护的是状态的读改写,持有的却是包括网络下载在内的整个安装。第一行的缺陷 +又把它放大了:本来什么都不需要装的构建也去取这把锁。 + +#### 3.11.2 设计 + +**一、条目只有一种读法(mcpp、mcpp-index)。** + +1. mcpp 的读者读懂「一个版本的值是对一个局部表的成员的引用」这一种写法,它是索引里已经在用的写法。 +2. 读者遇到它读不懂的写法时,结果是「未知」而不是 0。未知的修订不参与「是否需要重装」的判断(与没有安装记录的 + 载荷同样按内容判断),也不沉默:`mcpp xpkg parse` 把它报告为条目超出了读者的语法。 + 另有一道运行时的自检,使这个缺陷对任何索引、任何将来的写法都不能再形成循环:一次安装刚刚完成时,mcpp 把自己 + 读到的修订与安装器刚记下的相比;二者不同只能是读者读错了(安装器正是按这份条目装的)。此时该条目的修订按未知 + 处理,并经 `diag::degraded` 报告一次,点名条目与两个数值。索引的检查(第 3 条)只管得到 mcpp-index;这道自检 + 管得到每一个索引。 +3. 条目须处在每个仍受支持的 mcpp 版本(docs/51)的读者读得懂的范围之内;已发布的版本读不懂引用的写法,也无从 + 补救。各平台共有的版本只写一次(D15):一个平台的表陈述它们,其余平台以 xpackage V1 的平台引用 + (`macosx = { ref = "linux" }`,libxpkg 0.0.64 起由安装器读取)指向它,引用旁只陈述本平台独有的 `deps`。 + mcpp 的读者按安装器的解析读平台引用(SPEC-001 §10.5);已发布的版本经「各块共有的源码归档服务每个目标」 + 这一条(2026.11.9.1)读出同一组版本,修订取自就地写出的那一张表——前提是只有一个块陈述版本,所以一个平台与第三个 + 平台陈述不同版本时,各自保留自己的表。索引的检查固定三件事:一个版本的值是就地写出的表;各平台陈述同样的版本时 + 写一次并引用;引用指向存在的表且不成环。改写对每个条目核对:按安装器的解析求值后与原值相等,2026.11.22.1、 + 2026.11.27.1 与本版的读者读出相同。索引的自动更新工具读平台引用,把新版本写进被引用的那一张表一次,就地写出, + 不再生成局部表;索引站点的渲染器同样解析平台引用。 + +**二、叙述流只有一个写者(mcpp)。** + +4. 写到标准错误的每一行都经界面模块:它在有实时区域时先擦除区域、写出这一行、再重绘。安装器一层的状态行改为 + 调用它。仓库的检查脚本拒绝界面模块与日志模块之外对标准错误的直接写入;现有的调用登记在一份只减不增的清单里, + 本轮清掉取得依赖、规划与构建三段路径上的全部。 +5. 一个测试固定这一条:在伪终端里运行一次取得依赖,把字节流在虚拟终端上重放,断言结束时屏幕上每个依赖恰好一行, + 没有残留的进度条。重放是测试的一个辅助函数,按 AGENTS.md 的做法写在 mcpp 自己的测试里;它需要伪终端(`requires: pty`),在没有的 + 系统上跳过,那里由第 4 条的静态检查承担。 + +**三、每个依赖一行,一种写法,只说发生了的事(mcpp)。** + +6. 不再打印预告。安装器报告一次下载开始时出现进度条,完成时它被完成行取代;已经装好的依赖什么都不打印(`-v` 下 + 一行说明它被采用)。因修订改变而重装时,动词是 `Updating`,并写出修订从几到几。 +7. 三处都用使用者在清单里写的身份加版本(`compat.pugixml v1.16`);发给安装器的地址只出现在 `-v` 与错误消息里。 +8. 宽度不够时先缩短进度条到下限,再截断名字。现有代码的注释这样写,行为却相反。 + +**四、按波次取得(mcpp;优化)。** + +9. 解析到某一步时已知的全部依赖在一次安装器调用里请求,而不是每个依赖一次。安装器的调用本来就接受多个目标。 + 指针形式的条目要取得载荷之后才知道它自己的依赖,所以是若干波,每一波一次调用;同时进行的下载各占实时区域的 + 一行。失败按目标归属,重试的规则不变。开销在探针中测量(M12)。它同样是构建优化表的一个条目(`batch-fetch`,默认开, + `MCPP_BATCH_FETCH=each` 为逐个取得),取得依赖失败时的 `tip:` 点名它。 + +**五、安装的锁与它保护的对象一致(D14 已决定:分两步,本方案不改 xlings 的代码)。** + +目标的形状不变,实现分属两个仓库、两个时间: + +10. **目标(xlings,登记为 issue)。** 状态锁拆成两种:一个包的载荷(下载、解包、安装钩子把树放进它自己的目录) + 在**这个包的锁**之下;版本数据库与工作区的读改写(包括配置钩子的登记)在**状态锁**之下,只在这一小段持有。 + 两个进程安装不同的包时同时下载;安装同一个包时后到者等那个包的锁,然后发现它已在。钩子里再调用 xlings 的包 + (已有的重入约定)照常工作。issue 写明问题、测量、这个形状与验收,不规定实现。 +11. **本轮(mcpp)。** 不依赖 xlings 的改动而成立的部分全部在本轮做:上面的一至四(已装好的依赖不再回到安装器, + 因而不再取任何安装的锁);等待安装时的报告按 §3.7.2 的形状;`--lock-wait` 在调用安装器时经它已有的上限 + (`XLINGS_LOCK_TIMEOUT`,默认十分钟)传给它,使一个上限管辖一次命令里的每一处等待。mcpp 自己的安装轮次 + **保留**:它当初存在是因为两个进程同时请求同一个包时,后到者在前者尚未放好时就被告知成功;在安装器消除这个 + 情形之前,去掉它会把那个缺陷带回来。 +12. **收尾(mcpp,xlings 发布之后的一个 PR)。** 改钉带有第 10 条的 xlings;去掉 mcpp 的安装轮次,同一件事不再 + 两层各一把锁;把安装器的等待事件按 §3.7.2 的形状转述;补上两条 e2e(两个进程同时安装不同的包互不等待, + 同时安装同一个包只下载一次)。 +13. **备注 issue(mcpp)。** 记下第 12 条的四件事、它所等待的 xlings 的 issue 与本节。它是收尾的检查清单, + 也使「mcpp 的轮次为什么还在」对读代码的人有据可查。 + +本轮之后、收尾之前的状态写明:装好依赖的构建不取锁、不等待;两个进程都确实要安装时(首次构建、并行的 CI、 +并行的 agent)仍然串行,等待有报告、有上限。 + +xlings 的锁的记录已经写明「是提示而不是事实」,与规则五一致。 + +**验收。** 上述测试;e2e:一个依赖全部装好的工程连续构建两次,第二次不启动安装器、不打印任何下载行;一个条目的 +修订改变后恰好重装一次并打印 `Updating`;等待另一个进程的安装时报告的形状,以及 `--lock-wait` 到期时以原因码 +拒绝。并发安装的两条 e2e 属于收尾(第 12 条)。 + +## 4. 各仓库改动的性质、最佳方案与理由 + +性质分四类:**缺陷修复**(实现与已写明的行为不符,或默认配置失败)、**优化**(结果不变,时机或信息更好)、 +**新功能**(增量,旧写法不受影响)、**语义变化**(此前被接受的输入得到不同结果)。 + +| 仓库 | 改动 | 性质 | 最佳方案 | 理由 | +|---|---|---|---|---| +| mcpp | 1 表到达构建程序(#1034) | 缺陷修复 | 表写进为构建程序生成的工作空间清单,子构建从清单读 | 文档已陈述该行为;读表只有清单一个实现;生成的目录可以独立重现。实测两类编译用了两个编译器 | +| mcpp | 2a 归档器取自宿主时点名 | 缺陷修复 | 解析为绝对路径、进指纹、报告、`--strict` 拒绝 | 文档称归档器从不是裸名字;与宿主汇编器的既有处理一致;不打断此前靠它构建的工程 | +| mcpp | 2b 归档器不接受响应文件 | 新功能 | 探测后由 mcpp 展开并分批调用 | 响应文件是 mcpp 引入的要求;对任何归档器成立;不引入规模上限 | +| mcpp | 2c 链接器与运行库按树决定 | 缺陷修复 | 陈述优先,其次探测,否则驱动默认;两类链接同一规则 | 实测没有 lld 的树不陈述就无法链接,陈述了的树其构建程序仍无法链接 | +| mcpp | 2d 模块语法的探测 | 优化 | 接到已有的「没有模块的编译器」路径 | 结果同样是该单元不能构建,但在规划时由 mcpp 指出文件,而不是编译器的语法错误 | +| mcpp | 3a 每个问题带着构建的词(#1039) | 缺陷修复 | 一个提问的函数,接收驱动与词;标准库模块的源文件在预编译的词已知之处询问 | 「默认封闭」被违反:托管工具链用了宿主的文件。同一缺陷在运行库归档的问题上修过一次,只改了那一处;一个函数使下一个问题不会再漏 | +| mcpp | 3b 答案须在声明的根之内 | 缺陷修复(防线) | 根之外的答案不被采用,转向下一个探测;都不可采用时在规划时说明 | 按根判定而不按标准库的名字判定,对任何实现与任何问题成立;把编译器的报错换成规划时的说明 | +| mcpp | 4 链接跟随编译(#1031) | 缺陷修复 | 按规划已知的接口供给关系取共享镜像 | 比「再导出」完整(内联与模板、头文件);不依赖只有部分链接器才有的开关;与静态链接的结果一致 | +| mcpp | 5 ABI 成员一处渲染(#1029) | 缺陷修复 | 一个记录、一次解析、一个渲染函数、四个去处 | 实测默认配置对带 `setjmp` 的 C 依赖失败且消费者无法补救;两处手写的补入正是遗漏的来源 | +| mcpp | 6 测试与可执行目标同路径(#1028) | 语义变化(已合入);补全为优化 | 规划时拒绝;补原因码的登记、消息、命令一级的测试与按文件系统的判同 | 与同类输出冲突的既有处理一致;被拒绝的状态此前没有定义的结果;实测影响面小 | +| mcpp | 7a 库包的索引条目由命令写出 | 缺陷修复(补全);其中在库包目录里不带 `--package` 的 `emit xpkg` 由写出错误条目改为拒绝 | `pack` 写出 `mcpp-package.json`,`emit xpkg --package` 读它 | docs/12 已把索引条目列为消费库包的写法,docs/10 已陈述每次打包都写描述;实测两者对库都不成立 | +| mcpp | 7b 库包的 `.pc` 与条目面向环境的一面 | 新功能 | `.pc` 取自已有的链接意图;条目调用索引已有的函数,不重写它;运行时写下界,编译器不写进依赖 | `.pc` 是索引中库载荷的既有约定与环境已有的视图;放进视图是索引与 xlings 的机制;下界是索引的约定;实测对编译器的依赖不起作用 | +| mcpp | 8a 完整的条目不加锁地读(#1040) | 缺陷修复 | 记录作完成标记,原子写出一次;只有要写条目的构建取锁 | SPEC-011 规定规划段不持锁、读者不加锁,这个条目是例外;例外使一个不释放的持有者挡住使用同一工具链的每一次构建 | +| mcpp | 8b 「被持有」与「不能加锁」分开 | 缺陷修复 | 原语返回原因;不能加锁立即报错 | 现在任何失败都被读作被持有并无限等待,报告的还是一份无关的旧记录 | +| mcpp | 8c 等待的报告与一个等待的原语 | 优化 | 路径、记录、可见性,周期性重复;三处自己的循环并入 | 等待此前只说一次,两处完全不说;记录被当作事实陈述,而它只是最后一个持有者留下的 | +| mcpp | 8d 等待的上限 | 新功能(D10 已决定) | 显式的覆盖,默认不设上限 | 规范规定后到者等待;正当的等待没有 mcpp 可知的上界;上限是调用者的陈述。推翻 2026-10-26 设计 §4.2 的决定,理由见 §3.7.2 | +| mcpp | 8e 锁的粒度:计划属于选择,配置的锁分共享与排他 | 优化(构建优化表的条目 `plan-locks`),改变 SPEC-011 §2(决定 D12) | 单元由发布协议与单元缓存保护;条件不成立的配置保持排他 | 实测不相交的成员互相等待;锁属于配置只因 ninja 的状态,而那是计划的一部分;所依靠的机制已存在 | +| mcpp | 9 `mcpp new` 初始化版本库(#1038) | 新功能,带一处可见的行为变化(D11 已决定) | 默认 `git`,`--vcs` 与 `config.toml` 覆盖;子工程不带版本库,显式的要求被照做;不提交;做不到时报告 | 与同类工具的默认及其对子工程的习惯一致(实测);覆盖是 AGENTS.md §2 的要求;`.git` 不是工程的内容,不进入构建 | +| mcpp | 10a 根帮助由命令树生成;每个出口给出下一步 | 缺陷修复与优化 | 删去手写的用法文本;用法错误一行原因加 `help:` | 实测帮助与命令树已经不一致;整份帮助作为报错对人与 agent 都是噪声 | +| mcpp | 10b 用法随二进制携带(`--agent-skill-doc`) | 新功能 | 启用 cmdline 的约定;文档在 `docs/mcpp-skills/`,构建时渲染;两道一致性检查 | 只有二进制的读者此前得不到用法;复用库已有的机制,不自建 | +| mcpp | 10c `mcpp explain` 覆盖三类代码 | 缺陷修复 | 一处登记,docs/50 的表由它生成 | 实测原因码查不到,而每条拒绝都带着它 | +| mcpp | 11a 条目的修订读对;读不懂是「未知」 | 缺陷修复 | 读者读懂对局部表成员的引用;未知不参与重装的判断并由 `xpkg parse` 报告 | 实测每次构建都回到安装器并取得 home 的安装锁;两个读者对同一个条目给出两个答案 | +| mcpp | 11b 叙述流只有一个写者 | 缺陷修复 | 每一行经界面模块;仓库的检查拒绝直接写标准错误,现有的登记在只减不增的清单里 | 实测一行绕过界面模块的输出使每次下载留下一条孤行;同类调用约二百三十处 | +| mcpp | 11c 每个依赖一行、一种写法、不预告 | 优化 | 进度条在下载开始时出现;名字用清单里的身份;宽度先让名字 | 预告在什么都不下载时是假的;一个依赖三种写法 | +| mcpp | 11d 按波次取得依赖 | 优化(构建优化表的条目 `batch-fetch`) | 一步已知的全部依赖一次调用 | 实测四个小包约 27 秒,时间在逐个启动与连接上 | +| mcpp | 收尾(xlings 发布之后的一个 PR) | 优化 | 改钉 xlings;去掉 mcpp 的安装轮次;转述安装器的等待;两条并发安装的 e2e。由一个备注 issue 记录 | 同一件事不需要两层各一把锁;在安装器消除同包并发的缺陷之前,轮次不能去掉 | +| mcpp | 同一个包在两处陈述给出两个版本时的说明;一棵树里有两个族的驱动时的说明 | 优化 | 各一条说明,每个工程一次 | 行为不变;读者此前只能从文件系统或 `Using` 行重建这个事实 | +| openkal-windows | 12 启动时的名字(mcpp#1032) | 缺陷修复 | 三步称呼,前两步与句柄核对为同一对象 | 与直接启动的结果一致;不增加状态、不改规范;边界(当前目录之外的工作目录)写明 | +| openkal-musl | 13 C 库一层的陈述(openkal-musl#93) | 新功能 | `posix_spawn_file_actions_addclosefrom_np` | 别的 C 库已有的词与含义;内核抽象层已有对应的启动;默认值不变 | +| openkal 规范 | 14 偏好的继承途径 | 规范的澄清 | 7.17 补一句;测试集增加一例 | 八个实现已分成两种行为,测试集没有分辨出来 | +| openkal-linux、openkal-macos、openkal-windows | 14 环境按原样到达 | 语义变化(一种情形) | 改为其余五个实现已有的行为 | 收敛到一种行为;不增加接口;变化只在「自己带偏好、又给出不含该变量的新环境」的调用者 | +| mcpplibs.os、openkal-llvm-runtime | 版本级联 | 无功能变化 | 按家族的确切版本钉 | 家族的发布规则 | +| mcpp-index | 15 显示栈的缺包 | 新功能 | 按既有形状与命名各自成包 | 可分离性判据全部满足;使库以源码交付给 mcpp 消费者这条路完整 | +| mcpp-index | 16 `mcpplibs.cmdline` 条目的钩子;每个所列版本安装一次的检查 | 缺陷修复(回归)与优化 | 钩子在解包出的树所在之处写清单再放置;CI 对被改动条目的每个版本安装一次 | 钩子违反 docs/32 的契约;测试成员只依赖最新版本,所以回归通过了索引自己的 CI | +| mcpp-index | 17 各平台共有的版本写一次并以平台引用指向它;版本的值就地写出;由检查固定 | 缺陷修复(对已发布的 mcpp)与优化 | 数据的等价改写(316 个条目,删去约一万八千行重复);自动更新工具与站点渲染器读平台引用 | 已发布的版本无从补救,索引的数据是唯一能到达它们的地方;平台引用是安装器已有的写法,已发布的读者读出相同 | +| mcpplibs.cmdline | 18 相近的名字;说明与命令树的核对;合并重复的实现 | 新功能与优化 | 在库里做,发布一个新版本 | 命令树在库里;每个使用这个约定的程序需要同一道检查 | +| xlings | 19 安装的锁的粒度 | 本方案不改代码:登记一个 issue(D14) | issue 写明问题、测量、目标的形状与验收;由 xlings 实现 | 状态锁保护的是读改写,持有的却是整个安装;实测一个包的下载可达一分钟,其间 home 里别的安装都在等。它动的是安装器最核心的路径,由拥有它的仓库按自己的节奏做 | +| xlings | 名字的拼写 | 不改动 | — | 实测别名本身不导致失败;另两项观察未重现,没有可设计的失败点 | + +**各 issue 的去向。** + +| issue | 性质 | 落在 | +|---|---|---| +| mcpp#1028 | 缺陷 | 已由 #1036 合入;补全为改动 6 | +| mcpp#1029 | 缺陷,范围大于报告(默认配置失败) | 改动 5 | +| mcpp#1031 | 缺陷 | 改动 4 | +| mcpp#1032 | 缺陷,位于 openkal-windows | 改动 12 | +| mcpp#1034 | 缺陷 | 改动 1,并引出改动 2 | +| mcpp#1038 | 功能请求 | 改动 9;「不引入开关」一条不采用 | +| mcpp#1039 | 缺陷 | 改动 3;第二条建议以按根的判据代替 | +| mcpp#1040 | 缺陷,原因与报告的归因不同 | 改动 8;「按进程标识回收」与「清除锁的命令」不采用;评审中扩展到锁的粒度 | +| openkal-musl#93 | 功能缺口 | 改动 13、14 | + +## 5. 各层的规范与本方案的一致性 + +| 规范 | 本方案对应之处 | +|---|---| +| mcpp:机制在引擎、事实在数据 | §3.1.2 的四项事实成为工具链记录的字段;引擎不出现厂商名 | +| mcpp:每个默认值都是数据并有显式覆盖 | 探测结果可由 `tools` 的陈述覆盖;`mcpp new` 的版本库有 `--vcs` 与 `config.toml`;等待的上限是覆盖而不是默认值 | +| mcpp:默认封闭 | 驱动的答案须落在构建声明的根之内(改动 3);`.git` 不是构建的输入(§3.8) | +| mcpp:做得更少决不沉默 | 取自宿主的归档器被报告;输出冲突被拒绝;没有 git 时被报告;等待被说出并重复 | +| mcpp:一个概念一个拼写 | 不增加清单的键与命令行的开关;不为问题一增加入口;库包的描述复用已有的链接意图,`.pc` 的命名复用归档的命名;交付物的环境复用 `[xlings]` | +| mcpp:被移除的读法先弃用 | 本轮没有移除任何读法;改动 6 拒绝的是输出冲突,不是读法(§3.2.3) | +| mcpp SPEC-019 与 docs/26:每一项优化是表中的一个条目,默认开的有参数与一次调用的关法,失败时有 `tip:` | 改动 8 的 `plan-locks` 与改动 11 的 `batch-fetch` | +| mcpp:一个机制只有一份实现 | 向驱动提问、等待一把锁、输出路径的判同、ABI 成员的渲染各合为一处;相近的名字与说明的核对放在命令行库里 | +| xlings:只有改变状态的命令取锁,读不取锁;记录是提示 | 改动 19 沿用,并把持有缩到状态的读改写 | +| mcpp:一个概念一个拼写(用于输出) | 一个依赖在每一行里是清单中的那个名字(改动 11) | +| mcpp SPEC-011:规划段不持锁,读者不加锁,后到者等待 | 改动 8 使标准库模块的条目遵循前两条;第三条不变,上限只是覆盖 | +| xlings:外部的一切来自索引;运行时属于环境 | 库包的依赖是索引中的运行时包;编译器由环境的声明决定 | +| xlings:载荷规则 P | `.pc` 的前缀相对自身 | +| xlings 与索引:放进环境视图是它们的机制 | 条目调用索引已有的函数,mcpp 不重写 | +| openkal 7.1:不维护名字解析器 | 启动路径上以最终路径称呼目录,改为以预开的名字或当前目录的名字称呼;不为句柄保存名字 | +| openkal 7.13:别无其他句柄 | C 库一层得到说出它的词 | +| mcpp-index:默认从源码构建;可分离性是唯一判据 | §3.6 的每个包都有自己的上游发布 | + +## 6. 各仓库的 PR 与次序 + +每个仓库一个 PR,一次提交;它是该仓库的检查点。唯一的例外是 mcpp-index:改动 16 是一次回归的修复,单独、最先进行 +(决定 D13)。 + +| 次序 | 仓库 | PR 的内容 | 前置 | 验收 | +|---|---|---|---|---| +| 0 | mcpp-index | 改动 16:`mcpplibs.cmdline` 条目的钩子;每个所列版本安装一次的检查。改动 17:共有的版本以平台引用写一次及其检查;自动更新工具与站点渲染器各一个 PR 先合入 | — | 0.0.1 可安装;mcpp 的 CI 恢复;已发布的 mcpp 对这些包不再每次构建都回到安装器;改写前后每个条目求值相同、各版本的读者读出相同 | +| 1 | mcpp(探针 PR,已有) | M7 至 M11 的测量 | 第 0 行 | 数据并入 §8 | +| 2 | openkal | 规范 7.17 的一句;测试集的一例 | — | 新的一例对五个已符合的实现通过 | +| 2 | mcpplibs.cmdline | 改动 18,发布一个新版本 | — | 库自己的测试;夹具程序的三种应答 | +| 2 | mcpp-index | 改动 15 | 第 0 行 | 新成员的测试,三个平台按门控 | +| 3 | openkal-linux、openkal-macos | 改动 14 | openkal | 测试集的新例通过 | +| 3 | openkal-windows | 改动 12 与改动 14 | openkal | 测试集的新例通过;§3.5 的两例 | +| 3 | mcpp-index | cmdline 新版本的条目(条目自带的自动更新) | cmdline | 上述检查 | +| 4 | openkal-musl | 改动 13,§3.4.3 的测试;依赖范围接纳上面的版本 | openkal 各实现 | 外部子进程只有 0、1、2,环境与给出的相同 | +| 5 | openkal-llvm-runtime、mcpplibs.os | 按家族的确切版本钉级联;无功能改动 | 上一行 | 各自的 CI | +| 6 | mcpp | 改动 1 至 11 与两条说明;mcpplibs.os 与 mcpplibs.cmdline 的新版本;SPEC-004、006、011、014、017、019 的条款;docs/01、04、07、08、09、10、12、20、25、26、50、52 两种语言;`docs/mcpp-skills/`;CHANGELOG | 第 1、3、5 行 | §10.3 | + +次序相同的行互不依赖,可以同时进行。探针 PR(mcpp#1035)保留到 mcpp 的发布完成。mcpp 的改动 3、6、8、9、10 不依赖 +openkal 的任何一行;它们与其余各项同在最后一行,是因为一个仓库一个 PR。 + +mcpp 这一个 PR 有十一项改动,是本方案里最大的检查点。其中最大的一项是改动 8 的锁的粒度(§3.7.1):它改的是 SPEC-011 的第 2 节与并发的执行路径。它的前提 +由 M10 核实;M10 发现有一类路径无法归入四种对象时,按 §3.7.1 末尾的规则那一类配置保持排他,PR 的其余部分不受影响。 + +方案确定后另做四件不属于上表的事:登记 xlings 的 issue 与 mcpp 的备注 issue(§3.11.2 第 10、13 条),xlings 发布 +该项之后的收尾 PR 不在本方案的次序之内,由备注 issue 跟踪;对各 issue 回复(§4 的去向表是回复的提纲);把 §3.1.3 所记的上游事实登记进 +mcpp#1027。 + +## 7. 决定 + +### 7.1 已决定 + +| | 事项 | 决定 | 未取的选项与理由 | +|---|---|---|---| +| **D1** | 测试与可执行目标同路径(#1028) | **修订(2026-12-04):规划时立即拒绝**,即已合入的 #1036;本文补全它(§3.2.3) | v4 的决定(弃用表一行,到期后拒绝):docs/51 管辖的是拼写与读法,这里是两个产物写同一个文件;同类冲突一律立即拒绝;警告期内后果照样发生。测试程序放进自己的子目录:改变所有工程的测试产物路径 | +| **D2** | 库包面向其他构建系统的描述 | 本轮包含 `.pc` 与条目面向环境的一面(§3.3.3) | 不做:其他构建系统的消费者只剩具名的树 | +| **D3** | 归档器不接受响应文件(BSD 系的归档器把 `@file` 当文件名;只影响以路径点名的树) | 识别时探测,由 mcpp 展开后调用,超出上限时分批 | 识别时拒绝:要求用户为一棵本身完整的树另装一个归档器 | +| **D4** | C 库一层的陈述用哪个词 | `posix_spawn_file_actions_addclosefrom_np` | 新的非标准标志:别的 C 库没有的词 | +| **D5** | 未陈述偏好时的环境 | 不写入、不去掉;规范 7.17 补一句。其范围是三个实现向另外五个收敛,并加测试集的一例(§3.4.2) | 增加「不传递偏好」的标志:多一个接口。只做描述符:不满足「环境与给出的完全相同」 | +| **D6** | openkal-windows 称呼目录时是否核对 | 核对为同一对象 | 不核对:目录改名后启动的是另一个文件 | +| **D7** | 索引补包的范围 | §3.6 全部 | — | +| **D8** | 同一个包在两处陈述给出两个版本 | 报告一行,行为不变 | — | +| **D9** | Windows 上工作目录的名字 | **(a)(2026-12-04)**:三步称呼,规范不改,边界写明并登记(§3.5) | 规范的启动结构以「目录加相对名」称呼工作目录:改的是每个实现都读的结构,而边界之外的情形没有报告或测量 | +| **D10** | 等待一把锁的上限 | **(a)(2026-12-04)**:默认等待,`--lock-wait`、`MCPP_LOCK_WAIT`、`[build] lock_wait` 为覆盖;并要求做好锁的粒度、同一工作区内不同成员的构建与等待的提示(§3.7.1、§3.7.2) | 默认设上限:与 SPEC-011 相反。不提供上限:没有覆盖 | +| **D11** | `mcpp new` 的版本库 | **(a)(2026-12-04)**:默认 `git`,有覆盖;子工程不带自己的版本库,显式的 `--vcs git` 被照做(§3.8) | 默认 `none`:功能对不知道它的人不存在。子工程也初始化:工作区的根成为仓库时成为嵌套的仓库 | +| **D12** | 同一工作区内不同成员的同时构建 | **(a)(2026-12-04)**:计划的锁属于选择,单元由发布协议与单元缓存保护,配置的锁分共享与排他;条件不成立的配置保持排他(§3.7.1) | 每个选择一个配置目录:产物路径随选择而变。保持一把锁:不满足要求 | +| **D13** | 索引的回归修复是否单独先行 | **(a)(2026-12-04)**:单独、最先 | 与补包同一个 PR:mcpp 的 CI 一直失败到那时 | +| **D14** | 安装的锁 | **(a) 的形状,分两步(2026-12-04)**:本方案不改 xlings 的代码,登记一个 xlings 的 issue;mcpp 本轮做不依赖它的部分并保留自己的安装轮次;xlings 发布之后一个收尾的 PR,由 mcpp 的备注 issue 跟踪(§3.11.2 第 10 至 13 条) | 在本方案内直接改 xlings:它动的是安装器最核心的路径,与本轮其余各项没有次序上的依赖。两层的锁都不动:首次构建与并行的安装永远串行。mcpp 自己按包加锁:安装器自己取的是 home 的锁 | +| **D15** | 各平台共有的版本如何写 | **平台引用(2026-12-04)**:一个平台的表陈述,其余平台 `{ ref = "<平台>" }` 指向它;mcpp 的读者按安装器的解析读它;工具一并读它 | 内联地写进每个平台:已发布的读者读得对,但三个平台同样的内容各写一遍,一万八千行重复,索引的作者为读者的缺陷付出代价。局部表的引用:已发布的读者读错修订 | +| — | 诊断 | §10 的规则与清单是本轮验收的一部分 | — | + +另有先前作出、本文据以设计的决定:引擎不内置厂商工具链的名字;索引的缺包补齐;交付物的环境经 `[xlings]` 这一 +机制陈述与消费;对各 issue 的回复在方案确定之后。 + +### 7.2 待决定 + +没有。 + +## 8. 测量的结果 + +探针 PR mcpp#1035,运行 45997639603;各步只打印,不断言。 + +| | 测量 | 结果 | 对设计的作用 | +|---|---|---|---| +| **M1** | 替换盘符下经 mcpp 启动一个报告自身的程序 | 直接启动:模块路径为别名。经 mcpp:模块路径与工作目录为物理路径,命令行保留别名。盘符表含该盘符 | 证实 #1032 的机制,并证实工作目录同样受影响;§3.5 的预开名字可用 | +| **M2** | 环境声明编译器的一个版本,装入依赖另一版本的载荷;mcpp 中两条陈述并存 | 被依赖的版本装在旁边、不激活、无提示;mcpp 中两个版本都被供给、无提示 | §3.3 第 3 点:编译器不进依赖。新增决定 D8 | +| **M3** | `wasm32-emscripten` 七个变体 | 根包:默认与两者都陈述成功,只陈述异常失败。依赖包:默认、只陈述异常、两者都陈述均失败;`js` 成功 | 证实两个缺口相互独立;默认配置失败,#1029 的范围大于报告 | +| **M4** | 以路径点名运行器自带的树(macOS 与 Linux) | macOS:不陈述链接器则链接失败;陈述后程序成功,构建程序仍失败;归档失败;模块单元被编译器拒绝。Linux:`{ path = "/usr" }` 选中 clang;陈述 `family` 与 `sysroot` 后程序成功,构建程序由 clang 规划并被拒绝 | 证实 #1034 在两个平台的后果;§3.1.2 增加模块语法一项;确定 §3.1.4 的第三例 | +| **M5** | home 位于替换盘符与符号链接之下 | mcpp 构建成功,全部命令行与产物只含给定的拼写;xlings 向符号链接下的 home 从离线包安装成功 | 规则三在 mcpp 成立;xlings 的拼写不需改动 | +| **M6** | 现有的 xkbcommon 包是否构建 X11 部分 | 否 | §3.6 该行是同一上游仓库的新成员 | + +**实现前待测(M7,在同一个探针 PR 中)。** 带安装步骤的库条目的两个读者:(1) mcpp 取这个包时,两步把 `.pc` 放进 +构建程序读的 pkg-config 视图,除此之外不改变消费者的构建;(2) 索引的两个函数在 mcpp 为之写条目的索引中可用, +不可用时条目给出 `.pc` 的目录而不失败;(3) 视图中的 `.pc` 经改写后的前缀指向载荷,`pkg-config --cflags --libs` 的输出 +可以被另一个构建系统链接。结果不改变 D2 的决定,只确定条目的两步怎样写。 + +**M8(#1039)。** 在一个宿主带模块清单的容器作业中:复现报告;记录带上构建的词之后三个探测各自的答案,哪一个 +给出载荷内的源文件;带词时是否仍有答案落在声明的根之外。结果确定 §3.1.3 第 2 条在这个载荷上是否被触发。 + +**M9(#1040)。** (1) 锁文件不可打开时,基线上的构建是否无限等待并报告一份无关的记录(读码的结论);(2) 持有者 +位于另一个进程命名空间时,基线上的那一行与本进程所见;(3) 两个进程同时构建一个不完整的条目、第三个进程读一个 +完整的条目,后者不取锁时的结果;(4) Windows 上原语对「被持有」与「被拒绝」各返回什么。结果确定 §3.7 第 3 条的 +分类表。 + +**M10(锁的粒度)。** (1) 逐一列出现在在配置锁之下写入的路径,归入 §3.7.1 的四种对象;(2) 在 GCC 与 clang 的托管 +工具链上让两个计划同时编译同一个单元,核对发布的结果与两方的构建;(3) 一个选择首次构建时放置全部单元的开销; +(4) 归档写临时名后改名在三个平台上的行为;(5) 旧版本的 mcpp 与新版本同时构建一个配置;(6) 共享与排他两种持有 +方式在网络文件系统上的行为(已有的 NFS 作业)。第 3 项的数值决定 §3.7.1 的快路径是否加入:上限为每单元两毫秒。 + +**M11(命令行)。** (1) `.xlings.json` 所钉的自举版本能否读 cmdline 新版本的清单并构建带 `agent-skills` 特性的 mcpp; +(2) 渲染进二进制的说明对各平台的归档大小的影响;(3) 在没有网络、当前目录为空的环境里,只凭 `mcpp --help` 与 +`--agent-skill-doc` 完成「新建、构建、运行、加一个依赖、读懂一条拒绝」的步骤数。第三项是规则六的验收。 + +**M12(取得依赖)。** (1) 按波次取得相对逐个取得的时间,以 §3.11.1 的四个包与一个有二十个依赖的工程各测一次; +(2) 现在两个进程同时安装同一个包时,mcpp 的轮次与 xlings 的状态锁各自起的作用——它决定收尾时轮次能否去掉, +结果写进备注 issue;(3) 取得依赖、规划与构建三段路径上直接写标准错误的调用的清单,以及其中在实时区域存在时会触发的; +(4) 嵌套的子构建(构建程序的那一次)是否在同一个终端上画自己的实时区域。 + +未能测量的:按拼写授权的沙箱本身。报告中的两项观察(自带 xlings 的引导异常退出、存储根的链接告警)在普通运行器上 +没有出现,需要报告者那种环境下的日志才能归因。 + +**顺带的观察(不属于本方案的六个问题,另行登记)。** 把发布包里的 xlings 与一个尚未初始化的 `XLINGS_HOME` 一起使用 +时,编译器载荷的配置钩子因找不到环境中的 `xlings` 而失败,`self doctor` 给出的提示是「只读存储?」,与原因不符。 + +## 9. 不采用的做法 + +| 做法 | 不采用的理由 | +|---|---| +| 放开 `[toolchain] … = "system"` | 没有被点名的编译器不能被识别与记录;`{ path }` 已是被点名的形式 | +| 为某个厂商的编译器增加一个被定位的工具链族 | 已决定不做。它的专有事实(归档器、链接器、驱动的固定词)由 §3.1.2 的探测与 `tools` 承担,不需要引擎认识厂商 | +| 增加面向全图的 `cflags` 键 | 全图事实已有两个通道(方言 flag、ABI 成员);通用键会让任意 flag 进入每个依赖的缓存键 | +| 增加旧版编译器载荷以匹配旧发行版的消费者 | 交付物的环境由生态供给时,消费者取得同一环境(§3.3);不取的消费者属于具名的树 | +| 把库包对编译器的要求写成载荷依赖 | 实测不改变环境在用的编译器,也不产生提示 | +| 把授权不随启动传递改为默认 | 受限的调用者启动的 openkal 程序会得到更多 | +| 按被启动程序的种类自动决定是否传授权 | 宿主系统上的 openkal 程序不带可识别的标记;只有调用者知道它启动的是什么 | +| 在句柄表里为每个目录句柄保存名字 | 规范 7.1 的判据排除它,实现自己的句柄构造也写明不建表 | +| 工作目录不在当前目录之内时,在物理盘符与别名盘符之间选一个 | 没有一个是调用者给出的;猜错的方向同样被按拼写授权的环境拒绝 | +| 由 mcpp 生成把 `.pc` 放进环境视图的步骤 | 那是索引已有的函数所做的事,带着对各版本客户端的处理;重写一份就有两份实现 | +| 一个条目服务一个读者,库包发布两个条目 | 两个条目描述同一个归档,地址与摘要各写一遍;一个条目的两个字段由两个读者各读其一 | +| 把依赖的归档捆进库包,使 `.pc` 自带闭包 | docs/12 的既有规则是声明而不捆绑:消费者同时依赖同一个包时会得到两份定义 | +| 为 xlings 设计拼写规则的改动 | 没有测得失败;没有失败点的改动无从验收 | +| 标准库为某一实现时,拒绝另一实现的模块清单 | 按实现的名字判定;按根判定对任何实现与任何问题成立,且不在引擎里点名标准库 | +| 按记录中的进程标识(连同启动时间)判定持有者已死并回收锁 | 进程标识在命名空间之间不通用、会被重用、在另一台机器上没有意义;误判使两个进程同时写一个条目。持有与否是系统的锁的事实 | +| 提供清除锁的命令,或把删除锁文件作为补救 | 新文件是另一个对象,原持有者仍持有旧的,互斥随之失效 | +| 给等待设一个默认的上限 | SPEC-011 规定后到者等待;正当的等待没有 mcpp 可知的上界 | +| 锁被持有一段时间后绕过缓存,为这次构建私下编译一份标准库模块 | 标准库模块的路径在每一条编译命令里;私下的一份使整个工程按另一组命令重建,条目空出后再重建一次。命中不再取锁之后,余下的等待都是两个进程要写同一个条目,等待是正确的 | +| `mcpp new` 的版本库初始化不设覆盖 | AGENTS.md §2:每个默认值都有显式的覆盖 | +| `mcpp new` 写出第一个提交,或选定分支名 | 提交的内容与作者、分支名都是使用者的 | +| 在脚手架事务之内初始化版本库 | 「是否位于一个工作树之内」须按最终位置判断;`.git` 不是模板的内容,不属于「失败不留半成品」所保护的对象 | +| 测试与可执行目标同路径:先弃用、到期后拒绝 | v4 的决定,已修订(§3.2.3) | +| 每个选择一个配置目录,以换取成员之间互不等待 | 一个成员的产物路径随选中它的选择而变;目录数随选择的组合增长;推翻「各选择共用构建目录」的既有设计 | +| 每个成员一份计划,选中多个成员时逐个运行 | 被多个成员共有的依赖在每个成员的计划里各查找一遍,开销随「成员数乘以共有的单元数」增长 | +| 锁的粒度不设关法 | docs/26:每一项优化都能单独关掉,失败时点名它 | +| 每个包一份 ninja 的状态与一把锁 | 跨包的调度与模块的先后由一个 ninja 的一张图完成;拆开后并行度下降 | +| 把一个选择的 ninja 日志从别的选择的日志里拼出来,以免首次构建时逐个放置 | 那是 ninja 内部的格式;单元缓存已经给出同样的结果而不依赖它 | +| 两个同时进行的构建之间共享一个作业数的上限 | 两个工程同时构建时现在也各用各的;这是另一个问题,`--jobs` 是已有的控制 | +| 「agent 模式」:探测调用者并改变行为或输出 | 第二份语义;探测出错时无从发现。差别只在调用者自己陈述的通道上 | +| `mcpp new` 向新工程写入面向 agent 的说明文件 | 工程的内容属于使用者;发现的途径是命令本身(`--help` 的那一行) | +| 在 mcpp 里实现相近名字的建议与说明的核对 | 命令树在命令行库里;mcpp 自己做一份就有两份 | +| 运行时从磁盘读取用法说明 | 二进制与说明可以不一致;只有二进制的读者没有那个目录 | +| 子工程在显式要求下也不初始化版本库 | 命令行是最高的一层;默认的行为须有覆盖 | +| 在 mcpp 里嵌入解释器来执行索引条目 | 执行条目的是安装器;mcpp 读的是条目的一个声明式的子集,这个子集就是两者之间的契约。第二个执行者会成为第二个可以不一致的地方 | +| 读不懂修订时按 0 处理(现状),或一律视为相符 | 前者使每次构建都重装;后者在修订确实改变时沉默地用旧的载荷 | +| 保留预告行,只修残留的进度条 | 预告在什么都不下载时是假的,这正是「每次都打印」被读作缺陷的原因 | +| 在进度条里用发给安装器的地址 | 使用者写的是身份;地址是实现的细节,只在排查时有用 | +| 只修那一处直接写标准错误的调用 | 同类调用约二百三十处;没有检查,下一处会重现同一个现象 | +| mcpp 在自己的安装轮次之内按包加锁,xlings 不动 | 安装器自己取的是 home 的锁,外层的细分被它重新串起来 | +| 两个进程的下载共用一个并发数的上限 | 与两个构建各用各的作业数同理,是另一个问题 | + +## 10. 诊断:拒绝、报错、警告与说明 + +本轮的报告有一个共同的外观:使用者看到的消息来自被启动的工具,而不是来自 mcpp。实测的五条是归档器的 +`@….rsp: No such file or directory`、驱动的 `invalid linker name in argument '-fuse-ld=lld'`、编译器对 +`export module` 的语法错误、链接器的 `undefined symbol: emscripten_longjmp`,以及没有任何消息的两个命令互相覆盖 +同一个文件。后并入的两项相同:编译器的 `'bits/stdc++.h' file not found`,以及一行只说一次、点名一个无关进程的 +`Waiting`。每一条都准确,没有一条指向原因或补救。读者是人还是 agent 没有区别:二者都只能从这条消息出发。 + +### 10.1 规则 + +| | 规则 | 依据 | +|---|---|---| +| G1 | **在最早能判定的地方说。** 规划时能判定的,不留给编译器、链接器、归档器或运行时 | 上面五条都在规划时可知 | +| G2 | **一条消息四个部分:** 发生了什么并点名涉及的两个对象;原因;影响(做得更少时必有);补救,写成可以照抄的那一行 | AGENTS.md §2;`diag::Record` 的 `what`、`impact`、`hint` | +| G3 | **严重度的含义固定。** 拒绝:结果不可能或将是错的。降级:mcpp 做得比陈述的少,必带影响。警告:清单被照做,但它的读法将改变或有风险。说明:一个事实,每个工程说一次 | `src/diag.cppm` | +| G4 | **机器读代码,不读句子。** 每条有稳定的 `code`;由清单的键引起的带 `path` 与 `range`,指到那个键;拒绝带原因码,`mcpp explain <原因码>` 给出长说明与例子 | docs/50 | +| G5 | **消息点名使用者的对象。** 文件是使用者给出的那个,不是 mcpp 的临时目录;子构建的消息标明它属于哪个构建程序,并指回主工程中管辖它的陈述 | 实测:`emit xpkg` 的消息点名临时目录 | +| G6 | **一个事实说一次,说在根因处。** 由同一原因引起的后续失败不再各自报告 | — | +| G7 | **`--strict` 把降级与弃用变为拒绝**,用于 CI | 既有行为 | +| G8 | **代码的两种形状各有含义。** 降级与说明的代码是 `域/名字`;拒绝的原因码是不带域的短横线词。一个情形在两种严重度下出现时用两个代码 | docs/50 与 SPEC-011 的既有用法 | + +### 10.2 本轮的每一条 + +「现在」一列是基线上实测或读码得到的;「设计」一列的消息文本是英文,与 mcpp 的其余消息一致。 + +| 情形 | 现在 | 设计:时机 · 严重度 · 代码 | 消息的要素与补救 | +|---|---|---|---| +| 具名的树没有归档器,取宿主的 | 裸名字 `ar` 写入构建文件,无消息 | 规划 · 降级 · `build/archiver-from-host` | `the archiver for this build is the host's ('<路径>'): the toolchain at '<树>' carries none`;影响:两台机器可能用不同的归档器;补救:`tools = { ar = "<路径>" }`。`--strict` 拒绝 | +| 具名的树没有归档器,宿主也没有 | 归档时 `ar: not found` | 规划 · 拒绝 · `toolchain-has-no-archiver` | 点名树与查找过的位置;补救同上 | +| 归档器不接受响应文件 | 归档时失败,消息来自归档器 | 不报告(构建成功);`mcpp why toolchain` 的归档器一行写明 `takes its arguments directly` | — | +| 树中没有 lld,也没有陈述链接器 | 链接时 `invalid linker name` | 不报告(用驱动的默认链接器);`mcpp why toolchain` 的链接器一行写明来源:陈述、树中的 lld、驱动的默认 | — | +| 树的驱动不接受模块语法,工程有模块单元 | 编译时的语法错误 | 规划 · 拒绝 · 已有路径的原因码 | 指出第一个模块单元的文件、驱动及其版本、探测的结论;补救三选一:换一套工具链(`mcpp toolchain list`)、`tools.cxx` 指向带上所需开关的驱动脚本、该目标不含模块单元 | +| 一棵树里有两个族的驱动,没有陈述 `family` | 选中其一,只在 `Using` 行可见 | 规划 · 说明 · `toolchain/tree-holds-two-families` | `'<树>' holds clang and gcc ; clang is used`;补救:`family = "gcc"` | +| 构建程序的子构建失败 | `planning the build programs failed: …`,其余是子构建自己的消息 | 沿用,按 G5 补全 | 以 `build program '<名字>':` 开头;工具链引起的拒绝附一行,指向主工程 `[toolchain]` 所在的行 | +| 测试程序与可执行目标写同一个文件 | 已合入:规划 · 拒绝 · `[test-output-collision]`,点名包、测试程序、目标与路径;补救是「改测试程序或目标的名字」 | 规划 · 拒绝 · `test-output-collision`(不变) | 补全:点名测试的目录或文件与目标在清单中的键(带 `path`、`range`);补救写成可以照抄的一行;原因码进入 docs/50 与 `mcpp explain` | +| 驱动的答案落在构建声明的根之外,其后的探测给出了根之内的答案 | 宿主的文件被采用,编译时由编译器报错 | 不报告(构建成功);`mcpp why toolchain` 的标准库模块一行写明源文件的来源,并列出未被采用的答案 | — | +| 同上,没有任何探测给出可采用的答案 | 同上 | 规划 · 拒绝 · 已有的「没有标准库模块」的原因码 | 点名驱动、提出的问题与所带的词、每个未被采用的答案及原因(在哪个根之外);补救:换一套带标准库模块的工具链,或以 `allow_host_libs` 陈述取用宿主 | +| 根包陈述的 ABI 成员没有到达依赖 | 链接时 `undefined symbol` | 不再发生 | — | +| 共享镜像缺少经接口到达的库 | 链接时 `undefined reference` | 不再发生;`mcpp why flags` 对链接行上的每个共享镜像给出来源:直接依赖,或经哪个包的接口到达 | — | +| `emit xpkg --package` 得到一个不是 `mcpp pack` 写出的归档 | `'<临时目录>/…' has no mcpp-package.json` | 拒绝 · `not-a-package-of-mcpp-pack` | 点名使用者给出的文件;补救:`mcpp pack --pkg-format tar` | +| 同上,归档是旧版本写出的库包 | 同上 | 拒绝 · `package-without-description` | 点名写出它的版本(取自清单的来源记录);补救:用本版本重新打包 | +| 在库包目录里运行不带 `--package` 的 `emit xpkg` | 写出占位符与三个系统的条目 | 拒绝 · `emit-inside-a-package` | `this directory is a library package written by mcpp pack, not a source tree`;补救:`mcpp emit xpkg --package <归档> --url <前缀>` | +| 为具名的树构建的库包写条目 | 不适用 | 拒绝 · `package-built-outside-the-ecosystem` | 点名树与驱动的身份;原因:条目会许诺一个消费者装不到的环境;补救:以 `path` 或 `git` 交付,或用托管工具链打包 | +| 库包只有模块接口 | 不适用 | 打包时 · 说明 · `pack/no-header-interface` | `<包> publishes a module interface and no header interface: no .pc is written`;影响:mcpp 以外的构建系统没有可读的描述 | +| 带依赖的静态库包 | 不适用 | 打包时 · 说明 · `pack/closure-not-in-package` | 点名每个依赖;影响:mcpp 以外的消费者须在环境中另有这些依赖的二进制与描述;补救:以共享库交付,或把这些依赖也作为库包发布 | +| 写条目时同一系统与架构有两条腿 | 不适用 | `emit xpkg` · 说明 · `emit/two-legs-for-one-system` | 点名两条腿;影响:条目不带面向环境的一面;补救:每种 ABI 发布一个包 | +| 用具名的树打包库 | 已有警告(宿主耦合的运行库) | 沿用;打包的汇总行写明 `built with the toolchain at '<树>'` | 影响:这份二进制只对使用同一套工具链的消费者成立 | +| `[toolchain]` 与 `[xlings.workspace]` 给同一个包两个版本 | 两者都被供给,无消息 | 规划 · 说明 · `xlings/package-at-two-versions` | 点名两个键与两个版本,各自管什么:前者编译这次构建,后者在构建启动的程序的 `PATH` 上;补救:去掉其一,或保留(需要两者时) | +| 一把锁被另一个进程持有 | `Waiting for …, compiled by pid N (…)`,说一次;N 取自记录,可能与持有者无关 | 等待 · 状态行,周期性重复 · `waiting` 事件 | 等的是什么(哪个条目、哪个选择的计划);锁文件的路径;最后记录的持有者;该进程在此是否可见,不可见时的两种含义与列出持有者的命令;已等待的时间;首次报告带 `help:` 一行(`--lock-wait`),样子见 §3.7.2 | +| 不能加锁(没有权限、只读、文件系统不支持锁) | 无限等待,报告同上 | 立即 · 错误 · `lock-unavailable` | 点名路径与系统的原因;补救按原因:改正该文件的属主,或把 home 放在支持锁的本地文件系统上 | +| 等待超过陈述的上限 | 不适用 | 拒绝 · `lock-wait-exceeded` | 同「被持有」的各项,加上上限的来源(选项、变量或键) | +| `mcpp new`:值来自默认或 `config.toml`,没有 git 或初始化失败 | 不适用 | 创建之后 · 降级 · `new/vcs-unavailable` | 工程已创建;影响:该目录不是仓库,`.gitignore` 在 `git init` 之前不起作用;补救:那一行命令,或 `--vcs none` | +| `mcpp new --vcs git`,没有 git 或初始化失败 | 不适用 | 创建之后 · 错误 · `vcs-unavailable` | 写明工程已创建、失败的是初始化这一步及 git 自己的消息;退出非零 | +| `mcpp new`:新建的是子工程(位于另一个工程或仓库之内),值来自默认或 `config.toml` | 不适用 | 不报告 | — | +| `mcpp new --vcs git`:新建的是子工程 | 不适用 | 创建之后 · 说明 · `new/vcs-inside-another` | 点名它位于哪个仓库或工程之内;仓库已按要求建立 | +| 未知的命令 | `error: unknown command '<名字>'` 加整份帮助 | 用法错误 · 一行加 `help:` | 名字相近的命令;`mcpp --help` | +| 未知的选项 | `error: unknown option: --<名字>` | 用法错误 · 一行加 `help:` | 该命令名字相近的选项;`mcpp <命令> --help` | +| 在没有工程的目录里运行需要工程的命令 | `error: no mcpp.toml found in current directory or any parent` | 错误 · 一行加 `help:` | `mcpp new `;或在工程的目录里运行 | +| `mcpp explain` 得到一个不认识的代码 | 只列出 `E0001..E0006` | 错误 · 一行加 `help:` | 名字相近的代码;三类代码各自的列出方式 | +| 一个配置因条件不成立而保持排他 | 不适用 | 不报告;`mcpp why` 的一行写明原因(输出不可重定向,或没有使用 home 的单元缓存) | — | +| 一个已经装好的依赖 | 每次构建一行 `Downloading <包> v<版本>`(修订读错时) | 不报告;`-v` 下一行说明它被采用 | — | +| 一个依赖正在下载 | 三行:预告、残留的进度条、完成行;三种写法 | 一行,下载开始时出现,完成时被完成行取代 | 清单中的身份加版本;大小、用时;宽度不够时先缩短进度条 | +| 一个依赖因条目的修订改变而重装 | 与下载相同 | 一行,动词 `Updating` | 修订从几到几 | +| 条目的写法超出读者的语法 | 无消息;修订读作 0 | `mcpp xpkg parse` · 错误;构建时不报告、不重装 | 点名条目、版本与读不懂的那个值;补救:写成内联的表 | +| 等待另一个进程的安装 | `Waiting for another mcpp of this home, installing <包>` | 与 §3.7.2 同一形状 | 等的是哪个包的锁或状态锁;持有者的记录与可见性;`--lock-wait` | + +openkal 一侧没有诊断通道,它的「消息」是返回值与文档:`posix_spawn_file_actions_addclosefrom_np` 对 `lowfd > 3` +返回 `ENOSYS`,端口的差异表写明含义与理由;旧版本的库没有这个符号,调用者在链接时得知。openkal-windows 在核对 +不通过时退回现在的行为,不报告。 + +### 10.3 验收 + +- 上表每一条拒绝、降级、警告与说明各有一个 e2e 断言:`code` 或原因码、点名的两个对象、补救的那一行。 +- 上表「不报告」的每一条有一个 e2e 断言构建成功,并断言 `mcpp why` 的相应一行。 +- 每个新的原因码在 `mcpp explain` 中有条目;docs/50 的代码表与原因码表同步,两种语言。 +- 消息中不出现 mcpp 的临时目录,不出现只有实现者才认识的名字。 + +### 10.4 其余可见的变化 + +- **一处写,处处生效。** 工程不再需要为构建程序另放一套包装目录;一个 `tools.cxx` 对两类编译生效。 +- **默认配置可用。** `wasm32-emscripten` 上带 C 依赖的工程不需要任何陈述即可链接。 +- **来源可见。** §3.1.2 的每项能力在 `mcpp why toolchain` 与机器输出中带上「陈述」「探测」或「宿主」。 +- **在自建沙箱里启动子进程的程序**用一个已有的 C 库调用得到确切的三个流与确切的环境,不需要自己的再执行跳板。 +- **在按拼写授权的环境里运行的工具**以它被给出的名字启动编译器;编译器读到的自身路径与用户写下的一致。 +- **不同的成员同时构建。** 同一个工作区里选择不同成员的两个命令不再互相等待;共有的依赖只编译一次。此时配置的 + 结果记录是最后写它的那个命令的;每个命令自己的记录在它的机器输出与计划目录里。 +- **只凭二进制学会使用。** `mcpp --help` 列出命令树的每个命令并指向 `--agent-skill-doc`;每个报错给出下一步;每个 + 代码都能用 `mcpp explain` 查到。 +- **装好的依赖不再出现在输出里**,也不再每次构建去取 home 的安装锁;首次拉取时每个依赖一行,不留残行。 +- **两个工程同时首次构建**,各自的依赖同时下载——在 xlings 实现改动 19 并收尾之后;此前它们串行,等待有报告与上限。 +- **命中不等待。** 标准库模块已经构建好的工程,不再因为另一个进程持有那个条目的锁而停在规划。 +- **等待说得清。** 一次等待给出路径、最后的记录与它是否可见,并周期性重复;CI 与 agent 可以陈述上限。 +- **新工程即仓库。** `mcpp new` 之后 `git status` 可用,`.gitignore` 立即生效;不需要的写 `--vcs none`。 +- **文档。** docs/01 与 docs/09 陈述 `mcpp new` 的版本库与覆盖;docs/25 陈述共享条目的读法与等待;docs/20 增加一节,陈述「为不由生态供给的环境构建交付物」这一任务的写法与它放弃的保证;docs/12 增加 + 库包的索引条目的步骤、中立描述、经工程环境消费的写法,以及编译器由消费者声明这一点。两种语言同步。 + +## 11. 自查 + +五轮。前四轮的角度是架构、通用性、简洁、语义一致、划分、跨平台、兼容性,以及使用者与 agent 的体验;第五轮 +另加稳定性、性能、可扩展性与生态的规范。 + +### 11.1 第一轮(v3 至 v4,2026-11-27) + +对 v3 逐节复查,并对存疑之处读码或读索引核实。下表是查出并已改正的十二处;其中三处改变了改动的范围,标为**范围**。 +表中的改动编号是本版的。 + +| 角度 | 查出的问题 | 核实 | 本版的处理 | +|---|---|---|---| +| 跨平台 | **范围。** 改动 14 只列了 openkal-linux | 读八个实现:五个已是目标行为,linux、macos、windows 是另一种 | 改为三个实现的收敛,规范的测试集加一例(§3.4.2) | +| 架构、语义 | **范围。** §3.5 称工作目录与映像同理,验收也这样写 | 读 mcpplibs.os 与 openkal-windows:工作目录以打开后的句柄到达,拼写没有越过接口 | 三步称呼,边界写明,新增决定 D9(§3.5) | +| 划分 | **范围。** 条目的安装步骤被写成由 mcpp 生成 | 读索引:把 `.pc` 放进视图的是索引自带的函数库,含前缀改写与对旧客户端的处理 | mcpp 只写数据,条目调用那两个函数;新增测量 M7(§3.3.3) | +| 语义一致 | `.pc` 的位置在同一文档里有两种写法 | 库文件一律在 `lib//` 下 | 一律 `lib//pkgconfig/` | +| 通用性 | `.pc` 以包的短名命名,两个命名空间下同名的包在视图中相撞 | 归档已按身份命名 | 复用同一个命名函数 | +| 语义一致 | `addclosefrom_np` 对小于 3 的参数只说「不传授权」,与别的 C 库关闭流的含义不符 | — | 小于 3 时流按各自的 `addclose` 处理(§3.4.1) | +| 兼容性 | 移除月份写死为 2027.3 | 弃用表按弃用的月份给出移除的月份 | 改为按规则得出(§3.2.3) | +| 通用性 | `.pc` 的 `Requires` 默认依赖在环境中可得,而索引中的依赖是源码包 | docs/12:库包声明依赖而不捆绑 | 写明「描述这个包自己」,带依赖的静态库包在打包时报告(§3.3.3、§10) | +| 跨平台 | 条目面向环境的一面没有说同一系统与架构有两条腿时取哪条 | docs/12 的既有限制:每种 ABI 一个包 | 只有一条腿时才写,否则报告(§3.3.3、§10) | +| 架构 | 归档器的探测与查找的名字没有说明来源 | — | 探测是一次真实的归档;名字取自族的数据行(§3.1.2) | +| 通用性 | ABI 成员的修正只针对已知的两个缺口 | — | 加按表驱动的测试,覆盖每个成员的六个位置(§3.2.2) | +| 兼容性 | 链接行新增库的范围与后果没有写 | 读码:mcpp 只在一处使用「按需」的链接器开关 | 写明上界是公开依赖的闭包,未被引用的也成为装载依赖(§3.2.1) | + +### 11.2 第二轮(v4 至 v5,2026-12-04) + +把 #1036 的合入与 #1038、#1039、#1040 并入之后,按同样的角度复查全文。下表是查出并已在本版处理的十四处;其中 +两处改变了改动的范围。 + +| 角度 | 查出的问题 | 核实 | 本版的处理 | +|---|---|---|---| +| 架构、语义一致 | **范围。** §3.1.2 的四项探测没有说带着什么词向驱动提问;#1039 表明不带词的提问得到的是宿主的答案,v4 的探测会重复这个缺陷 | 读码:询问运行库归档的函数带链接行的 flag,询问标准库模块源文件的两次探测不带 | 新增 §3.1.3:一个提问的函数,答案按「驱动加词」缓存;§3.1.2 的探测经它进行;规则二补上后半句 | +| 架构 | **范围。** #1040 的报告把原因归于「不是建议锁、记录残留」。照此设计会重写一遍已有的实现,并引入按进程标识的回收 | 读码:锁已是建议锁,记录从不删除;本机 44 个条目的记录全部指向不存在的进程而没有一把锁被持有;分析所在的会话处于非初始的进程命名空间 | §3.7 的五条针对读码找到的四个缺陷;回收与删除锁文件列入不采用的做法;那一次的直接原因如实写为未确定 | +| 语义一致 | D1 与合入的实现不一致;v4 称立即拒绝违反 docs/51 | 读 docs/51 的条文:管辖拼写与读法;同类输出冲突的既有处理都是立即拒绝;粗筛本机的清单 | 修订 D1,写明代价 | +| 划分、规范一致 | 标准库模块的条目在规划段取排他锁,与 SPEC-011 自己的两条(规划段不持锁、读者不加锁)不一致 | 读码与规范 | 改动 8a;规范增加一条而不是开一个例外 | +| 通用性 | 等待有三处自己的循环,报告的有无与阈值各不相同 | 读码 | 并入一个原语 | +| 跨平台 | 「被持有」在两个系统上是不同的返回值;Windows 上另一个程序占用文件时打开会被瞬时拒绝 | 读两个系统的原语 | 原语返回原因;瞬时拒绝沿用读文件已有的两秒重试,之后才是「不能加锁」 | +| 兼容性 | 新旧版本的 mcpp 同用一个 home:旧版本每次重写记录且不带「部分」字段 | 读码 | 旧记录按未完成处理一次,不重编译;读到不完整或不相符的记录一律走取锁的路径,正确性不依赖记录的新旧 | +| 通用性 | #1038 的「不嵌套」只考虑已有的工作树 | — | 加上「位于 mcpp 工作区之内」:成员自带版本库,在根成为仓库时变成嵌套的仓库 | +| 跨平台、语义 | 环境中的 `GIT_DIR` 使 `git init` 把仓库建在别处(从钩子里运行时即是) | git 的既定行为 | 子进程的环境去掉这一组变量,判断是否在工作树内的那次询问亦然 | +| 语义一致 | 没有 git 时算什么严重度没有定 | `src/diag.cppm` 的含义 | 值来自默认时是降级并带影响;来自命令行时是错误 | +| 通用性 | 改动 6 的判同区分大小写,在两个默认不区分大小写的系统上漏掉只差大小写的名字;既有的测试重名检查同样 | 读合入的实现 | 一个判同的函数,向文件系统询问,两处共用 | +| 语义一致 | 原因码的名字:v4 设计为 `test-named-as-target`,合入的是 `test-output-collision` | — | 取合入的名字:判据是输出路径,名字与判据一致 | +| 诊断 | #1039 的失败由编译器报告,违反 G1 | — | §10.2 增加两行 | +| 简洁 | v4 称本轮「不增加命令行的开关」 | — | 如实改写(见下) | + +### 11.3 第三轮(v5 至 v6,2026-12-04) + +并入对锁的粒度、命令行与索引回归的要求之后复查。下表是查出并已处理的九处,三处改变了范围。 + +| 角度 | 查出的问题 | 核实 | 本版的处理 | +|---|---|---|---| +| 架构 | **范围。** v5 把「配置一把锁」当作前提,只修了它上面的等待 | 实测:两个不相交的成员互相等待 4.5 秒;读文档:锁属于配置是因为 ninja 的状态,而单元此后已能自己保护自己 | §3.7.1:三种对象三种粒度,条件是数据 | +| 语义一致 | §10 的 G4 与 §10.3 假设 `mcpp explain <原因码>` 存在 | 实测:它只认识 `E0001` 至 `E0006` | §3.9.2 第 6 条:三类代码登记在一处 | +| 架构、体验 | **范围。** 方案只设计了消息,没有设计「怎样知道有哪些命令、怎样用」 | 实测六种入口的输出;读 cmdline 0.0.7 与 0.1.0 | §3.9;cmdline 成为方案涉及的一个仓库 | +| 划分 | 相近名字的建议、说明与命令树的核对若写在 mcpp 里 | 命令树在 cmdline 里 | 放在 cmdline(改动 18) | +| 语义一致 | D10 的 (a) 与 2026-10-26 设计 §4.2 的决定相反,v5 没有引用它 | 读该设计 | §3.7.2 引用并写明推翻的理由 | +| 规范一致 | SPEC-011 §2 第 5 条与实现、与 docs/07 不一致 | 读三处 | 规范随本轮改正 | +| 语义一致 | v5 的「不嵌套,与值无关」使命令行的显式陈述不起作用 | 实测 cargo 的四种情形 | 子工程不带版本库是默认的行为;显式的要求被照做 | +| 通用性 | 「子工程」只列了工作树与工作区 | — | 任何一个上级目录持有 `mcpp.toml` 即是 | +| 兼容性、划分 | **范围。** 索引的一次改动使 mcpp 的全部 CI 失败,方案的次序以 mcpp 的 CI 可用为前提 | 读失败作业的日志与索引的提交 | 改动 16 与 §3.10;次序表以它为第 0 行 | + +顺带的观察,本轮不设计:mcpp 的 e2e 直接依赖线上的索引里的旧版本,索引的回归因此立即在 mcpp 显现(这次正是这样 +被发现的),也因此挡住无关的 PR。改动 16 的检查从来源处消除这一类回归。 + +### 11.4 第四轮(v6 至 v7,2026-12-04) + +并入取得依赖的三个现象之后复查。五处,一处改变了范围。 + +| 角度 | 查出的问题 | 核实 | 本版的处理 | +|---|---|---|---| +| 划分 | **范围。** 前三版的结论是 xlings 不改动,依据是「没有测得属于它的失败」 | 实测一次构建等待另一个工程的安装;读 xlings 的锁:以 home 为范围,贯穿整个安装 | 目标的形状写进 §3.11.2;按评审的决定不在本方案内改 xlings 的代码,登记为它的 issue,mcpp 先做不依赖它的部分,收尾另一个 PR(D14) | +| 语义一致 | 规则五的「粒度与对象一致」在 v6 只用于构建目录 | home 的安装锁是同一个问题 | §3.11.2 第 10 至 12 条;一个上限管辖一次命令里的每一处等待 | +| 兼容性 | 只修读者不能到达已发布的 mcpp | docs/51 的受支持版本;mcpp 自己的 CI 用的自举版本也是旧版本 | 改动 17:索引的数据改写,检查固定到受支持的最低版本读得懂为止 | +| 通用性 | 残留的进度条若只修那一行输出 | 读码:直接写标准错误的调用约二百三十处 | 一个写者加仓库的检查;现有的登记在只减不增的清单里 | +| 诊断 | G5(点名使用者的对象)没有用于取得依赖的输出 | 实测一个依赖三种写法 | 清单中的身份是唯一的写法 | + +### 11.5 第五轮(v7 至 v8,2026-12-04) + +全部决定作出之后,对全文按十三个角度再查一遍。十二处,无一改变改动的范围。其中最重的一处是此前各轮都漏掉的 +既有规范:docs/26 要求每一项优化是表中的一个可以单独关掉的条目。 + +| 角度 | 查出的问题 | 核实 | 本版的处理 | +|---|---|---|---| +| mcpp 的规范 | 改动 8 的锁的粒度与改动 11 的按波次取得都是优化,却没有按 docs/26 的要求成为构建优化表的条目 | 读 docs/26 与 SPEC-019:每个条目有参数、一次调用的关法与失败时的 `tip:` | `plan-locks` 与 `batch-fetch` 两个条目(§3.7.1、§3.11.2) | +| 性能 | 一个选择首次构建时逐单元查找,大的工作区里可达数十秒,文中只写了「十几毫秒一个」 | 该数值含放置文件的开销,对已发布的单元会低,但没有测过 | 写明上限(每单元两毫秒)与超过时的快路径;M10 的数值决定是否加入 | +| 性能 | 向驱动提的问题若只在进程内缓存,每次构建都重新启动驱动若干次 | — | 答案随工具链记录保存,键含驱动的身份(§3.1.3) | +| 稳定性、通用性 | 修订读错的缺陷只靠读者的修补与 mcpp-index 的检查防止;别的索引、将来的写法仍会重现 | 修订的两个数值在一次安装刚完成时必然相同 | 运行时的自检:不同即读者读错,按未知处理并报告一次(§3.11.2 第 2 条) | +| 兼容性 | 计划的目录会带走已写进文档的文件(结果记录、编译数据库),读它们的程序随之失效;两个命令同时构建时配置的结果记录是谁的,没有陈述 | 读 docs/50:这些路径与「开始时写 `running`、结束时再写」都已写进文档 | 写进文档的路径不变;记录是最后写它的命令的,每个命令自己的记录在它的输出与计划目录里(§3.7.1) | +| 兼容性 | cmdline 的升级跨过四个版本,其间有行为变化 | 读该库各版本的说明 | 写明由命令行 e2e 与补全的快照覆盖(§3.9.3) | +| agent 的语义 | 用法错误的 `help:` 只有给人读的形式 | docs/50 的诊断有稳定的代码 | 机器输出下带代码与建议的数组(§3.9.2 第 5 条) | +| 跨平台 | 说明文档若含非 ASCII 字符,在某些终端的代码页下不能原样显示;伪终端的重放测试在没有伪终端的系统上不能运行 | — | 说明只含 ASCII;重放测试写明所需能力,静态检查在每个系统上承担同一条规则 | +| 跨平台 | 共享持有方式在网络文件系统上的行为没有列入测量 | CI 已有 NFS 的作业 | M10 第 6 项 | +| 语义一致 | 代码有 `域/名字` 与短横线词两种形状,文中没有陈述各自的含义;`mcpp new` 的一行在两种严重度下用了同一个代码 | docs/50 与 SPEC-011 的既有用法 | G8;改为两个代码 | +| 简洁 | 改动的编号按加入的先后,同一个仓库的改动不连续;全文没有一处能一眼看到问题、规则、改动、仓库与报告的对应 | — | 编号按仓库连续(mcpp 为 1 至 11);§0 增加一张对应表 | +| 生态 | 索引的自动更新工具可能再写出引用的形式 | 条目带自动更新的声明 | 由同一条检查约束(§3.11.2 第 3 条) | + +### 11.6 复查后的总体判断 + +- **简洁。** 清单不增加键,工具链不增加入口。新增的命令行选项三个(`--vcs`、`--lock-wait`,以及来自命令行库的 + `--agent-skill-doc`)、`config.toml` 的键两个、环境变量一个。其余新增的是:包里的两个文件(其一是程序包已有的 + 描述)、一组随二进制携带的说明、一个 C 库已有名字的函数、规范的若干句、十余个原因码。被删去的有一份手写的用法 + 文本。六处重复的实现被合并:向驱动提问、等待一把锁、输出路径的判同、ABI 成员的渲染、三类代码的登记、命令行库 + 里的索引;另有两处「两层各做一遍」被收成一层:叙述流只有界面模块一个写者;安装的锁在收尾之后只在 + 安装器里。 +- **划分。** 每一项改动落在拥有那个事实的仓库:工具链表的通道、向驱动提问、链接行、锁、脚手架在 mcpp;命令树的 + 事实(相近的名字、说明的核对)在命令行库;条目的钩子在索引;启动 + 时的名字在承担那个系统的实现;被启动的程序持有什么在 C 库的端口与规范;包在索引。安装的锁在安装器(xlings),因为 + 取它的是安装器;读条目的语法在 mcpp,条目处在这个语法之内由索引的检查保证。 +- **语义。** 六条规则各对应一组改动,没有一项改动需要第二条规则来解释;同一事实在一处写、一处渲染、一处询问。 + 规则三与规则五是同一个形状用在两种对象上:称呼用给出的名字(拼写、记录),判定用系统的事实(文件标识、锁)。 +- **跨平台。** 没有一条设计点名系统:归档器的名字、列出锁的持有者的命令、文件系统是否区分大小写,分别是族的数据、 + 平台模块的数据与一次探测;锁的粒度的条件是工具链模型的一个字段。只在一个系统上有效果的改动只有改动 12(它位于 + 那个系统的实现里)。 +- **兼容。** 托管工具链的构建不经过 §3.1.2 的任何一条新路径。被改变结果的输入有六种,各有说明:测试与可执行目标 + 同路径(已合入,立即拒绝);在库包目录里不带 `--package` 的 `emit xpkg`(此前写出错误的条目);带偏好的调用者给出 + 不含该变量的新环境(三个实现);以路径点名的工具链的构建程序(此前用了另一个编译器,身份改变,重建一次); + `mcpp new` 的输出目录多出 `.git`(有覆盖);宿主带模块清单时的交叉构建(此前失败,现在成功)。`waiting` 事件 + 只增加字段。另有三处可见而不改变结果的变化:配置目录里多出 `plans/`;用法错误不再打印整份帮助;根帮助的文本由 + 命令树生成,措辞与次序随之改变。 +- **稳定性。** 风险最高的两项(锁的粒度、按波次取得)各是构建优化表的一个条目,可以单独关掉,失败时点名;锁的粒度 + 另由数据决定在哪些配置上成立。读者与安装器的不一致有三道防线:读者本身、索引的检查、运行时的自检。mcpp 的安装 + 轮次在安装器消除它所防的缺陷之前保留。余下的风险是规模:mcpp 的一个 PR 含十一项改动。 +- **性能。** 变快的:命中的标准库模块条目不取锁;装好的依赖不启动安装器;依赖按波次取得;不同成员同时构建;向驱动 + 提的问题只问一次。可能变慢的只有一处,并有上限与对策:一个选择的首次构建。 +- **可扩展性。** 新的一类事实各有一个不需要改结构的去处:新的驱动问题进提问的函数,新的 ABI 成员进渲染的函数(表驱动 + 的测试会指出漏掉的位置),新的版本库是 `vcs` 的一个值,新的命令的用法是一份说明,新的优化是表中的一个条目,新的 + 代码进同一处登记。 +- **生态。** 本方案确立或沿用了四条跨仓库的约定:条目处在每个受支持版本的读者的语法之内(索引);钩子的契约与 + 「每个所列版本都可安装」(索引);命令行工具随二进制携带自己的用法(命令行库的约定,生态内其他工具可以采用,本方案 + 不改它们);锁的记录是提示而不是事实(mcpp 与 xlings 的陈述相同)。 +- **使用者与 agent。** 本轮每一项报告的可见症状都来自被启动的工具或来自沉默;§10 把它们全部移到规划时,由 mcpp + 说出原因与可以照抄的补救。对 agent 特别有用的三处:等待会重复并带路径,不再是一个不动的进程;「看不见持有者」 + 被直接说出,而不是让读者自己去查进程表并得出错误的结论;每条拒绝有稳定的原因码与 `mcpp explain` 的条目。 + +**仍未由测量支撑的。** 按拼写授权的沙箱本身(§8);M7 至 M12 的各项,其中 M10 决定改动 8e 的条件在多大范围内成立、 +快路径是否加入;#1040 那一次的直接原因;D9 的边界之外的 +情形是否在实际中出现。 diff --git a/.github/tools/check_stderr_writers.sh b/.github/tools/check_stderr_writers.sh new file mode 100755 index 000000000..89de27468 --- /dev/null +++ b/.github/tools/check_stderr_writers.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# The narrative stream has one writer (design 2026-11-27, ecosystem boundary §3.11.2 point 4). +# +# A line written to standard error outside mcpp.ui and mcpp.log does not erase the live region +# first and does not redraw it: the region's bookkeeping is one line short, and the line above it +# (a progress bar) stays on the screen. Measured 2026-12-04: the provider's `Source +# ` line, written once per download, left one stale progress bar per dependency. +# +# Each file's count of direct writes to standard error is at most its line in +# stderr-writers.baseline, and a file not listed has none. The baseline only falls; the +# fetch, prepare and build paths of the process that draws the live region are not on it. +# The programs ninja starts (compiler supervisors, link-output and the other internal +# commands) write to their own standard error, which the build captures; they are listed. +set -u +cd "$(dirname "$0")/../.." + +baseline=.github/tools/stderr-writers.baseline +[ -f "$baseline" ] || { echo "::error::missing $baseline"; exit 1; } + +pattern='libc::stderr\(\)|std::cerr|[(,][[:space:]]*stderr[[:space:]]*[,)]|STDERR_FILENO' +current=$(grep -rnE "$pattern" src modules --include='*.cppm' --include='*.cpp' \ + | grep -vE '^(src/ui\.cppm|src/ui/[^:]*|modules/log/src/[^:]*|modules/[^/]+/tests/[^:]*):' \ + | grep -vE '^[^:]+:[0-9]+:[[:space:]]*//' \ + | cut -d: -f1 | sort | uniq -c | awk '{ print $2, $1 }') + +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 writes to standard error directly $n time(s); write through mcpp::ui (status, info, block, error) or mcpp::diag" + rc=1 + elif [ "$n" -gt "$allowed" ]; then + echo "::error::$file writes to standard error directly $n times, more than the $allowed of $baseline" + rc=1 + elif [ "$n" -lt "$allowed" ]; then + echo "::error::$file writes to standard error directly $n times, fewer than the $allowed of $baseline; lower its line" + rc=1 + fi +done <<< "$current" +while read -r file allowed; do + case "$file" in ''|'#'*) continue ;; esac + if ! grep -q "^$file " <<< "$current"; then + echo "::error::$file no longer writes to standard error directly; remove its line from $baseline" + rc=1 + fi +done < "$baseline" +[ "$rc" = 0 ] && echo "OK: standard error is written through mcpp.ui and mcpp.log, and $baseline is exact" +exit "$rc" diff --git a/.github/tools/stderr-writers.baseline b/.github/tools/stderr-writers.baseline new file mode 100644 index 000000000..24113631c --- /dev/null +++ b/.github/tools/stderr-writers.baseline @@ -0,0 +1,21 @@ +# One line per source file that writes to standard error without mcpp.ui or mcpp.log: its count +# (.github/tools/check_stderr_writers.sh). The numbers only fall. +src/build/execute.cppm 47 +src/build/schedule/compiler_transaction.cppm 1 +src/build/schedule/detach_codegen.cppm 41 +src/cli/cmd_build.cppm 56 +src/cli/cmd_cache.cppm 1 +src/cli/cmd_new.cppm 1 +src/cli/cmd_publish.cppm 4 +src/cli/cmd_registry.cppm 2 +src/cli/cmd_self.cppm 8 +src/cli/cmd_toolchain.cppm 1 +src/cli/cmd_xpkg.cppm 1 +src/cli.cppm 17 +src/config.cppm 3 +src/doctor.cppm 7 +src/fallback/xlings_binary.cppm 4 +src/main.cpp 1 +src/pack/distribution.cppm 5 +src/publish/pipeline.cppm 6 +src/run/run.cpp 6 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac22c0520..9b74b947f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,6 +214,9 @@ jobs: - name: Check that every warning and note goes through mcpp.diag run: bash .github/tools/check_diag_sink.sh + - name: Check that standard error is written through mcpp.ui and mcpp.log + run: bash .github/tools/check_stderr_writers.sh + - name: Check that the engine's sources name no more systems than the baseline run: python3 .github/tools/check_system_names.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d0d8a9d21..ebadcc6df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,23 @@ ## [Unreleased] +### Added + +- A platform of a descriptor's `xpm` table that refers to another — `macosx = { ref = "linux" }`, or + `inherits = "linux"` (xpackage V1) — holds the versions it does not state itself and that + platform's `deps` when it states none, as the installer reads it; versions every platform shares + are written once. `mcpp xpkg parse` refuses a reference to a platform the table has no block for + and a chain of references that returns to itself (SPEC-001 §10.5). + ### Fixed +- A version stated through a local table of its descriptor (`["1.2.1"] = versions["1.2.1"]`) is + read through the table. It was read as revision 0, so a package whose entry states revision 1 + was reinstalled by every build and shown as `Downloading`. A version written in a form mcpp does + not read has no revision rather than revision 0, and `mcpp xpkg parse` refuses it; a revision + mcpp reads differently from the installer is reported once as `fetch/revision-misread` + (SPEC-001 §10.5). + - Test planning refuses a test program whose executable would overwrite an executable target from the same package. The diagnostic names both programs and their shared path (mcpp#1028). diff --git a/docs/11-publishing-a-library.md b/docs/11-publishing-a-library.md index b91263f11..269a7f553 100644 --- a/docs/11-publishing-a-library.md +++ b/docs/11-publishing-a-library.md @@ -85,10 +85,35 @@ In `mcpplibs/mcpp-index`, `pkgs//.lua`: }, ``` -**In all three platform blocks** — `linux`, `macosx`, `windows`. A source -tarball is the same bytes on every platform, and an entry present in only one -of them fails on the others as "no such version", which reads like a typo in -the consumer's manifest. +**Once, for every platform.** A source tarball is the same bytes on every +platform, so the version is written in one platform's block and the other +platforms refer to that block: + +```lua +xpm = { + linux = { + ["0.0.48"] = { url = { GLOBAL = "…", CN = "…" }, sha256 = "…" }, + }, + macosx = { ref = "linux" }, + windows = { ref = "linux" }, +}, +``` + +A platform that refers to another — `ref = ""`, or +`inherits = ""`, the xpackage V1 platform reference — holds the +versions it does not state itself, and the other platform's `deps` when it +states none. Beside the reference a platform states only what is its own: +`deps = { … }`, or `deps = {}` for none. A version absent from a platform fails +there as "no such version", which reads like a typo in the consumer's manifest. + +mcpp reads the reference from 2026.12.4.1 on (SPEC-001 §10.5). An earlier +release reads a referring platform as the versions every block that states +versions has in common, which is the same set when one block states them. A +version's value is a table written in place, `["0.0.48"] = { … }`; a release +before 2026.12.4.1 reads a version stated through a local table, +`versions["0.0.48"]`, as revision 0. `mcpp xpkg parse` refuses a reference to a +platform the table has no block for, a chain of references that returns to a +platform it passed, and a version written in a form mcpp does not read. A target that is none of the three reads the blocks its row names, in order, and never the build machine's (2026.10.30.1+): @@ -101,8 +126,9 @@ and never the build machine's (2026.10.30.1+): | iOS | `ios`, then `macosx` | | bare metal (`-none-`) | `none` | -The first block present is the one read, both for the versions under `xpm` -and for the per-platform table of the `mcpp` segment. A library that builds +The first block present is the one read, together with the blocks it refers +to, for the versions under `xpm`; the per-platform table of the `mcpp` segment +is read from the first block present. A library that builds differently for the Web — without the `-pthread` its Linux block adds, say — gives it an `emscripten` block; one that builds for bare metal gives it a `none` block, and without one it has no version there. Before 2026.10.30.1 such diff --git a/docs/specs/README.md b/docs/specs/README.md index 1db188936..86ef10957 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -30,7 +30,7 @@ | 编号 | 标题 | 状态 | 最后修改 | 对应实现 | |---|---|---|---|---| -| [SPEC-001](package-identity.md) | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | 评审中 v1.13 | 2026-11-21 | mcpp >= 0.0.106;§3.5 与 §10.4 mcpp >= 2026.11.19.1;§4.5、§3.5 的 `installed_manifest` 与 §10.4 第 7 条 mcpp >= 2026.11.21.1 | +| [SPEC-001](package-identity.md) | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | 评审中 v1.14 | 2026-12-04 | mcpp >= 0.0.106;§3.5 与 §10.4 mcpp >= 2026.11.19.1;§4.5、§3.5 的 `installed_manifest` 与 §10.4 第 7 条 mcpp >= 2026.11.21.1;§10.5 mcpp >= 2026.12.4.1 | | [SPEC-002](target-side.md) | 目标侧模型与能力声明(`mcpp:` 保留命名空间、五层、三条规则、目标侧执行、一个进程一套 C++ 运行时) | 评审中 v1.13 | 2026-11-27 | mcpp >= 2026.8.24.2;§2.4 与 §6 mcpp >= 2026.10.24.1;§2.2 的对象形式与 §7 mcpp >= 2026.10.26.1;§2.5 与 §3.8 mcpp >= 2026.11.10.1;§3.6 以目标的解析判断 mcpp >= 2026.11.19.1;§3.9 与 §3.10 mcpp >= 2026.11.23.1;§3.11 mcpp >= 2026.11.27.1 | | [SPEC-003](exit-codes.md) | 退出码契约(分类、语义、稳定性承诺) | 评审中 v1.2 | 2026-10-26 | mcpp >= 2026.9.1.1;`5` 与信号 mcpp >= 2026.10.26.1 | | [SPEC-004](manifest-semantics.md) | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | 草案 v1.30 | 2026-11-27 | 条件化形状 mcpp >= 2026.8.29.1;目标轴 mcpp >= 2026.9.6.4;`linkage` 默认值 mcpp >= 2026.9.15.2;链接 flag 的词读法 mcpp >= 2026.9.26.2;条件化的 `dialect_cxxflags` 与 `-p` 的包身份 mcpp >= 2026.9.28.1;条件表按具体程度生效 mcpp >= 2026.9.28.2;平台前缀规约 mcpp >= 2026.10.5.1;根包的继承、根位置的 profile、链接 flag 的作用域、链接期优化与导出发现 mcpp >= 2026.10.5.2;架构段的 `x86` 即 `i686` mcpp >= 2026.10.5.3;前缀即语义与工作空间层 mcpp >= 2026.10.10.1;依赖的库与配置(§12) mcpp >= 2026.10.11.1;值的四档层次与 `run_under` mcpp >= 2026.10.24.1;§12 第 3 条一个程序一个版本 mcpp >= 2026.11.19.1;§9 第 21 至 23 条与 §16 mcpp >= 2026.11.21.1;v1.29 条款 mcpp >= 2026.11.23.1;§9 第 24 条、§11 第 7 与 8 条、§17 mcpp >= 2026.11.27.1 | diff --git a/docs/specs/package-identity.md b/docs/specs/package-identity.md index a68ae5d85..972c94780 100644 --- a/docs/specs/package-identity.md +++ b/docs/specs/package-identity.md @@ -5,8 +5,8 @@ | **规范编号** | SPEC-001 | | **标题** | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | | **状态** | **评审中(Review)** —— 已实现 | -| **版本** | 1.13 | -| **最后修改** | 2026-11-21 | +| **版本** | 1.14 | +| **最后修改** | 2026-12-04 | | **最低实现版本** | 描述符身份:mcpp **0.0.106**;精确 selector:mcpp **2026.8.10.1**(xlings >= 0.4.69) | | **作者/维护** | mcpp-community | | **相关设计文档** | `.agents/docs/2026-06-20-package-resolution-architecture.md` §4
`.agents/docs/2026-06-26-identity-first-resolution-no-filename.md`
`.agents/docs/2026-07-25-issue278-descriptor-name-form-canonicalization-design.md`
`.agents/docs/2026-07-25-name-namespace-bidirectional-verification-report.md`
`.agents/docs/2026-07-25-name-namespace-canonical-implementation-spec.md` | @@ -616,12 +616,34 @@ mcpp 侧的使用: 缓存以修改时间命名 `path` 包的树。2026.11.19.1 的条目收入根目录之下的每个单元,两个成员的 `src/main.cpp` 落在同一个 地址 `obj/src/main.o`,自干净的 target 目录构建时一个成员链接了另一个成员的目标文件(mcpp#979)。 +### 10.5 版本表的读法(mcpp 2026.12.4.1+) + +mcpp 不运行描述符,读的是 `xpm` 表的一个声明式子集;安装器(xlings 经 libxpkg)运行描述符。同一个条目的两种 +读法**必须**一致,否则 mcpp 判定的修订与安装器记录的修订不同,每次构建都重装该包。 + +1. **版本的值。** 一个版本的值是就地写出的表;或是对描述符顶层 `local` 表的引用——整张表 + (`["2.0.0"] = snapshot`),或其中以字面键取出的一项(`["1.2.1"] = versions["1.2.1"]`)——按所引用的表读取。 + 其他写法(函数调用、运算)是**未读**的:该版本的修订是未知,**禁止**当作 0;依赖的判定只依据载荷的文件, + `mcpp xpkg parse` 拒绝该描述符,写出就地写表的改法。 +2. **平台引用。** 平台表中的 `inherits = "<平台>"` 或 `ref = "<平台>"`(xpackage V1,libxpkg 0.0.64)是对另一 + 平台表的引用,`inherits` 优先。一个平台持有自身未陈述的版本(自身的在前,被引用表的在后),并在自身未陈述 + `deps` 时持有被引用表的 `deps`;`deps = {}` 陈述为无。引用链被依次跟随;指向已经过的平台或 `xpm` 中没有表的 + 平台时,链在此结束——与安装器相同——且 `mcpp xpkg parse` 拒绝该描述符并写出原因。 +3. **读法不一致的报告。** 一次安装之后,mcpp 读到的修订与安装器为该载荷记录的修订不同时,mcpp 记录这一对数值 + (`<元数据缓存>/revision-reads/`),**必须**作为降级报告(`fetch/revision-misread`,写出两个数值、影响与改法), + 之后的构建对同一对数值不再重装;两者重新一致时记录被移除。 + +**已实现**(mcpp 2026.12.4.1)。此前第 1 条的引用读作修订 0:修订为 1 的条目每次构建都重装一次,并对已安装的包 +显示 `Downloading`(2026-12-04 测得);第 2 条的引用平台按 2026.11.9.1 起的规则读作所有陈述版本的块共有的版本, +只有一个块陈述版本时与安装器一致,另一平台陈述不同版本时该平台没有版本;第 3 条不存在。 + --- ## 11. 变更记录 | 版本 | 日期 | 变更 | |---|---|---| +| 1.14 | 2026-12-04 | 新增 §10.5:版本表的读法——经局部表引用的版本按所引用的表读取,未读的写法修订未知并被 `mcpp xpkg parse` 拒绝;平台引用 `ref`/`inherits` 与安装器同样解析;读到的修订与安装器记录不一致时报告一次(mcpp 2026.12.4.1) | | 1.13 | 2026-11-21 | §3.5 新增已安装版本的清单经 `installed_manifest` 读取,构建与包特性的查询共用(mcpp#992);§10.4 新增第 7 条:条目只按它编译时所读的接口提供(mcpp 2026.11.21.1) | | 1.12 | 2026-11-21 | 新增 §4.5:命令行中 `@` 的读法——写出的前缀、`@=` 的精确键、带运算符的要求;§4.4 的模板表与 §5.5 的命令行引用按它陈述(mcpp 2026.11.21.1) | | 1.11 | 2026-11-20 | §10.4 新增第 6 条:条目只含包自己的单元,嵌套于依赖树中的包(如成员的构建程序导入仓库自身包的 workspace)的单元属于该包,在原处构建(mcpp 2026.11.20.1,mcpp#979) | diff --git a/docs/zh/11-publishing-a-library.md b/docs/zh/11-publishing-a-library.md index 3da0726e9..ab724c393 100644 --- a/docs/zh/11-publishing-a-library.md +++ b/docs/zh/11-publishing-a-library.md @@ -78,9 +78,26 @@ cmp cn.tar.gz pkg-0.0.48.tar.gz # must be identical, not merely present }, ``` -**三个平台块都要写** —— `linux`、`macosx`、`windows`。源码 tarball 在每个平台上是 -同样的字节;只写在其中一个平台块里,会在另外两个平台上以 `no such version` 失败, -读起来像是消费方 manifest 里打错了字。 +**为所有平台写一次。** 源码 tarball 在每个平台上是同样的字节,因此版本写在一个平台的块里,其余平台引用该块: + +```lua +xpm = { + linux = { + ["0.0.48"] = { url = { GLOBAL = "…", CN = "…" }, sha256 = "…" }, + }, + macosx = { ref = "linux" }, + windows = { ref = "linux" }, +}, +``` + +引用另一平台的平台——`ref = ""` 或 `inherits = ""`,即 xpackage V1 的平台引用——持有自身 +未陈述的版本,并在自身未陈述 `deps` 时持有被引用平台的 `deps`。引用旁只陈述本平台独有的内容:`deps = { … }`, +没有时写 `deps = {}`。某平台缺少的版本会在该平台上以 `no such version` 失败,读起来像是消费方 manifest 里打错了字。 + +mcpp 自 2026.12.4.1 起读取平台引用(SPEC-001 §10.5)。更早的版本把引用平台读作所有陈述版本的块共有的版本, +只有一个块陈述版本时二者是同一组。版本的值是就地写出的表 `["0.0.48"] = { … }`;2026.12.4.1 之前的版本把经局部表 +陈述的版本 `versions["0.0.48"]` 读作修订 0。`mcpp xpkg parse` 拒绝指向表中没有块的平台的引用、回到已经过的平台 +的引用链,以及 mcpp 不读的版本写法。 不属于这三者的目标,按其目标行列出的块依次读取,与构建机无关(2026.10.30.1+): @@ -92,7 +109,7 @@ cmp cn.tar.gz pkg-0.0.48.tar.gz # must be identical, not merely present | iOS | `ios`,其次 `macosx` | | 裸机(`-none-`) | `none` | -读取的是第一个存在的块,`xpm` 下的版本与 `mcpp` 段的按平台表都如此。一个为 Web 构建时有所不同的库——例如不要 +`xpm` 下的版本读取第一个存在的块及其引用的块;`mcpp` 段的按平台表读取第一个存在的块。一个为 Web 构建时有所不同的库——例如不要 Linux 块添加的 `-pthread`——写一个 `emscripten` 块;为裸机构建的库写一个 `none` 块,没有它就在裸机上没有版本。 2026.10.30.1 之前,这类目标读构建机的块,同一个项目在 Linux 与 Windows 机器上会得到不同的标志。 diff --git a/modules/buildopt/src/registry.cppm b/modules/buildopt/src/registry.cppm index 28177adef..d09b8f58e 100644 --- a/modules/buildopt/src/registry.cppm +++ b/modules/buildopt/src/registry.cppm @@ -31,7 +31,9 @@ import mcpp.invocation; export namespace mcpp::buildopt::registry { enum class Level { Exact, Conditional, Shape, Source }; -enum class Seam { Source, Graph, Edge }; +// Fetch: how dependencies reach the home. Run: how two commands share a +// configuration. Neither shapes a graph, so neither is part of its identity. +enum class Seam { Source, Graph, Edge, Fetch, Run }; constexpr std::string_view to_string(Level l) { switch (l) { @@ -47,6 +49,8 @@ constexpr std::string_view to_string(Seam s) { case Seam::Source: return "source"; case Seam::Graph: return "graph"; case Seam::Edge: return "edge"; + case Seam::Fetch: return "fetch"; + case Seam::Run: return "run"; } return "edge"; } @@ -78,8 +82,10 @@ inline constexpr std::string_view kGcmLocations = "gcm-locations"; inline constexpr std::string_view kScanPass = "scan-pass"; inline constexpr std::string_view kSplitSchedule = "split-schedule"; inline constexpr std::string_view kPrivateFragment = "private-fragment"; +inline constexpr std::string_view kBatchFetch = "batch-fetch"; +inline constexpr std::string_view kPlanLocks = "plan-locks"; -inline constexpr std::array kEntries{{ +inline constexpr std::array kEntries{{ {kKeepBmi, "a BMI compiled to the bytes it had is kept, and its importers are not compiled", Seam::Edge, Level::Exact, true, {}, {}, {}}, {kKeepObject, "an object compiled to the bytes it had is kept, and nothing is archived or linked for it", @@ -96,6 +102,15 @@ inline constexpr std::array kEntries{{ {kPrivateFragment, "a private module fragment is built as a unit of its own, so an edit of it reaches no importer", Seam::Source, Level::Source, true, "[build] private_fragment", "MCPP_PRIVATE_FRAGMENT", "unit | conservative | as-written", "as-written", "conservative"}, + // Design 2026-11-27 §3.11.2, point 9: the payloads are the same, fetched + // in fewer starts of the provider and connections. + {kBatchFetch, "the dependencies one step of the walk knows are fetched by one call of the provider", + Seam::Fetch, Level::Conditional, true, "[build] batch_fetch", "MCPP_BATCH_FETCH", "waves | each", "each"}, + // Design 2026-11-27 §3.7.1: a plan's lock is its selection's and the + // configuration's is shared, so commands that select different members + // build at once. It ran on every host before its default (SPEC-019 §3). + {kPlanLocks, "commands that select different members of a configuration build at once; a unit is protected by its publication", + Seam::Run, Level::Shape, true, "[build] plan_locks", "MCPP_PLAN_LOCKS", "selection | configuration", "configuration"}, }}; constexpr const Entry* find(std::string_view id) { @@ -121,6 +136,13 @@ std::string stated_shape(); // The table as `mcpp explain` and the README print it: one row an entry. std::string table(); +// Whether an entry with a switch of two values is on: `MCPP_BUILDOPT=off`, or +// its environment variable, or `stated` (its manifest key) naming the entry's +// `check` value turns it off; any other value keeps the default. `onInvalid` +// hears a value the entry does not have. +bool on(std::string_view id, std::string_view stated, + const std::function& onInvalid = {}); + } // namespace mcpp::buildopt::registry namespace mcpp::buildopt::registry { @@ -130,10 +152,24 @@ bool standard_only() { return stated && *stated == "off"; } +bool on(std::string_view id, std::string_view stated, + const std::function& onInvalid) { + const Entry* e = find(id); + if (!e) return false; + if (standard_only()) return false; + std::string v(stated); + if (auto env = mcpp::invocation::get(e->env)) v = *env; + if (v.empty()) return e->byDefault; + if (v == e->check) return false; + if (v == e->values.substr(0, e->values.find(' '))) return true; + if (onInvalid) onInvalid(v); + return e->byDefault; +} + std::string stated_shape() { std::string shape; for (auto const& e : kEntries) - if (e.seam != Seam::Edge && !e.env.empty()) + if ((e.seam == Seam::Source || e.seam == Seam::Graph) && !e.env.empty()) if (auto v = mcpp::invocation::get(e.env)) shape += std::format("{}={};", e.env, *v); if (auto v = mcpp::invocation::get(kStandardEnv)) shape += std::format("{}={};", kStandardEnv, *v); return shape; diff --git a/modules/manifest/src/key_registry.cppm b/modules/manifest/src/key_registry.cppm index 310946a00..72d2447fb 100644 --- a/modules/manifest/src/key_registry.cppm +++ b/modules/manifest/src/key_registry.cppm @@ -53,6 +53,12 @@ inline constexpr KeyClass kKeyRegistry[] = { {"build", "allow_host_tools", KeyScope::Configuration, KeyMerge::Scalar, false, false}, {"build", "offline", KeyScope::Configuration, KeyMerge::Scalar, false, false}, {"build", "bmi_schedule", KeyScope::Configuration, KeyMerge::Scalar, false, false}, + // Two entries of the build optimizations (SPEC-019): dependencies fetched + // by waves, and a plan's lock that is its selection's. + {"build", "batch_fetch", KeyScope::Configuration, KeyMerge::Scalar, false, false}, + {"build", "plan_locks", KeyScope::Configuration, KeyMerge::Scalar, false, false}, + // The longest a command waits for a lock another process holds (SPEC-011 §2). + {"build", "lock_wait", KeyScope::Configuration, KeyMerge::Scalar, false, false}, // The memory a compiler may start below (SPEC-004 §9, design 2026-11-20 §5.5, mcpp#802). {"build", "memory_threshold", KeyScope::Configuration, KeyMerge::Scalar, false, false}, {"build", "build_program_timeout", KeyScope::Package, KeyMerge::Scalar, false, false}, diff --git a/modules/manifest/src/toml.cppm b/modules/manifest/src/toml.cppm index c1b82a619..00a4ced97 100644 --- a/modules/manifest/src/toml.cppm +++ b/modules/manifest/src/toml.cppm @@ -3372,6 +3372,9 @@ std::expected parse_document(const t::Document& documen // the whole manifest unloadable. (A published package carrying an unknown // key must never break an older mcpp — same rule the dependency keys follow.) if (auto v = doc->get_string("build.bmi_schedule")) m.buildConfig.bmiSchedule = *v; + if (auto v = doc->get_string("build.batch_fetch")) m.buildConfig.batchFetch = *v; + if (auto v = doc->get_string("build.plan_locks")) m.buildConfig.planLocks = *v; + if (auto v = doc->get_string("build.lock_wait")) m.buildConfig.lockWait = *v; if (auto v = doc->get_string("build.memory_threshold")) m.buildConfig.memoryThreshold = *v; else if (auto n = doc->get_int("build.memory_threshold")) m.buildConfig.memoryThreshold = std::to_string(*n); if (auto v = doc->get_string("build.private_fragment")) m.buildConfig.privateFragment = *v; diff --git a/modules/manifest/src/types.cppm b/modules/manifest/src/types.cppm index f261e136e..acd0645d7 100644 --- a/modules/manifest/src/types.cppm +++ b/modules/manifest/src/types.cppm @@ -1053,6 +1053,15 @@ struct BuildConfig : BuildInputs { // compiler doing the build, and resolving it at parse time would freeze one // machine's answer into a manifest that travels. std::string bmiSchedule; + // `[build] batch_fetch` ("waves" | "each") and `[build] plan_locks` + // ("selection" | "configuration"): two entries of the build optimizations + // (SPEC-019, mcpp.buildopt.registry), each with its environment variable. + std::string batchFetch; + std::string planLocks; + // `[build] lock_wait`: the longest a command waits for a lock another + // process holds ("30s", "10m", "0" for not at all); empty: no bound + // (SPEC-011 §2). `--lock-wait` and MCPP_LOCK_WAIT state it for one run. + std::string lockWait; // `[build] memory_threshold` -- the memory the system must have available // before a compiler starts ("2GiB", "512MiB", or bytes; design 2026-11-20 // §5.5, mcpp#802). Below it the compiler waits for one already running to diff --git a/modules/manifest/src/xpkg.cppm b/modules/manifest/src/xpkg.cppm index 6223a8644..1f4cb5eda 100644 --- a/modules/manifest/src/xpkg.cppm +++ b/modules/manifest/src/xpkg.cppm @@ -40,8 +40,14 @@ struct XpkgVersionEntry { std::string sha256; // payload digest when declared at entry level // The packaging revision of this version's payload (xpkg V2 `revision`), // 0 when the entry states none or states something that is not a - // non-negative integer -- the reference implementation's reading. - int revision = 0; + // non-negative integer -- the reference implementation's reading. None when + // the version's value is written in a form this reader does not read, so + // that no caller takes the absence for revision 0: the installer, which runs + // the descriptor, records the real one. + std::optional revision = 0; + // The version's value is a form this reader does not read (`mcpp xpkg + // parse` reports it); `revision` is then none and `sha256` empty. + bool unread = false; }; // Extract the version entries for `platform` (e.g. "linux", "macosx", @@ -54,6 +60,13 @@ std::vector list_xpkg_version_entries(std::string_view luaContent, const mcpp::toolchain::platform::PlatformKey& platform); +// WHAT A PLATFORM REFERENCE NAMES WRONG: a block that refers to a platform +// xpm has no table for, or a chain of references that returns to a platform +// it passed. Both end the chain for every reader, the installer included, so +// the referring platform silently holds only what it declares; a lint +// (`mcpp xpkg parse`) refuses them. One sentence each, empty when none. +std::vector xpkg_platform_reference_problems(std::string_view luaContent); + // Keys only, aliases included — the shape every caller that just wants to show // or existence-check the published versions wants. std::vector @@ -1117,6 +1130,53 @@ struct LuaScan { return std::nullopt; } + // `local = { ... }` at the top level of the descriptor, as its braces. + std::optional> local_table(std::string_view name) const { + for (std::size_t from = 0;;) { + const auto at = word_at_lhs(name, from); + if (at == std::string_view::npos) return std::nullopt; + std::size_t b = at; + while (b > 0 && (text[b - 1] == ' ' || text[b - 1] == '\t')) --b; + const bool declared = b >= 5 && text.substr(b - 5, 5) == "local" + && (b == 5 || !std::isalnum(static_cast(text[b - 6]))); + if (declared && depth_at(0, at) == 0) { + const auto o = open_brace(at); + std::size_t q = at + name.size(); + while (q < o && (text[q] == ' ' || text[q] == '\t' || text[q] == '\n' || text[q] == '\r' || text[q] == '=')) ++q; + if (o == std::string_view::npos || q != o) return std::nullopt; + const auto e = table_end(o); + if (e == std::string_view::npos) return std::nullopt; + return std::pair{o, e}; + } + from = at + name.size(); + } + } + + // The table `[""] = { ... }` written directly inside [open, end]. The + // key is read from `original`, where the sanitized text blanked it. + std::optional> + keyed_table_in(std::string_view original, std::string_view key, std::size_t open, std::size_t end) const { + for (std::size_t q = open + 1; q < end; ++q) { + if (text[q] != '[') continue; + std::size_t r = q + 1; + while (r < end && (text[r] == ' ' || text[r] == '\t')) ++r; + if (r >= end || (text[r] != '"' && text[r] != '\'')) continue; + const char quote = text[r]; + const std::size_t start = ++r; + while (r < end && text[r] != quote && text[r] != '\n') ++r; + if (r >= end || text[r] != quote || original.substr(start, r - start) != key) continue; + if (depth_at(open, q) != 1) continue; + std::size_t v = r + 1; + while (v < end && (text[v] == ' ' || text[v] == '\t' || text[v] == ']' || text[v] == '=' + || text[v] == '\n' || text[v] == '\r')) ++v; + if (v >= end || text[v] != '{') return std::nullopt; + const auto e = table_end(v); + if (e == std::string_view::npos || e > end) return std::nullopt; + return std::pair{v, e}; + } + return std::nullopt; + } + // How deep `at` is below the table opened at `open` (1: directly inside it). int depth_at(std::size_t open, std::size_t at) const { int depth = 0; @@ -1127,20 +1187,62 @@ struct LuaScan { return depth; } - // `xpm.`, the platform being the first of the axis's keys the - // xpm table has a block for. - std::optional> - platform_table(const mcpp::toolchain::platform::PlatformKey& platformAxis) const { + // The `xpm = { ... }` table, as its braces. + std::optional> xpm_table() const { const auto xpm_pos = word_at_lhs("xpm", 0); if (xpm_pos == std::string_view::npos) return std::nullopt; const auto xpm_open = open_brace(xpm_pos); if (xpm_open == std::string_view::npos) return std::nullopt; const auto xpm_end = table_end(xpm_open); if (xpm_end == std::string_view::npos) return std::nullopt; + return std::pair{xpm_open, xpm_end}; + } + + // `xpm.`, the platform being the first of the axis's keys the + // xpm table has a block for. + std::optional> + platform_table(const mcpp::toolchain::platform::PlatformKey& platformAxis) const { + const auto xpm = xpm_table(); + if (!xpm) return std::nullopt; for (auto const& key : platformAxis.keys()) - if (auto t = table_in(key, xpm_open, xpm_end)) return t; + if (auto t = table_in(key, xpm->first, xpm->second)) return t; return std::nullopt; } + + // THE PLATFORM REFERENCE (xpackage V1; libxpkg 0.0.64): a block that + // writes `inherits = ""`, or `ref = ""`, holds what it + // does not declare itself from that platform's block -- the versions it + // lacks, and its `deps` when it has none. One artifact for every system + // is written once this way. The blocks the axis reads, its own first, then + // each platform referred to in turn; a reference to a platform xpm has no + // block for, or back into the chain, ends it, as it does for the + // installer (`platform_reference_problems` names both to a lint). + std::vector> + platform_chain(std::string_view original, const mcpp::toolchain::platform::PlatformKey& platformAxis) const { + std::vector> chain; + const auto xpm = xpm_table(); + if (!xpm) return chain; + std::vector seen; + for (auto const& key : platformAxis.keys()) + if (table_in(key, xpm->first, xpm->second)) { seen.push_back(key); break; } + while (!seen.empty()) { + const auto block = table_in(seen.back(), xpm->first, xpm->second); + if (!block) break; + chain.push_back(*block); + const auto parent = referred_platform(original, *block); + if (parent.empty() || std::ranges::contains(seen, parent)) break; + seen.push_back(parent); + } + return chain; + } + + // The platform a block refers to, or empty. `inherits` is read first, as + // the installer reads it. + std::string referred_platform(std::string_view original, std::pair block) const { + const auto body = original.substr(block.first + 1, block.second - block.first - 1); + auto parent = top_level_string_value_for_key(body, "inherits"); + return parent.empty() ? top_level_string_value_for_key(body, "ref") : parent; + } }; std::vector @@ -1155,9 +1257,8 @@ entries_of_first_block(std::string_view luaContent, std::vector versions; auto find_table_end = [&](std::size_t open) { return scan.table_end(open); }; - const auto plat = scan.platform_table(platformAxis); - if (!plat) return versions; - const auto [plat_open, plat_end] = *plat; + const auto chain = scan.platform_chain(luaContent, platformAxis); + if (chain.empty()) return versions; // Does this entry body declare `ref = ...` at its own top level? Nested // tables are skipped so a `url = { ref = ... }` (no such shape today, but @@ -1188,53 +1289,126 @@ entries_of_first_block(std::string_view luaContent, }; // Inside platform table: scan for ["X.Y.Z"] = { ... }, skipping each - // entry's own body so nested bracket keys are not read as versions. - std::size_t q = plat_open + 1; - while (q < plat_end) { - if (text[q] != '[') { ++q; continue; } - std::size_t r = q + 1; - while (r < plat_end && (text[r] == ' ' || text[r] == '\t')) ++r; - if (r >= plat_end || (text[r] != '"' && text[r] != '\'')) { ++q; continue; } - const char quote = text[r]; - ++r; - const std::size_t key_start = r; - while (r < plat_end && text[r] != quote && text[r] != '\n') ++r; - if (r >= plat_end || text[r] != quote) { ++q; continue; } - XpkgVersionEntry e; - e.version = std::string(luaContent.substr(key_start, r - key_start)); - - // Past the closing quote: `] = `. Only a table value can be an - // alias, and only a table value has a body worth skipping. - std::size_t v = r + 1; - auto skip_blank = [&] { - while (v < plat_end && (text[v] == ' ' || text[v] == '\t' || - text[v] == '\n' || text[v] == '\r')) ++v; + // entry's own body so nested bracket keys are not read as versions. A + // block referred to adds the versions the blocks before it lack. + for (std::size_t link = 0; link < chain.size(); ++link) { + const auto [plat_open, plat_end] = chain[link]; + const std::size_t inherited = versions.size(); + auto declared = [&](std::string_view version) { + return link > 0 && std::ranges::contains( + std::span(versions).first(inherited), version, &XpkgVersionEntry::version); }; - skip_blank(); - if (v < plat_end && text[v] == ']') ++v; - skip_blank(); - if (v < plat_end && text[v] == '=') ++v; - skip_blank(); - if (v < plat_end && text[v] == '{') { - const auto entry_end = find_table_end(v); - if (entry_end != std::string_view::npos && entry_end <= plat_end) { - e.alias = entry_is_alias(v, entry_end); - e.sha256 = top_level_string_value_for_key( - luaContent.substr(v + 1, entry_end - v - 1), "sha256"); - e.revision = top_level_nonneg_int_for_key( - luaContent.substr(v + 1, entry_end - v - 1), "revision"); - versions.push_back(std::move(e)); - q = entry_end + 1; + std::size_t q = plat_open + 1; + while (q < plat_end) { + if (text[q] != '[') { ++q; continue; } + std::size_t r = q + 1; + while (r < plat_end && (text[r] == ' ' || text[r] == '\t')) ++r; + if (r >= plat_end || (text[r] != '"' && text[r] != '\'')) { ++q; continue; } + const char quote = text[r]; + ++r; + const std::size_t key_start = r; + while (r < plat_end && text[r] != quote && text[r] != '\n') ++r; + if (r >= plat_end || text[r] != quote) { ++q; continue; } + XpkgVersionEntry e; + e.version = std::string(luaContent.substr(key_start, r - key_start)); + + // Past the closing quote: `] = `. Only a table value can be an + // alias, and only a table value has a body worth skipping. + std::size_t v = r + 1; + auto skip_blank = [&] { + while (v < plat_end && (text[v] == ' ' || text[v] == '\t' || + text[v] == '\n' || text[v] == '\r')) ++v; + }; + skip_blank(); + if (v < plat_end && text[v] == ']') ++v; + skip_blank(); + if (v < plat_end && text[v] == '=') ++v; + skip_blank(); + if (v < plat_end && text[v] == '{') { + const auto entry_end = find_table_end(v); + if (entry_end != std::string_view::npos && entry_end <= plat_end) { + e.alias = entry_is_alias(v, entry_end); + e.sha256 = top_level_string_value_for_key( + luaContent.substr(v + 1, entry_end - v - 1), "sha256"); + e.revision = top_level_nonneg_int_for_key( + luaContent.substr(v + 1, entry_end - v - 1), "revision"); + if (!declared(e.version)) versions.push_back(std::move(e)); + q = entry_end + 1; + continue; + } + } + // A VERSION STATED THROUGH A LOCAL TABLE (`versions["1.2.1"]`, or the + // table's own name), a form the index wrote for 28 packages: read + // through the reference. Before, it read as revision 0 while the + // installer, which runs the descriptor, recorded 1, and every build + // reinstalled the package. Any other form is unread, never revision 0. + e.revision = std::nullopt; + e.unread = true; + auto ident = [&](std::size_t at) { + std::size_t n = at; + while (n < plat_end && (std::isalnum(static_cast(text[n])) || text[n] == '_')) ++n; + return n; + }; + if (v < plat_end && (std::isalpha(static_cast(text[v])) || text[v] == '_')) { + const std::size_t name_end = ident(v); + std::size_t w = name_end; + while (w < plat_end && (text[w] == ' ' || text[w] == '\t')) ++w; + std::optional> body = scan.local_table(text.substr(v, name_end - v)); + std::size_t after = name_end; + if (body && w < plat_end && text[w] == '[') { + std::size_t k = w + 1; + while (k < plat_end && (text[k] == ' ' || text[k] == '\t')) ++k; + const char quote = k < plat_end ? text[k] : '\0'; + std::size_t kend = quote == '"' || quote == '\'' ? k + 1 : plat_end; + while (kend < plat_end && text[kend] != quote) ++kend; + body = kend < plat_end + ? scan.keyed_table_in(luaContent, luaContent.substr(k + 1, kend - k - 1), body->first, body->second) + : std::nullopt; + after = kend + 1; + } + if (body) { + const auto [o, end] = *body; + e.alias = entry_is_alias(o, end); + e.sha256 = top_level_string_value_for_key(luaContent.substr(o + 1, end - o - 1), "sha256"); + e.revision = top_level_nonneg_int_for_key(luaContent.substr(o + 1, end - o - 1), "revision"); + e.unread = false; + } + if (!declared(e.version)) versions.push_back(std::move(e)); + q = after; continue; } + if (!declared(e.version)) versions.push_back(std::move(e)); + q = r + 1; } - versions.push_back(std::move(e)); - q = r + 1; } return versions; } } // namespace +std::vector xpkg_platform_reference_problems(std::string_view luaContent) { + std::vector out; + const auto sanitized = strip_lua_comments_and_strings(luaContent); + const LuaScan scan{ sanitized }; + const auto xpm = scan.xpm_table(); + if (!xpm) return out; + for (auto os : mcpp::toolchain::platform::xpkg_platforms) { + std::vector seen{ std::string(os) }; + auto block = scan.table_in(os, xpm->first, xpm->second); + std::string problem; + while (block && problem.empty()) { + const auto parent = scan.referred_platform(luaContent, *block); + if (parent.empty()) break; + if (std::ranges::contains(seen, parent)) + problem = std::format("platform '{}' refers to '{}', which refers back to it", seen.back(), parent); + else if (!(block = scan.table_in(parent, xpm->first, xpm->second))) + problem = std::format("platform '{}' refers to '{}', which xpm has no table for", seen.back(), parent); + seen.push_back(parent); + } + if (!problem.empty() && !std::ranges::contains(out, problem)) out.push_back(std::move(problem)); + } + return out; +} + std::vector list_xpkg_versions(std::string_view luaContent, const mcpp::toolchain::platform::PlatformKey& platformAxis) { @@ -1250,9 +1424,10 @@ xpkg_runtime_deps(std::string_view luaContent, std::vector out; const auto sanitized = strip_lua_comments_and_strings(luaContent); const LuaScan scan{ sanitized }; - const auto plat = scan.platform_table(platformAxis); - if (!plat) return out; - auto list = scan.table_in("deps", plat->first, plat->second); + // A block without `deps` takes the ones of the block it refers to. + std::optional> list; + for (auto const& block : scan.platform_chain(luaContent, platformAxis)) + if ((list = scan.table_in("deps", block.first, block.second))) break; if (!list) return out; if (auto runtime = scan.table_in("runtime", list->first, list->second)) list = runtime; // The strings directly inside the list; a nested table (`build = {...}`) diff --git a/src/build/prepare/graph.cpp b/src/build/prepare/graph.cpp index 6f78961cd..83992a2fd 100644 --- a/src/build/prepare/graph.cpp +++ b/src/build/prepare/graph.cpp @@ -2217,6 +2217,7 @@ std::expected phase4b_graph_worklist(PrepareState& state) { state.laterWaves.erase(next); continue; } + if (state.prefetchPending) state.prefetchPending(); WorklistItemCtx ctx; ctx.item = std::move(state.worklist.front()); state.worklist.pop_front(); diff --git a/src/build/prepare/graph_load.cpp b/src/build/prepare/graph_load.cpp index 910ad97ef..bbd777a2e 100644 --- a/src/build/prepare/graph_load.cpp +++ b/src/build/prepare/graph_load.cpp @@ -32,7 +32,9 @@ import mcpp.build.build_program; import mcpp.build.backend; // BuildOptions for the tool sub-build import mcpp.build.ninja; // make_ninja_backend — driving that sub-build import mcpp.config; +import mcpp.buildopt.registry; // batch-fetch: whether the walk fetches by waves import mcpp.home.files; // the home's install turn +import mcpp.toolchain.fingerprint; // hash_string: a stable key for a payload's record import mcpp.fetcher; import mcpp.pm.package_fetcher; // the offline refusals every install path says alike import mcpp.fetcher.progress; @@ -733,6 +735,10 @@ struct LoadVersionDepCtx { bool useProjectEnv = false; std::optional luaContent; std::optional installed; + // The revision this reader read of the entry (none: a form it does not + // read), and the one a payload about to be replaced recorded. + std::optional recipeRevision; + std::optional reinstallFrom; }; // The body of the `readLuaContent` closure the single-function version of @@ -774,6 +780,65 @@ step4a_find_raw_installed(PrepareState& state, LoadVersionDepCtx& ctx) { return fetcher.install_path(ctx.ns, ctx.shortName, ctx.version); } +// THE READER AND THE INSTALLER DISAGREEING ABOUT A REVISION (design +// 2026-11-27 §3.11.2, point 2). Right after an install the two read the same +// entry, so a difference is the reader's misreading, not a change. It is +// recorded in the home, keyed by the payload and the two numbers, so that the +// next build that reads the same pair takes the payload as current instead of +// reinstalling it again; a descriptor that later changes its revision reads a +// different pair and is reinstalled once. +static std::filesystem::path disagreement_record(const mcpp::config::GlobalConfig& cfg, + const std::filesystem::path& payload) { + const auto spelled = payload.lexically_normal().u8string(); + return cfg.metaCacheDir / "revision-reads" + / mcpp::toolchain::hash_string(std::string_view(reinterpret_cast(spelled.data()), spelled.size())); +} + +static bool known_disagreement(const mcpp::config::GlobalConfig& cfg, const std::filesystem::path& payload, + int read, int installed) { + const auto text = mcpp::home::read_whole(disagreement_record(cfg, payload)); + return text && *text == std::format("{} {}\n", read, installed); +} + +static void check_read_revision(PrepareState& state, LoadVersionDepCtx& ctx) { + if (!ctx.installed || !ctx.recipeRevision) return; + const auto installed = mcpp::provider::revision_of(*ctx.installed); + auto cfg = state.get_cfg(true); + if (!installed || !cfg) return; + const auto record = disagreement_record(**cfg, *ctx.installed); + if (*installed == *ctx.recipeRevision) { + std::error_code ec; + std::filesystem::remove(record, ec); + return; + } + std::error_code ec; + std::filesystem::create_directories(record.parent_path(), ec); + if (!mcpp::home::write_replacing(record, std::format("{} {}\n", *ctx.recipeRevision, *installed))) return; + mcpp::diag::degraded("fetch/revision-misread", + std::format("{} v{}: this mcpp read revision {} of the index entry, and the installer recorded {} " + "for the payload it just installed from the same entry", + ctx.depName, ctx.version, *ctx.recipeRevision, *installed), + "the revision of this entry is not taken into account: the payload is judged by its files, " + "and a later change of the entry's revision may not reinstall it", + "write the entry's version as a table in place, or update mcpp"); +} + +// THE INSTALL HOOK'S ENVIRONMENT (#613) for the length of one call of the +// provider, under the names and the rule a build program gets +// (`install_hook_env`): one call of one dependency, or a wave. +struct InstallHookScope { + std::vector> vars; + explicit InstallHookScope(PrepareState& state) { + mcpp::build::BuildProgramEnv hookEnv; + fill_target_build_env(hookEnv, *state.m, state.tc ? &*state.tc : nullptr, + state.cfg_opt ? &*state.cfg_opt : nullptr); + hookEnv.targetTriple = state.overrides.target_triple; + hookEnv.targetProvider = state.targetChoice.provider; + for (auto const& [name, value] : mcpp::build::install_hook_env(hookEnv)) + vars.push_back(std::make_unique(name, value)); + } +}; + static std::expected step4a_load_version_dep_locate(PrepareState& state, LoadVersionDepCtx& ctx) { // ─── Routing: check if this dep's namespace maps to a custom index ── @@ -803,19 +868,28 @@ step4a_load_version_dep_locate(PrepareState& state, LoadVersionDepCtx& ctx) { // complete it is, and goes back through xlings, which reinstalls it // and records the new revision. A payload with no xlings record at // all is judged by the marker alone, as before. - const int recipeRevision = [&] { + // NONE WHEN THE ENTRY IS WRITTEN IN A FORM THE READER DOES NOT READ: + // an unknown revision does not take part in the judgement, which then + // rests on the payload's files as for a payload with no record. Taking it + // for 0 reinstalled such a package on every build. + const std::optional recipeRevision = [&]() -> std::optional { if (!ctx.luaContent) return 0; for (auto const& e : mcpp::manifest::list_xpkg_version_entries( *ctx.luaContent, *state.targetPlatform)) if (e.version == ctx.version) return e.revision; return 0; }(); + ctx.recipeRevision = recipeRevision; auto revisionIsCurrent = [&](const std::filesystem::path& p) { const auto installed = mcpp::provider::revision_of(p); - if (!installed || *installed == recipeRevision) return true; + if (!installed || !recipeRevision || *installed == *recipeRevision) return true; + if (auto cfg = state.get_cfg(true); + cfg && known_disagreement(**cfg, p, *recipeRevision, *installed)) + return true; mcpp::log::verbose("fetcher", std::format( "{}@{}: installed revision {}, descriptor revision {}; reinstalling", - ctx.depName, ctx.version, *installed, recipeRevision)); + ctx.depName, ctx.version, *installed, *recipeRevision)); + ctx.reinstallFrom = installed; return false; }; @@ -833,6 +907,9 @@ step4a_load_version_dep_locate(PrepareState& state, LoadVersionDepCtx& ctx) { // For custom indices, try project-level data roots first. ctx.installed = findCompleteInstalled(); + if (ctx.installed) + mcpp::log::verbose("fetcher", std::format("{} v{}: installed at {}; used as it is", + ctx.depName, ctx.version, ctx.installed->string())); return {}; } @@ -980,7 +1057,17 @@ step4a_load_version_dep_fetch(PrepareState& state, LoadVersionDepCtx& ctx) { if (mcpp::effects::install_sources() == mcpp::effects::InstallSources::None) return std::unexpected(mcpp::pm::offline_without_sources( std::format("dependency '{}' v{}", displayName, version))); - mcpp::ui::info("Downloading", std::format("{} v{}", displayName, version)); + // NO LINE IS PRINTED BEFORE THE PROVIDER IS ASKED (design 2026-11-27 + // §3.11.2, point 6): a line appears when the provider reports a + // download, named as the manifest names the dependency, and its + // completion replaces it. A payload replaced because the entry's + // revision changed says so with its verb. + const mcpp::fetcher::DownloadLabel label{ + std::format("{} v{}{}", displayName, version, + ctx.reinstallFrom && ctx.recipeRevision + ? std::format(" (revision {} to {})", *ctx.reinstallFrom, *ctx.recipeRevision) + : std::string{}), + ctx.reinstallFrom ? "Updating" : "" }; // #238: retain whatever error/warn text the child DID emit so we // can fold it into a diagnostic if install_packages exits non-zero. @@ -1008,14 +1095,16 @@ step4a_load_version_dep_fetch(PrepareState& state, LoadVersionDepCtx& ctx) { auto argsJson = std::format( R"({{"targets":["{}"],"yes":true}})", target); mcpp::fetcher::InstallProgressHandler progress; + progress.labels.emplace(target, label); auto r = mcpp::provider::open(projEnv)->call("install_packages", argsJson, &progress); capturedChildError = progress.captured_error(); if (!r) return std::unexpected(mcpp::pm::CallError{r.error()}); append_xlings_stderr(capturedChildError, *r); return *r; } - std::vector targets{ std::move(target) }; mcpp::fetcher::InstallProgressHandler progress; + progress.labels.emplace(target, label); + std::vector targets{ std::move(target) }; auto r = fetcher.install(targets, &progress); capturedChildError = progress.captured_error(); if (r) append_xlings_stderr(capturedChildError, *r); @@ -1056,18 +1145,7 @@ step4a_load_version_dep_fetch(PrepareState& state, LoadVersionDepCtx& ctx) { // not name the variant, because the store is keyed by package and // version. Scoped: restored when this dependency's install returns, // compat retries below included. - mcpp::build::BuildProgramEnv hookEnv; - fill_target_build_env(hookEnv, *state.m, state.tc ? &*state.tc : nullptr, state.cfg_opt ? &*state.cfg_opt : nullptr); - hookEnv.targetTriple = state.overrides.target_triple; - hookEnv.targetProvider = state.targetChoice.provider; - // Six names, fixed by install_hook_env; one guard each. - const auto hookVars = mcpp::build::install_hook_env(hookEnv); - mcpp::invocation::ScopedEnv hookVar0(hookVars.at(0).first, hookVars.at(0).second); - mcpp::invocation::ScopedEnv hookVar1(hookVars.at(1).first, hookVars.at(1).second); - mcpp::invocation::ScopedEnv hookVar2(hookVars.at(2).first, hookVars.at(2).second); - mcpp::invocation::ScopedEnv hookVar3(hookVars.at(3).first, hookVars.at(3).second); - mcpp::invocation::ScopedEnv hookVar4(hookVars.at(4).first, hookVars.at(4).second); - mcpp::invocation::ScopedEnv hookVar5(hookVars.at(5).first, hookVars.at(5).second); + const InstallHookScope hookScope(state); auto r = install_one(target); // A MISS AT INSTALL REFRESHES THE INDEX, THEN ASKS ONCE MORE. The // walk refreshes when a descriptor is missing, and deliberately not @@ -1126,8 +1204,6 @@ step4a_load_version_dep_fetch(PrepareState& state, LoadVersionDepCtx& ctx) { std::format("compat:{}@{}", shortName, version), std::format("compat.{}@{}", shortName, version) }) { if (compatTarget == target) continue; - mcpp::ui::info("Downloading", std::format("{} v{}", - compatTarget.substr(0, compatTarget.rfind('@')), version)); attempted.push_back(compatTarget); r = install_one(compatTarget); if (!r || r->exitCode == 0) break; @@ -1201,6 +1277,7 @@ step4a_load_version_dep_fetch(PrepareState& state, LoadVersionDepCtx& ctx) { } // After install, check project data first for custom index packages. ctx.installed = step4a_find_raw_installed(state, ctx); + if (ctx.installed) check_read_revision(state, ctx); if (!ctx.installed) { // Where the payload was expected, so that a provider that // placed it elsewhere is seen at once. @@ -1314,6 +1391,79 @@ std::expected phase4a_graph_load(PrepareState& state) { return std::unexpected(r.error()); return step4a_load_version_dep_read_manifest(state, ctx); }; + state.prefetchPending = [&]() { + if (mcpp::effects::install_sources() == mcpp::effects::InstallSources::None) return; + if (!mcpp::buildopt::registry::on(mcpp::buildopt::registry::kBatchFetch, + state.m->buildConfig.batchFetch, + [](std::string_view bad) { + mcpp::diag::warning("build", std::format( + "ignoring invalid batch_fetch '{}' (expected \"waves\" or \"each\")", bad)); + })) + return; + auto cfg = state.get_cfg(true); + if (!cfg) return; + struct Pending { LoadVersionDepCtx ctx; std::string target; }; + std::vector pending; + for (auto const& item : state.worklist) { + auto const& spec = item.spec; + // An exact version of a named namespace, with no patches: what the + // walk would ask of the provider as it is. A range is pinned by the + // walk first, and an unqualified name is routed by it. + if (!spec.isVersion() || !spec.patches.empty() || spec.namespace_.empty() + || mcpp::pm::is_version_constraint(spec.version)) + continue; + LoadVersionDepCtx ctx; + ctx.depName = item.name; + ctx.ns = spec.namespace_; + ctx.shortName = spec.shortName.empty() ? item.name : spec.shortName; + ctx.version = spec.version; + if (!state.prefetchConsidered.insert(std::format("{}:{}@{}", ctx.ns, ctx.shortName, ctx.version)).second) + continue; + if (!step4a_load_version_dep_locate(state, ctx)) continue; + if (ctx.installed || ctx.useProjectEnv || !ctx.luaContent) continue; + if (mcpp::manifest::xpkg_name_form_violation_from_lua(*ctx.luaContent)) continue; + // An inline descriptor with mcpp dependencies has them installed + // before its own hook runs; the path of one dependency does that. + if (mcpp::pm::descriptor_is_inline(*ctx.luaContent)) { + auto own = mcpp::manifest::synthesize_from_xpkg_lua(*ctx.luaContent, ctx.shortName, ctx.version, + *state.targetPlatform); + if (!own || !own->dependencies.empty()) continue; + } + auto target = std::format("{}@{}", + mcpp::manifest::xpkg_wire_address(*ctx.luaContent, ctx.ns, ctx.shortName).target, ctx.version); + pending.push_back({std::move(ctx), std::move(target)}); + } + // One dependency gains nothing from a wave; its own path says more. + if (pending.size() < 2) return; + std::vector targets; + mcpp::fetcher::InstallProgressHandler progress; + for (auto const& p : pending) { + targets.push_back(p.target); + progress.labels.emplace(p.target, mcpp::fetcher::DownloadLabel{ + std::format("{}.{} v{}", p.ctx.ns, p.ctx.shortName, p.ctx.version), + p.ctx.reinstallFrom ? "Updating" : ""}); + } + const auto provider = mcpp::provider::open(mcpp::config::make_xlings_env(**cfg)); + bool waited = false; + mcpp::home::Turn turn(provider->state_dir(), mcpp::provider::kStateTurn, + std::format("installing {} dependencies", pending.size()), + std::chrono::milliseconds(0), + [](std::string_view holder) { + mcpp::ui::status("Waiting", holder.empty() + ? std::string("for another mcpp of this home to finish an install") + : std::format("for another mcpp of this home, {}", holder)); + }, &waited); + const InstallHookScope hookScope(state); + mcpp::fetcher::Fetcher fetcher(**cfg); + auto r = fetcher.install(targets, &progress); + mcpp::log::verbose("fetcher", std::format("a wave of {} dependencies: {}", targets.size(), + !r ? r.error().message : r->exitCode == 0 ? std::string("installed") + : std::format("the provider exited {}; each not installed is asked alone", r->exitCode))); + for (auto& p : pending) { + if (!step4a_load_version_dep_locate(state, p.ctx)) continue; + if (p.ctx.installed) check_read_revision(state, p.ctx); + } + }; state.loadVersionDepVariant = [&](const std::string& depName, const std::string& ns, const std::string& shortName, diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index 368060e37..a361c1e7f 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -996,6 +996,14 @@ struct PrepareState { const std::vector&, const std::string&, const std::string&)> loadVersionDepVariant; + // FETCHING BY WAVES (SPEC-019 `batch-fetch`, design 2026-11-27 §3.11.2, + // point 9): the version dependencies the worklist holds now, not yet + // installed, asked of the provider in one call before they are walked one + // by one. Each is then found installed; one the call did not install takes + // the path of one dependency, which says why. `prefetchConsidered` holds + // the `ns:name@version` already asked about. + std::function prefetchPending; + std::set prefetchConsidered; std::map resolved; // The features asked of each resolved dependency so far (by dep_manifests diff --git a/src/cli/cmd_xpkg.cppm b/src/cli/cmd_xpkg.cppm index 7dfbc41cc..6d0fe5d91 100644 --- a/src/cli/cmd_xpkg.cppm +++ b/src/cli/cmd_xpkg.cppm @@ -190,6 +190,41 @@ export int cmd_xpkg_parse(const mcpplibs::cmdline::ParsedArgs& parsed) { return 1; } + // A PLATFORM REFERENCE THAT NAMES NO PLATFORM, or a cycle of them: every + // reader, the installer included, ends the chain there, and the referring + // platform holds only what it declares itself. + for (auto const& problem : mcpp::manifest::xpkg_platform_reference_problems(lua)) { + const auto what = std::format("{}: {}; refer to a platform xpm has a table for", file, problem); + if (asJson) + emit_xpkg(std::format("{{\"namespace\":\"{}\",\"name\":\"{}\",\"error\":\"{}\"}}", + json_escape(id.ns), json_escape(id.name), json_escape(what)), enveloped); + else + mcpp::ui::error(what); + return 1; + } + + // A VERSION WRITTEN IN A FORM THE RESOLVER DOES NOT READ. Its revision is + // then unknown to every mcpp that reads the entry, which judges the payload + // by its files alone and never sees a revision change; the installer runs + // the descriptor and does read it. Refused here so an index's lint stops + // it, naming the form every release reads. + for (auto plat : kPlatforms) { + for (auto const& e : mcpp::manifest::list_xpkg_version_entries( + lua, mcpp::toolchain::platform::TargetPlatform::for_lint_of(plat))) { + if (!e.unread) continue; + const auto what = std::format( + "{}: version '{}' of '{}' is written in a form the resolver does not read; " + "write its value as a table in place (`[\"{}\"] = {{ url = ..., sha256 = ... }}`)", + file, e.version, plat, e.version); + if (asJson) + emit_xpkg(std::format("{{\"namespace\":\"{}\",\"name\":\"{}\",\"error\":\"{}\"}}", + json_escape(id.ns), json_escape(id.name), json_escape(what)), enveloped); + else + mcpp::ui::error(what); + return 1; + } + } + // The pointer form (Form A; SPEC-001 §3.5) carries no table: build info // comes from the manifest in the payload. Nothing further to parse. // The xpm version tables are independent of that segment and are the diff --git a/src/fetcher/progress.cppm b/src/fetcher/progress.cppm index a057b5802..3e9ff4823 100644 --- a/src/fetcher/progress.cppm +++ b/src/fetcher/progress.cppm @@ -178,17 +178,26 @@ std::vector to_ui_download_files(const std::vector out.push_back({ f.name, static_cast(f.downloadedBytes), static_cast(f.totalBytes), - f.started, f.finished }); + f.started, f.finished, {} }); } else { out.push_back({ f.name, static_cast(f.downloaded), static_cast(f.total), - f.started, f.finished }); + f.started, f.finished, {} }); } } return out; } +// How a dependency is named on its line: the identity and version the user +// wrote in the manifest (`compat.pugixml v1.16`), not the address the provider +// is asked for (`compat:pugixml@1.16`), which -v and errors show. One spelling +// of a dependency in every line about it (design 2026-11-27 §3.11.2, point 7). +export struct DownloadLabel { + std::string text; + std::string verb; // empty: Downloading +}; + // One line of git's `--progress` output: the phase and its percentage. // `remote: Counting objects: 40% (2/5)` and `Receiving objects: 100% (5/5), // 1.20 MiB | 800.00 KiB/s, done.` both parse; the phase has no `remote: ` @@ -229,6 +238,8 @@ export mcpp::config::BootstrapProgressCallback make_bootstrap_progress_callback( // installs alike, so all three show identical UI. export struct InstallProgressHandler : mcpp::fetcher::EventHandler { mcpp::ui::DownloadProgress progress_; + // Provider address (`ns:name@version`) -> the line's name and verb. + std::map> labels; // #238: retain any error/warn text the child DID emit so the caller can // fold it into the install_packages failure diagnostic. The known @@ -268,6 +279,11 @@ export struct InstallProgressHandler : mcpp::fetcher::EventHandler { if (files.empty()) return; double elapsed = extract_payload_number(d.payloadJson, "elapsedSec"); auto ui_files = to_ui_download_files(files); + for (auto& f : ui_files) + if (const auto it = labels.find(f.name); it != labels.end()) { + f.name = it->second.text; + f.verb = it->second.verb; + } progress_.update(ui_files, elapsed); } diff --git a/src/project.cppm b/src/project.cppm index fc217058b..4e9fe4302 100644 --- a/src/project.cppm +++ b/src/project.cppm @@ -1168,6 +1168,11 @@ export std::string root_position_key( if (!abiLongjmp.empty()) field("abi_longjmp", abiLongjmp); field("accel", b.accel); field("bmi_schedule", b.bmiSchedule); + // Joined where stated, as `abi longjmp` is: a project that states none keeps + // the key an earlier engine wrote. + if (!b.batchFetch.empty()) field("batch_fetch", b.batchFetch); + if (!b.planLocks.empty()) field("plan_locks", b.planLocks); + if (!b.lockWait.empty()) field("lock_wait", b.lockWait); field("private_fragment", b.privateFragment); field("jobs", b.jobs); field("memory_threshold", b.memoryThreshold); @@ -1247,6 +1252,9 @@ virtual_workspace_root(const mcpp::manifest::Manifest& workspace, b.runExclusive = f.runExclusive; b.jobs = f.jobs; b.bmiSchedule = f.bmiSchedule; + b.batchFetch = f.batchFetch; + b.planLocks = f.planLocks; + b.lockWait = f.lockWait; b.privateFragment = f.privateFragment; b.accel = f.accel; b.staticStdlib = f.staticStdlib; diff --git a/src/provider/xlings/xlings.cpp b/src/provider/xlings/xlings.cpp index 22d267bc2..08f547bf6 100644 --- a/src/provider/xlings/xlings.cpp +++ b/src/provider/xlings/xlings.cpp @@ -56,13 +56,21 @@ namespace { // Right-pad a verb to 12 columns for bootstrap status lines, on standard // error: the stream mcpp.ui narrates on. +// THROUGH THE NARRATION STREAM'S ONE WRITER (design 2026-11-27 §3.11.2, point +// 4). A line written to standard error beside mcpp.ui moved the cursor under a +// live region the module had drawn, so its next frame rose one row too few and +// left the first bar of a download on the screen. void print_status(std::string_view verb, std::string_view msg) { - constexpr std::size_t W = 12; - if (verb.size() >= W) { - std::println(libc::stderr(), "{} {}", verb, msg); - } else { - std::println(libc::stderr(), "{}{} {}", std::string(W - verb.size(), ' '), verb, msg); - } + mcpp::ui::status(verb, msg); +} + +// Which source a download is taken from: said when it changes after the first +// attempt (a retry on another host is news); the first attempt is in -v. +void print_source(std::string_view name, std::string_view host, int attempt) { + if (attempt <= 1) + mcpp::log::verbose("xlings", std::format("{} from {} (attempt {})", name, host, attempt)); + else + print_status("Source", std::format("{} {} (attempt {})", name, host, attempt)); } std::filesystem::path default_index_dir(const Env& env) { @@ -1348,8 +1356,7 @@ call(const Env& env, std::string_view capability, for (const auto& file : progress->files) if (!file.sourceHost.empty() && sourceAttempts[file.name] != file.sourceAttempt) { sourceAttempts[file.name] = file.sourceAttempt; - print_status("Source", std::format("{} {} (attempt {})", - file.name, file.sourceHost, file.sourceAttempt)); + print_source(file.name, file.sourceHost, file.sourceAttempt); } } @@ -1716,7 +1723,7 @@ int install_with_progress(const Env& env, std::string_view target, for (const auto& file : prog->files) { if (!quiet && !file.sourceHost.empty() && sourceAttempts[file.name] != file.sourceAttempt) { sourceAttempts[file.name] = file.sourceAttempt; - print_status("Source", std::format("{} {} (attempt {})", file.name, file.sourceHost, file.sourceAttempt)); + print_source(file.name, file.sourceHost, file.sourceAttempt); } } if (cb) cb(*prog); @@ -1763,7 +1770,7 @@ int install_direct(const Env& env, std::string_view target, bool quiet) { // terminal showed them before, unless the caller asked for quiet. They are // xlings' own progress text, narration: standard error. inv.options.streams = quiet ? mcpp::run::Streams::discard : mcpp::run::Streams::output_error_shown; - inv.options.on_line = [](std::string_view line) { std::println(libc::stderr(), "{}", line); }; + inv.options.on_line = [](std::string_view line) { mcpp::ui::block(std::string(line) + "\n"); }; inv.options.total = std::chrono::duration_cast(kDirectInstallTimeout); const auto ran = mcpp::run::execute(inv.argv, inv.options); const bool timedOut = ran.timed_out; @@ -1778,7 +1785,7 @@ int install_direct(const Env& env, std::string_view target, bool quiet) { namespace { int run_shown(Invocation inv) { inv.options.streams = mcpp::run::Streams::output_error_shown; - inv.options.on_line = [](std::string_view line) { std::println(libc::stderr(), "{}", line); }; + inv.options.on_line = [](std::string_view line) { mcpp::ui::block(std::string(line) + "\n"); }; inv.options.total = std::chrono::duration_cast(kDirectInstallTimeout); const auto ran = mcpp::run::execute(inv.argv, inv.options); if (ran.timed_out) @@ -1959,9 +1966,9 @@ void ensure_init(const Env& env, bool quiet) { inv.options.total = std::chrono::seconds{120}; const int rc = mcpp::run::execute(inv.argv, inv.options).exit_code; if (rc != 0 && !quiet) { - std::println(libc::stderr(), - "warning: `xlings self init` failed for sandbox at '{}'", - env.home.string()); + mcpp::diag::degraded("provider/sandbox-init", + std::format("`xlings self init` failed for the sandbox at '{}'", env.home.string()), + "packages that are installed into the sandbox may fail to install"); } // The first real `xlings install` (the next bootstrap step) triggers @@ -1994,9 +2001,9 @@ void ensure_patchelf(const Env& env, bool quiet, int rc = install_with_progress(env, std::format("xim:patchelf@{}", pinned::kPatchelfVersion), cb, quiet); if (rc != 0 && !quiet) { - std::println(libc::stderr(), - "warning: failed to bootstrap patchelf into mcpp sandbox; " - "subsequent xim installs may skip ELF rewriting"); + mcpp::diag::degraded("provider/patchelf-bootstrap", + "patchelf could not be installed into mcpp's sandbox", + "later installs may skip rewriting the interpreter and search paths of ELF files"); } } @@ -2043,10 +2050,9 @@ void ensure_ninja(const Env& env, bool quiet, if (rc != 0 && !other.empty()) { std::ofstream(attempt) << pinned::kNinjaVersion << "\n"; if (!quiet) - std::println(libc::stderr(), - "warning: ninja {} could not be installed (exit {}); builds run ninja {}, which " - "lacks the correction of ninja-build/ninja#2662", - pinned::kNinjaVersion, rc, other); + mcpp::diag::degraded("provider/ninja-pin", + std::format("ninja {} could not be installed (exit {})", pinned::kNinjaVersion, rc), + std::format("builds run ninja {}, which lacks the correction of ninja-build/ninja#2662", other)); return; } if (rc != 0) { @@ -2055,19 +2061,20 @@ void ensure_ninja(const Env& env, bool quiet, // home takes that one and says what it lacks, and the pin is asked // again after a day. if (!quiet) - std::println(libc::stderr(), - "warning: ninja {} could not be installed (exit {}); installing ninja {}, which " - "lacks the correction of ninja-build/ninja#2662", - pinned::kNinjaVersion, rc, pinned::kNinjaBaseVersion); + mcpp::diag::degraded("provider/ninja-pin", + std::format("ninja {} could not be installed (exit {}); installing ninja {}", + pinned::kNinjaVersion, rc, pinned::kNinjaBaseVersion), + std::format("builds run ninja {}, which lacks the correction of ninja-build/ninja#2662", + pinned::kNinjaBaseVersion)); rc = install_with_progress(env, std::format("xim:ninja@{}", pinned::kNinjaBaseVersion), cb, quiet); std::error_code ec; if (rc == 0 && std::filesystem::exists(root, ec)) std::ofstream(attempt) << pinned::kNinjaVersion << "\n"; } if (rc != 0 && !quiet) { - std::println(libc::stderr(), - "warning: failed to bootstrap ninja into mcpp sandbox (exit {})", - rc); + mcpp::diag::degraded("provider/ninja-bootstrap", + std::format("ninja could not be installed into mcpp's sandbox (exit {})", rc), + "builds use a ninja found on PATH, or cannot run"); } } @@ -2358,11 +2365,11 @@ int update_index_unguarded(const Env& env, bool quiet) { // would only be waited on three times. The caller treats the refresh as // failed and resolves from the local index, as it does for any failure. if (timedOut) { - std::println(libc::stderr(), - "warning: the package index refresh did not finish within {} seconds and was " - "stopped; continuing with the local index " - "(the bound is [index] refresh_timeout in mcpp's config.toml)", - refreshBound.count()); + mcpp::diag::degraded("index/refresh-timeout", + std::format("the package index refresh did not finish within {} seconds and was stopped", + refreshBound.count()), + "the build continues with the local index, which may not have the newest versions", + "the bound is [index] refresh_timeout in mcpp's config.toml"); return rc != 0 ? rc : 124; } if (attempt < kMaxAttempts) { @@ -2377,9 +2384,9 @@ int update_index_unguarded(const Env& env, bool quiet) { // the TTL refresh before a build), which continues with the local index; // `mcpp index update` reports the failure itself. if (quiet) - std::println(libc::stderr(), - "warning: the package index refresh failed after {} attempts (exit {}); " - "continuing with the local index", kMaxAttempts, rc); + mcpp::diag::degraded("index/refresh-failed", + std::format("the package index refresh failed after {} attempts (exit {})", kMaxAttempts, rc), + "the build continues with the local index, which may not have the newest versions"); return rc; } } // namespace diff --git a/src/ui.cppm b/src/ui.cppm index a74fabd7c..2b5d96fd3 100644 --- a/src/ui.cppm +++ b/src/ui.cppm @@ -335,6 +335,9 @@ struct DownloadFile { std::size_t total = 0; // 0 = size not known yet (connecting) bool started = false; bool finished = false; + // The verb of its line; empty: `Downloading`. A payload replaced because + // its index entry's revision changed is `Updating`. + std::string verb; }; // Centralized renderer for a streaming multi-file download. Owns the @@ -1281,13 +1284,12 @@ std::string status_bar_text(std::string_view verb, const std::string& label, } auto contentBudget = budget - fixed; // barInner + visible-label-cols - std::size_t barW = std::min(kBarMax, contentBudget); + // The label first, then the bar: the bar shrinks to its minimum before the + // label is cut, so a narrow terminal still names what is downloading. + const std::size_t labelW = display_width(label); + std::size_t barW = contentBudget > labelW ? std::min(kBarMax, contentBudget - labelW) : 0; + if (barW < kBarMin) barW = std::min(kBarMin, contentBudget); std::size_t labelMax = contentBudget - barW; - if (barW < kBarMin && labelMax > 0) { - auto steal = std::min(kBarMin - barW, labelMax); - barW += steal; - labelMax -= steal; - } auto bar = makeBar(barW); auto lbl = trunc_visible(label, labelMax); return verb_line(kBrightCyan, verb, std::format("{} {} {}", lbl, bar, info_text)); @@ -1507,7 +1509,8 @@ void DownloadProgress::update(std::span files, if (current->name != active_) { if (bar_) bar_->finish(); active_ = current->name; - bar_.emplace("Downloading", current->name); + bar_.emplace(current->verb.empty() ? std::string_view("Downloading") : std::string_view(current->verb), + current->name); } if (current->total > 0) { bar_->update_bytes(current->downloaded, current->total, elapsed_sec); diff --git a/tests/unit/test_manifest.cpp b/tests/unit/test_manifest.cpp index 37533e4f9..f09dffa8d 100644 --- a/tests/unit/test_manifest.cpp +++ b/tests/unit/test_manifest.cpp @@ -748,6 +748,93 @@ package = { expect(eq(e[5].revision, 0)); // nor is a negative number }}; +// A version stated through a local table is read through it (design +// 2026-11-27 §3.1): before, it read as revision 0 while the installer recorded +// the table's revision, and every build reinstalled the package. A form the +// reader does not follow is unread, its revision none rather than 0. +UTest a_version_through_a_local_table_is_read{"ListXpkgVersions/AVersionThroughALocalTableIsRead", [] { + constexpr auto src = R"( +local versions = { + ["1.0.0"] = { url = "u", sha256 = "a", revision = 1 }, +} +local snapshot = { url = "u", sha256 = "b", revision = 2 } +package = { + name = "refs", + xpm = { + linux = { + ["1.0.0"] = versions["1.0.0"], + ["2.0.0"] = snapshot, + ["3.0.0"] = make_entry("3.0.0"), + }, + }, +} +)"; + auto e = mcpp::manifest::list_xpkg_version_entries( + src, mcpp::toolchain::platform::TargetPlatform::for_lint_of("linux")); + expect(fatal(eq(e.size(), 3u))); + expect(eq(e[0].sha256, "a")); expect(eq(e[0].revision, 1)); expect(!e[0].unread); + expect(eq(e[1].sha256, "b")); expect(eq(e[1].revision, 2)); expect(!e[1].unread); + expect(bool(e[2].unread)); expect(!e[2].revision.has_value()); +}}; + +// THE PLATFORM REFERENCE (xpackage V1; libxpkg 0.0.64): one artifact for every +// system is written once. A block that refers to another holds the versions +// it lacks, after its own, and its deps when it states none; `inherits` is +// the other spelling, and the chain is followed. +UTest a_platform_reference_holds_what_it_lacks{"ListXpkgVersions/APlatformReferenceHoldsWhatItLacks", [] { + constexpr auto src = R"( +package = { + name = "shared", + xpm = { + linux = { + deps = { "xim:zlib@1.3.1" }, + ["1.0.0"] = { url = "u", sha256 = "a", revision = 1 }, + ["2.0.0"] = { url = "u", sha256 = "b" }, + }, + macosx = { + ref = "linux", + ["2.0.0"] = { url = "m", sha256 = "own" }, + }, + windows = { inherits = "macosx", deps = {} }, + }, +} +)"; + using mcpp::toolchain::platform::TargetPlatform; + auto mac = mcpp::manifest::list_xpkg_version_entries(src, TargetPlatform::for_lint_of("macosx")); + expect(fatal(eq(mac.size(), 2u))); + expect(eq(mac[0].version, "2.0.0")); expect(eq(mac[0].sha256, "own")); + expect(eq(mac[1].version, "1.0.0")); expect(eq(mac[1].revision, 1)); + auto win = mcpp::manifest::list_xpkg_version_entries(src, TargetPlatform::for_lint_of("windows")); + expect(fatal(eq(win.size(), 2u))); + expect(eq(win[0].sha256, "own")); expect(eq(win[1].sha256, "a")); + auto macDeps = mcpp::manifest::xpkg_runtime_deps(src, TargetPlatform::for_lint_of("macosx")); + expect(fatal(eq(macDeps.size(), 1u))); + expect(eq(macDeps[0], "xim:zlib@1.3.1")); + expect(mcpp::manifest::xpkg_runtime_deps(src, TargetPlatform::for_lint_of("windows")).empty()); + expect(mcpp::manifest::xpkg_platform_reference_problems(src).empty()); +}}; + +// A reference to a platform xpm has no table for, or back into its own chain, +// ends the chain for every reader; the lint names it. +UTest a_platform_reference_to_nothing_is_named{"ListXpkgVersions/APlatformReferenceToNothingIsNamed", [] { + constexpr auto src = R"( +package = { + name = "broken", + xpm = { + linux = { ref = "windows" }, + windows = { ref = "linux" }, + macosx = { ref = "linx" }, + }, +} +)"; + auto problems = mcpp::manifest::xpkg_platform_reference_problems(src); + expect(fatal(eq(problems.size(), 3u))); + expect(problems[0].find("refers back") != std::string::npos); + expect(problems[1].find("'linx', which xpm has no table for") != std::string::npos); + expect(mcpp::manifest::list_xpkg_version_entries( + src, mcpp::toolchain::platform::TargetPlatform::for_lint_of("macosx")).empty()); +}}; + // The scanner used to walk the platform table character by character, so a // bracket key nested inside a version's own body (mirror tables write // `["GLOBAL"] = "https://..."`) counted as a published version. From 45af1fae5df662e519877b2f2777d8b2e093924e Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 4 Dec 2026 23:21:14 +0900 Subject: [PATCH 02/36] Locks: one wait that reports and is bounded, held told from cannot-lock, the std module read without its lock Every wait for a lock goes through FileLock::acquire: reported at 300 ms, 10 s, 30 s, 60 s and each minute with the resource, the lock file, the last recorded holder and whether that process is visible here; bounded by --lock-wait, MCPP_LOCK_WAIT or [build] lock_wait (lock-wait-exceeded), which reaches the provider as XLINGS_LOCK_TIMEOUT. A file the system cannot lock is refused at once with the system's reason and a remedy (lock-unavailable). The std module entry's record is its completion marker, written by a rename and listing its parts; a complete entry is read without the lock. --- src/build/dirlock.cppm | 157 ++++------------ src/build/execute.cppm | 34 +++- src/build/prepare/features.cpp | 12 +- src/build/prepare/graph_load.cpp | 24 ++- src/build/prepare/host_graph.cpp | 10 +- src/build/prepare/manifest.cpp | 13 ++ src/build/prepare/plan.cpp | 6 +- src/build/refusal.cppm | 8 + src/build/schedule/detach_codegen.cppm | 18 +- src/cli.cppm | 82 ++++++++- src/cli/cmd_build.cppm | 7 +- src/config.cppm | 13 ++ src/home/files.cpp | 240 +++++++++++++++++++++---- src/home/files.cppm | 156 ++++++++++++---- src/native/posix/lock.cpp | 45 ++++- src/native/windows/lock.cpp | 56 +++++- src/provider/xlings/xlings.cpp | 57 ++++-- src/toolchain/stdmod.cppm | 120 ++++++++----- 18 files changed, 757 insertions(+), 301 deletions(-) diff --git a/src/build/dirlock.cppm b/src/build/dirlock.cppm index 3b1ac826a..45d6101f4 100644 --- a/src/build/dirlock.cppm +++ b/src/build/dirlock.cppm @@ -20,131 +20,59 @@ // releases it before the first test runs. A crashed holder holds nothing: the // operating system releases the lock with the process. // -// A waiter is told who holds it once the wait has lasted 300 ms, which is what -// the owner record exists for: the process, the command, the caller's label -// (`MCPP_CLIENT`), and how long ago it started. +// A waiter is told who last held it as every wait of mcpp is told +// (mcpp::home::FileLock::acquire): the record the holder left, whether that +// process is visible here, and the wait so far, repeated as the wait goes on. export module mcpp.build.dirlock; import std; import mcpp.invocation; import mcpp.home.files; -import mcpp.ui; +import mcpp.build.refusal; export namespace mcpp::build::dirlock { inline constexpr std::string_view kLockName = ".mcpp-build.lock"; -// The holder a waiter is shown, parsed from the owner record. Fields absent -// from the record are empty. -struct Holder { - std::string pid; - std::string command; - std::string client; - std::int64_t startedAt = 0; // seconds since the epoch, 0 when unknown -}; - -Holder parse_holder(std::string_view record); - -// "pid 1234 (mcpp build, from mcpp-ide, 8s)" -- or "another mcpp" when the -// holder published nothing. -std::string describe(const Holder& h, std::int64_t now); - -// This process's owner record. -std::string owner_record(); +// The holder record and its reading are the home's (mcpp.home.files), shared +// by every lock of mcpp; these names stay for the build's callers. +using Holder = mcpp::home::Holder; +inline Holder parse_holder(std::string_view record) { return mcpp::home::parse_holder(record); } +inline std::string describe(const Holder& h, std::int64_t now) { return mcpp::home::describe(h, now); } +inline std::string owner_record() { return mcpp::home::owner_record(); } +inline const std::string& command() { return mcpp::home::command(); } +inline void set_command(std::string command) { mcpp::home::set_command(std::move(command)); } // This process, as the owner record and the result record name it. long process_id(); -const std::string& command(); - -// The command this process runs, as the owner record names it: set once from -// argv by the CLI, "mcpp" otherwise. -void set_command(std::string command); - -// Called once when a wait has lasted long enough to report (the event stream -// listens here; the human line is printed by `acquire` itself). -void set_waiting_observer(std::function observer); // Waits for the build directory's lock. Shared, because a BuildContext is // copied, and the last copy to go releases it; `release` drops it early. -std::shared_ptr acquire(const std::filesystem::path& outputDir); +// Refused -- the wait limit passed, or the directory cannot be locked -- with +// the failure, whose sentence names the lock and the remedy. +std::expected, mcpp::home::LockFailure> +acquire(const std::filesystem::path& outputDir); -// The time this process waited for build directories another command held: -// part of `Finished`'s account (2026-11-12 §17, W3). -std::chrono::milliseconds waited(); +// A lock not taken, as a refusal: its code recorded (lock-wait-exceeded, +// lock-unavailable) and the sentence that names the lock, the cause and the +// remedy, with the token. +std::string refused(const mcpp::home::LockFailure& f); + +// The time this process waited for locks other commands held: part of +// `Finished`'s account (2026-11-12 §17, W3). +inline std::chrono::milliseconds waited() { return mcpp::home::time_waited(); } } // namespace mcpp::build::dirlock namespace mcpp::build::dirlock { -namespace { -std::string& command_slot() { - static std::string command = "mcpp"; - return command; -} -std::function& observer_slot() { - static std::function observer; - return observer; -} -std::atomic g_waitedMs{0}; -long current_pid() { return mcpp::invocation::process_id(); } -std::int64_t now_seconds() { - return std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); -} -} // namespace +long process_id() { return mcpp::invocation::process_id(); } -void set_command(std::string command) { command_slot() = std::move(command); } -const std::string& command() { return command_slot(); } -long process_id() { return current_pid(); } - -void set_waiting_observer(std::function observer) { - observer_slot() = std::move(observer); -} - -Holder parse_holder(std::string_view record) { - Holder h; - std::size_t pos = 0; - while (pos < record.size()) { - auto end = record.find('\n', pos); - if (end == std::string_view::npos) end = record.size(); - const auto line = record.substr(pos, end - pos); - pos = end + 1; - const auto eq = line.find('='); - if (eq == std::string_view::npos) continue; - const auto key = line.substr(0, eq); - const auto value = std::string(line.substr(eq + 1)); - if (key == "pid") h.pid = value; - else if (key == "command") h.command = value; - else if (key == "client") h.client = value; - else if (key == "started") { - std::int64_t v = 0; - const auto r = std::from_chars(value.data(), value.data() + value.size(), v); - if (r.ec == std::errc{}) h.startedAt = v; - } - } - return h; -} - -std::string describe(const Holder& h, std::int64_t now) { - if (h.pid.empty()) return "another mcpp"; - std::vector parts; - if (!h.command.empty()) parts.push_back(h.command); - if (!h.client.empty()) parts.push_back("from " + h.client); - if (h.startedAt > 0 && now >= h.startedAt) parts.push_back(std::format("{}s", now - h.startedAt)); - std::string out = "pid " + h.pid; - if (!parts.empty()) { - out += " ("; - for (std::size_t i = 0; i < parts.size(); ++i) out += (i ? ", " : "") + parts[i]; - out += ")"; - } - return out; -} - -std::string owner_record() { - std::string client = mcpp::invocation::get("MCPP_CLIENT").value_or(""); - return std::format("pid={}\nstarted={}\ncommand={}\nclient={}\n", - current_pid(), now_seconds(), - command_slot(), client); +std::string refused(const mcpp::home::LockFailure& f) { + namespace refusal = mcpp::build::refusal; + refusal::record(f.kind == mcpp::home::LockFailure::Kind::Exceeded ? refusal::Code::LockWaitExceeded + : refusal::Code::LockUnavailable); + return std::format("{} [{}]", f.message(), f.token()); } // HELD ONCE PER PROCESS. One run may enter a configuration's directory more @@ -158,32 +86,19 @@ std::map>& held() { return m; } -std::shared_ptr acquire(const std::filesystem::path& outputDir) { +std::expected, mcpp::home::LockFailure> +acquire(const std::filesystem::path& outputDir) { const auto key = outputDir.lexically_normal().generic_string(); std::lock_guard heldLock(g_heldMutex); if (auto existing = held()[key].lock()) return existing; - const auto start = std::chrono::steady_clock::now(); - bool waiting = false; auto lock = mcpp::home::FileLock::acquire( - outputDir, kLockName, owner_record(), std::chrono::milliseconds(300), - [&](std::string_view record) { - waiting = true; - const auto holder = parse_holder(record); - mcpp::ui::status("Waiting", std::format("for the build directory, held by {}", - describe(holder, now_seconds()))); - if (auto& observe = observer_slot()) - observe(holder, std::chrono::duration_cast( - std::chrono::steady_clock::now() - start)); - }); - if (waiting) - g_waitedMs += std::chrono::duration_cast( - std::chrono::steady_clock::now() - start).count(); - if (!lock) return nullptr; + outputDir, kLockName, + {.resource = std::format("the build directory {}", outputDir.filename().string()), + .doing = "building"}); + if (!lock) return std::unexpected(lock.error()); auto shared = std::make_shared(std::move(*lock)); held()[key] = shared; return shared; } -std::chrono::milliseconds waited() { return std::chrono::milliseconds(g_waitedMs.load()); } - } // namespace mcpp::build::dirlock diff --git a/src/build/execute.cppm b/src/build/execute.cppm index 75b72e51f..6a3512362 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -958,7 +958,15 @@ void write_build_cache(const std::filesystem::path& projectRoot, std::lock_guard lock(cacheWrite); auto path = projectRoot / kBuildCacheFile; auto fileLock = mcpp::home::FileLock::acquire( - path.parent_path(), ".build_cache.lock", {}, std::chrono::hours(1), {}); + path.parent_path(), ".build_cache.lock", + {.resource = "the project's record of its builds (target/.build_cache)", .doing = "recording a build"}); + // Not held: the build stands, and the next one takes the full path once. + if (!fileLock) { + mcpp::diag::degraded("build/cache-record", + std::format("{} [{}]", fileLock.error().message(), fileLock.error().token()), + "the next build of this configuration plans in full instead of replaying this one"); + return; + } auto entries = read_build_cache(projectRoot); // Remove the existing entry for this (target, profile) pair. Keying on the @@ -3344,7 +3352,13 @@ export std::optional try_fast_build(const std::filesystem::path& projectRoo // Taken BEFORE admission: a build of this configuration that held it may // have rewritten build.ninja (a test graph, another request) while this // one waited, and the record is judged against what is there now. + // Not taken (the wait limit, or a directory that cannot be locked): the + // command refuses here rather than waiting again on the full path. auto buildLock = mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir)); + if (!buildLock) { + mcpp::ui::error(mcpp::build::dirlock::refused(buildLock.error())); + return 1; + } // The gates every fast path shares (see admit_recorded_build); what is left // here is the project's own tree. @@ -3455,7 +3469,12 @@ export std::optional try_fast_workspace_build( // Each group's directory under its own lock, taken before admission // for the reason try_fast_build gives. Groups are visited in one // order by every command, so two never wait on each other. - locks.push_back(mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir))); + auto groupLock = mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir)); + if (!groupLock) { + mcpp::ui::error(mcpp::build::dirlock::refused(groupLock.error())); + return 1; + } + locks.push_back(std::move(*groupLock)); // The gates every fast path shares (see admit_recorded_build). A // workspace has no project tree of its own to sweep: its members are // recorded roots, each classified by its own package. @@ -3711,6 +3730,10 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, // program starts: a program that runs for an hour holds nothing, and a // build of the same configuration meanwhile proceeds (mcpp#839). auto buildLock = mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir)); + if (!buildLock) { + mcpp::ui::error(mcpp::build::dirlock::refused(buildLock.error())); + return kRunBuildFailed; + } // The gates every fast path shares (see admit_recorded_build), for the // reason `mcpp run` is among the paths that need them: it execs the @@ -3747,7 +3770,7 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, validatedBefore)) return fast_path_declined("run", "ninja relinked an artifact, whose closure the full path validates"); // never execute an artifact not validated for this binding fast_path_end(record, true); - buildLock.reset(); + buildLock->reset(); // The cache records the program's path with `/`; the full path spells it // natively (`bin\app.exe` on Windows), and so does this one, so that the @@ -7471,7 +7494,10 @@ fast_test_plan(const std::filesystem::path& projectRoot, const TestOptions& test for (auto const& t : record["tests"]) recordedNames.insert(t.value("name", "")); if (recordedNames != discoveredNames) return declined("the package's tests are not the recorded ones"); - ctx.buildLock = mcpp::build::dirlock::acquire(outputDir); + // A lock not taken declines: the full path refuses with it. + auto testLock = mcpp::build::dirlock::acquire(outputDir); + if (!testLock) return declined(testLock.error().message()); + ctx.buildLock = std::move(*testLock); if (test_graph_stamp(outputDir / graphFile) != record.value("graph_stamp", "")) return declined("the test graph is not the one the record was written with"); auto admitted = admit_recorded_build(*match, { diff --git a/src/build/prepare/features.cpp b/src/build/prepare/features.cpp index c7899c2da..a8b198f5a 100644 --- a/src/build/prepare/features.cpp +++ b/src/build/prepare/features.cpp @@ -9,6 +9,7 @@ import mcpp.build.prepare_inputs; import std; import mcpp.platform; import mcpp.diag; +import mcpp.build.dirlock; // refused: a lock not taken, as a refusal import mcpp.log; import mcpp.build.refusal; import mcpp.build.version_floor; @@ -2091,12 +2092,11 @@ static std::expected step6_dependency_build_programs(PrepareS bpEnv.outDir = dir / "out"; bpEnv.genBase = bpEnv.outDir; bpEnv.artifactsDir = dir / "run"; - outLock = mcpp::home::FileLock::acquire( - dir, "run.lock", std::format("{}'s build program", label), std::chrono::seconds{2}, - [&](std::string_view holder) { - mcpp::ui::info("note", std::format("waiting for {} ({})", holder.empty() ? label : holder, - mcpp::home::spelling(dir))); - }); + auto held = mcpp::home::FileLock::acquire( + dir, "run.lock", {.resource = std::format("the output of {}'s build program", label), + .doing = std::format("running {}'s build program", label)}); + if (!held) return std::unexpected(mcpp::build::dirlock::refused(held.error())); + outLock = std::move(*held); // Its last use, which `mcpp cache gc` collects by. std::ofstream(dir / ".mcpp-used", std::ios::binary | std::ios::trunc); state.programOutDirs[i] = bpEnv.outDir; diff --git a/src/build/prepare/graph_load.cpp b/src/build/prepare/graph_load.cpp index bbd777a2e..1bdf7490f 100644 --- a/src/build/prepare/graph_load.cpp +++ b/src/build/prepare/graph_load.cpp @@ -33,6 +33,7 @@ import mcpp.build.backend; // BuildOptions for the tool sub-build import mcpp.build.ninja; // make_ninja_backend — driving that sub-build import mcpp.config; import mcpp.buildopt.registry; // batch-fetch: whether the walk fetches by waves +import mcpp.build.dirlock; // refused: a lock not taken, as a refusal import mcpp.home.files; // the home's install turn import mcpp.toolchain.fingerprint; // hash_string: a stable key for a payload's record import mcpp.fetcher; @@ -958,12 +959,11 @@ step4a_load_version_dep_fetch(PrepareState& state, LoadVersionDepCtx& ctx) { ? mcpp::config::make_project_xlings_env(**cfg, state.projectIndexRoot()) : mcpp::config::make_xlings_env(**cfg)); turn.emplace(provider->state_dir(), mcpp::provider::kStateTurn, - std::format("installing {}@{}", depName, version), std::chrono::milliseconds(0), - [](std::string_view holder) { - mcpp::ui::status("Waiting", holder.empty() - ? std::string("for another mcpp of this home to finish an install") - : std::format("for another mcpp of this home, {}", holder)); - }, &waited); + mcpp::home::LockRequest{.resource = "the install state of this home", + .doing = std::format("installing {}@{}", depName, version)}, + &waited); + if (turn->failure()) + return std::unexpected(mcpp::build::dirlock::refused(*turn->failure())); if (waited) if (auto again = step4a_load_version_dep_locate(state, ctx); !again) return again; } @@ -1444,15 +1444,11 @@ std::expected phase4a_graph_load(PrepareState& state) { p.ctx.reinstallFrom ? "Updating" : ""}); } const auto provider = mcpp::provider::open(mcpp::config::make_xlings_env(**cfg)); - bool waited = false; mcpp::home::Turn turn(provider->state_dir(), mcpp::provider::kStateTurn, - std::format("installing {} dependencies", pending.size()), - std::chrono::milliseconds(0), - [](std::string_view holder) { - mcpp::ui::status("Waiting", holder.empty() - ? std::string("for another mcpp of this home to finish an install") - : std::format("for another mcpp of this home, {}", holder)); - }, &waited); + {.resource = "the install state of this home", + .doing = std::format("installing {} dependencies", pending.size())}); + // Not held: each dependency's own path refuses with why. + if (turn.failure()) return; const InstallHookScope hookScope(state); mcpp::fetcher::Fetcher fetcher(**cfg); auto r = fetcher.install(targets, &progress); diff --git a/src/build/prepare/host_graph.cpp b/src/build/prepare/host_graph.cpp index f4ed37403..290915e1a 100644 --- a/src/build/prepare/host_graph.cpp +++ b/src/build/prepare/host_graph.cpp @@ -30,6 +30,7 @@ import :state; import std; import mcpp.diag; +import mcpp.build.dirlock; // refused: a lock not taken, as a refusal import mcpp.log; import mcpp.build.backend; import mcpp.build.build_program; @@ -1277,12 +1278,9 @@ ensure_build_programs(PrepareState& state, const std::vector& packa fs::create_directories(dir, ec); // Two configuration groups of one command may share a host toolchain // and a standard: one builds, the other waits and finds it built. - std::optional lock; - for (int waited = 0; !(lock = mcpp::home::FileLock::try_acquire(dir)); ++waited) { - if (waited == 0) - mcpp::log::verbose("host-graph", std::format("waiting for {}", path_text(dir))); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } + auto lock = mcpp::home::FileLock::acquire(dir, ".lock", + {.resource = std::format("the build programs of {}", path_text(dir)), .doing = "building build programs"}); + if (!lock) return std::unexpected(mcpp::build::dirlock::refused(lock.error())); auto record = read_record(dir / "programs.json"); bool recordChanged = false; diff --git a/src/build/prepare/manifest.cpp b/src/build/prepare/manifest.cpp index 61fdb9193..d90bb7b75 100644 --- a/src/build/prepare/manifest.cpp +++ b/src/build/prepare/manifest.cpp @@ -9,6 +9,7 @@ import mcpp.build.prepare_inputs; import std; import mcpp.targetside; import mcpp.diag; +import mcpp.home.files; // the project tier of the wait limit import mcpp.build.version_floor; import mcpp.manifest; import mcpp.version; // this binary's release, for E9's floor @@ -569,6 +570,18 @@ std::expected phase0_manifest_and_workspace(PrepareState& sta if (auto r = refuse_unknown_capability(*state.m, *state.root / "mcpp.toml"); !r) return r; + // The project's tier of the wait limit (`[build] lock_wait`), for every + // wait from here on; a host-tool sub-build plans under its root's. + if (!state.overrides.preloaded_manifest && !state.m->buildConfig.lockWait.empty()) { + const auto limit = mcpp::home::parse_wait(state.m->buildConfig.lockWait); + if (!limit) + return std::unexpected(std::format( + "{}: [build] lock_wait = \"{}\" is not a duration; expected a number with s, m, h or ms " + "(\"30s\", \"2m\"), or \"0\" for no wait", (*state.root / "mcpp.toml").string(), + state.m->buildConfig.lockWait)); + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Project, limit); + } + // A DISTRIBUTION package is not a source tree, and building "in" one is a // failure that looks like a success: `interface/` holds declarations whose // definitions are in the prebuilt archive, so the build compiles the diff --git a/src/build/prepare/plan.cpp b/src/build/prepare/plan.cpp index 58e9b516c..4a3e4ba83 100644 --- a/src/build/prepare/plan.cpp +++ b/src/build/prepare/plan.cpp @@ -1898,7 +1898,11 @@ std::expected phase13_finish(PrepareState& state) { "the project (--deny write-project)", ctx.outputDir.generic_string())); } if (!state.overrides.describes()) adopt_predecessor_dir(state, ctx.outputDir); - if (!state.overrides.describes()) ctx.buildLock = mcpp::build::dirlock::acquire(ctx.outputDir); + if (!state.overrides.describes()) { + auto lock = mcpp::build::dirlock::acquire(ctx.outputDir); + if (!lock) return std::unexpected(mcpp::build::dirlock::refused(lock.error())); + ctx.buildLock = std::move(*lock); + } std::filesystem::path graphEngine; if (!state.overrides.describes()) graphEngine = renew_build_dir(state, ctx.outputDir); diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index 015d17ef2..4960855d2 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -244,6 +244,12 @@ enum class Code { // candidates of one name. Distinct from a dependency the index lacks: here // the index has it twice (design 2026-11-22 §6.2). IndexLocationNamedTwice, + // A lock another process holds was waited for as long as the caller + // allowed (--lock-wait, MCPP_LOCK_WAIT, [build] lock_wait). + LockWaitExceeded, + // A lock file the system cannot lock at all: permissions, a read-only or + // lockless file system, no descriptor left. Waiting would not end. + LockUnavailable, Other, // a refusal that has not been given a code yet }; @@ -317,6 +323,8 @@ constexpr std::string_view name(Code c) { case Code::BundleOlderThanLock: return "bundle-older-than-lock"; case Code::IndexLocationNamedTwice: return "index-location-named-twice"; + case Code::LockWaitExceeded: return "lock-wait-exceeded"; + case Code::LockUnavailable: return "lock-unavailable"; case Code::Other: return "other"; } return "other"; diff --git a/src/build/schedule/detach_codegen.cppm b/src/build/schedule/detach_codegen.cppm index c5930fccc..d323e96a2 100644 --- a/src/build/schedule/detach_codegen.cppm +++ b/src/build/schedule/detach_codegen.cppm @@ -838,11 +838,11 @@ std::expected retire_compiler_runs(const std::filesystem::pat if (!located) return std::unexpected(located.error()); std::error_code ec; if (!std::filesystem::is_directory(located->root, ec)) return {}; - auto gate = mcpp::home::FileLock::acquire(located->root, "gate.lock", "", - std::chrono::milliseconds(300), {}); - if (!gate) return std::unexpected(std::format( - "an mcpp is building {}: it holds the compiler-run gate of {}; it was not cleaned", - mcpp::home::spelling(outputDir), mcpp::home::spelling(located->root))); + auto gate = mcpp::home::FileLock::acquire(located->root, "gate.lock", + {.resource = std::format("the compiler runs of {}", mcpp::home::spelling(outputDir)), + .doing = "cleaning the compiler runs"}); + if (!gate) return std::unexpected(std::format("{}; {} was not cleaned [{}]", gate.error().message(), + mcpp::home::spelling(outputDir), gate.error().token())); std::filesystem::directory_iterator runs(located->root, ec); if (ec) return std::unexpected("cannot inspect the compiler runs of " + mcpp::home::spelling(outputDir)); for (const auto& entry : runs) { @@ -876,9 +876,11 @@ std::expected RunScope::begin(const std::filesystem::path state->root = located->root; std::filesystem::create_directories(state->root, ec); if (ec) return std::unexpected("cannot create compiler-run runtime state: " + ec.message()); - state->gate = mcpp::home::FileLock::acquire(state->root, "gate.lock", "", - std::chrono::milliseconds(300), {}); - if (!state->gate) return std::unexpected("cannot acquire the compiler-run generation gate"); + auto gate = mcpp::home::FileLock::acquire(state->root, "gate.lock", + {.resource = std::format("the compiler runs of {}", mcpp::home::spelling(outputDir)), + .doing = "building"}); + if (!gate) return std::unexpected(std::format("{} [{}]", gate.error().message(), gate.error().token())); + state->gate = std::move(*gate); std::filesystem::directory_iterator previous(state->root, ec); if (ec) return std::unexpected("cannot inspect previous compiler runs"); for (const auto& entry : previous) { diff --git a/src/cli.cppm b/src/cli.cppm index 9adab8882..23fcf4ed5 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -46,6 +46,7 @@ import mcpp.home.files; import mcpp.build.action_progress; import mcpp.build.progress; // __action reports its start import mcpp.build.dirlock; // the build directory lock names this command +import mcpp.build.result; // the `waiting` event of the one wait reporter import mcpp.build.execute; // the sweep after a build (design 2026-10-31 §8.3) import mcpp.ui; import mcpp.log; @@ -253,8 +254,13 @@ int enter_system_home(int argc, char** argv) { if constexpr (mcpplibs::os::is_posix) mcpplibs::os::posix::set_creation_mask(022); mcpp::invocation::set("MCPP_HOME", home.string()); static std::optional held; - while (!(held = mcpp::home::FileLock::try_acquire(home))) - std::this_thread::sleep_for(std::chrono::milliseconds(200)); + auto lock = mcpp::home::FileLock::acquire(home, ".lock", + {.resource = std::format("the machine's home {}", home.string()), .doing = "setting up the machine's home"}); + if (!lock) { + mcpp::ui::error(std::format("{} [{}]", lock.error().message(), lock.error().token())); + return 4; + } + held = std::move(*lock); if (!mcpp::home::is_system_home(home)) std::ofstream(home / std::string(mcpp::home::kHomeMarker)) << "# The machine's mcpp home: written by `mcpp --system`, read by every user.\nmode = \"system\"\n"; return 0; @@ -383,6 +389,42 @@ int run(int argc, char** argv) { mcpp::build::dirlock::set_command(std::move(command)); } + // THE ONE SHAPE OF A WAIT (design 2026-11-27 §3.7 point 4). The first + // report names what is waited for, the lock file as given, the last + // recorded holder and whether that process is visible here, and how to + // bound the wait; each later report is one line. A holder that is not + // visible is not known to be gone: it may run in another process + // namespace, a container, or on a machine sharing the home. The machine + // stream gets the same facts as `waiting` events. + mcpp::home::set_wait_reporter([](const mcpp::home::WaitReport& r) { + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + const auto holder = mcpp::home::parse_holder(r.record); + const bool visible = mcpp::home::holder_visible(holder); + const auto who = mcpp::home::describe(holder, now); + if (r.first) { + mcpp::ui::status("Waiting", std::format("for {} ({})", r.resource, r.file.string())); + std::string more = std::format(" last recorded holder: {}{}\n", who, + holder.pid.empty() ? "" : visible ? ", a process visible here" : ", not a process visible here"); + if (!holder.pid.empty() && !visible) + more += std::format( + " it may run where this process cannot see it (another process namespace, a " + "container, or a machine sharing this home), or be a process that inherited the file; " + "`{}` lists the holders on this system\n", mcpp::home::holder_listing(r.file)); + more += " help: it ends when that process lets go; to stop waiting after a limit, " + "--lock-wait \n"; + mcpp::ui::block(more); + } else { + mcpp::ui::status("Waiting", std::format("{}s for {}, held by {}", + std::chrono::duration_cast(r.waited).count(), r.resource, who)); + } + mcpp::build::result::emit("waiting", { + {"holder", {{"pid", holder.pid}, {"command", holder.command}, {"client", holder.client}, + {"startedAt", holder.startedAt}}}, + {"waitedMs", r.waited.count()}, {"path", r.file.string()}, {"resource", r.resource}, + {"holderVisible", visible}}); + }); + // ─── --home : this run's home (design 2026-10-26 §9.1, SPEC-010) ── // Exactly MCPP_HOME for this process: the raw home of the two-step // selection, so its locator is still followed. Taken out of argv before @@ -485,6 +527,39 @@ int run(int argc, char** argv) { if (!denied.empty()) mcpp::invocation::set("MCPP_DENY_EFFECTS", denied); } + // ─── --lock-wait (design 2026-11-27 §3.7.2, D10) ─────────── + // The longest any wait of this command for a lock another process holds + // lasts; published as MCPP_LOCK_WAIT, which the provider's own lock reads + // as XLINGS_LOCK_TIMEOUT, so one limit governs every wait of the command. + // A value that is not a duration is a usage error before anything runs. + { + std::optional stated = mcpp::invocation::get("MCPP_LOCK_WAIT"); + bool fromFlag = false; + for (int i = 1; i < argc; ++i) { + const std::string_view a = argv[i]; + if (a == "--") break; + if (a == "--lock-wait") { + if (i + 1 >= argc) { mcpp::ui::error("--lock-wait needs a duration (30s, 2m, 1h, 0)"); return 2; } + stated = argv[i + 1]; + fromFlag = true; + } else if (a.starts_with("--lock-wait=")) { + stated = std::string(a.substr(12)); + fromFlag = true; + } + } + if (stated && !stated->empty()) { + const auto limit = mcpp::home::parse_wait(*stated); + if (!limit) { + mcpp::ui::error(std::format("{}: '{}' is not a duration; expected a number with s, m, h or " + "ms (30s, 2m, 1h, 500ms), or 0 for no wait", + fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT", *stated)); + return 2; + } + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, limit); + mcpp::invocation::set("MCPP_LOCK_WAIT", *stated); + } + } + // ─── --quiet / --no-color: pre-scan ───────────────────────────────── // The cmdline lib propagates global options into nested subcommand // ParsedArgs, but we set ui:: state up-front so that *every* line @@ -704,6 +779,9 @@ int run(int argc, char** argv) { .option(cl::Option("managed-only") .help("Fail if a toolchain, payload or plugin tool does not come from the ecosystem") .global()) + .option(cl::Option("lock-wait").takes_value().value_name("DURATION") + .help("Wait at most this long for a lock another mcpp holds, then refuse (30s, 2m, 0; also: MCPP_LOCK_WAIT)") + .global()) // Answers "what do you speak" without spawning a command that might // fail. An optimisation, NOT the client's detection rule: on any mcpp diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index 4d1457bd4..34cd6d4f0 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -235,12 +235,7 @@ namespace { void stream_build_events() { namespace res = mcpp::build::result; res::enable_events(true); - mcpp::build::dirlock::set_waiting_observer( - [](const mcpp::build::dirlock::Holder& h, std::chrono::milliseconds waited) { - res::emit("waiting", {{"holder", {{"pid", h.pid}, {"command", h.command}, - {"client", h.client}, {"startedAt", h.startedAt}}}, - {"waitedMs", waited.count()}}); - }); + // `waiting` is emitted by the one wait reporter the CLI sets (cli.cppm). mcpp::build::progress::set_step_observer([](std::size_t finished, std::size_t total) { res::emit("progress", {{"finished", finished}, {"total", total}}); }); diff --git a/src/config.cppm b/src/config.cppm index 9da97d273..27c8a6dc4 100644 --- a/src/config.cppm +++ b/src/config.cppm @@ -576,6 +576,10 @@ keep_days = 3 # project whose mcpp.toml does not say ([build] compile_commands). Unset: the # database stays in the build directory (target///). # compile_commands = "compile_commands.json" +# Wait at most this long for a lock another mcpp holds, then refuse +# (lock-wait-exceeded). Unset: the project's [build] lock_wait, else wait as +# long as the holder holds. --lock-wait and MCPP_LOCK_WAIT override it. +# lock_wait = "10m" )"; } @@ -1128,6 +1132,15 @@ std::expected load_or_init( if (auto v = doc->get_string("build.memory_threshold")) cfg.memoryThreshold = *v; else if (auto n = doc->get_int("build.memory_threshold")) cfg.memoryThreshold = std::to_string(*n); cfg.compileCommands = doc->get_string("build.compile_commands").value_or(""); + // The machine's tier of the wait limit (design 2026-11-27 §3.7.2). + if (auto v = doc->get_string("build.lock_wait")) { + if (auto limit = mcpp::home::parse_wait(*v)) + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Machine, limit); + else + mcpp::diag::warning("config", std::format("{}: ignoring [build] lock_wait = \"{}\", which is " + "not a duration (\"30s\", \"2m\", \"0\")", + cfg.configFile.string(), *v)); + } cfg.defaultToolchain = doc->get_string("toolchain.default").value_or(""); cfg.defaultTarget = doc->get_string("toolchain.default_target").value_or(""); // The system-level configuration (design 2026-10-16 §8.1, §9): what an diff --git a/src/home/files.cpp b/src/home/files.cpp index f02f98dc9..334ec7a0d 100644 --- a/src/home/files.cpp +++ b/src/home/files.cpp @@ -5,6 +5,7 @@ module mcpp.home.files; import std; import mcpplibs.os.fs; import mcpplibs.os.env; +import mcpplibs.os.process; namespace mcpp::home { @@ -32,12 +33,166 @@ void contention_point() { std::this_thread::sleep_for(std::chrono::milliseconds{wait}); } +// ── Holder records ──────────────────────────────────────────────────────── + +namespace { +std::string& command_slot() { + static std::string command = "mcpp"; + return command; +} +std::int64_t now_seconds() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); +} +} // namespace + +void set_command(std::string command) { command_slot() = std::move(command); } +const std::string& command() { return command_slot(); } + +Holder parse_holder(std::string_view record) { + Holder h; + std::size_t pos = 0; + while (pos < record.size()) { + auto end = record.find('\n', pos); + if (end == std::string_view::npos) end = record.size(); + const auto line = record.substr(pos, end - pos); + pos = end + 1; + const auto eq = line.find('='); + // A record before 2026.12.4.1 may be one line of prose (a turn's + // `what`): it is what the holder was doing. + if (eq == std::string_view::npos) { + if (h.doing.empty()) h.doing = std::string(line); + continue; + } + const auto key = line.substr(0, eq); + auto value = std::string(line.substr(eq + 1)); + if (key == "pid") h.pid = std::move(value); + else if (key == "command") h.command = std::move(value); + else if (key == "client") h.client = std::move(value); + else if (key == "doing") h.doing = std::move(value); + else if (key == "started") { + std::int64_t v = 0; + if (std::from_chars(value.data(), value.data() + value.size(), v).ec == std::errc{}) h.startedAt = v; + } + } + return h; +} + +std::string describe(const Holder& h, std::int64_t now) { + if (h.pid.empty()) return h.doing.empty() ? "another mcpp" : std::format("another mcpp, {}", h.doing); + std::vector parts; + if (!h.command.empty()) parts.push_back(h.command); + if (!h.doing.empty()) parts.push_back(h.doing); + if (!h.client.empty()) parts.push_back("from " + h.client); + if (h.startedAt > 0 && now >= h.startedAt) parts.push_back(std::format("started {}s ago", now - h.startedAt)); + std::string out = "pid " + h.pid; + if (!parts.empty()) { + out += " ("; + for (std::size_t i = 0; i < parts.size(); ++i) out += (i ? ", " : "") + parts[i]; + out += ")"; + } + return out; +} + +bool holder_visible(const Holder& h) { + std::uint64_t id = 0; + if (std::from_chars(h.pid.data(), h.pid.data() + h.pid.size(), id).ec != std::errc{} || id == 0) return false; + return mcpplibs::os::process::describe(id).has_value(); +} + +std::string holder_listing(const std::filesystem::path& file) { return native::holder_listing(file); } + +std::string owner_record(std::string_view doing) { + const auto client = mcpplibs::os::env::get("MCPP_CLIENT").value_or(""); + auto self = mcpplibs::os::process::self(); + return std::format("pid={}\nstarted={}\ncommand={}\nclient={}\ndoing={}\n", + self ? self->id : 0, now_seconds(), command_slot(), client, doing); +} + +// ── Waiting ─────────────────────────────────────────────────────────────── + +namespace { +std::mutex g_waitMutex; +std::function& reporter_slot() { + static std::function r; + return r; +} +std::array, 3> g_limits; +std::atomic g_waitedMs{0}; + +void report(const WaitReport& r) { + std::function reporter; + { + std::lock_guard g(g_waitMutex); + reporter = reporter_slot(); + } + if (reporter) reporter(r); +} + +// The waits at which a wait is reported: 300 ms, 10 s, 30 s, 60 s, then each minute. +std::chrono::milliseconds next_report(std::chrono::milliseconds after) { + using namespace std::chrono_literals; + for (auto at : {300ms, 10'000ms, 30'000ms, 60'000ms}) + if (after < at) return at; + return (after / 60'000ms + 1) * 60'000ms; +} +} // namespace + +void set_wait_reporter(std::function reporter) { + std::lock_guard g(g_waitMutex); + reporter_slot() = std::move(reporter); +} +void state_wait_limit(WaitSource source, std::optional limit) { + std::lock_guard g(g_waitMutex); + g_limits[static_cast(source)] = limit; +} +std::optional wait_limit() { + std::lock_guard g(g_waitMutex); + for (auto const& l : g_limits) + if (l) return l; + return std::nullopt; +} +std::chrono::milliseconds time_waited() { return std::chrono::milliseconds(g_waitedMs.load()); } + +std::optional parse_wait(std::string_view text) { + std::uint64_t n = 0; + const auto* first = text.data(); + const auto* last = text.data() + text.size(); + const auto [end, ec] = std::from_chars(first, last, n); + if (ec != std::errc{} || end == first) return std::nullopt; + const std::string_view unit(end, static_cast(last - end)); + std::uint64_t ms = 0; + if (unit.empty() || unit == "s") ms = n * 1000; + else if (unit == "ms") ms = n; + else if (unit == "m") ms = n * 60'000; + else if (unit == "h") ms = n * 3'600'000; + else return std::nullopt; + return std::chrono::milliseconds(static_cast(ms)); +} + +std::string LockFailure::message() const { + if (kind == Kind::Unavailable) + return std::format("cannot lock {} for {}: {}; {}", file.string(), resource, reason, remedy); + return std::format("waited {}s for {} ({}), the limit the wait was given; last recorded holder: {}. " + "It ends when that process does; wait longer with --lock-wait , or stop " + "the holder (`{}` lists it)", + std::chrono::duration_cast(waited).count(), resource, + file.string(), describe(parse_holder(record), now_seconds()), + native::holder_listing(file)); +} + +std::string_view LockFailure::token() const { + return kind == Kind::Unavailable ? "lock-unavailable" : "lock-wait-exceeded"; +} + +// ── FileLock ────────────────────────────────────────────────────────────── + std::optional FileLock::try_acquire(const std::filesystem::path& dir, std::string_view name) { std::error_code ec; std::filesystem::create_directories(dir, ec); - const auto handle = native::lock_file(dir / std::string(name)); - if (handle == -1) return std::nullopt; - return FileLock{handle}; + const auto attempt = native::lock_file(dir / std::string(name), false); + if (attempt.handle == -1) return std::nullopt; + return FileLock{attempt.handle}; } FileLock::~FileLock() { if (native_ != -1) native::unlock_file(native_); } @@ -53,39 +208,49 @@ FileLock& FileLock::operator=(FileLock&& o) noexcept { return *this; } -std::optional FileLock::acquire( - const std::filesystem::path& dir, std::string_view name, std::string_view owner, - std::chrono::milliseconds notice, - const std::function& waiting, bool* waited) { +std::expected FileLock::acquire( + const std::filesystem::path& dir, std::string_view name, const LockRequest& request, bool* waited) { namespace fs = std::filesystem; if (waited) *waited = false; contention_point(); + std::error_code ec; + fs::create_directories(dir, ec); + const auto file = dir / std::string(name); const auto start = std::chrono::steady_clock::now(); + const auto limit = request.bounded ? wait_limit() : std::nullopt; auto pause = std::chrono::milliseconds(20); - bool told = false; + auto reportAt = next_report(std::chrono::milliseconds(0)); + bool reported = false; + bool heldOnce = false; for (;;) { - if (auto lock = try_acquire(dir, name)) { - if (!owner.empty()) { - const auto record = dir / (std::string(name) + ".owner"); - auto tmp = record; - tmp += std::format(".{:x}", std::random_device{}()); - { - std::ofstream out(tmp, std::ios::binary | std::ios::trunc); - out << owner; - } - std::error_code ec; - fs::rename(tmp, record, ec); - if (ec) fs::remove(tmp, ec); - } - return lock; + const auto attempt = native::lock_file(file, request.shared); + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + if (attempt.handle != -1) { + if (heldOnce) g_waitedMs += elapsed.count(); + const auto record = dir / (std::string(name) + ".owner"); + (void)write_replacing(record, owner_record(request.doing)); + return FileLock{attempt.handle}; + } + if (!attempt.held && !(attempt.transient && elapsed < std::chrono::seconds(2))) + return std::unexpected(LockFailure{.kind = LockFailure::Kind::Unavailable, .file = file, + .resource = request.resource, .reason = attempt.reason, + .remedy = attempt.remedy, .waited = elapsed}); + if (attempt.held) { + heldOnce = true; + if (waited) *waited = true; } - // try_acquire could not even create the file: nothing to wait for. - std::error_code ec; - if (!fs::exists(dir / std::string(name), ec)) return std::nullopt; - if (waited) *waited = true; - if (!told && std::chrono::steady_clock::now() - start >= notice) { - told = true; - if (waiting) waiting(holder(dir, name)); + if (attempt.held && limit && elapsed >= *limit) { + g_waitedMs += elapsed.count(); + return std::unexpected(LockFailure{.kind = LockFailure::Kind::Exceeded, .file = file, + .resource = request.resource, + .record = holder(dir, name), .waited = elapsed}); + } + if (attempt.held && elapsed >= reportAt) { + report({.resource = request.resource, .file = file, .record = holder(dir, name), + .waited = elapsed, .first = !reported}); + reported = true; + reportAt = next_report(elapsed); } std::this_thread::sleep_for(pause); pause = (std::min)(pause * 2, std::chrono::milliseconds(200)); // parenthesised: defines min @@ -93,8 +258,7 @@ std::optional FileLock::acquire( } std::string FileLock::holder(const std::filesystem::path& dir, std::string_view name) { - std::ifstream in(dir / (std::string(name) + ".owner"), std::ios::binary); - return in ? std::string(std::istreambuf_iterator(in), {}) : std::string{}; + return read_whole(dir / (std::string(name) + ".owner")).value_or(""); } @@ -107,9 +271,7 @@ std::map& held_turns() { } } // namespace -Turn::Turn(const std::filesystem::path& dir, std::string_view name, std::string_view what, - std::chrono::milliseconds notice, - const std::function& waiting, bool* waited) { +Turn::Turn(const std::filesystem::path& dir, std::string_view name, const LockRequest& request, bool* waited) { if (waited) *waited = false; // A state not yet made has its directory made here when the directory // above it exists (a home's first install, before the provider wrote its @@ -120,7 +282,15 @@ Turn::Turn(const std::filesystem::path& dir, std::string_view name, std::string_ key_ = (dir / std::string(name)).lexically_normal().generic_string(); auto& t = held_turns()[key_]; if (t.depth++ > 0) return; - t.lock = FileLock::acquire(dir, name, what, notice, waiting, waited); + auto lock = FileLock::acquire(dir, name, request, waited); + if (lock) { + t.lock = std::move(*lock); + return; + } + // Not held: the writer refuses with why, rather than writing alone. + failure_ = lock.error(); + held_turns().erase(key_); + key_.clear(); } Turn::~Turn() { diff --git a/src/home/files.cppm b/src/home/files.cppm index 8cce90532..e4fd2580f 100644 --- a/src/home/files.cppm +++ b/src/home/files.cppm @@ -15,9 +15,95 @@ export namespace mcpp::home { // concurrent runs meet (design 2026-11-20 §5.19). void contention_point(); +// ── Holder records ──────────────────────────────────────────────────────── +// +// WHO LAST HELD A LOCK, as that process wrote it beside the lock +// (.owner, replaced atomically): a hint, never a fact. The system's lock +// is the fact; the record is written once the lock is held and never removed, +// so a record naming a process that no longer exists is every entry's normal +// state, not a sign of a lock left behind (design 2026-11-27 §3.7). +struct Holder { + std::string pid; + std::string command; + std::string client; // MCPP_CLIENT of the holder + std::string doing; // what the holder said it does ("installing compat.fmt v11") + std::int64_t startedAt = 0; // seconds since the epoch, 0 when unknown +}; +Holder parse_holder(std::string_view record); +// "pid 1234 (mcpp build -p a, from mcpp-ide, started 8s ago)"; "another mcpp" for no record. +std::string describe(const Holder& h, std::int64_t now); +// Whether the process the record names is one this process can see. Not +// seeing it does not mean it is gone: it may be in another process +// namespace, a container, or on another machine sharing the home. +bool holder_visible(const Holder& h); +// The command that lists the processes holding `file` on this system. +std::string holder_listing(const std::filesystem::path& file); +// This process's record; `doing` says what it holds the lock for. +std::string owner_record(std::string_view doing = {}); +// The command this process runs, as records name it: set once from argv. +void set_command(std::string command); +const std::string& command(); + +// ── Waiting ─────────────────────────────────────────────────────────────── + +// What a wait is for, and what a holder publishes. +struct LockRequest { + std::string resource; // what a waiter waits for: "the std module of gcc 15.1.0" + std::string doing; // published in the record once held + bool shared = false; // a shared hold; exclusive otherwise + bool bounded = true; // the wait limit applies (a gate on compile slots is not a state) +}; + +// One report of a wait in progress: at 300 ms, 10 s, 30 s, 60 s, then each +// minute (`first` on the first only). One shape for every wait in mcpp. +struct WaitReport { + std::string resource; + std::filesystem::path file; // the lock file, as given + std::string record; // the last holder's record + std::chrono::milliseconds waited{}; + bool first = false; +}; + +// Why a lock was not taken. +struct LockFailure { + enum class Kind { + Unavailable, // the system cannot lock the file: permissions, a read-only or + // lockless file system, no descriptor left; waiting would not end + Exceeded, // held by another past the wait limit (--lock-wait) + }; + Kind kind = Kind::Unavailable; + std::filesystem::path file; + std::string resource; + std::string reason; // the system's words (Unavailable) + std::string remedy; // by the reason (Unavailable) + std::string record; // the last holder's record (Exceeded) + std::chrono::milliseconds waited{}; + // The refusal's sentence, with its cause and its remedy. + std::string message() const; + // The reason token (docs/50): `lock-unavailable`, `lock-wait-exceeded`. + std::string_view token() const; +}; + +// Renders the reports of every wait; set once by the CLI for every command, +// so that no wait of mcpp is silent. +void set_wait_reporter(std::function reporter); +// The longest a bounded wait lasts, by the four tiers of a default (SPEC-004 +// §2): the override (`--lock-wait`, MCPP_LOCK_WAIT), the project's `[build] +// lock_wait`, the machine's (config.toml `[build] lock_wait`); none of them: +// as long as the holder holds (SPEC-011 §2). Each tier is stated when it is +// read; the first stated is the limit. +enum class WaitSource { Override, Project, Machine }; +void state_wait_limit(WaitSource source, std::optional limit); +std::optional wait_limit(); +// `30s`, `2m`, `1h`, `500ms`, or a number of seconds; `0` does not wait. +std::optional parse_wait(std::string_view text); +// The time this process spent waiting for locks others held: part of +// `Finished`'s account. +std::chrono::milliseconds time_waited(); + // ── FileLock ────────────────────────────────────────────────────────────── // -// RAII exclusive non-blocking file lock. +// RAII file lock, exclusive or shared. // Windows: LockFileEx on a HANDLE // POSIX: flock(2) on a file descriptor // NOT mcpplibs::os::fs::lock, whose POSIX lock is an open file description's @@ -28,33 +114,27 @@ void contention_point(); // here (src/native//lock.cpp) and nowhere else in mcpp. class FileLock { public: - // Try to acquire an exclusive lock on /.lock (or /). - // Returns nullopt if another process holds the lock. + // An exclusive lock on /.lock (or /), without waiting: + // nothing when another process holds it or the system cannot lock it -- + // for a caller that does something else then (skip a cache write). static std::optional try_acquire(const std::filesystem::path& dir, std::string_view name = ".lock"); - // WAITS for the lock on /, which `try_acquire` never does. - // - // Once held, `owner` is published beside the lock as /.owner - // (replaced atomically): who holds it, for a waiter to name. A sidecar - // rather than the lock file's own bytes, because a Windows byte-range lock - // is mandatory and would refuse that read. While the lock is taken by - // another process, `waiting` is called once, after `notice` has passed, - // with what the holder published (empty when it published nothing). - // - // The wait polls with a backoff from 20 ms to 200 ms rather than blocking - // in the kernel: a blocking flock/LockFileEx cannot report the wait, and a - // waiter killed by a signal holds nothing either way. nullopt only when - // the lock file cannot be created at all (an unwritable directory, whose - // build fails on its own terms). - // `waited`, when given, is set when the lock was held by another at the + // THE ONE WAIT FOR A LOCK. Taken at once when free. Held by another + // process: waited for, reported through the wait reporter, until it is + // free or the wait limit passes (Exceeded). Not lockable at all + // (Unavailable): refused at once, naming the file, the system's reason + // and the remedy -- before, such a failure was taken for a holder and + // waited for without end. Once held, this process's record is published + // beside the lock. The wait polls with a backoff from 20 ms to 200 ms + // rather than blocking in the kernel, which could not report. + // `waited`, when given, is set when another process held the lock at the // first try, however short the wait. - static std::optional acquire( - const std::filesystem::path& dir, std::string_view name, std::string_view owner, - std::chrono::milliseconds notice, - const std::function& waiting, bool* waited = nullptr); + static std::expected acquire( + const std::filesystem::path& dir, std::string_view name, const LockRequest& request, + bool* waited = nullptr); - // What the current holder of / published (see acquire). + // The record the last holder of / published. static std::string holder(const std::filesystem::path& dir, std::string_view name); ~FileLock(); @@ -79,19 +159,23 @@ private: // directory, so every path that reaches the state through a link takes one // turn. `waited` is set when another holder was waited out: what that holder // wrote is then looked for again. `dir` is made when the directory above it -// exists; a relative `dir`, or one whose lock cannot be created, gives no turn, -// and the caller goes on as before the turn existed. +// exists; a relative `dir` names no state and gives no turn. A turn that is +// not held -- the wait limit passed, or the file cannot be locked -- says why +// in `failure`, and the writer refuses with it. +// A turn the wait limit ended is not held: `failure` says why, and the +// writer refuses with it. class Turn { public: - Turn(const std::filesystem::path& dir, std::string_view name, std::string_view what, - std::chrono::milliseconds notice, - const std::function& waiting, bool* waited = nullptr); + Turn(const std::filesystem::path& dir, std::string_view name, const LockRequest& request, + bool* waited = nullptr); ~Turn(); Turn(const Turn&) = delete; Turn& operator=(const Turn&) = delete; + const std::optional& failure() const { return failure_; } private: std::string key_; + std::optional failure_; }; // `source` renamed over `destination`, which is not removed first: a failed @@ -137,7 +221,19 @@ void mark_used(const std::filesystem::path& recordFile); // The one primitive per system (src/native//lock.cpp). Not exported. namespace mcpp::home::native { -// An exclusive lock on the file, taken without waiting: the handle, or -1. -std::intptr_t lock_file(const std::filesystem::path& file); +// A lock on the file, taken without waiting: the handle; or -1 with `held` +// when another holds it; or -1 with the system's reason when the file cannot +// be locked at all, and whether the reason may pass in a moment (Windows +// refuses an open while another program renames over the file). +struct Attempt { + std::intptr_t handle = -1; + bool held = false; + bool transient = false; + std::string reason; + std::string remedy; +}; +Attempt lock_file(const std::filesystem::path& file, bool shared); void unlock_file(std::intptr_t handle); +// The command that lists the processes holding `file` on this system. +std::string holder_listing(const std::filesystem::path& file); } // namespace mcpp::home::native diff --git a/src/native/posix/lock.cpp b/src/native/posix/lock.cpp index 3f8c7fbb5..9795e14f9 100644 --- a/src/native/posix/lock.cpp +++ b/src/native/posix/lock.cpp @@ -1,5 +1,7 @@ // The lock every release of mcpp takes on Linux and macOS: flock(2). module; +#include +#include #include #include #include @@ -10,14 +12,43 @@ import std; namespace mcpp::home::native { -std::intptr_t lock_file(const std::filesystem::path& file) { +namespace { +// What to do about a file that cannot be locked, by the system's reason. +std::string remedy_for(int err, const std::filesystem::path& file) { + const auto dir = file.parent_path().string(); + switch (err) { + case EACCES: case EPERM: + return std::format("this user cannot create or write files in {}: give it write access, or point " + "MCPP_HOME (or the project) at a directory it owns", dir); + case EROFS: + return std::format("{} is on a read-only file system: point MCPP_HOME (or the project) at a " + "writable directory", dir); + case ENOLCK: case EINVAL: case EOPNOTSUPP: + return std::format("the file system of {} does not support file locks: point MCPP_HOME (or the " + "project) at a directory on a local file system", dir); + case EMFILE: case ENFILE: + return "the process has no file descriptor left: raise the limit (`ulimit -n`) or run fewer jobs"; + default: + return std::format("check that {} exists and this user can write it", dir); + } +} +} // namespace + +Attempt lock_file(const std::filesystem::path& file, bool shared) { const int fd = ::open(file.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644); - if (fd < 0) return -1; - if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + if (fd < 0) { + const int err = errno; + return {.reason = std::strerror(err), .remedy = remedy_for(err, file)}; + } + if (::flock(fd, (shared ? LOCK_SH : LOCK_EX) | LOCK_NB) != 0) { + const int err = errno; ::close(fd); - return -1; + // EWOULDBLOCK is the one answer that means another process holds it. + if (err == EWOULDBLOCK || err == EAGAIN) return {.held = true}; + if (err == EINTR) return {.transient = true, .reason = std::strerror(err)}; + return {.reason = std::strerror(err), .remedy = remedy_for(err, file)}; } - return fd; + return {.handle = fd}; } void unlock_file(std::intptr_t handle) { @@ -25,4 +56,8 @@ void unlock_file(std::intptr_t handle) { ::close(static_cast(handle)); } +std::string holder_listing(const std::filesystem::path& file) { + return std::format("lsof {}", file.string()); +} + } // namespace mcpp::home::native diff --git a/src/native/windows/lock.cpp b/src/native/windows/lock.cpp index 88e81752f..31e63c709 100644 --- a/src/native/windows/lock.cpp +++ b/src/native/windows/lock.cpp @@ -10,17 +10,58 @@ import std; namespace mcpp::home::native { -std::intptr_t lock_file(const std::filesystem::path& file) { +namespace { +std::string system_text(DWORD err) { + char* text = nullptr; + const DWORD n = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err, 0, + reinterpret_cast(&text), 0, nullptr); + std::string out = n && text ? std::string(text, n) : std::format("system error {}", err); + if (text) LocalFree(text); + while (!out.empty() && (out.back() == '\n' || out.back() == '\r' || out.back() == '.')) out.pop_back(); + return out; +} +std::string remedy_for(DWORD err, const std::filesystem::path& file) { + const auto dir = file.parent_path().string(); + switch (err) { + case ERROR_ACCESS_DENIED: + return std::format("this user cannot create or write files in {}: give it write access, or point " + "MCPP_HOME (or the project) at a directory it owns", dir); + case ERROR_WRITE_PROTECT: + return std::format("{} is on a read-only volume: point MCPP_HOME (or the project) at a writable " + "directory", dir); + case ERROR_NOT_SUPPORTED: case ERROR_INVALID_FUNCTION: + return std::format("the file system of {} does not support file locks: point MCPP_HOME (or the " + "project) at a directory on a local volume", dir); + case ERROR_TOO_MANY_OPEN_FILES: + return "the process has no handle left: run fewer jobs"; + default: + return std::format("check that {} exists and this user can write it", dir); + } +} +} // namespace + +Attempt lock_file(const std::filesystem::path& file, bool shared) { HANDLE h = CreateFileW(file.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) return -1; + if (h == INVALID_HANDLE_VALUE) { + const DWORD err = GetLastError(); + // Refused for a moment while another program renames over the file or + // a scanner holds it: retried by the caller, as a read is. + const bool transient = err == ERROR_SHARING_VIOLATION || err == ERROR_ACCESS_DENIED; + return {.transient = transient, .reason = system_text(err), .remedy = remedy_for(err, file)}; + } OVERLAPPED ov = {}; - if (!LockFileEx(h, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &ov)) { + const DWORD flags = (shared ? 0 : LOCKFILE_EXCLUSIVE_LOCK) | LOCKFILE_FAIL_IMMEDIATELY; + if (!LockFileEx(h, flags, 0, 1, 0, &ov)) { + const DWORD err = GetLastError(); CloseHandle(h); - return -1; + // The answers that mean another process holds the byte. + if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) return {.held = true}; + return {.reason = system_text(err), .remedy = remedy_for(err, file)}; } - return reinterpret_cast(h); + return {.handle = reinterpret_cast(h)}; } void unlock_file(std::intptr_t handle) { @@ -29,4 +70,9 @@ void unlock_file(std::intptr_t handle) { CloseHandle(reinterpret_cast(handle)); } +std::string holder_listing(const std::filesystem::path& file) { + return std::format("handle.exe {} (Sysinternals), or Resource Monitor's \"Associated Handles\"", + file.string()); +} + } // namespace mcpp::home::native diff --git a/src/provider/xlings/xlings.cpp b/src/provider/xlings/xlings.cpp index 08f547bf6..d0ac580f6 100644 --- a/src/provider/xlings/xlings.cpp +++ b/src/provider/xlings/xlings.cpp @@ -1086,6 +1086,14 @@ std::vector invocation_env(const Env& env) { } if (mcpp::effects::offline_mode()) vars.push_back({"XLINGS_NET_UNREACHABLE", "mcpp runs offline", true}); + // ONE LIMIT FOR EVERY WAIT OF THE COMMAND (design 2026-11-27 §3.11.2 + // point 11): a stated wait limit reaches the provider's own state lock as + // XLINGS_LOCK_TIMEOUT, in whole seconds. There `0` waits without end, so + // mcpp's `0` (do not wait) is its shortest wait, one second. + if (const auto limit = mcpp::home::wait_limit()) { + const auto seconds = std::max(1, (limit->count() + 999) / 1000); + vars.push_back({"XLINGS_LOCK_TIMEOUT", std::to_string(seconds), true}); + } return vars; } @@ -1126,12 +1134,20 @@ namespace { // takes the turn; a caller already holding it (an install in prepare) nests. // When the provider writes atomically, the turn orders writers that no longer // collide, and costs a lock per install. -void hold_state_turn(std::optional& t, const Env& env, std::string_view what) { - t.emplace(state_dir(env), mcpp::provider::kStateTurn, what, std::chrono::seconds(2), - [](std::string_view holder) { - mcpp::log::verbose("xlings", std::format("waiting for the provider's state turn{}{}", - holder.empty() ? "" : ", held by ", holder)); - }); +// False when the turn is not held: the wait limit passed, or its lock cannot +// be taken. The refusal is said here, once, and the writer does not write. +[[nodiscard]] std::string refused_turn(const std::optional& t) { + if (!t || !t->failure()) return {}; + return std::format("{} [{}]", t->failure()->message(), t->failure()->token()); +} +[[nodiscard]] bool hold_state_turn(std::optional& t, const Env& env, std::string_view what) { + t.emplace(state_dir(env), mcpp::provider::kStateTurn, + mcpp::home::LockRequest{.resource = "the install state of this home", .doing = std::string(what)}); + if (auto why = refused_turn(t); !why.empty()) { + mcpp::ui::error(why); + return false; + } + return true; } bool writes_state(std::string_view capability) { return capability == "install_packages" || capability == "add_repo" || capability == "remove_repo"; @@ -1140,7 +1156,7 @@ bool writes_state(std::string_view capability) { void select_runtime(const Env& env, std::string_view runtimeId) { std::optional turn; - hold_state_turn(turn, env, "choosing the runtime"); + if (!hold_state_turn(turn, env, "choosing the runtime")) return; auto inv = invocation(env, { "config", "--runtime", std::string(runtimeId) }); inv.options.streams = mcpp::run::Streams::discard; (void)mcpp::run::execute(inv.argv, inv.options); @@ -1325,7 +1341,12 @@ call(const Env& env, std::string_view capability, // split an event; discarding it lost the one line that names a rejection. // It is read only when the call fails. std::optional turn; - if (writes_state(capability)) hold_state_turn(turn, env, std::format("xlings {}", capability)); + if (writes_state(capability)) { + turn.emplace(state_dir(env), mcpp::provider::kStateTurn, + mcpp::home::LockRequest{.resource = "the install state of this home", + .doing = std::format("xlings {}", capability)}); + if (auto why = refused_turn(turn); !why.empty()) return std::unexpected(why); + } auto inv = invocation(env, { "interface", std::string(capability), "--args", std::string(argsJson) }); const auto cmd = mcpp::build::command_line::display(inv.argv); @@ -1678,7 +1699,7 @@ int install_with_progress(const Env& env, std::string_view target, if (!quiet) print_status("Installing", target); mcpp::effects::note_network_access(); std::optional turn; - hold_state_turn(turn, env, std::format("installing {}", target)); + if (!hold_state_turn(turn, env, std::format("installing {}", target))) return 1; auto inv = invocation(env, { "interface", "install_packages", "--args", argsJson }); int resultExitCode = -1; @@ -1763,7 +1784,7 @@ int install_with_progress(const Env& env, std::string_view target, int install_direct(const Env& env, std::string_view target, bool quiet) { std::optional turn; - hold_state_turn(turn, env, std::format("installing {}", target)); + if (!hold_state_turn(turn, env, std::format("installing {}", target))) return 1; auto inv = invocation(env, { "install", std::string(target), "-y" }); mcpp::effects::note_network_access(); // An empty standard input. Lines are passed through as the inherited @@ -1806,7 +1827,7 @@ int download_to(const Env& env, std::span refs, const std::fi int install_from(const Env& env, const std::filesystem::path& dir, std::span refs) { std::optional turn; - hold_state_turn(turn, env, std::format("installing from {}", dir.string())); + if (!hold_state_turn(turn, env, std::format("installing from {}", dir.string()))) return 1; std::vector args{"install", "--from", dir.string()}; args.insert(args.end(), refs.begin(), refs.end()); args.push_back("-y"); @@ -1817,7 +1838,7 @@ int collect_store(const Env& env, bool dryRun) { // A collection removes payloads an install of another process may be // about to name: it holds the turn every writer of the home's state holds. std::optional turn; - if (!dryRun) hold_state_turn(turn, env, "collecting the store"); + if (!dryRun && !hold_state_turn(turn, env, "collecting the store")) return 1; std::vector args{"self", "clean"}; if (dryRun) args.push_back("--dry-run"); return run_shown(invocation(env, std::move(args))); @@ -1960,7 +1981,7 @@ void ensure_init(const Env& env, bool quiet) { Env globalEnv = env; globalEnv.projectDir.clear(); std::optional turn; - hold_state_turn(turn, globalEnv, "initialising the sandbox"); + if (!hold_state_turn(turn, globalEnv, "initialising the sandbox")) return; auto inv = invocation(globalEnv, { "self", "init" }); inv.options.streams = mcpp::run::Streams::discard; inv.options.total = std::chrono::seconds{120}; @@ -2301,10 +2322,12 @@ int update_index_unguarded(const Env& env, bool quiet) { return 0; } auto waited = mcpp::home::FileLock::acquire( - paths::index_data(env), ".lock", "a refresh of the package index", - std::chrono::milliseconds(500), [&](std::string_view) { - if (!quiet) print_status("Waiting", "for the package index another mcpp is refreshing"); - }); + paths::index_data(env), ".lock", + {.resource = "the package index another mcpp is refreshing", .doing = "refreshing the package index"}); + if (!waited) { + mcpp::ui::error(waited.error().message() + std::format(" [{}]", waited.error().token())); + return 1; + } return 0; } diff --git a/src/toolchain/stdmod.cppm b/src/toolchain/stdmod.cppm index 319a38a32..0039f0baa 100644 --- a/src/toolchain/stdmod.cppm +++ b/src/toolchain/stdmod.cppm @@ -240,21 +240,33 @@ bool metadata_matches(const std::filesystem::path& path, const nlohmann::json& e == expected["std_compat_build_commands"]; } +// THE RECORD IS THE ENTRY'S COMPLETION MARKER (design 2026-11-27 §3.7 point 1): +// written by the process that built the entry once every file of the parts it +// lists is in place, by a rename, so a reader sees the previous record or this +// one and never a part. `parts` lists what is complete: `std`, `std.compat`. std::expected write_metadata(const std::filesystem::path& path, - const nlohmann::json& metadata) { - std::ofstream os(path, std::ios::binary); - if (!os) { + nlohmann::json metadata, + const std::vector& parts) { + metadata["parts"] = parts; + if (!mcpp::home::write_replacing(path, metadata.dump(2) + "\n")) return std::unexpected(StdModError{ std::format("cannot write std module metadata '{}'", path.string())}); - } - os << metadata.dump(2) << "\n"; - if (!os) { - return std::unexpected(StdModError{ - std::format("failed while writing std module metadata '{}'", path.string())}); - } return {}; } +// The parts a record states complete; none for a record before 2026.12.4.1, +// which states none. +std::vector recorded_parts(const std::filesystem::path& path) { + const auto text = mcpp::home::read_whole(path); + if (!text) return {}; + auto doc = nlohmann::json::parse(*text, nullptr, false); + std::vector out; + if (doc.is_object() && doc.contains("parts") && doc["parts"].is_array()) + for (auto const& p : doc["parts"]) + if (p.is_string()) out.push_back(p.get()); + return out; +} + // Toolchain-declared env (MSVC's INCLUDE/LIB/PATH) applies to every std // module build command; empty for GCC/Clang, whose LD_LIBRARY_PATH need is // part of the recorded command text (an `env` prefix on Linux). @@ -481,33 +493,62 @@ std::expected ensure_built( const auto& compatCommands = desc.compatCommands; const auto& metadata = derivation->metadata; auto metaPath = metadata_path(sm.cacheDir); - // ONE BUILDER PER ENTRY. The entry is shared by every build of this home, and two + // ONE BUILDER PER ENTRY, AND NO LOCK FOR A READER (design 2026-11-27 §3.7, + // SPEC-011 §3). The entry is shared by every build of this home, and two // processes that found it missing compiled into the same files at once: the // second clang read a std.pcm the first was rewriting (SIGBUS), and a build - // went on with no std.o. The check and the build happen under the entry's - // lock, so a second process waits and then finds the entry built. + // went on with no std.o. A builder holds the entry's lock. A reader does + // not: the record is written last, by a rename, and lists the parts it + // completed, so a record that lists what this build needs, beside its + // files, is a finished entry. Before, every build took the lock, a hit + // included, and a holder that never let go stopped every build of the home + // that used this toolchain. + const bool wantCompat = want_compat && !compatCommands.empty(); + auto files_of_std = [&] { + return std::filesystem::exists(sm.bmiPath) && std::filesystem::exists(sm.objectPath); + }; + auto files_of_compat = [&] { return std::filesystem::exists(desc.compatBmiPath); }; + auto complete = [&] { + if (!metadata_matches(metaPath, metadata)) return false; + const auto parts = recorded_parts(metaPath); + auto listed = [&](std::string_view p) { return std::ranges::contains(parts, p); }; + return listed("std") && files_of_std() && (!wantCompat || (listed("std.compat") && files_of_compat())); + }; + auto finished = [&]() -> StdModule { + // A hit is a use, stated on the record (mcpp::home::mark_used). + mcpp::home::mark_used(metaPath); + if (wantCompat) { + sm.compatBmiPath = desc.compatBmiPath; + sm.compatObjectPath = desc.compatObjectPath; + } + return sm; + }; + if (complete()) return finished(); + { std::error_code ec; std::filesystem::create_directories(sm.cacheDir, ec); } - namespace dirlock = mcpp::build::dirlock; auto entryLock = mcpp::home::FileLock::acquire( - sm.cacheDir, ".mcpp-build.lock", dirlock::owner_record(), std::chrono::milliseconds(300), - [&](std::string_view record) { - const auto now = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); - mcpp::ui::status("Waiting", std::format("for the std module, compiled by {}", - dirlock::describe(dirlock::parse_holder(record), now))); - }); - bool std_cached = std::filesystem::exists(sm.bmiPath) - && std::filesystem::exists(sm.objectPath) - && metadata_matches(metaPath, metadata); - bool rebuiltStd = false; - // A hit is a use, stated on the record (mcpp::home::mark_used). - if (std_cached) mcpp::home::mark_used(metaPath); - - if (!std_cached) { + sm.cacheDir, ".mcpp-build.lock", + {.resource = std::format("the std module entry of {} {}", tc.label(), cpp_standard), + .doing = "building the std module"}); + if (!entryLock) + return std::unexpected(StdModError{mcpp::build::dirlock::refused(entryLock.error())}); + // Another process may have finished it while this one waited. + if (complete()) return finished(); + + // What is already there, by a record that matches: a record written before + // 2026.12.4.1 lists no parts, and its files are the parts it built -- they + // are listed now, once, without compiling them again. + const bool matches = metadata_matches(metaPath, metadata); + bool stdDone = matches && files_of_std(); + bool compatDone = matches && stdDone && files_of_compat(); + if (!stdDone) { + // Rebuilt: the record goes first, so no reader takes the entry while + // its files are rewritten. std::error_code ec; + std::filesystem::remove(metaPath, ec); std::filesystem::create_directories(sm.bmiPath.parent_path(), ec); if (ec) return std::unexpected(StdModError{ std::format("cannot create '{}': {}", sm.bmiPath.parent_path().string(), ec.message())}); @@ -520,28 +561,25 @@ std::expected ensure_built( std::format("expected BMI at '{}' but it wasn't produced; output:\n{}", sm.bmiPath.string(), *out)}); } - rebuiltStd = true; + stdDone = true; + compatDone = false; } // Build std.compat after std (std.compat imports std; Clang + MSVC), and // only for a build that imports it. - if (want_compat && !compatCommands.empty()) { - const auto& compatBmi = desc.compatBmiPath; - if (rebuiltStd || !std::filesystem::exists(compatBmi) - || !metadata_matches(metaPath, metadata)) { - if (auto out = run_commands(compatCommands, tc); !out) { - return std::unexpected(with_coroutine_note(out.error())); - } + if (wantCompat && !compatDone) { + if (auto out = run_commands(compatCommands, tc); !out) { + return std::unexpected(with_coroutine_note(out.error())); } - sm.compatBmiPath = desc.compatBmiPath; - sm.compatObjectPath = desc.compatObjectPath; + compatDone = true; } - if (auto r = write_metadata(metaPath, metadata); !r) { + std::vector parts{"std"}; + if (compatDone) parts.push_back("std.compat"); + if (auto r = write_metadata(metaPath, metadata, parts); !r) { return std::unexpected(r.error()); } - - return sm; + return finished(); } } // namespace mcpp::toolchain From 5bdf5770b41684bf8112cf7b045db85bec4bad8c Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 4 Dec 2026 23:37:54 +0900 Subject: [PATCH 03/36] mcpp new makes a git repository: --vcs and [new] vcs override it; none inside another tree unless asked After the scaffold is committed, `git init` runs with the variables that point git elsewhere removed; nothing is added or committed. A project made inside a git work tree or a directory holding an mcpp.toml gets no repository unless --vcs git states it. Without git the project is made and reported (new/vcs-unavailable), or refused with vcs-unavailable when --vcs git asked. --- src/build/prepare/manifest.cpp | 2 +- src/build/refusal.cppm | 4 + src/cli.cppm | 5 +- src/cli/cmd_new.cppm | 19 +++++ src/config.cppm | 8 +- src/home/files.cpp | 20 +++-- src/home/files.cppm | 8 +- src/scaffold/create.cppm | 114 ++++++++++++++++++++++++++++ tests/e2e/_inherit_toolchain.sh | 6 ++ tests/e2e/cli/new_repository.cpp | 123 +++++++++++++++++++++++++++++++ tests/support/src/support.cpp | 7 ++ tests/support/src/support.cppm | 1 + tests/unit/test_platform_fs.cpp | 83 +++++++++++++++++++-- 13 files changed, 386 insertions(+), 14 deletions(-) create mode 100644 tests/e2e/cli/new_repository.cpp diff --git a/src/build/prepare/manifest.cpp b/src/build/prepare/manifest.cpp index d90bb7b75..93c4eb82a 100644 --- a/src/build/prepare/manifest.cpp +++ b/src/build/prepare/manifest.cpp @@ -579,7 +579,7 @@ std::expected phase0_manifest_and_workspace(PrepareState& sta "{}: [build] lock_wait = \"{}\" is not a duration; expected a number with s, m, h or ms " "(\"30s\", \"2m\"), or \"0\" for no wait", (*state.root / "mcpp.toml").string(), state.m->buildConfig.lockWait)); - mcpp::home::state_wait_limit(mcpp::home::WaitSource::Project, limit); + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Project, limit, "[build] lock_wait in mcpp.toml"); } // A DISTRIBUTION package is not a source tree, and building "in" one is a diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index 4960855d2..1a6078bc2 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -250,6 +250,9 @@ enum class Code { // A lock file the system cannot lock at all: permissions, a read-only or // lockless file system, no descriptor left. Waiting would not end. LockUnavailable, + // `mcpp new --vcs git` made the project, and `git init` could not be + // done: git is not on PATH, or it failed. The project is kept. + VcsUnavailable, Other, // a refusal that has not been given a code yet }; @@ -325,6 +328,7 @@ constexpr std::string_view name(Code c) { return "index-location-named-twice"; case Code::LockWaitExceeded: return "lock-wait-exceeded"; case Code::LockUnavailable: return "lock-unavailable"; + case Code::VcsUnavailable: return "vcs-unavailable"; case Code::Other: return "other"; } return "other"; diff --git a/src/cli.cppm b/src/cli.cppm index 23fcf4ed5..cc5da93dc 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -555,7 +555,8 @@ int run(int argc, char** argv) { fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT", *stated)); return 2; } - mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, limit); + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, limit, + fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT"); mcpp::invocation::set("MCPP_LOCK_WAIT", *stated); } } @@ -800,6 +801,8 @@ int run(int argc, char** argv) { .help("bin (default) | lib | platform | [ns.]pkg[@ver][:template] — exact package template")) .option(cl::Option("list-templates").takes_value().value_name("PKG") .help("List templates from exact [ns.]pkg[@ver]")) + .option(cl::Option("vcs").takes_value().value_name("VCS") + .help("git (default) | none: a repository for the new project; inside another project or repository, only when stated (config.toml [new] vcs)")) .action(cmd_new)) .subcommand(cl::App("build") .description("Build the current package") diff --git a/src/cli/cmd_new.cppm b/src/cli/cmd_new.cppm index e7c069354..16e43d7db 100644 --- a/src/cli/cmd_new.cppm +++ b/src/cli/cmd_new.cppm @@ -53,6 +53,25 @@ export int cmd_new(const mcpplibs::cmdline::ParsedArgs& parsed) { return 2; } + // The version control of the new project: `--vcs`, else config.toml's + // `[new] vcs`, else git (design 2026-11-27 §3.8). + { + mcpp::scaffold::VcsRequest vcs; + auto valid = [](std::string_view v) { return v == "git" || v == "none"; }; + if (auto v = parsed.value("vcs")) { + if (!valid(*v)) { + mcpp::ui::error(std::format("--vcs '{}': expected git or none", *v)); + return 2; + } + vcs = {*v, mcpp::scaffold::VcsRequest::From::Command}; + } else if (auto m = mcpp::scaffold::machine_vcs()) { + if (valid(*m)) vcs = {*m, mcpp::scaffold::VcsRequest::From::Machine}; + else mcpp::diag::warning("config", std::format( + "ignoring [new] vcs = \"{}\" of config.toml: expected \"git\" or \"none\"", *m)); + } + mcpp::scaffold::set_vcs_request(std::move(vcs)); + } + // `--template` exact package SPEC: // builtin registry (bin, lib; gui = transitional alias), else a // package template: [ns.]pkg | [ns.]pkg:tmpl | [ns.]pkg@ver:tmpl. diff --git a/src/config.cppm b/src/config.cppm index 27c8a6dc4..6000411d1 100644 --- a/src/config.cppm +++ b/src/config.cppm @@ -580,6 +580,12 @@ keep_days = 3 # (lock-wait-exceeded). Unset: the project's [build] lock_wait, else wait as # long as the holder holds. --lock-wait and MCPP_LOCK_WAIT override it. # lock_wait = "10m" + +[new] +# Version control for a project `mcpp new` creates: "git" makes a repository +# (no commit; the branch is git's), "none" makes none. A project created inside +# another project or repository gets one only with `mcpp new --vcs git`. +# vcs = "git" )"; } @@ -1135,7 +1141,7 @@ std::expected load_or_init( // The machine's tier of the wait limit (design 2026-11-27 §3.7.2). if (auto v = doc->get_string("build.lock_wait")) { if (auto limit = mcpp::home::parse_wait(*v)) - mcpp::home::state_wait_limit(mcpp::home::WaitSource::Machine, limit); + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Machine, limit, "[build] lock_wait in config.toml"); else mcpp::diag::warning("config", std::format("{}: ignoring [build] lock_wait = \"{}\", which is " "not a duration (\"30s\", \"2m\", \"0\")", diff --git a/src/home/files.cpp b/src/home/files.cpp index 334ec7a0d..7f073ce0f 100644 --- a/src/home/files.cpp +++ b/src/home/files.cpp @@ -118,6 +118,7 @@ std::function& reporter_slot() { return r; } std::array, 3> g_limits; +std::array g_limitSources; std::atomic g_waitedMs{0}; void report(const WaitReport& r) { @@ -142,9 +143,17 @@ void set_wait_reporter(std::function reporter) { std::lock_guard g(g_waitMutex); reporter_slot() = std::move(reporter); } -void state_wait_limit(WaitSource source, std::optional limit) { +void state_wait_limit(WaitSource source, std::optional limit, + std::string stated) { std::lock_guard g(g_waitMutex); g_limits[static_cast(source)] = limit; + g_limitSources[static_cast(source)] = std::move(stated); +} +std::string wait_limit_source() { + std::lock_guard g(g_waitMutex); + for (std::size_t i = 0; i < g_limits.size(); ++i) + if (g_limits[i]) return g_limitSources[i]; + return {}; } std::optional wait_limit() { std::lock_guard g(g_waitMutex); @@ -173,12 +182,12 @@ std::optional parse_wait(std::string_view text) { std::string LockFailure::message() const { if (kind == Kind::Unavailable) return std::format("cannot lock {} for {}: {}; {}", file.string(), resource, reason, remedy); - return std::format("waited {}s for {} ({}), the limit the wait was given; last recorded holder: {}. " + return std::format("waited {}s for {} ({}), the limit {} states; last recorded holder: {}. " "It ends when that process does; wait longer with --lock-wait , or stop " "the holder (`{}` lists it)", std::chrono::duration_cast(waited).count(), resource, - file.string(), describe(parse_holder(record), now_seconds()), - native::holder_listing(file)); + file.string(), limitSource.empty() ? std::string("the wait limit") : limitSource, + describe(parse_holder(record), now_seconds()), native::holder_listing(file)); } std::string_view LockFailure::token() const { @@ -244,7 +253,8 @@ std::expected FileLock::acquire( g_waitedMs += elapsed.count(); return std::unexpected(LockFailure{.kind = LockFailure::Kind::Exceeded, .file = file, .resource = request.resource, - .record = holder(dir, name), .waited = elapsed}); + .record = holder(dir, name), + .limitSource = wait_limit_source(), .waited = elapsed}); } if (attempt.held && elapsed >= reportAt) { report({.resource = request.resource, .file = file, .record = holder(dir, name), diff --git a/src/home/files.cppm b/src/home/files.cppm index e4fd2580f..2424d2d9c 100644 --- a/src/home/files.cppm +++ b/src/home/files.cppm @@ -77,6 +77,7 @@ struct LockFailure { std::string reason; // the system's words (Unavailable) std::string remedy; // by the reason (Unavailable) std::string record; // the last holder's record (Exceeded) + std::string limitSource; // where the limit was stated (Exceeded) std::chrono::milliseconds waited{}; // The refusal's sentence, with its cause and its remedy. std::string message() const; @@ -92,9 +93,14 @@ void set_wait_reporter(std::function reporter); // lock_wait`, the machine's (config.toml `[build] lock_wait`); none of them: // as long as the holder holds (SPEC-011 §2). Each tier is stated when it is // read; the first stated is the limit. +// `stated` names where the value was written, for the refusal that ends a +// wait: `--lock-wait`, `MCPP_LOCK_WAIT`, `[build] lock_wait in mcpp.toml`. enum class WaitSource { Override, Project, Machine }; -void state_wait_limit(WaitSource source, std::optional limit); +void state_wait_limit(WaitSource source, std::optional limit, + std::string stated); std::optional wait_limit(); +// Where the limit in force was stated; empty when there is none. +std::string wait_limit_source(); // `30s`, `2m`, `1h`, `500ms`, or a number of seconds; `0` does not wait. std::optional parse_wait(std::string_view text); // The time this process spent waiting for locks others held: part of diff --git a/src/scaffold/create.cppm b/src/scaffold/create.cppm index f40daf516..25884d1f6 100644 --- a/src/scaffold/create.cppm +++ b/src/scaffold/create.cppm @@ -17,6 +17,11 @@ import mcpp.pm.resolver; import mcpp.scaffold; import mcpp.scaffold.project_name; import mcpp.ui; +import mcpp.diag; +import mcpp.run; +import mcpp.home; +import mcpp.libs.toml; +import mcpp.build.refusal; // vcs-unavailable import mcpp.build.test_protocol; // the release of mtest the skeleton's tests use import mcpp.toolchain.target_schema; import mcpp.toolchain.target_rows; // the llvm a platform skeleton pins, as the built-in rows do @@ -169,6 +174,112 @@ void print_template_listing(const FetchedTemplatePackage& pkg, pkg.selector); } +// ── The new project's version control (design 2026-11-27 §3.8, #1038) ────── +// +// One concept, `vcs`, two values: `git` (the engine's default) and `none`. +// The command's `--vcs` is the highest tier and config.toml's `[new] vcs` the +// machine's; a project has none, for it does not exist yet. A project made +// inside another project or a version-controlled tree is that tree's: it gets +// no repository of its own unless `--vcs git` asks for one. `git init` runs +// after the scaffold is committed and is not part of it: it adds nothing and +// commits nothing, and leaves the branch name to the user's git. +export struct VcsRequest { + std::string value = "git"; + enum class From { Engine, Machine, Command } from = From::Engine; +}; + +namespace { +VcsRequest g_vcs; + +// The variables that point git at another repository. With them `git init` +// makes the repository elsewhere -- `mcpp new` run from a git hook does. +// git's own list (`git rev-parse --local-env-vars`). +const std::vector& foreign_repository_variables() { + static const std::vector names{ + "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", + "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", + "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX", + "GIT_SHALLOW_FILE", "GIT_COMMON_DIR"}; + return names; +} + +mcpp::run::RunResult git(std::vector args) { + args.insert(args.begin(), "git"); + mcpp::run::Options o; + o.unset = foreign_repository_variables(); + o.streams = mcpp::run::Streams::output_error_kept; + o.report_spawn_failure = false; + return mcpp::run::execute(args, o); +} + +// The tree `dir` is made inside, when it is another's: a git work tree, or a +// directory that holds an mcpp.toml (a workspace's root, or any project). +std::string enclosing_tree(const std::filesystem::path& dir) { + const auto parent = dir.parent_path(); + if (auto r = git({"-C", parent.string(), "rev-parse", "--show-toplevel"}); + r.spawn_error == 0 && r.exit_code == 0) { + auto top = r.output; + while (!top.empty() && (top.back() == '\n' || top.back() == '\r')) top.pop_back(); + return std::format("the git work tree at {}", top); + } + std::error_code ec; + for (auto p = parent; !p.empty(); p = p.parent_path()) { + if (std::filesystem::is_regular_file(p / "mcpp.toml", ec)) + return std::format("the project at {}", p.string()); + if (p == p.parent_path()) break; + } + return {}; +} +} // namespace + +export void set_vcs_request(VcsRequest request) { g_vcs = std::move(request); } + +// The machine's `[new] vcs` (config.toml of this home, then the system's), +// read without making a home: `mcpp new` needs none. +export std::optional machine_vcs() { + for (auto const& file : {mcpp::home::root() / "config.toml", mcpp::home::system_config_file()}) { + std::error_code ec; + if (!std::filesystem::is_regular_file(file, ec)) continue; + auto doc = mcpp::libs::toml::parse_file(file); + if (!doc) continue; + if (auto v = doc->get_string("new.vcs")) return *v; + } + return std::nullopt; +} + +// After the scaffold of `dir` is committed: 0, or 1 when a `--vcs git` the +// command stated could not be done (the project stays). +export int init_vcs(const std::filesystem::path& dir) { + if (g_vcs.value == "none") return 0; + const bool stated = g_vcs.from == VcsRequest::From::Command; + const auto inside = enclosing_tree(dir); + if (!inside.empty() && !stated) return 0; // the enclosing tree's; nothing to say + const auto r = git({"init", "--quiet", dir.string()}); + if (r.spawn_error != 0 || r.exit_code != 0) { + std::string why = r.spawn_error != 0 + ? std::format("git could not be started ({})", r.spawn_detail.empty() ? "not found on PATH" : r.spawn_detail) + : std::format("`git init` exited {}: {}", r.exit_code, r.error_output.empty() ? r.output : r.error_output); + while (!why.empty() && (why.back() == '\n' || why.back() == ' ')) why.pop_back(); + if (stated) { + mcpp::build::refusal::record(mcpp::build::refusal::Code::VcsUnavailable); + mcpp::ui::error(std::format("{} was created, but it is not a repository: {} [vcs-unavailable]", + dir.string(), why)); + return 1; + } + mcpp::diag::degraded("new/vcs-unavailable", + std::format("{} was created without a repository: {}", dir.string(), why), + "the directory is not a repository, and its .gitignore takes effect only once it is one", + std::format("`git init {}`, or `mcpp new --vcs none` (config.toml [new] vcs = \"none\")", + dir.string())); + return 0; + } + if (!inside.empty()) + mcpp::diag::note("new/vcs-inside-another", + std::format("{} is inside {}; it has a repository of its own, as --vcs git asks", dir.string(), inside)); + mcpp::ui::status("Initialized", std::format("a git repository in {}", dir.string())); + return 0; +} + export int list_package_templates(const mcpp::scaffold::TemplateSpec& spec) { auto pkg = fetch_template_package(spec); if (!pkg) { mcpp::ui::error(pkg.error()); return 1; } @@ -268,6 +379,7 @@ export int new_from_package_template( "{} (template {}@{}:{})", project.qualifiedName, pkg->selector, pkg->version, chosen->name)); + if (const int vcs = init_vcs(tx.final_path()); vcs != 0) return vcs; // What `new` says about what it made is narration, like the `Created` // line above it: standard error, so that the project's creation is not // part of what a pipe receives. @@ -549,6 +661,7 @@ UTest greeting{"hello greets by name", [] { mcpp::ui::line(std::format("Created {} package '{}' at {}", lib ? "lib" : gui ? "gui" : "bin", project.qualifiedName, tx.final_path().string())); + if (const int vcs = init_vcs(tx.final_path()); vcs != 0) return vcs; mcpp::ui::line(lib ? std::format("Next: cd {} && mcpp build && mcpp test", project.directoryName) : std::format("Next: cd {} && mcpp build && mcpp run (or `mcpp test`)", project.directoryName)); @@ -628,6 +741,7 @@ driver = "compiler" } mcpp::ui::line(std::format("Created platform package '{}' at {}, defining {}", project.qualifiedName, tx.final_path().string(), triple)); + if (const int vcs = init_vcs(tx.final_path()); vcs != 0) return vcs; mcpp::ui::line(std::format("Next: cd {} && mcpp why platform", project.directoryName)); return 0; } diff --git a/tests/e2e/_inherit_toolchain.sh b/tests/e2e/_inherit_toolchain.sh index 77556d5f2..85b7b9e15 100644 --- a/tests/e2e/_inherit_toolchain.sh +++ b/tests/e2e/_inherit_toolchain.sh @@ -66,3 +66,9 @@ if [[ -d "$USER_MCPP/bin" ]]; then || ln -sf "$USER_MCPP/bin" "$MCPP_HOME/bin" 2>/dev/null \ || cp -r "$USER_MCPP/bin" "$MCPP_HOME/bin" fi +# A case's project is a fixture, not a repository: `mcpp new` in this home makes +# none (design 2026-11-27 §3.8); a case of that feature states `--vcs` itself. +# A home with no config.toml is a fresh one, whose first run writes it: left so. +if [[ -f "$MCPP_HOME/config.toml" ]] && ! grep -q '^\[new\]' "$MCPP_HOME/config.toml"; then + printf '\n[new]\nvcs = "none"\n' >> "$MCPP_HOME/config.toml" +fi diff --git a/tests/e2e/cli/new_repository.cpp b/tests/e2e/cli/new_repository.cpp new file mode 100644 index 000000000..02d26873a --- /dev/null +++ b/tests/e2e/cli/new_repository.cpp @@ -0,0 +1,123 @@ +// `mcpp new` and the new project's version control (design 2026-11-27 §3.8, mcpp#1038): a project +// made alone is a git repository with no commit; one made inside another tree is that tree's unless +// `--vcs git` asks; `--vcs none` and config.toml's `[new] vcs` make none; without git the project is +// made and the missing repository reported, or refused when `--vcs git` asked for it. +import std; +import mcpplibs.mtest; +import mcpp.test.support; + +using namespace mcpplibs::mtest; +namespace s = mcpp::test::support; +namespace fs = std::filesystem; + +namespace { + +using Env = std::vector>>; + +// `mcpp new` as a user types it -- not through the kit, which states `--vcs none` -- in an empty +// home of the case, which states nothing about version control. +e2e::outcome plain_new(const fs::path& cwd, std::vector args, Env env = {}) { + args.insert(args.begin(), "new"); + env.push_back({"MCPP_HOME", s::another_home(s::home::fresh).string()}); + return s::run(s::mcpp_path(), args, cwd, env); +} + +std::string git(const fs::path& dir, std::vector args, Env env = {}) { + const auto program = s::on_path("git"); + if (!program) skip("git is not installed"); + args.insert(args.begin(), {"-C", dir.string()}); + auto r = s::run(*program, args, {}, std::move(env)); + return s::last_line(r.out); +} + +bool repository(const fs::path& dir) { return fs::exists(dir / ".git"); } + +// Three places a project is made inside another tree: a git work tree, a workspace, a project. +std::vector enclosing_places(const fs::path& base) { + const auto tree = base / "tree", workspace = base / "workspace", project = base / "project"; + fs::create_directories(tree); + (void)git(tree, {"init", "--quiet"}); + fs::create_directories(workspace); + std::ofstream(workspace / "mcpp.toml") << "[workspace]\nmembers = []\n"; + fs::create_directories(project); + std::ofstream(project / "mcpp.toml") << "[package]\nname = \"outer\"\nversion = \"0.1.0\"\n"; + return {tree, workspace, project}; +} + +E2E new_repository{"new-repository", [] { + "a project made alone is a repository with no commit, on git's branch"_test[s::git] = [] { + const auto dir = s::case_dir(); + const auto config = dir / "gitconfig"; + std::ofstream(config) << "[init]\n\tdefaultBranch = trunk\n"; + const Env gitEnv{{"GIT_CONFIG_GLOBAL", config.string()}, {"GIT_CONFIG_NOSYSTEM", "1"}}; + const auto r = plain_new(dir, {"alpha"}, gitEnv); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(repository(dir / "alpha"))); + expect(e2e::contains(r.err, "Initialized a git repository in")); + expect(git(dir / "alpha", {"symbolic-ref", "--short", "HEAD"}, gitEnv) == "trunk"); + expect(git(dir / "alpha", {"rev-list", "--all", "--count"}) == "0") << "a commit was made"; + expect(git(dir / "alpha", {"status", "--porcelain"}) != "") << "the files were added"; + }; + + "a project made inside another tree has no repository of its own"_test[s::git] = [] { + for (const auto& place : enclosing_places(s::case_dir())) { + const auto r = plain_new(place, {"inner"}); + expect(fatal(e2e::succeeded(r))) << place << s::text(r); + expect(!repository(place / "inner")) << place; + expect(!e2e::contains(r.err, "Initialized")) << place; + } + }; + + "--vcs git makes one there, and names the tree it is inside"_test[s::git] = [] { + for (const auto& place : enclosing_places(s::case_dir())) { + const auto r = s::mcpp({"new", "inner", "--vcs", "git"}, place); + expect(fatal(e2e::succeeded(r))) << place << s::text(r); + expect(repository(place / "inner")) << place; + expect(e2e::contains(r.err, "is inside")) << place << r.err; + } + }; + + "--vcs none, and config.toml's [new] vcs, make none"_test = [] { + const auto dir = s::case_dir(); + expect(fatal(e2e::succeeded(s::mcpp({"new", "plain", "--vcs", "none"}, dir)))); + expect(!repository(dir / "plain")); + const auto home = s::another_home(s::home::fresh); + std::ofstream(home / "config.toml") << "[new]\nvcs = \"none\"\n"; + const auto r = s::run(s::mcpp_path(), {"new", "configured"}, dir, {{"MCPP_HOME", home.string()}}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(!repository(dir / "configured")); + e2e::expect_diagnostic("--vcs 'svn': expected git or none"); + const auto bad = s::mcpp({"new", "other", "--vcs", "svn"}, dir); + expect(bad.status == 2) << s::text(bad); + }; + + "without git the project is made and the missing repository said, or refused when asked"_test[s::unix_shell] = [] { + const auto dir = s::case_dir(); + const auto empty = dir / "no-git"; + fs::create_directories(empty); + e2e::expect_diagnostic("was created without a repository"); + e2e::expect_diagnostic("was created, but it is not a repository"); + const auto quiet = plain_new(dir, {"unversioned"}, {{"PATH", empty.string()}}); + expect(fatal(e2e::succeeded(quiet))) << s::text(quiet); + expect(fs::exists(dir / "unversioned" / "mcpp.toml")); + expect(e2e::contains(quiet.err, "was created without a repository")) << quiet.err; + const auto asked = s::mcpp({"new", "versioned", "--vcs", "git"}, dir, {.env = {{"PATH", empty.string()}}}); + expect(asked.status != 0) << s::text(asked); + expect(fs::exists(dir / "versioned" / "mcpp.toml")) << "the project was not kept"; + expect(e2e::contains(asked.err, "[vcs-unavailable]")) << asked.err; + }; + + "GIT_DIR naming another repository does not move the new one"_test[s::git] = [] { + const auto dir = s::case_dir(); + const auto other = dir / "other"; + fs::create_directories(other); + (void)git(other, {"init", "--quiet"}); + const auto r = plain_new(dir, {"zeta"}, {{"GIT_DIR", (other / ".git").string()}, + {"GIT_WORK_TREE", other.string()}}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(repository(dir / "zeta")); + expect(git(other, {"status", "--porcelain"}) == "") << "the other repository was written"; + }; +}}; + +} // namespace diff --git a/tests/support/src/support.cpp b/tests/support/src/support.cpp index 2a111fb6c..bea3e5e4c 100644 --- a/tests/support/src/support.cpp +++ b/tests/support/src/support.cpp @@ -368,6 +368,13 @@ e2e::outcome mcpp(std::vector args, const fs::path& cwd, const opti std::optional own_home_of_case(); // below, with the case's directories e2e::command mcpp_command(std::vector args, const fs::path& cwd, const options& o) { + // `mcpp new` makes a git repository by default (design 2026-11-27 §3.8). A case's project is a + // fixture, not a repository: `--vcs none` unless the case states `--vcs` itself, which the + // cases of that feature do. + if (!args.empty() && args.front() == "new" && std::ranges::none_of(args, [](const std::string& a) { + return a == "--vcs" || a.starts_with("--vcs=") || a == "--list-templates"; + })) + args.insert(args.begin() + 1, {"--vcs", "none"}); e2e::command c; c.argv = o.wrap; c.argv.push_back(mcpp_path()); diff --git a/tests/support/src/support.cppm b/tests/support/src/support.cppm index 2ab5f92cb..d0ac3f067 100644 --- a/tests/support/src/support.cppm +++ b/tests/support/src/support.cppm @@ -74,6 +74,7 @@ const capability gcc{"gcc", {.os = {platform::linux}, .program = {"g++"}}}; const capability patchelf{"patchelf", {.os = {platform::linux}, .program = {"patchelf"}}}; const capability pack{"pack", {.all = {patchelf}}}; const capability python3{"python3", {.program = {"python3"}}}; +const capability git{"git", {.program = {"git"}}}; const capability jq{"jq", {.program = {"jq"}}}; const capability wine{"wine", {.os = {platform::linux}, .program = {"wine"}}}; const capability qemu_riscv{"qemu-riscv", {.os = {platform::linux}, .program = {"qemu-system-riscv64"}}}; diff --git a/tests/unit/test_platform_fs.cpp b/tests/unit/test_platform_fs.cpp index fe6dfdd99..65252cb00 100644 --- a/tests/unit/test_platform_fs.cpp +++ b/tests/unit/test_platform_fs.cpp @@ -136,9 +136,9 @@ UTest a_turn_is_held_once_and_nests{"PlatformFs/ATurnIsHeldOnceAndNests", [] { std::atomic inside{false}; std::atomic overlaps{0}; auto hold = [&](bool* waited) { - mcpp::home::Turn outer(dir.path, ".turn", "test", std::chrono::seconds(60), {}, waited); + mcpp::home::Turn outer(dir.path, ".turn", {.resource = "the test's turn", .doing = "test"}, waited); { - mcpp::home::Turn inner(dir.path, ".turn", "test", std::chrono::seconds(60), {}); + mcpp::home::Turn inner(dir.path, ".turn", {.resource = "the test's turn", .doing = "test"}); if (inside.exchange(true)) ++overlaps; std::this_thread::sleep_for(std::chrono::milliseconds(200)); inside = false; @@ -161,10 +161,10 @@ UTest a_turn_is_held_once_and_nests{"PlatformFs/ATurnIsHeldOnceAndNests", [] { bool linkedWaited = false; { std::optional held; - held.emplace(dir.path, ".turn", "test", std::chrono::seconds(60), std::function{}); + held.emplace(dir.path, ".turn", mcpp::home::LockRequest{.resource = "the test's turn", .doing = "test"}); std::jthread other([&] { - mcpp::home::Turn through(std::filesystem::canonical(link), ".turn", "test", std::chrono::seconds(60), {}, - &linkedWaited); + mcpp::home::Turn through(std::filesystem::canonical(link), ".turn", + {.resource = "the test's turn", .doing = "test"}, &linkedWaited); }); std::this_thread::sleep_for(std::chrono::milliseconds(100)); held.reset(); @@ -173,3 +173,76 @@ UTest a_turn_is_held_once_and_nests{"PlatformFs/ATurnIsHeldOnceAndNests", [] { std::filesystem::remove(link, ec); expect(linkedWaited) << "a turn reached through a link was not the same turn"; }}; + +// THE ONE WAIT (design 2026-11-27 §3.7): a wait for a lock another holder holds is reported, first +// with everything and then one line at a time, and ends at the limit with the holder's record; a +// file that cannot be locked at all is refused at once, never waited for. +UTest a_wait_is_reported_and_ends_at_its_limit{"PlatformFs/AWaitIsReportedAndEndsAtItsLimit", [] { + TempDir dir; + std::vector reports; + std::mutex m; + mcpp::home::set_wait_reporter([&](const mcpp::home::WaitReport& r) { + std::lock_guard g(m); + reports.push_back(r); + }); + auto held = mcpp::home::FileLock::acquire(dir.path, ".lock", {.resource = "the test's lock", .doing = "holding"}); + expect(fatal(held.has_value())); + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, std::chrono::milliseconds(700), "--lock-wait"); + // Another open file description of the same file: flock and LockFileEx exclude it as they + // exclude another process. + std::expected second = std::unexpected(mcpp::home::LockFailure{}); + std::jthread other([&] { + second = mcpp::home::FileLock::acquire(dir.path, ".lock", {.resource = "the test's lock", .doing = "waiting"}); + }); + other.join(); + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, std::nullopt, ""); + mcpp::home::set_wait_reporter({}); + expect(fatal(!second.has_value())); + expect(second.error().kind == mcpp::home::LockFailure::Kind::Exceeded); + expect(eq(second.error().token(), std::string_view("lock-wait-exceeded"))); + expect(second.error().message().find("the limit --lock-wait states") != std::string::npos) << second.error().message(); + expect(second.error().message().find("doing=") == std::string::npos); + expect(fatal(!reports.empty())) << "the wait was not reported"; + expect(reports.front().first); + expect(eq(reports.front().resource, std::string("the test's lock"))); + expect(mcpp::home::parse_holder(reports.front().record).doing == "holding") << reports.front().record; +}}; + +UTest a_wait_limit_is_read_by_tier{"PlatformFs/AWaitLimitIsReadByTier", [] { + using mcpp::home::WaitSource; + expect(eq(mcpp::home::parse_wait("30s")->count(), 30'000)); + expect(eq(mcpp::home::parse_wait("2m")->count(), 120'000)); + expect(eq(mcpp::home::parse_wait("500ms")->count(), 500)); + expect(eq(mcpp::home::parse_wait("0")->count(), 0)); + expect(!mcpp::home::parse_wait("soon").has_value()); + expect(!mcpp::home::parse_wait("5 s").has_value()); + mcpp::home::state_wait_limit(WaitSource::Machine, std::chrono::milliseconds(3000), "config"); + mcpp::home::state_wait_limit(WaitSource::Project, std::chrono::milliseconds(2000), "project"); + expect(eq(mcpp::home::wait_limit()->count(), 2000)); + expect(eq(mcpp::home::wait_limit_source(), std::string("project"))); + mcpp::home::state_wait_limit(WaitSource::Override, std::chrono::milliseconds(1000), "--lock-wait"); + expect(eq(mcpp::home::wait_limit()->count(), 1000)); + for (auto w : {WaitSource::Override, WaitSource::Project, WaitSource::Machine}) + mcpp::home::state_wait_limit(w, std::nullopt, ""); + expect(!mcpp::home::wait_limit().has_value()); +}}; + +UTest a_file_that_cannot_be_locked_is_refused_at_once{"PlatformFs/AFileThatCannotBeLockedIsRefusedAtOnce", [] { + // Windows grants an administrator what the permissions here would deny; the refusal by the + // system's own words is the same code on every system. + if constexpr (mcpplibs::os::is_windows) return; + TempDir dir; + { std::ofstream(dir.path / ".lock") << ""; } + std::filesystem::permissions(dir.path / ".lock", std::filesystem::perms::none); + // A user that reads every file (root) opens it anyway: nothing to observe. + if (std::ifstream(dir.path / ".lock")) return; + const auto start = std::chrono::steady_clock::now(); + auto r = mcpp::home::FileLock::acquire(dir.path, ".lock", {.resource = "the test's lock"}); + expect(std::chrono::steady_clock::now() - start < std::chrono::seconds(1)) << "it waited"; + expect(fatal(!r.has_value())); + expect(r.error().kind == mcpp::home::LockFailure::Kind::Unavailable); + expect(eq(r.error().token(), std::string_view("lock-unavailable"))); + expect(!r.error().reason.empty()); + expect(!r.error().remedy.empty()); + std::filesystem::permissions(dir.path / ".lock", std::filesystem::perms::owner_all); +}}; From 6d0ba9092ea2fd085dbacf1e87bdfc0982ff75c5 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 27 Nov 2026 17:53:46 +0900 Subject: [PATCH 04/36] test(e2e): a link and a pack under a caller's XLINGS_SUBOS_LD_PATHS keep the run path mcpp derived xlings' ld wrapper appends -rpath "$XLINGS_SUBOS_LIB" to a link of a non-system loader unless XLINGS_SUBOS_LD_PATHS=0, which mcpp declares for everything it starts. Two cases state what that holds from mcpp's side, with the caller's XLINGS_SUBOS_LD_PATHS=1 and a XLINGS_SUBOS_LIB of its own: - the programs the link starts (observed through gcc's -wrapper, which sees collect2, the linker's parent) and a build program read XLINGS_SUBOS_LD_PATHS=0, and the artifact's run path equals the -Wl,-rpath entries of the link line, without the caller's directory; - every ELF object a pack bundles names only $ORIGIN directories. The declaration is the one cli.cppm makes for the invocation; no spawn dropped it, so no code changes. Without the declaration the first case fails on both observations. Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- tests/e2e/build/linker_declaration.cpp | 169 +++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 tests/e2e/build/linker_declaration.cpp diff --git a/tests/e2e/build/linker_declaration.cpp b/tests/e2e/build/linker_declaration.cpp new file mode 100644 index 000000000..6ecc1acdc --- /dev/null +++ b/tests/e2e/build/linker_declaration.cpp @@ -0,0 +1,169 @@ +// The linker's run-path rule from mcpp's side (xlings design 2026-11-27 §8.3, C1): xlings' `ld` +// wrapper appends `-rpath "$XLINGS_SUBOS_LIB"` to a link of a non-system loader unless +// XLINGS_SUBOS_LD_PATHS=0. mcpp declares the 0 for everything it starts, whatever its caller set, +// so an artifact's run path is the one mcpp itself derived from the binding it selected, and a +// pack holds no path of the machine that built it. +// +// What these cases hold without the wrapper (binutils before its r1 carries none): the variable +// each program mcpp starts receives, and the run path the artifact ends with. With the wrapper +// installed the second would fail were the declaration missing. +import std; +import mcpplibs.mtest; +import mcpp.test.support; + +using namespace mcpplibs::mtest; +namespace s = mcpp::test::support; +namespace fs = std::filesystem; + +namespace { + +std::vector split(std::string_view text, char sep) { + std::vector out; + for (auto part : std::views::split(text, sep)) + if (part.begin() != part.end()) out.emplace_back(part.begin(), part.end()); + return out; +} + +// The first build.ninja of the project's target, outside the build program's tree. +std::string graph_of(const s::project& p) { + for (const auto& f : s::find_files(p.at("target"), R"(build\.ninja)")) + if (f.generic_string().find("/.build-mcpp/") == std::string::npos) return s::read_file(f); + expect(fatal(false)) << "no build.ninja generated"; + return {}; +} + +// The directories the link line gives the linker as run path (`-Wl,-rpath,`), as the linker +// reads them (ninja's `$$` is a `$`). +std::set rpath_of_graph(const std::string& graph) { + std::set out; + static const std::regex rpath{R"(-Wl,-rpath,([^\s"']+))"}; + for (std::sregex_iterator it{graph.begin(), graph.end(), rpath}, end; it != end; ++it) { + std::string dir = (*it)[1].str(); + for (auto at = dir.find("$$"); at != std::string::npos; at = dir.find("$$", at + 1)) dir.erase(at, 1); + out.insert(std::move(dir)); + } + return out; +} + +std::set rpath_of_artifact(const fs::path& file) { + const auto parts = split(s::read_header(file).runpath, ':'); + return {parts.begin(), parts.end()}; +} + +std::string joined(const std::set& entries) { + std::string out; + for (const auto& e : entries) out += (out.empty() ? "" : ":") + e; + return out; +} + +std::optional program_under(const fs::path& root, std::string_view name) { + for (const auto& f : s::find_files(root, std::string(name))) + if (f.generic_string().find("/.build-mcpp/") == std::string::npos && f.generic_string().find("/bin/") != std::string::npos) + return f; + return std::nullopt; +} + +std::string output_of(const fs::path& program) { + auto out = s::run(program).out; + while (out.ends_with('\n') || out.ends_with('\r')) out.pop_back(); + return out; +} + +// The regular files under `root`, not the links. +std::vector plain_files(const fs::path& root) { + std::vector out; + std::error_code ec; + if (fs::is_directory(root, ec)) + for (const auto& e : fs::recursive_directory_iterator(root)) + if (!e.is_symlink() && e.is_regular_file()) out.push_back(e.path()); + std::ranges::sort(out); + return out; +} + +// What a caller that meets the wrapper without mcpp's declaration would give it: a directory of +// the caller's own as the active SubOS's library directory, and the variable that lets the +// wrapper add it. +std::vector>> callers_env(const fs::path& subos_lib) { + return {{"XLINGS_SUBOS_LIB", subos_lib.string()}, {"XLINGS_SUBOS_LD_PATHS", std::string("1")}}; +} + +E2E linker_declaration{"linker_declaration", s::home_fixture, [] { + "1177 a link under a caller's SubOS keeps the run path mcpp derived"_test[s::gcc][s::elf][s::unix_shell] = [] { + // The caller's XLINGS_SUBOS_LD_PATHS=1 and XLINGS_SUBOS_LIB do not reach the link as + // they were given: the programs the link starts (the compiler driver, and what it starts + // for the link) and a build program read XLINGS_SUBOS_LD_PATHS=0, and the artifact's run + // path is exactly the `-Wl,-rpath,` of the link line, without the caller's directory. + const auto tmp = s::case_dir(); + const auto subos_lib = tmp / "callers-subos" / "lib"; + fs::create_directories(subos_lib); + const auto log = tmp / "driver-env.log"; + s::write_executable(tmp / "observe.sh", std::format(R"sh(#!/bin/sh +# gcc's -wrapper runs each program of the link (collect2, which starts the linker) as `$@`. +printf '%s LD_PATHS=%s LIB=%s\n' "$(basename "$1")" "${{XLINGS_SUBOS_LD_PATHS-unset}}" "${{XLINGS_SUBOS_LIB-unset}}" >> '{}' +exec "$@" +)sh", log.string())); + s::project p{tmp / "p", {{"mcpp.toml", std::format(R"([package] +name = "rp" +version = "0.1.0" + +[build] +ldflags = ["-wrapper", "{}"] +)", (tmp / "observe.sh").string())}, + {"src/main.cpp", R"cpp(#include +int main() { std::printf("%d\n", LD_PATHS_SEEN_BY_BUILD_PROGRAM); } +)cpp"}, + {"build.mcpp", R"cpp(import mcpp; +import std; +int main() { + const char* v = std::getenv("XLINGS_SUBOS_LD_PATHS"); + mcpp::cxxflag(std::format("-DLD_PATHS_SEEN_BY_BUILD_PROGRAM={}", v && *v == '0' && !v[1] ? 0 : 7).c_str()); +} +)cpp"}}}; + auto r = p.mcpp({"build"}, {.env = callers_env(subos_lib)}); + expect(fatal(e2e::succeeded(r))) << "the build failed\n" << s::text(r); + const auto bin = program_under(p.at("target"), "rp"); + expect(fatal(bin.has_value())) << "no program was produced"; + expect(output_of(*bin) == "0") << "the build program saw XLINGS_SUBOS_LD_PATHS other than 0 (7 is anything else, the caller's 1 included): " << output_of(*bin); + + const auto seen = s::read_file(log); + expect(fatal(e2e::contains(seen, "collect2 "))) << "the compiler driver started no collect2 under -wrapper: the link was not observed\n" << seen; + for (const auto& l : split(seen, '\n')) { + expect(e2e::contains(l, "LD_PATHS=0 ")) << "a program of the link was not told XLINGS_SUBOS_LD_PATHS=0: " << l; + expect(e2e::contains(l, "LIB=" + subos_lib.string())) << "the caller's XLINGS_SUBOS_LIB was dropped on the way (the case would prove nothing about the opt-out): " << l; + } + + const auto intent = rpath_of_graph(graph_of(p)); + const auto actual = rpath_of_artifact(*bin); + expect(fatal(actual == intent)) << "the artifact's run path is not the one mcpp put on the link line\n link line: " << joined(intent) << "\n artifact: " << joined(actual); + expect(fatal(!joined(actual).contains(subos_lib.string()))) << "the caller's SubOS directory is in the run path: " << joined(actual); + expect(fatal(!joined(actual).contains("callers-subos"))) << "the caller's SubOS is in the run path: " << joined(actual); + }; + + "1178 a pack holds no run path outside its bundle"_test[s::pack][s::gcc][s::elf] = [] { + // Under a caller's XLINGS_SUBOS_LD_PATHS=1 and XLINGS_SUBOS_LIB, no ELF object of the + // packed program names a directory other than one under its own $ORIGIN: not the + // caller's SubOS, not the home's store, not the registry's farm. + const auto tmp = s::case_dir(); + const auto subos_lib = tmp / "callers-subos" / "lib"; + fs::create_directories(subos_lib); + auto app = s::project::scaffold("bundled"); + auto r = app.mcpp({"pack"}, {.env = callers_env(subos_lib)}); + expect(fatal(e2e::succeeded(r))) << "pack failed\n" << s::text(r); + std::optional tarball; + for (const auto& f : s::find_files(app.at("target/dist"), R"(.*\.tar\.gz)")) tarball = f; + expect(fatal(tarball.has_value())) << "no tarball\n" << s::text(r); + s::tar_extract(*tarball, tmp / "x"); + std::size_t objects = 0; + for (const auto& obj : plain_files(tmp / "x")) { + const auto h = s::read_header(obj); + if (h.kind != s::format::elf || !h.wide) continue; + ++objects; + const auto rel = fs::relative(obj, tmp / "x").generic_string(); + for (const auto& entry : split(h.runpath, ':')) + expect(entry.starts_with("$ORIGIN")) << rel << " names a run-path directory outside the bundle: " << entry << " (run path " << h.runpath << ")"; + } + expect(fatal(objects > 0u)) << "the bundle holds no ELF object: nothing was checked"; + }; +}}; + +} // namespace From 385096f0109916c71076f408818ad6c52a1bca81 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 00:16:01 +0900 Subject: [PATCH 05/36] The command line as its own guide: help from the tree, --agent-skill-doc sheets, usage errors with next steps, one explain registry mcpplibs.cmdline 0.2.0 with its agent-skills feature. The root help is printed from the command tree in its groups and ends with the line that points agents at --agent-skill-doc; `mcpp help ` is ` --help`; internal commands are hidden. The sheets under docs/mcpp-skills are rendered into the binary by build.mcpp and answered at every level of the tree without a project, a home or the network; a unit test parses every example by the tree. A usage error is one line and at most two help lines (the closest declared names, the --help to read), and a mcpp.usage envelope when JSON was asked for. A command run outside a project names the two next steps. mcpp explain answers E codes, MCPP_* codes and every reason token from mcpp.explain, whose titles docs/50 states; an unknown code gets the closest. Documentation of the lock waits (SPEC-011 v1.3, docs/25, docs/50) and of the new project's repository (docs/01). --- .../2026-11-27-ecosystem-boundary-design.md | 5 +- .agents/skills/mcpp-usage/SKILL.md | 190 +- AGENTS.md | 2 +- CHANGELOG.md | 43 + README.md | 7 +- README.zh-CN.md | 8 +- build.mcpp | 14 + docs/01-getting-started.md | 11 + docs/04-mcpp-toml.md | 1 + docs/09-commands-by-scenario.md | 17 +- docs/25-home-indices-and-store.md | 29 + docs/50-machine-output.md | 57 +- docs/52-driving-mcpp-from-a-program.md | 27 + docs/README.md | 1 + docs/mcpp-skills/mcpp-add/SKILL.md | 36 + docs/mcpp-skills/mcpp-build/SKILL.md | 55 + docs/mcpp-skills/mcpp-cache/SKILL.md | 35 + docs/mcpp-skills/mcpp-clean/SKILL.md | 35 + docs/mcpp-skills/mcpp-emit/SKILL.md | 35 + docs/mcpp-skills/mcpp-explain/SKILL.md | 32 + docs/mcpp-skills/mcpp-fetch/SKILL.md | 39 + docs/mcpp-skills/mcpp-index/SKILL.md | 38 + docs/mcpp-skills/mcpp-new/SKILL.md | 42 + docs/mcpp-skills/mcpp-pack/SKILL.md | 41 + docs/mcpp-skills/mcpp-publish/SKILL.md | 34 + docs/mcpp-skills/mcpp-remove/SKILL.md | 29 + docs/mcpp-skills/mcpp-resolve/SKILL.md | 28 + docs/mcpp-skills/mcpp-run/SKILL.md | 43 + docs/mcpp-skills/mcpp-search/SKILL.md | 33 + docs/mcpp-skills/mcpp-self/SKILL.md | 43 + docs/mcpp-skills/mcpp-stage/SKILL.md | 34 + docs/mcpp-skills/mcpp-test/SKILL.md | 48 + docs/mcpp-skills/mcpp-toolchain/SKILL.md | 40 + docs/mcpp-skills/mcpp-update/SKILL.md | 32 + docs/mcpp-skills/mcpp-version/SKILL.md | 31 + docs/mcpp-skills/mcpp-why/SKILL.md | 39 + docs/mcpp-skills/mcpp-write/SKILL.md | 31 + docs/mcpp-skills/mcpp-xpkg/SKILL.md | 33 + docs/mcpp-skills/mcpp/SKILL.md | 97 + docs/specs/README.md | 2 +- docs/specs/concurrency.md | 43 +- docs/zh/01-getting-started.md | 8 + docs/zh/04-mcpp-toml.md | 1 + docs/zh/09-commands-by-scenario.md | 16 +- docs/zh/25-home-indices-and-store.md | 22 + docs/zh/50-machine-output.md | 45 +- docs/zh/52-driving-mcpp-from-a-program.md | 19 + docs/zh/README.md | 1 + mcpp.toml | 8 +- src/build/execute.cppm | 4 +- src/build/prepare/manifest.cpp | 2 +- src/cli.cppm | 2041 ++++++++--------- src/cli/cmd_build.cppm | 8 +- src/cli/cmd_publish.cppm | 2 +- src/cli/cmd_self.cppm | 24 +- src/doctor.cppm | 72 - src/explain.cppm | 375 +++ src/pack/route.cppm | 2 +- src/pm/commands.cppm | 6 +- src/pm/index_management.cppm | 4 +- src/project.cppm | 8 + src/publish/pipeline.cppm | 2 +- src/wire.cppm | 11 +- tests/e2e/cli/commands.cpp | 6 +- tests/e2e/cli/usage.cpp | 133 ++ tests/unit/test_cli_documents.cpp | 100 + 66 files changed, 3016 insertions(+), 1344 deletions(-) create mode 100644 build.mcpp create mode 100644 docs/mcpp-skills/mcpp-add/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-build/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-cache/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-clean/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-emit/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-explain/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-fetch/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-index/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-new/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-pack/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-publish/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-remove/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-resolve/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-run/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-search/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-self/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-stage/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-test/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-toolchain/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-update/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-version/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-why/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-write/SKILL.md create mode 100644 docs/mcpp-skills/mcpp-xpkg/SKILL.md create mode 100644 docs/mcpp-skills/mcpp/SKILL.md create mode 100644 src/explain.cppm create mode 100644 tests/e2e/cli/usage.cpp create mode 100644 tests/unit/test_cli_documents.cpp diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index d4356f6bc..0cdebaf93 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -853,7 +853,8 @@ mcpp 依赖的 mcpplibs.cmdline 是 0.0.6。它此后的三个版本提供了: 与「在工程的目录里运行」。这是 §10 的 G2 用于用法错误。退出码不变。 `--message-format json` 下,同一条错误是一条带稳定代码的诊断,相近的名字是其中的一个数组,读它的程序不需要解析句子。 6. **代码都查得到。** `mcpp explain` 接受三类代码:`E` 开头的错误码、`MCPP_*` 的诊断代码、docs/50 的原因码。三者登记 - 在一处,docs/50 的表由这一处生成;查不到时给出名字相近的代码。§10.3 的验收「每个新的原因码在 `mcpp explain` 中有 + 在一处(`mcpp.explain`);docs/50 原因码表的每一行与这一处的标题逐字相同,由单元测试核对,而不是生成一份提交进仓库的 + 文本;查不到时给出名字相近的代码。§10.3 的验收「每个新的原因码在 `mcpp explain` 中有 条目」由此才可能。 **不做的区分。** 没有「agent 模式」。mcpp 不探测调用者是谁,同一条命令对人与 agent 的含义相同;差别只在已有的、由 @@ -1026,7 +1027,7 @@ xlings 的锁的记录已经写明「是提示而不是事实」,与规则五 | mcpp | 9 `mcpp new` 初始化版本库(#1038) | 新功能,带一处可见的行为变化(D11 已决定) | 默认 `git`,`--vcs` 与 `config.toml` 覆盖;子工程不带版本库,显式的要求被照做;不提交;做不到时报告 | 与同类工具的默认及其对子工程的习惯一致(实测);覆盖是 AGENTS.md §2 的要求;`.git` 不是工程的内容,不进入构建 | | mcpp | 10a 根帮助由命令树生成;每个出口给出下一步 | 缺陷修复与优化 | 删去手写的用法文本;用法错误一行原因加 `help:` | 实测帮助与命令树已经不一致;整份帮助作为报错对人与 agent 都是噪声 | | mcpp | 10b 用法随二进制携带(`--agent-skill-doc`) | 新功能 | 启用 cmdline 的约定;文档在 `docs/mcpp-skills/`,构建时渲染;两道一致性检查 | 只有二进制的读者此前得不到用法;复用库已有的机制,不自建 | -| mcpp | 10c `mcpp explain` 覆盖三类代码 | 缺陷修复 | 一处登记,docs/50 的表由它生成 | 实测原因码查不到,而每条拒绝都带着它 | +| mcpp | 10c `mcpp explain` 覆盖三类代码 | 缺陷修复 | 一处登记(`mcpp.explain`),docs/50 的表与它由测试核对一致 | 实测原因码查不到,而每条拒绝都带着它 | | mcpp | 11a 条目的修订读对;读不懂是「未知」 | 缺陷修复 | 读者读懂对局部表成员的引用;未知不参与重装的判断并由 `xpkg parse` 报告 | 实测每次构建都回到安装器并取得 home 的安装锁;两个读者对同一个条目给出两个答案 | | mcpp | 11b 叙述流只有一个写者 | 缺陷修复 | 每一行经界面模块;仓库的检查拒绝直接写标准错误,现有的登记在只减不增的清单里 | 实测一行绕过界面模块的输出使每次下载留下一条孤行;同类调用约二百三十处 | | mcpp | 11c 每个依赖一行、一种写法、不预告 | 优化 | 进度条在下载开始时出现;名字用清单里的身份;宽度先让名字 | 预告在什么都不下载时是假的;一个依赖三种写法 | diff --git a/.agents/skills/mcpp-usage/SKILL.md b/.agents/skills/mcpp-usage/SKILL.md index b65cdc909..8075a47d9 100644 --- a/.agents/skills/mcpp-usage/SKILL.md +++ b/.agents/skills/mcpp-usage/SKILL.md @@ -1,189 +1,19 @@ --- name: mcpp-usage -description: Use when helping users install, configure, or use mcpp — the C++23 modular build tool. Covers installation, project creation, building, dependency management, toolchain management, workspace setup, packaging, diagnostics, and troubleshooting. +description: Use when helping users install, configure, or use mcpp - the C++23 modular build tool. The usage lives in docs/mcpp-skills and in the binary. --- -# mcpp 基础用法 +# mcpp usage -## Overview +How to use mcpp is stated once, in the sheets under +[`docs/mcpp-skills/`](../../../docs/mcpp-skills/mcpp/SKILL.md), which the build renders into +the binary: -mcpp 是一个现代 C++ 模块化构建工具,纯 C++23 模块编写,已实现自举。一条命令安装,`import std` 开箱即用。 - -- 仓库:https://github.com/mcpp-community/mcpp -- 文档:https://github.com/mcpp-community/mcpp/tree/main/docs -- 包索引:https://github.com/mcpp-community/mcpp-index -- 模块化库:https://github.com/mcpplibs - -## Quick Reference - -| 命令 | 用途 | -|---|---| -| `mcpp new ` | 创建项目 | -| `mcpp build` | 构建 | -| `mcpp run [-- args]` | 构建并运行 | -| `mcpp test [pattern] [-- args]` | 发现并运行 `tests/**/*.cpp` 测试 | -| `mcpp add [@ver]` | 添加依赖 | -| `mcpp remove ` | 移除依赖 | -| `mcpp update [pkg]` | 更新依赖 | -| `mcpp search ` | 搜索包 | -| `mcpp toolchain list` | 查看工具链 | -| `mcpp toolchain install gcc 16` | 安装工具链 | -| `mcpp pack` | 打包 | -| `mcpp why [toolchain|runtime|deps]` | 解释解析出的构建决策 | -| `mcpp --offline` | 只使用已有本地状态 | -| `mcpp self doctor` | 环境诊断 | -| `mcpp explain ` | 错误码解释 | - -## 安装 - -```bash -# 推荐;Windows 请在 PowerShell 中运行 -xlings install mcpp -y - -# 或 Unix release 一键脚本(仅 Linux x86_64/aarch64 与 macOS ARM64) -curl -fsSL https://github.com/mcpp-community/mcpp/releases/latest/download/install.sh | bash -``` - -一键脚本不支持 Windows;Windows 使用 PowerShell 的 xlings 安装命令。安装到 -`~/.mcpp/` 后会自动加入 PATH。首次使用时,mcpp 按宿主选择默认工具链并 -安装到隔离沙盒:Linux 通常为 GCC,macOS 为 LLVM,Windows 在有可用 MSVC -时为 LLVM,否则为面向 `x86_64-windows-gnu` 的 MinGW-w64 GCC。 - -## 创建项目 - -```bash -mcpp new hello && cd hello -mcpp build -mcpp run -``` - -生成的项目包含最小 manifest 和可立即运行的 smoke test: - -```toml -[package] -name = "hello" -version = "0.1.0" -description = "A modular C++23 package" -license = "Apache-2.0" -``` - -`src/main.cpp` 会自动推断为 binary target,`tests/test_smoke.cpp` 会由 -`mcpp test` 自动发现;无需手写 `[targets.hello]`。 - -## mcpp.toml 配置 - -### 传统头文件库的模块化封装 - -`mcpplibs.mwrap.<库名>` 为传统 C/C++ 库提供模块入口;API namespace 保留上游,例如 -`import mcpplibs.mwrap.opencv.core;` 后仍使用 `cv::Mat`。包版本对齐上游,封装修订最多追加一个数字尾号。 -具体已发布的版本/feature 先查索引,不把文档中的候选库当已发布包。 - -每个新建或重构的 -m 库提供包自带快捷模板: - -```bash -mcpp new vision --template mcpplibs.mwrap.opencv@5.0.0.1 -mcpp new --list-templates mcpplibs.mwrap.opencv@5.0.0.1 -``` - -模板语法为 `[namespace.]name[@version][:template]`,只有一个默认模板时可以省略模板名。 -包模板中的 `{{self.name}}` 是完整包选择器,应用 `"{{self.name}}"` 作为单个依赖 key, -不要放到另一层 namespace 表下。模板必须实际创建、构建、运行,而不只做字符串检查。 - -feature 是加法并集;消费者可在依赖声明中使用 `default-features = false` 关闭该边的默认集合, -显式 features 仍会启用,其他依赖边的请求不会被取消。根项目没有 `--no-default-features` 命令行选项。 -可选大依赖由包作者显式门控。模块可导入不等于实际后端已启用,窗口/推理/设备能力需分别验证。 -宏不能经 import 传递;`.macros` 只提供可保持语义的常量/函数映射,原始宏仍需兼容头。 - -维护规范与包装流程见 [mcpp-index mwrap 规范](https://github.com/mcpplibs/mcpp-index/blob/main/docs/mwrap.md)。 -修改普通消费者项目时按现有包契约使用,不自动替用户迁移其他依赖。 - -```toml -[package] -name = "myapp" -version = "0.1.0" - -[targets.myapp] -kind = "bin" # bin / lib / shared; tests are discovered from tests/**/*.cpp -main = "src/main.cpp" - -[dev-dependencies] -gtest = "1.15.2" # 仅测试使用;SemVer: ^, ~, 范围, 精确 - -[toolchain] -default = "gcc@16.1.0" -``` - -更多配置:https://github.com/mcpp-community/mcpp/blob/main/docs/04-mcpp-toml.md - -## 工具链 - -```bash -mcpp toolchain list # 查看已装 -mcpp toolchain install gcc 16 # 装 GCC 16 -mcpp toolchain install llvm 20 # 装 LLVM 20 -mcpp toolchain default gcc@16.1.0 # 设默认 -mcpp build --target x86_64-linux-musl # 需要全静态 Linux 产物时显式选择 -``` - -## 测试结果与按用例运行 - -`mcpp test --message-format json` 每个测试一条 NDJSON 记录(通过的也带 `run_output`),最后是每个成员的 -`summary`。`status` 取 `pass`、`compile_fail`、`run_fail`(`timed_out` 为真即超时)、`not_run`(带 `reason`)、 -`built`(`--no-run`);退出码 0 为全部通过,1 为有测试失败,2 为有测试未能运行。 - -mcpp 的单位是测试程序;用例属于测试框架。按用例运行时,把框架的参数放在 `--` 之后: - -```bash -mcpp test unit/math -- --gtest_filter='Math.Adds:Math.Spans' # GoogleTest 只跑这两个用例 -mcpp test unit/math -- --gtest_output=json:"$PWD/math-report.json" # 每个用例的结果写成 JSON 报告 -mcpp test unit/math --print-launch -- --gtest_filter='Math.Adds' # 只构建,打印启动方式(argv、cwd、环境),供调试器使用 -``` - -读取用例结果时以框架报告为准(GoogleTest 的 `--gtest_output=json`、Catch2 的 `--reporter json`),程序输出中 -`[ RUN ] X` 与 `[ OK ] X` / `[ FAILED ] X` 之间是用例 X 的输出。 - -## 工作空间 - -```toml -[workspace] -members = ["libs/*", "apps/*"] - -[workspace.dependencies] -gtest = "1.15.2" ``` - -```bash -mcpp build -p member-name # 构建指定成员 +mcpp --agent-skill-doc # the root sheet and an index of the commands' sheets +mcpp --agent-skill-doc # one command's sheet ``` -## 自定义索引 - -```toml -[indices] -my-index = "git@gitlab.example.com:team/index.git" -local = { path = "/path/to/index" } - -[dependencies.my-index] -internal-lib = "1.0.0" -``` - -## 常见问题 - -| 问题 | 解决 | -|---|---| -| 首次构建慢 | 正常,需下载工具链。后续使用缓存 | -| command not found | 重开终端。Unix release 安装脚本应确认 `~/.mcpp/bin` 在当前 shell 的 `PATH` 中;经 xlings 安装则确认 xlings 当前激活的 bin 目录。Windows 不要执行 `source`,重开 PowerShell 后用 `Get-Command mcpp.exe` 验证命令已激活。 | -| 编译错误 | `mcpp clean && mcpp build`,确认 `mcpp toolchain list` | -| 依赖找不到 | `mcpp index update`,确认 `mcpp search ` | -| 需要无网络构建 | 使用 `mcpp --offline` 或设置 `MCPP_OFFLINE=1`;缺失的工具链/依赖会直接报错 | - -## 问题反馈 - -1. **项目 Issue**:https://github.com/mcpp-community/mcpp/issues - - 描述复现步骤、期望/实际行为、mcpp 版本和 OS - - 可用 `gh issue create` 提交 - -2. **社区论坛**:https://forum.d2learn.org/category/20 - - 使用疑问和讨论 - -如果 AI Agent 无法直接创建 Issue,请提示用户手动创建并提供整理好的问题描述。 +Install mcpp with `xlings install mcpp -y`, or on Linux and macOS with +`curl -fsSL https://github.com/mcpp-community/mcpp/releases/latest/download/install.sh | bash`. +The user documentation is [`docs/`](../../../docs/README.md). diff --git a/AGENTS.md b/AGENTS.md index bf925378f..f7c3d8af5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ linked document holds. | [`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 | | [`.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) | ordered steps with criteria | +| [`.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 | A change of behaviour updates the spec clause, the usage chapter in both languages and the diff --git a/CHANGELOG.md b/CHANGELOG.md index ebadcc6df..9c77da03b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,55 @@ ### Added +- `--agent-skill-doc` at every level of the command tree prints how to use mcpp: the root sheet + (the daily loop, reading a message, the output for programs, the statuses) with an index of the + commands' sheets, and each command's sheet (when to use it, examples, what it reads, writes and + downloads, its refusals with their remedies, what it may wait for). The sheets live in + `docs/mcpp-skills/` and are rendered into the binary when it is built; the answer needs no + project, no home and no network. A test parses every example of a sheet by the command tree. +- `mcpp help ` is `mcpp --help`. +- A usage error asked for JSON (`--format json`, `--message-format json`) is also a `mcpp.usage` + envelope on standard output: one diagnostic with a `MCPP_USAGE_*` code and the closest declared + names in `suggestions` (docs/50 §3). +- `mcpp explain` answers every reason token a refusal can carry, the `MCPP_*` codes of JSON + diagnostics and the `E` codes, each with its remedy, from one registry; an unknown code is + answered with the closest codes. Three reason tokens: `lock-wait-exceeded`, + `lock-unavailable`, `vcs-unavailable`. + +- `--lock-wait ` (also `MCPP_LOCK_WAIT`, `[build] lock_wait` in `mcpp.toml` and in + `config.toml`) bounds every wait for a lock another run holds; past it the run is refused with + `[lock-wait-exceeded]`, naming the holder. A wait is reported after 300 ms and then at 10 s, + 30 s, 60 s and each minute, with the resource, the lock file and the last recorded holder, as a + `waiting` event under `--message-format json`. A file the system cannot lock is refused at once + with `[lock-unavailable]`, the system's reason and a remedy (SPEC-011). +- `mcpp new` makes the new project a git repository with nothing committed. `--vcs git|none` + and `config.toml` `[new] vcs` state it; inside another git work tree or project, no repository + is made unless one is stated. Without git the project is made and the missing repository + reported, or refused with `[vcs-unavailable]` when `--vcs git` asked for one. - A platform of a descriptor's `xpm` table that refers to another — `macosx = { ref = "linux" }`, or `inherits = "linux"` (xpackage V1) — holds the versions it does not state itself and that platform's `deps` when it states none, as the installer reads it; versions every platform shares are written once. `mcpp xpkg parse` refuses a reference to a platform the table has no block for and a chain of references that returns to itself (SPEC-001 §10.5). +### Changed + +- `mcpp --help` is printed from the command tree, in its groups, and ends with the line that + points agents at `--agent-skill-doc`; the hand-written usage text is removed. Internal commands + are hidden from the help and the completion. +- A usage error is one line and at most two `help:` lines -- the closest declared names and the + `--help` that lists what is -- instead of the whole help. An unknown command at a lower level is + reported as one (exit 2); an unknown top-level command still exits 127. +- A command that needs a project, run outside one, says + `no mcpp.toml in the current directory or any parent` and names the two next steps. +- mcpp depends on mcpplibs.cmdline 0.2.0 with its `agent-skills` feature. +- Fetching the dependencies prints one line per dependency under its manifest name, with no + announcement before the provider downloads, and `Updating` when its revision changes; the + dependencies known at one step are fetched in one call to the provider. The provider's lines + reach standard error through mcpp's one writer. +- A standard library module whose record is complete is read without taking its lock; the record + is written by a rename and lists the files of the entry. + ### Fixed - A version stated through a local table of its descriptor (`["1.2.1"] = versions["1.2.1"]`) is diff --git a/README.md b/README.md index 20ed6456c..a9857f5ab 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ Copy the following prompt to your AI coding assistant (Claude Code / Cursor / Co ``` Read the README of https://github.com/mcpp-community/mcpp, then install mcpp for me and create a C++23 module project, build and run it. -The repo's .agents/skills/mcpp-usage/SKILL.md has a detailed usage guide. +Once mcpp is installed, `mcpp --agent-skill-doc` prints how to use it. ``` @@ -521,12 +521,13 @@ a command in front of a reader, to the chapter that owns it. Every directory under [`examples/`](examples/) is a project that builds, and [03 — Examples](docs/03-examples.md) says which one teaches what. Full options -for any command are available via `mcpp --help`. +for any command are available via `mcpp --help`, and `mcpp --agent-skill-doc` +prints the command's usage sheet ([docs/mcpp-skills](docs/mcpp-skills/mcpp/SKILL.md)). **AI-assisted learning**: send the following prompt to an AI coding assistant to get up to speed with mcpp quickly: ``` -Read .agents/skills/mcpp-usage/SKILL.md and the docs/ directory of the +Run `mcpp --agent-skill-doc`, then read the docs/ directory of the https://github.com/mcpp-community/mcpp repository, then tell me how to create a C++23 module project with dependencies using mcpp. ``` diff --git a/README.zh-CN.md b/README.zh-CN.md index a625f9c66..949d28f15 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -182,7 +182,7 @@ nix profile install github:mcpp-community/nix-mcpp # 同上,Nix 2.30 之 ``` 阅读 https://github.com/mcpp-community/mcpp 的 README, 安装 mcpp,创建一个 C++23 模块项目,然后构建并运行它。 -仓库中的 .agents/skills/mcpp-usage/SKILL.md 提供了详细的使用指南。 +安装之后,`mcpp --agent-skill-doc` 会给出 mcpp 的用法。 ``` @@ -443,13 +443,13 @@ mcpp 的身份模型有两条正交的轴:**工具链**是 `family@version`( | `5x` 面向程序的契约 | [50 机器可读输出](docs/zh/50-machine-output.md) · [51 受支持的版本与兼容性](docs/zh/51-supported-versions.md) · [52 从程序或 agent 驱动 mcpp](docs/zh/52-driving-mcpp-from-a-program.md) · [规范](docs/specs/README.md) | | `9x` mcpp 自身 | [90 从源码构建与参与贡献](docs/zh/90-build-from-source.md) · [92 发布 mcpp](docs/zh/92-release.md) | -[`examples/`](examples/) 下的每个目录都是一个可以构建的项目,[03 —— 示例项目](docs/zh/03-examples.md) 说明每个示例演示什么。任意命令的完整选项可通过 `mcpp --help` 查看。 +[`examples/`](examples/) 下的每个目录都是一个可以构建的项目,[03 —— 示例项目](docs/zh/03-examples.md) 说明每个示例演示什么。任意命令的完整选项可通过 `mcpp --help` 查看,`mcpp --agent-skill-doc` 给出该命令的用法说明([docs/mcpp-skills](docs/mcpp-skills/mcpp/SKILL.md))。 **AI 辅助学习**:将以下提示词发给 AI 编码助手,可以快速了解 mcpp: ``` -阅读 https://github.com/mcpp-community/mcpp 仓库的 -.agents/skills/mcpp-usage/SKILL.md 和 docs/ 目录下的文档, +运行 `mcpp --agent-skill-doc`,再阅读 https://github.com/mcpp-community/mcpp 仓库 +docs/ 目录下的文档, 说明如何用 mcpp 创建一个带依赖的 C++23 模块项目。 ``` diff --git a/build.mcpp b/build.mcpp new file mode 100644 index 000000000..52f52cd58 --- /dev/null +++ b/build.mcpp @@ -0,0 +1,14 @@ +// The build program of mcpp: the usage documents under docs/mcpp-skills become +// the module `mcpp.skills`, whose table `--agent-skill-doc` answers from. No +// file is read at run time: a reader of the binary alone has the documents +// (design 2026-11-27 §3.9.2 point 2). mcpplibs.mplugin.cmdline is re-exported +// by mcpplibs.cmdline, so the dependency above is the only one. +import mcpplibs.mplugin.cmdline; + +int main() { + mcpplibs::mplugin::cmdline::options o; + o.app = "mcpp"; + o.module_name = "mcpp.skills"; + o.name_space = "mcpp::skills"; + return mcpplibs::mplugin::cmdline::embed(o) ? 0 : 1; +} diff --git a/docs/01-getting-started.md b/docs/01-getting-started.md index a464d423c..902251561 100644 --- a/docs/01-getting-started.md +++ b/docs/01-getting-started.md @@ -111,6 +111,8 @@ This generates the following directory structure: ``` hello/ +├── .git/ ← a repository, nothing added or committed +├── .gitignore ├── mcpp.toml ← project manifest ├── src/ │ └── main.cpp @@ -118,6 +120,15 @@ hello/ └── test_smoke.cpp ← runs with `mcpp test` ``` +The project is a git repository in which nothing is added or committed +(2026.12.4.1+). `--vcs none` makes none, and `--vcs git` makes one; the +machine's default is `[new] vcs = "git" | "none"` in `config.toml`. Inside +another git work tree, or inside a directory holding an `mcpp.toml`, no +repository is made unless one of the two states it, so a member created in a +workspace stays part of the workspace's repository. Without git the project is +made and a warning says it is not a repository; with `--vcs git` the command +fails with `[vcs-unavailable]` and the project is kept. + The generated manifest contains only package metadata; mcpp infers a binary target from `src/main.cpp`. By default, that file is a C++23 modular hello world: ```cpp diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index 267ab4513..01059c076 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -1138,6 +1138,7 @@ longer updated; the first build that finds it says so once, naming this key. | `allow_host_libs` | [20 — Toolchains](20-toolchains.md), [22 — Target Side](22-target-side.md) | | `allow_host_tools` | [25 — Home, Indices and Store](25-home-indices-and-store.md) | | `ios_deployment_target` | [20 — Toolchains](20-toolchains.md) | +| `lock_wait` | [25 — Home, Indices and Store](25-home-indices-and-store.md), "Waiting for a lock" | | `offline` | [05 — Dependencies](05-dependencies.md), "Offline builds and mcpp fetch" | | `platform-dependencies` | [22 — Target Side](22-target-side.md) | | `std-module`, `std-compat-module` | [22 — Target Side](22-target-side.md) | diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index 4536fb7af..af0a17ccf 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -10,7 +10,9 @@ environment. links to the chapter that owns it. Before: [08 — Testing](08-testing.md). The command reference is `mcpp --help`, and each subcommand carries its own -`--help`. This chapter answers a different question: which command applies to a +`--help` (`mcpp help ` is the same); `mcpp --agent-skill-doc` and +`mcpp --agent-skill-doc` print the usage sheets the binary carries +([52](52-driving-mcpp-from-a-program.md)). This chapter answers a different question: which command applies to a situation that has already arisen — a build directory that keeps growing, a resolution nobody expected, a descriptor about to be published, an index that may be stale. The commands collected here are the ones whose name does not @@ -292,15 +294,16 @@ when none is named. `--target` and `--toolchain` turn the report into a query about a pair the current directory does not use, which is how a target matrix asks one cell at a time. -An error code in a diagnostic expands through `mcpp self explain`: +A code expands through `mcpp explain` (also `mcpp self explain`): an `E` code, +the `MCPP_*` code of a JSON diagnostic, or the reason token a refusal ends with +in brackets. The answer states what the code means and what to do; a code it +does not hold is answered with the closest codes it holds (2026.12.4.1+): ``` -$ mcpp self explain E0006 -E0006: index requires a newer mcpp +$ mcpp explain layer-cycle +layer-cycle: the packages that supply the layers require one another in a circle (...) -The package index declares (index.toml [index].min_mcpp) that its -descriptors need a newer mcpp than this binary — parsing them would -silently misbehave, so resolution stops instead. Upgrade mcpp: +Remove one of the requires edges the message names. ``` ## Index freshness and offline builds diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index 442827f10..24f5ed338 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -217,6 +217,35 @@ The locator is saved after local validation, before acquisition. An incomplete offline or failed-network init returns 1 while retaining the chosen directory. Rerunning `self init` continues there. +### Waiting for a lock (2026.12.4.1+) + +Runs that share a home, or a project, take turns on what one of them writes: a +build directory, an install into the home, a standard library module, an index +refresh. A run that waits says so after 300 ms, naming what it waits for, the +lock file, the last recorded holder and whether that process is visible on this +machine; it repeats one line at 10 s, 30 s, 60 s and then each minute. A holder +that is not visible is not known to be gone: it may run in another process +namespace, a container, or on another machine that shares the home, and the +report names the command that lists the file's holders on this system. + +A run waits as long as the holder holds, unless a limit is stated. The limit is +a duration (`30s`, `2m`, `1h`; `0` does not wait), taken from the first of: + +| tier | where | +|---|---| +| override | `--lock-wait `, `MCPP_LOCK_WAIT` | +| project | `[build] lock_wait` in `mcpp.toml` | +| machine | `[build] lock_wait` in `config.toml` | + +Past the limit the run is refused with `[lock-wait-exceeded]`, naming the +holder and where the limit was stated. The provider's own locks are bounded by +the same limit (`XLINGS_LOCK_TIMEOUT`). A lock file the system cannot lock -- a +directory without write permission, a read-only or lockless file system, no +descriptor left -- is refused at once with `[lock-unavailable]`, the system's +reason and a remedy: waiting would not end. A standard library module that is +complete is read without its lock. The contract is +[SPEC-011](specs/concurrency.md). + ## 2. Refreshing an index An index mcpp owns is fetched into a staging directory beside it, checked there diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index 459a3e081..64779bed8 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -75,10 +75,14 @@ its `diagnostics` state why; `mcpp.build-database` is such a kind (§8). "path": "mcpp.toml", // omitted when there is none "range": { "start": {"line": 3, "column": 1}, "end": {"line": 3, "column": 9} }, // omitted when there is none - "shown": false // omitted when the terminal showed it + "shown": false, // omitted when the terminal showed it + "suggestions": ["--jobs"] // omitted when there are none } ``` +`suggestions` lists the declared names closest to an unknown one, closest first +(a usage error, `mcpp.usage`; 2026.12.4.1+). + `shown` is `false` for a diagnostic the terminal did not show: a notice said once per project that this project was already told of, and a note under `--quiet` (2026.11.21.1+). The envelope carries every diagnostic whether or not @@ -134,7 +138,24 @@ $ echo $? A request that does not yet know what it will be given must not write into the channel the protocol owns. Combined with §1, a client's rule is complete: no -JSON on stdout means "not supported", whatever the reason. +envelope of the kind it asked for on stdout means "not supported", whatever the +reason. + +A command line the parser refuses -- an unknown command or option, an option +without its value, a value or an argument the command does not take -- is a +usage error (2026.12.4.1+). On stderr it is one line and at most two `help:` +lines: the declared names closest to the word that was not understood, and the +`--help` that lists what is. When the words ask for JSON (`--format json` or +`--message-format json`), stdout carries one `mcpp.usage` envelope as well +(§8): its kind is never the kind that was asked for, so the rule above holds. +An unknown top-level command exits 127, every other usage error 2. + +``` +$ mcpp build --jbos 3 --message-format json +{ "kind": "mcpp.usage", "data": {"command": "mcpp build"}, + "diagnostics": [{"code": "MCPP_USAGE_UNKNOWN_OPTION", "message": "unknown option: --jbos", + "suggestions": ["--jobs"], ...}], ... } +``` Exit codes **of the enveloped commands** — the kinds `--protocol-version` advertises. This table is scoped to them on purpose; a code another command @@ -673,7 +694,7 @@ a program classifying the outcome reads `reason`: | `static-tls-image` | a shared image whose exact `exports` say a host loads it by `dlopen` asks for the static TLS block (`DF_STATIC_TLS`) with more than the C library serves to such an image (2026.11.27.1+) | | `soname-collision` | two shared libraries of one build are loaded by one name, their file name or a stated `soname` (2026.11.27.1+) | | `build-program-unpublished-input` | `mcpp publish`: the package's build program reads a file its archive does not carry -- one outside the package's directory, or one HEAD does not track (2026.11.21.1+) | -| `companion-too-old` | a companion stated beside the toolchain (`companions = { binutils = … }`) is older than the one the toolchain's payload declares (SPEC-006 §2.9) | +| `companion-too-old` | a companion stated beside the toolchain (`companions = { binutils = ... }`) is older than the one the toolchain's payload declares (SPEC-006 section 2.9) | | `tool-version-conflict` | two declarations name one xlings package at versions that cannot both hold | | `shared-library-cxx-runtime` | a dependency's C++ shared library in a graph whose C++ runtime is a package, with no private copy stated | | `offline-download-required` | the run is offline and the plan needs a download: a toolchain, a package, a git revision or the package index; from 2026.11.21.1, with no archive directory named *(2026.9.16.1+)* | @@ -698,6 +719,9 @@ a program classifying the outcome reads `reason`: | `platform-tool-absent` | a program the platform's link or seal runs (`okld` for an ok image) is neither built by the graph nor found on this machine *(2026.10.27.1+; `image-tool-absent` in 2026.10.26.2)* | | `platform-version-group` | a package of the platform's version group is in the graph at another version *(2026.10.27.1+)*, or no release of a platform series admits the build's requests *(2026.11.19.1+)* | | `platform-phase-directive` | a platform's plugin stated a directive its phase does not take *(2026.10.27.1+)* | +| `lock-wait-exceeded` | another run held a lock past the wait limit (`--lock-wait`, `MCPP_LOCK_WAIT`, `[build] lock_wait`); the message names the holder *(2026.12.4.1+)* | +| `lock-unavailable` | the system cannot lock a file mcpp needs: permissions, a read-only or lockless file system, no descriptor left; waiting would not end *(2026.12.4.1+)* | +| `vcs-unavailable` | `mcpp new` was asked for a repository and git cannot run *(2026.12.4.1+)* | | `other` | a refusal whose branch has not been given a token yet | **One token is also printed by `mcpp build` itself.** @@ -1054,7 +1078,7 @@ Standard output is NDJSON. Each line but the last is an event: | event | carries | |---|---| | `plan` | `configuration`: the configuration whose build directory the build has entered; `platform` and `hostPlatform` (2026.10.27.1+) are the platforms of the target and host graphs, or `null` | -| `waiting` | `holder` (`pid`, `command`, `client`, `startedAt`) and `waitedMs`: another build holds this build directory, and this one waits for it (§11) | +| `waiting` | `holder` (`pid`, `command`, `client`, `startedAt`) and `waitedMs`: another run holds a lock this one needs, and this one waits for it (§11). From 2026.12.4.1 every wait is reported, with `resource` (what is waited for: the build directory, the install state of the home, a standard library module), `path` (the lock file) and `holderVisible` (whether the holder is a process visible here) | | `progress` | `finished`, `total`: ninja's count of steps; a build may run more than one ninja pass, and each restarts the count | | `diagnostic` | `diagnostic`: one diagnostic of a compiler, from the output of a failed step, in the shape of `diagnostics[]` of the record below | | `artifact` | `artifact`: one product, as in `artifacts[]` of the record below | @@ -1204,10 +1228,13 @@ did. ## 11. Concurrent runs One configuration's build directory is written by one run at a time. A second -build of the same configuration waits for the first, reports the holder on -standard error (`Waiting for the build directory, held by pid 1234 (mcpp -build, from vscode, 8s)`) and as a `waiting` event, and then finds little left -to do. Builds of different configurations, queries (`emit build-database`, +build of the same configuration waits for the first, reports what it waits for +and the last recorded holder on standard error (`Waiting for the build directory +`, then `last recorded holder: pid 1234 (mcpp build, from vscode, +8s)`) and as a `waiting` event, and then finds little left to do. Every other +lock a run waits for is reported the same way, and a stated limit +(`--lock-wait`) ends a wait with `[lock-wait-exceeded]` (2026.12.4.1+; +[25](25-home-indices-and-store.md)). Builds of different configurations, queries (`emit build-database`, `cache list`, reading the records) and the programs `mcpp run` and `mcpp test` start never wait. A linked product is replaced whole, so a program started while a build links never runs a partial file. `mcpp.lock` is written @@ -1289,6 +1316,20 @@ the last one when repeated) the graph is that target's, and the formats of its platform are listed: `mcpp pack --target x86_64-openkal --list-formats` names `okb`, provided by `mcpplibs.openkal-platform`. +### `mcpp.usage` — a usage error *(mcpp 2026.12.4.1+)* + +``` +mcpp --format json | --message-format json +``` + +`data.command` is the command the words reached (`mcpp build`, `mcpp cache`), +whose `--help` lists what it takes. `diagnostics` holds one `error`: its `code` +is `MCPP_USAGE_UNKNOWN_COMMAND`, `MCPP_USAGE_UNKNOWN_OPTION`, +`MCPP_USAGE_MISSING_VALUE`, `MCPP_USAGE_INVALID_VALUE`, +`MCPP_USAGE_MISSING_ARGUMENT` or `MCPP_USAGE_INVALID_ARGUMENT`, and its +`suggestions` the declared names closest to an unknown one. `effects` is empty: +nothing ran. `mcpp explain ` describes each code. + ## Current limitations - **The exit-code table is scoped to the commands it names.** A code another diff --git a/docs/52-driving-mcpp-from-a-program.md b/docs/52-driving-mcpp-from-a-program.md index 56c5bb987..ed779d1d3 100644 --- a/docs/52-driving-mcpp-from-a-program.md +++ b/docs/52-driving-mcpp-from-a-program.md @@ -117,3 +117,30 @@ right-aligned word (`Compiling`, `Finished`); an mcpp message starts with `:::`; and a next step is on its own line starting `help:`. Colour is off in a pipe unless `CLICOLOR_FORCE` or `FORCE_COLOR` asks for it. The words themselves carry no compatibility promise; the records above do. + +## 8. The usage the binary carries + +`mcpp --agent-skill-doc` prints how to use mcpp: the daily loop of commands, +how a message reads, the output for programs, the statuses, and an index of +the commands' sheets. `mcpp --agent-skill-doc` prints the sheet of +one command: when it applies, examples to copy, what it reads, writes and +downloads, its usual refusals with their remedies, and what it may wait for. +A subcommand without a sheet of its own answers with its nearest ancestor's. +The sheets are part of the binary (2026.12.4.1+): the answer needs no project, +no home and no network, and describes the release that prints it. An +instruction for a particular agent can be the single line "run +`mcpp --agent-skill-doc`". + +`mcpp --help` lists the command tree in its groups and ends with the line that +points at the sheets; `mcpp help ` is `mcpp --help`. + +A usage error is one line and at most two `help:` lines: the declared names +closest to the word that was not understood, and the `--help` that lists what +is. Asked for JSON (`--message-format json`, `--format json`), the same error +is also a `mcpp.usage` envelope on standard output, whose diagnostic carries a +`MCPP_USAGE_*` code and the closest names in `suggestions` +([50](50-machine-output.md)). A command that needs a project and is run outside +one says so and names the two next steps. `mcpp explain ` describes an +`E` code, the `MCPP_*` code of a diagnostic and the reason token in brackets at +the end of a refusal, with its remedy, and names the closest codes to one it +does not hold. diff --git a/docs/README.md b/docs/README.md index 769f0c06d..af1b7fa54 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ records, which are not user documentation. | tree | reader | contents | |---|---|---| | `docs/**` | someone with a task in hand | how to use what mcpp implements | +| [`docs/mcpp-skills/**`](mcpp-skills/mcpp/SKILL.md) | an agent, or anyone with the binary alone | the usage sheets the binary prints with `--agent-skill-doc`: English, ASCII, at most one hundred lines each | | [`docs/specs/**`](specs/README.md) | someone implementing against a mechanism: index authors, downstream tools, contributors | semantics, constraints and matching rules, each tagged with its implementation status | | `.agents/docs/**` | whoever made a change, and whoever later asks why it is that way | the reasoning, the measurements, and what was refuted | | `.agents/skills/**` | a contributor or agent following a procedure | ordered steps with criteria | diff --git a/docs/mcpp-skills/mcpp-add/SKILL.md b/docs/mcpp-skills/mcpp-add/SKILL.md new file mode 100644 index 000000000..c77881246 --- /dev/null +++ b/docs/mcpp-skills/mcpp-add/SKILL.md @@ -0,0 +1,36 @@ +--- +name: mcpp-add +description: Use when adding a dependency, a test-only dependency or a build dependency to mcpp.toml. +--- + +# mcpp add + +Writes a dependency into `mcpp.toml`, at an exact version. + +## Examples + +``` +mcpp add mcpplibs.cmdline@0.2.0 +mcpp add gtest@1.15.2 --dev +mcpp add mcpplibs.mplugin.cmdline@0.2.0 --build +``` + +The version is required and exact; `mcpp search ` lists the versions +published. `--dev` writes `[dev-dependencies]` +(tests only), `--build` writes `[build-dependencies]` (a build program or a +tool the build runs). + +## Reads, writes, network + +Reads the package index (refreshed when stale; network); writes `mcpp.toml`. +The next build resolves it and updates `mcpp.lock`. + +## Refusals + +- No version: `mcpp add @`. +- A version the index does not have for this platform: the message lists + those it has. + +## Waits + +An index refresh waits for another run's; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-build/SKILL.md b/docs/mcpp-skills/mcpp-build/SKILL.md new file mode 100644 index 000000000..16525f75a --- /dev/null +++ b/docs/mcpp-skills/mcpp-build/SKILL.md @@ -0,0 +1,55 @@ +--- +name: mcpp-build +description: Use when compiling the project in the current directory, for the host or another target, with a profile, features or a toolchain. +--- + +# mcpp build + +Builds the project whose `mcpp.toml` is in the current directory or the +nearest parent: its programs, libraries and the modules they import. Outputs +go under `target///`. + +## Examples + +``` +mcpp build +mcpp build --release +mcpp build --target x86_64-linux-musl --static +mcpp build --toolchain llvm@22.1.8 +mcpp build --features simd,cli/color +mcpp build -p core --jobs 8 +mcpp build --workspace --exclude bench +mcpp build --configure-only +mcpp build --message-format json +``` + +`--configure-only` writes `compile_commands.json` and builds nothing. +`--message-format json` streams NDJSON events and ends with the `mcpp.build` +envelope. + +## Reads, writes, network + +- Reads the project and `mcpp.lock`; writes `target/` and the lock. +- Writes the home: toolchains, dependencies, the build cache. +- Downloads what the plan lacks; `--offline` refuses instead, and + `mcpp fetch` puts it in the home beforehand. +- Runs the build programs (`build.mcpp`) of the project and its dependencies. + +## Refusals + +- `[offline-download-required]`: offline and the plan needs a download. +- `[unknown-target]`, `[os-mismatch]`: the `--target` spelling; see + `mcpp toolchain list` for the targets this host serves. +- `[layer-requirement]`, `[layer-cycle]`, `[package-cycle]`: the graph; + `mcpp why deps` shows who requires what. +- `[compiler-requirement-conflict]`: packages need another compiler; + `mcpp why toolchain`. +- Compiler errors are printed as the compiler wrote them, exit 1. + +`mcpp explain ` describes any of them. + +## Waits + +The build directory of one configuration is built by one run at a time; a +second run waits for it, as it waits for an install in the home. `--lock-wait` +bounds the wait. diff --git a/docs/mcpp-skills/mcpp-cache/SKILL.md b/docs/mcpp-skills/mcpp-cache/SKILL.md new file mode 100644 index 000000000..945510d1a --- /dev/null +++ b/docs/mcpp-skills/mcpp-cache/SKILL.md @@ -0,0 +1,35 @@ +--- +name: mcpp-cache +description: Use when inspecting or reclaiming the global build cache of mcpp's home. +--- + +# mcpp cache + +The global build cache holds built dependencies, standard library modules +and host tools, shared by every project of the home. + +## Examples + +``` +mcpp cache dir +mcpp cache list +mcpp cache info mcpplibs.cmdline +mcpp cache gc --max-size 5GiB +mcpp cache gc --older-than 30d --dry-run +mcpp cache prune --older-than 30d +mcpp cache clean --all +mcpp cache verify +``` + +## Reads, writes, network + +Reads and deletes in the home; no network; needs no project. An entry that +is removed is rebuilt by the next build that needs it. + +## Refusals + +None of their own; `verify` lists entries whose files are missing (`E0005`). + +## Waits + +An entry a running build uses is waited for; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-clean/SKILL.md b/docs/mcpp-skills/mcpp-clean/SKILL.md new file mode 100644 index 000000000..ef85653fc --- /dev/null +++ b/docs/mcpp-skills/mcpp-clean/SKILL.md @@ -0,0 +1,35 @@ +--- +name: mcpp-clean +description: Use when removing a project's build outputs, or only those no configuration still uses. +--- + +# mcpp clean + +Removes `target/`. With `--stale`, only what no recorded build still uses. + +## Examples + +``` +mcpp clean +mcpp clean --stale +mcpp clean --dry-run +mcpp clean --report +mcpp clean --older-than 12h +mcpp clean --bmi-cache +``` + +`--report` shows where `target/` holds its bytes and removes nothing. +`--bmi-cache` also empties the global build cache (`mcpp cache clean`). + +## Reads, writes, network + +Reads the project's build records; writes nothing but deletions; no network. + +## Refusals + +Outside a project there is nothing to clean: the message says so. + +## Waits + +A configuration another run is building is waited for, bounded by +`--lock-wait`. diff --git a/docs/mcpp-skills/mcpp-emit/SKILL.md b/docs/mcpp-skills/mcpp-emit/SKILL.md new file mode 100644 index 000000000..fdb1bb5e8 --- /dev/null +++ b/docs/mcpp-skills/mcpp-emit/SKILL.md @@ -0,0 +1,35 @@ +--- +name: mcpp-emit +description: Use when generating a document about the project (xpkg descriptor, SBOM, build database) or about mcpp (its surface). +--- + +# mcpp emit + +Writes a document: `xpkg` (the package's index descriptor), `sbom` (a +CycloneDX bill of materials of the recorded resolution), `build-database` +(the build plan for an IDE) or `surface` (mcpp's commands, flags, keys and +reason tokens). + +## Examples + +``` +mcpp emit xpkg -V 0.2.0 -o cmdline.lua +mcpp emit sbom -o sbom.json +mcpp emit build-database --format json +mcpp emit build-database --spec compile-commands -o compile_commands.json +mcpp emit surface +``` + +## Reads, writes, network + +Writes standard output or `-o FILE`. `build-database` plans as a build does +(home, network, build programs) and writes nothing into the project. + +## Refusals + +`build-database` reports a plan that cannot be made as diagnostics +(`MCPP_BUILD_DATABASE_*`); `mcpp explain ` describes each. + +## Waits + +`build-database` as a fetch; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-explain/SKILL.md b/docs/mcpp-skills/mcpp-explain/SKILL.md new file mode 100644 index 000000000..78ad34e1d --- /dev/null +++ b/docs/mcpp-skills/mcpp-explain/SKILL.md @@ -0,0 +1,32 @@ +--- +name: mcpp-explain +description: Use when a message names a reason token in brackets, an E code or an MCPP_ diagnostic code and you need its meaning and remedy. +--- + +# mcpp explain + +Describes a code and what to do about it: a reason token (the word in +brackets at the end of a refusal), an `E0001`-style error code, or the +`MCPP_*` code of a JSON diagnostic. + +## Examples + +``` +mcpp explain layer-cycle +mcpp explain E0003 +mcpp explain MCPP_USAGE_UNKNOWN_OPTION +``` + +A code it does not know is answered with the closest known codes. + +## Reads, writes, network + +Reads only what the binary holds; no project, no home, no network. + +## Refusals + +An unknown code exits 2 with the closest codes. + +## Waits + +None. diff --git a/docs/mcpp-skills/mcpp-fetch/SKILL.md b/docs/mcpp-skills/mcpp-fetch/SKILL.md new file mode 100644 index 000000000..b14f2cba4 --- /dev/null +++ b/docs/mcpp-skills/mcpp-fetch/SKILL.md @@ -0,0 +1,39 @@ +--- +name: mcpp-fetch +description: Use when putting everything a build needs into the home before going offline, or moving it to a machine without network. +--- + +# mcpp fetch + +Puts what the project's build needs in the home: the toolchain, the standard +library module's inputs, every dependency and the index snapshot. Builds +nothing. + +## Examples + +``` +mcpp fetch +mcpp fetch --target x86_64-linux-musl --target aarch64-linux-musl +mcpp fetch --to bundle/ +mcpp fetch --from bundle/ +mcpp build --offline +``` + +`--to DIR` then writes what the build uses into DIR; `--from DIR` first takes +such a directory into the home, on a machine without network. + +## Reads, writes, network + +- Reads the project and `mcpp.lock`; writes the home (and DIR with `--to`). +- Downloads what the home lacks; with `--from` and `--offline` it does not. + +## Refusals + +- `[bundle-older-than-lock]`: the bundle lacks a version `mcpp.lock` records; + write it again with `mcpp fetch --to` from the current lock. +- `[offline-download-required]`, `[artifact-unavailable-offline]`: offline, + and neither the home nor the named directories hold an archive. + +## Waits + +Installs into the home wait for one another; `--lock-wait` bounds the wait. diff --git a/docs/mcpp-skills/mcpp-index/SKILL.md b/docs/mcpp-skills/mcpp-index/SKILL.md new file mode 100644 index 000000000..814a6f04e --- /dev/null +++ b/docs/mcpp-skills/mcpp-index/SKILL.md @@ -0,0 +1,38 @@ +--- +name: mcpp-index +description: Use when listing, adding, refreshing or pinning the package indexes mcpp resolves dependencies from. +--- + +# mcpp index + +Manages the package registries: `list`, `add`, `remove`, `update`, +`status`, `pin`, `unpin`. + +## Examples + +``` +mcpp index list +mcpp index add team https://example.com/team/index.git +mcpp index update +mcpp index status +mcpp index pin team 1a2b3c4 +mcpp index unpin team +mcpp index list --format json +``` + +A project states its own indexes in `[indices]` of `mcpp.toml`, as a git URL +or `{ path = "..." }`. + +## Reads, writes, network + +`update` and `add` clone or fetch (network); `pin` and `unpin` write +`mcpp.toml`; `status` reads only. + +## Refusals + +- `[index-location-named-twice]`: two entries name one directory. +- `E0006`: the index needs a newer mcpp; upgrade mcpp. + +## Waits + +A refresh waits for another run's; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-new/SKILL.md b/docs/mcpp-skills/mcpp-new/SKILL.md new file mode 100644 index 000000000..483b6b31f --- /dev/null +++ b/docs/mcpp-skills/mcpp-new/SKILL.md @@ -0,0 +1,42 @@ +--- +name: mcpp-new +description: Use when creating a new mcpp project, a library, or a project from a package's template. +--- + +# mcpp new + +Creates a project directory: `mcpp.toml`, `src/main.cpp` (or a module for a +library), `tests/test_smoke.cpp`, `.gitignore` and a git repository. + +## Examples + +``` +mcpp new hello +mcpp new mathlib --template lib +mcpp new vision --template mcpplibs.mwrap.opencv@5.0.0.1 +mcpp new --list-templates mcpplibs.mwrap.opencv@5.0.0.1 +mcpp new tool --vcs none +``` + +A template is `bin` (default), `lib`, `platform`, or a package's own: +`[namespace.]name[@version][:template]`; the template name may be left out +when the package has one. + +## Reads, writes, network + +- Writes only the new directory. A package template is fetched from the + package index (network; `--offline` uses what the home holds). +- The repository: `--vcs git` (default) or `--vcs none`; `config.toml` + `[new] vcs` states the machine's default. Inside another repository or + project, no repository is made unless one is stated. + +## Refusals + +- The directory exists and is not empty: choose another name. +- `[vcs-unavailable]`: git was asked for and cannot run; install git or pass + `--vcs none`. +- A template a package does not have: `--list-templates ` lists them. + +## Waits + +None of its own; a package template waits as a fetch does (`--lock-wait`). diff --git a/docs/mcpp-skills/mcpp-pack/SKILL.md b/docs/mcpp-skills/mcpp-pack/SKILL.md new file mode 100644 index 000000000..ea7144b45 --- /dev/null +++ b/docs/mcpp-skills/mcpp-pack/SKILL.md @@ -0,0 +1,41 @@ +--- +name: mcpp-pack +description: Use when packaging a program as a distributable bundle, or a library as an interface with prebuilt binaries. +--- + +# mcpp pack + +Builds, then packages: a program becomes a bundle, a library its interface +and prebuilt binaries. Packages go under `target/dist/`. + +## Examples + +``` +mcpp pack +mcpp pack --target x86_64-linux-musl --mode static +mcpp pack --pkg-format tar,okb +mcpp pack --target openkal +mcpp pack --list-formats +mcpp pack --message-format json +``` + +`--mode` states what the machine provides: `system`, `vendored` (default), +`self-contained`, `static`. `--pkg-format` is `tar`, `zip`, `dir`, +`single-file`, `polyglot`, or a format the resolved graph provides. +`mcpp pack --help` lists the options in two groups. + +## Reads, writes, network + +What `mcpp build` reads and writes, then `target/dist/`. + +## Refusals + +- `[runtime-closure]`: a library the program loads is not in the package; + the message names it and the file the link read. +- `[soname-collision]`, `[static-package-in-two-images]`: two images of one + package; the message names both. +- Everything `mcpp build` refuses. + +## Waits + +As `mcpp build`; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-publish/SKILL.md b/docs/mcpp-skills/mcpp-publish/SKILL.md new file mode 100644 index 000000000..e1c727b86 --- /dev/null +++ b/docs/mcpp-skills/mcpp-publish/SKILL.md @@ -0,0 +1,34 @@ +--- +name: mcpp-publish +description: Use when publishing the package, or every workspace member, to its index. +--- + +# mcpp publish + +Archives the package, writes its descriptor and publishes it to the default +registry; `--dry-run` prints the descriptor only. + +## Examples + +``` +mcpp publish --dry-run +mcpp publish +mcpp publish --tag "{name}-v{version}" +mcpp publish --workspace --exclude bench +``` + +## Reads, writes, network + +Reads the project and its git state; writes the archive and the descriptor; +uploads (network). A tree with uncommitted changes is refused unless +`--allow-dirty`. + +## Refusals + +- `[build-program-unpublished-input]`: the build program reads a file the + archive does not carry; include it in the package or stop reading it. +- Uncommitted changes: commit them, or `--allow-dirty`. + +## Waits + +None of its own. diff --git a/docs/mcpp-skills/mcpp-remove/SKILL.md b/docs/mcpp-skills/mcpp-remove/SKILL.md new file mode 100644 index 000000000..2a7bfe307 --- /dev/null +++ b/docs/mcpp-skills/mcpp-remove/SKILL.md @@ -0,0 +1,29 @@ +--- +name: mcpp-remove +description: Use when removing a dependency from mcpp.toml. +--- + +# mcpp remove + +Removes a dependency from `mcpp.toml`. + +## Examples + +``` +mcpp remove mcpplibs.cmdline +mcpp remove gtest --dev +mcpp remove mcpplibs.mplugin.cmdline --build +``` + +## Reads, writes, network + +Writes `mcpp.toml`; no network. The next build rewrites `mcpp.lock`. + +## Refusals + +A name the manifest does not list in that table: the message says which +tables were read. + +## Waits + +None. diff --git a/docs/mcpp-skills/mcpp-resolve/SKILL.md b/docs/mcpp-skills/mcpp-resolve/SKILL.md new file mode 100644 index 000000000..6c42cce0c --- /dev/null +++ b/docs/mcpp-skills/mcpp-resolve/SKILL.md @@ -0,0 +1,28 @@ +--- +name: mcpp-resolve +description: Use when re-resolving the build plan and printing what it resolved to. +--- + +# mcpp resolve + +Re-resolves the build plan and, with `--explain`, prints the resolved +toolchain, runtime, dependencies and runners: the same answer as `mcpp why`. + +## Examples + +``` +mcpp resolve --explain +``` + +## Reads, writes, network + +As `mcpp why`: reads the project, may install into the home and use the +network; builds nothing. + +## Refusals + +As `mcpp why`. + +## Waits + +As `mcpp why`; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-run/SKILL.md b/docs/mcpp-skills/mcpp-run/SKILL.md new file mode 100644 index 000000000..9d8cfe004 --- /dev/null +++ b/docs/mcpp-skills/mcpp-run/SKILL.md @@ -0,0 +1,43 @@ +--- +name: mcpp-run +description: Use when building and running one of the project's programs, passing it arguments, or asking how it would be started. +--- + +# mcpp run + +Builds the project, then runs a program target. Arguments after `--` reach +the program unchanged. + +## Examples + +``` +mcpp run +mcpp run server -- --port 8080 +mcpp run --release +mcpp run --target aarch64-linux-musl +mcpp run --file data/input.txt +mcpp run --print-launch --message-format json +mcpp run --list-runners +``` + +Of several programs, name the one to run. A target this host cannot execute +runs through the runner the target states (an emulator, a device); `--runner` +names another and `--no-runner` runs the file directly. + +## Reads, writes, network + +What `mcpp build` reads and writes, then the program runs in the project +directory (or, with `--file`, in a directory of the build tree). The exit +status is the program's. + +## Refusals + +- A program the project does not have: the message lists the programs. +- A runner that is not enabled: the message carries `[runner-not-enabled]` + and says how to enable it; `--list-runners` lists the named runners. +- Everything `mcpp build` refuses. + +## Waits + +As `mcpp build`; `--lock-wait` bounds it. The program itself is not waited +on by mcpp's locks. diff --git a/docs/mcpp-skills/mcpp-search/SKILL.md b/docs/mcpp-skills/mcpp-search/SKILL.md new file mode 100644 index 000000000..fdaabfd13 --- /dev/null +++ b/docs/mcpp-skills/mcpp-search/SKILL.md @@ -0,0 +1,33 @@ +--- +name: mcpp-search +description: Use when looking for a package in the configured indexes, its versions and features. +--- + +# mcpp search + +Searches the configured package indexes by keyword. + +## Examples + +``` +mcpp search cmdline +mcpp search opencv --all-versions +mcpp search json --format json +``` + +`--format json` prints the `mcpp.search` envelope: every version, licenses, +repository and features. + +## Reads, writes, network + +Refreshes an index older than its time to live (network); `--offline` reads +what the home holds. Needs no project. + +## Refusals + +None of its own; an index that cannot be refreshed is reported and the local +copy is read. + +## Waits + +An index refresh waits for another run's; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-self/SKILL.md b/docs/mcpp-skills/mcpp-self/SKILL.md new file mode 100644 index 000000000..51707a4a8 --- /dev/null +++ b/docs/mcpp-skills/mcpp-self/SKILL.md @@ -0,0 +1,43 @@ +--- +name: mcpp-self +description: Use when inspecting or maintaining mcpp itself - its home, health, configuration, shell completion and version. +--- + +# mcpp self + +About mcpp itself: `init`, `doctor`, `env`, `config`, `version`, +`completion`, `explain`, `store`. + +## Examples + +``` +mcpp self doctor +mcpp self env +mcpp self env --format json +mcpp self env --target x86_64-linux-musl +mcpp self init --home /data/mcpp +mcpp self config --mirror CN +mcpp self config --keep-days 7 +mcpp self completion bash +mcpp self store dedupe +``` + +`self env` prints the home, the toolchains and the configuration; with +`--target`, one configuration as a build would prepare it. +`self completion` writes the shell's completion script into the home and +prints the line that loads it. + +## Reads, writes, network + +`init` and `config` write the home; `doctor` and `env` read it; `--system` +maintains the machine's system home. Needs no project. + +## Refusals + +`self init --home` on a path that cannot be written: the message names the +path. `self doctor` reports problems and their remedies; it refuses nothing. + +## Waits + +`init` waits for another run's install into the home; `--lock-wait` bounds +it. diff --git a/docs/mcpp-skills/mcpp-stage/SKILL.md b/docs/mcpp-skills/mcpp-stage/SKILL.md new file mode 100644 index 000000000..ca7a23e05 --- /dev/null +++ b/docs/mcpp-skills/mcpp-stage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: mcpp-stage +description: Use when a build action must copy a file into place, writing only when its content differs. +--- + +# mcpp stage + +Copies one file to `-o PATH`, creating the parent directory and writing only +when the content differs, so that what depends on the destination is not +rebuilt for an identical copy. A tool for actions: `build.ninja` and actions +declared with `${mcpp.self}` run it. + +## Examples + +``` +mcpp stage assets/logo.png -o target/assets/logo.png +mcpp stage --list placements.tsv +mcpp stage big.bin -o out/big.bin --verify size +``` + +`--list FILE` places every `` line of FILE in one +process. + +## Reads, writes, network + +Reads the source and writes the destination; no network. + +## Refusals + +A missing source: the message names it; exit 1. + +## Waits + +None. diff --git a/docs/mcpp-skills/mcpp-test/SKILL.md b/docs/mcpp-skills/mcpp-test/SKILL.md new file mode 100644 index 000000000..945fedf47 --- /dev/null +++ b/docs/mcpp-skills/mcpp-test/SKILL.md @@ -0,0 +1,48 @@ +--- +name: mcpp-test +description: Use when building and running the project's tests, selecting tests or cases, reading results as JSON, or building tests for another machine. +--- + +# mcpp test + +Builds every `tests/**/*.cpp` as a test program and runs it. Arguments after +`--` reach each test program. + +## Examples + +``` +mcpp test +mcpp test unit/math +mcpp test unit/math -- --gtest_filter=Math.Adds +mcpp test --list +mcpp test --failed +mcpp test --case "parser/*" +mcpp test --message-format json +mcpp test --since origin/main +mcpp test --shard 1/4 +mcpp test --target aarch64-linux-musl --no-run --archive tests.tar +``` + +A pattern selects test programs by path. `--case` selects the cases of a +program that speaks the test protocol (mtest); other frameworks take their +own filter after `--`. + +## Reads, writes, network + +What `mcpp build` reads and writes; the run's results are kept in the +project's store, which `--failed` and `--shard` read. + +## Results + +`--message-format json` writes one NDJSON record per test and a `summary` per +member. Exit 0: every test passed; 1: a test failed; 2: a test could not run. +`--timeout SECS` kills a test still running (default 300). + +## Refusals + +- No test matches the pattern: `mcpp test --list` lists them. +- Everything `mcpp build` refuses. + +## Waits + +As `mcpp build`; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-toolchain/SKILL.md b/docs/mcpp-skills/mcpp-toolchain/SKILL.md new file mode 100644 index 000000000..315d090ee --- /dev/null +++ b/docs/mcpp-skills/mcpp-toolchain/SKILL.md @@ -0,0 +1,40 @@ +--- +name: mcpp-toolchain +description: Use when installing, listing, selecting or removing the C++ toolchains mcpp builds with. +--- + +# mcpp toolchain + +Manages the toolchains in mcpp's home: `list`, `install`, `default`, +`remove`. + +## Examples + +``` +mcpp toolchain list +mcpp toolchain install gcc 16 +mcpp toolchain install llvm 22 +mcpp toolchain install llvm 22 --target x86_64-windows-gnu +mcpp toolchain default gcc@16.1.0 +mcpp toolchain remove llvm@20.1.8 +mcpp toolchain list --format json +``` + +A project pins its toolchain in `[toolchain]`; `--toolchain SPEC` on a build +uses one for that build. + +## Reads, writes, network + +Installs into the home (network); `list` reads it. `--system` maintains the +machine's system home. + +## Refusals + +- A version the index does not have: `mcpp toolchain list` and the message + name those that exist. +- `[host-cannot-serve]`: no payload for this host and target. + +## Waits + +An install waits for another run's install into the home; `--lock-wait` +bounds it. diff --git a/docs/mcpp-skills/mcpp-update/SKILL.md b/docs/mcpp-skills/mcpp-update/SKILL.md new file mode 100644 index 000000000..ffef96086 --- /dev/null +++ b/docs/mcpp-skills/mcpp-update/SKILL.md @@ -0,0 +1,32 @@ +--- +name: mcpp-update +description: Use when re-resolving dependencies to newer allowed versions and rewriting mcpp.lock. +--- + +# mcpp update + +Re-resolves the dependencies within what `mcpp.toml` allows and rewrites +`mcpp.lock`; with a name, that package alone. + +## Examples + +``` +mcpp update +mcpp update mcpplibs.cmdline +``` + +## Reads, writes, network + +Refreshes the package indexes (network) and writes `mcpp.lock`. +`--locked` (or `MCPP_LOCKED=1`) on other commands refuses instead of +changing the lock. + +## Refusals + +- `E0003`: no published version satisfies a constraint; loosen it in + `mcpp.toml`. +- `[package-cycle]`: the graph has a cycle; the message names its edges. + +## Waits + +An index refresh waits for another run's; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-version/SKILL.md b/docs/mcpp-skills/mcpp-version/SKILL.md new file mode 100644 index 000000000..e4292ad3d --- /dev/null +++ b/docs/mcpp-skills/mcpp-version/SKILL.md @@ -0,0 +1,31 @@ +--- +name: mcpp-version +description: Use when reading which mcpp release is running. +--- + +# mcpp version + +Prints `mcpp `, as `mcpp --version` does. + +## Examples + +``` +mcpp version +mcpp --version +``` + +The version is the release's date and a sequence number, `2026.12.4.1`. +`mcpp self env --format json` carries it with the protocol and features a +client gates on. + +## Reads, writes, network + +Nothing. + +## Refusals + +None. + +## Waits + +None. diff --git a/docs/mcpp-skills/mcpp-why/SKILL.md b/docs/mcpp-skills/mcpp-why/SKILL.md new file mode 100644 index 000000000..540c84f0c --- /dev/null +++ b/docs/mcpp-skills/mcpp-why/SKILL.md @@ -0,0 +1,39 @@ +--- +name: mcpp-why +description: Use when asking how mcpp resolved the target, toolchain, dependencies, features, flags or the source of a tool. +--- + +# mcpp why + +Prepares the build without building and states how each decision was reached. + +## Examples + +``` +mcpp why +mcpp why toolchain +mcpp why deps +mcpp why features +mcpp why flags main.cpp +mcpp why tool ninja +mcpp why toolchain --target x86_64-windows-gnu --format json +``` + +Topics: `target`, `toolchain`, `sysroot`, `runtime`, `deps`, `runners`, +`sources`, `tool`, `payload`, `build-programs`, `compat`, `flags`, +`platform`, `features`. Without a topic, all but `flags`, `platform` and +`features`. + +## Reads, writes, network + +Reads the project; resolving may install a toolchain or a dependency (the +home, the network) and run build programs. Writes nothing into the project. + +## Refusals + +The refusals a build would meet are reported as the answer, with their +reason tokens; `mcpp explain ` describes each. + +## Waits + +As a fetch: installs into the home; `--lock-wait` bounds it. diff --git a/docs/mcpp-skills/mcpp-write/SKILL.md b/docs/mcpp-skills/mcpp-write/SKILL.md new file mode 100644 index 000000000..7caf5fc1d --- /dev/null +++ b/docs/mcpp-skills/mcpp-write/SKILL.md @@ -0,0 +1,31 @@ +--- +name: mcpp-write +description: Use when a build action must write a generated text file from lines and other files, writing only when the content differs. +--- + +# mcpp write + +Writes the lines after `--`, then each `--append` file, to `-o PATH`; the +file is written only when its content differs. A tool for actions declared +with `${mcpp.self}`, which runs it on every platform without a shell. + +## Examples + +``` +mcpp write -o target/gen/version.txt -- 2026.12.4.1 +mcpp write -o target/gen/all.list --append a.list --append b.list -- header +``` + +Declare each `--append` file as an input of the action. + +## Reads, writes, network + +Reads the appended files and writes the destination; no network. + +## Refusals + +A file to append that cannot be read: the message names it; exit 1. + +## Waits + +None. diff --git a/docs/mcpp-skills/mcpp-xpkg/SKILL.md b/docs/mcpp-skills/mcpp-xpkg/SKILL.md new file mode 100644 index 000000000..c3e0a5d95 --- /dev/null +++ b/docs/mcpp-skills/mcpp-xpkg/SKILL.md @@ -0,0 +1,33 @@ +--- +name: mcpp-xpkg +description: Use when validating an xpkg descriptor (a package index entry) the way mcpp's resolver reads it. +--- + +# mcpp xpkg + +`mcpp xpkg parse ` reads a descriptor's `mcpp` segment exactly as +the resolver does; unknown keys are errors. + +## Examples + +``` +mcpp xpkg parse pkgs/c/cmdline.lua +mcpp xpkg parse pkgs/c/cmdline.lua --all-os +mcpp xpkg parse pkgs/c/cmdline.lua --format json +``` + +`--all-os` validates every platform's section, not only this host's. + +## Reads, writes, network + +Reads the file; writes nothing; no network; needs no project. + +## Refusals + +A key the resolver does not know, a version table it cannot read, or a +platform that refers to one `xpm` has no table for: the message names the key +and the line. Exit 1 with the document when `--format json` is asked for. + +## Waits + +None. diff --git a/docs/mcpp-skills/mcpp/SKILL.md b/docs/mcpp-skills/mcpp/SKILL.md new file mode 100644 index 000000000..ca49de364 --- /dev/null +++ b/docs/mcpp-skills/mcpp/SKILL.md @@ -0,0 +1,97 @@ +--- +name: mcpp +description: Use mcpp, the build tool and package manager for C++23 modules - create, build, run and test a project, add dependencies, and read what mcpp reports. +--- + +# mcpp + +mcpp builds C++23 module projects that `mcpp.toml` describes. It installs the +toolchain, the standard library module and the dependencies a project needs +into its home (`~/.mcpp`, or `MCPP_HOME`); a compiler of the host is used only +when the project states it. Every command answers `--agent-skill-doc` with its +own sheet; `mcpp --help` lists its options. + +## The daily loop + +``` +mcpp new hello +cd hello +mcpp build +mcpp run -- --name world +mcpp test +mcpp add mcpplibs.cmdline@0.2.0 +``` + +`mcpp new` writes `mcpp.toml`, `src/main.cpp`, `tests/test_smoke.cpp` and a +git repository. A command that reads a project runs in the one whose +`mcpp.toml` is in the current directory or the nearest parent; `new`, +`search`, `self`, `toolchain`, `cache`, `index` and `explain` need none. + +## The manifest + +```toml +[package] +name = "hello" +version = "0.1.0" + +[dependencies] +mcpplibs.cmdline = "0.2.0" + +[dev-dependencies] +gtest = "1.15.2" +``` + +`src/main.cpp` is a program, `src/**/*.cppm` are modules, `tests/**/*.cpp` +are tests; `[targets.]` states a target the layout does not imply. +A key mcpp does not know is reported, never ignored. Chapter 04 of the +documentation lists every key. + +## Reading a message + +- `error:` stopped the command; `warning:` and `note:` did not. +- A `help:` line is the next step; an `impact:` line what a reduced run lost. +- A refusal ends with its reason token in brackets: `[layer-cycle]`. + `mcpp explain layer-cycle` describes it and the remedy, as it does for the + `E0001` codes and the `MCPP_*` codes of JSON diagnostics. +- `mcpp why ` states how a decision was reached: `mcpp why toolchain`, + `mcpp why deps`, `mcpp why flags`. +- A usage error names the closest declared names and the `--help` to read. + +## Output for programs + +- `--message-format json` on `build`, `test`, `run --print-launch` and `pack`, + and `--format json` on the queries (`self env`, `why`, `search`, `cache list`, + `toolchain list`, `index list`), print JSON on standard output; standard + error carries the narration. A document has `schemaVersion` and `kind`. +- A usage error asked for JSON is a `mcpp.usage` envelope: its diagnostic has + a `MCPP_USAGE_*` code and the closest names in `suggestions`. +- `MCPP_CLIENT=` names the caller in what mcpp records. +- `--offline` never touches the network; `--deny network,write-project` stops + before the named effects and exits 5. + +## Exit status + +| status | meaning | +|---|---| +| 0 | success | +| 1 | the command ran and failed: a compile, a test, a refusal | +| 2 | a usage error, or a request refused before anything ran | +| 5 | stopped before an effect the caller denied | +| 70 | an internal error | +| 127 | an unknown command | + +## Waiting + +Two runs that need one lock take turns. The one that waits says what it +waits for and which run holds it; it waits as long as the holder holds unless +`--lock-wait 2m` (or `MCPP_LOCK_WAIT`, `[build] lock_wait`) bounds it, and +then refuses with `[lock-wait-exceeded]`. A file system that cannot lock is +refused at once with `[lock-unavailable]`. + +## Where to read on + +- `mcpp --agent-skill-doc`: the sheet of one command (index below). +- `mcpp self doctor`: the health of the home and the toolchains. +- https://github.com/mcpp-community/mcpp/tree/main/docs: the documentation. +- https://github.com/mcpp-community/mcpp/issues: report a defect with the + command, its output and `mcpp --version`. diff --git a/docs/specs/README.md b/docs/specs/README.md index 86ef10957..1c2f74918 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -40,7 +40,7 @@ | [SPEC-008](library-interface.md) | 库的接口:公开模块、发布闭包与两种形态的一致 | 草案 v0.2 | 2026-10-11 | 第一阶段(只警告)mcpp >= 2026.9.28.3;v0.2 mcpp >= 2026.10.11.1 | | [SPEC-009](toolchain-maintenance.md) | 工具链的支持与维护:版本线、默认值、来源、移动与退役 | 草案 v0.7 | 2026-11-21 | 逐条标注;本版只有规范,多数条款未实现;§6.4 mcpp >= 2026.10.8.1 | | [SPEC-010](home-initialization.md) | home 选择、单跳入口、初始化、网络边界、单次运行的 `--home` 与来自目录的 home | 草案 v0.3 | 2026-11-21 | mcpp >= 2026.10.19.1;网络能力逐条标注;§6 mcpp >= 2026.10.26.1、xlings >= 2026.10.26.1 | -| [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.2 | 2026-11-19 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1 | +| [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁、等待的报告与上限、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.3 | 2026-12-04 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1;§2.1、§2.2 mcpp >= 2026.12.4.1 | | [SPEC-012](human-output.md) | 面向人的输出:两条流、两种介质、行的种类、颜色、程序的文本 | 评审中 v1.1 | 2026-11-19 | mcpp >= 2026.10.26.1;§5 mcpp >= 2026.11.19.1 | | [SPEC-013](platforms.md) | 平台:`[platform]` 的七组键、版本组与 `hosted`,三种写法与层次,目标图与宿主图的选择,`cfg(platform)`,依赖图的补全,链接、命名与封装,运行器与载体,平台阶段与协议 17 | 评审中 v1.17 | 2026-11-23 | mcpp >= 2026.10.27.1;§10 的执行宿主与 §11 的载体架构 mcpp >= 2026.10.29.1;§7.5 版本组参与解析与 §14 平台系列 mcpp >= 2026.11.7.1;§14 内置平台为确切版本 mcpp >= 2026.11.7.2;v1.7 条款 mcpp >= 2026.11.10.1;§14 索引的平台列 mcpp >= 2026.11.17.1;§14 系列取可用的最新版本与 §15.1 的 `+b` 条目 mcpp >= 2026.11.19.1;v1.17 条款 mcpp >= 2026.11.23.1 | | [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.2 | 2026-11-10 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1 | diff --git a/docs/specs/concurrency.md b/docs/specs/concurrency.md index c39cb8cc4..8a2233d21 100644 --- a/docs/specs/concurrency.md +++ b/docs/specs/concurrency.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-011 | | 标题 | 同一工程上的并发运行:构建目录锁、原子发布、乐观写入与取消 | -| 状态 | 评审中 v1.2 | -| 版本 | 1.2 | -| 最后修改 | 2026-11-19 | -| 对应实现 | 基础保证: mcpp >= 2026.10.26.1; §5.1: mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条: mcpp >= 2026.11.19.1 | +| 状态 | 评审中 v1.3 | +| 版本 | 1.3 | +| 最后修改 | 2026-12-04 | +| 对应实现 | 基础保证: mcpp >= 2026.10.26.1; §5.1: mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条: mcpp >= 2026.11.19.1;§2 第 3 条的报告、§2.1、§2.2 与 §6 的标准库模块: mcpp >= 2026.12.4.1 | | 相关设计文档 | `.agents/docs/2026-10-26-control-contract-runtime-and-ide-ecosystem-design.md` §3、§4、§5.4 | | 相关 issue | #839 | | 使用文档 | [50 — 机器可读输出](../zh/50-machine-output.md) §9、§11 | @@ -41,9 +41,8 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 `pid`、开始时间、命令行与调用方标签(`MCPP_CLIENT`)。 2. 锁**必须**在修改段开始时获取(完整规划时在准备的收尾阶段之前,快速路径在接纳记录的 计划之前),持有到修改段结束。规划段**禁止**持有它。 -3. 后到者**必须**等待而不是失败。等待超过 300 ms 时,标准错误上出现一行 - `Waiting for the build directory, held by pid N (, from , Ns)`, - `--message-format json` 下另有 `waiting` 事件。取得锁后,ninja 只做前者未做完的事。 +3. 后到者**必须**等待而不是失败,等待按 §2.1 报告并受其上限约束。取得锁后,ninja 只做 + 前者未做完的事。 4. 不同配置的构建使用不同的目录与不同的锁,**禁止**相互等待。 5. 锁描述符**必须**带 close-on-exec;`mcpp run` **必须**在 exec 程序之前释放锁,程序 运行期间同配置的构建不被阻塞。`mcpp test` 持锁直到测试结束,因为它在同一构建目录中 @@ -51,6 +50,31 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 6. 进程崩溃或被 SIGKILL 时由操作系统释放锁,不存在僵死锁。Windows 使用 `LockFileEx`, 语义相同(实测见设计 E24)。 +### 2.1 等待 已实现 + +本节适用于 mcpp 的每一把锁:构建目录、home 的安装状态、标准库模块条目、索引刷新、工程的 +构建记录。 + +1. 每一次等待**必须**经同一个原语进行。等待超过 300 ms 时,标准错误上**必须**写出等待的 + 对象、锁文件、最后记录的持有者(`pid`、命令、调用方标签、开始时间)以及该进程在本机 + 是否可见;此后在 10 s、30 s、60 s 与每分钟各写一行。`--message-format json` 下每次报告 + 另为一个 `waiting` 事件,带同样的事实。 +2. 持有者记录是提示而非证明。持有者在本机不可见时,**禁止**据此判定锁已失效:它可能运行在 + 另一个进程命名空间、容器或共享 home 的另一台机器上。报告**必须**写出在本系统上列出该 + 文件持有者的命令。 +3. 等待的上限是一个时长(`0` 表示不等待),按 [SPEC-004](manifest-semantics.md) §2 的 + 四层取第一个写明的:覆盖(`--lock-wait`、`MCPP_LOCK_WAIT`)、工程(`mcpp.toml` 的 + `[build] lock_wait`)、机器(`config.toml` 的 `[build] lock_wait`);都没有写明时等到 + 持有者放手。 +4. 超过上限的运行**必须**以 `[lock-wait-exceeded]` 被拒绝,消息写出持有者与上限的出处。 + 提供者自己的锁**必须**受同一上限约束(`XLINGS_LOCK_TIMEOUT`,以整秒计)。 + +### 2.2 不能加锁 已实现 + +系统无法为锁文件加锁时(权限、只读或不支持锁的文件系统、描述符耗尽),等待不会结束。 +运行**必须**立即以 `[lock-unavailable]` 被拒绝,消息写出锁文件、系统给出的原因与补救, +**禁止**把它当作被他人持有而等待。 + ## 3. 原子发布 已实现 | 资源 | 规则 | @@ -152,7 +176,9 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 ## 6. 全局一侧 全局 `MCPP_HOME` 保持既有的细粒度保护:索引刷新使用非阻塞锁,BMI 缓存按条目加锁, -工具链按版本目录安装。编译器探测缓存(`/cache/probe`)与提供者握手缓存 +工具链按版本目录安装。标准库模块条目的记录是它的完成标记:记录以改名写入并列出条目的 +各个文件;记录完整且所列文件都存在的条目**必须**不加锁即可读取,只有构建它的运行持锁 +(2026.12.4.1+)。编译器探测缓存(`/cache/probe`)与提供者握手缓存 (`/cache/provider-handshake`)的条目以写临时文件后改名的方式发布,并发的写入者 写出相同的内容。它们只由声明了 `write-global-cache` 的运行(规划或构建)写入,其他命令 只读取:`self doctor`、`self env`、`toolchain list` 不改变 home。 @@ -164,3 +190,4 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 1.0 | 2026-10-26 | 首版:三段、构建目录锁、原子发布、`mcpp.lock` 的乐观写入、取消(#839) | | 1.1 | 2026-11-06 | 分离编译的单元观察、共享名额、绝对输出事务与有限恢复边界;对齐取消请求的 OS 接收方式。 | | 1.2 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#952,设计 2026-11-19 §10):§5.1 第 6 条不可观察单元的恢复与报告、拒绝写出个数与出路;第 8 条输出可重定向的工具链上编译写入尝试私有的路径并由执行器发布;第 9 条清理退役运行状态;第 10 条准入的条件、执行器的结束原因与不能声明单元的环境;第 11 条编译器的记录由执行器写为依赖文件,第 12 条程序的文本在执行器中解码为 UTF-8(mcpp#970,设计 2026-11-19 §20)。 | +| 1.3 | 2026-12-04 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7):§2.1 每一次等待经同一原语、按时刻报告、持有者记录为提示、四层上限与 `[lock-wait-exceeded]`、提供者的锁受同一上限;§2.2 不能加锁时立即以 `[lock-unavailable]` 拒绝;§6 完整的标准库模块条目不加锁读取。 | diff --git a/docs/zh/01-getting-started.md b/docs/zh/01-getting-started.md index dd06a0f27..d4063eb84 100644 --- a/docs/zh/01-getting-started.md +++ b/docs/zh/01-getting-started.md @@ -97,6 +97,8 @@ mcpp new hello && cd hello ``` hello/ +├── .git/ ← 一个仓库,未加入、未提交任何文件 +├── .gitignore ├── mcpp.toml ← project manifest ├── src/ │ └── main.cpp @@ -104,6 +106,12 @@ hello/ └── test_smoke.cpp ← runs with `mcpp test` ``` +工程是一个 git 仓库,其中未加入、也未提交任何文件(2026.12.4.1+)。`--vcs none` 不建仓库, +`--vcs git` 建仓库;本机的默认值是 `config.toml` 中的 `[new] vcs = "git" | "none"`。 +在另一个 git 工作树之中,或在一个含 `mcpp.toml` 的目录之中,除非上述两者之一要求,否则不建 +仓库,因此在工作空间里新建的成员仍属于工作空间的仓库。没有 git 时工程照常建立,并以一条警告 +说明它不是仓库;带 `--vcs git` 时命令以 `[vcs-unavailable]` 失败,已建立的工程保留。 + 生成的 manifest 只含包元数据;mcpp 从 `src/main.cpp` 推断 binary target。默认情况下该文件是一个 C++23 模块化的 hello world: diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index 238990dca..95376f32f 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -1022,6 +1022,7 @@ compile_commands = "compile_commands.json" # 相对工程根目录的路径 | `allow_host_libs` | [20 —— 工具链](20-toolchains.md)、[22 —— 目标侧](22-target-side.md) | | `allow_host_tools` | [25 —— home、索引与 store](25-home-indices-and-store.md) | | `ios_deployment_target` | [20 —— 工具链](20-toolchains.md) | +| `lock_wait` | [25 —— home、索引与 store](25-home-indices-and-store.md),「等待锁」 | | `offline` | [05 —— 依赖](05-dependencies.md),「离线构建与 mcpp fetch」 | | `platform-dependencies` | [22 —— 目标侧](22-target-side.md) | | `std-module`、`std-compat-module` | [22 —— 目标侧](22-target-side.md) | diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index 7c6df2c7c..231d105e9 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -8,7 +8,9 @@ **不在这里:** 每条命令含义上的细节。一个场景点名命令,并链接到拥有它的 那一章。在此之前:[08 —— 测试](08-testing.md)。 -命令清单是 `mcpp --help`,每个子命令还带自己的 `--help`。本章回答的是另一个 +命令清单是 `mcpp --help`,每个子命令还带自己的 `--help`(`mcpp help ` 与之 +同义);`mcpp --agent-skill-doc` 与 `mcpp --agent-skill-doc` 给出二进制携带的用法 +说明([52](52-driving-mcpp-from-a-program.md))。本章回答的是另一个 问题:某个情形已经发生时该用哪条命令 —— 构建目录一直在变大、一次解析结果 出乎意料、一个描述符即将发布、一份索引可能已经陈旧。这里收的都是名字本身 没有说出它所属场景的命令。 @@ -234,15 +236,15 @@ dependency graph: `--target` 与 `--toolchain` 把报告变成对当前目录并不使用的那一对的查询, 一个目标矩阵正是这样逐格提问的。 -诊断里的一个错误码,可以用 `mcpp self explain` 展开: +一个代码可以用 `mcpp explain`(亦即 `mcpp self explain`)展开:`E` 开头的错误码、JSON +诊断的 `MCPP_*` 代码,或拒绝末尾括号中的原因码。应答说明代码的含义与补救;查不到的代码 +给出最相近的已有代码(2026.12.4.1+): ``` -$ mcpp self explain E0006 -E0006: index requires a newer mcpp +$ mcpp explain layer-cycle +layer-cycle: the packages that supply the layers require one another in a circle (...) -The package index declares (index.toml [index].min_mcpp) that its -descriptors need a newer mcpp than this binary — parsing them would -silently misbehave, so resolution stops instead. Upgrade mcpp: +Remove one of the requires edges the message names. ``` ## 索引新鲜度与离线构建 diff --git a/docs/zh/25-home-indices-and-store.md b/docs/zh/25-home-indices-and-store.md index 8590e0244..b741aba34 100644 --- a/docs/zh/25-home-indices-and-store.md +++ b/docs/zh/25-home-indices-and-store.md @@ -168,6 +168,28 @@ upstream(§3)与归档目录是不同事物的来源,两者并存:upstre locator 在本地校验成功后、获取资源之前保存。离线缺资源或联网失败导致初始化未完成时, 退出码为 1,所选目录仍保留。再次运行 `self init` 会在该目录继续。 +### 等待锁(2026.12.4.1+) + +共享一个 home 或一个工程的多次运行,轮流写入其中一次正在写的东西:构建目录、向 home 的安装、 +标准库模块、索引刷新。等待的运行在 300 ms 后说明这一点:它等的是什么、锁文件、最后记录的 +持有者,以及该进程在本机是否可见;之后在 10 s、30 s、60 s 与此后每分钟各重复一行。不可见的 +持有者并不意味着已经结束:它可能运行在另一个进程命名空间、容器,或共享该 home 的另一台机器上, +报告给出在本系统上列出该文件持有者的命令。 + +没有写明上限时,运行一直等到持有者放手。上限是一个时长(`30s`、`2m`、`1h`;`0` 不等待), +取以下第一个写明的: + +| 层 | 位置 | +|---|---| +| 覆盖 | `--lock-wait `、`MCPP_LOCK_WAIT` | +| 工程 | `mcpp.toml` 的 `[build] lock_wait` | +| 机器 | `config.toml` 的 `[build] lock_wait` | + +超过上限时运行以 `[lock-wait-exceeded]` 被拒绝,消息写出持有者与上限的出处。提供者自己的锁受同一 +上限约束(`XLINGS_LOCK_TIMEOUT`)。系统无法加锁的锁文件 —— 没有写权限的目录、只读或不支持锁的 +文件系统、描述符耗尽 —— 立即以 `[lock-unavailable]` 被拒绝,并给出系统的原因与补救:等待不会 +结束。已完整的标准库模块不加锁即可读取。契约见 [SPEC-011](../specs/concurrency.md)。 + ## 2. 刷新索引 mcpp 所有的索引被拉取到它旁边的暂存目录,在那里按其声明的下限(`index.toml` 的 `min_mcpp`)检查,只有当前 mcpp diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index f9f237fc9..6ceeb1f87 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -66,10 +66,14 @@ CI 脚本,以及任何解析 mcpp 输出的程序,都可以依赖本章陈 "path": "mcpp.toml", // omitted when there is none "range": { "start": {"line": 3, "column": 1}, "end": {"line": 3, "column": 9} }, // omitted when there is none - "shown": false // omitted when the terminal showed it + "shown": false, // omitted when the terminal showed it + "suggestions": ["--jobs"] // omitted when there are none } ``` +`suggestions` 列出与一个未知名字最相近的已声明名字,最相近的在前(用法错误,`mcpp.usage`; +2026.12.4.1+)。 + `shown` 为 `false` 表示终端没有显示这条诊断:工程已被告知过、一个工程只说一次的提示,以及 `--quiet` 下的说明(2026.11.21.1+)。信封携带每一条诊断,终端是否显示都携带;读取者不受终端的 显示策略影响。在自己的目录中规划的命令(`mcpp emit build-database`)读取工程已被告知的内容,不作记录: @@ -118,9 +122,22 @@ $ echo $? ``` 一个还不知道自己会得到什么格式的请求,不应该往协议独占的那个通道里写东西。 -结合 §1,客户端的规则就是完整的了:**stdout 上没有 JSON,就意味着不支持**, +结合 §1,客户端的规则就是完整的了:**stdout 上没有它所要求的 kind 的信封,就意味着不支持**, 无论原因是什么。 +解析器拒绝的命令行 —— 未知的命令或选项、缺少值的选项、命令不接受的值或参数 —— 是用法错误 +(2026.12.4.1+)。它在 stderr 上是一行原因加至多两行 `help:`:与未被理解的词最相近的已声明 +名字,以及列出可用名字的那一级 `--help`。命令行要求 JSON 时(`--format json` 或 +`--message-format json`),stdout 上另有一个 `mcpp.usage` 信封(§8):它的 kind 从不是所要求 +的 kind,所以上面的规则仍然成立。未知的顶层命令退出码为 127,其余用法错误为 2。 + +``` +$ mcpp build --jbos 3 --message-format json +{ "kind": "mcpp.usage", "data": {"command": "mcpp build"}, + "diagnostics": [{"code": "MCPP_USAGE_UNKNOWN_OPTION", "message": "unknown option: --jbos", + "suggestions": ["--jobs"], ...}], ... } +``` + **带信封命令**的退出码 —— 即 `--protocol-version` 所声明的那几个 kind。这张 表刻意只覆盖它们:别的命令返回的退出码不在其中,把它写进来等于记录一件这些 命令给不出的事实。跨越 mcpp 全部命令的完整映射见 @@ -624,6 +641,9 @@ replaced}` —— `origin` 与构建的状态行使用的是同一句话 | `platform-tool-absent` | 平台的链接或封装要运行的程序(ok 映像的 `okld`)既不由图构建,也不在本机 *(2026.10.27.1+;2026.10.26.2 中为 `image-tool-absent`)* | | `platform-version-group` | 平台版本组中的一个包以另一个版本出现在图中 *(2026.10.27.1+)*,或平台系列中没有版本容许本次构建的请求 *(2026.11.19.1+)* | | `platform-phase-directive` | 平台插件陈述了其阶段不接受的指令 *(2026.10.27.1+)* | +| `lock-wait-exceeded` | 另一次运行持有锁超过等待上限(`--lock-wait`、`MCPP_LOCK_WAIT`、`[build] lock_wait`);消息写出持有者 *(2026.12.4.1+)* | +| `lock-unavailable` | 系统无法为 mcpp 需要的文件加锁:权限、只读或不支持锁的文件系统、描述符耗尽;等待不会结束 *(2026.12.4.1+)* | +| `vcs-unavailable` | `mcpp new` 被要求建立仓库而 git 无法运行 *(2026.12.4.1+)* | | `other` | 一个尚未被赋予记号的拒绝分支 | **其中一个记号也由 `mcpp build` 自己打印。** `interface-not-provided` 会 @@ -938,7 +958,7 @@ mcpp build [target] [-p ] [--release] --message-format json | 事件 | 携带 | |---|---| | `plan` | `configuration`:构建已进入其构建目录的那个配置;`platform` 与 `hostPlatform`(2026.10.27.1+)是目标图与宿主图的平台,或 `null` | -| `waiting` | `holder`(`pid`、`command`、`client`、`startedAt`)与 `waitedMs`:另一次构建持有这个构建目录,本次在等待(§11) | +| `waiting` | `holder`(`pid`、`command`、`client`、`startedAt`)与 `waitedMs`:另一次运行持有本次需要的锁,本次在等待(§11);自 2026.12.4.1 起构建的每次等待都报告,另有 `resource`(等待的对象:构建目录、home 的安装状态、标准库模块)、`path`(锁文件)与 `holderVisible`(持有者是否为本机可见的进程) | | `progress` | `finished`、`total`:ninja 的步骤计数;一次构建可以运行不止一轮 ninja,每轮重新计数 | | `diagnostic` | `diagnostic`:失败步骤输出中的一条编译器诊断,形状同下文记录的 `diagnostics[]` | | `artifact` | `artifact`:一个产物,形状同下文记录的 `artifacts[]` | @@ -1059,8 +1079,11 @@ exit status 5` 结束,退出 **5**。被拒绝的 `write-global-cache` 不会 ## 11. 并发运行 一个配置的构建目录同一时刻只由一次运行写入。同一配置的第二次构建等待第一次,在 -标准错误上报告持有者(`Waiting for the build directory, held by pid 1234 (mcpp -build, from vscode, 8s)`),并发出 `waiting` 事件,之后几乎无事可做。不同配置的 +标准错误上报告等待的对象与最后记录的持有者(`Waiting for the build directory +`,随后是 `last recorded holder: pid 1234 (mcpp build, from vscode, 8s)`), +并发出 `waiting` 事件,之后几乎无事可做。运行等待的其余每一把锁都以同样方式报告,写明的上限 +(`--lock-wait`)以 `[lock-wait-exceeded]` 结束等待(2026.12.4.1+; +[25](25-home-indices-and-store.md))。不同配置的 构建、查询(`emit build-database`、`cache list`、读取记录),以及 `mcpp run` 与 `mcpp test` 启动的程序从不等待。链接产物整体替换,因此在链接期间启动的程序不会 执行半个文件。`mcpp.lock` 以乐观方式写入:本次解析期间被另一次运行写入的锁文件 @@ -1132,6 +1155,18 @@ mcpp pack --list-formats 规划的是该目标的依赖图,并列出其平台的格式:`mcpp pack --target x86_64-openkal --list-formats` 列出 `okb`,由 `mcpplibs.openkal-platform` 提供。 +### `mcpp.usage` —— 用法错误 *(mcpp 2026.12.4.1+)* + +``` +mcpp <解析器拒绝的命令行> --format json | --message-format json +``` + +`data.command` 是命令行到达的那一级命令(`mcpp build`、`mcpp cache`),它的 `--help` 列出它 +接受的名字。`diagnostics` 中只有一条 `error`:`code` 为 `MCPP_USAGE_UNKNOWN_COMMAND`、 +`MCPP_USAGE_UNKNOWN_OPTION`、`MCPP_USAGE_MISSING_VALUE`、`MCPP_USAGE_INVALID_VALUE`、 +`MCPP_USAGE_MISSING_ARGUMENT` 或 `MCPP_USAGE_INVALID_ARGUMENT`,`suggestions` 为与未知名字最 +相近的已声明名字。`effects` 为空:什么也没有运行。`mcpp explain ` 解释每个代码。 + ## 当前边界 - **退出码表的作用域仅限于它点名的那些命令。** 别的命令返回的退出码不在表 diff --git a/docs/zh/52-driving-mcpp-from-a-program.md b/docs/zh/52-driving-mcpp-from-a-program.md index 8add8fd44..7ed37452c 100644 --- a/docs/zh/52-driving-mcpp-from-a-program.md +++ b/docs/zh/52-driving-mcpp-from-a-program.md @@ -104,3 +104,22 @@ MCPP_CLIENT=my-agent mcpp build `Finished`);mcpp 的消息以 `error:`、`warning:` 或 `note:` 开头;关于某个文件的消息以 `:::` 开头;下一步单独成行,以 `help:` 开头。管道中没有颜色,除非 `CLICOLOR_FORCE` 或 `FORCE_COLOR` 要求。这些词本身没有兼容承诺;上文的记录有。 + +## 8. 二进制携带的用法 + +`mcpp --agent-skill-doc` 给出 mcpp 的用法:日常的一组命令、消息怎样读、面向程序的输出、 +退出状态,以及各命令说明的索引。`mcpp --agent-skill-doc` 给出一个命令的说明: +何时用它、可照抄的例子、它读什么、写什么、下载什么、常见的拒绝与补救、它可能等待什么。 +没有自己说明的子命令给出最近的上级的说明。说明是二进制的一部分(2026.12.4.1+):应答不需要 +工程、home 与网络,描述的就是打印它的那个发布。面向某个具体 agent 的指令可以只有一句 +「运行 `mcpp --agent-skill-doc`」。 + +`mcpp --help` 按分组列出命令树,末尾一行指向这些说明;`mcpp help ` 与 +`mcpp --help` 同义。 + +用法错误是一行原因加至多两行 `help:`:与未被理解的词最相近的已声明名字,以及列出可用名字的 +那一级 `--help`。要求 JSON 时(`--message-format json`、`--format json`),同一条错误同时是 +标准输出上的一个 `mcpp.usage` 信封,其诊断带 `MCPP_USAGE_*` 代码,相近的名字在 +`suggestions` 中([50](50-machine-output.md))。需要工程的命令在工程之外运行时说明这一点, +并给出两个下一步。`mcpp explain ` 解释 `E` 开头的错误码、诊断的 `MCPP_*` 代码与拒绝 +末尾括号中的原因码,给出补救,并对查不到的代码给出最相近的代码。 diff --git a/docs/zh/README.md b/docs/zh/README.md index e7651eefe..1f175c51f 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -11,6 +11,7 @@ | 树 | 读者 | 内容 | |---|---|---| | `docs/**` | 手上有任务的人 | mcpp 已实现的东西怎么用 | +| [`docs/mcpp-skills/**`](../mcpp-skills/mcpp/SKILL.md) | agent,以及手上只有二进制的人 | 二进制以 `--agent-skill-doc` 打印的用法说明:英文、ASCII,每份不超过一百行 | | [`docs/specs/**`](../specs/README.md) | 对着机制做实现的人:索引作者、下游工具、贡献者 | 语义、约束与匹配规则,每条标注实现状态 | | `.agents/docs/**` | 做过某次改动的人,以及以后问「为什么是这样」的人 | 推理、实测,以及什么被推翻了 | | `.agents/skills/**` | 照流程执行的贡献者或 agent | 带判据的步骤 | diff --git a/mcpp.toml b/mcpp.toml index c13e46917..148e6c06c 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -105,12 +105,10 @@ linkage = "static" linkage = "static" # Eat our own dog food: mcpp uses mcpplibs.cmdline for argument parsing. -# TOML-native namespaced form: `mcpplibs.cmdline` is the dotted subtable -# `[dependencies.mcpplibs] cmdline = "0.0.6"` ⇒ identity (mcpplibs, cmdline). -# The bootstrap mcpp used by the self-host build (xlings install mcpp, well -# past 0.0.6) understands this, so the legacy quoted form is no longer needed. +# `agent-skills` answers `--agent-skill-doc` from docs/mcpp-skills, which +# build.mcpp renders into the module mcpp.skills (design 2026-11-27 §3.9). [dependencies] -mcpplibs.cmdline = "0.0.6" +mcpplibs.cmdline = { version = "0.2.0", features = ["agent-skills"] } # JSON for Modern C++, as the index's module package (no copied header). nlohmann.json = "3.12.0" # The C library's macros (`stdout`, `stderr`, `EOF`, `errno` …) as C++ names: diff --git a/src/build/execute.cppm b/src/build/execute.cppm index 6a3512362..41a62fa43 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -7636,7 +7636,7 @@ export int run_tests(std::span passthrough, auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) { - mcpp::ui::error("no mcpp.toml found in current directory or any parent"); + mcpp::ui::error(mcpp::project::no_project_message()); return 2; } @@ -7901,7 +7901,7 @@ export int run_test_legs(std::span passthrough, const std::string memberName = base.package_filter; auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) { - mcpp::ui::error("no mcpp.toml found in current directory or any parent"); + mcpp::ui::error(mcpp::project::no_project_message()); return 2; } auto discovered = mcpp::build::discover_test_targets(*root, base.package_filter, base.target_triple); diff --git a/src/build/prepare/manifest.cpp b/src/build/prepare/manifest.cpp index 93c4eb82a..764473787 100644 --- a/src/build/prepare/manifest.cpp +++ b/src/build/prepare/manifest.cpp @@ -510,7 +510,7 @@ std::expected phase0_manifest_and_workspace(PrepareState& sta ? mcpp::project::find_manifest_root(std::filesystem::current_path()) : std::optional(state.overrides.project_root); if (!state.root) { - return std::unexpected("no mcpp.toml found in current directory or any parent"); + return std::unexpected(mcpp::project::no_project_message()); } // THE PROJECT'S PATH IS PART OF EVERY DOCUMENT A BUILD WRITES, and those // documents are UTF-8 text (build.ninja, compile_commands.json). A diff --git a/src/cli.cppm b/src/cli.cppm index cc5da93dc..066981f26 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -17,6 +17,8 @@ import mcpplibs.mwrap.libc; import mcpp.build.depfile; import mcpp.build.schedule.detach_codegen; import mcpplibs.cmdline; +import mcpplibs.cmdline.agent_skills; +import mcpp.skills; // the sheets build.mcpp rendered from docs/mcpp-skills import mcpp.cli.cmd_build; import mcpp.cli.cmd_cache; import mcpp.cli.cmd_new; @@ -29,6 +31,7 @@ import mcpp.cli.cmd_toolchain; import mcpp.pm.commands; import mcpp.toolchain.fingerprint; // MCPP_VERSION import mcpp.wire; +import nlohmann.json; import mcpp.cli.cmd_sbom; import mcpp.cli.cmd_surface; import mcpplibs.os.platform; @@ -59,67 +62,52 @@ namespace libc = mcpplibs::mwrap::libc::macros; export namespace mcpp::cli { int run(int argc, char** argv); +mcpplibs::cmdline::App command_tree(const std::vector& passthrough, + const mcpplibs::cmdline::App*& self); } // namespace mcpp::cli namespace mcpp::cli { -// Custom top-level help. cmdline's auto-generated `print_help` is a fine -// default but its layout (`USAGE:`, no command-specific blurbs) doesn't -// match what the e2e tests assert against — they check for `Usage:` -// (mixed case) plus `mcpp new` / `mcpp build` literals. We keep the -// canonical printer here so the docs/CHANGELOG examples don't drift -// every time cmdline tweaks its formatting. -void print_usage() { - std::println("mcpp v{} - modern C++23 build tool", mcpp::toolchain::MCPP_VERSION); - std::println(""); - std::println("Usage:"); - std::println("Project commands:"); - std::println(" mcpp new Create a new package skeleton"); - std::println(" mcpp build [options] Build the current package"); - std::println(" mcpp fetch [--to DIR | --from DIR] Put what the build needs in the home; to or from a directory"); - std::println(" mcpp run [target] [-- args...] Build + run a binary target"); - std::println(" mcpp test [pattern] [-- args...] Build + run tests/**/*.cpp (--list, --no-run, --shard, --failed, --timeout, --build-timeout, --message-format json, --no-runner)"); - std::println(" mcpp clean [--stale] [--bmi-cache] Remove target/ (or, with --stale, only its non-current fingerprint dirs)"); - std::println(" mcpp add [ns.]pkg@ver Add an exact dependency to mcpp.toml"); - std::println(" mcpp remove [ns.]pkg Remove an exact dependency from mcpp.toml"); - std::println(" mcpp update [pkg] Re-resolve deps and rewrite mcpp.lock"); - std::println(" mcpp search Search packages in registries"); - std::println(" mcpp publish [--dry-run] Publish package to default registry"); - std::println(" mcpp pack [target] Build + package (program: bundle; library: interface + binaries)"); - std::println(" mcpp emit xpkg [-V VER] [-o FILE] Generate xpkg Lua entry"); - std::println(" mcpp xpkg parse [--json] Validate an xpkg descriptor (resolver grammar)"); - std::println(""); - std::println("Resource management:"); - std::println(" mcpp toolchain install|list|default Manage mcpp's private toolchains"); - std::println(" mcpp cache dir|list|info|gc|... Inspect/manage the global build cache"); - std::println(" mcpp index list|add|remove|update Manage package registries"); - std::println(""); - std::println("About mcpp itself:"); - std::println(" mcpp self doctor Diagnose mcpp environment health"); - std::println(" mcpp self env Print mcpp paths and toolchain"); - std::println(" mcpp self init [--force] [--home PATH] Initialize or select a remembered home"); - std::println(" mcpp self config [--mirror auto|CN|GLOBAL] Show or modify mcpp's xlings config"); - std::println(" mcpp self version Show mcpp version"); - std::println(" mcpp self explain Show extended description for an error code"); - std::println(" mcpp --help / --version Help / version"); - std::println(""); - std::println("Build options:"); - std::println(" --verbose, -v Verbose compiler output"); - std::println(" --quiet, -q Suppress status output"); - std::println(" --print-fingerprint Show toolchain fingerprint and 11 inputs"); - std::println(" --configure-only Generate CDB without compiling or linking"); - std::println(" --cache Dependency cache: global (default) | local | off"); - std::println(" --no-cache Deprecated alias for --cache=off (clears the build dir)"); - std::println(" --no-color Disable colored output"); - std::println(" --offline Never touch the network (also: MCPP_OFFLINE=1)"); - std::println(" --system Maintain the machine's system home (administrators)"); - std::println(" --locked Fail if resolution differs from mcpp.lock (also: --frozen, MCPP_LOCKED=1)"); - std::println(" --play-game[=NAME] Play snake, stack or runner in the status row while it builds"); - std::println(" --jobs N|auto, -j Concurrent compiles ('auto' = cores + free RAM)"); - std::println(" --toolchain SPEC Use this toolchain for one build (e.g. llvm@22.1.8)"); - std::println(""); - std::println("Docs: https://github.com/mcpp-community/mcpp/tree/main/docs"); +// A USAGE ERROR (design 2026-11-27 §3.9.2): one line naming what was not +// understood, then at most two `help:` lines -- the declared names closest to +// it, from the list the help prints, and the help that lists what is. The +// whole help is not printed: a screen of text unrelated to the cause hid the +// cause. Asked for JSON (`--message-format json`, `--format json`), the same +// error is also the one diagnostic of a `mcpp.usage` envelope on standard +// output, with a stable code and the names as an array (docs/50 §3). An +// unknown top-level command exits 127, every other usage error 2. +int usage_error(const mcpplibs::cmdline::ParseError& e, std::span words) { + const std::string command = e.command.empty() ? std::string("mcpp") : e.command; + const bool unknownCommand = e.code == "unknown-command"; + const bool argument = e.code == "missing-argument" || e.code == "invalid-argument"; + std::string text = e.message; + if (!e.suggestions.empty()) { + std::string names; + for (const auto& name : e.suggestions) names += std::format("{}`{}`", names.empty() ? "" : ", ", name); + text += std::format("\n help: the closest {}{}: {}", unknownCommand ? "command" : "option", + e.suggestions.size() == 1 ? "" : "s", names); + } + text += std::format("\n help: `{} --help` lists its {}", command, + unknownCommand ? "commands" : argument ? "arguments" : "options"); + mcpp::ui::error(text); + + bool json = false; + for (std::size_t i = 0; i < words.size(); ++i) { + const std::string_view word = words[i]; + for (const std::string_view flag : {"--message-format", "--format"}) { + if (word == flag && i + 1 < words.size() && std::string_view(words[i + 1]) == "json") json = true; + if (word.starts_with(flag) && word.substr(flag.size()) == "=json") json = true; + } + } + if (json) { + std::string code = "MCPP_USAGE_"; + for (const char c : e.code) code += c == '-' ? '_' : static_cast(std::toupper(static_cast(c))); + mcpp::wire::Envelope envelope{.kind = "mcpp.usage", .data = nlohmann::json{{"command", command}}}; + envelope.diagnostics.push_back({.code = code, .message = e.message, .suggestions = e.suggestions}); + mcpp::wire::emit(envelope); + } + return unknownCommand && command == "mcpp" ? 127 : 2; } // `mcpp pack --help`, IN TWO GROUPS (design 2026-10-29 §4.8): the options a @@ -284,515 +272,69 @@ int cmd_toolchain_any(const mcpplibs::cmdline::ParsedArgs& p) { return cmd_install_configuration(*target); } -int run(int argc, char** argv) { +// THE COMMAND TREE: every command, option and argument of mcpp, its help, +// its completion and its `--agent-skill-doc` sheets. One declaration, read by +// the parse, the help, the completion, `emit surface` and the test that checks +// the sheets against it (tests/unit/test_repo_consistency.cpp). `passthrough` +// is what followed `--` on the command line; `self` is set by the caller once +// the tree is where it stays, for `emit surface`. +mcpplibs::cmdline::App command_tree(const std::vector& passthrough, + const mcpplibs::cmdline::App*& self) { namespace cl = mcpplibs::cmdline; + auto app = cl::App("mcpp") + .version(std::string{mcpp::toolchain::MCPP_VERSION}) + .description("modern C++ build tool") + // Completion is the library's (design 2026-11-27 §4.11): `mcpp + // __complete ` answers from this tree, and `mcpp self + // completion` writes the adapter a shell reads. + .completion({.command = ""}) + // The root's help is the command tree: each group a section of its + // own, then where an agent and a reader go next (design 2026-11-27 + // §3.9.2). + .help_options({.groups_as_sections = true}) + .help_epilogue("Agents: mcpp --agent-skill-doc prints how to use mcpp; every command takes the flag.\n" + "Docs: https://github.com/mcpp-community/mcpp/tree/main/docs") + .option(cl::Option("quiet").short_name('q') + .help("Suppress status output").global()) + .option(cl::Option("verbose").short_name('v') + .help("Show detailed progress on stderr").global()) + .option(cl::Option("no-color") + .help("Disable colored output").global()) + .option(cl::Option("offline") + .help("Never touch the network (index refresh, downloads, toolchain install); = --deny network") + .global()) + .option(cl::Option("deny").takes_value().value_name("EFFECTS") + .help("Stop before any of these effects, exit 5: network, write-project, write-global-cache, exec-build-script, init-mcpp-home (also: MCPP_DENY_EFFECTS)") + .global()) + .option(cl::Option("system") + .help("Maintain the machine's system home (self init|doctor|store, toolchain install|remove|default, index update)") + .global()) + // Declared here as well as read in the pre-pass: the pre-pass sets the + // env var, and this makes the parser accept the token instead of + // rejecting it as unknown. Both halves are needed, which is exactly the + // arrangement `--offline` above already has. + .option(cl::Option("locked") + .help("Fail if dependency resolution differs from mcpp.lock") + .global()) + .option(cl::Option("frozen") + .help("Alias for --locked") + .global()) + .option(cl::Option("managed-only") + .help("Fail if a toolchain, payload or plugin tool does not come from the ecosystem") + .global()) + .option(cl::Option("lock-wait").takes_value().value_name("DURATION") + .help("Wait at most this long for a lock another mcpp holds, then refuse (30s, 2m, 0; also: MCPP_LOCK_WAIT)") + .global()) - // 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. - if (argc > 1 && std::string_view(argv[1]) == "__compiler-cap") { - std::filesystem::path semaphore; - std::filesystem::path output; - std::filesystem::path depfile; - std::filesystem::path bmi; - std::string relocate; - mcpp::build::schedule::detach::Reading reading; - bool object = false; - int cap = 0, i = 2; - for (; i < argc && std::string_view(argv[i]) != "--"; ++i) { - const std::string_view option = argv[i]; - // `--output` is an object of a compile: it is kept when the - // compiler writes the bytes it had. - if (option == "--object") { object = true; continue; } - if ((option != "--sem" && option != "--cap" && option != "--output" && option != "--depfile" - && option != "--bmi" && option != "--relocate" && option != "--source-dependencies" - && option != "--text") || i + 1 >= argc) { - std::println(libc::stderr(), "error: __compiler-cap: expected --sem [--cap ] [--object] [--bmi ] [--relocate ] [--source-dependencies ] [--text console] -- ..."); - return 2; - } - const std::string_view value = argv[++i]; - if (option == "--sem") semaphore = value; - else if (option == "--output") output = value; - else if (option == "--depfile") depfile = value; - else if (option == "--bmi") bmi = value; - else if (option == "--relocate") relocate = value; - else if (option == "--source-dependencies") reading.sourceDependencies = value; - else if (option == "--text") { - if (value != "console") { - std::println(libc::stderr(), "error: __compiler-cap: --text takes `console`, not `{}`", value); - return 2; - } - reading.text = mcpplibs::os::text::encoding::console; - } else { - const auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), cap); - if (ec != std::errc{} || end != value.data() + value.size()) return 2; - } - } - // No --cap: the generation's, or MCPP_COMPILER_CAP outside one. - if (semaphore.empty() || cap < 0 || i + 1 >= argc) return 2; - std::vector command; - for (++i; i < argc; ++i) command.emplace_back(argv[i]); - // THE EDGE, MEASURED (design 2026-11-20 §5.6): its start, for the - // progress line of a long compile, and, once the compiler is reaped, - // its processor time and largest resident set -- this process starts - // no other program, so its children's use is the compiler's. - mcpp::build::progress::record_action_start(output.generic_string()); - const auto unixMs = [] { - return std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); - }; - const auto started = unixMs(); - // THE UNIT CACHE (design 2026-11-20 §5.3): a compile whose command and - // read files hold the contents an earlier one's did is placed, not run. - std::optional units; - mcpp::build::unit_cache::Unit unit{command, std::filesystem::current_path(), object ? output : std::filesystem::path{}, bmi}; - if (const auto dir = mcpp::invocation::get(mcpp::build::unit_cache::kDirEnv); dir && !dir->empty() && object) { - std::vector roots; - std::istringstream in(mcpp::invocation::get(mcpp::build::unit_cache::kRootsEnv).value_or("")); - for (std::string line; std::getline(in, line);) - if (!line.empty()) roots.push_back(mcpp::home::from_utf8(line)); - units.emplace(mcpp::home::from_utf8(*dir), std::move(roots), unit.cwd); - if (units->serve(unit)) { - if (const auto file = mcpp::invocation::get(mcpp::build::record::kUsageEnv); file && !file->empty()) { - mcpp::build::record::Usage u{output.generic_string(), started, unixMs()}; - u.served = true; - (void)mcpplibs::os::fs::append(mcpp::home::from_utf8(*file), mcpp::build::record::usage_line(u)); - } - return 0; - } - } - const int status = mcpp::build::schedule::detach::run_capped(command, semaphore, cap, output, depfile, bmi, - object, relocate, reading); - if (status == 0 && units) units->keep(unit); - else if (object) mcpp::build::unit_cache::Cache::forget(unit); - if (const auto file = mcpp::invocation::get(mcpp::build::record::kUsageEnv); file && !file->empty()) { - mcpp::build::record::Usage u{output.generic_string(), started, unixMs()}; - if (const auto used = mcpplibs::os::process::resources(mcpplibs::os::process::of::children)) { - u.cpuMs = std::chrono::duration(used->user + used->system).count(); - u.peakBytes = used->peak_memory; - } - (void)mcpplibs::os::fs::append(mcpp::home::from_utf8(*file), mcpp::build::record::usage_line(u)); - } - return status; - } - - ReportUnnarrowablePaths reportUnnarrowable_; - - // What a build that waits for this one is told it waits for (mcpp#839): - // the command as typed, cut where a long argument list would bury it. - { - std::string command = "mcpp"; - for (int i = 1; i < argc && command.size() < 80; ++i) { - command += ' '; - command += argv[i]; - } - mcpp::build::dirlock::set_command(std::move(command)); - } - - // THE ONE SHAPE OF A WAIT (design 2026-11-27 §3.7 point 4). The first - // report names what is waited for, the lock file as given, the last - // recorded holder and whether that process is visible here, and how to - // bound the wait; each later report is one line. A holder that is not - // visible is not known to be gone: it may run in another process - // namespace, a container, or on a machine sharing the home. The machine - // stream gets the same facts as `waiting` events. - mcpp::home::set_wait_reporter([](const mcpp::home::WaitReport& r) { - const auto now = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); - const auto holder = mcpp::home::parse_holder(r.record); - const bool visible = mcpp::home::holder_visible(holder); - const auto who = mcpp::home::describe(holder, now); - if (r.first) { - mcpp::ui::status("Waiting", std::format("for {} ({})", r.resource, r.file.string())); - std::string more = std::format(" last recorded holder: {}{}\n", who, - holder.pid.empty() ? "" : visible ? ", a process visible here" : ", not a process visible here"); - if (!holder.pid.empty() && !visible) - more += std::format( - " it may run where this process cannot see it (another process namespace, a " - "container, or a machine sharing this home), or be a process that inherited the file; " - "`{}` lists the holders on this system\n", mcpp::home::holder_listing(r.file)); - more += " help: it ends when that process lets go; to stop waiting after a limit, " - "--lock-wait \n"; - mcpp::ui::block(more); - } else { - mcpp::ui::status("Waiting", std::format("{}s for {}, held by {}", - std::chrono::duration_cast(r.waited).count(), r.resource, who)); - } - mcpp::build::result::emit("waiting", { - {"holder", {{"pid", holder.pid}, {"command", holder.command}, {"client", holder.client}, - {"startedAt", holder.startedAt}}}, - {"waitedMs", r.waited.count()}, {"path", r.file.string()}, {"resource", r.resource}, - {"holderVisible", visible}}); - }); - - // ─── --home : this run's home (design 2026-10-26 §9.1, SPEC-010) ── - // Exactly MCPP_HOME for this process: the raw home of the two-step - // selection, so its locator is still followed. Taken out of argv before - // anything parses it. After `self init` the flag is that command's own -- - // the home to select persistently -- and stays; a global one naming a - // different directory beside it is a usage error, the same one naming the - // same directory is that command's flag written twice. - std::vector homeFiltered(argv, argv + argc); - { - std::optional global; - std::vector kept{homeFiltered.front()}; - std::vector words; - bool initArgs = false; - for (std::size_t i = 1; i < homeFiltered.size(); ++i) { - const std::string_view a = homeFiltered[i]; - if (a == "--") { kept.insert(kept.end(), homeFiltered.begin() + static_cast(i), homeFiltered.end()); break; } - if (!a.starts_with("-")) { - words.push_back(a); - initArgs = initArgs || (words.size() == 2 && words[0] == "self" && words[1] == "init"); - } - if (!initArgs && (a == "--home" || a.starts_with("--home="))) { - if (a == "--home") { - if (i + 1 >= homeFiltered.size()) { - mcpp::ui::error("--home needs a directory"); - return 2; - } - global = std::string(homeFiltered[++i]); - } else global = std::string(a.substr(7)); - continue; - } - kept.push_back(homeFiltered[i]); - } - if (global) { - std::error_code ec; - const auto absolute = std::filesystem::absolute(*global, ec).lexically_normal(); - for (std::size_t i = 1; initArgs && i < kept.size(); ++i) { - const std::string_view a = kept[i]; - std::string other; - if (a == "--home" && i + 1 < kept.size()) other = kept[i + 1]; - else if (a.starts_with("--home=")) other = std::string(a.substr(7)); - else continue; - if (std::filesystem::absolute(other, ec).lexically_normal() != absolute) { - mcpp::ui::error(std::format("--home names {} and `self init --home` names {}; give one of them", - absolute.string(), other)); - return 2; - } - } - mcpp::invocation::set("MCPP_HOME", absolute.string()); - homeFiltered = std::move(kept); - argc = static_cast(homeFiltered.size()); - argv = homeFiltered.data(); - } - } - - // A SELF-CONTAINED HOME IS STATED for the programs mcpp starts. It is - // derived from where this engine is (`/bin/mcpp`), and a build - // directory's graph runs the engine through its own link (2026-11-12 §17), - // from which the same home cannot be derived. - mcpp::home::state_portable_home(); - - // ─── --deny (design 2026-10-26 §5.5) ─────────────────────── - // Published as MCPP_DENY_EFFECTS, the union of what the caller's - // environment already denies and what the flag adds, for the reason - // --offline is an env var: the consumers sit in every subsystem. A name - // that is not a deniable effect is a usage error, before anything runs. - { - auto valid = [](std::string_view list) -> std::optional { - std::size_t pos = 0; - while (pos <= list.size()) { - auto comma = list.find(',', pos); - auto item = list.substr(pos, comma == std::string_view::npos ? std::string_view::npos : comma - pos); - while (!item.empty() && item.front() == ' ') item.remove_prefix(1); - while (!item.empty() && item.back() == ' ') item.remove_suffix(1); - const auto& names = mcpp::effects::deniable_effects(); - if (!item.empty() && std::ranges::find(names, item) == names.end()) - return std::string(item); - if (comma == std::string_view::npos) break; - pos = comma + 1; - } - return std::nullopt; - }; - std::string denied = mcpp::invocation::get("MCPP_DENY_EFFECTS").value_or(""); - for (int i = 1; i < argc; ++i) { - const std::string_view a = argv[i]; - if (a == "--") break; - std::string value; - if (a == "--deny") { - if (i + 1 >= argc) { mcpp::ui::error("--deny needs a list of effects"); return 2; } - value = argv[i + 1]; - } else if (a.starts_with("--deny=")) value = std::string(a.substr(7)); - else continue; - denied += (denied.empty() ? "" : ",") + value; - } - if (auto bad = valid(denied)) { - mcpp::ui::error(std::format( - "--deny / MCPP_DENY_EFFECTS: '{}' is not an effect that can be denied; expected " - "init-mcpp-home, write-project, write-global-cache, network, exec-build-script", *bad)); - return 2; - } - if (!denied.empty()) mcpp::invocation::set("MCPP_DENY_EFFECTS", denied); - } - - // ─── --lock-wait (design 2026-11-27 §3.7.2, D10) ─────────── - // The longest any wait of this command for a lock another process holds - // lasts; published as MCPP_LOCK_WAIT, which the provider's own lock reads - // as XLINGS_LOCK_TIMEOUT, so one limit governs every wait of the command. - // A value that is not a duration is a usage error before anything runs. - { - std::optional stated = mcpp::invocation::get("MCPP_LOCK_WAIT"); - bool fromFlag = false; - for (int i = 1; i < argc; ++i) { - const std::string_view a = argv[i]; - if (a == "--") break; - if (a == "--lock-wait") { - if (i + 1 >= argc) { mcpp::ui::error("--lock-wait needs a duration (30s, 2m, 1h, 0)"); return 2; } - stated = argv[i + 1]; - fromFlag = true; - } else if (a.starts_with("--lock-wait=")) { - stated = std::string(a.substr(12)); - fromFlag = true; - } - } - if (stated && !stated->empty()) { - const auto limit = mcpp::home::parse_wait(*stated); - if (!limit) { - mcpp::ui::error(std::format("{}: '{}' is not a duration; expected a number with s, m, h or " - "ms (30s, 2m, 1h, 500ms), or 0 for no wait", - fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT", *stated)); - return 2; - } - mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, limit, - fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT"); - mcpp::invocation::set("MCPP_LOCK_WAIT", *stated); - } - } - - // ─── --quiet / --no-color: pre-scan ───────────────────────────────── - // The cmdline lib propagates global options into nested subcommand - // ParsedArgs, but we set ui:: state up-front so that *every* line - // emitted from the action lambdas (including the very first - // "Resolving toolchain" banner) honours the user's intent. This is - // a side-channel only — the global options are still declared on - // the App below so they show up in --help and pass schema checks. - for (int i = 1; i < argc; ++i) { - std::string_view a = argv[i]; - // Everything after a bare `--` belongs to the program being run or the - // test binary being invoked, not to mcpp. Without this, `mcpp run -- -j 4` - // reads the child's flag as mcpp's own concurrency setting — `-j` is a - // common enough flag that this is a matter of when, not whether. - if (a == "--") break; - if (a == "--quiet" || a == "-q") mcpp::ui::set_quiet(true); - else if (a == "--no-color") mcpp::ui::disable_color(); - else if (a == "--verbose" || a == "-v") mcpp::log::set_verbose(true); - // --offline is published as the env var rather than plumbed through - // BuildOverrides: its consumers are index refresh, package install and - // toolchain auto-install, which sit in three subsystems and would each - // need a parameter threaded down. Same shape as MCPP_VERBOSE above, and - // it makes `MCPP_OFFLINE=1` and `--offline` literally the same switch. - else if (a == "--offline") mcpp::invocation::set("MCPP_OFFLINE", "1"); - // `--locked` rides the same side channel, and for the stronger form - // of the same reason: its consumer is the resolution write point deep - // in mcpp.build.prepare, and it applies to every command that resolves - // — build, run, test, flash, monitor, debug — so a per-subcommand - // option would have to be declared six times and threaded six times. - // - // It asserts rather than pins: the resolution that happens must equal - // the one mcpp.lock records, and a difference is reported naming the - // package that moved. See the check itself for why assertion is the - // half that reproducibility needs first. - else if (a == "--locked" || a == "--frozen") - mcpp::invocation::set("MCPP_LOCKED", "1"); - // `--managed-only` (mcpp#755) rides the same channel: its consumer is - // the decision record at the end of prepare, for every command that - // prepares, and the fast paths that would skip that record. - else if (a == "--managed-only") - mcpp::invocation::set("MCPP_MANAGED_ONLY", "1"); - // --jobs rides the same side channel as --offline, for the same reason - // recorded there: its consumer is deep in mcpp.build.execute and - // threading a parameter down would touch every caller in between. - // Accepts `--jobs N`, `--jobs=N`, `-j N` and `-jN`. - else if (a == "--jobs" || a == "-j") { - if (i + 1 < argc) mcpp::invocation::set("MCPP_JOBS", argv[++i]); - } - else if (a.starts_with("--jobs=")) mcpp::invocation::set("MCPP_JOBS", std::string(a.substr(7))); - // --toolchain rides the same channel, for the same reason: its consumer - // is deep inside prepare's resolution and threading a parameter down - // would touch every caller in between. - else if (a == "--toolchain") { - if (i + 1 < argc) mcpp::invocation::set("MCPP_TOOLCHAIN", argv[++i]); - } - else if (a.starts_with("--toolchain=")) mcpp::invocation::set("MCPP_TOOLCHAIN", std::string(a.substr(12))); - // --sysroot is `MCPP_SYSROOT` for this invocation (design 2026-10-23 - // §3.3), for the reason --toolchain is: its consumer is the base - // statement deep in prepare, and the fast paths read the variable to - // know a build's base changed. - else if (a == "--sysroot") { - if (i + 1 < argc) mcpp::invocation::set("MCPP_SYSROOT", argv[++i]); - } - else if (a.starts_with("--sysroot=")) mcpp::invocation::set("MCPP_SYSROOT", std::string(a.substr(10))); - // --platform and --host-platform are `MCPP_PLATFORM` and - // `MCPP_HOST_PLATFORM` for this invocation (SPEC-013 §3, §6.1), for - // the reason --sysroot is: the selection is made deep in prepare, and - // the fast paths read the variables to know the configuration moved. - else if (a == "--platform") { - if (i + 1 < argc) mcpp::invocation::set("MCPP_PLATFORM", argv[++i]); - } - else if (a.starts_with("--platform=")) mcpp::invocation::set("MCPP_PLATFORM", std::string(a.substr(11))); - else if (a == "--host-platform") { - if (i + 1 < argc) mcpp::invocation::set("MCPP_HOST_PLATFORM", argv[++i]); - } - else if (a.starts_with("--host-platform=")) - mcpp::invocation::set("MCPP_HOST_PLATFORM", std::string(a.substr(16))); - else if (a.starts_with("-j") && a.size() > 2) - mcpp::invocation::set("MCPP_JOBS", std::string(a.substr(2))); - // --play-game rides the same channel: its value is optional - // (`--play-game` chooses a game, `--play-game=snake` names one), which - // the parser's options do not express, and its consumer is the build's - // report deep in mcpp.build.progress (build output design revision 3, - // §5.14). The option is also declared on build, run and test below, so - // that --help lists it and the parser accepts both spellings. - else if (a == "--play-game") mcpp::invocation::set("MCPP_PLAY_GAME", "random"); - else if (a.starts_with("--play-game=")) - mcpp::invocation::set("MCPP_PLAY_GAME", std::string(a.substr(12))); - } - // `--system` (design 2026-10-16 §9.2): the maintenance commands act on - // the machine's system home, whatever the caller's HOME and MCPP_HOME - // say. Building as root would write root's files into a user's project, - // so no other command takes it. - if (std::ranges::any_of(std::span(argv + 1, argv + argc), [](const char* a) { return std::string_view(a) == "--system"; })) { - if (std::ranges::any_of(std::span(argv + 1, argv + argc), [](const char* a) { - const std::string_view arg{a}; - return arg == "--home" || arg.starts_with("--home="); - })) { - mcpp::ui::error("--home cannot be combined with --system"); - return 2; - } - if (int rc = enter_system_home(argc, argv); rc != 0) return rc; - } - // Decline xlings' linker-wrapper path injection, for this process and - // everything it spawns (openxlings/xlings#540). - // - // That wrapper appends `-rpath "$XLINGS_SUBOS_LIB"` to every link it sees. - // mcpp wants the TAG half of what it does and must refuse the PATH half: - // `$XLINGS_SUBOS_LIB` names the ACTIVE SHELL's SubOS, which is measurably - // not the one mcpp resolved — mcpp keeps its own xlings home under - // `/registry`, so on an ordinary developer machine the variable - // points at a different farm backed by a DIFFERENT PHYSICAL glibc payload. - // Inheriting it would put a second libc on the artifact's search path, - // which is the one thing rule B exists to prevent. mcpp emits its own farm - // entry, derived from the binding it actually selected. - // - // Set here rather than per link command: the link line has a hard 128KiB - // ceiling that real workspaces already spend 43% of, and children inherit - // the environment for free. Declared BEFORE the wrapper ships, because - // "the exit must be declared, not inferred" is the rule that whole - // negotiation established — today this is a no-op. - mcpp::invocation::set( - std::string(mcpp::runtime::search::kLinkerPathInjectionOptOut), - std::string(mcpp::runtime::search::kLinkerPathInjectionOptOutValue)); - - // Env override (observability, esp. CI): MCPP_VERBOSE= - // turns on verbose logging for EVERY mcpp invocation — including the ones - // nested inside e2e test scripts that call $MCPP without flags. Lets a - // workflow flip on diagnostics globally with one env var. An explicit - // --quiet still wins (it is processed above and gates the verbose sinks). - if (auto v = mcpp::invocation::get("MCPP_VERBOSE"); v && *v != "0") - mcpp::log::set_verbose(true); - - // ─── top-level --help / -h / --version intercept ──────────────────── - // cmdline auto-handles these but its formatter doesn't match the - // mixed-case "Usage:" + per-command blurbs that documentation + - // e2e tests pin. Print our canonical screen and `mcpp X.Y.Z` - // version line up-front so the App never sees these tokens. - if (argc >= 2) { - std::string_view a = argv[1]; - if (a == "--help" || a == "-h") { print_usage(); return 0; } - if (a == "pack") - for (int i = 2; i < argc; ++i) - if (std::string_view h = argv[i]; h == "--help" || h == "-h") { - print_pack_usage(); - return 0; - } else if (h == "--") { - break; - } - if (a == "--version" || a == "-V") { - std::println("mcpp {}", mcpp::toolchain::MCPP_VERSION); - return 0; - } - } - - // Every action returns its status, and `App::run` dispatches to the - // deepest named command at any depth (mcpplibs.cmdline 0.0.4): a parent - // such as `cache` or `self` carries no dispatch table of its own. - - // ─── `--` passthrough for `mcpp run` / `mcpp test` ────────────────── - // cmdline natively recognises `--` and dumps everything after it - // into `parsed.positionals` (with the bare `--` token dropped). For - // `mcpp run [target] -- args...` we need to distinguish the - // optional `target` (a real positional) from the passthrough - // tokens (which must reach the executed binary verbatim, even when - // they look like `-x` / `--foo`). We split ourselves at the first - // `--` and present cmdline only the pre-`--` slice; post-args go - // into `passthrough` and are handed to the action helper directly. - std::vector passthrough; - std::vector trimmed_argv(argv, argv + argc); - { - for (std::size_t i = 1; i < trimmed_argv.size(); ++i) { - if (std::string_view(trimmed_argv[i]) != "--") continue; - for (std::size_t j = i + 1; j < trimmed_argv.size(); ++j) - passthrough.emplace_back(trimmed_argv[j]); - trimmed_argv.resize(i); // drop `--` and everything after - break; - } - } - int trimmed_argc = static_cast(trimmed_argv.size()); - char** trimmed_argp = trimmed_argv.empty() ? nullptr : trimmed_argv.data(); - - // ─── Build the top-level App ──────────────────────────────────────── - // `emit surface` lists the definition it is part of; it is set once the definition exists. - const cl::App* self = nullptr; - auto app = cl::App("mcpp") - .version(std::string{mcpp::toolchain::MCPP_VERSION}) - .description("modern C++ build tool") - // Completion is the library's (design 2026-11-27 §4.11): `mcpp - // __complete ` answers from this tree, and `mcpp self - // completion` writes the adapter a shell reads. - .completion({.command = ""}) - .option(cl::Option("quiet").short_name('q') - .help("Suppress status output").global()) - .option(cl::Option("verbose").short_name('v') - .help("Show detailed progress on stderr").global()) - .option(cl::Option("no-color") - .help("Disable colored output").global()) - .option(cl::Option("offline") - .help("Never touch the network (index refresh, downloads, toolchain install); = --deny network") - .global()) - .option(cl::Option("deny").takes_value().value_name("EFFECTS") - .help("Stop before any of these effects, exit 5: network, write-project, write-global-cache, exec-build-script, init-mcpp-home (also: MCPP_DENY_EFFECTS)") - .global()) - .option(cl::Option("system") - .help("Maintain the machine's system home (self init|doctor|store, toolchain install|remove|default, index update)") - .global()) - // Declared here as well as read in the pre-pass: the pre-pass sets the - // env var, and this makes the parser accept the token instead of - // rejecting it as unknown. Both halves are needed, which is exactly the - // arrangement `--offline` above already has. - .option(cl::Option("locked") - .help("Fail if dependency resolution differs from mcpp.lock") - .global()) - .option(cl::Option("frozen") - .help("Alias for --locked") - .global()) - .option(cl::Option("managed-only") - .help("Fail if a toolchain, payload or plugin tool does not come from the ecosystem") - .global()) - .option(cl::Option("lock-wait").takes_value().value_name("DURATION") - .help("Wait at most this long for a lock another mcpp holds, then refuse (30s, 2m, 0; also: MCPP_LOCK_WAIT)") - .global()) - - // Answers "what do you speak" without spawning a command that might - // fail. An optimisation, NOT the client's detection rule: on any mcpp - // predating it this is itself an unknown option, so a client must - // still detect the protocol by parsing stdout for schemaVersion+kind. - .option(cl::Option("protocol-version") - .help("Print the machine-output protocol this build speaks (JSON)")) + // Answers "what do you speak" without spawning a command that might + // fail. An optimisation, NOT the client's detection rule: on any mcpp + // predating it this is itself an unknown option, so a client must + // still detect the protocol by parsing stdout for schemaVersion+kind. + .option(cl::Option("protocol-version") + .help("Print the machine-output protocol this build speaks (JSON)")) // ─── project commands ────────────────────────────────────────── - .subcommand(cl::App("new") + .subcommand(cl::App("new").group("PROJECT COMMANDS") .description("Create a new mcpp package skeleton") // not .required(): `--list-templates` runs without a name // (cmd_new validates presence for project creation itself). @@ -804,7 +346,7 @@ int run(int argc, char** argv) { .option(cl::Option("vcs").takes_value().value_name("VCS") .help("git (default) | none: a repository for the new project; inside another project or repository, only when stated (config.toml [new] vcs)")) .action(cmd_new)) - .subcommand(cl::App("build") + .subcommand(cl::App("build").group("PROJECT COMMANDS") .description("Build the current package") .option(cl::Option("configure-only") .help("Generate compile_commands.json without compiling or linking")) @@ -858,7 +400,7 @@ int run(int argc, char** argv) { if (rc == 0) mcpp::build::sweep_after_build(); return rc; })) - .subcommand(cl::App("fetch") + .subcommand(cl::App("fetch").group("PROJECT COMMANDS") .description("Put what the package's build needs in the home; write it to a directory, or take it from one") .option(cl::Option("to").takes_value().value_name("DIR") .help("Then write what the build uses (payloads, index snapshots, git clones) into DIR")) @@ -883,7 +425,7 @@ int run(int argc, char** argv) { .option(cl::Option("features").takes_value().value_name("LIST") .help("Activate root-package features, and a dependency's as /")) .action(cmd_fetch)) - .subcommand(cl::App("run") + .subcommand(cl::App("run").group("PROJECT COMMANDS") .description("Build + run a binary target (after `--`, args are passed to it)") // Named `bin`, NOT `target`, and the rename is load-bearing. // @@ -1000,7 +542,7 @@ int run(int argc, char** argv) { .action([&passthrough](const cl::ParsedArgs& p) { return cmd_run(p, std::span(passthrough)); })) - .subcommand(cl::App("test") + .subcommand(cl::App("test").group("PROJECT COMMANDS") .description("Build + run all tests/**/*.cpp (after `--`, args go to each test binary)") .arg(cl::Arg("pattern") .help("Run only tests whose name contains a PATTERN; several select every test one of them names (optional)")) @@ -1084,7 +626,7 @@ int run(int argc, char** argv) { if (rc == 0) mcpp::build::sweep_after_build(); return rc; })) - .subcommand(cl::App("clean") + .subcommand(cl::App("clean").group("PROJECT COMMANDS") .description("Remove target/, or with --stale only what no configuration still uses: fingerprint directories, generated sources, build-program groups") .option(cl::Option("bmi-cache").help("Also wipe the global build cache (see `mcpp cache clean`)")) .option(cl::Option("stale").help("Only remove target/// directories that no recorded build considers current")) @@ -1093,7 +635,7 @@ int run(int argc, char** argv) { .option(cl::Option("older-than").takes_value().value_name("DURATION") .help("Keep unrecorded directories written more recently than this, e.g. 12h, 3d (default [build] keep_days, 3d; 0 keeps none; implies --stale)")) .action(cmd_clean)) - .subcommand(cl::App("why") + .subcommand(cl::App("why").group("PROJECT COMMANDS") .description("Explain how the target / toolchain / runtime / deps / runners / sources / flags were resolved") .arg(cl::Arg("topic").help("target | toolchain | sysroot | runtime | deps | runners | sources | tool | payload | build-programs | compat | flags | platform | features (default: all but flags, platform and features)")) .arg(cl::Arg("subject").help("for `tool` and `payload`: the name to look up; for `flags`: the unit, by the end of its path")) @@ -1116,11 +658,11 @@ int run(int argc, char** argv) { .option(cl::Option("format").takes_value().value_name("json") .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) .action(cmd_why)) - .subcommand(cl::App("resolve") + .subcommand(cl::App("resolve").group("PROJECT COMMANDS") .description("Re-resolve the build plan and explain it") .option(cl::Option("explain").help("Print resolved toolchain / runtime / deps / runners")) .action(cmd_why)) - .subcommand(cl::App("add") + .subcommand(cl::App("add").group("PROJECT COMMANDS") .description("Add a dependency to mcpp.toml") .arg(cl::Arg("pkg").help( "Exact package spec, e.g. foo@1.0.0 or compat.gtest@1.15.2") @@ -1130,18 +672,18 @@ int run(int argc, char** argv) { .option(cl::Option("build").help( "Add to [build-dependencies] (a build plugin or a tool the build runs)")) .action(mcpp::pm::commands::cmd_add)) - .subcommand(cl::App("remove") + .subcommand(cl::App("remove").group("PROJECT COMMANDS") .description("Remove a dependency from mcpp.toml") .arg(cl::Arg("pkg").help("Exact package selector [ns.]name").required() .complete(mcpp::cli::complete::dependencies)) .option(cl::Option("dev").help("Remove from [dev-dependencies]")) .option(cl::Option("build").help("Remove from [build-dependencies]")) .action(mcpp::pm::commands::cmd_remove)) - .subcommand(cl::App("update") + .subcommand(cl::App("update").group("PROJECT COMMANDS") .description("Re-resolve dependencies and rewrite mcpp.lock") .arg(cl::Arg("pkg").help("If given, update only that package")) .action(mcpp::pm::commands::cmd_update)) - .subcommand(cl::App("search") + .subcommand(cl::App("search").group("PROJECT COMMANDS") .description("Search packages in configured registries") .arg(cl::Arg("keyword").help("Search keyword (substring match); optional with --format json, which then lists every package")) .option(cl::Option("all-versions") @@ -1149,7 +691,7 @@ int run(int argc, char** argv) { .option(cl::Option("format").takes_value().value_name("FMT") .help("json: the mcpp.search envelope (every version, licenses, repo)")) .action(cmd_search)) - .subcommand(cl::App("publish") + .subcommand(cl::App("publish").group("PROJECT COMMANDS") .description("Publish package to default registry") .option(cl::Option("dry-run").help("Print xpkg.lua without uploading")) .option(cl::Option("allow-dirty").help("Allow uncommitted changes")) @@ -1162,7 +704,7 @@ int run(int argc, char** argv) { .option(cl::Option("exclude").takes_value().multiple().value_name("NAME") .help("With --workspace: leave the named member out; repeatable")) .action(cmd_publish)) - .subcommand(cl::App("pack") + .subcommand(cl::App("pack").group("PROJECT COMMANDS") // "archive", not "tarball": a Windows target produces a .zip, and // the help said tarball while the code had already stopped // agreeing. `--format tar` likewise selects "an archive rather @@ -1253,430 +795,914 @@ int run(int argc, char** argv) { .help("Write the separated *.debug files here (default: discard)")) .action(cmd_pack)) - // ─── emit (one nested subcommand: xpkg) ──────────────────────── - .subcommand(cl::App("emit") - .description("Generate a document describing this project (xpkg, sbom, build-database) or mcpp (surface)") - .subcommand(cl::App("xpkg") - .description("Generate xpkg Lua entry") - .option(cl::Option("version").short_name('V').takes_value().value_name("VER") - .help("Override package version")) - .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") - .help("Write to file instead of stdout")) - .option(cl::Option("namespace").takes_value().value_name("NS") - .help("Package namespace for the emitted descriptor " - "(overrides [package] namespace). Emits both " - "`namespace` and the fully-qualified `name`")) - .option(cl::Option("package").takes_value().multiple().value_name("ARCHIVE") - .help("Describe packages `mcpp pack` wrote (repeatable): an xim-pkgindex entry " - "of the program, from their mcpp-package.json")) - .option(cl::Option("url").takes_value().value_name("PREFIX") - .help("With --package: where the packages are published (/)")) - .action(cmd_emit_xpkg)) - // `sbom` belongs HERE rather than at the top level: `emit` - // already means "generate a document describing this project" and - // already carries `-o`. A separate `mcpp sbom` would be a second - // spelling of an abstraction that exists. - .subcommand(cl::App("sbom") - .description("Write a CycloneDX bill of materials for the recorded resolution") - .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") - .help("Write to file instead of stdout")) - .action(mcpp::cli::cmd_sbom)) - // The plan as an S1 build database, planned as `build - // --configure-only` plans it and written into nothing; the build - // selectors are `build`'s own (docs/specs/build-database.md). - .subcommand(cl::App("build-database") - .description("Print the build plan as an S1 build database, without writing into the project") - .option(cl::Option("spec").takes_value().value_name("NAME") - .help("Document specification: s1 (default; the S1 IDE profile of P2977R2) | compile-commands")) - .option(cl::Option("format").takes_value().value_name("json") - .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) - .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") - .help("Write to file instead of stdout")) - .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().value_name("TRIPLE") - .help("Describe the build for (same axis as `mcpp build --target`)")) - .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") - .help("Describe the build with this toolchain, e.g. llvm@22.1.8")) - .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") - .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) - .option(cl::Option("platform").takes_value().value_name("SPEC") - .help("The target's platform for this invocation (= MCPP_PLATFORM): @, path:, none")) - .option(cl::Option("host-platform").takes_value().value_name("SPEC") - .help("The host graph's platform for this invocation (= MCPP_HOST_PLATFORM)")) - .option(cl::Option("accel").takes_value().value_name("SPEC") - .help("Device backends and architectures (same axis as `mcpp build --accel`)")) - .option(cl::Option("no-accel") - .help("Describe the variant built for no accelerator")) - .option(cl::Option("static").help("Describe the build with --static")) - .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") - .help("Describe the named workspace member (namespace.name or package name, then directory); repeat to describe several")) - .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") - .help("Build profile: dev (default) | release | dist | <[profile.*] name>")) - .option(cl::Option("release").help("Shorthand for --profile release")) - .option(cl::Option("dev").help("Shorthand for --profile dev")) - .option(cl::Option("features").takes_value().value_name("LIST") - .help("Activate root-package features, and a dependency's as / (comma-separated)")) - .option(cl::Option("cap").takes_value().value_name("LIST") - .help("Pin capability providers (e.g. blas=openblas,lapack=mkl)")) - .option(cl::Option("strict") - .help("Treat manifest schema warnings (unknown feature/platform) as errors")) - .option(cl::Option("workspace") - .help("Describe all workspace members in one document")) - .option(cl::Option("exclude").takes_value().multiple().value_name("NAME") - .help("With --workspace (or at a virtual workspace root), leave the named member out; repeatable, refused with -p")) - .action(mcpp::cli::cmd_emit_build_database)) - // The surface is the product's, not a project's; it is a document mcpp writes about - // itself, and `emit` already means "write a document" (design 2026-11-20 §5.16). - .subcommand(cl::App("surface") - .description("List mcpp's commands, flags, manifest keys and reason tokens, one per line") - .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") - .help("Write to file instead of stdout")) - .action([&self](const cl::ParsedArgs& p) { return mcpp::cli::cmd_emit_surface(*self, p); }))) + // ─── emit (one nested subcommand: xpkg) ──────────────────────── + .subcommand(cl::App("emit").group("PROJECT COMMANDS") + .description("Generate a document describing this project (xpkg, sbom, build-database) or mcpp (surface)") + .subcommand(cl::App("xpkg") + .description("Generate xpkg Lua entry") + .option(cl::Option("version").short_name('V').takes_value().value_name("VER") + .help("Override package version")) + .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") + .help("Write to file instead of stdout")) + .option(cl::Option("namespace").takes_value().value_name("NS") + .help("Package namespace for the emitted descriptor " + "(overrides [package] namespace). Emits both " + "`namespace` and the fully-qualified `name`")) + .option(cl::Option("package").takes_value().multiple().value_name("ARCHIVE") + .help("Describe packages `mcpp pack` wrote (repeatable): an xim-pkgindex entry " + "of the program, from their mcpp-package.json")) + .option(cl::Option("url").takes_value().value_name("PREFIX") + .help("With --package: where the packages are published (/)")) + .action(cmd_emit_xpkg)) + // `sbom` belongs HERE rather than at the top level: `emit` + // already means "generate a document describing this project" and + // already carries `-o`. A separate `mcpp sbom` would be a second + // spelling of an abstraction that exists. + .subcommand(cl::App("sbom") + .description("Write a CycloneDX bill of materials for the recorded resolution") + .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") + .help("Write to file instead of stdout")) + .action(mcpp::cli::cmd_sbom)) + // The plan as an S1 build database, planned as `build + // --configure-only` plans it and written into nothing; the build + // selectors are `build`'s own (docs/specs/build-database.md). + .subcommand(cl::App("build-database") + .description("Print the build plan as an S1 build database, without writing into the project") + .option(cl::Option("spec").takes_value().value_name("NAME") + .help("Document specification: s1 (default; the S1 IDE profile of P2977R2) | compile-commands")) + .option(cl::Option("format").takes_value().value_name("json") + .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) + .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") + .help("Write to file instead of stdout")) + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().value_name("TRIPLE") + .help("Describe the build for (same axis as `mcpp build --target`)")) + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") + .help("Describe the build with this toolchain, e.g. llvm@22.1.8")) + .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") + .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) + .option(cl::Option("platform").takes_value().value_name("SPEC") + .help("The target's platform for this invocation (= MCPP_PLATFORM): @, path:, none")) + .option(cl::Option("host-platform").takes_value().value_name("SPEC") + .help("The host graph's platform for this invocation (= MCPP_HOST_PLATFORM)")) + .option(cl::Option("accel").takes_value().value_name("SPEC") + .help("Device backends and architectures (same axis as `mcpp build --accel`)")) + .option(cl::Option("no-accel") + .help("Describe the variant built for no accelerator")) + .option(cl::Option("static").help("Describe the build with --static")) + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") + .help("Describe the named workspace member (namespace.name or package name, then directory); repeat to describe several")) + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") + .help("Build profile: dev (default) | release | dist | <[profile.*] name>")) + .option(cl::Option("release").help("Shorthand for --profile release")) + .option(cl::Option("dev").help("Shorthand for --profile dev")) + .option(cl::Option("features").takes_value().value_name("LIST") + .help("Activate root-package features, and a dependency's as / (comma-separated)")) + .option(cl::Option("cap").takes_value().value_name("LIST") + .help("Pin capability providers (e.g. blas=openblas,lapack=mkl)")) + .option(cl::Option("strict") + .help("Treat manifest schema warnings (unknown feature/platform) as errors")) + .option(cl::Option("workspace") + .help("Describe all workspace members in one document")) + .option(cl::Option("exclude").takes_value().multiple().value_name("NAME") + .help("With --workspace (or at a virtual workspace root), leave the named member out; repeatable, refused with -p")) + .action(mcpp::cli::cmd_emit_build_database)) + // The surface is the product's, not a project's; it is a document mcpp writes about + // itself, and `emit` already means "write a document" (design 2026-11-20 §5.16). + .subcommand(cl::App("surface") + .description("List mcpp's commands, flags, manifest keys and reason tokens, one per line") + .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") + .help("Write to file instead of stdout")) + .action([&self](const cl::ParsedArgs& p) { return mcpp::cli::cmd_emit_surface(*self, p); }))) + + // ─── xpkg (descriptor tooling: parse) ────────────────────────── + .subcommand(cl::App("xpkg").group("PROJECT COMMANDS") + .description("Inspect / validate xpkg descriptors") + .subcommand(cl::App("parse") + .description("Parse a descriptor's mcpp segment exactly as the resolver would (strict: unknown keys are errors)") + .option(cl::Option("json") + .help("Emit machine-readable JSON (legacy payload, kept for ever)")) + .option(cl::Option("format").takes_value().value_name("json") + .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) + .option(cl::Option("allow-unknown") + .help("Downgrade unknown mcpp-segment keys from error to warning")) + .option(cl::Option("all-os") + .help("Validate every per-OS section (linux/macosx/windows), " + "not just the running host's")) + .option(cl::Option("allow-split-name") + .help("OBSOLETE (kept accepted so 0.0.105-era index CI keeps " + "working): skip the package.name form check. Since " + "0.0.106 the canonical form IS the short name, so " + "xlings-native descriptors pass without this flag")) + .action(cmd_xpkg_parse))) + + // ─── resource management ─────────────────────────────────────── + .subcommand(cl::App("toolchain").group("RESOURCE MANAGEMENT") + .description("Install / list / select / remove C++ toolchains") + .subcommand(cl::App("list").description("List installed toolchains") + .option(cl::Option("format").takes_value().value_name("json") + .help("Machine-readable output (enveloped; see docs/50-machine-output.md)"))) + .subcommand(cl::App("install") + .description("Install a toolchain via mcpp's xlings") + // Both `mcpp toolchain install gcc 16.1.0` and `mcpp toolchain + // install gcc@16.1.0` are accepted, and the version may be + // partial (`15`, `15.1`) — mcpp resolves to the highest match. + // With --target the family may be omitted entirely (taken from + // the target's convention pin): + // mcpp toolchain install --target x86_64-windows-gnu + .arg(cl::Arg("compiler").help("gcc | llvm | msvc | emsdk | android-ndk (or gcc@16.1.0; legacy aliases accepted)")) + .arg(cl::Arg("version").help("e.g. 16.1.0, 15, 15.1")) + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( + "Install the toolchain payload for (e.g. x86_64-windows-gnu)")) + .option(cl::Option("platform").takes_value().value_name("SPEC") + .help("With --target: the target's platform for this invocation (= MCPP_PLATFORM)"))) + .subcommand(cl::App("default") + .description("Set the default toolchain (and optionally the default target)") + // Same dual-form as `install`: `gcc@16.1.0` or `gcc 16.1.0`, + // partial versions allowed. + .arg(cl::Arg("spec").help("[@] (version may be partial)").required()) + .arg(cl::Arg("version").help("(optional, alternative to @-form)")) + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( + "Default build target (omit = host)"))) + .subcommand(cl::App("remove") + .description("Uninstall a toolchain") + // Same dual-form as `default`: `gcc@16.1.0` or `gcc 16.1.0`. + // NOT partial versions: `default` resolves `gcc 15` to the + // highest installed 15.x.y, but a removal must name the one + // payload it deletes, so the version here is exact. + .arg(cl::Arg("spec") + .help("[@] (exact version)") + .required()) + .arg(cl::Arg("version").help("(optional, alternative to @-form)")) + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( + "Remove the payload for instead of the host one"))) + .action(cmd_toolchain_any)) + .subcommand(cl::App("cache").group("RESOURCE MANAGEMENT") + .description("Inspect and manage the global build cache") + .subcommand(cl::App("dir") + .description("Print the cache root (and any pre-v1 cache)") + .action(cmd_cache_dir)) + .subcommand(cl::App("list") + .description("List cache entries with size + last-use") + .option(cl::Option("json") + .help("Emit machine-readable JSON (legacy payload, kept for ever)")) + .option(cl::Option("format").takes_value().value_name("json") + .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) + .action(cmd_cache_list)) + .subcommand(cl::App("info") + .description("Show details (incl. key inputs) for a cached package") + .arg(cl::Arg("pkg").help("@").required()) + .action(cmd_cache_info)) + .subcommand(cl::App("prune") + .description("Drop entries not used within a threshold") + .option(cl::Option("older-than").takes_value().value_name("N{s|m|h|d}") + .help("Age threshold (e.g. 30d)")) + .action(cmd_cache_prune)) + .subcommand(cl::App("gc") + .description("LRU-collect package and host tool entries to a size and/or age budget") + .option(cl::Option("max-size").takes_value().value_name("N{MiB|GiB}") + .help("Keep the package cache under this size (e.g. 5GiB)")) + .option(cl::Option("older-than").takes_value().value_name("N{s|m|h|d}") + .help("Also drop entries, and the store's roots, unused for longer than this")) + .option(cl::Option("dry-run") + .help("Say what would be collected, and remove nothing")) + .action(cmd_cache_gc)) + .subcommand(cl::App("clean") + .description("Drop cache entries (default: package entries only)") + .option(cl::Option("deps").help("Drop package entries (default)")) + .option(cl::Option("std").help("Drop std module entries")) + .option(cl::Option("tools").help("Drop host tool entries")) + .option(cl::Option("all").help("Drop every kind of entry")) + .option(cl::Option("legacy") + .help("Remove the unused pre-v1 cache at $MCPP_HOME/bmi")) + .action(cmd_cache_clean)) + .subcommand(cl::App("verify") + .description("Check every entry's manifest against the files on disk") + .action(cmd_cache_verify))) + .subcommand(cl::App("index").group("RESOURCE MANAGEMENT") + .description("Manage configured package registries") + .subcommand(cl::App("list") + .description("List configured registries") + .option(cl::Option("format").takes_value().value_name("FMT") + .help("json: the mcpp.index envelope")) + .action(cmd_index_list)) + .subcommand(cl::App("add") + .description("Add a custom registry") + .arg(cl::Arg("name").help("Registry name").required()) + .arg(cl::Arg("url").help("Registry URL").required()) + .action(cmd_index_add)) + .subcommand(cl::App("remove") + .description("Remove a registry") + .arg(cl::Arg("name").help("Registry name").required()) + .action(cmd_index_remove)) + .subcommand(cl::App("update") + // #540: the argument selects among the PROJECT's custom + // indices only. The global repos are always synced wholesale, + // because `xlings update` has no per-index mode to call — a + // limitation index_management.cppm has recorded as a follow-up + // since it was written, in a comment no one typing the command + // can read. Saying it here is not the fix; it is the honest + // description until the upstream mode exists. + .description("Refresh local registry clones " + "(global repos always sync in full)") + .arg(cl::Arg("name").help( + "Update only this PROJECT-level custom index " + "(the global repos sync regardless)")) + .action(cmd_index_update)) + .subcommand(cl::App("status") + .description("Show local index presence/freshness (offline)") + .action(cmd_index_status)) + .subcommand(cl::App("pin") + .description("Pin a custom index to a commit rev in mcpp.toml") + .arg(cl::Arg("name").help("Index name").required()) + .arg(cl::Arg("rev").help("Commit sha (defaults to current lock rev)")) + .action(cmd_index_pin)) + .subcommand(cl::App("unpin") + .description("Remove rev pin from a custom index in mcpp.toml") + .arg(cl::Arg("name").help("Index name").required()) + .action(cmd_index_unpin))) + + // ─── about mcpp itself ───────────────────────────────────────── + .subcommand(cl::App("self").group("ABOUT MCPP ITSELF") + .description("Inspect and manage mcpp itself") + .subcommand(cl::App("init") + .description("Initialize or repair mcpp sandbox") + .option(cl::Option("home").takes_value().value_name("PATH") + .help("Initialize PATH and remember it from the original home (does not migrate data)")) + .option(cl::Option("force") + .help("Rebuild registry/caches; with --home, replace the default without deleting data")) + .action(cmd_self_init)) + .subcommand(cl::App("doctor") + .description("Diagnose mcpp environment health") + .action(cmd_doctor)) + .subcommand(cl::App("env") + .description("Print mcpp paths and configuration; with --target, one configuration: toolchain, platform, tools, runner") + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().value_name("TRIPLE") + .help("Report this target's configuration (prepared, not built; the project's when run in one); " + "a target set or several reports each leg")) + .option(cl::Option("host") + .help("Report the host graph's configuration: what build programs and tools are built for")) + .option(cl::Option("platform").takes_value().value_name("SPEC") + .help("The target's platform for this invocation (= MCPP_PLATFORM): @, path:, none")) + .option(cl::Option("host-platform").takes_value().value_name("SPEC") + .help("The host graph's platform for this invocation (= MCPP_HOST_PLATFORM)")) + .option(cl::Option("format").takes_value().value_name("json") + .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) + .action(cmd_env_any)) + .subcommand(cl::App("config") + .description("Show or modify mcpp's configuration: the xlings mirror and the retention of build outputs") + .option(cl::Option("mirror").takes_value().value_name("auto|CN|GLOBAL") + .help("Set xlings mirror for mcpp's private registry")) + .option(cl::Option("cache-unused-days").takes_value().value_name("DAYS") + .help("Collect build-cache entries no build used for DAYS days (default 30; 0 keeps all)")) + .option(cl::Option("keep-days").takes_value().value_name("DAYS") + .help("Sweep a project's build directories no configuration used for DAYS days (default 3; 0 keeps all)")) + .action(cmd_self_config)) + .subcommand(cl::App("version") + .description("Show mcpp version") + .action(cmd_self_version)) + .subcommand(cl::App("completion") + .description("Write the completion script of a shell into the home and say how to load it") + .arg(cl::Arg("shell").values({"bash", "zsh", "fish", "powershell"}) + .help("bash, zsh, fish or powershell; the shell $SHELL names when absent")) + .option(cl::Option("print").help("Print the script instead of writing it")) + .action(cmd_self_completion)) + .subcommand(cl::App("explain") + .description("Explain a code and its remedy: an E code, an MCPP_* diagnostic code or a reason token") + .arg(cl::Arg("code").help("An E code (E0001), the MCPP_* code of a JSON diagnostic, or a refusal's reason token (layer-cycle)").required()) + .action(cmd_explain_action)) + .subcommand(cl::App("store") + .description("Compare this home's payloads with its upstreams") + .subcommand(cl::App("dedupe") + .description("List payloads an upstream has the same of; --apply links them") + .option(cl::Option("apply").help("Replace each by a link to the upstream's"))) + .action(cmd_self_store))) + + // ─── top-level explain alias ────────────────────────────────── + // Preserves `mcpp explain E0001` as a shortcut for + // `mcpp self explain E0001`. + .subcommand(cl::App("explain").group("ABOUT MCPP ITSELF") + .description("Explain a code and its remedy: an E code, an MCPP_* diagnostic code or a reason token") + .arg(cl::Arg("code").help("An E code (E0001), the MCPP_* code of a JSON diagnostic, or a refusal's reason token (layer-cycle)").required()) + .action(cmd_explain_action)) + + // ─── bareword `version` alias ───────────────────────────────── + // cmdline natively handles `--help`/`--version`/`-h`; the bareword + // `mcpp help` is intercepted by the pre-scan above (prints the + // canonical usage screen). `mcpp version` is wired through the + // App so it shows up in the auto-generated subcommand list. + .subcommand(cl::App("version").group("ABOUT MCPP ITSELF") + .description("Show mcpp version") + .action(cmd_self_version)) + + // ─── hidden / internal ───────────────────────────────────────── + .subcommand(cl::App("dyndep").hidden() + .description("(internal: invoked by ninja) Emit ninja dyndep file from .ddi inputs") + .option(cl::Option("output").short_name('o').takes_value().value_name("PATH") + .help("Path to write dyndep file")) + .option(cl::Option("single").help("Single-file mode: one .ddi → one .dd")) + .option(cl::Option("bmi-dir").takes_value().value_name("DIR") + .help("BMI cache directory name (default: gcm.cache)")) + .option(cl::Option("bmi-ext").takes_value().value_name("EXT") + .help("BMI file extension (default: .gcm)")) + .option(cl::Option("module-map").takes_value().value_name("FILE") + .help("Module name -> BMI path, one ` ` per line (mcpp#732)")) + .option(cl::Option("split-module") + .help("Also emit a record for the provided BMI (two-phase " + "schedule: BMI and object are separate edges)")) + .option(cl::Option("expect-provides").takes_value().value_name("NAME") + .help("(verification) planned provided module for this TU")) + .option(cl::Option("expect-imports").takes_value().value_name("CSV") + .help("(verification) planned imports for this TU, comma-separated")) + .option(cl::Option("expect-none") + .help("(verification) planner assumed no provides/imports")) + .action(cmd_dyndep)) + // Named by generated build.ninja edges and, since 2026.9.13.1, by a + // build program's own actions through `${mcpp.self}` (docs/30), so + // the argument shape below is a contract: `stage --verify content + // --output ` copies one file, creates the destination's + // parent, and writes only when the bytes differ. + .subcommand(cl::App("stage").group("TOOLS FOR ACTIONS") + .description("Copy one file into place: create the destination's parent, write only when the content differs (invoked by build.ninja and by ${mcpp.self} actions)") + .option(cl::Option("output").short_name('o').takes_value().value_name("PATH") + .help("Destination path; its parent directory is created")) + .option(cl::Option("verify").takes_value().value_name("MODE") + .help("How an existing destination is judged up to date: content (default) | size")) + .option(cl::Option("list").takes_value().value_name("FILE") + .help("Place every `\\t` pair of FILE in one process (#734 E4); several lines naming one destination are its sources")) + .action(cmd_stage)) + // Named by a build program's actions through `${mcpp.self}` (SPEC-007 + // R3.8): one output, its content decided by the lines after `--` and + // the files named by `--append`, written only when the bytes differ. + .subcommand(cl::App("write").group("TOOLS FOR ACTIONS") + .description("Write the lines after `--`, then each --append file, to --output; write only when the content differs (invoked by ${mcpp.self} actions)") + .option(cl::Option("output").short_name('o').takes_value().value_name("PATH") + .help("Destination path; its parent directory is created")) + .option(cl::Option("append").takes_value().multiple().value_name("FILE") + .help("A file whose bytes follow the lines, in the order given; declare it as the action's input")) + .action([&passthrough](const cl::ParsedArgs& p) { + return cmd_write(p, std::span(passthrough)); + })) + .subcommand(cl::App("link-output").hidden() + .description("(internal: invoked by ninja) Remove the row's companions, move a linked artifact aside, then run the linker command after `--` (a running program keeps its file)") + .option(cl::Option("output").takes_value().value_name("PATH").help("the artifact the command links")) + .option(cl::Option("companions").takes_value().value_name("SUFFIXES").help("the row's companions, removed before the link (`.wasm`)")) + .option(cl::Option("aside").help("move the previous artifact aside first (a Windows host)")) + .option(cl::Option("temporary").help("link under a temporary name in the artifact's directory, then rename it over the artifact (POSIX)")) + .option(cl::Option("text").takes_value().value_name("ENCODING").help("`console`: the command writes its text in the console's code page, which is read as UTF-8 (link.exe, lib.exe)")) + .action([&passthrough](const cl::ParsedArgs& p) { + return cmd_link_output(p, std::span(passthrough)); + })) + .subcommand(cl::App("platform-step").hidden() + .description("(internal: invoked by ninja for a platform's link) `capture --out F -- argv…` saves a program's output; `seal --steps F -- [needed…]` runs the platform's seal steps, then publishes") + .arg(cl::Arg("mode").help("capture | seal")) + .option(cl::Option("out").takes_value().value_name("PATH").help("capture: the file the output is saved as")) + .option(cl::Option("steps-hex").takes_value().value_name("HEX").help("seal: the steps, one per line, words separated by a tab, hex-encoded (the command is the steps, so a changed step reseals)")) + .action([&passthrough](const cl::ParsedArgs& p) { + return cmd_platform_step(p, std::span(passthrough)); + })) + .subcommand(cl::App("place-dlls").hidden() + .description("(internal: invoked by ninja) Place beside a Windows program the DLLs it imports from its runtime search directories") + .option(cl::Option("output").takes_value().value_name("PATH").help("the stamp to write")) + .option(cl::Option("depfile").takes_value().value_name("PATH").help("the depfile naming every DLL placed")) + .option(cl::Option("crt").takes_value().value_name("RULE") + .help("how the contract governs the MSVC C++ runtime's names: carry | system | static | not-applicable")) + .option(cl::Option("toolset-crt").takes_value().value_name("DIR") + .help("the selected toolset's C++ runtime directory")) + .action(cmd_place_dlls)) + .subcommand(cl::App("coff-def").hidden() + .description("(internal: invoked by ninja) Discover exports in COFF and LLVM bitcode objects") + .option(cl::Option("output").takes_value().value_name("PATH").help("the .def to write")) + .option(cl::Option("name").takes_value().value_name("DLL").help("LIBRARY name recorded in the .def")) + .option(cl::Option("llvm-cxx").takes_value().value_name("PATH").help("selected LLVM compiler for bitcode inspection")) + .option(cl::Option("llvm-nm").takes_value().value_name("PATH").help("llvm-nm from the selected LLVM installation")) + .option(cl::Option("llvm-target").takes_value().value_name("TRIPLE").help("selected target triple")) + .option(cl::Option("exports-file").takes_value().value_name("PATH").help("the target's `exports` patterns, one per line")) + .option(cl::Option("required").help("a consumer of this build links the DLL: an empty export surface is an error")) + .action(cmd_coff_def)) + // The three edges of the detach-codegen schedule. Internal, and named as + // such: they are only ever invoked by a generated build.ninja. + .subcommand(cl::App("bmi-compile").hidden() + .description("(internal) Compile a module interface and return when its BMI is published") + .option(cl::Option("bmi").takes_value().value_name("PATH").help("BMI this unit publishes")) + .option(cl::Option("object").takes_value().value_name("PATH")) + .option(cl::Option("slot").takes_value().value_name("PATH").help("where .log/.rc are kept")) + .option(cl::Option("self").takes_value().value_name("PATH").help("path to mcpp, re-invoked as supervisor")) + .option(cl::Option("sem").takes_value().value_name("DIR").help("concurrency token directory")) + .option(cl::Option("cap").takes_value().value_name("N").help("max concurrent compilers")) + .option(cl::Option("command-file").takes_value().value_name("PATH").help("file holding the compiler command line")) + .option(cl::Option("dep-from").takes_value().value_name("PATH").help("scanner depfile to adopt")) + .option(cl::Option("dep-to").takes_value().value_name("PATH").help("where ninja expects this edge's depfile")) + .option(cl::Option("relocate").takes_value().value_name("NAMING").help("write below an attempt of its own and publish (design 2026-11-19 §10.6)")) + .action(cmd_bmi_compile)) + .subcommand(cl::App("bmi-supervise").hidden() + .description("(internal) Run a compiler to completion and record its status") + .option(cl::Option("slot").takes_value().value_name("PATH")) + .option(cl::Option("sem").takes_value().value_name("PATH")) + .option(cl::Option("cap").takes_value().value_name("N")) + .option(cl::Option("object").takes_value().value_name("PATH")) + .option(cl::Option("command-file").takes_value().value_name("PATH")) + .option(cl::Option("relocation").takes_value().value_name("DIR")) + .action(cmd_bmi_supervise)) + .subcommand(cl::App("bmi-await").hidden() + .description("(internal) Join a detached compiler and replay its diagnostics") + .option(cl::Option("slot").takes_value().value_name("PATH")) + .option(cl::Option("object").takes_value().value_name("PATH")) + .action(cmd_bmi_await)) + ; + + // `--agent-skill-doc` at every level of the tree answers from the sheets + // the build rendered into the binary (docs/mcpp-skills; build.mcpp): no + // file is read and nothing is asked of the home or the network. The root's + // index lists the commands in the order the help does. + std::vector listed; + for (const auto& command : cl::snapshot(app).subcommands) listed.push_back(command.name); + cl::agent_skills::install_default(app, mcpp::skills::sheets, + {.help = "Print the command's usage sheet: when to use it, examples, refusals and remedies", + .root_commands = std::move(listed)}); + return app; +} + +int run(int argc, char** argv) { + namespace cl = mcpplibs::cmdline; + + // `mcpp help ...` is `mcpp ... --help`, and a bare + // `mcpp help` the root's: one help, printed from the command tree (design + // 2026-11-27 §3.9.2). Rewritten before anything reads the words, so the + // help of `pack` is the one `mcpp pack --help` prints. + static char helpFlag[] = "--help"; + std::vector helpWords; + if (argc > 1 && std::string_view(argv[1]) == "help") { + helpWords.push_back(argv[0]); + for (int i = 2; i < argc; ++i) helpWords.push_back(argv[i]); + helpWords.push_back(helpFlag); + helpWords.push_back(nullptr); + argc = static_cast(helpWords.size()) - 1; + argv = helpWords.data(); + } + + // 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. + if (argc > 1 && std::string_view(argv[1]) == "__compiler-cap") { + std::filesystem::path semaphore; + std::filesystem::path output; + std::filesystem::path depfile; + std::filesystem::path bmi; + std::string relocate; + mcpp::build::schedule::detach::Reading reading; + bool object = false; + int cap = 0, i = 2; + for (; i < argc && std::string_view(argv[i]) != "--"; ++i) { + const std::string_view option = argv[i]; + // `--output` is an object of a compile: it is kept when the + // compiler writes the bytes it had. + if (option == "--object") { object = true; continue; } + if ((option != "--sem" && option != "--cap" && option != "--output" && option != "--depfile" + && option != "--bmi" && option != "--relocate" && option != "--source-dependencies" + && option != "--text") || i + 1 >= argc) { + std::println(libc::stderr(), "error: __compiler-cap: expected --sem [--cap ] [--object] [--bmi ] [--relocate ] [--source-dependencies ] [--text console] -- ..."); + return 2; + } + const std::string_view value = argv[++i]; + if (option == "--sem") semaphore = value; + else if (option == "--output") output = value; + else if (option == "--depfile") depfile = value; + else if (option == "--bmi") bmi = value; + else if (option == "--relocate") relocate = value; + else if (option == "--source-dependencies") reading.sourceDependencies = value; + else if (option == "--text") { + if (value != "console") { + std::println(libc::stderr(), "error: __compiler-cap: --text takes `console`, not `{}`", value); + return 2; + } + reading.text = mcpplibs::os::text::encoding::console; + } else { + const auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), cap); + if (ec != std::errc{} || end != value.data() + value.size()) return 2; + } + } + // No --cap: the generation's, or MCPP_COMPILER_CAP outside one. + if (semaphore.empty() || cap < 0 || i + 1 >= argc) return 2; + std::vector command; + for (++i; i < argc; ++i) command.emplace_back(argv[i]); + // THE EDGE, MEASURED (design 2026-11-20 §5.6): its start, for the + // progress line of a long compile, and, once the compiler is reaped, + // its processor time and largest resident set -- this process starts + // no other program, so its children's use is the compiler's. + mcpp::build::progress::record_action_start(output.generic_string()); + const auto unixMs = [] { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + }; + const auto started = unixMs(); + // THE UNIT CACHE (design 2026-11-20 §5.3): a compile whose command and + // read files hold the contents an earlier one's did is placed, not run. + std::optional units; + mcpp::build::unit_cache::Unit unit{command, std::filesystem::current_path(), object ? output : std::filesystem::path{}, bmi}; + if (const auto dir = mcpp::invocation::get(mcpp::build::unit_cache::kDirEnv); dir && !dir->empty() && object) { + std::vector roots; + std::istringstream in(mcpp::invocation::get(mcpp::build::unit_cache::kRootsEnv).value_or("")); + for (std::string line; std::getline(in, line);) + if (!line.empty()) roots.push_back(mcpp::home::from_utf8(line)); + units.emplace(mcpp::home::from_utf8(*dir), std::move(roots), unit.cwd); + if (units->serve(unit)) { + if (const auto file = mcpp::invocation::get(mcpp::build::record::kUsageEnv); file && !file->empty()) { + mcpp::build::record::Usage u{output.generic_string(), started, unixMs()}; + u.served = true; + (void)mcpplibs::os::fs::append(mcpp::home::from_utf8(*file), mcpp::build::record::usage_line(u)); + } + return 0; + } + } + const int status = mcpp::build::schedule::detach::run_capped(command, semaphore, cap, output, depfile, bmi, + object, relocate, reading); + if (status == 0 && units) units->keep(unit); + else if (object) mcpp::build::unit_cache::Cache::forget(unit); + if (const auto file = mcpp::invocation::get(mcpp::build::record::kUsageEnv); file && !file->empty()) { + mcpp::build::record::Usage u{output.generic_string(), started, unixMs()}; + if (const auto used = mcpplibs::os::process::resources(mcpplibs::os::process::of::children)) { + u.cpuMs = std::chrono::duration(used->user + used->system).count(); + u.peakBytes = used->peak_memory; + } + (void)mcpplibs::os::fs::append(mcpp::home::from_utf8(*file), mcpp::build::record::usage_line(u)); + } + return status; + } + + ReportUnnarrowablePaths reportUnnarrowable_; - // ─── xpkg (descriptor tooling: parse) ────────────────────────── - .subcommand(cl::App("xpkg") - .description("Inspect / validate xpkg descriptors") - .subcommand(cl::App("parse") - .description("Parse a descriptor's mcpp segment exactly as the resolver would (strict: unknown keys are errors)") - .option(cl::Option("json") - .help("Emit machine-readable JSON (legacy payload, kept for ever)")) - .option(cl::Option("format").takes_value().value_name("json") - .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) - .option(cl::Option("allow-unknown") - .help("Downgrade unknown mcpp-segment keys from error to warning")) - .option(cl::Option("all-os") - .help("Validate every per-OS section (linux/macosx/windows), " - "not just the running host's")) - .option(cl::Option("allow-split-name") - .help("OBSOLETE (kept accepted so 0.0.105-era index CI keeps " - "working): skip the package.name form check. Since " - "0.0.106 the canonical form IS the short name, so " - "xlings-native descriptors pass without this flag")) - .action(cmd_xpkg_parse))) + // What a build that waits for this one is told it waits for (mcpp#839): + // the command as typed, cut where a long argument list would bury it. + { + std::string command = "mcpp"; + for (int i = 1; i < argc && command.size() < 80; ++i) { + command += ' '; + command += argv[i]; + } + mcpp::build::dirlock::set_command(std::move(command)); + } + + // THE ONE SHAPE OF A WAIT (design 2026-11-27 §3.7 point 4). The first + // report names what is waited for, the lock file as given, the last + // recorded holder and whether that process is visible here, and how to + // bound the wait; each later report is one line. A holder that is not + // visible is not known to be gone: it may run in another process + // namespace, a container, or on a machine sharing the home. The machine + // stream gets the same facts as `waiting` events. + mcpp::home::set_wait_reporter([](const mcpp::home::WaitReport& r) { + const auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + const auto holder = mcpp::home::parse_holder(r.record); + const bool visible = mcpp::home::holder_visible(holder); + const auto who = mcpp::home::describe(holder, now); + if (r.first) { + mcpp::ui::status("Waiting", std::format("for {} ({})", r.resource, r.file.string())); + std::string more = std::format(" last recorded holder: {}{}\n", who, + holder.pid.empty() ? "" : visible ? ", a process visible here" : ", not a process visible here"); + if (!holder.pid.empty() && !visible) + more += std::format( + " it may run where this process cannot see it (another process namespace, a " + "container, or a machine sharing this home), or be a process that inherited the file; " + "`{}` lists the holders on this system\n", mcpp::home::holder_listing(r.file)); + more += " help: it ends when that process lets go; to stop waiting after a limit, " + "--lock-wait \n"; + mcpp::ui::block(more); + } else { + mcpp::ui::status("Waiting", std::format("{}s for {}, held by {}", + std::chrono::duration_cast(r.waited).count(), r.resource, who)); + } + mcpp::build::result::emit("waiting", { + {"holder", {{"pid", holder.pid}, {"command", holder.command}, {"client", holder.client}, + {"startedAt", holder.startedAt}}}, + {"waitedMs", r.waited.count()}, {"path", r.file.string()}, {"resource", r.resource}, + {"holderVisible", visible}}); + }); + + // ─── --home : this run's home (design 2026-10-26 §9.1, SPEC-010) ── + // Exactly MCPP_HOME for this process: the raw home of the two-step + // selection, so its locator is still followed. Taken out of argv before + // anything parses it. After `self init` the flag is that command's own -- + // the home to select persistently -- and stays; a global one naming a + // different directory beside it is a usage error, the same one naming the + // same directory is that command's flag written twice. + std::vector homeFiltered(argv, argv + argc); + { + std::optional global; + std::vector kept{homeFiltered.front()}; + std::vector words; + bool initArgs = false; + for (std::size_t i = 1; i < homeFiltered.size(); ++i) { + const std::string_view a = homeFiltered[i]; + if (a == "--") { kept.insert(kept.end(), homeFiltered.begin() + static_cast(i), homeFiltered.end()); break; } + if (!a.starts_with("-")) { + words.push_back(a); + initArgs = initArgs || (words.size() == 2 && words[0] == "self" && words[1] == "init"); + } + if (!initArgs && (a == "--home" || a.starts_with("--home="))) { + if (a == "--home") { + if (i + 1 >= homeFiltered.size()) { + mcpp::ui::error("--home needs a directory"); + return 2; + } + global = std::string(homeFiltered[++i]); + } else global = std::string(a.substr(7)); + continue; + } + kept.push_back(homeFiltered[i]); + } + if (global) { + std::error_code ec; + const auto absolute = std::filesystem::absolute(*global, ec).lexically_normal(); + for (std::size_t i = 1; initArgs && i < kept.size(); ++i) { + const std::string_view a = kept[i]; + std::string other; + if (a == "--home" && i + 1 < kept.size()) other = kept[i + 1]; + else if (a.starts_with("--home=")) other = std::string(a.substr(7)); + else continue; + if (std::filesystem::absolute(other, ec).lexically_normal() != absolute) { + mcpp::ui::error(std::format("--home names {} and `self init --home` names {}; give one of them", + absolute.string(), other)); + return 2; + } + } + mcpp::invocation::set("MCPP_HOME", absolute.string()); + homeFiltered = std::move(kept); + argc = static_cast(homeFiltered.size()); + argv = homeFiltered.data(); + } + } + + // A SELF-CONTAINED HOME IS STATED for the programs mcpp starts. It is + // derived from where this engine is (`/bin/mcpp`), and a build + // directory's graph runs the engine through its own link (2026-11-12 §17), + // from which the same home cannot be derived. + mcpp::home::state_portable_home(); + + // ─── --deny (design 2026-10-26 §5.5) ─────────────────────── + // Published as MCPP_DENY_EFFECTS, the union of what the caller's + // environment already denies and what the flag adds, for the reason + // --offline is an env var: the consumers sit in every subsystem. A name + // that is not a deniable effect is a usage error, before anything runs. + { + auto valid = [](std::string_view list) -> std::optional { + std::size_t pos = 0; + while (pos <= list.size()) { + auto comma = list.find(',', pos); + auto item = list.substr(pos, comma == std::string_view::npos ? std::string_view::npos : comma - pos); + while (!item.empty() && item.front() == ' ') item.remove_prefix(1); + while (!item.empty() && item.back() == ' ') item.remove_suffix(1); + const auto& names = mcpp::effects::deniable_effects(); + if (!item.empty() && std::ranges::find(names, item) == names.end()) + return std::string(item); + if (comma == std::string_view::npos) break; + pos = comma + 1; + } + return std::nullopt; + }; + std::string denied = mcpp::invocation::get("MCPP_DENY_EFFECTS").value_or(""); + for (int i = 1; i < argc; ++i) { + const std::string_view a = argv[i]; + if (a == "--") break; + std::string value; + if (a == "--deny") { + if (i + 1 >= argc) { mcpp::ui::error("--deny needs a list of effects"); return 2; } + value = argv[i + 1]; + } else if (a.starts_with("--deny=")) value = std::string(a.substr(7)); + else continue; + denied += (denied.empty() ? "" : ",") + value; + } + if (auto bad = valid(denied)) { + mcpp::ui::error(std::format( + "--deny / MCPP_DENY_EFFECTS: '{}' is not an effect that can be denied; expected " + "init-mcpp-home, write-project, write-global-cache, network, exec-build-script", *bad)); + return 2; + } + if (!denied.empty()) mcpp::invocation::set("MCPP_DENY_EFFECTS", denied); + } - // ─── resource management ─────────────────────────────────────── - .subcommand(cl::App("toolchain") - .description("Install / list / select / remove C++ toolchains") - .subcommand(cl::App("list").description("List installed toolchains") - .option(cl::Option("format").takes_value().value_name("json") - .help("Machine-readable output (enveloped; see docs/50-machine-output.md)"))) - .subcommand(cl::App("install") - .description("Install a toolchain via mcpp's xlings") - // Both `mcpp toolchain install gcc 16.1.0` and `mcpp toolchain - // install gcc@16.1.0` are accepted, and the version may be - // partial (`15`, `15.1`) — mcpp resolves to the highest match. - // With --target the family may be omitted entirely (taken from - // the target's convention pin): - // mcpp toolchain install --target x86_64-windows-gnu - .arg(cl::Arg("compiler").help("gcc | llvm | msvc | emsdk | android-ndk (or gcc@16.1.0; legacy aliases accepted)")) - .arg(cl::Arg("version").help("e.g. 16.1.0, 15, 15.1")) - .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( - "Install the toolchain payload for (e.g. x86_64-windows-gnu)")) - .option(cl::Option("platform").takes_value().value_name("SPEC") - .help("With --target: the target's platform for this invocation (= MCPP_PLATFORM)"))) - .subcommand(cl::App("default") - .description("Set the default toolchain (and optionally the default target)") - // Same dual-form as `install`: `gcc@16.1.0` or `gcc 16.1.0`, - // partial versions allowed. - .arg(cl::Arg("spec").help("[@] (version may be partial)").required()) - .arg(cl::Arg("version").help("(optional, alternative to @-form)")) - .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( - "Default build target (omit = host)"))) - .subcommand(cl::App("remove") - .description("Uninstall a toolchain") - // Same dual-form as `default`: `gcc@16.1.0` or `gcc 16.1.0`. - // NOT partial versions: `default` resolves `gcc 15` to the - // highest installed 15.x.y, but a removal must name the one - // payload it deletes, so the version here is exact. - .arg(cl::Arg("spec") - .help("[@] (exact version)") - .required()) - .arg(cl::Arg("version").help("(optional, alternative to @-form)")) - .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( - "Remove the payload for instead of the host one"))) - .action(cmd_toolchain_any)) - .subcommand(cl::App("cache") - .description("Inspect and manage the global build cache") - .subcommand(cl::App("dir") - .description("Print the cache root (and any pre-v1 cache)") - .action(cmd_cache_dir)) - .subcommand(cl::App("list") - .description("List cache entries with size + last-use") - .option(cl::Option("json") - .help("Emit machine-readable JSON (legacy payload, kept for ever)")) - .option(cl::Option("format").takes_value().value_name("json") - .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) - .action(cmd_cache_list)) - .subcommand(cl::App("info") - .description("Show details (incl. key inputs) for a cached package") - .arg(cl::Arg("pkg").help("@").required()) - .action(cmd_cache_info)) - .subcommand(cl::App("prune") - .description("Drop entries not used within a threshold") - .option(cl::Option("older-than").takes_value().value_name("N{s|m|h|d}") - .help("Age threshold (e.g. 30d)")) - .action(cmd_cache_prune)) - .subcommand(cl::App("gc") - .description("LRU-collect package and host tool entries to a size and/or age budget") - .option(cl::Option("max-size").takes_value().value_name("N{MiB|GiB}") - .help("Keep the package cache under this size (e.g. 5GiB)")) - .option(cl::Option("older-than").takes_value().value_name("N{s|m|h|d}") - .help("Also drop entries, and the store's roots, unused for longer than this")) - .option(cl::Option("dry-run") - .help("Say what would be collected, and remove nothing")) - .action(cmd_cache_gc)) - .subcommand(cl::App("clean") - .description("Drop cache entries (default: package entries only)") - .option(cl::Option("deps").help("Drop package entries (default)")) - .option(cl::Option("std").help("Drop std module entries")) - .option(cl::Option("tools").help("Drop host tool entries")) - .option(cl::Option("all").help("Drop every kind of entry")) - .option(cl::Option("legacy") - .help("Remove the unused pre-v1 cache at $MCPP_HOME/bmi")) - .action(cmd_cache_clean)) - .subcommand(cl::App("verify") - .description("Check every entry's manifest against the files on disk") - .action(cmd_cache_verify))) - .subcommand(cl::App("index") - .description("Manage configured package registries") - .subcommand(cl::App("list") - .description("List configured registries") - .option(cl::Option("format").takes_value().value_name("FMT") - .help("json: the mcpp.index envelope")) - .action(cmd_index_list)) - .subcommand(cl::App("add") - .description("Add a custom registry") - .arg(cl::Arg("name").help("Registry name").required()) - .arg(cl::Arg("url").help("Registry URL").required()) - .action(cmd_index_add)) - .subcommand(cl::App("remove") - .description("Remove a registry") - .arg(cl::Arg("name").help("Registry name").required()) - .action(cmd_index_remove)) - .subcommand(cl::App("update") - // #540: the argument selects among the PROJECT's custom - // indices only. The global repos are always synced wholesale, - // because `xlings update` has no per-index mode to call — a - // limitation index_management.cppm has recorded as a follow-up - // since it was written, in a comment no one typing the command - // can read. Saying it here is not the fix; it is the honest - // description until the upstream mode exists. - .description("Refresh local registry clones " - "(global repos always sync in full)") - .arg(cl::Arg("name").help( - "Update only this PROJECT-level custom index " - "(the global repos sync regardless)")) - .action(cmd_index_update)) - .subcommand(cl::App("status") - .description("Show local index presence/freshness (offline)") - .action(cmd_index_status)) - .subcommand(cl::App("pin") - .description("Pin a custom index to a commit rev in mcpp.toml") - .arg(cl::Arg("name").help("Index name").required()) - .arg(cl::Arg("rev").help("Commit sha (defaults to current lock rev)")) - .action(cmd_index_pin)) - .subcommand(cl::App("unpin") - .description("Remove rev pin from a custom index in mcpp.toml") - .arg(cl::Arg("name").help("Index name").required()) - .action(cmd_index_unpin))) + // ─── --lock-wait (design 2026-11-27 §3.7.2, D10) ─────────── + // The longest any wait of this command for a lock another process holds + // lasts; published as MCPP_LOCK_WAIT, which the provider's own lock reads + // as XLINGS_LOCK_TIMEOUT, so one limit governs every wait of the command. + // A value that is not a duration is a usage error before anything runs. + { + std::optional stated = mcpp::invocation::get("MCPP_LOCK_WAIT"); + bool fromFlag = false; + for (int i = 1; i < argc; ++i) { + const std::string_view a = argv[i]; + if (a == "--") break; + if (a == "--lock-wait") { + if (i + 1 >= argc) { mcpp::ui::error("--lock-wait needs a duration (30s, 2m, 1h, 0)"); return 2; } + stated = argv[i + 1]; + fromFlag = true; + } else if (a.starts_with("--lock-wait=")) { + stated = std::string(a.substr(12)); + fromFlag = true; + } + } + if (stated && !stated->empty()) { + const auto limit = mcpp::home::parse_wait(*stated); + if (!limit) { + mcpp::ui::error(std::format("{}: '{}' is not a duration; expected a number with s, m, h or " + "ms (30s, 2m, 1h, 500ms), or 0 for no wait", + fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT", *stated)); + return 2; + } + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Override, limit, + fromFlag ? "--lock-wait" : "MCPP_LOCK_WAIT"); + mcpp::invocation::set("MCPP_LOCK_WAIT", *stated); + } + } + + // ─── --quiet / --no-color: pre-scan ───────────────────────────────── + // The cmdline lib propagates global options into nested subcommand + // ParsedArgs, but we set ui:: state up-front so that *every* line + // emitted from the action lambdas (including the very first + // "Resolving toolchain" banner) honours the user's intent. This is + // a side-channel only — the global options are still declared on + // the App below so they show up in --help and pass schema checks. + for (int i = 1; i < argc; ++i) { + std::string_view a = argv[i]; + // Everything after a bare `--` belongs to the program being run or the + // test binary being invoked, not to mcpp. Without this, `mcpp run -- -j 4` + // reads the child's flag as mcpp's own concurrency setting — `-j` is a + // common enough flag that this is a matter of when, not whether. + if (a == "--") break; + if (a == "--quiet" || a == "-q") mcpp::ui::set_quiet(true); + else if (a == "--no-color") mcpp::ui::disable_color(); + else if (a == "--verbose" || a == "-v") mcpp::log::set_verbose(true); + // --offline is published as the env var rather than plumbed through + // BuildOverrides: its consumers are index refresh, package install and + // toolchain auto-install, which sit in three subsystems and would each + // need a parameter threaded down. Same shape as MCPP_VERBOSE above, and + // it makes `MCPP_OFFLINE=1` and `--offline` literally the same switch. + else if (a == "--offline") mcpp::invocation::set("MCPP_OFFLINE", "1"); + // `--locked` rides the same side channel, and for the stronger form + // of the same reason: its consumer is the resolution write point deep + // in mcpp.build.prepare, and it applies to every command that resolves + // — build, run, test, flash, monitor, debug — so a per-subcommand + // option would have to be declared six times and threaded six times. + // + // It asserts rather than pins: the resolution that happens must equal + // the one mcpp.lock records, and a difference is reported naming the + // package that moved. See the check itself for why assertion is the + // half that reproducibility needs first. + else if (a == "--locked" || a == "--frozen") + mcpp::invocation::set("MCPP_LOCKED", "1"); + // `--managed-only` (mcpp#755) rides the same channel: its consumer is + // the decision record at the end of prepare, for every command that + // prepares, and the fast paths that would skip that record. + else if (a == "--managed-only") + mcpp::invocation::set("MCPP_MANAGED_ONLY", "1"); + // --jobs rides the same side channel as --offline, for the same reason + // recorded there: its consumer is deep in mcpp.build.execute and + // threading a parameter down would touch every caller in between. + // Accepts `--jobs N`, `--jobs=N`, `-j N` and `-jN`. + else if (a == "--jobs" || a == "-j") { + if (i + 1 < argc) mcpp::invocation::set("MCPP_JOBS", argv[++i]); + } + else if (a.starts_with("--jobs=")) mcpp::invocation::set("MCPP_JOBS", std::string(a.substr(7))); + // --toolchain rides the same channel, for the same reason: its consumer + // is deep inside prepare's resolution and threading a parameter down + // would touch every caller in between. + else if (a == "--toolchain") { + if (i + 1 < argc) mcpp::invocation::set("MCPP_TOOLCHAIN", argv[++i]); + } + else if (a.starts_with("--toolchain=")) mcpp::invocation::set("MCPP_TOOLCHAIN", std::string(a.substr(12))); + // --sysroot is `MCPP_SYSROOT` for this invocation (design 2026-10-23 + // §3.3), for the reason --toolchain is: its consumer is the base + // statement deep in prepare, and the fast paths read the variable to + // know a build's base changed. + else if (a == "--sysroot") { + if (i + 1 < argc) mcpp::invocation::set("MCPP_SYSROOT", argv[++i]); + } + else if (a.starts_with("--sysroot=")) mcpp::invocation::set("MCPP_SYSROOT", std::string(a.substr(10))); + // --platform and --host-platform are `MCPP_PLATFORM` and + // `MCPP_HOST_PLATFORM` for this invocation (SPEC-013 §3, §6.1), for + // the reason --sysroot is: the selection is made deep in prepare, and + // the fast paths read the variables to know the configuration moved. + else if (a == "--platform") { + if (i + 1 < argc) mcpp::invocation::set("MCPP_PLATFORM", argv[++i]); + } + else if (a.starts_with("--platform=")) mcpp::invocation::set("MCPP_PLATFORM", std::string(a.substr(11))); + else if (a == "--host-platform") { + if (i + 1 < argc) mcpp::invocation::set("MCPP_HOST_PLATFORM", argv[++i]); + } + else if (a.starts_with("--host-platform=")) + mcpp::invocation::set("MCPP_HOST_PLATFORM", std::string(a.substr(16))); + else if (a.starts_with("-j") && a.size() > 2) + mcpp::invocation::set("MCPP_JOBS", std::string(a.substr(2))); + // --play-game rides the same channel: its value is optional + // (`--play-game` chooses a game, `--play-game=snake` names one), which + // the parser's options do not express, and its consumer is the build's + // report deep in mcpp.build.progress (build output design revision 3, + // §5.14). The option is also declared on build, run and test below, so + // that --help lists it and the parser accepts both spellings. + else if (a == "--play-game") mcpp::invocation::set("MCPP_PLAY_GAME", "random"); + else if (a.starts_with("--play-game=")) + mcpp::invocation::set("MCPP_PLAY_GAME", std::string(a.substr(12))); + } + // `--system` (design 2026-10-16 §9.2): the maintenance commands act on + // the machine's system home, whatever the caller's HOME and MCPP_HOME + // say. Building as root would write root's files into a user's project, + // so no other command takes it. + if (std::ranges::any_of(std::span(argv + 1, argv + argc), [](const char* a) { return std::string_view(a) == "--system"; })) { + if (std::ranges::any_of(std::span(argv + 1, argv + argc), [](const char* a) { + const std::string_view arg{a}; + return arg == "--home" || arg.starts_with("--home="); + })) { + mcpp::ui::error("--home cannot be combined with --system"); + return 2; + } + if (int rc = enter_system_home(argc, argv); rc != 0) return rc; + } + // Decline xlings' linker-wrapper path injection, for this process and + // everything it spawns (openxlings/xlings#540). + // + // That wrapper appends `-rpath "$XLINGS_SUBOS_LIB"` to every link it sees. + // mcpp wants the TAG half of what it does and must refuse the PATH half: + // `$XLINGS_SUBOS_LIB` names the ACTIVE SHELL's SubOS, which is measurably + // not the one mcpp resolved — mcpp keeps its own xlings home under + // `/registry`, so on an ordinary developer machine the variable + // points at a different farm backed by a DIFFERENT PHYSICAL glibc payload. + // Inheriting it would put a second libc on the artifact's search path, + // which is the one thing rule B exists to prevent. mcpp emits its own farm + // entry, derived from the binding it actually selected. + // + // Set here rather than per link command: the link line has a hard 128KiB + // ceiling that real workspaces already spend 43% of, and children inherit + // the environment for free. Declared BEFORE the wrapper ships, because + // "the exit must be declared, not inferred" is the rule that whole + // negotiation established — today this is a no-op. + mcpp::invocation::set( + std::string(mcpp::runtime::search::kLinkerPathInjectionOptOut), + std::string(mcpp::runtime::search::kLinkerPathInjectionOptOutValue)); - // ─── about mcpp itself ───────────────────────────────────────── - .subcommand(cl::App("self") - .description("Inspect and manage mcpp itself") - .subcommand(cl::App("init") - .description("Initialize or repair mcpp sandbox") - .option(cl::Option("home").takes_value().value_name("PATH") - .help("Initialize PATH and remember it from the original home (does not migrate data)")) - .option(cl::Option("force") - .help("Rebuild registry/caches; with --home, replace the default without deleting data")) - .action(cmd_self_init)) - .subcommand(cl::App("doctor") - .description("Diagnose mcpp environment health") - .action(cmd_doctor)) - .subcommand(cl::App("env") - .description("Print mcpp paths and configuration; with --target, one configuration: toolchain, platform, tools, runner") - .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().value_name("TRIPLE") - .help("Report this target's configuration (prepared, not built; the project's when run in one); " - "a target set or several reports each leg")) - .option(cl::Option("host") - .help("Report the host graph's configuration: what build programs and tools are built for")) - .option(cl::Option("platform").takes_value().value_name("SPEC") - .help("The target's platform for this invocation (= MCPP_PLATFORM): @, path:, none")) - .option(cl::Option("host-platform").takes_value().value_name("SPEC") - .help("The host graph's platform for this invocation (= MCPP_HOST_PLATFORM)")) - .option(cl::Option("format").takes_value().value_name("json") - .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) - .action(cmd_env_any)) - .subcommand(cl::App("config") - .description("Show or modify mcpp's configuration: the xlings mirror and the retention of build outputs") - .option(cl::Option("mirror").takes_value().value_name("auto|CN|GLOBAL") - .help("Set xlings mirror for mcpp's private registry")) - .option(cl::Option("cache-unused-days").takes_value().value_name("DAYS") - .help("Collect build-cache entries no build used for DAYS days (default 30; 0 keeps all)")) - .option(cl::Option("keep-days").takes_value().value_name("DAYS") - .help("Sweep a project's build directories no configuration used for DAYS days (default 3; 0 keeps all)")) - .action(cmd_self_config)) - .subcommand(cl::App("version") - .description("Show mcpp version") - .action(cmd_self_version)) - .subcommand(cl::App("completion") - .description("Write the completion script of a shell into the home and say how to load it") - .arg(cl::Arg("shell").values({"bash", "zsh", "fish", "powershell"}) - .help("bash, zsh, fish or powershell; the shell $SHELL names when absent")) - .option(cl::Option("print").help("Print the script instead of writing it")) - .action(cmd_self_completion)) - .subcommand(cl::App("explain") - .description("Show extended description for an error code") - .arg(cl::Arg("code").help("Error code such as E0001, or a refusal's reason token such as platform-version-group").required()) - .action(cmd_explain_action)) - .subcommand(cl::App("store") - .description("Compare this home's payloads with its upstreams") - .subcommand(cl::App("dedupe") - .description("List payloads an upstream has the same of; --apply links them") - .option(cl::Option("apply").help("Replace each by a link to the upstream's"))) - .action(cmd_self_store))) + // Env override (observability, esp. CI): MCPP_VERBOSE= + // turns on verbose logging for EVERY mcpp invocation — including the ones + // nested inside e2e test scripts that call $MCPP without flags. Lets a + // workflow flip on diagnostics globally with one env var. An explicit + // --quiet still wins (it is processed above and gates the verbose sinks). + if (auto v = mcpp::invocation::get("MCPP_VERBOSE"); v && *v != "0") + mcpp::log::set_verbose(true); - // ─── top-level explain alias ────────────────────────────────── - // Preserves `mcpp explain E0001` as a shortcut for - // `mcpp self explain E0001`. - .subcommand(cl::App("explain") - .description("Show extended description for an error code") - .arg(cl::Arg("code").help("Error code such as E0001, or a refusal's reason token such as platform-version-group").required()) - .action(cmd_explain_action)) + // ─── `pack --help` and the version line ───────────────────────────── + // The root's help and every other command's come from the command tree. + // `pack --help` lists its options in two groups, which the tree does not + // state; the version line is `mcpp X.Y.Z`, the name first, which scripts + // read. + if (argc >= 2) { + std::string_view a = argv[1]; + if (a == "pack") + for (int i = 2; i < argc; ++i) + if (std::string_view h = argv[i]; h == "--help" || h == "-h") { + print_pack_usage(); + return 0; + } else if (h == "--") { + break; + } + if (a == "--version" || a == "-V") { + std::println("mcpp {}", mcpp::toolchain::MCPP_VERSION); + return 0; + } + } - // ─── bareword `version` alias ───────────────────────────────── - // cmdline natively handles `--help`/`--version`/`-h`; the bareword - // `mcpp help` is intercepted by the pre-scan above (prints the - // canonical usage screen). `mcpp version` is wired through the - // App so it shows up in the auto-generated subcommand list. - .subcommand(cl::App("version") - .description("Show mcpp version") - .action(cmd_self_version)) + // Every action returns its status, and `App::run` dispatches to the + // deepest named command at any depth (mcpplibs.cmdline 0.0.4): a parent + // such as `cache` or `self` carries no dispatch table of its own. - // ─── hidden / internal ───────────────────────────────────────── - .subcommand(cl::App("dyndep") - .description("(internal: invoked by ninja) Emit ninja dyndep file from .ddi inputs") - .option(cl::Option("output").short_name('o').takes_value().value_name("PATH") - .help("Path to write dyndep file")) - .option(cl::Option("single").help("Single-file mode: one .ddi → one .dd")) - .option(cl::Option("bmi-dir").takes_value().value_name("DIR") - .help("BMI cache directory name (default: gcm.cache)")) - .option(cl::Option("bmi-ext").takes_value().value_name("EXT") - .help("BMI file extension (default: .gcm)")) - .option(cl::Option("module-map").takes_value().value_name("FILE") - .help("Module name -> BMI path, one ` ` per line (mcpp#732)")) - .option(cl::Option("split-module") - .help("Also emit a record for the provided BMI (two-phase " - "schedule: BMI and object are separate edges)")) - .option(cl::Option("expect-provides").takes_value().value_name("NAME") - .help("(verification) planned provided module for this TU")) - .option(cl::Option("expect-imports").takes_value().value_name("CSV") - .help("(verification) planned imports for this TU, comma-separated")) - .option(cl::Option("expect-none") - .help("(verification) planner assumed no provides/imports")) - .action(cmd_dyndep)) - // Named by generated build.ninja edges and, since 2026.9.13.1, by a - // build program's own actions through `${mcpp.self}` (docs/30), so - // the argument shape below is a contract: `stage --verify content - // --output ` copies one file, creates the destination's - // parent, and writes only when the bytes differ. - .subcommand(cl::App("stage") - .description("Copy one file into place: create the destination's parent, write only when the content differs (invoked by build.ninja and by ${mcpp.self} actions)") - .option(cl::Option("output").short_name('o').takes_value().value_name("PATH") - .help("Destination path; its parent directory is created")) - .option(cl::Option("verify").takes_value().value_name("MODE") - .help("How an existing destination is judged up to date: content (default) | size")) - .option(cl::Option("list").takes_value().value_name("FILE") - .help("Place every `\\t` pair of FILE in one process (#734 E4); several lines naming one destination are its sources")) - .action(cmd_stage)) - // Named by a build program's actions through `${mcpp.self}` (SPEC-007 - // R3.8): one output, its content decided by the lines after `--` and - // the files named by `--append`, written only when the bytes differ. - .subcommand(cl::App("write") - .description("Write the lines after `--`, then each --append file, to --output; write only when the content differs (invoked by ${mcpp.self} actions)") - .option(cl::Option("output").short_name('o').takes_value().value_name("PATH") - .help("Destination path; its parent directory is created")) - .option(cl::Option("append").takes_value().multiple().value_name("FILE") - .help("A file whose bytes follow the lines, in the order given; declare it as the action's input")) - .action([&passthrough](const cl::ParsedArgs& p) { - return cmd_write(p, std::span(passthrough)); - })) - .subcommand(cl::App("link-output") - .description("(internal: invoked by ninja) Remove the row's companions, move a linked artifact aside, then run the linker command after `--` (a running program keeps its file)") - .option(cl::Option("output").takes_value().value_name("PATH").help("the artifact the command links")) - .option(cl::Option("companions").takes_value().value_name("SUFFIXES").help("the row's companions, removed before the link (`.wasm`)")) - .option(cl::Option("aside").help("move the previous artifact aside first (a Windows host)")) - .option(cl::Option("temporary").help("link under a temporary name in the artifact's directory, then rename it over the artifact (POSIX)")) - .option(cl::Option("text").takes_value().value_name("ENCODING").help("`console`: the command writes its text in the console's code page, which is read as UTF-8 (link.exe, lib.exe)")) - .action([&passthrough](const cl::ParsedArgs& p) { - return cmd_link_output(p, std::span(passthrough)); - })) - .subcommand(cl::App("platform-step") - .description("(internal: invoked by ninja for a platform's link) `capture --out F -- argv…` saves a program's output; `seal --steps F -- [needed…]` runs the platform's seal steps, then publishes") - .arg(cl::Arg("mode").help("capture | seal")) - .option(cl::Option("out").takes_value().value_name("PATH").help("capture: the file the output is saved as")) - .option(cl::Option("steps-hex").takes_value().value_name("HEX").help("seal: the steps, one per line, words separated by a tab, hex-encoded (the command is the steps, so a changed step reseals)")) - .action([&passthrough](const cl::ParsedArgs& p) { - return cmd_platform_step(p, std::span(passthrough)); - })) - .subcommand(cl::App("place-dlls") - .description("(internal: invoked by ninja) Place beside a Windows program the DLLs it imports from its runtime search directories") - .option(cl::Option("output").takes_value().value_name("PATH").help("the stamp to write")) - .option(cl::Option("depfile").takes_value().value_name("PATH").help("the depfile naming every DLL placed")) - .option(cl::Option("crt").takes_value().value_name("RULE") - .help("how the contract governs the MSVC C++ runtime's names: carry | system | static | not-applicable")) - .option(cl::Option("toolset-crt").takes_value().value_name("DIR") - .help("the selected toolset's C++ runtime directory")) - .action(cmd_place_dlls)) - .subcommand(cl::App("coff-def") - .description("(internal: invoked by ninja) Discover exports in COFF and LLVM bitcode objects") - .option(cl::Option("output").takes_value().value_name("PATH").help("the .def to write")) - .option(cl::Option("name").takes_value().value_name("DLL").help("LIBRARY name recorded in the .def")) - .option(cl::Option("llvm-cxx").takes_value().value_name("PATH").help("selected LLVM compiler for bitcode inspection")) - .option(cl::Option("llvm-nm").takes_value().value_name("PATH").help("llvm-nm from the selected LLVM installation")) - .option(cl::Option("llvm-target").takes_value().value_name("TRIPLE").help("selected target triple")) - .option(cl::Option("exports-file").takes_value().value_name("PATH").help("the target's `exports` patterns, one per line")) - .option(cl::Option("required").help("a consumer of this build links the DLL: an empty export surface is an error")) - .action(cmd_coff_def)) - // The three edges of the detach-codegen schedule. Internal, and named as - // such: they are only ever invoked by a generated build.ninja. - .subcommand(cl::App("bmi-compile").hidden() - .description("(internal) Compile a module interface and return when its BMI is published") - .option(cl::Option("bmi").takes_value().value_name("PATH").help("BMI this unit publishes")) - .option(cl::Option("object").takes_value().value_name("PATH")) - .option(cl::Option("slot").takes_value().value_name("PATH").help("where .log/.rc are kept")) - .option(cl::Option("self").takes_value().value_name("PATH").help("path to mcpp, re-invoked as supervisor")) - .option(cl::Option("sem").takes_value().value_name("DIR").help("concurrency token directory")) - .option(cl::Option("cap").takes_value().value_name("N").help("max concurrent compilers")) - .option(cl::Option("command-file").takes_value().value_name("PATH").help("file holding the compiler command line")) - .option(cl::Option("dep-from").takes_value().value_name("PATH").help("scanner depfile to adopt")) - .option(cl::Option("dep-to").takes_value().value_name("PATH").help("where ninja expects this edge's depfile")) - .option(cl::Option("relocate").takes_value().value_name("NAMING").help("write below an attempt of its own and publish (design 2026-11-19 §10.6)")) - .action(cmd_bmi_compile)) - .subcommand(cl::App("bmi-supervise").hidden() - .description("(internal) Run a compiler to completion and record its status") - .option(cl::Option("slot").takes_value().value_name("PATH")) - .option(cl::Option("sem").takes_value().value_name("PATH")) - .option(cl::Option("cap").takes_value().value_name("N")) - .option(cl::Option("object").takes_value().value_name("PATH")) - .option(cl::Option("command-file").takes_value().value_name("PATH")) - .option(cl::Option("relocation").takes_value().value_name("DIR")) - .action(cmd_bmi_supervise)) - .subcommand(cl::App("bmi-await").hidden() - .description("(internal) Join a detached compiler and replay its diagnostics") - .option(cl::Option("slot").takes_value().value_name("PATH")) - .option(cl::Option("object").takes_value().value_name("PATH")) - .action(cmd_bmi_await)) - ; + // ─── `--` passthrough for `mcpp run` / `mcpp test` ────────────────── + // cmdline natively recognises `--` and dumps everything after it + // into `parsed.positionals` (with the bare `--` token dropped). For + // `mcpp run [target] -- args...` we need to distinguish the + // optional `target` (a real positional) from the passthrough + // tokens (which must reach the executed binary verbatim, even when + // they look like `-x` / `--foo`). We split ourselves at the first + // `--` and present cmdline only the pre-`--` slice; post-args go + // into `passthrough` and are handed to the action helper directly. + std::vector passthrough; + std::vector trimmed_argv(argv, argv + argc); + { + for (std::size_t i = 1; i < trimmed_argv.size(); ++i) { + if (std::string_view(trimmed_argv[i]) != "--") continue; + for (std::size_t j = i + 1; j < trimmed_argv.size(); ++j) + passthrough.emplace_back(trimmed_argv[j]); + trimmed_argv.resize(i); // drop `--` and everything after + break; + } + } + int trimmed_argc = static_cast(trimmed_argv.size()); + char** trimmed_argp = trimmed_argv.empty() ? nullptr : trimmed_argv.data(); + + // ─── The command tree ─────────────────────────────────────────────── + // `emit surface` lists the definition it is part of; it is set once the + // definition is where it stays. + const cl::App* self = nullptr; + auto app = command_tree(passthrough, self); self = &app; - // The bareword `mcpp help` and `mcpp` (no args) both print the - // canonical help screen. if (argc <= 1) { - print_usage(); - return 0; - } - if (std::string_view(argv[1]) == "help") { - print_usage(); + app.print_help(); return 0; } @@ -2007,7 +2033,7 @@ int run(int argc, char** argv) { // invoking the App. if (std::string_view(argv[1]) == "--explain") { if (argc < 3) { - std::println(libc::stderr(), "error: --explain requires an error code (e.g. E0001)"); + mcpp::ui::error("--explain needs a code: an E code (E0001), an MCPP_* code, or a reason token (layer-cycle)"); return 2; } return cmd_explain(argv[2]); @@ -2096,35 +2122,6 @@ int run(int argc, char** argv) { } } - // Unknown-command pre-check. cmdline doesn't error on an unknown - // top-level word — it just treats it as a positional and returns - // 0 silently (since the root App has no top-level action). The - // pre-existing CLI returned 127 for "unknown command", and e2e - // #01 asserts that exit code, so reproduce it here. - { - std::string_view first = argv[1]; - if (!first.starts_with('-')) { - // Size is deduced, not spelled: an explicit count turns "add a - // command" into "add a command AND remember to bump a number", - // and the compiler only catches the direction that overflows. - static constexpr std::array known = std::to_array({ - "new", "build", "fetch", "run", "test", "clean", "add", "remove", - "update", "search", "publish", "pack", "emit", "xpkg", - "toolchain", "cache", "index", "self", "explain", - "version", "dyndep", "why", "resolve", "stage", "write", "coff-def", - "place-dlls", "link-output", "platform-step", - "bmi-compile", "bmi-supervise", "bmi-await", "__complete", - }); - bool ok = false; - for (auto k : known) if (k == first) { ok = true; break; } - if (!ok) { - std::println(libc::stderr(), "error: unknown command '{}'", first); - print_usage(); - return 127; - } - } - } - // Parse and dispatch separately, rather than `app.run(argc, argv)`. // // `App::run` prints its parse errors with `std::println` -- to STDOUT -- @@ -2145,9 +2142,11 @@ int run(int argc, char** argv) { // `--help` / `--version` come back as a non-error "failure": the // parser handled them and printed. Nothing to add, nothing to report. if (!parsed.error().is_error()) return 0; - mcpp::ui::error(parsed.error().message); - return 2; + return usage_error(parsed.error(), std::span(trimmed_argp + 1, trimmed_argp + trimmed_argc)); } + // `--agent-skill-doc` is answered here, after the parse and before any + // action: the sheet needs no project, no home and no network. + if (auto answered = app.answer_flags(*parsed)) return *answered; mcpp::cli::record_invocation(app, *parsed); const int action_rc = app.run(*parsed); // The run's closing notices come last, after everything the command diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index 34cd6d4f0..edf5e97d8 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -264,7 +264,7 @@ export int cmd_fetch(const mcpplibs::cmdline::ParsedArgs& parsed) { } std::error_code ec; const auto root = mcpp::project::find_manifest_root(std::filesystem::current_path(ec)); - if (!root) { mcpp::ui::error("no mcpp.toml found in current directory or any parent"); return 2; } + if (!root) { mcpp::ui::error(mcpp::project::no_project_message()); return 2; } mcpp::build::BuildOverrides ov = overrides_from_selectors(parsed); auto legs = target_legs(parsed, ov); if (!legs) { mcpp::ui::error(legs.error()); return 2; } @@ -420,7 +420,7 @@ int build_several_legs(const mcpplibs::cmdline::ParsedArgs& parsed, std::filesystem::path root; if (*selection) root = (*selection)->root; else if (auto r = mcpp::project::find_manifest_root(std::filesystem::current_path(ec))) root = *r; - else { mcpp::ui::error("no mcpp.toml found in current directory or any parent"); return 2; } + else { mcpp::ui::error(mcpp::project::no_project_message()); return 2; } // The specs: one per leg, or in a workspace one per configuration group // of each leg. @@ -546,7 +546,7 @@ int cmd_build_body(const mcpplibs::cmdline::ParsedArgs& parsed, BodyMode mode) { }; auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) { - where("no mcpp.toml found in current directory or any parent"); + where(mcpp::project::no_project_message()); return 2; } auto discovered = mcpp::build::discover_test_targets(*root, memberOv.package_filter, @@ -860,7 +860,7 @@ export int cmd_emit_build_database(const mcpplibs::cmdline::ParsedArgs& parsed) auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) return failed("MCPP_BUILD_DATABASE_NO_PROJECT", - "no mcpp.toml found in current directory or any parent"); + std::string(mcpp::project::kNoProject)); // One plan per configuration group, as `mcpp build` plans a workspace // (workspace design 2026-09-29 §15): a package the members share is one diff --git a/src/cli/cmd_publish.cppm b/src/cli/cmd_publish.cppm index cbff21605..e95bcf138 100644 --- a/src/cli/cmd_publish.cppm +++ b/src/cli/cmd_publish.cppm @@ -403,7 +403,7 @@ int cmd_pack_body(const mcpplibs::cmdline::ParsedArgs& parsed, int cmd_pack_list_formats(const mcpplibs::cmdline::ParsedArgs& parsed) { auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) { - mcpp::ui::error("no mcpp.toml found in current directory or any parent"); + mcpp::ui::error(mcpp::project::no_project_message()); return 2; } mcpp::build::BuildOverrides ov; diff --git a/src/cli/cmd_self.cppm b/src/cli/cmd_self.cppm index 140ac10f6..879865a4f 100644 --- a/src/cli/cmd_self.cppm +++ b/src/cli/cmd_self.cppm @@ -10,6 +10,7 @@ import mcpp.provider.select; import mcpp.build.engine_package; import mcpplibs.cmdline; import mcpp.doctor; +import mcpp.explain; import mcpp.toolchain.fingerprint; // MCPP_VERSION import mcpp.home; import mcpplibs.os.platform; @@ -151,8 +152,27 @@ export int cmd_why(const mcpplibs::cmdline::ParsedArgs& parsed) { } // Also called directly by the dispatcher for the legacy `--explain CODE` form. +// A code it does not hold is answered with the closest it holds: the three +// kinds share one registry (mcpp.explain), so the closest may be of any kind. export int cmd_explain(std::string_view code) { - return mcpp::doctor::explain_code(code); + if (const auto* entry = mcpp::explain::find(code)) { + std::println("{}: {}", entry->code, entry->title); + std::println(""); + std::println("{}", entry->body); + return 0; + } + std::vector known; + for (const auto& entry : mcpp::explain::entries()) known.push_back(entry.code); + std::string text = std::format("unknown code '{}'", code); + if (const auto close = mcpplibs::cmdline::similar_names(code, known); !close.empty()) { + std::string names; + for (const auto& name : close) names += std::format("{}`{}`", names.empty() ? "" : ", ", name); + text += std::format("\n help: the closest code{}: {}", close.size() == 1 ? "" : "s", names); + } + text += "\n help: a code is an E code (E0001), the MCPP_* code of a JSON diagnostic, " + "or the reason token in brackets at the end of a refusal"; + mcpp::ui::error(text); + return 2; } export int cmd_self_version(const mcpplibs::cmdline::ParsedArgs& /*parsed*/) { @@ -284,7 +304,7 @@ export int cmd_self_store(const mcpplibs::cmdline::ParsedArgs& parsed) { export int cmd_explain_action(const mcpplibs::cmdline::ParsedArgs& parsed) { std::string code = parsed.positional(0); if (code.empty()) { - std::println(libc::stderr(), "error: explain requires an error code (e.g. E0001)"); + mcpp::ui::error("explain needs a code: an E code (E0001), an MCPP_* code, or a reason token (layer-cycle)"); return 2; } return cmd_explain(code); diff --git a/src/doctor.cppm b/src/doctor.cppm index 873867c40..3eb345102 100644 --- a/src/doctor.cppm +++ b/src/doctor.cppm @@ -1979,78 +1979,6 @@ export int why_report(const std::string& topic, const std::string& features, return 0; } -// ─── M4 #8.2: mcpp --explain CODE ─────────────────────────────────────── -export int explain_code(std::string_view code) { - struct Entry { std::string_view code, title, body; }; - static constexpr Entry table[] = { - {"E0001", "dependency name mismatch", - "The package located at the [dependencies.] path declares a different\n" - "name in its own [package].name. Either rename the [dependencies.] in\n" - "the consumer's mcpp.toml to match the producer, or fix the producer's\n" - "[package].name."}, - {"E0002", "module imported but not provided", - "A source file does `import X;` but no source file in the build graph\n" - "exports `X`. Either add a dependency that provides X (mcpp add or\n" - "[dependencies.X] path = \"...\") or fix the import."}, - {"E0003", "version constraint unsatisfiable", - "No published version of the package matches the requested constraint.\n" - "Run `mcpp search ` to list available versions, then loosen the\n" - "constraint in mcpp.toml (e.g. ^1.2 instead of =1.2.3)."}, - {"E0004", "toolchain pin mismatch", - "The [toolchain] pin in mcpp.toml does not match the detected toolchain.\n" - "Either install the pinned toolchain (xlings install ...) or relax the\n" - "pin (e.g. \"gcc@>=15\" instead of \"gcc@15.1.0\")."}, - {"E0005", "build cache corruption", - "A file listed in a cache entry's entry.json is missing on disk. Such an\n" - "entry is treated as a miss and rebuilt, so this is never wrong output —\n" - "only wasted space. `mcpp cache verify` lists every affected entry and\n" - "`mcpp cache gc --older-than 0s` reclaims them."}, - {"E0006", "index requires a newer mcpp", - "The package index declares (index.toml [index].min_mcpp) that its\n" - "descriptors need a newer mcpp than this binary — parsing them would\n" - "silently misbehave, so resolution stops instead. Upgrade mcpp:\n" - " curl -fsSL https://github.com/mcpp-community/mcpp/releases/latest/download/install.sh | bash\n" - "To bypass for debugging only: MCPP_INDEX_FLOOR=ignore mcpp build"}, - // The platform's refusals (SPEC-013 §14), by their reason token. - {"platform-not-a-platform", "the selected package states no platform", - "The package selected as the target's platform (--platform, MCPP_PLATFORM,\n" - "[target.] platform, config.toml, the target table) has no [platform]\n" - "section. Select a platform package, or none: --platform none."}, - {"platform-target-unserved", "the platform does not state this target", - "The platform's [platform] targets (and [platform.hosted] targets) do not name\n" - "the target being built. Build one of the targets it names, or select another\n" - "platform for this target under [target.] platform."}, - {"platform-tool-absent", "a tool the platform names is not available", - "The platform links or seals with a tool ([platform.tools]) that the graph did\n" - "not build and this machine does not have. Name the package that builds it:\n" - " [target.'cfg(platform = \"\")'.tools]\n" - " = \"@\""}, - {"platform-version-group", "a family package outside the platform's version group", - "The platform's [platform.versions] names one version of each package of its\n" - "family, whose pins are exact; the graph holds another version of one. Select\n" - "the platform release of that version, or write the group's version where the\n" - "package is requested. `mcpp why` names who requested it. A platform selected\n" - "as a series skips a release whose group the build does not admit; the build\n" - "is refused when no release of the series is left, naming each one."}, - {"platform-phase-directive", "a platform plugin stated what a platform cannot", - "A platform's build.mcpp runs in the platform phase (mcpp::phase() == \"platform\")\n" - "and states the platform's build, link and runner fields and the package formats\n" - "it provides (pack-format, artifact actions). Move any other directive to a\n" - "package of the graph."}, - }; - for (auto& e : table) { - if (e.code == code) { - std::println("{}: {}", e.code, e.title); - std::println(""); - std::println("{}", e.body); - return 0; - } - } - std::println(libc::stderr(), "error: unknown error code '{}'", code); - std::println(libc::stderr(), " known codes: E0001..E0006"); - return 2; -} - // ─── M6.1: `mcpp self ...` — about mcpp itself ────────────────────────── // // `self` is declared as a parent subcommand on the top-level App with diff --git a/src/explain.cppm b/src/explain.cppm new file mode 100644 index 000000000..01548b001 --- /dev/null +++ b/src/explain.cppm @@ -0,0 +1,375 @@ +// mcpp.explain -- what a code means and what to do about it. +// +// ONE REGISTRY FOR THE THREE KINDS OF CODE a reader meets (design 2026-11-27 +// §3.9.2 point 6): the `E` codes of the early resolver, the `MCPP_*` codes of +// JSON diagnostics, and the reason tokens a refusal carries in brackets +// (docs/50). `mcpp explain` answers from it, and from nothing else, so a code +// that is emitted and has no entry is a test failure rather than a question +// nobody can answer. The reason tokens' titles are docs/50's table, read the +// other way round: tests/unit/test_repo_consistency.cpp checks that every token +// of mcpp.build.refusal has an entry here and that docs/50 states each title. +// +// ASCII only: an entry is printed to any console code page. + +export module mcpp.explain; + +import std; + +export namespace mcpp::explain { + +enum class Kind { Error, Diagnostic, Reason }; + +struct Entry { + std::string_view code; + Kind kind; + std::string_view title; // what the code means, one sentence + std::string_view body; // what to do about it +}; + +std::span entries(); +const Entry* find(std::string_view code); + +} // namespace mcpp::explain + +namespace mcpp::explain { +namespace { + +constexpr Entry kEntries[] = { + // The error codes. + {"E0001", Kind::Error, "dependency name mismatch", + "The package at the [dependencies.] path declares another name in its\n" + "[package].name. Rename the key in the consumer's mcpp.toml, or fix the\n" + "producer's [package].name."}, + {"E0002", Kind::Error, "module imported but not provided", + "A source file imports a module no source of the build graph exports. Add\n" + "the dependency that provides it (mcpp add), or fix the import."}, + {"E0003", Kind::Error, "version constraint unsatisfiable", + "No published version matches the constraint. `mcpp search ` lists\n" + "the versions; loosen the constraint in mcpp.toml."}, + {"E0004", Kind::Error, "toolchain pin mismatch", + "The [toolchain] pin does not match the toolchain found. Install the pinned\n" + "one (mcpp toolchain install), or relax the pin."}, + {"E0005", Kind::Error, "build cache corruption", + "A file a cache entry lists is missing. The entry is treated as a miss and\n" + "rebuilt, so no output is wrong. `mcpp cache verify` lists the entries and\n" + "`mcpp cache gc --older-than 0s` reclaims them."}, + {"E0006", Kind::Error, "index requires a newer mcpp", + "The package index declares ([index].min_mcpp) that its descriptors need a\n" + "newer mcpp. Upgrade mcpp (xlings install mcpp). For debugging only:\n" + "MCPP_INDEX_FLOOR=ignore."}, + // The codes of JSON diagnostics (docs/50). + {"MCPP_BUILD_FAILED", Kind::Diagnostic, + "the build did not succeed (`--message-format json`)", + "The diagnostics before it carry the compiler's errors, located where\n" + "their messages say; target/.last-result.json keeps the record."}, + {"MCPP_EFFECT_DENIED", Kind::Diagnostic, + "the run stopped before an effect its caller denied (`--deny`, `--offline`); exit 5", + "Allow the effect, or prepare beforehand: `mcpp fetch` puts what a build\n" + "downloads in the home."}, + {"MCPP_CONFIGURATION_FAILED", Kind::Diagnostic, + "a configuration `mcpp self env --target` asked for cannot be prepared", + "The message carries the refusal and its reason token; `mcpp explain\n" + "` describes it."}, + {"MCPP_CONFIGURATION_SOURCES_REFUSED", Kind::Diagnostic, + "the project's sources would be refused in this configuration; the configuration is still reported", + "The message names the reason, such as `import std` with no C++ runtime in\n" + "the graph."}, + {"MCPP_LOCK_WOULD_CHANGE", Kind::Diagnostic, + "the resolution differs from the project's mcpp.lock, which the command does not write", + "Run `mcpp build` or `mcpp update` to write the lock, or keep the lock and\n" + "adjust mcpp.toml."}, + {"MCPP_GENERATED_FILE_NOT_MATERIALIZED", Kind::Diagnostic, + "a root `[build] generated_files` entry is missing or stale on disk, and the command does not write it", + "Run `mcpp build` (or `mcpp build --configure-only`) to write it."}, + {"MCPP_OFFLINE_DOWNLOAD_REQUIRED", Kind::Diagnostic, + "an offline plan needs a download: a toolchain, a package, a git revision or the package index", + "Run once with the network, or `mcpp fetch` beforehand."}, + {"MCPP_BUILD_DATABASE_NO_PROJECT", Kind::Diagnostic, + "`mcpp emit build-database` ran outside a project", + "Run it in a project's directory."}, + {"MCPP_BUILD_DATABASE_PLAN_FAILED", Kind::Diagnostic, + "a member's plan could not be made", + "The message carries the refusal and its reason token; `mcpp explain\n" + "` describes it."}, + {"MCPP_BUILD_DATABASE_PROGRAM_FAILED", Kind::Diagnostic, + "a package's build program failed; the package is described without its directives", + "`path` names the build.mcpp; `mcpp build` shows the program's own output."}, + {"MCPP_BUILD_DATABASE_HOST_TOOL_DEFERRED", Kind::Diagnostic, + "a host tool the plan requests is not in the tool store; describing builds no tool", + "`mcpp build` builds the tool; the next description uses it."}, + {"MCPP_BUILD_DATABASE_PAYLOAD_DEFERRED", Kind::Diagnostic, + "a build program asked for an on-request payload; describing installs nothing", + "`mcpp build` installs the payload; the next description uses it."}, + {"MCPP_BUILD_DATABASE_STD_UNIT_UNDESCRIBED", Kind::Diagnostic, + "no standard-library build command names its module source, so that unit is not listed", + "The toolchain's std module is built without a command a database can name;\n" + "the other units are described."}, + {"MCPP_PACK_FAILED", Kind::Diagnostic, + "a pack did not succeed (`--message-format json`)", + "The reason is on standard error; a workspace pack carries one diagnostic\n" + "per member that failed."}, + {"MCPP_PACK_FORMATS_PLAN_FAILED", Kind::Diagnostic, + "`mcpp pack --list-formats` could not plan the project", + "The message carries the refusal; `mcpp build` shows it in full."}, + {"MCPP_SEARCH_FAILED", Kind::Diagnostic, + "`mcpp search --format json` could not read the indexes", + "`mcpp index status` shows each index; `mcpp index update` refreshes them."}, + {"prepare.failed", Kind::Diagnostic, + "`mcpp why target|platform|flags --format json`: the build could not be prepared", + "The message carries the refusal and its reason token; `mcpp explain\n" + "` describes it."}, + {"MCPP_USAGE_UNKNOWN_COMMAND", Kind::Diagnostic, + "a word names no command at that level", + "`suggestions` holds the closest commands; ` --help` lists them."}, + {"MCPP_USAGE_UNKNOWN_OPTION", Kind::Diagnostic, + "an option the command does not declare", + "`suggestions` holds the closest options; ` --help` lists them."}, + {"MCPP_USAGE_MISSING_VALUE", Kind::Diagnostic, + "an option that takes a value was given none", + "Write the value after the option, or as --option=value."}, + {"MCPP_USAGE_INVALID_VALUE", Kind::Diagnostic, + "an option's value is not one it takes", + "The message lists the values it takes."}, + {"MCPP_USAGE_MISSING_ARGUMENT", Kind::Diagnostic, + "a required argument was not given", + "` --help` names the arguments."}, + {"MCPP_USAGE_INVALID_ARGUMENT", Kind::Diagnostic, + "an argument's value is not one it takes", + "The message lists the values it takes."}, + // The reason tokens of refusals: docs/50's table, in its order. + {"unknown-target", Kind::Reason, + "the spelling names no row, and no `(arch, os)` group either", + "Spell the target as a triple (x86_64-linux-gnu, aarch64-linux-musl,\n" + "x86_64-windows-gnu) or a target set (openkal, linux-musl).\n" + "`mcpp toolchain list` lists the targets this host serves."}, + {"ambiguous-request", Kind::Reason, + "several rows serve this `(arch, os)` and none is the default", + "Name the whole triple, its environment included (x86_64-linux-gnu or\n" + "x86_64-linux-musl), instead of the (arch, os) pair."}, + {"compiler-requirement-conflict", Kind::Reason, + "the graph's required compiler cannot be used here", + "`mcpp why toolchain` names the requirement and the package that states it.\n" + "Build with a toolchain that satisfies it (--toolchain, [toolchain] in\n" + "mcpp.toml), or change the requirement."}, + {"tier-planned", Kind::Reason, + "the row exists in the vocabulary; nothing is wired yet", + "This mcpp names the target and does not build it yet. Build for a target\n" + "that `mcpp toolchain list` shows as served."}, + {"host-cannot-serve", Kind::Reason, + "no payload here, and no dependency supplied the system", + "Build on a host that serves the target, add the package that supplies its\n" + "system, or choose another target."}, + {"capability-pin", Kind::Reason, + "the row's toolchain is a capability, not a preference", + "The row needs the toolchain it names. `mcpp why toolchain` shows it; build\n" + "with that toolchain."}, + {"managed-only", Kind::Reason, + "`--managed-only` met a source that is not the ecosystem's: the message names each one and where it was stated", + "Replace each source the message names with an ecosystem package, or run\n" + "without --managed-only."}, + {"payload-override", Kind::Reason, + "an `[xlings.overrides]` entry names a path that does not exist, a version a requirement refuses, or is stated by a dependency", + "Correct the path or the version the [xlings.overrides] entry names, or\n" + "remove the entry; only the project states one, not a dependency."}, + {"payload-request", Kind::Reason, + "a build program asked for a payload no manifest of this build declares `provision = \"on-request\"`, or asked again in three consecutive runs", + "Declare the payload with provision = \"on-request\" in the manifest of the\n" + "package whose build program asks for it."}, + {"lto-export-discovery", Kind::Reason, + "a PE shared library whose exports are discovered would be compiled by cl.exe into `/GL` objects, which hold no symbol table: `windows_auto_export = true` stated under `lto = true`, or `/GL` written into the flags of a package it links", + "State the library's exports instead of discovering them, or build it\n" + "without lto and without /GL."}, + {"local-toolchain", Kind::Reason, + "a toolchain named by path, or stated by a build program's toolchain phase, cannot be used: no driver, a contradicting family, a missing tool, or `spec` stated with a key only a toolchain named by path has", + "Point the toolchain at a directory holding a driver of the stated family\n" + "and every tool, or remove the key only a toolchain named by path takes."}, + {"target-base", Kind::Reason, + "the target base (`sysroot`) cannot serve this build: a spelling the row does not take, a path that does not exist, a directory that supplies no C library, a C library older than the compiler's runtime requires, a native base without its loader, or a second C library supplier in the graph; the kernel headers: a prebuilt `layers` form on a row or layer that takes none, a payload without the target architecture's headers, no headers to answer the default, or a measurement that contradicts the statement", + "The message names the part of the base that fails. Name a base that has it\n" + "(--sysroot, MCPP_SYSROOT, [target.] sysroot), or none for the\n" + "target's default."}, + {"convention-unreplaced", Kind::Reason, + "the convention was overridden and nothing replaced it", + "State what replaces the convention the project overrode, or remove the\n" + "override."}, + {"os-mismatch", Kind::Reason, + "the requested and resolved triples name different systems", + "Check --target and the [target.] tables; `mcpp why target` shows\n" + "how the triple was resolved."}, + {"layer-requirement", Kind::Reason, + "a package requires a layer the resolution did not give it", + "`mcpp why deps` names the package that requires the layer. Add the package\n" + "that supplies it, or choose a target that provides it."}, + {"layer-ordering", Kind::Reason, + "the five layers do not stack", + "Replace the supplier the message names as out of order."}, + {"layer-cycle", Kind::Reason, + "the packages that supply the layers require one another in a circle (a kernel-abi written above a C library under a C library written above a kernel-abi); the message names each package, the layer it supplies and the layer it requires, and carries the token in brackets", + "Remove one of the requires edges the message names."}, + {"exclusive-capability", Kind::Reason, + "two packages provide one capability and at least one declared it exclusive", + "Keep one of the two providers, or pin one with --cap or [capabilities]."}, + {"version-floor-unmet", Kind::Reason, + "a package requires more of the machine than the machine was declared to have", + "Declare the machine the target runs on (its OS or C library version) at\n" + "the floor the package needs, or use a version of the package that needs\n" + "less."}, + {"accel-mismatch", Kind::Reason, + "a `[build] sources` entry is constrained to a device set this build does not cover", + "Build with --accel naming the device the entry is constrained to, or widen\n" + "the entry's constraint."}, + {"accel-backend-undeclared", Kind::Reason, + "a `[build] sources` entry names a backend its own package does not list in `[package] accelerators`", + "List the backend in [package] accelerators of the package whose [build]\n" + "sources names it."}, + {"device-source-unconsumed", Kind::Reason, + "a device-kind source reached no action, so nothing compiles it", + "Add the accelerator backend that compiles the source, or remove it from\n" + "[build] sources."}, + {"host-module-missing", Kind::Reason, + "`build.mcpp` imports a module no dependency supplies as a host module", + "Add the package that supplies the module to [build-dependencies]."}, + {"runtime-closure", Kind::Reason, + "an image's `DT_NEEDED` is not answered at load time by the file its link read for it: no file on the image's search path answers it, or another file of that name does (2026.11.27.1+)", + "Ship the library the message names beside the program (mcpp pack --mode\n" + "vendored), or correct the search path the image states."}, + {"static-tls-image", Kind::Reason, + "a shared image whose exact `exports` say a host loads it by `dlopen` asks for the static TLS block (`DF_STATIC_TLS`) with more than the C library serves to such an image (2026.11.27.1+)", + "Build the library with the global-dynamic TLS model, or keep its\n" + "initial-exec TLS data within what the C library serves."}, + {"soname-collision", Kind::Reason, + "two shared libraries of one build are loaded by one name, their file name or a stated `soname` (2026.11.27.1+)", + "Rename one of the two libraries: its file name or its stated soname."}, + {"build-program-unpublished-input", Kind::Reason, + "`mcpp publish`: the package's build program reads a file its archive does not carry -- one outside the package's directory, or one HEAD does not track (2026.11.21.1+)", + "Track the file in git inside the package's directory, or stop reading it\n" + "from the build program."}, + {"companion-too-old", Kind::Reason, + "a companion stated beside the toolchain (`companions = { binutils = ... }`) is older than the one the toolchain's payload declares (SPEC-006 section 2.9)", + "Raise the companion's version to the one the toolchain's payload declares,\n" + "or remove the statement."}, + {"tool-version-conflict", Kind::Reason, + "two declarations name one xlings package at versions that cannot both hold", + "Align the two declarations the message names on one version."}, + {"shared-library-cxx-runtime", Kind::Reason, + "a dependency's C++ shared library in a graph whose C++ runtime is a package, with no private copy stated", + "State a private copy of the C++ runtime for that library, or link the\n" + "dependency statically."}, + {"offline-download-required", Kind::Reason, + "the run is offline and the plan needs a download: a toolchain, a package, a git revision or the package index; from 2026.11.21.1, with no archive directory named", + "Run once with the network, or put what the plan needs in the home first:\n" + "`mcpp fetch`, or `mcpp fetch --from ` on a machine without network."}, + {"artifact-unavailable-offline", Kind::Reason, + "the run is offline, archive directories are named, and neither they nor the download cache hold an archive the plan needs; the message carries the provider's list", + "Put the archive the message names in one of the archive directories, or\n" + "run with the network."}, + {"bundle-older-than-lock", Kind::Reason, + "`mcpp fetch --from`: the bundle lacks a version `mcpp.lock` records", + "Write the bundle again with `mcpp fetch --to ` from the current\n" + "mcpp.lock."}, + {"index-location-named-twice", Kind::Reason, + "two entries of the effective `[indices]` (a manifest's, or a member's beside its workspace's) name one directory, or one repository at one pin; the message names both and the location", + "Remove one of the two entries the message names; a member reads its\n" + "workspace's indexes without restating them."}, + {"package-cycle", Kind::Reason, + "the dependency graph contains a cycle of packages; the message names its edges", + "Remove one of the edges the message names."}, + {"program-cxx-runtime-split", Kind::Reason, + "a program or test that states a self-contained C++ runtime loads a C++ shared library of the build that couples to a shared one", + "State one C++ runtime contract for the program and the library it loads."}, + {"static-package-in-two-images", Kind::Reason, + "a static package several images of the build reach, on a target where an image cannot use another image's copy", + "Make the package a shared library, or link it into one image only."}, + {"c-env-unrealisable", Kind::Reason, + "the resolved C library's `[c-abi]` declaration has no known realisation for this target, or the resolved compiler cannot carry one out", + "Choose a C library or a compiler that realises the declared [c-abi]\n" + "configuration for this target."}, + {"c-env-verification-mismatch", Kind::Reason, + "the probe compiled with the realised `[c-abi]` configuration disagrees with what was declared", + "Correct the [c-abi] declaration of the C library package to what the\n" + "probe measured."}, + {"platform-dependency", Kind::Reason, + "`[build] platform-dependencies = \"refuse\"` and a package in the graph brings a platform SDK", + "Remove the package that brings the platform SDK, or allow it:\n" + "[build] platform-dependencies."}, + {"interface-not-provided", Kind::Reason, + "a package's `[kernel-abi] requires-interfaces` names an interface the resolved implementation does not provide", + "Choose a kernel-abi implementation that provides the interface, or remove\n" + "the requirement."}, + {"apple-sdk-absent", Kind::Reason, + "the target needs an Apple SDK this machine does not provide; it is located rather than installed, because it is not redistributable", + "Install Xcode or the Command Line Tools (xcode-select --install); mcpp\n" + "locates the SDK and does not install it."}, + {"lld-required-absent", Kind::Reason, + "the target links through lld directly and the resolved toolchain payload ships none", + "Build with an LLVM toolchain whose payload includes lld."}, + {"host-tool-toolchain", Kind::Reason, + "`build.mcpp` under a cross `--target` needs a resolvable HOST toolchain and none is set", + "Install a toolchain for the host (mcpp toolchain install) so that\n" + "build.mcpp can be built while cross-compiling."}, + {"std-module-precompile", Kind::Reason, + "the standard library's module could not be precompiled for this configuration", + "The message carries the compiler's output. `mcpp self doctor` checks the\n" + "toolchain; `mcpp cache clean --std` drops a damaged module."}, + {"msvc-redist-unavailable", Kind::Reason, + "an explicit `cxx_runtime = \"toolchain-coupled\"` on an MSVC-ABI row whose toolset has no redistributable directory to stage", + "Install the toolset's redistributable component, or remove\n" + "cxx_runtime = \"toolchain-coupled\"."}, + {"crt-declared-under-host-coupled", Kind::Reason, + "a file of the MSVC C++ runtime is declared beside the program while its contract is host-coupled, under which the system's runtime serves it and no copy is placed", + "Remove the runtime file from the program's declarations, or state a\n" + "toolchain-coupled runtime contract."}, + {"platform-not-a-platform", Kind::Reason, + "the package selected as the target's platform has no `[platform]` section", + "The package selected as the target's platform (--platform, MCPP_PLATFORM,\n" + "[target.] platform, config.toml, the target table) has no\n" + "[platform] section. Select a platform package, or none: --platform none."}, + {"platform-target-unserved", Kind::Reason, + "the selected platform does not serve the target: the triple is not among its `targets`, and a host triple is not among its `[platform.hosted] targets`", + "The platform's [platform] targets (and [platform.hosted] targets) do not\n" + "name the target being built. Build one of the targets it names, or select\n" + "another platform under [target.] platform."}, + {"platform-tool-absent", Kind::Reason, + "a program the platform's link or seal runs (`okld` for an ok image) is neither built by the graph nor found on this machine", + "Name the package that builds the tool:\n" + " [target.'cfg(platform = \"\")'.tools]\n" + " = \"@\""}, + {"platform-version-group", Kind::Reason, + "a package of the platform's version group is in the graph at another version, or no release of a platform series admits the build's requests", + "The platform's [platform.versions] names one version of each package of\n" + "its family. Select the platform release of the version the graph holds, or\n" + "write the group's version where the package is requested; `mcpp why` names\n" + "who requested it."}, + {"platform-phase-directive", Kind::Reason, + "a platform's plugin stated a directive its phase does not take", + "A platform's build.mcpp states the platform's build, link and runner\n" + "fields and the package formats it provides. Move any other directive to a\n" + "package of the graph."}, + {"lock-wait-exceeded", Kind::Reason, + "another run held a lock past the wait limit (`--lock-wait`, `MCPP_LOCK_WAIT`, `[build] lock_wait`); the message names the holder", + "Let the run the message names finish and run again, or raise the limit\n" + "(--lock-wait 10m; 0 does not wait)."}, + {"lock-unavailable", Kind::Reason, + "the system cannot lock a file mcpp needs: permissions, a read-only or lockless file system, no descriptor left; waiting would not end", + "Make the directory the message names writable, or move MCPP_HOME or the\n" + "project to a file system that locks files."}, + {"vcs-unavailable", Kind::Reason, + "`mcpp new` was asked for a repository and git cannot run", + "Install git, or create the project without a repository: --vcs none."}, + {"other", Kind::Reason, + "a refusal whose branch has not been given a token yet", + "Read the message: it names the cause and the remedy. Report the case so\n" + "that its branch gets a token of its own."}, +}; + +} // namespace + +std::span entries() { return kEntries; } + +const Entry* find(std::string_view code) { + for (const auto& e : kEntries) + if (e.code == code) return &e; + return nullptr; +} + +} // namespace mcpp::explain diff --git a/src/pack/route.cppm b/src/pack/route.cppm index 6c9fd1804..ebd7b85d6 100644 --- a/src/pack/route.cppm +++ b/src/pack/route.cppm @@ -60,7 +60,7 @@ namespace mcpp::pack { std::expected route_pack_target(std::string_view requested) { auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); - if (!root) return std::unexpected("no mcpp.toml in current dir or parents"); + if (!root) return std::unexpected(mcpp::project::no_project_message()); // The effective manifest (#690): a workspace member that leaves `version` // to `[workspace.package]` is refused by a raw load before any routing // question is asked. diff --git a/src/pm/commands.cppm b/src/pm/commands.cppm index f0bd18b84..05ccff300 100644 --- a/src/pm/commands.cppm +++ b/src/pm/commands.cppm @@ -152,7 +152,7 @@ inline int cmd_add(const mcpplibs::cmdline::ParsedArgs& parsed) { } auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); - if (!root) { mcpp::ui::error("no mcpp.toml in current dir or parents"); return 2; } + if (!root) { mcpp::ui::error(mcpp::project::no_project_message()); return 2; } auto manifestPath = *root / "mcpp.toml"; // ── Existence gate (#305) ────────────────────────────────────────── @@ -384,7 +384,7 @@ inline int cmd_remove(const mcpplibs::cmdline::ParsedArgs& parsed) { } auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); - if (!root) { mcpp::ui::error("no mcpp.toml in current dir or parents"); return 2; } + if (!root) { mcpp::ui::error(mcpp::project::no_project_message()); return 2; } auto manifestPath = *root / "mcpp.toml"; std::ifstream in(manifestPath); @@ -470,7 +470,7 @@ inline int cmd_update(const mcpplibs::cmdline::ParsedArgs& parsed) { if (parsed.positional_count() > 0) only = parsed.positional(0); auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); - if (!root) { mcpp::ui::error("no mcpp.toml in current dir or parents"); return 2; } + if (!root) { mcpp::ui::error(mcpp::project::no_project_message()); return 2; } // Refresh the index FIRST (#315/D6). // diff --git a/src/pm/index_management.cppm b/src/pm/index_management.cppm index 422e4fc49..4c91435c0 100644 --- a/src/pm/index_management.cppm +++ b/src/pm/index_management.cppm @@ -356,7 +356,7 @@ export int index_status() { export int index_pin(const std::string& name, std::string rev) { auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) { - mcpp::ui::error("no mcpp.toml found in current directory or any parent"); + mcpp::ui::error(mcpp::project::no_project_message()); return 2; } @@ -488,7 +488,7 @@ export int index_pin(const std::string& name, std::string rev) { export int index_unpin(const std::string& name) { auto root = mcpp::project::find_manifest_root(std::filesystem::current_path()); if (!root) { - mcpp::ui::error("no mcpp.toml found in current directory or any parent"); + mcpp::ui::error(mcpp::project::no_project_message()); return 2; } diff --git a/src/project.cppm b/src/project.cppm index 4e9fe4302..3c9065c84 100644 --- a/src/project.cppm +++ b/src/project.cppm @@ -13,6 +13,14 @@ import mcpp.diag; namespace mcpp::project { +// A COMMAND RUN OUTSIDE A PROJECT says it in one sentence, with the two next +// steps (design 2026-11-27 §3.9.2): every command that needs a project uses +// these words, so a reader, a test and an agent meet one message. +export inline constexpr std::string_view kNoProject = "no mcpp.toml in the current directory or any parent"; +export std::string no_project_message() { + return std::format("{}\n help: run it in a project's directory, or create a project: mcpp new ", kNoProject); +} + // Locate mcpp.toml by walking upward from cwd. export std::optional find_manifest_root(std::filesystem::path start) { auto p = std::filesystem::absolute(start); diff --git a/src/publish/pipeline.cppm b/src/publish/pipeline.cppm index af5a4cbbd..b8a0a1913 100644 --- a/src/publish/pipeline.cppm +++ b/src/publish/pipeline.cppm @@ -221,7 +221,7 @@ std::expected publish_one(const std::filesystem::path& root, // `mcpp publish [--dry-run] [--allow-dirty] [--tag TEMPLATE] [--workspace | -p MEMBER...]`. export int publish_package(const PublishRequest& req) { auto here = mcpp::project::find_manifest_root(std::filesystem::current_path()); - if (!here) { mcpp::ui::error("no mcpp.toml in current dir or parents"); return 2; } + if (!here) { mcpp::ui::error(mcpp::project::no_project_message()); return 2; } const auto top = req.members.empty() ? *here : req.workspaceRoot; // Sanity: working tree clean (best-effort via git status). diff --git a/src/wire.cppm b/src/wire.cppm index a68745344..44cb1c90b 100644 --- a/src/wire.cppm +++ b/src/wire.cppm @@ -64,7 +64,7 @@ inline constexpr int kEnvelopeVersion = 1; // from what comes back. struct KindVersion { std::string_view kind; int version; }; -inline constexpr std::array kKinds{{ +inline constexpr std::array kKinds{{ {"mcpp.env", 1}, {"mcpp.xpkg", 1}, {"mcpp.cache", 1}, @@ -112,6 +112,11 @@ inline constexpr std::array kKinds{{ {"mcpp.index", 1}, // `mcpp pack --list-formats --format json` (§5.6). {"mcpp.pack.formats", 1}, + // A usage error under `--message-format json` or `--format json` + // (design 2026-11-27 §3.9.2): no `data` of a command, the command the + // words reached (`data.command`) and one diagnostic, `MCPP_USAGE_*`, whose + // `suggestions` are the declared names closest to an unknown one. + {"mcpp.usage", 1}, }}; // What running a command does, beyond writing to stdout. @@ -173,6 +178,9 @@ struct Diagnostic { // false: the terminal was not shown it (a `once` notice already said to this project, a note // under --quiet). Written only when false, so an envelope that has none is unchanged. bool shown = true; + // The declared names closest to an unknown one, closest first (a usage + // error, `mcpp.usage`). Written only when there are any. + std::vector suggestions; }; // ── The envelope ─────────────────────────────────────────────────────────── @@ -252,6 +260,7 @@ inline nlohmann::json to_json(const Diagnostic& in) { }; if (!d.path.empty()) j["path"] = d.path; if (!d.shown) j["shown"] = false; + if (!d.suggestions.empty()) j["suggestions"] = d.suggestions; if (d.range) { j["range"] = { {"start", {{"line", d.range->start.line}, {"column", d.range->start.column}}}, diff --git a/tests/e2e/cli/commands.cpp b/tests/e2e/cli/commands.cpp index 7e1789256..9e6a68520 100644 --- a/tests/e2e/cli/commands.cpp +++ b/tests/e2e/cli/commands.cpp @@ -44,7 +44,7 @@ std::string graph_text(const s::project& p) { E2E commands{"commands", s::home_fixture, [] { "01 help and version"_test = [] { - // --version is `mcpp `; --help names the commands; an unknown + // --version is `mcpp `; --help lists the commands; an unknown // command exits 127. const fs::path here = fs::current_path(); auto r = s::mcpp({"--version"}, here); @@ -61,9 +61,11 @@ E2E commands{"commands", s::home_fixture, [] { } expect(fatal(!expected.empty())) << "Failed to read mcpp.toml package version"; expect(fatal(out.starts_with("mcpp " + expected))) << "Version mismatch: mcpp.toml=" << expected << ", --version='" << out << "'"; + // The help itself is the command tree's (tests/e2e/cli/usage.cpp). r = s::mcpp({"--help"}, here); - for (std::string_view w : {"Usage:", "mcpp new", "mcpp build", "--configure-only"}) + for (std::string_view w : {"PROJECT COMMANDS:", " new ", " build "}) expect(fatal(e2e::contains(r.out, w))) << "--help missing '" << w << "'"; + e2e::expect_diagnostic("unknown command 'doesnotexist'"); r = s::mcpp({"doesnotexist"}, here); expect(fatal(e2e::exited(r, 127))) << "expected exit 127 for unknown command"; }; diff --git a/tests/e2e/cli/usage.cpp b/tests/e2e/cli/usage.cpp new file mode 100644 index 000000000..d51bf2bc0 --- /dev/null +++ b/tests/e2e/cli/usage.cpp @@ -0,0 +1,133 @@ +// The command line as its own guide (design 2026-11-27 §3.9): the root's help is the command tree, +// in its groups, with the line that points agents at --agent-skill-doc; `mcpp help ` is +// ` --help`; --agent-skill-doc answers at the root and below without a project, a home or +// the network; a usage error is one line and its `help:` lines, and a `mcpp.usage` envelope when +// JSON was asked for; a command run outside a project names the next step; `mcpp explain` answers +// the three kinds of code, and the closest codes to one it does not hold. +import std; +import mcpplibs.mtest; +import mcpp.test.support; + +using namespace mcpplibs::mtest; +namespace s = mcpp::test::support; +namespace fs = std::filesystem; + +namespace { + +// The visible top-level commands, in the order the help lists them, and some hidden ones. +constexpr std::array kVisible{"new", "build", "fetch", "run", "test", "clean", "why", "resolve", "add", "remove", + "update", "search", "publish", "pack", "emit", "xpkg", "toolchain", "cache", "index", + "self", "explain", "version", "stage", "write"}; +constexpr std::array kHidden{"dyndep", "link-output", "platform-step", "place-dlls", "coff-def", "bmi-compile"}; + +std::size_t lines(std::string_view text) { return static_cast(std::ranges::count(text, '\n')); } + +// An empty directory of the case, with no manifest above it. +fs::path empty_dir(std::string_view name) { + const auto dir = s::case_dir() / name; + fs::create_directories(dir); + return dir; +} + +E2E usage{"usage", [] { + "the root help is the command tree and points agents at the sheets"_test = [] { + const auto here = empty_dir("help"); + const auto r = s::mcpp({"--help"}, here); + expect(fatal(e2e::succeeded(r))) << s::text(r); + for (const std::string_view heading : {"PROJECT COMMANDS:", "RESOURCE MANAGEMENT:", "ABOUT MCPP ITSELF:", "TOOLS FOR ACTIONS:"}) + expect(e2e::contains(r.out, heading)) << "--help has no section " << heading; + std::size_t last = 0; + for (const std::string_view command : kVisible) { + const auto at = r.out.find(std::format("\n {} ", command)); + expect(at != std::string::npos) << "--help does not list '" << command << "'"; + if (at != std::string::npos) { + expect(at > last) << "'" << command << "' is listed out of the tree's order"; + last = at; + } + } + for (const std::string_view command : kHidden) + expect(!e2e::contains(r.out, std::format("\n {} ", command))) << "--help lists the internal '" << command << "'"; + expect(e2e::contains(r.out, "Agents: mcpp --agent-skill-doc prints how to use mcpp; every command takes the flag.")) + << r.out; + expect(s::mcpp({}, here).out == r.out) << "a bare `mcpp` prints another help"; + expect(s::mcpp({"help"}, here).out == r.out) << "`mcpp help` prints another help"; + const auto build = s::mcpp({"build", "--help"}, here); + expect(fatal(e2e::succeeded(build))); + expect(s::mcpp({"help", "build"}, here).out == build.out) << "`mcpp help build` is not `mcpp build --help`"; + expect(e2e::contains(s::mcpp({"help", "pack"}, here).out, "Advanced options:")) << "`mcpp help pack` is not pack's help"; + }; + + "--agent-skill-doc answers without a project, a home or the network"_test = [] { + const auto here = empty_dir("skills"); + const auto unused = s::case_dir() / "unused-home"; + const s::options noHome{.env = {{"MCPP_HOME", unused.string()}}}; + const auto root = s::mcpp({"--agent-skill-doc"}, here, noHome); + expect(fatal(e2e::succeeded(root))) << s::text(root); + expect(root.out.starts_with("# mcpp\n")) << root.out.substr(0, 80); + expect(e2e::contains(root.out, "| `mcpp build --agent-skill-doc` | mcpp-build |")) << "the root has no index of the sheets"; + const auto build = s::mcpp({"build", "--agent-skill-doc"}, here, noHome); + expect(e2e::succeeded(build) && build.out.starts_with("# mcpp build\n")) << s::text(build); + // A subcommand with no sheet of its own answers with its nearest ancestor's. + const auto env = s::mcpp({"self", "env", "--agent-skill-doc"}, here, noHome); + expect(e2e::succeeded(env) && env.out.starts_with("# mcpp self\n")) << s::text(env); + expect(!fs::exists(unused)) << "answering a sheet made the home"; + }; + + "a usage error is one line and its help lines"_test = [] { + const auto here = empty_dir("usage"); + e2e::expect_diagnostic("unknown command 'buidl'"); + const auto command = s::mcpp({"buidl"}, here); + expect(e2e::exited(command, 127)) << s::text(command); + expect(command.out.empty()) << command.out; + expect(e2e::contains(command.err, "help: the closest command: `build`")) << command.err; + expect(e2e::contains(command.err, "help: `mcpp --help` lists its commands")) << command.err; + expect(lines(command.err) == 3) << "a usage error printed more than its line and two help lines:\n" << command.err; + + e2e::expect_diagnostic("unknown option: --jbos"); + const auto option = s::mcpp({"build", "--jbos", "3"}, here); + expect(e2e::exited(option, 2)) << s::text(option); + expect(e2e::contains(option.err, "help: the closest option: `--jobs`")) << option.err; + expect(e2e::contains(option.err, "help: `mcpp build --help` lists its options")) << option.err; + + e2e::expect_diagnostic("unknown command 'lst'"); + const auto nested = s::mcpp({"cache", "lst"}, here); + expect(e2e::exited(nested, 2)) << s::text(nested); + expect(e2e::contains(nested.err, "`list`")) << nested.err; + expect(e2e::contains(nested.err, "`mcpp cache --help`")) << nested.err; + + const auto json = s::mcpp({"build", "--jbos", "3", "--message-format", "json"}, here); + expect(fatal(e2e::exited(json, 2))) << s::text(json); + const auto doc = s::json(json.out); + expect(fatal(doc.is_object())) << json.out; + expect(doc.value("kind", "") == "mcpp.usage") << json.out; + expect(doc["data"].value("command", "") == "mcpp build") << json.out; + const auto& d = doc["diagnostics"].at(0); + expect(d.value("code", "") == "MCPP_USAGE_UNKNOWN_OPTION") << json.out; + expect(d["suggestions"].is_array() && d["suggestions"].at(0) == "--jobs") << json.out; + }; + + "a command run outside a project names the next step"_test = [] { + const auto here = empty_dir("no-project"); + e2e::expect_diagnostic("no mcpp.toml in the current directory or any parent"); + for (const std::vector args : {std::vector{"build"}, std::vector{"add", "gtest@1.15.2"}}) { + const auto r = s::mcpp(args, here); + expect(e2e::exited(r, 2) || e2e::exited(r, 1)) << s::text(r); + expect(e2e::contains(r.err, "no mcpp.toml in the current directory or any parent")) << r.err; + expect(e2e::contains(r.err, "help: run it in a project's directory, or create a project: mcpp new ")) << r.err; + } + }; + + "explain answers the three kinds of code and the closest to an unknown one"_test = [] { + const auto here = empty_dir("explain"); + for (const std::string_view code : {"E0003", "MCPP_USAGE_UNKNOWN_OPTION", "layer-cycle", "lock-wait-exceeded"}) { + const auto r = s::mcpp({"explain", std::string(code)}, here); + expect(e2e::succeeded(r) && r.out.starts_with(std::format("{}: ", code))) << s::text(r); + } + e2e::expect_diagnostic("unknown code 'layer-cycel'"); + const auto unknown = s::mcpp({"explain", "layer-cycel"}, here); + expect(e2e::exited(unknown, 2)) << s::text(unknown); + expect(e2e::contains(unknown.err, "`layer-cycle`")) << unknown.err; + }; +}}; + +} // namespace diff --git a/tests/unit/test_cli_documents.cpp b/tests/unit/test_cli_documents.cpp new file mode 100644 index 000000000..17f65c096 --- /dev/null +++ b/tests/unit/test_cli_documents.cpp @@ -0,0 +1,100 @@ +// The documents the binary carries agree with the binary (design 2026-11-27 §3.9.2 points 4 and 6): +// every `mcpp ...` example of a sheet under docs/mcpp-skills parses by the command tree and every +// visible top-level command has a sheet; every reason token a refusal can carry, and every code a +// usage error can carry, has an entry `mcpp explain` answers from; docs/50 states each reason +// token's title as the registry does. +import std; +import mcpplibs.mtest; +import mcpplibs.cmdline; +import mcpplibs.cmdline.agent_skills; +import mcpp.cli; +import mcpp.skills; +import mcpp.explain; +import mcpp.build.refusal; + +using namespace mcpplibs::mtest; +namespace fs = std::filesystem; + +namespace { + +fs::path repository() { return fs::path(__FILE__).parent_path().parent_path().parent_path(); } + +std::string read(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + return {std::istreambuf_iterator(in), {}}; +} + +UTest sheets_agree_with_the_tree{"CliDocuments/SheetsAgreeWithTheCommandTree", [] { + const std::vector passthrough; + const mcpplibs::cmdline::App* self = nullptr; + const auto app = mcpp::cli::command_tree(passthrough, self); + const auto problems = mcpplibs::cmdline::agent_skills::check( + app, mcpp::skills::sheets, {.ascii_only = true, .max_lines = 100}); + for (const auto& problem : problems) expect(false) << problem; +}}; + +UTest every_reason_token_is_explained{"CliDocuments/EveryReasonTokenIsExplained", [] { + namespace refusal = mcpp::build::refusal; + std::set tokens; + for (const auto code : refusal::codes()) { + const auto token = refusal::name(code); + tokens.insert(token); + const auto* entry = mcpp::explain::find(token); + expect(entry != nullptr && entry->kind == mcpp::explain::Kind::Reason) + << "reason token '" << token << "' has no entry in mcpp.explain"; + } + for (const auto& entry : mcpp::explain::entries()) + if (entry.kind == mcpp::explain::Kind::Reason) + expect(tokens.contains(entry.code)) << "mcpp.explain explains '" << entry.code << "', which no refusal carries"; +}}; + +UTest every_usage_code_is_explained{"CliDocuments/EveryUsageCodeIsExplained", [] { + // The codes mcpplibs.cmdline gives a usage error that a command line can reach, as + // `MCPP_USAGE_*` (src/cli.cppm usage_error). + for (const std::string_view code : {"UNKNOWN_COMMAND", "UNKNOWN_OPTION", "MISSING_VALUE", "INVALID_VALUE", + "MISSING_ARGUMENT", "INVALID_ARGUMENT"}) + expect(mcpp::explain::find(std::format("MCPP_USAGE_{}", code)) != nullptr) + << "MCPP_USAGE_" << code << " has no entry in mcpp.explain"; +}}; + +UTest docs_state_the_registry_titles{"CliDocuments/Docs50StatesTheRegistryTitles", [] { + // docs/50's reason table, a row per token: the description without its `*(version+)*` + // annotations is the registry's title. + const auto text = read(repository() / "docs" / "50-machine-output.md"); + expect(fatal(!text.empty())) << "docs/50-machine-output.md is missing"; + static const std::regex row{R"(^\| `([a-z][a-z0-9-]*)` \| (.+) \|\s*$)"}; + static const std::regex annotation{R"(\s*\*\([^)]*\)\*)"}; + std::map documented; + std::istringstream in(text); + bool inTable = false; + for (std::string line; std::getline(in, line);) { + // The table's header has an empty second column; other tables have a row named `reason`. + if (line.starts_with("| `reason` | |")) { inTable = true; continue; } + if (!inTable) continue; + if (!line.starts_with("|")) break; + std::smatch m; + if (std::regex_match(line, m, row)) documented[m[1]] = std::regex_replace(std::string(m[2]), annotation, ""); + } + expect(fatal(!documented.empty())) << "docs/50 has no reason table"; + for (const auto& entry : mcpp::explain::entries()) { + if (entry.kind != mcpp::explain::Kind::Reason) continue; + const auto it = documented.find(std::string(entry.code)); + expect(it != documented.end()) << "docs/50 has no row for '" << entry.code << "'"; + if (it != documented.end()) + expect(it->second == entry.title) << "docs/50 row '" << entry.code << "' states \"" << it->second + << "\"; mcpp.explain states \"" << entry.title << "\""; + } +}}; + +bool printable_ascii(std::string_view text) { + return std::ranges::all_of(text, [](unsigned char c) { return c == '\n' || (c >= 0x20 && c <= 0x7e); }); +} + +UTest explain_text_is_ascii{"CliDocuments/ExplainTextIsAscii", [] { + // An entry is printed to any console code page. + for (const auto& entry : mcpp::explain::entries()) + expect(printable_ascii(entry.title) && printable_ascii(entry.body)) + << "mcpp.explain entry '" << entry.code << "' holds a byte outside printable ASCII"; +}}; + +} // namespace From 26fc03afc71b4e0acb4f67a555145fec4b5d7962 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 01:05:18 +0900 Subject: [PATCH 06/36] Build programs take the table a toolchain is named by; a link follows its compiles; the ABI members reach every unit; a test that would overwrite a program is refused - A project whose toolchain is a table (path, launcher, sysroot, tools) builds its build programs with that table, stated as [workspace.toolchain] of their workspace; their identity holds every field and the launcher's stamp (mcpp#1034). - A shared library whose interface reaches a unit's compile (a module of its import closure, the include directories of its public closure) is on that unit's link line after its direct dependencies (mcpp#1031). - The [target..abi] members are one record rendered by one function into the C and C++ units of the root and of each dependency and into the link; an unstated longjmp follows exceptions = "wasm" from the row or the project (mcpp#1029). - mcpp test refuses a test program whose executable is an executable target's file with [test-output-collision], naming the test's file and an example name; names compare as the output directory's file system compares them (mcpp#1028, SPEC-017 v2.7 B1 item 8). --- CHANGELOG.md | 23 +++- docs/04-mcpp-toml.md | 12 ++ docs/08-testing.md | 12 +- docs/20-toolchains.md | 18 ++- docs/22-target-side.md | 22 +++- docs/50-machine-output.md | 1 + docs/specs/README.md | 2 +- docs/specs/test.md | 13 ++- docs/zh/04-mcpp-toml.md | 6 + docs/zh/08-testing.md | 7 +- docs/zh/20-toolchains.md | 13 ++- docs/zh/22-target-side.md | 10 +- docs/zh/50-machine-output.md | 1 + modules/manifest/src/toml.cppm | 1 + modules/manifest/src/types.cppm | 2 + src/build/plan.cppm | 154 +++++++++++++++++++++++--- src/build/prepare.cppm | 1 + src/build/prepare/graph.cpp | 6 +- src/build/prepare/graph_edges.cpp | 6 + src/build/prepare/graph_load.cpp | 6 +- src/build/prepare/host_graph.cpp | 46 +++++++- src/build/prepare/local_toolchain.cpp | 15 ++- src/build/prepare/package_root.cpp | 5 + src/build/prepare/records.cpp | 3 + src/build/prepare/state.cppm | 4 +- src/build/prepare/toolchain.cpp | 46 ++++---- src/build/prepare_inputs.cppm | 31 ++++++ src/build/refusal.cppm | 3 + src/build/test_targets.cppm | 16 ++- src/explain.cppm | 6 + src/modgraph/scanner.cppm | 6 + tests/e2e/build/link.cpp | 25 +++++ tests/e2e/test/collision.cpp | 79 +++++++++++++ tests/e2e/toolchain/custom.cpp | 40 +++++++ tests/e2e/web/emscripten.cpp | 39 +++++++ tests/unit/test_abi.cpp | 39 +++++++ tests/unit/test_test_targets.cpp | 17 +++ 37 files changed, 645 insertions(+), 91 deletions(-) create mode 100644 tests/e2e/test/collision.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c77da03b..d32c61692 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,12 @@ - A command that needs a project, run outside one, says `no mcpp.toml in the current directory or any parent` and names the two next steps. - mcpp depends on mcpplibs.cmdline 0.2.0 with its `agent-skills` feature. +- `mcpp test` refuses, while planning, a test program whose executable would be the same file as + an executable target of its package, with `[test-output-collision]` (mcpp#1028). The message + names the test's file or directory and an example name, or the target's table; names are + compared as the output directory's file system compares them, so `App` and `app` collide where + it does not distinguish case, here and between test names. A project in this state has no + transition period: rename the test (`tests/app.cpp` to `tests/app_test.cpp`) or the target. - Fetching the dependencies prints one line per dependency under its manifest name, with no announcement before the provider downloads, and `Updating` when its revision changes; the dependencies known at one step are fetched in one call to the provider. The provider's lines @@ -59,6 +65,20 @@ ### Fixed +- A build program of a project whose toolchain is named by a table (`{ path = ..., launcher = ..., + sysroot = ..., tools = ... }`) is compiled with that table: the build programs' workspace states it + as `[workspace.toolchain]`, and their identity holds every field and the stamp of each program, + the launcher's included. Before, only `path:` reached them, and the launcher, the sysroot + and the stated tools did not (mcpp#1034). +- A shared library whose interface reaches a unit's compile -- a module of the import closure, or + include directories of the public closure -- is on the link line of that unit's image, after + its direct dependencies. A consumer of a shared library whose header calls another shared + library inline no longer fails to link (mcpp#1031). +- The `[target..abi]` members are resolved once and rendered by one function into the C + units of the root and of every dependency, the C++ units and the link; an unstated `longjmp` + follows `exceptions = "wasm"` whether the row or the project stated it. A dependency's C unit + that calls `setjmp` on `wasm32-emscripten` links under the row's default, under + `exceptions = "wasm"` alone and with both members stated (mcpp#1029). - A version stated through a local table of its descriptor (`["1.2.1"] = versions["1.2.1"]`) is read through the table. It was read as revision 0, so a package whose entry states revision 1 was reinstalled by every build and shown as `Downloading`. A version written in a form mcpp does @@ -66,9 +86,6 @@ mcpp reads differently from the installer is reported once as `fetch/revision-misread` (SPEC-001 §10.5). -- Test planning refuses a test program whose executable would overwrite an executable target - from the same package. The diagnostic names both programs and their shared path (mcpp#1028). - ## [2026.11.27.1] - 2026-11-27 ### Changed diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index 01059c076..99016945c 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -883,6 +883,18 @@ alone, and `compat.sdl3` and `mcpplibs.mwrap.sdl3` both made `libsdl3.so` (mcpp#975). mcpp links and finds the library by the new name; a script outside mcpp that names a dependency's library by its file name follows the change. +**A link takes the libraries its compiles used** *(2026.12.4.1+)*. A package +whose interface reaches the compile of a unit -- a module the unit imports, +directly or through another module, or include directories the usage +requirements hand it -- has its shared library on the link line of the image +that unit belongs to, after the image's direct dependencies. An inline function +or a template of a dependency's header that calls another package is a direct +reference from the consumer's object, and a link that held only the direct +dependency's library left it undefined (mcpp#1031). A private dependency's +include directories do not reach its consumers, so what is added is the public +closure and the import closure; such a library becomes a load dependency of +the image even where no symbol of it is referenced. + **This is not `[target.].linkage`** (§2.7.1). That key answers the same-sounding question about the **C library** (a musl `-static` link, MSVC's `/MT`). The two are not independent, and the direction matters: a fully static diff --git a/docs/08-testing.md b/docs/08-testing.md index 431b4220b..a9ba1f018 100644 --- a/docs/08-testing.md +++ b/docs/08-testing.md @@ -73,9 +73,15 @@ the fixed directory, `mcpp test` notes how many stay programs of their own; when it forms no group at all, the note is a degradation, which `--strict` refuses (2026.11.13.1+). -Test planning refuses a test program whose executable would replace a program -built by the same package (@NEXT@+). The diagnostic names both programs and -the shared path. Rename the test program or the executable target. +Test planning refuses a test program whose executable would be the same file as +an executable target of its package, with `[test-output-collision]` +(2026.12.4.1+): one would replace the other, whichever command ran last. The +message names both programs, the shared path, the test's file or directory with +an example name (`tests/app.cpp` to `tests/app_test.cpp`), and the target's +table. Names are compared as the output directory's file system compares them, +so where it does not distinguish case, `App` and `app` collide; test names +among themselves are compared the same way. `mcpp build` is unaffected, and +the program it wrote is left as it was. `[test] programs = "package"` (2026.11.13.1+) makes every file the package discovers one program, named by the first glob's fixed directory (`tests`). At diff --git a/docs/20-toolchains.md b/docs/20-toolchains.md index f73695566..d6428d7dd 100644 --- a/docs/20-toolchains.md +++ b/docs/20-toolchains.md @@ -609,10 +609,20 @@ link line, its own hermetic check, its own `import std` decision. It writes nothing into the tree — the generated `clang++.cfg` of a managed payload is mcpp's own file, and a tree mcpp does not own does not get one. -**Identity.** The driver and each tool named by `tools` enter the build's -fingerprint by path, size and modification time, so rebuilding the toolchain in -place rebuilds what it produced, and a build records them beside its output so -the fast paths decline once one of them changed. A machine that does not have +**Identity.** The driver, each tool named by `tools` and the launcher enter the +build's fingerprint by path, size and modification time, with every other field +of the table, so rebuilding the toolchain in place rebuilds what it produced, +and a build records them beside its output so the fast paths decline once one +of them changed. + +**Build programs.** Without `bootstrap`, a native build compiles its build +programs with the same table: the workspace mcpp writes for them states it as +`[workspace.toolchain]`, every path absolute, and the programs' builds read it +as any project reads its own (2026.12.4.1+). The launcher, the sysroot and the +stated tools therefore apply to `build.mcpp` as they apply to the project's +units, and the programs are compiled again when any of them changes. A driver +that needs a fixed word is named by `tools.cxx` as a script that adds it, and +the script serves both kinds of compile. A machine that does not have the tree is told so by name — the declaration is refused where it is read — rather than building with another toolchain. diff --git a/docs/22-target-side.md b/docs/22-target-side.md index 300e4a59b..17b322d91 100644 --- a/docs/22-target-side.md +++ b/docs/22-target-side.md @@ -1506,11 +1506,23 @@ render it. **`longjmp` and `exceptions` name one mechanism.** WebAssembly's exception handling carries both the throw and the long jump, and the JavaScript model -carries both. An unstated `longjmp` follows `exceptions`, as the SDK's own -default does. A build that states one model for `exceptions` and the other for -`longjmp` is refused with both statements, before any compile. A declared -`longjmp` is part of the configuration's key; a project that does not state it -keeps the key it had. +carries both. An unstated `longjmp` follows `exceptions`: under the +WebAssembly model it is rendered as `-sSUPPORT_LONGJMP=wasm`, whether the +model is the row's default or the project's statement, and under the +JavaScript model it is the SDK's default (2026.12.4.1+; before, an explicit +`exceptions = "wasm"` left C's `setjmp` on the JavaScript model and the link +failed with `undefined symbol: emscripten_longjmp`, mcpp#1029). A build that +states one model for `exceptions` and the other for `longjmp` is refused with +both statements, before any compile. A declared `longjmp` is part of the +configuration's key; a project that does not state it keeps the key it had. + +**One record, rendered in every package.** The three members are resolved once +into the root's record and rendered by one function: `threads` and `longjmp` +reach the C units of the root and of every dependency, every member reaches the +C++ units through the graph's dialect set, and every member reaches the link +(2026.12.4.1+). Before, `longjmp` reached the root's C units only, and a +dependency's C unit that calls `setjmp` failed the link under the row's default +(mcpp#1029). **Only the root manifest decides.** The switch belongs to the artefact, and the root is the only package that builds one. A dependency that writes diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index 64779bed8..8f3014a9f 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -722,6 +722,7 @@ a program classifying the outcome reads `reason`: | `lock-wait-exceeded` | another run held a lock past the wait limit (`--lock-wait`, `MCPP_LOCK_WAIT`, `[build] lock_wait`); the message names the holder *(2026.12.4.1+)* | | `lock-unavailable` | the system cannot lock a file mcpp needs: permissions, a read-only or lockless file system, no descriptor left; waiting would not end *(2026.12.4.1+)* | | `vcs-unavailable` | `mcpp new` was asked for a repository and git cannot run *(2026.12.4.1+)* | +| `test-output-collision` | a test program and an executable target of one package write one file; the message names the test's file or directory to rename *(2026.12.4.1+)* | | `other` | a refusal whose branch has not been given a token yet | **One token is also printed by `mcpp build` itself.** diff --git a/docs/specs/README.md b/docs/specs/README.md index 1c2f74918..55ea09c7b 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -46,7 +46,7 @@ | [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.2 | 2026-11-10 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1 | | [SPEC-015](target-sets.md) | 目标集合与腿:集合的写法与展开,命令对多条腿的语义,串行规划与一起构建,测试归档,机器输出 | 评审中 v1.0 | 2026-10-30 | mcpp >= 2026.10.30.1 | | [SPEC-016](targets-and-providers.md) | 目标与提供者:行、提供者、选择规则、平台定义的行、C 环境与执行、报告、机器输出与锁 | 评审中 v1.10 | 2026-11-27 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.9 条款 mcpp >= 2026.11.23.1;v1.10 条款 mcpp >= 2026.11.27.1 | -| [SPEC-017](test.md) | mcpp 测试规范:测试程序、测试协议、记录、存储、启动描述与框架声明;基础能力 B1–B6 与可选能力 O1–O12 | 评审中 v2.6 | 2026-11-21 | 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 | +| [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.2 | 2026-11-26 | mcpp >= 2026.11.17.2;§5、§9 的新增自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.1 | diff --git a/docs/specs/test.md b/docs/specs/test.md index e8a37d92e..a6faa16e8 100644 --- a/docs/specs/test.md +++ b/docs/specs/test.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-017 | | 标题 | mcpp 测试规范:测试程序、测试协议、记录、存储、启动描述与框架声明;基础能力与可选能力 | -| 状态 | 评审中 v2.6 | -| 版本 | 2.6 | -| 最后修改 | 2026-11-21 | -| 对应实现 | 逐条标注。B1–B4 与 O1、O2、O4–O7 mcpp >= 2026.11.8.1 至 2026.11.10.1(逐条);B5、B6、O3 的运行器一侧、O8 mcpp >= 2026.11.10.1;O9 由框架的工具实现(mtest >= 0.6.0);O10 mcpp >= 2026.11.13.1;P5 的 `step` 与 `exercise`、B4 的 `builds.ndjson` 与机器的字段、O5 在选择之下的时限、O6 的运行器一侧、O11、O12 mcpp >= 2026.11.21.1,mtest >= 0.11.0 | +| 状态 | 评审中 v2.7 | +| 版本 | 2.7 | +| 最后修改 | 2026-12-04 | +| 对应实现 | 逐条标注。B1–B4 与 O1、O2、O4–O7 mcpp >= 2026.11.8.1 至 2026.11.10.1(逐条);B5、B6、O3 的运行器一侧、O8 mcpp >= 2026.11.10.1;O9 由框架的工具实现(mtest >= 0.6.0);O10 mcpp >= 2026.11.13.1;P5 的 `step` 与 `exercise`、B4 的 `builds.ndjson` 与机器的字段、O5 在选择之下的时限、O6 的运行器一侧、O11、O12 mcpp >= 2026.11.21.1,mtest >= 0.11.0;B1 第 8 条 mcpp >= 2026.12.4.1 | | 取代 | SPEC-017 v1.0(`test-runner.md`);mtest 测试协议版本 1(mtest `spec/protocol.md`)的规范正文;SPEC-004 中 `[test]` 的键 | | 相关规范 | [SPEC-004](manifest-semantics.md)(清单的平面与命名)、[SPEC-006](build-database.md)(构建数据库) | | 相关 issue | mcpp#914、mcpp#915、mcpp#917 | @@ -56,7 +56,9 @@ `name` 相对于工作目录;`[target.<选择器>.test] files` 为该选择器选中的目标追加文件。工作目录的规则见 SPEC-002 §6.2.1 (mcpp >= 2026.11.17.1)。 7. `[test]` 中的其他键产生警告,在 `--strict` 下为错误。 -8. 若测试程序与同一包内的可执行目标产生相同路径,测试计划**必须**拒绝,并列出测试程序、可执行目标和共用路径(mcpp >= @NEXT@)。 +8. 若测试程序与同一包内的可执行目标产生相同路径,测试计划**必须**以原因码 `test-output-collision` 拒绝,并列出测试程序、 + 可执行目标、共用路径,以及应改名的测试文件或目录与一个例子;路径**必须**按输出目录所在文件系统的方式比较(不区分 + 大小写的文件系统上按折叠后的名字),测试名字之间的比较同此(mcpp >= 2026.12.4.1)。 ### B2. 协议核心 @@ -389,5 +391,6 @@ mcpp 以 feature(docs/50 §4)宣告它实现的条款;客户端按需门 | 2.2 | 2026-11-14 | O10 按测量调度(顺序、`split = "auto"`、`--shard`、`--failed`);B4 的 `shard` 与 `part_of` | | 2.4 | 2026-11-17 | B1 第 6 条 `[test] files`;B5 的 `cwd` 为已备好的工作目录(mcpp 2026.11.17.1,设计 2026-11-16 §5) | | 2.5 | 2026-11-21 | P5.6 的 `step` 与 `exercise`;B4 的 `builds.ndjson`、`cpu_ms`、`steps`、`exercised` 与机器的字段(P12.4);O5 的时限只陈述一次;O11 预算;O12 抖动(设计 2026-11-20 §5.5 至 §5.9、§5.16、§5.19) | +| 2.7 | 2026-12-04 | B1 第 8 条:测试程序与可执行目标写同一个文件时以 `test-output-collision` 拒绝,消息写出应改名的测试文件或目录;路径按输出目录所在文件系统的方式比较(mcpp#1028,设计 2026-11-27 §3.2.3) | | 2.6 | 2026-11-21 | P5.6:以作用域运行的用例的事件不指名用例(mtest 0.11.2);O10:`--failed` 中同一秒开始的两次运行按索引中写入的次序;O11 第 5 条:等待机器之门的工作者不持有槽位 | | 2.3 | 2026-11-15 | P4.3 排除与按声明选择(mtest 0.9.0);O10 按声明的用例划分并以测量判定是否保留(`divides`),用例的用时按程序与标识记取 | diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index 95376f32f..78e564d76 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -790,6 +790,12 @@ dependency_linkage = "shared" # per profile 此前依赖包的共享库只取目标名,`compat.sdl3` 与 `mcpplibs.mwrap.sdl3` 都产出 `libsdl3.so`(mcpp#975)。mcpp 按新名字 链接与查找该库;mcpp 之外按文件名引用依赖共享库的脚本随之改变。 +**链接取其编译用到的库** *(2026.12.4.1+)*。一个包的接口到达某个单元的编译时 —— 单元直接或经另一个 +模块导入的模块,或使用要求交给它的包含目录 —— 该包的共享库位于这个单元所属镜像的链接行上,排在镜像的 +直接依赖之后。依赖的头文件中调用另一个包的内联函数或模板,是消费者目标文件的直接引用,只含直接依赖的 +库的链接会留下未定义的符号(mcpp#1031)。私有依赖的包含目录不到达它的消费者,所以新增的只是公开闭包与 +导入闭包;这样的库即使没有符号被引用,也成为镜像的装载依赖。 + **这不是 `[target.].linkage`**(§2.7.1)。那个键回答的是一个 听起来相似、但关于 **C 库**的问题(musl 的 `-static` 链接、MSVC 的 `/MT`)。这两者不是独立的,而且方向很重要:一个完全静态的镜像没有 diff --git a/docs/zh/08-testing.md b/docs/zh/08-testing.md index 5dfda1e6f..df8bf66d1 100644 --- a/docs/zh/08-testing.md +++ b/docs/zh/08-testing.md @@ -61,8 +61,11 @@ discover = ["checks/**/*.cpp", "!checks/fixtures/**"] 一次,后者正是由许多小文件组成的套件在构建上花费的时间。该设置留下直接位于固定目录中的文件时,`mcpp test` 给出一条 note,说明有多少文件仍各自是一个程序;它不形成任何组时,该说明是一次降级,`--strict` 拒绝(2026.11.13.1+)。 -若测试程序与同一包构建的可执行程序共用一个产物路径,测试计划会拒绝该配置(@NEXT@+)。 -诊断会列出两个程序及其共用路径。可重命名测试程序或可执行目标。 +测试程序的可执行文件与本包的可执行目标是同一个文件时,测试计划以 `[test-output-collision]` 拒绝 +(2026.12.4.1+):否则后运行的命令决定这个文件是什么。消息写出两个程序、共同的路径、测试的文件或目录与 +一个改名的例子(`tests/app.cpp` 改为 `tests/app_test.cpp`),以及目标的表。名字按输出目录所在文件系统的 +方式比较,在不区分大小写的文件系统上 `App` 与 `app` 相撞;测试名字之间按同一方式比较。`mcpp build` +不受影响,它写出的程序保持原样。 `[test] programs = "package"`(2026.11.13.1+)使包所发现的全部文件成为一个程序,以第一个 glob 的固定目录命名(`tests`)。 其中定义 `main` 的文件至多一个,两个则被拒绝并点出两者。该程序仍按文件各起一个进程运行,以文件在固定目录之下的路径命名(`tests/unit/b.cpp` 为 `tests/unit/b`),隔离与并行 diff --git a/docs/zh/20-toolchains.md b/docs/zh/20-toolchains.md index 337dbbce0..31bc47435 100644 --- a/docs/zh/20-toolchains.md +++ b/docs/zh/20-toolchains.md @@ -525,9 +525,16 @@ MCPP_TOOLCHAIN=path:/opt/llvm-trunk mcpp build 对 `import std` 的判定。它不向该目录树写入任何东西 —— 托管载荷里生成的 `clang++.cfg` 是 mcpp 自己的文件,而一棵不属于 mcpp 的树不会得到一份。 -**身份。** 驱动与 `tools` 点名的每个程序以路径、大小与修改时间进入构建指纹,因此原地重建 -工具链会重建它产出的东西;构建还把它们记在产物旁边,于是其中之一改变后快速路径会让行。 -没有这棵树的机器会被点名告知——声明在被读取的地方就被拒绝——而不是改用另一个工具链。 +**身份。** 驱动、`tools` 点名的每个程序与启动器以路径、大小与修改时间,连同表的其余每个字段 +进入构建指纹,因此原地重建工具链会重建它产出的东西;构建还把它们记在产物旁边,于是其中之一 +改变后快速路径会让行。没有这棵树的机器会被点名告知——声明在被读取的地方就被拒绝——而不是改用 +另一个工具链。 + +**构建程序。** 没有 `bootstrap` 时,本机构建以同一张表编译它的构建程序:mcpp 为构建程序写出的 +工作空间以 `[workspace.toolchain]` 陈述这张表,各路径为绝对路径,构建程序的构建像任何工程读自己 +的表一样读它(2026.12.4.1+)。启动器、基底与写明的工具因此对 `build.mcpp` 与对工程的单元同样 +生效,其中任何一项改变时构建程序重新编译。需要固定一个词的驱动,由 `tools.cxx` 指向添加该词的 +脚本,这个脚本对两类编译同样生效。 这不是上一节的 `system` 编译器。`system` 是「`PATH` 上碰巧有什么」,而这里是工程点名的 一棵树,由 mcpp 识别并记录,与 `msvc@system` 一直以来的形状相同。 diff --git a/docs/zh/22-target-side.md b/docs/zh/22-target-side.md index bb9564cd9..a5b6130bb 100644 --- a/docs/zh/22-target-side.md +++ b/docs/zh/22-target-side.md @@ -1227,8 +1227,14 @@ WebAssembly 上,每个目标文件、预编译的标准库模块与链接必 所以引擎不渲染它。 **`longjmp` 与 `exceptions` 所指的是同一机制。** WebAssembly 的异常处理同时承载抛出与长跳转,JavaScript 模型也同时承载 -二者。未写 `longjmp` 时它随 `exceptions`,与 SDK 自身的缺省一致。为 `exceptions` 写一种模型、为 `longjmp` 写另一种的构建, -在任何编译之前被拒绝,并写出两处陈述。声明了的 `longjmp` 是配置键的一部分;未声明它的项目保持原有的键。 +二者。未写 `longjmp` 时它随 `exceptions`:WebAssembly 模型下渲染为 `-sSUPPORT_LONGJMP=wasm`,无论该模型是行的默认值 +还是工程的陈述;JavaScript 模型下为 SDK 的默认(2026.12.4.1+;此前显式写出 `exceptions = "wasm"` 时 C 的 `setjmp` 仍是 +JavaScript 模型,链接以 `undefined symbol: emscripten_longjmp` 失败,mcpp#1029)。为 `exceptions` 写一种模型、为 `longjmp` +写另一种的构建,在任何编译之前被拒绝,并写出两处陈述。声明了的 `longjmp` 是配置键的一部分;未声明它的项目保持原有的键。 + +**一个记录,渲染到每个包。** 三个成员解析为根包的一个记录,由同一个函数渲染:`threads` 与 `longjmp` 进入根包与每个 +依赖包的 C 单元,每个成员经依赖图的方言 flag 集合进入 C++ 单元,并进入链接(2026.12.4.1+)。此前 `longjmp` 只进入根包 +的 C 单元,在行的默认值下,调用 `setjmp` 的依赖包 C 单元使链接失败(mcpp#1029)。 **新程序应选 `"wasm"`。** 它的代码比 JavaScript 模型更小、更快,要求宿主支持 WebAssembly 异常处理:Safari 15.2、 Firefox 100、Chrome 95、Node 17 及以上。`true` 保持自 2026.9.12.3 起的含义,即 JavaScript 模型。依赖的 diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 6ceeb1f87..6b8202867 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -644,6 +644,7 @@ replaced}` —— `origin` 与构建的状态行使用的是同一句话 | `lock-wait-exceeded` | 另一次运行持有锁超过等待上限(`--lock-wait`、`MCPP_LOCK_WAIT`、`[build] lock_wait`);消息写出持有者 *(2026.12.4.1+)* | | `lock-unavailable` | 系统无法为 mcpp 需要的文件加锁:权限、只读或不支持锁的文件系统、描述符耗尽;等待不会结束 *(2026.12.4.1+)* | | `vcs-unavailable` | `mcpp new` 被要求建立仓库而 git 无法运行 *(2026.12.4.1+)* | +| `test-output-collision` | 同一个包的测试程序与可执行目标写同一个文件;消息写出应改名的测试文件或目录 *(2026.12.4.1+)* | | `other` | 一个尚未被赋予记号的拒绝分支 | **其中一个记号也由 `mcpp build` 自己打印。** `interface-not-provided` 会 diff --git a/modules/manifest/src/toml.cppm b/modules/manifest/src/toml.cppm index 00a4ced97..e296cf89e 100644 --- a/modules/manifest/src/toml.cppm +++ b/modules/manifest/src/toml.cppm @@ -2159,6 +2159,7 @@ std::expected parse_document(const t::Document& documen } Target t; t.name = tname; + t.line = static_cast(tval.position.line); auto& tt = tval.as_table(); auto kit = tt.find("kind"); diff --git a/modules/manifest/src/types.cppm b/modules/manifest/src/types.cppm index acd0645d7..98bac9e3c 100644 --- a/modules/manifest/src/types.cppm +++ b/modules/manifest/src/types.cppm @@ -194,6 +194,8 @@ inline std::string windows_code_page_problem(std::string_view value) { struct Target { std::string name; + // Where `[targets.]` was written; 0 when the target was inferred. + int line = 0; // `Application` (#622 A3, `kind = "app"`) is "the thing a user launches", // and its link form is a property of the ROW, not of this enum: on every // row but Android it links exactly as `Binary` does; on `*-linux-android` diff --git a/src/build/plan.cppm b/src/build/plan.cppm index df4257d55..9512a1574 100644 --- a/src/build/plan.cppm +++ b/src/build/plan.cppm @@ -1016,6 +1016,17 @@ bool link_unit_holds_cxx(const BuildPlan& plan, const LinkUnit& lu); // this (#646 F3a). bool image_loads_cxx_shared_library(const BuildPlan& plan, LinkUnit::Kind kind); +// WHETHER TWO NAMES THAT DIFFER ONLY IN CASE NAME ONE FILE in `dir`: asked of +// the file system that holds it (its nearest existing ancestor), once per +// directory, by a probe rather than by the name of a system -- a volume of +// either kind is mounted on every system. A directory that cannot be probed +// is read as distinguishing case. +bool folds_case(const std::filesystem::path& dir); +// The text two output paths are compared by: folded to lower case where the +// file system does not distinguish case. Every check that two products would +// write one file compares through it. +std::string output_key(const std::filesystem::path& p, bool foldCase); + // The `trim_paths` map (`BuildPlan::trimMap`) of the packages `keep` marks, // `keep[i]` for `packages[i]`; every package when `keep` is empty. The fixed // roots are always in it. @@ -1128,6 +1139,35 @@ bool image_loads_cxx_shared_library(const BuildPlan& plan, LinkUnit::Kind kind) return false; } +bool folds_case(const std::filesystem::path& dir) { + namespace fs = std::filesystem; + static std::mutex lock; + static std::map asked; + std::error_code ec; + auto at = fs::absolute(dir, ec).lexically_normal(); + while (!at.empty() && !fs::is_directory(at, ec) && at.has_parent_path() && at.parent_path() != at) + at = at.parent_path(); + std::lock_guard guard(lock); + if (auto it = asked.find(at); it != asked.end()) return it->second; + const auto lower = std::format(".mcpp-case-probe-{:x}", std::random_device{}()); + std::string upper = lower; + for (auto& c : upper) c = static_cast(std::toupper(static_cast(c))); + bool folds = false; + if (std::ofstream(at / lower).good()) { + folds = fs::exists(at / upper, ec); + fs::remove(at / lower, ec); + } + asked.emplace(at, folds); + return folds; +} + +std::string output_key(const std::filesystem::path& p, bool foldCase) { + auto text = p.lexically_normal().generic_string(); + if (foldCase) + for (auto& c : text) c = static_cast(std::tolower(static_cast(c))); + return text; +} + namespace { std::string sanitize_for_path(std::string_view module_name) { @@ -1223,26 +1263,50 @@ std::filesystem::path target_output(const mcpp::manifest::Target& t, } // Build and test select different targets, but share the product directory. +// Refused while planning (mcpp#1028): two products writing one file leave it +// to whichever command ran last. The message names what the user can rename: +// the test's file or directory, with an example, and the target's table. std::optional test_output_collision( const mcpp::manifest::Manifest& manifest, const mcpp::toolchain::triple::ArtifactNaming& naming, const std::filesystem::path& productDir, bool applicationsAreExecutables, + bool foldCase, const auto& placeProgram) { using Target = mcpp::manifest::Target; - std::map programs; + std::map programs; for (const auto& t : manifest.targets) { if (t.kind == Target::Binary || (t.kind == Target::Application && applicationsAreExecutables)) - programs.emplace(placeProgram(target_output(t, naming)).lexically_normal(), t.name); + programs.emplace(output_key(placeProgram(target_output(t, naming)), foldCase), &t); } for (const auto& t : manifest.targets) { if (t.kind != Target::TestBinary) continue; const auto path = productDir / target_output(t, naming).lexically_relative("bin"); - if (const auto it = programs.find(path.lexically_normal()); it != programs.end()) - return std::format( - "[test-output-collision] package '{}': test program '{}' ({}) and executable target '{}' " - "both write '{}'. Rename the test program or the executable target", - manifest.package.name, t.name, t.main, it->second, path.generic_string()); + const auto it = programs.find(output_key(path, foldCase)); + if (it == programs.end()) continue; + // A test is named by its file (`tests/app.cpp`) or by its directory + // (`tests/app/main.cpp`); the rename applies to that one. + const std::filesystem::path main(t.main); + auto stem = main; + stem.replace_extension(""); + const bool byFile = stem.generic_string().ends_with(t.name); + const auto named = byFile ? main : main.parent_path(); + auto renamed = named.parent_path() / (named.stem().string() + "_test" + named.extension().string()); + const auto& target = *it->second; + const auto where = target.line > 0 + ? std::format("[targets.{}] in mcpp.toml, line {}", target.name, target.line) + : std::format("the target inferred from {}, named after the package; [targets.] in mcpp.toml names it", target.main); + mcpp::build::refusal::record(mcpp::build::refusal::Code::TestOutputCollision); + // Located at the target's table when the manifest states one: a reader + // of the JSON diagnostic gets its `path` and `range` (docs/50 §2). + const auto located = target.line > 0 && !manifest.sourcePath.empty() + ? std::format("{}:{}: ", manifest.sourcePath.generic_string(), target.line) : std::string(); + return located + std::format( + "[test-output-collision] package '{}': the test program '{}' and the executable target '{}' " + "both write '{}'\n help: rename the test's {} {}, e.g. to {}{}; or rename the target ({})", + manifest.package.name, t.name, target.name, path.generic_string(), + byFile ? "file" : "directory", named.generic_string() + (byFile ? "" : "/"), + renamed.generic_string(), byFile ? "" : "/", where); } return std::nullopt; } @@ -3290,14 +3354,17 @@ make_plan(const mcpp::manifest::Manifest& manifest, } } - auto append_direct_shared_deps = [&](LinkUnit& lu, std::size_t packageIndex) { - auto depsIt = directPackageDeps.find(packageIndex); - if (depsIt == directPackageDeps.end()) return; - for (auto depIndex : depsIt->second) { + // One dependency's shared images on a link unit's line. `followed`: the + // package reached the unit by its interface rather than by an edge of the + // package linked, so an image already on the line, or the unit's own, is + // not added again. + auto append_shared_image = [&](LinkUnit& lu, std::size_t depIndex, bool followed) { auto targetsIt = sharedTargetsByPackage.find(depIndex); - if (targetsIt == sharedTargetsByPackage.end()) continue; + if (targetsIt == sharedTargetsByPackage.end()) return; for (auto targetIndex : targetsIt->second) { auto const& dep = sharedDepTargets[targetIndex]; + if (followed && (dep.output == lu.output || std::ranges::contains(lu.implicitInputs, dep.output))) + continue; lu.implicitInputs.push_back(dep.output); // On PE what the consumer actually LINKS is the import library, // so that is the file the edge has to wait for — the `.dll` @@ -3341,8 +3408,65 @@ make_plan(const mcpp::manifest::Manifest& manifest, : "-Wl,-rpath,'$$ORIGIN/" + rel + "'"); } } + }; + + // LINK FOLLOWS COMPILE (design 2026-11-27 §3.2.1, mcpp#1031). A package + // whose interface reaches the compile of a unit of `packageIndex` -- a + // module the unit imports, directly or through another module, or include + // directories its usage requirements hand it -- is referenced by that + // unit's object directly (a re-exported module, an inline function, a + // template), whether or not it is a direct dependency. Under shared + // linking only a direct dependency's library was on the line, and such a + // reference was left undefined. The usage requirements stop at a private + // edge, so these are the public closure and the import closure, not the + // whole graph. + // Asked when a link is formed, of the units planned by then: a program's + // own main unit is planned just before its link. + auto import_providers = [&](std::size_t packageIndex, std::set& out) { + std::map provider; + for (auto const& cu : plan.compileUnits) + if (!cu.providesModule.empty()) provider.emplace(cu.providesModule, &cu); + const auto name = qualified_package_name(packages[packageIndex].manifest); + std::set seen; + std::vector work; + for (auto const& cu : plan.compileUnits) + if (cu.packageName == name) work.insert(work.end(), cu.imports.begin(), cu.imports.end()); + while (!work.empty()) { + const auto module = std::move(work.back()); + work.pop_back(); + const auto it = provider.find(module); + if (!seen.insert(module).second || it == provider.end()) continue; + if (auto p = packageIndexByName.find(it->second->packageName); p != packageIndexByName.end()) + out.insert(p->second); + work.insert(work.end(), it->second->imports.begin(), it->second->imports.end()); } }; + // Kept while no unit is planned beside them: a workspace's test programs + // are hundreds of links over the same packages. + std::map>> interfaceOf; + auto interface_packages_of = [&](std::size_t packageIndex) { + if (packageIndex >= packages.size()) return std::vector{}; + if (auto it = interfaceOf.find(packageIndex); + it != interfaceOf.end() && it->second.first == plan.compileUnits.size()) + return it->second.second; + std::set reached; + for (auto const& name : packages[packageIndex].privateBuild.interfacePackages) + if (auto p = packageIndexByName.find(name); p != packageIndexByName.end()) reached.insert(p->second); + import_providers(packageIndex, reached); + reached.erase(packageIndex); + std::vector out(reached.begin(), reached.end()); + interfaceOf[packageIndex] = {plan.compileUnits.size(), out}; + return out; + }; + + // The shared images a unit that links the objects of `packageIndex` + // needs: its direct dependencies', then those its interface reached, in + // the dependency slot after them. + auto append_direct_shared_deps = [&](LinkUnit& lu, std::size_t packageIndex) { + if (auto depsIt = directPackageDeps.find(packageIndex); depsIt != directPackageDeps.end()) + for (auto depIndex : depsIt->second) append_shared_image(lu, depIndex, false); + for (auto depIndex : interface_packages_of(packageIndex)) append_shared_image(lu, depIndex, true); + }; auto append_shared_deps_for_linked_objects = [&](LinkUnit& lu) { std::set linkedPackages; @@ -3963,7 +4087,8 @@ make_plan(const mcpp::manifest::Manifest& manifest, const bool applicationsAreExecutables = mcpp::toolchain::triple::application_form(targetTriple) == mcpp::toolchain::triple::ApplicationForm::Executable; if (inTestMode) - if (auto why = test_output_collision(manifest, naming, "bin", applicationsAreExecutables, std::identity{})) + if (auto why = test_output_collision(manifest, naming, "bin", applicationsAreExecutables, + folds_case(outputDir), std::identity{})) return std::unexpected(*why); for (auto& t : manifest.targets) { if (inTestMode && t.kind != mcpp::manifest::Target::TestBinary) continue; @@ -4536,7 +4661,8 @@ make_plan(const mcpp::manifest::Manifest& manifest, return t.kind == mcpp::manifest::Target::TestBinary; }); if (memberTestMode) - if (auto why = test_output_collision(pkg.manifest, naming, productDir, applicationsAreExecutables, place)) + if (auto why = test_output_collision(pkg.manifest, naming, productDir, applicationsAreExecutables, + folds_case(outputDir), place)) return std::unexpected(*why); const auto memberExtTable = mcpp::extension_table_for( pkg.manifest.buildConfig.moduleExtensions, diff --git a/src/build/prepare.cppm b/src/build/prepare.cppm index 38c34ad0f..c91ef1aa9 100644 --- a/src/build/prepare.cppm +++ b/src/build/prepare.cppm @@ -1172,6 +1172,7 @@ export std::vector parse_feature_request(std::string_view s); export std::vector feature_forward_request_tokens(std::string_view s); export bool is_local_git_remote(std::string_view url); + // PrepareState (the state every phase reads and writes) and the phase // declarations live in the implementation partition `:state` — see the // file-header comment above for why this file imports no partition at all, diff --git a/src/build/prepare/graph.cpp b/src/build/prepare/graph.cpp index 83992a2fd..05a5be271 100644 --- a/src/build/prepare/graph.cpp +++ b/src/build/prepare/graph.cpp @@ -1770,9 +1770,9 @@ step4b_acquire_dependency_source(PrepareState& state, WorklistItemCtx& ctx) { } report_flag_words_changes(*dep_manifest); fold_build_defines_into_flags(dep_manifest->buildConfig); - // The root's `abi.threads` reaches this dependency's C translation - // units here, as it does for a version dependency. - if (state.abiThreadsRendered) state.add_once(dep_manifest->buildConfig.cflags, "-pthread"); + // The root's ABI reaches this dependency's C translation units + // here, as it does for a version dependency. + render_abi(state.abi, dep_manifest->buildConfig, AbiPlace::Dependency); } else { auto loaded = spec.patches.empty() ? state.loadVersionDep(name, key.ns, key.shortName, spec.version) diff --git a/src/build/prepare/graph_edges.cpp b/src/build/prepare/graph_edges.cpp index f1e5fac42..d63bdafed 100644 --- a/src/build/prepare/graph_edges.cpp +++ b/src/build/prepare/graph_edges.cpp @@ -279,6 +279,9 @@ void define_usage_requirements(PrepareState& state) { changed = state.appendUniqueFlags(consumer.privateBuild.cxxflags, dependency.publicUsage.cxxflags) || changed; + changed = state.appendUniqueFlags(consumer.privateBuild.interfacePackages, + dependency.publicUsage.interfacePackages) + || changed; } if (edge.visibility == mcpp::modgraph::DependencyVisibility::Public || edge.visibility == mcpp::modgraph::DependencyVisibility::Interface) { @@ -294,6 +297,9 @@ void define_usage_requirements(PrepareState& state) { changed = state.appendUniqueFlags(consumer.publicUsage.cxxflags, dependency.publicUsage.cxxflags) || changed; + changed = state.appendUniqueFlags(consumer.publicUsage.interfacePackages, + dependency.publicUsage.interfacePackages) + || changed; } } } diff --git a/src/build/prepare/graph_load.cpp b/src/build/prepare/graph_load.cpp index 1bdf7490f..141224eba 100644 --- a/src/build/prepare/graph_load.cpp +++ b/src/build/prepare/graph_load.cpp @@ -1346,9 +1346,9 @@ step4a_load_version_dep_read_manifest(PrepareState& state, LoadVersionDepCtx& ct } report_flag_words_changes(*manifest); fold_build_defines_into_flags(manifest->buildConfig); - // The root's `abi.threads` reaches a dependency's C translation units - // here; its C++ units already receive it through the dialect flag set. - if (state.abiThreadsRendered) state.add_once(manifest->buildConfig.cflags, "-pthread"); + // The root's ABI reaches a dependency's C translation units here; its + // C++ units already receive it through the dialect flag set. + render_abi(state.abi, manifest->buildConfig, AbiPlace::Dependency); return std::pair{effRoot, std::move(*manifest)}; } diff --git a/src/build/prepare/host_graph.cpp b/src/build/prepare/host_graph.cpp index 290915e1a..a87e1e102 100644 --- a/src/build/prepare/host_graph.cpp +++ b/src/build/prepare/host_graph.cpp @@ -216,6 +216,12 @@ std::string features_of(const PrepareState& state, std::size_t d) { struct HostToolchain { std::string spec; std::string identity; + // A toolchain named by path, as its table (design 2026-11-27 §3.1.1): the + // build programs' workspace states it as `[workspace.toolchain]` and the + // sub-build reads it there, as any project reads its own. A string spec + // carries no table, and `path:` alone lost the sysroot, the launcher + // and the tools the project stated. + std::optional table; // The host graph's platform (SPEC-013 §6): the spelling the sub-build is // told it by and the target of this machine's architecture it serves. // Empty: the build programs are this machine's programs. @@ -243,9 +249,37 @@ std::expected host_toolchain(PrepareState& state) { t.spec = state.host_spec_for_build_program(); t.identity = std::format("{}|{}|{}|{}", t.spec, path_text(host->first), host->second.version, host->second.targetTriple); + // The table the build's own toolchain was named by, when the build + // programs use that toolchain: its fields and its programs' stamps are in + // the driver's identity (local_identity), which keys the programs too. + if (state.localToolchain && !state.localToolchain->configure + && t.spec == "path:" + state.localToolchain->path) { + t.table = *state.localToolchain; + t.identity += "|" + mcpp::toolchain::hash_string(host->second.driverIdent); + } return t; } +// `[workspace.toolchain]` for the build programs' workspace: this platform's +// entry, the table of the toolchain named by path, every path absolute (the +// manifest is written elsewhere than the project's). +std::string toolchain_table_text(const mcpp::manifest::LocalToolchain& lt) { + std::vector fields{"path = " + toml_string(lt.path)}; + if (!lt.prefix.empty()) fields.push_back("prefix = " + toml_string(lt.prefix)); + if (!lt.sysroot.empty()) fields.push_back("sysroot = " + toml_string(lt.sysroot)); + if (!lt.family.empty()) fields.push_back("family = " + toml_string(lt.family)); + if (!lt.launcher.empty()) fields.push_back("launcher = " + toml_string(lt.launcher)); + if (!lt.tools.empty()) { + std::string tools; + for (auto const& [role, program] : lt.tools) + tools += std::format("{}{} = {}", tools.empty() ? "" : ", ", role, toml_string(program)); + fields.push_back("tools = { " + tools + " }"); + } + std::string row; + for (auto const& f : fields) row += (row.empty() ? "" : ", ") + f; + return std::format("\n[workspace.toolchain]\n{} = {{ {} }}\n", kCurrentPlatform, row); +} + fs::path host_root(const PrepareState& state) { if (!state.overrides.host_programs_root.empty()) return state.overrides.host_programs_root; return state.workRoot / "target" / ".build-mcpp" / "host"; @@ -654,7 +688,7 @@ fs::path program_main(const PrepareState& state, const Program& p) { void write_group(PrepareState& state, const fs::path& dir, const std::vector& programs, const std::string& standard, const fs::path& enginePackage, - const std::string& toolchainSpec, const std::map& pins) { + const HostToolchain& tc, const std::map& pins) { std::string root = std::format( "# Written by mcpp {}: the build programs of {} (mcpp#797).\n" "# `mcpp build` here reproduces their compile; it is rewritten on every build.\n" @@ -666,6 +700,7 @@ void write_group(PrepareState& state, const fs::path& dir, const std::vector={}\"\n", mcpp::MCPP_VERSION); root += "\n[workspace.profile.build-program]\nopt = 0\ndebug = false\n"; + if (tc.table) root += toolchain_table_text(*tc.table); if (!state.m->indices.empty()) { root += "\n[workspace.indices]\n"; for (auto const& [name, idx] : state.m->indices) { @@ -724,8 +759,9 @@ void write_group(PrepareState& state, const fs::path& dir, const std::vector sub.work_dir = dir; sub.target_triple = ""; sub.host_target = true; - sub.toolchain = tc.spec; + sub.toolchain = tc.table ? std::string() : tc.spec; // Under a host platform: the platform's target of this architecture, and // its toolchain by the platform's own pin. if (!tc.platform.empty()) { @@ -1342,7 +1378,7 @@ ensure_build_programs(PrepareState& state, const std::vector& packa // Described, not built: `mcpp emit build-database` lists the graph // of programs that are current too. if (state.overrides.describes()) { - write_group(state, dir, programs, standard, *enginePackage, tc->spec, pins); + write_group(state, dir, programs, standard, *enginePackage, *tc, pins); if (auto r = build_group(state, dir, programs, {}, *tc, pins); !r) mcpp::log::verbose("host-graph", r.error()); } @@ -1356,7 +1392,7 @@ ensure_build_programs(PrepareState& state, const std::vector& packa return std::unexpected(r.error()); } - write_group(state, dir, programs, standard, *enginePackage, tc->spec, pins); + write_group(state, dir, programs, standard, *enginePackage, *tc, pins); const auto began = std::chrono::steady_clock::now(); for (auto const* p : stale) mcpp::build::progress::program_compiling(qualified(manifest_of(state, p->index)), diff --git a/src/build/prepare/local_toolchain.cpp b/src/build/prepare/local_toolchain.cpp index c4416e02b..df368a587 100644 --- a/src/build/prepare/local_toolchain.cpp +++ b/src/build/prepare/local_toolchain.cpp @@ -107,10 +107,12 @@ read_statement(const std::vector& lines, std::string& spec, } // What makes a toolchain named by path a different toolchain without the -// version changing: a rebuilt trunk driver, a replaced linker. The path, size -// and modification time of each program, not their bytes -- a driver is -// hundreds of megabytes and this is read on every prepare. -std::string local_identity(const mcpp::toolchain::Toolchain& tc) { +// version changing: a rebuilt trunk driver, a replaced linker, another +// launcher. Every field of the table and the path, size and modification time +// of each program, not their bytes -- a driver is hundreds of megabytes and +// this is read on every prepare. The build programs' graph is keyed by the +// same text (host_graph.cpp), so the two kinds of compile change together. +std::string local_identity(const mcpp::toolchain::Toolchain& tc, const mcpp::manifest::LocalToolchain& lt) { std::uint64_t h = 1469598103934665603ull; auto mix = [&](std::string_view s) { for (unsigned char c : s) { h ^= c; h *= 1099511628211ull; } @@ -126,6 +128,9 @@ std::string local_identity(const mcpp::toolchain::Toolchain& tc) { stamp(tc.binaryPath); for (auto const& [role, p] : tc.toolOverrides) { mix(role); stamp(p); } mix(tc.toolPrefix); + mix(lt.family); + mix(lt.sysroot); + if (!tc.launcher.empty()) stamp(tc.launcher); return std::format("{:016x}", h); } @@ -341,7 +346,7 @@ std::expected step2_apply_local_toolchain(PrepareState& state } // A stated sysroot is the target's base, resolved with every other // statement of it (base.cpp), not here. - tc.driverIdent += "\nmcpp-local-toolchain " + local_identity(tc); + tc.driverIdent += "\nmcpp-local-toolchain " + local_identity(tc, lt); // Announced beside the resolution, with what the probe found. auto d = state.localToolchainOrigin; d.subject = "toolchain.build"; diff --git a/src/build/prepare/package_root.cpp b/src/build/prepare/package_root.cpp index 22fe48c68..73ee90d3b 100644 --- a/src/build/prepare/package_root.cpp +++ b/src/build/prepare/package_root.cpp @@ -117,6 +117,11 @@ std::expected makePackageRoot( for (auto const& d : pkg.privateBuild.includeDirs) if (std::ranges::find(privateExpanded, d) == privateExpanded.end()) pkg.publicUsage.includeDirs.push_back(d); + if (!pkg.publicUsage.includeDirs.empty() || !pkg.publicUsage.includeDirsAfter.empty()) + pkg.publicUsage.interfacePackages.push_back( + manifest.package.namespace_.empty() || manifest.package.name.starts_with(manifest.package.namespace_ + ".") + ? manifest.package.name + : manifest.package.namespace_ + "." + manifest.package.name); // AN ENTRY THAT WITHHOLDS NOTHING IS REPORTED, because the way // it fails is the very defect this key exists to prevent: a diff --git a/src/build/prepare/records.cpp b/src/build/prepare/records.cpp index 954b68c4c..23e8a91ae 100644 --- a/src/build/prepare/records.cpp +++ b/src/build/prepare/records.cpp @@ -883,6 +883,9 @@ void step13_resolution_json(PrepareState& state, BuildContext& ctx) { }; put(ctx.tc.binaryPath); for (auto const& [role, p] : ctx.tc.toolOverrides) put(p); + // The launcher prefixes every compile, the build programs' too + // (design 2026-11-27 §3.1.1): it is one of the programs. + if (!ctx.tc.launcher.empty()) put(ctx.tc.launcher); } ec.clear(); } diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index a361c1e7f..bb6dd13f7 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -677,7 +677,9 @@ struct PrepareState { std::function resolvedAccel; std::function cfgCtx; std::optional targetPlatform; - bool abiThreadsRendered = false; + // The root's ABI (render_abi): resolved in the toolchain phase, rendered + // into the root there and into each dependency where it is loaded. + AbiRecord abi; std::function&, std::string_view)> add_once; std::optional tc; bool firstRunNeedsTargetPass = false; diff --git a/src/build/prepare/toolchain.cpp b/src/build/prepare/toolchain.cpp index d82d2cdbd..b0519c961 100644 --- a/src/build/prepare/toolchain.cpp +++ b/src/build/prepare/toolchain.cpp @@ -1454,23 +1454,18 @@ static std::expected step1_device_axis_and_layer_merge(Prepar // For hosted targets that are not PE. On PE the MSVC runtime is always // multithreaded and mingw-w64's threading model belongs to its payload; a // freestanding target has no thread library to select. - state.abiThreadsRendered = [&] { - if (!state.m->buildConfig.abiThreads) return false; + state.abi = {}; + { const auto abiTriple = mcpp::toolchain::triple::parse( state.overrides.target_triple.empty() ? mcpp::toolchain::triple::host_triple().str() : state.overrides.target_triple); - return abiTriple && !abiTriple->is_pe() && !abiTriple->is_freestanding(); - }(); + if (state.m->buildConfig.abiThreads && abiTriple && !abiTriple->is_pe() && !abiTriple->is_freestanding()) + state.abi.threads = "-pthread"; + } state.add_once = [](std::vector& v, std::string_view flag) { if (std::ranges::find(v, flag) == v.end()) v.emplace_back(flag); }; - if (state.abiThreadsRendered) { - state.add_once(state.m->buildConfig.dialectCxxflags, "-pthread"); - state.add_once(state.m->buildConfig.cflags, "-pthread"); - state.add_once(state.m->buildConfig.ldflags, "-pthread"); - state.add_once(state.m->buildConfig.graphLdflags, "-pthread"); - } // `[target..abi] exceptions` -- design 2026-09-12 (the UI // framework record), section 2.1, A1: the second `abi` member, the // ROOT's statement, rendered once. Reaches the dialect flag set (every @@ -1500,21 +1495,21 @@ static std::expected step1_device_axis_and_layer_merge(Prepar if (auto const* row = mcpp::toolchain::target::find_row(t->str()); row && !row->exceptions.empty()) { state.m->buildConfig.abiExceptions = true; state.m->buildConfig.abiExceptionsModel = std::string(row->exceptions); - // The long jump follows WebAssembly exception handling (D6), - // stated for the C translation units too, which do not read - // the C++ flag; under another model it is the SDK's default. - if (!state.m->buildConfig.abiLongjmpDeclared && row->exceptions == "wasm") { - state.m->buildConfig.abiLongjmpDeclared = true; - state.m->buildConfig.abiLongjmpModel = "wasm"; - } } const bool abiExceptionsRendered = state.m->buildConfig.abiExceptions && emscripten; - if (abiExceptionsRendered) { - const char* flag = state.m->buildConfig.abiExceptionsModel == "wasm" + if (abiExceptionsRendered) + state.abi.exceptions = state.m->buildConfig.abiExceptionsModel == "wasm" ? "-fwasm-exceptions" : "-fexceptions"; - state.add_once(state.m->buildConfig.dialectCxxflags, flag); - state.add_once(state.m->buildConfig.ldflags, flag); - state.add_once(state.m->buildConfig.graphLdflags, flag); + // THE LONG JUMP FOLLOWS WEBASSEMBLY EXCEPTION HANDLING when unstated (D6), + // whether the row or the project stated the exception model: emcc's + // `-fwasm-exceptions` alone leaves `setjmp` on the JavaScript model, and a + // C unit's `longjmp` then fails the link (`undefined symbol: + // emscripten_longjmp`; measured, M3). Under another model it is the SDK's + // default, which follows the exception model. + if (abiExceptionsRendered && !state.m->buildConfig.abiLongjmpDeclared + && state.m->buildConfig.abiExceptionsModel == "wasm") { + state.m->buildConfig.abiLongjmpDeclared = true; + state.m->buildConfig.abiLongjmpModel = "wasm"; } // `[target..abi] longjmp` -- the third member (2026.11.12.1): // how `sigsetjmp`/`siglongjmp` cross the WebAssembly boundary. The flag @@ -1550,13 +1545,10 @@ static std::expected step1_device_axis_and_layer_merge(Prepar state.m->buildConfig.abiLongjmpModel, state.m->buildConfig.abiExceptionsModel.empty() ? std::string("js") : state.m->buildConfig.abiExceptionsModel)); - const std::string flag = "-sSUPPORT_LONGJMP=" + state.abi.longjmp = "-sSUPPORT_LONGJMP=" + (wasmLongjmp ? std::string("wasm") : std::string("emscripten")); - state.add_once(state.m->buildConfig.dialectCxxflags, flag); - state.add_once(state.m->buildConfig.cflags, flag); - state.add_once(state.m->buildConfig.ldflags, flag); - state.add_once(state.m->buildConfig.graphLdflags, flag); } + render_abi(state.abi, state.m->buildConfig, AbiPlace::Root); // #851: emcc runs wasm-opt and minifies the JavaScript launcher AT THE // LINK, from the optimisation level the link is given; a link without // one is -O0 whatever the compiles were. The profile's level reaches it. diff --git a/src/build/prepare_inputs.cppm b/src/build/prepare_inputs.cppm index d743331fe..57ff74ae4 100644 --- a/src/build/prepare_inputs.cppm +++ b/src/build/prepare_inputs.cppm @@ -32,6 +32,37 @@ import mcpp.ui; export namespace mcpp::build { +// THE ROOT'S ABI, ONE RECORD (design 2026-11-27 §3.2.2, mcpp#1029): the three +// `[target..abi]` members as the graph is built with them, resolved +// once -- the long-jump model follows the exception model when unstated, +// whether that model came from the target row or from the project. Each field +// is the flag the member renders, empty when it renders none. +struct AbiRecord { + std::string threads; // `-pthread` + std::string exceptions; // `-fwasm-exceptions` | `-fexceptions` + std::string longjmp; // `-sSUPPORT_LONGJMP=` +}; +// Where a record is rendered: the root package (the graph's dialect flag set, +// its C flags, the link) or a dependency (its C flags: its C++ units read the +// dialect set, and the link is the root's). +enum class AbiPlace { Root, Dependency }; +// The one renderer. A member that changes the code a C compiler emits +// (`threads`, `longjmp`) reaches every package's C units; `exceptions` has no +// C meaning and reaches the C++ units and the link. +inline void render_abi(const AbiRecord& abi, mcpp::manifest::BuildConfig& bc, AbiPlace place) { + auto add = [](std::vector& v, const std::string& flag) { + if (!flag.empty() && std::ranges::find(v, flag) == v.end()) v.push_back(flag); + }; + for (auto const* flag : {&abi.threads, &abi.longjmp}) add(bc.cflags, *flag); + if (place == AbiPlace::Dependency) return; + for (auto const* flag : {&abi.threads, &abi.exceptions, &abi.longjmp}) { + add(bc.dialectCxxflags, *flag); + add(bc.ldflags, *flag); + add(bc.graphLdflags, *flag); + } +} + + // ── L1 platform-conditional config: cfg() predicate evaluation ────────────── // Context = the RESOLVED target's coordinates. A `[target.'cfg(...)'.build]` // predicate is evaluated against this (target triple for a cross build, host diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index 1a6078bc2..e738271fe 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -253,6 +253,8 @@ enum class Code { // `mcpp new --vcs git` made the project, and `git init` could not be // done: git is not on PATH, or it failed. The project is kept. VcsUnavailable, + // A test program and an executable target of one package write one file. + TestOutputCollision, Other, // a refusal that has not been given a code yet }; @@ -329,6 +331,7 @@ constexpr std::string_view name(Code c) { case Code::LockWaitExceeded: return "lock-wait-exceeded"; case Code::LockUnavailable: return "lock-unavailable"; case Code::VcsUnavailable: return "vcs-unavailable"; + case Code::TestOutputCollision: return "test-output-collision"; case Code::Other: return "other"; } return "other"; diff --git a/src/build/test_targets.cppm b/src/build/test_targets.cppm index 38d19094c..a79a4eea9 100644 --- a/src/build/test_targets.cppm +++ b/src/build/test_targets.cppm @@ -224,7 +224,12 @@ discover_test_targets(const std::filesystem::path& manifestRoot, } result.targets.reserve(testFiles.size()); - std::map seenNames; + // Names are compared as the file system that will hold the programs + // compares them (plan's output_key): where it does not distinguish case, + // `Math` and `math` are one program. + const bool foldCase = folds_case(packageRoot); + struct Seen { std::string name; std::filesystem::path main; }; + std::map seenNames; for (auto const& [file, discoverBase] : testFiles) { auto lexical_relative = [&](const std::filesystem::path& base, std::string_view boundary) @@ -252,12 +257,13 @@ discover_test_targets(const std::filesystem::path& manifestRoot, auto name = named != programNameOf.end() ? named->second : directoryProgram ? testRelative->parent_path().generic_string() : testRelative->replace_extension("").generic_string(); - if (auto [it, fresh] = seenNames.emplace(name, *mainRelative); !fresh) { + if (auto [it, fresh] = seenNames.emplace(output_key(name, foldCase), Seen{name, *mainRelative}); !fresh) { return std::unexpected(std::format( - "duplicate test name '{}': '{}' and '{}' map to the same name " + "duplicate test name '{}': '{}' and '{}' map to the same name{} " "(a test's name is its path relative to the fixed directory of " "the [test] discover glob that found it)", - name, it->second.generic_string(), mainRelative->generic_string())); + name, it->second.main.generic_string(), mainRelative->generic_string(), + it->second.name == name ? "" : " on a file system that does not distinguish case")); } mcpp::manifest::Target target; @@ -300,7 +306,7 @@ discover_test_targets(const std::filesystem::path& manifestRoot, return std::unexpected(std::format( "test '{}' ({}) is a directory of test '{}' ({}): a test's name is the path of its " "program, and one cannot be both; move one of them", - it->first, it->second.generic_string(), next->first, next->second.generic_string())); + it->second.name, it->second.main.generic_string(), next->second.name, next->second.main.generic_string())); } return result; } diff --git a/src/explain.cppm b/src/explain.cppm index 01548b001..2c4e11197 100644 --- a/src/explain.cppm +++ b/src/explain.cppm @@ -356,6 +356,12 @@ constexpr Entry kEntries[] = { {"vcs-unavailable", Kind::Reason, "`mcpp new` was asked for a repository and git cannot run", "Install git, or create the project without a repository: --vcs none."}, + {"test-output-collision", Kind::Reason, + "a test program and an executable target of one package write one file; the message names the test's file or directory to rename", + "Rename the test's file or directory the message names (tests/app.cpp to\n" + "tests/app_test.cpp, tests/app/ to tests/app_test/), or give the executable\n" + "target another name. Where the file system does not distinguish case,\n" + "names that differ only in case are one file."}, {"other", Kind::Reason, "a refusal whose branch has not been given a token yet", "Read the message: it names the cause and the remedy. Report the case so\n" diff --git a/src/modgraph/scanner.cppm b/src/modgraph/scanner.cppm index bfaf39284..d450fb0c3 100644 --- a/src/modgraph/scanner.cppm +++ b/src/modgraph/scanner.cppm @@ -150,6 +150,12 @@ struct UsageRequirements { std::vector asmflags; std::vector ldflags; std::vector modules; + // The packages whose include directories this usage carries (qualified + // names), the package itself among them when it publishes any. A unit + // compiled with a package's headers references its symbols directly -- + // an inline function, a template -- so the link follows the compile + // (design 2026-11-27 §3.2.1, mcpp#1031). + std::vector interfacePackages; }; // Scan multiple packages (primary + path-based deps) into one combined Graph. diff --git a/tests/e2e/build/link.cpp b/tests/e2e/build/link.cpp index dcfb99371..ea179f185 100644 --- a/tests/e2e/build/link.cpp +++ b/tests/e2e/build/link.cpp @@ -600,6 +600,31 @@ platform = { path = "../plat" } expect(fatal(fs::exists(d / "app.data"))) << "a file the row does not name as a companion was removed"; expect(fatal(s::read_file(d / "app.js") == "new")) << "the linker did not run"; }; + + "1031 the link follows the compile across shared libraries"_test[s::elf] = [] { + // Design 2026-11-27 §3.2.1 (mcpp#1031): `app` depends on the shared library `lowb`, whose + // public header calls the shared library `lowc` from an inline function; `app`'s object then + // references `lowc` directly. Every package whose interface reaches a unit's compile has its + // shared image on that unit's link line, so the program links and runs; the import + // closure of a module counts as the include directories do. + const auto dir = s::case_dir(); + s::project c(dir / "lowc", { + {"mcpp.toml", "[package]\nname = \"lowc\"\nversion = \"0.1.0\"\n\n[targets.lowc]\nkind = \"shared\"\n\n[build]\ninclude_dirs = [\"include\"]\n"}, + {"include/c.h", "#pragma once\nint c_value();\n"}, + {"src/c.cpp", "#include \"c.h\"\nint c_value() { return 41; }\n"}, + }); + s::project b(dir / "lowb", { + {"mcpp.toml", "[package]\nname = \"lowb\"\nversion = \"0.1.0\"\n\n[targets.lowb]\nkind = \"shared\"\n\n[build]\ninclude_dirs = [\"include\"]\n\n[dependencies]\nlowc = { path = \"../lowc\" }\n"}, + {"include/b.h", "#pragma once\n#include \"c.h\"\ninline int b_value() { return c_value() + 1; }\nint b_marker();\n"}, + {"src/b.cpp", "#include \"b.h\"\nint b_marker() { return 1; }\n"}, + }); + s::project app(dir / "app", { + {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\nlowb = { path = \"../lowb\" }\n"}, + {"src/main.cpp", "#include \"b.h\"\nint main() { return b_value() == 42 && b_marker() == 1 ? 0 : 1; }\n"}, + }); + auto r = app.mcpp({"run"}); + expect(fatal(e2e::succeeded(r))) << "the program over lowb and lowc did not link or run: " << s::text(r); + }; }}; } // namespace diff --git a/tests/e2e/test/collision.cpp b/tests/e2e/test/collision.cpp new file mode 100644 index 000000000..eeb9eb1a5 --- /dev/null +++ b/tests/e2e/test/collision.cpp @@ -0,0 +1,79 @@ +// A test program and an executable target that would write one file (mcpp#1028, design 2026-11-27 +// §3.2.3): `mcpp test` refuses while planning, with `[test-output-collision]`, naming the test's file +// and an example name; the program `mcpp build` wrote is left as it was; after the rename the tests +// run. The same holds for a workspace member. +import std; +import mcpplibs.mtest; +import mcpp.test.support; + +using namespace mcpplibs::mtest; +namespace s = mcpp::test::support; +namespace fs = std::filesystem; + +namespace { + +constexpr std::string_view kProgram = "import std;\nint main() { std::println(\"the program\"); }\n"; +constexpr std::string_view kTest = "int main() { return 0; }\n"; + +// The one program `name` below a `bin/` directory of the project's target directory (a member's +// programs are in `bin//`), outside the build programs'. +std::optional program(const s::project& p, std::string_view name) { + for (const auto& f : s::find_files(p.at("target"), std::format("^{}$", name))) + if (!f.generic_string().contains("/.build-mcpp/") && f.generic_string().contains("/bin/") + && fs::is_regular_file(f)) + return f; + return std::nullopt; +} + +// Build, then test: refused naming `testFile` (as its package names it), the built program +// unchanged; renamed, the tests run. `memberDir` is the package's directory in the project. +void refuse_then_rename(s::project& p, std::string_view program_name, std::string_view package, + const std::string& testFile, const fs::path& memberDir, + std::vector selection) { + auto build = selection; + build.insert(build.begin(), "build"); + expect(fatal(e2e::succeeded(p.mcpp(build)))) << "the build failed"; + const auto built = program(p, program_name); + expect(fatal(built.has_value())) << "no program " << program_name; + const auto before = s::read_file(*built); + + auto test = selection; + test.insert(test.begin(), "test"); + e2e::expect_diagnostic("\\[test-output-collision\\]"); + const auto refused = p.mcpp(test); + expect(fatal(!e2e::succeeded(refused))) << "the colliding test ran: " << s::text(refused); + const auto text = s::text(refused); + expect(e2e::contains(text, std::format("package '{}'", package))) << text; + const auto renamed = fs::path(testFile).parent_path() / (fs::path(testFile).stem().string() + "_test.cpp"); + expect(e2e::contains(text, std::format("rename the test's file {}, e.g. to {}", testFile, renamed.generic_string()))) + << text; + expect(s::read_file(*built) == before) << "the refused test overwrote the program"; + + fs::rename(p.at((memberDir / testFile).generic_string()), p.at((memberDir / renamed).generic_string())); + const auto ran = p.mcpp(test); + expect(e2e::succeeded(ran)) << "the renamed test did not run: " << s::text(ran); + expect(s::read_file(*built) == before) << "the renamed test overwrote the program"; +} + +E2E collision{"test-output-collision", [] { + "a test named as the package's program is refused, and runs once renamed"_test = [] { + s::project app(s::case_dir() / "app", { + {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n"}, + {"src/main.cpp", std::string(kProgram)}, + {"tests/app.cpp", std::string(kTest)}, + }); + refuse_then_rename(app, "app", "app", "tests/app.cpp", "", {}); + }; + + "a member's test named as the member's program is refused, and runs once renamed"_test = [] { + s::project ws(s::case_dir() / "ws", { + {"mcpp.toml", "[workspace]\nmembers = [\"tool\"]\n"}, + {"tool/mcpp.toml", "[package]\nname = \"tool\"\nversion = \"0.1.0\"\n"}, + {"tool/src/main.cpp", std::string(kProgram)}, + {"tool/tests/tool.cpp", std::string(kTest)}, + }); + refuse_then_rename(ws, "tool", "tool", "tests/tool.cpp", "tool", {"-p", "tool"}); + }; +}}; + +} // namespace diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index ce759beb2..7bfd00e01 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -125,6 +125,46 @@ E2E custom{"custom", s::home_fixture, [] { } }; + "the table of a toolchain named by path reaches the build programs"_test[s::llvm][s::unix_shell][s::symlink] = [] { + // Design 2026-11-27 §3.1.1 (mcpp#1034): a build program is compiled by the toolchain the + // project names by path with every field of its table, so the launcher and the stated + // driver see the build program's compile as they see the project's; a changed launcher + // rebuilds both. + 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 log = work / "calls.log"; + const auto launcher = work / "launcher"; + s::write_executable(launcher, std::format("#!/bin/sh\necho \"launcher $*\" >> '{}'\nexec \"$@\"\n", log.string())); + const auto driver = work / "driver" / "clang++"; + fs::create_directories(driver.parent_path()); + s::write_executable(driver, std::format("#!/bin/sh\necho \"driver $*\" >> '{}'\nexec '{}/bin/clang++' \"$@\"\n", + log.string(), T.string())); + s::project app(work / "app", {{"src/main.cpp", "int main() { return 0; }\n"}, + {"build.mcpp", "int main() { return 0; }\n"}}); + app.write("mcpp.toml", std::format( + "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[toolchain]\n" + "default = {{ path = \"{}\", launcher = \"{}\", tools = {{ cxx = \"{}\" }} }}\n", + T.string(), launcher.string(), driver.string())); + const s::options o{.env = {{"NO_COLOR", "1"}}}; + auto r = app.mcpp({"build"}, o); + expect(fatal(e2e::succeeded(r))) << s::text(r); + auto calls = s::read_file(log); + for (const std::string_view who : {"launcher", "driver"}) + for (const std::string_view unit : {"build.mcpp", "main.cpp"}) + expect(s::has_line(calls, std::format("^{} .*{}", who, literal(unit)))) + << "the compile of " << unit << " did not go through the " << who << ":\n" << calls; + // Another launcher is another toolchain: the build program is compiled again. + s::write_executable(launcher, std::format("#!/bin/sh\necho \"launcher2 $*\" >> '{}'\nexec \"$@\"\n", log.string())); + fs::last_write_time(launcher, fs::file_time_type::clock::now() + std::chrono::minutes{1}); + r = app.mcpp({"build"}, o); + expect(fatal(e2e::succeeded(r))) << s::text(r); + calls = s::read_file(log); + expect(s::has_line(calls, "^launcher2 .*build\\.mcpp")) << "a changed launcher did not rebuild the build program:\n" << calls; + }; + "876 toolchain phase"_test[s::llvm][s::unix_shell][s::symlink] = [] { // `[toolchain] default = { configure = "build.mcpp" }` (mcpp#755): the build program's // toolchain phase states the toolchain (a path, reported with its origin; a managed spec, diff --git a/tests/e2e/web/emscripten.cpp b/tests/e2e/web/emscripten.cpp index 41978016c..e66e4e9e9 100644 --- a/tests/e2e/web/emscripten.cpp +++ b/tests/e2e/web/emscripten.cpp @@ -400,6 +400,45 @@ int main(void) { expect(fatal(!r)) << "longjmp = \"wasm\" on a Linux row was accepted: " << s::text(r); expect(fatal(e2e::contains(s::text(r), "not an Emscripten row"))) << "the refusal does not name the row's own os: " << s::text(r); }; + + "1029 the long jump follows the exception model in every package"_test[s::elf] = [] { + // Design 2026-11-27 §3.2.2 (mcpp#1029), the seven variants of M3: a C unit that calls + // `setjmp` in the root package or in a path dependency, under the row's default, under + // `exceptions = "wasm"` alone, under both members stated, and under `exceptions = "js"`. + // Every one links and runs: the root's ABI is rendered into every package's C units, and + // an unstated long-jump model follows the exception model whoever stated it. + if (!have_emsdk() || !s::on_path("node")) skip("1029 -- no emsdk payload or node on this machine"); + const std::string jumper = "#include \nstatic jmp_buf env;\n" + "static void away(void) { longjmp(env, 1); }\n" + "int jumps(void) { if (setjmp(env) == 0) { away(); return 0; } return 1; }\n"; + const std::string program = "extern \"C\" int jumps();\nint main() { return jumps() == 1 ? 0 : 1; }\n"; + struct Variant { std::string_view name; bool inDependency; std::string_view abi; }; + const std::vector variants{ + {"root, row default", false, ""}, + {"root, both stated", false, "exceptions = \"wasm\"\nlongjmp = \"wasm\"\n"}, + {"root, exceptions alone", false, "exceptions = \"wasm\"\n"}, + {"dependency, row default", true, ""}, + {"dependency, exceptions alone", true, "exceptions = \"wasm\"\n"}, + {"dependency, both stated", true, "exceptions = \"wasm\"\nlongjmp = \"wasm\"\n"}, + {"dependency, js", true, "exceptions = \"js\"\n"}, + }; + for (const auto& v : variants) { + const auto dir = s::case_dir() / std::format("v{}", &v - variants.data()); + std::string manifest = "[package]\nname = \"lj\"\nversion = \"0.1.0\"\n\n[target.wasm32-emscripten]\nrunner = [\"node\"]\n"; + if (!v.abi.empty()) manifest += std::format("\n[target.'cfg(os = \"emscripten\")'.abi]\n{}", v.abi); + s::project app(dir / "app", {{"src/main.cpp", program}}); + if (v.inDependency) { + s::project dep(dir / "jumper", {{"mcpp.toml", "[package]\nname = \"jumper\"\nversion = \"0.1.0\"\n\n[targets.jumper]\nkind = \"lib\"\n"}, + {"src/jumper.c", jumper}}); + manifest += "\n[dependencies]\njumper = { path = \"../jumper\" }\n"; + } else { + app.write("src/jumper.c", jumper); + } + app.write("mcpp.toml", manifest); + const auto r = app.mcpp({"run", "--target", "wasm32-emscripten"}); + expect(e2e::succeeded(r)) << v.name << ": " << s::text(r); + } + }; }}; } // namespace diff --git a/tests/unit/test_abi.cpp b/tests/unit/test_abi.cpp index 7459b70f1..787c1e622 100644 --- a/tests/unit/test_abi.cpp +++ b/tests/unit/test_abi.cpp @@ -324,3 +324,42 @@ mt = { exceptions = true } expect(eq(lin.targetFeatureRequiresAbiThreads.at("mt").front(), "cfg(linux)")); expect(!lin.targetFeatureRequiresAbiExceptions.contains("mt")); }}; + +// Each ABI member, rendered into the six places of a graph (the root package and a dependency, +// each in its C units, its C++ units and the link), by the one renderer (design 2026-11-27 §3.2.2, +// mcpp#1029). A C++ unit of any package reads the graph's dialect set, which the root carries; the +// link is the root's. A member added to the record and missed in one place fails here. +UTest abi_members_reach_every_place{"Abi/MembersReachEveryPlace", [] { + using mcpp::build::AbiPlace; + struct Row { + std::string_view member; + mcpp::build::AbiRecord record; + std::string flag; + bool inC; // `exceptions` has no C meaning + }; + const std::vector rows{ + {"threads", {.threads = "-pthread"}, "-pthread", true}, + {"exceptions", {.exceptions = "-fwasm-exceptions"}, "-fwasm-exceptions", false}, + {"longjmp", {.longjmp = "-sSUPPORT_LONGJMP=wasm"}, "-sSUPPORT_LONGJMP=wasm", true}, + }; + auto has = [](const std::vector& v, const std::string& f) { return std::ranges::contains(v, f); }; + for (const auto& row : rows) { + mcpp::manifest::BuildConfig root, dependency; + mcpp::build::render_abi(row.record, root, AbiPlace::Root); + mcpp::build::render_abi(row.record, dependency, AbiPlace::Dependency); + mcpp::build::render_abi(row.record, dependency, AbiPlace::Dependency); // once, however often + const std::vector> places{ + {"root C units", has(root.cflags, row.flag), row.inC}, + {"root C++ units", has(root.dialectCxxflags, row.flag), true}, + {"root link", has(root.ldflags, row.flag) && has(root.graphLdflags, row.flag), true}, + {"dependency C units", has(dependency.cflags, row.flag), row.inC}, + {"dependency C++ units (the graph's dialect set)", has(root.dialectCxxflags, row.flag), true}, + {"dependency link (the root's)", has(root.graphLdflags, row.flag), true}, + }; + for (const auto& [place, present, wanted] : places) + expect(present == wanted) << row.member << " in " << place << ": " << (present ? "present" : "absent"); + expect(std::ranges::count(dependency.cflags, row.flag) <= 1) << row.member << " rendered twice"; + expect(dependency.dialectCxxflags.empty() && dependency.ldflags.empty()) + << row.member << ": a dependency carries no dialect set or link flags of its own"; + } +}}; diff --git a/tests/unit/test_test_targets.cpp b/tests/unit/test_test_targets.cpp index 7c6180276..4b1dc57d1 100644 --- a/tests/unit/test_test_targets.cpp +++ b/tests/unit/test_test_targets.cpp @@ -380,3 +380,20 @@ programs = "directory" if (auto&& failed = expect(fatal(moved.has_value())); !failed) failed << moved.error(); expect(eq(moved->targets.size(), 3u)); }}; + +UTest output_names_compare_as_the_file_system_does{"TestTargets/OutputNamesCompareAsTheFileSystemDoes", [] { + // Design 2026-11-27 §3.2.3 point 4: two output names are one file where the file system does + // not distinguish case, and two where it does; the answer is asked of the directory. + expect(mcpp::build::output_key("bin/App", true) == mcpp::build::output_key("bin/app", true)); + expect(mcpp::build::output_key("bin/App", false) != mcpp::build::output_key("bin/app", false)); + expect(mcpp::build::output_key("bin/./tests/../app", false) == "bin/app"); + const auto dir = std::filesystem::temp_directory_path() / std::format("mcpp-case-{:x}", std::random_device{}()); + std::filesystem::create_directories(dir); + { + std::ofstream(dir / "probe-name"); + } + std::error_code ec; + const bool measured = std::filesystem::exists(dir / "PROBE-NAME", ec); + expect(mcpp::build::folds_case(dir) == measured) << "the probe does not agree with the directory"; + std::filesystem::remove_all(dir, ec); +}}; From 3b7cf8a5d95047f2de6ee7db2b99d0047e478e90 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 01:18:52 +0900 Subject: [PATCH 07/36] The std module source is taken inside the toolchain's tree and asked with the build's words A clang driver's answers about its std module source (the module manifest, the directory of libc++.a) are taken only inside the toolchain's tree -- the directory a path-named toolchain names, or the one above a managed driver's bin/ and the one its driver resolves to -- and the target base. Identification holds a managed driver's answers to its tree; a build asks again with the words the module's precompile is given on a cross build, or when the answer it has lies outside its roots. A compiler of the host is not held, and [build] allow_host_libs takes any answer. When no answer is taken, import std is refused naming each answer not taken (mcpp#1039). One function asks a driver where a file is (ask_driver); the runtime archive question goes through it as well. --- .../2026-11-27-ecosystem-boundary-design.md | 8 ++ CHANGELOG.md | 6 ++ docs/20-toolchains.md | 11 +++ docs/zh/20-toolchains.md | 8 ++ modules/toolchain-model/src/model.cppm | 4 + src/build/prepare/retarget.cpp | 65 +++++++++++++++++ src/build/prepare/scan.cpp | 7 +- src/build/prepare/state.cppm | 3 + src/build/prepare/toolchain_resolver.cpp | 1 + src/toolchain/clang.cpp | 73 ++++++++++++++----- src/toolchain/clang.cppm | 18 ++++- src/toolchain/probe.cppm | 56 ++++++++++++++ tests/e2e/toolchain/custom.cpp | 55 ++++++++++++++ 13 files changed, 294 insertions(+), 21 deletions(-) diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index 0cdebaf93..cf85ff739 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -300,6 +300,14 @@ C flags 通用键;不为追随旧发行版而增加旧版编译器载荷;不 报告的两条建议中,第一条(带上目标)就是第 1 条;第二条(标准库为某一实现时拒绝另一实现的清单)不采用:它按实现的 名字判定,而第 2 条按根判定,对任何标准库成立,也覆盖归档与运行库的同类答案。 +**实现(2026-12-05)。** 与上文两处不同。其一,识别阶段仍不带目标地提问,因为不针对目标的查询(`mcpp toolchain list`) +要一个答案;它的答案对托管的工具链限定在工具链的树内,报告中的宿主清单因此在识别时就不被采用,第三个探测找到 NDK +自带的 `std.cppm`。构建在两种情形下带着词再问一次:交叉构建(词即标准库模块预编译所带的词,由同一个函数产生), +以及已有的答案落在根外。其二,宿主的编译器(既非托管、也非以路径点名)不受根的限定,与封闭链接的检查一致:选用它 +就是对宿主文件的许可。向驱动询问文件位置的函数(`ask_driver`)为标准库模块与运行库归档的问题共用;基底的探测 +(`crt1.o` 等)本来就带着基底的词,经它自己的、不缓存的函数提问,因为一个被陈述的目录可以在两次构建之间多出一个 +文件,而 `ask_driver` 的答案是缓存的。 + 报告另记一个上游事实:该载荷自带的模块清单里相对路径多了一层,按它找不到文件。mcpp 已对「清单指向不存在的文件」 转向下一个探测,行为不变;这个事实登记进上游缺陷登记表(mcpp#1027)。 diff --git a/CHANGELOG.md b/CHANGELOG.md index d32c61692..0a649a426 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,6 +79,12 @@ follows `exceptions = "wasm"` whether the row or the project stated it. A dependency's C unit that calls `setjmp` on `wasm32-emscripten` links under the row's default, under `exceptions = "wasm"` alone and with both members stated (mcpp#1029). +- The `std` module source a clang driver names is taken only inside the toolchain's tree or the + target base, and a cross build asks for it with the words its precompile is given. A driver that + names the host's `libstdc++.modules.json` (an NDK clang asked without `--target`, on a host whose + GCC ships one) no longer hands the host's `bits/std.cc` to the precompile; the next question finds + the tree's own `std.cppm`. When no answer is taken, `import std` is refused naming each answer not + taken (mcpp#1039). - A version stated through a local table of its descriptor (`["1.2.1"] = versions["1.2.1"]`) is read through the table. It was read as revision 0, so a package whose entry states revision 1 was reinstalled by every build and shown as `Downloading`. A version written in a form mcpp does diff --git a/docs/20-toolchains.md b/docs/20-toolchains.md index d6428d7dd..126b76b28 100644 --- a/docs/20-toolchains.md +++ b/docs/20-toolchains.md @@ -1415,6 +1415,17 @@ Each module is compiled once per configuration into the global cache, and that imports `std.compat` from a library that does not provide it is refused before any compile, naming the library. +A clang driver is asked where its `std` module source is: the module manifest +(`-print-library-module-manifest-path`), then the directory of `libc++.a`, then +`share/libc++/v1/` beside the driver. A build asks with the words the module's +precompile is given (its `--target`, its base, `-stdlib=libc++`), and takes an +answer only inside the toolchain's tree (the directory a path-named toolchain +names, or the one above the driver's `bin/` and the one its driver resolves +to) or the target base; `[build] allow_host_libs = true` takes any answer, and a +compiler of the host, neither managed nor named by path, is not held. An answer +outside is not taken and the next question is asked. When no answer is taken, +`import std` is refused naming each answer not taken (2026.12.4.1+). + ## Project-Level Version Pinning If a project needs to pin a specific version rather than rely on the global default, declare it in the project's `mcpp.toml`: diff --git a/docs/zh/20-toolchains.md b/docs/zh/20-toolchains.md index 31bc47435..1f15a545f 100644 --- a/docs/zh/20-toolchains.md +++ b/docs/zh/20-toolchains.md @@ -1230,6 +1230,14 @@ iOS 设备上运行,而那不是一个构建工具能供给的东西。 (2026.10.5.2+)。从不提供 `std.compat` 的标准库 import 它的构建,会在任何编译之前 被拒绝,并点名该标准库。 +mcpp 向 clang 驱动询问 `std` 模块源码的位置:先问模块清单 +(`-print-library-module-manifest-path`),再问 `libc++.a` 所在的目录,最后看驱动旁的 +`share/libc++/v1/`。构建以模块预编译所带的词提问(它的 `--target`、基底、`-stdlib=libc++`), +只采用落在工具链的树(以路径点名的工具链所指的目录,或驱动所在 `bin/` 的上一级及驱动解析到的 +目录)或目标基底之内的答案;`[build] allow_host_libs = true` 时任何答案都被采用,宿主的编译器 +(既非托管、也非以路径点名)不受此限。落在其外的答案不被采用,转问下一个问题;没有答案被采用时, +`import std` 被拒绝,并列出每个未被采用的答案(2026.12.4.1+)。 + ## 项目级版本锁定 若工程需要锁定某个特定版本,而不依赖全局默认值,可在工程自己的 `mcpp.toml` diff --git a/modules/toolchain-model/src/model.cppm b/modules/toolchain-model/src/model.cppm index ddec42076..2cdfc2f02 100644 --- a/modules/toolchain-model/src/model.cppm +++ b/modules/toolchain-model/src/model.cppm @@ -243,6 +243,10 @@ struct Toolchain { // Why no std module was found, when the compiler did not answer the // question (its probe failed); empty when it answered that it has none. std::string stdModuleUnanswered; + // The answers a driver gave for the std module source that lay outside the + // build's roots and were not taken, one per line (design 2026-11-27 + // §3.1.3); said by the refusal when no answer was taken. + std::string stdModuleRejected; // Whether the clang driver takes `-dumpdir` and names a compile's // auxiliary outputs from it, asked of the driver at detection // (`mcpp::toolchain::driver_takes_dumpdir`). A driver's own number does diff --git a/src/build/prepare/retarget.cpp b/src/build/prepare/retarget.cpp index 1e7b6ba5a..0643f802a 100644 --- a/src/build/prepare/retarget.cpp +++ b/src/build/prepare/retarget.cpp @@ -34,6 +34,8 @@ import mcpp.toolchain.post_install; import mcpp.toolchain.abi; import mcpp.toolchain.triple; import mcpp.toolchain.target_rows; +import mcpp.toolchain.clang; // the std module source, asked with the build's words +import mcpp.toolchain.probe; // inside_roots, compiler_env import mcpp.toolchain.base; import mcpp.toolchain.base_probe; import mcpp.home; @@ -451,6 +453,69 @@ step2_retarget_for_retargetable_driver(PrepareState& state) { return {}; } +// THE STD MODULE SOURCE, ASKED WITH THE BUILD'S WORDS (design 2026-11-27 +// §3.1.3, mcpp#1039). Identification asks the driver without a target, for +// the queries that have none (`mcpp toolchain list`), and holds the answer to +// the toolchain's tree. A driver that serves several targets answers that +// question for the host: measured, an NDK clang named the host GCC's +// `libstdc++.modules.json` without `--target` and nothing with it, and the +// host's module source reached a precompile for Bionic and libc++. A build +// knows its words and its roots -- the toolchain's tree and the target base, +// every file when host libraries are allowed -- so it asks again where the +// first answer can be another machine's (a cross build of a retargetable +// driver) or lies outside its roots, as the runtime archives are asked with +// the link's words. An answer not taken is kept for the refusal that names it. +// A base, a paired system or a freestanding row decides the module on purpose +// (each sets or clears it), and nothing is asked. +void step2_ask_std_module_with_words(PrepareState& state) { + if (!state.tc) return; + auto& tc = *state.tc; + if (tc.compiler != mcpp::toolchain::CompilerId::Clang || mcpp::toolchain::is_msvc_target(tc)) return; + if (!tc.base.layers.cxx.empty() || !tc.base.layers.stdModule.empty() || !tc.pairedSysroot.empty()) { + tc.stdModuleRejected.clear(); // the driver's answers are not this build's question + return; + } + if (!tc.hasImportStd) return; + // Spelled as the hermetic link check spells it: the manifest key or the variable. + const auto allowEnv = mcpp::invocation::get("MCPP_ALLOW_HOST_LIBS"); + const bool hostAllowed = state.m->buildConfig.allowHostLibs || (allowEnv && allowEnv->front() != '0'); + std::vector roots; + if (!hostAllowed) { + roots = mcpp::toolchain::clang::tree_roots(tc); + if (!roots.empty() && !tc.base.root.empty()) roots.push_back(tc.base.root); + } + const bool cross = !tc.crossTargetFlag.empty(); + 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; + if (cross) { + mcpp::toolchain::HostFlagOptions hopt; + hopt.cfgBypass = mcpp::toolchain::HostFlagOptions::CfgBypass::Always; + hopt.clangStdlibSelect = true; + hopt.cAbiPrebuilt = tc.cAbiPrebuilt; + words = mcpp::toolchain::host_compile_tokens(tc, hopt, mcpp::toolchain::no_escape); + } + std::vector rejected; + const auto env = mcpp::toolchain::compiler_env(tc); + if (auto p = mcpp::toolchain::clang::find_libcxx_std_module_source(tc.binaryPath, env, words, roots, &rejected)) { + std::error_code ec; + const auto compat = p->parent_path() / "std.compat.cppm"; + tc.set_std_modules(*p, std::filesystem::exists(compat, ec) ? compat : std::filesystem::path{}); + tc.stdModuleRejected.clear(); + return; + } + // The first answer stands when it lies inside the roots. + if (mcpp::toolchain::inside_roots(tc.stdModuleSource, roots)) return; + if (cross) + rejected.push_back(std::format("the question without the target answered '{}', outside the build's roots", + tc.stdModuleSource.generic_string())); + tc.clear_std_modules(); + std::string text; + for (auto const& r : rejected) text += (text.empty() ? "" : "\n ") + r; + tc.stdModuleRejected = std::move(text); +} + // THE SYSTEM A PAIRED PROVIDER SUPPLIES (SPEC-016 §6). The MinGW-w64 provider // pairs with gcc and with llvm; with llvm, the payload its row names is // installed as for gcc and becomes clang's sysroot: the C library, libstdc++ diff --git a/src/build/prepare/scan.cpp b/src/build/prepare/scan.cpp index d3cab2926..d0e1d8aa9 100644 --- a/src/build/prepare/scan.cpp +++ b/src/build/prepare/scan.cpp @@ -1080,7 +1080,12 @@ step11_std_module_availability_gate(PrepareState& state, bool needsStdModule) { state.tc->label(), state.tc->stdModuleUnanswered.empty() ? std::string{} - : std::format("\n the compiler did not answer: {}", state.tc->stdModuleUnanswered))); + : std::format("\n the compiler did not answer: {}", state.tc->stdModuleUnanswered)) + + (state.tc->stdModuleRejected.empty() + ? std::string{} + : std::format("\n answers not taken, outside the toolchain's tree and the target base:\n {}" + "\n help: use a toolchain that ships the std module for this target, or allow host libraries " + "([build] allow_host_libs = true)", state.tc->stdModuleRejected))); } // `std.compat` is a second module of the same library, and not every // library has it: a package that supplies `std` alone, or a toolset without diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index bb6dd13f7..8b6907851 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -1602,6 +1602,9 @@ std::vector platform_unit_cxxflags(const PrepareState& state); std::expected step13_finish_platform(PrepareState& state, BuildContext& ctx); // retarget.cpp: a retargetable driver told its target, sysroot and multilib. std::expected step2_retarget_for_retargetable_driver(PrepareState& state); +// The std module source asked of a clang driver with the build's words, held to +// the build's roots (design 2026-11-27 §3.1.3). +void step2_ask_std_module_with_words(PrepareState& state); // The system a paired provider supplies to the declared compiler (SPEC-016 §6). std::expected step2_paired_system(PrepareState& state); // The platform root a first pass asks the second to read in P1, once. diff --git a/src/build/prepare/toolchain_resolver.cpp b/src/build/prepare/toolchain_resolver.cpp index 13c3f175f..69d6759ed 100644 --- a/src/build/prepare/toolchain_resolver.cpp +++ b/src/build/prepare/toolchain_resolver.cpp @@ -1046,6 +1046,7 @@ std::expected phase2_define_toolchain_resolver(PrepareState& if (auto r = step2_paired_system(state); !r) return std::unexpected(r.error()); 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); if (auto r = step2_resolve_run_under(state); !r) return std::unexpected(r.error()); step2_windows_runtime_identity(state); if (auto r = step2_msvc_abi_without_msvc_repair(state); !r) return std::unexpected(r.error()); diff --git a/src/toolchain/clang.cpp b/src/toolchain/clang.cpp index 58a7ef58f..407966602 100644 --- a/src/toolchain/clang.cpp +++ b/src/toolchain/clang.cpp @@ -52,14 +52,28 @@ bool matches_version_output(std::string_view firstLineLower, std::optional find_libcxx_std_module_source( const std::filesystem::path& cxx_binary, - const mcpp::run::Env& env) + const mcpp::run::Env& env, + const std::vector& words, + const std::vector& roots, + std::vector* rejected) { - auto manifest_r = mcpp::toolchain::run_capture( - { cxx_binary.string(), "-print-library-module-manifest-path" }, env); - if (manifest_r) { - auto manifestPath = std::filesystem::path( - mcpp::toolchain::trim_line(*manifest_r)); - if (!manifestPath.empty() && std::filesystem::exists(manifestPath)) { + std::string asked; + for (auto const& w : words) asked += (asked.empty() ? "" : " ") + w; + // An answer outside the build's roots is the host's, or another target's: + // said, and the next probe asked. + auto take = [&](const std::filesystem::path& p, std::string_view question) { + if (mcpp::toolchain::inside_roots(p, roots)) return true; + if (rejected) + rejected->push_back(std::format("`{}{}{}` answered '{}', outside the build's roots", + question, asked.empty() ? "" : " ", asked, p.generic_string())); + return false; + }; + const auto manifestAnswer = mcpp::toolchain::ask_driver( + cxx_binary, words, "-print-library-module-manifest-path", env); + { + auto manifestPath = std::filesystem::path(manifestAnswer); + if (!manifestPath.empty() && std::filesystem::exists(manifestPath) + && take(manifestPath, "-print-library-module-manifest-path")) { std::ifstream is(manifestPath); std::stringstream ss; ss << is.rdbuf(); @@ -79,7 +93,7 @@ std::optional find_libcxx_std_module_source( std::error_code ec; auto canon = std::filesystem::weakly_canonical(p, ec); if (!ec) p = canon; - if (std::filesystem::exists(p)) return p; + if (std::filesystem::exists(p) && take(p, "-print-library-module-manifest-path")) return p; } } cursor = logical + 1; @@ -108,17 +122,16 @@ std::optional find_libcxx_std_module_source( // would have been written against llvm, passed, and then been a guessed // layout for the next payload -- which is the mistake the line this // replaces made with `bin/../share`. - if (auto lib_r = mcpp::toolchain::run_capture( - { cxx_binary.string(), "--print-file-name=libc++.a" }, env)) { - std::filesystem::path lib(mcpp::toolchain::trim_line(*lib_r)); - // A driver that cannot place the library echoes the bare name back. - if (lib.has_parent_path()) { + if (auto answer = mcpp::toolchain::ask_driver(cxx_binary, words, "--print-file-name=libc++.a", env); + !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(); for (int up = 0; up < 4 && !dir.empty(); ++up) { auto cand = dir / "share" / "libc++" / "v1" / "std.cppm"; - if (std::filesystem::exists(cand)) return cand; + if (std::filesystem::exists(cand) && mcpp::toolchain::inside_roots(cand, roots)) return cand; if (!dir.has_relative_path()) break; dir = dir.parent_path(); } @@ -132,6 +145,19 @@ std::optional find_libcxx_std_module_source( return std::nullopt; } +std::vector tree_roots(const Toolchain& tc) { + if (tc.localRoot.empty() && !mcpp::provider::store_of(tc.binaryPath)) return {}; + const auto tree = tc.localRoot.empty() ? tc.binaryPath.parent_path().parent_path() : tc.localRoot; + std::vector roots{tree}; + const auto rel = tc.binaryPath.lexically_normal().lexically_relative(tree.lexically_normal()); + if (!rel.empty() && *rel.begin() != "..") { + std::error_code ec; + if (auto real = std::filesystem::weakly_canonical(tc.binaryPath, ec); !ec) + if (auto resolved = real.parent_path().parent_path(); resolved != tree) roots.push_back(resolved); + } + return roots; +} + void enrich_toolchain(Toolchain& tc, const mcpp::run::Env& env) { // Clang targeting MSVC uses MSVC STL, not libc++. bool msvTarget = is_msvc_target(tc); @@ -143,7 +169,13 @@ void enrich_toolchain(Toolchain& tc, const mcpp::run::Env& env) { // and are written in place whatever it takes (`output_relocation`). tc.takesDumpdir = !msvTarget && mcpp::toolchain::driver_takes_dumpdir(tc.binaryPath, env); - if (auto p = find_libcxx_std_module_source(tc.binaryPath, env)) { + // Asked without a target, for the queries that have none, and held to the + // toolchain's tree: a driver that serves several targets answers for the + // 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`). + 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{})); // libc++ documents the std module for C++20 and later, and its @@ -160,6 +192,8 @@ void enrich_toolchain(Toolchain& tc, const mcpp::run::Env& env) { { tc.binaryPath.string(), "--print-file-name=libc++.a" }, env, /*withErrors=*/true); !r) tc.stdModuleUnanswered = r.error().message; } + for (auto const& r : rejected) + tc.stdModuleRejected += (tc.stdModuleRejected.empty() ? "" : "\n ") + r; if constexpr (mcpplibs::os::is_windows) { // Fallback: if libc++ std.cppm not found, look for MSVC STL's std.ixx. @@ -430,11 +464,12 @@ std::filesystem::path runtime_archive_path(const Toolchain& tc, if (auto it = answered.find(key); it != answered.end()) return it->second; } std::filesystem::path out; - if (auto r = mcpp::toolchain::run_capture(argv, mcpp::toolchain::compiler_env(tc))) { - std::filesystem::path lib(mcpp::toolchain::trim_line(*r)); + { + std::filesystem::path lib(mcpp::toolchain::ask_driver( + tc.binaryPath, driverFlags, std::format("--print-file-name={}", archive), + mcpp::toolchain::compiler_env(tc))); std::error_code ec; - if (lib.has_parent_path() && lib.is_absolute() - && std::filesystem::is_regular_file(lib, ec)) + if (lib.is_absolute() && std::filesystem::is_regular_file(lib, ec)) out = lib.lexically_normal(); } std::scoped_lock lock(mu); diff --git a/src/toolchain/clang.cppm b/src/toolchain/clang.cppm index a68b994d4..3000a3f30 100644 --- a/src/toolchain/clang.cppm +++ b/src/toolchain/clang.cppm @@ -11,9 +11,25 @@ export namespace mcpp::toolchain::clang { bool matches_version_output(std::string_view firstLineLower, std::string_view fullOutputLower); +// THE TOOLCHAIN'S TREE, the root its driver's answers are held to (design +// 2026-11-27 §3.1.3): the directory a path-named toolchain names, else the +// one above the driver's `bin/`; with the tree its driver resolves to when +// the driver lies inside it (a tree of links). Empty for a toolchain of the +// host (neither managed nor named by path): choosing it is the opt-in to the +// host's files, as for the hermetic link check. +std::vector tree_roots(const Toolchain& tc); + +// The std module source libc++ ships, asked of the driver with `words` (the +// build's target and base; none at identification, where the question is +// the host's) and taken only inside `roots` (design 2026-11-27 §3.1.3). An +// answer outside them is not taken: the next probe is asked, and `rejected` +// gains one line naming the answer and the question. std::optional find_libcxx_std_module_source( const std::filesystem::path& cxx_binary, - const mcpp::run::Env& env); + const mcpp::run::Env& env, + const std::vector& words = {}, + const std::vector& roots = {}, + std::vector* rejected = nullptr); void enrich_toolchain(Toolchain& tc, const mcpp::run::Env& env); diff --git a/src/toolchain/probe.cppm b/src/toolchain/probe.cppm index cea4af3d8..abc01add9 100644 --- a/src/toolchain/probe.cppm +++ b/src/toolchain/probe.cppm @@ -32,6 +32,24 @@ std::expected run_capture(const std::vector& words, + std::string_view question, const mcpp::run::Env& env = {}); + +// Whether `file` lies under one of `roots`, as spelled (absolute and normal) +// or with both resolved: the roots a build declared -- the toolchain's tree, +// the target base. A tree of links holds a file named through its links and +// the file they lead to only when the tree's driver leads there too (see +// `clang::tree_roots`). An empty list declares none and holds every file. +bool inside_roots(const std::filesystem::path& file, const std::vector& roots); + // Whether a build with this compiler can write compressed debug sections // (`-gz=zlib`): the linker its driver runs must read them. An `ld.lld` built // without zlib refuses `--compress-debug-sections` while clang says nothing @@ -347,6 +365,44 @@ bool driver_takes_dumpdir(const std::filesystem::path& compiler, const mcpp::run return answered[key] = yes; } +std::string ask_driver(const std::filesystem::path& compiler, const std::vector& words, + std::string_view question, const mcpp::run::Env& env) { + std::vector argv{compiler.string()}; + for (auto const& w : words) + if (!w.empty()) argv.push_back(w); + argv.emplace_back(question); + auto r = run_capture(argv, env); + if (!r) return {}; + auto answer = trim_line(*r); + if (auto nl = answer.rfind('\n'); nl != std::string::npos) answer = trim_line(answer.substr(nl + 1)); + // A driver that cannot place a file echoes the bare name back. + if (!std::filesystem::path(answer).has_parent_path()) return {}; + return answer; +} + +bool inside_roots(const std::filesystem::path& file, const std::vector& roots) { + if (roots.empty()) return true; + auto spelled = [](const std::filesystem::path& p) { + std::error_code ec; + auto a = std::filesystem::absolute(p, ec); + return (ec ? p : a).lexically_normal(); + }; + auto resolved = [&](const std::filesystem::path& p) { + std::error_code ec; + auto c = std::filesystem::weakly_canonical(p, ec); + return ec ? spelled(p) : c.lexically_normal(); + }; + 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; +} + std::expected run_capture(const std::vector& argv, const mcpp::run::Env& env, bool withErrors) { const auto key = probe_cache_key(argv, env, withErrors); diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index 7bfd00e01..3d48e0182 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -165,6 +165,61 @@ E2E custom{"custom", s::home_fixture, [] { expect(s::has_line(calls, "^launcher2 .*build\\.mcpp")) << "a changed launcher did not rebuild the build program:\n" << calls; }; + "a driver's answer outside the toolchain's tree is not taken"_test[s::llvm][s::unix_shell] = [] { + // Design 2026-11-27 §3.1.3 (mcpp#1039): a driver that answers the module-manifest question + // with a file outside the tree its table names (here: a host-like `libstdc++.modules.json` + // whose `std.cc` does not compile) is not taken; the next probe finds the tree's own + // `std.cppm` and `import std` builds. When every answer lies outside, the build is refused + // naming each answer not taken. + 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 host = work / "host"; + auto write = [](const fs::path& file, std::string_view text) { + fs::create_directories(file.parent_path()); + std::ofstream(file, std::ios::binary) << text; + }; + write(host / "libstdc++.modules.json", + R"({"version": 1, "revision": 1, "modules": [{"logical-name": "std", "source-path": "bits/std.cc"}]})"); + write(host / "bits/std.cc", "#error the module source of another library was taken\n"); + write(host / "libc++.a", ""); + const auto driver = work / "driver" / "clang++"; + auto write_driver = [&](bool archiveOutside) { + s::write_executable(driver, std::format( + "#!/bin/sh\nfor a in \"$@\"; do case \"$a\" in\n" + " -print-library-module-manifest-path) echo '{}'; exit 0;;\n{}" + "esac; done\nexec '{}/bin/clang++' \"$@\"\n", + (host / "libstdc++.modules.json").string(), + archiveOutside ? std::format(" --print-file-name=libc++.a) echo '{}'; exit 0;;\n", (host / "libc++.a").string()) + : std::string{}, + llvm_root.string())); + }; + write_driver(false); + s::project app(work / "app", {{"src/main.cpp", "import std;\nint main() { std::println(\"the tree's std module\"); }\n"}}); + app.write("mcpp.toml", std::format( + "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[toolchain]\n" + "default = {{ path = \"{}\", tools = {{ cxx = \"{}\" }} }}\n", + llvm_root.string(), driver.string())); + const s::options o{.env = {{"NO_COLOR", "1"}}}; + auto r = app.mcpp({"build"}, o); + expect(fatal(e2e::succeeded(r))) << "the build took the answer outside the tree: " << s::text(r); + const auto bins = s::glob(app.at("target"), "*/*/bin/app"); + expect(fatal(!bins.empty())) << "no app"; + expect(e2e::contains(s::run(bins.front()).out, "the tree's std module")); + + // Every probe answers outside the tree: refused, each answer named. + write_driver(true); + app.remove("target"); + e2e::expect_diagnostic("provides no std module source"); + r = app.mcpp({"build"}, o); + const auto out = s::text(r); + expect(fatal(!e2e::succeeded(r))) << "built with no std module of the tree: " << out; + expect(e2e::contains(out, "answers not taken")) << out; + expect(e2e::contains(out, (host / "libstdc++.modules.json").generic_string())) << out; + expect(e2e::contains(out, (host / "libc++.a").generic_string())) << out; + expect(s::lacks(out, "another library was taken")) << out; + }; + "876 toolchain phase"_test[s::llvm][s::unix_shell][s::symlink] = [] { // `[toolchain] default = { configure = "build.mcpp" }` (mcpp#755): the build program's // toolchain phase states the toolchain (a path, reported with its origin; a managed spec, From 2e1fa1d33a533c92928543e8d6dae1d0ae10dd05 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 01:40:40 +0900 Subject: [PATCH 08/36] A toolchain named by path takes what it can do from its statement or a probe A tree's archiver is tools.ar, the tree's, or the host's on PATH (reported as build/archiver-from-host, refused under --strict; none anywhere is refused with [toolchain-has-no-archiver]); an archiver that reads @file as a member's name is given the expanded words, in batches (link-output --expand). A clang tree links with -fuse-ld=lld only when it has lld, and with --rtlib/--unwindlib only when its driver names the library, for the project's links and the build programs' (tools.ld reaches both through --ld-path). A driver that refuses a module unit builds the units that use none; a module unit is refused with [compiler-without-modules]. Each answer is kept under the program's identity (one kept-probe helper, the -dumpdir probe moved onto it). mcpp why toolchain lists each fact with its source and the std module source with its origin; mcpp why flags names why each shared image is on a link line; the layer report writes custom for the layers a tree supplies; a build program whose planning failed is named, and a toolchain refusal points at the main project's [toolchain] line. Two notes said once per project: toolchain/tree-holds-two-families and xlings/package-at-two-versions. Root checks: path identity through mcpp.libs.path_identity, the stderr-writer baseline lowered, a docs table header, the agents index regenerated. --- .../2026-11-27-ecosystem-boundary-design.md | 6 + .agents/docs/README.md | 4 +- .github/tools/stderr-writers.baseline | 8 +- CHANGELOG.md | 17 ++ docs/20-toolchains.md | 17 ++ docs/23-the-project-environment.md | 5 + docs/25-home-indices-and-store.md | 2 +- docs/50-machine-output.md | 2 + docs/zh/20-toolchains.md | 14 ++ docs/zh/23-the-project-environment.md | 4 + docs/zh/50-machine-output.md | 2 + modules/manifest/src/targetside_model.cppm | 10 + modules/notice/src/notice.cppm | 2 + modules/toolchain-model/src/linkmodel.cppm | 32 ++-- modules/toolchain-model/src/model.cppm | 21 +++ src/build/flag_origins.cpp | 11 +- src/build/flag_origins.cppm | 3 + src/build/flags.cppm | 16 +- src/build/ninja_backend.cppm | 4 +- src/build/plan.cppm | 18 +- src/build/prepare/host_graph.cpp | 24 ++- src/build/prepare/local_toolchain.cpp | 142 +++++++++++++- src/build/prepare/scan.cpp | 22 ++- src/build/prepare/state.cppm | 5 + src/build/prepare/target_side.cpp | 1 + src/build/prepare/toolchain_resolver.cpp | 2 + src/build/refusal.cppm | 7 + src/cli.cppm | 1 + src/cli/cmd_build.cppm | 88 +++++++-- src/doctor.cppm | 21 +++ src/explain.cppm | 9 + src/toolchain/clang.cpp | 9 +- src/toolchain/hostflags.cppm | 9 +- src/toolchain/probe.cppm | 174 ++++++++++++++---- src/toolchain/provider.cppm | 3 + tests/e2e/toolchain/custom.cpp | 69 +++++++ 36 files changed, 686 insertions(+), 98 deletions(-) diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index cf85ff739..deeb5dbbf 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -270,6 +270,12 @@ C flags 通用键;不为追随旧发行版而增加旧版编译器载荷;不 托管载荷不经过这条路径:它们的形状是索引的数据,行为不变。 +**实现(2026-12-05)。** 与上文三处不同。其一,查找归档器的名字是 `ar`、`llvm-ar`、`ar`,树中与 `PATH` +上相同,不按族取自数据行:树中查找本来就用这三个名字,两个族的树都可能带其中任一个,按族分开会让一棵 gcc 树里的 +`llvm-ar` 不被找到。其二,归档器与响应文件在识别树时决定(它们不依赖目标);链接器、运行库与模块的探测在目标与基底 +确定之后进行,带着交叉构建的 `--target`。其三,探测的答案经同一个保存函数按程序的身份与词保存(`-dumpdir` 的探测 +一并迁入),不进入 §3.1.3 的 `ask_driver`:后者回答「文件在哪里」,前者回答「这个程序接受什么」。 + #### 3.1.3 每一个问题带着构建的词(#1039) **现状(读码;报告含两次对照)。** mcpp 向驱动提出若干问题:标准库模块的清单在哪里、链接用的标准库归档在哪里、 diff --git a/.agents/docs/README.md b/.agents/docs/README.md index fd3643636..640251c84 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 --- ``` -375 records. +376 records. ## By subject @@ -95,6 +95,7 @@ Records that declare one. Everything else is listed by date below. ### ecosystem +- [生态与外部的交界:工具链的事实、二进制库交付物、被启动的外部程序、名字的拼写与共享的状态](2026-11-27-ecosystem-boundary-design.md) — active - [包的特性作为机器可读的回答:一个目录项,两种来源,三种状态(mcpp#992)](2026-11-21-package-features-query-design.md) — active - [离线、宿主输入与工具链的缺省:按内容取归档的来源、项目的取齐、宿主输入的声明、工具链的解析与锁、缺省版本的规则(mcpp#988、#989、#990)](2026-11-21-offline-host-inputs-and-toolchain-defaults-design.md) — active - [生态规则收敛方案:2026.11.18.1 之后十个 issue 的五类成因、七项决定与实施范围](2026-11-19-ecosystem-rule-convergence-design.md) — landed @@ -218,6 +219,7 @@ Records that declare one. Everything else is listed by date below. ### 2026-11 - [陈述的闭包、单一读者与六项功能:十四项缺陷的收敛设计](2026-11-27-stated-closure-single-reader-and-feature-designs.md) — landed +- [生态与外部的交界:工具链的事实、二进制库交付物、被启动的外部程序、名字的拼写与共享的状态](2026-11-27-ecosystem-boundary-design.md) — active - [clang BMI 的截断与私有模块片段判定的收窄](2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md) — active - [测试与 CI 一轮的收尾:平台列未命中的刷新条件(mcpp#996)、`i686-windows-msvc` 行、工作区索引与引号键的迁移、索引的全量验证](2026-11-22-test-round-wrap-up-plan.md) — active - [生态级方案:内核接口的供给与能力,派生状态的核对,存储的引用](2026-11-22-kernel-interface-and-derived-state-ecosystem-design.md) — active diff --git a/.github/tools/stderr-writers.baseline b/.github/tools/stderr-writers.baseline index 24113631c..6cccdc564 100644 --- a/.github/tools/stderr-writers.baseline +++ b/.github/tools/stderr-writers.baseline @@ -3,17 +3,17 @@ src/build/execute.cppm 47 src/build/schedule/compiler_transaction.cppm 1 src/build/schedule/detach_codegen.cppm 41 -src/cli/cmd_build.cppm 56 +src/cli/cmd_build.cppm 53 src/cli/cmd_cache.cppm 1 src/cli/cmd_new.cppm 1 src/cli/cmd_publish.cppm 4 src/cli/cmd_registry.cppm 2 -src/cli/cmd_self.cppm 8 +src/cli/cmd_self.cppm 7 src/cli/cmd_toolchain.cppm 1 src/cli/cmd_xpkg.cppm 1 -src/cli.cppm 17 +src/cli.cppm 15 src/config.cppm 3 -src/doctor.cppm 7 +src/doctor.cppm 5 src/fallback/xlings_binary.cppm 4 src/main.cpp 1 src/pack/distribution.cppm 5 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a649a426..25273bbf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,23 @@ - A command that needs a project, run outside one, says `no mcpp.toml in the current directory or any parent` and names the two next steps. - mcpp depends on mcpplibs.cmdline 0.2.0 with its `agent-skills` feature. +- A toolchain named by path takes what it can do from its statement or a probe, as a managed + payload takes it from the index: the archiver from `tools.ar`, the tree, or the host's `PATH` + (reported as `build/archiver-from-host`, refused under `--strict`; none anywhere is refused with + `[toolchain-has-no-archiver]`); an archiver that reads `@file` as a member's name is given the + expanded words; a clang tree links with `-fuse-ld=lld` only when it has lld, and with a runtime + word only when its driver names the library, for the project's links and the build programs'; + a driver that refuses a module unit builds the units that use none, and a module unit is + refused with `[compiler-without-modules]`. `mcpp why toolchain` lists each fact with its source + and the std module source with its origin; the layer report writes `custom` for the layers a + tree supplies. +- A build program whose planning failed is named in the message, and a refusal about the + toolchain points at the main project's `[toolchain]` line. +- `mcpp why flags` names, for each shared image on a link line, why it is there: a direct + dependency, or the package whose interface reaches a compile. +- Two notes, each said once per project: a tree that holds both clang and gcc with no `family` + (`toolchain/tree-holds-two-families`), and a package `[toolchain]` and `[xlings.workspace]` + name at two versions (`xlings/package-at-two-versions`). - `mcpp test` refuses, while planning, a test program whose executable would be the same file as an executable target of its package, with `[test-output-collision]` (mcpp#1028). The message names the test's file or directory and an example name, or the target's table; names are diff --git a/docs/20-toolchains.md b/docs/20-toolchains.md index 126b76b28..eec0d422b 100644 --- a/docs/20-toolchains.md +++ b/docs/20-toolchains.md @@ -604,6 +604,23 @@ 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: + +| Fact | Taken from | +|---|---| +| 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 | +| 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 +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. + **What mcpp does with it.** The same as with a payload it installed: its own link line, its own hermetic check, its own `import std` decision. It writes nothing into the tree — the generated `clang++.cfg` of a managed payload is diff --git a/docs/23-the-project-environment.md b/docs/23-the-project-environment.md index 3f1a63e68..776807ba4 100644 --- a/docs/23-the-project-environment.md +++ b/docs/23-the-project-environment.md @@ -222,6 +222,11 @@ naming the payload's path. | a tool only one verb or one feature needs | `when = "run"`, `[feature-xlings.]` | | which environment | `[xlings] subos` | +`[toolchain]` and `[xlings.workspace]` may name one package at two versions +(`llvm@23.1.6` and `llvm = "22"`): the first compiles the build, the second is on +the `PATH` of the programs the build starts. Both are provided, and the pair is +noted once per project (`xlings/package-at-two-versions`, 2026.12.4.1+). + ## 7. `[xlings]` — the manifest keys ```toml diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index 24f5ed338..4ef32ce4e 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -231,7 +231,7 @@ report names the command that lists the file's holders on this system. A run waits as long as the holder holds, unless a limit is stated. The limit is a duration (`30s`, `2m`, `1h`; `0` does not wait), taken from the first of: -| tier | where | +| tier | statement | |---|---| | override | `--lock-wait `, `MCPP_LOCK_WAIT` | | project | `[build] lock_wait` in `mcpp.toml` | diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index 8f3014a9f..4a5e3e2a5 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -723,6 +723,8 @@ a program classifying the outcome reads `reason`: | `lock-unavailable` | the system cannot lock a file mcpp needs: permissions, a read-only or lockless file system, no descriptor left; waiting would not end *(2026.12.4.1+)* | | `vcs-unavailable` | `mcpp new` was asked for a repository and git cannot run *(2026.12.4.1+)* | | `test-output-collision` | a test program and an executable target of one package write one file; the message names the test's file or directory to rename *(2026.12.4.1+)* | +| `toolchain-has-no-archiver` | a toolchain named by path has no archiver, in its tree or on PATH *(2026.12.4.1+)* | +| `compiler-without-modules` | a unit declares or imports a module, and the compiler has no C++ modules (GCC before 14, or a tree's driver that refused a module unit) *(2026.12.4.1+)* | | `other` | a refusal whose branch has not been given a token yet | **One token is also printed by `mcpp build` itself.** diff --git a/docs/zh/20-toolchains.md b/docs/zh/20-toolchains.md index 1f15a545f..6324c993b 100644 --- a/docs/zh/20-toolchains.md +++ b/docs/zh/20-toolchains.md @@ -521,6 +521,20 @@ MCPP_TOOLCHAIN=path:/opt/llvm-trunk mcpp build 陈述 `ld` 会被拒绝:gcc 按 `-B` 给出的目录里的名字 `ld` 选链接器,叫别的名字的程序无法那样 被选中,而一个进了声明却不参与构建的工具,正是这套机制要防的事。 +**树能做什么,取自陈述或探测(2026.12.4.1+)。** 托管载荷的形状是索引的数据;树的形状从树中读取: + +| 事实 | 取自 | +|---|---| +| 归档器 | `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) | 只在驱动给出该库时写 `--rtlib=compiler-rt` 与 `--unwindlib=libunwind` | +| C++ 模块(clang) | 编译一次两行的模块单元;拒绝它的驱动构建不用模块的单元,声明或导入模块的单元以 `[compiler-without-modules]` 拒绝,并指出文件 | + +工程的链接与构建程序的链接用同样的词。每个答案按程序的身份保存,`mcpp why toolchain` 列出每一项及其来源; +层报告对树供给的层写 `custom`。一棵树同时有 `clang++` 与 `g++` 而未陈述 `family` 时,说明一次 +(`toolchain/tree-holds-two-families`),写出用的是哪一个。 + **mcpp 如何驱动它。** 与它自己安装的载荷相同:自己的链接行、自己的 hermetic 检查、自己 对 `import std` 的判定。它不向该目录树写入任何东西 —— 托管载荷里生成的 `clang++.cfg` 是 mcpp 自己的文件,而一棵不属于 mcpp 的树不会得到一份。 diff --git a/docs/zh/23-the-project-environment.md b/docs/zh/23-the-project-environment.md index 299b71523..395681d78 100644 --- a/docs/zh/23-the-project-environment.md +++ b/docs/zh/23-the-project-environment.md @@ -180,6 +180,10 @@ payload 的路径。 | 只有某一个命令或某一个 feature 需要的工具 | `when = "run"`、`[feature-xlings.]` | | 使用哪一个环境 | `[xlings] subos` | +`[toolchain]` 与 `[xlings.workspace]` 可以以两个版本点名同一个包(`llvm@23.1.6` 与 `llvm = "22"`): +前者编译这次构建,后者在构建启动的程序的 `PATH` 上。两者都被供给,这一对每个工程说明一次 +(`xlings/package-at-two-versions`,2026.12.4.1+)。 + ## 7. `[xlings]` —— manifest 键 ```toml diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 6b8202867..0638cc97a 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -645,6 +645,8 @@ replaced}` —— `origin` 与构建的状态行使用的是同一句话 | `lock-unavailable` | 系统无法为 mcpp 需要的文件加锁:权限、只读或不支持锁的文件系统、描述符耗尽;等待不会结束 *(2026.12.4.1+)* | | `vcs-unavailable` | `mcpp new` 被要求建立仓库而 git 无法运行 *(2026.12.4.1+)* | | `test-output-collision` | 同一个包的测试程序与可执行目标写同一个文件;消息写出应改名的测试文件或目录 *(2026.12.4.1+)* | +| `toolchain-has-no-archiver` | 以路径点名的工具链在树中与 PATH 上都没有归档器 *(2026.12.4.1+)* | +| `compiler-without-modules` | 有单元声明或导入模块,而编译器没有 C++ 模块(GCC 14 之前,或拒绝模块单元的树的驱动) *(2026.12.4.1+)* | | `other` | 一个尚未被赋予记号的拒绝分支 | **其中一个记号也由 `mcpp build` 自己打印。** `interface-not-provided` 会 diff --git a/modules/manifest/src/targetside_model.cppm b/modules/manifest/src/targetside_model.cppm index eabd9646f..3eebe35c1 100644 --- a/modules/manifest/src/targetside_model.cppm +++ b/modules/manifest/src/targetside_model.cppm @@ -248,6 +248,9 @@ struct Layer { // The package was added to the graph by the target's platform (SPEC-013 // §4.3): still a graph package, reported as the platform's. bool byPlatform = false; + // Supplied by a toolchain named by path, not by a payload of the + // ecosystem: reported as `custom` (design 2026-11-27 §3.1.2). + bool custom = false; // The kernel-abi layer's measured version, where its headers are a // package of the system's (design 2026-11-22 §3.4, §3.8): "6.18.64". std::string version; @@ -588,6 +591,9 @@ struct Inputs { // show the whole stack rather than the part of it packages happen to fill. std::string compilerFamily; // "llvm" / "gcc" / "msvc" std::string compilerVersion; + // The compiler is a tree named by path: what it supplies itself (the + // compiler, its runtime, its C++ library) is reported as `custom`. + bool compilerFromTree = false; // THE C LIBRARY THE TRIPLE ASKED FOR, WHICH IS NOT THE SAME QUESTION AS // WHICH ONE RESOLVED. @@ -808,6 +814,9 @@ inline TargetSide resolve(const Inputs& in) { else ts.cxx = { Origin::None, {}, {}, false }; ts.cxxOverBaseMeasured = ts.cAbi.origin == Origin::Xpkg && in.sysrootFitsPayloadCxx; + if (in.compilerFromTree) + for (Layer* l : {&ts.compiler, &ts.compilerRuntime, &ts.cxx}) + if (l->origin == Origin::Payload) l->custom = true; return ts; } @@ -1108,6 +1117,7 @@ inline std::string format_layers(const TargetSide& ts, bool verbose) { // One column layout whether or not an implementation is named, so the // rows read as a table rather than as a list of sentences. const std::string_view from = l.byPlatform ? std::string_view("platform") + : l.custom ? std::string_view("custom") : origin_name(l.origin); const auto shown = l.version.empty() ? l.interfaceName : std::format("{} {}", l.interfaceName, l.version); diff --git a/modules/notice/src/notice.cppm b/modules/notice/src/notice.cppm index af0a26231..bfd6273b2 100644 --- a/modules/notice/src/notice.cppm +++ b/modules/notice/src/notice.cppm @@ -26,6 +26,8 @@ inline constexpr Kind kKinds[] = { {"toolchain/default-changed", Policy::Once, "docs/20-toolchains.md, \"Resolution and the lock\""}, {"host-input", Policy::Once, "docs/25-home-indices-and-store.md, \"Host inputs\""}, {"machine-path-in-manifest", Policy::Once, "docs/25-home-indices-and-store.md, \"Archive directories\""}, + {"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\""}, }; diff --git a/modules/toolchain-model/src/linkmodel.cppm b/modules/toolchain-model/src/linkmodel.cppm index 1eec10934..fc48c58e5 100644 --- a/modules/toolchain-model/src/linkmodel.cppm +++ b/modules/toolchain-model/src/linkmodel.cppm @@ -300,16 +300,24 @@ struct ClangDriverModel { return render_tokens(compile_tokens(esc)); } - // Link-side driver selection, matching the cfg xlings generates. - static constexpr std::string_view kLinkDriverFlags = - " -stdlib=libc++ -fuse-ld=lld --rtlib=compiler-rt --unwindlib=libunwind"; - - // The same selection for a link that has no C++ in it (mcpp#426). Only - // `-stdlib=` comes off: the compiler runtime and the unwinder are just as - // much a C decision, and dropping them would make a C link resolve - // __udivti3 differently from every other link in the same build. - static constexpr std::string_view kLinkDriverFlagsC = - " -fuse-ld=lld --rtlib=compiler-rt --unwindlib=libunwind"; + // Link-side driver selection, matching the cfg xlings generates: the + // linker, the compiler runtime and the unwinder. A tree named by path + // states its own (`Toolchain::treeLinkWords`, design 2026-11-27 §3.1.2): + // `-fuse-ld=lld` only when it has lld, a runtime word only when its driver + // has that library. + std::vector linkWords{"-fuse-ld=lld", "--rtlib=compiler-rt", + "--unwindlib=libunwind"}; + + // The selection on a link line: with `-stdlib=libc++` for a link with C++ + // in it. A link that has no C++ (mcpp#426) takes the rest: the compiler + // runtime and the unwinder are just as much a C decision, and dropping + // them would make a C link resolve __udivti3 differently from every other + // link in the same build. + std::string link_driver_flags(bool cxx) const { + std::string out = cxx ? " -stdlib=libc++" : ""; + for (auto const& w : linkWords) out += " " + w; + return out; + } // Same, as argv tokens, WITHOUT `-stdlib=libc++`: a driver invocation that // both compiles and links (build.mcpp) already carries it on the compile @@ -317,8 +325,7 @@ struct ClangDriverModel { // Plus the libc++/compiler-rt library dirs, which a self-contained host // helper needs to both link against and find at run time. std::vector link_tokens(const PathEscape& esc) const { - std::vector out{"-fuse-ld=lld", "--rtlib=compiler-rt", - "--unwindlib=libunwind"}; + std::vector out = linkWords; for (auto& d : libDirs) { out.push_back("-L" + esc(d)); out.push_back("-Wl,-rpath," + esc(d)); @@ -405,6 +412,7 @@ ClangDriverModel resolve_clang_driver(const Toolchain& tc) { dm.hasCfg = std::filesystem::exists(root / "include" / "c++" / "v1", ec); } if (dm.hasCfg) dm.llvmRoot = tc.binaryPath.parent_path().parent_path(); + if (tc.treeLinkWords) dm.linkWords = *tc.treeLinkWords; // A BASE PACKAGE'S C++ HEADERS STAND WHERE THE PAYLOAD'S WOULD (E5), so // every reader of this model -- a unit, the std module, a build program -- // compiles against the library the base links. diff --git a/modules/toolchain-model/src/model.cppm b/modules/toolchain-model/src/model.cppm index 2cdfc2f02..4fe9392ee 100644 --- a/modules/toolchain-model/src/model.cppm +++ b/modules/toolchain-model/src/model.cppm @@ -292,6 +292,27 @@ struct Toolchain { std::vector toolOverrides; // The driver-and-tool prefix of a cross toolchain (`aarch64-none-linux-gnu-`). std::string toolPrefix; + // WHAT A TREE NAMED BY PATH CAN DO, TAKEN FROM THE STATEMENT OR A PROBE + // (design 2026-11-27 §3.1.2); a managed payload's shape is the index's data + // 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 + // 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; + bool archiverTakesResponseFiles = true; + bool compilesModules = true; + // A named struct for the reason `ToolOverride` is one (below). + struct TreeFact { + std::string name; + std::string value; + }; + std::vector treeFacts; // The `bin` directory of the binutils the project states beside a managed // GCC (`companions = { binutils = … }`, SPEC-006 §2.9); empty: the // binutils its payload declares. diff --git a/src/build/flag_origins.cpp b/src/build/flag_origins.cpp index ef49148db..5ce86ea74 100644 --- a/src/build/flag_origins.cpp +++ b/src/build/flag_origins.cpp @@ -134,6 +134,12 @@ FlagOrigins flag_origins(const BuildPlan& plan, std::string_view unit) { if (ldOwnSet.contains(w)) { o.link.push_back({ w, "package", root }); continue; } o.link.push_back(attribute(layers, w)); } + for (auto const& lu : plan.linkUnits) { + if (lu.package != root || lu.sharedImages.empty()) continue; + UnitFlagOrigins u{lu.output.generic_string(), lu.package, {}}; + for (auto const& si : lu.sharedImages) u.words.push_back({si.image.generic_string(), "image", si.reason}); + o.images.push_back(std::move(u)); + } return o; } @@ -147,7 +153,10 @@ nlohmann::json flag_origins_json(const FlagOrigins& o) { auto units = nlohmann::json::array(); for (auto const& u : o.units) units.push_back({ { "file", u.file }, { "package", u.package }, { "words", words(u.words) } }); - return { { "identity", o.identity }, { "units", units }, { "link", words(o.link) } }; + auto images = nlohmann::json::array(); + for (auto const& u : o.images) + images.push_back({ { "file", u.file }, { "package", u.package }, { "images", words(u.words) } }); + return { { "identity", o.identity }, { "units", units }, { "link", words(o.link) }, { "images", images } }; } } // namespace mcpp::build diff --git a/src/build/flag_origins.cppm b/src/build/flag_origins.cppm index 453b87741..8f34463d4 100644 --- a/src/build/flag_origins.cppm +++ b/src/build/flag_origins.cppm @@ -36,6 +36,9 @@ struct FlagOrigins { std::string identity; std::vector units; std::vector link; // the configuration's link flags + // The shared images on each of the root package's links, with why each is + // there (layer `image`, detail the reason). + std::vector images; }; // The units whose source path ends with `unit` (all of the root package's when diff --git a/src/build/flags.cppm b/src/build/flags.cppm index 139f1813e..53088ee43 100644 --- a/src/build/flags.cppm +++ b/src/build/flags.cppm @@ -93,6 +93,10 @@ struct CompileFlags { std::filesystem::path cxxBinary; // g++ / clang++ / cl.exe std::filesystem::path ccBinary; // gcc / clang (derived; cl.exe = same) std::filesystem::path arBinary; // ar / llvm-ar / lib.exe (empty → PATH) + // False for an archiver that reads `@file` as a member's name (a tree named + // by path, probed; design 2026-11-27 §3.1.2): mcpp expands the response + // file and archives in batches (`link-output --expand`). + bool archiverTakesResponseFiles = true; std::filesystem::path ldBinary; // link.exe (SeparateLinker dialects only) // THE LINK IS DRIVEN BY THIS BINARY INSTEAD OF BY THE COMPILER, AND // WHEN IT IS SET THE WHOLE FLAG VOCABULARY CHANGES WITH IT. @@ -1144,14 +1148,15 @@ CompileFlags compute_flags_impl(const BuildPlan& plan, bool packageLinkFlags) { // // `-fuse-ld=lld` stays because it names a FAMILY and the driver // picks the flavour from the target; that is the one part of the - // selection that is still ours to make. - link_toolchain_flags += " -fuse-ld=lld"; + // selection that is still ours to make. A tree named by path + // without lld is linked by its driver's default (§3.1.2). + if (std::ranges::contains(dm.linkWords, std::string("-fuse-ld=lld"))) + link_toolchain_flags += " -fuse-ld=lld"; link_toolchain_flags_c = link_toolchain_flags; } else { if (lm.mode == mcpp::toolchain::CLibMode::Sysroot) link_toolchain_flags += lm.link_flags(ninjaEsc); - link_toolchain_flags_c = link_toolchain_flags - + std::string(mcpp::toolchain::ClangDriverModel::kLinkDriverFlagsC); + link_toolchain_flags_c = link_toolchain_flags + dm.link_driver_flags(/*cxx=*/false); // A graph-supplied libstdc++ under the payload's clang: the driver // links it (`-lstdc++` from the package's library directory) and // libgcc's unwinder, which libstdc++.so is built against -- one @@ -1160,7 +1165,7 @@ CompileFlags compute_flags_impl(const BuildPlan& plan, bool packageLinkFlags) { // consulted (measured: NEEDED = libstdc++, libm, libgcc_s, libc). link_toolchain_flags += graphLibstdcxx ? std::string(" -stdlib=libstdc++ -fuse-ld=lld --rtlib=compiler-rt --unwindlib=libgcc") - : std::string(mcpp::toolchain::ClangDriverModel::kLinkDriverFlags); + : dm.link_driver_flags(/*cxx=*/true); } f.sysroot = link_toolchain_flags; } else if (lm.mode != mcpp::toolchain::CLibMode::None) { @@ -1321,6 +1326,7 @@ CompileFlags compute_flags_impl(const BuildPlan& plan, bool packageLinkFlags) { // AR binary f.arBinary = mcpp::toolchain::archive_tool(plan.toolchain); + f.archiverTakesResponseFiles = plan.toolchain.archiverTakesResponseFiles; // Opt level + debug come from the resolved build profile // ([profile.] → buildConfig). The level is the one the profile diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 4215c7852..283651ab3 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -2897,7 +2897,9 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, if (desc != "AR") cmd = linkPrefix + publish_link(std::move(cmd)); // An archive holds no permit; a lib.exe whose text is not UTF-8 // still runs through `link-output`, which only decodes it. - else if (!textWord.empty()) cmd = "$mcpp link-output --output $out" + textWord + " -- " + cmd; + else if (!textWord.empty() || !flags.archiverTakesResponseFiles) + cmd = "$mcpp link-output --output $out" + textWord + + (flags.archiverTakesResponseFiles ? "" : " --expand") + " -- " + cmd; append(std::format("rule {}\n", name)); if (useRsp) { if (auto pos = cmd.find("$in"); pos != std::string::npos) diff --git a/src/build/plan.cppm b/src/build/plan.cppm index 9512a1574..7d6f62e2f 100644 --- a/src/build/plan.cppm +++ b/src/build/plan.cppm @@ -189,6 +189,14 @@ struct LinkUnit { // no known rule to make it". Do not normalise this vector. std::vector objects; std::vector implicitInputs; // relative to plan.outputDir + // Each shared image on the line and why it is there: a direct dependency, + // or the package whose interface reached a unit's compile (design + // 2026-11-27 §3.2.1); read by `mcpp why flags`. + struct SharedImage { + std::filesystem::path image; + std::string reason; + }; + std::vector sharedImages; std::vector linkFlags; // per-link edge flags // The loader-tag flag for THIS unit's form (mcpp.build.loader_contract). // Separate from linkFlags because its correctness is positional: gcc specs @@ -3358,7 +3366,7 @@ make_plan(const mcpp::manifest::Manifest& manifest, // package reached the unit by its interface rather than by an edge of the // package linked, so an image already on the line, or the unit's own, is // not added again. - auto append_shared_image = [&](LinkUnit& lu, std::size_t depIndex, bool followed) { + auto append_shared_image = [&](LinkUnit& lu, std::size_t depIndex, bool followed, std::size_t of) { auto targetsIt = sharedTargetsByPackage.find(depIndex); if (targetsIt == sharedTargetsByPackage.end()) return; for (auto targetIndex : targetsIt->second) { @@ -3366,6 +3374,10 @@ make_plan(const mcpp::manifest::Manifest& manifest, if (followed && (dep.output == lu.output || std::ranges::contains(lu.implicitInputs, dep.output))) continue; lu.implicitInputs.push_back(dep.output); + const auto ofName = of < packages.size() ? qualified_package_name(packages[of].manifest) : std::string{}; + lu.sharedImages.push_back({dep.output, followed + ? std::format("its interface reaches a compile of {}", ofName) + : std::format("a direct dependency of {}", ofName)}); // On PE what the consumer actually LINKS is the import library, // so that is the file the edge has to wait for — the `.dll` // above is still a prerequisite because it must exist beside the @@ -3464,8 +3476,8 @@ make_plan(const mcpp::manifest::Manifest& manifest, // the dependency slot after them. auto append_direct_shared_deps = [&](LinkUnit& lu, std::size_t packageIndex) { if (auto depsIt = directPackageDeps.find(packageIndex); depsIt != directPackageDeps.end()) - for (auto depIndex : depsIt->second) append_shared_image(lu, depIndex, false); - for (auto depIndex : interface_packages_of(packageIndex)) append_shared_image(lu, depIndex, true); + for (auto depIndex : depsIt->second) append_shared_image(lu, depIndex, false, packageIndex); + for (auto depIndex : interface_packages_of(packageIndex)) append_shared_image(lu, depIndex, true, packageIndex); }; auto append_shared_deps_for_linked_objects = [&](LinkUnit& lu) { diff --git a/src/build/prepare/host_graph.cpp b/src/build/prepare/host_graph.cpp index a87e1e102..e32268275 100644 --- a/src/build/prepare/host_graph.cpp +++ b/src/build/prepare/host_graph.cpp @@ -958,9 +958,27 @@ build_group(PrepareState& state, const fs::path& dir, const std::vector ~Quiet() { mcpp::ui::set_quiet(prev); } } quiet; auto ctx = prepare_build(/*print_fingerprint=*/false, /*includeDevDeps=*/false, {}, sub); - if (!ctx) - return std::unexpected(std::format("planning the build programs failed: {}{}", - ctx.error(), reproduce())); + if (!ctx) { + // THE MESSAGE NAMES THE USER'S OBJECTS (design 2026-11-27 §10, G5): the + // build programs it is for, and, for a refusal about the toolchain, the + // statement of the main project that chose it. The sub-build's code is + // kept for the outer refusal. + const auto code = refusal::take_refused(); + refusal::record(code); + std::string names; + for (auto const& p : all) + names += std::format("{}'{}'", names.empty() ? "" : ", ", qualified(manifest_of(state, p.index))); + std::string toolchain; + using C = refusal::Code; + if (state.m && (code == C::LocalToolchain || code == C::TargetBase || code == C::ToolchainHasNoArchiver + || code == C::CompilerWithoutModules || code == C::StdModulePrecompile)) + if (const int line = state.m->toolchain.line_for(kCurrentPlatform); line > 0) + toolchain = std::format("\n the toolchain is the one {}:{} names ([toolchain])", + path_text(state.m->sourcePath), line); + return std::unexpected(std::format("build program{} {}: planning failed: {}{}{}", + all.size() == 1 ? "" : "s", names, ctx.error(), toolchain, + reproduce())); + } timer.mark("planned"); describe(*ctx); if (goals.empty()) return std::map{}; diff --git a/src/build/prepare/local_toolchain.cpp b/src/build/prepare/local_toolchain.cpp index df368a587..7f3c588d9 100644 --- a/src/build/prepare/local_toolchain.cpp +++ b/src/build/prepare/local_toolchain.cpp @@ -23,6 +23,9 @@ import mcpp.invocation; import mcpp.toolchain.registry; 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.diag; import mcpp.ui; namespace mcpp::build { @@ -134,6 +137,48 @@ std::string local_identity(const mcpp::toolchain::Toolchain& tc, const mcpp::man return std::format("{:016x}", h); } +// THE ARCHIVER OF A TREE NAMED BY PATH (design 2026-11-27 §3.1.2): the stated +// one, else the tree's (`ar`, `llvm-ar`, `ar` beside the driver), else +// the host's, by the same names on PATH -- an absolute path, stated as a tool +// so the identity holds its stamp, and reported as a degradation (`--strict` +// refuses). A bare name is never written into the build. Whether it reads a +// response file is asked once; one that does not is given the words. +std::expected resolve_tree_archiver(mcpp::toolchain::Toolchain& tc) { + using Fact = mcpp::toolchain::Toolchain::TreeFact; + std::string source = tc.tool_override("ar") ? "stated" : "the tree"; + auto archiver = mcpp::toolchain::archive_tool(tc); + if (archiver.empty()) { + std::vector names; + for (auto n : {tc.toolPrefix + "ar", std::string("llvm-ar"), std::string("ar")}) + if (std::ranges::find(names, n) == names.end()) names.push_back(std::move(n)); + for (auto const& n : names) + if (auto found = mcpp::invocation::which(n)) { archiver = *found; break; } + if (archiver.empty()) { + std::string looked; + for (auto const& n : names) looked += (looked.empty() ? "" : ", ") + n; + refusal::record(refusal::Code::ToolchainHasNoArchiver); + return std::unexpected(std::format( + "[toolchain-has-no-archiver] the toolchain named by path '{}' has no archiver: {} were looked " + "for in '{}' and on PATH\n" + " help: name one in the [toolchain] table: `tools = {{ ar = \"\" }}`", + tc.localRoot.generic_string(), looked, tc.binaryPath.parent_path().generic_string())); + } + tc.toolOverrides.push_back({"ar", archiver}); + source = "the host's PATH"; + mcpp::diag::degraded("build/archiver-from-host", + std::format("the archiver for this build is the host's ('{}'): the toolchain at '{}' carries none", + archiver.generic_string(), tc.localRoot.generic_string()), + "two machines may archive with different archivers", + std::format("state it in the [toolchain] table: `tools = {{ ar = \"{}\" }}`", archiver.generic_string())); + } + std::string why; + tc.archiverTakesResponseFiles = mcpp::toolchain::archiver_takes_response_files(archiver, {}, &why); + tc.treeFacts.push_back(Fact{"archiver", std::format("{} ({}){}", archiver.generic_string(), source, + tc.archiverTakesResponseFiles ? std::string{} + : std::format("; takes its arguments directly, the response file expanded by mcpp ({})", why))}); + return {}; +} + } // namespace std::optional, std::string>> take_toolchain_restart() { @@ -263,9 +308,27 @@ step2_use_local_toolchain(PrepareState& state, const mcpp::toolchain::ToolchainS family = spec.family == mcpp::toolchain::Family::Llvm ? "llvm" : "gcc"; fs::path driver; for (auto const& [role, p] : lt.tools) if (role == "cxx") driver = p; - if (driver.empty()) + if (driver.empty()) { driver = root / "bin" / (lt.prefix + (family == "llvm" ? "clang++" : "g++") + std::string(mcpplibs::os::exe_suffix)); + // A TREE THAT HOLDS BOTH FAMILIES (`/usr`): the one taken is said once, + // with the key that takes the other (design 2026-11-27 §10.2). + const auto other = root / "bin" / (lt.prefix + (family == "llvm" ? "g++" : "clang++") + + std::string(mcpplibs::os::exe_suffix)); + if (lt.family.empty() && fs::exists(driver, ec) && fs::exists(other, ec)) { + auto version = [](const fs::path& d) { + auto r = mcpp::toolchain::run_capture({d.string(), "-dumpversion"}); + return r ? mcpp::toolchain::trim_line(mcpp::toolchain::first_line_of(*r)) : std::string("?"); + }; + const auto clang = family == "llvm" ? driver : other, gcc = family == "llvm" ? other : driver; + mcpp::diag::notice(mcpp::diag::Severity::Note, "toolchain/tree-holds-two-families", + root.generic_string(), + std::format("'{}' holds clang {} and gcc {}; {} is used", root.generic_string(), + version(clang), version(gcc), family == "llvm" ? "clang" : "gcc"), + std::format("`family = \"{}\"` in the [toolchain] table uses the other", + family == "llvm" ? "gcc" : "llvm")); + } + } if (!fs::exists(driver, ec)) return refuse(std::format("no C++ driver at '{}'; a {} toolchain keeps it in " "`/bin/{}{}`, or names it with `tools = {{ cxx = ... }}`", @@ -344,6 +407,7 @@ std::expected step2_apply_local_toolchain(PrepareState& state } tc.launcher = l.generic_string(); } + if (auto r = resolve_tree_archiver(tc); !r) return std::unexpected(r.error()); // A stated sysroot is the target's base, resolved with every other // statement of it (base.cpp), not here. tc.driverIdent += "\nmcpp-local-toolchain " + local_identity(tc, lt); @@ -360,6 +424,82 @@ std::expected step2_apply_local_toolchain(PrepareState& state return {}; } +// 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; + auto& tc = *state.tc; + using Fact = mcpp::toolchain::Toolchain::TreeFact; + 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())}); + } else { + fs::path lld; + 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())}); + } + auto has = [&](std::vector w, std::string_view question) { + w.insert(w.begin(), base.begin(), base.end()); + const fs::path p(mcpp::toolchain::ask_driver(tc.binaryPath, w, question, env)); + return p.is_absolute() && fs::is_regular_file(p, ec) ? p : fs::path{}; + }; + if (auto rt = has({"--rtlib=compiler-rt"}, "-print-libgcc-file-name"); !rt.empty()) { + words.push_back("--rtlib=compiler-rt"); + tc.treeFacts.push_back(Fact{"compiler runtime", std::format("compiler-rt ({})", rt.generic_string())}); + } else { + tc.treeFacts.push_back(Fact{"compiler runtime", "the driver's default (no compiler-rt answered)"}); + } + fs::path unwind; + for (std::string_view lib : {"--print-file-name=libunwind.a", "--print-file-name=libunwind.so", + "--print-file-name=libunwind.dylib"}) + if (unwind.empty()) unwind = has({}, lib); + if (!unwind.empty()) words.push_back("--unwindlib=libunwind"); + tc.treeFacts.push_back(Fact{"unwinder", unwind.empty() ? std::string("the driver's default (no libunwind answered)") + : std::format("libunwind ({})", unwind.generic_string())}); + tc.treeLinkWords = std::move(words); + std::string why; + 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)}); +} + +// ONE PACKAGE AT TWO VERSIONS, ONE FOR EACH PURPOSE (design 2026-11-27 D8): +// `[toolchain]` names the compiler of this build and `[xlings.workspace]` a +// package on the PATH of the programs the build starts. Both are provided, as +// before; the pair is said once, with what each governs. +void step2_toolchain_in_workspace(PrepareState& state) { + if (!state.tcSpec || state.tcSpec->starts_with("path:") || !state.m) return; + auto spec = mcpp::toolchain::parse_toolchain_spec(*state.tcSpec); + if (!spec || spec->version.empty() || spec->version == "system") return; + const auto pkg = mcpp::toolchain::to_xim_package(*spec); + for (auto const& [key, value] : state.m->xlings.workspace) { + const auto name = key.contains(':') ? key.substr(key.find(':') + 1) : key; + if (name != pkg.ximName || value.empty()) continue; + // A version prefix names the versions it begins (`22` holds 22.1.8). + const bool same = pkg.ximVersion == value || pkg.ximVersion.starts_with(value + "."); + if (same) continue; + mcpp::diag::notice(mcpp::diag::Severity::Note, "xlings/package-at-two-versions", name, + std::format("{} is named twice: [toolchain] uses {}@{}, which compiles this build, and " + "[xlings.workspace] names {} = \"{}\", which is on the PATH of the programs the " + "build starts", name, name, pkg.ximVersion, key, value), + "drop one of the two, or keep both where both are wanted"); + } +} + std::expected step6_toolchain_phase(PrepareState& state) { if (!state.toolchainConfigure || !state.overrides.toolchain_statement.empty()) return {}; if (!std::filesystem::exists(*state.root / "build.mcpp")) { diff --git a/src/build/prepare/scan.cpp b/src/build/prepare/scan.cpp index d0e1d8aa9..a8a6f41cd 100644 --- a/src/build/prepare/scan.cpp +++ b/src/build/prepare/scan.cpp @@ -1435,11 +1435,25 @@ step11_cxx_compiler_gate(PrepareState& state) { else if (u.kind == mcpp::SourceKind::ModuleInterface) needs = "is a module interface by its extension"; if (needs.empty()) continue; + refusal::record(refusal::Code::CompilerWithoutModules); + if (state.tc->compiler == mcpp::toolchain::CompilerId::GCC) + return std::unexpected(std::format( + "[compiler-without-modules] {} has no C++ modules, which GCC provides from 14: {} {}. C++ " + "sources that declare and import no module, and C sources, build with it.\n" + " help: a program of modules on {} needs a toolchain of GCC 14 or later, or Clang", + state.tc->label(), u.relPath.generic_string(), needs, state.tc->targetTriple)); + std::string probed; + for (auto const& f : state.tc->treeFacts) + if (f.name == "C++ modules") probed = f.value; return std::unexpected(std::format( - "{} has no C++ modules, which GCC provides from 14: {} {}. C++ sources that declare " - "and import no module, and C sources, build with it.\n" - " help: a program of modules on {} needs a toolchain of GCC 14 or later, or Clang", - state.tc->label(), u.relPath.generic_string(), needs, state.tc->targetTriple)); + "[compiler-without-modules] {} ({}) did not compile a module unit{}: {} {}. C++ sources " + "that declare and import no module, and C sources, build with it.\n" + " help: name a toolchain with C++ modules (`mcpp toolchain list`), point " + "`tools.cxx` at a driver script that adds the word the driver needs, or build no " + "module units for {}", + state.tc->label(), state.tc->binaryPath.generic_string(), + probed.empty() ? std::string{} : std::format(" ({})", probed), + u.relPath.generic_string(), needs, state.tc->targetTriple)); } return {}; } diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index 8b6907851..b338b8333 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -1605,6 +1605,11 @@ std::expected step2_retarget_for_retargetable_driver(PrepareS // The std module source asked of a clang driver with the build's words, held to // the build's roots (design 2026-11-27 §3.1.3). 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); +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); // The platform root a first pass asks the second to read in P1, once. diff --git a/src/build/prepare/target_side.cpp b/src/build/prepare/target_side.cpp index 8c28b6277..74bed259e 100644 --- a/src/build/prepare/target_side.cpp +++ b/src/build/prepare/target_side.cpp @@ -340,6 +340,7 @@ step9_gather_target_side_candidates(PrepareState& state) { // checked against and so the report can show the whole stack. in.compilerFamily = std::string(state.tc->compiler_family()); in.compilerVersion = state.tc->version; + in.compilerFromTree = !state.tc->localRoot.empty(); // WHETHER THE PAYLOAD HAS A COMPILER RUNTIME FOR AN APPLE CROSS // TARGET, read from the payload's own resource directory. Clang's // Darwin driver adds `libclang_rt..a` from there when diff --git a/src/build/prepare/toolchain_resolver.cpp b/src/build/prepare/toolchain_resolver.cpp index 69d6759ed..0b3b8f18f 100644 --- a/src/build/prepare/toolchain_resolver.cpp +++ b/src/build/prepare/toolchain_resolver.cpp @@ -1047,6 +1047,8 @@ 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); + step2_toolchain_in_workspace(state); if (auto r = step2_resolve_run_under(state); !r) return std::unexpected(r.error()); step2_windows_runtime_identity(state); if (auto r = step2_msvc_abi_without_msvc_repair(state); !r) return std::unexpected(r.error()); diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index e738271fe..e1f8075c9 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -255,6 +255,11 @@ enum class Code { VcsUnavailable, // A test program and an executable target of one package write one file. TestOutputCollision, + // A toolchain named by path has no archiver, in its tree or on PATH. + ToolchainHasNoArchiver, + // A unit declares or imports a module, and the compiler has no C++ + // modules: GCC before 14, or a tree's driver that refused a module unit. + CompilerWithoutModules, Other, // a refusal that has not been given a code yet }; @@ -332,6 +337,8 @@ constexpr std::string_view name(Code c) { case Code::LockUnavailable: return "lock-unavailable"; case Code::VcsUnavailable: return "vcs-unavailable"; case Code::TestOutputCollision: return "test-output-collision"; + case Code::ToolchainHasNoArchiver: return "toolchain-has-no-archiver"; + case Code::CompilerWithoutModules: return "compiler-without-modules"; case Code::Other: return "other"; } return "other"; diff --git a/src/cli.cppm b/src/cli.cppm index 066981f26..e7fce8856 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -1149,6 +1149,7 @@ mcpplibs::cmdline::App command_tree(const std::vector& passthrough, .option(cl::Option("aside").help("move the previous artifact aside first (a Windows host)")) .option(cl::Option("temporary").help("link under a temporary name in the artifact's directory, then rename it over the artifact (POSIX)")) .option(cl::Option("text").takes_value().value_name("ENCODING").help("`console`: the command writes its text in the console's code page, which is read as UTF-8 (link.exe, lib.exe)")) + .option(cl::Option("expand").help("replace each `@file` with the words it holds, and run an archiver's command once per batch the host's command line holds (an archiver that takes no response file)")) .action([&passthrough](const cl::ParsedArgs& p) { return cmd_link_output(p, std::span(passthrough)); })) diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index edf5e97d8..11fb35a30 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -21,6 +21,7 @@ import mcpp.build.coff_exports; import mcpp.build.pe_exports; import mcpp.modgraph.glob; // escaped_spelling, for coff-def's warning import mcpp.build.stage; +import mcpp.build.command_line; // response_file_words, for --expand import mcpp.build.schedule.detach_codegen; import mcpp.build.test_targets; import mcpp.build.test_schedule; // --shard, --failed @@ -48,6 +49,7 @@ import mcpp.config; import mcpp.fetcher.progress; // bootstrap progress for load_or_init import mcpp.pm.bundle; // `mcpp fetch --to`, `--from` import mcpplibs.os.env; +import mcpplibs.os.platform; // link-output --expand: the host's command-line limit import mcpp.ui.terminal; import mcpp.project; import mcpp.manifest; @@ -1958,19 +1960,76 @@ export int cmd_dyndep(const mcpplibs::cmdline::ParsedArgs& parsed) { // `--text console` (design 2026-11-19 §20 T2): link.exe and lib.exe write their // text in the console's code page, so the command's two streams are read // through one pipe and written on as UTF-8, the text of everything mcpp reads. +// +// `--expand` (design 2026-11-27 §3.1.2): an archiver that reads `@file` as a +// member's name is given the words the file holds. When they do not fit on the +// host's command line, the command runs once per batch, its words before the +// response file and after it repeated: `ar rcs out.a ` adds the batch's +// members and indexes the archive, so the batches together leave the archive +// the one command would have written. export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, - std::span command) { + std::span given) { namespace fs = std::filesystem; + // Its one way to say a refusal: this command runs under ninja, whose + // output is the build's, so the line is the command's own. + auto fail = [](std::string_view why, int rc = 2) { + std::println(libc::stderr(), "error: link-output{}", why); + return rc; + }; const fs::path out = parsed.option_or_empty("output").value(); - if (out.empty() || command.empty()) { - std::println(libc::stderr(), "error: link-output needs --output -- "); - return 2; + if (out.empty() || given.empty()) return fail(" needs --output -- "); + std::vector expanded(given.begin(), given.end()); + if (parsed.is_flag_set("expand")) { + std::vector head, members, tail; + bool seen = false; + for (auto const& word : given) { + if (!seen && word.size() > 1 && word.front() == '@') { + std::ifstream in(word.substr(1), std::ios::binary); + if (!in) return fail(std::format(" --expand: cannot read {}", word.substr(1))); + const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + members = mcpp::build::command_line::response_file_words(text); + seen = true; + continue; + } + (seen ? tail : head).push_back(word); + } + // The host's limit, with room for the environment: cmd.exe and + // CreateProcess take 32 767 characters; a POSIX argument list takes + // far more, and one argument at most 128 KiB. + constexpr std::size_t kLine = mcpplibs::os::is_windows ? 30000 : 131072; + std::size_t fixed = 0; + for (auto const& w : head) fixed += w.size() + 1; + for (auto const& w : tail) fixed += w.size() + 1; + std::vector> batches(1); + std::size_t used = fixed; + for (auto& m : members) { + if (!batches.back().empty() && used + m.size() + 1 > kLine) { + batches.emplace_back(); + used = fixed; + } + used += m.size() + 1; + batches.back().push_back(std::move(m)); + } + auto argv_of = [&](const std::vector& batch) { + std::vector argv = head; + argv.insert(argv.end(), batch.begin(), batch.end()); + argv.insert(argv.end(), tail.begin(), tail.end()); + return argv; + }; + if (batches.size() > 1) { + for (auto const& batch : batches) + if (const int rc = mcpp::run::execute(argv_of(batch), {.input = mcpp::run::Input::inherit, + .streams = mcpp::run::Streams::inherit}) + .exit_code; + rc != 0) + return rc; + return 0; + } + expanded = argv_of(batches.front()); } + const std::span command(expanded); const std::string text = parsed.option_or_empty("text").value(); - if (!text.empty() && text != "console") { - std::println(libc::stderr(), "error: link-output: --text takes `console`, not `{}`", text); - return 2; - } + if (!text.empty() && text != "console") return fail(std::format(": --text takes `console`, not `{}`", text)); // The linker, on this program's streams or through the decoding pipe. auto run_linker = [&](const std::vector& argv) { if (text.empty()) @@ -2003,11 +2062,8 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, auto named = std::ranges::adjacent_find(argv, [&](const std::string& a, const std::string& b) { return a == "-o" && fs::path(b) == out; }); - if (named == argv.end()) { - std::println(libc::stderr(), "error: link-output --temporary: the linker command names no `-o {}`", - out.string()); - return 2; - } + if (named == argv.end()) + return fail(std::format(" --temporary: the linker command names no `-o {}`", out.string())); *std::next(named) = temporary.string(); if (const int linked = run_linker(argv); linked != 0) { fs::remove(temporary, ec); @@ -2015,10 +2071,10 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, } fs::rename(temporary, out, ec); if (ec) { - std::println(libc::stderr(), "error: link-output: cannot rename {} over {}: {}", - temporary.string(), out.string(), ec.message()); + const auto why = std::format(": cannot rename {} over {}: {}", temporary.string(), out.string(), + ec.message()); fs::remove(temporary, ec); - return 1; + return fail(why, 1); } return 0; } diff --git a/src/doctor.cppm b/src/doctor.cppm index 3eb345102..d81ed4b63 100644 --- a/src/doctor.cppm +++ b/src/doctor.cppm @@ -1771,6 +1771,10 @@ export int why_report(const std::string& topic, const std::string& features, for (auto const& w : o.link) std::println(" {:<9} {}{}", w.layer, w.word, w.detail.empty() ? std::string{} : std::format(" [{}]", w.detail)); + for (auto const& u : o.images) { + std::println("shared images on the link of {}:", u.file); + for (auto const& w : u.words) std::println(" {} [{}]", w.word, w.detail); + } return 0; } @@ -1790,6 +1794,23 @@ export int why_report(const std::string& topic, const std::string& features, std::println(" reason: {}{}", ctx->compilerChoice.origin, ctx->compilerChoice.requiredBy.empty() ? std::string{} : " (" + ctx->compilerChoice.requiredBy + ")"); + // The std module source with where it came from, and the answers a + // driver gave that lay outside the build's roots (design 2026-11-27 + // §3.1.3); a tree's facts with their sources (§3.1.2). + std::println(" std module: {}", !tc.hasImportStd ? std::string("none") + : std::format("{} ({})", tc.stdModuleSource.generic_string(), + !tc.base.layers.stdModule.empty() ? "the target base's" + : !tc.pairedSysroot.empty() ? "the paired system's" + : "the driver's answer")); + if (!tc.stdModuleRejected.empty()) { + std::println(" answers not taken (outside the toolchain's tree and the target base):"); + for (auto line : std::views::split(std::string_view(tc.stdModuleRejected), '\n')) { + std::string_view l(line.begin(), line.end()); + while (l.starts_with(' ')) l.remove_prefix(1); + std::println(" {}", l); + } + } + for (auto const& f : tc.treeFacts) std::println(" {}: {}", f.name, f.value); if (!ctx->manifest.package.platforms.empty()) { std::string ps; for (auto& p : ctx->manifest.package.platforms) { diff --git a/src/explain.cppm b/src/explain.cppm index 2c4e11197..4e23cde5d 100644 --- a/src/explain.cppm +++ b/src/explain.cppm @@ -362,6 +362,15 @@ constexpr Entry kEntries[] = { "tests/app_test.cpp, tests/app/ to tests/app_test/), or give the executable\n" "target another name. Where the file system does not distinguish case,\n" "names that differ only in case are one file."}, + {"toolchain-has-no-archiver", Kind::Reason, + "a toolchain named by path has no archiver, in its tree or on PATH", + "Name the archiver in the [toolchain] table:\n" + " default = { path = \"/opt/llvm\", tools = { ar = \"/usr/bin/ar\" } }"}, + {"compiler-without-modules", Kind::Reason, + "a unit declares or imports a module, and the compiler has no C++ modules (GCC before 14, or a tree's driver that refused a module unit)", + "Name a toolchain with C++ modules (mcpp toolchain list), point tools.cxx at a\n" + "driver script that adds the word the driver needs, or build no module units\n" + "for this target."}, {"other", Kind::Reason, "a refusal whose branch has not been given a token yet", "Read the message: it names the cause and the remedy. Report the case so\n" diff --git a/src/toolchain/clang.cpp b/src/toolchain/clang.cpp index 407966602..4f8335fc2 100644 --- a/src/toolchain/clang.cpp +++ b/src/toolchain/clang.cpp @@ -11,6 +11,7 @@ import mcpp.provider.select; import mcpplibs.os.platform; import mcpp.build.command_line; import mcpp.run; +import mcpp.libs.path_identity; // tree_roots: the tree a driver's link leads to namespace mcpp::toolchain::clang { @@ -150,11 +151,9 @@ std::vector tree_roots(const Toolchain& tc) { const auto tree = tc.localRoot.empty() ? tc.binaryPath.parent_path().parent_path() : tc.localRoot; std::vector roots{tree}; const auto rel = tc.binaryPath.lexically_normal().lexically_relative(tree.lexically_normal()); - if (!rel.empty() && *rel.begin() != "..") { - std::error_code ec; - if (auto real = std::filesystem::weakly_canonical(tc.binaryPath, ec); !ec) - if (auto resolved = real.parent_path().parent_path(); resolved != tree) roots.push_back(resolved); - } + 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); return roots; } diff --git a/src/toolchain/hostflags.cppm b/src/toolchain/hostflags.cppm index 81330964d..64a57c99d 100644 --- a/src/toolchain/hostflags.cppm +++ b/src/toolchain/hostflags.cppm @@ -659,6 +659,12 @@ 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). + if (is_clang(tc)) + if (auto* ld = tc.tool_override("ld")) out.push_back("--ld-path=" + esc(*ld)); + const bool bypassCfg = dm.hasCfg && (opt.cfgBypass == HostFlagOptions::CfgBypass::Always || (opt.cfgBypass == HostFlagOptions::CfgBypass::LinuxOnly @@ -689,7 +695,8 @@ std::vector host_link_tokens(const Toolchain& tc, // // lld ships with the very toolchain doing the compile, so it cannot // be diverted to a libc++ it was not built against. - if constexpr (mcpplibs::os::is_macos) out.push_back("-fuse-ld=lld"); + if constexpr (mcpplibs::os::is_macos) + if (std::ranges::contains(dm.linkWords, std::string("-fuse-ld=lld"))) out.push_back("-fuse-ld=lld"); // AND DELIBERATELY NOT THE TOOLCHAIN'S RUNTIME DIRECTORIES. THIS WAS // TRIED, AND WHAT IT COSTS IS RECORDED HERE RATHER THAN REDISCOVERED. // diff --git a/src/toolchain/probe.cppm b/src/toolchain/probe.cppm index abc01add9..e3fffaa7d 100644 --- a/src/toolchain/probe.cppm +++ b/src/toolchain/probe.cppm @@ -19,6 +19,7 @@ import mcpp.build.command_line; import mcpp.run; import mcpp.log; import mcpp.home; // the probe cache lives under the home's cache +import mcpp.libs.path_identity; // inside_roots: a file and a root compared as the same object import mcpp.toolchain.fingerprint; // hash_string import mcpp.fallback.sysroot_complete; import mcpp.fallback.probe_sysroot; @@ -78,6 +79,22 @@ bool linker_reports_inputs(const std::vector& argv, bool direct, // driver's identity. bool driver_takes_dumpdir(const std::filesystem::path& compiler, const mcpp::run::Env& env = {}); +// WHAT A TREE NAMED BY PATH CAN DO, ASKED ONCE (design 2026-11-27 §3.1.2). +// Each answer is kept under the program's identity and the words, as the +// `-dumpdir` answer is; `why`, when given, receives the first line the +// program wrote when the answer is no. +// +// Whether `archiver` reads `@file` as the words the file holds: a text file +// is archived through a response file and the archive listed (an archiver +// takes any file, so nothing is compiled). BSD archivers take the word as a +// member's name. +bool archiver_takes_response_files(const std::filesystem::path& archiver, const mcpp::run::Env& env = {}, + std::string* why = nullptr); +// Whether `compiler`, given `words`, compiles a two-line module unit (`export +// module`, one exported function) to an object. +bool driver_compiles_modules(const std::filesystem::path& compiler, const std::vector& words, + const mcpp::run::Env& env = {}, std::string* why = nullptr); + std::string extract_version(std::string_view s); std::string first_line_of(std::string_view s); std::string lower_copy(std::string_view s); @@ -324,45 +341,127 @@ bool linker_reports_inputs(const std::vector& argv, bool direct, return answered[key] = yes; } -bool driver_takes_dumpdir(const std::filesystem::path& compiler, const mcpp::run::Env& env) { +namespace { + +// ONE PROBE, ASKED ONCE AND KEPT: `ask` runs in `work` (the kept directory, or +// a temporary one for a run that writes no global cache) and answers yes or no +// with the program's first line. The answer is kept under `key` in +// `cache/probe//` by a run that writes the global cache, and only when +// the program answered (it started); a query (`self env`, `toolchain list`) +// asks and keeps nothing, and a cold home is not created for it. +struct ProbeAnswer { + bool yes = false; + std::string line; // the program's first line, when the answer is no + bool answered = true; // false: the program did not start +}; +bool kept_probe(std::string_view kind, const std::string& key, std::string* why, + const std::function& ask) { static std::mutex mutex; - static std::map answered; - const auto key = probe_cache_key({compiler.string(), "-dumpdir"}, env, true); + static std::map> answered; + const auto memo = std::string(kind) + "\x1d" + key; std::lock_guard lock(mutex); - if (auto it = answered.find(key); it != answered.end()) return it->second; - const auto kept = mcpp::home::root() / "cache" / "probe" / "dumpdir"; - const auto answer = kept / (mcpp::toolchain::hash_string(key) + ".answer"); - if (std::ifstream in(answer); in) { - std::string v; + auto give = [&](bool yes, std::string line) { + if (why) *why = line; + answered[memo] = {yes, std::move(line)}; + return yes; + }; + if (auto it = answered.find(memo); it != answered.end()) return give(it->second.first, it->second.second); + const auto kept = mcpp::home::root() / "cache" / "probe" / std::string(kind); + const auto file = kept / (mcpp::toolchain::hash_string(key) + ".answer"); + if (std::ifstream in(file); in) { + std::string v, line; in >> v; - if (v == "yes" || v == "no") return answered[key] = (v == "yes"); + std::getline(in >> std::ws, line); + if (v == "yes" || v == "no") return give(v == "yes", line); } - // Asked, by a query too (`self env`, `toolchain list`), in a directory of - // its own; only a run that writes the global cache keeps the answer, and a - // cold home is not created for a query. const bool keep = mcpp::effects::writes_global_cache(); const auto work = keep ? kept - : std::filesystem::temp_directory_path() / std::format("mcpp-dumpdir-{:x}", std::random_device{}()); + : std::filesystem::temp_directory_path() / std::format("mcpp-{}-{:x}", kind, std::random_device{}()); std::error_code ec; std::filesystem::create_directories(work, ec); - const auto src = work / "empty.c"; - if (!std::filesystem::exists(src, ec)) std::ofstream(src, std::ios::binary).flush(); - const auto stem = work / std::format("probe-{:x}", std::random_device{}()); - const auto object = stem.string() + ".o"; - auto r = mcpp::run::execute({compiler.string(), "-dumpdir", stem.string() + ".", "-c", "-x", "c", - src.string(), "-o", object}, - {.env = env, .host_tool = true, .streams = mcpp::run::Streams::merged, - .report_spawn_failure = false}); - // A word a driver knows and does not use is said in a warning, which - // names it: such a driver is not taken as naming its outputs from it. - const bool yes = r.exit_code == 0 && r.output.find("dumpdir") == std::string::npos; - std::filesystem::remove(object, ec); + const auto a = ask(work); if (!keep) std::filesystem::remove_all(work, ec); - mcpp::log::verbose("toolchain", std::format("'{}' takes -dumpdir: {}{}", compiler.string(), - yes ? "yes" : "no", yes ? std::string{} : " (" + first_line_of(r.output) + ")")); - // An answer the driver did not give (it did not start) is not kept. - if (keep && (yes || !r.output.empty())) std::ofstream(answer) << (yes ? "yes\n" : "no\n"); - return answered[key] = yes; + if (keep && a.answered) std::ofstream(file) << (a.yes ? "yes\n" : "no\n") << a.line << "\n"; + return give(a.yes, a.yes ? std::string{} : a.line); +} + +} // namespace + +bool driver_takes_dumpdir(const std::filesystem::path& compiler, const mcpp::run::Env& env) { + const auto key = probe_cache_key({compiler.string(), "-dumpdir"}, env, true); + return kept_probe("dumpdir", key, nullptr, [&](const std::filesystem::path& work) { + std::error_code ec; + const auto src = work / "empty.c"; + if (!std::filesystem::exists(src, ec)) std::ofstream(src, std::ios::binary).flush(); + const auto stem = work / std::format("probe-{:x}", std::random_device{}()); + const auto object = stem.string() + ".o"; + auto r = mcpp::run::execute({compiler.string(), "-dumpdir", stem.string() + ".", "-c", "-x", "c", + src.string(), "-o", object}, + {.env = env, .host_tool = true, .streams = mcpp::run::Streams::merged, + .report_spawn_failure = false}); + // A word a driver knows and does not use is said in a warning, which + // names it: such a driver is not taken as naming its outputs from it. + const bool yes = r.exit_code == 0 && r.output.find("dumpdir") == std::string::npos; + std::filesystem::remove(object, ec); + mcpp::log::verbose("toolchain", std::format("'{}' takes -dumpdir: {}{}", compiler.string(), + yes ? "yes" : "no", yes ? std::string{} : " (" + first_line_of(r.output) + ")")); + // An answer the driver did not give (it did not start) is not kept. + return ProbeAnswer{yes, first_line_of(r.output), yes || !r.output.empty()}; + }); +} + +bool archiver_takes_response_files(const std::filesystem::path& archiver, const mcpp::run::Env& env, + std::string* why) { + const auto key = probe_cache_key({archiver.string(), "@response-file"}, env, true); + return kept_probe("archiver-rsp", key, why, [&](const std::filesystem::path& work) { + std::error_code ec; + const auto tag = std::format("{:x}", std::random_device{}()); + const auto member = work / ("member-" + tag + ".txt"); + const auto list = work / ("list-" + tag + ".rsp"); + const auto archive = work / ("probe-" + tag + ".a"); + std::ofstream(member, std::ios::binary) << "mcpp\n"; + std::ofstream(list, std::ios::binary) << member.string() << "\n"; + const mcpp::run::Options opts{.env = env, .host_tool = true, .streams = mcpp::run::Streams::merged, + .report_spawn_failure = false}; + auto made = mcpp::run::execute({archiver.string(), "rc", archive.string(), "@" + list.string()}, opts); + auto listed = made.exit_code == 0 + ? mcpp::run::execute({archiver.string(), "t", archive.string()}, opts) : made; + const bool yes = made.exit_code == 0 && listed.exit_code == 0 + && listed.output.find(member.filename().string()) != std::string::npos; + for (auto const& f : {member, list, archive}) std::filesystem::remove(f, ec); + const auto line = first_line_of(made.exit_code != 0 ? made.output : listed.output); + mcpp::log::verbose("toolchain", std::format("'{}' takes a response file: {}{}", archiver.string(), + yes ? "yes" : "no", yes ? std::string{} : " (" + line + ")")); + return ProbeAnswer{yes, line, yes || !made.output.empty() || made.exit_code == 0}; + }); +} + +bool driver_compiles_modules(const std::filesystem::path& compiler, const std::vector& words, + const mcpp::run::Env& env, std::string* why) { + std::vector argv{compiler.string()}; + argv.insert(argv.end(), words.begin(), words.end()); + auto key = probe_cache_key(argv, env, true); + key += "\x1fexport-module"; + return kept_probe("modules", key, why, [&](const std::filesystem::path& work) { + std::error_code ec; + const auto tag = std::format("{:x}", std::random_device{}()); + const auto unit = work / ("probe-" + tag + ".cppm"); + const auto object = work / ("probe-" + tag + ".o"); + std::ofstream(unit, std::ios::binary) << "export module mcpp_probe;\nexport int mcpp_probe() { return 0; }\n"; + auto cmd = argv; + for (auto const& a : {std::string("-std=c++20"), std::string("-x"), std::string("c++-module"), + std::string("-c"), unit.string(), std::string("-o"), object.string()}) + cmd.push_back(a); + auto r = mcpp::run::execute(cmd, {.env = env, .host_tool = true, .streams = mcpp::run::Streams::merged, + .report_spawn_failure = false}); + const bool yes = r.exit_code == 0 && std::filesystem::is_regular_file(object, ec); + for (auto const& f : {unit, object}) std::filesystem::remove(f, ec); + // clang writes a module unit's BMI beside the object when asked for one + // only; nothing else is left. + mcpp::log::verbose("toolchain", std::format("'{}' compiles a module unit: {}{}", compiler.string(), + yes ? "yes" : "no", yes ? std::string{} : " (" + first_line_of(r.output) + ")")); + return ProbeAnswer{yes, first_line_of(r.output), yes || !r.output.empty()}; + }); } std::string ask_driver(const std::filesystem::path& compiler, const std::vector& words, @@ -382,16 +481,11 @@ 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; - auto spelled = [](const std::filesystem::path& p) { - std::error_code ec; - auto a = std::filesystem::absolute(p, ec); - return (ec ? p : a).lexically_normal(); - }; - auto resolved = [&](const std::filesystem::path& p) { - std::error_code ec; - auto c = std::filesystem::weakly_canonical(p, ec); - return ec ? spelled(p) : c.lexically_normal(); - }; + 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() != ".."; diff --git a/src/toolchain/provider.cppm b/src/toolchain/provider.cppm index 0861b3bc9..b95209d57 100644 --- a/src/toolchain/provider.cppm +++ b/src/toolchain/provider.cppm @@ -92,6 +92,9 @@ ProviderCapabilities capabilities_for(const Toolchain& tc) { bool msvc_target = is_msvc_target(tc); caps.has_scan_deps = true; // clang-scan-deps lives beside clang++ + // A tree named by path whose driver refused a module unit (probed, + // design 2026-11-27 §3.1.2) builds the units that use none. + caps.has_modules = tc.compilesModules; caps.stdlib_id = msvc_target ? "msvc-stl" : !tc.pairedSysroot.empty() && tc.base.layers.cxx != "libc++" ? "libstdc++" : "libc++"; diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index 3d48e0182..9967819b0 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -220,6 +220,75 @@ E2E custom{"custom", s::home_fixture, [] { expect(s::lacks(out, "another library was taken")) << out; }; + "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 + // why toolchain` names each with its source; the layer report says `custom`. A driver that + // refuses a module unit builds a program of no modules and refuses a module unit at + // planning with `[compiler-without-modules]`, naming the file. + 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); + for (std::string n : {"ld.lld", "ld64.lld", "lld-link", "lld", "wasm-ld"}) fs::remove(T / "bin" / n); + const auto log = work / "calls.log"; + const auto archiver = work / "ar-direct"; + s::write_executable(archiver, std::format( + "#!/bin/sh\nfor a in \"$@\"; do case \"$a\" in @*) echo \"ar-direct: '$a': no such member\" >&2; exit 1;; esac; done\n" + "echo \"ar-direct $*\" >> '{}'\nexec '{}/bin/llvm-ar' \"$@\"\n", log.string(), llvm_root.string())); + const auto table = std::format("[toolchain]\ndefault = {{ path = \"{}\", tools = {{ ar = \"{}\" }} }}\n", + T.string(), archiver.string()); + // A library package's own build archives it (a path dependency's objects are linked as they are). + s::project tally(work / "tally", { + {"mcpp.toml", "[package]\nname = \"tally\"\nversion = \"0.1.0\"\n\n[targets.tally]\nkind = \"lib\"\n\n" + table}, + {"src/tally.cppm", "export module tally;\nexport int tally_value() { return 42; }\n"}, + }); + const s::options o{.env = {{"NO_COLOR", "1"}}}; + auto r = tally.mcpp({"build"}, o); + expect(fatal(e2e::succeeded(r))) << s::text(r); + const auto calls = s::read_file(log); + expect(s::has_line(calls, R"(^ar-direct \S+ \S+\.a .*\.o)")) << "the archiver was not given the members:\n" << calls; + s::project app(work / "app", {{"src/main.cpp", "#include \nimport tally;\nint main() { std::printf(\"%d\\n\", tally_value()); }\n"}}); + app.write("mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\n" + "tally = { path = \"../tally\" }\n\n" + table); + r = app.mcpp({"build", "-v"}, o); + auto out = s::text(r); + expect(fatal(e2e::succeeded(r))) << out; + expect(s::has_line(out, R"(compiler +llvm .*\(.*custom\))")) << "the layer report does not say custom:\n" << out; + const auto bins = s::glob(app.at("target"), "*/*/bin/app"); + expect(fatal(!bins.empty())) << "no app"; + expect(e2e::contains(s::run(bins.front()).out, "42")); + std::string ninja; + for (const auto& n : s::glob(app.at("target"), "*/*/build.ninja")) ninja += s::read_file(n); + expect(s::lacks(ninja, "-fuse-ld=lld")) << "lld was named for a tree without it"; + r = app.mcpp({"why", "toolchain"}, o); + out = s::text(r); + expect(e2e::contains(out, "linker: the driver's default")) << out; + 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. + 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())); + 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" + "default = {{ path = \"{}\", tools = {{ cxx = \"{}\" }} }}\n", T.string(), driver.string())); + r = plain.mcpp({"build"}, o); + expect(fatal(e2e::succeeded(r))) << "a program of no modules did not build: " << s::text(r); + plain.write("src/extra.cppm", "export module extra;\nexport int extra() { return 1; }\n"); + e2e::expect_diagnostic("\\[compiler-without-modules\\]"); + r = plain.mcpp({"build"}, o); + out = s::text(r); + expect(fatal(!e2e::succeeded(r))) << "a module unit was accepted: " << out; + expect(e2e::contains(out, "src/extra.cppm")) << out; + expect(e2e::contains(out, "this driver takes no module unit")) << out; + }; + "876 toolchain phase"_test[s::llvm][s::unix_shell][s::symlink] = [] { // `[toolchain] default = { configure = "build.mcpp" }` (mcpp#755): the build program's // toolchain phase states the toolchain (a path, reported with its origin; a managed spec, From 09c7dbbecdef9a9060138f91016aa98246f376c3 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 02:04:50 +0900 Subject: [PATCH 09/36] A library package describes itself: mcpp-package.json, a .pc per leg, and its index entry mcpp pack writes mcpp-package.json for a library as for a program (kind library, the tree a path-named toolchain built it with, per shared leg the run-time lower bounds), and per leg a pkg-config description lib//pkgconfig/.pc from the package's own link intent (prefix relative to the file, the -l words of its ldflags as Libs.private, mcpp_abi). mcpp emit xpkg --package writes a library package's index entry: address and digest from the archive, the systems and architectures its legs cover, deps from the lower bounds, mcpp = "mcpp.toml", and the .pc relocated and declared into the environment's pkg-config view by xim.pkgindex.sysroot when the index has it. It refuses, naming the user's file, an archive mcpp pack did not write ([not-a-package-of-mcpp-pack]), a library package without the description ([package-without-description]), a library package's directory ([emit-inside-a-package]) and a package built with a toolchain named by path ([package-built-outside-the-ecosystem]). Notes: pack/no-header-interface, pack/closure-not-in-package, pack/built-with-a-tree, emit/two-legs-for-one-system. The program and library entries share one install(). The lower bounds are measured in mcpp.pack: importing mcpp.runtime.elf and mcpp.toolchain.base into mcpp.pack.library made GCC 16.1 crash at the first import of mcpp.cli. --- .../2026-11-27-ecosystem-boundary-design.md | 9 + CHANGELOG.md | 12 + docs/10-pack-and-release.md | 6 +- docs/12-binary-distribution.md | 69 ++++++ docs/50-machine-output.md | 4 + docs/zh/10-pack-and-release.md | 4 +- docs/zh/12-binary-distribution.md | 53 ++++ docs/zh/50-machine-output.md | 4 + src/build/refusal.cppm | 13 + src/cli/cmd_build.cppm | 10 +- src/cli/cmd_publish.cppm | 55 ++++- src/explain.cppm | 16 ++ src/pack/distribution.cppm | 232 +++++++++++++++--- src/pack/library.cppm | 109 ++++++++ src/pack/library_pipeline.cppm | 23 ++ src/pack/pack.cppm | 25 ++ tests/e2e/pack/library.cpp | 56 +++++ tests/e2e/toolchain/custom.cpp | 21 ++ 18 files changed, 684 insertions(+), 37 deletions(-) diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index deeb5dbbf..cacd7b7b2 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -510,6 +510,15 @@ ABI)的包不写这一面,`emit xpkg` 报告这一点,补救是按 docs/12 xlings 一侧不需要改动:库包作为载荷已在规则之内。 +**实现(2026-12-05)。** 与上文四处不同。其一,指针写作 `mcpp = "mcpp.toml"`:条目的 `install()` 把归档唯一的 +顶层目录移为安装目录本身(与程序包的条目同一段代码),清单因此在安装目录的根上,`*/mcpp.toml` 匹配不到。其二, +`.pc` 的名字由一个函数(`package_identity`)给出;归档的命名不变,改它会改变已发布的文件名。其三,`deps` 的下界只对 +共享库腿测量:静态归档不带版本化的符号引用;C++ 运行时只在构建者为 GCC、库引用 libstdc++ 时写 +`xim:gcc-runtime@>=<主版本>`,libc++ 在索引中没有对应的运行时包。测量放在 `mcpp.pack`:把 `mcpp.runtime.elf` 与 +`mcpp.toolchain.base` 导入 `mcpp.pack.library` 使 GCC 16.1 在首次导入 `mcpp.cli` 时崩溃(登记于 mcpp#1027)。其四, +§8 的 M7 没有在探针 PR 中测量;条目以 `pcall(import, "xim.pkgindex.sysroot")` 取这两个函数,取不到时写出 `.pc` +所在的目录而不失败,所以两种索引中的行为都已陈述。经索引消费的一步由条目文本的断言覆盖,没有在本地 e2e 中下载。 + ### 3.4 被启动的外部程序(openkal-musl、规范的一句与三个实现) openkal 规范 7.13 已规定被启动的程序得到三个流与调用者授予的目录,别无其他句柄。接口有三层,调用者在其中两层 diff --git a/CHANGELOG.md b/CHANGELOG.md index 25273bbf3..e2726d7bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,18 @@ - A command that needs a project, run outside one, says `no mcpp.toml in the current directory or any parent` and names the two next steps. - mcpp depends on mcpplibs.cmdline 0.2.0 with its `agent-skills` feature. +- A library package carries `mcpp-package.json`, as a program's package does, and per leg a + pkg-config description `lib//pkgconfig/.pc` from its own link intent, with + `mcpp_abi` stating its compatibility tag. `mcpp emit xpkg --package` writes a library package's + index entry: address and digest from the archive, the systems and architectures its legs cover, + a shared leg's run-time lower bounds as `deps`, `mcpp = "mcpp.toml"`, and the `.pc` declared into + the environment's pkg-config view by the index's own functions. `emit xpkg` refuses an archive + `mcpp pack` did not write (`[not-a-package-of-mcpp-pack]`), a library package without the + description (`[package-without-description]`), a library package's directory + (`[emit-inside-a-package]`) and a package built with a toolchain named by path + (`[package-built-outside-the-ecosystem]`), naming the user's file. Notes: + `pack/no-header-interface`, `pack/closure-not-in-package`, `pack/built-with-a-tree`, + `emit/two-legs-for-one-system`. - A toolchain named by path takes what it can do from its statement or a probe, as a managed payload takes it from the index: the archiver from `tools.ar`, the tree, or the host's `PATH` (reported as `build/archiver-from-host`, refused under `--strict`; none anywhere is refused with diff --git a/docs/10-pack-and-release.md b/docs/10-pack-and-release.md index d56970b58..6d2879bb9 100644 --- a/docs/10-pack-and-release.md +++ b/docs/10-pack-and-release.md @@ -1055,7 +1055,11 @@ Symbolic links are not listed. `linkage` is `static`, `shared` or `declared` (each library as it declares itself); `launch` is `program` for one native leg and `runner` with an `entry` per architecture for a tree; `runs_on` is where the package runs (`{"self": [...], "with": {"okrun": [...]}}`), and `systems` the -runners it carries. +runners it carries. A library's package states `"kind": "library"`, the tree it +was built with when its toolchain is named by path (`built_with_tree`), and per +shared leg its run-time lower bounds (`deps`); its entry is described in +[12](12-binary-distribution.md), "The index entry is written by a command" +(2026.12.4.1+). `mcpp emit xpkg --package [--package …] --url [-o ]` writes the xim-pkgindex entry (spec 2) of packages this command wrote, from diff --git a/docs/12-binary-distribution.md b/docs/12-binary-distribution.md index c30de0786..41ef46308 100644 --- a/docs/12-binary-distribution.md +++ b/docs/12-binary-distribution.md @@ -226,6 +226,75 @@ mathkit = "0.1.0" Nothing about the consumer's manifest says "this one is prebuilt". +### The index entry is written by a command (2026.12.4.1+) + +A library package carries `mcpp-package.json`, as a program's package does: +each leg's triple, each file with its role (`library`, `interface`, `metadata`) +and digest, and, for a shared leg, its run-time lower bounds (the highest +`GLIBC_` version it names; the builder's GCC major when it names libstdc++). +The entry is written from the archive: + +```bash +mcpp pack mathkit --pkg-format tar +mcpp emit xpkg --package target/dist/mathkit-0.1.0-.tar.gz --url https://example.org/v0.1.0 +``` + +The entry takes the address and the sha256 from the archive, lists the systems +and architectures its legs cover, states each shared leg's lower bounds as +`deps`, and names the manifest with `mcpp = "mcpp.toml"`: a consumer's build +reads the rest from the package. Several legs are several `--package` +arguments, combined into one entry. A compiler is not written into `deps`; the +consumer states its own. + +`emit xpkg` refuses, naming the file the user gave: + +| Case | Reason token | +|---|---| +| an archive `mcpp pack` did not write | `not-a-package-of-mcpp-pack` | +| a library package an earlier mcpp wrote, without `mcpp-package.json` | `package-without-description` | +| `emit xpkg` without `--package` in a library package's directory | `emit-inside-a-package` | +| a package built with a toolchain named by path | `package-built-outside-the-ecosystem` | + +A package built with a toolchain named by path holds for consumers that build +with the same toolchain; `mcpp pack` notes it, and it is delivered by `path` or +`git`. + +### For build systems other than mcpp (2026.12.4.1+) + +Each leg of a package with a header interface carries a pkg-config +description, `lib//pkgconfig/.pc` (`..pc` +with a namespace). Everything in it comes from the package's own link intent: + +``` +prefix=${pcfiledir}/../../.. +includedir=${prefix}/include +libdir=${prefix}/lib/x86_64-linux-gnu +mcpp_abi=x86_64-linux-gnu-gcc16-libstdcxx16-c++23 + +Name: mathkit +Cflags: -I${includedir} +Libs: -L${libdir} -lmathkit +Libs.private: -lm +Requires.private: +``` + +`Libs.private` holds the `-l` words of the package's `ldflags`. The prefix is +relative to the file, so a consumer that uses the package by path reads it as +it is. The entry places the `.pc` into the environment's pkg-config view with +the index's own two functions (`relocate_pkgconfig`, `declare_pkgconfig` of +`xim.pkgindex.sysroot`); in an index without them, the install prints where the +`.pc` is and succeeds. A package with two legs for one system and architecture +(two C libraries) shows the environment no `.pc`, which `emit xpkg` notes +(`emit/two-legs-for-one-system`). + +Three limits hold. The `.pc` describes the header interface: a package that +publishes only module interfaces writes none, noted as `pack/no-header-interface`. +pkg-config has no ABI check: `mcpp_abi` is readable, and the check is mcpp's +alone. A static library's package does not carry its dependencies' binaries: a +consumer outside mcpp needs them and their descriptions in its environment, +noted as `pack/closure-not-in-package`; a shared library that links its +dependencies into itself carries the closure. + ### Building inside a package is refused ``` diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index 4a5e3e2a5..2ef6bff83 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -725,6 +725,10 @@ a program classifying the outcome reads `reason`: | `test-output-collision` | a test program and an executable target of one package write one file; the message names the test's file or directory to rename *(2026.12.4.1+)* | | `toolchain-has-no-archiver` | a toolchain named by path has no archiver, in its tree or on PATH *(2026.12.4.1+)* | | `compiler-without-modules` | a unit declares or imports a module, and the compiler has no C++ modules (GCC before 14, or a tree's driver that refused a module unit) *(2026.12.4.1+)* | +| `not-a-package-of-mcpp-pack` | `mcpp emit xpkg --package` was given an archive that `mcpp pack` did not write *(2026.12.4.1+)* | +| `package-without-description` | a library package an earlier mcpp wrote carries no mcpp-package.json, which an index entry is written from *(2026.12.4.1+)* | +| `emit-inside-a-package` | `mcpp emit xpkg` ran in the directory of a library package, which is not a source tree *(2026.12.4.1+)* | +| `package-built-outside-the-ecosystem` | the package was built with a toolchain named by path, whose environment no index entry can supply *(2026.12.4.1+)* | | `other` | a refusal whose branch has not been given a token yet | **One token is also printed by `mcpp build` itself.** diff --git a/docs/zh/10-pack-and-release.md b/docs/zh/10-pack-and-release.md index 8ecb48b53..c72574de7 100644 --- a/docs/zh/10-pack-and-release.md +++ b/docs/zh/10-pack-and-release.md @@ -868,7 +868,9 @@ Authenticode 可以签名它。Linux 与 macOS 经 shell 启动它:`sh pg-0.1. `launcher`、`resource` 或 `metadata`;树中 `lib//` 下的每个文件都是该腿的映像。符号链接不列出。 `linkage` 为 `static`、`shared` 或 `declared`(每个库按它自己的声明);`launch` 对单个原生腿为 `program`, 对树为 `runner` 加每个架构的 `entry`;`runs_on` 为包在哪里运行(`{"self": [...], "with": {"okrun": [...]}}`), -`systems` 为它携带的运行器。 +`systems` 为它携带的运行器。库包写 `"kind": "library"`,以路径点名的工具链构建时写所用的树(`built_with_tree`), +并为每条共享库腿写运行时下界(`deps`);它的条目见 [12](12-binary-distribution.md)「索引条目由命令写出」 +(2026.12.4.1+)。 `mcpp emit xpkg --package <归档> [--package …] --url <前缀> [-o <文件>]` 由本命令写出的包的 `mcpp-package.json` 生成 xim-pkgindex 条目(spec 2)。树是一个资产,每个系统一项只写 `runs_on` 覆盖到的架构, diff --git a/docs/zh/12-binary-distribution.md b/docs/zh/12-binary-distribution.md index 656b4d875..40c27c635 100644 --- a/docs/zh/12-binary-distribution.md +++ b/docs/zh/12-binary-distribution.md @@ -208,6 +208,59 @@ mathkit = "0.1.0" 消费方的 manifest 里没有任何一处写着「这个是预编译的」。 +### 索引条目由命令写出(2026.12.4.1+) + +库包与程序包一样带 `mcpp-package.json`:每条腿的三元组,每个文件的角色(`library`、`interface`、`metadata`) +与摘要,以及共享库腿的运行时下界(它所引用的最高 `GLIBC_` 版本;引用 libstdc++ 时为构建所用 GCC 的主版本)。 +条目由归档写出: + +```bash +mcpp pack mathkit --pkg-format tar +mcpp emit xpkg --package target/dist/mathkit-0.1.0-.tar.gz --url https://example.org/v0.1.0 +``` + +条目的地址与 sha256 取自归档,只列出各条腿覆盖的系统与架构,共享库腿的下界写作 `deps`,并以 +`mcpp = "mcpp.toml"` 指向清单:消费者的构建从包内读取其余一切。多条腿各是一个 `--package`,合成一个条目。 +编译器不写进 `deps`,由消费者自己声明。 + +`emit xpkg` 在以下情形拒绝,并点名使用者给出的文件: + +| 情形 | 原因码 | +|---|---| +| 归档不是 `mcpp pack` 写出的 | `not-a-package-of-mcpp-pack` | +| 早先的 mcpp 写出的库包,不带 `mcpp-package.json` | `package-without-description` | +| 在库包目录中运行不带 `--package` 的 `emit xpkg` | `emit-inside-a-package` | +| 包由以路径点名的工具链构建 | `package-built-outside-the-ecosystem` | + +由以路径点名的工具链构建的包只对使用同一套工具链的消费者成立;`mcpp pack` 说明这一点,它以 `path` 或 `git` 交付。 + +### 面向 mcpp 以外的构建系统(2026.12.4.1+) + +带头文件接口的包每条腿有一份 pkg-config 描述 `lib//pkgconfig/.pc`(有命名空间时为 +`..pc`),内容全部取自包自己的链接意图: + +``` +prefix=${pcfiledir}/../../.. +includedir=${prefix}/include +libdir=${prefix}/lib/x86_64-linux-gnu +mcpp_abi=x86_64-linux-gnu-gcc16-libstdcxx16-c++23 + +Name: mathkit +Cflags: -I${includedir} +Libs: -L${libdir} -lmathkit +Libs.private: -lm +Requires.private: <包的依赖,以其身份为名> +``` + +`Libs.private` 为包的 `ldflags` 中的 `-l` 词。`prefix` 相对该文件给出,以路径使用库包的消费者原样读取它。条目经索引 +自带的两个函数(`xim.pkgindex.sysroot` 的 `relocate_pkgconfig`、`declare_pkgconfig`)把 `.pc` 放进环境的 +pkg-config 视图;索引中没有这两个函数时,安装写出 `.pc` 所在的目录并成功。同一系统与架构有两条腿(两个 C 库) +的包不向环境给出 `.pc`,`emit xpkg` 说明这一点(`emit/two-legs-for-one-system`)。 + +边界有三条。`.pc` 描述头文件接口:只有模块接口的包不写它,说明为 `pack/no-header-interface`。pkg-config +不核对 ABI:`mcpp_abi` 可读,核对只在 mcpp 一侧。静态库包不携带依赖的二进制:mcpp 以外的消费者须在环境中另有 +这些依赖及其描述,说明为 `pack/closure-not-in-package`;把依赖链接进自身的共享库包携带闭包。 + ### 在包目录内直接构建被拒绝 ``` diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 0638cc97a..23c92137c 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -647,6 +647,10 @@ replaced}` —— `origin` 与构建的状态行使用的是同一句话 | `test-output-collision` | 同一个包的测试程序与可执行目标写同一个文件;消息写出应改名的测试文件或目录 *(2026.12.4.1+)* | | `toolchain-has-no-archiver` | 以路径点名的工具链在树中与 PATH 上都没有归档器 *(2026.12.4.1+)* | | `compiler-without-modules` | 有单元声明或导入模块,而编译器没有 C++ 模块(GCC 14 之前,或拒绝模块单元的树的驱动) *(2026.12.4.1+)* | +| `not-a-package-of-mcpp-pack` | `mcpp emit xpkg --package` 收到的归档不是 `mcpp pack` 写出的 *(2026.12.4.1+)* | +| `package-without-description` | 早先的 mcpp 写出的库包不带 mcpp-package.json,而条目由它写出 *(2026.12.4.1+)* | +| `emit-inside-a-package` | `mcpp emit xpkg` 在库包的目录中运行,那不是源码树 *(2026.12.4.1+)* | +| `package-built-outside-the-ecosystem` | 包由以路径点名的工具链构建,它的环境不是条目能供给的 *(2026.12.4.1+)* | | `other` | 一个尚未被赋予记号的拒绝分支 | **其中一个记号也由 `mcpp build` 自己打印。** `interface-not-provided` 会 diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index e1f8075c9..8c934c06b 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -260,6 +260,15 @@ enum class Code { // A unit declares or imports a module, and the compiler has no C++ // modules: GCC before 14, or a tree's driver that refused a module unit. CompilerWithoutModules, + // `mcpp emit xpkg --package` and library packages (design 2026-11-27 + // §3.3.2): an archive `mcpp pack` did not write; a library package an + // mcpp wrote before it carried its description; the directory of a + // library package taken for a source tree; a package built with a + // toolchain named by path, whose environment no index supplies. + NotAPackageOfMcppPack, + PackageWithoutDescription, + EmitInsideAPackage, + PackageBuiltOutsideTheEcosystem, Other, // a refusal that has not been given a code yet }; @@ -339,6 +348,10 @@ constexpr std::string_view name(Code c) { case Code::TestOutputCollision: return "test-output-collision"; case Code::ToolchainHasNoArchiver: return "toolchain-has-no-archiver"; case Code::CompilerWithoutModules: return "compiler-without-modules"; + case Code::NotAPackageOfMcppPack: return "not-a-package-of-mcpp-pack"; + case Code::PackageWithoutDescription: return "package-without-description"; + case Code::EmitInsideAPackage: return "emit-inside-a-package"; + case Code::PackageBuiltOutsideTheEcosystem: return "package-built-outside-the-ecosystem"; case Code::Other: return "other"; } return "other"; diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index 11fb35a30..107483079 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -1972,12 +1972,12 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, namespace fs = std::filesystem; // Its one way to say a refusal: this command runs under ninja, whose // output is the build's, so the line is the command's own. - auto fail = [](std::string_view why, int rc = 2) { + auto fail = [](std::string_view why, int rc) { std::println(libc::stderr(), "error: link-output{}", why); return rc; }; const fs::path out = parsed.option_or_empty("output").value(); - if (out.empty() || given.empty()) return fail(" needs --output -- "); + if (out.empty() || given.empty()) return fail(" needs --output -- ", 2); std::vector expanded(given.begin(), given.end()); if (parsed.is_flag_set("expand")) { std::vector head, members, tail; @@ -1985,7 +1985,7 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, for (auto const& word : given) { if (!seen && word.size() > 1 && word.front() == '@') { std::ifstream in(word.substr(1), std::ios::binary); - if (!in) return fail(std::format(" --expand: cannot read {}", word.substr(1))); + if (!in) return fail(std::format(" --expand: cannot read {}", word.substr(1)), 2); const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; members = mcpp::build::command_line::response_file_words(text); seen = true; @@ -2029,7 +2029,7 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, } const std::span command(expanded); const std::string text = parsed.option_or_empty("text").value(); - if (!text.empty() && text != "console") return fail(std::format(": --text takes `console`, not `{}`", text)); + if (!text.empty() && text != "console") return fail(std::format(": --text takes `console`, not `{}`", text), 2); // The linker, on this program's streams or through the decoding pipe. auto run_linker = [&](const std::vector& argv) { if (text.empty()) @@ -2063,7 +2063,7 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, return a == "-o" && fs::path(b) == out; }); if (named == argv.end()) - return fail(std::format(" --temporary: the linker command names no `-o {}`", out.string())); + return fail(std::format(" --temporary: the linker command names no `-o {}`", out.string()), 2); *std::next(named) = temporary.string(); if (const int linked = run_linker(argv); linked != 0) { fs::remove(temporary, ec); diff --git a/src/cli/cmd_publish.cppm b/src/cli/cmd_publish.cppm index e95bcf138..ab9e63942 100644 --- a/src/cli/cmd_publish.cppm +++ b/src/cli/cmd_publish.cppm @@ -38,6 +38,31 @@ namespace libc = mcpplibs::mwrap::libc::macros; namespace mcpp::cli { +namespace { + +// THE WRITER OF A LIBRARY PACKAGE'S MANIFEST: `mcpp pack` opens it with +// "# Generated by ``. Do not edit." (mcpp.pack.manifest_emit). +// Nothing when the manifest is not one `mcpp pack` wrote. +std::optional packed_by(const std::filesystem::path& manifest) { + std::ifstream in(manifest, std::ios::binary); + std::string first; + if (!in || !std::getline(in, first)) return std::nullopt; + constexpr std::string_view head = "# Generated by `"; + if (!first.starts_with(head)) return std::nullopt; + const auto end = first.find("`. Do not edit.", head.size()); + if (end == std::string::npos) return std::nullopt; + return first.substr(head.size(), end - head.size()); +} + +// A refusal of `emit xpkg`: its reason recorded, its message said. +int refuse_emit(mcpp::build::refusal::Code code, const std::string& message) { + mcpp::build::refusal::record(code); + mcpp::ui::error(std::format("[{}] {}", mcpp::build::refusal::name(code), message)); + return 2; +} + +} // namespace + // `mcpp emit xpkg ...` — only one subcommand defined, so the action sits // directly on the `emit xpkg` nested subcommand and receives its ParsedArgs. export int cmd_emit_xpkg(const mcpplibs::cmdline::ParsedArgs& parsed) { @@ -69,7 +94,29 @@ export int cmd_emit_xpkg(const mcpplibs::cmdline::ParsedArgs& parsed) { auto root = d::unpack(file, work / std::to_string(assets.size())); if (!root) { mcpp::ui::error(root.error()); std::filesystem::remove_all(work, ec); return 2; } auto pkg = d::read(*root); - if (!pkg) { mcpp::ui::error(pkg.error()); std::filesystem::remove_all(work, ec); return 2; } + if (!pkg) { + // Named by the file the user gave, not the directory it was + // unpacked into (design 2026-11-27 §10, G5). + const bool described = std::filesystem::exists(*root / d::kFileName, ec); + const auto writer = described ? std::nullopt : packed_by(*root / "mcpp.toml"); + std::filesystem::remove_all(work, ec); + if (described) { mcpp::ui::error(pkg.error()); return 2; } + if (writer) + return refuse_emit(mcpp::build::refusal::Code::PackageWithoutDescription, std::format( + "{} is a library package mcpp {} wrote, before a library package carried its " + "description (mcpp-package.json)\n help: pack it again with this mcpp: " + "mcpp pack --pkg-format tar", p, *writer)); + return refuse_emit(mcpp::build::refusal::Code::NotAPackageOfMcppPack, std::format( + "{} holds no mcpp-package.json: it is not a package `mcpp pack` wrote\n help: " + "mcpp pack --pkg-format tar writes one", p)); + } + if (pkg->kind == "library" && !pkg->builtWithTree.empty()) { + std::filesystem::remove_all(work, ec); + return refuse_emit(mcpp::build::refusal::Code::PackageBuiltOutsideTheEcosystem, std::format( + "{} was built with the toolchain at {}: an index entry would promise an environment " + "its consumers cannot install\n help: deliver it by `path` or `git`, or pack it " + "with a managed toolchain", p, pkg->builtWithTree)); + } assets.push_back({ file, std::move(*pkg), d::sha256_file(file), root->filename().string() }); } std::filesystem::remove_all(work, ec); @@ -84,6 +131,12 @@ export int cmd_emit_xpkg(const mcpplibs::cmdline::ParsedArgs& parsed) { std::print("{}", *lua); return 0; } + // A LIBRARY PACKAGE IS NOT A SOURCE TREE: its entry is written from its + // archive (design 2026-11-27 §3.3.2). + if (auto writer = packed_by(std::filesystem::current_path() / "mcpp.toml")) + return refuse_emit(mcpp::build::refusal::Code::EmitInsideAPackage, std::format( + "this directory is a library package written by mcpp pack ({}), not a source tree\n help: " + "mcpp emit xpkg --package --url ", *writer)); return mcpp::publish::emit_xpkg_to( parsed.option_or_empty("version").value(), std::filesystem::path{parsed.option_or_empty("output").value()}, diff --git a/src/explain.cppm b/src/explain.cppm index 4e23cde5d..ceaa066cc 100644 --- a/src/explain.cppm +++ b/src/explain.cppm @@ -371,6 +371,22 @@ constexpr Entry kEntries[] = { "Name a toolchain with C++ modules (mcpp toolchain list), point tools.cxx at a\n" "driver script that adds the word the driver needs, or build no module units\n" "for this target."}, + {"not-a-package-of-mcpp-pack", Kind::Reason, + "`mcpp emit xpkg --package` was given an archive that `mcpp pack` did not write", + "Pack the target and describe the archive it writes:\n" + " mcpp pack --pkg-format tar\n" + " mcpp emit xpkg --package target/dist/ --url "}, + {"package-without-description", Kind::Reason, + "a library package an earlier mcpp wrote carries no mcpp-package.json, which an index entry is written from", + "Pack it again with this mcpp: mcpp pack --pkg-format tar."}, + {"emit-inside-a-package", Kind::Reason, + "`mcpp emit xpkg` ran in the directory of a library package, which is not a source tree", + "Describe the package's archive instead:\n" + " mcpp emit xpkg --package --url "}, + {"package-built-outside-the-ecosystem", Kind::Reason, + "the package was built with a toolchain named by path, whose environment no index entry can supply", + "Deliver it by `path` or `git`, or pack it with a managed toolchain\n" + "(`[toolchain] default = \"llvm@...\"`)."}, {"other", Kind::Reason, "a refusal whose branch has not been given a token yet", "Read the message: it names the cause and the remedy. Report the case so\n" diff --git a/src/pack/distribution.cppm b/src/pack/distribution.cppm index 8c6dd3d8c..e82782f9e 100644 --- a/src/pack/distribution.cppm +++ b/src/pack/distribution.cppm @@ -19,6 +19,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.toolchain.target_rows; // the system table: `uname -s` words (N20) 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 mcpplibs.os; export namespace mcpp::pack::distribution { @@ -128,6 +129,14 @@ struct Package { std::map> runsOnWith; bool runsOnSet = false; std::vector files; + // A LIBRARY PACKAGE (design 2026-11-27 §3.3.2): `kind` "library" (absent: + // a program's package); the toolchain tree named by path it was built with + // (` ()`, empty: a managed toolchain), which an + // index entry cannot supply; and per leg the run-time lower bounds an + // entry states as `deps` ("xim:glibc@>=2.38"). + std::string kind; + std::string builtWithTree; + std::map> legDeps; }; // `runs_on` for `p`, from its legs, the runners it carries (`systems`), its @@ -1362,6 +1371,9 @@ std::string to_json(const Package& p) { for (auto const& [runner, pairs] : p.runsOnWith) with[runner] = pairs; j["runs_on"] = {{"self", p.runsOnSelf}, {"with", std::move(with)}}; } + if (!p.kind.empty()) j["kind"] = p.kind; + if (!p.builtWithTree.empty()) j["built_with_tree"] = p.builtWithTree; + if (!p.legDeps.empty()) j["deps"] = p.legDeps; j["files"] = std::move(files); return j.dump(2) + "\n"; } @@ -1417,6 +1429,11 @@ std::expected read(const fs::path& root) { p.entry[it.key()] = it.value().get(); if (l.contains("program") && l["program"].is_string()) p.program = l["program"].get(); } + p.kind = j.value("kind", std::string{}); + p.builtWithTree = j.value("built_with_tree", std::string{}); + if (j.contains("deps") && j["deps"].is_object()) + for (auto it = j["deps"].begin(); it != j["deps"].end(); ++it) + p.legDeps[it.key()] = it.value().get>(); for (auto const& f : j.value("files", nlohmann::json::array())) { File x; x.path = f.value("path", std::string{}); @@ -1726,6 +1743,186 @@ std::string archive_directory(const fs::path& archive) { return name; } +namespace { + +// The archives' suffixes, as a Lua list, each asset checked to be an archive xim +// unpacks whose one directory is named after it (as `mcpp pack` writes it). +std::expected archive_suffixes(const std::vector& assets) { + std::array used{}; + for (auto const& a : assets) { + const auto file = a.file.filename().string(); + const auto ext = std::ranges::find_if(kArchiveSuffixes, [&](std::string_view e) { return file.ends_with(e); }); + if (ext == kArchiveSuffixes.end()) + return std::unexpected(std::format("{} is not an archive xim unpacks (.tar.gz, .tgz, .tar.zst, " + ".tar.xz, .tar, .zip)", file)); + if (archive_directory(a.file) != a.top) + return std::unexpected(std::format( + "{} holds the directory {}/: an entry installs the directory named after the archive, as " + "mcpp pack writes it (name the archive {}{})", file, a.top, a.top, *ext)); + used[static_cast(ext - kArchiveSuffixes.begin())] = true; + } + std::string exts; + for (std::size_t i = 0; i < kArchiveSuffixes.size(); ++i) + if (used[i]) exts += std::format("{}\"{}\"", exts.empty() ? "" : ", ", kArchiveSuffixes[i]); + return exts; +} + +// `install()`: the archive's one top-level directory is the package; xim +// unpacks it beside the downloaded file, which names it. `after` runs in the +// installed tree before the function answers. +std::string install_lua(std::string_view exts, std::string_view after = {}) { + return std::format( + "function install()\n" + " -- The archive's one top-level directory is the package; it is named\n" + " -- after the archive, which xim unpacks beside it.\n" + " local top = pkginfo.install_file()\n" + " for _, ext in ipairs({{ {} }}) do\n" + " if top:sub(-#ext) == ext then top = top:sub(1, #top - #ext) break end\n" + " end\n" + " if not os.isdir(top) then return false end\n" + " os.tryrm(pkginfo.install_dir())\n" + " os.mv(top, pkginfo.install_dir())\n" + "{}" + " return os.isdir(pkginfo.install_dir())\n" + "end\n", exts, after); +} + +// THE ENTRY OF A LIBRARY PACKAGE (design 2026-11-27 §3.3.2, §3.3.3): its +// address and digest from the archive, the systems and architectures its legs +// cover, `mcpp = "mcpp.toml"` (the pointer form of a source package's entry; +// `install()` makes the archive's one directory the install directory, so the +// manifest is at its root, and a consumer's build reads the rest from it), each leg's run-time +// lower bounds as `deps`, and the face it shows an environment: the leg's +// `.pc`, made absolute and declared into the environment's pkg-config view by +// the index's own two functions, as the index's library recipes do. An index +// without them is told where the `.pc` is, and the install does not fail. +// One leg of one asset. +struct LegOf { + const Asset* asset = nullptr; + std::string triple; +}; + +std::expected library_descriptor(const std::vector& assets, + const std::string& prefix) { + auto const& first = assets.front().pkg; + // system -> arch -> the legs there + std::map>> legs; + std::vector archs; + for (auto const& a : assets) { + if (a.pkg.kind != "library") + return std::unexpected(std::format("{} is a program's package and {} a library's: one entry " + "describes one package", a.file.filename().string(), + assets.front().file.filename().string())); + for (auto const& triple : a.pkg.legs) { + const auto pair = host_pair_of(triple); + if (!pair) + return std::unexpected(std::format("{} holds a leg for {}, which is no system an index entry " + "installs on", a.file.filename().string(), triple)); + const auto dash = pair->find('-'); + const auto system = pair->substr(0, dash), arch = pair->substr(dash + 1); + legs[system][arch].push_back(LegOf{&a, triple}); + if (std::ranges::find(archs, arch) == archs.end()) archs.push_back(arch); + } + } + std::ranges::sort(archs); + auto exts = archive_suffixes(assets); + if (!exts) return std::unexpected(exts.error()); + // Two legs for one system and architecture (two C libraries, two ABIs): + // the entry describes the package for mcpp and shows the environment no + // `.pc`, as it cannot tell which leg a machine takes. + bool twoLegs = false; + std::string blocks, pcDirs; + std::set pcSeen; + for (auto const& [system, byArch] : legs) { + std::string tmpl, shas; + std::set deps; + for (auto const& [arch, here] : byArch) { + std::vector files; + for (auto const& leg : here) { + if (std::ranges::find(files, leg.asset) == files.end()) files.push_back(leg.asset); + if (auto it = leg.asset->pkg.legDeps.find(leg.triple); it != leg.asset->pkg.legDeps.end()) + deps.insert(it->second.begin(), it->second.end()); + if (pcSeen.insert(leg.triple).second) + pcDirs += std::format("{}\"lib/{}/pkgconfig\"", pcDirs.empty() ? "" : ", ", lua_text(leg.triple)); + } + if (here.size() > 1) { + twoLegs = true; + std::string named; + for (auto const& leg : here) named += (named.empty() ? "" : " and ") + leg.triple; + mcpp::diag::note("emit/two-legs-for-one-system", std::format( + "{} has two legs for {}-{} ({}): the entry shows the environment no .pc, as it cannot " + "tell which leg a machine takes; publish one package for each ABI", + first.name, system, arch, named)); + } + if (files.size() > 1) + return std::unexpected(std::format("two packages hold a leg for {}-{}: an entry names one " + "archive for a system and an architecture", system, arch)); + const auto* a = files.front(); + auto name = a->file.filename().string(); + if (auto at = name.find(arch); at != std::string::npos) name.replace(at, arch.size(), "${arch}"); + if (!tmpl.empty() && tmpl != name && byArch.size() > 1 && name.find("${arch}") == std::string::npos) + return std::unexpected(std::format("the {} packages' names differ beyond the architecture " + "({} and {})", system, tmpl, name)); + tmpl = name; + shas += std::format(" [\"{}\"] = \"{}\",\n", lua_text(arch), lua_text(a->sha256)); + } + std::string depText; + for (auto const& d : deps) depText += std::format("{}\"{}\"", depText.empty() ? "" : ", ", lua_text(d)); + blocks += std::format( + " {} = {{\n" + " [\"latest\"] = {{ ref = \"{}\" }},\n" + " [\"{}\"] = {{\n url = \"{}/{}\",\n sha256 = {{\n{}" + " }},\n{} }},\n" + " }},\n", + system == "macos" ? "macosx" : system, lua_text(first.version), lua_text(first.version), + lua_text(prefix), lua_text(tmpl), shas, + depText.empty() ? std::string{} : std::format(" deps = {{ {} }},\n", depText)); + } + const std::string pcFind = std::format( + " local pcdir = nil\n" + " for _, rel in ipairs({{ {} }}) do\n" + " if os.isdir(path.join(pkginfo.install_dir(), rel)) then pcdir = rel break end\n" + " end\n", pcDirs); + const std::string relocate = twoLegs || pcDirs.empty() ? std::string{} : pcFind + + " local ok, sysroot = pcall(import, \"xim.pkgindex.sysroot\")\n" + " if pcdir and ok and sysroot and sysroot.relocate_pkgconfig then\n" + " sysroot.relocate_pkgconfig(pkginfo.install_dir(), pcdir)\n" + " end\n"; + const std::string declare = twoLegs || pcDirs.empty() ? std::string{} : pcFind + + " local ok, sysroot = pcall(import, \"xim.pkgindex.sysroot\")\n" + " if pcdir and ok and sysroot and sysroot.declare_pkgconfig then\n" + " sysroot.declare_pkgconfig(pkginfo.install_dir(), pcdir, package.name .. \"@\" .. pkginfo.version())\n" + " elseif pcdir then\n" + " print(package.name .. \": its pkg-config description is in \" .. path.join(pkginfo.install_dir(), pcdir))\n" + " end\n"; + return std::format( + "-- Generated by `mcpp emit xpkg --package` from the packages' mcpp-package.json\n" + "-- (SPEC-014 §8): a library package. mcpp consumers read `mcpp`; the ABI tag\n" + "-- each leg's .pc states as `mcpp_abi` is checked by mcpp alone.\n" + "package = {{\n" + " spec = \"2\",\n" + " name = \"{0}\",\n" + " description = \"{0} {1}, a library package written by mcpp pack\",\n" + " type = \"package\",\n" + " archs = {2},\n" + " mcpp = \"mcpp.toml\",\n" + " xpm = {{\n{3} }},\n" + "}}\n\n" + "import(\"xim.libxpkg.pkginfo\")\n\n" + "{4}\n" + "function config()\n" + "{5}" + " return true\n" + "end\n\n" + "function uninstall()\n" + " return true\n" + "end\n", + lua_text(first.name), lua_text(first.version), lua_list(archs), blocks, + install_lua(*exts, relocate), declare); +} + +} // namespace + std::expected xpkg_descriptor(const std::vector& assets, std::string_view urlPrefix) { if (assets.empty()) return std::unexpected(std::string("no package to describe")); @@ -1740,6 +1937,8 @@ std::expected xpkg_descriptor(const std::vector "package", assets.front().file.filename().string(), first.name, first.version, a.file.filename().string(), a.pkg.name, a.pkg.version)); + if (std::ranges::any_of(assets, [](const Asset& a) { return a.pkg.kind == "library"; })) + return library_descriptor(assets, prefix); const bool tree = !first.runner.empty(); std::vector archs; // system -> block text @@ -1874,22 +2073,8 @@ std::expected xpkg_descriptor(const std::vector // names the archive's one top-level directory after the archive; the // install takes the directory from that file's name, which holds for // every system, architecture and later version of the entry. - std::array used{}; - for (auto const& a : assets) { - const auto file = a.file.filename().string(); - const auto ext = std::ranges::find_if(kArchiveSuffixes, [&](std::string_view e) { return file.ends_with(e); }); - if (ext == kArchiveSuffixes.end()) - return std::unexpected(std::format("{} is not an archive xim unpacks (.tar.gz, .tgz, .tar.zst, " - ".tar.xz, .tar, .zip)", file)); - if (archive_directory(a.file) != a.top) - return std::unexpected(std::format( - "{} holds the directory {}/: an entry installs the directory named after the archive, as " - "mcpp pack writes it (name the archive {}{})", file, a.top, a.top, *ext)); - used[static_cast(ext - kArchiveSuffixes.begin())] = true; - } - std::string exts; - for (std::size_t i = 0; i < kArchiveSuffixes.size(); ++i) - if (used[i]) exts += std::format("{}\"{}\"", exts.empty() ? "" : ", ", kArchiveSuffixes[i]); + auto exts = archive_suffixes(assets); + if (!exts) return std::unexpected(exts.error()); return std::format( "-- Generated by `mcpp emit xpkg --package` from the packages' mcpp-package.json\n" "-- (SPEC-014 §8).\n" @@ -1905,18 +2090,7 @@ std::expected xpkg_descriptor(const std::vector "}}\n\n" "import(\"xim.libxpkg.pkginfo\")\n" "import(\"xim.libxpkg.xvm\")\n\n" - "function install()\n" - " -- The archive's one top-level directory is the package; it is named\n" - " -- after the archive, which xim unpacks beside it.\n" - " local top = pkginfo.install_file()\n" - " for _, ext in ipairs({{ {5} }}) do\n" - " if top:sub(-#ext) == ext then top = top:sub(1, #top - #ext) break end\n" - " end\n" - " if not os.isdir(top) then return false end\n" - " os.tryrm(pkginfo.install_dir())\n" - " os.mv(top, pkginfo.install_dir())\n" - " return os.isdir(pkginfo.install_dir())\n" - "end\n\n" + "{5}\n" "function config()\n" "{9}" " local opts = {{ bindir = path.join(pkginfo.install_dir(), {6}) }}\n" @@ -1929,7 +2103,7 @@ std::expected xpkg_descriptor(const std::vector "end\n", lua_text(command), lua_text(first.version), tree ? std::format(", one package for every system ({})", lua_text(first.platform)) : std::string(), - lua_list(archs), xpm, exts, bindir, alias, lua_text(first.name), bindirs); + lua_list(archs), xpm, install_lua(*exts), bindir, alias, lua_text(first.name), bindirs); } // ─── --merge ────────────────────────────────────────────────────────────── diff --git a/src/pack/library.cppm b/src/pack/library.cppm index 63e81f08c..12bef3ea6 100644 --- a/src/pack/library.cppm +++ b/src/pack/library.cppm @@ -113,8 +113,24 @@ struct LibraryPackPlan { std::filesystem::path debugDir; std::vector legs; + + // FOR OTHER BUILD SYSTEMS (design 2026-11-27 §3.3.3): the system libraries + // the package's own link states (`-l` of its ldflags), written as + // `Libs.private` of each leg's `.pc`; and the toolchain tree named by path + // the package was built with (` ()`), empty for a managed + // toolchain, which `mcpp emit xpkg` refuses to describe. + std::vector systemLibs; + std::string builtWithTree; + // Per leg, the run-time lower bounds of a shared leg (measured by + // mcpp::pack::shared_library_floors), written into the description. + std::map> legDeps; }; +// The name a package's pkg-config description has: `.`, or +// `` without a namespace. The view of an environment is one flat +// namespace, so two packages of one name under two namespaces do not collide. +std::string package_identity(std::string_view ns, std::string_view name); + // NOT `Error`. `mcpp.pack` already exports a `mcpp::pack::Error`, and a name // can only be attached to one module — clang rejects the second outright // ("cannot be attached to other modules"), and mcpp.pack.library_pipeline @@ -209,6 +225,41 @@ std::vector archive_remove_command(const std::filesystem::path& too return argv; } +std::string package_identity(std::string_view ns, std::string_view name) { + return ns.empty() ? std::string(name) : std::format("{}.{}", ns, name); +} + +namespace { + +// One leg's pkg-config description (design 2026-11-27 §3.3.3): everything from +// the package's own link intent, the prefix relative to the file itself. +std::string pc_text(const LibraryPackPlan& plan, const LibraryLeg& leg) { + std::string requires_; + for (auto const& [dep, _] : plan.dependencies) requires_ += (requires_.empty() ? "" : ", ") + dep; + std::string libsPrivate; + for (auto const& l : plan.systemLibs) libsPrivate += (libsPrivate.empty() ? "" : " ") + l; + return std::format( + "# Written by mcpp pack. It describes the header interface of this leg;\n" + "# `mcpp_abi` is the compatibility tag mcpp checks, which pkg-config does not.\n" + "prefix=${{pcfiledir}}/../../..\n" + "includedir=${{prefix}}/include\n" + "libdir=${{prefix}}/lib/{}\n" + "mcpp_abi={}\n\n" + "Name: {}\n" + "Description: {} {}, a library package written by mcpp pack\n" + "Version: {}\n" + "{}" + "Cflags: -I${{includedir}}\n" + "Libs: -L${{libdir}} -l{}\n" + "{}", + leg.triple, leg.abiTag, package_identity(plan.namespace_, plan.packageName), plan.packageName, + plan.packageVersion, plan.packageVersion, + requires_.empty() ? std::string{} : std::format("Requires.private: {}\n", requires_), + leg.linkName, libsPrivate.empty() ? std::string{} : std::format("Libs.private: {}\n", libsPrivate)); +} + +} // namespace + std::expected run_library_pack(const LibraryPackPlan& plan) { @@ -486,6 +537,64 @@ run_library_pack(const LibraryPackPlan& plan) os << emit_package_manifest(doc); } + // ── for other build systems (design 2026-11-27 §3.3.3) ──────────── + namespace d = mcpp::pack::distribution; + const auto identity = package_identity(plan.namespace_, plan.packageName); + const bool headers = std::filesystem::is_directory(plan.stagingRoot / "include", ec); + if (headers) { + for (auto const& leg : plan.legs) { + const auto pc = plan.stagingRoot / "lib" / leg.triple / "pkgconfig" / (identity + ".pc"); + std::filesystem::create_directories(pc.parent_path(), ec); + std::ofstream os(pc, std::ios::binary); + os << pc_text(plan, leg); + if (!os) return std::unexpected(LibraryPackError{ std::format("cannot write '{}'", pc.string()) }); + } + } else { + mcpp::diag::note("pack/no-header-interface", std::format( + "{} publishes a module interface and no header interface: no .pc is written, so a build " + "system other than mcpp has no description to read", identity)); + } + if (!plan.targetShared && !plan.dependencies.empty()) { + std::string deps; + for (auto const& [dep, _] : plan.dependencies) deps += (deps.empty() ? "" : ", ") + dep; + mcpp::diag::note("pack/closure-not-in-package", std::format( + "{} is a static library with dependencies ({}), which the package does not carry: a " + "consumer outside mcpp needs their binaries and descriptions in its environment. A shared " + "library, or these dependencies published as library packages, carry the closure", + identity, deps)); + } + // The package's description, as a program's package writes it: each + // file with its role, leg and digest, and what an index entry reads. + { + d::Package pkg; + pkg.name = plan.packageName; + pkg.version = plan.packageVersion; + pkg.linkage = plan.targetShared ? "shared" : "static"; + pkg.mode = "library"; + pkg.kind = "library"; + pkg.builtWithTree = plan.builtWithTree; + d::Stated stated; + for (auto const& leg : plan.legs) { + pkg.legs.push_back(leg.triple); + } + pkg.legDeps = plan.legDeps; + for (auto const& rel : walk(plan.stagingRoot)) { + const auto path = rel.generic_string(); + auto parts = rel.begin(); + if (path.starts_with("lib/") && std::distance(rel.begin(), rel.end()) > 2) { + const auto triple = (++parts)->string(); + stated.leg[path] = triple; + stated.role[path] = path.find("/pkgconfig/") != std::string::npos ? "metadata" : "library"; + } else if (path.starts_with("include/") || path.starts_with("interface/")) { + stated.role[path] = "interface"; + } else { + stated.role[path] = "metadata"; + } + } + if (auto r = d::describe(plan.stagingRoot, pkg, stated); !r) + return std::unexpected(LibraryPackError{ r.error() }); + } + if (!plan.writeArchive) return plan.stagingRoot; // ── archive ─────────────────────────────────────────────────────── diff --git a/src/pack/library_pipeline.cppm b/src/pack/library_pipeline.cppm index 8ce9a23de..ac5435575 100644 --- a/src/pack/library_pipeline.cppm +++ b/src/pack/library_pipeline.cppm @@ -416,6 +416,14 @@ export int build_and_pack_library(const std::string& targetName, plan.cxxRuntime = ctx->manifest.buildConfig.cxxRuntime; declaredPlatforms = ctx->manifest.package.platforms; plan.dependencies = publishable_dependencies(ctx->manifest); + // The system libraries the package's own link states, for the + // `.pc` (design 2026-11-27 §3.3.3); nothing new is stated. + for (auto const& w : mcpp::manifest::flag_words(ctx->manifest.buildConfig.ldflags)) + if (w.starts_with("-l") || w == "-pthread") plan.systemLibs.push_back(w); + // A tree named by path: what the description says, and what an + // index entry cannot supply. + if (!ctx->tc.localRoot.empty()) + plan.builtWithTree = std::format("{} ({})", ctx->tc.localRoot.generic_string(), ctx->tc.label()); plan.extras = extras_of(ctx->manifest, ctx->projectRoot); // Read from the FIRST leg's manifest, like every other package-wide // fact here: one package, one answer. A `[pack] strip` that differed @@ -485,6 +493,16 @@ export int build_and_pack_library(const std::string& targetName, .inBandDebugInfo = mcpp::pack::debug_info_is_in_band(triple), }, }); + // A shared leg's run-time lower bounds, as an index entry's `deps` + // states them; the C++ run-time a NEEDED libstdc++ is takes the + // builder's GCC major as its floor. + if (shared) { + const auto cxxRuntime = ctx->tc.compiler == mcpp::toolchain::CompilerId::GCC && !ctx->tc.version.empty() + ? std::format("xim:gcc-runtime@>={}", ctx->tc.version.substr(0, ctx->tc.version.find('.'))) + : std::string{}; + if (auto deps = mcpp::pack::shared_library_floors(artifact, cxxRuntime); !deps.empty()) + plan.legDeps[triple] = std::move(deps); + } mcpp::ui::status("Packed leg", std::format("{} [{}]", triple, tag.str())); } @@ -619,6 +637,11 @@ export int build_and_pack_library(const std::string& targetName, auto out = run_library_pack(plan); if (!out) { mcpp::ui::error(out.error().message); return 1; } mcpp::ui::status("Packed", out->string()); + // What the binary holds for: a tree named by path is the consumer's too. + if (!plan.builtWithTree.empty()) + mcpp::diag::note("pack/built-with-a-tree", std::format( + "{} was built with the toolchain at {}: it holds for consumers that build with the same " + "toolchain, and `mcpp emit xpkg` describes no such package", plan.packageName, plan.builtWithTree)); if (report) { std::error_code ec; report->artifact = std::filesystem::absolute(*out, ec).lexically_normal(); diff --git a/src/pack/pack.cppm b/src/pack/pack.cppm index d254d86d0..bd83214b5 100644 --- a/src/pack/pack.cppm +++ b/src/pack/pack.cppm @@ -660,10 +660,35 @@ std::string_view mode_cli_name(Mode m); std::string_view mode_tarball_suffix(Mode m); std::optional parse_mode(std::string_view s); +// THE RUN-TIME LOWER BOUNDS OF A SHARED LIBRARY, as an index entry's `deps` +// states them (design 2026-11-27 §3.3.3): the C library from the highest +// `GLIBC_` version the library names (the reading a program's package makes), +// and `cxxRuntimeDep` when it names libstdc++. Empty for a file that is no ELF +// shared object (a static archive names no version). +// +// Here, not in mcpp.pack.library: importing mcpp.runtime.elf and +// mcpp.toolchain.base into that module made GCC 16.1 crash at the first +// import of mcpp.cli (a segmentation fault reading the BMIs, mcpp#1027). +std::vector shared_library_floors(const std::filesystem::path& artifact, + std::string_view cxxRuntimeDep); + } // namespace mcpp::pack namespace mcpp::pack { +std::vector shared_library_floors(const std::filesystem::path& artifact, + std::string_view cxxRuntimeDep) { + std::vector deps; + auto facts = mcpp::runtime::elf::inspect_elf_runtime(artifact); + if (!facts) return deps; + if (auto floor = mcpp::toolchain::base::highest_glibc(facts->requiredGlibcVersions); !floor.empty()) + deps.push_back(std::format("xim:glibc@>={}", floor)); + if (!cxxRuntimeDep.empty()) + for (auto const& n : facts->needed) + if (n.starts_with("libstdc++.so")) { deps.emplace_back(cxxRuntimeDep); break; } + return deps; +} + std::string_view mode_cli_name(Mode m) { switch (m) { case Mode::None: return "system"; diff --git a/tests/e2e/pack/library.cpp b/tests/e2e/pack/library.cpp index 1ec2358a1..56ac1e6ea 100644 --- a/tests/e2e/pack/library.cpp +++ b/tests/e2e/pack/library.cpp @@ -832,6 +832,62 @@ version = "0.1.0" expect(fatal(e2e::contains(s::text(r), "imports 'Beta' of 'probe.flatlib', which is not one of that package's public modules"))) << "I3: W3 is missing\n" << s::text(r); expect(e2e::contains(s::text(r), "import a public module of 'probe.flatlib': Alpha")) << "I3: W3 does not name the public modules\n" << s::text(r); }; + + "a library package describes itself to other build systems and to an index entry"_test[s::unix_shell] = [] { + // Design 2026-11-27 §3.3.2, §3.3.3: a library package carries mcpp-package.json and, per + // leg, a `.pc` from its own link intent (prefix relative to the file, `-l` of its ldflags + // as Libs.private, `mcpp_abi`); `mcpp emit xpkg --package` writes its entry (address and + // digest from the archive, `mcpp = "mcpp.toml"`, the .pc declared into the environment). + // An archive mcpp pack did not write, one an earlier mcpp wrote without the description, + // and a library package's directory taken for a source tree are refused by name. + const auto tmp = s::case_dir(); + s::project lib{tmp / "mathkit", { + {"src/mathkit.cppm", "export module mathkit;\nexport namespace mk { int add(int a, int b); }\n"}, + {"src/impl.cpp", "module mathkit;\nnamespace mk { int add(int a, int b) { return a + b; } }\n"}, + {"src/capi.c", "int mathkit_add(int a, int b) { return a + b; }\n"}, + {"include/mathkit_c.h", "int mathkit_add(int a, int b);\n"}, + {"mcpp.toml", "[package]\nname = \"mathkit\"\nversion = \"0.1.0\"\n[build]\n" + "sources = [\"src/*.cppm\", \"src/*.cpp\", \"src/*.c\"]\ninclude_dirs = [\"include\"]\n" + "ldflags = [\"-lm\"]\n[targets.mathkit]\nkind = \"lib\"\n"}}}; + auto r = lib.mcpp({"pack", "mathkit", "--pkg-format", "tar"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + const auto pkg = dist_dir(lib, "mathkit-0.1.0-"); + const auto archive = dist_file(lib, "mathkit-0.1.0-", ".tar.gz"); + expect(fatal(pkg.has_value() && archive.has_value())) << s::text(r); + const auto pcs = s::find_files(*pkg / "lib", R"(mathkit\.pc)"); + expect(fatal(pcs.size() == 1)) << "one .pc per leg, under lib//pkgconfig/"; + const auto pc = s::read_file(pcs.front()); + for (std::string_view line : {"prefix=${pcfiledir}/../../..", "Libs: -L${libdir} -lmathkit", "Libs.private: -lm", + "mcpp_abi="}) + expect(e2e::contains(pc, line)) << "the .pc lacks '" << line << "':\n" << pc; + const auto description = s::read_file(*pkg / "mcpp-package.json"); + expect(e2e::contains(description, R"("kind": "library")")) << description; + if (auto tool = s::on_path("pkg-config")) { + auto read = s::run(*tool, {"--cflags", "--libs", "--static", "mathkit"}, {}, + {{"PKG_CONFIG_PATH", pcs.front().parent_path().string()}}); + expect(e2e::contains(read.out, "-lmathkit") && e2e::contains(read.out, "-lm") + && e2e::contains(read.out, "include")) << "pkg-config read: " << read.out; + } + r = lib.mcpp({"emit", "xpkg", "--package", archive->string(), "--url", "https://example.org/v0.1.0"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + const auto entry = r.out; + for (std::string_view word : {R"(mcpp = "mcpp.toml")", "linux = {", "https://example.org/v0.1.0/", + "declare_pkgconfig", "relocate_pkgconfig"}) + expect(e2e::contains(entry, word)) << "the entry lacks '" << word << "':\n" << entry; + + // Refused by name. + const auto foreign = tmp / "foreign-0.1.tar.gz"; + s::write_executable(tmp / "make-foreign.sh", std::format( + "#!/bin/sh\nset -e\nmkdir -p '{0}/foreign-0.1'\necho hi > '{0}/foreign-0.1/README'\n" + "tar -C '{0}' -czf '{1}' foreign-0.1\n", tmp.string(), foreign.string())); + expect(fatal(s::run(tmp / "make-foreign.sh").status == 0)); + e2e::expect_diagnostic("\\[not-a-package-of-mcpp-pack\\]"); + r = lib.mcpp({"emit", "xpkg", "--package", foreign.string(), "--url", "https://example.org"}); + expect(failed(r) && e2e::contains(s::text(r), "foreign-0.1.tar.gz")) << s::text(r); + e2e::expect_diagnostic("\\[emit-inside-a-package\\]"); + r = s::mcpp({"emit", "xpkg"}, *pkg); + expect(failed(r)) << "emit xpkg in a library package's directory was not refused: " << s::text(r); + }; }}; } // namespace diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index 9967819b0..544f9639e 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -289,6 +289,27 @@ E2E custom{"custom", s::home_fixture, [] { expect(e2e::contains(out, "this driver takes no module unit")) << out; }; + "a library packed with a tree named by path gets no index entry"_test[s::llvm] = [] { + // Design 2026-11-27 §3.3.3: the package records the tree it was built with, the pack notes + // for whom it holds, and `mcpp emit xpkg --package` refuses it with + // `[package-built-outside-the-ecosystem]`: an index cannot supply its environment. + 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())); + s::project lib(s::case_dir() / "lib", { + {"mcpp.toml", std::format("[package]\nname = \"treelib\"\nversion = \"0.1.0\"\n\n[targets.treelib]\n" + "kind = \"lib\"\n\n[toolchain]\ndefault = {{ path = \"{}\" }}\n", llvm_root.generic_string())}, + {"src/treelib.cppm", "export module treelib;\nexport int treelib_value() { return 7; }\n"}, + }); + e2e::expect_diagnostic("built with the toolchain at"); + auto r = lib.mcpp({"pack", "treelib", "--pkg-format", "tar"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + const auto archives = s::glob(lib.at("target/dist"), "treelib-0.1.0-*.tar.gz"); + expect(fatal(archives.size() == 1)) << s::text(r); + e2e::expect_diagnostic("\\[package-built-outside-the-ecosystem\\]"); + r = lib.mcpp({"emit", "xpkg", "--package", archives.front().string(), "--url", "https://example.org"}); + expect(!e2e::succeeded(r) && e2e::contains(s::text(r), llvm_root.generic_string())) << s::text(r); + }; + "876 toolchain phase"_test[s::llvm][s::unix_shell][s::symlink] = [] { // `[toolchain] default = { configure = "build.mcpp" }` (mcpp#755): the build program's // toolchain phase states the toolchain (a path, reported with its origin; a managed spec, From f18619e5f883aa91bd329858605590e6ac7339ec Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 04:19:48 +0900 Subject: [PATCH 10/36] Workspace selections build one configuration at once: a plan is held by its own lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A command's selection of workspace members is a plan with its own directory, plans/<16 hex digits>/ of the configuration's, named by the members as a set: its graph, ninja's state (build.ninja, .ninja_log, .ninja_deps), the schedule, the placements, the records and the runs, under the plan's lock (.mcpp-plan.lock). The configuration's directory is held shared by plans and alone by what changes it as a whole (SPEC-011 §2 items 7 to 10, design 2026-11-27 §3.7.1, D12). A unit two plans reach is compiled by the first and placed for the other by the unit cache, under a lock beside its output; response files are named per plan; an artifact two plans link is written under a temporary name of its own and renamed, and on a POSIX host an archive is written whole and renamed as a link is. The holding needs relocatable compiler outputs and the unit cache; under --cache off, bmi_schedule = "on", a graph that runs actions, or the build optimization plan-locks turned off ([build] plan_locks = "configuration", MCPP_PLAN_LOCKS), the configuration is held alone as before. mcpp why toolchain states the holding and its reason; a wait names the plan's members. batch-fetch is listed as a build optimization. result.json holds the record of the command that wrote it last, each command's own record is in its plan's directory, which .last-result.json names. The command-line length limit is the host's, stated in each system's native file. The design record (v10) also carries the CPS sub-design (§3.12, D22 to D24): mcpp's model is the centre, CPS a compatibility at two boundaries. --- .../2026-11-27-ecosystem-boundary-design.md | 178 +++++++++++++++- CHANGELOG.md | 17 ++ docs/04-mcpp-toml.md | 2 + docs/07-workspace.md | 48 +++-- docs/26-build-optimizations.md | 17 +- docs/50-machine-output.md | 10 + docs/mcpp-skills/mcpp-build/SKILL.md | 7 +- docs/specs/README.md | 4 +- docs/specs/build-optimizations.md | 26 ++- docs/specs/concurrency.md | 37 +++- docs/zh/04-mcpp-toml.md | 2 + docs/zh/07-workspace.md | 22 +- docs/zh/26-build-optimizations.md | 12 +- docs/zh/50-machine-output.md | 6 + modules/buildopt/README.md | 6 +- modules/buildopt/src/advice.cppm | 19 ++ modules/unit-cache/src/unit_cache.cppm | 5 +- src/build/command_line.cppm | 5 + src/build/dirlock.cppm | 83 +++++++- src/build/execute.cppm | 196 ++++++++++++------ src/build/graph_engine.cppm | 8 + src/build/ninja_backend.cppm | 171 ++++++++++----- src/build/plan.cppm | 48 ++++- src/build/prepare.cppm | 9 + src/build/prepare/build_dir.cpp | 40 +++- src/build/prepare/plan.cpp | 112 ++++++++-- src/build/prepare/records.cpp | 31 +-- src/build/prepare/state.cppm | 7 +- src/build/result.cppm | 38 +++- src/build/runtime_validation.cppm | 69 +++--- src/build/schedule/compiler_transaction.cpp | 13 +- src/build/schedule/detach_codegen.cppm | 75 ++++++- src/build/schedule/relocation.cppm | 18 +- src/cli/cmd_build.cppm | 99 +++++---- src/doctor.cppm | 9 +- src/native/posix/command_line.cpp | 12 ++ src/native/windows/command_line.cpp | 12 ++ src/pack/distribution.cppm | 4 +- tests/e2e/cache/invariants.cpp | 55 +---- tests/e2e/cli/terminal.cpp | 99 +-------- tests/e2e/index/local.cpp | 86 ++++++++ tests/e2e/pack/members.cpp | 11 +- tests/e2e/workspace/graph.cpp | 125 ++++++++--- tests/e2e/workspace/inheritance.cpp | 20 +- tests/e2e/workspace/members.cpp | 17 +- tests/e2e/workspace/statements.cpp | 2 +- tests/support/src/support.cpp | 148 ++++++++++++- tests/support/src/support.cppm | 30 ++- tests/unit/test_ninja_backend.cpp | 22 ++ tests/unit/test_plan_locks.cpp | 57 +++++ 50 files changed, 1619 insertions(+), 530 deletions(-) create mode 100644 src/native/posix/command_line.cpp create mode 100644 src/native/windows/command_line.cpp create mode 100644 tests/unit/test_plan_locks.cpp diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index cacd7b7b2..388e6b9a6 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -5,7 +5,7 @@ status: active # 生态与外部的交界:工具链的事实、二进制库交付物、被启动的外部程序、名字的拼写与共享的状态 -**日期:** 2026-11-27,2026-12-04 修订 · **版本:** v8(待评审;决定全部作出,见 §7;五轮自查的结论见 §11) · +**日期:** 2026-11-27,2026-12-04、2026-12-05 修订 · **版本:** v10(v9 增加 §3.12 CPS 与决定 D16 至 D21;v10 以 mcpp 为中心重写 §3.12,D22 至 D24 取代 D16 至 D18 与 D21;决定全部作出,见 §7;五轮自查的结论见 §11) · **基线:** mcpp main `30fcd5a0`(2026.11.27.1 之后,含 #1036)、xlings 2026.11.23.1、openkal 0.26.0、openkal-linux 0.27.2、 openkal-windows 0.23、openkal-musl 0.30.3、mcpplibs.os 0.4.8、mcpplibs.cmdline 0.1.0(mcpp 所钉为 0.0.6)、 mcpp-index `9788068b` · @@ -31,6 +31,7 @@ mcpp 的一个命令默认运行宿主的程序,按同一组规则设计。评 回答了宿主的(#1039)。 - **问题二(二进制库交付物)。** 一个库以二进制形式交付给不使用 mcpp 的构建系统。C++ 静态库没有跨标准库实现的稳定 ABI,所以交付物的 ABI 由构建它的那套环境决定。 + 它的另一面是读:一个由其他构建系统安装、以 CPS 描述的库被 mcpp 工程的构建程序使用(§3.12)。 - **问题三(被启动的外部程序)。** 生态内的程序启动生态外的程序(版本控制工具、命令解释器、自建沙箱的包装程序)。 调用者需要确切知道被启动的程序持有什么。 - **问题四(名字的拼写)。** 生态的工具运行在按拼写授权的环境里(替换出的盘符、经符号链接到达的目录、只对某个 @@ -739,6 +740,18 @@ docs/07 的陈述与实现一致。规范的这一条随本轮改正。 让两个计划同时编译同一个单元;测量一个选择首次构建的放置开销;归档的原子发布;在网络文件系统上的共享持有。有一条路径归不进任何一行时, 它所属的配置保持排他,而不是为它开一个例外。 +**实现(2026-12-05)。** 与上文五处不同。其一,计划的键是配置组的成员集合(排序后的路径),不是选择与组: +`-p b -p a` 与 `-p a -p b` 的构建图相同,二者共用一个计划与它的 ninja 状态,与此前共用配置目录相同。其二,条件 +多两条:`bmi_schedule = "on"` 的监督进程比它的步骤活得久;动作原地写出它的输出,没有发布协议。这样的构建保持排他。其三,计划目录另收纳运行时校验 +记录、`resolution.json` 与 `result.json` 的计划副本以及构建优化记录;配置一级的副本以整份替换写出,快速路径读 +计划自己的那一份(一份被另一个计划替换的结果记录会让快速路径复述别的计划的产物)。其四,ninja 在一条边结束时删除 +它的响应文件,两个计划同时运行同一条链接边时会删掉对方将要读的文件:计划有自己的目录时响应文件以计划命名,单元 +缓存以响应文件的内容而非名字作键。链接的临时名带进程号并保留扩展名(`.<主名>.<扩展名>`),归档在 POSIX 宿主上同样写临时名后 +改名。其五,`--no-cache` 与显式的 `--cache` 同时给出时构建仍是共享持有,这时只清空该计划自己的状态并经 +`degraded`(`build/cold`)说明。M10 的第 3 项未单独测量:一个选择首次构建时被放置的单元经单元缓存,量级与 +2026.11.21.1 的单元缓存命中相同(本机 GCC 16.1,`-p b` 首次构建在 `-p a` 之后 1.1 秒,其中共有单元一个);快路径 +的那一层没有加入。 + #### 3.7.2 等待的上限与提示(D10 已决定) 默认仍然等待:SPEC-011 §2 第 3 条规定后到者等待而不是失败,而一次正当的等待有多长,mcpp 无从得知。上限作为显式的 @@ -1023,6 +1036,132 @@ xlings 的锁的记录已经写明「是提示而不是事实」,与规则五 修订改变后恰好重装一次并打印 `Updating`;等待另一个进程的安装时报告的形状,以及 `--lock-wait` 到期时以原因码 拒绝。并发安装的两条 e2e 属于收尾(第 12 条)。 +**实现(2026-12-05)。** 与上文一处不同:`batch-fetch` 没有失败时的 `tip:`。提供者没有完成的一批之后,每个没有装上的 +依赖各自取得,这就是取值 `each` 的做法;此后仍然存在的失败在 `each` 之下同样发生,点名这个条目的提示会把人引向一个 +不是原因的开关(SPEC-019 §9 第 3 条写明这一点)。第 5 条的重放测试由一个代替安装器的脚本在一次调用里下载两个依赖, +其间向自己的标准错误写一行;终端的字节流在测试辅助函数里重放,断言每个依赖恰好一行 `Downloading`,没有残留的帧, +第二次构建不调用安装器(e2e `index/local` 1180)。 + +### 3.12 CPS:mcpp 的事实写给其他构建系统,其他构建系统的包经构建程序的声明进入(mcpp) + +CPS(Common Package Specification,规范 v0.15.0)以一个 JSON 文件描述一个包供其他工程使用:组件(`archive`、 +`dylib`、`interface` 等)、各组件的 `includes`、`definitions`、`location`、`requires`,包的 `platform` +(`isa`、`kernel`、C 与 C++ 运行时的厂商与下界)、按配置的补充文件(`<名>@<配置>.cps`)与 `@prefix@` 的可重定位路径。 +CMake 4.3(2026-03)正式支持导入与写出,Conan 有实验性的支持;Meson、vcpkg、xmake 未见原生支持。 + +#### 3.12.0 立场:以 mcpp 为中心,CPS 是边界上的可选兼容 + +mcpp 的模型不因 CPS 改变。包、依赖图、索引与解析、目标侧、库包(`mcpp-package.json` 与它的清单)、构建程序的协议、 +`prepare` 的契约与锁是 mcpp 自己的规范,CPS 不进入其中任何一项的定义。CPS 只出现在两条边界上: + +- **向外**:`mcpp pack` 已算出的库包事实,多一种写给其他构建系统的写法,与 `.pc` 并列(§3.3.3)。 +- **向内**:其他构建系统安装的包,由构建程序以一条声明读取,读取的结果是已有指令的效果(包含目录、编译词、链接词、 + 运行时目录、重跑的输入),与手写这些指令的构建程序没有区别。它不是依赖图中的包,与 `deps-cmake`、`deps-vcpkg` + 交来的包同一种地位。 + +三条约束由此而来:(1) 不为 CPS 增加清单的键、索引的种类、锁的条目或命令行命令,唯一新增的面是 `[pack] descriptions` +与构建程序的一条声明;(2) CPS 的词汇(组件、配置名、厂商词)只在 CPS 的代码里与 mcpp 的词互译,不成为 mcpp 的词; +(3) CPS 的代码自成一个模块包 `modules/cps/`,每个使用处一个适配文件,去掉它们,mcpp 的其余部分不变。 + +#### 3.12.1 现状(读码;实测,CMake 4.5.0,本机) + +mcpp 既不写也不读 CPS。最近的机制是 §3.3.3 的 `.pc` 与库包清单;`deps-cmake`、`deps-vcpkg` 由使用者写出每个库文件名。 +实测(M13):(1) CMake 4.5 对 `install(PACKAGE_INFO)` 写出主文件与 `<名>@release.cps`,`cps_version` 为 `0.15.0`,**不写 +`platform`**;(2) CMake 的读取**不比较 `platform`**:读码(`cmPackageInfoReader`、`cmFindPackageCommand`)没有对 +`isa`、`kernel` 的比较,把 `x86_64` 腿的 `isa` 改为不存在的值后它仍被选中;`lib/cps/<名>/*/` 下有多条腿时,选中哪一条 +取决于目录的枚举;`x_mcpp_` 属性被容忍,带点的名字可用(`find_package(acme.imaging)`、`acme.imaging::image`); +(3) 带 `cpp_module_metadata` 的组件导入后没有任何 C++ 模块属性,CMake 不经 CPS 导入模块;(4) 经符号链接放进另一前缀的 +`.cps` 以链接所在的位置减去 `cps_path` 推导前缀,库路径因此错;文件写有存在的绝对 `prefix` 时,CMake 先用它,经链接 +与复制都正确;(5) CMake 的查找包括 +`<前缀>/cps/<名>/` 与 `<前缀>/(lib/|lib*|share)/cps/<名>/`,前缀由文件所在目录减去 `cps_path` 的尾部得到; +(6) xim 的 cmake 在三个平台都有 4.5.x。 + +#### 3.12.2 设计 + +**一、写出属于 `mcpp pack`。** `.cps` 与 `.pc` 同源于引擎已算出的事实,写在 `.pc` 旁,规则相同。 + +- 每条腿一份:`lib/<三元组>/cps/<身份>/<身份>.cps`,与 `lib/<三元组>/pkgconfig/<身份>.pc` 同一层次; + `cps_path = "@prefix@/lib/<三元组>/cps/<身份>"`,`name` 为包的身份,`version`、`compat_version`(按 mcpp 的语义化版本: + 主版本不为零时为 `<主>.0.0`,否则为 `0.<次>.0`)。腿各在自己的目录中,不依赖读者比较 `platform`(M13 第 2 项): + 在多架构布局的主机上 CMake 经 `lib/` 直接找到它,其他主机上使用者把 `<包>/lib/<三元组>` 加入 + `CMAKE_PREFIX_PATH`,与 `.pc` 时把 `lib/<三元组>/pkgconfig` 加入 `PKG_CONFIG_PATH` 是同一件事。 +- `platform` 照写,取自目标侧:`isa` 为三元组的架构,`kernel` 为系统表的 `uname` 词(没有时为系统名),两个运行时的 + 厂商由三元组的环境与 C++ 标准库得出;词的互译在 `modules/cps` 中,读写共用一张表。 +- 每个库目标一个组件,名为包名(不带命名空间):静态库 `archive`(`link_languages = ["cpp"]`),共享库 `dylib`(PE 另有 + `link_location` 指向导入库);`includes` 为 `@prefix@/include`;`ldflags` 的 `-l` 词为 `link_libraries`;依赖为包一级的 + `requires`(版本取依赖的要求中可表达的下界)与组件一级的 `<依赖>:<依赖名>`,`private` 依赖在静态库上为 + `link_requires`、在共享库上不写;`default_components` 为该组件;`x_mcpp_abi` 为兼容标签。mcpp 没有公开的宏,因此不写 + `definitions`。 +- 只有模块接口的包不写,与 `.pc` 同一条说明(`pack/no-header-interface` 说两种描述):CMake 不经 CPS 导入模块。 +- `[pack] descriptions = ["pkg-config", "cps"]` 为默认值,可写其子集或空表;一个键管两种写给其他构建系统的描述。 +- `mcpp-package.json` 记 `.cps` 为 `metadata` 角色;`mcpp emit xpkg` 写出的条目在 `.pc` 的两行旁以同样的 `pcall` 调用 + `relocate_cps` 与 `declare_cps`(见五)。 + +**二、读取:构建程序的一条声明,展开为已有指令的效果。** + +```cpp +mcpp::cps_package imaging; +imaging.name = "acme.imaging"; +imaging.prefix("third_party/prefix").component("image"); +imaging.submit(); +``` + +(线上为 `mcpp:cps-package={"name":…,"prefixes":[…],"components":[…],"version":…,"configuration":…}`,协议 22; +与 `mcpp::action`、`mcpp::runner_spec` 同一种声明的形状。)引擎在构建程序运行之后、应用指令之前读取,展开为: + +| CPS | 展开为 | +|---|---| +| `includes`(不分语言) | `include-dir` | +| `includes` 按语言、`definitions`、`compile_flags` | `cflag`、`cxxflag`(`-I`、`-D`、原样) | +| `archive`、`dylib` 的 `location`(PE 为 `link_location`)、`link_libraries`、`link_flags` | `link-flag` | +| `dylib` 所在目录 | `runtime-search-dir` | +| 读过的每个 `.cps` | `rerun-if-changed` | + +展开在构建程序的记录写出之前完成,记录里只有已有的指令,重放照旧;`.cps` 变化时构建程序重跑,读取随之重做。 +声明的效果与这些指令相同:编译的一面属于声明它的包,链接的一面到达消费者,`mcpp pack` 的闭包经运行时目录找到共享库。 + +- **查找。** 在所列前缀中依次按 CMake 的位置找 `<名>.cps`(原样与小写):`cps/<名>/`、`cps/<名>/*/`、`cps/`、`<名>/cps/`、 + `lib*/cps/<名>/`、`lib*/cps/<名>/*/`、`lib/*/cps/<名>/`、`lib*/cps/`、`share/cps/<名>/`、`share/cps/`;同目录的 + `<名>-*.cps` 补充组件,`<名>@<配置>.cps` 补充配置。前缀为相对路径时相对于包的根。 +- **匹配。** 候选的 `platform` 中写出的字段与这次构建的目标侧比较(`isa`、`kernel`、两个运行时的厂商,词经一的表互译, + 大小写不计);未写出的字段按 CPS 不约束。声明写了 `version` 时按 `compat_version` 至 `version` 比较。不符的候选跳过; + 没有候选或都不符时拒绝(`cps-no-matching-package`),列出查找过的位置或每个候选与不符的字段。 +- **组件。** 未指定时取 `default_components`;两者都没有时拒绝(`cps-components-unstated`)并列出组件。指定的或被 + `requires` 引用的组件不存在时拒绝(`cps-component-not-found`)。`requires`、`link_requires` 在同一组前缀中递归读取; + `executable`、`module`、`jar`、`symbolic` 不进入链接,被指定时说明一次(`cps/component-not-linked`)。 +- **配置。** profile 到配置的偏好是 `modules/cps` 的数据(`dev` → `Debug`;`release` → `Release`、`RelWithDebInfo`、 + `MinSizeRel`),之后是包自己的 `configurations`,再之后是唯一的一份;声明的 `configuration` 是覆盖。 +- **说明。** 带 `cpp_module_metadata` 的组件按其库与头文件使用,说明一次(`cps/modules-not-imported`)。读不成 CPS 的文件 + 拒绝(`cps-description-invalid`),点名文件与原因。 + +**三、构建时才填好的前缀不经 CPS 读取。** `deps-cmake`、`deps-vcpkg` 的前缀由 `prepare` 动作在构建时填好,构建程序运行时 +它还不存在。读取它需要「编译与链接的词取自一个动作写出的文件」这一新的通用契约(响应文件作为边的输入,名字在配置时 +固定、内容随动作而来),它只为一种格式而引入。这些插件照旧以 `libraries` 选项写出库名;本方案不改 mcpp-plugins。 + +**四、与多包管理器规范的关系。** mcpp 的依赖图只有 mcpp 的包;其他包管理器的包经构建程序进入(插件与这条声明), +CPS 是其中一种被读取的描述。`mcpp-package.json` 仍是 mcpp 的权威描述(文件角色、摘要、腿与接口—二进制的绑定是 CPS 没有 +的);`.pc`、`.cps` 是写给其他工具的写法,由同一组事实生成。扩展只用 `x_mcpp_` 前缀,不改 CPS 已有属性的含义。 + +**五、环境一侧。** 照 `relocate_pkgconfig`、`declare_pkgconfig` 的两步:xim-pkgindex 的 `xim.pkgindex.sysroot` 增加 +`relocate_cps`(安装时在载荷自己的 `.cps` 中写入载荷的绝对 `prefix`,与 `.pc` 的前缀同属载荷)与 `declare_cps`(配置时把 +`<目录>/<名>/` 声明进环境的 `usr/lib/cps/<名>/`)。M13 第 4 项:写有绝对 `prefix` 的文件经链接被正确读取,所以不需要 +逐个环境的副本。环境的 `usr/` 因而是一个 CPS 前缀,环境中的 CMake 把它加入 `CMAKE_PREFIX_PATH` 即可。`mcpp emit xpkg` +写出的条目以 `pcall` 调用这两个函数;没有它们的索引中,条目打印 `.cps` 的位置并成功。 + +**六、代码的位置。** `modules/cps/` 是独立的模块包:`mcpp.cps`(模型、读取与补充文件的合并、写出、版本比较、词的互译) +与 `mcpp.cps.usage`(查找、匹配、组件闭包、配置选择,得出与指令同形的结果),只依赖 JSON 库,单元测试在包内。使用处 +各一个适配文件:`src/pack/library/descriptions.cpp`(`mcpp.pack.library` 的实现单元,`.pc` 与 `.cps` 两种描述都在此)、 +`src/build/cps_package.cppm`(把声明展开为指令)。构建程序一侧只有内置模块中的声明类型与指令表的一行。 + +**七、文档与示例。** 新章 docs/14「Common Package Specification」两种语言:立场、两个方向、声明与展开、匹配与拒绝、 +与 pkg-config 的分工。SPEC-014 记写出,SPEC-007 记声明;docs/10、12 记文件,docs/30 记声明,docs/04 记 +`[pack] descriptions`,docs/50 记原因码。示例:`05-lib-distribution/cmake-consumer/`(CMake ≥ 4.3 以 `find_package` +使用打出的库包);新例 `14-cps`(一个 CMake 工程写出 CPS,一个 mcpp 工程以声明使用它);docs/03 的课程表加一行。 + +**验收。** 单元:读取(补充文件的合并、`@prefix@` 与 `prefix`、按语言的映射、配置覆盖、`null`)、写出、往返、平台匹配、 +版本、查找的位置。e2e:库包的 `.cps` 合乎规范并被 CMake 4.5 找到与链接运行;声明的默认组件、指定组件、`requires` 链、 +平台不符的跳过与拒绝、配置的选取、`.cps` 改变后重跑、各拒绝的原因码。 + ## 4. 各仓库改动的性质、最佳方案与理由 性质分四类:**缺陷修复**(实现与已写明的行为不符,或默认配置失败)、**优化**(结果不变,时机或信息更好)、 @@ -1057,6 +1196,10 @@ xlings 的锁的记录已经写明「是提示而不是事实」,与规则五 | mcpp | 11d 按波次取得依赖 | 优化(构建优化表的条目 `batch-fetch`) | 一步已知的全部依赖一次调用 | 实测四个小包约 27 秒,时间在逐个启动与连接上 | | mcpp | 收尾(xlings 发布之后的一个 PR) | 优化 | 改钉 xlings;去掉 mcpp 的安装轮次;转述安装器的等待;两条并发安装的 e2e。由一个备注 issue 记录 | 同一件事不需要两层各一把锁;在安装器消除同包并发的缺陷之前,轮次不能去掉 | | mcpp | 同一个包在两处陈述给出两个版本时的说明;一棵树里有两个族的驱动时的说明 | 优化 | 各一条说明,每个工程一次 | 行为不变;读者此前只能从文件系统或 `Using` 行重建这个事实 | +| mcpp | 20a 库包写出 `.cps`(D19、D20) | 新功能 | 与 `.pc` 同源、同位、同一条说明;`[pack] descriptions` 为覆盖 | CMake 4.3+ 与 Conan 不经 mcpp 即可使用 mcpp 的库包;事实已在引擎中,放在别处是第二份实现 | +| mcpp | 20b 构建程序声明前缀中的包(D22) | 新功能 | 声明 `cps_package`,引擎在应用指令之前把它展开为已有指令的效果 | 其他包管理器的包经构建程序进入是 mcpp 既有的方式;展开的结果与手写指令相同,不增加清单、索引、锁的概念 | +| mcpp | 20c CPS 的代码自成模块包(D24) | 结构 | `modules/cps/` 加每个使用处一个适配文件 | CPS 是边界上的可选兼容;去掉它不改变 mcpp 的其余部分 | +| xim-pkgindex | 21 `relocate_cps`、`declare_cps` | 新功能 | 载荷自己的 `.cps` 写入绝对 `prefix`,再声明进环境的 `usr/lib/cps/<名>/`(M13) | 与 `declare_pkgconfig` 同一位置、同一用法;链接到环境的文件推导出错误的前缀 | | openkal-windows | 12 启动时的名字(mcpp#1032) | 缺陷修复 | 三步称呼,前两步与句柄核对为同一对象 | 与直接启动的结果一致;不增加状态、不改规范;边界(当前目录之外的工作目录)写明 | | openkal-musl | 13 C 库一层的陈述(openkal-musl#93) | 新功能 | `posix_spawn_file_actions_addclosefrom_np` | 别的 C 库已有的词与含义;内核抽象层已有对应的启动;默认值不变 | | openkal 规范 | 14 偏好的继承途径 | 规范的澄清 | 7.17 补一句;测试集增加一例 | 八个实现已分成两种行为,测试集没有分辨出来 | @@ -1122,7 +1265,8 @@ xlings 的锁的记录已经写明「是提示而不是事实」,与规则五 | 3 | mcpp-index | cmdline 新版本的条目(条目自带的自动更新) | cmdline | 上述检查 | | 4 | openkal-musl | 改动 13,§3.4.3 的测试;依赖范围接纳上面的版本 | openkal 各实现 | 外部子进程只有 0、1、2,环境与给出的相同 | | 5 | openkal-llvm-runtime、mcpplibs.os | 按家族的确切版本钉级联;无功能改动 | 上一行 | 各自的 CI | -| 6 | mcpp | 改动 1 至 11 与两条说明;mcpplibs.os 与 mcpplibs.cmdline 的新版本;SPEC-004、006、011、014、017、019 的条款;docs/01、04、07、08、09、10、12、20、25、26、50、52 两种语言;`docs/mcpp-skills/`;CHANGELOG | 第 1、3、5 行 | §10.3 | +| 6 | mcpp | 改动 1 至 11、改动 20 与两条说明;mcpplibs.os 与 mcpplibs.cmdline 的新版本;SPEC-004、006、007、011、014、017、019 的条款;docs/01、03、04、07、08、09、10、12、14、20、25、26、30、50、52 两种语言;示例 05 与 14;`docs/mcpp-skills/`;CHANGELOG | 第 1、3、5 行 | §10.3 | +| 6 | xim-pkgindex | 改动 21 | — | `relocate_cps`、`declare_cps` 的测试;mcpp 的条目在有无该函数的索引中都安装成功 | 次序相同的行互不依赖,可以同时进行。探针 PR(mcpp#1035)保留到 mcpp 的发布完成。mcpp 的改动 3、6、8、9、10 不依赖 openkal 的任何一行;它们与其余各项同在最后一行,是因为一个仓库一个 PR。 @@ -1155,6 +1299,15 @@ mcpp#1027。 | **D13** | 索引的回归修复是否单独先行 | **(a)(2026-12-04)**:单独、最先 | 与补包同一个 PR:mcpp 的 CI 一直失败到那时 | | **D14** | 安装的锁 | **(a) 的形状,分两步(2026-12-04)**:本方案不改 xlings 的代码,登记一个 xlings 的 issue;mcpp 本轮做不依赖它的部分并保留自己的安装轮次;xlings 发布之后一个收尾的 PR,由 mcpp 的备注 issue 跟踪(§3.11.2 第 10 至 13 条) | 在本方案内直接改 xlings:它动的是安装器最核心的路径,与本轮其余各项没有次序上的依赖。两层的锁都不动:首次构建与并行的安装永远串行。mcpp 自己按包加锁:安装器自己取的是 home 的锁 | | **D15** | 各平台共有的版本如何写 | **平台引用(2026-12-04)**:一个平台的表陈述,其余平台 `{ ref = "<平台>" }` 指向它;mcpp 的读者按安装器的解析读它;工具一并读它 | 内联地写进每个平台:已发布的读者读得对,但三个平台同样的内容各写一遍,一万八千行重复,索引的作者为读者的缺陷付出代价。局部表的引用:已发布的读者读错修订 | +| ~~D16~~ | CPS 的读取怎样写(2026-12-05;由 D22 取代) | 索引的一种:`[indices] = { cps = [...] }`,依赖照常写(§3.12.2 二) | 依赖上的 `{ cps = "<名>", prefix = … }`:查找位置散在每个依赖上,`requires` 链没有归属的索引,锁与 `override` 要另说 | +| ~~D17~~ | 选组件的键(2026-12-05;由 D22 取代) | `components`,只在 CPS 索引的依赖上有效 | `targets`、`artifacts`:已有的词另有含义(程序随消费者交付),借用会让一个词两义;不设键:多组件的包无法只取其一 | +| ~~D18~~ | 宿主的 CPS 前缀(2026-12-05;由 D22 取代) | `@host` 显式写出,且只在 `allow_host_libs` 下 | 默认查找 `/usr`:违背默认封闭 | +| **D19** | 写出的开关(2026-12-05) | **默认写出;`[pack] descriptions` 为覆盖,`.pc` 一并纳入** | 只为 CPS 设一个布尔键:两种同类的描述两个键,违背一个概念一个写法 | +| **D20** | 只有模块接口的包(2026-12-05) | **不写 `.cps`,与 `.pc` 同一条说明;读到的模块元数据说明一次** | 写出 P3286 元数据:实测 CMake 4.5 不经 CPS 导入模块,mcpp 自己的包有自己的描述,没有读者 | +| ~~D21~~ | 构建时安装的前缀(2026-12-05;由 D23 取代) | 构建程序的声明 `cps_package`,引擎写出内部步骤;不设命令行命令 | 一级命令 `mcpp cps`:格式不是任务,且无使用者。「TOOLS FOR ACTIONS」中的工具:插件绑定参数形状并转述目标侧。插件内置读取器:第二份实现 | +| **D22** | CPS 的读取(2026-12-05,取代 D16 至 D18) | **构建程序的声明 `mcpp::cps_package`,在应用指令之前展开为已有指令的效果**(§3.12.2 二);mcpp 的依赖图只有 mcpp 的包,组件、配置、厂商词留在 CPS 的代码里 | CPS 前缀作为索引的一种(D16):CPS 与 mcpp 自己的来源并列,带来索引的种类、`components` 键、`@host`、锁的条目,而需要的效果是声明者的用法,已有指令能表达。依赖上的路径指向 `.cps` 并合成清单:mcpp 没有公开的宏,`definitions` 无处可放 | +| **D23** | 构建时才填好的前缀(2026-12-05,取代 D21) | **不经 CPS 读取**;插件照旧写库名(§3.12.2 三);不设命令行命令 | 引擎写出读取的步骤(D21):需要「词取自动作写出的文件」这一新的通用契约,只为一种格式。一级命令 `mcpp cps`:格式不是任务,且无使用者。「TOOLS FOR ACTIONS」中的工具:插件绑定参数形状 | +| **D24** | CPS 的代码放在哪里(2026-12-05) | **独立的模块包 `modules/cps/`,每个使用处一个适配文件**(§3.12.2 六) | 分散进 `mcpp.pack.library` 与构建程序的应用:格式的知识与 mcpp 的机制交织,去掉或升级格式要改多处 | | — | 诊断 | §10 的规则与清单是本轮验收的一部分 | — | 另有先前作出、本文据以设计的决定:引擎不内置厂商工具链的名字;索引的缺包补齐;交付物的环境经 `[xlings]` 这一 @@ -1204,6 +1357,12 @@ mcpp#1027。 结果写进备注 issue;(3) 取得依赖、规划与构建三段路径上直接写标准错误的调用的清单,以及其中在实时区域存在时会触发的; (4) 嵌套的子构建(构建程序的那一次)是否在同一个终端上画自己的实时区域。 +**M13(CPS,本机 CMake 4.5.0,2026-12-05)。** 结果见 §3.12.1:CMake 写出的 `.cps` 不带 `platform`;CMake 不比较 +`platform`(读码,并把被选中的腿的 `isa` 改为不存在的值后它仍被选中;v9 记作「`isa` 不符的腿被跳过」,是目录枚举的 +巧合,v10 更正);`x_mcpp_` 被容忍;`cpp_module_metadata` 不产生任何导入的模块;链接到另一前缀的 `.cps` 推导出错误的 +前缀,写入存在的绝对 `prefix` 后经链接与复制都正确;xim 的 cmake 三个平台都有 4.5.x。它确定 D20、§3.12.2 一的每腿 +一个目录与五的「先写入前缀、再声明」。 + 未能测量的:按拼写授权的沙箱本身。报告中的两项观察(自带 xlings 的引导异常退出、存储根的链接告警)在普通运行器上 没有出现,需要报告者那种环境下的日志才能归因。 @@ -1220,6 +1379,13 @@ mcpp#1027。 | 增加旧版编译器载荷以匹配旧发行版的消费者 | 交付物的环境由生态供给时,消费者取得同一环境(§3.3);不取的消费者属于具名的树 | | 把库包对编译器的要求写成载荷依赖 | 实测不改变环境在用的编译器,也不产生提示 | | 把授权不随启动传递改为默认 | 受限的调用者启动的 openkal 程序会得到更多 | +| 只在 mcpp-plugins 做一个读 CPS 的成员 | 写出已需要引擎持有 CPS 的模型,插件中的读取是格式的第二份实现;展开的结果是同一组指令,放在引擎中只多一行指令表 | +| CPS 前缀作为索引的一种(v9 的 D16 至 D18) | 见 D22:CPS 成为与 mcpp 自己的来源并列的一种来源,带来新的清单词汇,而需要的效果已有指令能表达 | +| 引擎写出读取构建时前缀的步骤(v9 的 D21) | 见 D23:需要只为一种格式而设的新契约 | +| 写出 `lib/cps/<身份>/<三元组>/` 的多腿布局 | CMake 不比较 `platform`,多腿时选中哪一条取决于目录的枚举(M13);每腿一个目录与 `.pc` 同一层次 | +| 以 CPS 取代 `mcpp-package.json` | CPS 没有文件的角色与摘要、腿与接口—二进制的绑定 | +| 读取 `*Config.cmake` | 那是 CMake 的代码,只有 CMake 能执行;CPS 正为此而设 | +| 以 cps-config 读取 | 外部程序的依赖且不活跃;读取是一个小的 JSON 读取 | | 按被启动程序的种类自动决定是否传授权 | 宿主系统上的 openkal 程序不带可识别的标记;只有调用者知道它启动的是什么 | | 在句柄表里为每个目录句柄保存名字 | 规范 7.1 的判据排除它,实现自己的句柄构造也写明不建表 | | 工作目录不在当前目录之内时,在物理盘符与别名盘符之间选一个 | 没有一个是调用者给出的;猜错的方向同样被按拼写授权的环境拒绝 | @@ -1298,7 +1464,13 @@ mcpp#1027。 | 同上,归档是旧版本写出的库包 | 同上 | 拒绝 · `package-without-description` | 点名写出它的版本(取自清单的来源记录);补救:用本版本重新打包 | | 在库包目录里运行不带 `--package` 的 `emit xpkg` | 写出占位符与三个系统的条目 | 拒绝 · `emit-inside-a-package` | `this directory is a library package written by mcpp pack, not a source tree`;补救:`mcpp emit xpkg --package <归档> --url <前缀>` | | 为具名的树构建的库包写条目 | 不适用 | 拒绝 · `package-built-outside-the-ecosystem` | 点名树与驱动的身份;原因:条目会许诺一个消费者装不到的环境;补救:以 `path` 或 `git` 交付,或用托管工具链打包 | -| 库包只有模块接口 | 不适用 | 打包时 · 说明 · `pack/no-header-interface` | `<包> publishes a module interface and no header interface: no .pc is written`;影响:mcpp 以外的构建系统没有可读的描述 | +| 库包只有模块接口 | 不适用 | 打包时 · 说明 · `pack/no-header-interface` | `<包> publishes a module interface and no header interface: no .pc or .cps is written`;影响:mcpp 以外的构建系统没有可读的描述 | +| `cps_package` 的前缀中没有该包,或没有平台与版本都符合的候选 | 不适用 | 配置 · 拒绝 · `cps-no-matching-package` | 点名包与前缀;列出查找过的位置,或逐个列出候选文件与不符的字段(如 `isa x86_64, this build aarch64`);补救:确认安装写出了 `.cps`,或把该平台的安装加入前缀 | +| 声明没有指定组件,包也没有 `default_components` | 不适用 | 配置 · 拒绝 · `cps-components-unstated` | 列出包的组件;补救:`.component("<组件>")` | +| 指定的或被 `requires` 引用的组件不存在 | 不适用 | 配置 · 拒绝 · `cps-component-not-found` | 点名包、组件与引用它的组件;列出包的组件 | +| 读不成 CPS 的文件(JSON、必需的属性、前缀无法推导) | 不适用 | 配置 · 拒绝 · `cps-description-invalid` | 点名文件与原因 | +| 选中的 CPS 组件带模块元数据 | 不适用 | 配置 · 说明 · `cps/modules-not-imported` | 点名包与组件;影响:只使用其库与头文件 | +| 指定的组件是 `executable`、`module`、`jar` 或 `symbolic` | 不适用 | 配置 · 说明 · `cps/component-not-linked` | 点名包、组件与类型;影响:该组件不进入编译与链接 | | 带依赖的静态库包 | 不适用 | 打包时 · 说明 · `pack/closure-not-in-package` | 点名每个依赖;影响:mcpp 以外的消费者须在环境中另有这些依赖的二进制与描述;补救:以共享库交付,或把这些依赖也作为库包发布 | | 写条目时同一系统与架构有两条腿 | 不适用 | `emit xpkg` · 说明 · `emit/two-legs-for-one-system` | 点名两条腿;影响:条目不带面向环境的一面;补救:每种 ABI 发布一个包 | | 用具名的树打包库 | 已有警告(宿主耦合的运行库) | 沿用;打包的汇总行写明 `built with the toolchain at '<树>'` | 影响:这份二进制只对使用同一套工具链的消费者成立 | diff --git a/CHANGELOG.md b/CHANGELOG.md index e2726d7bc..576087d75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,6 +91,23 @@ reach standard error through mcpp's one writer. - A standard library module whose record is complete is read without taking its lock; the record is written by a rename and lists the files of the entry. +- Commands that select different members of a workspace build one configuration at once. Each + selection is a plan with its own directory, `plans/<16 hex digits>/` of the configuration's: + its graph, ninja's state, its records and its runs, under the plan's lock; the configuration's + directory is held shared, and alone by what changes it as a whole. A unit both reach is + compiled by the first and placed for the other by the unit cache; an artifact both link is + written under a temporary name of its own and renamed. The holding needs relocatable compiler + outputs and the unit cache; otherwise, under `--cache off`, under `bmi_schedule = "on"`, in a + graph that runs actions and with the new build optimization `plan-locks` off (`[build] plan_locks = "configuration"`, + `MCPP_PLAN_LOCKS`), the configuration is held alone as before. `mcpp why toolchain` states the + holding and its reason. A selection's first build runs each of its edges once, a lookup for a + unit another selection built. `batch-fetch` (`[build] batch_fetch`, `MCPP_BATCH_FETCH`) is + listed as the build optimization it is. `/result.json` holds the record of the + command that wrote it last; each command's own record is in its plan's directory, which + `.last-result.json` names (docs/07 §5.5, docs/50, SPEC-011 §2 items 7 to 10). +- On a POSIX host an archive is written whole under a temporary name and renamed over the + artifact, as a link is; it is no longer updated in place, so a member an earlier archive held + and the sources no longer name does not remain. ### Fixed diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index 99016945c..1d057f44e 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -1149,9 +1149,11 @@ longer updated; the first build that finds it says so once, naming this key. |---|---| | `allow_host_libs` | [20 — Toolchains](20-toolchains.md), [22 — Target Side](22-target-side.md) | | `allow_host_tools` | [25 — Home, Indices and Store](25-home-indices-and-store.md) | +| `batch_fetch` | [26 — Build Optimizations](26-build-optimizations.md) | | `ios_deployment_target` | [20 — Toolchains](20-toolchains.md) | | `lock_wait` | [25 — Home, Indices and Store](25-home-indices-and-store.md), "Waiting for a lock" | | `offline` | [05 — Dependencies](05-dependencies.md), "Offline builds and mcpp fetch" | +| `plan_locks` | [07 — Workspace](07-workspace.md), [26 — Build Optimizations](26-build-optimizations.md) | | `platform-dependencies` | [22 — Target Side](22-target-side.md) | | `std-module`, `std-compat-module` | [22 — Target Side](22-target-side.md) | diff --git a/docs/07-workspace.md b/docs/07-workspace.md index 75055b91e..9db6908b9 100644 --- a/docs/07-workspace.md +++ b/docs/07-workspace.md @@ -685,22 +685,40 @@ member that several members use is compiled once. ### 5.5 Two commands at once, and a configuration's directory over time -A configuration's build directory has one lock, held while the directory is -written and not otherwise. Reading the manifests, resolving, fetching, finding -the toolchain and scanning hold nothing; `mcpp test` releases the lock before -its first test runs, and `mcpp run` before the program starts. So: - -- **One member is tested while another is edited and built.** The two commands - queue only while each compiles and links, and the one that waits says which - command holds the directory (`Waiting for the build directory, held by …`). - A test that runs while a source changes runs the program linked before the - change; the next build compiles the change. +A configuration's build directory is written under two kinds of lock, held +while the directory is written and not otherwise. Reading the manifests, +resolving, fetching, finding the toolchain and scanning hold nothing; `mcpp test` +releases its locks before its first test runs, and `mcpp run` before the program +starts. + +- **Each selection has a plan of its own (2026.12.4.1+).** The members a command + selects name a plan: its graph, its ninja state, its records and its runs + live in `plans/<16 hex digits>/` of the configuration's directory, under the + plan's lock. The directory itself is held shared by every plan and alone by + what changes it as a whole: its creation, its takeover, its renewal for + another compiler build, and `mcpp clean`. +- **Commands that select different members build at once.** A unit both reach + is compiled by the first; the other's compiler executor finds it in the unit + cache and places it, without starting the compiler. An artifact both link is + written under a temporary name and renamed over the artifact. +- **Commands of one selection queue.** The one that waits says which command + holds the plan (`Waiting … for the plan of member 'a', held by …`), and finds + little to do when it proceeds. A test that runs while a source changes runs + the program linked before the change; the next build compiles the change. +- **The holding is a condition, not a promise.** A plan has a directory of its + own when the compiler's outputs are relocatable and the unit cache is on; + otherwise, outside a workspace, under `--cache off`, under + `bmi_schedule = "on"`, in a graph that runs actions (which write their + outputs in place) and when the `plan-locks` entry is off + ([26](26-build-optimizations.md)), the configuration's directory is held + alone, as before 2026.12.4.1. `mcpp why toolchain` states which holding a + build takes and why (`plan locks: selection (…)`). - **Commands of different configurations do not wait for each other.** A - profile, a target or a selection that plans a different configuration is a - different directory. -- **The lock is the configuration's, not the member's.** A configuration has - one `build.ninja` and one ninja state, which two ninja processes cannot write - at once (mcpp#839). + profile or a target that plans a different configuration is a different + directory. +- The first build of a selection runs each of its edges once: a unit another + selection built is a lookup, not a compile. Its later builds are those of + any plan. - `Finished` says how long a command waited for a directory when it waited a second or more (2026.11.13.1+). diff --git a/docs/26-build-optimizations.md b/docs/26-build-optimizations.md index 4629001ad..a91242d67 100644 --- a/docs/26-build-optimizations.md +++ b/docs/26-build-optimizations.md @@ -28,6 +28,8 @@ by default; the others are stated by a parameter. | `scan-pass` | on | — | The scans of a graph run before its compiles, as a pass of their own | | `split-schedule` | off | `[build] bmi_schedule`, `MCPP_BMI_SCHEDULE` | Importers start when a BMI exists, not when its compiler exits | | `private-fragment` | on | `[build] private_fragment` (`unit`, `conservative`, `as-written`), `MCPP_PRIVATE_FRAGMENT` | A private module fragment is built as a unit of its own | +| `batch-fetch` | on | `[build] batch_fetch` (`waves`, `each`), `MCPP_BATCH_FETCH` | The dependencies one step of the resolution knows are fetched by one call of the provider | +| `plan-locks` | on | `[build] plan_locks` (`selection`, `configuration`), `MCPP_PLAN_LOCKS` | Commands that select different members of a workspace build one configuration at once ([07 §5.5](07-workspace.md)) | `MCPP_BUILDOPT=off mcpp build` is the standard build for one invocation: every entry off. An entry with no parameter produces the bytes the standard build produces, so @@ -118,9 +120,13 @@ ladder is the same for every entry: 3. A failure that remains after both is not an entry's. A failure that goes with one is worth a report naming the file, and the manifest keys above keep the statement. -Three tips exist: a source built as two units that failed, a unit that imports a BMI kept -with earlier lines that failed, and a failed link where either is in the graph (which cannot -say which unit). A test program that fails when it runs gives none. +Four tips exist: a source built as two units that failed, a unit that imports a BMI kept +with earlier lines that failed, a failed link where either is in the graph (which cannot +say which unit), and a failed step while another command built a plan of the same +configuration (`MCPP_PLAN_LOCKS=configuration mcpp build`). A test program that fails when +it runs gives none. `batch-fetch` gives none either: a wave the provider does not complete is +followed by each dependency's own fetch, which is what `each` does, so a failure that remains +is not the wave's. ## What the home's cache places (2026.11.21.1+) @@ -163,13 +169,16 @@ run for a minute is named once on a `Running` line, with the package and source [build] private_fragment = "as-written" # "unit" (default) | "conservative" | "as-written" bmi_schedule = "on" # "auto" (default, = off) | "on" | "off" +batch_fetch = "each" # "waves" (default) | "each" +plan_locks = "configuration" # "selection" (default) | "configuration" [profile.dev] bmi_cutoff = "exact" # "ignore-locations" (default) | "exact" ``` Each has an environment name for one invocation (`MCPP_PRIVATE_FRAGMENT`, -`MCPP_BMI_SCHEDULE`, `MCPP_BMI_CUTOFF`), and `MCPP_BUILDOPT=off` covers all of them. +`MCPP_BMI_SCHEDULE`, `MCPP_BMI_CUTOFF`, `MCPP_BATCH_FETCH`, `MCPP_PLAN_LOCKS`), and +`MCPP_BUILDOPT=off` covers all of them. ## Recorded, not implemented diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index 2ef6bff83..db32184b4 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -1148,6 +1148,16 @@ A run ended by SIGINT, SIGTERM or SIGHUP leaves `cancelled` in both files ([exit codes](specs/exit-codes.md) §3.7). A record still `running` whose `pid` no longer exists belongs to a run that was killed. +**Two commands of one configuration** *(2026.12.4.1+)*. Commands that select +different members of a workspace build one configuration at once +([07 §5.5](07-workspace.md)). Each writes `/result.json`, which +therefore holds the record of the command that wrote it last; its `pid` and +`command` say which, and an `ok` one command writes may replace the `running` +of another that has not ended. Each command's own record is also in its plan's +directory, `/plans/<16 hex digits>/result.json`, which no other +command writes; `.last-result.json` names that copy, and the `mcpp.build` +envelope is the command's own record. The fields are the same. + `.last-result.json`: ```json diff --git a/docs/mcpp-skills/mcpp-build/SKILL.md b/docs/mcpp-skills/mcpp-build/SKILL.md index 16525f75a..983adce65 100644 --- a/docs/mcpp-skills/mcpp-build/SKILL.md +++ b/docs/mcpp-skills/mcpp-build/SKILL.md @@ -50,6 +50,7 @@ envelope. ## Waits -The build directory of one configuration is built by one run at a time; a -second run waits for it, as it waits for an install in the home. `--lock-wait` -bounds the wait. +Runs that select the same members of a workspace, or build one package, +take turns on its build directory; a second run waits, as it waits for an +install in the home. Runs that select different members of a workspace build +at once. `--lock-wait` bounds the wait. diff --git a/docs/specs/README.md b/docs/specs/README.md index 55ea09c7b..edcc6354c 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -40,7 +40,7 @@ | [SPEC-008](library-interface.md) | 库的接口:公开模块、发布闭包与两种形态的一致 | 草案 v0.2 | 2026-10-11 | 第一阶段(只警告)mcpp >= 2026.9.28.3;v0.2 mcpp >= 2026.10.11.1 | | [SPEC-009](toolchain-maintenance.md) | 工具链的支持与维护:版本线、默认值、来源、移动与退役 | 草案 v0.7 | 2026-11-21 | 逐条标注;本版只有规范,多数条款未实现;§6.4 mcpp >= 2026.10.8.1 | | [SPEC-010](home-initialization.md) | home 选择、单跳入口、初始化、网络边界、单次运行的 `--home` 与来自目录的 home | 草案 v0.3 | 2026-11-21 | mcpp >= 2026.10.19.1;网络能力逐条标注;§6 mcpp >= 2026.10.26.1、xlings >= 2026.10.26.1 | -| [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁、等待的报告与上限、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.3 | 2026-12-04 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1;§2.1、§2.2 mcpp >= 2026.12.4.1 | +| [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁与计划的锁、等待的报告与上限、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.4 | 2026-12-05 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1;§2 第 7 至 10 条、§2.1、§2.2、§5.1 第 13 条 mcpp >= 2026.12.4.1 | | [SPEC-012](human-output.md) | 面向人的输出:两条流、两种介质、行的种类、颜色、程序的文本 | 评审中 v1.1 | 2026-11-19 | mcpp >= 2026.10.26.1;§5 mcpp >= 2026.11.19.1 | | [SPEC-013](platforms.md) | 平台:`[platform]` 的七组键、版本组与 `hosted`,三种写法与层次,目标图与宿主图的选择,`cfg(platform)`,依赖图的补全,链接、命名与封装,运行器与载体,平台阶段与协议 17 | 评审中 v1.17 | 2026-11-23 | mcpp >= 2026.10.27.1;§10 的执行宿主与 §11 的载体架构 mcpp >= 2026.10.29.1;§7.5 版本组参与解析与 §14 平台系列 mcpp >= 2026.11.7.1;§14 内置平台为确切版本 mcpp >= 2026.11.7.2;v1.7 条款 mcpp >= 2026.11.10.1;§14 索引的平台列 mcpp >= 2026.11.17.1;§14 系列取可用的最新版本与 §15.1 的 `+b` 条目 mcpp >= 2026.11.19.1;v1.17 条款 mcpp >= 2026.11.23.1 | | [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.2 | 2026-11-10 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1 | @@ -48,7 +48,7 @@ | [SPEC-016](targets-and-providers.md) | 目标与提供者:行、提供者、选择规则、平台定义的行、C 环境与执行、报告、机器输出与锁 | 评审中 v1.10 | 2026-11-27 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.9 条款 mcpp >= 2026.11.23.1;v1.10 条款 mcpp >= 2026.11.27.1 | | [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.2 | 2026-11-26 | mcpp >= 2026.11.17.2;§5、§9 的新增自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.1 | +| [SPEC-019](build-optimizations.md) | 构建优化:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | 评审中 v1.3 | 2026-12-05 | 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 | ## 文档约定 diff --git a/docs/specs/build-optimizations.md b/docs/specs/build-optimizations.md index 4b42108c8..be3eb92eb 100644 --- a/docs/specs/build-optimizations.md +++ b/docs/specs/build-optimizations.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-019 | | 标题 | mcpp 在标准构建之外所做的事:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | -| 状态 | 评审中 v1.2 | -| 版本 | 1.2 | -| 最后修改 | 2026-11-26 | -| 对应实现 | mcpp >= 2026.11.17.2;§5 第 4、7、8 条与 §9 自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.1 | +| 状态 | 评审中 v1.3 | +| 版本 | 1.3 | +| 最后修改 | 2026-12-05 | +| 对应实现 | mcpp >= 2026.11.17.2;§5 第 4、7、8 条与 §9 自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.1;§1 的 `batch-fetch` 与 `plan-locks`、§3 的取得与运行两处接缝、§9 的 R4 自 2026.12.4.1 | | 相关设计文档 | `.agents/docs/2026-11-17-ninja-cascade-publish-supplement-design.md` §11、`.agents/docs/2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md` | | 相关 issue | #946 | | 使用文档 | [26 — 构建优化](../zh/26-build-optimizations.md)、[13 — 代码与工程风格](../zh/13-code-and-project-style.md) | @@ -39,6 +39,8 @@ | `scan-pass` | 图 | 严格 | 开 | — | 图的扫描先于编译,作为单独的一遍执行 | | `split-schedule` | 图 | 形态 | 关 | `[build] bmi_schedule`,`MCPP_BMI_SCHEDULE` | BMI 存在时导入者即开始,不等编译器退出(SPEC-011) | | `private-fragment` | 源码 | 源码 | 开 | `[build] private_fragment`(`unit`、`conservative`、`as-written`),`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元(§5) | +| `batch-fetch` | 取得 | 有条件 | 开 | `[build] batch_fetch`(`waves`、`each`),`MCPP_BATCH_FETCH` | 解析的一步已知的依赖由提供者的一次调用取得;这一批没有完成时每个依赖各自取得 | +| `plan-locks` | 运行 | 形态 | 开 | `[build] plan_locks`(`selection`、`configuration`),`MCPP_PLAN_LOCKS` | 选择工作区不同成员的命令同时构建一个配置,单元由其发布保护(SPEC-011 §2 第 7 至 10 条) | ## 2. 级别 @@ -54,13 +56,15 @@ ## 3. 接缝 -通用管线在三处询问 `mcpp.buildopt`,不认识任何条目: +通用管线在五处询问 `mcpp.buildopt`,不认识任何条目: | 接缝 | 位置 | 询问 | |---|---|---| | 源码 | 扫描之后、校验之前 | 一个源文件构建为哪些单元 | | 图 | 计划写成图时 | 模块边取何种形态 | | 边 | 每条编译边的执行器 | 此前的 BMI 或对象是否保留 | +| 取得 | 解析依赖的每一步 | 这一步已知的依赖是否由提供者的一次调用取得 | +| 运行 | 准备的收尾,取得构建目录的锁时 | 构建持有配置的锁,还是共享它并持有计划的锁 | 1. 保留、比较与放回文件的执行器,以及写图的生成器,属于管线;判定属于 `mcpp.buildopt`。 2. 一种编译器的专门知识**必须**是所属部分之下的独立模块(`mcpp.buildopt.keep.gcm`); @@ -165,12 +169,15 @@ int f() { return 1; } → module m; // 实现单元 | R1 | 源文件是私有片段拆出的单元 | 点名原文件 | | R2 | 编译一个单元,它导入了当前以此前的行号保留着的 BMI | 点名模块 | | R3 | 链接,而图中有拆出的片段或保留着的 BMI | 说明无法归属到单元 | - | R4 | 其他任何步骤 | 不给出 | + | R4 | 任何步骤,而计划共享配置的目录且失败时另一个计划持有它的锁(`plan-locks`) | 说明两个命令同时构建 | + | R5 | 其他任何步骤 | 不给出 | -3. 失败的步骤取自 ninja 的 `FAILED:` 行与步骤记录;取不到时按 R4。测试程序的运行失败不给出提示。 +3. 失败的步骤取自 ninja 的 `FAILED:` 行与步骤记录;取不到时按 R5。测试程序的运行失败不给出提示。 + `batch-fetch` 没有提示:提供者没有完成的一批之后每个依赖各自取得,即取值 `each` 的做法,仍然存在的 + 失败不属于这一批。 4. 文本由登记表行的清单键、环境变量与 `check` 组成:`MCPP_PRIVATE_FRAGMENT=as-written mcpp build` - (GCC 上为 `conservative`)、`MCPP_BMI_CUTOFF=exact mcpp build`;并写出 `MCPP_BUILDOPT=off` - 是下一级。两步之后失败依旧,原因不在这些条目之中。 + (GCC 上为 `conservative`)、`MCPP_BMI_CUTOFF=exact mcpp build`、`MCPP_PLAN_LOCKS=configuration mcpp build`; + 并写出 `MCPP_BUILDOPT=off` 是下一级。两步之后失败依旧,原因不在这些条目之中。 5. 构建图与此前的取值不同时,第一次构建**必须**按新的取值重新生成图:`MCPP_BUILDOPT`、 `MCPP_PRIVATE_FRAGMENT`、`MCPP_BMI_SCHEDULE` 的陈述是图自身所记的请求(`build.ninja` 首行的 `request=`)的一部分,快速路径在重放之前比较它。这一陈述**禁止**只记在构建的记录里:记录由成功的 @@ -185,3 +192,4 @@ int f() { return 1; } → module m; // 实现单元 | 1.0 | 2026-11-17 | 首版(mcpp 2026.11.17.2):登记表、级别、接缝、总开关;私有模块片段作为独立单元;构建后的建议;语义提供者的边界;四项已记录、未实现 | | 1.1 | 2026-11-26 | 私有片段的判定:条件指令与 `#error`、`#warning` 放行,条件须在声明与片段处闭合;词法修正(数字分隔符、原始字符串、`extern "C"`、行连接);取值 `conservative`;登记表的 `check`;新增 §9 失败时的提示;§8 记录 clang 读者的实测结论 | | 1.2 | 2026-11-26 | §9 第 5 条:决定图的形态的陈述记在图自身的请求里,不记在构建的记录里;核对失败之后的构建与核对之前相同(mcpp 2026.11.27.1) | +| 1.3 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7.1、§3.11.2):条目 `batch-fetch` 与 `plan-locks`;接缝增加取得与运行;§9 增加 R4,`batch-fetch` 没有提示的理由 | diff --git a/docs/specs/concurrency.md b/docs/specs/concurrency.md index 8a2233d21..448b52214 100644 --- a/docs/specs/concurrency.md +++ b/docs/specs/concurrency.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-011 | | 标题 | 同一工程上的并发运行:构建目录锁、原子发布、乐观写入与取消 | -| 状态 | 评审中 v1.3 | -| 版本 | 1.3 | -| 最后修改 | 2026-12-04 | -| 对应实现 | 基础保证: mcpp >= 2026.10.26.1; §5.1: mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条: mcpp >= 2026.11.19.1;§2 第 3 条的报告、§2.1、§2.2 与 §6 的标准库模块: mcpp >= 2026.12.4.1 | +| 状态 | 评审中 v1.4 | +| 版本 | 1.4 | +| 最后修改 | 2026-12-05 | +| 对应实现 | 基础保证: mcpp >= 2026.10.26.1; §5.1: mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条: mcpp >= 2026.11.19.1;§2 第 3 条的报告、第 7 至 10 条、§2.1、§2.2、§3 的归档、§5.1 第 13 条与 §6 的标准库模块: mcpp >= 2026.12.4.1 | | 相关设计文档 | `.agents/docs/2026-10-26-control-contract-runtime-and-ide-ecosystem-design.md` §3、§4、§5.4 | | 相关 issue | #839 | | 使用文档 | [50 — 机器可读输出](../zh/50-machine-output.md) §9、§11 | @@ -29,7 +29,7 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 段 | 内容 | 写入 | 锁 | |---|---|---|---| | 规划 | 读清单、解析依赖与工具链(可联网)、目标侧、扫描,直到配置指纹确定 | 不写构建目录 | 无 | -| 修改 | 准备的收尾(动作、`resolution.json`、`build.ninja`、配置级编译数据库)、ninja、产物校验、配置记录与结果记录 | 构建目录 | 构建目录锁 | +| 修改 | 准备的收尾(动作、`resolution.json`、`build.ninja`、配置级编译数据库)、ninja、产物校验、配置记录与结果记录 | 构建目录 | 构建目录锁;计划有自己的目录时为构建目录的共享锁与计划的锁(§2 第 7 条) | | 执行 | `mcpp run` 启动程序;`mcpp test` 之后的程序运行由测试命令持锁(§2.3) | 无 | `run`:无 | 配置目录 `target///` 由指纹决定,指纹在规划末尾才确定。规划段 @@ -45,10 +45,28 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 前者未做完的事。 4. 不同配置的构建使用不同的目录与不同的锁,**禁止**相互等待。 5. 锁描述符**必须**带 close-on-exec;`mcpp run` **必须**在 exec 程序之前释放锁,程序 - 运行期间同配置的构建不被阻塞。`mcpp test` 持锁直到测试结束,因为它在同一构建目录中 - 运行刚链接的测试程序。 + 运行期间同配置的构建不被阻塞。`mcpp test` 在全部构建完成之后、第一个测试运行之前释放锁 + (mcpp#915 起);测试运行期间被重新链接的程序由 §3 的原子发布保护。 6. 进程崩溃或被 SIGKILL 时由操作系统释放锁,不存在僵死锁。Windows 使用 `LockFileEx`, 语义相同(实测见设计 E24)。 +7. **计划。** 一个命令选择的成员确定一个计划,其目录为 + `/plans/<配置组成员集合(排序后的路径)的 64 位 FNV-1a,16 位十六进制>/`;计划的锁为其中的 `.mcpp-plan.lock`,以不同顺序选择同一组成员的命令共用一个计划。 + 计划有自己的目录,当且仅当:这是工作区的构建(构建程序的工作区除外),工具链的输出可重定向(§5.1 第 8 条),单元缓存 + 开启(`--cache` 不为 `off`),`bmi_schedule` 不为 `on`,图中没有动作(动作原地写出其输出),且构建优化条目 `plan-locks` 开启 + ([SPEC-019](build-optimizations.md))。条件成立时,构建**必须**以共享方式持有构建目录锁、以排他 + 方式持有计划的锁,第 2 至 5 条对二者同样适用;否则以排他方式持有构建目录锁。快速路径**必须**取得 + 记录它的那次构建所取得的锁。`mcpp why toolchain` 写出采用哪一种及其原因。 +8. 计划的目录收纳只属于该计划的状态:构建图、ninja 的日志与依赖(`builddir`)、编译上限的信号量、 + 运行的各代与尝试、步骤记录、放置清单、构建优化记录、运行时校验记录、`uses.list`,以及 + `resolution.json` 与 `result.json` 的计划副本。目标文件、BMI、产物、模块映射与配置记录留在构建 + 目录。配置一级的 `resolution.json` 与 `result.json` 是最后写它的计划的([50](../50-machine-output.md))。 +9. 整体改变构建目录的操作——创建、接替前代目录、为另一编译器构建或另一个 mcpp 而更新、`mcpp clean`、 + `--cache off` 的冷构建——**必须**以排他方式持有构建目录锁。早于 2026.12.4.1 的 mcpp 以排他方式持有, + 与共享持有者互斥,因此新旧版本在同一目录上退回串行。 +10. 两个计划都到达的单元由编译执行器在编译与发布期间以单元的锁(`<输出>.mcpp-unit.lock`)保护; + 后到者取得锁后在单元缓存中找到该单元并放置,不启动编译器。两个计划都链接的产物按 §3 写临时名后 + 改名;ninja 的响应文件以计划命名(`<输出>.<计划>.rsp`),因为 ninja 在一条边结束时删除它;单元缓存 + 以响应文件的内容而非名字作为键。 ### 2.1 等待 已实现 @@ -79,7 +97,7 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 资源 | 规则 | |---|---| -| 链接产物(可执行文件、共享库、测试程序) | POSIX 非 PE 目标:链接写 `.tmp`,再 `mv -f` 改名。Windows 宿主:`mcpp link-output` 先把旧产物改名为 `.old-`,再原地链接;运行中的程序保留旧文件,以后的链接清理不再被占用的 `.old-*`。POSIX 宿主上的 PE 目标:原地链接 | +| 链接产物(可执行文件、共享库、测试程序)与归档 | POSIX 宿主上的非 PE、非 WebAssembly 目标:`mcpp link-output` 让链接写同一目录中本进程自己的临时名 `.<主名>.<扩展名>`,再改名到产物上;归档同样整个写出后改名(2026.12.4.1+),不在原处更新。Windows 宿主:`mcpp link-output` 先把旧产物改名为 `.old-`,再原地链接;运行中的程序保留旧文件,以后的链接清理不再被占用的 `.old-*`。PE 与 WebAssembly 目标:原地链接 | | `result.json`、`target/.last-result.json`、`resolution.json`、配置级与根目录的 `compile_commands.json` | 写临时文件后改名替换 | | `target/.build_cache`(配置记录) | 读改写在 `target/.build_cache.lock` 下进行,写临时文件后改名替换;格式不变 | | `mcpp.lock` | 写临时文件后改名替换;乐观并发(§4) | @@ -172,6 +190,8 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 12. 工具链方言说明其程序的文本不是 UTF-8 时(`textEncoding = "console"`:cl.exe、link.exe、lib.exe、rc.exe), 运行该程序的执行器(`__compiler-cap`、`link-output`)**必须**以一个管道读取它的两个输出流,逐行解码为 UTF-8 后写到自己的标准输出;归档边因此也经 `link-output` 运行。解码**禁止**改变内容与顺序(SPEC-012 §5)。 +13. 计划有自己的目录时(§2 第 7 条),运行的各代、闸锁与尝试目录(`<计划目录>/.mcpp-attempts/`)属于该计划, + 恢复只清理该计划的尝试。恢复**禁止**收回其单元锁正被持有的完成证书:那是另一个计划正在编译的单元。 ## 6. 全局一侧 @@ -191,3 +211,4 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 1.1 | 2026-11-06 | 分离编译的单元观察、共享名额、绝对输出事务与有限恢复边界;对齐取消请求的 OS 接收方式。 | | 1.2 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#952,设计 2026-11-19 §10):§5.1 第 6 条不可观察单元的恢复与报告、拒绝写出个数与出路;第 8 条输出可重定向的工具链上编译写入尝试私有的路径并由执行器发布;第 9 条清理退役运行状态;第 10 条准入的条件、执行器的结束原因与不能声明单元的环境;第 11 条编译器的记录由执行器写为依赖文件,第 12 条程序的文本在执行器中解码为 UTF-8(mcpp#970,设计 2026-11-19 §20)。 | | 1.3 | 2026-12-04 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7):§2.1 每一次等待经同一原语、按时刻报告、持有者记录为提示、四层上限与 `[lock-wait-exceeded]`、提供者的锁受同一上限;§2.2 不能加锁时立即以 `[lock-unavailable]` 拒绝;§6 完整的标准库模块条目不加锁读取。 | +| 1.4 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7.1):§2 第 5 条改正为 `mcpp test` 在测试运行之前释放锁;第 7 至 10 条计划的锁、计划的目录、整体操作的排他持有与两个计划共有的单元;§3 链接的临时名与归档的原子发布;§5.1 第 13 条运行与恢复属于计划。 | diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index 78e564d76..fc5ef9391 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -1027,9 +1027,11 @@ compile_commands = "compile_commands.json" # 相对工程根目录的路径 |---|---| | `allow_host_libs` | [20 —— 工具链](20-toolchains.md)、[22 —— 目标侧](22-target-side.md) | | `allow_host_tools` | [25 —— home、索引与 store](25-home-indices-and-store.md) | +| `batch_fetch` | [26 —— 构建优化](26-build-optimizations.md) | | `ios_deployment_target` | [20 —— 工具链](20-toolchains.md) | | `lock_wait` | [25 —— home、索引与 store](25-home-indices-and-store.md),「等待锁」 | | `offline` | [05 —— 依赖](05-dependencies.md),「离线构建与 mcpp fetch」 | +| `plan_locks` | [07 —— 工作空间](07-workspace.md)、[26 —— 构建优化](26-build-optimizations.md) | | `platform-dependencies` | [22 —— 目标侧](22-target-side.md) | | `std-module`、`std-compat-module` | [22 —— 目标侧](22-target-side.md) | diff --git a/docs/zh/07-workspace.md b/docs/zh/07-workspace.md index 47f0f489e..1148bc120 100644 --- a/docs/zh/07-workspace.md +++ b/docs/zh/07-workspace.md @@ -579,13 +579,21 @@ mcpp test --workspace --workspace-timeout 1800 # whole fan-out (default 0 = no ### 5.5 同时的两个命令,与一个配置的目录随时间的变化 -一个配置的构建目录有一把锁,只在写目录时持有。读取清单、解析、下载、确定工具链与扫描都不持锁;`mcpp test` 在第一个测试 -运行之前释放锁,`mcpp run` 在程序启动之前释放。因此: - -- **测试一个成员的同时可以修改并构建另一个成员。** 两个命令只在各自编译与链接时排队,等待的一方说明持有目录的命令 - (`Waiting for the build directory, held by …`)。源码改动时正在运行的测试运行的是改动前链接的程序;下一次构建编译该改动。 -- **不同配置的命令互不等待。** 规划出不同配置的 profile、目标或选择是不同的目录。 -- **锁属于配置,不属于成员。** 一个配置只有一份 `build.ninja` 与一份 ninja 状态,两个 ninja 进程不能同时写它们(mcpp#839)。 +一个配置的构建目录在两种锁之下写入,只在写目录时持有。读取清单、解析、下载、确定工具链与扫描都不持锁;`mcpp test` 在第一个 +测试运行之前释放它的锁,`mcpp run` 在程序启动之前释放。 + +- **每个选择有自己的计划(2026.12.4.1+)。** 一个命令选择的成员确定一个计划:它的构建图、ninja 状态、记录与运行位于配置目录的 + `plans/<16 位十六进制>/`,在计划的锁之下。目录本身由每个计划以共享方式持有,由整体改变它的操作以排他方式持有:创建、接替、 + 为另一个编译器构建而更新,以及 `mcpp clean`。 +- **选择不同成员的命令同时构建。** 二者都到达的单元由先到者编译;另一方的编译执行器在单元缓存中找到它并放置,不启动编译器。 + 二者都链接的产物写入临时名后改名到产物上。 +- **同一选择的命令排队。** 等待的一方说明持有计划的命令(`Waiting … for the plan of member 'a', held by …`),继续时 + 几乎无事可做。源码改动时正在运行的测试运行的是改动前链接的程序;下一次构建编译该改动。 +- **这种持有方式是条件,不是承诺。** 编译器的输出可重定向且单元缓存开启时,计划才有自己的目录;否则——工作区之外、 + `--cache off`、`bmi_schedule = "on"`、图中有动作(动作原地写出输出)、以及 `plan-locks` 条目关闭时([26](26-build-optimizations.md))——配置的目录以排他 + 方式持有,与 2026.12.4.1 之前相同。`mcpp why toolchain` 说明一次构建采用哪一种及其原因(`plan locks: selection (…)`)。 +- **不同配置的命令互不等待。** 规划出不同配置的 profile 或目标是不同的目录。 +- 一个选择的第一次构建把它的每条边各运行一次:别的选择已构建的单元是一次查找,不是一次编译。此后它的构建与任何计划相同。 - 等待目录一秒以上时,`Finished` 说明等待的时长(2026.11.13.1+)。 一个配置的目录以其**谱系**命名(2026.11.13.1+):编译器家族、目标、标准库家族、C++ 标准、配置的选项与所陈述的基座(默认基座 diff --git a/docs/zh/26-build-optimizations.md b/docs/zh/26-build-optimizations.md index 9e15c2b0c..fc1b8d536 100644 --- a/docs/zh/26-build-optimizations.md +++ b/docs/zh/26-build-optimizations.md @@ -24,6 +24,8 @@ profile 的各个键,见 [04 —— mcpp.toml](04-mcpp-toml.md);精确规则,见 | `scan-pass` | 开 | — | 图的扫描先于编译,作为单独的一遍执行 | | `split-schedule` | 关 | `[build] bmi_schedule`,`MCPP_BMI_SCHEDULE` | BMI 存在时导入者即开始,不等编译器退出 | | `private-fragment` | 开 | `[build] private_fragment`(`unit`、`conservative`、`as-written`),`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元 | +| `batch-fetch` | 开 | `[build] batch_fetch`(`waves`、`each`),`MCPP_BATCH_FETCH` | 解析的一步已知的依赖由提供者的一次调用取得 | +| `plan-locks` | 开 | `[build] plan_locks`(`selection`、`configuration`),`MCPP_PLAN_LOCKS` | 选择工作区不同成员的命令同时构建同一个配置([07 §5.5](07-workspace.md)) | `MCPP_BUILDOPT=off mcpp build` 对一次调用给出标准构建:全部条目关闭。没有参数的条目产出的字节与 标准构建相同,因此没有可选之处,只由这一条语句关闭。 @@ -103,8 +105,10 @@ tip: src/c.cppm was built as two units (private-fragment), and one of them faile 3. 两步之后失败依旧,原因不在条目之中。失败随其中一步消失时,请连同文件名报告;上文的清单键 使该取值持久。 -提示有三种:拆为两个单元的源文件失败;导入了以较早行号保留的 BMI 的单元失败;链接失败而图中有 -其中之一(链接说不出是哪个单元)。测试程序运行时的失败不给出提示。 +提示有四种:拆为两个单元的源文件失败;导入了以较早行号保留的 BMI 的单元失败;链接失败而图中有 +其中之一(链接说不出是哪个单元);另一个命令同时构建同一配置的计划时一步失败 +(`MCPP_PLAN_LOCKS=configuration mcpp build`)。测试程序运行时的失败不给出提示。`batch-fetch` 也不给出: +提供者没有完成的一批之后,每个依赖各自取得,即 `each` 的做法,所以仍然存在的失败不属于这一批。 ## home 的缓存放置的内容(2026.11.21.1+) @@ -136,13 +140,15 @@ tip: src/c.cppm was built as two units (private-fragment), and one of them faile [build] private_fragment = "as-written" # "unit"(默认)| "conservative" | "as-written" bmi_schedule = "on" # "auto"(默认,即 off)| "on" | "off" +batch_fetch = "each" # "waves"(默认)| "each" +plan_locks = "configuration" # "selection"(默认)| "configuration" [profile.dev] bmi_cutoff = "exact" # "ignore-locations"(默认)| "exact" ``` 每一项有对一次调用生效的环境变量(`MCPP_PRIVATE_FRAGMENT`、`MCPP_BMI_SCHEDULE`、 -`MCPP_BMI_CUTOFF`),`MCPP_BUILDOPT=off` 覆盖全部。 +`MCPP_BMI_CUTOFF`、`MCPP_BATCH_FETCH`、`MCPP_PLAN_LOCKS`),`MCPP_BUILDOPT=off` 覆盖全部。 ## 已记录、未实现 diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 23c92137c..3caaef6b8 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -1017,6 +1017,12 @@ CI 按 `launch` 启动程序,与 `mcpp run` 的启动一致。 ([退出码](../specs/exit-codes.md) §3.7)。`status` 仍为 `running`、而 `pid` 已不存在 的记录属于一次被强制结束的运行。 +**同一配置的两个命令** *(2026.12.4.1+)*。选择工作区不同成员的命令同时构建一个配置([07 §5.5](07-workspace.md))。 +每个命令都写 `/result.json`,所以它保存的是最后写它的那个命令的记录;其中的 `pid` 与 `command` 说明是哪一个, +一个命令写下的 `ok` 可以替换另一个尚未结束的命令的 `running`。每个命令自己的记录另在它的计划目录 +`/plans/<16 位十六进制>/result.json` 中,别的命令不写它;`.last-result.json` 指向这一份,`mcpp.build` 信封 +是该命令自己的记录。字段相同。 + `.last-result.json`: ```json diff --git a/modules/buildopt/README.md b/modules/buildopt/README.md index 7b54121cd..ad72bb7c0 100644 --- a/modules/buildopt/README.md +++ b/modules/buildopt/README.md @@ -4,8 +4,8 @@ What mcpp does to a build beyond what the compiler and ninja do, in one package. A build with none of it is the standard build: one edge per unit, every output the compiler writes stands, and whatever follows an output is run. Each addition to that is -an entry of one register (`src/registry.cppm`). The pipeline asks at three seams — -source, graph, edge — and knows no entry. The specification is +an entry of one register (`src/registry.cppm`). The pipeline asks at five seams — +source, graph, edge, fetch, run — and knows no entry. The specification is [SPEC-019](../../docs/specs/build-optimizations.md); the user's chapter is [docs/26](../../docs/26-build-optimizations.md). @@ -23,6 +23,8 @@ by a parameter. | `scan-pass` | graph | exact | on | — | The scans of a graph run as a pass of their own before its compiles | | `split-schedule` | graph | shape | off | `[build] bmi_schedule = "auto" \| "on" \| "off"`, `MCPP_BMI_SCHEDULE` | Importers start when a BMI exists, not when its compiler exits (two-phase with clang, detached code generation with gcc) | | `private-fragment` | source | source | on | `[build] private_fragment = "unit" \| "conservative" \| "as-written"`, `MCPP_PRIVATE_FRAGMENT` | A private module fragment is built as a unit of its own, so an edit of it reaches no importer | +| `batch-fetch` | fetch | conditional | on | `[build] batch_fetch = "waves" \| "each"`, `MCPP_BATCH_FETCH` | The dependencies one step of the resolution knows are fetched by one call of the provider | +| `plan-locks` | run | shape | on | `[build] plan_locks = "selection" \| "configuration"`, `MCPP_PLAN_LOCKS` | Commands that select different members of a workspace build one configuration at once; a unit is protected by its publication | `MCPP_BUILDOPT=off` turns every entry off for one invocation: the standard build. An entry with no parameter has nothing to choose — its products are the bytes the standard build gives — and is turned off only by that statement. diff --git a/modules/buildopt/src/advice.cppm b/modules/buildopt/src/advice.cppm index baf792c4a..8c4527575 100644 --- a/modules/buildopt/src/advice.cppm +++ b/modules/buildopt/src/advice.cppm @@ -79,6 +79,9 @@ struct Applied { std::vector fragments; std::vector importers; std::string fragmentCheck; // the `private_fragment` value that checks, for this compiler + // The plan had a directory of its own and shared the configuration's + // (plan-locks, design 2026-11-27 §3.7.1). + bool sharedPlan = false; }; inline constexpr std::string_view kAppliedFile = "buildopt-applied.tsv"; // Written when it differs from what is there. @@ -90,6 +93,9 @@ Applied read_applied(const std::filesystem::path& dir); struct Failed { std::vector sources; bool linked = false; + // Another plan of the configuration held its lock when the step failed: + // two plans were building at once. + bool concurrentPlans = false; }; // The outputs each `FAILED:` line of ninja's output names. std::vector> failed_outputs(std::string_view ninjaOutput); @@ -197,6 +203,7 @@ bool first_time(const std::filesystem::path& dir, std::string_view module) { void write_applied(const std::filesystem::path& dir, const Applied& applied) { std::string text; + if (applied.sharedPlan) text += "plan\tshared\n"; if (!applied.fragments.empty()) text += std::format("check\t{}\n", applied.fragmentCheck); for (auto const& f : applied.fragments) { text += std::format("fragment\t{}", f.written); @@ -231,6 +238,7 @@ Applied read_applied(const std::filesystem::path& dir) { } if (cells.size() < 2) continue; if (cells[0] == "check") a.fragmentCheck = cells[1]; + else if (cells[0] == "plan") a.sharedPlan = cells[1] == "shared"; else if (cells[0] == "fragment") a.fragments.push_back({cells[1], {cells.begin() + 2, cells.end()}}); else if (cells[0] == "imports") a.importers.push_back({cells[1], {cells.begin() + 2, cells.end()}}); } @@ -312,6 +320,17 @@ std::vector suspects(const Applied& applied, const std::vector list, how_to_check(*cutoff, cutoff->check), off)}); } + // R4: two plans of the configuration were building at once, and the step + // failed: a unit both reach is the first suspect of plan-locks. + if (tips.empty() && applied.sharedPlan && failed.concurrentPlans) + if (const auto* plans = registry::find(registry::kPlanLocks)) + tips.push_back({"buildopt/plan-locks", std::format( + "another command was building a plan of this configuration at the same time (plan-locks), " + "and a step failed.\n" + " To check whether that is the cause: {}\n" + " If it builds, report the step; {}=off turns every optimization off for one run.", + how_to_check(*plans, plans->check), off)}); + // R3: a link failed, and the graph holds something either entry acted on. if (tips.empty() && failed.linked) { if (!applied.fragments.empty() && fragment) diff --git a/modules/unit-cache/src/unit_cache.cppm b/modules/unit-cache/src/unit_cache.cppm index 2cb44b4f5..ad5bb3e9f 100644 --- a/modules/unit-cache/src/unit_cache.cppm +++ b/modules/unit-cache/src/unit_cache.cppm @@ -467,8 +467,11 @@ std::string Cache::refusal(const Unit& u) const { std::string Cache::first_key(const Unit& u, const Shape& s) { std::string text = "unit-cache-v1\n"; text += "cwd=" + u.cwd.lexically_normal().generic_string() + "\n"; + // A response file is keyed by what it holds (below), not by its name: a + // plan with a directory of its own names its response files after itself + // (design 2026-11-27 §3.7.1), and one unit is still one unit. for (const auto& w : u.argv) { - text += w; + text += w.starts_with("@") && w.size() > 1 ? std::string_view("@") : std::string_view(w); text += '\0'; } text += "\nsource=" + digest(s.source.is_absolute() ? s.source : u.cwd / s.source) + "\n"; diff --git a/src/build/command_line.cppm b/src/build/command_line.cppm index fa3297aa4..c696bdd36 100644 --- a/src/build/command_line.cppm +++ b/src/build/command_line.cppm @@ -20,6 +20,11 @@ export namespace mcpp::build::command_line { // Platform-aware shell argument quoting. std::string quote(std::string_view s); +// The length of a command line this host starts a program with, leaving room +// for the environment: what one batch of an archiver's members may take when +// the archiver reads no response file (src/native//command_line.cpp). +std::size_t host_line_limit(); + // The two halves of `quote`, callable regardless of host. Exposed so the // Windows command-line shape can be built and unit-tested from any platform // — the cmd.exe quoting rules are the easiest thing in mcpp to get wrong and diff --git a/src/build/dirlock.cppm b/src/build/dirlock.cppm index 45d6101f4..8f9dcd0a9 100644 --- a/src/build/dirlock.cppm +++ b/src/build/dirlock.cppm @@ -50,6 +50,31 @@ long process_id(); // copied, and the last copy to go releases it; `release` drops it early. // Refused -- the wait limit passed, or the directory cannot be locked -- with // the failure, whose sentence names the lock and the remedy. +// The configuration directory's lock: exclusive, or shared (`shared`) by the +// commands whose plans each hold a lock of their own (design 2026-11-27 +// §3.7.1). An exclusive holder -- the directory created, taken over, renewed, +// cleaned, or a build whose units cannot protect themselves -- excludes every +// other; an earlier mcpp, which holds it exclusively, does too. +std::expected, mcpp::home::LockFailure> +acquire(const std::filesystem::path& outputDir, bool shared); + +// A selection's plan, beside the configuration's directory's other plans: +// `plans/<16 hex digits of its group>`. The group -- the members the plan +// builds, joined by U+001E -- is taken as a set, so two selections that name +// the same members in another order share one plan, its graph and its ninja +// state, as they shared the configuration's before. +std::filesystem::path plan_state_dir(std::string_view group); + +// The plan a wait names: "the plan of members 'a', 'b'" for a workspace's +// group, "the plan of this package" else. +std::string plan_named(std::string_view group); + +// The lock of the plan in `outputDir / stateDir`, exclusive: two commands of +// one selection queue there, as they queued on the directory before. `what` +// names the plan in a wait's report ("the plan of member 'a'"). +std::expected, mcpp::home::LockFailure> +acquire_plan(const std::filesystem::path& outputDir, const std::filesystem::path& stateDir, std::string_view what); + std::expected, mcpp::home::LockFailure> acquire(const std::filesystem::path& outputDir); @@ -88,17 +113,67 @@ std::map>& held() { std::expected, mcpp::home::LockFailure> acquire(const std::filesystem::path& outputDir) { + return acquire(outputDir, false); +} + +std::expected, mcpp::home::LockFailure> +acquire(const std::filesystem::path& outputDir, bool shared) { + // A process that holds the directory exclusively holds it for a shared + // use too; a shared hold is not an exclusive one. const auto key = outputDir.lexically_normal().generic_string(); std::lock_guard heldLock(g_heldMutex); if (auto existing = held()[key].lock()) return existing; + if (shared) + if (auto existing = held()[key + "\x1fshared"].lock()) return existing; auto lock = mcpp::home::FileLock::acquire( outputDir, kLockName, {.resource = std::format("the build directory {}", outputDir.filename().string()), - .doing = "building"}); + .doing = shared ? "building a selection" : "building", + .shared = shared}); + if (!lock) return std::unexpected(lock.error()); + auto held_ = std::make_shared(std::move(*lock)); + held()[shared ? key + "\x1fshared" : key] = held_; + return held_; +} + +std::filesystem::path plan_state_dir(std::string_view group) { + std::vector members; + for (auto part : std::views::split(group, '\x1e')) members.emplace_back(part.begin(), part.end()); + std::ranges::sort(members); + // FNV-1a, 64 bits: a name, not a secret. + std::uint64_t h = 1469598103934665603ull; + for (auto m : members) { + for (unsigned char c : m) { h ^= c; h *= 1099511628211ull; } + h ^= 0x1e; h *= 1099511628211ull; + } + return std::filesystem::path("plans") / std::format("{:016x}", h); +} + +std::string plan_named(std::string_view group) { + if (group.empty()) return "the plan of this package"; + std::string names; + std::size_t count = 0; + for (auto part : std::views::split(group, '\x1e')) { + names += std::format("{}'{}'", names.empty() ? "" : ", ", std::string_view(part.begin(), part.end())); + ++count; + } + return std::format("the plan of {} {}", count == 1 ? "member" : "members", names); +} + +std::expected, mcpp::home::LockFailure> +acquire_plan(const std::filesystem::path& outputDir, const std::filesystem::path& stateDir, std::string_view what) { + const auto dir = outputDir / stateDir; + const auto key = dir.lexically_normal().generic_string(); + std::lock_guard heldLock(g_heldMutex); + if (auto existing = held()[key].lock()) return existing; + std::error_code ec; + std::filesystem::create_directories(dir, ec); + auto lock = mcpp::home::FileLock::acquire(dir, ".mcpp-plan.lock", + {.resource = std::string(what), .doing = "building"}); if (!lock) return std::unexpected(lock.error()); - auto shared = std::make_shared(std::move(*lock)); - held()[key] = shared; - return shared; + auto held_ = std::make_shared(std::move(*lock)); + held()[key] = held_; + return held_; } } // namespace mcpp::build::dirlock diff --git a/src/build/execute.cppm b/src/build/execute.cppm index 41a62fa43..f53fbb685 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -613,6 +613,11 @@ export struct BuildCacheEntry { // fast path matches every entry of its selection. std::string selection; std::string group; + // The directory of the entry's own plan, relative to `outputDir` + // (`plans/`, design 2026-11-27 §3.7.1); empty when the build + // held the configuration's directory alone. A fast path replays the graph + // there, holding the directory shared and the plan alone, as the build did. + std::string planState; // The engine that wrote the graph this entry records, absent for an entry // written before the field (see EngineIdentity). Optional rather than an // empty identity, because an engine whose version is the empty string does @@ -858,6 +863,10 @@ export std::vector read_build_cache(const std::filesystem::path e.group = line.substr(6); haveNextLine = static_cast(std::getline(f, line)); } + if (haveNextLine && line.starts_with("plan=")) { + e.planState = line.substr(5); + haveNextLine = static_cast(std::getline(f, line)); + } if (haveNextLine && line.starts_with("compileDb=")) { e.rootCompileDb = line.substr(10); e.rootCompileDbRecorded = true; @@ -946,7 +955,8 @@ void write_build_cache(const std::filesystem::path& projectRoot, const std::string& selection = {}, const std::string& group = {}, const std::string& rootCompileDb = {}, - std::vector runPathDirs = {}) { + std::vector runPathDirs = {}, + const std::filesystem::path& planState = {}) { // The configuration groups of one workspace command build at the same // time (workspace design 2026-09-29 §6) and record into one file; the // read, the edit and the write are one step -- within this process under @@ -996,6 +1006,7 @@ void write_build_cache(const std::filesystem::path& projectRoot, newEntry.xlingsPayloadsRecorded = true; newEntry.selection = selection; newEntry.group = group; + newEntry.planState = planState.generic_string(); newEntry.rootCompileDb = rootCompileDb; newEntry.rootCompileDbRecorded = true; newEntry.runPathDirs = std::move(runPathDirs); @@ -1085,6 +1096,7 @@ void write_build_cache_entries(const std::filesystem::path& path, f << "selection=" << e.selection << '\n'; f << "group=" << e.group << '\n'; } + if (!e.planState.empty()) f << "plan=" << e.planState << '\n'; if (e.rootCompileDbRecorded) f << "compileDb=" << e.rootCompileDb << '\n'; if (!e.lockDigest.empty()) f << "lock=" << e.lockDigest << '\n'; if (e.engine) @@ -2103,6 +2115,7 @@ std::vector result_artifacts(const BuildContext& mcpp::build::result::Record start_record(const BuildContext& ctx) { auto r = mcpp::build::result::begin(ctx.projectRoot, ctx.outputDir); + if (!ctx.planStateDir.empty()) r.planDir = ctx.plan.state_dir(); r.command = mcpp::build::dirlock::command(); r.pid = mcpp::build::dirlock::process_id(); r.triple = ctx.tc.targetTriple; @@ -2154,12 +2167,16 @@ struct FastRecord { mcpp::build::result::Record record; std::vector artifacts; }; +// `stateDir`: the plan's directory, `outputDir` for a plan without one; the +// previous record read is the plan's, which another plan's build leaves alone. FastRecord fast_path_begin(const std::filesystem::path& projectRoot, - const std::filesystem::path& outputDir) { + const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir) { namespace res = mcpp::build::result; FastRecord f; - auto previous = res::read(outputDir); + auto previous = res::read(stateDir); f.record = res::begin(projectRoot, outputDir); + if (stateDir != outputDir) f.record.planDir = stateDir; f.record.command = mcpp::build::dirlock::command(); f.record.pid = mcpp::build::dirlock::process_id(); if (previous) { @@ -2230,7 +2247,21 @@ export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache, // `--cache=off` means a cold build: no global cache, and target/ cleared — // which is exactly what `--no-cache` has always done, hence the alias. const bool coldBuild = no_cache || ctx.cacheMode == CacheMode::Off; - if (coldBuild) { + // `--cache off` holds the directory alone (§3.7.1); `--no-cache` beside an + // explicit `--cache` does not, and the plans that share the directory + // keep what they build in it. + if (coldBuild && !ctx.planStateDir.empty()) { + mcpp::diag::degraded("build/cold", + "--no-cache was given with --cache, and this build shares its directory with other plans", + "only this plan's own state is cleared; `--cache off` clears the whole directory"); + std::error_code ec; + for (auto const& e : std::filesystem::directory_iterator(ctx.plan.state_dir(), ec)) { + const auto name = e.path().filename(); + if (name == ".mcpp-plan.lock" || name == ".mcpp-plan.lock.owner" || name == "uses.list") continue; + std::error_code rec; + std::filesystem::remove_all(e.path(), rec); + } + } else if (coldBuild) { // Everything but the directory's records and its lock: the records // (written by the plan, for this configuration) are what the next build // reads to tell that the compiler or the base changed, and without them @@ -2432,7 +2463,8 @@ export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache, for (auto const& d : child_path_dirs(ctx, Child::Run)) v.push_back(d.generic_string()); return v; - }()); + }(), + ctx.planStateDir); } // The one place the --strict policy is settled. Degradations reported by @@ -2452,7 +2484,7 @@ export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache, // manifest, which `compute_flags` reads. It once read the declared level // while the compile used another, and said `[optimized]` over `-Og`. The // step record's header carries the same value for the fast path. - mcpp::build::progress::note_sources(ctx.plan.outputDir); + mcpp::build::progress::note_sources(ctx.plan.state_dir()); mcpp::build::progress::finished( ctx.profile, mcpp::build::profile_descriptor(ctx.plan.manifest.buildConfig)); report_freestanding_size(ctx); @@ -2667,9 +2699,12 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, const std::string& runtimeEnvKey, const std::string& runtimeEnvValue, std::chrono::milliseconds* elapsedOut = nullptr) { + // THE PLAN'S DIRECTORY: the graph's (design 2026-11-27 §3.7.1), which is the + // output directory itself when the plan has none of its own. + const auto stateDir = ninjaPath.parent_path(); // A build that reuses its graph renews the roots the graph's plan // recorded: their time is the payloads' last use (design 2026-11-22 §3.11). - mcpp::provider::roots::hold(outputDir); + mcpp::provider::roots::hold(stateDir); // Read as it runs, into this directory's report, unless nothing is to be // shown (build progress design 2026-09-29, §6.1). const bool reporting = !mcpp::ui::is_quiet(); @@ -2677,6 +2712,10 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, if (!verbose && !reporting) argv.push_back("--quiet"); argv.push_back("-C"); argv.push_back(outputDir.string()); + if (const auto graph = ninjaPath.lexically_relative(outputDir).generic_string(); graph != "build.ninja") { + argv.push_back("-f"); + argv.push_back(graph); + } if (verbose) argv.push_back("-v"); // MCPP_NINJA_DEBUG: append ninja's own `-d` topics. The one instrument that // works on a process nobody can attach to. @@ -2725,20 +2764,20 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, if (capped) { // The graph names no cap; its first drive left it beside build.ninja. // Without it the graph is replanned rather than run unbounded. - const int cap = mcpp::build::read_compiler_cap_sidecar(outputDir); + const int cap = mcpp::build::read_compiler_cap_sidecar(stateDir); if (cap <= 0) return std::nullopt; - auto opened = mcpp::build::schedule::detach::RunScope::begin(outputDir, cap); + auto opened = mcpp::build::schedule::detach::RunScope::begin(outputDir, stateDir, cap); if (!opened) { mcpp::ui::error(opened.error()); return 1; } compilerRun.emplace(std::move(*opened)); compilerRun->environment(childEnv); childEnv.emplace_back("MCPP_MEMORY_THRESHOLD", - std::to_string(mcpp::build::read_memory_threshold_sidecar(outputDir))); - for (auto& kv : mcpp::build::read_unit_cache_sidecar(outputDir)) childEnv.push_back(std::move(kv)); + std::to_string(mcpp::build::read_memory_threshold_sidecar(stateDir))); + for (auto& kv : mcpp::build::read_unit_cache_sidecar(stateDir)) childEnv.push_back(std::move(kv)); } // The build's record, as the full path keeps it (design 2026-11-20 §5.6). - const auto logMark = mcpp::build::progress::mark_log(outputDir); - const auto usageFile = outputDir / mcpp::build::record::kUsageFile; + const auto logMark = mcpp::build::progress::mark_log(stateDir); + const auto usageFile = stateDir / mcpp::build::record::kUsageFile; std::ofstream(usageFile, std::ios::binary | std::ios::trunc); childEnv.emplace_back(std::string(mcpp::build::record::kUsageEnv), mcpplibs::os::fs::utf8(usageFile)); const auto compilerStopped=[&] {return compilerRun&&compilerRun->failed();}; @@ -2770,7 +2809,7 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, } } if (reporting) { - mcpp::build::progress::Build report(outputDir); + mcpp::build::progress::Build report(stateDir); mcpp::build::NinjaRun run; if (scanArgv) run = mcpp::build::run_ninja_reporting(*scanArgv, childEnv, std::chrono::milliseconds{0}, @@ -2787,7 +2826,7 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, // A stale graph is not this build's outcome: the full path plans // again and builds, and reports the packages then. if (status == 0 || reported || !is_stale_ninja_failure(out)) { - mcpp::build::progress::keep_ran(outputDir, logMark, usageFile, &report); + mcpp::build::progress::keep_ran(stateDir, logMark, usageFile, &report); report.finish(status == 0); } } else { @@ -2799,7 +2838,7 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, if (r.exit_code == 0) r = mcpp::run::execute(argv,{.env=childEnv,.should_stop=compilerStopped}); out = std::move(r.output); status = r.exit_code; - if (status == 0 || !is_stale_ninja_failure(out)) mcpp::build::progress::keep_ran(outputDir, logMark, usageFile, nullptr); + if (status == 0 || !is_stale_ninja_failure(out)) mcpp::build::progress::keep_ran(stateDir, logMark, usageFile, nullptr); } const auto bmiRun = mcpp::buildopt::keep::run_end(outputDir); for (auto const& line : mcpp::buildopt::keep::summary(bmiRun)) @@ -2865,7 +2904,7 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, mcpp::ui::block(advice); } // SPEC-019 §9: whether an entry of the register acted on the step that failed. - mcpp::build::report_buildopt_failure(ninjaPath.parent_path(), out); + mcpp::build::report_buildopt_failure(outputDir, stateDir, out); return 1; } // Verbose ninja output is narration, so it goes to the narration stream, @@ -3169,11 +3208,33 @@ export struct ReplayAsk { // what tells afterwards whether an artifact was relinked. export struct ReplayableBuild { std::filesystem::path outputDir; + // The plan's own directory, `outputDir` for a plan that has none. + std::filesystem::path stateDir; std::filesystem::path ninjaPath; std::string ninjaProgram; mcpp::build::runtime_validation::ArtifactSnapshot validated; }; +// THE LOCKS A RECORDED BUILD IS REPLAYED UNDER are the ones its full path held +// (design 2026-11-27 §3.7.1): the configuration's directory alone, or the +// directory shared and the plan's own lock alone. Taken before admission: a +// build of the plan that held them may have rewritten the graph while this +// one waited, and the record is judged against what is there now. +using ReplayLocks = std::vector>; +std::expected replay_locks(const BuildCacheEntry& e) { + const std::filesystem::path outputDir(e.outputDir); + ReplayLocks held; + auto dir = mcpp::build::dirlock::acquire(outputDir, /*shared=*/!e.planState.empty()); + if (!dir) return std::unexpected(dir.error()); + held.push_back(std::move(*dir)); + if (e.planState.empty()) return held; + auto plan = mcpp::build::dirlock::acquire_plan(outputDir, e.planState, + mcpp::build::dirlock::plan_named(e.group)); + if (!plan) return std::unexpected(plan.error()); + held.push_back(std::move(*plan)); + return held; +} + export std::expected admit_recorded_build(const BuildCacheEntry& e, const ReplayAsk& ask) { // The engine that wrote the graph is the engine that replays it (#757). @@ -3196,7 +3257,10 @@ admit_recorded_build(const BuildCacheEntry& e, const ReplayAsk& ask) { std::error_code ec; const bool testGraph = ask.graphFile != "build.ninja"; - const auto ninjaPath = outputDir / ask.graphFile; + // A plan of its own replays the graph in its directory (§3.7.1); a test + // graph's record names the graph with that directory already. + const auto stateDir = e.planState.empty() ? outputDir : outputDir / e.planState; + const auto ninjaPath = testGraph ? outputDir / ask.graphFile : stateDir / ask.graphFile; if (!std::filesystem::exists(ninjaPath, ec)) return std::unexpected(std::format("{} does not exist", ask.graphFile)); // The graph names the engine it runs, and that is asked of the graph, not @@ -3270,7 +3334,7 @@ admit_recorded_build(const BuildCacheEntry& e, const ReplayAsk& ask) { auto validated = testGraph ? std::optional( mcpp::build::runtime_validation::ArtifactSnapshot{}) : mcpp::build::runtime_validation::validated_artifact_snapshot( - outputDir, *e.runtimeBinding); + outputDir, e.planState, *e.runtimeBinding); if (!validated) return std::unexpected("no validated artifact snapshot is recorded for this build"); auto ninjaProgram = e.ninjaProgram; @@ -3278,7 +3342,7 @@ admit_recorded_build(const BuildCacheEntry& e, const ReplayAsk& ask) { if (ninjaProgram.size() >= 2 && ninjaProgram.front() == '\'' && ninjaProgram.back() == '\'') ninjaProgram = ninjaProgram.substr(1, ninjaProgram.size() - 2); - return ReplayableBuild{outputDir, ninjaPath, std::move(ninjaProgram), std::move(*validated)}; + return ReplayableBuild{outputDir, stateDir, ninjaPath, std::move(ninjaProgram), std::move(*validated)}; } // `programs`, when given, receives the recorded build's programs (name, path) @@ -3348,13 +3412,11 @@ export std::optional try_fast_build(const std::filesystem::path& projectRoo if (match->runtimeBinding && !match->runtimeBinding->baseIdentity.empty()) return fast_path_declined("build", "a stated target base is measured on the full path"); - // The directory is written by ninja below, under its lock (mcpp#839). - // Taken BEFORE admission: a build of this configuration that held it may - // have rewritten build.ninja (a test graph, another request) while this - // one waited, and the record is judged against what is there now. - // Not taken (the wait limit, or a directory that cannot be locked): the - // command refuses here rather than waiting again on the full path. - auto buildLock = mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir)); + // The directory is written by ninja below, under its locks (mcpp#839, + // replay_locks). Not taken (the wait limit, or a directory that cannot be + // locked): the command refuses here rather than waiting again on the full + // path. + auto buildLock = replay_locks(*match); if (!buildLock) { mcpp::ui::error(mcpp::build::dirlock::refused(buildLock.error())); return 1; @@ -3384,7 +3446,7 @@ export std::optional try_fast_build(const std::filesystem::path& projectRoo // see it back. restore_root_compile_commands(projectRoot, outputDir, match->rootCompileDb); std::chrono::milliseconds elapsed{}; - auto record = fast_path_begin(projectRoot, outputDir); + auto record = fast_path_begin(projectRoot, outputDir, admitted->stateDir); auto rc = run_ninja_fast(admitted->ninjaProgram, outputDir, ninjaPath, verbose, runtimeEnvKey, runtimeEnvValue, &elapsed); if (!rc) return fast_path_declined("build", "ninja reported a stale graph"); @@ -3402,7 +3464,7 @@ export std::optional try_fast_build(const std::filesystem::path& projectRoo // The descriptor the plan recorded (revision 3, §7.3); empty for a record // written before it was carried. - mcpp::build::progress::note_sources(outputDir); + mcpp::build::progress::note_sources(admitted->stateDir); mcpp::build::progress::finished(want->profile, mcpp::build::progress::read_descriptor(outputDir)); return 0; @@ -3439,7 +3501,7 @@ export std::optional try_fast_workspace_build( const auto entries = read_build_cache(wsRoot); struct Ready { - std::filesystem::path outputDir; + std::filesystem::path outputDir, stateDir, ninjaPath; std::string ninjaProgram, runtimeEnvKey, runtimeEnvValue, rootCompileDb; mcpp::build::runtime_validation::ArtifactSnapshot validated; }; @@ -3466,15 +3528,15 @@ export std::optional try_fast_workspace_build( && e.toolchainRecorded && e.toolchainRequest == want->toolchainRequest && e.selection == selection && e.group == group) { match = &e; break; } if (!match) return fast_path_declined("workspace", "no recorded build matches this selection"); - // Each group's directory under its own lock, taken before admission - // for the reason try_fast_build gives. Groups are visited in one - // order by every command, so two never wait on each other. - auto groupLock = mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir)); + // Each group's directory under its own locks (replay_locks). Groups + // are visited in one order by every command, so two never wait on + // each other. + auto groupLock = replay_locks(*match); if (!groupLock) { mcpp::ui::error(mcpp::build::dirlock::refused(groupLock.error())); return 1; } - locks.push_back(std::move(*groupLock)); + locks.insert(locks.end(), groupLock->begin(), groupLock->end()); // The gates every fast path shares (see admit_recorded_build). A // workspace has no project tree of its own to sweep: its members are // recorded roots, each classified by its own package. @@ -3485,7 +3547,8 @@ export std::optional try_fast_workspace_build( .treesName = "a member's or a path dependency's", }); if (!admitted) return fast_path_declined("workspace", admitted.error()); - ready.push_back({admitted->outputDir, admitted->ninjaProgram, match->runtimeEnvKey, + ready.push_back({admitted->outputDir, admitted->stateDir, admitted->ninjaPath, + admitted->ninjaProgram, match->runtimeEnvKey, match->runtimeEnvValue, match->rootCompileDb, std::move(admitted->validated)}); profile = want->profile; } @@ -3503,8 +3566,8 @@ export std::optional try_fast_workspace_build( // The group's record, restated as the single project's fast path // restates it: `--message-format json` reports the artifacts of a // workspace replayed as it reports those of a package (docs/50 §9). - auto record = fast_path_begin(wsRoot, r.outputDir); - auto rc = run_ninja_fast(r.ninjaProgram, r.outputDir, r.outputDir / "build.ninja", + auto record = fast_path_begin(wsRoot, r.outputDir, r.stateDir); + auto rc = run_ninja_fast(r.ninjaProgram, r.outputDir, r.ninjaPath, verbose, r.runtimeEnvKey, r.runtimeEnvValue, &elapsed); if (!rc) return fast_path_declined("workspace", "ninja reported a stale graph"); if (*rc != 0) { @@ -3514,7 +3577,7 @@ export std::optional try_fast_workspace_build( if (!mcpp::build::runtime_validation::artifact_snapshot_unchanged(r.validated)) return fast_path_declined("workspace", "ninja relinked an artifact, whose closure the full path validates"); fast_path_end(record, true); - mcpp::build::progress::note_sources(r.outputDir); + mcpp::build::progress::note_sources(r.stateDir); } // The groups share the profile, and so its descriptor. mcpp::build::progress::finished( @@ -3729,7 +3792,7 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, // Under the directory's lock while ninja writes it, released before the // program starts: a program that runs for an hour holds nothing, and a // build of the same configuration meanwhile proceeds (mcpp#839). - auto buildLock = mcpp::build::dirlock::acquire(std::filesystem::path(match->outputDir)); + auto buildLock = replay_locks(*match); if (!buildLock) { mcpp::ui::error(mcpp::build::dirlock::refused(buildLock.error())); return kRunBuildFailed; @@ -3758,7 +3821,7 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, // Fresh → run ninja (picks up any incremental object/link work) then // exec the cached exe path directly. C1, same reason as try_fast_build's. restore_root_compile_commands(projectRoot, outputDir, match->rootCompileDb); - auto record = fast_path_begin(projectRoot, outputDir); + auto record = fast_path_begin(projectRoot, outputDir, admitted->stateDir); auto rc = run_ninja_fast(admitted->ninjaProgram, outputDir, ninjaPath, /*verbose=*/false, match->runtimeEnvKey, match->runtimeEnvValue); if (!rc) return fast_path_declined("run", "ninja reported a stale graph"); @@ -3770,7 +3833,7 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, validatedBefore)) return fast_path_declined("run", "ninja relinked an artifact, whose closure the full path validates"); // never execute an artifact not validated for this binding fast_path_end(record, true); - buildLock->reset(); + buildLock->clear(); // The cache records the program's path with `/`; the full path spells it // natively (`bin\app.exe` on Windows), and so does this one, so that the @@ -7447,7 +7510,7 @@ void write_test_plan(const TestBuild& tb, std::string_view targetOverride) { for (auto const& p : ctx.xlingsPayloads) v.push_back(p.generic_string()); return v; }(), - std::string(kTestPlanSelection), {}, ctx.plan.rootCompileDb); + std::string(kTestPlanSelection), {}, ctx.plan.rootCompileDb, {}, ctx.planStateDir); } // The tests of an unchanged project, from the record; nullopt: the full path. @@ -7495,9 +7558,10 @@ fast_test_plan(const std::filesystem::path& projectRoot, const TestOptions& test if (recordedNames != discoveredNames) return declined("the package's tests are not the recorded ones"); // A lock not taken declines: the full path refuses with it. - auto testLock = mcpp::build::dirlock::acquire(outputDir); + auto testLock = replay_locks(*match); if (!testLock) return declined(testLock.error().message()); - ctx.buildLock = std::move(*testLock); + ctx.buildLock = testLock->front(); + if (testLock->size() > 1) ctx.planLock = testLock->back(); if (test_graph_stamp(outputDir / graphFile) != record.value("graph_stamp", "")) return declined("the test graph is not the one the record was written with"); auto admitted = admit_recorded_build(*match, { @@ -7797,13 +7861,13 @@ export int run_tests(std::span passthrough, std::move(testTargets), std::move(overrides)); if (!prepared) { mcpp::ui::error(prepared.error()); return 2; } - prepared->plan.graphFile = "test.ninja"; + prepared->plan.graphFile = (prepared->plan.stateDir / "test.ninja").generic_string(); TestBuild tb; tb.programEnv = std::move(programEnv); tb.ctx.emplace(std::move(*prepared)); if (int rc = select_by_change(tb, testOpts, json)) return rc; tb.backend = mcpp::build::make_ninja_backend(); - tb.ninjaLog = tb.ctx->outputDir / ".ninja_log"; + tb.ninjaLog = tb.ctx->plan.state_dir() / ".ninja_log"; { std::error_code ec; tb.logFrom = std::filesystem::file_size(tb.ninjaLog, ec); @@ -7970,11 +8034,11 @@ export int run_test_legs(std::span passthrough, auto prepared = prepare_build(/*print_fp=*/false, /*includeDevDeps=*/true, discovered->targets, std::move(o)); if (!prepared) { if (int rc = refused(prepared.error())) return rc; continue; } - prepared->plan.graphFile = "test.ninja"; + prepared->plan.graphFile = (prepared->plan.stateDir / "test.ninja").generic_string(); leg->tb.ctx.emplace(std::move(*prepared)); if (int rc = select_by_change(leg->tb, testOpts, json)) return rc; leg->tb.backend = mcpp::build::make_ninja_backend(); - leg->tb.ninjaLog = leg->tb.ctx->outputDir / ".ninja_log"; + leg->tb.ninjaLog = leg->tb.ctx->plan.state_dir() / ".ninja_log"; std::error_code ec; leg->tb.logFrom = std::filesystem::file_size(leg->tb.ninjaLog, ec); if (ec) leg->tb.logFrom = 0; @@ -8212,7 +8276,7 @@ export void run_workspace_tests(std::span passthrough, auto prepared = prepare_build(/*print_fp=*/false, /*includeDevDeps=*/true, /*extraTargets=*/{}, std::move(mo)); if (!prepared) return std::unexpected(prepared.error()); - prepared->plan.graphFile = "test.ninja"; + prepared->plan.graphFile = (prepared->plan.stateDir / "test.ninja").generic_string(); auto tb = std::make_unique(); tb->prepareMs = std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); @@ -8220,7 +8284,7 @@ export void run_workspace_tests(std::span passthrough, if (select_by_change(*tb, testOpts, json) != 0) return std::unexpected(std::format("--since {}: the change could not be read", testOpts.since)); tb->backend = mcpp::build::make_ninja_backend(); - tb->ninjaLog = tb->ctx->outputDir / ".ninja_log"; + tb->ninjaLog = tb->ctx->plan.state_dir() / ".ninja_log"; std::error_code ec; tb->logFrom = std::filesystem::file_size(tb->ninjaLog, ec); if (ec) tb->logFrom = 0; @@ -8704,6 +8768,16 @@ std::optional target_budget(const std::filesystem::path& root) { return std::nullopt; } +// The lists of what a configuration's directory uses (`uses.list`): its own +// and each plan's, `plans//uses.list` (design 2026-11-27 §3.7.1). +std::vector uses_lists(const std::filesystem::path& fpDir) { + std::vector out{fpDir / "uses.list"}; + std::error_code ec; + for (std::filesystem::directory_iterator p(fpDir / "plans", ec), end; p != end; p.increment(ec)) + out.push_back(p->path() / "uses.list"); + return out; +} + std::uintmax_t tree_bytes(const std::filesystem::path& dir) { std::uintmax_t total = 0; std::error_code ec; @@ -8764,12 +8838,15 @@ export void sweep_after_build() { clean_stale(false, days * 86400, true); // The build-cache entries the remaining configurations use are used today, // whether this build planned or replayed its graph (design 2026-10-31 §4.6). - for (fs::recursive_directory_iterator it(*root / "target", ec), end; it != end; it.increment(ec)) { - if (it.depth() >= 2) it.disable_recursion_pending(); - if (it->path().filename() != "uses.list") continue; - std::ifstream in(it->path()); + auto mark = [](const fs::path& list) { + std::ifstream in(list); for (std::string l; std::getline(in, l);) if (l.starts_with("cache ")) mcpp::home::mark_used(l.substr(6)); + }; + for (fs::recursive_directory_iterator it(*root / "target", ec), end; it != end; it.increment(ec)) { + if (it.depth() >= 1) it.disable_recursion_pending(); + if (it.depth() != 1 || !it->is_directory(ec)) continue; + for (auto const& list : uses_lists(it->path())) mark(list); } } @@ -9002,9 +9079,8 @@ export int clean_stale(bool dryRun, std::int64_t keepWithinSecs, bool quiet) { // be unused and nothing here is removed. std::set usedOut, usedHost; bool usesKnown = false; - auto readUses = [&](const fs::path& fpDir) { - if (swept.contains(fpDir)) return; - std::ifstream in(fpDir / "uses.list"); + auto readList = [&](const fs::path& list) { + std::ifstream in(list); if (!in) return; usesKnown = true; for (std::string l; std::getline(in, l);) { @@ -9014,6 +9090,10 @@ export int clean_stale(bool dryRun, std::int64_t keepWithinSecs, bool quiet) { else if (l.starts_with("host ")) usedHost.insert(l.substr(sp + 1)); } }; + auto readUses = [&](const fs::path& fpDir) { + if (swept.contains(fpDir)) return; + for (auto const& list : uses_lists(fpDir)) readList(list); + }; { std::error_code uec; for (fs::directory_iterator t(target, uec), end; t != end; t.increment(uec)) { diff --git a/src/build/graph_engine.cppm b/src/build/graph_engine.cppm index c92c78530..418f6c98f 100644 --- a/src/build/graph_engine.cppm +++ b/src/build/graph_engine.cppm @@ -41,6 +41,10 @@ std::filesystem::path place(const std::filesystem::path& to); // a link that is the same file or a copy of it. bool is_this_engine(const std::filesystem::path& named); +// Whether the directory's link of `epoch` is this engine already: `refresh` +// then changes nothing (a build that shares the directory asks first). +bool current(const std::filesystem::path& outputDir, int epoch); + } // namespace mcpp::build::graph_engine namespace mcpp::build::graph_engine { @@ -105,6 +109,10 @@ std::filesystem::path place(const std::filesystem::path& to) { return self; } +bool current(const std::filesystem::path& outputDir, int epoch) { + return same_engine(link(outputDir, epoch), mcpp::invocation::self_exe_path()); +} + std::filesystem::path refresh(const std::filesystem::path& outputDir, int epoch) { namespace fs = std::filesystem; const auto to = link(outputDir, epoch); diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 283651ab3..592ecbe93 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -53,6 +53,7 @@ import mcpp.provider.roots; import mcpp.buildopt.keep; import mcpp.buildopt.advice; import mcpp.buildopt.registry; +import mcpp.home.files; // plan-locks: whether another plan holds its lock import mcpp.modgraph.graph; import mcpplibs.os.platform; import mcpplibs.os.windows; @@ -113,8 +114,10 @@ std::string emit_ninja_string(const BuildPlan& plan); // program and in its runtime environment. `placed.list`, beside build.ninja, // holds the destinations of the previous graph; one that is not among // `placed` now is removed when it is a file inside `outputDir`. +// `stateDir` holds the plan's list of what it placed (`placed.list`). void sweep_stale_placements(const std::filesystem::path& outputDir, - const std::vector& placed); + const std::vector& placed, + const std::filesystem::path& stateDir); // The same, and when the plan places two or more files beside its programs, // the placement list the one `stage_list` edge reads (#734 E4), for the caller // to write as `/placements.list`. Empty when there is no such edge. @@ -375,7 +378,10 @@ void write_buildopt_sidecar(const BuildPlan& plan); // After a failed run, in either path: says, as a tip of the failed run, how to // check whether an entry is the cause, when an entry acted on the step that // failed. `ninjaOutput` is the run's raw output. -void report_buildopt_failure(const std::filesystem::path& outputDir, std::string_view ninjaOutput); +// `stateDir` is the plan's directory (the output directory when the plan has +// none of its own), where the statement and the step record are. +void report_buildopt_failure(const std::filesystem::path& outputDir, const std::filesystem::path& stateDir, + std::string_view ninjaOutput); // #693 (M4): whether a Ninja reads build.ninja in the encoding mcpp writes it. // @@ -1026,13 +1032,13 @@ link_inputs(const BuildPlan& plan, const std::string& ninjaProgram, const mcpp::build::runtime_validation::ArtifactSnapshot& artifacts) { mcpp::build::runtime_validation::LinkInputs out; if (artifacts.empty() || ninjaProgram.empty()) return out; - std::vector argv{ninjaProgram, "-C", plan.outputDir.string(), "-t", "deps"}; + std::vector argv{ninjaProgram, "-C", plan.outputDir.string(), "-f", plan.graphFile, "-t", "deps"}; for (auto const& [artifact, _] : artifacts) { std::error_code ec; auto rel = std::filesystem::relative(artifact, plan.outputDir, ec); if (!ec && !rel.empty()) argv.push_back(rel.generic_string()); } - if (argv.size() == 5) return out; + if (argv.size() == 7) return out; auto r = mcpp::run::capture_stdout(argv); if (r.exit_code != 0) return out; // `: #deps N, deps mtime T (VALID)` and then the inputs, indented. @@ -1478,19 +1484,29 @@ void write_buildopt_sidecar(const BuildPlan& plan) { if (const auto* entry = mcpp::buildopt::registry::find(mcpp::buildopt::registry::kPrivateFragment)) applied.fragmentCheck = std::string(plan.toolchain.compiler == mcpp::toolchain::CompilerId::GCC && !entry->checkGcc.empty() ? entry->checkGcc : entry->check); - advice::write_applied(plan.outputDir, applied); + applied.sharedPlan = !plan.stateDir.empty(); + advice::write_applied(plan.state_dir(), applied); } -void report_buildopt_failure(const std::filesystem::path& outputDir, std::string_view ninjaOutput) { +void report_buildopt_failure(const std::filesystem::path& outputDir, const std::filesystem::path& stateDir, + std::string_view ninjaOutput) { namespace advice = mcpp::buildopt::advice; if (mcpp::buildopt::registry::standard_only()) return; - const auto applied = advice::read_applied(outputDir); + const auto applied = advice::read_applied(stateDir); const auto kept = mcpp::buildopt::keep::kept(outputDir); - if (applied.fragments.empty() && kept.empty()) return; + if (applied.fragments.empty() && kept.empty() && !applied.sharedPlan) return; advice::Failed failed; failed.linked = advice::linker_failed(ninjaOutput); + // Another plan whose lock is held now was building beside this one. + if (applied.sharedPlan) { + std::error_code ec; + for (auto const& e : std::filesystem::directory_iterator(outputDir / "plans", ec)) + if (e.path() != stateDir && e.is_directory(ec) + && !mcpp::home::FileLock::try_acquire(e.path(), ".mcpp-plan.lock")) + failed.concurrentPlans = true; + } // The step that failed, by the source it reads (the step record). - if (const auto record = mcpp::build::progress::read_record(outputDir)) { + if (const auto record = mcpp::build::progress::read_record(stateDir)) { for (auto const& outputs : advice::failed_outputs(ninjaOutput)) { for (auto const& o : outputs) { const auto step = record->step.find(mcpp::build::progress::normalise(o)); @@ -1847,7 +1863,8 @@ std::string emit_ninja_string(const BuildPlan& plan) { } void sweep_stale_placements(const std::filesystem::path& outputDir, - const std::vector& placed) { + const std::vector& placed, + const std::filesystem::path& stateDir) { namespace fs = std::filesystem; std::set now; std::string text; @@ -1857,7 +1874,7 @@ void sweep_stale_placements(const std::filesystem::path& outputDir, if (line.empty() || line.starts_with("..")) continue; if (now.insert(line).second) text += line + "\n"; } - const auto listPath = outputDir / "placed.list"; + const auto listPath = stateDir / "placed.list"; std::error_code ec; std::string old; if (fs::exists(listPath, ec)) { @@ -1898,7 +1915,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // No number of compilers here: the generation carries the cap, so the // graph is the same whatever the job count (e2e 861). const std::string compilerPrefix = plan.scheduleCompilerCap > 0 - ? std::string("$mcpp __compiler-cap --sem .mcpp-sched --output $out --depfile $out.d -- ") + ? std::string("$mcpp __compiler-cap --sem $sched_dir --output $out --depfile $out.d -- ") : std::string{}; // WHAT THE EXECUTOR READS FOR THE COMPILER (design 2026-11-19 §20): the // record of the files a compile read, when the compiler writes one that is @@ -1921,11 +1938,11 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, ? std::format(" --relocate {}", relocation.auxNaming.empty() ? std::string_view("none") : relocation.auxNaming) : std::string{}; const std::string driverPrefix = plan.scheduleCompilerCap > 0 - ? std::format("$mcpp __compiler-cap --sem .mcpp-sched --output $out --depfile $out.d{}{}{} -- ", + ? std::format("$mcpp __compiler-cap --sem $sched_dir --output $out --depfile $out.d{}{}{} -- ", relocateWord, recordWord, textWord) : std::string{}; const std::string scanPrefix = plan.scheduleCompilerCap > 0 - ? std::format("$mcpp __compiler-cap --sem .mcpp-sched --output $out --depfile $out.d{}{} -- ", + ? std::format("$mcpp __compiler-cap --sem $sched_dir --output $out --depfile $out.d{}{} -- ", relocation.relocatable ? " --relocate none" : "", textWord) : std::string{}; // The same executor for an edge that writes a BMI: it holds the previous @@ -1941,13 +1958,13 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // as `$out`. auto bmi_keeping_prefix = [&](std::string_view bmi) { return plan.scheduleCompilerCap > 0 - ? std::format("$mcpp __compiler-cap --sem .mcpp-sched --output $out --depfile $out.d{}" + ? std::format("$mcpp __compiler-cap --sem $sched_dir --output $out --depfile $out.d{}" " --bmi \"{}\"{}{}{} -- ", bmi == "$out" ? "" : " --object", bmi, relocateWord, recordWord, textWord) : std::string{}; }; const std::string objectPrefix = plan.scheduleCompilerCap > 0 - ? std::format("$mcpp __compiler-cap --sem .mcpp-sched --output $out --depfile $out.d --object{}{}{} -- ", + ? std::format("$mcpp __compiler-cap --sem $sched_dir --output $out --depfile $out.d --object{}{}{} -- ", relocateWord, recordWord, textWord) : std::string{}; // The other split shape. Clang publishes no BMI early — it writes the BMI @@ -1984,6 +2001,18 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, plan.accelOverridden, plan.packFormat, plan.requestTag) + "\n"); append("ninja_required_version = 1.11\n\n"); + // THE PLAN'S OWN STATE (design 2026-11-27 §3.7.1): ninja's log and + // dependencies, the compilers' semaphore and the placement list, in the + // plan's directory when it has one and in the configuration's otherwise, + // where they always were (the evaluated commands are then unchanged). + { + const auto at = [&](std::string_view name) { + return escape_ninja_path(plan.stateDir.empty() ? std::filesystem::path(name) + : plan.stateDir / name); + }; + if (!plan.stateDir.empty()) append(std::format("builddir = {}\n", escape_ninja_path(plan.stateDir))); + append(std::format("sched_dir = {}\nplacements_list = {}\n\n", at(".mcpp-sched"), at("placements.list"))); + } // All compile/link flags are computed once via flags.cppm. auto flags = compute_flags(plan); @@ -2302,7 +2331,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // input of the edge, so adding or removing an entry re-runs it; `restat` // keeps an unchanged destination's time stamp. append("rule stage_list\n"); - append(" command = $mcpp stage --list placements.list\n"); + append(" command = $mcpp stage --list $placements_list\n"); append(" description = STAGE $count files\n"); append(" restat = 1\n\n"); @@ -2518,6 +2547,13 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // the same over-approximation the link rules use (`separateLinker || // is_windows`). const bool useCompileRsp = mcpplibs::os::is_windows || msvcDialect; + // A RESPONSE FILE OF THE PLAN'S OWN when the plan has a directory of its + // own (design 2026-11-27 §3.7.1): ninja removes an edge's response file + // once the edge ends, and two plans that run one edge at once -- a member + // both select -- would otherwise remove the file the other's command is + // about to read. The unit cache keys a response file by its content. + const std::string rspFile = plan.stateDir.empty() + ? std::string("$out.rsp") : std::format("$out.{}.rsp", plan.stateDir.filename().string()); // THE BYTE ORDER MARK, FOR THE TOOLS THAT NEED ONE TO READ UTF-8 (#693). // // build.ninja is UTF-8, and Ninja copies `rspfile_content` into the @@ -2532,11 +2568,11 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // Both take the payload with its leading space, so callers read as // `command = $cxx{payload} ...` exactly like the inline form did. auto rsp_ref = [&](const std::string& payload) { - return useCompileRsp ? std::string(" @$out.rsp") : payload; + return useCompileRsp ? " @" + rspFile : payload; }; auto append_rspfile = [&](const std::string& payload) { if (!useCompileRsp) return; - append(" rspfile = $out.rsp\n"); + append(std::format(" rspfile = {}\n", rspFile)); append(std::format(" rspfile_content ={}{}\n", msvcDialect ? " " + std::string(kUtf8ByteOrderMark) : "", payload)); }; @@ -2774,7 +2810,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, append("rule rc_object\n"); // The cl.exe toolchain's rc.exe writes its text as cl.exe does (T2). const std::string rcPrefix = plan.scheduleCompilerCap > 0 - ? std::format("$mcpp __compiler-cap --sem .mcpp-sched --output $out --depfile $out.d{} -- ", + ? std::format("$mcpp __compiler-cap --sem $sched_dir --output $out --depfile $out.d{} -- ", plan.rcStyle == "msvc" ? textWord : std::string{}) : std::string{}; if (plan.rcStyle == "msvc") @@ -2858,10 +2894,27 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, const std::string companionOption = companions.empty() ? std::string() : " --companions " + companions; // link.exe and lib.exe write their text as cl.exe does: `link-output` // decodes it where it reads it (design 2026-11-19 §20 T2). - auto publish_link = [&](std::string cmd) { + // An archive (`archive`) holds no permit and names its output as a word + // of its own. On a POSIX host it is written whole under a temporary name + // and renamed over the artifact, as a link is (design 2026-11-27 §3.7.1): + // an archiver updates an archive in place, so two plans that archive one + // library at once, or an archiver that is stopped, would leave a mix. A + // lib.exe whose text is not UTF-8, and an archiver that reads no response + // file, still run through `link-output`, which decodes the text or + // expands the words. + const std::string expandWord = flags.archiverTakesResponseFiles ? std::string{} : std::string(" --expand"); + auto publish_link = [&](std::string cmd, bool archive) { if constexpr (mcpplibs::os::is_windows) { + if (archive) + return textWord.empty() && expandWord.empty() + ? cmd : "$mcpp link-output --output $out" + textWord + expandWord + " -- " + cmd; return "$mcpp link-output --output $out --aside" + companionOption + textWord + " -- " + cmd; } else { + if (archive) + return separateLinker + ? (textWord.empty() && expandWord.empty() + ? cmd : "$mcpp link-output --output $out" + textWord + expandWord + " -- " + cmd) + : "$mcpp link-output --output $out" + textWord + " --temporary" + expandWord + " -- " + cmd; if (!companions.empty() || !textWord.empty()) return "$mcpp link-output --output $out" + companionOption + textWord + " -- " + cmd; if (inPlaceTarget) return cmd; @@ -2884,7 +2937,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // together are what this machine runs at once; the graph still names no // number (e2e 861). An archive copies its members and holds none. const std::string linkPrefix = plan.scheduleCompilerCap > 0 - ? std::string("$mcpp __compiler-cap --sem .mcpp-sched --output $out -- ") + ? std::string("$mcpp __compiler-cap --sem $sched_dir --output $out -- ") : std::string{}; auto link_rule = [&](std::string_view name, std::string cmd, std::string_view desc) { @@ -2894,18 +2947,14 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, if (reports) cmd += flags.linkReport; // The permit wraps the publication: the attempt's output is the // artifact in place when the command it holds exits. - if (desc != "AR") cmd = linkPrefix + publish_link(std::move(cmd)); - // An archive holds no permit; a lib.exe whose text is not UTF-8 - // still runs through `link-output`, which only decodes it. - else if (!textWord.empty() || !flags.archiverTakesResponseFiles) - cmd = "$mcpp link-output --output $out" + textWord - + (flags.archiverTakesResponseFiles ? "" : " --expand") + " -- " + cmd; + if (desc != "AR") cmd = linkPrefix + publish_link(std::move(cmd), false); + else cmd = publish_link(std::move(cmd), true); append(std::format("rule {}\n", name)); if (useRsp) { if (auto pos = cmd.find("$in"); pos != std::string::npos) - cmd.replace(pos, 3, "@$out.rsp"); + cmd.replace(pos, 3, "@" + rspFile); append(std::format(" command = {}\n", cmd)); - append(" rspfile = $out.rsp\n"); + append(std::format(" rspfile = {}\n", rspFile)); // `$in_newline`, not `$in`: ninja separates by newlines instead // of spaces. Routing the objects through a response file // removed the COMMAND-LINE ceiling but left a second one @@ -3756,7 +3805,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, e += " obj_out = " + obj + "\n"; e += " slot = " + slot + "\n"; e += " scan_dep = " + escape_ninja_path(ddi) + ".dep\n"; - e += " sched_sem = .mcpp-sched\n"; + e += " sched_sem = $sched_dir\n"; if (auto inc = local_include_flags(cu, dial); !inc.empty()) e += " local_includes =" + inc + "\n"; if (auto fl = unit_cxx_flags(cu); !fl.empty()) @@ -4370,7 +4419,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, list += std::format("{}\t{}\n", s.generic_string(), d.dest.generic_string()); } } - append(std::format("build{} : stage_list{} | placements.list\n count = {}\n", + append(std::format("build{} : stage_list{} | $placements_list\n count = {}\n", outs, ins, placedFiles.size())); if (placements) *placements = std::move(list); } else { @@ -5104,7 +5153,7 @@ std::expected NinjaBackend::build(const BuildPlan& plan mcpp::build::progress::Build* report = opts.progress; if (!report && !opts.dryRun && opts.report == BuildOptions::Report::Region && mcpp::build::progress::is_open() && !mcpp::ui::is_quiet()) { - ownReport.emplace(plan.outputDir); + ownReport.emplace(plan.state_dir()); report = &*ownReport; } // Where a drive's wall clock went. `mcpp test` calls this once per test on @@ -5137,10 +5186,11 @@ std::expected NinjaBackend::build(const BuildPlan& plan plan.outputDir}); std::optional compilerRun; if (!opts.dryRun && plan.scheduleCompilerCap > 0) { - auto opened = mcpp::build::schedule::detach::RunScope::begin(plan.outputDir, plan.scheduleCompilerCap); + auto opened = mcpp::build::schedule::detach::RunScope::begin(plan.outputDir, plan.state_dir(), + plan.scheduleCompilerCap); if (!opened) return std::unexpected(BuildError{opened.error(), plan.outputDir}); compilerRun.emplace(std::move(*opened)); - reclaim_stale_schedule_tokens(plan.outputDir); + reclaim_stale_schedule_tokens(plan.state_dir()); } auto ninja_path = plan.outputDir / plan.graphFile; @@ -5149,31 +5199,31 @@ std::expected NinjaBackend::build(const BuildPlan& plan // reach both channels or it appears depending on whether build.ninja // happened to be up to date. write_c_abi_absent_sidecar( - plan.outputDir, plan.targetSide.cAbi.interfaceName, + plan.state_dir(), plan.targetSide.cAbi.interfaceName, plan.targetSide.cAbiDecl ? plan.targetSide.cAbiDecl->absent : std::vector{}); - write_consumer_include_sidecar(plan.outputDir, root_include_dirs_of(plan)); - write_compiler_cap_sidecar(plan.outputDir, plan.scheduleCompilerCap); - write_memory_threshold_sidecar(plan.outputDir, plan.memoryThreshold); - write_unit_cache_sidecar(plan.outputDir, plan.unitCacheDir, plan.immutableRoots); + write_consumer_include_sidecar(plan.state_dir(), root_include_dirs_of(plan)); + write_compiler_cap_sidecar(plan.state_dir(), plan.scheduleCompilerCap); + write_memory_threshold_sidecar(plan.state_dir(), plan.memoryThreshold); + write_unit_cache_sidecar(plan.state_dir(), plan.unitCacheDir, plan.immutableRoots); write_buildopt_sidecar(plan); - write_graph_c_library_sidecar(plan.outputDir, plan.targetSide.cAbi); + write_graph_c_library_sidecar(plan.state_dir(), plan.targetSide.cAbi); std::string placements; mcpp::build::progress::Attribution attribution; std::vector placed; auto manifest = emit_ninja_string(plan, &placements, &attribution, &placed); - if (!opts.dryRun) sweep_stale_placements(plan.outputDir, placed); + if (!opts.dryRun) sweep_stale_placements(plan.outputDir, placed, plan.state_dir()); stage("emit-ninja"); // The step record, beside build.ninja like the other files the fast path // reads (build progress design 2026-09-29, §6.3). { auto record = step_record(plan, attribution); - mcpp::build::progress::write_record(plan.outputDir, record); + mcpp::build::progress::write_record(plan.state_dir(), record); if (report) report->set_record(std::move(record)); } if (!placements.empty()) { // Written only when it changes: it is an input of the placement edge. - const auto listPath = plan.outputDir / "placements.list"; + const auto listPath = plan.state_dir() / "placements.list"; std::error_code lec; std::string old; if (std::filesystem::exists(listPath, lec)) { @@ -5223,10 +5273,21 @@ std::expected NinjaBackend::build(const BuildPlan& plan write_file(ninja_path, manifest); if (existed && !tec && std::filesystem::last_write_time(ninja_path, tec) == before && !tec) std::filesystem::last_write_time(ninja_path, std::filesystem::file_time_type::clock::now(), tec); + // A plan of its own leaves its graph where a reader of the + // configuration finds one, too: the last plan's, written whole, as the + // configuration's result record is the last command's. + if (!plan.stateDir.empty()) { + const auto shown = plan.outputDir / std::filesystem::path(plan.graphFile).filename(); + auto tmp = shown; + tmp += std::format(".{:x}", std::random_device{}()); + { std::ofstream(tmp, std::ios::binary | std::ios::trunc) << manifest; } + std::filesystem::rename(tmp, shown, tec); + if (tec) std::filesystem::remove(tmp, tec); + } } // The payloads this graph names are held as the store's roots, so that the // provider's collection keeps them (design 2026-11-22 §3.11). - if (!opts.dryRun) mcpp::provider::roots::hold(plan.outputDir, manifest); + if (!opts.dryRun) mcpp::provider::roots::hold(plan.state_dir(), manifest); stage("write-ninja"); // compile_commands.json — via the dedicated module. @@ -5512,11 +5573,11 @@ std::expected NinjaBackend::build(const BuildPlan& plan nenv.emplace_back(ev.key, ev.value); if (compilerRun) compilerRun->environment(nenv); nenv.emplace_back("MCPP_MEMORY_THRESHOLD", std::to_string(plan.memoryThreshold)); - for (auto& kv : read_unit_cache_sidecar(plan.outputDir)) nenv.push_back(std::move(kv)); + for (auto& kv : read_unit_cache_sidecar(plan.state_dir())) nenv.push_back(std::move(kv)); // THE BUILD'S RECORD (design 2026-11-20 §5.6): where ninja's log ends now, // and the file each compile's executor appends its measurement to. - const auto logMark = mcpp::build::progress::mark_log(plan.outputDir); - const auto usageFile = plan.outputDir / mcpp::build::record::kUsageFile; + const auto logMark = mcpp::build::progress::mark_log(plan.state_dir()); + const auto usageFile = plan.state_dir() / mcpp::build::record::kUsageFile; std::ofstream(usageFile, std::ios::binary | std::ios::trunc); nenv.emplace_back(std::string(mcpp::build::record::kUsageEnv), mcpplibs::os::fs::utf8(usageFile)); const auto compilerStopped=[&] {return compilerRun&&compilerRun->failed();}; @@ -5677,7 +5738,7 @@ std::expected NinjaBackend::build(const BuildPlan& plan } // The edges this build ran, kept for the command (`mcpp test` writes them // into its run) and appended to MCPP_BUILD_RECORD's file. - mcpp::build::progress::keep_ran(plan.outputDir, logMark, usageFile, report); + mcpp::build::progress::keep_ran(plan.state_dir(), logMark, usageFile, report); // Every package gets its final line before what the build has to say // after ninja: validations, advice, `Finished`. if (report) { @@ -5879,7 +5940,7 @@ std::expected NinjaBackend::build(const BuildPlan& plan plan.targetSide.cAbiDecl->absent); // (the fast path reads the same list from the sidecar this build // wrote beside build.ninja — see `write_c_abi_absent_sidecar`) - report_buildopt_failure(plan.outputDir, out); + report_buildopt_failure(plan.outputDir, plan.state_dir(), out); BuildError failure{"build failed", plan.outputDir / plan.graphFile, std::move(diagnostics)}; failure.reported = reported; @@ -5953,8 +6014,14 @@ void write_module_maps(const BuildPlan& plan) { std::ifstream in(path, std::ios::binary); if (std::string(std::istreambuf_iterator(in), {}) == text) return; } + // Written whole: its name is its content's, so two plans that write one + // write the same bytes, and a compiler never reads half of it. std::filesystem::create_directories(path.parent_path(), ec); - std::ofstream(path, std::ios::binary | std::ios::trunc) << text; + auto tmp = path; + tmp += std::format(".{:x}", std::random_device{}()); + { std::ofstream(tmp, std::ios::binary | std::ios::trunc) << text; } + std::filesystem::rename(tmp, path, ec); + if (ec) std::filesystem::remove(tmp, ec); }; for (auto const& [key, scope] : plan.moduleScopes) { write_if_changed(plan.outputDir / scope.mapFile, scope.content); @@ -5966,7 +6033,7 @@ void write_module_maps(const BuildPlan& plan) { // uses now (design 2026-11-19 §11.1); the others age in `instances.tsv`. std::vector used; for (auto const& [pkg, dir] : plan.instanceDirs) used.push_back(dir); - record_instances(plan.outputDir, used); + record_instances(plan.outputDir, used, !plan.stateDir.empty()); } void report_failed_drive(const BuildError& error) { diff --git a/src/build/plan.cppm b/src/build/plan.cppm index 7d6f62e2f..f26082b2e 100644 --- a/src/build/plan.cppm +++ b/src/build/plan.cppm @@ -32,6 +32,8 @@ import mcpp.runtime.binding; import mcpp.provider; import mcpp.provider.select; import mcpp.home; +import mcpp.home.files; +import mcpp.diag; import mcpp.platform; export namespace mcpp::build { @@ -564,6 +566,19 @@ struct BuildPlan { // directory's objects, `.ninja_log` and `.ninja_deps`, so an output both // graphs name is rebuilt when one names another command for it. std::string graphFile = "build.ninja"; + // WHERE THIS PLAN'S OWN STATE LIVES, relative to the output directory + // (design 2026-11-27 §3.7.1, SPEC-019 `plan-locks`): empty when the plan + // holds the configuration's directory alone, `plans/` when + // commands that select different members share it. The graph, ninja's log + // and dependencies, the schedule's semaphore, the step record, the + // placement lists and the sidecars the fast path reads are the plan's; + // objects, BMIs and the members' programs stay in the output directory, + // protected by their publication. + std::filesystem::path stateDir; + std::filesystem::path state_dir() const { return stateDir.empty() ? outputDir : outputDir / stateDir; } + // The plan's record of what it resolved (`resolution.json`, docs/05), + // kept with the plan; write_resolution publishes it as the configuration's. + std::filesystem::path resolution_record() const { return state_dir() / "resolution.json"; } // The module-edge schedule this plan will emit, resolved ONCE (see // mcpp.build.schedule.policy). The backend writes the graph in this shape, // the graph records the tag, and the fast path compares against it — three @@ -968,9 +983,19 @@ struct InstanceUse { std::map read_instances(const std::filesystem::path& outputDir); void write_instances(const std::filesystem::path& outputDir, const std::map& instances); -void record_instances(const std::filesystem::path& outputDir, const std::vector& used); +// `sharedPlans`: the configuration's directory is shared by plans of their own +// (design 2026-11-27 §3.7.1), and the record is read and written under its own +// lock. The last plan to record is the last plan, as when plans follow each +// other: another plan's instances keep the time of their use. +void record_instances(const std::filesystem::path& outputDir, const std::vector& used, + bool sharedPlans = false); void touch_last_instances(const std::filesystem::path& outputDir); +// Writes the plan's `resolution.json` and, for a plan with a directory of its +// own, the configuration's copy: each replaced whole, so plans that finish at +// once leave one plan's record in the output directory, never a mix of two. +void write_resolution(const BuildPlan& plan, std::string_view text); + // Replaces `${mcpp.objects:}` and `${mcpp.objects_rsp:}` in `s` // with `objects_list_path` of the unit `resolve_target_file` names, records the // unit in `units` once, and a name no unit has, or several members define, in @@ -5331,7 +5356,26 @@ std::int64_t now_seconds() { } } // namespace -void record_instances(const std::filesystem::path& outputDir, const std::vector& used) { +void write_resolution(const BuildPlan& plan, std::string_view text) { + mcpp::home::write_replacing(plan.resolution_record(), text); + if (!plan.stateDir.empty()) mcpp::home::write_replacing(plan.outputDir / "resolution.json", text); +} + +void record_instances(const std::filesystem::path& outputDir, const std::vector& used, + bool sharedPlans) { + std::optional held; + if (sharedPlans) { + auto lock = mcpp::home::FileLock::acquire(outputDir, ".mcpp-instances.lock", + {.resource = "the record of this configuration's package instances", .doing = "recording a plan's instances"}); + if (!lock) { + mcpp::diag::degraded("build/instances-record", + std::format("{} [{}]", lock.error().message(), lock.error().token()), + "this plan's package instances keep the date of their last record, " + "and an age-based clean may take one this plan still uses"); + return; + } + held.emplace(std::move(*lock)); + } auto instances = read_instances(outputDir); for (auto& [dir, use] : instances) use.last = false; for (auto const& dir : used) instances[dir] = {now_seconds(), true}; diff --git a/src/build/prepare.cppm b/src/build/prepare.cppm index c91ef1aa9..731870d25 100644 --- a/src/build/prepare.cppm +++ b/src/build/prepare.cppm @@ -619,6 +619,15 @@ export struct BuildContext { // context is copied; the last copy releases it. Null for a planning pass // that describes (PrepareIntent::Describe), which works in its own directory. std::shared_ptr buildLock; + // THE PLAN'S LOCK (design 2026-11-27 §3.7.1, SPEC-019 `plan-locks`): held + // with `buildLock` shared when the plan has a directory of its own + // (`planStateDir`, relative to `outputDir`), so commands that select + // different members build at once. `planLocks` says which holding this + // build took, `selection` or `configuration`, and `planLocksWhy` why. + std::shared_ptr planLock; + std::filesystem::path planStateDir; + std::string planLocks = "configuration"; + std::string planLocksWhy; std::filesystem::path stdBmi; std::filesystem::path stdObject; // PrepareIntent::Describe: what the std module build WOULD be (sources are on the diff --git a/src/build/prepare/build_dir.cpp b/src/build/prepare/build_dir.cpp index 27efbdb7e..3ee58520d 100644 --- a/src/build/prepare/build_dir.cpp +++ b/src/build/prepare/build_dir.cpp @@ -172,7 +172,31 @@ std::filesystem::path renew_build_dir(const PrepareState& state, const std::file // What this configuration uses beside its directory (`mcpp clean --stale`); its // lineage and toolchain, which the next build of the configuration reads; and // the whole fingerprint, which the directory's name no longer states. -void record_build_dir(const PrepareState& state, const std::filesystem::path& outputDir) { +// A file of the directory written whole: beside it, then renamed over it, so a +// build that shares the directory never reads half of it. +void write_whole(const std::filesystem::path& file, const std::string& text) { + std::error_code ec; + auto tmp = file; + tmp += std::format(".{:x}", std::random_device{}()); + { std::ofstream(tmp, std::ios::binary | std::ios::trunc) << text; } + std::filesystem::rename(tmp, file, ec); + if (ec) std::filesystem::remove(tmp, ec); +} + +bool build_dir_needs_whole(const PrepareState& state, const std::filesystem::path& outputDir) { + namespace fs = std::filesystem; + std::error_code ec; + // A directory without a graph may be taken over from its predecessor; one + // of another toolchain is emptied; one of another fingerprint drops the + // compiler records; one whose engine link is another engine's is relinked. + if (!fs::exists(outputDir / "build.ninja", ec)) return true; + if (read_small(outputDir / "toolchain") != toolchain_text(state.fp)) return true; + if (read_small(outputDir / "fingerprint") != state.fp.hex + "\n") return true; + return !mcpp::build::graph_engine::current(outputDir, mcpp::build::cache_key::kCacheEpoch); +} + +void record_build_dir(const PrepareState& state, const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir) { std::string uses; for (auto const& h : state.usedProgramOut) uses += "out " + h + "\n"; for (auto const& g : state.usedHostGroups) uses += "host " + g + "\n"; @@ -183,18 +207,20 @@ void record_build_dir(const PrepareState& state, const std::filesystem::path& ou records.insert((state.describedStdModule->cacheDir / "std-module.json").string()); for (auto const& r : records) uses += "cache " + r + "\n"; std::error_code uec; - std::filesystem::create_directories(outputDir, uec); - std::ifstream in(outputDir / "uses.list", std::ios::binary); + // A plan of its own lists what it uses in its directory (the sweeps read + // every plan's list). + const auto usesDir = stateDir.empty() ? outputDir : outputDir / stateDir; + std::filesystem::create_directories(usesDir, uec); + std::ifstream in(usesDir / "uses.list", std::ios::binary); const std::string was{std::istreambuf_iterator(in), {}}; in.close(); // Written when it is absent too: an empty list states that nothing is used. - if (was != uses || !std::filesystem::exists(outputDir / "uses.list", uec)) - std::ofstream(outputDir / "uses.list", std::ios::binary) << uses; + if (was != uses || !std::filesystem::exists(usesDir / "uses.list", uec)) + write_whole(usesDir / "uses.list", uses); for (auto const& [name, text] : {std::pair{"lineage", lineage_text(state.fp)}, std::pair{"toolchain", toolchain_text(state.fp)}, std::pair{"fingerprint", state.fp.hex + "\n"}}) - if (read_small(outputDir / name) != text) - std::ofstream(outputDir / name, std::ios::binary) << text; + if (read_small(outputDir / name) != text) write_whole(outputDir / name, text); } } // namespace mcpp::build diff --git a/src/build/prepare/plan.cpp b/src/build/prepare/plan.cpp index 4a3e4ba83..52c0c9bcc 100644 --- a/src/build/prepare/plan.cpp +++ b/src/build/prepare/plan.cpp @@ -11,6 +11,7 @@ import std; import mcpp.diag; import mcpp.build.stage; import mcpp.build.dirlock; +import mcpp.buildopt.registry; // plan-locks: whether a plan holds a lock of its own import mcpp.build.cxx_runtime; // the C++ island (design 2026-10-26 §6.3) import mcpp.toolchain.provider; // capabilities_for: the payload's C++ runtime import mcpp.runtime.elf; // DT_NEEDED of a library the line names @@ -501,6 +502,21 @@ static void step13_dependency_debug(PrepareState& state) { mcpp::log::verbose("profile", std::format("dependency_debug = {}: {} on {} package(s)", level, flag, named.size())); } +// The request a graph is planned for (§3, §15): the members its plan builds +// (`group`), and the members the command named (`request`), each joined by a +// record separator. Empty outside a workspace. `.build_cache` keys a +// selection's entry by them, and a plan of its own is named after them. +static std::pair selection_strings(const PrepareState& state) { + if (!state.workspacePlan()) return {}; + auto join = [](const std::vector& v) { + std::string out; + for (auto const& x : v) { if (!out.empty()) out += '\x1e'; out += x; } + return out; + }; + const auto group = join(state.selectedMemberPaths); + return {state.overrides.workspace_request.empty() ? group : join(state.overrides.workspace_request), group}; +} + static std::expected step13_make_plan(PrepareState& state, BuildContext& ctx) { step13_dependency_debug(state); // An image that is not the root's links with its owner's closure's own @@ -552,16 +568,11 @@ static std::expected step13_make_plan(PrepareState& state, Bu if (auto r = scope_lto(state, ctx); !r) return std::unexpected(r.error()); // The request the graph is planned for (§3, §15): the plan's members and // the requested features, which name no directory. - if (state.workspacePlan()) { - auto join = [](const std::vector& v) { - std::string out; - for (auto const& x : v) { if (!out.empty()) out += '\x1e'; out += x; } - return out; - }; - ctx.workspaceGroup = join(state.selectedMemberPaths); - ctx.workspaceRequest = state.overrides.workspace_request.empty() - ? ctx.workspaceGroup : join(state.overrides.workspace_request); - } + if (state.workspacePlan()) + std::tie(ctx.workspaceRequest, ctx.workspaceGroup) = selection_strings(state); + // The plan's own directory, when it has one (§3.7.1). + ctx.plan.stateDir = ctx.planStateDir; + if (!ctx.planStateDir.empty()) ctx.plan.graphFile = (ctx.planStateDir / "build.ninja").generic_string(); ctx.plan.requestTag = mcpp::build::request_tag( ctx.workspaceGroup, state.workspacePlan() ? state.requestedFeatures : state.overrides.features); @@ -1897,14 +1908,81 @@ std::expected phase13_finish(PrepareState& state) { "effect denied: write-project -- the build writes {}, and the caller denied writing " "the project (--deny write-project)", ctx.outputDir.generic_string())); } - if (!state.overrides.describes()) adopt_predecessor_dir(state, ctx.outputDir); + // THE LOCKS A BUILD HOLDS (design 2026-11-27 §3.7.1, SPEC-019 `plan-locks`). + // A unit protects itself where the compiler's outputs are relocatable (it + // writes a private path and publishes it by a rename) and the unit cache + // is on (a unit two plans reach is compiled by one and placed for the + // other): the configuration's directory is then held shared and the plan, + // its selection's, exclusively, so commands that select different members + // build at once. Otherwise, or when the entry is off, the configuration is + // held alone, as it was. What the directory as a whole needs -- created, + // taken over, renewed, relinked to this engine -- is done holding it alone. + std::filesystem::path graphEngine; + { + namespace reg = mcpp::buildopt::registry; + if (!reg::on(reg::kPlanLocks, state.m->buildConfig.planLocks, [](std::string_view bad) { + mcpp::diag::warning("build", std::format( + "ignoring invalid plan_locks '{}' (expected \"selection\" or \"configuration\")", bad)); + })) + ctx.planLocksWhy = "plan-locks is off (MCPP_BUILDOPT, MCPP_PLAN_LOCKS or [build] plan_locks)"; + else if (!state.workspacePlan()) + ctx.planLocksWhy = "a package outside a workspace has one selection, whose plan is the configuration's"; + else if (state.overrides.build_program_graph) + ctx.planLocksWhy = "the build programs' workspace is planned by one build at a time"; + else if (!mcpp::toolchain::output_relocation(*state.tc).relocatable) + ctx.planLocksWhy = std::format("{} writes its outputs in place, so a unit cannot be published", + state.tc->label()); + else if (state.cacheMode == CacheMode::Off) + ctx.planLocksWhy = "the unit cache is off (--cache off), so two plans would compile one unit twice"; + else if (mcpp::build::schedule::requested_switch(*state.m) == "on") + ctx.planLocksWhy = "the split schedule is on (bmi_schedule), whose supervisors outlive their steps"; + else if (!state.m->buildConfig.actions.empty() + || std::ranges::any_of(state.packages, [](auto const& p) { return !p.manifest.buildConfig.actions.empty(); })) + ctx.planLocksWhy = "the graph runs actions, which write their outputs in place"; + else { + ctx.planLocks = "selection"; + ctx.planLocksWhy = "the compiler's outputs are relocatable and the unit cache is on"; + } + } + // A pass that only describes takes no lock and states the holding a build + // of the request would take (`mcpp why toolchain`). if (!state.overrides.describes()) { - auto lock = mcpp::build::dirlock::acquire(ctx.outputDir); - if (!lock) return std::unexpected(mcpp::build::dirlock::refused(lock.error())); - ctx.buildLock = std::move(*lock); + if (ctx.planLocks == "selection") { + const auto group = selection_strings(state).second; + ctx.planStateDir = mcpp::build::dirlock::plan_state_dir(group); + // Renewed alone, then held shared; a build of another compiler that + // renewed it in between is seen again, and this build renews it back. + for (int turn = 0; turn < 3 && !ctx.buildLock; ++turn) { + if (build_dir_needs_whole(state, ctx.outputDir)) { + adopt_predecessor_dir(state, ctx.outputDir); + auto alone = mcpp::build::dirlock::acquire(ctx.outputDir, /*shared=*/false); + if (!alone) return std::unexpected(mcpp::build::dirlock::refused(alone.error())); + graphEngine = renew_build_dir(state, ctx.outputDir); + } + auto shared = mcpp::build::dirlock::acquire(ctx.outputDir, /*shared=*/true); + if (!shared) return std::unexpected(mcpp::build::dirlock::refused(shared.error())); + if (!build_dir_needs_whole(state, ctx.outputDir)) ctx.buildLock = std::move(*shared); + } + // Renewed back each time: this build holds the directory alone. + if (!ctx.buildLock) { + auto alone = mcpp::build::dirlock::acquire(ctx.outputDir, /*shared=*/false); + if (!alone) return std::unexpected(mcpp::build::dirlock::refused(alone.error())); + graphEngine = renew_build_dir(state, ctx.outputDir); + ctx.buildLock = std::move(*alone); + } + auto plan = mcpp::build::dirlock::acquire_plan(ctx.outputDir, ctx.planStateDir, + mcpp::build::dirlock::plan_named(group)); + if (!plan) return std::unexpected(mcpp::build::dirlock::refused(plan.error())); + ctx.planLock = std::move(*plan); + if (graphEngine.empty()) graphEngine = renew_build_dir(state, ctx.outputDir); + } else { + adopt_predecessor_dir(state, ctx.outputDir); + auto lock = mcpp::build::dirlock::acquire(ctx.outputDir); + if (!lock) return std::unexpected(mcpp::build::dirlock::refused(lock.error())); + ctx.buildLock = std::move(*lock); + graphEngine = renew_build_dir(state, ctx.outputDir); + } } - std::filesystem::path graphEngine; - if (!state.overrides.describes()) graphEngine = renew_build_dir(state, ctx.outputDir); // Each step states its duration under `build/stage` in the log file, as // the phases do (build wall-time plan, W9; see prepare_build). @@ -1959,7 +2037,7 @@ std::expected phase13_finish(PrepareState& state) { return std::unexpected(r.error()); timed("report packages", [&] { step13_report_packages(state, ctx); return 0; }); // Last: what the plan used is known only now (the dependency cache's hits). - if (!state.overrides.describes()) record_build_dir(state, ctx.outputDir); + if (!state.overrides.describes()) record_build_dir(state, ctx.outputDir, ctx.planStateDir); ctx.planNotes = std::move(state.planNotes); return ctx; diff --git a/src/build/prepare/records.cpp b/src/build/prepare/records.cpp index 23e8a91ae..e6851bad9 100644 --- a/src/build/prepare/records.cpp +++ b/src/build/prepare/records.cpp @@ -11,6 +11,7 @@ import mcpp.build.stage; import mcpp.build.refusal; import mcpp.build.version_floor; import mcpp.home; +import mcpp.home.files; import mcpp.invocation; import mcpp.runtime.search; import nlohmann.json; @@ -859,7 +860,8 @@ void step13_resolution_json(PrepareState& state, BuildContext& ctx) { // from here, beside the steps record the fast path already reads. { auto summary = sources_summary(ctx.sources); - auto sp = ctx.plan.outputDir / "sources.summary"; + std::filesystem::create_directories(ctx.plan.state_dir(), ec); + auto sp = ctx.plan.state_dir() / "sources.summary"; if (summary.empty()) std::filesystem::remove(sp, ec); else if (std::ofstream so(sp); so) so << summary << "\n"; ec.clear(); @@ -870,39 +872,28 @@ void step13_resolution_json(PrepareState& state, BuildContext& ctx) { auto stampPath = ctx.plan.outputDir / "local-toolchain.stamp"; if (ctx.tc.localRoot.empty()) { std::filesystem::remove(stampPath, ec); - } else if (std::ofstream st(stampPath, std::ios::binary); st) { + } else { + // Replaced whole: plans that share the directory each write it + // (design 2026-11-27 §3.7.1), and a fast path reads it. + std::string st; auto put = [&](const std::filesystem::path& p) { std::error_code fe; const auto size = std::filesystem::file_size(p, fe); const auto time = std::filesystem::last_write_time(p, fe); // The same two spellings the fast path compares against. - st << std::format("{}", static_cast(size)) << '\t' - << std::format("{}", static_cast( - time.time_since_epoch().count())) << '\t' - << p.string() << '\n'; + st += std::format("{}\t{}\t{}\n", static_cast(size), + static_cast(time.time_since_epoch().count()), p.string()); }; put(ctx.tc.binaryPath); for (auto const& [role, p] : ctx.tc.toolOverrides) put(p); // The launcher prefixes every compile, the build programs' too // (design 2026-11-27 §3.1.1): it is one of the programs. if (!ctx.tc.launcher.empty()) put(ctx.tc.launcher); + mcpp::home::write_replacing(stampPath, st); } ec.clear(); } - auto path = ctx.plan.outputDir / "resolution.json"; - auto tmp = path; - tmp += ".tmp"; - if (std::ofstream js(tmp); js) { - js << j.dump(2) << "\n"; - js.close(); - std::filesystem::rename(tmp, path, ec); - if (ec) { - ec.clear(); - std::filesystem::remove(path, ec); - ec.clear(); - std::filesystem::rename(tmp, path, ec); - } - } + write_resolution(ctx.plan, j.dump(2) + "\n"); } } diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index b338b8333..a48551739 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -1348,7 +1348,12 @@ void adopt_predecessor_dir(const PrepareState& state, const std::filesystem::pat // made this one. std::filesystem::path renew_build_dir(const PrepareState& state, const std::filesystem::path& outputDir); // `uses.list`, `lineage` and `toolchain` in the directory. -void record_build_dir(const PrepareState& state, const std::filesystem::path& outputDir); +void record_build_dir(const PrepareState& state, const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir = {}); +// Whether a build that shares the directory has to hold it alone first: the +// directory is new or taken over, of another toolchain or fingerprint, or its +// engine link is another engine's (design 2026-11-27 §3.7.1). +bool build_dir_needs_whole(const PrepareState& state, const std::filesystem::path& outputDir); // ── The build programs' graph (mcpp#797), defined in host_graph.cpp ─────── // Compile, in one build of the build programs' graph, every program of diff --git a/src/build/result.cppm b/src/build/result.cppm index 1f0e0c24d..6bd4b95da 100644 --- a/src/build/result.cppm +++ b/src/build/result.cppm @@ -92,6 +92,10 @@ struct Record { // host's own build. std::string target = "null"; std::filesystem::path outputDir; + // The command's plan's own directory when it has one (design 2026-11-27 + // §3.7.1): the record is written there too, where no other command's + // record replaces it. Not a field of the record. + std::filesystem::path planDir; std::filesystem::path projectRoot; std::filesystem::path compileDatabase; std::vector artifacts; @@ -102,7 +106,8 @@ nlohmann::json to_json(const Launch& l); nlohmann::json to_json(const Record& r); std::optional read(const std::filesystem::path& outputDir); -// Writes `/result.json` and `/target/.last-result.json`. +// Writes `/result.json`, the plan's own copy, and +// `/target/.last-result.json`. void write(const Record& r); // A record for this process, started now. @@ -134,6 +139,11 @@ bool legs(); void write_last_of_legs(const std::filesystem::path& projectRoot, std::span outputDirs); +// The `.last-result.json` this process wrote last, empty before its first: +// commands that build one project at once (design 2026-11-27 §3.7.1) each +// replace the file, and a command reports its own records. +std::string last_written(); + } // namespace mcpp::build::result namespace mcpp::build::result { @@ -141,6 +151,13 @@ namespace mcpp::build::result { namespace { std::atomic g_events{false}; std::mutex g_emit; +std::mutex g_lastMutex; +std::string g_lastText; + +void remember_last(std::string text) { + std::lock_guard lock(g_lastMutex); + g_lastText = std::move(text); +} void write_atomically(const std::filesystem::path& file, const std::string& text) { std::error_code ec; @@ -287,7 +304,7 @@ std::string render_last(const Record& r) { {"schemaVersion", 1}, {"kind", "mcpp.last-result"}, {"kindVersion", 1}, - {"data", {{"result", (r.outputDir / "result.json").generic_string()}, + {"data", {{"result", ((r.planDir.empty() ? r.outputDir : r.planDir) / "result.json").generic_string()}, {"status", r.status}, {"finishedAt", r.finishedAt == 0 ? nlohmann::json(nullptr) : nlohmann::json(r.finishedAt)}}}, @@ -300,8 +317,13 @@ void write(const Record& r) { // mcpp is ending at a request: the record it leaves is already written. if (mcpp::run::ending()) return; write_atomically(r.outputDir / "result.json", render(r)); + if (!r.planDir.empty()) write_atomically(r.planDir / "result.json", render(r)); const auto last = r.projectRoot / "target" / ".last-result.json"; - if (!r.projectRoot.empty()) write_atomically(last, render_last(r)); + if (!r.projectRoot.empty()) { + auto text = render_last(r); + write_atomically(last, text); + remember_last(std::move(text)); + } // A running record is armed with its interrupted form: a signal that ends // the build leaves `cancelled`, not a `running` record whose process is // gone (§5.4). The end of the build disarms it. @@ -310,6 +332,7 @@ void write(const Record& r) { cancelled.status = "cancelled"; std::vector> files{ {r.outputDir / "result.json", render(cancelled)}}; + if (!r.planDir.empty()) files.emplace_back(r.planDir / "result.json", render(cancelled)); if (!r.projectRoot.empty()) files.emplace_back(last, render_last(cancelled)); mcpp::run::set_interrupt_files(files); } else { @@ -458,7 +481,14 @@ void write_last_of_legs(const std::filesystem::path& projectRoot, {"finishedAt", finishedAt == 0 ? nlohmann::json(nullptr) : nlohmann::json(finishedAt)}, {"legs", std::move(legs)}}}, }; - write_atomically(projectRoot / "target" / ".last-result.json", mcpp::wire::text(last, 2) + "\n"); + auto text = mcpp::wire::text(last, 2) + "\n"; + write_atomically(projectRoot / "target" / ".last-result.json", text); + remember_last(std::move(text)); +} + +std::string last_written() { + std::lock_guard lock(g_lastMutex); + return g_lastText; } void emit(std::string_view event, nlohmann::json fields) { diff --git a/src/build/runtime_validation.cppm b/src/build/runtime_validation.cppm index 6586ff873..1b1c987eb 100644 --- a/src/build/runtime_validation.cppm +++ b/src/build/runtime_validation.cppm @@ -112,8 +112,11 @@ latest_stored_verdict(const std::filesystem::path& targetRoot); // was validated. The returned snapshot can be compared after ninja; any // change drops to the full path, which reconstructs the search closure and // validates before reporting success/running the program. +// `stateDir`: the plan's own directory under `outputDir`, empty for none +// (design 2026-11-27 §3.7.1); the verdicts are the plan's record. std::optional validated_artifact_snapshot( const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir, const mcpp::runtime::RuntimeBinding& binding); bool artifact_snapshot_unchanged(const ArtifactSnapshot& snapshot); @@ -448,7 +451,7 @@ nlohmann::json merge_post_link(const nlohmann::json& stored, void persist_post_link(const mcpp::build::BuildPlan& plan, std::string_view name, std::string_view key, const nlohmann::json& entries) { - auto doc = read_cache(plan.outputDir); + auto doc = read_cache(plan.state_dir()); if (!doc.is_object()) doc = nlohmann::json::object(); // A key change invalidates the OTHER pass's entries too — they were derived // under the same farm and the same policy — so they go with it rather than @@ -462,7 +465,7 @@ void persist_post_link(const mcpp::build::BuildPlan& plan, if (keyMoved || doc.value(std::string(name), nlohmann::json::array()) != entries) { doc["post_link_key"] = std::string(key); doc[std::string(name)] = entries; - write_cache(plan.outputDir, doc); + write_cache(plan.state_dir(), doc); } // THE PUBLISHED COPY IS REWRITTEN UNCONDITIONALLY, and the store above is @@ -473,31 +476,16 @@ void persist_post_link(const mcpp::build::BuildPlan& plan, // `runtime.symbol_provision` absent on every warm build — the record was // correct and the documented place to read it was empty, which is the // failure this whole change exists to remove, moved one file over. - const auto path = plan.outputDir / "resolution.json"; nlohmann::json resolution; { - std::ifstream input(path); + std::ifstream input(plan.resolution_record()); resolution = nlohmann::json::parse(input, nullptr, false); } if (resolution.is_discarded() || !resolution.is_object()) return; auto runtime = resolution.find("runtime"); if (runtime == resolution.end() || !runtime->is_object()) return; (*runtime)[std::string(name)] = entries; - - std::error_code ec; - auto tmp = path; - tmp += ".tmp"; - if (std::ofstream output(tmp); output) { - output << resolution.dump(2) << '\n'; - output.close(); - std::filesystem::rename(tmp, path, ec); - if (ec) { - ec.clear(); - std::filesystem::remove(path, ec); - ec.clear(); - std::filesystem::rename(tmp, path, ec); - } - } + mcpp::build::write_resolution(plan, resolution.dump(2) + "\n"); } std::vector @@ -677,8 +665,7 @@ void store_artifact(nlohmann::json& doc, void sync_resolution_verdict(const mcpp::build::BuildPlan& plan, const nlohmann::json& cache) { - const auto path = plan.outputDir / "resolution.json"; - std::ifstream input(path); + std::ifstream input(plan.resolution_record()); auto resolution = nlohmann::json::parse(input, nullptr, false); if (resolution.is_discarded() || !resolution.is_object()) return; auto runtime = resolution.find("runtime"); @@ -719,21 +706,8 @@ void sync_resolution_verdict(const mcpp::build::BuildPlan& plan, {"contract_hash", plan.runtimeBinding.contractHash}, {"artifacts", std::move(checked)}, }; - - std::error_code ec; - auto tmp = path; - tmp += ".tmp"; - if (std::ofstream output(tmp); output) { - output << resolution.dump(2) << '\n'; - output.close(); - std::filesystem::rename(tmp, path, ec); - if (ec) { - ec.clear(); - std::filesystem::remove(path, ec); - ec.clear(); - std::filesystem::rename(tmp, path, ec); - } - } + input.close(); + mcpp::build::write_resolution(plan, resolution.dump(2) + "\n"); } } // namespace @@ -758,7 +732,7 @@ ArtifactSnapshot snapshot_link_artifacts(const mcpp::build::BuildPlan& plan) { // validated artifact snapshot is recorded for this build"). void record_without_rules(const mcpp::build::BuildPlan& plan, const ArtifactSnapshot& before) { - auto doc = read_cache(plan.outputDir); + auto doc = read_cache(plan.state_dir()); bool changed = false; if (doc.value("schema", 0) != kValidationSchema || doc.value("contract_hash", "") != plan.runtimeBinding.contractHash) { @@ -782,7 +756,7 @@ void record_without_rules(const mcpp::build::BuildPlan& plan, store_artifact(doc, key, fp, v); changed = true; } - if (changed) write_cache(plan.outputDir, doc); + if (changed) write_cache(plan.state_dir(), doc); } std::vector dlopen_unreachable(const mcpp::build::BuildPlan& plan, @@ -868,7 +842,7 @@ ValidationReport validate_changed_artifacts( return report; } - auto doc = read_cache(plan.outputDir); + auto doc = read_cache(plan.state_dir()); bool changedCache = false; if (doc.value("schema", 0) != kValidationSchema || doc.value("contract_hash", "") != plan.runtimeBinding.contractHash) { @@ -973,15 +947,16 @@ ValidationReport validate_changed_artifacts( changedCache = true; report.artifacts.push_back(std::move(validated)); } - if (changedCache) write_cache(plan.outputDir, doc); + if (changedCache) write_cache(plan.state_dir(), doc); sync_resolution_verdict(plan, doc); return report; } std::optional validated_artifact_snapshot( const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir, const mcpp::runtime::RuntimeBinding& binding) { - auto doc = read_cache(outputDir); + auto doc = read_cache(stateDir.empty() ? outputDir : outputDir / stateDir); if (doc.value("schema", 0) != kValidationSchema || doc.value("contract_hash", "") != binding.contractHash) return std::nullopt; @@ -1064,7 +1039,7 @@ check_and_record_loader_tags(const mcpp::build::BuildPlan& plan, const auto key = post_link_key(plan); const auto recorded = - stored_post_link(read_cache(plan.outputDir), kLoaderTagsRecord, key); + stored_post_link(read_cache(plan.state_dir()), kLoaderTagsRecord, key); auto recorded_entry = [&](const std::string& rel) -> const nlohmann::json* { for (auto const& e : recorded) if (e.is_object() && e.value("path", "") == rel) return &e; @@ -1183,7 +1158,7 @@ check_symbol_provision(const mcpp::build::BuildPlan& plan, // of an entry would read exactly like "checked and clean". const auto key = post_link_key(plan); const auto recorded = - stored_post_link(read_cache(plan.outputDir), kSymbolProvisionRecord, key); + stored_post_link(read_cache(plan.state_dir()), kSymbolProvisionRecord, key); auto stored_for = [&](const std::string& rel) -> const nlohmann::json* { for (auto const& entry : recorded) if (entry.is_object() && entry.value("path", "") == rel) return &entry; @@ -1509,6 +1484,10 @@ latest_stored_verdict(const std::filesystem::path& targetRoot) { } if (!found) return std::nullopt; auto doc = read_cache(newest.parent_path()); + // The keys are relative to the output directory; a plan's record sits two + // levels below it, in `plans/` (design 2026-11-27 §3.7.1). + auto base = newest.parent_path(); + if (base.parent_path().filename() == "plans") base = base.parent_path().parent_path(); auto artifacts = doc.find("artifacts"); if (artifacts == doc.end() || !artifacts->is_object()) return std::nullopt; @@ -1522,7 +1501,7 @@ latest_stored_verdict(const std::filesystem::path& targetRoot) { const bool worse = status == Status::ProvenMismatch || (status == Status::Inconclusive && summary.verdict.status == Status::Pass); if (!worse && !summary.artifact.empty()) continue; - summary.artifact = newest.parent_path() / it.key(); + summary.artifact = base / it.key(); summary.verdict.status = status; summary.verdict.diagnostics = it.value().value( "diagnostics", std::vector{}); @@ -1562,7 +1541,7 @@ check_dlopen_surface(const mcpp::build::BuildPlan& plan) { // already cleared the record before this runs. auto publish_reason = [&](std::string_view why) { const auto key = post_link_key(plan); - auto doc = read_cache(plan.outputDir); + auto doc = read_cache(plan.state_dir()); if (doc.is_object() && doc.value("post_link_key", "") == key) { auto it = doc.find(std::string(kDlopenSurfaceRecord)); if (it != doc.end() && it->is_object() && !it->contains("reason")) { diff --git a/src/build/schedule/compiler_transaction.cpp b/src/build/schedule/compiler_transaction.cpp index 33441c846..59d5e089d 100644 --- a/src/build/schedule/compiler_transaction.cpp +++ b/src/build/schedule/compiler_transaction.cpp @@ -127,8 +127,19 @@ std::expected admit_cached_outputs(const fs::path& output_dire if(ec)return std::unexpected("cannot enumerate cached compiler outputs"); // Invalidation removes its certificate. Finish enumeration first so those // removals cannot change which other cached objects this admission checks. - for(const auto& path:certificates) + for(const auto& path:certificates) { + // A unit another plan holds is being compiled now (design 2026-11-27 + // §3.7.1): what it leaves is that plan's to settle, not an interrupted + // build's. + const auto name=spelling(path.filename()); + const auto object=name.substr(0,name.size()-std::string_view(".sched.completed").size()); + std::optional idle; + if(fs::exists(path.parent_path()/(object+".mcpp-unit.lock"),ec)) { + idle=mcpp::home::FileLock::try_acquire(path.parent_path(),object+".mcpp-unit.lock"); + if(!idle)continue; + } if(auto admitted=admit_completed(path,output_directory);!admitted)return admitted; + } return {}; } } // namespace mcpp::build::schedule::transaction diff --git a/src/build/schedule/detach_codegen.cppm b/src/build/schedule/detach_codegen.cppm index d323e96a2..b582156ba 100644 --- a/src/build/schedule/detach_codegen.cppm +++ b/src/build/schedule/detach_codegen.cppm @@ -113,7 +113,11 @@ std::expected retire_compiler_runs(const std::filesystem::pat class RunScope { public: - static std::expected begin(const std::filesystem::path& outputDir, int compilerCap); + // `stateDir`: the plan's directory, the output directory when the plan has + // none of its own (design 2026-11-27 §3.7.1). A plan's runs, their gate and + // their attempts are its own; the outputs they admit are the directory's. + static std::expected begin(const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir, int compilerCap); RunScope(RunScope&&) noexcept; RunScope& operator=(RunScope&&) noexcept; ~RunScope(); @@ -813,6 +817,12 @@ 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)); +} + struct RunsLocation { std::filesystem::path canonical, work, root; }; std::expected locate_runs(const std::filesystem::path& outputDir) { std::error_code ec; @@ -828,22 +838,46 @@ std::expected locate_runs(const std::filesystem::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.root = at.work / ".mcpp" / "compiler-runs" / mcpp::toolchain::hash_string(mcpp::home::spelling(at.canonical)); + at.root = runs_root(at.work, at.canonical); return at; } + +// The runs of a plan with a directory of its own (design 2026-11-27 §3.7.1), +// apart from the configuration's: named after the plan's directory as the +// configuration's are after its own. +std::filesystem::path plan_runs_root(const RunsLocation& at, const std::filesystem::path& relative) { + return runs_root(at.work, (at.canonical / relative).lexically_normal()); +} + +std::expected retire_runs_at(const std::filesystem::path& root, + const std::filesystem::path& outputDir); } // namespace +// The configuration's runs and every plan's. std::expected retire_compiler_runs(const std::filesystem::path& outputDir) { auto located = locate_runs(outputDir); if (!located) return std::unexpected(located.error()); + if (auto retired = retire_runs_at(located->root, outputDir); !retired) return retired; std::error_code ec; - if (!std::filesystem::is_directory(located->root, ec)) return {}; - auto gate = mcpp::home::FileLock::acquire(located->root, "gate.lock", + for (std::filesystem::directory_iterator plan(outputDir / "plans", ec), end; !ec && plan != end; plan.increment(ec)) + if (auto retired = retire_runs_at(plan_runs_root(*located, std::filesystem::path("plans") / plan->path().filename()), + outputDir); + !retired) + return retired; + return {}; +} + +namespace { +std::expected retire_runs_at(const std::filesystem::path& root, + const std::filesystem::path& outputDir) { + std::error_code ec; + if (!std::filesystem::is_directory(root, ec)) return {}; + auto gate = mcpp::home::FileLock::acquire(root, "gate.lock", {.resource = std::format("the compiler runs of {}", mcpp::home::spelling(outputDir)), .doing = "cleaning the compiler runs"}); if (!gate) return std::unexpected(std::format("{}; {} was not cleaned [{}]", gate.error().message(), mcpp::home::spelling(outputDir), gate.error().token())); - std::filesystem::directory_iterator runs(located->root, ec); + std::filesystem::directory_iterator runs(root, ec); if (ec) return std::unexpected("cannot inspect the compiler runs of " + mcpp::home::spelling(outputDir)); for (const auto& entry : runs) { if (!entry.path().filename().native().starts_with(std::filesystem::path("run-").native())) continue; @@ -858,11 +892,13 @@ std::expected retire_compiler_runs(const std::filesystem::pat } if (auto retired = retire_generation(entry.path()); !retired) return std::unexpected(retired.error()); } - sweep_retired(located->root); + sweep_retired(root); return {}; } +} // namespace -std::expected RunScope::begin(const std::filesystem::path& outputDir, int compilerCap) { +std::expected RunScope::begin(const std::filesystem::path& outputDir, + const std::filesystem::path& stateDir, int compilerCap) { if (compilerCap <= 0) return std::unexpected("a compiler-run generation needs a compiler cap"); const auto self = mcpplibs::os::process::self(); if (!self || self->id == 0 || self->started_ns == 0) @@ -871,6 +907,12 @@ std::expected RunScope::begin(const std::filesystem::path auto located = locate_runs(outputDir); if (!located) return std::unexpected(located.error()); const auto canonical = located->canonical; + // A PLAN OF ITS OWN (design 2026-11-27 §3.7.1): its runs are kept, gated + // and recovered apart from another plan's, and its attempts swept alone. + const auto rel = stateDir.lexically_normal().lexically_relative(outputDir.lexically_normal()); + const bool ownPlan = !stateDir.empty() && !rel.empty() && rel != "." && *rel.begin() != ".."; + const auto stateCanonical = ownPlan ? (canonical / rel).lexically_normal() : canonical; + if (ownPlan) located->root = plan_runs_root(*located, rel); auto state = std::make_unique(); mcpp::home::mark_project_state(located->work / ".mcpp"); state->root = located->root; @@ -915,7 +957,7 @@ std::expected RunScope::begin(const std::filesystem::path // no Ninja reader from this generation has started yet. // What the recovered attempts wrote below themselves goes with them // (§10.6); a file an orphan still holds stays until a later build. - relocation::sweep(canonical); + relocation::sweep(stateCanonical); if(auto admitted=transactions::admit_cached_outputs(canonical);!admitted) return std::unexpected(admitted.error()); // WHETHER A UNIT CAN BE DECLARED HERE IS A PROPERTY OF THE ENVIRONMENT @@ -1664,6 +1706,23 @@ int run_capped(const std::vector& argv, auto ended=[&](int status,std::string_view step,std::string_view why) { std::println(std::cerr,"mcpp: {} for {}: {}",step,out_name,why);return status; }; + // A PLAN OF ITS OWN (its semaphore below `plans//`, design 2026-11-27 + // §3.7.1): the attempts are the plan's, and the unit is held while it is + // compiled and published, since another plan may reach it at the same time; + // the second finds it in the unit cache and places it. + std::optional unitHeld; + if (!semaphore.parent_path().empty()) { + relocation::set_attempts_base(semaphore.parent_path()); + if (!output.empty()) { + std::error_code uec; + std::filesystem::create_directories(output.parent_path(), uec); + auto lock = mcpp::home::FileLock::acquire(output.parent_path(), output.filename().string() + ".mcpp-unit.lock", + {.resource = std::format("the unit {}", out_name), .doing = "compiling it"}); + if (!lock) + return ended(1, "holding the unit", std::format("{} [{}]", lock.error().message(), lock.error().token())); + unitHeld.emplace(std::move(*lock)); + } + } // THE ATTEMPT'S OWN PATHS (§10.6), decided before anything of the // compile is held or recorded. std::vector command = argv; diff --git a/src/build/schedule/relocation.cppm b/src/build/schedule/relocation.cppm index 0c8572759..6095c1e6b 100644 --- a/src/build/schedule/relocation.cppm +++ b/src/build/schedule/relocation.cppm @@ -69,8 +69,13 @@ struct Plan { bool relocated() const { return !outputs.empty(); } }; -// The attempt's directory for an attempt name. +// The attempt's directory for an attempt name: `.mcpp-attempts/`, below +// the plan's directory when the plan has one (`set_attempts_base`, design +// 2026-11-27 §3.7.1), so a run sweeps the attempts of its own plan alone. std::filesystem::path attempt_directory(std::string_view attempt); +// The directory, relative to the build directory, whose `.mcpp-attempts` this +// process's attempts are in: the directory of the plan's semaphore. +void set_attempts_base(const std::filesystem::path& base); // Rewrites `argv` (or one shell command line, whose words are separated by // spaces) for the attempt `attempt`, with the auxiliary-name words of @@ -337,8 +342,17 @@ std::expected publish_one(const Plan& plan, const Output& o) } // namespace +namespace { +fs::path& attempts_base() { + static fs::path base; + return base; +} +} // namespace + +void set_attempts_base(const fs::path& base) { attempts_base() = base; } + fs::path attempt_directory(std::string_view attempt) { - return fs::path{std::string(kAttempts)} / std::string(attempt); + return attempts_base() / std::string(kAttempts) / std::string(attempt); } std::vector aux_words(std::string_view auxNaming, std::string_view object) { diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index 107483079..fbe6b3805 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -360,8 +360,13 @@ export int cmd_build(const mcpplibs::cmdline::ParsedArgs& parsed) { env.data = nullptr; std::error_code ec; if (auto root = mcpp::project::find_manifest_root(std::filesystem::current_path(ec))) { - std::ifstream in(*root / "target" / ".last-result.json", std::ios::binary); - auto last = nlohmann::json::parse(in, nullptr, false); + // This process's own, when it wrote one: another command of the + // project may have replaced the file since. + auto last = [&] { + if (auto text = res::last_written(); !text.empty()) return nlohmann::json::parse(text, nullptr, false); + std::ifstream in(*root / "target" / ".last-result.json", std::ios::binary); + return nlohmann::json::parse(in, nullptr, false); + }(); // The record this process wrote, at `path`; null otherwise. auto record_of = [](const std::filesystem::path& recordPath) -> nlohmann::json { if (auto record = res::read(recordPath.parent_path()); @@ -493,8 +498,9 @@ int build_several_legs(const mcpplibs::cmdline::ParsedArgs& parsed, }); mcpp::build::result::set_legs(false); rc = L::first_failure(results); + // Each leg's own record: its plan's copy when the plan has a directory. std::vector dirs; - for (auto* c : contexts) dirs.push_back(c->outputDir); + for (auto* c : contexts) dirs.push_back(c->plan.state_dir()); mcpp::build::result::write_last_of_legs(contexts.front()->projectRoot, dirs); } mcpp::build::publish_workspace_compile_commands(root, firstDirs, rootDb); @@ -1919,9 +1925,9 @@ export int cmd_dyndep(const mcpplibs::cmdline::ParsedArgs& parsed) { std::ifstream in(outPath, std::ios::binary); if (in && std::string(std::istreambuf_iterator(in), {}) == *body) return 0; } - std::ofstream os(outPath, std::ios::binary); - os << *body; - return os ? 0 : 1; + // Replaced whole: two plans that share the directory may bind one unit at + // once (design 2026-11-27 §3.7.1), and the other's ninja reads the file. + return mcpp::home::write_replacing(outPath, *body) ? 0 : 1; } // Invoked by ninja during build (stage_file rule): @@ -1949,10 +1955,12 @@ export int cmd_dyndep(const mcpplibs::cmdline::ParsedArgs& parsed) { // nothing holds any more are deleted here. A process started while the linker // writes fails to start (file not found, sharing violation) -- Windows never // starts an image that is being written -- rather than running half of one. -// On POSIX (`--temporary`) the linker writes `/.` -- the -// argument after its `-o`, renamed; the name keeps its extension, as a driver -// that names a file after it writes a second one otherwise (design 2026-11-15 -// N9) -- and the file is renamed over the artifact once the linker succeeds: a +// On POSIX (`--temporary`) the linker writes `/..` +// -- the argument after its `-o`, or an archiver's word that is the artifact, +// renamed; the name keeps its extension, as a driver that names a file after +// it writes a second one otherwise (design 2026-11-15 N9), and the process's +// own, as two plans may link one artifact at once (design 2026-11-27 §3.7.1) +// -- and the file is renamed over the artifact once the linker succeeds: a // rename replaces a running program there, and a program started meanwhile // never meets a partial file. The publication is one command, so an edge that // holds a permit for the link holds it until the artifact is in place. @@ -1978,7 +1986,9 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, }; const fs::path out = parsed.option_or_empty("output").value(); if (out.empty() || given.empty()) return fail(" needs --output -- ", 2); - std::vector expanded(given.begin(), given.end()); + // The commands to run: the one given, or, with `--expand`, one per batch + // of the response file's words the host's command line holds. + std::vector> commands{std::vector(given.begin(), given.end())}; if (parsed.is_flag_set("expand")) { std::vector head, members, tail; bool seen = false; @@ -1993,10 +2003,7 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, } (seen ? tail : head).push_back(word); } - // The host's limit, with room for the environment: cmd.exe and - // CreateProcess take 32 767 characters; a POSIX argument list takes - // far more, and one argument at most 128 KiB. - constexpr std::size_t kLine = mcpplibs::os::is_windows ? 30000 : 131072; + const std::size_t kLine = mcpp::build::command_line::host_line_limit(); std::size_t fixed = 0; for (auto const& w : head) fixed += w.size() + 1; for (auto const& w : tail) fixed += w.size() + 1; @@ -2010,24 +2017,15 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, used += m.size() + 1; batches.back().push_back(std::move(m)); } - auto argv_of = [&](const std::vector& batch) { + commands.clear(); + for (auto const& batch : batches) { std::vector argv = head; argv.insert(argv.end(), batch.begin(), batch.end()); argv.insert(argv.end(), tail.begin(), tail.end()); - return argv; - }; - if (batches.size() > 1) { - for (auto const& batch : batches) - if (const int rc = mcpp::run::execute(argv_of(batch), {.input = mcpp::run::Input::inherit, - .streams = mcpp::run::Streams::inherit}) - .exit_code; - rc != 0) - return rc; - return 0; + commands.push_back(std::move(argv)); } - expanded = argv_of(batches.front()); } - const std::span command(expanded); + const std::span command(commands.front()); const std::string text = parsed.option_or_empty("text").value(); if (!text.empty() && text != "console") return fail(std::format(": --text takes `console`, not `{}`", text), 2); // The linker, on this program's streams or through the decoding pipe. @@ -2052,23 +2050,31 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, companion.replace_extension(std::string(std::string_view(part.begin(), part.end()))); fs::remove(companion, ec); } - // Moved aside when the edge asks (`--aside`, a Windows host, where a - // running program's file cannot be overwritten). An edge that reaches here - // for its companions alone does not: an aside file would be named like a - // companion (`app.js.old-1`). + // THROUGH A TEMPORARY NAME OF THIS PROCESS'S OWN (`/..`), + // renamed over the artifact: a program starting sees the old file or the + // new one, and two plans that link one artifact at once (design 2026-11-27 + // §3.7.1) each write their own file. A linker's output follows `-o`; an + // archiver's is the word that is the artifact, and its archive is then + // written whole rather than updated in place. if (parsed.is_flag_set("temporary")) { - std::vector argv(command.begin(), command.end()); - const auto temporary = out.parent_path() / ("." + out.filename().string()); - auto named = std::ranges::adjacent_find(argv, [&](const std::string& a, const std::string& b) { - return a == "-o" && fs::path(b) == out; - }); - if (named == argv.end()) - return fail(std::format(" --temporary: the linker command names no `-o {}`", out.string()), 2); - *std::next(named) = temporary.string(); - if (const int linked = run_linker(argv); linked != 0) { - fs::remove(temporary, ec); - return linked; - } + const auto temporary = out.parent_path() + / std::format(".{}.{}{}", out.stem().string(), mcpp::invocation::process_id(), out.extension().string()); + for (auto& argv : commands) { + auto named = std::ranges::adjacent_find(argv, [&](const std::string& a, const std::string& b) { + return a == "-o" && fs::path(b) == out; + }); + auto word = named != argv.end() ? std::next(named) + : std::ranges::find_if(argv.begin() + 1, argv.end(), [&](const std::string& w) { return fs::path(w) == out; }); + if (word == argv.end()) + return fail(std::format(" --temporary: the command names no `-o {0}` and no `{0}`", out.string()), 2); + *word = temporary.string(); + } + fs::remove(temporary, ec); + for (auto const& argv : commands) + if (const int linked = run_linker(argv); linked != 0) { + fs::remove(temporary, ec); + return linked; + } fs::rename(temporary, out, ec); if (ec) { const auto why = std::format(": cannot rename {} over {}: {}", temporary.string(), out.string(), @@ -2078,6 +2084,11 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, } return 0; } + if (commands.size() > 1) { + for (auto const& argv : commands) + if (const int rc = run_linker(argv); rc != 0) return rc; + return 0; + } if (!parsed.is_flag_set("aside")) { if (!text.empty()) return run_linker(std::vector(command.begin(), command.end())); return mcpp::run::run_exec(std::vector(command.begin(), command.end())); diff --git a/src/doctor.cppm b/src/doctor.cppm index d81ed4b63..c327d53ae 100644 --- a/src/doctor.cppm +++ b/src/doctor.cppm @@ -1642,7 +1642,7 @@ export int why_records_json(std::string_view topic, const std::string& features) .message = ctx.error()}); if (topic == "compat") data["uses"] = compat_uses_json(); else if (topic == "features") - data["packages"] = ctx ? graph_features_json(ctx->plan.outputDir / "resolution.json") + data["packages"] = ctx ? graph_features_json(ctx->plan.resolution_record()) : nlohmann::json::array(); else data["graphs"] = ctx ? build_programs_json(ctx->projectRoot) : nlohmann::json::array(); mcpp::wire::emit({ @@ -1727,7 +1727,7 @@ export int why_report(const std::string& topic, const std::string& features, // which are its defaults, and which this build activates. if (topic == "features") { std::println("features:"); - for (auto const& p : graph_features_json(ctx->plan.outputDir / "resolution.json")) { + for (auto const& p : graph_features_json(ctx->plan.resolution_record())) { std::println(" {}{}", p["package"].value("canonical", std::string("?")), p.value("root", false) ? " (root)" : ""); auto const& f = p["features"]; @@ -1811,6 +1811,9 @@ export int why_report(const std::string& topic, const std::string& features, } } for (auto const& f : tc.treeFacts) std::println(" {}: {}", f.name, f.value); + // Which locks a build of this request holds, and why (design + // 2026-11-27 §3.7.1, SPEC-019 `plan-locks`). + std::println(" plan locks: {} ({})", ctx->planLocks, ctx->planLocksWhy); if (!ctx->manifest.package.platforms.empty()) { std::string ps; for (auto& p : ctx->manifest.package.platforms) { @@ -1934,7 +1937,7 @@ export int why_report(const std::string& topic, const std::string& features, // dependency, which `mcpp.lock` does not record, is listed too. std::println("dependency graph:"); { - const auto recordPath = ctx->plan.outputDir / "resolution.json"; + const auto recordPath = ctx->plan.resolution_record(); std::ifstream record(recordPath); auto doc = record ? nlohmann::json::parse(record, nullptr, false) : nlohmann::json{}; diff --git a/src/native/posix/command_line.cpp b/src/native/posix/command_line.cpp new file mode 100644 index 000000000..49372aea0 --- /dev/null +++ b/src/native/posix/command_line.cpp @@ -0,0 +1,12 @@ +// The command line a POSIX host starts a program with. +module mcpp.build.command_line; + +import std; + +namespace mcpp::build::command_line { + +// One argument may hold at most 128 KiB (MAX_ARG_STRLEN on Linux); the list as a +// whole takes far more, so a batch of this size leaves room for the environment. +std::size_t host_line_limit() { return 131072; } + +} // namespace mcpp::build::command_line diff --git a/src/native/windows/command_line.cpp b/src/native/windows/command_line.cpp new file mode 100644 index 000000000..104636133 --- /dev/null +++ b/src/native/windows/command_line.cpp @@ -0,0 +1,12 @@ +// The command line a Windows host starts a program with. +module mcpp.build.command_line; + +import std; + +namespace mcpp::build::command_line { + +// CreateProcess and cmd.exe take 32 767 characters, the program's name included; +// the rest is room for what the caller adds before the words. +std::size_t host_line_limit() { return 30000; } + +} // namespace mcpp::build::command_line diff --git a/src/pack/distribution.cppm b/src/pack/distribution.cppm index e82782f9e..2df8603a8 100644 --- a/src/pack/distribution.cppm +++ b/src/pack/distribution.cppm @@ -18,6 +18,7 @@ import mcpp.pack.zip; 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.toolchain.target_rows; // the system table: `uname -s` words (N20) +import mcpp.toolchain.platform; // a system's key in a descriptor (`macosx`) 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 mcpplibs.os; @@ -1874,7 +1875,8 @@ std::expected library_descriptor(const std::vector cached; - std::set compiledPackages; - std::vector compiledOutputs; // ` `, for the failure's message -}; - -bool compiles(std::string_view output) { - for (auto ext : {".o", ".obj", ".gcm", ".pcm", ".ifc"}) - if (output.ends_with(ext)) return true; - return false; -} - -Built read_record(const fs::path& file) { - Built b; - for (const auto& line : s::json_lines(s::read_file(file))) { - if (line.value("cached", false)) { - b.cached[line.value("package", "")] += line.value("units", std::size_t{0}); - continue; - } - // A unit the unit cache placed (`served`) or copied for a package the cache served - // (`staged`) ran no compiler. - if (compiles(line.value("output", "")) && !line.value("served", false) && !line.value("staged", false)) { - ++b.compiled; - b.compiledPackages.insert(line.value("package", "")); - b.compiledOutputs.push_back(line.value("package", "") + " " + line.value("output", "")); - } - } - return b; -} - -// mcpp in `p` with its build record written to a file of the case: what the build did. -std::pair recorded(const s::project& p, std::vector args, std::string_view name) { - const auto file = s::case_dir() / std::format("record-{}.ndjson", name); - std::error_code ec; - fs::remove(file, ec); - auto r = p.mcpp(std::move(args), {.env = {{"MCPP_BUILD_RECORD", file.string()}}}); - return {r, read_record(file)}; -} +using s::recorded; E2E invariants{"invariants", s::home_fixture, [] { "1121 an unchanged project builds again with no compile"_test[s::gcc][at_most{"edges.compiled", 0}] = [] { @@ -63,10 +24,10 @@ E2E invariants{"invariants", s::home_fixture, [] { auto p = s::project::scaffold("same"); auto [first, built] = recorded(p, {"build"}, "first"); expect(fatal(e2e::succeeded(first))) << s::text(first); - expect(fatal(gt(built.compiled, std::size_t{0}))) << "the first build compiled nothing: its record is empty"; + expect(fatal(gt(built.compiled.size(), std::size_t{0}))) << "the first build compiled nothing: its record is empty"; auto [again, rebuilt] = recorded(p, {"build"}, "again"); expect(fatal(e2e::succeeded(again))) << s::text(again); - metric("edges.compiled", static_cast(rebuilt.compiled), "edges"); + metric("edges.compiled", static_cast(rebuilt.compiled.size()), "edges"); }; "1176 a build with no edit after an edit of a module compiles nothing"_test[at_most{"edges.compiled", 0}] = [] { @@ -87,13 +48,13 @@ E2E invariants{"invariants", s::home_fixture, [] { p.write("src/c.cppm", "export module c;\nexport int cv() { return 3; }\n"); auto [edit, edited] = recorded(p, {"build"}, "edit"); expect(fatal(e2e::succeeded(edit))) << s::text(edit); - expect(fatal(gt(edited.compiled, std::size_t{0}))) << "the edit compiled nothing"; + expect(fatal(gt(edited.compiled.size(), std::size_t{0}))) << "the edit compiled nothing"; auto [again, rebuilt] = recorded(p, {"build"}, "again"); expect(fatal(e2e::succeeded(again))) << s::text(again); std::string compiled; - for (auto const& o : rebuilt.compiledOutputs) compiled += "\n " + o; - expect(eq(rebuilt.compiled, std::size_t{0})) << "a build with no edit compiled:" << compiled; - metric("edges.compiled", static_cast(rebuilt.compiled), "edges"); + for (auto const& o : rebuilt.compiled) compiled += "\n " + o; + expect(eq(rebuilt.compiled.size(), std::size_t{0})) << "a build with no edit compiled:" << compiled; + metric("edges.compiled", static_cast(rebuilt.compiled.size()), "edges"); }; "1122 a dev-dependency is served from the cache to a second project"_test[s::gcc][at_most{"edges.compiled.dependency", 1}] = [] { @@ -109,7 +70,7 @@ E2E invariants{"invariants", s::home_fixture, [] { expect(fatal(e2e::succeeded(second))) << s::text(second); std::size_t dependency = 0; std::string compiled; - for (const auto& edge : rebuilt.compiledOutputs) + for (const auto& edge : rebuilt.compiled) if (edge.contains("mtest")) { ++dependency; compiled += "\n " + edge; } expect(le(dependency, std::size_t{1})) << "the second project compiled the dev-dependency:" << compiled << "\n" << s::text(second); diff --git a/tests/e2e/cli/terminal.cpp b/tests/e2e/cli/terminal.cpp index a4dc0706d..02bb42e0a 100644 --- a/tests/e2e/cli/terminal.cpp +++ b/tests/e2e/cli/terminal.cpp @@ -10,99 +10,6 @@ namespace fs = std::filesystem; namespace { -std::u32string decode(std::string_view b) { - std::u32string out; - for (std::size_t i = 0; i < b.size();) { - const auto c = static_cast(b[i]); - const int n = c < 0x80 ? 1 : (c >> 5) == 6 ? 2 : (c >> 4) == 14 ? 3 : (c >> 3) == 30 ? 4 : 0; - if (n == 0 || i + n > b.size()) { - out.push_back(0xfffd); - ++i; - continue; - } - char32_t cp = n == 1 ? c : c & (0x7f >> n); - for (int k = 1; k < n; ++k) cp = (cp << 6) | (static_cast(b[i + k]) & 0x3f); - out.push_back(cp); - i += n; - } - return out; -} - -std::string encode(std::u32string_view s) { - std::string out; - for (char32_t c : s) { - if (c < 0x80) { - out.push_back(static_cast(c)); - } else if (c < 0x800) { - out.push_back(static_cast(0xc0 | (c >> 6))); - out.push_back(static_cast(0x80 | (c & 0x3f))); - } else if (c < 0x10000) { - out.push_back(static_cast(0xe0 | (c >> 12))); - out.push_back(static_cast(0x80 | ((c >> 6) & 0x3f))); - out.push_back(static_cast(0x80 | (c & 0x3f))); - } else { - out.push_back(static_cast(0xf0 | (c >> 18))); - out.push_back(static_cast(0x80 | ((c >> 12) & 0x3f))); - out.push_back(static_cast(0x80 | ((c >> 6) & 0x3f))); - out.push_back(static_cast(0x80 | (c & 0x3f))); - } - } - return out; -} - -// The screen the terminal shows after `bytes`: carriage return, line feed, cursor up (`CSI n A`), -// erase to the end of the screen (`CSI J`) and of the line (`CSI K`); colour is ignored. Rows -// without their trailing blanks. -std::vector screen_of(std::string_view bytes) { - const auto s = decode(bytes); - std::vector rows{U""}; - std::size_t r = 0, c = 0, i = 0; - while (i < s.size()) { - const char32_t ch = s[i]; - if (ch == 0x1b && i + 1 < s.size() && s[i + 1] == U'[') { - std::size_t j = i + 2; - while (j < s.size() && !(s[j] >= U'@' && s[j] <= U'~')) ++j; - const std::u32string params = s.substr(i + 2, j - (i + 2)); - const char32_t final = j < s.size() ? s[j] : 0; - const bool digits = !params.empty() && std::ranges::all_of(params, [](char32_t d) { return d >= U'0' && d <= U'9'; }); - std::size_t n = 1; - if (digits) { - n = 0; - for (char32_t d : params) n = n * 10 + (d - U'0'); - } - if (final == U'A') { - r = r >= n ? r - n : 0; - } else if (final == U'J') { - rows[r] = rows[r].substr(0, c); - rows.erase(rows.begin() + static_cast(r) + 1, rows.end()); - } else if (final == U'K') { - rows[r] = params == U"2" ? U"" : rows[r].substr(0, c); - } - i = j + 1; - continue; - } - if (ch == U'\r') { - c = 0; - } else if (ch == U'\n') { - ++r; - while (rows.size() <= r) rows.emplace_back(); - } else { - auto& line = rows[r]; - if (line.size() < c) line.resize(c, U' '); - if (line.size() == c) line.push_back(ch); - else line[c] = ch; - ++c; - } - ++i; - } - std::vector out; - for (auto& row : rows) { - while (!row.empty() && (row.back() == U' ' || row.back() == U'\t')) row.pop_back(); - out.push_back(encode(row)); - } - return out; -} - bool matches(const std::string& text, std::string_view pattern) { return std::regex_search(text, std::regex{std::string(pattern)}); } @@ -110,7 +17,7 @@ bool matches(const std::string& text, std::string_view pattern) { // A run of `n` braille cells (U+2800..U+28FF). bool braille_run(std::string_view text, std::size_t n) { std::size_t run = 0; - for (char32_t c : decode(text)) { + for (char32_t c : s::decode_utf8(text)) { run = (c >= 0x2800 && c <= 0x28ff) ? run + 1 : 0; if (run >= n) return true; } @@ -245,7 +152,7 @@ E2E terminal{"terminal", s::home_fixture, [] { const int status = proc.wait(); const auto& text = proc.terminal(); const auto plain = s::strip_escapes(text); - const auto screen = screen_of(text); + const auto screen = s::screen_of(text); expect(fatal(status == 0)) << "the build failed\n" << plain; expect(fatal(matches(plain, R"(app: app:install \d+:\d\d)"))) << "T1: no status line named the running action\n" << plain; std::optional at; @@ -264,7 +171,7 @@ E2E terminal{"terminal", s::home_fixture, [] { expect(fatal(std::ranges::any_of(rows, [](const std::string& r) { return braille_run(r, 24); }))) << "T4: no status row carries the 24-cell screen" << rows; int checked = 0; for (std::size_t pos = text.find("\x1b[?7h"); pos != std::string::npos; pos = text.find("\x1b[?7h", pos + 1)) { - auto now = screen_of(std::string_view(text).substr(0, pos + 5)); + auto now = s::screen_of(std::string_view(text).substr(0, pos + 5)); while (!now.empty() && now.back().empty()) now.pop_back(); expect(fatal(!now.empty() && matches(now.back(), "^ *(Planning|Running|Building|Stopping|Checking) "))) << "T5: the last row after a frame is not the status row" << now; diff --git a/tests/e2e/index/local.cpp b/tests/e2e/index/local.cpp index 3709eac18..9f757cb8d 100644 --- a/tests/e2e/index/local.cpp +++ b/tests/e2e/index/local.cpp @@ -357,6 +357,92 @@ exit 0 r = app.mcpp({"build"}, inherited()); expect(fatal(r.started && r.status != 0)) << "mcpplibs.tensorvia-cpu must NOT resolve (the package is aimol-namespaced): " << s::text(r); }; + + "1180 dependencies fetched in one call leave one line each on a terminal"_test[s::gcc][s::fresh_sandbox][s::unix_shell] = [] { + // Design 2026-11-27 §3.11.2 items 5 and 9. The two dependencies the first step of the + // resolution knows are fetched by one call of the provider (`batch-fetch`). On a terminal + // the screen the bytes leave holds one `Downloading` line for each, under its manifest + // name, and no frame of the live region, although the provider writes a line of its own + // to its standard error while it downloads. A second build calls no provider. + const auto tmp = s::case_dir(); + const auto home = s::case_home(s::home::inherited); + s::project index(tmp / "local-index", { + {"pkgs/c/compat.one.lua", lua_package("compat.one", "1.0.0", "first of a wave", c_lib_segment("src/one.c", "one"))}, + {"pkgs/c/compat.two.lua", lua_package("compat.two", "1.0.0", "second of a wave", c_lib_segment("src/two.c", "two"))}}); + s::write_executable(tmp / "fake-bin/xlings", std::string("#!/usr/bin/env bash\n") + std::string(handshake) + R"SH( +set -e +if [[ "${1:-}" == "self" && "${2:-}" == "init" ]]; then + mkdir -p "${XLINGS_HOME:?}/subos/default" + printf '{}\n' > "$XLINGS_HOME/subos/default/.xlings.json" + exit 0 +fi +if [[ "${1:-}" == "update" || ( "${1:-}" == "interface" && "${2:-}" == "update_packages" ) ]]; then + exit 0 +fi +if [[ "${1:-}" == "interface" && "${2:-}" == "install_packages" ]]; then + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--args" ]]; then printf '%s\n' "$2" >> "${FAKE_INSTALL_LOG:?}"; break; fi + shift + done + for n in one two; do + root="${XLINGS_PROJECT_DIR:?}/.xlings/data/xpkgs/compat-x-compat.$n/1.0.0" + mkdir -p "$root/src" + printf 'int %s_value(void) { return 1; }\n' "$n" > "$root/src/$n.c" + done + frame() { + printf '{"kind":"data","dataKind":"download_progress","payload":{"elapsedSec":%s,"files":[{"name":"compat:compat.one@1.0.0","downloadedBytes":%s,"totalBytes":%s,"started":true,"finished":%s},{"name":"compat:compat.two@1.0.0","downloadedBytes":%s,"totalBytes":%s,"started":true,"finished":%s}]}}\n' "$@" + } + frame 0.1 0 0 false 0 0 false + sleep 0.3 + echo "Source compat:compat.one@1.0.0 example.invalid (attempt 1)" >&2 + frame 0.4 512 1024 false 0 0 false + sleep 0.3 + frame 0.7 1024 1024 true 512 1024 false + sleep 0.3 + frame 1.0 1024 1024 true 1024 1024 true + printf '{"kind":"result","exitCode":0}\n' + exit 0 +fi +if [[ "${1:-}" == "install" ]]; then + echo "direct install should not be used for project path indices" >&2 + exit 31 +fi +exit 0 +)SH"); + // The sandbox's tools before the fake xlings stands in (see 60). + auto primer = s::project::scaffold("primer"); + expect(fatal(e2e::succeeded(primer.mcpp({"build"}, inherited())))) << "the case's home did not bootstrap"; + fake_xlings_config(home, tmp / "fake-bin/xlings", home / "registry"); + s::project app(tmp / "project/app", { + {"src/main.cpp", "extern \"C\" int one_value(void);\nextern \"C\" int two_value(void);\nint main() { return one_value() + two_value() == 2 ? 0 : 1; }\n"}, + {"mcpp.toml", std::format("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[indices]\ncompat = {{ path = \"{}\" }}\n\n" + "[dependencies.compat]\none = \"1.0.0\"\ntwo = \"1.0.0\"\n\n[targets.app]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n", + index.dir().generic_string())}}); + const auto log = tmp / "fake-install.log"; + auto c = s::mcpp_command({"build"}, app.dir(), inherited({{"FAKE_INSTALL_LOG", log.string()}})); + s::spawn sp{.argv = c.argv, .cwd = app.dir(), .env = c.env}; + sp.out = sp.err = s::stream::terminal; + sp.session = true; + sp.cols = 100; + auto build = s::process::start(std::move(sp)); + const int rc = build.wait(); + expect(fatal(rc == 0)) << "the build on a terminal failed (" << rc << "):\n" << build.terminal(); + const auto calls = s::read_file(log); + expect(fatal(e2e::contains(calls, "compat:compat.one@1.0.0") && e2e::contains(calls, "compat:compat.two@1.0.0") + && s::count_lines(calls, "{") == 1)) + << "the two dependencies were not fetched by one call:\n" << calls; + std::string shown; + for (const auto& row : s::screen_of(build.terminal())) shown += row + "\n"; + for (std::string_view dep : {"compat.one v1.0.0", "compat.two v1.0.0"}) + expect(s::count_matching(shown, std::format("Downloading +{}", dep)) == 1u) << "not one line for " << dep << ":\n" << shown; + expect(s::no_line(shown, "connecting|\\[[=> -]+\\]")) << "a frame of the live region was left on the screen:\n" << shown; + expect(s::count_lines(shown, "example.invalid (attempt 1)") <= 1u) << "the provider's line was written more than once:\n" << shown; + + auto again = app.mcpp({"build"}, inherited({{"FAKE_INSTALL_LOG", log.string()}})); + expect(fatal(e2e::succeeded(again))) << s::text(again); + expect(s::count_lines(s::read_file(log), "{") == 1u) << "the second build called the provider:\n" << s::read_file(log); + expect(s::lacks(s::text(again), "Downloading")) << "the second build fetched: " << s::text(again); + }; }}; } // namespace diff --git a/tests/e2e/pack/members.cpp b/tests/e2e/pack/members.cpp index 7cc804901..c66c15535 100644 --- a/tests/e2e/pack/members.cpp +++ b/tests/e2e/pack/members.cpp @@ -398,12 +398,7 @@ int main() { for (std::string_view t : {"target", "core/target", "cli/target", "gui/target"}) ws.remove(t); r = ws.mcpp({"build", "--workspace", "--release"}, o); expect(fatal(e2e::succeeded(r))) << "C: the workspace did not build\n" << s::text(r); - auto build_dirs = [&] { - std::vector dirs; - for (const auto& f : s::find_files(ws.at("target"), R"(build\.ninja)")) - if (f.generic_string().find("/.build-mcpp/") == std::string::npos) dirs.push_back(f.parent_path()); - return dirs; - }; + auto build_dirs = [&] { return s::configuration_dirs(ws.at("target")); }; const auto dirs = build_dirs(); expect(fatal(dirs.size() == 1u)) << "C: expected one build directory, got " << dirs.size(); const auto before = objects(dirs.front()); @@ -816,9 +811,7 @@ members = ["app23", "app26"] } r = cfg.mcpp({"pack", "--mode", "system", "--workspace", "--message-format", "json"}, o); expect(fatal(e2e::succeeded(r))) << "P: members of two configurations were not packed\n" << r.err; - std::size_t graphs = 0; - for (const auto& f : s::find_files(cfg.at("target"), R"(build\.ninja)")) - graphs += f.generic_string().find("/.build-mcpp/") == std::string::npos; + const std::size_t graphs = s::configuration_dirs(cfg.at("target")).size(); expect(fatal(graphs == 2u)) << "P: expected one build directory for each configuration, found " << graphs; auto pdata = nlohmann::json::parse(r.out)["data"]; expect(fatal(members_in(pdata, "artifacts") == "app23 app26")) << "P: data.artifacts does not name the two members in order\n" << r.out; diff --git a/tests/e2e/workspace/graph.cpp b/tests/e2e/workspace/graph.cpp index 053d0365c..97d46d580 100644 --- a/tests/e2e/workspace/graph.cpp +++ b/tests/e2e/workspace/graph.cpp @@ -49,14 +49,8 @@ std::string output_of(const std::optional& program) { bool runs(const std::optional& program) { return program && s::run(*program).status == 0; } -// The directories of the graphs under target, outside the build programs' tree, sorted. -std::vector graph_dirs(const fs::path& root) { - std::vector out; - for (const auto& f : s::find_files(root / "target", R"(build\.ninja)")) - if (!f.generic_string().contains("/.build-mcpp/")) out.push_back(f.parent_path()); - std::ranges::sort(out); - return out; -} +// The configurations' directories under target, outside the build programs' tree, sorted. +std::vector graph_dirs(const fs::path& root) { return s::configuration_dirs(root / "target"); } std::size_t matching(const std::vector& outputs, const std::regex& re, std::size_t from = 0) { std::size_t n = 0; @@ -206,21 +200,20 @@ E2E graph{"graph", s::home_fixture, [] { auto outputs = s::ninja_log_outputs(main_dir); expect(fatal(matching(outputs, std::regex{R"(core\.m\.o)"}) == 1u)) << "G1: core's object was built " << matching(outputs, std::regex{R"(core\.m\.o)"}) << " times"; - const std::regex compiled{R"(\.(o|obj|gcm|pcm|ifc)$|^bin/cli/app)"}; - const auto before = matching(outputs, compiled); - r = ws.mcpp({"build", "-p", "cli"}); - expect(fatal(e2e::succeeded(r))) << "G2: -p cli failed: " << s::text(r); - expect(fatal(matching(s::ninja_log_outputs(main_dir), compiled) == before)) << "G2: -p cli recompiled after --workspace"; + // A selection is a plan of its own (SPEC-011 §2 item 7): its first build runs its edges + // once, and the compiler executor places each unit --workspace compiled. + auto [g2, g2built] = s::recorded(ws, {"build", "-p", "cli"}, "g2"); + expect(fatal(e2e::succeeded(g2))) << "G2: -p cli failed: " << s::text(g2); + std::string g2compiled; + for (const auto& c : g2built.compiled) g2compiled += "\n " + c; + expect(fatal(g2built.compiled.empty())) << "G2: -p cli compiled after --workspace:" << g2compiled; std::this_thread::sleep_for(1100ms); ws.write("gui/mcpp.toml", ws.read("gui/mcpp.toml") + "\n[build]\ncxxflags = [\"-DGUI_EXTRA=1\"]\n"); - const auto lines = s::ninja_log_outputs(main_dir).size(); - r = ws.mcpp({"build", "--workspace"}); - expect(fatal(e2e::succeeded(r))) << "G3: the build after the edit failed: " << s::text(r); - outputs = s::ninja_log_outputs(main_dir); + auto [g3run, g3built] = s::recorded(ws, {"build", "--workspace"}, "g3"); + expect(fatal(e2e::succeeded(g3run))) << "G3: the build after the edit failed: " << s::text(g3run); std::string g3; - for (std::size_t i = lines; i < outputs.size(); ++i) - if (std::regex_search(outputs[i], std::regex{R"(\.(o|obj|gcm|pcm|ifc)$|/app(\.exe)?$)"})) g3 += outputs[i] + "\n"; + for (const auto& c : g3built.compiled) g3 += c + "\n"; expect(fatal(e2e::contains(g3, "gui"))) << "G3: gui was not rebuilt after its flags changed: " << g3; expect(fatal(s::no_line(g3, "core|/cli/|_cli|ns1|ns2"))) << "G3: an edit to gui's flags rebuilt another member"; expect(fatal(fs::is_directory(main_dir))) << "G3: the flag edit moved the build directory"; @@ -363,12 +356,12 @@ export int consumer_flag_v() { expect(fatal(v23 > 0 && v26 > v23)) << "A: app26 does not link the lib compiled for its own standard (" << v23 << " against " << v26 << ")"; ws.write("mcpp.toml", "[workspace]\nmembers = [\"lib\", \"app23\", \"app23b\", \"app26\"]\n"); - r = ws.mcpp({"build", "--workspace"}); - expect(fatal(e2e::succeeded(r))) << "B: the workspace did not build: " << s::text(r); + auto [rb, builtB] = s::recorded(ws, {"build", "--workspace"}, "b"); + expect(fatal(e2e::succeeded(rb))) << "B: the workspace did not build: " << s::text(rb); const auto d23 = ending(ws.at("target"), "/bin/app23/" + s::exe("app23")); expect(fatal(d23.has_value())) << "B: no app23"; - const auto dir23 = d23->parent_path().parent_path().parent_path(); - expect(fatal(matching(s::ninja_log_outputs(dir23), lib_object) == 1u)) << "B: lib's object was compiled more than once for its two consumers"; + expect(fatal(std::ranges::count_if(builtB.compiled, [&](const std::string& c) { return std::regex_search(c, lib_object); }) <= 1)) + << "B: lib's object was compiled more than once for its two consumers"; const auto [vb, xb, fb] = values("app23b"); expect(fatal(fb == 0)) << "B: a consumer's own cxxflags reached lib's compile"; expect(fatal(xb == 1)) << "B: lib was not compiled with the union of its consumers' features"; @@ -507,16 +500,19 @@ export int consumer_flag_v() { expect(fatal(e2e::succeeded(r))) << "A: the workspace did not build: " << s::text(r); for (const auto& [name, value] : std::vector>{{"app", "42"}, {"tool", "43"}, {"tool2", "7"}}) expect(fatal(output_of(bin_of(ws.at("target"), name)) == value)) << "A: " << name << " does not print " << value; - const std::regex object{R"(\.(o|obj)$)"}; auto dirs = graph_dirs(ws.dir()); expect(fatal(dirs.size() == 1u)) << "B: expected one build directory, got " << dirs.size(); const auto dev = dirs[0]; - auto none_after = [&](const fs::path& dir, std::vector args, std::string_view label) { - const auto before = s::ninja_log_outputs(dir).size(); - auto b = ws.mcpp(args); + // A selection's first build runs its plan's edges once and places what another selection + // compiled (SPEC-011 §2 item 7); what it compiles is what its record says ran a compiler. + std::size_t asked = 0; + auto none_after = [&](const fs::path&, std::vector args, std::string_view label) { + auto [b, built] = s::recorded(ws, args, std::format("none-{}", ++asked)); expect(fatal(e2e::succeeded(b))) << label << ": " << b.line << " failed: " << s::text(b); - const auto n = matching(s::ninja_log_outputs(dir), object, before); - expect(fatal(n == 0u)) << label << ": " << b.line << " compiled " << n << " units after --workspace"; + std::string compiled; + for (const auto& c : built.compiled) compiled += "\n " + c; + expect(fatal(built.compiled.empty())) << label << ": " << b.line << " compiled " << built.compiled.size() + << " units after --workspace:" << compiled; }; for (std::string sel : {"core", "app", "tool", "tool2", "dso", "app", "tool2", "app"}) none_after(dev, {"build", "-p", sel}, "B"); none_after(dev, {"build", "--workspace"}, "B"); @@ -742,6 +738,77 @@ int main() { compiles += matching(s::ninja_log_outputs(log.parent_path()), std::regex{R"(shared\.m\.o$)"}); expect(fatal(compiles == 1u)) << "B: the library was compiled " << compiles << " times"; }; + + "1179 commands that select different members build at once"_test[s::unix_shell][s::python3] = [] { + // Design 2026-11-27 §3.7.1, SPEC-011 §2 items 7 to 10. A: while member a's plan is held, + // a build of member b proceeds without waiting, and places the unit of the library both + // reach instead of compiling it. B: a build of a waits for a's plan, and one that may not + // wait is refused naming the plan. C: a plan build holds the configuration shared, so a + // shared holder does not stop it; D: `--cache off` holds the configuration alone, and + // waits for a shared holder. E: `mcpp why toolchain` states the holding and its reason, + // and the entry's parameter turns it off. + const auto tmp = s::case_dir(); + s::project ws(tmp / "ws", { + {"mcpp.toml", "[workspace]\nmembers = [\"a\", \"b\", \"c\"]\n"}, + {"c/mcpp.toml", "[package]\nname = \"c\"\nversion = \"0.1.0\"\n\n[targets.c]\nkind = \"lib\"\n"}, + {"c/src/c.cppm", "export module plan1179.c;\nexport int c_value() { return 40; }\n"}, + }); + for (std::string m : {"a", "b"}) { + ws.write(m + "/mcpp.toml", std::format("[package]\nname = \"{0}\"\nversion = \"0.1.0\"\n\n[dependencies]\nc = {{ path = \"../c\" }}\n\n" + "[targets.{0}]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n", m)); + ws.write(m + "/src/main.cpp", "import plan1179.c;\nint main() { return c_value() == 40 ? 0 : 1; }\n"); + } + // Holds `file` with flock(2), the primitive mcpp takes (`shared` or alone), until the case ends. + ws.write("hold.py", "import fcntl, sys, time\nf = open(sys.argv[1], 'a')\n" + "fcntl.flock(f, fcntl.LOCK_SH if sys.argv[2] == 'shared' else fcntl.LOCK_EX)\n" + "print('held', flush=True)\ntime.sleep(600)\n"); + auto hold = [&](const fs::path& file, std::string_view how) { + auto h = s::process::start({.argv = {"python3", ws.at("hold.py").string(), file.string(), std::string(how)}, .cwd = ws.dir()}); + expect(fatal(h.wait_for("held", std::chrono::seconds{30}))) << "the lock " << file << " could not be held"; + return h; + }; + const s::options noWait{.env = {{"MCPP_LOCK_WAIT", "0"}}}; + auto r = ws.mcpp({"build", "-p", "a"}); + expect(fatal(e2e::succeeded(r))) << "a did not build: " << s::text(r); + const auto dirs = graph_dirs(ws.dir()); + expect(fatal(dirs.size() == 1u)) << "expected one build directory, got " << dirs.size(); + const auto dir = dirs.front(); + std::vector plans; + for (const auto& e : fs::directory_iterator(dir / "plans")) plans.push_back(e.path()); + expect(fatal(plans.size() == 1u)) << "a's build did not plan in a directory of its own"; + expect(fatal(fs::is_regular_file(plans.front() / "build.ninja") && fs::is_regular_file(plans.front() / ".ninja_log"))) + << "a's plan holds no graph or ninja state"; + + { + auto held = hold(plans.front() / ".mcpp-plan.lock", "alone"); + auto [b, built] = s::recorded(ws, {"build", "-p", "b"}, "b", noWait); + expect(fatal(e2e::succeeded(b))) << "A: b waited for a's plan or failed: " << s::text(b); + expect(s::no_line(s::text(b), "Waiting")) << "A: b waited: " << s::text(b); + std::string compiled; + for (const auto& c : built.compiled) compiled += c + "\n"; + expect(s::no_line(compiled, "^c ")) << "A: b compiled the library a's build compiled:\n" << compiled; + ws.write("a/src/main.cpp", ws.read("a/src/main.cpp") + "// edit\n"); + r = ws.mcpp({"build", "-p", "a"}, noWait); + expect(fatal(failed(r))) << "B: a was built while its plan was held"; + expect(e2e::contains(s::text(r), "lock-wait-exceeded")) << "B: the refusal carries no reason token: " << s::text(r); + expect(e2e::contains(s::text(r), "the plan of member 'a'")) << "B: the refusal does not name the plan: " << s::text(r); + } + { + auto held = hold(dir / ".mcpp-build.lock", "shared"); + r = ws.mcpp({"build", "-p", "a"}, noWait); + expect(fatal(e2e::succeeded(r))) << "C: a shared holder of the configuration stopped a plan build: " << s::text(r); + ws.write("a/src/main.cpp", ws.read("a/src/main.cpp") + "// edit\n"); + r = ws.mcpp({"build", "-p", "a", "--cache", "off"}, noWait); + expect(fatal(failed(r))) << "D: --cache off did not hold the configuration alone"; + expect(e2e::contains(s::text(r), "lock-wait-exceeded")) << "D: " << s::text(r); + } + r = ws.mcpp_in("a", {"why", "toolchain"}); + expect(fatal(e2e::succeeded(r))) << "E: " << s::text(r); + expect(s::has_line(r.out, "plan locks: selection \\(")) << "E: the holding is not stated: " << r.out; + r = ws.mcpp_in("a", {"why", "toolchain"}, {.env = {{"MCPP_PLAN_LOCKS", "configuration"}}}); + expect(fatal(e2e::succeeded(r))) << "E: " << s::text(r); + expect(s::has_line(r.out, "plan locks: configuration \\(plan-locks is off")) << "E: the entry's parameter did not turn it off: " << r.out; + }; }}; } // namespace diff --git a/tests/e2e/workspace/inheritance.cpp b/tests/e2e/workspace/inheritance.cpp index 6f8646172..9ba49ac94 100644 --- a/tests/e2e/workspace/inheritance.cpp +++ b/tests/e2e/workspace/inheritance.cpp @@ -593,12 +593,20 @@ main = "src/main.cpp" }); auto r = ws.mcpp({"build", "-p", "one"}); expect(fatal(e2e::succeeded(r))) << "the first member did not build: " << s::text(r); - r = ws.mcpp({"build", "-p", "two", "--verbose"}); - expect(fatal(e2e::succeeded(r))) << "the second member did not build: " << s::text(r); - expect(s::lacks(s::text(r), "shared.cppm")) << "A: the package was compiled again for the second member: " << s::text(r); - r = ws.mcpp({"build", "-p", "one", "--verbose"}); - expect(fatal(e2e::succeeded(r))) << s::text(r); - expect(s::lacks(s::text(r), "shared.cppm") && s::lacks(s::text(r), "mid.cppm")) << "B: back at the first member a package was compiled again: " << s::text(r); + // What ran a compiler, from the build's record: a member's first build places the units + // another selection compiled (SPEC-011 §2 item 7), and a unit with another command line + // would be compiled. + auto compiled = [](const s::BuildRecord& b) { + std::string out; + for (const auto& c : b.compiled) out += c + "\n"; + return out; + }; + auto [two, twoBuilt] = s::recorded(ws, {"build", "-p", "two"}, "two"); + expect(fatal(e2e::succeeded(two))) << "the second member did not build: " << s::text(two); + expect(s::lacks(compiled(twoBuilt), "shared")) << "A: the package was compiled again for the second member:\n" << compiled(twoBuilt); + auto [one, oneBuilt] = s::recorded(ws, {"build", "-p", "one"}, "one"); + expect(fatal(e2e::succeeded(one))) << s::text(one); + expect(s::lacks(compiled(oneBuilt), "shared") && s::lacks(compiled(oneBuilt), "mid")) << "B: back at the first member a package was compiled again:\n" << compiled(oneBuilt); }; "953 a package compiled under two feature sets keeps both instances"_test[s::gcc][s::elf] = [] { // mcpp#953 D5, design 2026-11-19 §11.1. `mcpp test` enables a feature of a shared package diff --git a/tests/e2e/workspace/members.cpp b/tests/e2e/workspace/members.cpp index a82b4cea4..f3366119b 100644 --- a/tests/e2e/workspace/members.cpp +++ b/tests/e2e/workspace/members.cpp @@ -43,21 +43,14 @@ std::string output_of(const std::optional& program) { return out; } -// The directory of the first build.ninja under target, outside the build programs' tree. +// The first configuration's directory under target, outside the build programs' tree. std::optional build_dir(const fs::path& root) { - auto all = s::find_files(root / "target", R"(build\.ninja)"); - std::ranges::sort(all); - for (const auto& f : all) - if (!f.generic_string().contains("/.build-mcpp/")) return f.parent_path(); - return std::nullopt; + const auto all = s::configuration_dirs(root / "target"); + if (all.empty()) return std::nullopt; + return all.front(); } -std::size_t graphs(const fs::path& root) { - std::size_t n = 0; - for (const auto& f : s::find_files(root / "target", R"(build\.ninja)")) - if (!f.generic_string().contains("/.build-mcpp/")) ++n; - return n; -} +std::size_t graphs(const fs::path& root) { return s::configuration_dirs(root / "target").size(); } E2E members{"members", s::home_fixture, [] { "35 workspace"_test = [] { diff --git a/tests/e2e/workspace/statements.cpp b/tests/e2e/workspace/statements.cpp index a844d0ae9..84d5b868b 100644 --- a/tests/e2e/workspace/statements.cpp +++ b/tests/e2e/workspace/statements.cpp @@ -29,7 +29,7 @@ std::optional bin_of(const fs::path& root, std::string_view name) { std::vector graphs(const fs::path& root) { std::vector out; for (const auto& f : s::find_files(root / "target", R"(build\.ninja)")) - if (!f.generic_string().contains("/.build-mcpp/")) out.push_back(f); + if (!f.generic_string().contains("/.build-mcpp/") && !f.generic_string().contains("/plans/")) out.push_back(f); std::ranges::sort(out); return out; } diff --git a/tests/support/src/support.cpp b/tests/support/src/support.cpp index bea3e5e4c..aa559073f 100644 --- a/tests/support/src/support.cpp +++ b/tests/support/src/support.cpp @@ -906,9 +906,9 @@ std::optional> cdb_arguments(const fs::path& cdb, std:: return std::nullopt; } -std::vector ninja_log_outputs(const fs::path& build_dir) { - std::vector out; - for (auto l : split_lines(read_file(build_dir / ".ninja_log"))) { +namespace { +void append_log_outputs(const fs::path& log, std::vector& out) { + for (auto l : split_lines(read_file(log))) { if (l.starts_with('#')) continue; std::vector cols; @@ -916,9 +916,151 @@ std::vector ninja_log_outputs(const fs::path& build_dir) { if (cols.size() >= 4) out.emplace_back(cols[3]); } +} +} // namespace + +std::vector ninja_log_outputs(const fs::path& build_dir) { + std::vector out; + append_log_outputs(build_dir / ".ninja_log", out); + std::vector plans; + std::error_code ec; + for (fs::directory_iterator it(build_dir / "plans", ec), end; !ec && it != end; it.increment(ec)) + plans.push_back(it->path()); + std::ranges::sort(plans); + for (const auto& plan : plans) append_log_outputs(plan / ".ninja_log", out); + return out; +} + +std::u32string decode_utf8(std::string_view b) { + std::u32string out; + for (std::size_t i = 0; i < b.size();) { + const auto c = static_cast(b[i]); + const int n = c < 0x80 ? 1 : (c >> 5) == 6 ? 2 : (c >> 4) == 14 ? 3 : (c >> 3) == 30 ? 4 : 0; + if (n == 0 || i + n > b.size()) { + out.push_back(0xfffd); + ++i; + continue; + } + char32_t cp = n == 1 ? c : c & (0x7f >> n); + for (int k = 1; k < n; ++k) cp = (cp << 6) | (static_cast(b[i + k]) & 0x3f); + out.push_back(cp); + i += n; + } + return out; +} + +std::string encode_utf8(std::u32string_view s) { + std::string out; + for (char32_t c : s) { + if (c < 0x80) { + out.push_back(static_cast(c)); + } else if (c < 0x800) { + out.push_back(static_cast(0xc0 | (c >> 6))); + out.push_back(static_cast(0x80 | (c & 0x3f))); + } else if (c < 0x10000) { + out.push_back(static_cast(0xe0 | (c >> 12))); + out.push_back(static_cast(0x80 | ((c >> 6) & 0x3f))); + out.push_back(static_cast(0x80 | (c & 0x3f))); + } else { + out.push_back(static_cast(0xf0 | (c >> 18))); + out.push_back(static_cast(0x80 | ((c >> 12) & 0x3f))); + out.push_back(static_cast(0x80 | ((c >> 6) & 0x3f))); + out.push_back(static_cast(0x80 | (c & 0x3f))); + } + } + return out; +} + +std::vector screen_of(std::string_view bytes) { + const auto s = decode_utf8(bytes); + std::vector rows{U""}; + std::size_t r = 0, c = 0, i = 0; + while (i < s.size()) { + const char32_t ch = s[i]; + if (ch == 0x1b && i + 1 < s.size() && s[i + 1] == U'[') { + std::size_t j = i + 2; + while (j < s.size() && !(s[j] >= U'@' && s[j] <= U'~')) ++j; + const std::u32string params = s.substr(i + 2, j - (i + 2)); + const char32_t final = j < s.size() ? s[j] : 0; + const bool digits = !params.empty() && std::ranges::all_of(params, [](char32_t d) { return d >= U'0' && d <= U'9'; }); + std::size_t n = 1; + if (digits) { + n = 0; + for (char32_t d : params) n = n * 10 + (d - U'0'); + } + if (final == U'A') { + r = r >= n ? r - n : 0; + } else if (final == U'J') { + rows[r] = rows[r].substr(0, c); + rows.erase(rows.begin() + static_cast(r) + 1, rows.end()); + } else if (final == U'K') { + rows[r] = params == U"2" ? U"" : rows[r].substr(0, c); + } + i = j + 1; + continue; + } + if (ch == U'\r') { + c = 0; + } else if (ch == U'\n') { + ++r; + while (rows.size() <= r) rows.emplace_back(); + } else { + auto& line = rows[r]; + if (line.size() < c) line.resize(c, U' '); + if (line.size() == c) line.push_back(ch); + else line[c] = ch; + ++c; + } + ++i; + } + std::vector out; + for (auto& row : rows) { + while (!row.empty() && (row.back() == U' ' || row.back() == U'\t')) row.pop_back(); + out.push_back(encode_utf8(row)); + } return out; } +std::vector configuration_dirs(const fs::path& target) { + std::vector out; + for (const auto& f : find_files(target, R"(build\.ninja)")) { + const auto spelled = f.generic_string(); + if (!spelled.contains("/.build-mcpp/") && !spelled.contains("/plans/")) out.push_back(f.parent_path()); + } + std::ranges::sort(out); + return out; +} + +std::pair recorded(const project& p, std::vector args, std::string_view name, + options o) { + const auto file = case_dir() / std::format("record-{}.ndjson", name); + std::error_code ec; + fs::remove(file, ec); + o.env.emplace_back("MCPP_BUILD_RECORD", file.string()); + auto r = p.mcpp(std::move(args), o); + return {r, read_build_record(file)}; +} + +BuildRecord read_build_record(const fs::path& file) { + BuildRecord b; + auto compiles = [](std::string_view output) { + for (auto ext : {".o", ".obj", ".gcm", ".pcm", ".ifc"}) + if (output.ends_with(ext)) return true; + return false; + }; + for (const auto& line : json_lines(read_file(file))) { + if (line.value("cached", false)) { + b.cached[line.value("package", "")] += line.value("units", std::size_t{0}); + continue; + } + if (compiles(line.value("output", "")) && !line.value("served", false) && !line.value("staged", false)) { + b.compiledPackages.insert(line.value("package", "")); + b.compiled.push_back(line.value("package", "") + " " + line.value("output", "")); + } + } + return b; +} + // ---- executables ------------------------------------------------------------------------------------- namespace { diff --git a/tests/support/src/support.cppm b/tests/support/src/support.cppm index d0ac3f067..169884a20 100644 --- a/tests/support/src/support.cppm +++ b/tests/support/src/support.cppm @@ -426,9 +426,37 @@ std::size_t count_lines(std::string_view text, std::string_view needle); // The number of lines of `text` that match `pattern` (`grep -cE`). std::size_t count_matching(std::string_view text, std::string_view pattern); -// The outputs `.ninja_log` records, one per edge run (its fourth column), in order. +// The outputs `.ninja_log` records, one per edge run (its fourth column): the build directory's +// log and, after it, the log of each plan of its own (`plans//.ninja_log`, a workspace's +// selections, SPEC-011 §2 item 7), each in order. std::vector ninja_log_outputs(const fs::path& build_dir); +// The code points of UTF-8 `bytes`, a byte that begins no sequence read as U+FFFD; and back. +std::u32string decode_utf8(std::string_view bytes); +std::string encode_utf8(std::u32string_view text); +// The screen a terminal shows after `bytes`: carriage return, line feed, cursor up (`CSI n A`), +// erase to the end of the screen (`CSI J`) and of the line (`CSI K`); colour is ignored. Rows +// without their trailing blanks. +std::vector screen_of(std::string_view bytes); + +// The configuration directories below `target`: those that hold a `build.ninja` of their own, +// outside the build programs' tree (`.build-mcpp`) and the plans' directories, sorted. +std::vector configuration_dirs(const fs::path& target); + +// What builds did, from the file MCPP_BUILD_RECORD names (SPEC-017 B4): each compile edge that +// ran a compiler, as ` `, and the units the cache served each package. An edge +// the unit cache placed (`served`) or copied for a package the cache served (`staged`) ran none. +struct BuildRecord { + std::vector compiled; + std::set compiledPackages; + std::map cached; +}; +BuildRecord read_build_record(const fs::path& file); +// mcpp in `p` with MCPP_BUILD_RECORD naming a file of the case, `record-.ndjson`, emptied +// first: the outcome and what the build did. +std::pair recorded(const project& p, std::vector args, std::string_view name, + options o = {}); + // The words of the compile database `cdb`'s first entry whose `file` (with `\` read as `/`) ends // with `file_suffix`: its `arguments`, else its `command` split at spaces; nothing when no entry // does or the file is not a database. diff --git a/tests/unit/test_ninja_backend.cpp b/tests/unit/test_ninja_backend.cpp index afa1a74b1..e5a957f6f 100644 --- a/tests/unit/test_ninja_backend.cpp +++ b/tests/unit/test_ninja_backend.cpp @@ -265,11 +265,33 @@ UTest links_hold_a_permit_of_the_schedule_bound{"NinjaBackend/LinksHoldAPermitOf << name << "\n" << r; } expect(eq(rule(text, "cxx_archive").find("__compiler-cap"), std::string::npos)) << rule(text, "cxx_archive"); + // An archive is written whole under a temporary name and renamed, as a link is (SPEC-011 §3). + if constexpr (!mcpplibs::os::is_windows) + expect(ne(rule(text, "cxx_archive").find("$mcpp link-output --output $out --temporary -- $ar"), std::string::npos)) + << rule(text, "cxx_archive"); expect(eq(text.find("--cap"), std::string::npos)) << "the graph names no number of compilers"; plan.scheduleCompilerCap = 0; expect(eq(rule(emit_ninja_string(plan), "cxx_link").find("__compiler-cap"), std::string::npos)); }}; +// A plan with a directory of its own (SPEC-011 §2 item 7) keeps its ninja state there and names +// its response files after itself: ninja removes an edge's response file when the edge ends, and +// another plan may be running the same edge. +UTest a_plan_of_its_own_keeps_its_state_and_its_response_files{"NinjaBackend/APlanOfItsOwnKeepsItsStateAndItsResponseFiles", [] { + auto plan = minimal_plan(); + plan.scheduleCompilerCap = 2; + plan.stateDir = "plans/0123456789abcdef"; + const auto text = emit_ninja_string(plan); + expect(ne(text.find("builddir = plans/0123456789abcdef\n"), std::string::npos)) << text; + expect(ne(text.find("sched_dir = plans/0123456789abcdef/.mcpp-sched\n"), std::string::npos)) << text; + expect(ne(text.find("rspfile = $out.0123456789abcdef.rsp"), std::string::npos)) << text; + expect(eq(text.find("rspfile = $out.rsp"), std::string::npos)) << text; + plan.stateDir.clear(); + const auto shared = emit_ninja_string(plan); + expect(eq(shared.find("builddir"), std::string::npos)) << shared; + expect(ne(shared.find("rspfile = $out.rsp"), std::string::npos)) << shared; +}}; + UTest objective_c_source_uses_c_object_rule_and_c_flags{"NinjaBackend/ObjectiveCSourceUsesCObjectRuleAndCFlags", [] { auto plan = minimal_plan(); plan.compileUnits.push_back({ diff --git a/tests/unit/test_plan_locks.cpp b/tests/unit/test_plan_locks.cpp new file mode 100644 index 000000000..3d3969a3d --- /dev/null +++ b/tests/unit/test_plan_locks.cpp @@ -0,0 +1,57 @@ +// The locks of a configuration's directory (design 2026-11-27 §3.7.1, SPEC-011 §2 items 7 to +// 10): a plan is named by its members as a set, the directory is held shared by plans and alone +// by what changes it as a whole, and a plan's lock excludes a second command of the plan. +import std; +import mcpplibs.mtest; +import mcpp.build.dirlock; + +using namespace mcpplibs::mtest; +namespace dirlock = mcpp::build::dirlock; + +namespace { +struct Tmp { + std::filesystem::path path; + Tmp() { + path = std::filesystem::temp_directory_path() + / std::format("mcpp_plan_locks_test_{}", std::random_device{}()); + std::filesystem::create_directories(path); + } + ~Tmp() { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } +}; +} // namespace + +UTest a_plan_is_named_by_its_members_as_a_set{"PlanLocks/APlanIsNamedByItsMembersAsASet", [] { + const auto ab = dirlock::plan_state_dir("a\x1e" "b"); + expect(eq(ab, dirlock::plan_state_dir("b\x1e" "a"))); + expect(ne(ab, dirlock::plan_state_dir("a"))); + expect(ne(ab, dirlock::plan_state_dir("a\x1e" "b\x1e" "c"))); + expect(eq(ab.parent_path(), std::filesystem::path("plans"))); + expect(eq(ab.filename().string().size(), std::size_t{16})); +}}; + +UTest a_wait_names_the_plans_members{"PlanLocks/AWaitNamesThePlansMembers", [] { + expect(eq(dirlock::plan_named("a"), std::string("the plan of member 'a'"))); + expect(eq(dirlock::plan_named("a\x1e" "libs/b"), std::string("the plan of members 'a', 'libs/b'"))); + expect(eq(dirlock::plan_named(""), std::string("the plan of this package"))); +}}; + +// Held in this process, a lock is shared by every use of it (a run that builds and then packs one +// configuration), and a shared hold does not stand for an exclusive one. +UTest a_process_holds_each_lock_once{"PlanLocks/AProcessHoldsEachLockOnce", [] { + Tmp dir; + auto shared = dirlock::acquire(dir.path, true); + expect(fatal(shared.has_value())); + auto again = dirlock::acquire(dir.path, true); + expect(fatal(again.has_value())); + expect(eq(shared->get(), again->get())); + const auto stateDir = dirlock::plan_state_dir("a"); + auto plan = dirlock::acquire_plan(dir.path, stateDir, dirlock::plan_named("a")); + expect(fatal(plan.has_value())); + expect(std::filesystem::is_regular_file(dir.path / stateDir / ".mcpp-plan.lock")); + auto planAgain = dirlock::acquire_plan(dir.path, stateDir, dirlock::plan_named("a")); + expect(fatal(planAgain.has_value())); + expect(eq(plan->get(), planAgain->get())); +}}; From a567552fd15ba1c40d145155a0cf3bf39993cb98 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 04:51:02 +0900 Subject: [PATCH 11/36] test(e2e): the fetch-waves case writes its progress frames without pacing them by time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A test waits for an event, never for a time (design 2026-11-20 §5.20): the fake installer's frames arrive at once, and what the case asserts is the screen they leave. --- tests/e2e/index/local.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/e2e/index/local.cpp b/tests/e2e/index/local.cpp index 9f757cb8d..e561ff064 100644 --- a/tests/e2e/index/local.cpp +++ b/tests/e2e/index/local.cpp @@ -393,12 +393,9 @@ if [[ "${1:-}" == "interface" && "${2:-}" == "install_packages" ]]; then printf '{"kind":"data","dataKind":"download_progress","payload":{"elapsedSec":%s,"files":[{"name":"compat:compat.one@1.0.0","downloadedBytes":%s,"totalBytes":%s,"started":true,"finished":%s},{"name":"compat:compat.two@1.0.0","downloadedBytes":%s,"totalBytes":%s,"started":true,"finished":%s}]}}\n' "$@" } frame 0.1 0 0 false 0 0 false - sleep 0.3 echo "Source compat:compat.one@1.0.0 example.invalid (attempt 1)" >&2 frame 0.4 512 1024 false 0 0 false - sleep 0.3 frame 0.7 1024 1024 true 512 1024 false - sleep 0.3 frame 1.0 1024 1024 true 1024 1024 true printf '{"kind":"result","exitCode":0}\n' exit 0 From 0fe97043f45087aef783ddca09e38031975f83b0 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 04:51:16 +0900 Subject: [PATCH 12/36] CPS at mcpp's boundary: a library package writes a .cps per leg; a build program declares an installed package by its description MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mcpp's model is unchanged (design 2026-11-27 §3.12, D22 to D24): CPS (Common Package Specification 0.15.0) is a compatibility at two boundaries, and its code is one module package, modules/cps (mcpp.cps: the model, reading with the supplemental files, writing, versions, the words; mcpp.cps.usage: the search, the platform match, the closure of components), with one implementation unit at each use site. Out: mcpp pack writes, beside each leg's .pc, lib//cps//.cps from the same facts: one component named after the package (archive, or dylib with the import library as link_location on PE), @prefix@/include, the -l words as link_libraries, the dependencies as requirements on their components (a private one of a static library as link_requires), the leg's platform and x_mcpp_abi. Each leg has its own directory, because CMake 4.5 does not compare `platform` (measured; read in its sources). [pack] descriptions (default ["pkg-config", "cps"]) selects the descriptions written. The index entry of mcpp emit xpkg --package calls the index's relocate_cps and declare_cps beside the pkg-config pair. In: mcpp::cps_package (protocol 22, mcpp:cps-package=) declares a package another build system installed. After the program runs and before anything is checked, applied or recorded, the engine finds .cps in the prefixes where CMake looks, matches the platform and the version, closes the components over requires, link_requires and compile_requires under the configuration the profile prefers, and accepts what they state as include-dir, cflag, cxxflag, link-flag, runtime-search-dir and rerun-if-changed lines; the record holds those. Refusals cps-no-matching-package, cps-components-unstated, cps-component-not-found, cps-description-invalid; notes cps/modules-not-imported, cps/component-not-linked. Both adapters are implementation units: importing the format's modules into the interface of mcpp.build.build_program made GCC 16.1 crash at src/main.cpp's `import mcpp.cli`. Docs: docs/14 (both languages), docs/10, 12, 30, 50, 03; SPEC-007 v0.17 (R2.5, protocol 22), SPEC-014 v2.9 (§2.2 descriptions, §8.1); examples 14-cps and 05-lib-distribution/cmake-consumer. --- .../2026-11-27-ecosystem-boundary-design.md | 5 +- .github/tools/build_examples.sh | 3 + CHANGELOG.md | 15 + docs/03-examples.md | 1 + docs/10-pack-and-release.md | 1 + docs/12-binary-distribution.md | 24 +- docs/14-cps.md | 173 +++++ docs/30-build-mcpp.md | 22 + docs/50-machine-output.md | 4 + docs/README.md | 1 + docs/specs/README.md | 4 +- docs/specs/build-plugins.md | 19 +- docs/specs/packaging.md | 27 +- docs/zh/03-examples.md | 1 + docs/zh/10-pack-and-release.md | 1 + docs/zh/12-binary-distribution.md | 13 +- docs/zh/14-cps.md | 146 ++++ docs/zh/30-build-mcpp.md | 17 + docs/zh/50-machine-output.md | 4 + docs/zh/README.md | 1 + examples/05-lib-distribution/README.md | 20 +- .../cmake-consumer/CMakeLists.txt | 16 + .../05-lib-distribution/cmake-consumer/main.c | 7 + examples/14-cps/README.md | 42 ++ examples/14-cps/app/build.mcpp | 14 + examples/14-cps/app/mcpp.toml | 9 + examples/14-cps/app/src/main.cpp | 7 + .../prefix/include/greeting/greeting.h | 7 + .../prefix/lib/cps/Greeting/Greeting.cps | 14 + mcpp.toml | 2 + modules/buildmcpp/src/directives.cppm | 19 +- modules/buildmcpp/src/program_protocol.cppm | 9 +- modules/cps/mcpp.toml | 23 + modules/cps/src/cps.cppm | 671 ++++++++++++++++++ modules/cps/src/usage.cppm | 375 ++++++++++ modules/cps/tests/test_cps.cpp | 237 +++++++ modules/manifest/src/toml.cppm | 13 + modules/manifest/src/types.cppm | 4 + src/build/build_program.cppm | 21 + src/build/build_program/cps_package.cpp | 144 ++++ src/build/hostprogram.cppm | 34 + src/build/refusal.cppm | 12 + src/explain.cppm | 18 + src/pack/distribution.cppm | 45 +- src/pack/library.cppm | 82 +-- src/pack/library/descriptions.cpp | 142 ++++ src/pack/library_pipeline.cppm | 14 + tests/e2e/build-program/protocol.cpp | 137 ++++ tests/e2e/pack/library.cpp | 40 +- tests/unit/test_build_directives.cpp | 28 +- 50 files changed, 2589 insertions(+), 99 deletions(-) create mode 100644 docs/14-cps.md create mode 100644 docs/zh/14-cps.md create mode 100644 examples/05-lib-distribution/cmake-consumer/CMakeLists.txt create mode 100644 examples/05-lib-distribution/cmake-consumer/main.c create mode 100644 examples/14-cps/README.md create mode 100644 examples/14-cps/app/build.mcpp create mode 100644 examples/14-cps/app/mcpp.toml create mode 100644 examples/14-cps/app/src/main.cpp create mode 100644 examples/14-cps/third_party/prefix/include/greeting/greeting.h create mode 100644 examples/14-cps/third_party/prefix/lib/cps/Greeting/Greeting.cps create mode 100644 modules/cps/mcpp.toml create mode 100644 modules/cps/src/cps.cppm create mode 100644 modules/cps/src/usage.cppm create mode 100644 modules/cps/tests/test_cps.cpp create mode 100644 src/build/build_program/cps_package.cpp create mode 100644 src/pack/library/descriptions.cpp diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index 388e6b9a6..82d07d75a 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -1151,7 +1151,10 @@ CPS 是其中一种被读取的描述。`mcpp-package.json` 仍是 mcpp 的权 **六、代码的位置。** `modules/cps/` 是独立的模块包:`mcpp.cps`(模型、读取与补充文件的合并、写出、版本比较、词的互译) 与 `mcpp.cps.usage`(查找、匹配、组件闭包、配置选择,得出与指令同形的结果),只依赖 JSON 库,单元测试在包内。使用处 各一个适配文件:`src/pack/library/descriptions.cpp`(`mcpp.pack.library` 的实现单元,`.pc` 与 `.cps` 两种描述都在此)、 -`src/build/cps_package.cppm`(把声明展开为指令)。构建程序一侧只有内置模块中的声明类型与指令表的一行。 +`src/build/build_program/cps_package.cpp`(`mcpp.build.build_program` 的实现单元,把声明展开为指令)。两个适配都是 +实现单元而不是模块:把格式的模块导入 `mcpp.build.build_program` 的接口时,GCC 16.1 在 `src/main.cpp` 的 `import mcpp.cli` +处崩溃(mcpp#1027 登记的同一类缺陷);在实现单元中导入,它们不进入任何导入者读取的 BMI。构建程序一侧只有内置模块中的 +声明类型与指令表的一行。 **七、文档与示例。** 新章 docs/14「Common Package Specification」两种语言:立场、两个方向、声明与展开、匹配与拒绝、 与 pkg-config 的分工。SPEC-014 记写出,SPEC-007 记声明;docs/10、12 记文件,docs/30 记声明,docs/04 记 diff --git a/.github/tools/build_examples.sh b/.github/tools/build_examples.sh index c2e6ded78..992423c74 100755 --- a/.github/tools/build_examples.sh +++ b/.github/tools/build_examples.sh @@ -70,6 +70,9 @@ BUILD=( # vocabulary, and the example's README records the measured artifacts and # the emulator run for the binary it describes. examples/13-platform-targets + # A package another build system installed, read through its CPS + # description by `mcpp::cps_package`: header-only, so the prefix is text. + examples/14-cps/app ) # `key|reason`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 576087d75..8cf942465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,21 @@ platform's `deps` when it states none, as the installer reads it; versions every platform shares are written once. `mcpp xpkg parse` refuses a reference to a platform the table has no block for and a chain of references that returns to itself (SPEC-001 §10.5). +- CPS (Common Package Specification 0.15.0) at mcpp's boundary; mcpp's model is unchanged and a + package read through CPS is not a node of the dependency graph (docs/14). `mcpp pack` writes, + beside each leg's `.pc`, `lib//cps//.cps` from the same facts: one + component named after the package, the header interface, the `-l` words as `link_libraries`, the + dependencies as requirements, the leg's platform and `x_mcpp_abi`; CMake 4.3 and later finds it + with the leg's directory as a prefix. `[pack] descriptions` (default `["pkg-config", "cps"]`) + selects the descriptions written. The index entry of `mcpp emit xpkg --package` gives the `.cps` + its absolute prefix and declares it into the environment's `usr/lib/cps/` with the index's + `relocate_cps` and `declare_cps`. A build program's `mcpp::cps_package` (protocol 22) declares a + package another build system installed: the engine finds its `.cps` in the prefixes, matches its + platform and version, closes the components over their requirements under the configuration the + profile prefers, and applies them as `include-dir`, `cflag`, `cxxflag`, `link-flag`, + `runtime-search-dir` and `rerun-if-changed`. Reason tokens `cps-no-matching-package`, + `cps-components-unstated`, `cps-component-not-found`, `cps-description-invalid`; notes + `cps/modules-not-imported`, `cps/component-not-linked` (SPEC-007 R2.5, SPEC-014 §8.1). ### Changed diff --git a/docs/03-examples.md b/docs/03-examples.md index 2d0dd2346..81a2deafa 100644 --- a/docs/03-examples.md +++ b/docs/03-examples.md @@ -44,6 +44,7 @@ not repeated. |---|---| | [`03-pack-static`](../examples/03-pack-static/) | `mcpp pack --mode static`, `[target.]`, `[pack]` | | [`05-lib-distribution`](../examples/05-lib-distribution/) | a library's interface and its prebuilt binaries; a C header and a C++ module from one source | +| [`14-cps`](../examples/14-cps/) | `mcpp::cps_package`: a package another build system installed, read through its CPS description; [`05-lib-distribution/cmake-consumer`](../examples/05-lib-distribution/cmake-consumer/) is the other direction | ### C — The environment diff --git a/docs/10-pack-and-release.md b/docs/10-pack-and-release.md index 6d2879bb9..03bd9afe9 100644 --- a/docs/10-pack-and-release.md +++ b/docs/10-pack-and-release.md @@ -1114,6 +1114,7 @@ compress = "zstd" # the default of --compress sign = ["signtool", "sign", "{}"] # run on each program, image, library and loader before the container strip = true # default. false ships the artifacts as built debug_symbols = "dist/debug" # separate the debug info here instead of discarding it +descriptions = ["pkg-config", "cps"] # a library package's descriptions for other build systems (14) include = ["share/**", "config/*.toml"] # project files staged at the same path, once exclude = ["debug/**"] diff --git a/docs/12-binary-distribution.md b/docs/12-binary-distribution.md index 41ef46308..9a9560ec7 100644 --- a/docs/12-binary-distribution.md +++ b/docs/12-binary-distribution.md @@ -284,13 +284,27 @@ it is. The entry places the `.pc` into the environment's pkg-config view with the index's own two functions (`relocate_pkgconfig`, `declare_pkgconfig` of `xim.pkgindex.sysroot`); in an index without them, the install prints where the `.pc` is and succeeds. A package with two legs for one system and architecture -(two C libraries) shows the environment no `.pc`, which `emit xpkg` notes +(two C libraries) shows the environment no `.pc` and no `.cps`, which `emit xpkg` notes (`emit/two-legs-for-one-system`). -Three limits hold. The `.pc` describes the header interface: a package that -publishes only module interfaces writes none, noted as `pack/no-header-interface`. -pkg-config has no ABI check: `mcpp_abi` is readable, and the check is mcpp's -alone. A static library's package does not carry its dependencies' binaries: a +Beside it, each leg carries a CPS description, +`lib//cps//.cps`, from the same facts: one +component named after the package (`archive` or `dylib`, with the import +library as `link_location` on PE), `@prefix@/include`, the `-l` words as +`link_libraries`, the dependencies as requirements on their own components, +the leg's platform (`isa`, `kernel`, the C and C++ run-time vendors) and the +tag as `x_mcpp_abi`. CMake 4.3 and later finds it with +`CMAKE_PREFIX_PATH=/lib/` and links `::`; +[14 — The Common Package Specification](14-cps.md) states both directions. The +entry gives the `.cps` its absolute prefix and places it into the +environment's `usr/lib/cps/` with `relocate_cps` and `declare_cps`, as it does +the `.pc`. `[pack] descriptions` selects which of the two are written +(default both). + +Three limits hold. The `.pc` and the `.cps` describe the header interface: a +package that publishes only module interfaces writes neither, noted as +`pack/no-header-interface`. pkg-config and CMake have no ABI check: `mcpp_abi` +and `x_mcpp_abi` are readable, and the check is mcpp's alone. A static library's package does not carry its dependencies' binaries: a consumer outside mcpp needs them and their descriptions in its environment, noted as `pack/closure-not-in-package`; a shared library that links its dependencies into itself carries the closure. diff --git a/docs/14-cps.md b/docs/14-cps.md new file mode 100644 index 000000000..8ff67e757 --- /dev/null +++ b/docs/14-cps.md @@ -0,0 +1,173 @@ +# 14 — The Common Package Specification + +**English** | [简体中文](zh/14-cps.md) + +**Reader:** a publisher whose library is used by CMake, and an author whose +build uses a library CMake installed. + +**The question this chapter answers:** what mcpp writes and reads in the Common +Package Specification (CPS, version 0.15.0), and what each direction means for +a build. + +**Not here:** the library package itself, which is +[12 — Distributing a Prebuilt Library](12-binary-distribution.md), and build +programs in general, which are [30 — build.mcpp](30-build-mcpp.md). + +## Position + +mcpp's own description of a package is its manifest and `mcpp-package.json`; +its dependency graph holds mcpp packages. CPS is a compatibility at two +boundaries and changes neither: + +| Direction | Behaviour | Chapter | +|---|---|---| +| out | `mcpp pack` writes a `.cps` for each leg of a library package, from the facts it writes the `.pc` from | [12](12-binary-distribution.md) | +| in | a build program declares a package another build system installed, and the build receives what the package's `.cps` states as the directives a program would write | [30](30-build-mcpp.md) | + +A package read through CPS is not a node of the dependency graph: it is not +locked, not resolved by an index and not visible to the declaring package's +consumers' compiles, as a package a `deps-cmake` or `deps-vcpkg` plugin maps is +not. + +## Out: a library package's `.cps` + +Each leg of a library package with a header interface carries +`lib//cps//.cps` beside its +`lib//pkgconfig/.pc`: + +```json +{ + "cps_version": "0.15.0", + "name": "mathkit", + "version": "0.1.0", + "version_schema": "simple", + "compat_version": "0.1.0", + "cps_path": "@prefix@/lib/x86_64-linux-gnu/cps/mathkit", + "platform": { "isa": "x86_64", "kernel": "linux", + "c_runtime_vendor": "gnu", "cpp_runtime_vendor": "gnu" }, + "x_mcpp_abi": "x86_64-linux-gnu-gcc16-libstdcxx16-c++23", + "default_components": ["mathkit"], + "components": { + "mathkit": { + "type": "archive", + "location": "@prefix@/lib/x86_64-linux-gnu/libmathkit.a", + "includes": ["@prefix@/include"], + "link_libraries": ["m"], + "link_languages": ["cpp"] + } + } +} +``` + +| Field | Source | +|---|---| +| `name` | the package's identity, `.` with a namespace | +| `compat_version` | the oldest version the package is compatible with: `.0.0`, or `0..0` below 1 | +| `platform` | the leg's triple and C++ standard library, in CPS's words | +| the component | named after the package; `archive` for a static library, `dylib` for a shared one, with the import library as `link_location` on PE | +| `link_libraries` | the `-l` words of the package's `ldflags` | +| `link_languages` | `cpp` for an archive that holds C++ objects | +| `requires` | each dependency, by its identity, with the lowest version its requirement admits; a component requires `:`, and a `private` dependency of a static library is a `link_requires` | + +A package has no public macros, so the file states no `definitions`. Each leg +has its own directory: CMake does not compare `platform`, so a leg is selected +by where the file is. CMake 4.3 and later finds it with the leg's directory as +a prefix: + +```cmake +find_package(mathkit REQUIRED) # CMAKE_PREFIX_PATH=/lib/x86_64-linux-gnu +target_link_libraries(app mathkit::mathkit) +``` + +On a multiarch host whose library architecture is the triple, the package's +root is the prefix. `[pack] descriptions` selects the descriptions written: + +```toml +[pack] +descriptions = ["pkg-config", "cps"] # the default; ["pkg-config"], ["cps"] or [] for fewer +``` + +A package that publishes only module interfaces writes neither description +(`pack/no-header-interface`): CMake does not import C++ modules through CPS. +An index entry `mcpp emit xpkg --package` writes gives the `.cps` the +package's absolute `prefix` and places it into the environment's +`usr/lib/cps//` (`relocate_cps`, `declare_cps` of +`xim.pkgindex.sysroot`), so CMake in that environment finds it with the +environment's `usr/` as a prefix. + +## In: `mcpp::cps_package` + +A build program declares a package by its CPS description (protocol 22): + +```cpp +import mcpp; +int main() { + mcpp::cps_package imaging; + imaging.name = "Imaging"; + imaging.prefix("third_party/prefix"); // relative to the package root, or absolute + imaging.component("image"); // none: the package's default components + imaging.submit(); +} +``` + +| Field | Meaning | +|---|---| +| `name` | the package's CPS name | +| `prefix(dir)` | an installation prefix, searched in the order given | +| `component(c)` | a component the build uses; with none, the package's `default_components` | +| `version` | the version requested: a candidate satisfies it from its `compat_version` to its `version` | +| `configuration` | the configuration read, over the profile's preference | + +The engine reads the description after the program runs and applies it as +these directives, which the program's record then holds: + +| The description states | The build receives | +|---|---| +| `includes` for every language | `include-dir` | +| `includes` for C or C++, `definitions`, `compile_flags` | `cflag`, `cxxflag` | +| an `archive`'s or a `dylib`'s library, `link_libraries`, `link_flags` | `link-flag`, a library by its path | +| the directory of a `dylib` | `runtime-search-dir` | +| every file read | `rerun-if-changed` | + +The compile side reaches the declaring package, the link side its consumers' +links, and `mcpp pack` finds a shared library through the run-time directory, +as for the same directives written by hand. A changed description runs the +program again. + +**Search.** In each prefix, in order: `cps//`, `cps//*/`, `cps/`, +`/cps/`, `/*/cps/`, `lib*/cps//`, `lib*/cps//*/`, +`lib/*/cps//`, `lib*/cps/`, `share/cps//`, `share/cps//*/`, +`share/cps/`, for `.cps` as written and in lower case. A file's +`-*.cps` beside it adds components, and `@.cps` the +attributes of a configuration. + +**Match.** The fields a candidate's `platform` states are compared with the +build's, without case (`isa`, `kernel`, and the C and C++ run-time vendors); a +field it does not state constrains nothing. A candidate that differs, or whose +version does not satisfy the request, is passed over. + +**Components.** A component's `requires` are read in the same prefixes, its +compile and link attributes both reaching the build; a `link_requires` +component's link attributes alone, a `compile_requires` component's compile +attributes alone. A library is named before the libraries it requires. + +**Configuration.** The declaration's `configuration`; else the profile's +preference (`dev`: `Debug`; `release`: `Release`, `RelWithDebInfo`, +`MinSizeRel`); else the package's `configurations`; else the first by name. +A configuration's lists follow the component's, and its locations replace them. + +**Refusals and notes.** + +| Case | Token | +|---|---| +| no description of the package in the prefixes, or none for this build's platform or the requested version; the message lists the locations or each candidate and the field it differs in | `cps-no-matching-package` | +| no component named, and the package states no default components | `cps-components-unstated` | +| a component named or required is not in its package | `cps-component-not-found` | +| a file is not CPS, or its prefix cannot be found from `cps_path` or `prefix` | `cps-description-invalid` | +| a component describes C++ modules: its library and headers are used | note `cps/modules-not-imported` | +| a component is an `executable`, `module`, `jar` or `symbolic`: it reaches neither compile nor link | note `cps/component-not-linked` | + +**What is not read.** A prefix exists when the build program runs. One that a +`prepare` action fills at build time (a CMake subproject, a vcpkg manifest) +is named by library, as `deps-cmake` and `deps-vcpkg` take it, because the +names of a build are fixed when the program runs. diff --git a/docs/30-build-mcpp.md b/docs/30-build-mcpp.md index cc983b47d..2f13619b9 100644 --- a/docs/30-build-mcpp.md +++ b/docs/30-build-mcpp.md @@ -188,6 +188,7 @@ int main() { | `mcpp::run_host(h)` *(protocol 17)* | `mcpp:run-host=` — `"same-arch"` or `"any"`; `runner.host` | | `mcpp::runner(tok)` *(2026.8.19.2+)* | `mcpp:runner=` — see below | | `mcpp::runner_spec` *(protocol 19)* | `mcpp:runner-spec=` — a runner as one statement, the table of data field for field; see below | +| `mcpp::cps_package` *(protocol 22)* | `mcpp:cps-package=` — a package another build system installed, by its CPS description, applied as `include-dir`, `cflag`, `cxxflag`, `link-flag`, `runtime-search-dir` and `rerun-if-changed`; see below | | `mcpp::xpkg_dir(ns, name)` / `mcpp::xpkg_dir(name)` *(2026.8.19+)* | the payload directory of a package declared in `[xlings.workspace]` — by this manifest, or by a dependency compiled into this build program *(2026.9.6.6+)*; `""` when it was not declared or is not installed (see below) | | `mcpp::xpkg_source(ns, name)` / `mcpp::xpkg_program(ns, name)` *(protocol 15)* | where that payload comes from — `payload`, `override`, `pending`, or `""` — and the program an override named | | `mcpp::xpkg_request(ns, name)` / `mcpp::xpkg_pending()` *(protocol 15)* | the directory of a payload declared `provision = "on-request"`, asking for it when it is not installed yet; `xpkg_pending()` is then true and the program should return (see below) | @@ -342,6 +343,27 @@ token calls, a `runner_spec` submitted twice for a name, one without a command, or a `host` other than the two words is refused before anything is applied. The token calls keep their meaning; overriding, `enabled` and the one supplier per name follow the rules of data. + +### `cps_package` — a package by its CPS description (2026.12.4.1+, protocol 22) + +```cpp +mcpp::cps_package imaging; +imaging.name = "Imaging"; // the package's CPS name +imaging.prefix("third_party/prefix"); // relative to the package root, or absolute; repeatable +imaging.component("image"); // none: the package's default components +imaging.submit(); +``` + +`version` requests a version and `configuration` overrides the profile's +preference. The engine finds `.cps` in the prefixes, checks its platform +against the build's, closes the components over their requirements and +applies what they state as the directives in the table above, before anything +is applied or recorded: the program's record holds those directives, and a +changed description runs the program again. The prefix exists when the program +runs. The search, the match, the configuration and the refusals +(`cps-no-matching-package`, `cps-components-unstated`, +`cps-component-not-found`, `cps-description-invalid`) are stated in +[14 — The Common Package Specification](14-cps.md). : `toolchain_dir` / `sysroot_dir` (2026.8.19.4+) ```cpp diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index db32184b4..56ad6c96a 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -729,6 +729,10 @@ a program classifying the outcome reads `reason`: | `package-without-description` | a library package an earlier mcpp wrote carries no mcpp-package.json, which an index entry is written from *(2026.12.4.1+)* | | `emit-inside-a-package` | `mcpp emit xpkg` ran in the directory of a library package, which is not a source tree *(2026.12.4.1+)* | | `package-built-outside-the-ecosystem` | the package was built with a toolchain named by path, whose environment no index entry can supply *(2026.12.4.1+)* | +| `cps-no-matching-package` | a build program's `mcpp::cps_package` names a package no description in its prefixes matches: none is there, or none is for this build's platform or the requested version *(2026.12.4.1+)* | +| `cps-components-unstated` | a build program's `mcpp::cps_package` names no component, and the package states no default components *(2026.12.4.1+)* | +| `cps-component-not-found` | a component a `mcpp::cps_package` names, or one of them requires, is not in its package *(2026.12.4.1+)* | +| `cps-description-invalid` | a file a `mcpp::cps_package` reads is not a CPS description, or its prefix cannot be found from it *(2026.12.4.1+)* | | `other` | a refusal whose branch has not been given a token yet | **One token is also printed by `mcpp build` itself.** diff --git a/docs/README.md b/docs/README.md index af1b7fa54..af5040142 100644 --- a/docs/README.md +++ b/docs/README.md @@ -76,6 +76,7 @@ Within a part the order is a reading order, not an alphabet. - [11 — Publishing a Library to mcpp-index](11-publishing-a-library.md) - [12 — Distributing a Prebuilt Library](12-binary-distribution.md) - [13 — Code and Project Style](13-code-and-project-style.md) — the shape of a module, headers, macros, and what mcpp's build adds +- [14 — The Common Package Specification](14-cps.md) — the `.cps` a library package carries, and a build program's `cps_package` ### 2x — Toolchains and targets diff --git a/docs/specs/README.md b/docs/specs/README.md index edcc6354c..5112af928 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -36,14 +36,14 @@ | [SPEC-004](manifest-semantics.md) | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | 草案 v1.30 | 2026-11-27 | 条件化形状 mcpp >= 2026.8.29.1;目标轴 mcpp >= 2026.9.6.4;`linkage` 默认值 mcpp >= 2026.9.15.2;链接 flag 的词读法 mcpp >= 2026.9.26.2;条件化的 `dialect_cxxflags` 与 `-p` 的包身份 mcpp >= 2026.9.28.1;条件表按具体程度生效 mcpp >= 2026.9.28.2;平台前缀规约 mcpp >= 2026.10.5.1;根包的继承、根位置的 profile、链接 flag 的作用域、链接期优化与导出发现 mcpp >= 2026.10.5.2;架构段的 `x86` 即 `i686` mcpp >= 2026.10.5.3;前缀即语义与工作空间层 mcpp >= 2026.10.10.1;依赖的库与配置(§12) mcpp >= 2026.10.11.1;值的四档层次与 `run_under` mcpp >= 2026.10.24.1;§12 第 3 条一个程序一个版本 mcpp >= 2026.11.19.1;§9 第 21 至 23 条与 §16 mcpp >= 2026.11.21.1;v1.29 条款 mcpp >= 2026.11.23.1;§9 第 24 条、§11 第 7 与 8 条、§17 mcpp >= 2026.11.27.1 | | [SPEC-005](build-database.md) | 构建数据库:`mcpp emit build-database` 的内容、取值规则与不写工程目录的保证 | 评审中 v1.10 | 2026-11-23 | mcpp >= 2026.9.15.1;v1.3 条款 mcpp >= 2026.9.26.2;v1.4 条款 mcpp >= 2026.9.27.1;v1.5 条款 mcpp >= 2026.9.28.1;v1.6 条款 mcpp >= 2026.9.29.5;v1.7 条款 mcpp >= 2026.9.30.2;v1.8 条款 mcpp >= 2026.10.11.1;v1.10 条款 mcpp >= 2026.11.23.1 | | [SPEC-006](toolchain-management.md) | 工具链管理:身份、来源、选择与载荷契约 | 草案 v0.14 | 2026-11-23 | 逐条标注;已实现条款 mcpp >= 2026.9.24.1;§3.7 mcpp >= 2026.9.28.1;§3.7.1 mcpp >= 2026.9.28.2;§2.2.1 与 §3.3 的非缺省来源 mcpp >= 2026.10.1.3;§3.8 mcpp >= 2026.10.8.1;§3.9 至 §3.11 mcpp >= 2026.10.24.1;v0.11 条款 mcpp >= 2026.11.10.1;v0.14 条款 mcpp >= 2026.11.23.1 | -| [SPEC-007](build-plugins.md) | 构建插件:配置、施工与校验的分工,运行时与规划期的义务 | 草案 v0.16 | 2026-11-21 | 逐条标注;mcpp >= 2026.9.26.2;v0.3 条款 mcpp >= 2026.9.27.1;v0.4 条款 mcpp >= 2026.9.28.1;v0.5 条款 mcpp >= 2026.9.28.2;v0.6(§9)mcpp >= 2026.9.28.3;R3.9、R3.10 mcpp >= 2026.10.10.1;§10 mcpp >= 2026.10.11.1;§3.1 协议 18 mcpp >= 2026.11.5.1;协议 19 mcpp >= 2026.11.16.1;协议 20、R10.7 mcpp >= 2026.11.19.1;协议 21、R10.8–R10.10 mcpp >= 2026.11.21.1 | +| [SPEC-007](build-plugins.md) | 构建插件:配置、施工与校验的分工,运行时与规划期的义务 | 草案 v0.17 | 2026-12-05 | 逐条标注;mcpp >= 2026.9.26.2;v0.3 条款 mcpp >= 2026.9.27.1;v0.4 条款 mcpp >= 2026.9.28.1;v0.5 条款 mcpp >= 2026.9.28.2;v0.6(§9)mcpp >= 2026.9.28.3;R3.9、R3.10 mcpp >= 2026.10.10.1;§10 mcpp >= 2026.10.11.1;§3.1 协议 18 mcpp >= 2026.11.5.1;协议 19 mcpp >= 2026.11.16.1;协议 20、R10.7 mcpp >= 2026.11.19.1;协议 21、R10.8–R10.10 mcpp >= 2026.11.21.1;v0.17 mcpp >= 2026.12.4.1 | | [SPEC-008](library-interface.md) | 库的接口:公开模块、发布闭包与两种形态的一致 | 草案 v0.2 | 2026-10-11 | 第一阶段(只警告)mcpp >= 2026.9.28.3;v0.2 mcpp >= 2026.10.11.1 | | [SPEC-009](toolchain-maintenance.md) | 工具链的支持与维护:版本线、默认值、来源、移动与退役 | 草案 v0.7 | 2026-11-21 | 逐条标注;本版只有规范,多数条款未实现;§6.4 mcpp >= 2026.10.8.1 | | [SPEC-010](home-initialization.md) | home 选择、单跳入口、初始化、网络边界、单次运行的 `--home` 与来自目录的 home | 草案 v0.3 | 2026-11-21 | mcpp >= 2026.10.19.1;网络能力逐条标注;§6 mcpp >= 2026.10.26.1、xlings >= 2026.10.26.1 | | [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁与计划的锁、等待的报告与上限、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.4 | 2026-12-05 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1;§2 第 7 至 10 条、§2.1、§2.2、§5.1 第 13 条 mcpp >= 2026.12.4.1 | | [SPEC-012](human-output.md) | 面向人的输出:两条流、两种介质、行的种类、颜色、程序的文本 | 评审中 v1.1 | 2026-11-19 | mcpp >= 2026.10.26.1;§5 mcpp >= 2026.11.19.1 | | [SPEC-013](platforms.md) | 平台:`[platform]` 的七组键、版本组与 `hosted`,三种写法与层次,目标图与宿主图的选择,`cfg(platform)`,依赖图的补全,链接、命名与封装,运行器与载体,平台阶段与协议 17 | 评审中 v1.17 | 2026-11-23 | mcpp >= 2026.10.27.1;§10 的执行宿主与 §11 的载体架构 mcpp >= 2026.10.29.1;§7.5 版本组参与解析与 §14 平台系列 mcpp >= 2026.11.7.1;§14 内置平台为确切版本 mcpp >= 2026.11.7.2;v1.7 条款 mcpp >= 2026.11.10.1;§14 索引的平台列 mcpp >= 2026.11.17.1;§14 系列取可用的最新版本与 §15.1 的 `+b` 条目 mcpp >= 2026.11.19.1;v1.17 条款 mcpp >= 2026.11.23.1 | -| [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.2 | 2026-11-10 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1 | +| [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.9 | 2026-12-05 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1;v2.9 mcpp >= 2026.12.4.1 | | [SPEC-015](target-sets.md) | 目标集合与腿:集合的写法与展开,命令对多条腿的语义,串行规划与一起构建,测试归档,机器输出 | 评审中 v1.0 | 2026-10-30 | mcpp >= 2026.10.30.1 | | [SPEC-016](targets-and-providers.md) | 目标与提供者:行、提供者、选择规则、平台定义的行、C 环境与执行、报告、机器输出与锁 | 评审中 v1.10 | 2026-11-27 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.9 条款 mcpp >= 2026.11.23.1;v1.10 条款 mcpp >= 2026.11.27.1 | | [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 | diff --git a/docs/specs/build-plugins.md b/docs/specs/build-plugins.md index d56ec1198..50d7ab6b2 100644 --- a/docs/specs/build-plugins.md +++ b/docs/specs/build-plugins.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-007 | | 标题 | 构建插件:配置、施工与校验的分工,运行时与规划期的义务 | -| 状态 | 草案 v0.16 | -| 版本 | 0.16 | -| 最后修改 | 2026-11-21 | -| 对应实现 | 逐条标注。未注明版本的「已实现」条款对应 mcpp >= 2026.9.26.1;注明 mcpp#702 的条款对应 mcpp >= 2026.9.26.2;注明 mcpp#707、#708、#709、#711 的条款对应 mcpp >= 2026.9.27.1;注明 mcpp#723 的条款对应 mcpp >= 2026.9.28.1;注明 mcpp 2026.9.28.2 的条款对应该版本;§9 与注明 mcpp#734 的条款对应 mcpp >= 2026.9.28.3;注明 mcpp#778 的条款对应 mcpp >= 2026.10.10.1;§10 对应 mcpp >= 2026.10.11.1;R9.10 与协议 17 对应 mcpp >= 2026.10.27.1;§3.1 与协议 18 对应 mcpp >= 2026.11.5.1;协议 19 对应 mcpp >= 2026.11.16.1;协议 20 与 R3.16、R3.17、R6.7、R10.7 对应 mcpp >= 2026.11.19.1;协议 21 与 R10.8–R10.10 对应 mcpp >= 2026.11.21.1 | +| 状态 | 草案 v0.17 | +| 版本 | 0.17 | +| 最后修改 | 2026-12-05 | +| 对应实现 | 逐条标注。未注明版本的「已实现」条款对应 mcpp >= 2026.9.26.1;注明 mcpp#702 的条款对应 mcpp >= 2026.9.26.2;注明 mcpp#707、#708、#709、#711 的条款对应 mcpp >= 2026.9.27.1;注明 mcpp#723 的条款对应 mcpp >= 2026.9.28.1;注明 mcpp 2026.9.28.2 的条款对应该版本;§9 与注明 mcpp#734 的条款对应 mcpp >= 2026.9.28.3;注明 mcpp#778 的条款对应 mcpp >= 2026.10.10.1;§10 对应 mcpp >= 2026.10.11.1;R9.10 与协议 17 对应 mcpp >= 2026.10.27.1;§3.1 与协议 18 对应 mcpp >= 2026.11.5.1;协议 19 对应 mcpp >= 2026.11.16.1;协议 20 与 R3.16、R3.17、R6.7、R10.7 对应 mcpp >= 2026.11.19.1;协议 21 与 R10.8–R10.10 对应 mcpp >= 2026.11.21.1;协议 22 与 R2.5 对应 mcpp >= 2026.12.4.1 | | 相关设计文档 | `.agents/docs/2026-09-26-compile-database-and-issue-699-design.md`(§5)、`.agents/docs/2026-09-28-ecosystem-design-and-optimisation-plan.md`(WS1、WS3)、`.agents/docs/2026-09-28-build-cost-foreign-toolsets-and-library-surface-design.md`(§3、§4)、`.agents/docs/2026-10-10-one-source-one-meaning-design.md`(§4)、`.agents/docs/2026-10-11-build-dependencies-one-pipeline-design.md` | | 相关 issue | mcpp#699、mcpp#701、mcpp#702、mcpp#703、mcpp#707、mcpp#708、mcpp#709、mcpp#711、mcpp#734、mcpp#755、mcpp#778、mcpp#797、mcpp#852、mcpp#991 | | 使用文档 | [docs/30 - build.mcpp](../30-build-mcpp.md)、[docs/31 - 编写规则包](../31-authoring-a-rule-package.md) | @@ -79,6 +79,7 @@ | 生成的源 | `generated`、`source` 与 `role = "source"` 的 action | `generated`、`source`、`action` | 协议 1 | | 重新运行构建程序的依据 | `rerun_if_changed`、`rerun_if_changed_glob`、`rerun_if_env_changed` | 同名 | 协议 1、2 | | 报告与探测 | `warning`;`fact`、`floor` | 同名 | 协议 5、7 | + | 其他构建系统安装的包,以其 CPS 描述(R2.5) | `cps_package` | `cps-package` | 协议 22 | - **R2.2** 相对路径按声明它的包的根目录解析。插件**禁止**把宿主系统目录(`/usr/include`、 `/usr/lib`、`/lib`、`C:\Windows\System32` 及同类)声明为头文件、链接或运行时搜索目录;SDK @@ -89,6 +90,14 @@ - **R2.4** 链接选项的一个元素按 SPEC-004 §8 读成词,每个词原样到达链接器。插件**禁止**依赖 引擎内部的转义拼写(例如 `'$$ORIGIN'`)。(**已实现**,mcpp#703;此前 `ldflags` 与 `link_flag` 中的 `$` 会被宿主 shell 展开) +- **R2.5** `cps_package` 声明的包由引擎在构建程序运行之后、任何指令被检查、应用与记录之前读取:在所列前缀 + (相对声明它的包的根目录)中按 CMake 的位置查找 `<名>.cps` 及其补充文件,候选的 `platform` 中写出的字段**必须**与 + 构建的目标侧相符、版本**必须**满足所要求的版本,所取组件按 `requires`、`link_requires`、`compile_requires` + 闭合,属性取 profile 所偏好的配置;结果**必须**以本表中前述各行的指令应用(`include-dir`、`cflag`、`cxxflag`、 + `link-flag`、`runtime-search-dir`、`rerun-if-changed`),程序的记录持有这些指令而不持有声明。读取的结果不是依赖图 + 的节点。无法回答的声明被拒绝,原因码为 `cps-no-matching-package`、`cps-components-unstated`、 + `cps-component-not-found`、`cps-description-invalid`(docs/14)。工具链阶段与平台阶段**禁止**这条声明。 + (**已实现**,mcpp >= 2026.12.4.1) ## 3. 施工:action @@ -297,6 +306,7 @@ | 19 | 2026.11.16.1 | 包格式提供者陈述它组装产物所取的程序:`pack_program`(`mcpp:pack-program=`,SPEC-014 §6);一条陈述的运行器:`runner_spec`(`mcpp:runner-spec=`,一个 JSON 载荷,字段与 SPEC-013 §10 的表一一对应;同一名字不能既由它又由逐词调用陈述) | | 20 | 2026.11.19.1 | 链接单元的对象清单:`objects_of`、`objects_rsp_of`(`${mcpp.objects:<名字>}`、`${mcpp.objects_rsp:<名字>}`,R3.16);`dep_bin` 对未声明的工具陈述 `mcpp:undeclared-tool=`(R6.7) | | 21 | 2026.11.21.1 | 类型化读取者按弃用的读法回答时陈述 `mcpp:deprecated=\t<问题>\t<拼写>`(R10.10) | + | 22 | 2026.12.4.1 | 以 CPS 描述声明的包:`cps_package`(`mcpp:cps-package=`,一个 JSON 载荷,R2.5) | - **R9.3** 构建信息以事实陈述解析出的工具链,不针对任何外部构建系统:`tool(role)`(这一行的 工具)、`abi_tool(role)`(目标 ABI 的原生工具,MSVC ABI 上为工具集的 `cl`、`link`、`lib`、 @@ -411,3 +421,4 @@ | 0.14 | 2026-11-19 | 随 mcpp 2026.11.19.1(设计 2026-11-19 §8):新增 R3.16(链接单元的对象清单,协议 20,mcpp#959)、R3.17(引擎自身命令的判据与 `${mcpp.self} write`)、R6.7(未声明的工具);R6.3 补充特性的工具到达链接该包库的每个构建程序(mcpp#955);R9.2 的协议表增加协议 20。 | | 0.15 | 2026-11-20 | 随 mcpp 2026.11.19.1(mcpp#972,设计 2026-11-19 §21 A1、A2):新增 R10.7 构建程序的库按程序解析;R10.2 构建程序图按版本划分。 | | 0.16 | 2026-11-21 | 随 mcpp 2026.11.21.1(mcpp#991、#852,设计 2026-11-21 构建程序的输入):R10.3 的身份覆盖编译读取;新增 R10.8 头文件的用法提示、R10.9 包外读取与发布的拒绝、R10.10 契约中名字的歧义按变量判定;R9.2 的协议表增加协议 21。 | +| 0.17 | 2026-12-05 | 随 mcpp 2026.12.4.1(设计 2026-11-27 §3.12):R2.1 的表与 R9.2 的协议表增加协议 22(`cps_package`);新增 R2.5 以 CPS 描述声明的包展开为既有指令。 | diff --git a/docs/specs/packaging.md b/docs/specs/packaging.md index 027c48a61..616557c83 100644 --- a/docs/specs/packaging.md +++ b/docs/specs/packaging.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-014 | | 标题 | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与包元数据,运行覆盖、单文件、容器列表、签名、压缩、合并与分发描述 | -| 状态 | 评审中 v2.8 | -| 版本 | 2.8 | -| 最后修改 | 2026-11-24 | -| 对应实现 | mcpp >= 2026.10.31.1;v2.2 条款 mcpp >= 2026.11.10.1;v2.3 条款 mcpp >= 2026.11.12.1;v2.4 条款 mcpp >= 2026.11.13.1;v2.5 条款 mcpp >= 2026.11.16.1;v2.6 条款 mcpp >= 2026.11.17.1;v2.7 条款 mcpp >= 2026.11.23.1;v2.8 条款 mcpp >= 2026.11.24.1 | +| 状态 | 评审中 v2.9 | +| 版本 | 2.9 | +| 最后修改 | 2026-12-05 | +| 对应实现 | mcpp >= 2026.10.31.1;v2.2 条款 mcpp >= 2026.11.10.1;v2.3 条款 mcpp >= 2026.11.12.1;v2.4 条款 mcpp >= 2026.11.13.1;v2.5 条款 mcpp >= 2026.11.16.1;v2.6 条款 mcpp >= 2026.11.17.1;v2.7 条款 mcpp >= 2026.11.23.1;v2.8 条款 mcpp >= 2026.11.24.1;v2.9 条款(§2.2 `descriptions`、§8.1)mcpp >= 2026.12.4.1 | | 相关设计文档 | `.agents/docs/2026-11-15-ecosystem-gap-supplement-design.md`(§5)、`.agents/docs/2026-10-30-ecosystem-part2-ide-and-language-service-design.md`(§19.6)、`.agents/docs/2026-10-29-ecosystem-target-sets-packaging-and-editors-design.md`(§4、§13)、`.agents/docs/2026-10-28-platforms-part2-packaging-and-distribution-design.md`(§2–§7、§14)、`.agents/docs/2026-10-28-platforms-design.md`(§4.7)、`.agents/docs/2026-10-29-openkal-run-test-pack-design.md`(§2.2、§2.6) | | 相关 issue | mcpp#847、mcpp#849、mcpp#860 | | 相关规范 | [SPEC-007](build-plugins.md)(包格式提供者、artifact action)、[SPEC-011](concurrency.md)(原子发布)、[SPEC-013](platforms.md)(平台、运行器、载体)、[SPEC-015](target-sets.md)(目标集合与腿) | @@ -173,6 +173,7 @@ openkal 目标上 `static` 为一个 `.oke`、无 `.okso`,`shared` 为 `.oke` | `universal` | 已弃用(docs/51 的 `pack-universal`):`true` 被拒绝,出路 `[pack] targets = ["openkal"]`;`false` 写出提示后忽略 | | `include`、`exclude` | 工程中按 glob 选出的文件(相对工程根),放在暂存树中同样的相对路径下,一个包只放一份(树亦然);`exclude` 去掉其中匹配的文件;`mcpp-package.json` 中角色为 `resource` | | `strip`、`debug_symbols`、`[pack.bundle-project]` | 既有键 | +| `descriptions` | 库包写给其他构建系统的描述(§8.1):`"pkg-config"`、`"cps"` 的列表;未写为两者,空表为都不写;其他词被拒绝 | ## 3. 管线 @@ -471,6 +472,23 @@ openkal 目标的单文件:载体携带一条腿的映像本身(映像不引用 不带 `--package` 时 `mcpp emit xpkg` 照旧生成源码包的描述。 +### 8.1 库包的描述 + +- `mcpp pack` 为库目标写出的包**必须**带 `mcpp-package.json`(`kind = "library"`,§4.5),它是 mcpp 对该包的权威 + 描述。`.pc` 与 `.cps` 是由同一组事实生成的、写给其他构建系统的写法,mcpp 不读回它们。 +- 带头文件接口的包每条腿写出 `lib/<三元组>/pkgconfig/<身份>.pc` 与 `lib/<三元组>/cps/<身份>/<身份>.cps` + (`[pack] descriptions` 所选的那些),在 `mcpp-package.json` 中角色为 `metadata`。`.cps` 合乎 CPS 0.15.0:`cps_path` + 为 `@prefix@/lib/<三元组>/cps/<身份>`,`compat_version` 按语义化版本,`platform` 取自该腿的三元组与 C++ 标准库,一个 + 以包名为名的组件(静态库为 `archive`,共享库为 `dylib`,PE 上导入库为 `link_location`),`includes` 为 + `@prefix@/include`,`ldflags` 的 `-l` 词为 `link_libraries`,依赖为包一级的 `requires` 与组件一级的 + `<依赖>:<名>`(静态库的 `private` 依赖为 `link_requires`,共享库不写),兼容标签为 `x_mcpp_abi`;不写 + `definitions`。每条腿一个目录,因为读者(CMake 4.5)不比较 `platform`。 +- 只有模块接口的包两者都不写,说明为 `pack/no-header-interface`。 +- `mcpp emit xpkg --package` 为库包写出的条目以 `pcall` 调用索引的 `xim.pkgindex.sysroot`:安装时 + `relocate_pkgconfig`、`relocate_cps`(写入绝对的前缀),配置时 `declare_pkgconfig`、`declare_cps`(放进环境的 + `usr/lib/pkgconfig/` 与 `usr/lib/cps/<身份>/`);索引没有这些函数时写出描述所在的目录并成功。同一系统与架构有两条腿 + 时条目不向环境给出两种描述,说明为 `emit/two-legs-for-one-system`。 + ## 9. 机器输出 `mcpp pack --message-format json` 打印一个 `mcpp.pack` 信封(docs/50)。`data` 增加: @@ -530,3 +548,4 @@ openkal 目标的单文件:载体携带一条腿的映像本身(映像不引用 | 2.5 | 2026-11-16 | mcpp 2026.11.16.1(设计 2026-11-15 N11、N20):§4.3 携带运行器的包不回落到 `PATH`,本机没有时以 126 退出并写出所含各项;`` 取系统表的 `uname`;`--all-programs` 的树中每个程序有自己的启动器;§6 `mcpp::pack_program` 与提供者不提交的原因(N30)。 | | 2.7 | 2026-11-23 | mcpp 2026.11.23.1(mcpp#1011):§1.2 部署的对象是闭包的根,其需求按程序的规则解析与携带。 | | 2.8 | 2026-11-24 | mcpp 2026.11.24.1:§6 `-o <目录>/` 写入提供者的产物及其在产物目录下消费的输出。 | +| 2.9 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.3、§3.12):§2.2 增加 `descriptions`;新增 §8.1 库包的描述:`mcpp-package.json`、每条腿的 `.pc` 与 `.cps`、条目对环境的一面。 | diff --git a/docs/zh/03-examples.md b/docs/zh/03-examples.md index 9dffbd2b4..d3cb5bc72 100644 --- a/docs/zh/03-examples.md +++ b/docs/zh/03-examples.md @@ -40,6 +40,7 @@ mcpp build && mcpp run |---|---| | [`03-pack-static`](../../examples/03-pack-static/) | `mcpp pack --mode static`、`[target.]`、`[pack]` | | [`05-lib-distribution`](../../examples/05-lib-distribution/) | 一个库的接口与它的预编译二进制;从同一份源产出 C 头文件与 C++ 模块 | +| [`14-cps`](../../examples/14-cps/) | `mcpp::cps_package`:经 CPS 描述读取其他构建系统安装的包;另一个方向见 [`05-lib-distribution/cmake-consumer`](../../examples/05-lib-distribution/cmake-consumer/) | ### C —— 环境 diff --git a/docs/zh/10-pack-and-release.md b/docs/zh/10-pack-and-release.md index c72574de7..6d358a9cb 100644 --- a/docs/zh/10-pack-and-release.md +++ b/docs/zh/10-pack-and-release.md @@ -907,6 +907,7 @@ compress = "zstd" # the default of --compress sign = ["signtool", "sign", "{}"] # run on each program, image, library and loader before the container strip = true # default. false ships the artifacts as built debug_symbols = "dist/debug" # separate the debug info here instead of discarding it +descriptions = ["pkg-config", "cps"] # 库包写给其他构建系统的描述(14) include = ["share/**", "config/*.toml"] # 工程文件,放在包中同样的相对路径下,只放一份 exclude = ["debug/**"] diff --git a/docs/zh/12-binary-distribution.md b/docs/zh/12-binary-distribution.md index 40c27c635..9ae27f5d1 100644 --- a/docs/zh/12-binary-distribution.md +++ b/docs/zh/12-binary-distribution.md @@ -255,10 +255,17 @@ Requires.private: <包的依赖,以其身份为名> `Libs.private` 为包的 `ldflags` 中的 `-l` 词。`prefix` 相对该文件给出,以路径使用库包的消费者原样读取它。条目经索引 自带的两个函数(`xim.pkgindex.sysroot` 的 `relocate_pkgconfig`、`declare_pkgconfig`)把 `.pc` 放进环境的 pkg-config 视图;索引中没有这两个函数时,安装写出 `.pc` 所在的目录并成功。同一系统与架构有两条腿(两个 C 库) -的包不向环境给出 `.pc`,`emit xpkg` 说明这一点(`emit/two-legs-for-one-system`)。 +的包不向环境给出 `.pc` 与 `.cps`,`emit xpkg` 说明这一点(`emit/two-legs-for-one-system`)。 -边界有三条。`.pc` 描述头文件接口:只有模块接口的包不写它,说明为 `pack/no-header-interface`。pkg-config -不核对 ABI:`mcpp_abi` 可读,核对只在 mcpp 一侧。静态库包不携带依赖的二进制:mcpp 以外的消费者须在环境中另有 +每条腿在其旁另有一份 CPS 描述 `lib//cps//.cps`,取自同一组事实:一个以包名为名的组件 +(`archive` 或 `dylib`,PE 上导入库为 `link_location`)、`@prefix@/include`、`-l` 词作 `link_libraries`、依赖作对其 +自身组件的要求、该腿的平台(`isa`、`kernel`、C 与 C++ 运行时的厂商)与以 `x_mcpp_abi` 写出的标签。CMake 4.3 及以后 +以 `CMAKE_PREFIX_PATH=<包>/lib/` 找到它并链接 `::`;两个方向见 +[14 —— Common Package Specification](14-cps.md)。条目以 `relocate_cps`、`declare_cps` 给 `.cps` 写入绝对前缀并放进 +环境的 `usr/lib/cps/`,与 `.pc` 相同。`[pack] descriptions` 选择写出哪几种(默认两种)。 + +边界有三条。`.pc` 与 `.cps` 描述头文件接口:只有模块接口的包两者都不写,说明为 `pack/no-header-interface`。 +pkg-config 与 CMake 不核对 ABI:`mcpp_abi` 与 `x_mcpp_abi` 可读,核对只在 mcpp 一侧。静态库包不携带依赖的二进制:mcpp 以外的消费者须在环境中另有 这些依赖及其描述,说明为 `pack/closure-not-in-package`;把依赖链接进自身的共享库包携带闭包。 ### 在包目录内直接构建被拒绝 diff --git a/docs/zh/14-cps.md b/docs/zh/14-cps.md new file mode 100644 index 000000000..b49cffc7a --- /dev/null +++ b/docs/zh/14-cps.md @@ -0,0 +1,146 @@ +# 14 —— Common Package Specification + +[English](../14-cps.md) | **简体中文** + +**读者:** 库被 CMake 使用的发布者,以及构建要使用 CMake 安装的库的作者。 + +**本章回答的那一个问题:** mcpp 以 Common Package Specification(CPS,版本 0.15.0)写出与读取什么,每个方向对构建意味着 +什么。 + +**不在这里:** 库包本身见 [12 —— 分发预编译库](12-binary-distribution.md),构建程序的一般规则见 +[30 —— build.mcpp](30-build-mcpp.md)。 + +## 立场 + +mcpp 对一个包的描述是它的清单与 `mcpp-package.json`;依赖图中只有 mcpp 的包。CPS 是两条边界上的兼容,不改变两者: + +| 方向 | mcpp 的行为 | 章节 | +|---|---|---| +| 向外 | `mcpp pack` 为库包的每条腿写出一份 `.cps`,取自写出 `.pc` 的同一组事实 | [12](12-binary-distribution.md) | +| 向内 | 构建程序声明一个由其他构建系统安装的包,构建得到该包的 `.cps` 所陈述的、即程序会写出的那些指令 | [30](30-build-mcpp.md) | + +经 CPS 读取的包不是依赖图的节点:它不进锁,不由索引解析,声明它的包的消费者的编译也看不到它,与 `deps-cmake`、 +`deps-vcpkg` 插件映射进来的包相同。 + +## 向外:库包的 `.cps` + +带头文件接口的库包每条腿在 `lib//pkgconfig/.pc` 旁带有 +`lib//cps//.cps`: + +```json +{ + "cps_version": "0.15.0", + "name": "mathkit", + "version": "0.1.0", + "version_schema": "simple", + "compat_version": "0.1.0", + "cps_path": "@prefix@/lib/x86_64-linux-gnu/cps/mathkit", + "platform": { "isa": "x86_64", "kernel": "linux", + "c_runtime_vendor": "gnu", "cpp_runtime_vendor": "gnu" }, + "x_mcpp_abi": "x86_64-linux-gnu-gcc16-libstdcxx16-c++23", + "default_components": ["mathkit"], + "components": { + "mathkit": { + "type": "archive", + "location": "@prefix@/lib/x86_64-linux-gnu/libmathkit.a", + "includes": ["@prefix@/include"], + "link_libraries": ["m"], + "link_languages": ["cpp"] + } + } +} +``` + +| 字段 | 来源 | +|---|---| +| `name` | 包的身份,有命名空间时为 `.` | +| `compat_version` | 包兼容的最早版本:`<主>.0.0`,主版本为零时为 `0.<次>.0` | +| `platform` | 该腿的三元组与 C++ 标准库,以 CPS 的词写出 | +| 组件 | 以包名为名;静态库为 `archive`,共享库为 `dylib`,PE 上导入库为 `link_location` | +| `link_libraries` | 包的 `ldflags` 中的 `-l` 词 | +| `link_languages` | 含 C++ 目标文件的归档为 `cpp` | +| `requires` | 每个依赖,以其身份为名,带其要求所容许的最低版本;组件要求 `<依赖>:<名>`,静态库的 `private` 依赖为 `link_requires` | + +包没有公开的宏,因此文件不写 `definitions`。每条腿有自己的目录:CMake 不比较 `platform`,腿由文件所在的位置选定。 +CMake 4.3 及以后以该腿的目录为前缀找到它: + +```cmake +find_package(mathkit REQUIRED) # CMAKE_PREFIX_PATH=<包>/lib/x86_64-linux-gnu +target_link_libraries(app mathkit::mathkit) +``` + +在库架构即该三元组的多架构主机上,包的根目录就是前缀。`[pack] descriptions` 选择写出的描述: + +```toml +[pack] +descriptions = ["pkg-config", "cps"] # 默认值;可写 ["pkg-config"]、["cps"] 或 [] 以少写 +``` + +只发布模块接口的包两种描述都不写(`pack/no-header-interface`):CMake 不经 CPS 导入 C++ 模块。 +`mcpp emit xpkg --package` 写出的索引条目给 `.cps` 写入包的绝对 `prefix`,并把它放进环境的 +`usr/lib/cps//`(`xim.pkgindex.sysroot` 的 `relocate_cps`、`declare_cps`),该环境中的 CMake 以环境的 +`usr/` 为前缀即可找到它。 + +## 向内:`mcpp::cps_package` + +构建程序以一个包的 CPS 描述声明它(协议 22): + +```cpp +import mcpp; +int main() { + mcpp::cps_package imaging; + imaging.name = "Imaging"; + imaging.prefix("third_party/prefix"); // 相对包的根目录,或绝对路径 + imaging.component("image"); // 不写时取包的默认组件 + imaging.submit(); +} +``` + +| 字段 | 含义 | +|---|---| +| `name` | 包的 CPS 名 | +| `prefix(dir)` | 一个安装前缀,按给出的次序查找 | +| `component(c)` | 构建使用的组件;不写时取包的 `default_components` | +| `version` | 所要求的版本:候选从其 `compat_version` 到其 `version` 满足它 | +| `configuration` | 读取的配置,覆盖 profile 的偏好 | + +引擎在程序运行之后读取描述,以下列指令应用它,程序的记录随后持有的就是这些指令: + +| 描述陈述的 | 构建得到的 | +|---|---| +| 不分语言的 `includes` | `include-dir` | +| C 或 C++ 的 `includes`、`definitions`、`compile_flags` | `cflag`、`cxxflag` | +| `archive` 或 `dylib` 的库、`link_libraries`、`link_flags` | `link-flag`,库以其路径 | +| `dylib` 所在的目录 | `runtime-search-dir` | +| 读过的每个文件 | `rerun-if-changed` | + +编译的一面到达声明它的包,链接的一面到达其消费者的链接,`mcpp pack` 经运行时目录找到共享库,与手写同样的指令 +相同。描述改变时程序重新运行。 + +**查找。** 在每个前缀中依次查找 `cps//`、`cps//*/`、`cps/`、`/cps/`、`/*/cps/`、 +`lib*/cps//`、`lib*/cps//*/`、`lib/*/cps//`、`lib*/cps/`、`share/cps//`、 +`share/cps//*/`、`share/cps/` 中原样与小写的 `.cps`。文件旁的 `-*.cps` 增加组件, +`@<配置>.cps` 增加一个配置的属性。 + +**匹配。** 候选的 `platform` 中写出的字段与这次构建的比较,大小写不计(`isa`、`kernel`、C 与 C++ 运行时的厂商); +未写出的字段不构成约束。不符的候选,或版本不满足要求的候选,被跳过。 + +**组件。** 组件的 `requires` 在同一组前缀中读取,其编译与链接的属性都到达构建;`link_requires` 的组件只到达链接, +`compile_requires` 的组件只到达编译。库排在它所需要的库之前。 + +**配置。** 声明的 `configuration`;否则 profile 的偏好(`dev`:`Debug`;`release`:`Release`、`RelWithDebInfo`、 +`MinSizeRel`);否则包的 `configurations`;否则按名字的第一个。配置的列表接在组件的之后,它的位置取代组件的。 + +**拒绝与说明。** + +| 情形 | 原因码 | +|---|---| +| 前缀中没有该包的描述,或没有一个是为这次构建的平台或所要求的版本;消息列出查找过的位置,或每个候选与它不符的字段 | `cps-no-matching-package` | +| 没有指定组件,包也没有陈述默认组件 | `cps-components-unstated` | +| 指定的或被要求的组件不在它的包中 | `cps-component-not-found` | +| 文件不是 CPS,或无法由 `cps_path`、`prefix` 求得前缀 | `cps-description-invalid` | +| 组件描述 C++ 模块:使用其库与头文件 | 说明 `cps/modules-not-imported` | +| 组件为 `executable`、`module`、`jar` 或 `symbolic`:它不进入编译与链接 | 说明 `cps/component-not-linked` | + +**不读取的。** 前缀在构建程序运行时已经存在。由 `prepare` 动作在构建时填好的前缀(CMake 子工程、vcpkg 清单) +以库名使用,如 `deps-cmake`、`deps-vcpkg` 所取,因为一次构建的名字在程序运行时就已固定。 diff --git a/docs/zh/30-build-mcpp.md b/docs/zh/30-build-mcpp.md index 4d1a5abb2..7a6945230 100644 --- a/docs/zh/30-build-mcpp.md +++ b/docs/zh/30-build-mcpp.md @@ -172,6 +172,7 @@ int main() { | `mcpp::run_host(h)` *(协议 17)* | `mcpp:run-host=` —— `"same-arch"` 或 `"any"`;即 `runner.host` | | `mcpp::runner(tok)` *(2026.8.19.2+)* | `mcpp:runner=` —— 见下 | | `mcpp::runner_spec` *(协议 19)* | `mcpp:runner-spec=` —— 一条陈述的 runner,与数据中的表逐字段对应;见下 | +| `mcpp::cps_package` *(协议 22)* | `mcpp:cps-package=` —— 以 CPS 描述声明的、由其他构建系统安装的包,以 `include-dir`、`cflag`、`cxxflag`、`link-flag`、`runtime-search-dir`、`rerun-if-changed` 应用;见下 | | `mcpp::xpkg_dir(ns, name)` / `mcpp::xpkg_dir(name)` *(2026.8.19+)* | `[xlings.workspace]` 里声明的包的载荷目录 —— 本 manifest 声明的,或编进本构建程序的某个依赖声明的(2026.9.6.6+);没声明或没安装时返回 `""`(见下) | | `mcpp::xpkg_source(ns, name)` / `mcpp::xpkg_program(ns, name)` *(协议 15)* | 该载荷从哪里来 —— `payload`、`override`、`pending` 或 `""` —— 以及一条覆盖点名的程序 | | `mcpp::xpkg_request(ns, name)` / `mcpp::xpkg_pending()` *(协议 15)* | 一个声明了 `provision = "on-request"` 的载荷的目录;尚未安装时请求它,此时 `xpkg_pending()` 为真,程序应当返回(见下) | @@ -297,6 +298,22 @@ web.submit(); `{}` 是产物,`{pkg:}` 是 `require()` 中该包的根,由第一次使用该 runner 的 `mcpp run` 或 `mcpp test` 安装,构建 不安装。一个 runner 只用一种方式陈述:同一名字既由 `runner_spec` 又由逐词调用陈述、同一名字提交两次、没有命令、或 `host` 不是两个词之一时,在应用任何指令之前拒绝。逐词调用保持原义;覆盖、`enabled` 与每个名字一个提供者遵循数据的规则。 + +### `cps_package` —— 以 CPS 描述声明一个包(2026.12.4.1+,协议 22) + +```cpp +mcpp::cps_package imaging; +imaging.name = "Imaging"; // 包的 CPS 名 +imaging.prefix("third_party/prefix"); // 相对包的根目录,或绝对路径;可多次 +imaging.component("image"); // 不写:包的默认组件 +imaging.submit(); +``` + +`version` 要求一个版本,`configuration` 覆盖 profile 的偏好。引擎在各前缀中找到 `.cps`,以构建的平台核对它的 +平台,按组件的要求闭合组件,并在应用与记录任何指令之前,把它们所陈述的作为上表中的指令应用:程序的记录持有这些 +指令,描述改变时程序重新运行。程序运行时前缀已经存在。查找、匹配、配置与拒绝(`cps-no-matching-package`、 +`cps-components-unstated`、`cps-component-not-found`、`cps-description-invalid`)见 +[14 —— Common Package Specification](14-cps.md)。 :`toolchain_dir` / `sysroot_dir`(2026.8.19.4+) ```cpp diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 3caaef6b8..765c8b5ba 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -651,6 +651,10 @@ replaced}` —— `origin` 与构建的状态行使用的是同一句话 | `package-without-description` | 早先的 mcpp 写出的库包不带 mcpp-package.json,而条目由它写出 *(2026.12.4.1+)* | | `emit-inside-a-package` | `mcpp emit xpkg` 在库包的目录中运行,那不是源码树 *(2026.12.4.1+)* | | `package-built-outside-the-ecosystem` | 包由以路径点名的工具链构建,它的环境不是条目能供给的 *(2026.12.4.1+)* | +| `cps-no-matching-package` | 构建程序的 `mcpp::cps_package` 所指的包在其前缀中没有相符的描述:没有,或没有一个是为这次构建的平台或所要求的版本 *(2026.12.4.1+)* | +| `cps-components-unstated` | 构建程序的 `mcpp::cps_package` 没有指定组件,包也没有陈述默认组件 *(2026.12.4.1+)* | +| `cps-component-not-found` | `mcpp::cps_package` 指定的组件或其所需的组件不在它的包中 *(2026.12.4.1+)* | +| `cps-description-invalid` | `mcpp::cps_package` 读到的文件不是 CPS 描述,或无法由它求得前缀 *(2026.12.4.1+)* | | `other` | 一个尚未被赋予记号的拒绝分支 | **其中一个记号也由 `mcpp build` 自己打印。** `interface-not-provided` 会 diff --git a/docs/zh/README.md b/docs/zh/README.md index 1f175c51f..e15489876 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -72,6 +72,7 @@ - [11 —— 发布一个库到 mcpp-index](11-publishing-a-library.md) - [12 —— 分发预编译库](12-binary-distribution.md) - [13 —— 代码与工程风格](13-code-and-project-style.md)——模块的形态、头文件、宏,以及 mcpp 的构建所增加的 +- [14 —— Common Package Specification](14-cps.md)——库包带的 `.cps`,以及构建程序的 `cps_package` ### 2x —— 工具链与目标 diff --git a/examples/05-lib-distribution/README.md b/examples/05-lib-distribution/README.md index d45a7e973..70f3c6f99 100644 --- a/examples/05-lib-distribution/README.md +++ b/examples/05-lib-distribution/README.md @@ -3,8 +3,9 @@ Both halves of one story, because they are only interesting together: ``` -producer/ a library with TWO interfaces — a C header and a C++ module -consumer/ three programs using it: header only, module only, both +producer/ a library with TWO interfaces — a C header and a C++ module +consumer/ three programs using it: header only, module only, both +cmake-consumer/ a C program CMake builds against the same package, through its CPS description ``` ```bash @@ -103,3 +104,18 @@ x86_64-linux-gnu # an extern "C" interface only A tag names the dimensions the artifact actually constrains, and unnamed ones are don't-care. So an `extern "C"` library needs one tag per triple instead of one per triple per compiler — no flag, no mode: the shape *is* the statement. + +## A consumer that is not mcpp + +Each leg of the package carries `lib//pkgconfig/mathkit.pc` and +`lib//cps/mathkit/mathkit.cps`, written from the same facts. CMake 4.3 +and later reads the second with the leg's directory as the prefix: + +```bash +cd cmake-consumer +cmake -S . -B build -DCMAKE_PREFIX_PATH=../producer/target/dist/mathkit-0.1.0-/lib/ +cmake --build build && ./build/consume-c # mathkit_add(40, 2) = 42 +``` + +The C header is the interface such a consumer uses: CMake does not import C++ +modules through CPS. See [docs/14](../../docs/14-cps.md). diff --git a/examples/05-lib-distribution/cmake-consumer/CMakeLists.txt b/examples/05-lib-distribution/cmake-consumer/CMakeLists.txt new file mode 100644 index 000000000..5cc514f3c --- /dev/null +++ b/examples/05-lib-distribution/cmake-consumer/CMakeLists.txt @@ -0,0 +1,16 @@ +# A consumer that is not built by mcpp: CMake 4.3 or later finds the package +# `mcpp pack` wrote through the CPS description each leg carries +# (lib//cps/mathkit/mathkit.cps). Configure with the leg's directory as +# the prefix: +# +# cmake -S . -B build -DCMAKE_PREFIX_PATH=/target/dist/mathkit-0.1.0-/lib/ +# cmake --build build && ./build/consume-c +cmake_minimum_required(VERSION 4.3) +project(cmake_consumer LANGUAGES C CXX) + +find_package(mathkit REQUIRED) + +# The archive holds C++ objects (`link_languages = ["cpp"]`), so CMake links +# the program with the C++ driver; the program itself is C. +add_executable(consume-c main.c) +target_link_libraries(consume-c mathkit::mathkit) diff --git a/examples/05-lib-distribution/cmake-consumer/main.c b/examples/05-lib-distribution/cmake-consumer/main.c new file mode 100644 index 000000000..c6641b39e --- /dev/null +++ b/examples/05-lib-distribution/cmake-consumer/main.c @@ -0,0 +1,7 @@ +#include +#include + +int main(void) { + printf("mathkit_add(40, 2) = %d\n", mathkit_add(40, 2)); + return 0; +} diff --git a/examples/14-cps/README.md b/examples/14-cps/README.md new file mode 100644 index 000000000..591de18fc --- /dev/null +++ b/examples/14-cps/README.md @@ -0,0 +1,42 @@ +# 14 — A package described by CPS + +``` +third_party/prefix/ an installation another build system made, with lib/cps/Greeting/Greeting.cps +app/ a program whose build.mcpp declares the package by that description +``` + +```bash +cd app && mcpp run # hello from a CPS package +``` + +Full reference: [docs/14 — The Common Package Specification](../../docs/14-cps.md). + +## What the declaration does + +`build.mcpp` states one thing: + +```cpp +mcpp::cps_package greeting; +greeting.name = "Greeting"; +greeting.prefix("../third_party/prefix"); +greeting.submit(); +``` + +The engine finds `Greeting.cps` where CMake would, checks the platform it states +against the build's, takes the package's default components and applies what +they state as the directives a program writes itself: here `include-dir` for +`@prefix@/include/greeting` and `cxxflag`/`cflag` for `GREETING_TEXT`. A +compiled component adds its library by path (`link-flag`) and, for a shared +library, its directory as a run-time search directory. The program's record +holds those directives; editing `Greeting.cps` runs the program again. + +The package is not a dependency of `cps-app` in mcpp's graph: it is not locked, +and `cps-app`'s own consumers do not see its headers. A package mcpp should +resolve, lock and build belongs in `[dependencies]`; CPS is how a package that +another build system installed reaches a build. + +## The other direction + +A library `mcpp pack` writes carries a `.cps` for each leg, which CMake reads; +[`05-lib-distribution/cmake-consumer`](../05-lib-distribution/cmake-consumer/) +uses one. diff --git a/examples/14-cps/app/build.mcpp b/examples/14-cps/app/build.mcpp new file mode 100644 index 000000000..c83dbc382 --- /dev/null +++ b/examples/14-cps/app/build.mcpp @@ -0,0 +1,14 @@ +// The package in ../third_party/prefix is described by CPS, as CMake 4.3 and +// later install it. The declaration names it; the engine reads Greeting.cps and +// applies what it states (an include directory and a macro here; a library by +// its path and a run-time directory for a compiled one) as the directives this +// program could have written by hand. +import mcpp; + +int main() { + mcpp::cps_package greeting; + greeting.name = "Greeting"; + greeting.prefix("../third_party/prefix"); + greeting.submit(); + return 0; +} diff --git a/examples/14-cps/app/mcpp.toml b/examples/14-cps/app/mcpp.toml new file mode 100644 index 000000000..aa0b7e34b --- /dev/null +++ b/examples/14-cps/app/mcpp.toml @@ -0,0 +1,9 @@ +[package] +name = "cps-app" +version = "0.1.0" +description = "Demo: a package another build system installed, used through its CPS description" +license = "Apache-2.0" + +[targets.cps-app] +kind = "bin" +main = "src/main.cpp" diff --git a/examples/14-cps/app/src/main.cpp b/examples/14-cps/app/src/main.cpp new file mode 100644 index 000000000..ed3bda8c7 --- /dev/null +++ b/examples/14-cps/app/src/main.cpp @@ -0,0 +1,7 @@ +import std; +#include + +int main() { + std::println("{}", greeting()); + return 0; +} diff --git a/examples/14-cps/third_party/prefix/include/greeting/greeting.h b/examples/14-cps/third_party/prefix/include/greeting/greeting.h new file mode 100644 index 000000000..2ed9d4eca --- /dev/null +++ b/examples/14-cps/third_party/prefix/include/greeting/greeting.h @@ -0,0 +1,7 @@ +/* A header-only library another build system installed into this prefix. + GREETING_TEXT comes from the package's CPS description, not from here. */ +#pragma once +#ifndef GREETING_TEXT +#error "GREETING_TEXT is stated by Greeting.cps; the build did not read it" +#endif +static inline const char* greeting(void) { return GREETING_TEXT; } diff --git a/examples/14-cps/third_party/prefix/lib/cps/Greeting/Greeting.cps b/examples/14-cps/third_party/prefix/lib/cps/Greeting/Greeting.cps new file mode 100644 index 000000000..51f8e0a9f --- /dev/null +++ b/examples/14-cps/third_party/prefix/lib/cps/Greeting/Greeting.cps @@ -0,0 +1,14 @@ +{ + "cps_version": "0.15.0", + "name": "Greeting", + "version": "1.0.0", + "cps_path": "@prefix@/lib/cps/Greeting", + "default_components": ["greeting"], + "components": { + "greeting": { + "type": "interface", + "includes": ["@prefix@/include/greeting"], + "definitions": { "*": { "GREETING_TEXT": "\"hello from a CPS package\"" } } + } + } +} diff --git a/mcpp.toml b/mcpp.toml index 148e6c06c..472fba1d4 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -155,6 +155,7 @@ mcpp.build-record = { path = "modules/build-record" } mcpp.unit-cache = { path = "modules/unit-cache" } mcpp.surface = { path = "modules/surface" } mcpp.notice = { path = "modules/notice" } +mcpp.cps = { path = "modules/cps" } [target.linux.build] sources = ["!src/native/windows/**"] @@ -194,6 +195,7 @@ members = [ "modules/unit-cache", "modules/surface", "modules/notice", + "modules/cps", ] # `mcpp build` ignores [dev-dependencies]; only `mcpp test` resolves them. diff --git a/modules/buildmcpp/src/directives.cppm b/modules/buildmcpp/src/directives.cppm index b37969fb3..f7bcd1c0f 100644 --- a/modules/buildmcpp/src/directives.cppm +++ b/modules/buildmcpp/src/directives.cppm @@ -227,6 +227,12 @@ enum class Slot : std::size_t { // answered by the first (`ambiguous-contract-name`). The engine warns by // the registry's row, on a replay too. DeprecatedReadings, + // Protocol 22 (design 2026-11-27 §3.12.2 two): a package another build + // system installed, declared by its CPS description (`mcpp::cps_package`), + // one JSON payload. The engine reads it into the slots above before + // anything is applied (mcpp.build.cps_package), and the record holds what + // it was read into, never the declaration. + CpsPackages, Count }; inline constexpr std::size_t kSlotCount = static_cast(Slot::Count); @@ -282,6 +288,11 @@ enum class Scope { // consumer, a test binary or a second executable of the same package, it is // the defect #618 reports against `[build] ldflags`. TargetLink, + // EXPANDED, NEVER APPLIED. A declaration the engine reads into the + // directives of the other scopes before anything is applied, so it reaches + // the build exactly as those directives do; its slot is empty by the time + // `apply` and the record see the program's output. + Declaration, }; // How the raw wire value is normalized before it is stored. Applied ONCE, at @@ -325,7 +336,7 @@ struct Def { int sinceProtocol; }; -inline constexpr std::array kTable{{ +inline constexpr std::array kTable{{ // wire tag slot scope transform must missingPrefix missingSuffix since {"cxxflag", "cxxflag", Slot::CxxFlags, Scope::PackagePrivate, Transform::Verbatim, false, "", "", 1}, {"cflag", "cflag", Slot::CFlags, Scope::PackagePrivate, Transform::Verbatim, false, "", "", 1}, @@ -442,6 +453,12 @@ inline constexpr std::array kTable{{ {"diagnostic", "diagnostic", Slot::Diagnostics, Scope::Advisory, Transform::Verbatim, false, "", "", 14}, {"undeclared-tool", "undeclared-tool", Slot::UndeclaredTools, Scope::Advisory, Transform::Verbatim, false, "", "", 20}, {"deprecated", "deprecated", Slot::DeprecatedReadings, Scope::Advisory, Transform::Verbatim, false, "", "", 21}, + // A package installed by another build system, by its CPS description + // (protocol 22, design 2026-11-27 §3.12.2 two). No tag: it is expanded + // into `include-dir`, `cflag`, `cxxflag`, `link-flag`, + // `runtime-search-dir` and `rerun-if-changed` lines before the record is + // written, and those are what a replay applies. + {"cps-package", "", Slot::CpsPackages, Scope::Declaration, Transform::Verbatim, false, "", "", 22}, {"action", "action", Slot::Actions, Scope::GraphNode, Transform::Verbatim, false, "", "", 1}, // The probe channel: a rule package measures, the engine compares. See // Slot::Facts for the shape of each value. diff --git a/modules/buildmcpp/src/program_protocol.cppm b/modules/buildmcpp/src/program_protocol.cppm index e94214ce2..a930e594b 100644 --- a/modules/buildmcpp/src/program_protocol.cppm +++ b/modules/buildmcpp/src/program_protocol.cppm @@ -145,7 +145,14 @@ export namespace mcpp::build::program_protocol { // when it answers a name several dependencies answer by the first. An older // engine ignores the line with an unknown-directive warning; no directive of // v20 changes spelling. -inline constexpr int kProtocolVersion = 21; +// v22 (design 2026-11-27 §3.12.2 two): `mcpp::cps_package`, a package another +// build system installed, declared by its CPS description, on the wire +// `mcpp:cps-package={json}`. The engine reads the description and applies what +// it states as the directives `include-dir`, `cflag`, `cxxflag`, `link-flag`, +// `runtime-search-dir` and `rerun-if-changed`. Same cost as v5's: a package +// using it fails on an older engine at the build.mcpp COMPILE. No directive of +// v21 changes spelling. +inline constexpr int kProtocolVersion = 22; // ── Cache-format epoch ───────────────────────────────────────────────────── // diff --git a/modules/cps/mcpp.toml b/modules/cps/mcpp.toml new file mode 100644 index 000000000..c2a1ccf2c --- /dev/null +++ b/modules/cps/mcpp.toml @@ -0,0 +1,23 @@ +# mcpp.cps -- the Common Package Specification at mcpp's boundary (design 2026-11-27 §3.12). +# +# CPS is an optional compatibility, not a model of mcpp: `mcpp pack` writes a library package's +# facts as a `.cps` beside its `.pc`, and a build program's `mcpp::cps_package` declaration reads +# a package another build system installed into the effects of directives mcpp already has. This +# package is the format: the model, reading with its supplemental files, writing, version +# comparison, the translation between mcpp's words and CPS's (mcpp.cps), and the search, the +# platform match and the closure of components that answer a declaration (mcpp.cps.usage). It +# knows nothing of the plan, the pack pipeline or the directive table; the two use sites adapt. + +[package] +name = "cps" +namespace = "mcpp" +version = "0.1.0" +description = "The Common Package Specification: reading, writing and resolving .cps descriptions" +license = "Apache-2.0" + +[dependencies] +nlohmann.json = "3.12.0" +mcpp.libs = { path = "../libs" } + +[dev-dependencies] +mcpplibs.mtest = "0.11.3" diff --git a/modules/cps/src/cps.cppm b/modules/cps/src/cps.cppm new file mode 100644 index 000000000..9dd19e1e6 --- /dev/null +++ b/modules/cps/src/cps.cppm @@ -0,0 +1,671 @@ +// mcpp.cps -- one CPS description, as the specification states it (v0.15.0): the model, a file +// read with the supplemental files beside it, the text written for one, versions, where `@prefix@` +// is, and the words CPS uses for what mcpp calls a target (design 2026-11-27 §3.12). +// +// THE MODEL IS CPS'S, NOT MCPP'S. Nothing here is a package of mcpp's graph: the two users are +// `mcpp pack`, which fills a `Package` from the facts it already computed, and the expansion of a +// build program's `mcpp::cps_package`, which reads one into directives. A field this file does +// not model is not lost on the reading side (it has no effect mcpp could give it) and is never +// written. + +export module mcpp.cps; + +import std; +import nlohmann.json; +import mcpp.libs.path_identity; + +export namespace mcpp::cps { + +// The version of the specification this file reads and writes. +inline constexpr std::string_view kSpecVersion = "0.15.0"; + +// A value stated for every language (`"*"`) or for one (`"c"`, `"cpp"`, ...): the list form of +// `includes` and `compile_flags` reads as `"*"`. +using ByLanguage = std::map>; +// `definitions`: language, then name, then value; no value is `-D`. +using Definitions = std::map>>; + +// What a component and each of its configurations state. A list a configuration states is +// appended to the component's; a location replaces it (`merged`). +struct Attributes { + ByLanguage includes; + Definitions definitions; + ByLanguage compileFlags; + std::string location; + std::string linkLocation; + std::vector requires_; + std::vector linkRequires; + std::vector compileRequires; + std::vector linkLibraries; + std::vector linkFlags; + std::vector linkLanguages; + std::string moduleMetadata; // cpp_module_metadata +}; + +struct Component { + std::string type; // archive, dylib, module, jar, interface, symbolic, executable + Attributes attributes; + std::map configurations; +}; + +// A package-level requirement: the version it asks for (empty: any) and the components it needs. +struct Requirement { + std::string version; + std::vector components; +}; + +// The platform a package runs on; an empty field is not stated and constrains nothing. +struct Platform { + std::string isa; + std::string kernel; + std::string cRuntimeVendor; + std::string cRuntimeVersion; + std::string cppRuntimeVendor; + std::string cppRuntimeVersion; + bool empty() const { + return isa.empty() && kernel.empty() && cRuntimeVendor.empty() && cRuntimeVersion.empty() + && cppRuntimeVendor.empty() && cppRuntimeVersion.empty(); + } +}; + +struct Package { + std::string cpsVersion = std::string(kSpecVersion); + std::string name; + std::string version; + std::string compatVersion; + std::string cpsPath; + std::string prefix; + Platform platform; + std::vector configurations; // the package's own preference + std::vector defaultComponents; + std::map requires_; + std::map components; + // `x_`-prefixed attributes, kept as written: `x_mcpp_abi` on the writing side. + std::map extensions; + // Where it was read from (empty for one being written), and every file that went into it: + // the main file first, then its supplements. + std::filesystem::path file; + std::vector files; + // The configurations its components state, from the configuration files and the + // `configurations` of each component. + std::vector available; +}; + +// One file's text. The configuration a configuration-specific file names is in `configuration`. +struct Parsed { + Package package; + std::string configuration; +}; +std::expected parse(std::string_view text); + +// A package's main file, with the supplemental files beside it merged in: `-*.cps` adds +// components, `@.cps` (and `@.cps`) adds the +// attributes of a configuration. +std::expected read(const std::filesystem::path& file); + +// The text of a package: what `mcpp pack` writes. +std::string write(const Package& p); + +// The prefix `@prefix@` stands for: an existing absolute `prefix`, else the directory of the file +// less the tail `cps_path` states. +std::expected prefix_of(const Package& p); +// A path attribute: `@prefix@/...` under the prefix, an absolute path as written, any other +// relative to the file's directory. +std::filesystem::path resolve(std::string_view path, const std::filesystem::path& prefix, + const std::filesystem::path& fileDir); + +// A component's attributes under a configuration: the component's, with the configuration's +// lists appended and its locations replacing; an empty or absent configuration is the component's. +Attributes merged(const Component& c, std::string_view configuration); + +// ── versions (`version_schema = "simple"`) ───────────────────────────────── +// The numeric tuples compared, the shorter padded with zeros; nullopt when either is not simple. +std::optional compare_versions(std::string_view a, std::string_view b); +// A request a package satisfies: `compat_version` (else `version`) <= request <= `version`. +bool satisfies(const Package& p, std::string_view requested); +// The oldest version a semantic version is compatible with: `.0.0`, or `0..0` +// below 1, or itself below 0.1. +std::string compat_version_of(std::string_view version); + +// ── mcpp's words and CPS's ───────────────────────────────────────────────── +// What mcpp knows of a target, in its own words: the triple's architecture, system and +// environment, the system's `uname -s` word (empty where it has none), and the C++ standard +// library (`libstdc++`, `libc++`, `msvc-stl`). +struct TargetWords { + std::string arch; + std::string os; + std::string env; + std::string uname; + std::string cxxStdlib; +}; +// The platform of a build for the target, in CPS's words; what is not known stays empty. +Platform platform_of(const TargetWords& t); +// The fields a stated platform names that the build's differs in, as "isa aarch64, this build +// x86_64"; empty when it matches. Words are compared without case, through the aliases `uname -m` +// spells one architecture with. +std::vector mismatches(const Platform& stated, const Platform& build); +// The configurations a profile prefers, most preferred first: `dev` is `Debug`; `release` is +// `Release`, `RelWithDebInfo`, `MinSizeRel`; another profile prefers none. +std::vector preferred_configurations(std::string_view profile); + +} // namespace mcpp::cps + +namespace mcpp::cps { + +namespace { + +using json = nlohmann::json; + +std::string lower(std::string_view s) { + std::string out(s); + for (char& c : out) c = static_cast(std::tolower(static_cast(c))); + return out; +} + +std::expected, std::string> strings(const json& j, std::string_view what) { + if (!j.is_array()) return std::unexpected(std::format("`{}` is not a list", what)); + std::vector out; + for (auto const& e : j) { + if (!e.is_string()) return std::unexpected(std::format("`{}` holds a value that is not a string", what)); + out.push_back(e.get()); + } + return out; +} + +std::expected by_language(const json& j, std::string_view what) { + ByLanguage out; + if (j.is_array()) { + auto list = strings(j, what); + if (!list) return std::unexpected(list.error()); + out["*"] = std::move(*list); + return out; + } + if (!j.is_object()) return std::unexpected(std::format("`{}` is neither a list nor a map", what)); + for (auto it = j.begin(); it != j.end(); ++it) { + auto list = strings(it.value(), std::format("{}.{}", what, it.key())); + if (!list) return std::unexpected(list.error()); + out[it.key()] = std::move(*list); + } + return out; +} + +std::expected attributes(const json& j, std::string_view where) { + Attributes a; + if (!j.is_object()) return std::unexpected(std::format("`{}` is not a map", where)); + auto list = [&](const char* key, std::vector& into) -> std::expected { + if (auto it = j.find(key); it != j.end()) { + auto v = strings(*it, std::format("{}.{}", where, key)); + if (!v) return std::unexpected(v.error()); + into = std::move(*v); + } + return {}; + }; + auto text = [&](const char* key, std::string& into) -> std::expected { + if (auto it = j.find(key); it != j.end()) { + if (!it->is_string()) + return std::unexpected(std::format("`{}.{}` is not a string", where, key)); + into = it->get(); + } + return {}; + }; + for (auto r : {list("requires", a.requires_), list("link_requires", a.linkRequires), + list("compile_requires", a.compileRequires), list("link_libraries", a.linkLibraries), + list("link_flags", a.linkFlags), list("link_languages", a.linkLanguages), + text("location", a.location), text("link_location", a.linkLocation), + text("cpp_module_metadata", a.moduleMetadata)}) + if (!r) return std::unexpected(r.error()); + if (auto it = j.find("includes"); it != j.end()) { + auto v = by_language(*it, std::format("{}.includes", where)); + if (!v) return std::unexpected(v.error()); + a.includes = std::move(*v); + } + if (auto it = j.find("compile_flags"); it != j.end()) { + auto v = by_language(*it, std::format("{}.compile_flags", where)); + if (!v) return std::unexpected(v.error()); + a.compileFlags = std::move(*v); + } + if (auto it = j.find("definitions"); it != j.end()) { + if (!it->is_object()) return std::unexpected(std::format("`{}.definitions` is not a map", where)); + for (auto lang = it->begin(); lang != it->end(); ++lang) { + if (!lang.value().is_object()) + return std::unexpected(std::format("`{}.definitions.{}` is not a map", where, lang.key())); + auto& into = a.definitions[lang.key()]; + for (auto d = lang.value().begin(); d != lang.value().end(); ++d) { + if (d.value().is_null()) into[d.key()] = std::nullopt; + else if (d.value().is_string()) into[d.key()] = d.value().get(); + else return std::unexpected(std::format("`{}.definitions.{}.{}` is neither a string nor null", + where, lang.key(), d.key())); + } + } + } + return a; +} + +void append(std::vector& to, const std::vector& from) { + to.insert(to.end(), from.begin(), from.end()); +} + +void append(ByLanguage& to, const ByLanguage& from) { + for (auto const& [lang, list] : from) append(to[lang], list); +} + +// The numeric parts of a simple version: `1.2.3-rc1` is {1, 2, 3}. +std::optional> numbers(std::string_view v) { + std::vector out; + std::size_t i = 0; + while (true) { + std::size_t j = i; + while (j < v.size() && std::isdigit(static_cast(v[j]))) ++j; + if (j == i) return std::nullopt; + long long n = 0; + if (std::from_chars(v.data() + i, v.data() + j, n).ec != std::errc{}) return std::nullopt; + out.push_back(n); + if (j == v.size() || v[j] == '-' || v[j] == '+') return out; + if (v[j] != '.') return std::nullopt; + i = j + 1; + } +} + +void add_available(Package& p, const std::string& configuration) { + if (configuration.empty()) return; + if (std::ranges::find(p.available, configuration) == p.available.end()) + p.available.push_back(configuration); +} + +void add_available(Package& p, const Component& c) { + for (auto const& [cfg, _] : c.configurations) add_available(p, cfg); +} + +// A configuration's attributes over what is already there: lists appended, a definition and a +// location replaced. +void merge_into(Attributes& a, const Attributes& x) { + append(a.includes, x.includes); + append(a.compileFlags, x.compileFlags); + for (auto const& [lang, defs] : x.definitions) + for (auto const& [k, v] : defs) a.definitions[lang][k] = v; + if (!x.location.empty()) a.location = x.location; + if (!x.linkLocation.empty()) a.linkLocation = x.linkLocation; + if (!x.moduleMetadata.empty()) a.moduleMetadata = x.moduleMetadata; + append(a.requires_, x.requires_); + append(a.linkRequires, x.linkRequires); + append(a.compileRequires, x.compileRequires); + append(a.linkLibraries, x.linkLibraries); + append(a.linkFlags, x.linkFlags); + append(a.linkLanguages, x.linkLanguages); +} + +// Spellings of one architecture in `uname -m` and in triples. +constexpr std::array, 4> kIsaAliases{{ + {"x86_64", "amd64", "x64"}, + {"aarch64", "arm64", ""}, + {"i686", "i386", "x86"}, + {"armv7", "armv7l", "arm"}, +}}; + +std::string_view isa_family(std::string_view isa) { + const auto l = lower(isa); + for (auto const& group : kIsaAliases) + for (auto const& w : group) + if (!w.empty() && w == l) return group.front(); + return {}; +} + +bool same_word(std::string_view a, std::string_view b) { return lower(a) == lower(b); } + +// The C library vendors that are one vendor under two words: MinGW's runtime is GNU's +// environment to a triple and `mingw` to CPS. +int vendor_family(std::string_view vendor) { + const auto l = lower(vendor); + return l == "gnu" || l == "mingw" ? 1 : 0; +} + +} // namespace + +std::expected parse(std::string_view text) { + auto j = json::parse(text, nullptr, false); + if (j.is_discarded()) return std::unexpected(std::string("it is not JSON")); + if (!j.is_object()) return std::unexpected(std::string("it is not a JSON object")); + Parsed out; + auto& p = out.package; + auto text_of = [&](const char* key, std::string& into) -> std::expected { + if (auto it = j.find(key); it != j.end()) { + if (!it->is_string()) return std::unexpected(std::format("`{}` is not a string", key)); + into = it->get(); + } + return {}; + }; + p.cpsVersion.clear(); + for (auto r : {text_of("cps_version", p.cpsVersion), text_of("name", p.name), text_of("version", p.version), + text_of("compat_version", p.compatVersion), text_of("cps_path", p.cpsPath), + text_of("prefix", p.prefix), text_of("configuration", out.configuration)}) + if (!r) return std::unexpected(r.error()); + if (p.name.empty()) return std::unexpected(std::string("it states no `name`")); + if (auto it = j.find("version_schema"); it != j.end() && it->is_string() + && it->get() != "simple" && it->get() != "semver") + p.extensions["version_schema"] = it->get(); + if (auto it = j.find("platform"); it != j.end()) { + if (!it->is_object()) return std::unexpected(std::string("`platform` is not a map")); + auto word = [&](const char* key) { return it->contains(key) && (*it)[key].is_string() + ? (*it)[key].get() : std::string{}; }; + p.platform = Platform{word("isa"), word("kernel"), word("c_runtime_vendor"), word("c_runtime_version"), + word("cpp_runtime_vendor"), word("cpp_runtime_version")}; + } + if (auto it = j.find("configurations"); it != j.end()) { + auto v = strings(*it, "configurations"); + if (!v) return std::unexpected(v.error()); + p.configurations = std::move(*v); + } + if (auto it = j.find("default_components"); it != j.end()) { + auto v = strings(*it, "default_components"); + if (!v) return std::unexpected(v.error()); + p.defaultComponents = std::move(*v); + } + if (auto it = j.find("requires"); it != j.end()) { + if (!it->is_object()) return std::unexpected(std::string("`requires` is not a map")); + for (auto r = it->begin(); r != it->end(); ++r) { + Requirement req; + if (r.value().is_object()) { + if (auto v = r.value().find("version"); v != r.value().end() && v->is_string()) + req.version = v->get(); + if (auto c = r.value().find("components"); c != r.value().end()) { + auto v = strings(*c, std::format("requires.{}.components", r.key())); + if (!v) return std::unexpected(v.error()); + req.components = std::move(*v); + } + } else if (!r.value().is_null()) { + return std::unexpected(std::format("`requires.{}` is neither a map nor null", r.key())); + } + p.requires_[r.key()] = std::move(req); + } + } + if (auto it = j.find("components"); it != j.end()) { + if (!it->is_object()) return std::unexpected(std::string("`components` is not a map")); + for (auto c = it->begin(); c != it->end(); ++c) { + const auto where = std::format("components.{}", c.key()); + auto attrs = attributes(c.value(), where); + if (!attrs) return std::unexpected(attrs.error()); + Component comp; + comp.type = c.value().value("type", std::string{}); + comp.attributes = std::move(*attrs); + if (auto cf = c.value().find("configurations"); cf != c.value().end()) { + if (!cf->is_object()) return std::unexpected(std::format("`{}.configurations` is not a map", where)); + for (auto k = cf->begin(); k != cf->end(); ++k) { + auto ca = attributes(k.value(), std::format("{}.configurations.{}", where, k.key())); + if (!ca) return std::unexpected(ca.error()); + comp.configurations[k.key()] = std::move(*ca); + } + } + p.components[c.key()] = std::move(comp); + } + } else if (out.configuration.empty()) { + return std::unexpected(std::string("it states no `components`")); + } + for (auto it = j.begin(); it != j.end(); ++it) + if (it.key().starts_with("x_") && it.value().is_string()) + p.extensions[it.key()] = it.value().get(); + return out; +} + +std::expected read(const std::filesystem::path& file) { + namespace fs = std::filesystem; + auto load = [](const fs::path& f) -> std::expected { + std::ifstream in(f, std::ios::binary); + if (!in) return std::unexpected(std::format("{} cannot be read", f.generic_string())); + const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + auto r = parse(text); + if (!r) return std::unexpected(std::format("{}: {}", f.generic_string(), r.error())); + return r; + }; + auto main = load(file); + if (!main) return std::unexpected(main.error()); + if (!main->configuration.empty()) + return std::unexpected(std::format("{} describes the configuration {} of a package, not a package", + file.generic_string(), main->configuration)); + Package p = std::move(main->package); + p.file = file; + p.files.push_back(file); + for (auto const& [_, c] : p.components) add_available(p, c); + + // The supplements, in name order so a merge is the same on every file system. + const auto stem = file.stem().string(); + std::vector appendices, configurationFiles; + std::error_code ec; + for (auto const& e : fs::directory_iterator(file.parent_path(), ec)) { + const auto name = e.path().filename().string(); + if (!name.ends_with(".cps") || e.path() == file || !name.starts_with(stem)) continue; + const char next = name.size() > stem.size() ? name[stem.size()] : '\0'; + if (next != '@' && next != '-' && next != ':') continue; + if (e.path().stem().string().find('@', stem.size()) != std::string::npos) configurationFiles.push_back(e.path()); + else appendices.push_back(e.path()); + } + std::ranges::sort(appendices); + std::ranges::sort(configurationFiles); + for (auto const& a : appendices) { + auto r = load(a); + if (!r) return std::unexpected(r.error()); + if (r->package.name != p.name) + return std::unexpected(std::format("{} names the package {}, and {} names {}", a.generic_string(), + r->package.name, file.generic_string(), p.name)); + p.files.push_back(a); + for (auto& [name, c] : r->package.components) { + add_available(p, c); + p.components.try_emplace(name, std::move(c)); + } + for (auto& [name, req] : r->package.requires_) p.requires_.try_emplace(name, std::move(req)); + } + for (auto const& f : configurationFiles) { + auto r = load(f); + if (!r) return std::unexpected(r.error()); + if (r->configuration.empty()) + return std::unexpected(std::format("{} names no `configuration`", f.generic_string())); + p.files.push_back(f); + add_available(p, r->configuration); + for (auto const& [name, c] : r->package.components) + merge_into(p.components[name].configurations[r->configuration], c.attributes); + } + return p; +} + +std::string write(const Package& p) { + using ojson = nlohmann::ordered_json; + auto by_language_json = [](const ByLanguage& v) { + if (v.size() == 1 && v.contains("*")) return ojson(v.at("*")); + ojson o = ojson::object(); + for (auto const& [lang, list] : v) o[lang] = list; + return o; + }; + auto attributes_json = [&](ojson& o, const Attributes& a) { + if (!a.location.empty()) o["location"] = a.location; + if (!a.linkLocation.empty()) o["link_location"] = a.linkLocation; + if (!a.includes.empty()) o["includes"] = by_language_json(a.includes); + if (!a.definitions.empty()) { + ojson d = ojson::object(); + for (auto const& [lang, defs] : a.definitions) + for (auto const& [k, v] : defs) d[lang][k] = v ? ojson(*v) : ojson(nullptr); + o["definitions"] = std::move(d); + } + if (!a.compileFlags.empty()) o["compile_flags"] = by_language_json(a.compileFlags); + if (!a.requires_.empty()) o["requires"] = a.requires_; + if (!a.linkRequires.empty()) o["link_requires"] = a.linkRequires; + if (!a.compileRequires.empty()) o["compile_requires"] = a.compileRequires; + if (!a.linkLibraries.empty()) o["link_libraries"] = a.linkLibraries; + if (!a.linkFlags.empty()) o["link_flags"] = a.linkFlags; + if (!a.linkLanguages.empty()) o["link_languages"] = a.linkLanguages; + if (!a.moduleMetadata.empty()) o["cpp_module_metadata"] = a.moduleMetadata; + }; + ojson j; + j["cps_version"] = p.cpsVersion.empty() ? std::string(kSpecVersion) : p.cpsVersion; + j["name"] = p.name; + if (!p.version.empty()) { + j["version"] = p.version; + j["version_schema"] = "simple"; + } + if (!p.compatVersion.empty()) j["compat_version"] = p.compatVersion; + if (!p.cpsPath.empty()) j["cps_path"] = p.cpsPath; + if (!p.prefix.empty()) j["prefix"] = p.prefix; + if (!p.platform.empty()) { + ojson pl = ojson::object(); + auto put = [&](const char* key, const std::string& v) { if (!v.empty()) pl[key] = v; }; + put("isa", p.platform.isa); + put("kernel", p.platform.kernel); + put("c_runtime_vendor", p.platform.cRuntimeVendor); + put("c_runtime_version", p.platform.cRuntimeVersion); + put("cpp_runtime_vendor", p.platform.cppRuntimeVendor); + put("cpp_runtime_version", p.platform.cppRuntimeVersion); + j["platform"] = std::move(pl); + } + for (auto const& [k, v] : p.extensions) + if (k.starts_with("x_")) j[k] = v; + if (!p.requires_.empty()) { + ojson r = ojson::object(); + for (auto const& [name, req] : p.requires_) { + ojson o = ojson::object(); + if (!req.version.empty()) o["version"] = req.version; + if (!req.components.empty()) o["components"] = req.components; + r[name] = std::move(o); + } + j["requires"] = std::move(r); + } + if (!p.configurations.empty()) j["configurations"] = p.configurations; + if (!p.defaultComponents.empty()) j["default_components"] = p.defaultComponents; + ojson comps = ojson::object(); + for (auto const& [name, c] : p.components) { + ojson o; + o["type"] = c.type; + attributes_json(o, c.attributes); + if (!c.configurations.empty()) { + ojson cf = ojson::object(); + for (auto const& [cfg, a] : c.configurations) { + ojson x = ojson::object(); + attributes_json(x, a); + cf[cfg] = std::move(x); + } + o["configurations"] = std::move(cf); + } + comps[name] = std::move(o); + } + j["components"] = std::move(comps); + return j.dump(2) + "\n"; +} + +std::expected prefix_of(const Package& p) { + namespace fs = std::filesystem; + std::error_code ec; + if (!p.prefix.empty()) { + const fs::path fixed(p.prefix); + if (fixed.is_absolute() && fs::is_directory(fixed, ec)) return fixed; + if (p.cpsPath.empty()) + return std::unexpected(std::format("its `prefix` {} is not an existing absolute directory", p.prefix)); + } + if (!p.cpsPath.starts_with("@prefix@")) + return std::unexpected(p.cpsPath.empty() + ? std::string("it states neither `cps_path` nor `prefix`") + : std::format("its `cps_path` {} does not begin with @prefix@", p.cpsPath)); + auto tail = std::string_view(p.cpsPath).substr(8); + while (!tail.empty() && (tail.front() == '/' || tail.front() == '\\')) tail.remove_prefix(1); + const fs::path rel = fs::path(std::string(tail)).lexically_normal(); + auto strip = [&](fs::path dir) -> std::optional { + dir = dir.lexically_normal(); + if (!dir.empty() && dir.filename().empty()) dir = dir.parent_path(); + if (rel.empty() || rel == ".") return dir; + std::vector parts(rel.begin(), rel.end()); + while (!parts.empty() && parts.back().empty()) parts.pop_back(); + for (auto it = parts.rbegin(); it != parts.rend(); ++it) { + if (dir.filename() != *it) return std::nullopt; + dir = dir.parent_path(); + } + return dir; + }; + 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; + return std::unexpected(std::format("its `cps_path` {} is not the tail of the directory {}", p.cpsPath, + dir.generic_string())); +} + +std::filesystem::path resolve(std::string_view path, const std::filesystem::path& prefix, + const std::filesystem::path& fileDir) { + if (path.starts_with("@prefix@")) { + auto rest = path.substr(8); + while (!rest.empty() && (rest.front() == '/' || rest.front() == '\\')) rest.remove_prefix(1); + return (prefix / std::string(rest)).lexically_normal(); + } + const std::filesystem::path p{std::string(path)}; + return p.is_absolute() ? p.lexically_normal() : (fileDir / p).lexically_normal(); +} + +Attributes merged(const Component& c, std::string_view configuration) { + Attributes a = c.attributes; + if (configuration.empty()) return a; + if (auto it = c.configurations.find(std::string(configuration)); it != c.configurations.end()) + merge_into(a, it->second); + return a; +} + +std::optional compare_versions(std::string_view a, std::string_view b) { + auto x = numbers(a), y = numbers(b); + if (!x || !y) return std::nullopt; + const auto n = std::max(x->size(), y->size()); + x->resize(n, 0); + y->resize(n, 0); + if (*x < *y) return -1; + if (*x > *y) return 1; + return 0; +} + +bool satisfies(const Package& p, std::string_view requested) { + if (requested.empty()) return true; + if (p.version.empty()) return false; + const auto upper = compare_versions(requested, p.version); + const auto lower = compare_versions(p.compatVersion.empty() ? p.version : p.compatVersion, requested); + return upper && lower && *upper <= 0 && *lower <= 0; +} + +std::string compat_version_of(std::string_view version) { + auto n = numbers(version); + if (!n || n->empty()) return std::string(version); + n->resize(3, 0); + if ((*n)[0] > 0) return std::format("{}.0.0", (*n)[0]); + if ((*n)[1] > 0) return std::format("0.{}.0", (*n)[1]); + return std::format("0.0.{}", (*n)[2]); +} + +Platform platform_of(const TargetWords& t) { + Platform p; + p.isa = t.arch; + p.kernel = !t.uname.empty() ? lower(t.uname) : lower(t.os); + // The C library's vendor is the triple's environment, in CPS's word for the one that + // differs (`msvc` is `microsoft`); a triple that states no environment states no vendor. + // MinGW's `gnu` and CPS's `mingw` are one vendor (`mismatches`); the kernel keeps them + // apart from glibc's. + p.cRuntimeVendor = t.env == "msvc" ? std::string("microsoft") : t.env; + if (t.cxxStdlib == "libstdc++") p.cppRuntimeVendor = "gnu"; + else if (t.cxxStdlib == "libc++") p.cppRuntimeVendor = "llvm"; + else if (t.cxxStdlib == "msvc-stl") p.cppRuntimeVendor = "microsoft"; + return p; +} + +std::vector mismatches(const Platform& stated, const Platform& build) { + std::vector out; + auto field = [&](std::string_view key, const std::string& s, const std::string& b, bool isa) { + if (s.empty() || b.empty()) return; + const bool same = isa && !isa_family(s).empty() ? isa_family(s) == isa_family(b) + : same_word(s, b) || (vendor_family(s) && vendor_family(s) == vendor_family(b)); + if (!same) out.push_back(std::format("{} {}, this build {}", key, s, b)); + }; + field("isa", stated.isa, build.isa, true); + field("kernel", stated.kernel, build.kernel, false); + field("c_runtime_vendor", stated.cRuntimeVendor, build.cRuntimeVendor, false); + field("cpp_runtime_vendor", stated.cppRuntimeVendor, build.cppRuntimeVendor, false); + return out; +} + +std::vector preferred_configurations(std::string_view profile) { + if (profile == "dev") return {"Debug"}; + if (profile == "release") return {"Release", "RelWithDebInfo", "MinSizeRel"}; + return {}; +} + +} // namespace mcpp::cps diff --git a/modules/cps/src/usage.cppm b/modules/cps/src/usage.cppm new file mode 100644 index 000000000..1c08fda7b --- /dev/null +++ b/modules/cps/src/usage.cppm @@ -0,0 +1,375 @@ +// mcpp.cps.usage -- what a package in a set of prefixes gives the build that asks for it: found by +// the locations CMake searches, matched against the build's platform and the requested version, +// its components closed over their `requires`, and each one's attributes under the configuration +// chosen for the build, in the shape of the directives a build program states (design 2026-11-27 +// §3.12.2 two). +// +// THE ANSWER IS DIRECTIVES' MATERIAL, NOT A PACKAGE OF MCPP'S GRAPH. Include directories, compile +// words, link words, run-time directories and the files read: the caller turns them into the +// directives it already has, so a declaration has exactly the effect of a program that wrote them. + +export module mcpp.cps.usage; + +import std; +import mcpp.cps; +import mcpp.libs.path_identity; + +export namespace mcpp::cps { + +struct Request { + std::string name; + std::vector prefixes; // absolute, searched in order + std::vector components; // empty: the package's default components + std::string version; // empty: any + std::string configuration; // empty: by `preferred`, then the package's own + std::vector preferred; // the profile's preference + Platform build; // the build's platform, in CPS's words +}; + +struct Usage { + std::vector includeDirs; // every language + std::vector cflags; // -I, -D and compile flags for C + std::vector cxxflags; // ... for C++ + std::vector linkWords; // libraries by path, then link libraries and flags + std::vector runtimeDirs; // the directories of shared libraries + std::vector filesRead; // every description that went into the answer + std::vector modulesNotImported; // ":" + std::vector notLinked; // ": ()" + // The package and configuration chosen for each package read, as " ()". + std::vector chosen; +}; + +// A refusal: its reason token and the sentence that names the cause and the remedy. +struct Refusal { + std::string code; // cps-no-matching-package | cps-components-unstated | + // cps-component-not-found | cps-description-invalid + std::string message; +}; + +// The directories a package of this name is looked for in under one prefix, in order. +std::vector search_directories(const std::filesystem::path& prefix, std::string_view name); +// The files that describe a package of this name under the prefixes, in search order. +std::vector candidates(const std::vector& prefixes, + std::string_view name); + +std::expected usage(const Request& r); + +} // namespace mcpp::cps + +namespace mcpp::cps { + +namespace { + +namespace fs = std::filesystem; + +std::string lower(std::string_view s) { + std::string out(s); + for (char& c : out) c = static_cast(std::tolower(static_cast(c))); + return out; +} + +// The subdirectories of a directory, in name order. +std::vector subdirectories(const fs::path& dir) { + std::vector out; + std::error_code ec; + for (auto const& e : fs::directory_iterator(dir, ec)) + if (e.is_directory(ec)) out.push_back(e.path()); + std::ranges::sort(out); + return out; +} + +// The directories under the prefix whose name begins with `lib`, `lib` first. +std::vector lib_directories(const fs::path& prefix) { + std::vector out; + for (auto const& d : subdirectories(prefix)) + if (d.filename().string().starts_with("lib")) out.push_back(d); + std::ranges::stable_partition(out, [](const fs::path& d) { return d.filename() == "lib"; }); + return out; +} + +void add_unique(std::vector& to, const std::string& w) { + if (std::ranges::find(to, w) == to.end()) to.push_back(w); +} + +std::string joined(const std::vector& v, std::string_view sep = ", ") { + std::string out; + for (auto const& s : v) out += (out.empty() ? "" : std::string(sep)) + s; + return out; +} + +// One package read for a request, with its prefix and the configuration chosen for it. +struct Chosen { + Package package; + fs::path prefix; + std::string configuration; +}; + +// What a component is needed for: compile, link, or both. +struct Need { + bool compile = false; + bool link = false; +}; + +class Resolver { +public: + explicit Resolver(const Request& r) : r_(r) {} + + std::expected run() { + auto root = load(r_.name, r_.version); + if (!root) return std::unexpected(root.error()); + auto wanted = r_.components.empty() ? root->package.defaultComponents : r_.components; + if (wanted.empty()) { + std::vector names; + for (auto const& [n, _] : root->package.components) names.push_back(n); + return std::unexpected(Refusal{"cps-components-unstated", std::format( + "{} ({}) states no default components and the declaration names none; its components " + "are {}. Name one: `.component(\"{}\")`", r_.name, root->package.file.generic_string(), + joined(names), names.empty() ? std::string("") : names.front())}); + } + for (auto const& c : wanted) + if (auto v = visit(r_.name, c, Need{true, true}, "the declaration"); !v) return std::unexpected(v.error()); + return finish(); + } + +private: + const Request& r_; + std::map packages_; + std::vector> order_; // post-order: (package, component) + std::map, Need> needs_; + Usage u_; + + std::expected load(const std::string& name, const std::string& version) { + if (auto it = packages_.find(name); it != packages_.end()) return it->second; + const auto files = candidates(r_.prefixes, name); + std::vector rejected; + for (auto const& f : files) { + auto p = read(f); + if (!p) return std::unexpected(Refusal{"cps-description-invalid", + std::format("{} is not a CPS description: {}", f.generic_string(), p.error())}); + const auto stem = f.stem().string(); + if (p->name != stem && lower(p->name) != stem) continue; // another package's file + auto why = mismatches(p->platform, r_.build); + if (!version.empty() && !satisfies(*p, version)) + why.push_back(std::format("version {}{}, requested {}", p->version.empty() ? "unstated" : p->version, + p->compatVersion.empty() ? "" : " (compatible from " + p->compatVersion + ")", + version)); + if (!why.empty()) { + rejected.push_back(std::format("{}: {}", f.generic_string(), joined(why, "; "))); + continue; + } + auto prefix = prefix_of(*p); + if (!prefix) return std::unexpected(Refusal{"cps-description-invalid", + std::format("{} cannot be located: {}", f.generic_string(), prefix.error())}); + for (auto const& read : p->files) u_.filesRead.push_back(read); + Chosen c{std::move(*p), *prefix, {}}; + c.configuration = choose_configuration(c.package); + u_.chosen.push_back(std::format("{} ({})", c.package.file.generic_string(), + c.configuration.empty() ? "no configuration" : c.configuration)); + return packages_.emplace(name, std::move(c)).first->second; + } + std::string prefixes; + for (auto const& p : r_.prefixes) prefixes += (prefixes.empty() ? "" : ", ") + p.generic_string(); + if (!rejected.empty()) + return std::unexpected(Refusal{"cps-no-matching-package", std::format( + "no description of {} in {} matches this build:\n {}\nAdd the installation for this build's " + "platform to a prefix{}", name, prefixes, joined(rejected, "\n "), + version.empty() ? std::string{} : ", or request another version")}); + std::string looked; + for (auto const& p : r_.prefixes) + for (auto const& d : search_directories(p, name)) looked += "\n " + d.generic_string(); + return std::unexpected(Refusal{"cps-no-matching-package", std::format( + "no {}.cps in {}; looked in:{}\nCheck that the installation wrote a CPS description " + "(CMake 4.3 or later: install(PACKAGE_INFO), or CMAKE_INSTALL_EXPORTS_AS_PACKAGE_INFO), and " + "that the prefix is the installation's", name, prefixes, looked)}); + } + + // The configuration a package's attributes are read under: the declaration's, the profile's + // preference, the package's own, then the first by name; none for a package that has none. + std::string choose_configuration(const Package& p) { + if (p.available.empty()) return {}; + auto has = [&](const std::string& c) { return std::ranges::find(p.available, c) != p.available.end(); }; + if (!r_.configuration.empty() && has(r_.configuration)) return r_.configuration; + for (auto const& c : r_.preferred) if (has(c)) return c; + for (auto const& c : p.configurations) if (has(c)) return c; + auto sorted = p.available; + std::ranges::sort(sorted); + return sorted.front(); + } + + // `pkg:comp` names a component of another package, `:comp` and `comp` one of `current`. + std::pair split(const std::string& current, const std::string& ref) { + const auto colon = ref.find(':'); + if (colon == std::string::npos) return {current, ref}; + if (colon == 0) return {current, ref.substr(1)}; + return {ref.substr(0, colon), ref.substr(colon + 1)}; + } + + std::expected visit(const std::string& pkgName, const std::string& comp, Need need, + const std::string& from) { + auto& had = needs_[{pkgName, comp}]; + const bool fresh = !had.compile && !had.link; + if ((had.compile || !need.compile) && (had.link || !need.link)) return {}; + had.compile = had.compile || need.compile; + had.link = had.link || need.link; + std::string version; + if (pkgName != r_.name) + if (auto root = packages_.find(r_.name); root != packages_.end()) + if (auto req = root->second.package.requires_.find(pkgName); req != root->second.package.requires_.end()) + version = req->second.version; + auto chosen = load(pkgName, pkgName == r_.name ? r_.version : version); + if (!chosen) return std::unexpected(chosen.error()); + auto const& p = chosen->package; + auto it = p.components.find(comp); + if (it == p.components.end()) { + std::vector names; + for (auto const& [n, _] : p.components) names.push_back(n); + return std::unexpected(Refusal{"cps-component-not-found", std::format( + "{} has no component {}, which {} names; its components are {}", pkgName, comp, from, + joined(names))}); + } + const auto a = merged(it->second, chosen->configuration); + const auto who = std::format("{}:{}", pkgName, comp); + // A required component's compile and link attributes both reach the build; a + // `link_requires` component's link alone, a `compile_requires` one's compile alone. + for (auto const& ref : a.requires_) { + auto [pk, c] = split(pkgName, ref); + if (auto v = visit(pk, c, need, who); !v) return v; + } + if (need.link) + for (auto const& ref : a.linkRequires) { + auto [pk, c] = split(pkgName, ref); + if (auto v = visit(pk, c, Need{false, true}, who); !v) return v; + } + if (need.compile) + for (auto const& ref : a.compileRequires) { + auto [pk, c] = split(pkgName, ref); + if (auto v = visit(pk, c, Need{true, false}, who); !v) return v; + } + if (fresh) order_.emplace_back(pkgName, comp); + return {}; + } + + void compile_words(const Chosen& c, const Attributes& a) { + const auto dir = c.package.file.parent_path(); + for (auto const& [lang, list] : a.includes) + for (auto const& inc : list) { + const auto path = resolve(inc, c.prefix, dir).generic_string(); + if (lang == "*") add_unique(u_.includeDirs, path); + else if (lang == "c") add_unique(u_.cflags, "-I" + path); + else if (lang == "cpp") add_unique(u_.cxxflags, "-I" + path); + } + auto define = [](const std::string& k, const std::optional& v) { + return v ? std::format("-D{}={}", k, *v) : std::format("-D{}", k); + }; + auto in = [&](std::string_view lang, const std::string& k) { + auto l = a.definitions.find(std::string(lang)); + return l != a.definitions.end() && l->second.contains(k); + }; + for (auto const& [lang, defs] : a.definitions) + for (auto const& [k, v] : defs) { + if (lang == "*" || lang == "c") + if (lang == "c" || !in("c", k)) add_unique(u_.cflags, define(k, v)); + if (lang == "*" || lang == "cpp") + if (lang == "cpp" || !in("cpp", k)) add_unique(u_.cxxflags, define(k, v)); + } + for (auto const& [lang, list] : a.compileFlags) + for (auto const& f : list) { + if (lang == "*" || lang == "c") u_.cflags.push_back(f); + if (lang == "*" || lang == "cpp") u_.cxxflags.push_back(f); + } + } + + void link_words(const Chosen& c, const std::string& comp, const std::string& type, const Attributes& a) { + const auto dir = c.package.file.parent_path(); + const auto who = std::format("{}:{}", c.package.name, comp); + if (type == "archive" || type == "dylib") { + const auto& at = type == "dylib" && !a.linkLocation.empty() ? a.linkLocation : a.location; + if (!at.empty()) add_unique(u_.linkWords, resolve(at, c.prefix, dir).generic_string()); + if (type == "dylib" && !a.location.empty()) + add_unique(u_.runtimeDirs, resolve(a.location, c.prefix, dir).parent_path().generic_string()); + } else if (type != "interface") { + add_unique(u_.notLinked, std::format("{} ({})", who, type.empty() ? "no type" : type)); + } + for (auto const& l : a.linkLibraries) { + if (l.starts_with("-") || std::filesystem::path(l).is_absolute()) u_.linkWords.push_back(l); + else u_.linkWords.push_back("-l" + l); + } + for (auto const& f : a.linkFlags) u_.linkWords.push_back(f); + } + + std::expected finish() { + // `order_` is post-order (a component after what it requires); a link line names a + // library before the ones it depends on, so the words are emitted in reverse. + for (auto it = order_.rbegin(); it != order_.rend(); ++it) { + auto const& [pkgName, comp] = *it; + auto const& c = packages_.at(pkgName); + auto const& component = c.package.components.at(comp); + const auto a = merged(component, c.configuration); + const auto need = needs_.at(*it); + if (need.compile) compile_words(c, a); + if (need.link) link_words(c, comp, component.type, a); + if (!a.moduleMetadata.empty()) add_unique(u_.modulesNotImported, std::format("{}:{}", pkgName, comp)); + } + return u_; + } +}; + +} // namespace + +std::vector search_directories(const std::filesystem::path& prefix, std::string_view name) { + std::vector out; + std::vector names{std::string(name)}; + if (lower(name) != name) names.push_back(lower(name)); + auto named = [&](const fs::path& base, bool wildcard) { + for (auto const& n : names) { + out.push_back(base / n); + if (wildcard) + for (auto const& sub : subdirectories(base / n)) out.push_back(sub); + } + }; + named(prefix / "cps", true); + out.push_back(prefix / "cps"); + for (auto const& n : names) { + out.push_back(prefix / n / "cps"); + for (auto const& sub : subdirectories(prefix / n)) + if (sub.filename() != "cps") out.push_back(sub / "cps"); + } + for (auto const& lib : lib_directories(prefix)) { + named(lib / "cps", true); + // `lib//cps//`: a package mcpp packed, one leg per directory (and CMake's + // `lib//cps//` on a multiarch host). + for (auto const& arch : subdirectories(lib)) + if (arch.filename() != "cps") named(arch / "cps", false); + out.push_back(lib / "cps"); + } + named(prefix / "share" / "cps", true); + out.push_back(prefix / "share" / "cps"); + return out; +} + +std::vector candidates(const std::vector& prefixes, + std::string_view name) { + std::vector dirs; + for (auto const& prefix : prefixes) { + auto here = search_directories(prefix, name); + dirs.insert(dirs.end(), here.begin(), here.end()); + } + std::vector out; + std::set seen; + std::error_code ec; + const std::array files{std::string(name) + ".cps", lower(name) + ".cps"}; + for (auto const& dir : dirs) + for (auto const& file : files) { + const auto f = dir / file; + if (!fs::is_regular_file(f, ec)) continue; + namespace id = mcpp::libs::path_identity; + if (seen.insert(id::identity(f).value_or(id::given(f))).second) out.push_back(f); + } + return out; +} + +std::expected usage(const Request& r) { + return Resolver(r).run(); +} + +} // namespace mcpp::cps diff --git a/modules/cps/tests/test_cps.cpp b/modules/cps/tests/test_cps.cpp new file mode 100644 index 000000000..42862cf9c --- /dev/null +++ b/modules/cps/tests/test_cps.cpp @@ -0,0 +1,237 @@ +import std; +import mcpplibs.mtest; +import mcpp.cps; +import mcpp.cps.usage; + +using namespace mcpplibs::mtest; + +// SUBSYSTEM-LEVEL: one CPS description read (with its supplemental files), written and read back, +// versions, the prefix `@prefix@` stands for, the platform words, and the answer to a declaration +// over a prefix laid out as CMake 4.5 and `mcpp pack` lay it out (design 2026-11-27 §3.12). That a +// build program's declaration reaches the build, and that CMake reads what `mcpp pack` writes, is +// stated by the e2e suite (tests/e2e/build-program/cps.cpp, tests/e2e/pack/library.cpp). + +namespace cps = mcpp::cps; +namespace fs = std::filesystem; + +namespace { + +struct Tmp { + fs::path path; + Tmp() { + path = fs::temp_directory_path() / std::format("mcpp_cps_test_{}", std::random_device{}()); + fs::create_directories(path); + } + ~Tmp() { + std::error_code ec; + fs::remove_all(path, ec); + } + void put(const fs::path& rel, std::string_view text) const { + fs::create_directories((path / rel).parent_path()); + std::ofstream(path / rel, std::ios::binary) << text; + } +}; + +// A CMake 4.5 installation (`install(PACKAGE_INFO)`): the main file states the components and +// their interface, the configuration file their locations. +void cmake_imaging(const Tmp& t) { + t.put("lib/cps/Imaging/Imaging.cps", R"({ + "cps_version": "0.15.0", "name": "Imaging", "version": "1.2.0", + "cps_path": "@prefix@/lib/cps/Imaging", + "components": { + "image": { "type": "archive", "includes": ["@prefix@/include"], + "definitions": { "*": { "IMAGING_STATIC": "1" }, "cpp": { "IMAGING_CXX": null } } }, + "shapes": { "type": "dylib", "includes": ["@prefix@/include"], "requires": [":image"] } + } + })"); + t.put("lib/cps/Imaging/Imaging@release.cps", R"({ + "name": "Imaging", "configuration": "Release", + "components": { + "image": { "link_languages": ["cpp"], "location": "@prefix@/lib/libimage.a" }, + "shapes": { "location": "@prefix@/lib/libshapes.so" } + } + })"); + t.put("lib/cps/Imaging/Imaging@debug.cps", R"({ + "name": "Imaging", "configuration": "Debug", + "components": { + "image": { "location": "@prefix@/lib/libimaged.a" }, + "shapes": { "location": "@prefix@/lib/libshapesd.so" } + } + })"); +} + +cps::Platform linux_x86_64() { + return cps::platform_of({"x86_64", "linux", "gnu", "Linux", "libstdc++"}); +} + +} // namespace + +UTest a_package_reads_with_its_configuration_files{"Cps/APackageReadsWithItsConfigurationFiles", [] { + Tmp t; + cmake_imaging(t); + auto p = cps::read(t.path / "lib/cps/Imaging/Imaging.cps"); + expect(fatal(p.has_value())) << (p ? "" : p.error()); + expect(eq(p->name, std::string("Imaging"))); + expect(eq(p->files.size(), std::size_t{3})); + expect(eq(p->available, std::vector{"Debug", "Release"})); + const auto a = cps::merged(p->components.at("image"), "Release"); + expect(eq(a.location, std::string("@prefix@/lib/libimage.a"))); + expect(eq(a.includes.at("*"), std::vector{"@prefix@/include"})); + expect(eq(a.linkLanguages, std::vector{"cpp"})); + expect(!p->components.at("image").attributes.definitions.at("cpp").at("IMAGING_CXX").has_value()) + << "a null definition is a name without a value"; + auto prefix = cps::prefix_of(*p); + expect(fatal(prefix.has_value())); + expect(eq(prefix->lexically_normal(), t.path.lexically_normal())); +}}; + +UTest a_written_package_reads_back{"Cps/AWrittenPackageReadsBack", [] { + cps::Package p; + p.name = "acme.imaging"; + p.version = "1.2.0"; + p.compatVersion = cps::compat_version_of(p.version); + p.cpsPath = "@prefix@/lib/x86_64-linux-gnu/cps/acme.imaging"; + p.platform = linux_x86_64(); + p.extensions["x_mcpp_abi"] = "x86_64-linux-gnu-gcc16"; + p.requires_["acme.json"] = {"1.0", {"json"}}; + p.defaultComponents = {"imaging"}; + cps::Component c; + c.type = "archive"; + c.attributes.location = "@prefix@/lib/x86_64-linux-gnu/libimaging.a"; + c.attributes.includes["*"] = {"@prefix@/include"}; + c.attributes.requires_ = {"acme.json:json"}; + c.attributes.linkLanguages = {"cpp"}; + p.components["imaging"] = c; + const auto text = cps::write(p); + expect(text.contains("\"cps_version\": \"0.15.0\"")); + auto back = cps::parse(text); + expect(fatal(back.has_value())) << (back ? "" : back.error()); + expect(eq(back->package.compatVersion, std::string("1.0.0"))); + expect(eq(back->package.platform.kernel, std::string("linux"))); + expect(eq(back->package.platform.cRuntimeVendor, std::string("gnu"))); + expect(eq(back->package.extensions.at("x_mcpp_abi"), std::string("x86_64-linux-gnu-gcc16"))); + expect(eq(back->package.requires_.at("acme.json").components, std::vector{"json"})); + expect(eq(back->package.components.at("imaging").attributes.location, c.attributes.location)); +}}; + +UTest versions_compare_by_their_numbers{"Cps/VersionsCompareByTheirNumbers", [] { + expect(cps::compare_versions("1.2", "1.2.0") == std::optional(0)); + expect(cps::compare_versions("1.10.0", "1.9.9") == std::optional(1)); + expect(!cps::compare_versions("1.x", "1.0")); + cps::Package p; + p.version = "1.4.2"; + p.compatVersion = "1.0.0"; + expect(cps::satisfies(p, "1.2")); + expect(!cps::satisfies(p, "1.5")); + expect(!cps::satisfies(p, "0.9")); + expect(eq(cps::compat_version_of("0.3.1"), std::string("0.3.0"))); + expect(eq(cps::compat_version_of("0.0.4"), std::string("0.0.4"))); +}}; + +UTest platforms_compare_in_cps_words{"Cps/PlatformsCompareInCpsWords", [] { + const auto build = linux_x86_64(); + expect(eq(build.kernel, std::string("linux"))); + expect(eq(build.cppRuntimeVendor, std::string("gnu"))); + expect(cps::mismatches({"AMD64", "Linux", "", "", "", ""}, build).empty()) << "case and aliases"; + expect(cps::mismatches({}, build).empty()) << "an unstated field constrains nothing"; + const auto m = cps::mismatches({"arm64", "linux", "musl", "", "llvm", ""}, build); + expect(eq(m.size(), std::size_t{3})); + expect(eq(m.front(), std::string("isa arm64, this build x86_64"))); + expect(eq(cps::platform_of({"x86_64", "windows", "gnu", "", "libstdc++"}).cRuntimeVendor, std::string("gnu"))); + expect(cps::mismatches({"x86_64", "windows", "mingw", "", "", ""}, + cps::platform_of({"x86_64", "windows", "gnu", "", "libstdc++"})).empty()) + << "MinGW's runtime is one vendor under two words"; + expect(eq(cps::platform_of({"x86_64", "windows", "msvc", "", "msvc-stl"}).cRuntimeVendor, std::string("microsoft"))); + expect(eq(cps::platform_of({"aarch64", "macos", "", "Darwin", "libc++"}).kernel, std::string("darwin"))); +}}; + +UTest a_declaration_takes_the_default_components_under_the_profiles_configuration{ + "Cps/ADeclarationTakesTheDefaultComponentsUnderTheProfilesConfiguration", [] { + Tmp t; + cmake_imaging(t); + cps::Request r{"Imaging", {t.path}, {"shapes"}, "", "", cps::preferred_configurations("dev"), linux_x86_64()}; + auto u = cps::usage(r); + expect(fatal(u.has_value())) << (u ? "" : u.error().message); + const auto lib = [&](std::string_view f) { return (t.path / "lib" / f).generic_string(); }; + expect(eq(u->linkWords, std::vector{lib("libshapesd.so"), lib("libimaged.a")})) + << "a library before the one it requires, under Debug"; + expect(eq(u->runtimeDirs, std::vector{(t.path / "lib").generic_string()})); + expect(eq(u->includeDirs, std::vector{(t.path / "include").generic_string()})); + expect(std::ranges::contains(u->cflags, std::string("-DIMAGING_STATIC=1"))); + expect(std::ranges::contains(u->cxxflags, std::string("-DIMAGING_CXX"))); + expect(!std::ranges::contains(u->cflags, std::string("-DIMAGING_CXX"))); + expect(eq(u->filesRead.size(), std::size_t{3})); + r.preferred = cps::preferred_configurations("release"); + auto rel = cps::usage(r); + expect(fatal(rel.has_value())); + expect(eq(rel->linkWords.front(), lib("libshapes.so"))); +}}; + +UTest components_that_are_not_stated_are_refused{"Cps/ComponentsThatAreNotStatedAreRefused", [] { + Tmp t; + cmake_imaging(t); + auto u = cps::usage({"Imaging", {t.path}, {}, "", "", {}, linux_x86_64()}); + expect(fatal(!u.has_value())); + expect(eq(u.error().code, std::string("cps-components-unstated"))); + expect(u.error().message.contains("image, shapes")); + auto missing = cps::usage({"Imaging", {t.path}, {"filters"}, "", "", {}, linux_x86_64()}); + expect(fatal(!missing.has_value())); + expect(eq(missing.error().code, std::string("cps-component-not-found"))); +}}; + +UTest a_leg_of_another_platform_is_skipped_and_named{"Cps/ALegOfAnotherPlatformIsSkippedAndNamed", [] { + Tmp t; + for (auto [triple, isa] : {std::pair{"aarch64-linux-gnu", "aarch64"}, std::pair{"x86_64-linux-gnu", "x86_64"}}) + t.put(std::format("lib/{}/cps/acme.imaging/acme.imaging.cps", triple), std::format(R"({{ + "cps_version": "0.15.0", "name": "acme.imaging", "version": "1.2.0", "compat_version": "1.0.0", + "cps_path": "@prefix@/lib/{0}/cps/acme.imaging", + "platform": {{ "isa": "{1}", "kernel": "linux" }}, + "default_components": ["imaging"], + "components": {{ "imaging": {{ "type": "archive", "location": "@prefix@/lib/{0}/libimaging.a" }} }} + }})", triple, isa)); + auto u = cps::usage({"acme.imaging", {t.path}, {}, "1.1", "", {}, linux_x86_64()}); + expect(fatal(u.has_value())) << (u ? "" : u.error().message); + expect(eq(u->linkWords, std::vector{(t.path / "lib/x86_64-linux-gnu/libimaging.a").generic_string()})); + auto none = cps::usage({"acme.imaging", {t.path}, {}, "2.0", "", {}, linux_x86_64()}); + expect(fatal(!none.has_value())); + expect(eq(none.error().code, std::string("cps-no-matching-package"))); + expect(none.error().message.contains("isa aarch64, this build x86_64")); + expect(none.error().message.contains("requested 2.0")); + auto absent = cps::usage({"zlib", {t.path}, {}, "", "", {}, linux_x86_64()}); + expect(fatal(!absent.has_value())); + expect(eq(absent.error().code, std::string("cps-no-matching-package"))); + expect(absent.error().message.contains("looked in")); +}}; + +UTest a_requirement_of_another_package_is_read_from_the_prefixes{ + "Cps/ARequirementOfAnotherPackageIsReadFromThePrefixes", [] { + Tmp t; + t.put("share/cps/app/app.cps", R"({ + "cps_version": "0.15.0", "name": "app", "cps_path": "@prefix@/share/cps/app", + "requires": { "zlib": { "version": "1.2" } }, + "default_components": ["core"], + "components": { "core": { "type": "interface", "includes": { "c": ["@prefix@/include/app"] }, + "link_requires": ["zlib:z"], "cpp_module_metadata": "core.json" } } + })"); + t.put("cps/zlib.cps", R"({ + "cps_version": "0.15.0", "name": "zlib", "version": "1.3.1", "compat_version": "1.0", + "cps_path": "@prefix@/cps", + "components": { "z": { "type": "archive", "location": "@prefix@/lib/libz.a", "includes": ["@prefix@/include"], + "link_libraries": ["m"] } } + })"); + auto u = cps::usage({"app", {t.path}, {}, "", "", {}, linux_x86_64()}); + expect(fatal(u.has_value())) << (u ? "" : u.error().message); + expect(eq(u->cflags, std::vector{"-I" + (t.path / "include/app").generic_string()})); + expect(u->includeDirs.empty()) << "a link requirement's compile attributes do not reach the build"; + expect(eq(u->linkWords, std::vector{(t.path / "lib/libz.a").generic_string(), "-lm"})); + expect(eq(u->modulesNotImported, std::vector{"app:core"})); +}}; + +UTest a_description_that_is_not_cps_is_refused{"Cps/ADescriptionThatIsNotCpsIsRefused", [] { + Tmp t; + t.put("cps/broken.cps", "{ \"name\": \"broken\", \"components\": [] }"); + auto u = cps::usage({"broken", {t.path}, {"x"}, "", "", {}, linux_x86_64()}); + expect(fatal(!u.has_value())); + expect(eq(u.error().code, std::string("cps-description-invalid"))); + expect(u.error().message.contains("broken.cps")); +}}; diff --git a/modules/manifest/src/toml.cppm b/modules/manifest/src/toml.cppm index e296cf89e..181f9cdea 100644 --- a/modules/manifest/src/toml.cppm +++ b/modules/manifest/src/toml.cppm @@ -4338,6 +4338,19 @@ std::expected parse_document(const t::Document& documen m.packConfig.sign = *v; } if (auto v = doc->get_bool("pack.universal")) m.packConfig.universal = *v; + // `[pack] descriptions`: which descriptions for other build systems a + // library package carries (design 2026-11-27 §3.12.2 one). + if (auto v = doc->get_string_array("pack.descriptions")) { + for (auto const& d : *v) + if (d != "pkg-config" && d != "cps") + return std::unexpected(error(origin, std::format( + "[pack].descriptions: '{}' is not a description mcpp writes; expected 'pkg-config' " + "| 'cps'", d))); + m.packConfig.descriptions = *v; + } else if (doc->get_string("pack.descriptions")) { + return std::unexpected(error(origin, std::string( + "[pack].descriptions is a list: `descriptions = [\"pkg-config\", \"cps\"]`, or `[]` for none"))); + } // `[pack] targets` (SPEC-015 §3.3): a string or a list; each a target or a // target set. A set's members are known only with the platform the // command selects, so a set is checked for its form here and expanded diff --git a/modules/manifest/src/types.cppm b/modules/manifest/src/types.cppm index 98bac9e3c..faa300717 100644 --- a/modules/manifest/src/types.cppm +++ b/modules/manifest/src/types.cppm @@ -2119,6 +2119,10 @@ struct PackConfig { // §3.3): targets and target sets, as `--target` takes them (`openkal`, // `x86_64-linux-musl`). Empty: unstated, the build's target. std::vector targets; + // The descriptions a library package carries for build systems other + // than mcpp (design 2026-11-27 §3.12.2 one): "pkg-config" and "cps". + // Unset: both; an empty list: none. + std::optional> descriptions; }; // `[workspace]` — multi-package workspace support (0.0.11+). diff --git a/src/build/build_program.cppm b/src/build/build_program.cppm index a0acce440..339b38181 100644 --- a/src/build/build_program.cppm +++ b/src/build/build_program.cppm @@ -689,6 +689,18 @@ void publish_by_variable(std::vector>& e, } // namespace mcpp::build +// A BUILD PROGRAM'S `mcpp::cps_package` DECLARATIONS (design 2026-11-27 §3.12.2 +// two), read into the directives they amount to and accepted into `d`, their +// slot emptied; `contract` is the program's environment, whose target and +// profile the reading matches. Defined in build_program/cps_package.cpp, an +// implementation unit, so the format's modules are no part of this interface. +namespace mcpp::build::cps_package { +std::expected expand(mcpp::build::directives::Directives& d, + const mcpp::toolchain::CommandDialect& dial, + const std::filesystem::path& root, std::string_view who, + const std::vector>& contract); +} // namespace mcpp::build::cps_package + namespace mcpp::build { // See the declaration for why this exists at all. @@ -1626,6 +1638,15 @@ std::expected run_build_program_impl( } const bool cacheThisRun = d.at(Slot::XpkgRequests).empty(); + // A PACKAGE DECLARED BY ITS CPS DESCRIPTION (design 2026-11-27 §3.12.2 + // two) becomes the directives it amounts to, here, before anything below + // checks, applies or records them: the record holds those directives and + // the files read as its inputs, and a replay applies them as it applies a + // program's own. + if (!d.at(Slot::CpsPackages).empty()) + if (auto r = mcpp::build::cps_package::expand(d, dial, root, who, childEnv); !r) + return std::unexpected(r.error()); + // Dependency mode (genBase set): relative `generated=` paths resolve // against OUT_DIR-style genBase, not the (possibly read-only, shared) // package root — rewrite them to absolute before validation/apply/cache. diff --git a/src/build/build_program/cps_package.cpp b/src/build/build_program/cps_package.cpp new file mode 100644 index 000000000..ac3b433d1 --- /dev/null +++ b/src/build/build_program/cps_package.cpp @@ -0,0 +1,144 @@ +// A build program's `mcpp::cps_package` declaration, read into the directives it amounts to +// (design 2026-11-27 §3.12.2 two). +// +// THE DECLARATION ADDS NO MECHANISM. A package another build system installed reaches the build +// the way any package a build program maps does: through `include-dir`, `cflag`, `cxxflag`, +// `link-flag`, `runtime-search-dir` and `rerun-if-changed`. This file turns a declaration into +// those lines and hands them to the directive table, which spells and checks them as it does a +// program's own; the record of the run then holds those lines and no declaration, so a replay +// applies them as it applies any other. What CPS means -- where a description is, which platform +// it is for, which components and configuration it gives -- is mcpp.cps's. +// +// AN IMPLEMENTATION UNIT OF mcpp.build.build_program, NOT A MODULE OF ITS OWN: importing the +// format's modules (and the system table) into the build program's interface made GCC 16.1 +// crash at `import mcpp.cli` in src/main.cpp, the shape mcpp#1027 records; imported here, they +// are no part of any BMI an importer reads. +module mcpp.build.build_program; + +import std; +import nlohmann.json; +import mcpp.cps; +import mcpp.cps.usage; +import mcpp.build.directives; +import mcpp.build.refusal; +import mcpp.diag; +import mcpp.manifest.flag_words; +import mcpp.toolchain.dialect; +import mcpp.toolchain.target_rows; + +namespace mcpp::build::cps_package { + +namespace { + +namespace dirs = mcpp::build::directives; +namespace refusal = mcpp::build::refusal; + +// What the declaring program's build is: the package's root (where a relative prefix is), its +// name for messages, its target in mcpp's words, and its profile. +struct Context { + std::filesystem::path root; + std::string packageName; + mcpp::cps::TargetWords target; + std::string profile; +}; + +refusal::Code code_of(std::string_view token) { + if (token == "cps-no-matching-package") return refusal::Code::CpsNoMatchingPackage; + if (token == "cps-components-unstated") return refusal::Code::CpsComponentsUnstated; + if (token == "cps-component-not-found") return refusal::Code::CpsComponentNotFound; + if (token == "cps-description-invalid") return refusal::Code::CpsDescriptionInvalid; + return refusal::Code::Other; +} + +std::vector strings(const nlohmann::json& j, const char* key) { + std::vector out; + if (auto it = j.find(key); it != j.end() && it->is_array()) + for (auto const& v : *it) + if (v.is_string()) out.push_back(v.get()); + return out; +} + +// The directive lines a package's usage amounts to, in the order a program would state them. +std::vector lines_of(const mcpp::cps::Usage& u) { + using mcpp::manifest::flag_element; + std::vector out; + for (auto const& f : u.filesRead) out.push_back("mcpp:rerun-if-changed=" + f.generic_string()); + for (auto const& i : u.includeDirs) out.push_back("mcpp:include-dir=" + i); + for (auto const& w : u.cflags) out.push_back("mcpp:cflag=" + flag_element(w)); + for (auto const& w : u.cxxflags) out.push_back("mcpp:cxxflag=" + flag_element(w)); + for (auto const& w : u.linkWords) out.push_back("mcpp:link-flag=" + flag_element(w)); + for (auto const& r : u.runtimeDirs) out.push_back("mcpp:runtime-search-dir=" + r); + return out; +} + +} // namespace + +std::expected expand(mcpp::build::directives::Directives& d, + const mcpp::toolchain::CommandDialect& dial, + const std::filesystem::path& root, std::string_view who, + const std::vector>& contract) { + namespace dirs = mcpp::build::directives; + auto value = [&](std::string_view key) { + auto it = std::ranges::find_if(contract, [&](auto const& kv) { return kv.first == key; }); + return it == contract.end() ? std::string{} : it->second; + }; + Context ctx; + ctx.root = root; + ctx.packageName = std::string(who); + ctx.target.arch = value("MCPP_TARGET_ARCH"); + ctx.target.os = value("MCPP_TARGET_OS"); + ctx.target.env = value("MCPP_TARGET_ENV"); + ctx.target.cxxStdlib = value("MCPP_CXX_STDLIB"); + if (const auto* system = mcpp::toolchain::target::find_system(ctx.target.os)) + ctx.target.uname = std::string(system->uname); + ctx.profile = value("MCPP_PROFILE"); + auto declarations = std::move(d.at(dirs::Slot::CpsPackages)); + d.at(dirs::Slot::CpsPackages).clear(); + const auto build = mcpp::cps::platform_of(ctx.target); + for (auto const& payload : declarations) { + auto j = nlohmann::json::parse(payload, nullptr, false); + const auto name = j.is_object() ? j.value("name", std::string{}) : std::string{}; + if (name.empty() || j.value("overflow", false)) { + refusal::record(refusal::Code::CpsDescriptionInvalid); + return std::unexpected(std::format( + "build.mcpp of '{}' emitted `mcpp:cps-package={}`, which is not a cps_package declaration " + "(it names no package{})", ctx.packageName, payload, + j.is_object() && j.value("overflow", false) ? ", or the program ran out of memory writing it" : "")); + } + mcpp::cps::Request r; + r.name = name; + for (auto const& p : strings(j, "prefixes")) { + const std::filesystem::path prefix(p); + r.prefixes.push_back((prefix.is_absolute() ? prefix : ctx.root / prefix).lexically_normal()); + } + r.components = strings(j, "components"); + r.version = j.value("version", std::string{}); + r.configuration = j.value("configuration", std::string{}); + r.preferred = mcpp::cps::preferred_configurations(ctx.profile); + r.build = build; + if (r.prefixes.empty()) { + refusal::record(refusal::Code::CpsNoMatchingPackage); + return std::unexpected(std::format( + "build.mcpp of '{}' declares the CPS package '{}' in no prefix: name the installation with " + "`.prefix(\"\")`", ctx.packageName, name)); + } + auto u = mcpp::cps::usage(r); + if (!u) { + refusal::record(code_of(u.error().code)); + return std::unexpected(std::format("build.mcpp of '{}' declares the CPS package '{}': {} [{}]", + ctx.packageName, name, u.error().message, u.error().code)); + } + for (auto const& line : lines_of(*u)) dirs::accept_line(d, dial, ctx.root, line); + for (auto const& c : u->modulesNotImported) + mcpp::diag::note("cps/modules-not-imported", std::format( + "{}: the CPS component {} describes C++ modules; mcpp uses its library and headers and does " + "not import modules through CPS", ctx.packageName, c)); + for (auto const& c : u->notLinked) + mcpp::diag::note("cps/component-not-linked", std::format( + "{}: the CPS component {} is not a library, so it reaches neither the compile nor the link", + ctx.packageName, c)); + } + return {}; +} + +} // namespace mcpp::build::cps_package diff --git a/src/build/hostprogram.cppm b/src/build/hostprogram.cppm index 66858c41a..156a062b1 100644 --- a/src/build/hostprogram.cppm +++ b/src/build/hostprogram.cppm @@ -547,6 +547,40 @@ private: json_detail::list cmd_, hosts_, requires_; bool overflow_ = false; }; +// A PACKAGE ANOTHER BUILD SYSTEM INSTALLED, BY ITS CPS DESCRIPTION (protocol +// 22; design 2026-11-27 §3.12.2 two). The engine finds `.cps` in the +// prefixes (relative to this package's root) as CMake does, checks its +// platform against this build's, takes the components named (else the +// package's default ones) with what they require, under the configuration +// this build's profile prefers, and applies what they state as `include_dir`, +// `cflag`, `cxxflag`, `link_flag`, `runtime_search_dir` and +// `rerun_if_changed` -- exactly what a program writing those would get. The +// prefix exists when this program runs: one a `prepare` action fills is named +// by library, as `link_lib` does. +// +// mcpp::cps_package imaging; +// imaging.name = "Imaging"; +// imaging.prefix("third_party/prefix").component("image"); +// imaging.submit(); +struct cps_package { + const char* name = ""; + const char* version = ""; // the version requested; empty: any + const char* configuration = ""; // overrides the profile's preference + cps_package& prefix(const char* dir) { put(prefixes_, dir); return *this; } + cps_package& component(const char* c) { put(components_, c); return *this; } + void submit() const { + std::printf("mcpp:cps-package={\"name\":"); json_detail::esc(name); + std::printf(",\"version\":"); json_detail::esc(version); + std::printf(",\"configuration\":"); json_detail::esc(configuration); + if (overflow_) std::printf(",\"overflow\":true"); + std::printf(",\"prefixes\":[%s]", prefixes_.c_str()); + std::printf(",\"components\":[%s]}\n", components_.c_str()); + } +private: + void put(json_detail::list& l, const char* s) { if (!json_detail::add(l, s)) overflow_ = true; } + json_detail::list prefixes_, components_; + bool overflow_ = false; +}; inline void rerun_if_changed(const char* path) { std::printf("mcpp:rerun-if-changed=%s\n", path); } // mcpp#359: re-run when the SET of files matching `pattern` changes — a file // appearing or disappearing, not its contents (declare those with diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index 8c934c06b..0b1ebfe0b 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -269,6 +269,14 @@ enum class Code { PackageWithoutDescription, EmitInsideAPackage, PackageBuiltOutsideTheEcosystem, + // A build program's `mcpp::cps_package` (design 2026-11-27 §3.12.2 two): + // no description of the package in the prefixes matches the build; the + // declaration names no component and the package states no default; a + // component named or required does not exist; a file is not CPS. + CpsNoMatchingPackage, + CpsComponentsUnstated, + CpsComponentNotFound, + CpsDescriptionInvalid, Other, // a refusal that has not been given a code yet }; @@ -352,6 +360,10 @@ constexpr std::string_view name(Code c) { case Code::PackageWithoutDescription: return "package-without-description"; case Code::EmitInsideAPackage: return "emit-inside-a-package"; case Code::PackageBuiltOutsideTheEcosystem: return "package-built-outside-the-ecosystem"; + case Code::CpsNoMatchingPackage: return "cps-no-matching-package"; + case Code::CpsComponentsUnstated: return "cps-components-unstated"; + case Code::CpsComponentNotFound: return "cps-component-not-found"; + case Code::CpsDescriptionInvalid: return "cps-description-invalid"; case Code::Other: return "other"; } return "other"; diff --git a/src/explain.cppm b/src/explain.cppm index ceaa066cc..33cb8f965 100644 --- a/src/explain.cppm +++ b/src/explain.cppm @@ -387,6 +387,24 @@ constexpr Entry kEntries[] = { "the package was built with a toolchain named by path, whose environment no index entry can supply", "Deliver it by `path` or `git`, or pack it with a managed toolchain\n" "(`[toolchain] default = \"llvm@...\"`)."}, + {"cps-no-matching-package", Kind::Reason, + "a build program's cps_package names a package no description in its prefixes matches: none is there, or none is for this build's platform or the requested version", + "Check that the installation wrote a CPS description (CMake 4.3 or later:\n" + "install(PACKAGE_INFO), or CMAKE_INSTALL_EXPORTS_AS_PACKAGE_INFO=ON) and that\n" + "the prefix is the installation's; the message lists every candidate and the\n" + "field it differs in."}, + {"cps-components-unstated", Kind::Reason, + "a build program's cps_package names no component, and the package states no default components", + "Name the components the build uses: `.component(\"\")`; the message\n" + "lists the package's components."}, + {"cps-component-not-found", Kind::Reason, + "a component a cps_package names, or a component one of them requires, is not in its package", + "Correct the name; the message lists the package's components and the\n" + "component that requires the missing one."}, + {"cps-description-invalid", Kind::Reason, + "a file a cps_package reads is not a CPS description, or its prefix cannot be found from it", + "The message names the file and what is wrong with it; reinstall the\n" + "package, or correct its `cps_path` or `prefix`."}, {"other", Kind::Reason, "a refusal whose branch has not been given a token yet", "Read the message: it names the cause and the remedy. Report the case so\n" diff --git a/src/pack/distribution.cppm b/src/pack/distribution.cppm index 2df8603a8..c5003f678 100644 --- a/src/pack/distribution.cppm +++ b/src/pack/distribution.cppm @@ -1830,9 +1830,9 @@ std::expected library_descriptor(const std::vector pcSeen; for (auto const& [system, byArch] : legs) { std::string tmpl, shas; @@ -1843,15 +1843,17 @@ std::expected library_descriptor(const std::vectorpkg.legDeps.find(leg.triple); it != leg.asset->pkg.legDeps.end()) deps.insert(it->second.begin(), it->second.end()); - if (pcSeen.insert(leg.triple).second) + if (pcSeen.insert(leg.triple).second) { pcDirs += std::format("{}\"lib/{}/pkgconfig\"", pcDirs.empty() ? "" : ", ", lua_text(leg.triple)); + cpsDirs += std::format("{}\"lib/{}/cps\"", cpsDirs.empty() ? "" : ", ", lua_text(leg.triple)); + } } if (here.size() > 1) { twoLegs = true; std::string named; for (auto const& leg : here) named += (named.empty() ? "" : " and ") + leg.triple; mcpp::diag::note("emit/two-legs-for-one-system", std::format( - "{} has two legs for {}-{} ({}): the entry shows the environment no .pc, as it cannot " + "{} has two legs for {}-{} ({}): the entry shows the environment no .pc or .cps, as it cannot " "tell which leg a machine takes; publish one package for each ABI", first.name, system, arch, named)); } @@ -1880,22 +1882,39 @@ std::expected library_descriptor(const std::vector> legDeps; + // Which descriptions for other build systems are written (`[pack] + // descriptions`): "pkg-config" and "cps". Per dependency of + // `dependencies`, its name without the namespace (the component an + // mcpp-written `.cps` names), and the dependencies the package's own + // interface does not show (`visibility = "private"`). + std::vector descriptions{"pkg-config", "cps"}; + std::map dependencyNames; + std::set privateDependencies; }; // The name a package's pkg-config description has: `.`, or @@ -168,6 +182,12 @@ std::vector archive_remove_command(const std::filesystem::path& too namespace mcpp::pack { +// THE DESCRIPTIONS FOR OTHER BUILD SYSTEMS (design 2026-11-27 §3.3.3, §3.12): +// each leg's `.pc` and `.cps` as `[pack] descriptions` selects, from the facts +// the plan holds, and the notes about what they cannot carry. Defined in +// library/descriptions.cpp, where the formats are; the stage calls it once. +std::expected write_descriptions(const LibraryPackPlan& plan); + namespace { std::expected copy_into(const std::filesystem::path& src, @@ -229,37 +249,6 @@ std::string package_identity(std::string_view ns, std::string_view name) { return ns.empty() ? std::string(name) : std::format("{}.{}", ns, name); } -namespace { - -// One leg's pkg-config description (design 2026-11-27 §3.3.3): everything from -// the package's own link intent, the prefix relative to the file itself. -std::string pc_text(const LibraryPackPlan& plan, const LibraryLeg& leg) { - std::string requires_; - for (auto const& [dep, _] : plan.dependencies) requires_ += (requires_.empty() ? "" : ", ") + dep; - std::string libsPrivate; - for (auto const& l : plan.systemLibs) libsPrivate += (libsPrivate.empty() ? "" : " ") + l; - return std::format( - "# Written by mcpp pack. It describes the header interface of this leg;\n" - "# `mcpp_abi` is the compatibility tag mcpp checks, which pkg-config does not.\n" - "prefix=${{pcfiledir}}/../../..\n" - "includedir=${{prefix}}/include\n" - "libdir=${{prefix}}/lib/{}\n" - "mcpp_abi={}\n\n" - "Name: {}\n" - "Description: {} {}, a library package written by mcpp pack\n" - "Version: {}\n" - "{}" - "Cflags: -I${{includedir}}\n" - "Libs: -L${{libdir}} -l{}\n" - "{}", - leg.triple, leg.abiTag, package_identity(plan.namespace_, plan.packageName), plan.packageName, - plan.packageVersion, plan.packageVersion, - requires_.empty() ? std::string{} : std::format("Requires.private: {}\n", requires_), - leg.linkName, libsPrivate.empty() ? std::string{} : std::format("Libs.private: {}\n", libsPrivate)); -} - -} // namespace - std::expected run_library_pack(const LibraryPackPlan& plan) { @@ -537,32 +526,9 @@ run_library_pack(const LibraryPackPlan& plan) os << emit_package_manifest(doc); } - // ── for other build systems (design 2026-11-27 §3.3.3) ──────────── + // ── for other build systems (design 2026-11-27 §3.3.3, §3.12) ───── namespace d = mcpp::pack::distribution; - const auto identity = package_identity(plan.namespace_, plan.packageName); - const bool headers = std::filesystem::is_directory(plan.stagingRoot / "include", ec); - if (headers) { - for (auto const& leg : plan.legs) { - const auto pc = plan.stagingRoot / "lib" / leg.triple / "pkgconfig" / (identity + ".pc"); - std::filesystem::create_directories(pc.parent_path(), ec); - std::ofstream os(pc, std::ios::binary); - os << pc_text(plan, leg); - if (!os) return std::unexpected(LibraryPackError{ std::format("cannot write '{}'", pc.string()) }); - } - } else { - mcpp::diag::note("pack/no-header-interface", std::format( - "{} publishes a module interface and no header interface: no .pc is written, so a build " - "system other than mcpp has no description to read", identity)); - } - if (!plan.targetShared && !plan.dependencies.empty()) { - std::string deps; - for (auto const& [dep, _] : plan.dependencies) deps += (deps.empty() ? "" : ", ") + dep; - mcpp::diag::note("pack/closure-not-in-package", std::format( - "{} is a static library with dependencies ({}), which the package does not carry: a " - "consumer outside mcpp needs their binaries and descriptions in its environment. A shared " - "library, or these dependencies published as library packages, carry the closure", - identity, deps)); - } + if (auto r = write_descriptions(plan); !r) return std::unexpected(r.error()); // The package's description, as a program's package writes it: each // file with its role, leg and digest, and what an index entry reads. { @@ -584,7 +550,9 @@ run_library_pack(const LibraryPackPlan& plan) if (path.starts_with("lib/") && std::distance(rel.begin(), rel.end()) > 2) { const auto triple = (++parts)->string(); stated.leg[path] = triple; - stated.role[path] = path.find("/pkgconfig/") != std::string::npos ? "metadata" : "library"; + const bool description = path.find("/pkgconfig/") != std::string::npos + || path.find("/cps/") != std::string::npos; + stated.role[path] = description ? "metadata" : "library"; } else if (path.starts_with("include/") || path.starts_with("interface/")) { stated.role[path] = "interface"; } else { diff --git a/src/pack/library/descriptions.cpp b/src/pack/library/descriptions.cpp new file mode 100644 index 000000000..0a6b743fe --- /dev/null +++ b/src/pack/library/descriptions.cpp @@ -0,0 +1,142 @@ +// The descriptions a library package carries for build systems other than mcpp (design +// 2026-11-27 §3.3.3, §3.12.2 one): per leg a pkg-config `.pc` and a CPS `.cps`, both from the +// facts the stage already holds, side by side under the leg's own directory. mcpp's own +// description is `mcpp-package.json` and the manifest; these two are renderings of the same facts, +// and nothing reads them back into the package. +module mcpp.pack.library; + +import std; +import mcpp.cps; +import mcpp.diag; +import mcpp.toolchain.triple; +import mcpp.toolchain.target_rows; + +namespace mcpp::pack { + +namespace { + +// One leg's pkg-config description: everything from the package's own link intent, the prefix +// relative to the file itself. +std::string pc_text(const LibraryPackPlan& plan, const LibraryLeg& leg) { + std::string requires_; + for (auto const& [dep, _] : plan.dependencies) requires_ += (requires_.empty() ? "" : ", ") + dep; + std::string libsPrivate; + for (auto const& l : plan.systemLibs) libsPrivate += (libsPrivate.empty() ? "" : " ") + l; + return std::format( + "# Written by mcpp pack. It describes the header interface of this leg;\n" + "# `mcpp_abi` is the compatibility tag mcpp checks, which pkg-config does not.\n" + "prefix=${{pcfiledir}}/../../..\n" + "includedir=${{prefix}}/include\n" + "libdir=${{prefix}}/lib/{}\n" + "mcpp_abi={}\n\n" + "Name: {}\n" + "Description: {} {}, a library package written by mcpp pack\n" + "Version: {}\n" + "{}" + "Cflags: -I${{includedir}}\n" + "Libs: -L${{libdir}} -l{}\n" + "{}", + leg.triple, leg.abiTag, package_identity(plan.namespace_, plan.packageName), plan.packageName, + plan.packageVersion, plan.packageVersion, + requires_.empty() ? std::string{} : std::format("Requires.private: {}\n", requires_), + leg.linkName, libsPrivate.empty() ? std::string{} : std::format("Libs.private: {}\n", libsPrivate)); +} + +// The lowest version a dependency's requirement admits, when CPS can state it: `1.2`, `^1.2`, +// `~1.2`, `>=1.2` and `=1.2` are `1.2`; a range or a wildcard states none. +std::string lower_bound_of(std::string_view req) { + for (std::string_view op : {">=", "^", "~", "="}) + if (req.starts_with(op)) { req.remove_prefix(op.size()); break; } + while (!req.empty() && req.front() == ' ') req.remove_prefix(1); + if (req.empty() || !mcpp::cps::compare_versions(req, req)) return {}; + return std::string(req); +} + +// One leg's CPS description: one component named after the package, its library under the leg's +// directory, the header interface, the dependencies as requirements on the components their own +// `.cps` names, and the platform of the leg in CPS's words. A package has no public macros, so it +// states no `definitions`. +mcpp::cps::Package cps_package(const LibraryPackPlan& plan, const LibraryLeg& leg) { + namespace cps = mcpp::cps; + const auto identity = package_identity(plan.namespace_, plan.packageName); + cps::Package p; + p.name = identity; + p.version = plan.packageVersion; + p.compatVersion = cps::compat_version_of(plan.packageVersion); + p.cpsPath = std::format("@prefix@/lib/{}/cps/{}", leg.triple, identity); + if (auto t = mcpp::toolchain::triple::parse(leg.triple)) { + const auto* system = mcpp::toolchain::target::find_system(t->os); + p.platform = cps::platform_of({t->arch, t->os, t->env, + system ? std::string(system->uname) : std::string{}, leg.cxxStdlib}); + } + if (!leg.abiTag.empty()) p.extensions["x_mcpp_abi"] = leg.abiTag; + p.defaultComponents = {plan.packageName}; + + cps::Component c; + c.type = leg.shared ? "dylib" : "archive"; + auto& a = c.attributes; + a.location = std::format("@prefix@/lib/{}/{}", leg.triple, leg.artifact.filename().string()); + if (!leg.importLibrary.empty()) + a.linkLocation = std::format("@prefix@/lib/{}/{}", leg.triple, leg.importLibrary.filename().string()); + a.includes["*"] = {"@prefix@/include"}; + if (!leg.shared && leg.cxx) a.linkLanguages = {"cpp"}; + for (auto const& l : plan.systemLibs) + if (l.starts_with("-l")) a.linkLibraries.push_back(l.substr(2)); + else a.linkFlags.push_back(l); + for (auto const& [dep, req] : plan.dependencies) { + auto name = plan.dependencyNames.contains(dep) ? plan.dependencyNames.at(dep) : dep; + p.requires_[dep] = cps::Requirement{lower_bound_of(req), {name}}; + const auto ref = std::format("{}:{}", dep, name); + // A private dependency is the archive's to link and nobody's to compile against; a + // shared library already holds what it links. + if (!plan.privateDependencies.contains(dep)) a.requires_.push_back(ref); + else if (!leg.shared) a.linkRequires.push_back(ref); + } + p.components[plan.packageName] = std::move(c); + return p; +} + +std::expected write_text(const std::filesystem::path& file, std::string_view text) { + std::error_code ec; + std::filesystem::create_directories(file.parent_path(), ec); + std::ofstream os(file, std::ios::binary); + os << text; + if (!os) return std::unexpected(LibraryPackError{ std::format("cannot write '{}'", file.string()) }); + return {}; +} + +} // namespace + +std::expected write_descriptions(const LibraryPackPlan& plan) { + const auto identity = package_identity(plan.namespace_, plan.packageName); + const bool pc = std::ranges::contains(plan.descriptions, std::string("pkg-config")); + const bool cps = std::ranges::contains(plan.descriptions, std::string("cps")); + if (!pc && !cps) return {}; + std::error_code ec; + if (!std::filesystem::is_directory(plan.stagingRoot / "include", ec)) { + mcpp::diag::note("pack/no-header-interface", std::format( + "{} publishes a module interface and no header interface: no .pc or .cps is written, so a " + "build system other than mcpp has no description to read", identity)); + } else { + for (auto const& leg : plan.legs) { + const auto dir = plan.stagingRoot / "lib" / leg.triple; + auto r = pc ? write_text(dir / "pkgconfig" / (identity + ".pc"), pc_text(plan, leg)) + : std::expected{}; + if (r && cps) + r = write_text(dir / "cps" / identity / (identity + ".cps"), mcpp::cps::write(cps_package(plan, leg))); + if (!r) return r; + } + } + if (!plan.targetShared && !plan.dependencies.empty()) { + std::string deps; + for (auto const& [dep, _] : plan.dependencies) deps += (deps.empty() ? "" : ", ") + dep; + mcpp::diag::note("pack/closure-not-in-package", std::format( + "{} is a static library with dependencies ({}), which the package does not carry: a " + "consumer outside mcpp needs their binaries and descriptions in its environment. A shared " + "library, or these dependencies published as library packages, carry the closure", + identity, deps)); + } + return {}; +} + +} // namespace mcpp::pack diff --git a/src/pack/library_pipeline.cppm b/src/pack/library_pipeline.cppm index ac5435575..20972a248 100644 --- a/src/pack/library_pipeline.cppm +++ b/src/pack/library_pipeline.cppm @@ -262,11 +262,13 @@ export int build_and_pack_library(const std::string& targetName, target = &kept; std::filesystem::path artifact; std::filesystem::path importLib; + bool holdsCxx = false; for (auto const& lu : ctx->plan.linkUnits) { if (lu.targetName != targetName) continue; if (lu.kind != mcpp::build::LinkUnit::StaticLibrary && lu.kind != mcpp::build::LinkUnit::SharedLibrary) continue; artifact = ctx->outputDir / lu.output; + holdsCxx = mcpp::build::link_unit_holds_cxx(ctx->plan, lu); // Also from the plan, for the same reason: the link unit knows // whether it produced an import library and where. if (!lu.importLibrary.empty()) importLib = ctx->outputDir / lu.importLibrary; @@ -416,6 +418,16 @@ export int build_and_pack_library(const std::string& targetName, plan.cxxRuntime = ctx->manifest.buildConfig.cxxRuntime; declaredPlatforms = ctx->manifest.package.platforms; plan.dependencies = publishable_dependencies(ctx->manifest); + // What a `.cps` names of each dependency: the component its own + // description has (its name), and whether the package's interface + // shows it (design 2026-11-27 §3.12.2 one). + for (auto const& [dep, _] : plan.dependencies) { + auto const& spec = ctx->manifest.dependencies.at(dep); + plan.dependencyNames[dep] = spec.shortName.empty() ? dep : spec.shortName; + if (spec.visibility == "private") plan.privateDependencies.insert(dep); + } + if (ctx->manifest.packConfig.descriptions) + plan.descriptions = *ctx->manifest.packConfig.descriptions; // The system libraries the package's own link states, for the // `.pc` (design 2026-11-27 §3.3.3); nothing new is stated. for (auto const& w : mcpp::manifest::flag_words(ctx->manifest.buildConfig.ldflags)) @@ -492,6 +504,8 @@ export int build_and_pack_library(const std::string& targetName, .objcopy = mcpp::toolchain::binutils_tool(ctx->tc, "objcopy"), .inBandDebugInfo = mcpp::pack::debug_info_is_in_band(triple), }, + .cxxStdlib = ctx->tc.stdlibId, + .cxx = holdsCxx, }); // A shared leg's run-time lower bounds, as an index entry's `deps` // states them; the C++ run-time a NEEDED libstdc++ is takes the diff --git a/tests/e2e/build-program/protocol.cpp b/tests/e2e/build-program/protocol.cpp index b566dbedf..aa41877d8 100644 --- a/tests/e2e/build-program/protocol.cpp +++ b/tests/e2e/build-program/protocol.cpp @@ -13,6 +13,14 @@ namespace { constexpr std::string_view ran_again = R"(^ *build\.mcpp .* ran [0-9])"; +bool failed(const e2e::outcome& r) { return r.started && r.status != 0; } + +// `text` written to `file`, its directories made: a prefix another build system installed. +void write_file(const fs::path& file, std::string_view text) { + fs::create_directories(file.parent_path()); + std::ofstream(file, std::ios::binary) << text; +} + E2E protocol{"protocol", s::home_fixture, [] { "89 build mcpp"_test[s::gcc] = [] { // mcpp compiles build.mcpp with the host toolchain and runs it before the build; its @@ -253,6 +261,135 @@ int main() { expect(s::has_line(s::text(p.mcpp({"run"})), "^ANSWER2=42$")) << "cached include-dir record lost"; }; + "a build program declares an installed package by its CPS description"_test[s::gcc] = [] { + // Design 2026-11-27 §3.12.2 two: `mcpp::cps_package` finds `.cps` in a prefix laid + // out as CMake 4.5 installs one (a main file and a file per configuration), takes the + // package's default components under the configuration the profile prefers, and applies + // what they state as the directives a program would write: the include directory and + // the macro reach the compile, the library by path the link. The record replays them; + // a changed description runs the program again. + const auto tmp = s::case_dir(); + s::project lib{tmp / "imaging", { + {"src/imaging.cpp", "int imaging_scale(int x) { return x * 2; }\n"}, + {"mcpp.toml", "[package]\nname = \"imaging\"\nversion = \"1.2.0\"\n[build]\n" + "sources = [\"src/*.cpp\"]\n[targets.imaging]\nkind = \"lib\"\n"}}}; + expect(fatal(e2e::succeeded(lib.mcpp({"build"})))); + const auto archive = s::find_files(lib.at("target"), R"(libimaging\.a)"); + expect(fatal(archive.size() == 1)) << "one archive from the library's build"; + const auto prefix = tmp / "prefix"; + fs::create_directories(prefix / "lib/cps/Imaging"); + fs::create_directories(prefix / "include"); + fs::copy_file(archive.front(), prefix / "lib/libimaging.a"); + fs::copy_file(archive.front(), prefix / "lib/libimaging_d.a"); + write_file(prefix / "include/imaging.h", "#pragma once\nint imaging_scale(int x);\n"); + const auto main_cps = [](int level) { + return std::format(R"({{ + "cps_version": "0.15.0", "name": "Imaging", "version": "1.2.0", + "cps_path": "@prefix@/lib/cps/Imaging", "default_components": ["image"], + "components": {{ "image": {{ "type": "archive", "includes": ["@prefix@/include"], + "definitions": {{ "*": {{ "IMAGING_LEVEL": "{}" }} }} }} }} +}})", level); + }; + write_file(prefix / "lib/cps/Imaging/Imaging.cps", main_cps(2)); + write_file(prefix / "lib/cps/Imaging/Imaging@release.cps", + R"({"name": "Imaging", "configuration": "Release", + "components": { "image": { "location": "@prefix@/lib/libimaging.a" } } })"); + write_file(prefix / "lib/cps/Imaging/Imaging@debug.cps", + R"({"name": "Imaging", "configuration": "Debug", + "components": { "image": { "location": "@prefix@/lib/libimaging_d.a" } } })"); + + s::project p{tmp / "app", {{"build.mcpp", std::format(R"cpp(import mcpp; +int main() {{ + mcpp::cps_package imaging; + imaging.name = "Imaging"; + imaging.prefix("{}"); + imaging.submit(); + return 0; +}} +)cpp", prefix.generic_string())}, + {"src/main.cpp", "#include \n#include \n" + "int main() { std::printf(\"SCALED=%d LEVEL=%d\\n\", imaging_scale(21), IMAGING_LEVEL); }\n"}, + {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n[targets.app]\nkind = \"bin\"\n" + "main = \"src/main.cpp\"\n"}}}; + auto r = p.mcpp({"run"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::has_line(s::text(r), "^SCALED=42 LEVEL=2$")) << s::text(r); + const auto ninja_holds = [&](std::string_view needle) { + return std::ranges::any_of(s::find_files(p.at("target"), R"(build\.ninja)"), [&](const fs::path& f) { + return !f.generic_string().contains("/.build-mcpp/") && s::read_file(f).contains(needle); + }); + }; + expect(ninja_holds("libimaging_d.a")) << "the dev profile takes the Debug configuration"; + r = p.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::no_line(s::text(r), ran_again)) << "the record of the declaration was not replayed"; + write_file(prefix / "lib/cps/Imaging/Imaging.cps", main_cps(3)); + r = p.mcpp({"run"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::has_line(s::text(r), "^SCALED=42 LEVEL=3$")) << "a changed description did not reach the build\n" + << s::text(r); + r = p.mcpp({"build", "--release"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(ninja_holds("/libimaging.a")) << "the release profile takes the Release configuration"; + }; + + "a CPS declaration that cannot be answered is refused by its reason"_test[s::gcc] = [] { + // Design 2026-11-27 §3.12.2 two, §10.2: no description in the prefix, none for this + // build's platform, no component named or defaulted, a component that is not there, and a + // file that is not CPS each refuse the configuration with their token; a component that + // describes C++ modules or is not a library is used as far as it can be and said once. + const auto tmp = s::case_dir(); + const auto prefix = tmp / "prefix"; + write_file(prefix / "cps/Elsewhere.cps", R"({"cps_version": "0.15.0", "name": "Elsewhere", + "cps_path": "@prefix@/cps", "platform": {"isa": "sparc64"}, "default_components": ["x"], + "components": {"x": {"type": "interface"}}})"); + write_file(prefix / "cps/Plain.cps", R"({"cps_version": "0.15.0", "name": "Plain", + "cps_path": "@prefix@/cps", "components": {"core": {"type": "interface"}}})"); + write_file(prefix / "cps/Broken.cps", R"({"cps_version": "0.15.0", "name": "Broken", "components": [)"); + write_file(prefix / "include/hdr/hdr.h", "#pragma once\n#define HDR_VALUE 7\n"); + write_file(prefix / "cps/Hdr.cps", R"({"cps_version": "0.15.0", "name": "Hdr", + "cps_path": "@prefix@/cps", "default_components": ["hdr", "tool"], + "components": {"hdr": {"type": "interface", "includes": ["@prefix@/include/hdr"], + "cpp_module_metadata": "@prefix@/modules.json"}, + "tool": {"type": "executable", "location": "@prefix@/bin/tool"}}})"); + s::project p{tmp / "app", { + {"src/main.cpp", "#include \nint main() { std::printf(\"ok\\n\"); }\n"}, + {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n[targets.app]\nkind = \"bin\"\n" + "main = \"src/main.cpp\"\n"}}}; + const auto declare = [&](std::string_view name, std::string_view component) { + p.write("build.mcpp", std::format(R"cpp(import mcpp; +int main() {{ + mcpp::cps_package pkg; + pkg.name = "{}"; + pkg.prefix("{}"); + {} + pkg.submit(); + return 0; +}} +)cpp", name, prefix.generic_string(), + component.empty() ? std::string{} : std::format("pkg.component(\"{}\");", component))); + }; + struct Refused { std::string_view name, component, code, says; }; + for (auto const& c : {Refused{"Nowhere", "", "cps-no-matching-package", "looked in"}, + Refused{"Elsewhere", "", "cps-no-matching-package", "isa sparc64, this build"}, + Refused{"Plain", "", "cps-components-unstated", "its components are core"}, + Refused{"Plain", "filters", "cps-component-not-found", "no component filters"}, + Refused{"Broken", "core", "cps-description-invalid", "Broken.cps"}}) { + declare(c.name, c.component); + e2e::expect_diagnostic(std::format("\\[{}\\]", c.code)); + auto r = p.mcpp({"build"}); + expect(failed(r) && e2e::contains(s::text(r), c.says) && e2e::contains(s::text(r), c.code)) + << c.name << " was not refused with " << c.code << ":\n" << s::text(r); + } + declare("Hdr", ""); + p.write("src/main.cpp", "#include \n#include \nint main() { std::printf(\"HDR=%d\\n\", HDR_VALUE); }\n"); + auto r = p.mcpp({"run"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::has_line(s::text(r), "^HDR=7$")) << s::text(r); + expect(e2e::contains(s::text(r), "does not import modules through CPS")) << s::text(r); + expect(e2e::contains(s::text(r), "Hdr:tool (executable) is not a library")) << s::text(r); + }; + "181 build mcpp import std"_test[s::unix_shell] = [] { // build.mcpp can `import std;`: alone, beside `import mcpp;`, and an #include-only program // that mentions `import std;` in a comment still takes the plain path. diff --git a/tests/e2e/pack/library.cpp b/tests/e2e/pack/library.cpp index 56ac1e6ea..0e7394bd8 100644 --- a/tests/e2e/pack/library.cpp +++ b/tests/e2e/pack/library.cpp @@ -862,6 +862,44 @@ version = "0.1.0" expect(e2e::contains(pc, line)) << "the .pc lacks '" << line << "':\n" << pc; const auto description = s::read_file(*pkg / "mcpp-package.json"); expect(e2e::contains(description, R"("kind": "library")")) << description; + // Design 2026-11-27 §3.12.2 one: beside each leg's `.pc`, its `.cps` under + // lib//cps//, the same facts in CPS's words. + const auto cpss = s::find_files(*pkg / "lib", R"(.*mathkit\.cps)"); + expect(fatal(cpss.size() == 1)) << "one .cps per leg, under lib//cps//"; + expect(cpss.front().parent_path().parent_path().filename() == "cps" + && cpss.front().parent_path().parent_path().parent_path() == pcs.front().parent_path().parent_path()) + << "the .cps is not beside the .pc: " << cpss.front(); + const auto cps = s::read_file(cpss.front()); + for (std::string_view word : {R"("cps_version": "0.15.0")", R"("cps_path": "@prefix@/lib/)", R"("isa": )", + R"("type": "archive")", R"("includes": [)", R"("@prefix@/include")", + R"("link_libraries": [)", R"("link_languages": [)", R"("x_mcpp_abi": )", + R"("default_components": [)"}) + expect(e2e::contains(cps, word)) << "the .cps lacks '" << word << "':\n" << cps; + expect(e2e::contains(description, "/cps/") && e2e::contains(description, R"("metadata")")) << description; + // CMake 4.3 and later reads it: the leg's directory is the prefix it searches. + if (auto cmake = s::on_path("cmake")) { + const auto version = s::run(*cmake, {"--version"}).out; + std::smatch m; + const std::string v = version; + if (std::regex_search(v, m, std::regex(R"(cmake version ([0-9]+)\.([0-9]+))")) + && std::pair{std::stoi(m[1]), std::stoi(m[2])} >= std::pair{4, 3}) { + s::project cons{tmp / "cmake-consumer", { + {"CMakeLists.txt", "cmake_minimum_required(VERSION 4.3)\nproject(cons LANGUAGES C CXX)\n" + "find_package(mathkit REQUIRED)\nadd_executable(cons main.c)\n" + "target_link_libraries(cons mathkit::mathkit)\n"}, + {"main.c", "#include \n#include \n" + "int main(void) { printf(\"SUM=%d\\n\", mathkit_add(40, 2)); return 0; }\n"}}}; + const auto legPrefix = pcs.front().parent_path().parent_path().string(); + auto c = s::run(*cmake, {"-S", cons.at("").string(), "-B", cons.at("b").string(), + "-DCMAKE_PREFIX_PATH=" + legPrefix}); + expect(fatal(c.status == 0)) << "CMake did not find the package's .cps:\n" << c.out << c.err; + c = s::run(*cmake, {"--build", cons.at("b").string()}); + expect(fatal(c.status == 0)) << c.out << c.err; + const auto exe = s::find_file(cons.at("b"), "cons"); + expect(fatal(exe.has_value())); + expect(s::has_line(s::run(*exe).out, "^SUM=42$")); + } + } if (auto tool = s::on_path("pkg-config")) { auto read = s::run(*tool, {"--cflags", "--libs", "--static", "mathkit"}, {}, {{"PKG_CONFIG_PATH", pcs.front().parent_path().string()}}); @@ -872,7 +910,7 @@ version = "0.1.0" expect(fatal(e2e::succeeded(r))) << s::text(r); const auto entry = r.out; for (std::string_view word : {R"(mcpp = "mcpp.toml")", "linux = {", "https://example.org/v0.1.0/", - "declare_pkgconfig", "relocate_pkgconfig"}) + "declare_pkgconfig", "relocate_pkgconfig", "relocate_cps", "declare_cps"}) expect(e2e::contains(entry, word)) << "the entry lacks '" << word << "':\n" << entry; // Refused by name. diff --git a/tests/unit/test_build_directives.cpp b/tests/unit/test_build_directives.cpp index 718036de2..83b378cde 100644 --- a/tests/unit/test_build_directives.cpp +++ b/tests/unit/test_build_directives.cpp @@ -58,7 +58,9 @@ UTest every_row_is_internally_consistent{"BuildDirectives/EveryRowIsInternallyCo // A RerunKey directive feeds only the re-run key, so it must NOT be // persisted as a `d` record; everything else must be, or a cache hit // would silently apply less than the program asked for. - if (def.scope == dirs::Scope::RerunKey) + // A Declaration is expanded into other directives before the record + // is written, so it is never persisted either. + if (def.scope == dirs::Scope::RerunKey || def.scope == dirs::Scope::Declaration) expect(def.tag.empty()) << def.wire; else expect(!def.tag.empty()) << def.wire; @@ -1131,16 +1133,32 @@ UTest deploy_row_is_protocol_eleven_with_link_global_scope_and_a_tag{"BuildDirec expect(eq(def->scope, dirs::Scope::LinkGlobal)); expect(eq(def->sinceProtocol, 11)); expect(!(def->tag.empty())); - expect(eq(dirs::kProtocolVersion, 21)); + expect(eq(dirs::kProtocolVersion, 22)); }}; -UTest protocol_twenty_one_is_accepted_and_twenty_two_is_not{"BuildDirectives/ProtocolTwentyOneIsAcceptedAndTwentyTwoIsNot", [] { - auto ok = parse("mcpp:protocol=21\n"); +UTest protocol_twenty_two_is_accepted_and_twenty_three_is_not{"BuildDirectives/ProtocolTwentyTwoIsAcceptedAndTwentyThreeIsNot", [] { + auto ok = parse("mcpp:protocol=22\n"); expect(!(dirs::protocol_error(ok).has_value())); - auto no = parse("mcpp:protocol=22\n"); + auto no = parse("mcpp:protocol=23\n"); expect(dirs::protocol_error(no).has_value()); }}; +// Design 2026-11-27 §3.12.2 two: a package declared by its CPS description is a +// declaration of protocol 22, held in its slot until the engine expands it and +// never written to the record. +UTest cps_package_is_a_protocol_twenty_two_declaration{"BuildDirectives/CpsPackageIsAProtocolTwentyTwoDeclaration", [] { + auto def = dirs::find_by_wire("cps-package"); + expect(fatal(ne(def, nullptr))); + expect(eq(def->scope, dirs::Scope::Declaration)); + expect(eq(def->sinceProtocol, 22)); + expect(def->tag.empty()); + auto d = parse("mcpp:protocol=22\nmcpp:cps-package={\"name\":\"zlib\",\"prefixes\":[\"p\"]}\n"); + expect(eq(d.at(dirs::Slot::CpsPackages).size(), std::size_t{1})); + std::ostringstream os; + dirs::serialize(os, d); + expect(!os.str().contains("zlib")) << "the record holds what a declaration was read into"; +}}; + // Design 2026-11-21 §3.7: a deprecated reading a typed reader applied is an // advisory of protocol 21, kept with the program's record so a replay warns too. UTest deprecated_reading_is_a_protocol_twenty_one_advisory{"BuildDirectives/DeprecatedReadingIsAProtocolTwentyOneAdvisory", [] { From 5a8f4256aaa1d6afd03c63891a839405dcf72e3f Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 05:29:06 +0900 Subject: [PATCH 13/36] Unit tests follow the plan locks; the CPS reason titles are docs/50's The plan-locks change gave RunScope::begin the plan's state directory and the scheduler semaphore a ninja variable of the plan, and joined batch_fetch, plan_locks and lock_wait to the grouping key where they are stated; the unit tests named the earlier forms. The explain registry's titles of the four CPS reason tokens now equal docs/50's rows, as the unit test of the two requires. --- src/explain.cppm | 8 ++++---- tests/unit/test_detach_status.cpp | 5 +++-- tests/unit/test_key_registry.cpp | 10 ++++++++-- tests/unit/test_ninja_backend.cpp | 4 ++-- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/explain.cppm b/src/explain.cppm index 33cb8f965..122a4af0c 100644 --- a/src/explain.cppm +++ b/src/explain.cppm @@ -388,21 +388,21 @@ constexpr Entry kEntries[] = { "Deliver it by `path` or `git`, or pack it with a managed toolchain\n" "(`[toolchain] default = \"llvm@...\"`)."}, {"cps-no-matching-package", Kind::Reason, - "a build program's cps_package names a package no description in its prefixes matches: none is there, or none is for this build's platform or the requested version", + "a build program's `mcpp::cps_package` names a package no description in its prefixes matches: none is there, or none is for this build's platform or the requested version", "Check that the installation wrote a CPS description (CMake 4.3 or later:\n" "install(PACKAGE_INFO), or CMAKE_INSTALL_EXPORTS_AS_PACKAGE_INFO=ON) and that\n" "the prefix is the installation's; the message lists every candidate and the\n" "field it differs in."}, {"cps-components-unstated", Kind::Reason, - "a build program's cps_package names no component, and the package states no default components", + "a build program's `mcpp::cps_package` names no component, and the package states no default components", "Name the components the build uses: `.component(\"\")`; the message\n" "lists the package's components."}, {"cps-component-not-found", Kind::Reason, - "a component a cps_package names, or a component one of them requires, is not in its package", + "a component a `mcpp::cps_package` names, or one of them requires, is not in its package", "Correct the name; the message lists the package's components and the\n" "component that requires the missing one."}, {"cps-description-invalid", Kind::Reason, - "a file a cps_package reads is not a CPS description, or its prefix cannot be found from it", + "a file a `mcpp::cps_package` reads is not a CPS description, or its prefix cannot be found from it", "The message names the file and what is wrong with it; reinstall the\n" "package, or correct its `cps_path` or `prefix`."}, {"other", Kind::Reason, diff --git a/tests/unit/test_detach_status.cpp b/tests/unit/test_detach_status.cpp index f8bc4c073..8d037d0a6 100644 --- a/tests/unit/test_detach_status.cpp +++ b/tests/unit/test_detach_status.cpp @@ -104,8 +104,9 @@ int lifetime_driver(const std::vector& argv) { } if (role == "root") { // The generation's cap; build.ninja names none (e2e 861). - auto run = detach::RunScope::begin(lifetime_env("MCPP_TEST_LIFETIME_OUTPUT", fs::current_path().string()), - std::stoi(lifetime_env("MCPP_TEST_LIFETIME_CAP", "1"))); + // The state directory is the output directory: the generation a build without a plan of its own opens. + const fs::path output = lifetime_env("MCPP_TEST_LIFETIME_OUTPUT", fs::current_path().string()); + auto run = detach::RunScope::begin(output, output, std::stoi(lifetime_env("MCPP_TEST_LIFETIME_CAP", "1"))); if (!run) { std::println(std::cerr, "{}", run.error()); return 2; } std::ofstream("root.ready") << mcpplibs::os::process::self()->id; mcpp::run::Env env; diff --git a/tests/unit/test_key_registry.cpp b/tests/unit/test_key_registry.cpp index 49e048b5c..69d5ff8f6 100644 --- a/tests/unit/test_key_registry.cpp +++ b/tests/unit/test_key_registry.cpp @@ -41,9 +41,15 @@ UTest the_shared_build_keys_are_the_workspace_build_keys{"KeyRegistry/TheSharedB }}; // Every configuration key of [build] is part of the value members are grouped -// by: two members that differ in one are not one plan. +// by: two members that differ in one are not one plan. `batch_fetch`, +// `plan_locks` and `lock_wait` join it where they are stated, so a project that +// states none keeps the key an earlier engine wrote; they are stated here. UTest every_configuration_key_enters_the_grouping_key{"KeyRegistry/EveryConfigurationKeyEntersTheGroupingKey", [] { - const auto key = mcpp::project::root_position_key(mm::Manifest{}); + mm::Manifest stated; + stated.buildConfig.batchFetch = "off"; + stated.buildConfig.planLocks = "off"; + stated.buildConfig.lockWait = "30s"; + const auto key = mcpp::project::root_position_key(stated); const std::map spelled = { {"profile", "default_profile"}, {"default-profile", "default_profile"}, {"platform-dependencies", "platform_dependencies"}, diff --git a/tests/unit/test_ninja_backend.cpp b/tests/unit/test_ninja_backend.cpp index e5a957f6f..45b17f9b8 100644 --- a/tests/unit/test_ninja_backend.cpp +++ b/tests/unit/test_ninja_backend.cpp @@ -213,7 +213,7 @@ UTest ordinary_compilers_share_the_detached_schedule_bound{"NinjaBackend/Ordinar expect(ne(start, std::string::npos)) << name; return start == std::string::npos ? std::string{} : text.substr(start, text.find("\n\n", start) - start); }; - const std::string executor = "__compiler-cap --sem .mcpp-sched --output $out --depfile $out.d"; + const std::string executor = "__compiler-cap --sem $sched_dir --output $out --depfile $out.d"; // GCC 16 writes its outputs below an attempt of the compile's own, which the // executor publishes (design 2026-11-19 §10.6): the driver's compiles, its // assembler and its scans, a scan with no auxiliary outputs to name. NASM, @@ -254,7 +254,7 @@ UTest links_hold_a_permit_of_the_schedule_bound{"NinjaBackend/LinksHoldAPermitOf return start == std::string::npos ? std::string{} : text.substr(start, text.find("\n\n", start) - start); }; const auto text = emit_ninja_string(plan); - const std::string permit = "$mcpp __compiler-cap --sem .mcpp-sched --output $out -- "; + const std::string permit = "$mcpp __compiler-cap --sem $sched_dir --output $out -- "; for (const auto name : {"cxx_link", "cxx_shared"}) { const auto r = rule(text, name); expect(ne(r.find(permit), std::string::npos)) << name << "\n" << r; From ece7819fbaf9fe694e811ca9485b7d6bd3e3eb5e Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 05:46:31 +0900 Subject: [PATCH 14/36] Fetch waves cover the project's own index; plan-locks is a shape that ran on every host A dependency of the project's own index installs into the project's environment, and the wave left it out: a project whose dependencies all come from its own index fetched them one call at a time, which the e2e case of two such dependencies states otherwise. Each environment now gets a wave of its own, the project's through the same environment the single path uses. SPEC-019 keeps a shape off until it has run on every host; the registry test names plan-locks, on by default since the CI of this release runs it on each host. --- docs/26-build-optimizations.md | 2 +- docs/specs/build-optimizations.md | 2 +- docs/zh/26-build-optimizations.md | 2 +- modules/buildopt/src/registry.cppm | 4 +- modules/buildopt/tests/test_source.cpp | 8 ++- src/build/prepare/graph_load.cpp | 68 +++++++++++++++----------- 6 files changed, 50 insertions(+), 36 deletions(-) diff --git a/docs/26-build-optimizations.md b/docs/26-build-optimizations.md index a91242d67..7ad962d4d 100644 --- a/docs/26-build-optimizations.md +++ b/docs/26-build-optimizations.md @@ -28,7 +28,7 @@ by default; the others are stated by a parameter. | `scan-pass` | on | — | The scans of a graph run before its compiles, as a pass of their own | | `split-schedule` | off | `[build] bmi_schedule`, `MCPP_BMI_SCHEDULE` | Importers start when a BMI exists, not when its compiler exits | | `private-fragment` | on | `[build] private_fragment` (`unit`, `conservative`, `as-written`), `MCPP_PRIVATE_FRAGMENT` | A private module fragment is built as a unit of its own | -| `batch-fetch` | on | `[build] batch_fetch` (`waves`, `each`), `MCPP_BATCH_FETCH` | The dependencies one step of the resolution knows are fetched by one call of the provider | +| `batch-fetch` | on | `[build] batch_fetch` (`waves`, `each`), `MCPP_BATCH_FETCH` | The dependencies one step of the resolution knows are fetched by one call of the provider per environment: the home's, and the project's for the dependencies of its own index | | `plan-locks` | on | `[build] plan_locks` (`selection`, `configuration`), `MCPP_PLAN_LOCKS` | Commands that select different members of a workspace build one configuration at once ([07 §5.5](07-workspace.md)) | `MCPP_BUILDOPT=off mcpp build` is the standard build for one invocation: every entry diff --git a/docs/specs/build-optimizations.md b/docs/specs/build-optimizations.md index be3eb92eb..ae2394cde 100644 --- a/docs/specs/build-optimizations.md +++ b/docs/specs/build-optimizations.md @@ -39,7 +39,7 @@ | `scan-pass` | 图 | 严格 | 开 | — | 图的扫描先于编译,作为单独的一遍执行 | | `split-schedule` | 图 | 形态 | 关 | `[build] bmi_schedule`,`MCPP_BMI_SCHEDULE` | BMI 存在时导入者即开始,不等编译器退出(SPEC-011) | | `private-fragment` | 源码 | 源码 | 开 | `[build] private_fragment`(`unit`、`conservative`、`as-written`),`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元(§5) | -| `batch-fetch` | 取得 | 有条件 | 开 | `[build] batch_fetch`(`waves`、`each`),`MCPP_BATCH_FETCH` | 解析的一步已知的依赖由提供者的一次调用取得;这一批没有完成时每个依赖各自取得 | +| `batch-fetch` | 取得 | 有条件 | 开 | `[build] batch_fetch`(`waves`、`each`),`MCPP_BATCH_FETCH` | 解析的一步已知的依赖按环境(home 的环境;工程自己的索引的依赖所装入的工程环境)由提供者的一次调用取得;这一批没有完成时每个依赖各自取得 | | `plan-locks` | 运行 | 形态 | 开 | `[build] plan_locks`(`selection`、`configuration`),`MCPP_PLAN_LOCKS` | 选择工作区不同成员的命令同时构建一个配置,单元由其发布保护(SPEC-011 §2 第 7 至 10 条) | ## 2. 级别 diff --git a/docs/zh/26-build-optimizations.md b/docs/zh/26-build-optimizations.md index fc1b8d536..921805b77 100644 --- a/docs/zh/26-build-optimizations.md +++ b/docs/zh/26-build-optimizations.md @@ -24,7 +24,7 @@ profile 的各个键,见 [04 —— mcpp.toml](04-mcpp-toml.md);精确规则,见 | `scan-pass` | 开 | — | 图的扫描先于编译,作为单独的一遍执行 | | `split-schedule` | 关 | `[build] bmi_schedule`,`MCPP_BMI_SCHEDULE` | BMI 存在时导入者即开始,不等编译器退出 | | `private-fragment` | 开 | `[build] private_fragment`(`unit`、`conservative`、`as-written`),`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元 | -| `batch-fetch` | 开 | `[build] batch_fetch`(`waves`、`each`),`MCPP_BATCH_FETCH` | 解析的一步已知的依赖由提供者的一次调用取得 | +| `batch-fetch` | 开 | `[build] batch_fetch`(`waves`、`each`),`MCPP_BATCH_FETCH` | 解析的一步已知的依赖按环境由提供者的一次调用取得:home 的环境,以及工程自己的索引的依赖所装入的工程环境 | | `plan-locks` | 开 | `[build] plan_locks`(`selection`、`configuration`),`MCPP_PLAN_LOCKS` | 选择工作区不同成员的命令同时构建同一个配置([07 §5.5](07-workspace.md)) | `MCPP_BUILDOPT=off mcpp build` 对一次调用给出标准构建:全部条目关闭。没有参数的条目产出的字节与 diff --git a/modules/buildopt/src/registry.cppm b/modules/buildopt/src/registry.cppm index d09b8f58e..43b64adba 100644 --- a/modules/buildopt/src/registry.cppm +++ b/modules/buildopt/src/registry.cppm @@ -104,11 +104,11 @@ inline constexpr std::array kEntries{{ "unit | conservative | as-written", "as-written", "conservative"}, // Design 2026-11-27 §3.11.2, point 9: the payloads are the same, fetched // in fewer starts of the provider and connections. - {kBatchFetch, "the dependencies one step of the walk knows are fetched by one call of the provider", + {kBatchFetch, "the dependencies one step of the walk knows are fetched by one call of the provider per environment", Seam::Fetch, Level::Conditional, true, "[build] batch_fetch", "MCPP_BATCH_FETCH", "waves | each", "each"}, // Design 2026-11-27 §3.7.1: a plan's lock is its selection's and the // configuration's is shared, so commands that select different members - // build at once. It ran on every host before its default (SPEC-019 §3). + // build at once. It ran on every host before its default (SPEC-019 §2 item 2). {kPlanLocks, "commands that select different members of a configuration build at once; a unit is protected by its publication", Seam::Run, Level::Shape, true, "[build] plan_locks", "MCPP_PLAN_LOCKS", "selection | configuration", "configuration"}, }}; diff --git a/modules/buildopt/tests/test_source.cpp b/modules/buildopt/tests/test_source.cpp index 5078c327f..1390e767d 100644 --- a/modules/buildopt/tests/test_source.cpp +++ b/modules/buildopt/tests/test_source.cpp @@ -277,8 +277,12 @@ UTest register_states_every_entry{"Registry/EveryEntryStatesItsDefaultAndWhatSta // environment name and its values. if (e.level == registry::Level::Exact) expect(e.key.empty() && e.byDefault) << e.id; else expect(!e.key.empty() && !e.env.empty() && !e.values.empty()) << e.id; - // A shape is off until it has run on every host. - if (e.level == registry::Level::Shape) expect(!e.byDefault) << e.id; + // A shape is off until it has run on every host (SPEC-019 §2 item 2); the + // ones on by default name the run that carried them on each host. + static const std::set ranOnEveryHost{ + registry::kPlanLocks, // the CI of 2026.12.4.1, on every host (design 2026-11-27 §3.7.1) + }; + if (e.level == registry::Level::Shape) expect(!e.byDefault || ranOnEveryHost.contains(e.id)) << e.id; expect(has(registry::table(), std::format("| `{}` |", e.id))) << e.id; } expect(registry::find(registry::kPrivateFragment) != nullptr); diff --git a/src/build/prepare/graph_load.cpp b/src/build/prepare/graph_load.cpp index 141224eba..821414cb8 100644 --- a/src/build/prepare/graph_load.cpp +++ b/src/build/prepare/graph_load.cpp @@ -1403,7 +1403,10 @@ std::expected phase4a_graph_load(PrepareState& state) { auto cfg = state.get_cfg(true); if (!cfg) return; struct Pending { LoadVersionDepCtx ctx; std::string target; }; - std::vector pending; + // A dependency of the project's own index installs into the project's + // environment, where its install hook finds its siblings of that index; + // the rest into the home's. Each environment gets its own wave. + std::vector home, project; for (auto const& item : state.worklist) { auto const& spec = item.spec; // An exact version of a named namespace, with no patches: what the @@ -1420,7 +1423,7 @@ std::expected phase4a_graph_load(PrepareState& state) { if (!state.prefetchConsidered.insert(std::format("{}:{}@{}", ctx.ns, ctx.shortName, ctx.version)).second) continue; if (!step4a_load_version_dep_locate(state, ctx)) continue; - if (ctx.installed || ctx.useProjectEnv || !ctx.luaContent) continue; + if (ctx.installed || !ctx.luaContent) continue; if (mcpp::manifest::xpkg_name_form_violation_from_lua(*ctx.luaContent)) continue; // An inline descriptor with mcpp dependencies has them installed // before its own hook runs; the path of one dependency does that. @@ -1431,34 +1434,41 @@ std::expected phase4a_graph_load(PrepareState& state) { } auto target = std::format("{}@{}", mcpp::manifest::xpkg_wire_address(*ctx.luaContent, ctx.ns, ctx.shortName).target, ctx.version); - pending.push_back({std::move(ctx), std::move(target)}); - } - // One dependency gains nothing from a wave; its own path says more. - if (pending.size() < 2) return; - std::vector targets; - mcpp::fetcher::InstallProgressHandler progress; - for (auto const& p : pending) { - targets.push_back(p.target); - progress.labels.emplace(p.target, mcpp::fetcher::DownloadLabel{ - std::format("{}.{} v{}", p.ctx.ns, p.ctx.shortName, p.ctx.version), - p.ctx.reinstallFrom ? "Updating" : ""}); - } - const auto provider = mcpp::provider::open(mcpp::config::make_xlings_env(**cfg)); - mcpp::home::Turn turn(provider->state_dir(), mcpp::provider::kStateTurn, - {.resource = "the install state of this home", - .doing = std::format("installing {} dependencies", pending.size())}); - // Not held: each dependency's own path refuses with why. - if (turn.failure()) return; - const InstallHookScope hookScope(state); - mcpp::fetcher::Fetcher fetcher(**cfg); - auto r = fetcher.install(targets, &progress); - mcpp::log::verbose("fetcher", std::format("a wave of {} dependencies: {}", targets.size(), - !r ? r.error().message : r->exitCode == 0 ? std::string("installed") - : std::format("the provider exited {}; each not installed is asked alone", r->exitCode))); - for (auto& p : pending) { - if (!step4a_load_version_dep_locate(state, p.ctx)) continue; - if (p.ctx.installed) check_read_revision(state, p.ctx); + (ctx.useProjectEnv ? project : home).push_back({std::move(ctx), std::move(target)}); } + auto wave = [&](std::vector& pending, bool projectEnv) { + // One dependency gains nothing from a wave; its own path says more. + if (pending.size() < 2) return; + std::string args = R"({"targets":[)"; + mcpp::fetcher::InstallProgressHandler progress; + for (auto const& p : pending) { + args += std::format("{}\"{}\"", &p == pending.data() ? "" : ",", p.target); + progress.labels.emplace(p.target, mcpp::fetcher::DownloadLabel{ + std::format("{}.{} v{}", p.ctx.ns, p.ctx.shortName, p.ctx.version), + p.ctx.reinstallFrom ? "Updating" : ""}); + } + args += R"(],"yes":true})"; + const auto provider = mcpp::provider::open(projectEnv + ? mcpp::config::make_project_xlings_env(**cfg, state.projectIndexRoot()) + : mcpp::config::make_xlings_env(**cfg)); + mcpp::home::Turn turn(provider->state_dir(), mcpp::provider::kStateTurn, + {.resource = "the install state of this home", + .doing = std::format("installing {} dependencies", pending.size())}); + // Not held: each dependency's own path refuses with why. + if (turn.failure()) return; + const InstallHookScope hookScope(state); + auto r = provider->call("install_packages", args, &progress); + mcpp::log::verbose("fetcher", std::format("a wave of {} dependencies{}: {}", pending.size(), + projectEnv ? " of the project's own index" : "", + !r ? std::format("{}", r.error()) : r->exitCode == 0 ? std::string("installed") + : std::format("the provider exited {}; each not installed is asked alone", r->exitCode))); + for (auto& p : pending) { + if (!step4a_load_version_dep_locate(state, p.ctx)) continue; + if (p.ctx.installed) check_read_revision(state, p.ctx); + } + }; + wave(home, false); + wave(project, true); }; state.loadVersionDepVariant = [&](const std::string& depName, const std::string& ns, From 275e96b931d459b165edd3e8bccb92bf8166fc62 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 05:46:41 +0900 Subject: [PATCH 15/36] The agent sheets as a network; mcpp info; mcpp add writes full identities as dotted keys The root sheet states the architecture, the command a task needs, the project conventions (a module in one .cppm with a private fragment; dependencies as full identities in name order; mcpp-index's module libraries first), how a message reads, and what to do when mcpp itself is wrong: analyse, reduce, work around, report with the user's consent and, when the cause is located, a fix, then print the address for review. Every command sheet ends with the commands related to it, each a visible command, which a unit test checks; the build sheet states build programs and the official plugins. mcpp info shows one package of the indices: its versions and the systems each serves, license, repository, features, what the project states and locks of it, and the mcpp add line (mcpp.info envelope with --format json). mcpp add writes a dependency's full identity as a dotted key in name order, the default namespace's packages as well, and replaces a bare key of the same package; a [dependencies.] table keeps its form. The hints of the bare-name fallback, of a declared identity and of a build program's missing import, the guide's examples and the examples' manifests use that spelling; an entry of [build-dependencies] that lists neither tools nor artifacts omits host-module, which restates the default there. The golden files carry this release's surface; the commands the help hides are not items of it. --- .../2026-11-27-ecosystem-boundary-design.md | 30 +++- CHANGELOG.md | 21 ++- docs/03-examples.md | 2 +- docs/05-dependencies.md | 32 ++-- docs/06-features-and-capabilities.md | 4 +- docs/07-workspace.md | 24 ++- docs/09-commands-by-scenario.md | 4 + docs/22-target-side.md | 4 +- docs/23-the-project-environment.md | 4 +- docs/30-build-mcpp.md | 14 +- docs/42-heterogeneous-builds.md | 6 +- docs/50-machine-output.md | 19 +- docs/mcpp-skills/mcpp-add/SKILL.md | 52 +++++- docs/mcpp-skills/mcpp-build/SKILL.md | 37 ++++ docs/mcpp-skills/mcpp-cache/SKILL.md | 5 + docs/mcpp-skills/mcpp-clean/SKILL.md | 5 + docs/mcpp-skills/mcpp-emit/SKILL.md | 5 + docs/mcpp-skills/mcpp-explain/SKILL.md | 6 + docs/mcpp-skills/mcpp-fetch/SKILL.md | 5 + docs/mcpp-skills/mcpp-index/SKILL.md | 5 + docs/mcpp-skills/mcpp-info/SKILL.md | 57 ++++++ docs/mcpp-skills/mcpp-new/SKILL.md | 6 + docs/mcpp-skills/mcpp-pack/SKILL.md | 6 + docs/mcpp-skills/mcpp-publish/SKILL.md | 5 + docs/mcpp-skills/mcpp-remove/SKILL.md | 5 + docs/mcpp-skills/mcpp-resolve/SKILL.md | 5 + docs/mcpp-skills/mcpp-run/SKILL.md | 5 + docs/mcpp-skills/mcpp-search/SKILL.md | 5 + docs/mcpp-skills/mcpp-self/SKILL.md | 6 + docs/mcpp-skills/mcpp-stage/SKILL.md | 5 + docs/mcpp-skills/mcpp-test/SKILL.md | 6 + docs/mcpp-skills/mcpp-toolchain/SKILL.md | 5 + docs/mcpp-skills/mcpp-update/SKILL.md | 5 + docs/mcpp-skills/mcpp-version/SKILL.md | 5 + docs/mcpp-skills/mcpp-why/SKILL.md | 6 + docs/mcpp-skills/mcpp-write/SKILL.md | 5 + docs/mcpp-skills/mcpp-xpkg/SKILL.md | 5 + docs/mcpp-skills/mcpp/SKILL.md | 165 +++++++++--------- docs/specs/README.md | 4 +- docs/specs/manifest-semantics.md | 15 +- docs/specs/package-identity.md | 22 +-- docs/zh/03-examples.md | 2 +- docs/zh/05-dependencies.md | 26 +-- docs/zh/06-features-and-capabilities.md | 4 +- docs/zh/07-workspace.md | 24 ++- docs/zh/09-commands-by-scenario.md | 3 + docs/zh/22-target-side.md | 4 +- docs/zh/23-the-project-environment.md | 4 +- docs/zh/30-build-mcpp.md | 10 +- docs/zh/42-heterogeneous-builds.md | 8 +- docs/zh/50-machine-output.md | 15 +- examples/09-heterogeneous/README.md | 4 +- examples/09-heterogeneous/boundary/mcpp.toml | 4 +- examples/09-heterogeneous/cann/app/mcpp.toml | 4 +- examples/09-heterogeneous/cuda/README.md | 8 +- examples/09-heterogeneous/cuda/app/mcpp.toml | 8 +- examples/09-heterogeneous/hip/README.md | 2 +- examples/09-heterogeneous/hip/app/mcpp.toml | 8 +- .../09-heterogeneous/multi-backend/README.md | 4 +- .../09-heterogeneous/multi-backend/mcpp.toml | 14 +- examples/09-heterogeneous/sycl/app/mcpp.toml | 8 +- .../09-heterogeneous/vulkan/app/mcpp.toml | 10 +- examples/10-graphics/README.md | 4 +- examples/10-graphics/offscreen/mcpp.toml | 8 +- modules/manifest/src/toml.cppm | 105 ++++++++--- src/build/prepare/graph_load.cpp | 18 +- src/build/prepare/host_graph.cpp | 4 +- src/cli.cppm | 7 + src/cli/cmd_registry.cppm | 7 + src/pm/index_management.cppm | 123 +++++++++++++ tests/e2e/cli/surface.cpp | 6 + tests/e2e/cli/usage.cpp | 2 +- tests/e2e/deps/identity.cpp | 2 +- tests/e2e/deps/names.cpp | 4 +- tests/e2e/deps/path.cpp | 13 +- tests/e2e/golden/protocol-version.json | 8 + tests/e2e/golden/surface.txt | 56 +++--- tests/unit/test_cli_documents.cpp | 28 +++ tests/unit/test_manifest.cpp | 40 ++++- 79 files changed, 921 insertions(+), 320 deletions(-) create mode 100644 docs/mcpp-skills/mcpp-info/SKILL.md diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index 82d07d75a..4358b2568 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -5,7 +5,7 @@ status: active # 生态与外部的交界:工具链的事实、二进制库交付物、被启动的外部程序、名字的拼写与共享的状态 -**日期:** 2026-11-27,2026-12-04、2026-12-05 修订 · **版本:** v10(v9 增加 §3.12 CPS 与决定 D16 至 D21;v10 以 mcpp 为中心重写 §3.12,D22 至 D24 取代 D16 至 D18 与 D21;决定全部作出,见 §7;五轮自查的结论见 §11) · +**日期:** 2026-11-27,2026-12-04、2026-12-05 修订 · **版本:** v11(v9 增加 §3.12 CPS 与决定 D16 至 D21;v10 以 mcpp 为中心重写 §3.12,D22 至 D24 取代 D16 至 D18 与 D21;v11 增加 §3.9.4 说明的网络、`mcpp info` 与依赖的写法,决定 D25 至 D27;决定全部作出,见 §7;五轮自查的结论见 §11) · **基线:** mcpp main `30fcd5a0`(2026.11.27.1 之后,含 #1036)、xlings 2026.11.23.1、openkal 0.26.0、openkal-linux 0.27.2、 openkal-windows 0.23、openkal-musl 0.30.3、mcpplibs.os 0.4.8、mcpplibs.cmdline 0.1.0(mcpp 所钉为 0.0.6)、 mcpp-index `9788068b` · @@ -919,6 +919,31 @@ mcpp 的自举版本须能读懂 cmdline 新版本的清单(它用到构建依 e2e:`mcpp --agent-skill-doc` 与一个子命令的应答在没有网络、当前目录为空的环境里可用;根帮助列出命令树的每个非隐藏 命令并含指向 skill 的那一行;三种用法错误各自的 `help:` 行;`mcpp explain` 对三类代码各一例。 +#### 3.9.4 说明的网络、一个包的信息与依赖的写法(v11) + +§3.9.2 的说明各自完整,但彼此不相连:一个 agent 读完 `mcpp add` 的说明,不知道下一步读哪一份;根说明讲日常循环, +不讲 mcpp 由什么构成、工程按什么约定写,也不讲 mcpp 自身出错时怎样做。本节补这三处,判据仍是「只凭这个二进制」。 + +1. **根说明是入口与地图。** 它陈述架构(数据驱动的计划与四档覆盖、home、两个索引、依赖图与构建程序、官方插件的 + 四个族),任务到命令的对照,工程的约定(一个模块一个 `.cppm`,非导出的接口与实现在私有片段;依赖写完整身份的 + 点号键并按名字排列;库的选择次序:mcpp-index 的模块库、`compat.*`、经 `deps-*` 插件的 CMake 与 vcpkg 包,已有的 + 模块被依赖而不重写),消息的读法,以及 mcpp 自身出错时的五步:分析(`explain`、`why`、`-v`、上次构建的记录、 + `self doctor`)、缩小到最小工程、解除阻塞(`mcpp clean`、`--cache off`、`-j 1`、另一个 `--toolchain`、`help:` 所点名 + 的开关,留在工程里的绕过带一条指明缺陷的注释)、提出报告、给出所建 issue 或 PR 的地址。缺陷的判据写明:退出码 70 + 或崩溃、补救无效、结果与文档不符、相同输入的两次运行不同;工程自身代码的编译错误不是。 +2. **报告经使用者同意。** 开 issue 或 PR 之前问使用者,除非上下文里已经同意;原因已经定位时,同一个问题里一并问是否 + 附带修复的 PR。issue 带一个标签(`bug`、`upstream-bug`、`documentation`、`enhancement`)与复现所需的材料。mcpp + 欢迎这样的报告,说明照此陈述,而不是让 agent 自己决定是否对外发布。 +3. **每份命令说明以 `## Related` 结束。** 其中点名的每个 `mcpp <命令>` 是一个可见命令,由单元测试核对;`explain`、`why`、 + `self` 与 `build` 的说明指回根说明中出错时的一节。说明由此是一张网,根说明是它的入口。 +4. **`mcpp info <包>`。** `search` 回答「有哪些」,决定依赖时还要「这一个怎样」:版本及各版本服务的系统、许可、仓库、 + 特性、工程已写与已锁的版本、加入它的那一行。它是 `search` 旁的一个工程命令,`--format json` 为 `mcpp.info` 信封。 +5. **`mcpp add` 写完整身份的点号键,按名字的次序。** 缺省命名空间的包同样写全(`mcpplibs.cmdline = "0.2.0"`),同一个包 + 的裸键被它取代;清单已有 `[dependencies.]` 表头时写入该表,保持清单自己的形式。用户可见的提示(裸名的回退、 + 路径与 git 依赖声明的身份、构建程序缺少的导入)与文档的例子用同一写法。 +6. **`host-module = true` 只写在需要它的地方。** `[build-dependencies]` 的条目未列出 `tools` 或 `artifacts` 时本来就请求库 + (SPEC-004 §12 第 5 条,2026.10.11.1 起),例子与插件的文档不再写它;它只在 `tools` 旁请求库时出现。 + ### 3.10 索引条目的每个版本都可安装(mcpp-index) **现状(读 CI 日志与索引的提交)。** 2026-12-03 收录 `mcpplibs.cmdline` 0.1.0 时,条目由内联的构建描述改为指向包内 @@ -1311,6 +1336,9 @@ mcpp#1027。 | **D22** | CPS 的读取(2026-12-05,取代 D16 至 D18) | **构建程序的声明 `mcpp::cps_package`,在应用指令之前展开为已有指令的效果**(§3.12.2 二);mcpp 的依赖图只有 mcpp 的包,组件、配置、厂商词留在 CPS 的代码里 | CPS 前缀作为索引的一种(D16):CPS 与 mcpp 自己的来源并列,带来索引的种类、`components` 键、`@host`、锁的条目,而需要的效果是声明者的用法,已有指令能表达。依赖上的路径指向 `.cps` 并合成清单:mcpp 没有公开的宏,`definitions` 无处可放 | | **D23** | 构建时才填好的前缀(2026-12-05,取代 D21) | **不经 CPS 读取**;插件照旧写库名(§3.12.2 三);不设命令行命令 | 引擎写出读取的步骤(D21):需要「词取自动作写出的文件」这一新的通用契约,只为一种格式。一级命令 `mcpp cps`:格式不是任务,且无使用者。「TOOLS FOR ACTIONS」中的工具:插件绑定参数形状 | | **D24** | CPS 的代码放在哪里(2026-12-05) | **独立的模块包 `modules/cps/`,每个使用处一个适配文件**(§3.12.2 六) | 分散进 `mcpp.pack.library` 与构建程序的应用:格式的知识与 mcpp 的机制交织,去掉或升级格式要改多处 | +| **D25** | 一个包的信息(2026-12-05) | **`mcpp info <包>`**,与 `search` 并列,读同一份索引与工程(§3.9.4 第 4 条) | 名为 `pkginfo`:与 `xlings info` 等既有习惯不一致,且 mcpp 的命令不带对象前缀。扩展 `search` 的输出:一次查询的列表与一个包的详情是两种回答 | +| **D26** | `mcpp add` 写出的形式(2026-12-05) | **完整身份的点号键,按名字的次序;已有的命名空间表头被保留**(§3.9.4 第 5 条) | 一律改写为点号键:改动用户自己选择的形式。继续为缺省命名空间写裸键:同一个清单里两种写法,且依赖于缺省命名空间这一隐含的事实 | +| **D27** | agent 发现 mcpp 自身的缺陷时(2026-12-05) | **本地分析与绕过,报告与修复先经使用者同意,建成后给出地址**(§3.9.4 第 2 条) | 不提报告:缺陷留在使用者的工程里。由 agent 自行提交:对外发布的内容未经使用者看过 | | — | 诊断 | §10 的规则与清单是本轮验收的一部分 | — | 另有先前作出、本文据以设计的决定:引擎不内置厂商工具链的名字;索引的缺包补齐;交付物的环境经 `[xlings]` 这一 diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf942465..8c9f9b57c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,18 @@ ### Added - `--agent-skill-doc` at every level of the command tree prints how to use mcpp: the root sheet - (the daily loop, reading a message, the output for programs, the statuses) with an index of the - commands' sheets, and each command's sheet (when to use it, examples, what it reads, writes and - downloads, its refusals with their remedies, what it may wait for). The sheets live in + (the architecture, the command a task needs, the project conventions, reading a message, what to + do when mcpp itself is wrong -- analyse, reduce, work around, report with the user's consent, + fix -- and how to contribute) with an index of the commands' sheets, and each command's sheet + (when to use it, examples, what it reads, writes and downloads, its refusals with their + remedies, what it may wait for), which ends with the commands related to it. The sheets live in `docs/mcpp-skills/` and are rendered into the binary when it is built; the answer needs no - project, no home and no network. A test parses every example of a sheet by the command tree. + project, no home and no network. Tests parse every example of a sheet by the command tree and + check that every related command is a visible one. +- `mcpp info ` shows one package of the indices: its identity, description, versions and + the systems each serves, its features, the version the project states and the one it locked, + and the `mcpp add` line that adds it; `--format json` prints the `mcpp.info` envelope + (docs/50). - `mcpp help ` is `mcpp --help`. - A usage error asked for JSON (`--format json`, `--message-format json`) is also a `mcpp.usage` envelope on standard output: one diagnostic with a `MCPP_USAGE_*` code and the closest declared @@ -65,6 +72,12 @@ - A command that needs a project, run outside one, says `no mcpp.toml in the current directory or any parent` and names the two next steps. - mcpp depends on mcpplibs.cmdline 0.2.0 with its `agent-skills` feature. +- `mcpp add` writes a dependency's full identity as a dotted key, the default namespace's + packages as well (`mcpplibs.cmdline = "0.2.0"`), in name order among the keys of its table, + and replaces a bare key of the same package; a table written as `[dependencies.]` + keeps its form. The hints of the bare-name fallback, of an identity a path or git dependency + declares and of a build program's missing import write the dotted key (SPEC-004 §17, + SPEC-001 §4.1). - A library package carries `mcpp-package.json`, as a program's package does, and per leg a pkg-config description `lib//pkgconfig/.pc` from its own link intent, with `mcpp_abi` stating its compatibility tag. `mcpp emit xpkg --package` writes a library package's diff --git a/docs/03-examples.md b/docs/03-examples.md index 81a2deafa..cb08752f3 100644 --- a/docs/03-examples.md +++ b/docs/03-examples.md @@ -81,7 +81,7 @@ the map; the table below is what each sub-example adds. | example | first to introduce | |---|---| -| [`08-build-rules`](../examples/08-build-rules/) | two rule packages and a project using both; `host-module = true`, `mcpp::action` with `role = "check"` | +| [`08-build-rules`](../examples/08-build-rules/) | two rule packages and a project using both as `[build-dependencies]` entries; `mcpp::action` with `role = "check"` | | [`12-a-new-device-language`](../examples/12-a-new-device-language/) | `device_extensions` and `rule_module`: a rule package teaching mcpp a language the engine has never heard of, whose compiler is a package built through `tools = [...]` for the build machine | | [`13-platform-targets`](../examples/13-platform-targets/) | one source and no `cfg`, built for Linux, WebAssembly and both Android ABIs by changing only `--target`; `min_api_level` as the project's own decision, and a capability pin that cannot be overridden | diff --git a/docs/05-dependencies.md b/docs/05-dependencies.md index f7bedca52..1019a930e 100644 --- a/docs/05-dependencies.md +++ b/docs/05-dependencies.md @@ -300,14 +300,14 @@ manifest by its path relative to the project root and lists the keys: ```toml # mcpp.toml; libs/fw and libs/comp declare namespace = "huxdemo" -[dependencies.acme] -fw = { path = "libs/fw" } -comp = { path = "libs/comp" } +[dependencies] +acme.comp = { path = "libs/comp" } +acme.fw = { path = "libs/fw" } ``` ``` -warning: mcpp.toml names 2 dependencies in namespace acme, and the manifests they reach declare huxdemo; the declared identity is used: acme.fw, acme.comp - help: write them in a [dependencies.huxdemo] table, for example `fw = { path = "libs/fw" }` +warning: mcpp.toml names 2 dependencies in namespace acme, and the manifests they reach declare huxdemo; the declared identity is used: acme.comp, acme.fw + help: write them in namespace huxdemo, for example `huxdemo.comp = { path = "libs/comp" }` ``` Two edges written `fw` and `huxdemo.fw` over one directory are therefore one @@ -363,7 +363,7 @@ There is no ordered fallback or fuzzy, index-wide search by short name: [dependencies] chriskohlhoff.asio = "1.38.1" -# Correct — namespace sub-table (preferred for several packages from one org) +# Correct — namespace sub-table (an equivalent spelling) [dependencies.chriskohlhoff] asio = "1.38.1" @@ -376,10 +376,15 @@ The third form fails with an error that names the exact `(mcpplibs, asio)` identity that was tried and, when the short name exists elsewhere, gives a copyable explicit selector. -**What `mcpp add` writes (2026.11.27.1+).** It writes into the form the table -already uses for the namespace: the short key under a `[dependencies.]` -header when there is one, and otherwise the dotted key `.` in -`[dependencies]`; a package of the default namespace is a bare key. `--dev` +**What `mcpp add` writes (2026.12.4.1+).** The package's full identity as a +dotted key, `.`, in `[dependencies]`, placed in name order among the +keys there; a package of the default namespace is written so as well +(`mcpplibs.cmdline = "0.2.0"`), and a bare key of the same package is replaced +by it. A table the manifest writes as a `[dependencies.]` header keeps that +form: the entry is the short key there, in name order. A key that would make +another key's path a table (`mcpplibs.mtest` beside `mcpplibs.mtest.gtest`) is +written quoted. Before 2026.12.4.1 a package of the default namespace was a bare +key and an entry went first in its table. `--dev` writes `[dev-dependencies]` and `--build` writes `[build-dependencies]`; `mcpp remove` takes the same flags and removes from `[dependencies]` without them. A header that reopens a table dotted keys already defined — `compat.libpng` @@ -553,8 +558,8 @@ nothing, whatever archive directories are named. ## `[dev-dependencies]` — Test Dependencies ```toml -[dev-dependencies.compat] -gtest = "1.15.2" +[dev-dependencies] +compat.gtest = "1.15.2" ``` `mcpp build` ignores these; `mcpp test` resolves and uses them, for the test units only: the package's own sources compile under `mcpp test` as under `mcpp build` (2026.11.8.1+, [08](08-testing.md#tests-that-reach-packages-the-artifact-does-not)). `mcpp test` automatically discovers `tests/**/*.cpp` and compiles them into test binaries. The runner is framework-agnostic: each file is an independent binary judged by exit code — a bare `main`, gtest (via `[dev-dependencies]` + `gtest_main`), or any other framework all work identically, and `-- args` are forwarded to every test binary (e.g. `-- --gtest_filter=...`). Note: synthesized test target names may contain `/` (`tests/00-a/0.cpp` → `00-a/0`), unlike `[targets.*]` names — the two namespaces are intentionally separate (test targets never enter the manifest or publishing). Tests are named by their `tests/`-relative path (`tests/00-a/0.cpp` → `00-a/0`), each test compiles in isolation (a broken test fails alone; package/dep breakage is reported as a build error instead), and `mcpp test ` / `--message-format json` filter and machine-format the run. @@ -598,7 +603,8 @@ each axis has its own place in the manifest. - The **request on the edge** decides which products are wanted. A `[build-dependencies]` entry asks for the package's library unless it lists `tools` or `artifacts`; `host-module = true` asks for the library beside them, - and `host-module = false` declines it. `tools = [...]` asks for programs built + and `host-module = false` declines it. An entry that lists neither omits the + key: `mcpp.plugins = { version = "0.27.0", features = ["rules-spirv"] }`. `tools = [...]` asks for programs built for the machine that runs the build, from either section. | Entry | Effect | diff --git a/docs/06-features-and-capabilities.md b/docs/06-features-and-capabilities.md index 3377bab02..d91c872c2 100644 --- a/docs/06-features-and-capabilities.md +++ b/docs/06-features-and-capabilities.md @@ -200,8 +200,8 @@ Two things follow, and neither puts a package name inside mcpp: The feature is still requested **by name**: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-spirv"] } ``` An earlier design derived the set from the extensions a project's sources diff --git a/docs/07-workspace.md b/docs/07-workspace.md index 9db6908b9..8df48a540 100644 --- a/docs/07-workspace.md +++ b/docs/07-workspace.md @@ -96,10 +96,8 @@ name = "http" version = "0.1.0" [dependencies] +compat.mbedtls.workspace = true myproject.core = { path = "../core" } - -[dependencies.compat] -mbedtls.workspace = true ``` ## 3. Inheriting Dependency Versions @@ -109,21 +107,19 @@ Declare dependency versions centrally under `[workspace.dependencies]`; members ```toml # root mcpp.toml [workspace.dependencies] -cmdline = "0.0.2" +cmdline = "0.0.2" +compat.gtest = "1.15.2" +compat.mbedtls = "3.6.1" mcpplibs.capi.lua = "0.0.3" # exact selector: (mcpplibs.capi, lua) - -[workspace.dependencies.compat] -mbedtls = "3.6.1" -gtest = "1.15.2" ``` ```toml # member mcpp.toml -[dependencies.compat] -mbedtls.workspace = true # inherits version → "3.6.1" +[dependencies] +compat.mbedtls.workspace = true # inherits version → "3.6.1" -[dev-dependencies.compat] -gtest.workspace = true # inherits version → "1.15.2" +[dev-dependencies] +compat.gtest.workspace = true # inherits version → "1.15.2" ``` The features an entry of `[workspace.dependencies]` requests are inherited @@ -153,8 +149,8 @@ no source and was resolved from the index. A member can override an inherited version: ```toml -[dependencies.compat] -mbedtls = "4.0.0" # override; does not use the workspace version +[dependencies] +compat.mbedtls = "4.0.0" # override; does not use the workspace version ``` An entry that says `.workspace = true` and that no workspace resolves is diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index af0a17ccf..5b8d1d502 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -165,6 +165,10 @@ $ mcpp search imgui The trailing `, ...` marks truncation: three versions are shown by default, and its absence means the list is complete. `--all-versions` prints the whole list. +`mcpp info .[@]` shows one package in depth: every +version and the systems the newest (or the one named) is published for, its +license and repository, whether it is an mcpp package and its features, what the +project states and locks of it, and the `mcpp add` line (2026.12.4.1+). A package whose descriptor cannot be read prints as two columns — the version list is best-effort display and never fails the search. diff --git a/docs/22-target-side.md b/docs/22-target-side.md index 17b322d91..3042f55e0 100644 --- a/docs/22-target-side.md +++ b/docs/22-target-side.md @@ -1111,8 +1111,8 @@ A selector may carry platform-conditional **dependencies** and **build flags**: ```toml # Concise bare-alias form — pull OpenBLAS and link it only on Windows. -[target.windows.dependencies.compat] -openblas = "0.3.33" +[target.windows.dependencies] +compat.openblas = "0.3.33" [target.windows.build] ldflags = ["-Llib", "-llibopenblas"] diff --git a/docs/23-the-project-environment.md b/docs/23-the-project-environment.md index 776807ba4..0e088a179 100644 --- a/docs/23-the-project-environment.md +++ b/docs/23-the-project-environment.md @@ -513,8 +513,8 @@ The table above is what a project writes when it has an opinion. Most projects have none, and nothing is what they write: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-cuda"], host-module = true } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-cuda"] } ``` That one edge is the whole declaration. The rule package names the packages its diff --git a/docs/30-build-mcpp.md b/docs/30-build-mcpp.md index 2f13619b9..832ebe6e9 100644 --- a/docs/30-build-mcpp.md +++ b/docs/30-build-mcpp.md @@ -1669,8 +1669,8 @@ reached, with the entry that would make it importable: error: build.mcpp imports 'mcpp.rules.spirv', and no build dependency provides it. ... - [build-dependencies.] - = { version = "..." } # or `host-module = true` beside `tools` + [build-dependencies] + . = { version = "..." } # or `host-module = true` beside `tools` declared without its library: mcpp.plugins (in [build-dependencies]) **The module name is declared by the rule's source, and `mcpp.*` is reserved.** @@ -1988,9 +1988,9 @@ int main() { } ``` -The entry asks for the library unless it lists `tools` or `artifacts`; -`host-module = true` asks for it beside them, and `host-module = false` -declines it (05 — Dependencies and Resolution). A library a dependency hands on +The entry asks for the library unless it lists `tools` or `artifacts`, so it +does not write `host-module = true`; that key asks for the library beside +them, and `host-module = false` declines it (05 — Dependencies and Resolution). A library a dependency hands on with `reexport = true` is used the same way. #### The build programs' graph @@ -2105,8 +2105,8 @@ rules-spirv = { sources = ["rules/spirv.cppm"], rule_module = "mcpp.rules.spirv" ```toml # a consumer -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-spirv"] } ``` The module set is the feature set: a unit whose feature is not active is not diff --git a/docs/42-heterogeneous-builds.md b/docs/42-heterogeneous-builds.md index a168140fc..9dfe0ab51 100644 --- a/docs/42-heterogeneous-builds.md +++ b/docs/42-heterogeneous-builds.md @@ -362,7 +362,7 @@ be read side by side. ## Compiling an island The command that invokes a device compiler is not built into mcpp. It is -supplied by a **build-rule package**, consumed with `host-module = true`, +supplied by a **build-rule package**, consumed as a `[build-dependencies]` entry, which emits build-graph edges whose outputs join the link. See [30 — build.mcpp](30-build-mcpp.md) for the mechanism and `examples/09-heterogeneous/cuda` for a working CUDA rule. @@ -376,8 +376,8 @@ its host-compiler requirements belong to the rule. A project that wants a CUDA island writes one edge: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-cuda"], host-module = true } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-cuda"] } ``` and nothing else. The vendor toolkit, its runtime and whatever else the rule diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index 56ad6c96a..be058896b 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -1053,7 +1053,8 @@ reason unknown-target The commands and flags are those of the definition the command line is parsed with (a global flag is named without a command); the keys are the manifest's key registry (a whole table by its name); the reasons are the tokens of the refusals' table (`mcpp.why.toolchain`, above). `--help` and `--version`, which the parser -adds, are not items. +adds, are not items, nor are the commands the help hides, which the build graph runs +(`link-output`, `dyndep`; 2026.12.4.1+). Two variables name a file an invocation appends to; each process of the invocation appends, so a build's own sub-builds and the compilers it starts through mcpp add to the same file: @@ -1313,6 +1314,22 @@ is not known here. Each feature has `name`, `default` (in the default set, its `implies` closure included), `implies` (features of the package), `enables` (`/`) and, when written, `description`. +### `mcpp.info` — one package of the indexes (2026.12.4.1+) + +``` +mcpp info .[@] --format json +``` + +`data` is `id` (`namespace.name`), `namespace`, `name`, `description`, +`index`, `versions` (newest first), `version` (the one asked for, else the +newest), `systems` (the descriptor platforms that publish `version`), +`licenses`, `repo`, `mcppPackage` (whether mcpp reads a manifest of it), +`features` (as in `mcpp.search`, for `version`; `null` for a package that is +not an mcpp package), `stated` (`table` and `version` when the project's +manifest names the package, else `null`), `locked` (the version `mcpp.lock` +holds, else `null`) and `add` (the `mcpp add` line for `version`). Nothing is +installed. + ### `mcpp.index` — the registries and the project's indexes ``` diff --git a/docs/mcpp-skills/mcpp-add/SKILL.md b/docs/mcpp-skills/mcpp-add/SKILL.md index c77881246..7503fc523 100644 --- a/docs/mcpp-skills/mcpp-add/SKILL.md +++ b/docs/mcpp-skills/mcpp-add/SKILL.md @@ -1,24 +1,53 @@ --- name: mcpp-add -description: Use when adding a dependency, a test-only dependency or a build dependency to mcpp.toml. +description: Use when adding a dependency, a test-only dependency or a build dependency (a plugin, a tool) to mcpp.toml. --- # mcpp add -Writes a dependency into `mcpp.toml`, at an exact version. +Writes a dependency into `mcpp.toml` at an exact version: its full identity +as a dotted key, in name order, under the table the flags name. ## Examples ``` mcpp add mcpplibs.cmdline@0.2.0 -mcpp add gtest@1.15.2 --dev -mcpp add mcpplibs.mplugin.cmdline@0.2.0 --build +mcpp add compat.gtest@1.15.2 --dev +mcpp add mcpp.plugins@0.27.0 --build ``` -The version is required and exact; `mcpp search ` lists the versions -published. `--dev` writes `[dev-dependencies]` -(tests only), `--build` writes `[build-dependencies]` (a build program or a -tool the build runs). +```toml +[dependencies] +mcpplibs.cmdline = "0.2.0" + +[dev-dependencies] +compat.gtest = "1.15.2" + +[build-dependencies] +mcpp.plugins = "0.27.0" +``` + +- The version is required and exact; `mcpp info ` lists the versions + published and the line to run. +- `--dev`: `[dev-dependencies]`, compiled for tests only. `--build`: + `[build-dependencies]`, for the build program (a plugin, a host tool). A + plugin's members are chosen by editing the entry into a table with + `features`; its library reaches `build.mcpp` without more (see + `mcpp build --agent-skill-doc`). +- A table written as `[dependencies.]` keeps its form: the entry + goes there under its short name. A bare key of the same package is + replaced by the dotted one; `mcpp.lock` changes at the next build. + +## Choosing what to add + +1. A module library of mcpp-index (`mcpplibs.*`): `import` it, no header. +2. A `compat.*` package: a C or C++ library built by mcpp, used by header. +3. A CMake or vcpkg package through the `deps-cmake` or `deps-vcpkg` plugin. + +A dependency is a package of mcpp's graph: resolved before planning, locked, +built with the project's toolchain for its target. A library another build +system already installed is declared in `build.mcpp` instead +(`mcpp::cps_package`), and is not locked. ## Reads, writes, network @@ -28,9 +57,16 @@ The next build resolves it and updates `mcpp.lock`. ## Refusals - No version: `mcpp add @`. +- A name no index has: the message lists the names tried. - A version the index does not have for this platform: the message lists those it has. ## Waits An index refresh waits for another run's; `--lock-wait` bounds it. + +## Related + +- `mcpp search` finds a package by keyword; `mcpp info` shows one. +- `mcpp remove` takes a dependency out; `mcpp update` moves the lock. +- `mcpp build` resolves and builds it; `mcpp why deps` states who needs what. diff --git a/docs/mcpp-skills/mcpp-build/SKILL.md b/docs/mcpp-skills/mcpp-build/SKILL.md index 983adce65..491597e63 100644 --- a/docs/mcpp-skills/mcpp-build/SKILL.md +++ b/docs/mcpp-skills/mcpp-build/SKILL.md @@ -54,3 +54,40 @@ Runs that select the same members of a workspace, or build one package, take turns on its build directory; a second run waits, as it waits for an install in the home. Runs that select different members of a workspace build at once. `--lock-wait` bounds the wait. + +## Build programs and plugins + +A `build.mcpp` beside `mcpp.toml` is a C++ program the build runs first; it +imports `mcpp` and prints what the build needs. A plugin is a library it +imports: the official ones are `mcpp.plugins`, one member per feature +(https://github.com/mcpp-community/mcpp-plugins). + +```toml +[build-dependencies] +mcpp.plugins = { version = "0.27.0", features = ["rules-spirv"] } +``` + +```cpp +import mcpp; +import mcpp.rules.spirv; +int main() { + mcpp::cxxflag("-DUSE_SIMD"); + mcpp::rerun_if_changed("config/simd.txt"); + mcpp::rules::spirv::options opt; + opt.includes = { "shaders" }; + return mcpp::rules::spirv::compile(opt) ? 0 : 1; +} +``` + +Families: `rules-*` compile what the compiler does not (CUDA, SPIR-V, Qt), +`deps-*` bring CMake, vcpkg and archive packages, `dist-*` package the +outputs, `tools-*` embed files and run steps. A library another build system +installed is declared with `mcpp::cps_package`. docs/30-build-mcpp.md states +every directive. + +## Related + +- `mcpp run` and `mcpp test` build first; `mcpp fetch` downloads without building. +- `mcpp why toolchain|deps|flags` states a decision; `mcpp explain ` a refusal. +- `mcpp toolchain list` lists the targets this host serves; `mcpp clean` and `mcpp cache` manage the outputs. +- `mcpp add --build` adds a plugin; `mcpp --agent-skill-doc`, when mcpp itself seems wrong. diff --git a/docs/mcpp-skills/mcpp-cache/SKILL.md b/docs/mcpp-skills/mcpp-cache/SKILL.md index 945510d1a..d910da10c 100644 --- a/docs/mcpp-skills/mcpp-cache/SKILL.md +++ b/docs/mcpp-skills/mcpp-cache/SKILL.md @@ -33,3 +33,8 @@ None of their own; `verify` lists entries whose files are missing (`E0005`). ## Waits An entry a running build uses is waited for; `--lock-wait` bounds it. + +## Related + +- `mcpp clean` removes a project's outputs; `mcpp fetch` fills the home. +- `mcpp self doctor` checks the home. diff --git a/docs/mcpp-skills/mcpp-clean/SKILL.md b/docs/mcpp-skills/mcpp-clean/SKILL.md index ef85653fc..e169293d7 100644 --- a/docs/mcpp-skills/mcpp-clean/SKILL.md +++ b/docs/mcpp-skills/mcpp-clean/SKILL.md @@ -33,3 +33,8 @@ Outside a project there is nothing to clean: the message says so. A configuration another run is building is waited for, bounded by `--lock-wait`. + +## Related + +- `mcpp cache` manages the cache every project shares. +- `mcpp build` writes the outputs again. diff --git a/docs/mcpp-skills/mcpp-emit/SKILL.md b/docs/mcpp-skills/mcpp-emit/SKILL.md index fdb1bb5e8..91f7e8548 100644 --- a/docs/mcpp-skills/mcpp-emit/SKILL.md +++ b/docs/mcpp-skills/mcpp-emit/SKILL.md @@ -33,3 +33,8 @@ Writes standard output or `-o FILE`. `build-database` plans as a build does ## Waits `build-database` as a fetch; `--lock-wait` bounds it. + +## Related + +- `mcpp pack` writes the packages an entry describes; `mcpp xpkg parse` checks it. +- `mcpp publish` sends a source package's entry to mcpp-index. diff --git a/docs/mcpp-skills/mcpp-explain/SKILL.md b/docs/mcpp-skills/mcpp-explain/SKILL.md index 78ad34e1d..94f52a656 100644 --- a/docs/mcpp-skills/mcpp-explain/SKILL.md +++ b/docs/mcpp-skills/mcpp-explain/SKILL.md @@ -30,3 +30,9 @@ An unknown code exits 2 with the closest codes. ## Waits None. + +## Related + +- `mcpp why` states how a decision was reached. +- `mcpp build --message-format json` carries the tokens and codes for a program. +- `mcpp --agent-skill-doc`: what to do when the remedy does not remedy. diff --git a/docs/mcpp-skills/mcpp-fetch/SKILL.md b/docs/mcpp-skills/mcpp-fetch/SKILL.md index b14f2cba4..3fe6906a5 100644 --- a/docs/mcpp-skills/mcpp-fetch/SKILL.md +++ b/docs/mcpp-skills/mcpp-fetch/SKILL.md @@ -37,3 +37,8 @@ such a directory into the home, on a machine without network. ## Waits Installs into the home wait for one another; `--lock-wait` bounds the wait. + +## Related + +- `mcpp build --offline` builds from what it fetched. +- `mcpp cache` and `mcpp clean` manage what it keeps; `mcpp update` moves the lock. diff --git a/docs/mcpp-skills/mcpp-index/SKILL.md b/docs/mcpp-skills/mcpp-index/SKILL.md index 814a6f04e..6a017e75d 100644 --- a/docs/mcpp-skills/mcpp-index/SKILL.md +++ b/docs/mcpp-skills/mcpp-index/SKILL.md @@ -36,3 +36,8 @@ or `{ path = "..." }`. ## Waits A refresh waits for another run's; `--lock-wait` bounds it. + +## Related + +- `mcpp search` and `mcpp info` read the indices; `mcpp update` re-resolves against them. +- `mcpp xpkg parse` checks an entry; `mcpp publish` adds one to mcpp-index. diff --git a/docs/mcpp-skills/mcpp-info/SKILL.md b/docs/mcpp-skills/mcpp-info/SKILL.md new file mode 100644 index 000000000..d2833e5d1 --- /dev/null +++ b/docs/mcpp-skills/mcpp-info/SKILL.md @@ -0,0 +1,57 @@ +--- +name: mcpp-info +description: Use when deciding whether and how to depend on one package - its versions, the systems they serve, its license, repository and features, and what the project already states or locks of it. +--- + +# mcpp info + +Shows one package of the indices in depth, and the line that adds it. + +## Examples + +``` +mcpp info mcpplibs.cmdline +mcpp info compat.gtest@1.15.2 +mcpp info mcpplibs.cmdline --format json +``` + +``` + mcpplibs.cmdline A simple command-line parsing library for modern C++ + versions 0.2.0, 0.1.0, 0.0.7, ... + version 0.2.0 (linux, macosx, windows) + license Apache-2.0 + repository https://github.com/mcpplibs/cmdline + index mcpplibs (an mcpp package: its mcpp.toml states its modules and features) + add mcpp add mcpplibs.cmdline@0.2.0 +``` + +- The name is the full identity, as `mcpp add` takes it; `@` asks + about that version instead of the newest. +- An mcpp package states its modules and features in its own manifest; a + package the index installs for other tools (a compiler, a C library's + payload) has none, and is used through a plugin or a toolchain. +- In a project, the line `this project` gives the table, the version the + manifest states and the one `mcpp.lock` holds. +- `--format json` prints the `mcpp.info` envelope. + +## Reads, writes, network + +Refreshes an index older than its time to live (network); `--offline` reads +what the home holds. Reads the project's `mcpp.toml` and `mcpp.lock` when run +in one; installs nothing. + +## Refusals + +- No index holds the identity: `mcpp search ` lists the names that hold + the word. +- The version is not published: the message lists those that are. + +## Waits + +An index refresh waits for another run's; `--lock-wait` bounds it. + +## Related + +- `mcpp search` finds packages by keyword; this sheet shows one of them. +- `mcpp add` writes the dependency; `mcpp why deps` shows who requires it. +- `mcpp update` moves a locked version; `mcpp index list` names the indices. diff --git a/docs/mcpp-skills/mcpp-new/SKILL.md b/docs/mcpp-skills/mcpp-new/SKILL.md index 483b6b31f..343b95f27 100644 --- a/docs/mcpp-skills/mcpp-new/SKILL.md +++ b/docs/mcpp-skills/mcpp-new/SKILL.md @@ -40,3 +40,9 @@ when the package has one. ## Waits None of its own; a package template waits as a fetch does (`--lock-wait`). + +## Related + +- `mcpp build`, `mcpp run`, `mcpp test`: the daily loop in the new project. +- `mcpp add` adds a library; `mcpp info` shows one before adding it. +- `mcpp new --list-templates` lists the templates the indices offer. diff --git a/docs/mcpp-skills/mcpp-pack/SKILL.md b/docs/mcpp-skills/mcpp-pack/SKILL.md index ea7144b45..ed5329fbe 100644 --- a/docs/mcpp-skills/mcpp-pack/SKILL.md +++ b/docs/mcpp-skills/mcpp-pack/SKILL.md @@ -39,3 +39,9 @@ What `mcpp build` reads and writes, then `target/dist/`. ## Waits As `mcpp build`; `--lock-wait` bounds it. + +## Related + +- `mcpp build` builds what it packs; `mcpp run` runs the program first. +- `mcpp emit xpkg --package` writes an index entry for a package it wrote. +- `mcpp publish` publishes the source package instead. diff --git a/docs/mcpp-skills/mcpp-publish/SKILL.md b/docs/mcpp-skills/mcpp-publish/SKILL.md index e1c727b86..a27f39bb6 100644 --- a/docs/mcpp-skills/mcpp-publish/SKILL.md +++ b/docs/mcpp-skills/mcpp-publish/SKILL.md @@ -32,3 +32,8 @@ uploads (network). A tree with uncommitted changes is refused unless ## Waits None of its own. + +## Related + +- `mcpp pack` and `mcpp emit xpkg --package` publish binaries instead. +- `mcpp xpkg parse` checks the entry; `mcpp index` names the indices. diff --git a/docs/mcpp-skills/mcpp-remove/SKILL.md b/docs/mcpp-skills/mcpp-remove/SKILL.md index 2a7bfe307..fad151fa4 100644 --- a/docs/mcpp-skills/mcpp-remove/SKILL.md +++ b/docs/mcpp-skills/mcpp-remove/SKILL.md @@ -27,3 +27,8 @@ tables were read. ## Waits None. + +## Related + +- `mcpp add` writes a dependency; `mcpp update` moves the lock. +- `mcpp why deps` shows whether another package still requires it. diff --git a/docs/mcpp-skills/mcpp-resolve/SKILL.md b/docs/mcpp-skills/mcpp-resolve/SKILL.md index 6c42cce0c..84437fb0d 100644 --- a/docs/mcpp-skills/mcpp-resolve/SKILL.md +++ b/docs/mcpp-skills/mcpp-resolve/SKILL.md @@ -26,3 +26,8 @@ As `mcpp why`. ## Waits As `mcpp why`; `--lock-wait` bounds it. + +## Related + +- `mcpp update` rewrites the lock; `mcpp fetch` downloads what it names. +- `mcpp why deps` states who requires what. diff --git a/docs/mcpp-skills/mcpp-run/SKILL.md b/docs/mcpp-skills/mcpp-run/SKILL.md index 9d8cfe004..20b5d7036 100644 --- a/docs/mcpp-skills/mcpp-run/SKILL.md +++ b/docs/mcpp-skills/mcpp-run/SKILL.md @@ -41,3 +41,8 @@ status is the program's. As `mcpp build`; `--lock-wait` bounds it. The program itself is not waited on by mcpp's locks. + +## Related + +- `mcpp build` builds what it runs; `mcpp test` runs the tests. +- `mcpp pack` ships the program; `mcpp toolchain list` names the runners of a target. diff --git a/docs/mcpp-skills/mcpp-search/SKILL.md b/docs/mcpp-skills/mcpp-search/SKILL.md index fdaabfd13..8e3f28659 100644 --- a/docs/mcpp-skills/mcpp-search/SKILL.md +++ b/docs/mcpp-skills/mcpp-search/SKILL.md @@ -31,3 +31,8 @@ copy is read. ## Waits An index refresh waits for another run's; `--lock-wait` bounds it. + +## Related + +- `mcpp info` shows one package in depth; `mcpp add` writes it. +- `mcpp index list` names the indices searched. diff --git a/docs/mcpp-skills/mcpp-self/SKILL.md b/docs/mcpp-skills/mcpp-self/SKILL.md index 51707a4a8..19ea5d9eb 100644 --- a/docs/mcpp-skills/mcpp-self/SKILL.md +++ b/docs/mcpp-skills/mcpp-self/SKILL.md @@ -41,3 +41,9 @@ path. `self doctor` reports problems and their remedies; it refuses nothing. `init` waits for another run's install into the home; `--lock-wait` bounds it. + +## Related + +- `mcpp toolchain` manages toolchains; `mcpp cache` the build cache. +- `mcpp version` prints the version; `mcpp explain` describes a code. +- `mcpp --agent-skill-doc`: what to do when mcpp itself seems wrong. diff --git a/docs/mcpp-skills/mcpp-stage/SKILL.md b/docs/mcpp-skills/mcpp-stage/SKILL.md index ca7a23e05..2b603778e 100644 --- a/docs/mcpp-skills/mcpp-stage/SKILL.md +++ b/docs/mcpp-skills/mcpp-stage/SKILL.md @@ -32,3 +32,8 @@ A missing source: the message names it; exit 1. ## Waits None. + +## Related + +- `mcpp write` writes lines into a file from an action. +- `mcpp build` runs the actions that call it. diff --git a/docs/mcpp-skills/mcpp-test/SKILL.md b/docs/mcpp-skills/mcpp-test/SKILL.md index 945fedf47..6d971e76c 100644 --- a/docs/mcpp-skills/mcpp-test/SKILL.md +++ b/docs/mcpp-skills/mcpp-test/SKILL.md @@ -46,3 +46,9 @@ member. Exit 0: every test passed; 1: a test failed; 2: a test could not run. ## Waits As `mcpp build`; `--lock-wait` bounds it. + +## Related + +- `mcpp build` builds the tests' code; `mcpp run` starts one program. +- `mcpp add --dev` adds a test framework (`compat.gtest`, `mcpplibs.mtest`). +- `mcpp why flags` states how a test was compiled. diff --git a/docs/mcpp-skills/mcpp-toolchain/SKILL.md b/docs/mcpp-skills/mcpp-toolchain/SKILL.md index 315d090ee..052d638a5 100644 --- a/docs/mcpp-skills/mcpp-toolchain/SKILL.md +++ b/docs/mcpp-skills/mcpp-toolchain/SKILL.md @@ -38,3 +38,8 @@ machine's system home. An install waits for another run's install into the home; `--lock-wait` bounds it. + +## Related + +- `mcpp build --target ` builds for a row it lists. +- `mcpp why toolchain` states which one a build took; `mcpp self doctor` checks them. diff --git a/docs/mcpp-skills/mcpp-update/SKILL.md b/docs/mcpp-skills/mcpp-update/SKILL.md index ffef96086..13a4d97fa 100644 --- a/docs/mcpp-skills/mcpp-update/SKILL.md +++ b/docs/mcpp-skills/mcpp-update/SKILL.md @@ -30,3 +30,8 @@ changing the lock. ## Waits An index refresh waits for another run's; `--lock-wait` bounds it. + +## Related + +- `mcpp add` changes a stated version; `mcpp resolve` resolves without building. +- `mcpp index update` refreshes the indices; `mcpp info` shows what is published. diff --git a/docs/mcpp-skills/mcpp-version/SKILL.md b/docs/mcpp-skills/mcpp-version/SKILL.md index e4292ad3d..62e07926f 100644 --- a/docs/mcpp-skills/mcpp-version/SKILL.md +++ b/docs/mcpp-skills/mcpp-version/SKILL.md @@ -29,3 +29,8 @@ None. ## Waits None. + +## Related + +- `mcpp self doctor` checks the home; `mcpp self env` shows it. +- `mcpp toolchain list` shows the toolchains, which have versions of their own. diff --git a/docs/mcpp-skills/mcpp-why/SKILL.md b/docs/mcpp-skills/mcpp-why/SKILL.md index 540c84f0c..b2b698e97 100644 --- a/docs/mcpp-skills/mcpp-why/SKILL.md +++ b/docs/mcpp-skills/mcpp-why/SKILL.md @@ -37,3 +37,9 @@ reason tokens; `mcpp explain ` describes each. ## Waits As a fetch: installs into the home; `--lock-wait` bounds it. + +## Related + +- `mcpp explain ` describes a refusal; `mcpp build -v` shows each step. +- `mcpp toolchain` changes the toolchain; `mcpp self env` shows the home. +- `mcpp --agent-skill-doc`: what to do when a decision contradicts the documentation. diff --git a/docs/mcpp-skills/mcpp-write/SKILL.md b/docs/mcpp-skills/mcpp-write/SKILL.md index 7caf5fc1d..83d4b583f 100644 --- a/docs/mcpp-skills/mcpp-write/SKILL.md +++ b/docs/mcpp-skills/mcpp-write/SKILL.md @@ -29,3 +29,8 @@ A file to append that cannot be read: the message names it; exit 1. ## Waits None. + +## Related + +- `mcpp stage` copies a file from an action. +- `mcpp build` runs the actions that call it. diff --git a/docs/mcpp-skills/mcpp-xpkg/SKILL.md b/docs/mcpp-skills/mcpp-xpkg/SKILL.md index c3e0a5d95..9f21de710 100644 --- a/docs/mcpp-skills/mcpp-xpkg/SKILL.md +++ b/docs/mcpp-skills/mcpp-xpkg/SKILL.md @@ -31,3 +31,8 @@ and the line. Exit 1 with the document when `--format json` is asked for. ## Waits None. + +## Related + +- `mcpp emit xpkg` writes an entry; `mcpp publish` sends one to mcpp-index. +- `mcpp index` manages the indices an entry lives in. diff --git a/docs/mcpp-skills/mcpp/SKILL.md b/docs/mcpp-skills/mcpp/SKILL.md index ca49de364..4c7310422 100644 --- a/docs/mcpp-skills/mcpp/SKILL.md +++ b/docs/mcpp-skills/mcpp/SKILL.md @@ -1,97 +1,100 @@ --- name: mcpp -description: Use mcpp, the build tool and package manager for C++23 modules - create, build, run and test a project, add dependencies, and read what mcpp reports. +description: Use mcpp, the build tool and package manager for C++23 modules - its architecture and concepts, which command a task needs, the project conventions, and what to do when mcpp itself is wrong - analyse it, work around it, report it, fix it. --- # mcpp -mcpp builds C++23 module projects that `mcpp.toml` describes. It installs the -toolchain, the standard library module and the dependencies a project needs -into its home (`~/.mcpp`, or `MCPP_HOME`); a compiler of the host is used only -when the project states it. Every command answers `--agent-skill-doc` with its -own sheet; `mcpp --help` lists its options. +mcpp builds C++23 module projects that `mcpp.toml` describes, and is built by +itself. Every command answers `--agent-skill-doc` with its own sheet, which +ends with the related commands: start here, then follow the links. -## The daily loop +## Architecture -``` -mcpp new hello -cd hello -mcpp build -mcpp run -- --name world -mcpp test -mcpp add mcpplibs.cmdline@0.2.0 -``` +- The engine plans a build from data: the manifest, the target's rows and + providers, the packages of the indices. A default is data, and every + default has an override (command line, `mcpp.toml`, `config.toml`). +- The home (`~/.mcpp`, or `MCPP_HOME`) holds the toolchains, the std module, + the packages and the cache. A compiler of the host is used only when the + project states it (`mcpp why toolchain` says which one was used). +- Two indices feed it: mcpp-index (C++ libraries: `mcpplibs.*` module + libraries, `compat.*` C libraries) and xim-pkgindex (toolchains, tools). +- A dependency is a package of mcpp's graph, resolved before planning and + locked in `mcpp.lock`. A build program (`build.mcpp`) runs before the build + and states flags, generated sources and actions; plugins are libraries it + imports (`mcpp.plugins`: `rules-*`, `deps-*`, `dist-*`, `tools-*`). -`mcpp new` writes `mcpp.toml`, `src/main.cpp`, `tests/test_smoke.cpp` and a -git repository. A command that reads a project runs in the one whose -`mcpp.toml` is in the current directory or the nearest parent; `new`, -`search`, `self`, `toolchain`, `cache`, `index` and `explain` need none. +## Tasks -## The manifest - -```toml -[package] -name = "hello" -version = "0.1.0" - -[dependencies] -mcpplibs.cmdline = "0.2.0" - -[dev-dependencies] -gtest = "1.15.2" -``` - -`src/main.cpp` is a program, `src/**/*.cppm` are modules, `tests/**/*.cpp` -are tests; `[targets.]` states a target the layout does not imply. -A key mcpp does not know is reported, never ignored. Chapter 04 of the -documentation lists every key. - -## Reading a message - -- `error:` stopped the command; `warning:` and `note:` did not. -- A `help:` line is the next step; an `impact:` line what a reduced run lost. -- A refusal ends with its reason token in brackets: `[layer-cycle]`. - `mcpp explain layer-cycle` describes it and the remedy, as it does for the - `E0001` codes and the `MCPP_*` codes of JSON diagnostics. -- `mcpp why ` states how a decision was reached: `mcpp why toolchain`, - `mcpp why deps`, `mcpp why flags`. -- A usage error names the closest declared names and the `--help` to read. - -## Output for programs - -- `--message-format json` on `build`, `test`, `run --print-launch` and `pack`, - and `--format json` on the queries (`self env`, `why`, `search`, `cache list`, - `toolchain list`, `index list`), print JSON on standard output; standard - error carries the narration. A document has `schemaVersion` and `kind`. -- A usage error asked for JSON is a `mcpp.usage` envelope: its diagnostic has - a `MCPP_USAGE_*` code and the closest names in `suggestions`. -- `MCPP_CLIENT=` names the caller in what mcpp records. -- `--offline` never touches the network; `--deny network,write-project` stops - before the named effects and exits 5. - -## Exit status - -| status | meaning | +| task | commands | |---|---| -| 0 | success | -| 1 | the command ran and failed: a compile, a test, a refusal | -| 2 | a usage error, or a request refused before anything ran | -| 5 | stopped before an effect the caller denied | -| 70 | an internal error | -| 127 | an unknown command | +| start a program, a library or a workspace | `new`, `build`, `run`, `test` | +| find and use a library | `search`, `info`, `add`, `remove`, `update` | +| understand a result or a refusal | `why`, `explain`, `self env` | +| another machine, another compiler | `toolchain`, `build --target` | +| ship a program or a library | `pack`, `emit`, `publish`, `xpkg` | +| offline, CI, disk | `fetch`, `cache`, `clean`, `self doctor` | + +Explore by asking mcpp: `mcpp --help`, `mcpp --agent-skill-doc`, +`mcpp why `, `mcpp self env --format json`. + +## Conventions + +- A module is one `.cppm`: the exported interface, then `module :private;` + with what is not exported and the implementation. mcpp builds the private + fragment as a unit of its own, so an edit there recompiles no importer. +- Dependencies are full identities as dotted keys in name order, as + `mcpp add` writes them: `mcpplibs.cmdline = "0.2.0"` under `[dependencies]`. +- A library is chosen in this order: a module library of mcpp-index (the + `mcpplibs` namespace is maintained by its community), a `compat.*` C + library, a CMake or vcpkg package through the `deps-cmake` or `deps-vcpkg` + plugin. A module that exists is depended on, not written again. +- A key mcpp does not know is reported, never ignored; fix it, do not mute it. -## Waiting +## Reading a message -Two runs that need one lock take turns. The one that waits says what it -waits for and which run holds it; it waits as long as the holder holds unless -`--lock-wait 2m` (or `MCPP_LOCK_WAIT`, `[build] lock_wait`) bounds it, and -then refuses with `[lock-wait-exceeded]`. A file system that cannot lock is -refused at once with `[lock-unavailable]`. +- `error:` stopped the command; `warning:` and `note:` did not; `help:` is the + next step; `impact:` is what a reduced run lost. +- A refusal ends with its reason token (`[layer-cycle]`); `mcpp explain + layer-cycle` gives the cause and the remedy, as for `E0001` and `MCPP_*`. +- `--message-format json` (build, test, pack) and `--format json` (queries) + print JSON on standard output. Exit 0 success, 1 failed, 2 a usage error, + 5 stopped by `--deny`, 70 an internal error. + +## When mcpp itself seems wrong + +A defect of mcpp is an exit 70 or a crash, a remedy that does not remedy, a +result the documentation states otherwise, or two runs of the same inputs +that differ. An error of the compiler in the project's own code is not one. + +1. Analyse: `mcpp explain `; `mcpp why toolchain|deps|flags`; + `mcpp build -v` for each step; `target/.last-result.json`, the record of + the last build; `mcpp self doctor` for the home. +2. Reduce it to the smallest project that shows it (`mcpp new repro`). +3. Unblock the work: `mcpp clean`, `--cache off`, `-j 1`, another + `--toolchain`, or the switch the `help:` line names. A workaround kept in + the project carries a comment naming the defect. +4. Propose a report: mcpp welcomes them. Ask the user before opening it, + unless they have already said to; when the cause is located, ask in the + same question whether to open a pull request with the fix as well. +5. Print the address of what was opened, for the user to review. + +An issue (`gh issue create -R mcpp-community/mcpp --label bug`) carries one +label - `bug`, `upstream-bug` (the cause is a compiler or a tool), +`documentation`, `enhancement` - and the command, its full output, +`mcpp --version`, `mcpp self env` and the smallest project. + +## Contributing to mcpp + +mcpp is built by itself: `mcpp build` in a checkout, `mcpp test` for its +tests (docs/90-build-from-source.md). A fix is one pull request from a branch +that closes its issue and carries a test of the behaviour, the spec clause, +the documentation in English and Chinese and a CHANGELOG entry; `AGENTS.md` +at the root states the rules, `.agents/skills/` the procedures. ## Where to read on -- `mcpp --agent-skill-doc`: the sheet of one command (index below). -- `mcpp self doctor`: the health of the home and the toolchains. -- https://github.com/mcpp-community/mcpp/tree/main/docs: the documentation. -- https://github.com/mcpp-community/mcpp/issues: report a defect with the - command, its output and `mcpp --version`. +- https://github.com/mcpp-community/mcpp/tree/main/docs (the documentation) +- https://github.com/mcpp-community/mcpp-index (the C++ library index) +- https://github.com/mcpp-community/mcpp-plugins (the official plugins) +- https://github.com/openxlings/xim-pkgindex (toolchains and tools) diff --git a/docs/specs/README.md b/docs/specs/README.md index 5112af928..f33390ccb 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -30,10 +30,10 @@ | 编号 | 标题 | 状态 | 最后修改 | 对应实现 | |---|---|---|---|---| -| [SPEC-001](package-identity.md) | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | 评审中 v1.14 | 2026-12-04 | mcpp >= 0.0.106;§3.5 与 §10.4 mcpp >= 2026.11.19.1;§4.5、§3.5 的 `installed_manifest` 与 §10.4 第 7 条 mcpp >= 2026.11.21.1;§10.5 mcpp >= 2026.12.4.1 | +| [SPEC-001](package-identity.md) | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | 评审中 v1.15 | 2026-12-05 | mcpp >= 0.0.106;§3.5 与 §10.4 mcpp >= 2026.11.19.1;§4.5、§3.5 的 `installed_manifest` 与 §10.4 第 7 条 mcpp >= 2026.11.21.1;§10.5 mcpp >= 2026.12.4.1 | | [SPEC-002](target-side.md) | 目标侧模型与能力声明(`mcpp:` 保留命名空间、五层、三条规则、目标侧执行、一个进程一套 C++ 运行时) | 评审中 v1.13 | 2026-11-27 | mcpp >= 2026.8.24.2;§2.4 与 §6 mcpp >= 2026.10.24.1;§2.2 的对象形式与 §7 mcpp >= 2026.10.26.1;§2.5 与 §3.8 mcpp >= 2026.11.10.1;§3.6 以目标的解析判断 mcpp >= 2026.11.19.1;§3.9 与 §3.10 mcpp >= 2026.11.23.1;§3.11 mcpp >= 2026.11.27.1 | | [SPEC-003](exit-codes.md) | 退出码契约(分类、语义、稳定性承诺) | 评审中 v1.2 | 2026-10-26 | mcpp >= 2026.9.1.1;`5` 与信号 mcpp >= 2026.10.26.1 | -| [SPEC-004](manifest-semantics.md) | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | 草案 v1.30 | 2026-11-27 | 条件化形状 mcpp >= 2026.8.29.1;目标轴 mcpp >= 2026.9.6.4;`linkage` 默认值 mcpp >= 2026.9.15.2;链接 flag 的词读法 mcpp >= 2026.9.26.2;条件化的 `dialect_cxxflags` 与 `-p` 的包身份 mcpp >= 2026.9.28.1;条件表按具体程度生效 mcpp >= 2026.9.28.2;平台前缀规约 mcpp >= 2026.10.5.1;根包的继承、根位置的 profile、链接 flag 的作用域、链接期优化与导出发现 mcpp >= 2026.10.5.2;架构段的 `x86` 即 `i686` mcpp >= 2026.10.5.3;前缀即语义与工作空间层 mcpp >= 2026.10.10.1;依赖的库与配置(§12) mcpp >= 2026.10.11.1;值的四档层次与 `run_under` mcpp >= 2026.10.24.1;§12 第 3 条一个程序一个版本 mcpp >= 2026.11.19.1;§9 第 21 至 23 条与 §16 mcpp >= 2026.11.21.1;v1.29 条款 mcpp >= 2026.11.23.1;§9 第 24 条、§11 第 7 与 8 条、§17 mcpp >= 2026.11.27.1 | +| [SPEC-004](manifest-semantics.md) | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | 草案 v1.31 | 2026-12-05 | 条件化形状 mcpp >= 2026.8.29.1;目标轴 mcpp >= 2026.9.6.4;`linkage` 默认值 mcpp >= 2026.9.15.2;链接 flag 的词读法 mcpp >= 2026.9.26.2;条件化的 `dialect_cxxflags` 与 `-p` 的包身份 mcpp >= 2026.9.28.1;条件表按具体程度生效 mcpp >= 2026.9.28.2;平台前缀规约 mcpp >= 2026.10.5.1;根包的继承、根位置的 profile、链接 flag 的作用域、链接期优化与导出发现 mcpp >= 2026.10.5.2;架构段的 `x86` 即 `i686` mcpp >= 2026.10.5.3;前缀即语义与工作空间层 mcpp >= 2026.10.10.1;依赖的库与配置(§12) mcpp >= 2026.10.11.1;值的四档层次与 `run_under` mcpp >= 2026.10.24.1;§12 第 3 条一个程序一个版本 mcpp >= 2026.11.19.1;§9 第 21 至 23 条与 §16 mcpp >= 2026.11.21.1;v1.29 条款 mcpp >= 2026.11.23.1;§9 第 24 条、§11 第 7 与 8 条、§17 mcpp >= 2026.11.27.1;v1.31 mcpp >= 2026.12.4.1 | | [SPEC-005](build-database.md) | 构建数据库:`mcpp emit build-database` 的内容、取值规则与不写工程目录的保证 | 评审中 v1.10 | 2026-11-23 | mcpp >= 2026.9.15.1;v1.3 条款 mcpp >= 2026.9.26.2;v1.4 条款 mcpp >= 2026.9.27.1;v1.5 条款 mcpp >= 2026.9.28.1;v1.6 条款 mcpp >= 2026.9.29.5;v1.7 条款 mcpp >= 2026.9.30.2;v1.8 条款 mcpp >= 2026.10.11.1;v1.10 条款 mcpp >= 2026.11.23.1 | | [SPEC-006](toolchain-management.md) | 工具链管理:身份、来源、选择与载荷契约 | 草案 v0.14 | 2026-11-23 | 逐条标注;已实现条款 mcpp >= 2026.9.24.1;§3.7 mcpp >= 2026.9.28.1;§3.7.1 mcpp >= 2026.9.28.2;§2.2.1 与 §3.3 的非缺省来源 mcpp >= 2026.10.1.3;§3.8 mcpp >= 2026.10.8.1;§3.9 至 §3.11 mcpp >= 2026.10.24.1;v0.11 条款 mcpp >= 2026.11.10.1;v0.14 条款 mcpp >= 2026.11.23.1 | | [SPEC-007](build-plugins.md) | 构建插件:配置、施工与校验的分工,运行时与规划期的义务 | 草案 v0.17 | 2026-12-05 | 逐条标注;mcpp >= 2026.9.26.2;v0.3 条款 mcpp >= 2026.9.27.1;v0.4 条款 mcpp >= 2026.9.28.1;v0.5 条款 mcpp >= 2026.9.28.2;v0.6(§9)mcpp >= 2026.9.28.3;R3.9、R3.10 mcpp >= 2026.10.10.1;§10 mcpp >= 2026.10.11.1;§3.1 协议 18 mcpp >= 2026.11.5.1;协议 19 mcpp >= 2026.11.16.1;协议 20、R10.7 mcpp >= 2026.11.19.1;协议 21、R10.8–R10.10 mcpp >= 2026.11.21.1;v0.17 mcpp >= 2026.12.4.1 | diff --git a/docs/specs/manifest-semantics.md b/docs/specs/manifest-semantics.md index 5497d12e6..735cbe8e3 100644 --- a/docs/specs/manifest-semantics.md +++ b/docs/specs/manifest-semantics.md @@ -5,8 +5,8 @@ | **规范编号** | SPEC-004 | | **标题** | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | | **状态** | **草案(Draft)** | -| **版本** | 1.30 | -| **最后修改** | 2026-11-27 | +| **版本** | 1.31 | +| **最后修改** | 2026-12-05 | | **最低实现版本** | 条件化形状:mcpp **2026.8.29.1**(`[target..build-dependencies]` 起齐备);目标轴:mcpp **2026.9.6.4** | | **作者/维护** | mcpp-community | | **相关设计文档** | `.agents/docs/2026-09-07-mcpp-toml-unified-semantics-design.md`
`.agents/docs/2026-06-04-manifest-schema-ownership.md`
`.agents/docs/2026-09-03-xlings-workspace-as-the-one-table.md`
`.agents/docs/2026-09-25-issue-690-workspace-build-inheritance-consistency.md`
`.agents/docs/2026-09-27-eight-reports-by-home-and-one-optimisation-plan.md`
`.agents/docs/2026-10-05-std-module-pair-msvc-lto-and-export-discovery-design.md`
`.agents/docs/2026-10-06-windows-x86-arch-vocabulary-and-rc-follow-ups-design.md`
`.agents/docs/2026-10-10-one-source-one-meaning-design.md`
`.agents/docs/2026-10-11-build-dependencies-one-pipeline-design.md`
`.agents/docs/2026-10-23-target-base-and-execution-host-design.md`
`.agents/docs/2026-10-26-control-contract-runtime-and-ide-ecosystem-design.md`(§24) | @@ -842,7 +842,7 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m 公开 include 目录、接口宏定义与链接 flag **禁止**进入目标的编译与链接。 5. **产物。** `[build-dependencies]` 的条目在没有列出 `tools` 或 `artifacts` 时请求包的库; `host-module = true` 在它们之外再请求库,`host-module = false` 不要库;请求声明了 `rule_module` - 的特性即请求库。`host-module` 的名字来自它只表示接口根模块的时期,按 §5.2 不改名;它的含义 + 的特性即请求库。两者都未列出的条目**应当**省略 `host-module`,写出 `true` 只是重述默认值。`host-module` 的名字来自它只表示接口根模块的时期,按 §5.2 不改名;它的含义 是"构建程序使用这个依赖的库":公开模块可导入、公开头文件可见、对象参与链接。在 `[dependencies]` 中,库就是这条边的含义。 6. **构建程序图。** 一次构建中宿主工具链与 C++ 标准相同、且在共有的包上版本相同的构建程序,是同一张 @@ -956,8 +956,10 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m `[feature-deps.<特性>]`,以及每种在 `[target.<选择器>]` 下的条件形式。加载、`mcpp add` 与 `mcpp remove` 的编辑、 `mcpp publish` 的归一化读同一份枚举(`mcpp.manifest.dependency_tables`),三者**禁止**各自列出表。 2. `mcpp add` 写入 `[dependencies]`;`--dev` 写入 `[dev-dependencies]`,`--build` 写入 `[build-dependencies]`。 - `mcpp remove` 以同样的旗标选择表,缺省为 `[dependencies]`。非缺省命名空间的条目:表中已有 `[<表>.<命名空间>]` - 表头时写为该节中的短键;否则写为 `[<表>]` 中的点号键 `<命名空间>.<名>`。缺省命名空间写裸键。 + `mcpp remove` 以同样的旗标选择表,缺省为 `[dependencies]`。条目:表中已有 `[<表>.<命名空间>]` 表头时写为该节中的 + 短键;否则写为 `[<表>]` 中的点号键 `<命名空间>.<名>`,缺省命名空间亦然,同一个包的裸键被它取代(2026.12.4.1 起; + 此前缺省命名空间写裸键)。条目**必须**按键的名字次序放在该节已有的键之间;会使另一个键的路径成为表的键写为带 + 引号的键。 3. 一个由点号键定义的表又被表头重新打开(或反之)是 TOML 1.0 的错误。mcpp 合并两者读取,并以弃用项 `reopened-dotted-table` 报告(docs/51);编辑该表时,表头下的条目改写为点号键,表头移除。编辑**禁止**写出这种 重复定义。 @@ -967,7 +969,7 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m 插件按 §12 的兼容读法(`host-module-in-dependencies`)读作构建依赖,报告给出 `mcpp remove` 与 `mcpp add --build` 两条命令。 -**状态:已实现**(mcpp 2026.11.27.1,mcpp#962、#964、#993)。 +**状态:已实现**(mcpp 2026.11.27.1,mcpp#962、#964、#993;第 2 条的完整身份与名字次序 mcpp 2026.12.4.1)。 ## 变更记录 @@ -1004,3 +1006,4 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m | 1.28 | 2026-11-22 | mcpp 2026.11.22.1(设计 2026-11-22 §6.2):§9 第 12 条,生效的 `[indices]` 中一个位置只有一个名字,两项指向同一位置时拒绝(`index-location-named-twice`)。 | | 1.30 | 2026-11-27 | mcpp 2026.11.27.1(设计 2026-11-27):§9 第 24 条 profile 的 `cflags`、`cxxflags` 的作用域与 `[profile.] dialect_cxxflags`,未知的 profile 键被报告(mcpp#1025);§11 第 7 条精确的导出名(mcpp#982)与第 8 条依赖包的共享库以限定名命名(mcpp#975);新增 §17 依赖表的单一枚举、`mcpp add --build` 与写法、重新打开的点号键表、发布对成员的改写(mcpp#962、#964、#993)。 | | 1.29 | 2026-11-23 | mcpp 2026.11.23.1(设计 2026-11-22 内核接口与派生状态 §3.1、§3.2):`layers.<层>` 的四种值,载荷与目录两种预制形式;平台键在没有平台的行上生效。 | +| 1.31 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27):§17 第 2 条 `mcpp add` 写完整身份的点号键(缺省命名空间亦然),按名字次序放置,路径冲突时写带引号的键;§12 第 5 条:既未列出 `tools` 也未列出 `artifacts` 的构建依赖条目省略 `host-module`。 | diff --git a/docs/specs/package-identity.md b/docs/specs/package-identity.md index 972c94780..8bf2f11fb 100644 --- a/docs/specs/package-identity.md +++ b/docs/specs/package-identity.md @@ -5,8 +5,8 @@ | **规范编号** | SPEC-001 | | **标题** | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | | **状态** | **评审中(Review)** —— 已实现 | -| **版本** | 1.14 | -| **最后修改** | 2026-12-04 | +| **版本** | 1.15 | +| **最后修改** | 2026-12-05 | | **最低实现版本** | 描述符身份:mcpp **0.0.106**;精确 selector:mcpp **2026.8.10.1**(xlings >= 0.4.69) | | **作者/维护** | mcpp-community | | **相关设计文档** | `.agents/docs/2026-06-20-package-resolution-architecture.md` §4
`.agents/docs/2026-06-26-identity-first-resolution-no-filename.md`
`.agents/docs/2026-07-25-issue278-descriptor-name-form-canonicalization-design.md`
`.agents/docs/2026-07-25-name-namespace-bidirectional-verification-report.md`
`.agents/docs/2026-07-25-name-namespace-canonical-implementation-spec.md` | @@ -183,13 +183,16 @@ e2e `163_identity_first_resolution.sh` 锁住:身份为 `(acme, widget)` 的描 |---|---|---|---| | 1 | `[dependencies]`
`cmdline = "0.0.2"` | `(mcpplibs, cmdline)` | **裸名**。省略 namespace 只表示默认 `mcpplibs` | | 2 | `[dependencies]`
`acme.widget = "1.0"` | `(acme, widget)` | **点式选择器**。最后一段是 name,之前所有段是 namespace | -| 3 | `[dependencies.acme]`
`widget = "1.0"` | `(acme, widget)` | **命名空间子表**。与 #2 完全等价,多个同 namespace 包时更清晰 | +| 3 | `[dependencies.acme]`
`widget = "1.0"` | `(acme, widget)` | **命名空间子表**。与 #2 完全等价 | | 4 | `[dependencies]`
`"acme.widget" = "1.0"` | `(acme, widget)` | **引号点式键**(legacy source shape)。身份仍与 #2/#3 相同 | **已实现**(`parse_package_selector` / `normalize_package_selector` / `make_direct_dependency_selector`)。 **#2 与 #3 只有 TOML 版式差异,没有解析差异。** 新增索引或同短名 sibling 不能改变其身份。 +推荐的写法是 #2,按名字的次序排列;`mcpp add` 即如此写出,清单已有 #3 的表头时写入该表(SPEC-004 §17, +mcpp 2026.12.4.1)。 + 多级命名空间同理,`ns` 逐层累积:`[dependencies.mcpplibs.capi]` + `lua = "0.0.3"` → 单候选 `(mcpplibs.capi, lua)`。 ### 4.2 裸名就是默认 mcpplibs @@ -249,12 +252,9 @@ error: dependency 'asio': no package found tried: (mcpplibs, asio) a package with this name exists under another namespace: chriskohlhoff.asio - namespace omission means `mcpplibs`; write the exact package: + namespace omission means `mcpplibs`. write the exact package: [dependencies] - "chriskohlhoff.asio" = "1.38.1" - or: - [dependencies.chriskohlhoff] - asio = "1.38.1" + chriskohlhoff.asio = "1.38.1" ``` 该 `did-you-mean` 扫描**仅**在已失败路径触发,结果**只进错误文案**,禁止回灌解析、lockfile 或安装层。 @@ -356,8 +356,9 @@ warning,规范列举命令是 `mcpp new --list-templates pkg`。 告警只针对写出了命名空间的键。裸键(不在 `[dependencies.]` 表内、不带点)对这类来源只表示短名 (§4.2),采用清单声明的命名空间**不得**告警。写出命名空间而与清单矛盾的键,实现**必须**告警, 且**按声明它的清单与清单声明的命名空间分组**,每组一条:以相对项目根的路径点名声明清单,列出各个键, -提示以 TOML 写法给出(例如 `write them in a [dependencies.xlings] table, for example -cancellation = { path = "modules/cancellation" }`)。告警在解析完成之后发出。 +提示以 TOML 写法给出,键为完整身份(例如 `write them in namespace xlings, for example +xlings.cancellation = { path = "modules/cancellation" }`;2026.12.4.1 起,此前为 `[dependencies.xlings]` 表的 +短键)。告警在解析完成之后发出。 采用而非拒绝:来源已由声明行固定,§4.2 反对候选搜索的理由(索引状态改变依赖的指向) 在这里不成立。 @@ -643,6 +644,7 @@ mcpp 不运行描述符,读的是 `xpm` 表的一个声明式子集;安装器(xl | 版本 | 日期 | 变更 | |---|---|---| +| 1.15 | 2026-12-05 | §4.1 推荐写法为 #2,按名字的次序;§4.3 的诊断与 §5.4 采用声明身份的告警:提示的示例键为完整身份(`. = ...`),与 `mcpp add` 写出的形式相同(mcpp 2026.12.4.1) | | 1.14 | 2026-12-04 | 新增 §10.5:版本表的读法——经局部表引用的版本按所引用的表读取,未读的写法修订未知并被 `mcpp xpkg parse` 拒绝;平台引用 `ref`/`inherits` 与安装器同样解析;读到的修订与安装器记录不一致时报告一次(mcpp 2026.12.4.1) | | 1.13 | 2026-11-21 | §3.5 新增已安装版本的清单经 `installed_manifest` 读取,构建与包特性的查询共用(mcpp#992);§10.4 新增第 7 条:条目只按它编译时所读的接口提供(mcpp 2026.11.21.1) | | 1.12 | 2026-11-21 | 新增 §4.5:命令行中 `@` 的读法——写出的前缀、`@=` 的精确键、带运算符的要求;§4.4 的模板表与 §5.5 的命令行引用按它陈述(mcpp 2026.11.21.1) | diff --git a/docs/zh/03-examples.md b/docs/zh/03-examples.md index d3cb5bc72..91a6977e7 100644 --- a/docs/zh/03-examples.md +++ b/docs/zh/03-examples.md @@ -76,7 +76,7 @@ mcpp build && mcpp run | 示例 | 首次引入的内容 | |---|---| -| [`08-build-rules`](../../examples/08-build-rules/) | 两个规则包与同时使用它们的工程;`host-module = true`、`role = "check"` 的 `mcpp::action` | +| [`08-build-rules`](../../examples/08-build-rules/) | 两个规则包与以 `[build-dependencies]` 条目同时使用它们的工程;`role = "check"` 的 `mcpp::action` | | [`12-a-new-device-language`](../../examples/12-a-new-device-language/) | `device_extensions` 与 `rule_module`:规则包教会 mcpp 一门引擎从未听说过的语言,而它的编译器是一个经 `tools = [...]` 为构建机构建出来的包 | | [`13-platform-targets`](../../examples/13-platform-targets/) | 一份源码、零个 `cfg`,只改 `--target` 就为 Linux、WebAssembly 和两个 Android ABI 构建;`min_api_level` 作为工程自己的决定,以及一条不能被覆盖的能力钉 | diff --git a/docs/zh/05-dependencies.md b/docs/zh/05-dependencies.md index 8bd53a5f5..4ca83c50a 100644 --- a/docs/zh/05-dependencies.md +++ b/docs/zh/05-dependencies.md @@ -240,14 +240,14 @@ manifest 与被声明的命名空间分组,每组告警一次;告警以相 ```toml # mcpp.toml; libs/fw and libs/comp declare namespace = "huxdemo" -[dependencies.acme] -fw = { path = "libs/fw" } -comp = { path = "libs/comp" } +[dependencies] +acme.comp = { path = "libs/comp" } +acme.fw = { path = "libs/fw" } ``` ``` -warning: mcpp.toml names 2 dependencies in namespace acme, and the manifests they reach declare huxdemo; the declared identity is used: acme.fw, acme.comp - help: write them in a [dependencies.huxdemo] table, for example `fw = { path = "libs/fw" }` +warning: mcpp.toml names 2 dependencies in namespace acme, and the manifests they reach declare huxdemo; the declared identity is used: acme.comp, acme.fw + help: write them in namespace huxdemo, for example `huxdemo.comp = { path = "libs/comp" }` ``` 因此,同一目录上分别写作 `fw` 与 `huxdemo.fw` 的两条边是同一个包,只编译 @@ -296,7 +296,7 @@ spike.fw-installer = { git = "https://example.org/fw.git", rev = "cc3c74c5", too [dependencies] chriskohlhoff.asio = "1.38.1" -# Correct — namespace sub-table (preferred for several packages from one org) +# Correct — namespace sub-table (an equivalent spelling) [dependencies.chriskohlhoff] asio = "1.38.1" @@ -308,8 +308,11 @@ asio = "1.38.1" 第三种写法会明确报错,指出实际尝试过的 `(mcpplibs, asio)` 身份;该短名若存在 于别处,错误信息会给出一个可直接复制的显式选择器。 -**`mcpp add` 写出的形式(2026.11.27.1+)。** 它按表中该命名空间已有的形式写入:已有 `[dependencies.]` 表头时, -写为该节中的短键;否则写为 `[dependencies]` 中的点号键 `.<名>`;缺省命名空间的包写裸键。`--dev` 写入 +**`mcpp add` 写出的形式(2026.12.4.1+)。** 包的完整身份写为 `[dependencies]` 中的点号键 `.<名>`,按名字的次序 +放在已有的键之间;缺省命名空间的包同样如此(`mcpplibs.cmdline = "0.2.0"`),同一个包的裸键被它取代。清单以 +`[dependencies.]` 表头书写的表保持该形式:条目为该节中的短键,按名字的次序。会使另一个键的路径成为表的键 +(`mcpplibs.mtest` 与 `mcpplibs.mtest.gtest` 并存)写为带引号的键。2026.12.4.1 之前,缺省命名空间的包写裸键, +条目写在表的最前。`--dev` 写入 `[dev-dependencies]`,`--build` 写入 `[build-dependencies]`;`mcpp remove` 接受同样的旗标,不带时从 `[dependencies]` 移除。点号键已经定义了一个表之后又用表头重新打开它——`[dependencies]` 下有 `compat.libpng`, 其后又写 `[dependencies.compat]`——是同一个表定义了两次,TOML 1.0 与每个严格的读者(toml++、Python 的 @@ -458,8 +461,8 @@ mcpp build --offline # 之后:不使用网络 ## `[dev-dependencies]` —— 测试依赖 ```toml -[dev-dependencies.compat] -gtest = "1.15.2" +[dev-dependencies] +compat.gtest = "1.15.2" ``` `mcpp build` 忽略这些依赖;`mcpp test` 解析并使用它们,且只用于测试单元:包自己的源文件 @@ -501,7 +504,8 @@ protobuf = { version = "35.1", tools = ["protoc"] } # 构建期间运行 继承,因此构建依赖自己的依赖同样服务构建程序。 - **边上的请求**决定需要哪些产物。`[build-dependencies]` 的条目在没有列出 `tools` 或 `artifacts` 时请求包的库;`host-module = true` 在它们之外再请求库, - `host-module = false` 不要库。`tools = [...]` 请求为执行构建的机器构建的程序, + `host-module = false` 不要库。两者都未列出的条目省略该键: + `mcpp.plugins = { version = "0.27.0", features = ["rules-spirv"] }`。`tools = [...]` 请求为执行构建的机器构建的程序, 两个段都可以写。 | 条目 | 效果 | diff --git a/docs/zh/06-features-and-capabilities.md b/docs/zh/06-features-and-capabilities.md index f89dfe450..75cf9c7ba 100644 --- a/docs/zh/06-features-and-capabilities.md +++ b/docs/zh/06-features-and-capabilities.md @@ -175,8 +175,8 @@ device_extensions = [".comp", ".vert", ".frag", ".glsl"] feature 仍然**按名字**请求: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-spirv"] } ``` 早先的一版设计,从工程源码里出现的扩展名推导这个集合。它被撤销了,原因有二: diff --git a/docs/zh/07-workspace.md b/docs/zh/07-workspace.md index 1148bc120..77cc69702 100644 --- a/docs/zh/07-workspace.md +++ b/docs/zh/07-workspace.md @@ -98,10 +98,8 @@ name = "http" version = "0.1.0" [dependencies] +compat.mbedtls.workspace = true myproject.core = { path = "../core" } - -[dependencies.compat] -mbedtls.workspace = true ``` ## 3. 依赖版本的继承 @@ -112,21 +110,19 @@ mbedtls.workspace = true ```toml # 根 mcpp.toml [workspace.dependencies] -cmdline = "0.0.2" +cmdline = "0.0.2" +compat.gtest = "1.15.2" +compat.mbedtls = "3.6.1" mcpplibs.capi.lua = "0.0.3" # 精确 selector:(mcpplibs.capi, lua) - -[workspace.dependencies.compat] -mbedtls = "3.6.1" -gtest = "1.15.2" ``` ```toml # 成员 mcpp.toml -[dependencies.compat] -mbedtls.workspace = true # 继承版本 → "3.6.1" +[dependencies] +compat.mbedtls.workspace = true # 继承版本 → "3.6.1" -[dev-dependencies.compat] -gtest.workspace = true # 继承版本 → "1.15.2" +[dev-dependencies] +compat.gtest.workspace = true # 继承版本 → "1.15.2" ``` `[workspace.dependencies]` 条目请求的特性随其来源一起继承,排在成员自己的特性之前; @@ -151,8 +147,8 @@ hl = { workspace = true, features = ["y"] } # 请求 x 与 y 成员可以覆盖继承来的版本: ```toml -[dependencies.compat] -mbedtls = "4.0.0" # override; does not use the workspace version +[dependencies] +compat.mbedtls = "4.0.0" # override; does not use the workspace version ``` 写了 `.workspace = true` 而没有工作空间解析它的条目,在该包进入构建的每个位置(根包、 diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index 231d105e9..185acd8a2 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -133,6 +133,9 @@ $ mcpp search imgui `--all-versions` 打印全部。一个描述符读不到的包,按两列输出 —— 版本列表是 尽力而为的展示,从不会让 search 失败。 +`mcpp info .[@]` 展开一个包:全部版本与最新版本(或所指版本)发布于哪些系统、许可证与 +仓库、是否为 mcpp 包及其 feature、工程对它写了什么与锁定了什么,以及 `mcpp add` 的一行(2026.12.4.1+)。 + `mcpp add` 在一个名字解析不到时,携带同样的信息。建议里给出该写的命名 空间,以及它背后的版本: diff --git a/docs/zh/22-target-side.md b/docs/zh/22-target-side.md index a5b6130bb..e33da3c19 100644 --- a/docs/zh/22-target-side.md +++ b/docs/zh/22-target-side.md @@ -931,8 +931,8 @@ schema 警告,并且该段不生效。它过去静默地求值为假,而那 ```toml # Concise bare-alias form — pull OpenBLAS and link it only on Windows. -[target.windows.dependencies.compat] -openblas = "0.3.33" +[target.windows.dependencies] +compat.openblas = "0.3.33" [target.windows.build] ldflags = ["-Llib", "-llibopenblas"] diff --git a/docs/zh/23-the-project-environment.md b/docs/zh/23-the-project-environment.md index 395681d78..6f04f0984 100644 --- a/docs/zh/23-the-project-environment.md +++ b/docs/zh/23-the-project-environment.md @@ -440,8 +440,8 @@ archives = ["vendor/archives"] # 相对于 mcpp.toml 它们要写的就是什么都不写: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-cuda"], host-module = true } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-cuda"] } ``` 这一条边就是全部的声明。规则包点名自己的规则需要哪些包、需要它们的哪个版本, diff --git a/docs/zh/30-build-mcpp.md b/docs/zh/30-build-mcpp.md index 7a6945230..4c4df2f47 100644 --- a/docs/zh/30-build-mcpp.md +++ b/docs/zh/30-build-mcpp.md @@ -1400,8 +1400,8 @@ shim,而可用的那份就在项目自己的环境里,根本不在 `PATH` error: build.mcpp imports 'mcpp.rules.spirv', and no build dependency provides it. ... - [build-dependencies.] - = { version = "..." } # or `host-module = true` beside `tools` + [build-dependencies] + . = { version = "..." } # or `host-module = true` beside `tools` declared without its library: mcpp.plugins (in [build-dependencies]) **模块名由规则的源码声明,`mcpp.*` 是保留前缀。** 模块以其接口单元声明的名字导入, @@ -1640,7 +1640,7 @@ int main() { } ``` -条目在没有列出 `tools` 或 `artifacts` 时请求库;`host-module = true` 在它们之外再请求库, +条目在没有列出 `tools` 或 `artifacts` 时请求库,因此不写 `host-module = true`;该键在它们之外再请求库, `host-module = false` 不要库(05 —— 依赖与解析)。依赖以 `reexport = true` 转交的库, 以同样的方式使用。 @@ -1725,8 +1725,8 @@ rules-spirv = { sources = ["rules/spirv.cppm"], rule_module = "mcpp.rules.spirv" ```toml # 消费方 -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-spirv"] } ``` 模块集合即特性集合:特性未启用的单元不编译,导入它时按特性名拒绝。`mcpp:plugins` 是 diff --git a/docs/zh/42-heterogeneous-builds.md b/docs/zh/42-heterogeneous-builds.md index 0998ce63a..62e59c004 100644 --- a/docs/zh/42-heterogeneous-builds.md +++ b/docs/zh/42-heterogeneous-builds.md @@ -309,8 +309,8 @@ mcpp::generated(out->interface_file.c_str()); ## 编译一个岛 -调用设备编译器的那条命令不内置在 mcpp 里,而是由一个**构建规则包**提供——以 -`host-module = true` 消费,emit 出的构建图边把输出汇入链接。机制见 +调用设备编译器的那条命令不内置在 mcpp 里,而是由一个**构建规则包**提供——作为 +`[build-dependencies]` 的条目消费,emit 出的构建图边把输出汇入链接。机制见 [30 —— build.mcpp](30-build-mcpp.md),可用的 CUDA 规则见 `examples/09-heterogeneous/cuda`。 @@ -322,8 +322,8 @@ mcpp::generated(out->interface_file.c_str()); 一个想要 CUDA 岛的工程只写一条边: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.3.0", features = ["rules-cuda"], host-module = true } +[build-dependencies] +mcpp.plugins = { version = "0.3.0", features = ["rules-cuda"] } ``` 别的什么都不写。厂商工具包、它的运行时,以及规则需要的其余东西,都由**规则包** diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 765c8b5ba..4b172a754 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -935,7 +935,8 @@ reason unknown-target ``` 命令与选项取自解析命令行所用的定义(全局选项不带命令);键取自清单的键登记表(整张表以其名字);原因取自拒绝的原因标记表(上文 `mcpp.why.toolchain`)中的 -标记。解析器自己加入的 `--help` 与 `--version` 不是项。 +标记。解析器自己加入的 `--help` 与 `--version` 不是项,帮助所隐藏、由构建图运行的命令(`link-output`、`dyndep`) +也不是(2026.12.4.1 起)。 两个变量各指明一个调用追加的文件;调用的每个进程都追加,因此构建自己的子构建与它经由 mcpp 启动的编译器写入同一文件: @@ -1151,6 +1152,18 @@ mcpp 索引中的包带 `features`(2026.11.21.1+):最新版本(`versions (在缺省集合中,含其 `implies` 闭包)、`implies`(本包的 feature)、`enables` (`<依赖>/`),写了时还有 `description`。 +### `mcpp.info` —— 索引中的一个包(2026.12.4.1+) + +``` +mcpp info .[@] --format json +``` + +`data` 为 `id`(`namespace.name`)、`namespace`、`name`、`description`、`index`、`versions`(最新在前)、 +`version`(所问的版本,未给出时为最新)、`systems`(发布 `version` 的描述符平台)、`licenses`、`repo`、 +`mcppPackage`(mcpp 是否读取它的清单)、`features`(与 `mcpp.search` 相同,针对 `version`;不是 mcpp 包时为 +`null`)、`stated`(工程清单写有该包时为 `table` 与 `version`,否则为 `null`)、`locked`(`mcpp.lock` 持有的版本, +否则为 `null`)与 `add`(对应 `version` 的 `mcpp add` 一行)。不安装任何东西。 + ### `mcpp.index` —— 注册表与工程的索引 ``` diff --git a/examples/09-heterogeneous/README.md b/examples/09-heterogeneous/README.md index 815f781a2..0ebcb2e3d 100644 --- a/examples/09-heterogeneous/README.md +++ b/examples/09-heterogeneous/README.md @@ -103,8 +103,8 @@ selects it and the accelerator it serves, so a project writes one edge and no `[xlings.workspace]` block: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } ``` `multi-backend/` is the one example here that also pins a version, and it does diff --git a/examples/09-heterogeneous/boundary/mcpp.toml b/examples/09-heterogeneous/boundary/mcpp.toml index 06a42a3c4..92225ef8b 100644 --- a/examples/09-heterogeneous/boundary/mcpp.toml +++ b/examples/09-heterogeneous/boundary/mcpp.toml @@ -7,8 +7,8 @@ standard = "c++23" # `tools-island` is not a device rule: it claims no extension and names no rule # module. A [build-dependencies] entry asks for the library all the same. -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["tools-island"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["tools-island"] } [build] sources = ["src/*.cpp", "src/kernels/**/*.c"] diff --git a/examples/09-heterogeneous/cann/app/mcpp.toml b/examples/09-heterogeneous/cann/app/mcpp.toml index 14f0b7e64..d7c852e05 100644 --- a/examples/09-heterogeneous/cann/app/mcpp.toml +++ b/examples/09-heterogeneous/cann/app/mcpp.toml @@ -13,8 +13,8 @@ import_std = true # The rule that compiles the kernel, selected by its feature; `build.mcpp` # imports it as `mcpp.rules.ascendc`. `[build-dependencies]`, because a rule # package's library must never reach the target while its rule is wanted. -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-ascendc"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-ascendc"] } # NO [xlings.workspace]. `mcpp.rules.ascendc` declares `xim:cann-toolkit` # itself, gated on this accelerator and on the feature that selects the rule -- diff --git a/examples/09-heterogeneous/cuda/README.md b/examples/09-heterogeneous/cuda/README.md index dcfa2a67c..6e7406df1 100644 --- a/examples/09-heterogeneous/cuda/README.md +++ b/examples/09-heterogeneous/cuda/README.md @@ -97,8 +97,8 @@ is compiled, with `accel-mismatch` on the machine-readable channel. The rule names it. This project writes one edge and no payload list at all: ```toml -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } ``` `mcpp.rules.cuda` declares nvcc, cudart, cuRAND's headers, CCCL and the driver @@ -254,8 +254,8 @@ the package declares a directory on the artifact's runtime search path and links through the sentinel. It is declared here as an ordinary dependency: ```toml -[dependencies.compat] -cuda-driver = "2026.09.05" +[dependencies] +compat.cuda-driver = "2026.09.05" ``` Without it the program builds and links, then reports diff --git a/examples/09-heterogeneous/cuda/app/mcpp.toml b/examples/09-heterogeneous/cuda/app/mcpp.toml index 3882992aa..2735b4265 100644 --- a/examples/09-heterogeneous/cuda/app/mcpp.toml +++ b/examples/09-heterogeneous/cuda/app/mcpp.toml @@ -22,8 +22,8 @@ default = "llvm@23.1.3" # `tools-island` is the second member this project uses: it writes the # `extern "C"` boundary the island's compiler reads and the module the seam # imports, so neither signature is stated twice. -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } # The driver's userspace library, reached through an index package that owns # the one hop mcpp needs: a directory on the artifact's runtime search path. @@ -31,8 +31,8 @@ plugins = { version = "0.5.2", features = ["rules-cuda", "tools-island"] } # linked CUDA runtime cannot dlopen the driver. It is the one CUDA component # that cannot be an ordinary payload -- the licence forbids redistributing it # and it is in ABI lockstep with the kernel module. -[dependencies.compat] -cuda-driver = "2026.09.05" +[dependencies] +compat.cuda-driver = "2026.09.05" # NO [xlings.workspace]. The toolkit is declared by the rule itself, under # `cfg(accelerator = ...)` and the feature that selects it, so this project diff --git a/examples/09-heterogeneous/hip/README.md b/examples/09-heterogeneous/hip/README.md index bb5f8d53c..939521f41 100644 --- a/examples/09-heterogeneous/hip/README.md +++ b/examples/09-heterogeneous/hip/README.md @@ -59,7 +59,7 @@ Three consequences, all visible in this example's manifest: half, invoked `-x cuda` with `-D__HIP_PLATFORM_NVIDIA__`; * `xim:hip-nvidia` contains no binaries, because on this platform there are none to contain; -* the payloads are CUDA's, and `[dependencies.compat] cuda-driver` is the same +* the payloads are CUDA's, and `compat.cuda-driver` in `[dependencies]` is the same one hop example 09 needs — mcpp's private loader does not consult `/usr/lib`, so the statically linked CUDA runtime could not otherwise `dlopen` the driver. diff --git a/examples/09-heterogeneous/hip/app/mcpp.toml b/examples/09-heterogeneous/hip/app/mcpp.toml index be1938ea8..88a942aaf 100644 --- a/examples/09-heterogeneous/hip/app/mcpp.toml +++ b/examples/09-heterogeneous/hip/app/mcpp.toml @@ -19,16 +19,16 @@ import_std = true [toolchain] default = "llvm@23.1.3" -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-hip"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-hip"] } # The driver's userspace library. HIP reaches the device through the CUDA # runtime here, so this is the same one hop the CUDA consumer needs: mcpp's # private loader does not consult /usr/lib, and without a directory on the # artifact's runtime search path the statically linked CUDA runtime cannot # dlopen the driver. -[dependencies.compat] -cuda-driver = "2026.09.05" +[dependencies] +compat.cuda-driver = "2026.09.05" # NO [xlings.workspace]. `mcpp.rules.hip` declares the payloads it drives: # `hip-nvidia` (headers only -- on this platform that is all HIP is) plus the diff --git a/examples/09-heterogeneous/multi-backend/README.md b/examples/09-heterogeneous/multi-backend/README.md index de09e1e84..c49788220 100644 --- a/examples/09-heterogeneous/multi-backend/README.md +++ b/examples/09-heterogeneous/multi-backend/README.md @@ -92,8 +92,8 @@ saying it after the vocabulary grows. ## Where the rule package is declared ```toml -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-cuda", "rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-cuda", "rules-spirv"] } ``` Two rules, in one build program, which is what an additive-backend package diff --git a/examples/09-heterogeneous/multi-backend/mcpp.toml b/examples/09-heterogeneous/multi-backend/mcpp.toml index 4953a062c..0819382af 100644 --- a/examples/09-heterogeneous/multi-backend/mcpp.toml +++ b/examples/09-heterogeneous/multi-backend/mcpp.toml @@ -39,8 +39,8 @@ default = "llvm@23.1.3" # which is the case docs/05 section 2.6.1 exists for. # The rules are declared unconditionally because `build.mcpp` imports them # unconditionally -- each returns immediately when its own backend is absent. -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-cuda", "rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-cuda", "rules-spirv"] } # ── the payloads, gated on the device they are for ────────────────────────── # @@ -86,8 +86,8 @@ plugins = { version = "0.5.2", features = ["rules-cuda", "rules-spirv"] } # linked CUDA runtime cannot otherwise dlopen the driver. It is the one CUDA # component that cannot be an ordinary payload -- the licence forbids # redistributing it and it is in ABI lockstep with the kernel module. -[target.'cfg(accelerator = "cuda")'.dependencies.compat] -cuda-driver = "2026.09.05" +[target.'cfg(accelerator = "cuda")'.dependencies] +compat.cuda-driver = "2026.09.05" # The shader compiler is NOT here: `mcpp.rules.spirv` declares `xim:glslang` for # itself. What stays is a DEVICE -- a Vulkan driver that is always present @@ -102,9 +102,9 @@ cuda-driver = "2026.09.05" # under mcpp's private loader. Neither is a driver: a driver has to match the # kernel module on the machine it runs on, which is why the software one above # is a payload and the hardware ones are the host's. -[target.'cfg(accelerator = "vulkan")'.dependencies.compat] -vulkan = "1.4.357.0" -vulkan-runtime = "2026.09.11" +[target.'cfg(accelerator = "vulkan")'.dependencies] +compat.vulkan = "1.4.357.0" +compat.vulkan-runtime = "2026.09.11" [build] # The device sources carry the accel they are for. A CONSTRAINED glob gates diff --git a/examples/09-heterogeneous/sycl/app/mcpp.toml b/examples/09-heterogeneous/sycl/app/mcpp.toml index 387203538..37e5b24f1 100644 --- a/examples/09-heterogeneous/sycl/app/mcpp.toml +++ b/examples/09-heterogeneous/sycl/app/mcpp.toml @@ -19,8 +19,8 @@ import_std = true [toolchain] default = "llvm@23.1.3" -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-sycl", "tools-island"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-sycl", "tools-island"] } # The SYCL runtime, on the artifact's runtime search path. mcpp's private # loader does not consult /usr/lib, so `libsycl.so.9` -- which the rule @@ -36,8 +36,8 @@ plugins = { version = "0.5.2", features = ["rules-sycl", "tools-island"] } # missing, the CUDA back end did not load, and the program aborted with no # message (#596). The farm now mirrors what the driver sentinel publishes # rather than naming a file. -[dependencies.compat] -sycl-runtime = "2026.09.11" +[dependencies] +compat.sycl-runtime = "2026.09.11" # NO [xlings.workspace]. `mcpp.rules.sycl` declares all five payloads this lane # needs, each closing one hole the host would otherwise fill: `dpcpp` (the diff --git a/examples/09-heterogeneous/vulkan/app/mcpp.toml b/examples/09-heterogeneous/vulkan/app/mcpp.toml index 913b23767..19e75cd4b 100644 --- a/examples/09-heterogeneous/vulkan/app/mcpp.toml +++ b/examples/09-heterogeneous/vulkan/app/mcpp.toml @@ -12,17 +12,17 @@ import_std = true # The rule that compiles the shaders lives in the official plugin collection, # selected by its feature; `build.mcpp` imports it as `mcpp.rules.spirv`. -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-spirv"] } # The Khronos loader, built by the index rather than taken from the host, and # the adapter that makes the host's own ICDs reachable from a binary running # under mcpp's private loader. Neither one is a driver: a driver has to match # the kernel module on the machine it runs on, which is why the software one # below is a payload and the hardware ones are the host's. -[dependencies.compat] -vulkan = "1.4.357.0" -vulkan-runtime = "2026.09.11" +[dependencies] +compat.vulkan = "1.4.357.0" +compat.vulkan-runtime = "2026.09.11" # ONE payload here, and the shader compiler is not it: `mcpp.rules.spirv` # declares `xim:glslang` for itself. What stays is a DEVICE, and the boundary is diff --git a/examples/10-graphics/README.md b/examples/10-graphics/README.md index 2f5308d06..163061321 100644 --- a/examples/10-graphics/README.md +++ b/examples/10-graphics/README.md @@ -52,8 +52,8 @@ tells the two apart, which is why it is printed. ## What the build system contributes ```toml -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-spirv"] } [build] accel = "vulkan1.2" diff --git a/examples/10-graphics/offscreen/mcpp.toml b/examples/10-graphics/offscreen/mcpp.toml index 40d80f9ce..718337fc8 100644 --- a/examples/10-graphics/offscreen/mcpp.toml +++ b/examples/10-graphics/offscreen/mcpp.toml @@ -12,8 +12,8 @@ import_std = true # One edge. `mcpp.rules.spirv` declares the shader compiler it drives, so this # project names no payload for it. -[build-dependencies.mcpp] -plugins = { version = "0.5.2", features = ["rules-spirv"] } +[build-dependencies] +mcpp.plugins = { version = "0.5.2", features = ["rules-spirv"] } # The Khronos loader. Unconditional, and the reason is a rule of the engine # rather than a preference: A DEPENDENCY CANNOT BE CONDITIONED ON A LAYER. @@ -27,8 +27,8 @@ plugins = { version = "0.5.2", features = ["rules-spirv"] } # `[build]` sources under the same predicate DO apply, which is what makes the # seam work: the CPU leg below is selected by the accelerator, and only the # packages are unconditional. -[dependencies.compat] -vulkan = "1.4.357.2" +[dependencies] +compat.vulkan = "1.4.357.2" # THE ADAPTER IS NOT NAMED HERE, AND THAT IS THE POINT. # diff --git a/modules/manifest/src/toml.cppm b/modules/manifest/src/toml.cppm index 181f9cdea..46cfc7347 100644 --- a/modules/manifest/src/toml.cppm +++ b/modules/manifest/src/toml.cppm @@ -6232,6 +6232,66 @@ key_line_span(std::string_view text, const SectionSpan& section, std::string_vie return std::nullopt; } +// The assignments of a section, each with its key as written (quotes taken off) +// and its span: what an entry is ordered among. +struct KeyLine { + std::string key; + std::size_t start = 0; + std::size_t end = 0; +}; + +std::vector key_lines(std::string_view text, const SectionSpan& section) { + std::vector out; + std::size_t at = section.bodyStart; + while (at < section.sectionEnd) { + const auto newline = std::min(text.find('\n', at), text.size()); + const auto line = trim_line(text.substr(at, std::min(newline, section.sectionEnd) - at)); + const auto eq = line.find('='); + if (line.empty() || line.front() == '#' || eq == std::string_view::npos) { + at = newline + 1; + continue; + } + auto key = trim_line(line.substr(0, eq)); + if (key.size() >= 2 && key.front() == '"' && key.back() == '"') key = key.substr(1, key.size() - 2); + const auto end = std::min(assignment_end(text, at), section.sectionEnd); + out.push_back(KeyLine{std::string(key), at, end}); + at = end + 1; + } + return out; +} + +// An entry placed in name order among the section's keys: before the first key +// that sorts after it, else after the last key, else first in the body. +void insert_ordered(std::string& text, const SectionSpan& section, std::string_view key, + const std::string& entry) { + const auto keys = key_lines(text, section); + for (auto const& k : keys) + if (k.key > key) { + text.insert(k.start, entry + "\n"); + return; + } + if (keys.empty()) { + if (section.bodyStart == section.headerEnd) text.insert(section.bodyStart, "\n" + entry); + else text.insert(section.bodyStart, entry + "\n"); + return; + } + const auto after = keys.back().end; + if (after >= text.size()) text += "\n" + entry; + else text.insert(after + 1, entry + "\n"); +} + +// Whether a dotted key and one of the section's keys name a value and a table +// at one path (`mcpplibs.mtest` beside `mcpplibs.mtest.gtest`): TOML takes one +// of them only as a quoted key (docs/05). +bool dotted_conflict(std::string_view text, const SectionSpan& section, std::string_view dotted) { + for (auto const& k : key_lines(text, section)) { + const std::string_view key = k.key; + if (key.starts_with(std::string(dotted) + ".") || dotted.starts_with(std::string(key) + ".")) + return true; + } + return false; +} + } // namespace @@ -6346,41 +6406,38 @@ upsert_dependency_text(std::string_view source, } } - // The default namespace's dotted spelling (`mcpplibs.cmdline = ...`) is the - // same package as the bare one: it is replaced by the bare key. - const std::string line = std::format("{} = {}", defaultNamespace ? edit.shortName : dotted, value); + // THE ENTRY IS THE FULL IDENTITY AS A DOTTED KEY, IN NAME ORDER (2026.12.4.1): + // `mcpplibs.cmdline = "0.2.0"` names one package in every project, where a + // bare `cmdline` means the default namespace's. A bare key of the same + // package is replaced by it. A table the manifest writes as a + // `[.]` header keeps that form: the short key goes there. const std::string shortLine = std::format("{} = {}", edit.shortName, value); - if (defaultNamespace) { - auto base = find_section(text, baseHeader); - if (base) - if (auto legacy = key_line_span(text, *base, dotted)) erase_span(*legacy); - base = find_section(text, baseHeader); - if (!base) { - if (!text.empty() && text.back() != '\n') text += '\n'; - text += std::format("\n{}\n{}\n", baseHeader, line); - } else if (auto existing = key_line_span(text, *base, edit.shortName)) { - text.replace(existing->first, existing->second - existing->first, line); - } else { - insert_in(*base, line); - } - } else if (auto sub = find_section(text, subHeader)) { + if (auto sub = find_section(text, subHeader)) { // The namespace's own header: the short key there, and no dotted twin. if (auto existing = key_line_span(text, *sub, edit.shortName)) { text.replace(existing->first, existing->second - existing->first, shortLine); } else { - insert_in(*sub, shortLine); + insert_ordered(text, *sub, edit.shortName, shortLine); } if (auto base = find_section(text, baseHeader)) if (auto twin = key_line_span(text, *base, dotted)) erase_span(*twin); - } else if (auto base = find_section(text, baseHeader)) { - if (auto existing = key_line_span(text, *base, dotted)) { + } else { + auto base = find_section(text, baseHeader); + if (base && defaultNamespace) + if (auto bare = key_line_span(text, *base, edit.shortName)) { + erase_span(*bare); + base = find_section(text, baseHeader); + } + const bool quoted = base && dotted_conflict(text, *base, dotted); + const std::string line = std::format("{} = {}", quoted ? std::format("\"{}\"", dotted) : dotted, value); + if (!base) { + if (!text.empty() && text.back() != '\n') text += '\n'; + text += std::format("\n{}\n{}\n", baseHeader, line); + } else if (auto existing = key_line_span(text, *base, dotted)) { text.replace(existing->first, existing->second - existing->first, line); } else { - insert_in(*base, line); + insert_ordered(text, *base, dotted, line); } - } else { - if (!text.empty() && text.back() != '\n') text += '\n'; - text += std::format("\n{}\n{}\n", baseHeader, line); } auto reparsed = parse_string(text); diff --git a/src/build/prepare/graph_load.cpp b/src/build/prepare/graph_load.cpp index 821414cb8..97eb0330e 100644 --- a/src/build/prepare/graph_load.cpp +++ b/src/build/prepare/graph_load.cpp @@ -264,11 +264,11 @@ static void step4a_define_split_and_identity_closures(PrepareState& state) { g.consumer = inside ? rel.generic_string() : consumerFile.generic_string(); g.declaredNs = declared.ns; g.example = item.spec.isGit() - ? std::format("{} = {{ git = \"{}\", {} = \"{}\" }}", - declared.shortName, item.spec.git, + ? std::format("{}.{} = {{ git = \"{}\", {} = \"{}\" }}", + declared.ns, declared.shortName, item.spec.git, item.spec.gitRefKind, item.spec.gitRev) - : std::format("{} = {{ path = \"{}\" }}", - declared.shortName, + : std::format("{}.{} = {{ path = \"{}\" }}", + declared.ns, declared.shortName, std::filesystem::path(item.spec.path).generic_string()); } g.writtenNs.insert(normalised.ns); @@ -288,7 +288,7 @@ static void step4a_define_split_and_identity_closures(PrepareState& state) { g.keys.size() == 1 ? "manifest" : "manifests", g.keys.size() == 1 ? "it reaches" : "they reach", g.keys.size() == 1 ? "declares" : "declare", g.declaredNs, keys), - std::format("write {} in a [dependencies.{}] table, for example `{}`", + std::format("write {} in namespace {}, for example `{}`", g.keys.size() == 1 ? "it" : "them", g.declaredNs, g.example)); } state.adoptionGroups.clear(); @@ -605,8 +605,8 @@ static void step4a_define_candidate_selection_closures(PrepareState& state) { "dependency '{}' resolved to '{}' through the " "deprecated bare-name search; namespace omission " "means `{}` only. Write the exact package:" - "\n [dependencies.{}]" - "\n {} = \"{}\"" + "\n [dependencies]" + "\n {}.{} = \"{}\"" "\n (or run `mcpp add {}@{}`). This fallback is " "removed in {}.", depName, @@ -668,8 +668,8 @@ static void step4a_define_candidate_selection_closures(PrepareState& state) { hint += std::format( "\n namespace omission means `{}`. write the " "exact package:" - "\n [dependencies.{}]" - "\n {} = \"{}\"", + "\n [dependencies]" + "\n {}.{} = \"{}\"", mcpp::pm::kDefaultNamespace, *suggested->namespace_, suggested->name, spec.version.empty() ? "" diff --git a/src/build/prepare/host_graph.cpp b/src/build/prepare/host_graph.cpp index e32268275..ef25cfff8 100644 --- a/src/build/prepare/host_graph.cpp +++ b/src/build/prepare/host_graph.cpp @@ -484,8 +484,8 @@ std::expected check_program_imports(PrepareState& state, std: " A build program imports the public modules of the libraries in its\n" " package's [build-dependencies]; an entry that lists only `tools`, or\n" " states `host-module = false`, asks for no library:\n" - " [build-dependencies.]\n" - " = {{ version = \"...\" }} # or `host-module = true` beside `tools`\n" + " [build-dependencies]\n" + " . = {{ version = \"...\" }} # or `host-module = true` beside `tools`\n" " importable here: {}\n" "{}", want, importable.empty() ? "(none)" : importable, diff --git a/src/cli.cppm b/src/cli.cppm index e7fce8856..d2359a3c3 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -691,6 +691,12 @@ mcpplibs::cmdline::App command_tree(const std::vector& passthrough, .option(cl::Option("format").takes_value().value_name("FMT") .help("json: the mcpp.search envelope (every version, licenses, repo)")) .action(cmd_search)) + .subcommand(cl::App("info").group("PROJECT COMMANDS") + .description("Show one package of the indices: versions, systems, license, features, the add line") + .arg(cl::Arg("package").help(".[@], as `mcpp add` takes it").required()) + .option(cl::Option("format").takes_value().value_name("FMT") + .help("json: the mcpp.info envelope")) + .action(cmd_info)) .subcommand(cl::App("publish").group("PROJECT COMMANDS") .description("Publish package to default registry") .option(cl::Option("dry-run").help("Print xpkg.lua without uploading")) @@ -2102,6 +2108,7 @@ int run(int argc, char** argv) { Effect::WriteGlobalCache, Effect::ExecBuildScript}}, // The index is refreshed when older than the search TTL. {"search", {Effect::InitMcppHome, Effect::Network}}, + {"info", {Effect::InitMcppHome, Effect::ReadProject, Effect::Network}}, {"index list", {Effect::InitMcppHome, Effect::ReadProject}}, // The same planning as `pack`, which runs the build programs that // declare formats; nothing is built. diff --git a/src/cli/cmd_registry.cppm b/src/cli/cmd_registry.cppm index bb3472344..5079f2b55 100644 --- a/src/cli/cmd_registry.cppm +++ b/src/cli/cmd_registry.cppm @@ -38,6 +38,13 @@ export int cmd_search(const mcpplibs::cmdline::ParsedArgs& parsed) { return mcpp::pm::search_packages(keyword, parsed.is_flag_set("all-versions"), json); } +export int cmd_info(const mcpplibs::cmdline::ParsedArgs& parsed) { + bool json = false; + if (auto rc = bad_format(parsed, json)) return *rc; + // The argument is required by the command tree, so a missing one is a usage error there. + return mcpp::pm::package_info(parsed.positional(0), json); +} + export int cmd_index_list(const mcpplibs::cmdline::ParsedArgs& parsed) { bool json = false; if (auto rc = bad_format(parsed, json)) return *rc; diff --git a/src/pm/index_management.cppm b/src/pm/index_management.cppm index 4c91435c0..877ce62db 100644 --- a/src/pm/index_management.cppm +++ b/src/pm/index_management.cppm @@ -13,6 +13,7 @@ import mcpp.manifest; import mcpp.effects; import mcpp.project; import mcpp.pm.index_route; +import mcpp.pm.dependency_selector; // `mcpp info`: the package named, as `mcpp add` reads it import mcpp.pm.package_manifest; // a package's features (mcpp#992) import mcpp.toolchain.platform; import mcpp.ui; @@ -123,6 +124,128 @@ export int search_packages(const std::string& keyword, bool allVersions, bool js return 0; } +// `mcpp info [@]` (2026.12.4.1): one package of the indices, +// in the depth `search` does not give a list -- its description, licenses and +// repository, every version and the systems the newest serves, whether it is an +// mcpp package and its features, what this project states and locks of it, and +// the `mcpp add` line. Read from the index descriptor and the project's files; +// nothing is installed. +// +// `--format json`: the `mcpp.info` envelope. +export int package_info(const std::string& spelling, bool json = false) { + const auto at = spelling.find('@'); + const auto name = spelling.substr(0, at); + const auto wanted = at == std::string::npos ? std::string{} : spelling.substr(at + 1); + auto selector = mcpp::pm::parse_package_selector(name); + if (!selector) { mcpp::ui::error(selector.error().message); return 2; } + const auto coordinate = mcpp::pm::normalize_package_selector(*selector); + // The full identity, the default namespace's packages included: the spelling `mcpp add` writes. + const auto identity = coordinate.namespace_.empty() + ? coordinate.shortName : std::format("{}.{}", coordinate.namespace_, coordinate.shortName); + + auto cfg = mcpp::config::load_or_init(/*quiet=*/false, mcpp::fetcher::make_bootstrap_progress_callback()); + if (!cfg) { mcpp::ui::error(cfg.error().message); return 4; } + auto xlEnv = mcpp::config::make_xlings_env(*cfg); + if (!mcpp::provider::open(xlEnv)->index_fresh(cfg->searchTtlSeconds)) { + mcpp::ui::status("Updating", "package index (auto-refresh)"); + mcpp::provider::open(xlEnv)->ensure_index_fresh(cfg->searchTtlSeconds, /*quiet=*/true); + } + mcpp::fetcher::Fetcher f(*cfg); + auto hits = f.search(coordinate.shortName); + if (!hits) { mcpp::ui::error(hits.error().message); return 1; } + const auto key = coordinate.namespace_ + ":" + coordinate.shortName; + const auto hit = std::ranges::find_if(*hits, [&](auto const& h) { return h.name == key; }); + if (hit == hits->end()) { + mcpp::ui::error(std::format("no index holds {}", identity)); + mcpp::ui::line(std::format("help: `mcpp search {}` lists the packages whose name holds it", + coordinate.shortName)); + return 1; + } + const auto d = f.describe_hits(std::span(&*hit, 1)).front(); + if (!wanted.empty() && std::ranges::find(d.versions, wanted) == d.versions.end()) { + mcpp::ui::error(std::format("{} publishes no version {}; it has {}", identity, wanted, + mcpp::manifest::join_versions_desc(d.versions, d.versions.size()))); + return 1; + } + const auto version = !wanted.empty() ? wanted : d.versions.empty() ? std::string{} : d.versions.front(); + // The systems `version` is published for, by the descriptor's own platform tables. + std::vector systems; + for (auto const& platform : mcpp::toolchain::platform::xpkg_platforms) { + const auto platformKey = mcpp::toolchain::platform::TargetPlatform::for_lint_of(platform); + if (std::ranges::contains(mcpp::manifest::list_xpkg_versions(d.descriptor, platformKey), version)) + systems.emplace_back(platform); + } + nlohmann::json features = nullptr; + if (d.mcppPackage && !version.empty()) { + const auto host = mcpp::toolchain::platform::HostPlatform::current(); + const auto dir = f.install_path(coordinate.namespace_, coordinate.shortName, version) + .value_or(std::filesystem::path{}); + features = mcpp::pm::feature_answer_json(mcpp::pm::package_features( + d.descriptor, dir, coordinate.shortName, version, host)); + } + // What this project states and locks of it. + std::string stated, table, locked; + if (auto root = mcpp::project::find_manifest_root(std::filesystem::current_path())) { + if (auto m = mcpp::manifest::load(*root / "mcpp.toml")) { + for (auto [t, deps] : {std::pair{"dependencies", &m->dependencies}, + std::pair{"dev-dependencies", &m->devDependencies}, + std::pair{"build-dependencies", &m->buildDependencies}}) { + auto dep = std::ranges::find_if(*deps, [&](auto const& kv) { + return kv.second.namespace_ == coordinate.namespace_ && kv.second.shortName == coordinate.shortName; + }); + if (dep == deps->end()) continue; + stated = dep->second.version; + table = t; + break; + } + } + if (auto lock = mcpp::lockfile::load(*root / "mcpp.lock")) + for (auto const& p : lock->packages) + if (p.namespace_ == coordinate.namespace_ && p.name == coordinate.shortName) locked = p.version; + } + const auto add = version.empty() ? std::string{} : std::format("mcpp add {}@{}", identity, version); + if (json) { + mcpp::wire::Envelope env{.kind = "mcpp.info", .effects = {mcpp::wire::Effect::InitMcppHome}}; + env.data = {{"id", identity}, {"namespace", coordinate.namespace_}, {"name", coordinate.shortName}, + {"description", hit->description}, {"index", hit->source}, {"versions", d.versions}, + {"version", version}, {"systems", systems}, {"licenses", d.catalog.licenses}, + {"repo", d.catalog.repo}, {"mcppPackage", d.mcppPackage}, {"features", features}, + {"stated", stated.empty() ? nlohmann::json(nullptr) : nlohmann::json{{"table", table}, {"version", stated}}}, + {"locked", locked.empty() ? nlohmann::json(nullptr) : nlohmann::json(locked)}, + {"add", add}}; + mcpp::wire::emit(env); + return 0; + } + auto join = [](const std::vector& v) { + std::string out; + for (auto const& s : v) out += (out.empty() ? "" : ", ") + s; + return out; + }; + std::println(""); + std::println(" {} {}", identity, hit->description); + std::println(" {:<11} {}", "versions", d.versions.empty() ? std::string("none published") + : mcpp::manifest::join_versions_desc(d.versions, mcpp::manifest::kVersionsShown)); + if (!version.empty()) + std::println(" {:<11} {} ({})", "version", version, systems.empty() ? std::string("no system") : join(systems)); + if (!d.catalog.licenses.empty()) std::println(" {:<11} {}", "license", join(d.catalog.licenses)); + if (!d.catalog.repo.empty()) std::println(" {:<11} {}", "repository", d.catalog.repo); + std::println(" {:<11} {} ({})", "index", hit->source, + d.mcppPackage ? "an mcpp package: its mcpp.toml states its modules and features" + : "a package the index installs; mcpp reads no manifest of it"); + if (features.is_object() && features.contains("features") && features["features"].is_array() + && !features["features"].empty()) { + std::vector names; + for (auto const& ft : features["features"]) + if (ft.is_object() && ft.contains("name")) names.push_back(ft["name"].get()); + if (!names.empty()) std::println(" {:<11} {}", "features", join(names)); + } + if (!stated.empty()) + std::println(" {:<11} [{}] {}{}", "this project", table, stated, + locked.empty() ? std::string{} : std::format(", locked {}", locked)); + if (!add.empty() && stated.empty()) std::println(" {:<11} {}", "add", add); + return 0; +} + // `mcpp index list` — global registries + project [indices]. // `--format json`: the `mcpp.index` envelope -- `registries` (name, url, // default) and the project's effective `indices` (name, and a path or a url diff --git a/tests/e2e/cli/surface.cpp b/tests/e2e/cli/surface.cpp index 1fa6bc3ef..03428093d 100644 --- a/tests/e2e/cli/surface.cpp +++ b/tests/e2e/cli/surface.cpp @@ -165,6 +165,12 @@ archives = ["{}"] expect(e2e::contains(s::read_file(dir / "surface.txt"), "flag emit surface --output")) << "the surface written lacks its own flag"; expect(s::lacks(run({"search", "mtest"}), "0.10.0") && e2e::contains(run({"search", "--all-versions", "mtest"}), "0.11.0, 0.10.0")) << "--all-versions listed what the newest few list"; + // `mcpp info` (2026.12.4.1): one package in depth, and the line that adds it. + out = run({"info", "mcpplibs.mtest"}); + expect(e2e::contains(out, "mcpplibs.mtest") && e2e::contains(out, "0.11.0, 0.10.0") + && e2e::contains(out, "version")) << out; + out = run({"info", "mcpplibs.mtest@0.10.0", "--format", "json"}); + expect(e2e::contains(out, "mcpp.info") && e2e::contains(out, "mcpp add mcpplibs.mtest@0.10.0")) << out; expect(e2e::contains(run({"self", "env", "--host", "--host-platform", "none"}), "host conventions")); expect(e2e::contains(run({"toolchain", "install", gcc, "--target", triple, "--platform", "none"}), "Installed")); expect(e2e::contains(run({"toolchain", "default", gcc, "--target", triple}), "Default set to")); diff --git a/tests/e2e/cli/usage.cpp b/tests/e2e/cli/usage.cpp index d51bf2bc0..ddb9d1ddb 100644 --- a/tests/e2e/cli/usage.cpp +++ b/tests/e2e/cli/usage.cpp @@ -16,7 +16,7 @@ namespace { // The visible top-level commands, in the order the help lists them, and some hidden ones. constexpr std::array kVisible{"new", "build", "fetch", "run", "test", "clean", "why", "resolve", "add", "remove", - "update", "search", "publish", "pack", "emit", "xpkg", "toolchain", "cache", "index", + "update", "search", "info", "publish", "pack", "emit", "xpkg", "toolchain", "cache", "index", "self", "explain", "version", "stage", "write"}; constexpr std::array kHidden{"dyndep", "link-output", "platform-step", "place-dlls", "coff-def", "bmi-compile"}; diff --git a/tests/e2e/deps/identity.cpp b/tests/e2e/deps/identity.cpp index 5a3cd53cd..ea3b11306 100644 --- a/tests/e2e/deps/identity.cpp +++ b/tests/e2e/deps/identity.cpp @@ -87,7 +87,7 @@ E2E identity{"identity", s::home_fixture, [] { expect(e2e::contains(warned[0], "mcpp.toml names 2 dependencies in namespace acme")) << "D: the warning does not name the manifest by its relative path and the count"; expect(e2e::contains(warned[0], "declare huxdemo")) << "D: the warning does not name the declared namespace"; expect(e2e::contains(warned[0], "acme.fw") && e2e::contains(warned[0], "acme.comp")) << "D: the warning does not list the keys"; - expect(e2e::contains(s::text(d), "[dependencies.huxdemo] table, for example")) << "D: the hint is not written in TOML"; + expect(e2e::contains(s::text(d), "in namespace huxdemo, for example `huxdemo.comp = { path = \"libs/comp\" }`")) << "D: the hint is not written in TOML"; expect(s::lacks(s::text(d), "libs/comp/mcpp.toml names")) << "D: the bare key inside libs/comp was reported"; }; diff --git a/tests/e2e/deps/names.cpp b/tests/e2e/deps/names.cpp index 24189638c..bb44c57c8 100644 --- a/tests/e2e/deps/names.cpp +++ b/tests/e2e/deps/names.cpp @@ -92,7 +92,7 @@ E2E names{"names", s::home_fixture, [] { write_manifest("[dependencies]\nwidget = \"1.0.0\""); auto bare = build(); expect(bare.started && bare.status != 0) << "a bare name must not reach the acme namespace"; - for (auto want : {"no package found for exact selector", "tried:", "acme.widget", "acme.widget (1.0.0)", "[dependencies.acme]"}) + for (auto want : {"no package found for exact selector", "tried:", "acme.widget", "acme.widget (1.0.0)", "acme.widget = \"1.0.0\""}) expect(e2e::contains(s::text(bare), want)) << want; write_manifest("[dependencies]\n\"acme.widget\" = \"1.0.0\""); expect(s::lacks(s::text(build()), "no package found for exact selector")) << "dotted selector must resolve to (acme, widget)"; @@ -103,7 +103,7 @@ E2E names{"names", s::home_fixture, [] { expect(s::lacks(compat, "no package found for exact selector")) << "bare gadget must still reach compat during the migration window"; expect(e2e::contains(compat, "deprecated bare-name search")) << "the bare-name fallback must announce itself"; expect(e2e::contains(compat, "compat.gadget")) << "the warning must name the exact replacement"; - expect(e2e::contains(compat, "[dependencies.compat]")) << "the warning must show the manifest edit"; + expect(e2e::contains(compat, "compat.gadget = \"2.0.0\"")) << "the warning must show the manifest edit"; write_manifest("[dependencies.compat]\ngadget = \"2.0.0\""); const auto explicit_compat = s::text(build()); expect(s::lacks(explicit_compat, "no package found for exact selector")) << "explicit compat.gadget must resolve"; diff --git a/tests/e2e/deps/path.cpp b/tests/e2e/deps/path.cpp index 6823dcce4..045ca379d 100644 --- a/tests/e2e/deps/path.cpp +++ b/tests/e2e/deps/path.cpp @@ -85,11 +85,12 @@ E2E path{"path", s::home_fixture, [] { app.mcpp({"add", "widget@0.1.0"}); expect(s::has_line(manifest(), R"(^\[dependencies\])")) << "no [dependencies] section"; - expect(s::has_line(manifest(), R"(^widget = "0\.1\.0"$)")) << "widget entry missing or quoted"; - expect(s::no_line(manifest(), R"(^"widget")")) << "default-ns key should not be quoted"; + expect(s::has_line(manifest(), R"(^mcpplibs\.widget = "0\.1\.0"$)")) << "widget entry missing, bare or quoted"; + expect(s::no_line(manifest(), R"(^"mcpplibs\.widget")")) << "the full identity should not be quoted"; app.mcpp({"add", "mcpplibs.gadget@0.2.0"}); expect(eq(s::count_matching(manifest(), R"(^\[dependencies\]$)"), std::size_t{1})) << "[dependencies] header duplicated"; - expect(s::has_line(manifest(), R"(^gadget = "0\.2\.0"$)")) << "gadget not set"; + expect(s::has_line(manifest(), R"(^mcpplibs\.gadget = "0\.2\.0"$)")) << "gadget not set"; + expect(manifest().find("mcpplibs.gadget") < manifest().find("mcpplibs.widget")) << "entries are not in name order\n" << manifest(); app.mcpp({"add", "acme.util@2.0.0"}); expect(s::has_line(manifest(), R"(^acme\.util = "2\.0\.0"$)")) << "util entry missing"; expect(s::no_line(manifest(), R"(^\[dependencies\.acme\]$)")) << "a section was opened where no section existed"; @@ -118,10 +119,10 @@ E2E path{"path", s::home_fixture, [] { expect(e2e::succeeded(app.mcpp({"add", "--dev", "gadget@0.2.0"}))) << "add --dev failed"; expect(s::has_line(manifest(), R"(^\[dev-dependencies\]$)")) << "add --dev wrote no [dev-dependencies]\n" << manifest(); expect(failed(app.mcpp({"add", "--dev", "--build", "gadget@0.2.0"}))) << "--dev and --build together were accepted"; - expect(eq(s::count_matching(manifest(), R"(^gadget = "0\.2\.0"$)"), std::size_t{3})) << "the three tables do not each hold gadget\n" << manifest(); + expect(eq(s::count_matching(manifest(), R"(^mcpplibs\.gadget = "0\.2\.0"$)"), std::size_t{3})) << "the three tables do not each hold gadget\n" << manifest(); expect(e2e::succeeded(app.mcpp({"remove", "--build", "gadget"}))) << "remove --build failed"; expect(e2e::succeeded(app.mcpp({"remove", "--dev", "gadget"}))) << "remove --dev failed"; - expect(eq(s::count_matching(manifest(), R"(^gadget = "0\.2\.0"$)"), std::size_t{1})) << "remove --build/--dev did not take the entries out of their tables, or took [dependencies]'\n" << manifest(); + expect(eq(s::count_matching(manifest(), R"(^mcpplibs\.gadget = "0\.2\.0"$)"), std::size_t{1})) << "remove --build/--dev did not take the entries out of their tables, or took [dependencies]'\n" << manifest(); auto bare = app.mcpp({"add", "bareword"}); expect(failed(bare)) << "expected error for missing version"; expect(e2e::contains(s::text(bare), "version required")) << "wrong error"; @@ -148,7 +149,7 @@ E2E path{"path", s::home_fixture, [] { expect(s::has_line(manifest(), R"(^unknownidx\.thing = "1\.0\.0"$)")) << "unverifiable namespace should still be added"; auto avail = app.mcpp({"add", "widget@9.9.9"}); expect(e2e::contains(s::text(avail), "available: 0.1.0")) << "expected available-versions warning"; - expect(s::has_line(manifest(), R"(^widget = "9\.9\.9"$)")) << "widget@9.9.9 should still be written"; + expect(s::has_line(manifest(), R"(^mcpplibs\.widget = "9\.9\.9"$)")) << "widget@9.9.9 should still be written"; // A workspace member reads its root's [workspace.indices]. const auto ws_dir = s::case_dir() / "ws"; diff --git a/tests/e2e/golden/protocol-version.json b/tests/e2e/golden/protocol-version.json index 81f322d2c..adb3246c4 100644 --- a/tests/e2e/golden/protocol-version.json +++ b/tests/e2e/golden/protocol-version.json @@ -28,6 +28,13 @@ "read-project" ] }, + "info": { + "effects": [ + "init-mcpp-home", + "read-project", + "network" + ] + }, "pack": { "effects": [ "init-mcpp-home", @@ -136,6 +143,7 @@ "mcpp.pack.formats": 1, "mcpp.search": 1, "mcpp.toolchain.list": 1, + "mcpp.usage": 1, "mcpp.why.build-programs": 1, "mcpp.why.compat": 1, "mcpp.why.features": 1, diff --git a/tests/e2e/golden/surface.txt b/tests/e2e/golden/surface.txt index 6bcfe5068..c9ef7387f 100644 --- a/tests/e2e/golden/surface.txt +++ b/tests/e2e/golden/surface.txt @@ -9,8 +9,6 @@ command cache list command cache prune command cache verify command clean -command coff-def -command dyndep command emit command emit build-database command emit sbom @@ -26,11 +24,9 @@ command index remove command index status command index unpin command index update -command link-output +command info command new command pack -command place-dlls -command platform-step command publish command remove command resolve @@ -59,8 +55,10 @@ command why command write command xpkg command xpkg parse +flag --agent-skill-doc flag --deny flag --frozen +flag --lock-wait flag --locked flag --managed-only flag --no-color @@ -111,22 +109,6 @@ flag clean --dry-run flag clean --older-than flag clean --report flag clean --stale -flag coff-def --exports-file -flag coff-def --llvm-cxx -flag coff-def --llvm-nm -flag coff-def --llvm-target -flag coff-def --name -flag coff-def --output -flag coff-def --required -flag dyndep --bmi-dir -flag dyndep --bmi-ext -flag dyndep --expect-imports -flag dyndep --expect-none -flag dyndep --expect-provides -flag dyndep --module-map -flag dyndep --output -flag dyndep --single -flag dyndep --split-module flag emit build-database --accel flag emit build-database --cap flag emit build-database --dev @@ -166,13 +148,10 @@ flag fetch --to flag fetch --toolchain flag fetch --workspace flag index list --format -flag link-output --aside -flag link-output --companions -flag link-output --output -flag link-output --temporary -flag link-output --text +flag info --format flag new --list-templates flag new --template +flag new --vcs flag pack --all-programs flag pack --compress flag pack --debug-symbols @@ -199,12 +178,6 @@ flag pack --systems flag pack --target flag pack --toolchain flag pack --workspace -flag place-dlls --crt -flag place-dlls --depfile -flag place-dlls --output -flag place-dlls --toolset-crt -flag platform-step --out -flag platform-step --steps-hex flag publish --allow-dirty flag publish --dry-run flag publish --exclude @@ -315,6 +288,7 @@ key build-dependencies key build.accel key build.allow_host_libs key build.allow_host_tools +key build.batch_fetch key build.bmi_schedule key build.build_program_timeout key build.c_standard @@ -334,10 +308,12 @@ key build.include_dirs_after key build.ios_deployment_target key build.jobs key build.ldflags +key build.lock_wait key build.macos_deployment_target key build.memory_threshold key build.module_extensions key build.offline +key build.plan_locks key build.platform-dependencies key build.private_fragment key build.private_include_dirs @@ -393,9 +369,15 @@ reason c-env-verification-mismatch reason capability-pin reason companion-too-old reason compiler-requirement-conflict +reason compiler-without-modules reason convention-unreplaced +reason cps-component-not-found +reason cps-components-unstated +reason cps-description-invalid +reason cps-no-matching-package reason crt-declared-under-host-coupled reason device-source-unconsumed +reason emit-inside-a-package reason exclusive-capability reason host-cannot-serve reason host-module-missing @@ -407,13 +389,18 @@ reason layer-ordering reason layer-requirement reason lld-required-absent reason local-toolchain +reason lock-unavailable +reason lock-wait-exceeded reason lto-export-discovery reason managed-only reason msvc-redist-unavailable +reason not-a-package-of-mcpp-pack reason offline-download-required reason os-mismatch reason other +reason package-built-outside-the-ecosystem reason package-cycle +reason package-without-description reason payload-override reason payload-request reason platform-dependency @@ -430,9 +417,12 @@ reason static-package-in-two-images reason static-tls-image reason std-module-precompile reason target-base +reason test-output-collision reason tier-planned reason tool-version-conflict +reason toolchain-has-no-archiver reason unknown-target +reason vcs-unavailable reason version-floor-unmet notice build-program/includes-header notice build-program/reads-outside @@ -440,3 +430,5 @@ notice bundle-lacks-target notice host-input notice machine-path-in-manifest notice toolchain/default-changed +notice toolchain/tree-holds-two-families +notice xlings/package-at-two-versions diff --git a/tests/unit/test_cli_documents.cpp b/tests/unit/test_cli_documents.cpp index 17f65c096..3c9e6885c 100644 --- a/tests/unit/test_cli_documents.cpp +++ b/tests/unit/test_cli_documents.cpp @@ -33,6 +33,34 @@ UTest sheets_agree_with_the_tree{"CliDocuments/SheetsAgreeWithTheCommandTree", [ for (const auto& problem : problems) expect(false) << problem; }}; +UTest sheets_end_with_related_commands{"CliDocuments/SheetsEndWithRelatedCommands", [] { + // A command's sheet ends with `## Related`, which names the commands an agent reads on with, + // each a visible command: the sheets are a network, the root sheet its entry. + const std::vector passthrough; + const mcpplibs::cmdline::App* self = nullptr; + const auto app = mcpp::cli::command_tree(passthrough, self); + std::set> commands; + for (const auto& command : mcpplibs::cmdline::snapshot(app).subcommands) commands.insert(command.name); + static const std::regex named{R"(`mcpp ([a-z][a-z-]*))"}; + for (const auto& sheet : mcpp::skills::sheets) { + const std::string key(sheet.key); + if (key == "root") continue; + const std::string text(reinterpret_cast(sheet.data), sheet.size); + const auto at = text.find("\n## Related\n"); + expect(at != std::string::npos) << "sheet '" << key << "' has no `## Related` section"; + if (at == std::string::npos) continue; + const std::string related = text.substr(at + 1); + expect(related.find("\n## ") == std::string::npos) << "sheet '" << key << "' has a section after `## Related`"; + std::size_t links = 0; + for (auto it = std::sregex_iterator(related.begin(), related.end(), named); it != std::sregex_iterator(); ++it) { + ++links; + expect(commands.contains((*it)[1].str())) + << "sheet '" << key << "' relates `mcpp " << (*it)[1].str() << "`, which is no visible command"; + } + expect(links > 0) << "sheet '" << key << "' relates no command"; + } +}}; + UTest every_reason_token_is_explained{"CliDocuments/EveryReasonTokenIsExplained", [] { namespace refusal = mcpp::build::refusal; std::set tokens; diff --git a/tests/unit/test_manifest.cpp b/tests/unit/test_manifest.cpp index f09dffa8d..ba992afa1 100644 --- a/tests/unit/test_manifest.cpp +++ b/tests/unit/test_manifest.cpp @@ -491,12 +491,50 @@ compat.libpng = "1.6.43" .namespace_ = "compat", .shortName = "zlib", .version = "1.3.2", }); if (auto&& failed = expect(fatal(edited.has_value())); !failed) failed << edited.error(); - expect(ne(edited->find("[dependencies]\ncompat.zlib = \"1.3.2\"\ncompat.libpng = \"1.6.43\"\n"), + expect(ne(edited->find("[dependencies]\ncompat.libpng = \"1.6.43\"\ncompat.zlib = \"1.3.2\"\n"), std::string::npos)) << *edited; expect(edited->find("[dependencies.compat]") == std::string::npos); expect(mcpp::manifest::reopened_dotted_tables(*edited).empty()); }}; +// 2026.12.4.1: every entry is its full identity as a dotted key, in name order; a +// bare key of the default namespace's package is replaced by it, and a key that +// would make another one's path a table is quoted (docs/05). +UTest writes_full_identities_in_name_order{"ManifestEditor/WritesFullIdentitiesInNameOrder", [] { + constexpr std::string_view source = R"([package] +name = "app" +version = "0.1.0" + +[dependencies] +# the parser +cmdline = "0.1.0" +mcpplibs.tinyhttps = "0.2.2" +zeta.last = "1.0.0" +)"; + auto edited = mcpp::manifest::upsert_dependency_text(source, { + .namespace_ = "mcpplibs", .shortName = "cmdline", .version = "0.2.0", + }); + if (auto&& failed = expect(fatal(edited.has_value())); !failed) failed << edited.error(); + expect(ne(edited->find("# the parser\nmcpplibs.cmdline = \"0.2.0\"\nmcpplibs.tinyhttps = \"0.2.2\"\nzeta.last"), + std::string::npos)) << *edited; + expect(edited->find("\ncmdline = ") == std::string::npos) << *edited; + auto more = mcpp::manifest::upsert_dependency_text(*edited, { + .namespace_ = "compat", .shortName = "gtest", .version = "1.15.2", + }); + if (auto&& failed = expect(fatal(more.has_value())); !failed) failed << more.error(); + expect(ne(more->find("[dependencies]\n# the parser\ncompat.gtest = \"1.15.2\"\nmcpplibs.cmdline"), std::string::npos) + || ne(more->find("[dependencies]\ncompat.gtest = \"1.15.2\"\n# the parser"), std::string::npos)) << *more; + auto nested = mcpp::manifest::upsert_dependency_text(*more, { + .namespace_ = "mcpplibs.cmdline", .shortName = "extra", .version = "0.1.0", + }); + if (auto&& failed = expect(fatal(nested.has_value())); !failed) failed << nested.error(); + expect(ne(nested->find("\"mcpplibs.cmdline.extra\" = \"0.1.0\""), std::string::npos)) << *nested; + auto parsed = mcpp::manifest::parse_string(*nested); + if (auto&& failed = expect(fatal(parsed.has_value())); !failed) failed << parsed.error().format(); + expect(eq(parsed->dependencies.size(), 5u)); + expect(eq(parsed->dependencies.at("mcpplibs.cmdline").version, "0.2.0")); +}}; + // A manifest an older `mcpp add` wrote: the reader takes it and names the // table; the next edit of that table writes the header's entries as dotted keys. UTest repairs_a_header_that_reopens_dotted_keys{"ManifestEditor/RepairsAHeaderThatReopensDottedKeys", [] { From dd7433dc82e159fa24e1ebb4e444ac92bc1a6211 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 05:47:34 +0900 Subject: [PATCH 16/36] The CPS adapter states why it is an implementation unit from the structure, not from a crash A GCC 16.1 crash once seen with the format's modules imported into the build program's interface coincided with crashes on unrelated files and compiler processes hung in the kernel on the same machine; it is not attributable to that form and is not recorded as an upstream defect. The adapter stays an implementation unit for what that gives: the format is in no importer's BMI. --- .agents/docs/2026-11-27-ecosystem-boundary-design.md | 7 ++++--- src/build/build_program/cps_package.cpp | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index 4358b2568..b07f7f677 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -1177,9 +1177,10 @@ CPS 是其中一种被读取的描述。`mcpp-package.json` 仍是 mcpp 的权 与 `mcpp.cps.usage`(查找、匹配、组件闭包、配置选择,得出与指令同形的结果),只依赖 JSON 库,单元测试在包内。使用处 各一个适配文件:`src/pack/library/descriptions.cpp`(`mcpp.pack.library` 的实现单元,`.pc` 与 `.cps` 两种描述都在此)、 `src/build/build_program/cps_package.cpp`(`mcpp.build.build_program` 的实现单元,把声明展开为指令)。两个适配都是 -实现单元而不是模块:把格式的模块导入 `mcpp.build.build_program` 的接口时,GCC 16.1 在 `src/main.cpp` 的 `import mcpp.cli` -处崩溃(mcpp#1027 登记的同一类缺陷);在实现单元中导入,它们不进入任何导入者读取的 BMI。构建程序一侧只有内置模块中的 -声明类型与指令表的一行。 +实现单元而不是模块:格式的模块只在实现单元中导入,不进入任何导入者读取的 BMI,格式的改动不使导入者重新编译,去掉 +格式只删两个文件与两处调用。构建程序一侧只有内置模块中的声明类型与指令表的一行。(把格式的模块导入构建程序的接口 +时曾遇到 GCC 16.1 的崩溃;同一时期这台机器在互不相关的文件上随机崩溃并有内核态挂起的编译进程,崩溃不能归于该写法, +因此不作为上游缺陷登记。) **七、文档与示例。** 新章 docs/14「Common Package Specification」两种语言:立场、两个方向、声明与展开、匹配与拒绝、 与 pkg-config 的分工。SPEC-014 记写出,SPEC-007 记声明;docs/10、12 记文件,docs/30 记声明,docs/04 记 diff --git a/src/build/build_program/cps_package.cpp b/src/build/build_program/cps_package.cpp index ac3b433d1..85b3804d1 100644 --- a/src/build/build_program/cps_package.cpp +++ b/src/build/build_program/cps_package.cpp @@ -9,10 +9,10 @@ // applies them as it applies any other. What CPS means -- where a description is, which platform // it is for, which components and configuration it gives -- is mcpp.cps's. // -// AN IMPLEMENTATION UNIT OF mcpp.build.build_program, NOT A MODULE OF ITS OWN: importing the -// format's modules (and the system table) into the build program's interface made GCC 16.1 -// crash at `import mcpp.cli` in src/main.cpp, the shape mcpp#1027 records; imported here, they -// are no part of any BMI an importer reads. +// AN IMPLEMENTATION UNIT OF mcpp.build.build_program, NOT A MODULE OF ITS OWN: the format's +// modules (and the system table) are imported here only, so they are no part of any BMI an +// importer reads -- a change of the format recompiles no importer, and removing the format +// removes this file and one call. module mcpp.build.build_program; import std; From 60a795855676b47e84cb1dd1cf3a7448093f192f Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 05:48:22 +0900 Subject: [PATCH 17/36] Version 2026.12.4.1 --- CHANGELOG.md | 2 +- mcpp.toml | 2 +- modules/versioning/src/version.cppm | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c9f9b57c..205bfc01e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ > 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.4.1] - 2026-12-05 ### Added diff --git a/mcpp.toml b/mcpp.toml index 472fba1d4..d55a86d8d 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,6 +1,6 @@ [package] name = "mcpp" -version = "2026.11.27.1" +version = "2026.12.4.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 447adb978..ecfd855f6 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.11.27.1"; +inline constexpr std::string_view MCPP_VERSION = "2026.12.4.1"; } // namespace mcpp From fc15c6ce91bf7dba9a2e3dfa6c30ed37cdcac397 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 08:18:56 +0900 Subject: [PATCH 18/36] CHANGELOG: on Windows a started program is named as mcpp was given its directories (mcpp#1032) openkal-windows 0.23.2, which mcpplibs.os 0.4.8 resolves to, names the image's directory and the working directory by the preopen mcpplibs.os located them under, so the compiler under a substituted drive is started as Z:\... rather than by its physical path. --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 205bfc01e..1dfbb56ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,6 +165,11 @@ not read has no revision rather than revision 0, and `mcpp xpkg parse` refuses it; a revision mcpp reads differently from the installer is reported once as `fetch/revision-misread` (SPEC-001 §10.5). +- On Windows a program mcpp starts -- the compiler, a tool -- and its working directory are named + as mcpp's process was given their directories (a volume or the working directory) rather than by + the physical path the system reports for a handle. Under a substituted drive the compiler is + started as `Z:\...`, which a sandbox that admits the drive and not the physical path requires + (openkal-windows 0.23.2, which mcpplibs.os resolves to; mcpp#1032). ## [2026.11.27.1] - 2026-11-27 From cae55c9581f77cb7a936fbb9c6e5db12259619df Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 12:07:20 +0900 Subject: [PATCH 19/36] The module probe's cache key names its word in a literal of its own "\x1fexport-module" is one hex escape, \x1fe, out of the range of a char: clang refuses it, and GCC only warns, so the tree built with GCC and failed on every host whose build uses clang (macOS, Windows, linux-aarch64). --- src/toolchain/probe.cppm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/toolchain/probe.cppm b/src/toolchain/probe.cppm index e3fffaa7d..4934f5c8e 100644 --- a/src/toolchain/probe.cppm +++ b/src/toolchain/probe.cppm @@ -441,7 +441,7 @@ bool driver_compiles_modules(const std::filesystem::path& compiler, const std::v std::vector argv{compiler.string()}; argv.insert(argv.end(), words.begin(), words.end()); auto key = probe_cache_key(argv, env, true); - key += "\x1fexport-module"; + key += "\x1f" "export-module"; return kept_probe("modules", key, why, [&](const std::filesystem::path& work) { std::error_code ec; const auto tag = std::format("{:x}", std::random_device{}()); From 4675fc89cd22ae3fc6004728a33bffaecd1e2823 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 12:51:57 +0900 Subject: [PATCH 20/36] e2e: the collision case finds the program as Windows names it; the std module case takes the entry its build used test-output-collision looked for the built program as `^app$`; on Windows it is app.exe. bmi-machine/1039 removed the std module entry whose record was newest, but the shared home holds one entry per toolchain and a record's time is set at most once in 12 hours (mark_used), so on Windows it removed another toolchain's entry, which no build then rebuilt. The case now takes the entry the build's uses.list names, and states that both projects use it. --- tests/e2e/modules/bmi.cpp | 35 +++++++++++++++++++++-------------- tests/e2e/test/collision.cpp | 6 +++--- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/tests/e2e/modules/bmi.cpp b/tests/e2e/modules/bmi.cpp index 470f0e6ce..c4c3d2a7c 100644 --- a/tests/e2e/modules/bmi.cpp +++ b/tests/e2e/modules/bmi.cpp @@ -25,6 +25,20 @@ std::optional graph_of(const fs::path& root) { return std::nullopt; } +// The std module entry the last build of the project at `root` used: its build directory's +// `uses.list` names the entry's record (`cache /std-module.json`). +std::optional std_entry_used(const fs::path& root) { + for (const auto& list : s::find_files(root / "target", R"(uses\.list)")) { + std::istringstream in(s::read_file(list)); + for (std::string l; std::getline(in, l);) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l.starts_with("cache ") && l.ends_with("std-module.json")) + return fs::path(l.substr(6)).parent_path(); + } + } + return std::nullopt; +} + // The build cache's entries whose name begins with `prefix` (`//*`), sorted. std::vector entries_of(const fs::path& pkg, std::string_view prefix) { std::vector out; @@ -556,24 +570,16 @@ bmi_schedule = "on" }; "1039 two builds that find the std module missing compile it once"_test = [] { // With the std module entry two projects use removed, the two build at once and both - // succeed; the entry is whole afterwards (its record and its object). + // succeed; the entry is whole afterwards (its record and its object). The entry is the + // one the build names as used: the shared home holds one per toolchain, and a record's + // time is set at most once in 12 hours (mcpp::home::mark_used), so the newest record + // need not be this build's. auto one = s::project::scaffold("one"); auto two = s::project::scaffold("two"); auto r = one.mcpp({"build"}); expect(fatal(e2e::succeeded(r))) << "the first build\n" << s::text(r); - const auto root = s::shared_home() / "build-cache/v1/std"; - std::optional entry; - fs::file_time_type newest{}; - std::error_code ec; - if (fs::is_directory(root, ec)) - for (const auto& d : fs::directory_iterator(root)) { - const auto rec = d.path() / "std-module.json"; - if (fs::is_regular_file(rec, ec) && (!entry || fs::last_write_time(rec) > newest)) { - entry = d.path(); - newest = fs::last_write_time(rec); - } - } - expect(fatal(entry.has_value())) << "no std module entry under " << root.string(); + const auto entry = std_entry_used(one.dir()); + expect(fatal(entry.has_value())) << "the build names no std module entry it used"; fs::remove_all(*entry); auto a = s::mcpp_command({"build"}, one.dir()); auto b = s::mcpp_command({"build"}, two.dir()); @@ -584,6 +590,7 @@ bmi_schedule = "on" } expect(fatal(e2e::succeeded(*ra))) << "the first of two builds at once\n" << s::text(*ra) << s::text(*rb); expect(fatal(e2e::succeeded(*rb))) << "the second of two builds at once\n" << s::text(*ra) << s::text(*rb); + expect(fatal(std_entry_used(two.dir()) == entry)) << "the two projects use different std module entries"; expect(fatal(fs::is_regular_file(*entry / "std-module.json"))) << "the entry has no record afterwards"; bool object = false; for (const auto& f : fs::directory_iterator(*entry)) object = object || f.path().extension() == ".o"; diff --git a/tests/e2e/test/collision.cpp b/tests/e2e/test/collision.cpp index eeb9eb1a5..8a3f37b02 100644 --- a/tests/e2e/test/collision.cpp +++ b/tests/e2e/test/collision.cpp @@ -15,10 +15,10 @@ namespace { constexpr std::string_view kProgram = "import std;\nint main() { std::println(\"the program\"); }\n"; constexpr std::string_view kTest = "int main() { return 0; }\n"; -// The one program `name` below a `bin/` directory of the project's target directory (a member's -// programs are in `bin//`), outside the build programs'. +// The one program `name` (`name.exe` on Windows) below a `bin/` directory of the project's target +// directory (a member's programs are in `bin//`), outside the build programs'. std::optional program(const s::project& p, std::string_view name) { - for (const auto& f : s::find_files(p.at("target"), std::format("^{}$", name))) + for (const auto& f : s::find_files(p.at("target"), std::format(R"(^{}(\.exe)?$)", name))) if (!f.generic_string().contains("/.build-mcpp/") && f.generic_string().contains("/bin/") && fs::is_regular_file(f)) return f; From 9211d3c5911ec968a3341181b674e56b12c8fb64 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 14:20:18 +0900 Subject: [PATCH 21/36] A process that holds a build directory shared and then needs it alone takes it alone in place of its hold MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mcpp pack holds the directory shared for the selection it built (plan locks), then plans its dispatch pass, whose graph runs actions, alone. flock and LockFileEx lock per open file, so the second open waited for the first without end (mcpp pack -p --pkg-format , the e2e pack/members cases). dirlock::acquire lets the shared hold go and takes the directory alone in its place; every holder in the process holds it alone from then on. SPEC-011 §2 item 11 states it (v1.5). --- docs/specs/README.md | 2 +- docs/specs/concurrency.md | 10 +++++++--- src/build/dirlock.cppm | 18 ++++++++++++++++-- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/docs/specs/README.md b/docs/specs/README.md index f33390ccb..e85e14bfa 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -40,7 +40,7 @@ | [SPEC-008](library-interface.md) | 库的接口:公开模块、发布闭包与两种形态的一致 | 草案 v0.2 | 2026-10-11 | 第一阶段(只警告)mcpp >= 2026.9.28.3;v0.2 mcpp >= 2026.10.11.1 | | [SPEC-009](toolchain-maintenance.md) | 工具链的支持与维护:版本线、默认值、来源、移动与退役 | 草案 v0.7 | 2026-11-21 | 逐条标注;本版只有规范,多数条款未实现;§6.4 mcpp >= 2026.10.8.1 | | [SPEC-010](home-initialization.md) | home 选择、单跳入口、初始化、网络边界、单次运行的 `--home` 与来自目录的 home | 草案 v0.3 | 2026-11-21 | mcpp >= 2026.10.19.1;网络能力逐条标注;§6 mcpp >= 2026.10.26.1、xlings >= 2026.10.26.1 | -| [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁与计划的锁、等待的报告与上限、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.4 | 2026-12-05 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1;§2 第 7 至 10 条、§2.1、§2.2、§5.1 第 13 条 mcpp >= 2026.12.4.1 | +| [SPEC-011](concurrency.md) | 并发运行:三段、构建目录锁与计划的锁、等待的报告与上限、原子发布、`mcpp.lock` 的乐观写入、取消;编译执行器的恢复、发布、记录与文本 | 评审中 v1.5 | 2026-12-05 | mcpp >= 2026.10.26.1;§5.1 mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条 mcpp >= 2026.11.19.1;§2 第 7 至 11 条、§2.1、§2.2、§5.1 第 13 条 mcpp >= 2026.12.4.1 | | [SPEC-012](human-output.md) | 面向人的输出:两条流、两种介质、行的种类、颜色、程序的文本 | 评审中 v1.1 | 2026-11-19 | mcpp >= 2026.10.26.1;§5 mcpp >= 2026.11.19.1 | | [SPEC-013](platforms.md) | 平台:`[platform]` 的七组键、版本组与 `hosted`,三种写法与层次,目标图与宿主图的选择,`cfg(platform)`,依赖图的补全,链接、命名与封装,运行器与载体,平台阶段与协议 17 | 评审中 v1.17 | 2026-11-23 | mcpp >= 2026.10.27.1;§10 的执行宿主与 §11 的载体架构 mcpp >= 2026.10.29.1;§7.5 版本组参与解析与 §14 平台系列 mcpp >= 2026.11.7.1;§14 内置平台为确切版本 mcpp >= 2026.11.7.2;v1.7 条款 mcpp >= 2026.11.10.1;§14 索引的平台列 mcpp >= 2026.11.17.1;§14 系列取可用的最新版本与 §15.1 的 `+b` 条目 mcpp >= 2026.11.19.1;v1.17 条款 mcpp >= 2026.11.23.1 | | [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.9 | 2026-12-05 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1;v2.9 mcpp >= 2026.12.4.1 | diff --git a/docs/specs/concurrency.md b/docs/specs/concurrency.md index 448b52214..1473995fc 100644 --- a/docs/specs/concurrency.md +++ b/docs/specs/concurrency.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-011 | | 标题 | 同一工程上的并发运行:构建目录锁、原子发布、乐观写入与取消 | -| 状态 | 评审中 v1.4 | -| 版本 | 1.4 | +| 状态 | 评审中 v1.5 | +| 版本 | 1.5 | | 最后修改 | 2026-12-05 | -| 对应实现 | 基础保证: mcpp >= 2026.10.26.1; §5.1: mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条: mcpp >= 2026.11.19.1;§2 第 3 条的报告、第 7 至 10 条、§2.1、§2.2、§3 的归档、§5.1 第 13 条与 §6 的标准库模块: mcpp >= 2026.12.4.1 | +| 对应实现 | 基础保证: mcpp >= 2026.10.26.1; §5.1: mcpp >= 2026.11.7.1;§5.1 第 6 条的不可观察单元与第 8 至 12 条: mcpp >= 2026.11.19.1;§2 第 3 条的报告、第 7 至 11 条、§2.1、§2.2、§3 的归档、§5.1 第 13 条与 §6 的标准库模块: mcpp >= 2026.12.4.1 | | 相关设计文档 | `.agents/docs/2026-10-26-control-contract-runtime-and-ide-ecosystem-design.md` §3、§4、§5.4 | | 相关 issue | #839 | | 使用文档 | [50 — 机器可读输出](../zh/50-machine-output.md) §9、§11 | @@ -67,6 +67,9 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 后到者取得锁后在单元缓存中找到该单元并放置,不启动编译器。两个计划都链接的产物按 §3 写临时名后 改名;ninja 的响应文件以计划命名(`<输出>.<计划>.rsp`),因为 ninja 在一条边结束时删除它;单元缓存 以响应文件的内容而非名字作为键。 +11. 一个进程对一个构建目录只持有一把锁,其内的各次规划共用它。进程共享持有之后又需要排他持有时 + (`mcpp pack` 先构建所选成员,其分派一遍的图中有动作),**必须**先放下共享持有再以排他方式取得, + 此后该进程内的持有者均为排他持有:对同一文件再次打开并加锁,会等待进程自己。 ### 2.1 等待 已实现 @@ -212,3 +215,4 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 1.2 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#952,设计 2026-11-19 §10):§5.1 第 6 条不可观察单元的恢复与报告、拒绝写出个数与出路;第 8 条输出可重定向的工具链上编译写入尝试私有的路径并由执行器发布;第 9 条清理退役运行状态;第 10 条准入的条件、执行器的结束原因与不能声明单元的环境;第 11 条编译器的记录由执行器写为依赖文件,第 12 条程序的文本在执行器中解码为 UTF-8(mcpp#970,设计 2026-11-19 §20)。 | | 1.3 | 2026-12-04 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7):§2.1 每一次等待经同一原语、按时刻报告、持有者记录为提示、四层上限与 `[lock-wait-exceeded]`、提供者的锁受同一上限;§2.2 不能加锁时立即以 `[lock-unavailable]` 拒绝;§6 完整的标准库模块条目不加锁读取。 | | 1.4 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7.1):§2 第 5 条改正为 `mcpp test` 在测试运行之前释放锁;第 7 至 10 条计划的锁、计划的目录、整体操作的排他持有与两个计划共有的单元;§3 链接的临时名与归档的原子发布;§5.1 第 13 条运行与恢复属于计划。 | +| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得。 | diff --git a/src/build/dirlock.cppm b/src/build/dirlock.cppm index 8f9dcd0a9..742cd6f7c 100644 --- a/src/build/dirlock.cppm +++ b/src/build/dirlock.cppm @@ -121,18 +121,32 @@ acquire(const std::filesystem::path& outputDir, bool shared) { // A process that holds the directory exclusively holds it for a shared // use too; a shared hold is not an exclusive one. const auto key = outputDir.lexically_normal().generic_string(); + const auto sharedKey = key + "\x1f" "shared"; std::lock_guard heldLock(g_heldMutex); if (auto existing = held()[key].lock()) return existing; if (shared) - if (auto existing = held()[key + "\x1fshared"].lock()) return existing; + if (auto existing = held()[sharedKey].lock()) return existing; + // ALONE AFTER SHARED, IN ONE PROCESS. `mcpp pack` holds the directory + // shared for the selection it built, then plans its dispatch pass, whose + // graph runs actions, alone; a second open of the lock file waited for the + // first without end (measured: `mcpp pack -p --pkg-format `). + // The shared hold is let go and the directory taken alone in its place, so + // every holder in this process holds it alone from then on. + auto sharedHold = shared ? nullptr : held()[sharedKey].lock(); + if (sharedHold) { auto released = std::move(*sharedHold); } auto lock = mcpp::home::FileLock::acquire( outputDir, kLockName, {.resource = std::format("the build directory {}", outputDir.filename().string()), .doing = shared ? "building a selection" : "building", .shared = shared}); if (!lock) return std::unexpected(lock.error()); + if (sharedHold) { + *sharedHold = std::move(*lock); + held()[key] = sharedHold; + return sharedHold; + } auto held_ = std::make_shared(std::move(*lock)); - held()[shared ? key + "\x1fshared" : key] = held_; + held()[shared ? sharedKey : key] = held_; return held_; } From 227f10c61375e619645d3482f990ffd402d1e4e9 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 14:20:18 +0900 Subject: [PATCH 22/36] The macOS stream-init shim is the configuration's: built once for every plan, and written whole Its object is below the configuration's directory while each plan keeps a ninja log of its own, so a plan that had not built it built it again (macOS: -p cli after --workspace compiled obj/mcpp_ios_init.o). The rule is a generator edge, which takes an object newer than its source as built, and it writes a name of its own process and renames it, so two plans that build it at once leave a whole file. --- src/build/ninja_backend.cppm | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 592ecbe93..f55309cc3 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -3058,10 +3058,22 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // is to run first. Its own rule rather than the C rule above because it // has no includes (so no depfile machinery) and must not be perturbed by // whatever that rule grows next. + // + // THE CONFIGURATION'S, NOT A PLAN'S (design 2026-11-27 §3.7.1). The object + // is below the configuration's directory and each plan keeps a ninja log + // of its own, so a plan that had not built it built it again (measured on + // macOS: `-p cli` after `--workspace` compiled it). `generator` takes an + // object newer than its source as built without the plan's log: the + // source is rewritten only when its bytes change, and the command is the + // configuration's, which names the directory. Two plans that build it at + // once each write a name of their own process and rename it, so a link + // reads a whole object. The shim exists on macOS only, where ninja runs + // the command through /bin/sh (`$$$$` is the shell's `$$`). if (need_ios_init_shim) { append("rule ios_init_object\n"); - append(" command = $cc $cflags -c $in -o $out\n"); - append(" description = CC $out\n\n"); + append(" command = $cc $cflags -c $in -o $out.$$$$.tmp && mv -f $out.$$$$.tmp $out\n"); + append(" description = CC $out\n"); + append(" generator = 1\n\n"); } // The auto-export edge. `mcpp coff-def` reads the same objects the link From 46ffffcdb0eff475b8531f23488f7c5b5096fedf Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 14:20:18 +0900 Subject: [PATCH 23/36] e2e: configurations are counted, not plans; expectations hold whatever the index lists and wherever the archive was packed A selection's plan has a build.ninja of its own (plans//), so routes/120, conditional/895 and the workspace cases count configuration directories (s::configuration_dirs, or a plan read as its configuration's, whose ninja log reading already includes the plan's). surface/1127 reads the shape of mcpp info's versions line rather than the versions the index lists, and the pack library case the platform table of the host the archive was packed on. --- tests/e2e/cli/surface.cpp | 5 +++-- tests/e2e/features/conditional.cpp | 3 ++- tests/e2e/index/routes.cpp | 6 ++---- tests/e2e/pack/library.cpp | 4 +++- tests/e2e/test/workspace.cpp | 13 +++++++++---- 5 files changed, 19 insertions(+), 12 deletions(-) diff --git a/tests/e2e/cli/surface.cpp b/tests/e2e/cli/surface.cpp index 03428093d..32ef0dba0 100644 --- a/tests/e2e/cli/surface.cpp +++ b/tests/e2e/cli/surface.cpp @@ -167,8 +167,9 @@ archives = ["{}"] << "--all-versions listed what the newest few list"; // `mcpp info` (2026.12.4.1): one package in depth, and the line that adds it. out = run({"info", "mcpplibs.mtest"}); - expect(e2e::contains(out, "mcpplibs.mtest") && e2e::contains(out, "0.11.0, 0.10.0") - && e2e::contains(out, "version")) << out; + // The newest versions the index lists, whichever they are as it grows. + expect(e2e::contains(out, "mcpplibs.mtest") && e2e::contains(out, "version")) << out; + expect(s::has_line(out, R"(^ *versions +[0-9]+\.[0-9]+\.[0-9]+, [0-9]+\.[0-9]+\.[0-9]+)")) << out; out = run({"info", "mcpplibs.mtest@0.10.0", "--format", "json"}); expect(e2e::contains(out, "mcpp.info") && e2e::contains(out, "mcpp add mcpplibs.mtest@0.10.0")) << out; expect(e2e::contains(run({"self", "env", "--host", "--host-platform", "none"}), "host conventions")); diff --git a/tests/e2e/features/conditional.cpp b/tests/e2e/features/conditional.cpp index 2561f640d..2b0973332 100644 --- a/tests/e2e/features/conditional.cpp +++ b/tests/e2e/features/conditional.cpp @@ -564,7 +564,8 @@ main = "src/main.cpp" member(r2, "a", "[target.'cfg(os = \"none\")'.build]\ndialect_cxxflags = [\"-DNEVER=1\"]"); member(r2, "b", ""); expect(fatal(e2e::succeeded(r2.mcpp({"build", "--workspace"}, inherited)))) << "--workspace"; - expect(fatal(ninjas(r2).size() == 1u)) << "a row for another target split the members into " << ninjas(r2).size() << " configurations"; + const auto configurations = s::configuration_dirs(r2.at("target")); + expect(fatal(configurations.size() == 1u)) << "a row for another target split the members into " << configurations.size() << " configurations"; s::project r3{tmp / "r3", {{"mcpp.toml", "[workspace]\nmembers = [\"a\", \"b\"]\n"}}}; member(r3, "a", std::format("[target.'{}'.build]\ndialect_cxxflags = [\"-DDIAL=3\"]", host)); diff --git a/tests/e2e/index/routes.cpp b/tests/e2e/index/routes.cpp index df7c74550..548a0a257 100644 --- a/tests/e2e/index/routes.cpp +++ b/tests/e2e/index/routes.cpp @@ -66,10 +66,8 @@ E2E routes{"routes", s::home_fixture, [] { expect(fatal(e2e::succeeded(r))) << "member-b's program failed: " << s::text(r); r = ws.mcpp({"build", "--workspace"}, inherited); expect(fatal(e2e::succeeded(r))) << "--workspace: " << s::text(r); - std::vector ninjas; - for (const auto& f : s::find_files(ws.at("target"), "build\\.ninja")) - if (!f.generic_string().contains("/.build-mcpp/")) ninjas.push_back(f.string()); - expect(fatal(ninjas.size() == 1u)) << "members naming one index tree are " << ninjas.size() << " configurations, expected 1"; + const auto configurations = s::configuration_dirs(ws.at("target")); + expect(fatal(configurations.size() == 1u)) << "members naming one index tree are " << configurations.size() << " configurations, expected 1"; expect(fatal(ws.exists("mcpp.lock") && e2e::contains(ws.read("mcpp.lock"), "[package.\"x.widget2\"]"))) << "expected an x.widget2 lock entry"; }; diff --git a/tests/e2e/pack/library.cpp b/tests/e2e/pack/library.cpp index 0e7394bd8..f1186eed2 100644 --- a/tests/e2e/pack/library.cpp +++ b/tests/e2e/pack/library.cpp @@ -909,9 +909,11 @@ version = "0.1.0" r = lib.mcpp({"emit", "xpkg", "--package", archive->string(), "--url", "https://example.org/v0.1.0"}); expect(fatal(e2e::succeeded(r))) << s::text(r); const auto entry = r.out; - for (std::string_view word : {R"(mcpp = "mcpp.toml")", "linux = {", "https://example.org/v0.1.0/", + for (std::string_view word : {R"(mcpp = "mcpp.toml")", "https://example.org/v0.1.0/", "declare_pkgconfig", "relocate_pkgconfig", "relocate_cps", "declare_cps"}) expect(e2e::contains(entry, word)) << "the entry lacks '" << word << "':\n" << entry; + // The table of the platform the archive was packed on. + expect(s::has_line(entry, R"(^ *(linux|macosx|windows) = \{)")) << "the entry has no platform table:\n" << entry; // Refused by name. const auto foreign = tmp / "foreign-0.1.tar.gz"; diff --git a/tests/e2e/test/workspace.cpp b/tests/e2e/test/workspace.cpp index 2dba0c1e4..c1c2a54f5 100644 --- a/tests/e2e/test/workspace.cpp +++ b/tests/e2e/test/workspace.cpp @@ -11,12 +11,17 @@ namespace fs = std::filesystem; namespace { -// The directories holding a graph (build.ninja, test.ninja or both), outside the build programs'. +// The configuration directories holding a graph (build.ninja, test.ninja or both), outside the +// build programs'. A selection's plan (`plans//`) counts as its configuration's directory, +// whose `.ninja_log` reading (s::ninja_log_outputs) already includes the plan's. std::vector graph_dirs(const s::project& p) { std::set dirs; - for (const auto& f : s::find_files(p.at("target"), "(build|test)\\.ninja")) - if (!f.generic_string().contains("/.build-mcpp/")) - dirs.insert(f.parent_path()); + for (const auto& f : s::find_files(p.at("target"), "(build|test)\\.ninja")) { + if (f.generic_string().contains("/.build-mcpp/")) continue; + auto dir = f.parent_path(); + if (dir.parent_path().filename() == "plans") dir = dir.parent_path().parent_path(); + dirs.insert(dir); + } return {dirs.begin(), dirs.end()}; } From 1b1257bb22818f1e14917811874dcf8cee4d0759 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 15:37:18 +0900 Subject: [PATCH 24/36] A link writes the artifact's own name in a directory of its own: a Mach-O program is the same file whichever command linked it A Mach-O linker writes the output's file name into the program as its signature's identifier; ld64.lld writes '.cli.123' and '.cli.456' into two different files and 'a/cli' and 'b/cli' into identical ones. The temporary name '..' therefore made every relink of an unchanged program differ, and a pack of one member differed from the pack of several on macOS. mcpp link-output --temporary now links '/.mcpp-link-/', renames the file over the artifact and removes the directory. Case 938 states that a relink of unchanged objects writes the same bytes and leaves no directory behind. SPEC-011 section 3, docs/07 and the CHANGELOG state the form. --- CHANGELOG.md | 12 +++++---- docs/07-workspace.md | 2 +- docs/specs/concurrency.md | 4 +-- docs/zh/07-workspace.md | 2 +- src/build/ninja_backend.cppm | 2 +- src/cli/cmd_build.cppm | 47 +++++++++++++++++++++--------------- tests/e2e/build/link.cpp | 14 ++++++++++- 7 files changed, 52 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dfbb56ee..0a9c0583c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -124,16 +124,18 @@ its graph, ninja's state, its records and its runs, under the plan's lock; the configuration's directory is held shared, and alone by what changes it as a whole. A unit both reach is compiled by the first and placed for the other by the unit cache; an artifact both link is - written under a temporary name of its own and renamed. The holding needs relocatable compiler - outputs and the unit cache; otherwise, under `--cache off`, under `bmi_schedule = "on"`, in a - graph that runs actions and with the new build optimization `plan-locks` off (`[build] plan_locks = "configuration"`, + written in a directory of its own under the artifact's name and renamed over it, so that a + Mach-O program, which carries its file name in its signature, is the same file whichever + command linked it. The holding needs relocatable compiler outputs and the unit cache; + otherwise, under `--cache off`, under `bmi_schedule = "on"`, in a graph that runs actions and + with the new build optimization `plan-locks` off (`[build] plan_locks = "configuration"`, `MCPP_PLAN_LOCKS`), the configuration is held alone as before. `mcpp why toolchain` states the holding and its reason. A selection's first build runs each of its edges once, a lookup for a unit another selection built. `batch-fetch` (`[build] batch_fetch`, `MCPP_BATCH_FETCH`) is listed as the build optimization it is. `/result.json` holds the record of the command that wrote it last; each command's own record is in its plan's directory, which - `.last-result.json` names (docs/07 §5.5, docs/50, SPEC-011 §2 items 7 to 10). -- On a POSIX host an archive is written whole under a temporary name and renamed over the + `.last-result.json` names (docs/07 §5.5, docs/50, SPEC-011 §2 items 7 to 11). +- On a POSIX host an archive is written whole in a directory of its own and renamed over the artifact, as a link is; it is no longer updated in place, so a member an earlier archive held and the sources no longer name does not remain. diff --git a/docs/07-workspace.md b/docs/07-workspace.md index 8df48a540..efc8f9faf 100644 --- a/docs/07-workspace.md +++ b/docs/07-workspace.md @@ -696,7 +696,7 @@ starts. - **Commands that select different members build at once.** A unit both reach is compiled by the first; the other's compiler executor finds it in the unit cache and places it, without starting the compiler. An artifact both link is - written under a temporary name and renamed over the artifact. + written in a directory of its own under the artifact's name and renamed over the artifact. - **Commands of one selection queue.** The one that waits says which command holds the plan (`Waiting … for the plan of member 'a', held by …`), and finds little to do when it proceeds. A test that runs while a source changes runs diff --git a/docs/specs/concurrency.md b/docs/specs/concurrency.md index 1473995fc..d9ea9f566 100644 --- a/docs/specs/concurrency.md +++ b/docs/specs/concurrency.md @@ -100,7 +100,7 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 资源 | 规则 | |---|---| -| 链接产物(可执行文件、共享库、测试程序)与归档 | POSIX 宿主上的非 PE、非 WebAssembly 目标:`mcpp link-output` 让链接写同一目录中本进程自己的临时名 `.<主名>.<扩展名>`,再改名到产物上;归档同样整个写出后改名(2026.12.4.1+),不在原处更新。Windows 宿主:`mcpp link-output` 先把旧产物改名为 `.old-`,再原地链接;运行中的程序保留旧文件,以后的链接清理不再被占用的 `.old-*`。PE 与 WebAssembly 目标:原地链接 | +| 链接产物(可执行文件、共享库、测试程序)与归档 | POSIX 宿主上的非 PE、非 WebAssembly 目标:`mcpp link-output` 让链接在同一目录中本进程自己的子目录 `.mcpp-link-/` 里以产物的名字写出,再改名到产物上,随后删除该子目录;Mach-O 链接器把输出的文件名写入程序的签名标识,因此临时的只是目录,同一程序重新链接得到相同的字节;归档同样整个写出后改名(2026.12.4.1+),不在原处更新。Windows 宿主:`mcpp link-output` 先把旧产物改名为 `.old-`,再原地链接;运行中的程序保留旧文件,以后的链接清理不再被占用的 `.old-*`。PE 与 WebAssembly 目标:原地链接 | | `result.json`、`target/.last-result.json`、`resolution.json`、配置级与根目录的 `compile_commands.json` | 写临时文件后改名替换 | | `target/.build_cache`(配置记录) | 读改写在 `target/.build_cache.lock` 下进行,写临时文件后改名替换;格式不变 | | `mcpp.lock` | 写临时文件后改名替换;乐观并发(§4) | @@ -215,4 +215,4 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 1.2 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#952,设计 2026-11-19 §10):§5.1 第 6 条不可观察单元的恢复与报告、拒绝写出个数与出路;第 8 条输出可重定向的工具链上编译写入尝试私有的路径并由执行器发布;第 9 条清理退役运行状态;第 10 条准入的条件、执行器的结束原因与不能声明单元的环境;第 11 条编译器的记录由执行器写为依赖文件,第 12 条程序的文本在执行器中解码为 UTF-8(mcpp#970,设计 2026-11-19 §20)。 | | 1.3 | 2026-12-04 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7):§2.1 每一次等待经同一原语、按时刻报告、持有者记录为提示、四层上限与 `[lock-wait-exceeded]`、提供者的锁受同一上限;§2.2 不能加锁时立即以 `[lock-unavailable]` 拒绝;§6 完整的标准库模块条目不加锁读取。 | | 1.4 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7.1):§2 第 5 条改正为 `mcpp test` 在测试运行之前释放锁;第 7 至 10 条计划的锁、计划的目录、整体操作的排他持有与两个计划共有的单元;§3 链接的临时名与归档的原子发布;§5.1 第 13 条运行与恢复属于计划。 | -| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得。 | +| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得;§3 链接写进程自己的子目录中的产物名,而非临时文件名。 | diff --git a/docs/zh/07-workspace.md b/docs/zh/07-workspace.md index 77cc69702..8a2eb29d1 100644 --- a/docs/zh/07-workspace.md +++ b/docs/zh/07-workspace.md @@ -582,7 +582,7 @@ mcpp test --workspace --workspace-timeout 1800 # whole fan-out (default 0 = no `plans/<16 位十六进制>/`,在计划的锁之下。目录本身由每个计划以共享方式持有,由整体改变它的操作以排他方式持有:创建、接替、 为另一个编译器构建而更新,以及 `mcpp clean`。 - **选择不同成员的命令同时构建。** 二者都到达的单元由先到者编译;另一方的编译执行器在单元缓存中找到它并放置,不启动编译器。 - 二者都链接的产物写入临时名后改名到产物上。 + 二者都链接的产物以产物的名字写入各自的临时目录,再改名到产物上。 - **同一选择的命令排队。** 等待的一方说明持有计划的命令(`Waiting … for the plan of member 'a', held by …`),继续时 几乎无事可做。源码改动时正在运行的测试运行的是改动前链接的程序;下一次构建编译该改动。 - **这种持有方式是条件,不是承诺。** 编译器的输出可重定向且单元缓存开启时,计划才有自己的目录;否则——工作区之外、 diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index f55309cc3..eef372649 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -2919,7 +2919,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, return "$mcpp link-output --output $out" + companionOption + textWord + " -- " + cmd; if (inPlaceTarget) return cmd; if (cmd.find("-o $out") == std::string::npos) return cmd; - // Through a temporary name, `/.` (cmd_link_output): one + // Through a directory of its own, `/.mcpp-link-/` (cmd_link_output): one // command, so a permit around it is held until the artifact is in // place (2026.11.16.1; before it a shell sequence that renamed the // file after the linker's command had ended). diff --git a/src/cli/cmd_build.cppm b/src/cli/cmd_build.cppm index fbe6b3805..de18dccef 100644 --- a/src/cli/cmd_build.cppm +++ b/src/cli/cmd_build.cppm @@ -1955,12 +1955,12 @@ export int cmd_dyndep(const mcpplibs::cmdline::ParsedArgs& parsed) { // nothing holds any more are deleted here. A process started while the linker // writes fails to start (file not found, sharing violation) -- Windows never // starts an image that is being written -- rather than running half of one. -// On POSIX (`--temporary`) the linker writes `/..` +// On POSIX (`--temporary`) the linker writes `/.mcpp-link-/` // -- the argument after its `-o`, or an archiver's word that is the artifact, -// renamed; the name keeps its extension, as a driver that names a file after -// it writes a second one otherwise (design 2026-11-15 N9), and the process's -// own, as two plans may link one artifact at once (design 2026-11-27 §3.7.1) -// -- and the file is renamed over the artifact once the linker succeeds: a +// renamed; the file keeps the artifact's name, which a Mach-O linker writes +// into the program, and the directory is the process's own, as two plans may +// link one artifact at once (design 2026-11-27 §3.7.1) -- and the file is +// renamed over the artifact once the linker succeeds: a // rename replaces a running program there, and a program started meanwhile // never meets a partial file. The publication is one command, so an edge that // holds a permit for the link holds it until the artifact is in place. @@ -2050,15 +2050,21 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, companion.replace_extension(std::string(std::string_view(part.begin(), part.end()))); fs::remove(companion, ec); } - // THROUGH A TEMPORARY NAME OF THIS PROCESS'S OWN (`/..`), - // renamed over the artifact: a program starting sees the old file or the - // new one, and two plans that link one artifact at once (design 2026-11-27 - // §3.7.1) each write their own file. A linker's output follows `-o`; an + // THROUGH A DIRECTORY OF THIS PROCESS'S OWN (`/.mcpp-link-/`), + // the file renamed over the artifact: a program starting sees the old file + // or the new one, and two plans that link one artifact at once (design + // 2026-11-27 §3.7.1) each write their own file. The linker writes the + // artifact's own name: a Mach-O linker writes the output's file name into + // the program as its signature's identifier (ld64.lld: `.cli.123` and + // `.cli.456` differ, `a/cli` and `b/cli` are identical), so a temporary file + // name made every link of an unchanged program differ; and a driver that + // names a second file after its output (design 2026-11-15 N9) writes it in + // the directory, removed with it. A linker's output follows `-o`; an // archiver's is the word that is the artifact, and its archive is then // written whole rather than updated in place. if (parsed.is_flag_set("temporary")) { - const auto temporary = out.parent_path() - / std::format(".{}.{}{}", out.stem().string(), mcpp::invocation::process_id(), out.extension().string()); + const auto scratch = out.parent_path() / std::format(".mcpp-link-{}", mcpp::invocation::process_id()); + const auto temporary = scratch / out.filename(); for (auto& argv : commands) { auto named = std::ranges::adjacent_find(argv, [&](const std::string& a, const std::string& b) { return a == "-o" && fs::path(b) == out; @@ -2069,20 +2075,21 @@ export int cmd_link_output(const mcpplibs::cmdline::ParsedArgs& parsed, return fail(std::format(" --temporary: the command names no `-o {0}` and no `{0}`", out.string()), 2); *word = temporary.string(); } - fs::remove(temporary, ec); + fs::remove_all(scratch, ec); + fs::create_directories(scratch, ec); + if (ec) + return fail(std::format(" --temporary: cannot create {}: {}", scratch.string(), ec.message()), 1); for (auto const& argv : commands) if (const int linked = run_linker(argv); linked != 0) { - fs::remove(temporary, ec); + fs::remove_all(scratch, ec); return linked; } fs::rename(temporary, out, ec); - if (ec) { - const auto why = std::format(": cannot rename {} over {}: {}", temporary.string(), out.string(), - ec.message()); - fs::remove(temporary, ec); - return fail(why, 1); - } - return 0; + const auto why = ec ? std::format(": cannot rename {} over {}: {}", temporary.string(), out.string(), + ec.message()) + : std::string(); + fs::remove_all(scratch, ec); + return why.empty() ? 0 : fail(why, 1); } if (commands.size() > 1) { for (auto const& argv : commands) diff --git a/tests/e2e/build/link.cpp b/tests/e2e/build/link.cpp index ea179f185..2e61a5ad1 100644 --- a/tests/e2e/build/link.cpp +++ b/tests/e2e/build/link.cpp @@ -267,7 +267,10 @@ ldflags = ["-Wl,-rpath='$$ORIGIN/../x'"] }; "938 a relink never exposes a partial file"_test = [] { // The link rule publishes through a temporary name, so a program started over and over - // while it is relinked twelve times never meets a partially written file (POSIX). + // while it is relinked twelve times never meets a partially written file (POSIX). C: the + // linker writes the artifact's own name in a directory of the process's own, which is gone + // afterwards, so a relink of unchanged objects writes the same bytes: a Mach-O linker + // writes the output's file name into the program's signature. if (!s::on_linux() && !s::on_macos()) skip("POSIX publication"); auto p = s::project::scaffold("app"); p.write("src/main.cpp", "int main() { return 0; }\n"); @@ -303,6 +306,15 @@ ldflags = ["-Wl,-rpath='$$ORIGIN/../x'"] stop = true; starter.join(); expect(errors.empty()) << "B: a start met a partially written program\n" << errors; + + const auto linked = s::read_file(*exe); + fs::remove(*exe); + r = p.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "C: the relink failed\n" << s::text(r); + expect(fatal(fs::exists(*exe))) << "C: the build did not link the removed program again"; + expect(s::read_file(*exe) == linked) << "C: a relink of unchanged objects wrote other bytes"; + for (const auto& e : entries(exe->parent_path())) + expect(!e.filename().string().starts_with(".mcpp-link-")) << "C: the link left " << e.filename().string(); }; "991 a prebuilt archive in ldflags is a link input"_test[s::gcc][s::unix_shell] = [] { From aa2650ad185ae098fc499b875eeb8e26f397bb21 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 15:37:22 +0900 Subject: [PATCH 25/36] e2e: what a selection compiles is what its record says ran a compiler A selection's plan has a ninja log of its own, and a unit another selection built is placed there by the unit cache, so an entry in a plan's log is no longer a compile. The workspace test and build cases and the pack of several members read MCPP_BUILD_RECORD, as the graph case does; the conditional case counts configurations, not graphs. The pack cases name the first file that differs between two trees. --- tests/e2e/features/conditional.cpp | 3 +- tests/e2e/pack/members.cpp | 45 +++++++++++++++--------------- tests/e2e/test/workspace.cpp | 18 ++++++++---- 3 files changed, 36 insertions(+), 30 deletions(-) diff --git a/tests/e2e/features/conditional.cpp b/tests/e2e/features/conditional.cpp index 2b0973332..f1e270726 100644 --- a/tests/e2e/features/conditional.cpp +++ b/tests/e2e/features/conditional.cpp @@ -571,7 +571,8 @@ main = "src/main.cpp" member(r3, "a", std::format("[target.'{}'.build]\ndialect_cxxflags = [\"-DDIAL=3\"]", host)); member(r3, "b", ""); expect(fatal(e2e::succeeded(r3.mcpp({"build", "--workspace"}, inherited)))) << "--workspace"; - expect(fatal(ninjas(r3).size() == 2u)) << "members whose rows evaluate differently share " << ninjas(r3).size() << " configuration(s)"; + const auto split = s::configuration_dirs(r3.at("target")); + expect(fatal(split.size() == 2u)) << "members whose rows evaluate differently share " << split.size() << " configuration(s)"; const auto a = run_of(r3, "a"); expect(fatal(a == "DIAL=3")) << "member a lost its dialect: " << a; const auto b = run_of(r3, "b"); diff --git a/tests/e2e/pack/members.cpp b/tests/e2e/pack/members.cpp index c66c15535..549c9a1c5 100644 --- a/tests/e2e/pack/members.cpp +++ b/tests/e2e/pack/members.cpp @@ -63,12 +63,13 @@ std::string trimmed(std::string s) { return s; } -// `diff -r a b` finds nothing: the same paths, and each file the same bytes. -bool same_tree(const fs::path& a, const fs::path& b) { - if (s::listing(a) != s::listing(b)) return false; +// What `diff -r a b` finds first: empty for the same paths with each file the same bytes, else +// the listings or the first file that differs. +std::string tree_difference(const fs::path& a, const fs::path& b) { + if (s::listing(a) != s::listing(b)) return "the listings"; for (const auto& rel : s::listing(a)) - if (fs::is_regular_file(a / rel) && s::read_file(a / rel) != s::read_file(b / rel)) return false; - return true; + if (fs::is_regular_file(a / rel) && s::read_file(a / rel) != s::read_file(b / rel)) return rel; + return {}; } // `cp -R from to`. @@ -357,11 +358,6 @@ int main() { } return fs::path{}; }; - auto objects = [](const fs::path& build_dir) { - std::size_t n = 0; - for (const auto& out : s::ninja_log_outputs(build_dir)) n += out.ends_with(".o"); - return n; - }; auto r = ws.mcpp({"pack", "--workspace", "--pkg-format", "zap"}, o); expect(fatal(e2e::succeeded(r))) << "A: the pack failed\n" << s::text(r); expect(fatal(count("core", "") == 1u)) << "A: core's program ran " << count("core", "") << " times, not once\n" << runs("core"); @@ -393,21 +389,24 @@ int main() { auto p = ws.mcpp({"pack", "-p", std::string(m), "--pkg-format", "zap"}, o); expect(fatal(e2e::succeeded(p))) << "B: mcpp pack -p " << m << " failed\n" << s::text(p); keep("single"); - expect(fatal(same_tree(ws.at(std::format("multi/{}", m)), ws.at(std::format("single/{}", m))))) << "B: " << m << "'s packed tree differs from the one mcpp pack -p " << m << " makes"; + const auto differs = tree_difference(ws.at(std::format("multi/{}", m)), ws.at(std::format("single/{}", m))); + expect(fatal(differs.empty())) << "B: " << m << "'s packed tree differs from the one mcpp pack -p " << m << " makes: " << differs; } for (std::string_view t : {"target", "core/target", "cli/target", "gui/target"}) ws.remove(t); - r = ws.mcpp({"build", "--workspace", "--release"}, o); - expect(fatal(e2e::succeeded(r))) << "C: the workspace did not build\n" << s::text(r); + auto [b, workspace] = s::recorded(ws, {"build", "--workspace", "--release"}, "c-build", o); + expect(fatal(e2e::succeeded(b))) << "C: the workspace did not build\n" << s::text(b); + expect(fatal(!workspace.compiled.empty())) << "C: the build compiled nothing, so this criterion measured nothing"; auto build_dirs = [&] { return s::configuration_dirs(ws.at("target")); }; - const auto dirs = build_dirs(); - expect(fatal(dirs.size() == 1u)) << "C: expected one build directory, got " << dirs.size(); - const auto before = objects(dirs.front()); - expect(fatal(before > 0u)) << "C: the build compiled nothing"; - r = ws.mcpp({"pack", "--workspace", "--pkg-format", "zap"}, o); - expect(fatal(e2e::succeeded(r))) << "C: the pack failed\n" << s::text(r); + expect(fatal(build_dirs().size() == 1u)) << "C: expected one build directory, got " << build_dirs().size(); + // The pack's dispatch pass runs actions, so it builds in the configuration's own graph + // (SPEC-011 §2 item 7) and places what the build compiled; what it compiles is what its + // record says ran a compiler. + auto [packed, built] = s::recorded(ws, {"pack", "--workspace", "--pkg-format", "zap"}, "c", o); + expect(fatal(e2e::succeeded(packed))) << "C: the pack failed\n" << s::text(packed); expect(fatal(build_dirs().size() == 1u)) << "C: the pack used another build directory"; - const auto after = objects(dirs.front()); - expect(after == before) << "C: the pack compiled " << (after - before) << " object(s) after the build"; + std::string compiled; + for (const auto& c : built.compiled) compiled += "\n " + c; + expect(built.compiled.empty()) << "C: the pack compiled " << built.compiled.size() << " unit(s) after the build:" << compiled; }; "870 a pack over several members resolves and fails per member"_test[s::unix_shell] = [] { // A pack of several members resolves a target name for the member an action is for @@ -747,8 +746,8 @@ main = "src/main.cpp" fs::copy_file(*archive_of(m), ws.at(std::format("alone/{}.tar.gz", m))); s::tar_extract(ws.at(std::format("together/{}.tar.gz", m)), ws.at(std::format("together/x-{}", m))); s::tar_extract(ws.at(std::format("alone/{}.tar.gz", m)), ws.at(std::format("alone/x-{}", m))); - expect(fatal(same_tree(ws.at(std::format("together/x-{}", m)), ws.at(std::format("alone/x-{}", m))))) - << "L: " << m << "'s archive from the pack of several differs from the one packed alone"; + const auto differs = tree_difference(ws.at(std::format("together/x-{}", m)), ws.at(std::format("alone/x-{}", m))); + expect(fatal(differs.empty())) << "L: " << m << "'s archive from the pack of several differs from the one packed alone: " << differs; } ws.remove("cli/target/dist"); ws.remove("gui/target/dist"); diff --git a/tests/e2e/test/workspace.cpp b/tests/e2e/test/workspace.cpp index c1c2a54f5..07f8deaef 100644 --- a/tests/e2e/test/workspace.cpp +++ b/tests/e2e/test/workspace.cpp @@ -181,12 +181,14 @@ kind = "lib" dirs = graph_dirs(ws); expect(fatal(!dirs.empty())); const auto dir = dirs.front(); - const auto before = core_edges(dir); - expect(before == 1 && runs() == 1) << "the build did not compile and run core once"; - auto g = ws.mcpp({"test", "--workspace"}); + expect(core_edges(dir) == 1 && runs() == 1) << "the build did not compile and run core once"; + // The tests are a selection of their own (a, b), whose plan places what the build compiled + // (SPEC-011 §2 items 7, 10); what it compiles is what its record says ran a compiler. + auto [g, built] = s::recorded(ws, {"test", "--workspace"}, "g"); expect(fatal(e2e::succeeded(g))); expect(eq(graph_dirs(ws).front(), dir)) << "the test build used another directory"; - expect(eq(core_edges(dir), before)) << "test --workspace compiled core again"; + expect(std::ranges::none_of(built.compiled, [](const std::string& c) { return c.ends_with("/src/core.m.o"); })) + << "test --workspace compiled core again"; expect(eq(runs(), 1u)) << "test --workspace ran core's build program again"; expect(e2e::contains(s::text(g), "workspace result ok. 3 member(s); 2 passed")); }; @@ -461,8 +463,12 @@ int main() { expect(fatal(e2e::succeeded(ws.mcpp({"test", "-p", "app"})))); expect(fatal(e2e::succeeded(ws.mcpp({"test", "-p", "app"})))); expect(eq(gen_edges(), 2)) << "one member's unchanged tests compiled the shared module again"; - expect(fatal(e2e::succeeded(ws.mcpp({"build"})))); - expect(eq(gen_edges(), 2)) << "mcpp build after the tests compiled the shared module again"; + // The build is a selection of its own, whose plan places what the tests' run compiled + // (SPEC-011 §2 items 7, 10); what it compiles is what its record says ran a compiler. + auto [b, built] = s::recorded(ws, {"build"}, "build"); + expect(fatal(e2e::succeeded(b))); + expect(std::ranges::none_of(built.compiled, [](const std::string& c) { return c.ends_with("/core/gen.m.o"); })) + << "mcpp build after the tests compiled the shared module again"; }; "1095 the guide at a workspace root plans nothing"_test[s::gcc] = [] { From 3af7c047cee30faf84b2e22d064c03b4d28649ab Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 18:05:35 +0900 Subject: [PATCH 26/36] A replayed build waits under the project's [build] lock_wait, as a planned build does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fast path took the build directory's and the plan's locks before any manifest was read by the planner, so the project's tier of the wait limit was never stated and a replay waited for a holder without end. The manifest the replay reads gives the limit of the build's root, the workspace's in a workspace, and it is stated before the locks are taken (SPEC-011 §2.1 item 3). --- docs/specs/concurrency.md | 5 +++-- src/build/execute.cppm | 24 ++++++++++++++++++------ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/specs/concurrency.md b/docs/specs/concurrency.md index d9ea9f566..b1bb57f2d 100644 --- a/docs/specs/concurrency.md +++ b/docs/specs/concurrency.md @@ -86,7 +86,8 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 3. 等待的上限是一个时长(`0` 表示不等待),按 [SPEC-004](manifest-semantics.md) §2 的 四层取第一个写明的:覆盖(`--lock-wait`、`MCPP_LOCK_WAIT`)、工程(`mcpp.toml` 的 `[build] lock_wait`)、机器(`config.toml` 的 `[build] lock_wait`);都没有写明时等到 - 持有者放手。 + 持有者放手。工程层取自构建的根(工作区中为工作区的清单);快速路径**必须**在取得锁之前写明它, + 与完整规划在取得锁之前写明它相同。 4. 超过上限的运行**必须**以 `[lock-wait-exceeded]` 被拒绝,消息写出持有者与上限的出处。 提供者自己的锁**必须**受同一上限约束(`XLINGS_LOCK_TIMEOUT`,以整秒计)。 @@ -215,4 +216,4 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 1.2 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#952,设计 2026-11-19 §10):§5.1 第 6 条不可观察单元的恢复与报告、拒绝写出个数与出路;第 8 条输出可重定向的工具链上编译写入尝试私有的路径并由执行器发布;第 9 条清理退役运行状态;第 10 条准入的条件、执行器的结束原因与不能声明单元的环境;第 11 条编译器的记录由执行器写为依赖文件,第 12 条程序的文本在执行器中解码为 UTF-8(mcpp#970,设计 2026-11-19 §20)。 | | 1.3 | 2026-12-04 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7):§2.1 每一次等待经同一原语、按时刻报告、持有者记录为提示、四层上限与 `[lock-wait-exceeded]`、提供者的锁受同一上限;§2.2 不能加锁时立即以 `[lock-unavailable]` 拒绝;§6 完整的标准库模块条目不加锁读取。 | | 1.4 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7.1):§2 第 5 条改正为 `mcpp test` 在测试运行之前释放锁;第 7 至 10 条计划的锁、计划的目录、整体操作的排他持有与两个计划共有的单元;§3 链接的临时名与归档的原子发布;§5.1 第 13 条运行与恢复属于计划。 | -| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得;§3 链接写进程自己的子目录中的产物名,而非临时文件名。 | +| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得;§3 链接写进程自己的子目录中的产物名,而非临时文件名;§2.1 第 3 条 快速路径在取得锁之前写明工程层的上限。 | diff --git a/src/build/execute.cppm b/src/build/execute.cppm index f53fbb685..83213cdd7 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -2965,6 +2965,10 @@ struct FastPathIdentity { // `[test] files`, unconditional or conditional (design 2026-11-16 §5.3): // the tests' working directories are prepared on the full path. bool testFiles = false; + // `[build] lock_wait` of the build's root, the workspace's in a workspace, + // as written: the project's tier of the wait limit (SPEC-011 §2), which a + // replay states before its locks as the full path states it before its own. + std::string lockWait; }; std::optional @@ -2994,6 +2998,7 @@ fast_path_identity(const std::filesystem::path& projectRoot, }()), !m->testFiles.empty() || std::ranges::any_of(m->conditionalConfigs, [](auto const& cc) { return !cc.testFiles.empty(); }), + effective->workspace ? effective->workspace->buildConfig.lockWait : m->buildConfig.lockWait, }; } @@ -3219,9 +3224,16 @@ export struct ReplayableBuild { // (design 2026-11-27 §3.7.1): the configuration's directory alone, or the // directory shared and the plan's own lock alone. Taken before admission: a // build of the plan that held them may have rewritten the graph while this -// one waited, and the record is judged against what is there now. +// one waited, and the record is judged against what is there now. They are +// waited for under the project's limit, read from the manifest this replay +// read; a value that is not a duration states nothing here, and the full path, +// which the changed manifest sends the build to, refuses it. using ReplayLocks = std::vector>; -std::expected replay_locks(const BuildCacheEntry& e) { +std::expected replay_locks(const BuildCacheEntry& e, + const FastPathIdentity& want) { + if (!want.lockWait.empty()) + if (const auto limit = mcpp::home::parse_wait(want.lockWait)) + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Project, limit, "[build] lock_wait in mcpp.toml"); const std::filesystem::path outputDir(e.outputDir); ReplayLocks held; auto dir = mcpp::build::dirlock::acquire(outputDir, /*shared=*/!e.planState.empty()); @@ -3416,7 +3428,7 @@ export std::optional try_fast_build(const std::filesystem::path& projectRoo // replay_locks). Not taken (the wait limit, or a directory that cannot be // locked): the command refuses here rather than waiting again on the full // path. - auto buildLock = replay_locks(*match); + auto buildLock = replay_locks(*match, *want); if (!buildLock) { mcpp::ui::error(mcpp::build::dirlock::refused(buildLock.error())); return 1; @@ -3531,7 +3543,7 @@ export std::optional try_fast_workspace_build( // Each group's directory under its own locks (replay_locks). Groups // are visited in one order by every command, so two never wait on // each other. - auto groupLock = replay_locks(*match); + auto groupLock = replay_locks(*match, *want); if (!groupLock) { mcpp::ui::error(mcpp::build::dirlock::refused(groupLock.error())); return 1; @@ -3792,7 +3804,7 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, // Under the directory's lock while ninja writes it, released before the // program starts: a program that runs for an hour holds nothing, and a // build of the same configuration meanwhile proceeds (mcpp#839). - auto buildLock = replay_locks(*match); + auto buildLock = replay_locks(*match, *want); if (!buildLock) { mcpp::ui::error(mcpp::build::dirlock::refused(buildLock.error())); return kRunBuildFailed; @@ -7558,7 +7570,7 @@ fast_test_plan(const std::filesystem::path& projectRoot, const TestOptions& test if (recordedNames != discoveredNames) return declined("the package's tests are not the recorded ones"); // A lock not taken declines: the full path refuses with it. - auto testLock = replay_locks(*match); + auto testLock = replay_locks(*match, *want); if (!testLock) return declined(testLock.error().message()); ctx.buildLock = testLock->front(); if (testLock->size() > 1) ctx.planLock = testLock->back(); From 59751b9d57536fdf207e0a29a4d4b187712648cd Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 18:05:35 +0900 Subject: [PATCH 27/36] A toolchain's package in [xlings.workspace] is compared by its version, without its namespace An entry is held as the environment file carries it, the version qualified by its namespace (`xim:16.1.0`), so `"xim:gcc" = "16.1.0"` beside gcc@16.1.0 was said to name a second version, and the note printed `gcc = "xim:15.1.0"`. The version is compared without the namespace, an entry of another namespace names another package, and the note writes the key and the version as written. --- src/build/prepare/local_toolchain.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/build/prepare/local_toolchain.cpp b/src/build/prepare/local_toolchain.cpp index 7f3c588d9..06d16279a 100644 --- a/src/build/prepare/local_toolchain.cpp +++ b/src/build/prepare/local_toolchain.cpp @@ -486,16 +486,22 @@ void step2_toolchain_in_workspace(PrepareState& state) { auto spec = mcpp::toolchain::parse_toolchain_spec(*state.tcSpec); if (!spec || spec->version.empty() || spec->version == "system") return; const auto pkg = mcpp::toolchain::to_xim_package(*spec); - for (auto const& [key, value] : state.m->xlings.workspace) { - const auto name = key.contains(':') ? key.substr(key.find(':') + 1) : key; - if (name != pkg.ximName || value.empty()) continue; + // An entry is held as the environment file carries it: the package, and + // `[:]`. A toolchain is a package of `xim`, so an entry + // of another namespace names another package. + for (auto const& [name, pin] : state.m->xlings.workspace) { + const auto colon = pin.find(':'); + const auto ns = colon == std::string::npos ? std::string() : pin.substr(0, colon); + const auto version = colon == std::string::npos ? pin : pin.substr(colon + 1); + if (name != pkg.ximName || version.empty() || (!ns.empty() && ns != "xim")) continue; // A version prefix names the versions it begins (`22` holds 22.1.8). - const bool same = pkg.ximVersion == value || pkg.ximVersion.starts_with(value + "."); + const bool same = pkg.ximVersion == version || pkg.ximVersion.starts_with(version + "."); if (same) continue; + const auto key = ns.empty() ? name : std::format("\"{}:{}\"", ns, name); mcpp::diag::notice(mcpp::diag::Severity::Note, "xlings/package-at-two-versions", name, std::format("{} is named twice: [toolchain] uses {}@{}, which compiles this build, and " "[xlings.workspace] names {} = \"{}\", which is on the PATH of the programs the " - "build starts", name, name, pkg.ximVersion, key, value), + "build starts", name, name, pkg.ximVersion, key, version), "drop one of the two, or keep both where both are wanted"); } } From 7baf9314686b3a382c8a515bf4698f9a1b4735c7 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 18:05:35 +0900 Subject: [PATCH 28/36] e2e: every surface item a case can reach is used by a passing case The full gate's surface ledger named nine items no passing case used: --lock-wait and [build] lock_wait, plan_locks and batch_fetch as manifest keys, the refusals lock-unavailable, package-without-description and toolchain-has-no-archiver, and the notes of a tree that holds two families and of a package named at two versions. Each is now a criterion of the case of its feature. --- tests/e2e/index/local.cpp | 17 ++++++++++- tests/e2e/pack/library.cpp | 11 +++++++ tests/e2e/self/config.cpp | 32 ++++++++++++++++++- tests/e2e/toolchain/custom.cpp | 41 +++++++++++++++++++++++-- tests/e2e/workspace/graph.cpp | 56 +++++++++++++++++++++++++++++++--- 5 files changed, 148 insertions(+), 9 deletions(-) diff --git a/tests/e2e/index/local.cpp b/tests/e2e/index/local.cpp index e561ff064..524cc1c6c 100644 --- a/tests/e2e/index/local.cpp +++ b/tests/e2e/index/local.cpp @@ -363,7 +363,8 @@ exit 0 // resolution knows are fetched by one call of the provider (`batch-fetch`). On a terminal // the screen the bytes leave holds one `Downloading` line for each, under its manifest // name, and no frame of the live region, although the provider writes a line of its own - // to its standard error while it downloads. A second build calls no provider. + // to its standard error while it downloads. A second build calls no provider. Under + // `[build] batch_fetch = "each"` a call names one dependency. const auto tmp = s::case_dir(); const auto home = s::case_home(s::home::inherited); s::project index(tmp / "local-index", { @@ -439,6 +440,20 @@ exit 0 expect(fatal(e2e::succeeded(again))) << s::text(again); expect(s::count_lines(s::read_file(log), "{") == 1u) << "the second build called the provider:\n" << s::read_file(log); expect(s::lacks(s::text(again), "Downloading")) << "the second build fetched: " << s::text(again); + + // `[build] batch_fetch = "each"` turns the entry off: a call of the provider names one + // dependency. + s::project each(tmp / "project/each", { + {"src/main.cpp", app.read("src/main.cpp")}, + {"mcpp.toml", app.read("mcpp.toml") + "\n[build]\nbatch_fetch = \"each\"\n"}}); + const auto eachLog = tmp / "fake-install-each.log"; + auto one = each.mcpp({"build"}, inherited({{"FAKE_INSTALL_LOG", eachLog.string()}})); + expect(fatal(e2e::succeeded(one))) << s::text(one); + const auto eachCalls = s::read_file(eachLog); + expect(fatal(s::count_lines(eachCalls, "{") >= 1u)) << "the dependencies were not fetched:\n" << eachCalls; + expect(s::count_lines(eachCalls, "compat.one@") + s::count_lines(eachCalls, "compat.two@") + == s::count_lines(eachCalls, "{")) + << "a call named both dependencies under batch_fetch = \"each\":\n" << eachCalls; }; }}; diff --git a/tests/e2e/pack/library.cpp b/tests/e2e/pack/library.cpp index f1186eed2..065d09717 100644 --- a/tests/e2e/pack/library.cpp +++ b/tests/e2e/pack/library.cpp @@ -924,6 +924,17 @@ version = "0.1.0" e2e::expect_diagnostic("\\[not-a-package-of-mcpp-pack\\]"); r = lib.mcpp({"emit", "xpkg", "--package", foreign.string(), "--url", "https://example.org"}); expect(failed(r) && e2e::contains(s::text(r), "foreign-0.1.tar.gz")) << s::text(r); + // A library package an earlier mcpp wrote: its manifest names the writer, and it carries + // no description. + const auto earlier = tmp / "earlier-0.1.tar.gz"; + s::write_executable(tmp / "make-earlier.sh", std::format( + "#!/bin/sh\nset -e\nmkdir -p '{0}/earlier-0.1'\n" + "printf '# Generated by `2026.11.22.1`. Do not edit.\\n[package]\\nname = \"earlier\"\\nversion = \"0.1\"\\n'" + " > '{0}/earlier-0.1/mcpp.toml'\ntar -C '{0}' -czf '{1}' earlier-0.1\n", tmp.string(), earlier.string())); + expect(fatal(s::run(tmp / "make-earlier.sh").status == 0)); + e2e::expect_diagnostic("\\[package-without-description\\]"); + r = lib.mcpp({"emit", "xpkg", "--package", earlier.string(), "--url", "https://example.org"}); + expect(failed(r) && e2e::contains(s::text(r), "is a library package mcpp 2026.11.22.1 wrote")) << s::text(r); e2e::expect_diagnostic("\\[emit-inside-a-package\\]"); r = s::mcpp({"emit", "xpkg"}, *pkg); expect(failed(r)) << "emit xpkg in a library package's directory was not refused: " << s::text(r); diff --git a/tests/e2e/self/config.cpp b/tests/e2e/self/config.cpp index ef42fcca2..92825cb7f 100644 --- a/tests/e2e/self/config.cpp +++ b/tests/e2e/self/config.cpp @@ -1,6 +1,7 @@ // A home's configuration: `self env` and `self init`, the mirror chosen without a bootstrap, the // index migrated and healed in config.toml and the registry's .xlings.json, and a project's -// xlings environment materialised (formerly tests/e2e/10, 38, 39, 46, 88, 151). +// xlings environment materialised, with a package it names at another version than the toolchain +// said once (formerly tests/e2e/10, 38, 39, 46, 88, 151). import std; import mcpplibs.mtest; import mcpp.test.support; @@ -138,6 +139,35 @@ E2E config{"config", s::home_fixture, [] { expect(fatal(e2e::contains(s::text(r), "[xlings.workspace]"))) << "no advisory for [xlings] deps: " << s::text(r); }; + "a package the toolchain and the environment name at two versions is said once"_test[s::gcc] = [] { + // Design 2026-11-27 D8: `[toolchain]` names the compiler of the build and + // `[xlings.workspace]` a package on the PATH of the programs it starts. The same version, or + // a prefix of it, says nothing; another version is said once per project, with the key as + // written. The entry is provided on request, so the case installs no second compiler. + const auto gcc = s::gcc_version(); + const std::string other = gcc.starts_with("15.") ? "16.1.0" : "15.1.0"; + s::project app(s::case_dir() / "app", {{"src/main.cpp", "int main() { return 0; }\n"}}); + auto manifest = [&](std::string_view version) { + app.write("mcpp.toml", std::format( + "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[toolchain]\ndefault = \"gcc@{}\"\n\n" + "[xlings.workspace]\n\"xim:gcc\" = {{ version = \"{}\", provision = \"on-request\" }}\n", gcc, version)); + }; + manifest(gcc.substr(0, gcc.find('.'))); + auto r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::lacks(s::text(r), "is named twice")) << "a version the toolchain's begins with was said: " << s::text(r); + manifest(other); + r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(e2e::contains(s::text(r), std::format("gcc is named twice: [toolchain] uses gcc@{}", gcc)) + && e2e::contains(s::text(r), std::format("names \"xim:gcc\" = \"{}\"", other))) + << "the two versions were not said as written: " << s::text(r); + app.write("src/main.cpp", "int main() { return 0; }\n// edit\n"); + r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::lacks(s::text(r), "is named twice")) << "the note was said again: " << s::text(r); + }; + "151 index url artifact migration"_test[s::python3] = [] { // A fresh seed names the new index url and its region artifact in both files; an old org // url is healed (idempotently, unrelated keys kept); a compact legacy entry is renamed and diff --git a/tests/e2e/toolchain/custom.cpp b/tests/e2e/toolchain/custom.cpp index 544f9639e..8c27a775e 100644 --- a/tests/e2e/toolchain/custom.cpp +++ b/tests/e2e/toolchain/custom.cpp @@ -40,7 +40,7 @@ E2E custom{"custom", s::home_fixture, [] { // with its launcher and its stated linker, is reported as custom, writes nothing into the // tree, keeps the fast path until one of its programs changes, is named by MCPP_TOOLCHAIN // too, and is identified (a contradicting family, a tree with no driver, and a gcc tree - // that states ld are refused). + // that states ld are refused; a tree that holds both families is said once). 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(); @@ -98,6 +98,17 @@ E2E custom{"custom", s::home_fixture, [] { write_manifest(work / "empty", ""); out = s::text(app.mcpp({"build"}, o)); expect(fatal(e2e::contains(out, "no C++ driver in bin/"))) << "FAIL: a tree without a driver was accepted: " << out; + // A tree that holds both families (`/usr`) builds with clang and says so, with the key + // that takes gcc (design 2026-11-27 §10.2). + s::write_executable(T / "bin/g++", "#!/bin/sh\necho 13.2.0\n"); + write_manifest(T, ""); + app.remove("target"); + r = app.mcpp({"build"}, o); + out = s::text(r); + expect(fatal(e2e::succeeded(r))) << "FAIL: a tree that holds both families did not build: " << out; + expect(fatal(e2e::contains(out, "and gcc 13.2.0; clang is used"))) << "FAIL: the two families were not said: " << out; + expect(fatal(e2e::contains(out, "`family = \"gcc\"` in the [toolchain] table uses the other"))) << "FAIL: " << out; + fs::remove(T / "bin/g++"); // The newest numeric gcc of ~/.mcpp, when it has a g++. const auto gcc_base = fs::path(s::env("HOME").value_or("")) / ".mcpp/registry/data/xpkgs/xim-x-gcc"; std::string gcc_ver; @@ -225,7 +236,9 @@ E2E custom{"custom", s::home_fixture, [] { // stated archiver that reads `@file` as a member's name is given the expanded words; `mcpp // why toolchain` names each with its source; the layer report says `custom`. A driver that // refuses a module unit builds a program of no modules and refuses a module unit at - // planning with `[compiler-without-modules]`, naming the file. + // planning with `[compiler-without-modules]`, naming the file. A tree without an archiver + // takes the host's, reported, and with none on PATH either is refused with + // `[toolchain-has-no-archiver]`. 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(); @@ -287,6 +300,30 @@ E2E custom{"custom", s::home_fixture, [] { expect(fatal(!e2e::succeeded(r))) << "a module unit was accepted: " << out; expect(e2e::contains(out, "src/extra.cppm")) << out; expect(e2e::contains(out, "this driver takes no module unit")) << out; + + // A tree without an archiver. + const auto bare = work / "no-archiver"; + llvm_tree(bare); + for (std::string n : {"llvm-ar", "ar"}) fs::remove(bare / "bin" / n); + s::project lone(work / "lone", {{"src/main.cpp", "int main() { return 0; }\n"}}); + lone.write("mcpp.toml", std::format("[package]\nname = \"lone\"\nversion = \"0.1.0\"\n\n[toolchain]\n" + "default = {{ path = \"{}\" }}\n", bare.string())); + if (s::on_path("ar") || s::on_path("llvm-ar")) { + e2e::expect_diagnostic("the archiver for this build is the host's"); + r = lone.mcpp({"build"}, o); + out = s::text(r); + expect(fatal(e2e::succeeded(r))) << "a tree without an archiver did not take the host's: " << out; + expect(e2e::contains(out, "the archiver for this build is the host's")) << out; + lone.remove("target"); + } else { + std::println("note: no archiver on PATH, so the host's archiver is not exercised here"); + } + fs::create_directories(work / "no-tools"); + e2e::expect_diagnostic("\\[toolchain-has-no-archiver\\]"); + r = lone.mcpp({"build"}, {.env = {{"NO_COLOR", "1"}, {"PATH", (work / "no-tools").string()}}}); + out = s::text(r); + expect(fatal(!e2e::succeeded(r))) << "a tree with no archiver anywhere was accepted: " << out; + expect(e2e::contains(out, "[toolchain-has-no-archiver]") && e2e::contains(out, "llvm-ar")) << out; }; "a library packed with a tree named by path gets no index entry"_test[s::llvm] = [] { diff --git a/tests/e2e/workspace/graph.cpp b/tests/e2e/workspace/graph.cpp index 97d46d580..db7b1bbd1 100644 --- a/tests/e2e/workspace/graph.cpp +++ b/tests/e2e/workspace/graph.cpp @@ -743,10 +743,13 @@ int main() { // Design 2026-11-27 §3.7.1, SPEC-011 §2 items 7 to 10. A: while member a's plan is held, // a build of member b proceeds without waiting, and places the unit of the library both // reach instead of compiling it. B: a build of a waits for a's plan, and one that may not - // wait is refused naming the plan. C: a plan build holds the configuration shared, so a - // shared holder does not stop it; D: `--cache off` holds the configuration alone, and - // waits for a shared holder. E: `mcpp why toolchain` states the holding and its reason, - // and the entry's parameter turns it off. + // wait (`--lock-wait 0`) is refused naming the plan and the limit. C: a plan build holds the + // configuration shared, so a shared holder does not stop it; D: `--cache off` holds the + // configuration alone, and waits for a shared holder. E: `mcpp why toolchain` states the + // holding and its reason, and the entry's parameter turns it off. F: a plan's lock the + // system refuses to create is refused at once with `[lock-unavailable]`. G: a rooted + // workspace's `[build] plan_locks` turns the entry off, and its `[build] lock_wait` bounds + // the wait of a build that replays its record. const auto tmp = s::case_dir(); s::project ws(tmp / "ws", { {"mcpp.toml", "[workspace]\nmembers = [\"a\", \"b\", \"c\"]\n"}, @@ -788,10 +791,11 @@ int main() { for (const auto& c : built.compiled) compiled += c + "\n"; expect(s::no_line(compiled, "^c ")) << "A: b compiled the library a's build compiled:\n" << compiled; ws.write("a/src/main.cpp", ws.read("a/src/main.cpp") + "// edit\n"); - r = ws.mcpp({"build", "-p", "a"}, noWait); + r = ws.mcpp({"build", "-p", "a", "--lock-wait", "0"}); expect(fatal(failed(r))) << "B: a was built while its plan was held"; expect(e2e::contains(s::text(r), "lock-wait-exceeded")) << "B: the refusal carries no reason token: " << s::text(r); expect(e2e::contains(s::text(r), "the plan of member 'a'")) << "B: the refusal does not name the plan: " << s::text(r); + expect(e2e::contains(s::text(r), "the limit --lock-wait states")) << "B: the refusal does not name the limit: " << s::text(r); } { auto held = hold(dir / ".mcpp-build.lock", "shared"); @@ -808,6 +812,48 @@ int main() { r = ws.mcpp_in("a", {"why", "toolchain"}, {.env = {{"MCPP_PLAN_LOCKS", "configuration"}}}); expect(fatal(e2e::succeeded(r))) << "E: " << s::text(r); expect(s::has_line(r.out, "plan locks: configuration \\(plan-locks is off")) << "E: the entry's parameter did not turn it off: " << r.out; + + // F: the plan's directory admits no new file (POSIX permissions; a user they do not bind is + // said and the criterion not held). + const auto planLock = plans.front() / ".mcpp-plan.lock"; + fs::remove(planLock); + fs::permissions(plans.front(), fs::perms::owner_write | fs::perms::group_write | fs::perms::others_write, + fs::perm_options::remove); + if (std::ofstream(plans.front() / ".probe")) { + fs::remove(plans.front() / ".probe"); + std::println("note: this user writes into a directory without write permission, so F is not held here"); + } else { + ws.write("a/src/main.cpp", ws.read("a/src/main.cpp") + "// edit\n"); + e2e::expect_diagnostic("\\[lock-unavailable\\]"); + r = ws.mcpp({"build", "-p", "a"}); + expect(failed(r)) << "F: a was built without its plan's lock"; + expect(e2e::contains(s::text(r), "[lock-unavailable]") && e2e::contains(s::text(r), planLock.string())) + << "F: the refusal does not name the lock and its token: " << s::text(r); + } + fs::permissions(plans.front(), fs::perms::owner_write, fs::perm_options::add); + + // G: the root's [build] states both. + s::project rooted(tmp / "rooted", { + {"mcpp.toml", "[package]\nname = \"r\"\nversion = \"0.1.0\"\n\n[workspace]\nmembers = [\"m\"]\n\n" + "[build]\nplan_locks = \"configuration\"\nlock_wait = \"0\"\n"}, + {"src/main.cpp", "int main() { return 0; }\n"}, + {"m/mcpp.toml", "[package]\nname = \"m\"\nversion = \"0.1.0\"\n"}, + {"m/src/main.cpp", "int main() { return 0; }\n"}, + }); + r = rooted.mcpp({"why", "toolchain"}); + expect(fatal(e2e::succeeded(r))) << "G: " << s::text(r); + expect(s::has_line(r.out, "plan locks: configuration \\(plan-locks is off")) << "G: [build] plan_locks did not turn it off: " << r.out; + r = rooted.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "G: the rooted workspace did not build: " << s::text(r); + const auto rootedDirs = graph_dirs(rooted.dir()); + expect(fatal(rootedDirs.size() == 1u)) << "G: expected one build directory, got " << rootedDirs.size(); + { + auto held = hold(rootedDirs.front() / ".mcpp-build.lock", "alone"); + rooted.write("src/main.cpp", "int main() { return 0; }\n// edit\n"); + r = rooted.mcpp({"build"}); + expect(fatal(failed(r))) << "G: the replay waited past [build] lock_wait or built under the holder"; + expect(e2e::contains(s::text(r), "the limit [build] lock_wait in mcpp.toml states")) << "G: " << s::text(r); + } }; }}; From 8d0e8c4b37cd3d7f08f38265c5f07ec6693f4371 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 20:00:30 +0900 Subject: [PATCH 29/36] e2e: a provider line written before the first frame leaves no Planning line on a terminal (mcpp#1042) The fetch-waves case writes a line of the provider to standard error before its first progress frame, while only the Planning line of the live region is drawn, as the report of mcpp#1042 shows on 2026.11.22.1. The screen the bytes leave holds no Planning line, no bar and each provider line at most once. --- CHANGELOG.md | 3 ++- tests/e2e/index/local.cpp | 12 ++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a9c0583c..78937a864 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,7 +116,8 @@ - Fetching the dependencies prints one line per dependency under its manifest name, with no announcement before the provider downloads, and `Updating` when its revision changes; the dependencies known at one step are fetched in one call to the provider. The provider's lines - reach standard error through mcpp's one writer. + reach standard error through mcpp's one writer, so a terminal keeps no frame of the live + region (the `Planning` line, a download's bar) beside them (mcpp#1042). - A standard library module whose record is complete is read without taking its lock; the record is written by a rename and lists the files of the entry. - Commands that select different members of a workspace build one configuration at once. Each diff --git a/tests/e2e/index/local.cpp b/tests/e2e/index/local.cpp index 524cc1c6c..627107ab0 100644 --- a/tests/e2e/index/local.cpp +++ b/tests/e2e/index/local.cpp @@ -362,8 +362,9 @@ exit 0 // Design 2026-11-27 §3.11.2 items 5 and 9. The two dependencies the first step of the // resolution knows are fetched by one call of the provider (`batch-fetch`). On a terminal // the screen the bytes leave holds one `Downloading` line for each, under its manifest - // name, and no frame of the live region, although the provider writes a line of its own - // to its standard error while it downloads. A second build calls no provider. Under + // name, and no frame of the live region (a download's bar, or the `Planning` line drawn + // before the first bar), although the provider writes lines of its own to its standard + // error before its first frame and while it downloads. A second build calls no provider. Under // `[build] batch_fetch = "each"` a call names one dependency. const auto tmp = s::case_dir(); const auto home = s::case_home(s::home::inherited); @@ -393,6 +394,7 @@ if [[ "${1:-}" == "interface" && "${2:-}" == "install_packages" ]]; then frame() { printf '{"kind":"data","dataKind":"download_progress","payload":{"elapsedSec":%s,"files":[{"name":"compat:compat.one@1.0.0","downloadedBytes":%s,"totalBytes":%s,"started":true,"finished":%s},{"name":"compat:compat.two@1.0.0","downloadedBytes":%s,"totalBytes":%s,"started":true,"finished":%s}]}}\n' "$@" } + echo "Source compat:compat.two@1.0.0 example.invalid (attempt 1)" >&2 frame 0.1 0 0 false 0 0 false echo "Source compat:compat.one@1.0.0 example.invalid (attempt 1)" >&2 frame 0.4 512 1024 false 0 0 false @@ -433,8 +435,10 @@ exit 0 for (const auto& row : s::screen_of(build.terminal())) shown += row + "\n"; for (std::string_view dep : {"compat.one v1.0.0", "compat.two v1.0.0"}) expect(s::count_matching(shown, std::format("Downloading +{}", dep)) == 1u) << "not one line for " << dep << ":\n" << shown; - expect(s::no_line(shown, "connecting|\\[[=> -]+\\]")) << "a frame of the live region was left on the screen:\n" << shown; - expect(s::count_lines(shown, "example.invalid (attempt 1)") <= 1u) << "the provider's line was written more than once:\n" << shown; + expect(s::no_line(shown, "connecting|\\[[=> -]+\\]|Planning")) << "a frame of the live region was left on the screen:\n" << shown; + for (std::string_view dep : {"compat.one@1.0.0", "compat.two@1.0.0"}) + expect(s::count_lines(shown, std::format("{} example.invalid (attempt 1)", dep)) <= 1u) + << "the provider's line for " << dep << " was written more than once:\n" << shown; auto again = app.mcpp({"build"}, inherited({{"FAKE_INSTALL_LOG", log.string()}})); expect(fatal(e2e::succeeded(again))) << s::text(again); From e37e537e0fb818d5b8a4503964f2a07c0d67782c Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 20:00:31 +0900 Subject: [PATCH 30/36] e2e: 992 states its own time limit; the suite keeps its 600 s bound for a hang 992 packs one file for every system and compiles the openkal stack once per leg. On the Linux runners it took 465 s to 885 s and once passed 900 s; 2026.11.22.1 and 2026.12.4.1 take the same wall clock for its pack on one machine, so the time is the case's work. The case states 25 minutes in tests/e2e/mtest.toml, which mtest applies before the run's --timeout; the suite returns to run_all.sh's 600 s, and the step's limit is above the case's. --- .github/workflows/ci-linux-e2e.yml | 15 +++++---------- tests/e2e/mtest.toml | 7 +++++++ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci-linux-e2e.yml b/.github/workflows/ci-linux-e2e.yml index ceca0eae0..e26b82f00 100644 --- a/.github/workflows/ci-linux-e2e.yml +++ b/.github/workflows/ci-linux-e2e.yml @@ -117,9 +117,11 @@ jobs: coverage: ${{ inputs.coverage }} - name: E2E suite - # About twice the shard's budget of ten minutes (R4): reached only by a - # hang. The per-test 600 s limit in run_all.sh names the test that hung. - timeout-minutes: 22 + # About twice the shard's budget of ten minutes (R4), and above the + # longest limit a case states (992, 25 minutes, tests/e2e/mtest.toml): + # reached only by a hang. The per-test 600 s limit in run_all.sh names + # the test that hung. + timeout-minutes: 30 run: | set -euo pipefail # MCPP is this commit's binary and MCPP_BOOT the released bootstrap @@ -132,13 +134,6 @@ jobs: # the global mirror while mcpp's default remains CN for fresh local # sandboxes. E2E tests with their own MCPP_HOME read this variable. export MCPP_E2E_TOOLCHAIN_MIRROR=GLOBAL - # 992 packs one image for every system, so it compiles the openkal - # stack once per leg. It took 465.6 s on 2026-11-24 (main, green) and - # has passed the 600 s limit on every runner since 2026-11-25, with - # and without a warm sandbox (main at 5032751e and 5d5c125c fail it - # alike). 900 s keeps the hung-test bound and leaves the shard well - # inside this step's 22 minutes. - export E2E_TEST_TIMEOUT=900 "$MCPP" self config bash tests/e2e/run_all.sh diff --git a/tests/e2e/mtest.toml b/tests/e2e/mtest.toml index 5d9d9d878..7d3bf9951 100644 --- a/tests/e2e/mtest.toml +++ b/tests/e2e/mtest.toml @@ -21,6 +21,13 @@ timeout = "10m" tags_from = { "# requires:" = "requires:" } resources_from = ["# resources:"] +# A CASE'S OWN TIME LIMIT comes before the run's (`run --timeout`, run_all.sh's bound for a hang, +# 600 s). 992 packs one file for every system, so it compiles the openkal stack once per leg: on the +# four-processor Linux runners it took 465 s to 885 s from 2026-11-24 to 2026-12-05 and once passed +# 900 s, while 2026.11.22.1 and 2026.12.4.1 take the same wall clock for its pack on one machine. +[cases."992_a_polyglot_file_runs_on_every_system_it_holds.sh"] +timeout = "25m" + # The shards of each host CI starts (ci.yml e2e-plan, `mtest ci plan`): the # selection's measured time there divided by `shard`, at most `max_shards`; a # case a host never ran counts `unknown`. The names are those the runs record. From ea85fff2579ce7a32aa74392d8b3ee0a790cc691 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 20:07:34 +0900 Subject: [PATCH 31/36] [build] lock_wait is the build's root's, the selected member's in a workspace, as every configuration key is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under a workspace root without [package], the root's [build] lock_wait was read while the same table was reported as acting on no package, and a member's own limit was not read; cache, jobs, batch_fetch and plan_locks were already the selected member's (SPEC-004 §9 item 10). Prepare states the limit after the selection and before the first lock, naming the member's manifest when the value is no duration, and a replay takes the member's. SPEC-011 §2.1 item 3, docs/25 and the CHANGELOG state it; e2e 1179 holds it (criterion H). --- CHANGELOG.md | 12 ++++++----- docs/25-home-indices-and-store.md | 4 ++++ docs/specs/concurrency.md | 7 ++++--- docs/zh/25-home-indices-and-store.md | 3 +++ src/build/execute.cppm | 9 ++++---- src/build/prepare/manifest.cpp | 31 +++++++++++++++++----------- tests/e2e/workspace/graph.cpp | 24 ++++++++++++++++++++- 7 files changed, 65 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78937a864..daa3bf0ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,11 +31,13 @@ `lock-unavailable`, `vcs-unavailable`. - `--lock-wait ` (also `MCPP_LOCK_WAIT`, `[build] lock_wait` in `mcpp.toml` and in - `config.toml`) bounds every wait for a lock another run holds; past it the run is refused with - `[lock-wait-exceeded]`, naming the holder. A wait is reported after 300 ms and then at 10 s, - 30 s, 60 s and each minute, with the resource, the lock file and the last recorded holder, as a - `waiting` event under `--message-format json`. A file the system cannot lock is refused at once - with `[lock-unavailable]`, the system's reason and a remedy (SPEC-011). + `config.toml`; the project's is the build's root's, the selected member's in a workspace, as + every configuration key's) bounds every wait for a lock another run holds; past it the run is + refused with `[lock-wait-exceeded]`, naming the holder. A wait is reported after 300 ms and + then at 10 s, 30 s, 60 s and each minute, with the resource, the lock file and the last + recorded holder, as a `waiting` event under `--message-format json`. A file the system cannot + lock is refused at once with `[lock-unavailable]`, the system's reason and a remedy + (SPEC-011). - `mcpp new` makes the new project a git repository with nothing committed. `--vcs git|none` and `config.toml` `[new] vcs` state it; inside another git work tree or project, no repository is made unless one is stated. Without git the project is made and the missing repository diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index 4ef32ce4e..503e7db85 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -237,6 +237,10 @@ a duration (`30s`, `2m`, `1h`; `0` does not wait), taken from the first of: | project | `[build] lock_wait` in `mcpp.toml` | | machine | `[build] lock_wait` in `config.toml` | +The project's limit is the build's root's, as every configuration key is: in a +workspace, the selected member's. A workspace root without `[package]` states +none; its `[build]` acts on no package and is reported. + Past the limit the run is refused with `[lock-wait-exceeded]`, naming the holder and where the limit was stated. The provider's own locks are bounded by the same limit (`XLINGS_LOCK_TIMEOUT`). A lock file the system cannot lock -- a diff --git a/docs/specs/concurrency.md b/docs/specs/concurrency.md index b1bb57f2d..54e19279c 100644 --- a/docs/specs/concurrency.md +++ b/docs/specs/concurrency.md @@ -86,8 +86,9 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 3. 等待的上限是一个时长(`0` 表示不等待),按 [SPEC-004](manifest-semantics.md) §2 的 四层取第一个写明的:覆盖(`--lock-wait`、`MCPP_LOCK_WAIT`)、工程(`mcpp.toml` 的 `[build] lock_wait`)、机器(`config.toml` 的 `[build] lock_wait`);都没有写明时等到 - 持有者放手。工程层取自构建的根(工作区中为工作区的清单);快速路径**必须**在取得锁之前写明它, - 与完整规划在取得锁之前写明它相同。 + 持有者放手。工程层取自构建的根,与每个配置键相同(SPEC-004 §9 第 10 条):工作区中为被选中的 + 成员,不带 `[package]` 的工作区根不写明它;快速路径**必须**在取得锁之前写明它,与完整规划在 + 取得锁之前写明它相同。 4. 超过上限的运行**必须**以 `[lock-wait-exceeded]` 被拒绝,消息写出持有者与上限的出处。 提供者自己的锁**必须**受同一上限约束(`XLINGS_LOCK_TIMEOUT`,以整秒计)。 @@ -216,4 +217,4 @@ CI。在 2026.10.24.1 上,同一配置的两次冷构建相隔 0.1–0.5 s 启 | 1.2 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#952,设计 2026-11-19 §10):§5.1 第 6 条不可观察单元的恢复与报告、拒绝写出个数与出路;第 8 条输出可重定向的工具链上编译写入尝试私有的路径并由执行器发布;第 9 条清理退役运行状态;第 10 条准入的条件、执行器的结束原因与不能声明单元的环境;第 11 条编译器的记录由执行器写为依赖文件,第 12 条程序的文本在执行器中解码为 UTF-8(mcpp#970,设计 2026-11-19 §20)。 | | 1.3 | 2026-12-04 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7):§2.1 每一次等待经同一原语、按时刻报告、持有者记录为提示、四层上限与 `[lock-wait-exceeded]`、提供者的锁受同一上限;§2.2 不能加锁时立即以 `[lock-unavailable]` 拒绝;§6 完整的标准库模块条目不加锁读取。 | | 1.4 | 2026-12-05 | mcpp 2026.12.4.1(设计 2026-11-27 §3.7.1):§2 第 5 条改正为 `mcpp test` 在测试运行之前释放锁;第 7 至 10 条计划的锁、计划的目录、整体操作的排他持有与两个计划共有的单元;§3 链接的临时名与归档的原子发布;§5.1 第 13 条运行与恢复属于计划。 | -| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得;§3 链接写进程自己的子目录中的产物名,而非临时文件名;§2.1 第 3 条 快速路径在取得锁之前写明工程层的上限。 | +| 1.5 | 2026-12-05 | mcpp 2026.12.4.1:§2 第 11 条 一个进程对一个构建目录只持有一把锁,先共享后排他时放下共享持有再排他取得;§3 链接写进程自己的子目录中的产物名,而非临时文件名;§2.1 第 3 条 工程层的上限取自构建的根(工作区中为被选中的成员),快速路径在取得锁之前写明它。 | diff --git a/docs/zh/25-home-indices-and-store.md b/docs/zh/25-home-indices-and-store.md index b741aba34..74611c32e 100644 --- a/docs/zh/25-home-indices-and-store.md +++ b/docs/zh/25-home-indices-and-store.md @@ -185,6 +185,9 @@ locator 在本地校验成功后、获取资源之前保存。离线缺资源或 | 工程 | `mcpp.toml` 的 `[build] lock_wait` | | 机器 | `config.toml` 的 `[build] lock_wait` | +工程层的上限取自构建的根,与每个配置键相同:工作区中为被选中的成员。不带 `[package]` 的 +工作区根不写明它,它的 `[build]` 不作用于任何包,并被报告。 + 超过上限时运行以 `[lock-wait-exceeded]` 被拒绝,消息写出持有者与上限的出处。提供者自己的锁受同一 上限约束(`XLINGS_LOCK_TIMEOUT`)。系统无法加锁的锁文件 —— 没有写权限的目录、只读或不支持锁的 文件系统、描述符耗尽 —— 立即以 `[lock-unavailable]` 被拒绝,并给出系统的原因与补救:等待不会 diff --git a/src/build/execute.cppm b/src/build/execute.cppm index 83213cdd7..814da5f23 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -2965,9 +2965,10 @@ struct FastPathIdentity { // `[test] files`, unconditional or conditional (design 2026-11-16 §5.3): // the tests' working directories are prepared on the full path. bool testFiles = false; - // `[build] lock_wait` of the build's root, the workspace's in a workspace, - // as written: the project's tier of the wait limit (SPEC-011 §2), which a - // replay states before its locks as the full path states it before its own. + // `[build] lock_wait` of the build's root (the member in a workspace, as + // every configuration key, SPEC-004 §9 item 10), as written: the project's + // tier of the wait limit (SPEC-011 §2), which a replay states before its + // locks as the full path states it before its own. std::string lockWait; }; @@ -2998,7 +2999,7 @@ fast_path_identity(const std::filesystem::path& projectRoot, }()), !m->testFiles.empty() || std::ranges::any_of(m->conditionalConfigs, [](auto const& cc) { return !cc.testFiles.empty(); }), - effective->workspace ? effective->workspace->buildConfig.lockWait : m->buildConfig.lockWait, + m->buildConfig.lockWait, }; } diff --git a/src/build/prepare/manifest.cpp b/src/build/prepare/manifest.cpp index 764473787..0f01e9867 100644 --- a/src/build/prepare/manifest.cpp +++ b/src/build/prepare/manifest.cpp @@ -570,18 +570,6 @@ std::expected phase0_manifest_and_workspace(PrepareState& sta if (auto r = refuse_unknown_capability(*state.m, *state.root / "mcpp.toml"); !r) return r; - // The project's tier of the wait limit (`[build] lock_wait`), for every - // wait from here on; a host-tool sub-build plans under its root's. - if (!state.overrides.preloaded_manifest && !state.m->buildConfig.lockWait.empty()) { - const auto limit = mcpp::home::parse_wait(state.m->buildConfig.lockWait); - if (!limit) - return std::unexpected(std::format( - "{}: [build] lock_wait = \"{}\" is not a duration; expected a number with s, m, h or ms " - "(\"30s\", \"2m\"), or \"0\" for no wait", (*state.root / "mcpp.toml").string(), - state.m->buildConfig.lockWait)); - mcpp::home::state_wait_limit(mcpp::home::WaitSource::Project, limit, "[build] lock_wait in mcpp.toml"); - } - // A DISTRIBUTION package is not a source tree, and building "in" one is a // failure that looks like a success: `interface/` holds declarations whose // definitions are in the prebuilt archive, so the build compiles the @@ -605,6 +593,25 @@ std::expected phase0_manifest_and_workspace(PrepareState& sta if (auto r = step0_workspace_handling(state); !r) return std::unexpected(r.error()); + // The project's tier of the wait limit (`[build] lock_wait`), for every + // wait from here on. It is the build's root's, as every configuration key + // is (SPEC-004 §9 item 10): the selected member in a workspace, whose + // values the plan's root carries, so a workspace root without [package] + // states none. Stated after the selection and before the first lock; a + // host-tool sub-build plans under its root's. + if (!state.overrides.preloaded_manifest && !state.m->buildConfig.lockWait.empty()) { + const auto limit = mcpp::home::parse_wait(state.m->buildConfig.lockWait); + if (!limit) { + const auto written = (state.workspacePlan() + ? (*state.root / state.selectedMemberPaths.front() / "mcpp.toml").lexically_normal() + : *state.root / "mcpp.toml"); + return std::unexpected(std::format( + "{}: [build] lock_wait = \"{}\" is not a duration; expected a number with s, m, h or ms " + "(\"30s\", \"2m\"), or \"0\" for no wait", written.string(), state.m->buildConfig.lockWait)); + } + mcpp::home::state_wait_limit(mcpp::home::WaitSource::Project, limit, "[build] lock_wait in mcpp.toml"); + } + // A TEST PLAN OF ONE PACKAGE (mcpp#941): the package's `[test] features` // join the request of the package under test, as `--features` would state // them for this build; every reader of the root request sees them, and the diff --git a/tests/e2e/workspace/graph.cpp b/tests/e2e/workspace/graph.cpp index db7b1bbd1..93c644a6b 100644 --- a/tests/e2e/workspace/graph.cpp +++ b/tests/e2e/workspace/graph.cpp @@ -749,7 +749,8 @@ int main() { // holding and its reason, and the entry's parameter turns it off. F: a plan's lock the // system refuses to create is refused at once with `[lock-unavailable]`. G: a rooted // workspace's `[build] plan_locks` turns the entry off, and its `[build] lock_wait` bounds - // the wait of a build that replays its record. + // the wait of a build that replays its record. H: under a root without `[package]` the + // limit is the selected member's. const auto tmp = s::case_dir(); s::project ws(tmp / "ws", { {"mcpp.toml", "[workspace]\nmembers = [\"a\", \"b\", \"c\"]\n"}, @@ -854,6 +855,27 @@ int main() { expect(fatal(failed(r))) << "G: the replay waited past [build] lock_wait or built under the holder"; expect(e2e::contains(s::text(r), "the limit [build] lock_wait in mcpp.toml states")) << "G: " << s::text(r); } + + // H: under a root without [package] the limit is the selected member's, as every + // configuration key is. The root's [build] is reported and not read (its value is no + // duration); a's own bounds a build of a that replays its record. + e2e::expect_diagnostic("acts on no package"); + ws.write("mcpp.toml", "[workspace]\nmembers = [\"a\", \"b\", \"c\"]\n\n[build]\nlock_wait = \"later\"\n"); + r = ws.mcpp({"build", "-p", "a"}); + expect(fatal(e2e::succeeded(r))) << "H: the root's [build] lock_wait was read: " << s::text(r); + expect(e2e::contains(s::text(r), "acts on no package")) << "H: the root's [build] was not reported: " << s::text(r); + ws.write("mcpp.toml", "[workspace]\nmembers = [\"a\", \"b\", \"c\"]\n"); + ws.write("a/mcpp.toml", ws.read("a/mcpp.toml") + "\n[build]\nlock_wait = \"0\"\n"); + r = ws.mcpp({"build", "-p", "a"}); + expect(fatal(e2e::succeeded(r))) << "H: a did not build with its own [build] lock_wait: " << s::text(r); + { + std::vector held; + for (const auto& d : graph_dirs(ws.dir())) held.push_back(hold(d / ".mcpp-build.lock", "alone")); + ws.write("a/src/main.cpp", ws.read("a/src/main.cpp") + "// edit\n"); + r = ws.mcpp({"build", "-p", "a"}); + expect(fatal(failed(r))) << "H: the replay waited past a's [build] lock_wait or built under the holder"; + expect(e2e::contains(s::text(r), "the limit [build] lock_wait in mcpp.toml states")) << "H: " << s::text(r); + } }; }}; From 87c91bb141a1c0ea7f9aa627feb7a9b5532f8b01 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 20:28:34 +0900 Subject: [PATCH 32/36] xlings 2026.12.5.2 is the pinned provider: a refused package fails with the provider's reason, and what a hook says is a note The index's snapshots from 3618c31f require xlings 2026.12.5.1; an earlier client stays on the snapshot before them. The handshake requires step_outcomes and hook_notices (protocol 1.20). A package the provider refuses on this machine fails with E_UNSUPPORTED and the provider's hint and is not retried, where 1.19's E_INVALID_INPUT drew the advice for a damaged archive and a retry. The install_notices a package's hooks produce are stated after the install as notes, at most eight lines a package, through the one writer (xlings#721). The SubOS ld wrapper the index's binutils carries honours the XLINGS_SUBOS_LD_PATHS=0 mcpp states (xlings#540); the comments state it. Every CI pin follows (check_version_pins.sh); docs/25 and the CHANGELOG state the provider; the fake providers of the e2e cases offer the two features, and e2e 1180 holds the note. --- .github/actions/bootstrap-mcpp/action.yml | 2 +- .github/actions/setup-macos-llvm/action.yml | 2 +- .github/workflows/bootstrap-macos.yml | 2 +- .github/workflows/ci-bootstrap.yml | 6 +-- .github/workflows/ci-fresh-install.yml | 6 +-- .github/workflows/ci-linux-e2e.yml | 2 +- .github/workflows/cross-build-test.yml | 4 +- .github/workflows/release-build.yml | 14 +++---- CHANGELOG.md | 9 +++++ docs/25-home-indices-and-store.md | 8 ++++ docs/zh/25-home-indices-and-store.md | 4 ++ src/cli.cppm | 6 +-- src/provider/xlings/xlings.cpp | 42 ++++++++++++++++++++- src/provider/xlings/xlings.cppm | 14 ++++++- src/runtime/search.cppm | 29 +++++++------- tests/e2e/build-program/deps.cpp | 2 +- tests/e2e/cdb/emit.cpp | 2 +- tests/e2e/index/local.cpp | 10 +++-- tests/e2e/index/refresh.cpp | 2 +- tests/unit/test_network.cpp | 7 +++- 20 files changed, 128 insertions(+), 45 deletions(-) diff --git a/.github/actions/bootstrap-mcpp/action.yml b/.github/actions/bootstrap-mcpp/action.yml index f39b83f82..681733102 100644 --- a/.github/actions/bootstrap-mcpp/action.yml +++ b/.github/actions/bootstrap-mcpp/action.yml @@ -33,7 +33,7 @@ inputs: # `package.name`, so one of the two was simply unreachable — and which one # depended on the machine, which is why CI failed on `compat:lua` on # Windows and `mcpplibs.capi:lua` on Linux. Never pin below that. - default: '2026.11.23.1' + default: '2026.12.5.2' outputs: sandbox-key: diff --git a/.github/actions/setup-macos-llvm/action.yml b/.github/actions/setup-macos-llvm/action.yml index 389916cac..0ce25b87a 100644 --- a/.github/actions/setup-macos-llvm/action.yml +++ b/.github/actions/setup-macos-llvm/action.yml @@ -15,7 +15,7 @@ inputs: # Floor imposed by the index, not a routine bump — see # .github/actions/bootstrap-mcpp/action.yml for why 0.4.69 is required # (two packages named `lua` in one repo need openxlings/xlings#381). - default: '2026.11.23.1' + default: '2026.12.5.2' image: description: > The runner label the job runs on (macos-15, xcode-27). It is part of the diff --git a/.github/workflows/bootstrap-macos.yml b/.github/workflows/bootstrap-macos.yml index a00c500f5..7d88c144a 100644 --- a/.github/workflows/bootstrap-macos.yml +++ b/.github/workflows/bootstrap-macos.yml @@ -17,7 +17,7 @@ jobs: # Dormant (workflow_dispatch only), but kept in step with the rest — # check_version_pins.sh holds it there. Floor: 0.4.69, below which the # index cannot resolve two packages that share a short name. - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/ci-bootstrap.yml b/.github/workflows/ci-bootstrap.yml index aa2f1abd4..ec1ad8403 100644 --- a/.github/workflows/ci-bootstrap.yml +++ b/.github/workflows/ci-bootstrap.yml @@ -41,7 +41,7 @@ jobs: os: [ubuntu-24.04, macos-15, windows-2025] env: XLINGS_NON_INTERACTIVE: '1' - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' steps: - uses: actions/checkout@v4 @@ -50,7 +50,7 @@ jobs: shell: bash run: | set -euo pipefail - curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.11.23.1 + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.12.5.2 echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH" echo "$HOME/.xlings/bin" >> "$GITHUB_PATH" @@ -124,7 +124,7 @@ jobs: shell: bash run: | set -euo pipefail - curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.11.23.1 + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.12.5.2 echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH" - name: Install the newest release and build the tree with it (mcpp build --strict) diff --git a/.github/workflows/ci-fresh-install.yml b/.github/workflows/ci-fresh-install.yml index e88e4fedd..ee815347e 100644 --- a/.github/workflows/ci-fresh-install.yml +++ b/.github/workflows/ci-fresh-install.yml @@ -182,7 +182,7 @@ jobs: env: XLINGS_NON_INTERACTIVE: '1' run: | - curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.11.23.1 + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.12.5.2 echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH" - name: Install mcpp and config mirror @@ -321,7 +321,7 @@ jobs: - name: Install xlings + mcpp run: | - curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.11.23.1 + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.12.5.2 # Deliberately NOT writing to $GITHUB_PATH here. On container # images that declare no PATH in their config (opensuse/ # tumbleweed), appending a single dir to GITHUB_PATH makes the @@ -470,7 +470,7 @@ jobs: # (older ones carry minos=15 and refuse to start). # v0.4.51+: in-process sha256 — this image has no sha256sum # binary, so pinned fetches failed before it. - curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.11.23.1 + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.12.5.2 echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH" - name: Install mcpp and config mirror diff --git a/.github/workflows/ci-linux-e2e.yml b/.github/workflows/ci-linux-e2e.yml index e26b82f00..4e5371a44 100644 --- a/.github/workflows/ci-linux-e2e.yml +++ b/.github/workflows/ci-linux-e2e.yml @@ -481,7 +481,7 @@ jobs: - name: Bootstrap xlings + released mcpp run: | - curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.11.23.1 + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.12.5.2 export PATH="$HOME/.xlings/subos/current/bin:$PATH" xlings update xlings install mcpp -y -g diff --git a/.github/workflows/cross-build-test.yml b/.github/workflows/cross-build-test.yml index 14085c2ec..033ec00be 100644 --- a/.github/workflows/cross-build-test.yml +++ b/.github/workflows/cross-build-test.yml @@ -132,7 +132,7 @@ jobs: # release assets were uploaded in a broken state (records present, # blobs missing → 404 on GET); re-uploaded clean. The stale-INDEX # half is handled by the marker-clear below. - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' run: | tarball="xlings-${XLINGS_VERSION}-linux-x86_64.tar.gz" bash "$GITHUB_WORKSPACE/.github/tools/fetch_release.sh" \ @@ -257,7 +257,7 @@ jobs: - name: Bootstrap mcpp via xlings env: XLINGS_NON_INTERACTIVE: '1' - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' run: | tarball="xlings-${XLINGS_VERSION}-linux-x86_64.tar.gz" bash "$GITHUB_WORKSPACE/.github/tools/fetch_release.sh" \ diff --git a/.github/workflows/release-build.yml b/.github/workflows/release-build.yml index 9c27e26e2..ddb5c68f0 100644 --- a/.github/workflows/release-build.yml +++ b/.github/workflows/release-build.yml @@ -88,7 +88,7 @@ jobs: # Pin xlings to a known-good version. The upstream install # script always grabs `latest` (no version override), so we # download + self-install manually to avoid broken releases. - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' run: | # BY VERSION, NOT BY PRESENCE. A restored ~/.xlings holds the # xlings of an earlier release, and this binary is the one the @@ -314,7 +314,7 @@ jobs: - name: Bootstrap mcpp via xlings env: XLINGS_NON_INTERACTIVE: '1' - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' run: | tarball="xlings-${XLINGS_VERSION}-linux-x86_64.tar.gz" bash "$GITHUB_WORKSPACE/.github/tools/fetch_release.sh" \ @@ -383,7 +383,7 @@ jobs: # below are pinned to the same version as XLINGS_VERSION; they are # NOT interpolated from it, so check_version_pins.sh scans for them # explicitly (they were absent from the old lock-step comment). - XLA="xlings-2026.11.23.1-linux-aarch64.tar.gz" + XLA="xlings-2026.12.5.2-linux-aarch64.tar.gz" # NOT fetch_release.sh: this asset is OPTIONAL and the `if` is the # point — an arch with no prebuilt xlings must fall through quietly, # while the helper retries a 404 five times before giving up. The one @@ -392,9 +392,9 @@ jobs: # cover it. if curl -fsSL --retry 3 --retry-delay 2 --retry-all-errors \ --connect-timeout 20 --max-time 600 -o "/tmp/$XLA" \ - "https://github.com/openxlings/xlings/releases/download/v2026.11.23.1/$XLA"; then + "https://github.com/openxlings/xlings/releases/download/v2026.12.5.2/$XLA"; then tar -xzf "/tmp/$XLA" -C /tmp - XLBIN=$(find /tmp/xlings-2026.11.23.1-linux-aarch64 -path '*/bin/xlings' -type f | head -1) + XLBIN=$(find /tmp/xlings-2026.12.5.2-linux-aarch64 -path '*/bin/xlings' -type f | head -1) if [ -n "$XLBIN" ]; then mkdir -p "$STAGING/$WRAPPER/registry/bin" cp "$XLBIN" "$STAGING/$WRAPPER/registry/bin/xlings" @@ -467,7 +467,7 @@ jobs: - name: Bootstrap mcpp via xlings env: XLINGS_NON_INTERACTIVE: '1' - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' run: | # By version, not by presence (see the Linux job). have=$("$HOME/.xlings/subos/default/bin/xlings" --version 2>/dev/null | awk '{print $2}') @@ -653,7 +653,7 @@ jobs: shell: bash env: XLINGS_NON_INTERACTIVE: '1' - XLINGS_VERSION: '2026.11.23.1' + XLINGS_VERSION: '2026.12.5.2' run: | # Captured before the `cd` below, in POSIX form: this step never # returns to the workspace, and GITHUB_WORKSPACE is a backslash diff --git a/CHANGELOG.md b/CHANGELOG.md index daa3bf0ed..bcb09f24d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,15 @@ ### Changed +- xlings 2026.12.5.2 is the pinned provider, and the handshake requires its `step_outcomes` and + `hook_notices` features (protocol 1.20); the index's snapshots from 3618c31f require it, and an + earlier provider stays on the snapshot before them. A package the provider refuses on this + machine fails its install with the provider's reason and is not retried; before, a target with + no artifact for the machine was answered with the advice for a damaged archive and retried. + What a package's install hooks say to the user is stated after the install as + `note: : (its hook)`, at most eight lines a package; it was lost. The + SubOS linker wrapper the index's binutils carries honours the `XLINGS_SUBOS_LD_PATHS=0` mcpp + states (openxlings/xlings#742, #752, #721, #540). - `mcpp --help` is printed from the command tree, in its groups, and ends with the line that points agents at `--agent-skill-doc`; the hand-written usage text is removed. Internal commands are hidden from the help and the completion. diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index 503e7db85..22c7e742e 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -363,6 +363,14 @@ mcpp asks it what it is (`xlings interface --version`): its version, its protocol and the features mcpp relies on. One that cannot serve this mcpp gives way to the bundled one, with a note naming why. +The bundled xlings is 2026.12.5.2 (protocol 1.20) from mcpp 2026.12.4.1, and a +provider below it is not used: the index's snapshots require it. A package the +provider refuses on this machine (no artifact for it, a recipe newer than the +provider) fails its install with the provider's reason and is not retried. +What a package's install hooks say to the user is stated after the install, as +`note: : (its hook)`, at most eight lines a package; the +rest is in the hook's log, which the last line names. + `[xlings] home` moves the registry; it names a home mcpp made. A home mcpp did not make (an `~/.xlings`) is refused there: reusing its packages is what `upstream` is for (§3). diff --git a/docs/zh/25-home-indices-and-store.md b/docs/zh/25-home-indices-and-store.md index 74611c32e..3b7a87c09 100644 --- a/docs/zh/25-home-indices-and-store.md +++ b/docs/zh/25-home-indices-and-store.md @@ -284,6 +284,10 @@ sysroot = { path = "/opt/acme/sysroot" } # 团队约定的路径,用于仓库 无论哪一个,mcpp 都会询问它是什么(`xlings interface --version`):版本、协议以及 mcpp 依赖的特性。不能服务当前 mcpp 的,让位于随附的 xlings,并以一条 note 说明原因。 +自 mcpp 2026.12.4.1 起随附的 xlings 为 2026.12.5.2(协议 1.20),低于它的提供者不被使用:索引的快照要求它。提供者在本机 +拒绝的包(没有本机的产物、配方新于提供者)以提供者给出的原因安装失败,不重试。包的安装钩子对用户说的话在安装之后 +陈述为 `note: <包>: <文本> (its <钩子> hook)`,每个包至多八行;其余在钩子的日志中,最后一行写出日志的位置。 + `[xlings] home` 移动 registry,它指向的必须是 mcpp 建立的 home。不是 mcpp 建立的 home(例如 `~/.xlings`)在这里被拒绝: 复用它的包应使用 `upstream`(§3)。 已经存在的 registry 保留建立它的 home 所记录的索引位置:指向它的另一个 home 读取这些索引和存储,不在其中记录自己的位置(2026.11.10.1)。`registry` 是指向另一个 home 的 registry 的链接时,该 home 同样是借用者(2026.11.13.1):索引的位置、上游以及其 `[index.repos]` 表的位置都不写入其中。 diff --git a/src/cli.cppm b/src/cli.cppm index d2359a3c3..1a848486d 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -1638,9 +1638,9 @@ int run(int argc, char** argv) { // // Set here rather than per link command: the link line has a hard 128KiB // ceiling that real workspaces already spend 43% of, and children inherit - // the environment for free. Declared BEFORE the wrapper ships, because - // "the exit must be declared, not inferred" is the rule that whole - // negotiation established — today this is a no-op. + // the environment for free. "The exit must be declared, not inferred" is + // the rule that negotiation established; the wrapper the index's binutils + // carries (for xlings 2026.12.5.1 and later) honours it. mcpp::invocation::set( std::string(mcpp::runtime::search::kLinkerPathInjectionOptOut), std::string(mcpp::runtime::search::kLinkerPathInjectionOptOutValue)); diff --git a/src/provider/xlings/xlings.cpp b/src/provider/xlings/xlings.cpp index d0ac580f6..6d3fe5ef0 100644 --- a/src/provider/xlings/xlings.cpp +++ b/src/provider/xlings/xlings.cpp @@ -73,6 +73,36 @@ void print_source(std::string_view name, std::string_view host, int attempt) { print_status("Source", std::format("{} {} (attempt {})", name, host, attempt)); } +// WHAT A PACKAGE'S HOOKS SAID TO THE USER (protocol 1.20, `install_notices`): +// a recipe's `log.warn` and `log.error`, by package, which an earlier provider +// did not pass on (openxlings/xlings#721). Stated as notes once the install has +// ended: they change nothing mcpp does, so `--strict` does not make a recipe's +// words refuse a build. At most eight lines a package, as the provider's own +// command line shows them; the rest is in the hook's log, which is named. +void state_install_notices(std::string_view payloadJson) { + constexpr std::size_t kLines = 8; + const auto j = nlohmann::json::parse(payloadJson, nullptr, false); + if (!j.is_object() || !j.contains("packages") || !j["packages"].is_array()) return; + for (const auto& p : j["packages"]) { + if (!p.is_object() || !p.contains("notices") || !p["notices"].is_array()) continue; + const auto package = p.value("package", std::string{}); + const auto& notices = p["notices"]; + for (std::size_t i = 0; i < std::min(kLines, notices.size()); ++i) { + const auto& n = notices[i]; + if (!n.is_object()) continue; + const auto hook = n.value("hook", std::string{}); + mcpp::diag::note("xlings/hook", std::format("{}: {} (its {}hook{})", package, n.value("text", std::string{}), + hook.empty() ? "" : hook + " ", + n.value("level", std::string{}) == "error" ? ", as an error" : "")); + } + if (notices.size() > kLines) { + const auto log = p.contains("logs") && p["logs"].is_array() && !p["logs"].empty() && p["logs"][0].is_string() + ? p["logs"][0].get() : std::string("the provider's log"); + mcpp::diag::note("xlings/hook", std::format("{}: {} more lines in {}", package, notices.size() - kLines, log)); + } + } +} + std::filesystem::path default_index_dir(const Env& env) { return paths::index_dir_of(env, "mcpplibs"); } @@ -406,7 +436,8 @@ std::string unmet(const mcpp::provider::ProviderInfo& info) { return std::format("is {}, older than {}", info.version, pinned::kXlingsVersion); for (auto feature : {"index_dir", "index_store", "upstreams", "payload_status", "sync_index", "payload_currency", "binding_state", "network_diagnostics", - "download_socket_budgets", "read_only_queries", "store_roots"}) + "download_socket_budgets", "read_only_queries", "store_roots", + "step_outcomes", "hook_notices"}) if (std::ranges::find(info.features, feature) == info.features.end()) return std::format("does not offer `{}`", feature); if (std::ranges::find(info.capabilities, "install_packages") == info.capabilities.end()) @@ -1419,6 +1450,8 @@ call(const Env& env, std::string_view capability, const auto ran = mcpp::run::execute(inv.argv, inv.options); const int rc = ran.exit_code; const bool timedOut = ran.timed_out; + for (const auto& d : result.dataEvents) + if (d.dataKind == "install_notices") state_install_notices(d.payloadJson); if (timedOut) { result.exitCode = result.exitCode != 0 ? result.exitCode : 124; const auto message = progressDeadlineReason.empty() @@ -1707,6 +1740,7 @@ int install_with_progress(const Env& env, std::string_view target, mcpp::ui::DownloadProgress download; InstallDeadline deadline; std::string progressDeadlineReason; + std::vector notices; // `install_notices` payloads, stated after the install auto handle_line = [&](std::string_view line) { deadline.observe(line); @@ -1716,6 +1750,11 @@ int install_with_progress(const Env& env, std::string_view target, resultExitCode = static_cast(ls.find_num("exitCode")); return; } + if (kind == "data" && ls.find_str("dataKind") == "install_notices") { + if (const auto j = nlohmann::json::parse(line, nullptr, false); j.is_object() && j.contains("payload")) + notices.push_back(j["payload"].dump()); + return; + } if (kind == "error") { const auto message = ls.find_str("message"); mcpp::log::warn("provider", message); @@ -1772,6 +1811,7 @@ int install_with_progress(const Env& env, std::string_view target, if (!idleTimedOut && resultExitCode == 0 && closeRc == 0) download.finish(); else download.finish_failed(); } + for (const auto& payload : notices) state_install_notices(payload); if (idleTimedOut) { const auto reason = progressDeadlineReason.empty() ? "provider process deadline exceeded" : progressDeadlineReason; diff --git a/src/provider/xlings/xlings.cppm b/src/provider/xlings/xlings.cppm index bf023fe3f..fbde396c1 100644 --- a/src/provider/xlings/xlings.cppm +++ b/src/provider/xlings/xlings.cppm @@ -211,7 +211,19 @@ namespace pinned { // builds have registered their payloads as roots, and an earlier xlings // reads none and removes them. Measured on one home before roots: `xlings // self clean --dry-run` listed 154 payloads (16 GB) projects use. - inline constexpr std::string_view kXlingsVersion = "2026.11.23.1"; + // + // Nineteenth, at 2026.12.5.2 (openxlings/xlings#742, #752, protocol 1.20). + // The index's snapshots from 3618c31f require 2026.12.5.1: an earlier + // client stays on the snapshot before them and receives no package or + // revision published since. A node a gate refuses fails its install with + // `E_UNSUPPORTED` (`step_outcomes`; before, a target with no artifact for + // this machine was `E_INVALID_INPUT`, which mcpp read as a damaged + // archive), and what a package's hooks say to the user arrives as + // `install_notices` (`hook_notices`; it was lost, xlings#721), which mcpp + // states as notes. The SubOS `ld` wrapper the index's binutils carries + // honours XLINGS_SUBOS_LD_PATHS=0, which mcpp states for its links + // (xlings#540, mcpp.runtime.search). + inline constexpr std::string_view kXlingsVersion = "2026.12.5.2"; inline constexpr std::string_view kNasmVersion = "3.02"; } diff --git a/src/runtime/search.cppm b/src/runtime/search.cppm index 2a6bcf030..94535a3c0 100644 --- a/src/runtime/search.cppm +++ b/src/runtime/search.cppm @@ -186,19 +186,22 @@ std::vector ordered(std::vector dirs) { // The declarative exit from xlings' linker wrapper (openxlings/xlings#540). // -// That wrapper appends `-rpath "$XLINGS_SUBOS_LIB" --disable-new-dtags` to -// every link it sees. mcpp wants the tag half and must refuse the path half: -// `$XLINGS_SUBOS_LIB` names the ACTIVE shell's SubOS, which is measurably not -// the one mcpp resolved — mcpp keeps its own xlings home under -// `/registry`, so the variable points at a different farm backed by -// a different physical glibc payload. Inheriting it would put a second libc on -// the artifact's search path, which is the one thing rule B exists to prevent. -// -// mcpp declares the exit BEFORE the wrapper ships. Today it is a no-op; the -// day the wrapper lands it keeps mcpp's DT_RPATH exactly what mcpp decided. -// Set in mcpp's own process environment rather than per link command: the link -// line has a hard 128KiB ceiling that real workspaces already spend 43% of, -// and children inherit the environment anyway. +// That wrapper appends `-rpath "$XLINGS_SUBOS_LIB" --disable-new-dtags` to the +// link of an executable whose loader is the environment's (openxlings/xlings +// #532), as mcpp's links through a SubOS gcc are. mcpp wants the tag half and +// must refuse the path half: `$XLINGS_SUBOS_LIB` names the ACTIVE shell's +// SubOS, which is measurably not the one mcpp resolved — mcpp keeps its own +// xlings home under `/registry`, so the variable points at a +// different farm backed by a different physical glibc payload. Inheriting it +// would put a second libc on the artifact's search path, which is the one thing +// rule B exists to prevent. +// +// The wrapper the index's binutils carries (for xlings 2026.12.5.1 and later) +// honours the exit: it still adds `--disable-new-dtags` and adds no path, so +// mcpp's DT_RPATH is exactly what mcpp decided. Set in mcpp's own process +// environment rather than per link command: the link line has a hard 128KiB +// ceiling that real workspaces already spend 43% of, and children inherit the +// environment anyway. inline constexpr std::string_view kLinkerPathInjectionOptOut = "XLINGS_SUBOS_LD_PATHS"; inline constexpr std::string_view kLinkerPathInjectionOptOutValue = "0"; diff --git a/tests/e2e/build-program/deps.cpp b/tests/e2e/build-program/deps.cpp index 065c04929..056cbc0c3 100644 --- a/tests/e2e/build-program/deps.cpp +++ b/tests/e2e/build-program/deps.cpp @@ -834,7 +834,7 @@ int main() { fs::create_directory_symlink(xpkgs, registry / "data/xpkgs"); s::write_executable(tmp / "fake-bin/xlings", R"sh(#!/usr/bin/env bash # The handshake mcpp asks of every xlings (docs/25 §5). -[[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots"]}'; exit 0; } +[[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots","step_outcomes","hook_notices"]}'; exit 0; } set -e if [[ "${1:-}" == "self" && "${2:-}" == "init" ]]; then mkdir -p "${XLINGS_HOME:?}/subos/default" diff --git a/tests/e2e/cdb/emit.cpp b/tests/e2e/cdb/emit.cpp index 5b9cc61f3..c9ab517ed 100644 --- a/tests/e2e/cdb/emit.cpp +++ b/tests/e2e/cdb/emit.cpp @@ -480,7 +480,7 @@ int main() { expect(fatal(e2e::succeeded(s::mcpp(install_default(), s::case_dir(), {.where = s::home::inherited})))) << "the case's home did not install its toolchain"; s::write_executable(out / "bin/xlings", R"(#!/usr/bin/env bash -[[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots"]}'; exit 0; } +[[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots","step_outcomes","hook_notices"]}'; exit 0; } echo "$*" >> "${STUB_LOG:?}" exit 0 )"); diff --git a/tests/e2e/index/local.cpp b/tests/e2e/index/local.cpp index 627107ab0..46a2cb23c 100644 --- a/tests/e2e/index/local.cpp +++ b/tests/e2e/index/local.cpp @@ -47,7 +47,7 @@ default = "{}" )", binary.generic_string(), xlings_home.generic_string(), toolchain)}}); } -constexpr std::string_view handshake = R"HS([[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots"]}'; exit 0; })HS"; +constexpr std::string_view handshake = R"HS([[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots","step_outcomes","hook_notices"]}'; exit 0; })HS"; std::string lua_package(std::string_view name, std::string_view version, std::string_view description, std::string_view mcpp_segment) { return std::format(R"(package = {{ @@ -364,8 +364,9 @@ exit 0 // the screen the bytes leave holds one `Downloading` line for each, under its manifest // name, and no frame of the live region (a download's bar, or the `Planning` line drawn // before the first bar), although the provider writes lines of its own to its standard - // error before its first frame and while it downloads. A second build calls no provider. Under - // `[build] batch_fetch = "each"` a call names one dependency. + // error before its first frame and while it downloads. What a package's hook said to the + // user (`install_notices`, protocol 1.20) is one note. A second build calls no provider. + // Under `[build] batch_fetch = "each"` a call names one dependency. const auto tmp = s::case_dir(); const auto home = s::case_home(s::home::inherited); s::project index(tmp / "local-index", { @@ -400,6 +401,7 @@ if [[ "${1:-}" == "interface" && "${2:-}" == "install_packages" ]]; then frame 0.4 512 1024 false 0 0 false frame 0.7 1024 1024 true 512 1024 false frame 1.0 1024 1024 true 1024 1024 true + printf '{"kind":"data","dataKind":"install_notices","payload":{"packages":[{"package":"compat:compat.one@1.0.0","notices":[{"level":"warn","text":"a word for its user","hook":"install"}],"logs":[]}]}}\n' printf '{"kind":"result","exitCode":0}\n' exit 0 fi @@ -439,6 +441,8 @@ exit 0 for (std::string_view dep : {"compat.one@1.0.0", "compat.two@1.0.0"}) expect(s::count_lines(shown, std::format("{} example.invalid (attempt 1)", dep)) <= 1u) << "the provider's line for " << dep << " was written more than once:\n" << shown; + expect(s::count_lines(shown, "note: compat:compat.one@1.0.0: a word for its user (its install hook)") == 1u) + << "what the package's hook said was not stated once:\n" << shown; auto again = app.mcpp({"build"}, inherited({{"FAKE_INSTALL_LOG", log.string()}})); expect(fatal(e2e::succeeded(again))) << s::text(again); diff --git a/tests/e2e/index/refresh.cpp b/tests/e2e/index/refresh.cpp index 7bacdf32b..da0462076 100644 --- a/tests/e2e/index/refresh.cpp +++ b/tests/e2e/index/refresh.cpp @@ -27,7 +27,7 @@ std::string trimmed(std::string t) { return t; } -constexpr std::string_view handshake = R"HS([[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots"]}'; exit 0; })HS"; +constexpr std::string_view handshake = R"HS([[ "${1:-}" == "interface" && "${2:-}" == "--version" ]] && { echo '{"protocol_version":"1.13","version":"9999.1.1.1","capabilities":["install_packages"],"home_layouts":[2],"features":["index_dir","index_store","upstreams","payload_status","sync_index","payload_currency","binding_state","network_diagnostics","download_socket_budgets","read_only_queries","store_roots","step_outcomes","hook_notices"]}'; exit 0; })HS"; // A stub xlings that answers the handshake and records every other command in STUB_LOG. void stub_logging_xlings(const fs::path& file) { diff --git a/tests/unit/test_network.cpp b/tests/unit/test_network.cpp index 6a57ff799..0dc061d1a 100644 --- a/tests/unit/test_network.cpp +++ b/tests/unit/test_network.cpp @@ -233,14 +233,17 @@ UTest legacy_status_and_handshake_do_not_write_the_selected_home{"NetworkCheck/L UTest bootstrap_requires_download_budgets_and_read_only_queries{"NetworkCheck/BootstrapRequiresDownloadBudgetsAndReadOnlyQueries", [] { // And `store_roots` (xlings 2026.11.23.1): a provider whose collection does - // not read roots is not asked for one. + // not read roots is not asked for one. And `step_outcomes`, `hook_notices` + // (2026.12.5.2): a refused node fails its install, and what a hook said + // arrives as data. mcpp::provider::ProviderInfo info; info.answered = true; info.version = "9999.1.1.1"; info.capabilities = {"install_packages"}; info.features = {"index_dir", "index_store", "upstreams", "payload_status", "sync_index", "payload_currency", "binding_state"}; - for (const auto* feature : {"network_diagnostics", "download_socket_budgets", "read_only_queries", "store_roots"}) { + for (const auto* feature : {"network_diagnostics", "download_socket_budgets", "read_only_queries", "store_roots", + "step_outcomes", "hook_notices"}) { expect(ne(mcpp::provider::xlings::unmet(info).find(feature), std::string::npos)); info.features.push_back(feature); } From 0837801a7d8069cffb755793759f3ca4279c9a7e Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 20:58:10 +0900 Subject: [PATCH 33/36] mcpp.toml: each comment states its reason in one or two lines The comments are shortened to the reason and the measurement or reference each stands on; the comment of the unit tests' code page moves above [test], which it describes. No key or value changes. --- mcpp.toml | 115 ++++++++---------------------------------------------- 1 file changed, 17 insertions(+), 98 deletions(-) diff --git a/mcpp.toml b/mcpp.toml index d55a86d8d..71d422b8b 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -7,49 +7,18 @@ authors = ["mcpp-community"] repo = "https://github.com/mcpp-community/mcpp" [build] -# The global default profile is now "dev" (-O0 -g, mainstream convention); -# mcpp itself is a shipped tool, so opt its plain `mcpp build` (and release.yml's -# self-host build) back into the optimized profile. Without this the released -# binary would be -O0. A `--profile`/`--dev`/`--release` flag still overrides. +# A shipped tool: `mcpp build` and release.yml build it optimized; a profile flag overrides. default-profile = "release" -# Split the module edge: importers start when the BMI is published rather than -# when the compiler exits. See docs/04-mcpp-toml.md. -# -# ON HERE, `auto` (= off) EVERYWHERE ELSE. The key stays opt-in until it has been -# through CI on every platform, and nothing was exercising it, so it could never -# accumulate the evidence needed to change that. mcpp's own build is where that -# evidence is cheapest: whatever this schedule produces has to pass 83 unit tests -# and the full e2e suite, on Linux (detach-codegen, gcc) and on macOS and Windows -# (two-phase, clang) — three platforms, every PR. -# -# THAT SAFETY NET IS NOT DECORATION — it has already caught one defect. The -# windows-host cross build to x86_64-linux-musl failed on the BMI edge with -# -# failed: gcm.cache/mcpp.libs.json.gcm -# modules/libs/src/json.cppm:3: fatal error: json.hpp: No such file or -# directory (the unit was src/libs/json.cppm when this was diagnosed) -# -# because `cmd.exe /c` does not use CreateProcess argument quoting, so the -# compiler ran with `-I` missing. Fixed in detach_codegen.cppm; see #425. -# -# Revert is this one line if anything here is ever unexplained. +# Importers start when a BMI is published (docs/04); on here so every PR's CI exercises it (#425). bmi_schedule = "on" -# mcpp's sources. The one primitive each system has of its own -- the lock -# every release of mcpp takes (src/native/, design 2026-10-26 §25.3) -- -# is selected per system below, each system's row excluding the others'. +# Each system's native primitive (src/native/) is selected by the target rows below. sources = ["src/**/*.cppm", "src/**/*.cpp"] -# mcpp.exe declares the UTF-8 code page (mcpp#693); see docs/res/mcpp.rc. Only a PE -# target compiles a resource script, so this changes nothing elsewhere. +# mcpp.exe declares the UTF-8 code page (mcpp#693); only a PE target compiles the script. [resources] files = ["docs/res/mcpp.rc"] -# The unit tests run in the code page mcpp.exe runs in, so a result does not -# depend on the region setting of the machine that runs them (2026.10.5.2). An -# engine older than the key reports it as unsupported and ignores it. -# The e2e coverage map (design 2026-11-08 W8; .github/workflows/e2e-coverage.yml): mcpp built with -# GCC's arc counters, so that each e2e test's run records the sources it executed (mtest's -# `run --coverage`). Not shipped; unoptimized, so that a line's counter is the line's. +# GCC's arc counters for the e2e coverage map (e2e-coverage.yml); unoptimized, not shipped. [profile.coverage] opt = 0 debug = false @@ -57,26 +26,19 @@ cflags = ["--coverage"] cxxflags = ["--coverage"] ldflags = ["--coverage"] -# The tests as CI builds them (ci-unit.yml, mcpp-unit): -O0 and no debug information. The -# package's default profile is release (-O2); building the library and its unit tests with it took -# 8988 s of compiler time, and with this 4183 s (design 2026-11-14 §6). A failure is read from -# mtest's report, which names the place of each check without debug information. +# CI's test builds: -O0 without debug information took 4183 s of compiler time, release 8988 s. [profile.ci] opt = 0 debug = false strip = true +# The tests run in mcpp.exe's code page; the support package, fixtures and canaries are not tests. [test] windows_code_page = "utf-8" programs = "directory" -# The unit tests, and the end-to-end cases (tests/e2e//*.cpp, one program per -# subsystem); the support package, the scripts' fixtures and the canaries (projects of their own, -# tests/canary) are not tests. discover = ["tests/**/*.cpp", "!tests/support/**", "!tests/e2e/fixtures/**", "!tests/fixtures/**", "!tests/canary/**"] -# Each entry equals its row's Default (SPEC-009 §12): the LLVM line moved to -# 23.1.3 — the first release carrying the macOS 27 arm64e.x1 linker fix -# (mcpp#669). Linux x86_64 retains GCC; native ARM64 uses LLVM and glibc. +# Each entry is its row's default (SPEC-009 §12); LLVM 23.1.3 carries the macOS 27 linker fix. [toolchain] default = "gcc@16.1.0" macos = "llvm@23.1.3" @@ -85,61 +47,29 @@ windows = "llvm@23.1.3" [target.aarch64-linux-gnu] toolchain = "llvm@23.1.3" -# Per-target overrides: `mcpp build --target x86_64-linux-musl` (or the -# four-segment form `x86_64-unknown-linux-musl`) picks musl-gcc 16.1 + full -# static linkage. Used by .github/workflows/release.yml to produce a -# portable static binary that drops in anywhere with no ELF interp / RUNPATH -# baggage. +# The portable release binary (release.yml): musl-gcc 16.1, fully static. [target.x86_64-linux-musl] toolchain = "gcc@16.1.0-musl" linkage = "static" -# aarch64 (ARM64) static target. No explicit toolchain: the target table pins -# gcc@16.1.0 for this row, and mcpp's host-aware convention picks the payload — -# on an aarch64 host a NATIVE build (xim:musl-gcc), on an x86_64 host a CROSS -# build (xim:aarch64-linux-musl-gcc 16.1.0; measured for #694, which found this -# comment still naming 15.1.0). linkage=static is also implied by the -musl -# suffix; kept explicit for clarity. See -# .agents/docs/2026-06-22-aarch64-android-mvp-design.md. +# The target table pins gcc@16.1.0: native on an aarch64 host, a cross build on x86_64. [target.aarch64-linux-musl] linkage = "static" -# Eat our own dog food: mcpp uses mcpplibs.cmdline for argument parsing. -# `agent-skills` answers `--agent-skill-doc` from docs/mcpp-skills, which -# build.mcpp renders into the module mcpp.skills (design 2026-11-27 §3.9). +# `agent-skills` answers `--agent-skill-doc` from docs/mcpp-skills, which build.mcpp renders. [dependencies] mcpplibs.cmdline = { version = "0.2.0", features = ["agent-skills"] } -# JSON for Modern C++, as the index's module package (no copied header). nlohmann.json = "3.12.0" -# The C library's macros (`stdout`, `stderr`, `EOF`, `errno` …) as C++ names: -# `import std` carries no macro (design 2026-11-07 D10). +# The C library's macros (`stdout`, `errno`, ...) as C++ names: `import std` carries none. mcpplibs.mwrap.libc = "17.0.0" -# The codecs of a package's container (SPEC-014 §5): gzip and raw DEFLATE, -# zstd, xz. The reference libraries, through their mwrap modules, so an archive -# is written the same way on every host and nothing is looked for on PATH. +# A container's codecs (SPEC-014 §5), the same on every host and never looked for on PATH. mcpplibs.mwrap.zlib = "1.3.2" mcpplibs.mwrap.zstd = "1.5.7" mcpplibs.mwrap.xz = "5.8.3.1" - -# The operating system is mcpplibs.os's (design 2026-10-26 §25): mcpp keeps no -# layer of its own. mcpplibs.os = "0.4.8" -# `modules/` holds what gets linked into this binary; `src/` is what has not -# been separated yet, and shrinking it is the direction. Each entry is an -# independent package with its own manifest, so the thing that used to be a -# directory convention is now a boundary the build enforces: a module under -# `modules/` cannot quietly reach back into the engine, because a package -# cannot depend on its consumer. -# -# A dependency KEY must match the package's identity, and these carry the -# `mcpp` namespace rather than squatting bare `json` / `toml` — dependency -# names resolve in one flat space, so `json = { path = … }` would take a name -# the registry may one day want. -# -# `[workspace] members` below is what makes `-p` and `mcpp test` address them; -# it is NOT what makes them importable. That is these path dependencies, and -# needing both is easy to get wrong because either one alone looks sufficient. +# The packages under modules/, linked into this binary; [workspace] members lets -p and +# `mcpp test` address them, these path dependencies make them importable. mcpp.invocation = { path = "modules/invocation" } mcpp.libs = { path = "modules/libs" } mcpp.log = { path = "modules/log" } @@ -166,12 +96,7 @@ sources = ["!src/native/windows/**"] [target.windows.build] sources = ["!src/native/posix/**"] -# THE MAIN THREAD'S STACK ON WINDOWS. A command nests whole builds in one process: `mcpp pack` -# prepares the program, a host tool its platform names, and that tool's build programs, and each -# pass holds a few hundred KiB of frames. A PE image's main thread has the 1 MiB its header -# reserves by default, where Linux and macOS give 8 MiB. Measured with 2026.11.27.1 on the -# openkal canary's `mcpp pack`: 1,046 KiB at the deepest manifest read, and an -# EXCEPTION_STACK_OVERFLOW on windows-x86_64. The image reserves what the other hosts give. +# A PE image reserves a 1 MiB main stack; `mcpp pack`'s nested builds took 1,046 KiB, so 8 MiB. [target.'cfg(all(os = "windows", env = "msvc"))'.build] ldflags = ["-Wl,/STACK:8388608"] @@ -198,13 +123,7 @@ members = [ "modules/cps", ] -# `mcpp build` ignores [dev-dependencies]; only `mcpp test` resolves them. +# Resolved by `mcpp test` only; tests/support is the e2e cases' support package. [dev-dependencies] mcpplibs.mtest = "0.11.3" -# The support of the end-to-end cases (tests/support, design 2026-11-12 §5.9). mcpp.test-support = { path = "tests/support" } - -# Everything else uses M5.0 conventions: -# - target = mcpp (kind=bin inferred from src/main.cpp) -# - standard = c++23 -# - static_stdlib = true (default; portable binary) From a8826394c7d5c2262011eb8d8ea0d432c0191c74 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 21:37:53 +0900 Subject: [PATCH 34/36] The recipe a payload keeps is read in the layout xlings 2026.12.5.1 writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 2026.12.5.1 an install keeps its recipe as an index of that one recipe, .xpkg/pkgs//.lua beside the libs it imports (xlings derived-state §4.1); an earlier client kept .xpkg.lua. mcpp read only the latter, so a gcc the pinned provider installed declared no kernel headers or binutils, and a build whose store held no index refused with [target-base] (e2e deps/58 and local/52 under the new provider). Both layouts are read; the unit case of the declared companion holds the new one. --- CHANGELOG.md | 6 ++++-- src/provider/xlings/xlings.cpp | 22 ++++++++++++++++++---- tests/unit/test_xlings.cpp | 17 +++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bcb09f24d..88a325b11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,8 +72,10 @@ no artifact for the machine was answered with the advice for a damaged archive and retried. What a package's install hooks say to the user is stated after the install as `note: : (its hook)`, at most eight lines a package; it was lost. The - SubOS linker wrapper the index's binutils carries honours the `XLINGS_SUBOS_LD_PATHS=0` mcpp - states (openxlings/xlings#742, #752, #721, #540). + recipe a payload keeps is read in the layout this provider writes, `.xpkg/pkgs//.lua`, + as the earlier `.xpkg.lua` is, so a toolchain it installed still declares its kernel headers and + binutils. The SubOS linker wrapper the index's binutils carries honours the + `XLINGS_SUBOS_LD_PATHS=0` mcpp states (openxlings/xlings#742, #752, #721, #540). - `mcpp --help` is printed from the command tree, in its groups, and ends with the line that points agents at `--agent-skill-doc`; the hand-written usage text is removed. Internal commands are hidden from the help and the completion. diff --git a/src/provider/xlings/xlings.cpp b/src/provider/xlings/xlings.cpp index 6d3fe5ef0..aee6d4273 100644 --- a/src/provider/xlings/xlings.cpp +++ b/src/provider/xlings/xlings.cpp @@ -699,7 +699,7 @@ std::optional active_home_xpkgs() { namespace { // A version dir qualifies as a payload only if it has real content — -// dot-prefixed entries (.xim-installed, .xpkg.lua) are install metadata, +// dot-prefixed entries (.xim-installed, .xpkg/, .xpkg.lua) are install metadata, // and a dir holding nothing else is the husk a delegating index package // leaves behind (the payload lives under another prefix; issue #120). // When requiredRelPath is given, the dir must also contain that path. @@ -739,11 +739,24 @@ payload_versions(const std::filesystem::path& xpkgs, std::string_view packageNam return out; } +// The recipe a payload was installed with (xlings derived-state §4.1): from +// 2026.12.5.1 an index of that one recipe, `.xpkg/pkgs//.lua`, beside +// the libs it imports; an earlier client kept `.xpkg.lua` alone, and the payload +// keeps it until a removal rewrites it. +std::optional kept_recipe(const std::filesystem::path& payload, std::string_view name) { + std::error_code ec; + for (std::filesystem::directory_iterator dir(payload / ".xpkg" / "pkgs", ec), end; !ec && dir != end; dir.increment(ec)) + if (const auto file = dir->path() / (std::string(name) + ".lua"); std::filesystem::is_regular_file(file, ec)) + return file; + if (const auto file = payload / ".xpkg.lua"; std::filesystem::is_regular_file(file, ec)) return file; + return std::nullopt; +} + // What the payload `compilerBin` belongs to declares for `packageName` on this // host, one entry per descriptor that names the package: the requirement of its // runtime dependency (`xim:binutils@2.42.1` gives `2.42.1`, an unversioned one -// gives ""). First the descriptor the payload was installed with -// (`/.xpkg.lua`), then the index's. +// gives ""). First the recipe the payload was installed with (`kept_recipe`), +// then the index's. // // TWO RECORDS, AND EITHER CAN BE THE ONE THIS STORE FOLLOWED. A home that // installed the payload installed the companions its own descriptor named; the @@ -786,7 +799,8 @@ declared_requirements(const std::filesystem::path& xpkgs, const std::filesystem: if (r && std::ranges::find(out, *r) == out.end()) out.push_back(std::move(*r)); }; if (auto version = std::next(rel.begin()); version != rel.end()) - if (auto body = read(xpkgs / *rel.begin() / *version / ".xpkg.lua")) add(requirement(*body)); + if (auto kept = kept_recipe(xpkgs / *rel.begin() / *version, owner)) + if (auto body = read(*kept)) add(requirement(*body)); for (const auto& file : descriptor_candidates(xpkgs.parent_path(), owner)) if (auto body = read(file)) { add(requirement(*body)); break; } return out; diff --git a/tests/unit/test_xlings.cpp b/tests/unit/test_xlings.cpp index 1b7884c2b..1aff14290 100644 --- a/tests/unit/test_xlings.cpp +++ b/tests/unit/test_xlings.cpp @@ -457,6 +457,23 @@ package = { std::filesystem::remove_all(xpkgs / "xim-x-binutils" / "2.48"); expect(!xp::find_sibling_binary(gccBin, "binutils", "bin/as").has_value()) << "declarations the store holds none of were replaced by another version"; + // The recipe as xlings 2026.12.5.1 keeps it, an index of that one recipe (its derived-state + // §4.1), is read as `.xpkg.lua` is: a gcc it installed declares its companions. + std::filesystem::remove(xpkgs / "xim-x-gcc" / "16.1.0" / ".xpkg.lua"); + touch(xpkgs / "xim-x-gcc" / "16.1.0" / ".xpkg" / "pkgs" / "g" / "gcc.lua", R"( +package = { + name = "gcc", + xpm = { + linux = { deps = { runtime = { "xim:binutils@2.40" } }, ["16.1.0"] = {} }, + macosx = { deps = { "xim:binutils@2.40" }, ["16.1.0"] = {} }, + windows = { deps = { "xim:binutils@2.40" }, ["16.1.0"] = {} }, + }, +} +)"); + expect(eq(xp::declared_dependency(gccBin, "binutils").value_or(""), std::string("2.40"))) + << "the recipe kept under .xpkg/ was not read"; + expect(eq(xp::find_sibling_binary(gccBin, "binutils", "bin/as").value_or(""), + xpkgs / "xim-x-binutils" / "2.40" / "bin" / "as")); std::filesystem::remove_all(tmp); }}; From ad75b0ac2376225c998d993969de0fe09801fe28 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 21:55:29 +0900 Subject: [PATCH 35/36] =?UTF-8?q?design=202026-11-27=20v12:=20network=20ch?= =?UTF-8?q?eck,=20the=20mirror's=20initial=20value=20and=20network=20advic?= =?UTF-8?q?e=20(=C2=A73.13,=20D28=20to=20D31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The check is one line of reachable endpoints; the mirror is decided once, from the time zone and the region, then checked against reachability, and written as CN or GLOBAL; network trouble is advised in five places without stopping the run, naming the command and the current mirror. The region and the time zone are read by mcpplibs.os. --- .../2026-11-27-ecosystem-boundary-design.md | 91 ++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index b07f7f677..cae227363 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -5,7 +5,7 @@ status: active # 生态与外部的交界:工具链的事实、二进制库交付物、被启动的外部程序、名字的拼写与共享的状态 -**日期:** 2026-11-27,2026-12-04、2026-12-05 修订 · **版本:** v11(v9 增加 §3.12 CPS 与决定 D16 至 D21;v10 以 mcpp 为中心重写 §3.12,D22 至 D24 取代 D16 至 D18 与 D21;v11 增加 §3.9.4 说明的网络、`mcpp info` 与依赖的写法,决定 D25 至 D27;决定全部作出,见 §7;五轮自查的结论见 §11) · +**日期:** 2026-11-27,2026-12-04、2026-12-05 修订 · **版本:** v12(v9 增加 §3.12 CPS 与决定 D16 至 D21;v10 以 mcpp 为中心重写 §3.12,D22 至 D24 取代 D16 至 D18 与 D21;v11 增加 §3.9.4 说明的网络、`mcpp info` 与依赖的写法,决定 D25 至 D27;v12 增加 §3.13 网络检查、镜像的初值与网络问题的提示,决定 D28 至 D31;决定全部作出,见 §7;五轮自查的结论见 §11) · **基线:** mcpp main `30fcd5a0`(2026.11.27.1 之后,含 #1036)、xlings 2026.11.23.1、openkal 0.26.0、openkal-linux 0.27.2、 openkal-windows 0.23、openkal-musl 0.30.3、mcpplibs.os 0.4.8、mcpplibs.cmdline 0.1.0(mcpp 所钉为 0.0.6)、 mcpp-index `9788068b` · @@ -1191,6 +1191,79 @@ CPS 是其中一种被读取的描述。`mcpp-package.json` 仍是 mcpp 的权 版本、查找的位置。e2e:库包的 `.cps` 合乎规范并被 CMake 4.5 找到与链接运行;声明的默认组件、指定组件、`requires` 链、 平台不符的跳过与拒绝、配置的选取、`.cps` 改变后重跑、各拒绝的原因码。 +### 3.13 网络检查、镜像的初值与网络问题的提示(mcpp、mcpplibs.os;v12) + +#### 3.13.1 现状(实测,读码;xlings 2026.12.5.2) + +| 现象 | 原因 | 来源 | +|---|---|---| +| 首次初始化打印四行网络状态(`Network xim GLOBAL raw.githubusercontent.com: reachable (proxy)` 等) | 初始化与 `mcpp self doctor` 经同一函数逐项打印「索引 × 区域」:两个索引、两个区域,同一主机说两次 | 实测;读码 | +| 这些行不经界面模块 | 直接写标准错误,登记在写者清单中(§3.11.2 第 4 条) | 读码 | +| 新 home 的 `mirror` 写为 `auto`,mcpp 的注释称安装器按延迟选择区域 | 安装器不认识 `auto` 这个区域名:资源服务器按 GLOBAL 取(唯一候选,不做比较),索引按「本区域、GLOBAL、其余」的链取,结果是 GitHub 优先、失败后 GitCode。注释所说的按延迟排序是安装器为配方中 GitHub 链接排代理顺序的模块,与区域无关 | 读安装器源码 | +| 网络检查测得的可达性与耗时不参与任何决定 | 只被打印 | 读码 | +| 网络问题的提示分在三处,措辞各异,并列出含 `auto` 的三个值 | 初始化的 `Hint`、安装器调用失败的提示、下载中止的提示各自成文 | 读码 | +| 中国大陆未经代理的机器首次安装工具链很慢 | 先连 GitHub,常见连得上、传得慢,直到下载被判为停滞才转向 GitCode | 实测(mcpp#1042 的截图:约 300 MB,4.8 MB/s 之前的等待) | + +mcpplibs.os 0.4.8 没有读取地区与时区的接口;mcpp 只在判断字符宽度时读 `LANG`(`src/ui/terminal.cpp`)。 + +#### 3.13.2 设计 + +**一、地区与时区(mcpplibs.os,一个新版本)。** + +1. 新模块 `mcpplibs.os.locale`,由 `mcpplibs.os` 导出:`locale::region()` 是用户设置的地区,ISO 3166-1 的两个字母 + (`CN`);`locale::time_zone()` 是系统时区的名字,按系统的写法:POSIX 上为 IANA 的名字,Windows 上为时区的键名 + (`China Standard Time`)。读不到时为空。 +2. 来源:地区取 `LC_ALL`、`LC_MESSAGES`、`LANG` 中第一个已设置且不是 `C`、`POSIX` 的值的地区部分(`zh_CN.UTF-8` + 给出 `CN`),macOS 在三者都未设置时取用户的区域设置,Windows 取用户的地理位置;时区取 `TZ`,否则 + `/etc/localtime` 指向的 zoneinfo 文件的相对名,Windows 取动态时区信息的键名。不联网,不启动进程。镜像与 wasm + 模块为空。按该仓库的规范:模块、两种系统的测试、CHANGELOG、发布与 mcpp-index 的条目。 + +**二、镜像的初值:区域先验,实测核对,逐级回退(mcpp)。** + +3. 只在写入新 home 时决定一次,以及改写旧值 `auto` 时;已写明 `CN` 或 `GLOBAL` 的 home 与 `mcpp self config --mirror` + 的选择不被改动。 +4. 先验,确定且不需要网络:时区与地区表明中国大陆的,取 `CN`(GitCode 加速);其他取 `GLOBAL`。时区为主, + 地区为辅。 +5. 核对,实测:初始化本来就做的网络检查(两个区域并行,预算 2 秒)给出各区域的可达性。先验的区域不可达而另一 + 区域可达,取另一区域;两者都可达,取先验,耗时的起伏不使选择摇摆,且 GLOBAL 是源头、GitCode 是随后同步的镜像; + 两者都不可达或离线,取先验,并按第四部分提示。 +6. 写入明确的 `CN` 或 `GLOBAL`,不另说一行:没有网络问题时,选择本身不需要读者处理。选择与依据(时区、地区、可达性) + 在 `--verbose` 与 `mcpp self doctor` 中写出。 +7. `auto` 不再写入。`mcpp self config --mirror auto` 按第 4、5 条重新决定并写入结果,已有脚本照常工作;home 中已有的 + `auto` 在下一次初始化检查时按同一规则改写一次,同样不另说。`auto` 在安装器中实际等于 GLOBAL,所以中国大陆以外的 + 机器行为不变。 + +**三、网络检查的输出(mcpp)。** + +8. 一行,计数为检查过的端点(索引 × 区域):`Network 4/4 reachable`,经代理时加 `(proxy)`;有失败时为 + `Network 2/4 reachable`,其后一行 `help:`(第 10 条)。初始化与 `mcpp self doctor` 相同。 +9. 每个端点一行(索引、区域、主机、状态、耗时、代理)只在 `--verbose` 下出现。输出经界面模块,`src/config.cppm` + 从写者清单中去掉。 + +**四、网络问题的提示:多层,每条命令每种一次,只提示不中断(mcpp)。** + +10. 一个函数产生网络的建议:发生了什么与测得的数、当前的镜像、可照抄的命令。`help:` 不替使用者选定镜像: + `help: check the network or proxy, or choose a mirror: mcpp self config --mirror (now GLOBAL)`。 + 它只在第 11 条的网络问题中出现;网络正常的运行不说任何与镜像有关的话。 +11. 触发与位置: + + | 层 | 触发 | 位置与形式 | 中断 | + |---|---|---|---| + | 检查 | 初始化或 doctor 的检查有失败 | 第 8 条那一行之后的 `help:` | 否 | + | 慢 | 有下载进行,最近 30 秒的总速度低于 100 KB/s | 终端:进度行的速度后标 `slow`,区域之上写一次警告;非终端:一行警告 | 否 | + | 停滞 | 安装器的停滞判定,或 mcpp 的进度期限 | 已有的消息之后的 `help:` | 已有的行为 | + | 失败 | `E_NETWORK`、超时、索引刷新失败 | 错误消息之后的 `help:` | 已有的行为 | + | 收尾 | 本次运行出现过以上任一 | 命令的输出之后一行 `tip:`(`diag::closing`),是读者与 agent 最后读到的一行 | 否 | + +12. 机器输出:诊断带代码 `MCPP_NETWORK_SLOW`、`MCPP_NETWORK_UNREACHABLE`,字段 `mirror`(当前)、`mirrors`(可选的值)、 + `command`;`mcpp explain` 各有一条。现有的三处提示改为调用第 10 条的函数。 +13. 速度的窗口只计下载进行的时间;一次下载不足 30 秒不判定;同一命令中慢的警告只说一次。 + +**验收。** mcpplibs.os:地区与时区的解析(各种 `LANG` 写法、`C`、`TZ`、`/etc/localtime` 的链接)。mcpp 单元:先验的 +判定表、核对的四种情形、速度窗口。e2e:以 `TZ`、`LANG` 与假的网络检查初始化新 home,断言写入的值与说明的一行; +检查的一行与 `--verbose` 的明细;假的安装器以慢速发出进度,断言警告一次、`tip:` 一行、JSON 的代码与字段,且安装 +照常完成;`mcpp self config --mirror auto` 写入推断的值。 + ## 4. 各仓库改动的性质、最佳方案与理由 性质分四类:**缺陷修复**(实现与已写明的行为不符,或默认配置失败)、**优化**(结果不变,时机或信息更好)、 @@ -1228,6 +1301,10 @@ CPS 是其中一种被读取的描述。`mcpp-package.json` 仍是 mcpp 的权 | mcpp | 20a 库包写出 `.cps`(D19、D20) | 新功能 | 与 `.pc` 同源、同位、同一条说明;`[pack] descriptions` 为覆盖 | CMake 4.3+ 与 Conan 不经 mcpp 即可使用 mcpp 的库包;事实已在引擎中,放在别处是第二份实现 | | mcpp | 20b 构建程序声明前缀中的包(D22) | 新功能 | 声明 `cps_package`,引擎在应用指令之前把它展开为已有指令的效果 | 其他包管理器的包经构建程序进入是 mcpp 既有的方式;展开的结果与手写指令相同,不增加清单、索引、锁的概念 | | mcpp | 20c CPS 的代码自成模块包(D24) | 结构 | `modules/cps/` 加每个使用处一个适配文件 | CPS 是边界上的可选兼容;去掉它不改变 mcpp 的其余部分 | +| mcpp | 22a 网络检查一行,明细在 `--verbose` | 优化 | 计数 `x/y`,有失败时一行 `help:` | 四行说的是两个主机的同一件事;区域与主机是诊断的细节 | +| mcpp | 22b 镜像的初值:区域先验、实测核对(D28) | 缺陷修复 | 初始化时写入明确的 `CN` 或 `GLOBAL`,`auto` 改写一次 | 实测 `auto` 在安装器中等于 GLOBAL,注释所称的按延迟选择不存在 | +| mcpp | 22c 网络问题的多层提示(D30、D31) | 优化 | 一个函数,五层触发,每条命令每种一次,只提示不中断 | 三处提示各自成文;慢而未失败时没有任何提示 | +| mcpplibs.os | 22d `locale::region()`、`locale::time_zone()`(D29) | 新功能 | 新模块,按系统的写法给出;不联网、不启动进程 | 平台的事实属于平台层;mcpp 不保留自己的一层 | | xim-pkgindex | 21 `relocate_cps`、`declare_cps` | 新功能 | 载荷自己的 `.cps` 写入绝对 `prefix`,再声明进环境的 `usr/lib/cps/<名>/`(M13) | 与 `declare_pkgconfig` 同一位置、同一用法;链接到环境的文件推导出错误的前缀 | | openkal-windows | 12 启动时的名字(mcpp#1032) | 缺陷修复 | 三步称呼,前两步与句柄核对为同一对象 | 与直接启动的结果一致;不增加状态、不改规范;边界(当前目录之外的工作目录)写明 | | openkal-musl | 13 C 库一层的陈述(openkal-musl#93) | 新功能 | `posix_spawn_file_actions_addclosefrom_np` | 别的 C 库已有的词与含义;内核抽象层已有对应的启动;默认值不变 | @@ -1294,7 +1371,8 @@ CPS 是其中一种被读取的描述。`mcpp-package.json` 仍是 mcpp 的权 | 3 | mcpp-index | cmdline 新版本的条目(条目自带的自动更新) | cmdline | 上述检查 | | 4 | openkal-musl | 改动 13,§3.4.3 的测试;依赖范围接纳上面的版本 | openkal 各实现 | 外部子进程只有 0、1、2,环境与给出的相同 | | 5 | openkal-llvm-runtime、mcpplibs.os | 按家族的确切版本钉级联;无功能改动 | 上一行 | 各自的 CI | -| 6 | mcpp | 改动 1 至 11、改动 20 与两条说明;mcpplibs.os 与 mcpplibs.cmdline 的新版本;SPEC-004、006、007、011、014、017、019 的条款;docs/01、03、04、07、08、09、10、12、14、20、25、26、30、50、52 两种语言;示例 05 与 14;`docs/mcpp-skills/`;CHANGELOG | 第 1、3、5 行 | §10.3 | +| 5 | mcpplibs.os | 改动 22d,发布一个新版本,mcpp-index 登记 | — | 库自己的测试,三个平台 | +| 6 | mcpp | 改动 1 至 11、改动 20、改动 22a 至 22c 与两条说明;mcpplibs.os 与 mcpplibs.cmdline 的新版本;SPEC-004、006、007、011、014、017、019 的条款;docs/01、03、04、07、08、09、10、12、14、20、25、26、30、50、52 两种语言;示例 05 与 14;`docs/mcpp-skills/`;CHANGELOG | 第 1、3、5 行(含 mcpplibs.os 的 22d) | §10.3 | | 6 | xim-pkgindex | 改动 21 | — | `relocate_cps`、`declare_cps` 的测试;mcpp 的条目在有无该函数的索引中都安装成功 | 次序相同的行互不依赖,可以同时进行。探针 PR(mcpp#1035)保留到 mcpp 的发布完成。mcpp 的改动 3、6、8、9、10 不依赖 @@ -1340,6 +1418,10 @@ mcpp#1027。 | **D25** | 一个包的信息(2026-12-05) | **`mcpp info <包>`**,与 `search` 并列,读同一份索引与工程(§3.9.4 第 4 条) | 名为 `pkginfo`:与 `xlings info` 等既有习惯不一致,且 mcpp 的命令不带对象前缀。扩展 `search` 的输出:一次查询的列表与一个包的详情是两种回答 | | **D26** | `mcpp add` 写出的形式(2026-12-05) | **完整身份的点号键,按名字的次序;已有的命名空间表头被保留**(§3.9.4 第 5 条) | 一律改写为点号键:改动用户自己选择的形式。继续为缺省命名空间写裸键:同一个清单里两种写法,且依赖于缺省命名空间这一隐含的事实 | | **D27** | agent 发现 mcpp 自身的缺陷时(2026-12-05) | **本地分析与绕过,报告与修复先经使用者同意,建成后给出地址**(§3.9.4 第 2 条) | 不提报告:缺陷留在使用者的工程里。由 agent 自行提交:对外发布的内容未经使用者看过 | +| **D28** | 镜像的初值(2026-12-05) | **区域先验(时区为主、地区为辅),实测核对可达性,逐级回退;写入明确的值,不写 `auto`**(§3.13.2 二) | 只按语言:语言不是位置,海外的中文使用者与用英文的中国大陆开发者都判反。只按测量:选择随耗时起伏摇摆,且测量需要网络。继续写 `auto`:安装器中它等于 GLOBAL | +| **D29** | 地区与时区的读取放在哪里(2026-12-05) | **mcpplibs.os 的新模块与新版本** | mcpp 自己的 `src/native`:平台的事实在 mcpp 中保留第二层,违背依赖而不复制 | +| **D30** | 下载慢(2026-12-05) | **最近 30 秒低于 100 KB/s 时提示,不中断** | 中断或自动换镜像:丢掉进行中的下载;换镜像已由安装器在停滞时做 | +| **D31** | 提示中的镜像(2026-12-05) | **只给命令与当前的值,不替使用者选定**(`--mirror (now GLOBAL)`) | 建议另一个镜像:两个区域都慢时是错的建议 | | — | 诊断 | §10 的规则与清单是本轮验收的一部分 | — | 另有先前作出、本文据以设计的决定:引擎不内置厂商工具链的名字;索引的缺包补齐;交付物的环境经 `[xlings]` 这一 @@ -1524,6 +1606,11 @@ mcpp#1027。 | 一个依赖因条目的修订改变而重装 | 与下载相同 | 一行,动词 `Updating` | 修订从几到几 | | 条目的写法超出读者的语法 | 无消息;修订读作 0 | `mcpp xpkg parse` · 错误;构建时不报告、不重装 | 点名条目、版本与读不懂的那个值;补救:写成内联的表 | | 等待另一个进程的安装 | `Waiting for another mcpp of this home, installing <包>` | 与 §3.7.2 同一形状 | 等的是哪个包的锁或状态锁;持有者的记录与可见性;`--lock-wait` | +| 首次初始化的网络检查 | 每个「索引 × 区域」一行,共四行 | 初始化 · 状态行 | `Network 4/4 reachable`,经代理时加 `(proxy)`;明细在 `--verbose`(§3.13.2 第 8、9 条) | +| 网络检查有失败 | 每个失败的端点一行,加一行列出 `auto\|CN\|GLOBAL` 的 `Hint` | 初始化、doctor · 状态行与 `help:` · `MCPP_NETWORK_UNREACHABLE` | `Network 2/4 reachable`;`help: check the network or proxy, or choose a mirror: mcpp self config --mirror (now GLOBAL)` | +| 写入镜像的初值 | 写 `auto`,不说 | 不报告;`--verbose` 与 `mcpp self doctor` 写出选择与依据 | — | +| 下载慢 | 无消息 | 下载中 · 警告 · `MCPP_NETWORK_SLOW` | `downloads are slow: 38 KB/s over the last 30 s (<包>)`;终端的进度行标 `slow`;`help:` 同上;不中断 | +| 本次运行出现过网络问题 | 无 | 命令结束 · `tip:` | 一行:检查网络或代理,或 `mcpp self config --mirror `,并写出当前的值 | openkal 一侧没有诊断通道,它的「消息」是返回值与文档:`posix_spawn_file_actions_addclosefrom_np` 对 `lowfd > 3` 返回 `ENOSYS`,端口的差异表写明含义与理由;旧版本的库没有这个符号,调用者在链接时得知。openkal-windows 在核对 From 17438750de170ddcec21123343b1faef42cd07f4 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 22:52:12 +0900 Subject: [PATCH 36/36] The mirror is chosen where the home is made; a network problem is one warning with one advice A new home's mirror is CN where the time zone is mainland China's and GLOBAL elsewhere; where the zone states no place (UTC), the locale's region decides. The first network check of the home replaces a choice whose region it does not reach while it reaches the other. The value is written as CN or GLOBAL, never `auto`, which the provider reads as GitHub first, with its basis beside it (registry/.mcpp-mirror), shown by `mcpp self config` and `mcpp self doctor`. `mcpp self config --mirror auto` chooses again; a home that states `auto` is given the chosen value once. A project's provider environment states no mirror, so the home's applies. The network check is one line; each source is listed under --verbose. A source not reached, a download that stops, and downloads below 100 KB/s over 30 s of the provider's time are each one warning (MCPP_NETWORK_UNREACHABLE, MCPP_NETWORK_SLOW) with the advice that names `mcpp self config --mirror ` and the mirror in effect, and the run ends with one `tip:` line; a slow download is not interrupted. The time zone and the region come from mcpplibs.os 0.4.9 (mcpplibs.os.locale). --- .../2026-11-27-ecosystem-boundary-design.md | 34 ++-- .github/tools/stderr-writers.baseline | 1 - CHANGELOG.md | 17 ++ docs/09-commands-by-scenario.md | 6 +- docs/25-home-indices-and-store.md | 20 ++- docs/mcpp-skills/mcpp-self/SKILL.md | 4 +- docs/zh/09-commands-by-scenario.md | 3 +- docs/zh/25-home-indices-and-store.md | 12 +- mcpp.toml | 2 +- modules/invocation/mcpp.toml | 2 +- modules/manifest/mcpp.toml | 2 +- modules/toolchain-model/mcpp.toml | 2 +- src/cli.cppm | 4 +- src/config.cppm | 168 +++++++++++++----- src/doctor.cppm | 26 ++- src/explain.cppm | 9 + src/pack/distribution.cppm | 2 +- src/pm/package_fetcher.cppm | 17 +- src/provider/network.cppm | 166 +++++++++++++++++ src/provider/provider.cppm | 5 +- src/provider/xlings/provider.cppm | 1 + src/provider/xlings/xlings.cpp | 59 +++++- src/provider/xlings/xlings.cppm | 17 +- tests/e2e/index/local.cpp | 58 +++++- tests/e2e/self/config.cpp | 60 ++++++- tests/e2e/self/homes.cpp | 6 +- tests/support/src/support.cppm | 1 + tests/unit/test_network.cpp | 50 ++++++ 28 files changed, 647 insertions(+), 107 deletions(-) create mode 100644 src/provider/network.cppm diff --git a/.agents/docs/2026-11-27-ecosystem-boundary-design.md b/.agents/docs/2026-11-27-ecosystem-boundary-design.md index cae227363..35f014467 100644 --- a/.agents/docs/2026-11-27-ecosystem-boundary-design.md +++ b/.agents/docs/2026-11-27-ecosystem-boundary-design.md @@ -1214,8 +1214,9 @@ mcpplibs.os 0.4.8 没有读取地区与时区的接口;mcpp 只在判断字符 (`CN`);`locale::time_zone()` 是系统时区的名字,按系统的写法:POSIX 上为 IANA 的名字,Windows 上为时区的键名 (`China Standard Time`)。读不到时为空。 2. 来源:地区取 `LC_ALL`、`LC_MESSAGES`、`LANG` 中第一个已设置且不是 `C`、`POSIX` 的值的地区部分(`zh_CN.UTF-8` - 给出 `CN`),macOS 在三者都未设置时取用户的区域设置,Windows 取用户的地理位置;时区取 `TZ`,否则 - `/etc/localtime` 指向的 zoneinfo 文件的相对名,Windows 取动态时区信息的键名。不联网,不启动进程。镜像与 wasm + 给出 `CN`),Windows 先取用户的地理位置;时区取 `TZ`,否则 `/etc/localtime` 指向的 zoneinfo 文件的相对名 + (macOS 相同),再否则 `/etc/timezone`,Windows 取动态时区信息的键名。Windows 的 `China Standard Time` 同时是 + 香港的时区,有地区时由地区决定。不联网,不启动进程。镜像与 wasm 模块为空。按该仓库的规范:模块、两种系统的测试、CHANGELOG、发布与 mcpp-index 的条目。 **二、镜像的初值:区域先验,实测核对,逐级回退(mcpp)。** @@ -1235,8 +1236,9 @@ mcpplibs.os 0.4.8 没有读取地区与时区的接口;mcpp 只在判断字符 **三、网络检查的输出(mcpp)。** -8. 一行,计数为检查过的端点(索引 × 区域):`Network 4/4 reachable`,经代理时加 `(proxy)`;有失败时为 - `Network 2/4 reachable`,其后一行 `help:`(第 10 条)。初始化与 `mcpp self doctor` 相同。 +8. 一行,计数为检查过的端点(索引 × 区域):`Network 4/4 reachable`,经代理时加 `(proxy)`;有失败时这一行由一条 + 警告代替:`the network check reached 2/4 sources; not reached: <主机>`,其后一行 `help:`(第 10 条)。初始化与 + `mcpp self doctor` 相同。 9. 每个端点一行(索引、区域、主机、状态、耗时、代理)只在 `--verbose` 下出现。输出经界面模块,`src/config.cppm` 从写者清单中去掉。 @@ -1249,20 +1251,22 @@ mcpplibs.os 0.4.8 没有读取地区与时区的接口;mcpp 只在判断字符 | 层 | 触发 | 位置与形式 | 中断 | |---|---|---|---| - | 检查 | 初始化或 doctor 的检查有失败 | 第 8 条那一行之后的 `help:` | 否 | - | 慢 | 有下载进行,最近 30 秒的总速度低于 100 KB/s | 终端:进度行的速度后标 `slow`,区域之上写一次警告;非终端:一行警告 | 否 | - | 停滞 | 安装器的停滞判定,或 mcpp 的进度期限 | 已有的消息之后的 `help:` | 已有的行为 | + | 检查 | 初始化或 doctor 的检查有失败 | 第 8 条的警告及其 `help:` | 否 | + | 慢 | 有下载进行,最近 30 秒的总速度低于 100 KB/s | 一条警告 `downloads are slow: <速度> KB/s over the last 30 s` 及其 `help:`,终端与非终端相同 | 否 | + | 停滞 | 安装器的停滞判定,或 mcpp 的进度期限 | 一条警告 `download stopped: <原因>` 及其 `help:` | 已有的行为 | | 失败 | `E_NETWORK`、超时、索引刷新失败 | 错误消息之后的 `help:` | 已有的行为 | | 收尾 | 本次运行出现过以上任一 | 命令的输出之后一行 `tip:`(`diag::closing`),是读者与 agent 最后读到的一行 | 否 | -12. 机器输出:诊断带代码 `MCPP_NETWORK_SLOW`、`MCPP_NETWORK_UNREACHABLE`,字段 `mirror`(当前)、`mirrors`(可选的值)、 - `command`;`mcpp explain` 各有一条。现有的三处提示改为调用第 10 条的函数。 -13. 速度的窗口只计下载进行的时间;一次下载不足 30 秒不判定;同一命令中慢的警告只说一次。 +12. 机器输出:诊断带代码 `MCPP_NETWORK_SLOW`、`MCPP_NETWORK_UNREACHABLE`,`mcpp explain` 各有一条,写出可选的值与 + 命令。JSON 诊断的字段集是 docs/50 的契约,不为这两个代码增加字段:代码与 `mcpp explain` 已给出命令。现有的三处 + 提示改为调用第 10 条的函数。进度行不另标 `slow`:下载区的一行只有名字、进度与速度,警告经同一个写者写在区域之上。 +13. 速度的窗口只计下载进行的时间,以安装器在每个进度帧中报告的时间(`elapsedSec`)计,不以 mcpp 读到帧的时刻计;一次下载 + 不足 30 秒不判定;同一命令中慢的警告只说一次。 **验收。** mcpplibs.os:地区与时区的解析(各种 `LANG` 写法、`C`、`TZ`、`/etc/localtime` 的链接)。mcpp 单元:先验的 判定表、核对的四种情形、速度窗口。e2e:以 `TZ`、`LANG` 与假的网络检查初始化新 home,断言写入的值与说明的一行; -检查的一行与 `--verbose` 的明细;假的安装器以慢速发出进度,断言警告一次、`tip:` 一行、JSON 的代码与字段,且安装 -照常完成;`mcpp self config --mirror auto` 写入推断的值。 +检查的警告与 `--verbose` 的明细;假的安装器以慢速发出进度,断言警告一次、`tip:` 是最后一行、`mcpp explain` 回答其 +代码,且安装照常完成;`mcpp self config --mirror auto` 写入推断的值与依据,明确的值去掉依据;旧值 `auto` 改写一次。 ## 4. 各仓库改动的性质、最佳方案与理由 @@ -1607,9 +1611,9 @@ mcpp#1027。 | 条目的写法超出读者的语法 | 无消息;修订读作 0 | `mcpp xpkg parse` · 错误;构建时不报告、不重装 | 点名条目、版本与读不懂的那个值;补救:写成内联的表 | | 等待另一个进程的安装 | `Waiting for another mcpp of this home, installing <包>` | 与 §3.7.2 同一形状 | 等的是哪个包的锁或状态锁;持有者的记录与可见性;`--lock-wait` | | 首次初始化的网络检查 | 每个「索引 × 区域」一行,共四行 | 初始化 · 状态行 | `Network 4/4 reachable`,经代理时加 `(proxy)`;明细在 `--verbose`(§3.13.2 第 8、9 条) | -| 网络检查有失败 | 每个失败的端点一行,加一行列出 `auto\|CN\|GLOBAL` 的 `Hint` | 初始化、doctor · 状态行与 `help:` · `MCPP_NETWORK_UNREACHABLE` | `Network 2/4 reachable`;`help: check the network or proxy, or choose a mirror: mcpp self config --mirror (now GLOBAL)` | -| 写入镜像的初值 | 写 `auto`,不说 | 不报告;`--verbose` 与 `mcpp self doctor` 写出选择与依据 | — | -| 下载慢 | 无消息 | 下载中 · 警告 · `MCPP_NETWORK_SLOW` | `downloads are slow: 38 KB/s over the last 30 s (<包>)`;终端的进度行标 `slow`;`help:` 同上;不中断 | +| 网络检查有失败 | 每个失败的端点一行,加一行列出 `auto\|CN\|GLOBAL` 的 `Hint` | 初始化、doctor · 警告与 `help:` · `MCPP_NETWORK_UNREACHABLE` | `the network check reached 2/4 sources; not reached: <主机>`;`help: check the network or proxy, or choose a mirror: mcpp self config --mirror (now GLOBAL)` | +| 写入镜像的初值 | 写 `auto`,不说 | 不报告;`--verbose`、`mcpp self config` 与 `mcpp self doctor` 写出选择与依据 | — | +| 下载慢 | 无消息 | 下载中 · 警告 · `MCPP_NETWORK_SLOW` | `downloads are slow: 38 KB/s over the last 30 s`;`help:` 同上;不中断 | | 本次运行出现过网络问题 | 无 | 命令结束 · `tip:` | 一行:检查网络或代理,或 `mcpp self config --mirror `,并写出当前的值 | openkal 一侧没有诊断通道,它的「消息」是返回值与文档:`posix_spawn_file_actions_addclosefrom_np` 对 `lowfd > 3` diff --git a/.github/tools/stderr-writers.baseline b/.github/tools/stderr-writers.baseline index 6cccdc564..ddd86a161 100644 --- a/.github/tools/stderr-writers.baseline +++ b/.github/tools/stderr-writers.baseline @@ -12,7 +12,6 @@ src/cli/cmd_self.cppm 7 src/cli/cmd_toolchain.cppm 1 src/cli/cmd_xpkg.cppm 1 src/cli.cppm 15 -src/config.cppm 3 src/doctor.cppm 5 src/fallback/xlings_binary.cppm 4 src/main.cpp 1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 88a325b11..0f379ca53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,23 @@ as the earlier `.xpkg.lua` is, so a toolchain it installed still declares its kernel headers and binutils. The SubOS linker wrapper the index's binutils carries honours the `XLINGS_SUBOS_LD_PATHS=0` mcpp states (openxlings/xlings#742, #752, #721, #540). +- A new home's mirror is chosen where the home is made: `CN` (GitCode) where the time zone is + mainland China's, `GLOBAL` (GitHub) elsewhere; where the zone states no place (`UTC`), the + locale's region decides. The first network check of the home replaces the choice when its region + is not reached and the other is. The value is written as `CN` or `GLOBAL`, never `auto`, which + the provider reads as GitHub first; its basis is kept beside it (`registry/.mcpp-mirror`) and + shown by `mcpp self config` and `mcpp self doctor`. `mcpp self config --mirror auto` chooses + again; a value stated with `--mirror` is kept as stated. A home from before that states `auto` + is given the chosen value once. A project's provider environment states no mirror, so the + home's applies; before, it stated `auto` and replaced the home's. mcpp depends on mcpplibs.os + 0.4.9 for the time zone and the region (`mcpplibs.os.locale`). +- The network check is one line, `Network 4/4 reachable`; each source is listed under + `--verbose`. A source the check does not reach, a download that stops and downloads that gain + less than 100 KB/s over 30 s are each one warning (`MCPP_NETWORK_UNREACHABLE`, + `MCPP_NETWORK_SLOW`) with one advice, + `check the network or proxy, or choose a mirror: mcpp self config --mirror (now GLOBAL)`, + and the run ends with one `tip:` line that repeats it; a slow download is not interrupted. A + run the network does not hinder says nothing of the mirror. - `mcpp --help` is printed from the command tree, in its groups, and ends with the line that points agents at `--agent-skill-doc`; the hand-written usage text is removed. Internal commands are hidden from the help and the completion. diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index 5b8d1d502..f173f4b49 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -651,8 +651,10 @@ warning: pre-v1 cache at '/home/speak/.mcpp/bmi' occupies 167.5 MiB and is no lo `mcpp self env` prints the paths and the resolved toolchain, `--format json` included. `mcpp self config --mirror CN|GLOBAL` selects the download mirror; -mcpp and xlings hold this setting separately, so selecting it for one does not -select it for the other. +a new home is given one by its time zone and its locale's region, and +`--mirror auto` chooses it again ([25](25-home-indices-and-store.md)). mcpp and +xlings hold this setting separately, so selecting it for one does not select it +for the other. ## Reusing another home, and a machine's system home diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index 22c7e742e..32610fbc7 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -116,9 +116,27 @@ baseline that only shrinks. ### Initialization and network diagnosis (2026.10.19.1+) `self env`, `self config`, `self doctor` and `toolchain list` read local state -without installing tools. `self config --mirror auto|CN|GLOBAL` updates only local +without installing tools. `self config --mirror CN|GLOBAL|auto` updates only local configuration, so it remains usable while the network is broken. +The mirror is the region downloads are taken from first: `CN` (GitCode) or +`GLOBAL` (GitHub), each falling back to the other. It is chosen once, when the +home is made *(2026.12.4.1+)*: `CN` where the time zone, or the locale's region +when the zone is UTC or unknown, is mainland China's, and `GLOBAL` otherwise; +the first network check keeps that choice unless its region was not reached +and the other was. `self config --mirror CN|GLOBAL` states it; `--mirror auto` +chooses again. A home that stated `auto` is given the chosen value once. +`self config` and `self doctor` show the mirror and what it was chosen by; a +run with no network problem says nothing about it. + +The network check of a new home is one line, `Network 4/4 reachable`; each +source it asked is listed under `--verbose`. A network problem is said once, +with `help: check the network or proxy, or choose a mirror: mcpp self config +--mirror (now GLOBAL)`, and the run ends with one `tip:` line; it +never stops a download. The problems are a source the check did not reach and +a download that stopped (`MCPP_NETWORK_UNREACHABLE`), downloads below 100 KB/s +over 30 s (`MCPP_NETWORK_SLOW`), and an install that failed on the network. + An install tracks byte progress and source changes separately for each active download. Time spent waiting for a download slot does not consume that budget. Progress on another file does not renew a stalled file's budget. diff --git a/docs/mcpp-skills/mcpp-self/SKILL.md b/docs/mcpp-skills/mcpp-self/SKILL.md index 19ea5d9eb..3011e9252 100644 --- a/docs/mcpp-skills/mcpp-self/SKILL.md +++ b/docs/mcpp-skills/mcpp-self/SKILL.md @@ -30,7 +30,9 @@ prints the line that loads it. ## Reads, writes, network `init` and `config` write the home; `doctor` and `env` read it; `--system` -maintains the machine's system home. Needs no project. +maintains the machine's system home. Needs no project. `doctor` checks the +network in one line; a network problem in any command is one warning that names +`mcpp self config --mirror ` and the mirror in effect. ## Refusals diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index 185acd8a2..ef85bcaa0 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -503,7 +503,8 @@ warning: pre-v1 cache at '/home/speak/.mcpp/bmi' occupies 167.5 MiB and is no lo ``` `mcpp self env` 打印路径与已解析的工具链,包括 `--format json`。 -`mcpp self config --mirror CN|GLOBAL` 选择下载镜像;mcpp 与 xlings 各自 +`mcpp self config --mirror CN|GLOBAL` 选择下载镜像;新 home 按时区与语言环境的地区得到一个, +`--mirror auto` 重新选择([25](25-home-indices-and-store.md))。mcpp 与 xlings 各自 持有这个设置,为其中一个选定,不会为另一个选定。 ## 复用另一个 home,以及机器的系统 home diff --git a/docs/zh/25-home-indices-and-store.md b/docs/zh/25-home-indices-and-store.md index 3b7a87c09..b28726dec 100644 --- a/docs/zh/25-home-indices-and-store.md +++ b/docs/zh/25-home-indices-and-store.md @@ -87,7 +87,17 @@ Windows 首次显式 `self init` 时,若 D 是可写的本地固定磁盘, ### 初始化与网络诊断(2026.10.19.1+) `self env`、`self config`、`self doctor` 和 `toolchain list` 读取本地状态,不安装工具。 -`self config --mirror auto|CN|GLOBAL` 仅更新本地配置,因此网络故障时仍可使用。 +`self config --mirror CN|GLOBAL|auto` 仅更新本地配置,因此网络故障时仍可使用。 + +镜像是下载首先取自的区域:`CN`(GitCode)或 `GLOBAL`(GitHub),两者互为回退。它在建立 home 时选定一次 +*(2026.12.4.1+)*:时区(时区为 UTC 或未知时取语言环境的地区)属于中国大陆时为 `CN`,否则为 `GLOBAL`;首次网络检查 +保留这一选择,除非它的区域不可达而另一区域可达。`self config --mirror CN|GLOBAL` 写明它;`--mirror auto` 重新选择。 +写着 `auto` 的 home 被改写为选定的值一次。`self config` 与 `self doctor` 显示镜像及其依据;没有网络问题的运行不提及它。 + +新 home 的网络检查为一行:`Network 4/4 reachable`;所检查的每个来源在 `--verbose` 下列出。网络问题只说一次, +附 `help: check the network or proxy, or choose a mirror: mcpp self config --mirror (now GLOBAL)`, +运行以一行 `tip:` 结束;它从不中断下载。网络问题包括:检查未能到达的来源与中止的下载(`MCPP_NETWORK_UNREACHABLE`), +30 秒内低于 100 KB/s 的下载(`MCPP_NETWORK_SLOW`),以及因网络而失败的安装。 安装过程分别跟踪每个活动下载的字节进度与来源切换,等待下载槽位的时间不消耗该预算。 其他文件取得进度不会延长停滞文件的预算。 diff --git a/mcpp.toml b/mcpp.toml index 71d422b8b..d1517c7c5 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -66,7 +66,7 @@ mcpplibs.mwrap.libc = "17.0.0" mcpplibs.mwrap.zlib = "1.3.2" mcpplibs.mwrap.zstd = "1.5.7" mcpplibs.mwrap.xz = "5.8.3.1" -mcpplibs.os = "0.4.8" +mcpplibs.os = "0.4.9" # The packages under modules/, linked into this binary; [workspace] members lets -p and # `mcpp test` address them, these path dependencies make them importable. diff --git a/modules/invocation/mcpp.toml b/modules/invocation/mcpp.toml index 554f2763e..d080fb78b 100644 --- a/modules/invocation/mcpp.toml +++ b/modules/invocation/mcpp.toml @@ -13,4 +13,4 @@ description = "The environment of one invocation of mcpp: statements over the st license = "Apache-2.0" [dependencies] -mcpplibs.os = "0.4.8" +mcpplibs.os = "0.4.9" diff --git a/modules/manifest/mcpp.toml b/modules/manifest/mcpp.toml index 61a32f44b..7b33c482e 100644 --- a/modules/manifest/mcpp.toml +++ b/modules/manifest/mcpp.toml @@ -25,7 +25,7 @@ mcpp.surface = { path = "../surface" } mcpp.toolchain-model = { path = "../toolchain-model" } mcpp.versioning = { path = "../versioning" } -mcpplibs.os = "0.4.8" +mcpplibs.os = "0.4.9" # Subsystem-level tests. They see only this package, which is what lets them # state its contract in isolation; the root `tests/unit/` states the facts two diff --git a/modules/toolchain-model/mcpp.toml b/modules/toolchain-model/mcpp.toml index eca5cda83..96c0f4101 100644 --- a/modules/toolchain-model/mcpp.toml +++ b/modules/toolchain-model/mcpp.toml @@ -23,7 +23,7 @@ license = "Apache-2.0" mcpp.invocation = { path = "../invocation" } mcpp.versioning = { path = "../versioning" } -mcpplibs.os = "0.4.8" +mcpplibs.os = "0.4.9" # Subsystem-level tests. They see only this package, which is what lets them # state its contract in isolation; the root `tests/unit/` states the facts two diff --git a/src/cli.cppm b/src/cli.cppm index 1a848486d..604ea7a3f 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -1056,8 +1056,8 @@ mcpplibs::cmdline::App command_tree(const std::vector& passthrough, .action(cmd_env_any)) .subcommand(cl::App("config") .description("Show or modify mcpp's configuration: the xlings mirror and the retention of build outputs") - .option(cl::Option("mirror").takes_value().value_name("auto|CN|GLOBAL") - .help("Set xlings mirror for mcpp's private registry")) + .option(cl::Option("mirror").takes_value().value_name("CN|GLOBAL|auto") + .help("Where downloads are taken from first: CN (GitCode) or GLOBAL (GitHub); auto chooses again")) .option(cl::Option("cache-unused-days").takes_value().value_name("DAYS") .help("Collect build-cache entries no build used for DAYS days (default 30; 0 keeps all)")) .option(cl::Option("keep-days").takes_value().value_name("DAYS") diff --git a/src/config.cppm b/src/config.cppm index 6000411d1..f732f473e 100644 --- a/src/config.cppm +++ b/src/config.cppm @@ -37,6 +37,8 @@ import mcpp.effects; import mcpp.home.files; import mcpp.log; import mcpp.diag; +import mcpp.ui; +import mcpp.provider.network; import mcpp.toolchain.triple; // pins: the host's first run, named in a hint import mcpp.fallback.xlings_binary; import mcpp.fallback.config_migration; @@ -360,28 +362,105 @@ std::string check_base_init(const GlobalConfig& cfg) { return {}; // all ok } -// Returns whether diagnosis found a warning. Network failure never prevents -// reuse of installed tools, and never changes the command's local errors. -bool report_network(const GlobalConfig& cfg, bool quiet = false) { - const auto report = mcpp::provider::open(make_xlings_env(cfg))->check_network(); - auto line = [&](std::string_view key, std::string_view value) { - if (!quiet) std::println(libc::stderr(), "{:>12} {}", key, value); - }; - if (report.status == "offline") { line("Network", "Skipped (offline mode)"); return false; } +// THE MIRROR MCPP CHOSE (design 2026-11-27 §3.13.2, items 3 to 7): the value it +// wrote and why, `CN: time zone Asia/Shanghai`, beside the provider's +// configuration. The file marks the value as inferred, which the first check +// of the network may correct; a value the user states removes it. +std::filesystem::path mirror_basis_file(const std::filesystem::path& xlingsHome) { + return xlingsHome / ".mcpp-mirror"; +} + +std::optional mirror_basis(const std::filesystem::path& xlingsHome) { + std::ifstream in(mirror_basis_file(xlingsHome), std::ios::binary); + std::string line; + if (!in || !std::getline(in, line) || line.empty()) return std::nullopt; + return line; +} + +void write_mirror_basis(const std::filesystem::path& xlingsHome, std::string_view mirror, std::string_view why) { + std::ofstream(mirror_basis_file(xlingsHome), std::ios::binary | std::ios::trunc) << mirror << ": " << why << "\n"; + mcpp::log::verbose("network", std::format("mirror {}: {}", mirror, why)); +} + +void forget_mirror_basis(const std::filesystem::path& xlingsHome) { + std::error_code ec; + std::filesystem::remove(mirror_basis_file(xlingsHome), ec); +} + +// The mirror in effect and why, for `mcpp self doctor` and `mcpp self config`. +std::string describe_mirror(const std::filesystem::path& xlingsHome, std::string_view mirror) { + if (mirror.empty()) return "none stated"; + if (const auto basis = mirror_basis(xlingsHome); basis && basis->starts_with(std::string(mirror) + ": ")) + return std::format("{} ({})", mirror, basis->substr(mirror.size() + 2)); + return std::format("{} (stated with mcpp self config --mirror)", mirror); +} + +// The first check of a home whose mirror mcpp inferred: the inference stands +// unless its region was not reached and the other region was. +void check_inferred_mirror(const std::filesystem::path& xlingsHome, const mcpp::provider::Provider& provider, + const mcpp::provider::NetworkReport& report) { + namespace net = mcpp::provider::network; + const auto basis = mirror_basis(xlingsHome); + const auto current = provider.mirror(); + if (!basis || current.empty() || !basis->starts_with(current + ": ")) return; + bool reached = false, otherReached = false; + for (const auto& e : report.endpoints) { + if (e.region == current) reached |= e.reachable; + else if (e.region == net::other(current)) otherReached |= e.reachable; + } + const auto chosen = net::checked(current, reached, otherReached); + if (chosen == current) return; + if (provider.set_mirror(chosen, /*quiet=*/true) != 0) return; + write_mirror_basis(xlingsHome, chosen, std::format("{}; {} was not reached and {} was", + basis->substr(current.size() + 2), net::host(current), net::host(chosen))); +} + +// THE NETWORK, IN ONE LINE (design 2026-11-27 §3.13.2, items 8 to 10): the +// sources reached of those checked; each source is in --verbose. A source not +// reached is one warning, with the advice that names the command and the +// mirror in effect. Returns whether the check found a problem. A network +// failure never prevents reuse of installed tools, and never changes the +// command's local errors. `choose`: the first initialization of the home, where +// an inferred mirror is checked against what was reached. +bool report_network(const GlobalConfig& cfg, bool quiet = false, bool choose = false) { + const auto provider = mcpp::provider::open(make_xlings_env(cfg)); + const auto report = provider->check_network(); + if (report.status == "offline") { + if (!quiet) mcpp::ui::status("Network", "Skipped (offline mode)"); + return false; + } if (report.status != "checked") { - line("Network", std::format("Check {} (local operations remain available)", report.status)); + if (!quiet) mcpp::ui::status("Network", std::format("Check {} (local operations remain available)", report.status)); return true; } - bool failed = false; - if (report.endpoints.empty()) line("Network", "No remote index sources configured"); + if (report.endpoints.empty()) { + if (!quiet) mcpp::ui::status("Network", "No remote index sources configured"); + return false; + } + if (choose) check_inferred_mirror(cfg.xlingsHome(), *provider, report); + std::size_t reached = 0; + bool proxy = false; + std::string missed; for (const auto& e : report.endpoints) { - line("Network", std::format("{} {} {}: {}{}", e.resource, - e.region.empty() ? "custom" : e.region, e.host.empty() ? "endpoint" : e.host, - e.status, e.proxy ? " (proxy)" : "")); - failed |= !e.reachable; + mcpp::log::verbose("network", std::format("{} {} {}: {}{}{}", e.resource, + e.region.empty() ? "custom" : e.region, e.host.empty() ? "endpoint" : e.host, e.status, + e.elapsedSeconds > 0 ? std::format(", {:.0f} ms", e.elapsedSeconds * 1000) : std::string(), + e.proxy ? " (proxy)" : "")); + reached += e.reachable ? 1 : 0; + proxy |= e.proxy; + const auto name = e.host.empty() ? e.resource : e.host; + if (!e.reachable && missed.find(name) == std::string::npos) + missed += (missed.empty() ? "" : ", ") + name; } - if (failed) line("Hint", "Check proxy settings or use mcpp self config --mirror auto|CN|GLOBAL"); - return failed; + const auto total = report.endpoints.size(); + if (reached == total) { + if (!quiet) mcpp::ui::status("Network", std::format("{}/{} reachable{}", reached, total, proxy ? " (proxy)" : "")); + return false; + } + mcpp::provider::network::trouble("network/unreachable", + std::format("the network check reached {}/{} sources; not reached: {}", reached, total, missed), + provider->mirror()); + return true; } // Delete the registry directory (sandbox) for a clean re-init. @@ -495,21 +574,10 @@ namespace t = mcpp::libs::toml; namespace { -// Right-pad a verb to 12 columns, matching mcpp::ui::verb_padded so the -// bootstrap status lines line up under the cyan "Downloading …" lines -// produced via the BootstrapProgressCallback. We can't import mcpp.ui -// from here (cyclic dep), so this is a tiny duplicate of that helper — -// no color, no fanciness. It writes to standard error, which is the stream -// mcpp.ui narrates on: a status line is never a command's result, and a -// pipe that reads the result must not receive it. -void print_status(std::string_view verb, std::string_view msg) { - constexpr std::size_t W = 12; - if (verb.size() >= W) { - std::println(libc::stderr(), "{} {}", verb, msg); - } else { - std::println(libc::stderr(), "{}{} {}", std::string(W - verb.size(), ' '), verb, msg); - } -} +// The bootstrap's status lines, through the narration stream's one writer +// (design 2026-11-27 §3.11.2, point 4): standard error, never a command's +// result. +void print_status(std::string_view verb, std::string_view msg) { mcpp::ui::status(verb, msg); } // config.toml and .xlings.json are read by every mcpp of the home: programs that // start at once on a fresh home each write config.toml, and an in-place rewrite @@ -606,15 +674,19 @@ bool write_default_xlings_json(const std::filesystem::path& path, // construct a temporary Env with home = path.parent_path(). mcpp::provider::Location env; env.home = path.parent_path(); - // No explicit --mirror: seed "auto" so xlings' own adaptive mirror module - // (latency-probed, with per-download failover) picks the best reachable - // host. The historic hardcoded "CN" FORCED the CN mirror and disabled that - // mechanism, stranding overseas users and GitHub-hosted CI on a - // slow/unreachable gitcode. An explicit --mirror always wins (else branch). - if (mirror_override.empty()) - mcpp::provider::open(env)->seed(pairs); // default = "auto" - else + // THE MIRROR, CHOSEN ONCE (design 2026-11-27 §3.13.2, items 3 to 6): by + // where the user is -- CN for mainland China, GLOBAL otherwise -- and + // recorded as inferred, which the first check of the network may correct. + // An explicit --mirror is written as given and is never corrected. + if (mirror_override.empty()) { + const auto at = mcpp::provider::network::this_machine(); + const auto mirror = mcpp::provider::network::prior(at); + mcpp::provider::open(env)->seed(pairs, mirror); + write_mirror_basis(env.home, mirror, mcpp::provider::network::basis(at)); + } else { mcpp::provider::open(env)->seed(pairs, mirror_override); + forget_mirror_basis(env.home); + } return std::filesystem::exists(path); } @@ -1364,6 +1436,17 @@ std::expected load_or_init( } else { mcpp::fallback::migrate_xlings_json_index_names(xjson); reconcile_index_repos(xjson, cfg.indexRepos, quiet, cfg.registryBorrowed); + // A home from before 2026.12.4.1 states `auto`, which xlings reads as + // no region (GitHub first): it is inferred as a new home's is, once. + if (!cfg.registryBorrowed) { + const auto provider = mcpp::provider::open(make_xlings_env(cfg)); + if (provider->mirror() == "auto") { + const auto at = mcpp::provider::network::this_machine(); + const auto mirror = mcpp::provider::network::prior(at); + if (provider->set_mirror(mirror, /*quiet=*/true) == 0) + write_mirror_basis(cfg.xlingsHome(), mirror, mcpp::provider::network::basis(at) + "; was auto"); + } + } } { // A home from before: its indices' places recorded, their data moved @@ -1450,7 +1533,7 @@ std::expected load_or_init( const bool bootstrapAllowed = mcpp::effects::install_sources() != mcpp::effects::InstallSources::None; ensure_sandbox_xlings_binary(cfg, quiet); if (bootstrapAllowed) { - if (!check_base_init(cfg).empty()) report_network(cfg, quiet); + if (!check_base_init(cfg).empty()) report_network(cfg, quiet, /*choose=*/true); ensure_sandbox_init(cfg, quiet); } else if (!quiet) { // Once per process: the doctor loads the configuration more than once, @@ -1572,7 +1655,8 @@ bool ensure_project_index_dir( // Seed .xlings.json with the custom index entries. mcpp::provider::Location env; env.home = dotMcpp; - mcpp::provider::open(env)->seed(customRepos, "auto", penv); + // No mirror: the home's applies (mcpp.provider.network). + mcpp::provider::open(env)->seed(customRepos, {}, penv); auto exposeLocalIndex = [&](const std::string& name, const std::filesystem::path& source, diff --git a/src/doctor.cppm b/src/doctor.cppm index c327d53ae..f461c72ef 100644 --- a/src/doctor.cppm +++ b/src/doctor.cppm @@ -45,6 +45,7 @@ import mcpp.ui; import mcpp.diag; import mcpp.provider; import mcpp.provider.select; +import mcpp.provider.network; import mcpplibs.os.fs; namespace libc = mcpplibs::mwrap::libc::macros; @@ -219,6 +220,8 @@ export int doctor_report() { if (cfg) { report_home(*cfg); if (mcpp::config::report_network(*cfg)) ++warns; + const auto provider = mcpp::provider::open(mcpp::config::make_xlings_env(*cfg)); + mcpp::ui::status("Mirror", mcpp::config::describe_mirror(cfg->xlingsHome(), provider->mirror())); } // ONE PREPARE, READ-ONLY, AND THE SECTIONS BELOW REPORT ON IT (design @@ -2158,11 +2161,15 @@ export int self_config(std::string mirror, std::optional cacheUnus mirror = upper_ascii(std::move(mirror)); if (mirror != "CN" && mirror != "GLOBAL" && mirror != "AUTO") { mcpp::ui::error(std::format( - "invalid mirror '{}'; expected auto, CN or GLOBAL", mirror)); + "invalid mirror '{}'; expected CN, GLOBAL or auto", mirror)); return 2; } } - if (mirror == "AUTO") mirror = "auto"; + // `auto` is no region (design 2026-11-27 §3.13.2, item 7): it asks for the + // value a new home is given -- by where the user is, then checked against + // the network -- and that value is written. + const bool infer = mirror == "AUTO"; + if (infer) mirror = std::string(mcpp::provider::network::prior(mcpp::provider::network::this_machine())); // Reading configuration is side-effect free; changing it creates only // local configuration. Neither operation bootstraps or invokes a download. @@ -2177,6 +2184,8 @@ export int self_config(std::string mirror, std::optional cacheUnus auto env = mcpp::config::make_xlings_env(*cfg); if (mirror.empty()) { report_home(*cfg); + mcpp::ui::status("Mirror", mcpp::config::describe_mirror(cfg->xlingsHome(), + mcpp::provider::open(env)->mirror())); mcpp::ui::status("Retention", std::format( "build cache: entries unused for {} days ([cache] unused_days); a project's build " "directories: unused for {} days ([build] keep_days)", cfg->cacheUnusedDays, @@ -2190,7 +2199,18 @@ export int self_config(std::string mirror, std::optional cacheUnus mcpp::ui::error(std::format("failed to set xlings mirror to {}", mirror)); return 1; } - mcpp::ui::status("Configured", std::format("xlings mirror = {}", mirror)); + if (infer) { + // The check is quiet: the value it settles is the one line below, and + // only a source not reached is a warning. A home whose provider is not + // installed yet is checked at its first initialization. + const auto at = mcpp::provider::network::this_machine(); + mcpp::config::write_mirror_basis(cfg->xlingsHome(), mirror, mcpp::provider::network::basis(at)); + (void)mcpp::config::report_network(*cfg, /*quiet=*/true, /*choose=*/true); + } else { + mcpp::config::forget_mirror_basis(cfg->xlingsHome()); + } + mcpp::ui::status("Configured", std::format("xlings mirror = {}", mcpp::config::describe_mirror( + cfg->xlingsHome(), mcpp::provider::open(env)->mirror()))); return 0; } diff --git a/src/explain.cppm b/src/explain.cppm index 122a4af0c..fb4f04356 100644 --- a/src/explain.cppm +++ b/src/explain.cppm @@ -114,6 +114,15 @@ constexpr Entry kEntries[] = { {"MCPP_SEARCH_FAILED", Kind::Diagnostic, "`mcpp search --format json` could not read the indexes", "`mcpp index status` shows each index; `mcpp index update` refreshes them."}, + {"MCPP_NETWORK_UNREACHABLE", Kind::Diagnostic, + "a source the network check asked was not reached, or a download stopped", + "Check the network or proxy, or choose a mirror: mcpp self config\n" + "--mirror CN (GitCode) or --mirror GLOBAL (GitHub). `mcpp self doctor`\n" + "checks each source; --verbose lists them."}, + {"MCPP_NETWORK_SLOW", Kind::Diagnostic, + "downloads gained less than 100 KB/s over 30 s", + "The download goes on. Check the network or proxy, or choose a mirror:\n" + "mcpp self config --mirror CN (GitCode) or --mirror GLOBAL (GitHub)."}, {"prepare.failed", Kind::Diagnostic, "`mcpp why target|platform|flags --format json`: the build could not be prepared", "The message carries the refusal and its reason token; `mcpp explain\n" diff --git a/src/pack/distribution.cppm b/src/pack/distribution.cppm index c5003f678..ca83dbcac 100644 --- a/src/pack/distribution.cppm +++ b/src/pack/distribution.cppm @@ -98,7 +98,7 @@ std::string exe_launcher_main(const Launch& l); // When the two shared one resolution, this had to be the release the plugin // linked (0.4.5, through mcpp.plugins 0.26.1): 0.4.4 and 0.4.6 were refused as // irreconcilable (e2e 988, the canaries' pack cells). -inline constexpr std::string_view kLauncherOs = "0.4.8"; +inline constexpr std::string_view kLauncherOs = "0.4.9"; // ─── mcpp-package.json (SPEC-014 §4.5) ──────────────────────────────────── diff --git a/src/pm/package_fetcher.cppm b/src/pm/package_fetcher.cppm index 260be83b5..91a409d1c 100644 --- a/src/pm/package_fetcher.cppm +++ b/src/pm/package_fetcher.cppm @@ -23,6 +23,7 @@ import mcpp.diag; import mcpp.pm.index_spec; import mcpp.provider; import mcpp.provider.select; +import mcpp.provider.network; import nlohmann.json; export namespace mcpp::pm { @@ -1196,10 +1197,14 @@ ParsedTarget parse_target(std::string_view target, std::string_view defaultIndex // failure used to end in "check network and retry": a phone whose app sandbox // refused hard links was sent to check its network (design 2026-10-10 §13). std::string install_failure_hint(const std::optional& error, - const std::filesystem::path& home) { + const std::filesystem::path& home, std::string_view mirror) { const std::string code = error ? error->code : std::string{}; - if (code == "E_NETWORK") - return "run `mcpp self doctor` to check the configured sources, then retry"; + // A network failure gets the one advice (design 2026-11-27 §3.13.2, + // item 10), and the run's closing tip. + if (code == "E_NETWORK") { + mcpp::provider::network::remember(mirror); + return mcpp::provider::network::advice(mirror); + } if (code == "E_DISK_FULL") return std::format("free space on the disk that holds {}, then retry", home.string()); if (code == "E_PERMISSION") @@ -1369,7 +1374,7 @@ Fetcher::resolve_xpkg_path(std::string_view target, // said, not stamped over. return std::unexpected(CallError{std::format( "'{}' reported a successful install, but its payload is not complete\n" - " help: {}", targets[0], install_failure_hint(inst->error, cfg_.xlingsHome()))}); + " help: {}", targets[0], install_failure_hint(inst->error, cfg_.xlingsHome(), provider->mirror()))}); } // The install failed. What happens next depends on why (D5). @@ -1411,11 +1416,11 @@ Fetcher::resolve_xpkg_path(std::string_view target, if (!after.dir.empty() && after.usable) return std::unexpected(CallError{std::format( "{}\n packaging revision {} is still installed and in use\n help: {}", - installError, after.installed, install_failure_hint(inst->error, cfg_.xlingsHome()))}); + installError, after.installed, install_failure_hint(inst->error, cfg_.xlingsHome(), provider->mirror()))}); } return std::unexpected(CallError{std::format( "{}\n help: {}", installError, - install_failure_hint(inst->error, cfg_.xlingsHome()))}); + install_failure_hint(inst->error, cfg_.xlingsHome(), provider->mirror()))}); } namespace { diff --git a/src/provider/network.cppm b/src/provider/network.cppm new file mode 100644 index 000000000..ff9455125 --- /dev/null +++ b/src/provider/network.cppm @@ -0,0 +1,166 @@ +// mcpp.provider.network - where the provider downloads from, and what mcpp +// says when the network is in the way (design 2026-11-27 §3.13). +// +// The provider's resources are in two regions: GLOBAL (GitHub, the source) and +// CN (GitCode, a mirror kept in step). The mirror is chosen once, when a home +// is made: by where the user is (the time zone, then the locale's region), and +// then by which region the network check reached. A run with no network +// problem says nothing about the mirror; a problem is advised once, with the +// command that changes it and the value in effect, and never stops the run. +export module mcpp.provider.network; + +import std; +import mcpplibs.os; +import mcpp.diag; + +export namespace mcpp::provider::network { + +inline constexpr std::string_view kGlobal = "GLOBAL"; +inline constexpr std::string_view kCn = "CN"; + +// What the initial value is chosen by: the system's time zone and the region +// of the user's locale (mcpplibs.os.locale), either unknown. +struct Locale { + std::optional zone; + std::optional region; +}; +Locale this_machine(); + +// CN where the time zone places the machine in mainland China, or, when the +// zone is UTC or unknown (or Windows' China Standard Time, which Hong Kong +// shares, and a region is stated), where the locale's region does; GLOBAL +// otherwise. +std::string_view prior(const Locale& at); + +// The prior, unless it was unreachable and the other region was reached. +std::string_view checked(std::string_view prior, bool priorReachable, bool otherReachable); + +std::string_view other(std::string_view mirror); + +// What `prior` was decided by, as one phrase: `time zone Asia/Shanghai`, +// `region CN (time zone UTC)`, `no time zone or region stated`. +std::string basis(const Locale& at); + +// The host a region's resources come from, for a reader: GitHub, GitCode. +std::string_view host(std::string_view mirror); + +// The one advice a network problem gets: what to check, and the command that +// chooses a mirror, naming none for the reader and stating the one in effect. +std::string advice(std::string_view current); + +// SLOW DOWNLOADS: the bytes the active downloads of one install gained over the +// last 30 s, below 100 KB/s. A window of less than 30 s of downloading is not +// judged; the first slow window answers true, and none after it. +class SlowWatch { +public: + static constexpr auto kWindow = std::chrono::seconds(30); + static constexpr double kFloor = 100.0 * 1024; // bytes per second + bool observe(std::uint64_t total, bool active, std::chrono::steady_clock::time_point now); + double rate() const { return rate_; } +private: + std::deque> samples_; + double rate_ = 0; + bool said_ = false; +}; + +// Network trouble this process met (`domain`: network/slow, network/unreachable): +// a warning with the advice, once per domain, and one closing `tip:` after the +// command's output, the last line a reader or an agent sees. +void trouble(std::string_view domain, std::string_view what, std::string_view current); + +// The closing `tip:` alone, for a problem an error already states with the +// advice. +void remember(std::string_view current); + +} // namespace mcpp::provider::network + +namespace mcpp::provider::network { + +namespace { + +// Mainland China's zones, as IANA and Windows name them. +constexpr std::array kMainland = { + "Asia/Shanghai", "Asia/Chongqing", "Asia/Chungking", "Asia/Harbin", + "Asia/Urumqi", "Asia/Kashgar", "PRC", "China Standard Time"}; + +// A zone that says nothing of where a machine is: a container's, a CI +// runner's, a server's. +constexpr std::array kUninformative = { + "UTC", "UCT", "GMT", "Universal", "Zulu", "Etc/UTC", "Etc/UCT", "Etc/GMT", + "Etc/Universal", "Etc/Zulu", "Coordinated Universal Time"}; + +bool among(std::string_view value, std::span set) { + return std::ranges::find(set, value) != set.end(); +} + +// The zone decides, unless it says nothing of the place, or is Windows' key +// for Beijing and Hong Kong alike and a region is stated. +bool zone_decides(const Locale& at) { + if (!at.zone || at.zone->empty() || among(*at.zone, kUninformative)) return false; + return !(*at.zone == "China Standard Time" && at.region); +} + +} // namespace + +Locale this_machine() { + return {mcpplibs::os::locale::time_zone(), mcpplibs::os::locale::region()}; +} + +std::string_view prior(const Locale& at) { + if (zone_decides(at)) return among(*at.zone, kMainland) ? kCn : kGlobal; + return at.region == std::optional("CN") ? kCn : kGlobal; +} + +std::string_view checked(std::string_view prior, bool priorReachable, bool otherReachable) { + return !priorReachable && otherReachable ? other(prior) : prior; +} + +std::string_view other(std::string_view mirror) { return mirror == kCn ? kGlobal : kCn; } + +std::string basis(const Locale& at) { + const bool zone = at.zone && !at.zone->empty(); + if (zone_decides(at)) return std::format("time zone {}", *at.zone); + if (at.region) return zone ? std::format("region {} (time zone {})", *at.region, *at.zone) + : std::format("region {}", *at.region); + return zone ? std::format("time zone {}, no region stated", *at.zone) : "no time zone or region stated"; +} + +std::string_view host(std::string_view mirror) { return mirror == kCn ? "GitCode" : "GitHub"; } + +std::string advice(std::string_view current) { + return std::format("check the network or proxy, or choose a mirror: mcpp self config --mirror {}", + current.empty() ? std::string() : std::format(" (now {})", current)); +} + +bool SlowWatch::observe(std::uint64_t total, bool active, std::chrono::steady_clock::time_point now) { + if (!active) { samples_.clear(); return false; } + samples_.emplace_back(now, total); + while (samples_.size() > 1 && now - samples_[1].first >= kWindow) samples_.pop_front(); + const auto span = now - samples_.front().first; + if (span < kWindow) return false; + const auto seconds = std::chrono::duration(span).count(); + rate_ = static_cast(total - std::min(total, samples_.front().second)) / seconds; + if (said_ || rate_ >= kFloor) return false; + said_ = true; + return true; +} + +void remember(std::string_view current) { + static std::once_flag once; + std::call_once(once, [&] { + mcpp::diag::closing("network", std::format("this run met a network problem: {}", advice(current))); + }); +} + +void trouble(std::string_view domain, std::string_view what, std::string_view current) { + static std::mutex m; + static std::set> said; + { + std::lock_guard lock(m); + if (!said.emplace(domain).second) return; + } + mcpp::diag::warning(domain, what, advice(current)); + remember(current); +} + +} // namespace mcpp::provider::network diff --git a/src/provider/provider.cppm b/src/provider/provider.cppm index 09c370b84..4de212a0a 100644 --- a/src/provider/provider.cppm +++ b/src/provider/provider.cppm @@ -491,7 +491,7 @@ public: virtual std::string operation_command(std::string_view operation, std::string_view argsJson) const = 0; // ── setup ── - virtual void seed(std::span repos, std::string_view mirror = "auto", + virtual void seed(std::span repos, std::string_view mirror = {}, const ProjectEnv& penv = {}) const = 0; // The upstreams this home installs from (replacing what it had; none: // self-contained). Never written to. @@ -503,6 +503,9 @@ public: virtual std::string link_to_upstream(const Duplicate& d) const = 0; virtual int show_config() const = 0; virtual int set_mirror(std::string_view mirror, bool quiet = false) const = 0; + // The region the provider downloads from first (`CN`, `GLOBAL`), as its + // configuration states it; empty when it states none. + virtual std::string mirror() const = 0; virtual void ensure_initialized(bool quiet) const = 0; // The runtime the toolchains this provider installs run on (design // 2026-10-16 §7.2): mcpp's selected one ("glibc@2.44.3"), pinned once. diff --git a/src/provider/xlings/provider.cppm b/src/provider/xlings/provider.cppm index 01152b9f6..616e7a0d5 100644 --- a/src/provider/xlings/provider.cppm +++ b/src/provider/xlings/provider.cppm @@ -403,6 +403,7 @@ public: } int show_config() const override { return config_show(env_); } int set_mirror(std::string_view mirror, bool quiet) const override { return config_set_mirror(env_, mirror, quiet); } + std::string mirror() const override { return configured_mirror(env_); } mcpp::provider::NetworkReport check_network(std::chrono::milliseconds budget) const override { return network_check(env_, budget); } diff --git a/src/provider/xlings/xlings.cpp b/src/provider/xlings/xlings.cpp index aee6d4273..8f288a137 100644 --- a/src/provider/xlings/xlings.cpp +++ b/src/provider/xlings/xlings.cpp @@ -17,6 +17,7 @@ import mcpp.home.files; import mcpp.log; import mcpp.ui; // closing notices of the refresh guard import mcpp.diag; +import mcpp.provider.network; // the mirror's advice, slow downloads import mcpp.home; import mcpp.xpkg_version; import mcpp.version_req; @@ -1370,6 +1371,31 @@ std::optional parse_event_line(std::string_view line) { namespace { std::optional download_progress_of(std::string_view line); + +// SLOW DOWNLOADS OF ONE INSTALL (design 2026-11-27 §3.13.2, item 11): the bytes +// its files gained over the last 30 s, below 100 KB/s, are said once with the +// advice; the install goes on. The seconds are the provider's (`elapsedSec` of +// each frame), the time its downloads took, not the time mcpp read the frames. +class SlowDownloads { +public: + explicit SlowDownloads(const Env& env) : env_(env) {} + void observe(const BootstrapProgress& p) { + std::uint64_t total = 0; + bool active = false; + for (const auto& f : p.files) { + total += static_cast(std::max(0.0, f.downloadedBytes)); + active |= f.started && !f.finished; + } + const auto at = std::chrono::steady_clock::time_point{} + std::chrono::duration_cast( + std::chrono::duration(std::max(0.0, p.elapsedSec))); + if (watch_.observe(total, active, at)) + mcpp::provider::network::trouble("network/slow", std::format( + "downloads are slow: {:.0f} KB/s over the last 30 s", watch_.rate() / 1024), configured_mirror(env_)); + } +private: + const Env& env_; + mcpp::provider::network::SlowWatch watch_; +}; } std::expected @@ -1412,18 +1438,21 @@ call(const Env& env, std::string_view capability, InstallDeadline deadline; std::string progressDeadlineReason; std::map sourceAttempts; + SlowDownloads slow{env}; inv.options.streams = mcpp::run::Streams::output_error_kept; inv.options.on_line = [&](std::string_view line) { if (line.empty()) return; if (installing) { deadline.observe(line); - if (!mcpp::ui::is_quiet()) - if (const auto progress = download_progress_of(line)) + if (const auto progress = download_progress_of(line)) { + slow.observe(*progress); + if (!mcpp::ui::is_quiet()) for (const auto& file : progress->files) if (!file.sourceHost.empty() && sourceAttempts[file.name] != file.sourceAttempt) { sourceAttempts[file.name] = file.sourceAttempt; print_source(file.name, file.sourceHost, file.sourceAttempt); } + } } auto ev = parse_event_line(line); @@ -1471,9 +1500,10 @@ call(const Env& env, std::string_view capability, const auto message = progressDeadlineReason.empty() ? std::format("provider {} exceeded its process deadline and was stopped", capability) : std::format("provider {} stopped: {}", capability, progressDeadlineReason); + if (installing || syncing) mcpp::provider::network::remember(configured_mirror(env)); if (!result.error) result.error = ErrorEvent{ installing || syncing ? "E_NETWORK" : "E_PROVIDER_TIMEOUT", message, - installing || syncing ? "check proxy settings or use mcpp self config --mirror auto|CN|GLOBAL" + installing || syncing ? mcpp::provider::network::advice(configured_mirror(env)) : "retry the local provider operation", true}; result.stderrTail.push_back(message); } @@ -1755,6 +1785,7 @@ int install_with_progress(const Env& env, std::string_view target, InstallDeadline deadline; std::string progressDeadlineReason; std::vector notices; // `install_notices` payloads, stated after the install + SlowDownloads slow{env}; auto handle_line = [&](std::string_view line) { deadline.observe(line); @@ -1794,6 +1825,7 @@ int install_with_progress(const Env& env, std::string_view target, if (kind != "data" || ls.find_str("dataKind") != "download_progress") return; const auto prog = download_progress_of(line); if (!prog) return; + slow.observe(*prog); for (const auto& file : prog->files) { if (!quiet && !file.sourceHost.empty() && sourceAttempts[file.name] != file.sourceAttempt) { sourceAttempts[file.name] = file.sourceAttempt; @@ -1830,7 +1862,8 @@ int install_with_progress(const Env& env, std::string_view target, const auto reason = progressDeadlineReason.empty() ? "provider process deadline exceeded" : progressDeadlineReason; mcpp::log::warn("xlings", std::format("package install stopped: {}", reason)); - if (!quiet) print_status("Network", std::format("Download stopped: {}; check proxy/mirror settings", reason)); + mcpp::provider::network::trouble("network/unreachable", std::format("download stopped: {}", reason), + configured_mirror(env)); return resultExitCode > 0 ? resultExitCode : 124; } return (resultExitCode != -1) ? resultExitCode : closeRc; @@ -1974,16 +2007,26 @@ void seed_xlings_json(const Env& env, if (!penv.workspace.empty()) emit_obj("workspace", penv.workspace); if (!penv.subos.empty()) json += std::format(" \"subos\": \"{}\",\n", json_escape(penv.subos)); - json += " \"lang\": \"en\",\n"; - json += std::format(" \"mirror\": \"{}\"\n", json_escape(mirror)); - json += "}\n"; + json += " \"lang\": \"en\""; + if (!mirror.empty()) json += std::format(",\n \"mirror\": \"{}\"", json_escape(mirror)); + json += "\n}\n"; write_file(path, json); } +// The top-level `mirror` key of the home's configuration; none when the file +// is missing or unreadable. +std::string configured_mirror(const Env& env) { + std::ifstream file(env.home / ".xlings.json", std::ios::binary); + if (!file) return {}; + const auto doc = nlohmann::json::parse(file, nullptr, false); + if (!doc.is_object() || !doc.contains("mirror") || !doc["mirror"].is_string()) return {}; + return doc["mirror"].get(); +} + int config_show(const Env& env) { std::ifstream file(env.home / ".xlings.json", std::ios::binary); if (!file) { - std::println("mirror = auto (default; registry configuration is not initialized)"); + std::println("mirror: chosen when the home is made (registry configuration is not initialized)"); return 0; } std::cout << file.rdbuf(); diff --git a/src/provider/xlings/xlings.cppm b/src/provider/xlings/xlings.cppm index fbde396c1..63d5e10c8 100644 --- a/src/provider/xlings/xlings.cppm +++ b/src/provider/xlings/xlings.cppm @@ -659,14 +659,11 @@ inline constexpr std::string_view kBundleSnapshotMarker = ".mcpp-bundle-snapshot // Write .xlings.json seed file. // -// The `mirror` default is "auto": xlings' own adaptive mirror module -// (xlings.core.mirror.adaptive — latency-probed with per-download failover and -// failure penalisation) then picks the best reachable host per download. This -// replaces the historic hardcoded "CN", which FORCED the CN mirror and disabled -// that mechanism — stranding overseas users and GitHub-hosted CI on a -// slow/unreachable gitcode. An explicit `mcpp self config --mirror CN|GLOBAL` -// still writes that fixed value (config priority). Mirror selection is xlings' -// responsibility; mcpp just declines to override it by default. +// `mirror` is the region the home downloads from first, `CN` or `GLOBAL`, +// which mcpp chose (mcpp.provider.network) or the user stated; empty writes no +// key. A project's file states none, so the home's applies: xlings lets a +// project's `mirror` override the home's, and the `auto` once written there +// is no region to xlings -- it took GitHub first whatever the home chose. // The project's build-environment payload (L-1), materialized 1:1 into the // `.xlings.json` keys xlings already understands. Plain types (no manifest // dependency); the caller fills it from a manifest's [xlings] section. @@ -680,12 +677,14 @@ using SeedRepo = mcpp::provider::SeedRepo; void seed_xlings_json(const Env& env, std::span repos, - std::string_view mirror = "auto", + std::string_view mirror = {}, const ProjectEnv& penv = {}); // Persist the xlings mirror selection in .xlings.json via xlings itself. int config_show(const Env& env); int config_set_mirror(const Env& env, std::string_view mirror, bool quiet = false); +// The `mirror` of the home's .xlings.json; empty when it states none. +std::string configured_mirror(const Env& env); // Run xlings self init. void ensure_init(const Env& env, bool quiet); diff --git a/tests/e2e/index/local.cpp b/tests/e2e/index/local.cpp index 46a2cb23c..bc24a689d 100644 --- a/tests/e2e/index/local.cpp +++ b/tests/e2e/index/local.cpp @@ -1,6 +1,7 @@ // A project's local path index and a home's own index: namespace-aware file names, the name a -// cached dependency is reported by, a payload directory without its marker reinstalled, and a -// custom namespace filed under a non-canonical file name (formerly tests/e2e/52, 53, 60, 76). +// cached dependency is reported by, a payload directory without its marker reinstalled, a +// custom namespace filed under a non-canonical file name (formerly tests/e2e/52, 53, 60, 76), and +// what a fetch says on a terminal and when its download is slow. import std; import mcpplibs.mtest; import mcpp.test.support; @@ -463,6 +464,59 @@ exit 0 == s::count_lines(eachCalls, "{")) << "a call named both dependencies under batch_fetch = \"each\":\n" << eachCalls; }; + + "a download below 100 KB/s for 30 s is advised once and goes on"_test[s::gcc][s::fresh_sandbox][s::unix_shell] = [] { + // Design 2026-11-27 §3.13.2 items 10 to 13. The provider's frames state a download that + // gains 20 KB a second for 32 s of its time (`elapsedSec`, the clock the window is judged + // on). The build is not interrupted; one warning states the rate, with the advice that + // names the command and the mirror in effect and chooses none; one closing `tip:` is the + // last line; `mcpp explain` answers the code a JSON reader is given. + const auto tmp = s::case_dir(); + const auto home = s::case_home(s::home::inherited); + s::project index(tmp / "local-index", { + {"pkgs/c/compat.slow.lua", lua_package("compat.slow", "1.0.0", "a slow download", c_lib_segment("src/slow.c", "slow"))}}); + s::write_executable(tmp / "fake-bin/xlings", std::string("#!/usr/bin/env bash\n") + std::string(handshake) + R"SH( +set -e +if [[ "${1:-}" == "self" && "${2:-}" == "init" ]]; then + mkdir -p "${XLINGS_HOME:?}/subos/default" + printf '{}\n' > "$XLINGS_HOME/subos/default/.xlings.json" + exit 0 +fi +if [[ "${1:-}" == "interface" && "${2:-}" == "install_packages" ]]; then + root="${XLINGS_PROJECT_DIR:?}/.xlings/data/xpkgs/compat-x-compat.slow/1.0.0" + mkdir -p "$root/src" + printf 'int slow_value(void) { return 1; }\n' > "$root/src/slow.c" + for s in $(seq 0 32); do + printf '{"kind":"data","dataKind":"download_progress","payload":{"elapsedSec":%s,"files":[{"name":"compat:compat.slow@1.0.0","downloadedBytes":%s,"totalBytes":1048576,"started":true,"finished":false}]}}\n' "$s" "$((s * 20480))" + done + printf '{"kind":"data","dataKind":"download_progress","payload":{"elapsedSec":33,"files":[{"name":"compat:compat.slow@1.0.0","downloadedBytes":1048576,"totalBytes":1048576,"started":true,"finished":true}]}}\n' + printf '{"kind":"result","exitCode":0}\n' + exit 0 +fi +exit 0 +)SH"); + auto primer = s::project::scaffold("primer"); + expect(fatal(e2e::succeeded(primer.mcpp({"build"}, inherited())))) << "the case's home did not bootstrap"; + fake_xlings_config(home, tmp / "fake-bin/xlings", home / "registry"); + s::project app(tmp / "project/app", { + {"src/main.cpp", "extern \"C\" int slow_value(void);\nint main() { return slow_value() == 1 ? 0 : 1; }\n"}, + {"mcpp.toml", std::format("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[indices]\ncompat = {{ path = \"{}\" }}\n\n" + "[dependencies.compat]\nslow = \"1.0.0\"\n\n[targets.app]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n", + index.dir().generic_string())}}); + auto r = app.mcpp({"build"}, inherited()); + expect(fatal(e2e::succeeded(r))) << "a slow download interrupted the build: " << s::text(r); + expect(s::count_lines(r.err, "warning: downloads are slow: ") == 1u) << "not one warning: " << r.err; + expect(s::count_lines(r.err, "help: check the network or proxy, or choose a mirror: mcpp self config --mirror (now ") == 1u) + << "the advice does not name the command and the mirror in effect: " << r.err; + std::string last; + for (auto&& part : std::views::split(std::string_view(r.err), '\n')) + if (!part.empty()) last.assign(part.begin(), part.end()); + expect(fatal(last.starts_with("tip: this run met a network problem: check the network or proxy"))) + << "the closing tip is not the last line: " << r.err; + expect(s::count_lines(r.err, "tip: this run met a network problem") == 1u) << r.err; + auto explained = s::mcpp({"explain", "MCPP_NETWORK_SLOW"}, tmp); + expect(fatal(e2e::succeeded(explained) && e2e::contains(explained.out, "--mirror CN (GitCode)"))) << s::text(explained); + }; }}; } // namespace diff --git a/tests/e2e/self/config.cpp b/tests/e2e/self/config.cpp index 92825cb7f..956ba1a62 100644 --- a/tests/e2e/self/config.cpp +++ b/tests/e2e/self/config.cpp @@ -1,5 +1,5 @@ -// A home's configuration: `self env` and `self init`, the mirror chosen without a bootstrap, the -// index migrated and healed in config.toml and the registry's .xlings.json, and a project's +// A home's configuration: `self env` and `self init`, the mirror chosen by where the user is and +// set without a bootstrap, the index migrated and healed in config.toml and the registry's .xlings.json, and a project's // xlings environment materialised, with a package it names at another version than the toolchain // said once (formerly tests/e2e/10, 38, 39, 46, 88, 151). import std; @@ -49,22 +49,68 @@ E2E config{"config", s::home_fixture, [] { }; "38 self config mirror"_test = [] { - // Reading the configuration initialises nothing; auto, GLOBAL and cn are written to the - // registry's .xlings.json; an invalid mirror is refused. + // Reading the configuration initialises nothing; auto writes the region mcpp infers, never + // `auto`, with its basis beside it; GLOBAL and cn are written as stated and remove the + // basis; an invalid mirror is refused. const cold_home h; auto r = h.mcpp({"self", "config"}); expect(fatal(e2e::succeeded(r))) << "reading a fresh configuration failed: " << s::text(r); expect(fatal(!fs::exists(h.dir))) << "reading configuration initialized the home"; - for (auto [arg, want] : {std::pair{"auto", "auto"}, {"GLOBAL", "GLOBAL"}, {"cn", "CN"}}) { + r = h.mcpp({"self", "config", "--mirror", "auto"}); + expect(fatal(e2e::succeeded(r))) << "self config --mirror auto failed: " << s::text(r); + const auto inferred = s::json_file(h.dir / "registry/.xlings.json").value("mirror", ""); + expect(fatal(inferred == "CN" || inferred == "GLOBAL")) << "auto wrote " << inferred << ": " << h.read("registry/.xlings.json"); + expect(fatal(h.read("registry/.mcpp-mirror").starts_with(inferred + ": "))) << "no basis for the inferred value: " << h.read("registry/.mcpp-mirror"); + expect(fatal(e2e::contains(s::text(r), std::format("xlings mirror = {} (", inferred)))) << s::text(r); + for (auto [arg, want] : {std::pair{"GLOBAL", "GLOBAL"}, {"cn", "CN"}}) { r = h.mcpp({"self", "config", "--mirror", arg}); expect(fatal(e2e::succeeded(r))) << "self config --mirror " << arg << " failed: " << s::text(r); expect(fatal(e2e::contains(h.read("registry/.xlings.json"), std::format("\"mirror\": \"{}\"", want)))) << "mirror should be " << want << ": " << h.read("registry/.xlings.json"); + expect(fatal(!fs::exists(h.dir / "registry/.mcpp-mirror"))) << "a stated mirror kept the inferred basis"; } + r = h.mcpp({"self", "config"}); + expect(fatal(e2e::contains(s::text(r), "Mirror CN (stated with mcpp self config --mirror)"))) << s::text(r); r = h.mcpp({"self", "config", "--mirror", "BAD"}); expect(fatal(r.started && r.status != 0)) << "an invalid mirror unexpectedly succeeded: " << s::text(r); expect(fatal(e2e::contains(s::text(r), "invalid mirror"))) << "invalid mirror diagnostic missing: " << s::text(r); }; + "a home's mirror follows where the user is"_test[s::tz_environment] = [] { + // Design 2026-11-27 §3.13.2: a home made without --mirror is given CN where the time zone + // is mainland China's and GLOBAL where another zone states the place; where the zone says + // nothing (UTC) the locale's region decides. The basis is written beside the value, shown + // by `self config` and never said while the network is not in the way; a home from before + // that states `auto` is given the inferred value once. + struct place { std::string_view tz, lang, mirror, basis; }; + const auto at = [](std::string_view name, std::string_view tz, std::string_view lang) { + cold_home h; + h.dir = s::case_dir() / name; + h.o.env = {{"MCPP_HOME", h.dir.string()}, {"TZ", std::string(tz)}, {"LANG", std::string(lang)}, + {"LC_ALL", std::nullopt}, {"LC_MESSAGES", std::nullopt}}; + return h; + }; + for (const auto& [tz, lang, mirror, basis] : {place{"Asia/Shanghai", "en_US.UTF-8", "CN", "time zone Asia/Shanghai"}, + place{"America/New_York", "zh_CN.UTF-8", "GLOBAL", "time zone America/New_York"}, + place{"UTC", "zh_CN.UTF-8", "CN", "region CN (time zone UTC)"}, + place{"UTC", "en_US.UTF-8", "GLOBAL", "region US (time zone UTC)"}}) { + const auto h = at(std::format("home-{}-{}", tz.substr(tz.find('/') + 1), lang.substr(0, 5)), tz, lang); + auto r = h.mcpp({"--offline", "self", "init"}); + expect(fatal(r.started && (r.status == 0 || r.status == 1))) << s::text(r); + expect(fatal(s::json_file(h.dir / "registry/.xlings.json").value("mirror", "") == mirror)) + << tz << ", " << lang << ": " << h.read("registry/.xlings.json"); + expect(fatal(h.read("registry/.mcpp-mirror") == std::format("{}: {}\n", mirror, basis))) << h.read("registry/.mcpp-mirror"); + expect(fatal(s::lacks(s::text(r), "self config --mirror"))) << "the choice was advised without a problem: " << s::text(r); + r = h.mcpp({"self", "config"}); + expect(fatal(e2e::contains(s::text(r), std::format("Mirror {} ({})", mirror, basis)))) << s::text(r); + } + const auto before = at("home-before", "Asia/Shanghai", "en_US.UTF-8"); + s::project(before.dir, {{"registry/.xlings.json", R"({"index_repos": [], "lang": "en", "mirror": "auto"})"}}); + auto r = before.mcpp({"--offline", "self", "init"}); + expect(fatal(r.started && (r.status == 0 || r.status == 1))) << s::text(r); + expect(fatal(s::json_file(before.dir / "registry/.xlings.json").value("mirror", "") == "CN")) << before.read("registry/.xlings.json"); + expect(fatal(before.read("registry/.mcpp-mirror") == "CN: time zone Asia/Shanghai; was auto\n")) << before.read("registry/.mcpp-mirror"); + }; + "39 xlings index migration"_test = [] { // A home naming the legacy mcpp-index has its config.toml and .xlings.json migrated to // mcpplibs by `self config --mirror auto`, and `self config` shows mcpplibs only. @@ -121,7 +167,8 @@ E2E config{"config", s::home_fixture, [] { "88 xlings environment"_test = [] { // A project's [xlings] deps and subos and its [xlings.workspace] are materialised once in - // .mcpp/.xlings.json (no envs), with an advisory naming [xlings.workspace]. + // .mcpp/.xlings.json (no envs, no mirror: the home's applies), with an advisory naming + // [xlings.workspace]. s::project app(s::case_dir() / "app", { {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[xlings]\ndeps = [\"ninja@1.12.1\"]\nsubos = \"dev\"\n\n[xlings.workspace]\nninja = \"1.12.1\"\n"}, {"src/main.cpp", "int main() { return 0; }\n"}, @@ -133,6 +180,7 @@ E2E config{"config", s::home_fixture, [] { for (std::string_view w : {"\"deps\"", "ninja@1.12.1", "\"subos\": \"dev\"", "\"workspace\"", "\"ninja\": \"1.12.1\""}) expect(fatal(e2e::contains(j, w))) << "not materialized: " << w << "\n" << j; expect(fatal(s::lacks(j, "\"envs\""))) << "envs is materialized and nothing reads it: " << j; + expect(fatal(s::lacks(j, "\"mirror\""))) << "a project states a mirror, which replaces the home's: " << j; std::size_t n = 0; for (auto at = j.find("ninja@1.12.1"); at != std::string::npos; at = j.find("ninja@1.12.1", at + 1)) ++n; expect(fatal(n == 1u)) << "the same statement was materialized " << n << " times"; diff --git a/tests/e2e/self/homes.cpp b/tests/e2e/self/homes.cpp index 9eb234c85..5c46dbec1 100644 --- a/tests/e2e/self/homes.cpp +++ b/tests/e2e/self/homes.cpp @@ -298,11 +298,15 @@ E2E homes{"homes", s::home_fixture, [] { expect(fatal(client_hellos.load() == 1)) << "the TLS probe never reached the handshake oracle (" << client_hellos.load() << ")"; const int before_doctor = requests.load(); const auto started = std::chrono::steady_clock::now(); - auto online = e2e::run({.argv = {s::mcpp_path(), "self", "doctor"}, .cwd = root, .env = env, .timeout = std::chrono::seconds{8}}); + auto online = e2e::run({.argv = {s::mcpp_path(), "self", "doctor", "--verbose"}, .cwd = root, .env = env, .timeout = std::chrono::seconds{8}}); expect(fatal(std::chrono::steady_clock::now() - started < std::chrono::seconds{7})) << online.err; expect(fatal(online.started && online.status == 1)) << online.status << online.out << online.err; + // Design 2026-11-27 §3.13.2: one warning with the sources reached of those checked and the + // advice; each source is in --verbose. expect(fatal(e2e::contains(online.err, "corp GLOBAL") && e2e::contains(online.err, ": reachable"))) << online.err; expect(fatal(e2e::contains(online.err, "corp CN") && e2e::contains(online.err, ": http"))) << online.err; + expect(fatal(e2e::contains(online.err, "the network check reached ") && e2e::contains(online.err, "mcpp self config --mirror "))) + << online.err; expect(fatal(e2e::contains(online.err, "Checking build policy"))) << online.err; expect(fatal(snapshot(home) == before)) << "the online doctor changed the home"; const int after_doctor = requests.load(); diff --git a/tests/support/src/support.cppm b/tests/support/src/support.cppm index 169884a20..29edf3813 100644 --- a/tests/support/src/support.cppm +++ b/tests/support/src/support.cppm @@ -57,6 +57,7 @@ using mcpplibs::mtest::platform; const only elf{platform::linux}; // a host whose programs are ELF const only unix_shell{platform::linux, platform::macos}; // a POSIX shell and its tools const only fresh_sandbox{platform::linux, platform::macos}; +const only tz_environment{platform::linux, platform::macos}; // TZ and LANG state the user's place // The shared home, served once per run before its first user (SPEC-017 P11): each group of cases // states it, and the time that fills the home is the fixture's, not its first case's. const mcpplibs::mtest::uses home_fixture{"home"}; diff --git a/tests/unit/test_network.cpp b/tests/unit/test_network.cpp index 0dc061d1a..c7ae946a3 100644 --- a/tests/unit/test_network.cpp +++ b/tests/unit/test_network.cpp @@ -3,6 +3,7 @@ import std; import mcpplibs.mtest; import mcpp.provider; import mcpp.provider.xlings; +import mcpp.provider.network; import mcpplibs.os.platform; import mcpp.invocation; import mcpp.run; @@ -286,3 +287,52 @@ wait << (metadata ? "metadata" : "resource") << " deadline left a descendant writing"; } }}; + +// THE MIRROR'S INITIAL VALUE (design 2026-11-27 §3.13.2, items 4 and 5): mainland China's time +// zone gives CN; a zone elsewhere gives GLOBAL whatever the language; a zone that says nothing +// (UTC, unknown) leaves it to the locale's region. The check keeps the prior unless only the +// other region was reached. +UTest the_mirror_is_chosen_by_where_the_user_is{"Network/TheMirrorIsChosenByWhereTheUserIs", [] { + namespace net = mcpp::provider::network; + using L = net::Locale; + auto s = [](const char* v) { return std::optional(v); }; + expect(eq(net::prior(L{s("Asia/Shanghai"), s("US")}), std::string_view("CN"))) << "a developer in China with en_US"; + expect(eq(net::prior(L{s("China Standard Time"), std::nullopt}), std::string_view("CN"))) << "Windows' key"; + expect(eq(net::prior(L{s("China Standard Time"), s("HK")}), std::string_view("GLOBAL"))) + << "Windows names Hong Kong's zone as Beijing's: the region decides"; + expect(eq(net::basis(L{s("China Standard Time"), s("CN")}), std::string("region CN (time zone China Standard Time)"))); + expect(eq(net::prior(L{s("America/Los_Angeles"), s("CN")}), std::string_view("GLOBAL"))) << "a zh_CN user abroad"; + expect(eq(net::prior(L{s("Asia/Taipei"), s("TW")}), std::string_view("GLOBAL"))) << "only mainland China"; + expect(eq(net::prior(L{s("UTC"), s("CN")}), std::string_view("CN"))) << "a container in China: the region decides"; + expect(eq(net::prior(L{s("Etc/UTC"), s("US")}), std::string_view("GLOBAL"))) << "a CI runner"; + expect(eq(net::prior(L{std::nullopt, std::nullopt}), std::string_view("GLOBAL"))) << "nothing stated"; + expect(eq(net::basis(L{s("Asia/Shanghai"), s("US")}), std::string("time zone Asia/Shanghai"))); + expect(eq(net::basis(L{s("UTC"), s("CN")}), std::string("region CN (time zone UTC)"))); + expect(eq(net::checked("CN", true, true), std::string_view("CN"))) << "both reached: the prior stands"; + expect(eq(net::checked("CN", false, true), std::string_view("GLOBAL"))) << "only the other reached"; + expect(eq(net::checked("GLOBAL", false, false), std::string_view("GLOBAL"))) << "none reached: the prior stands"; + const auto advice = net::advice("GLOBAL"); + expect(advice.find("mcpp self config --mirror (now GLOBAL)") != std::string::npos) + << "the advice names the command and the mirror in effect, and chooses none: " << advice; +}}; + +// SLOW DOWNLOADS (§3.13.2, items 11 and 13): judged over a window of 30 s of downloading, said +// once, and never while nothing is active. +UTest slow_downloads_are_judged_over_thirty_seconds{"Network/SlowDownloadsAreJudgedOverThirtySeconds", [] { + using namespace std::chrono_literals; + const auto t0 = std::chrono::steady_clock::time_point{} + 1h; + mcpp::provider::network::SlowWatch fast, slow; + bool said = false; + for (int s = 0; s <= 40; ++s) { + expect(!fast.observe(static_cast(s) * 1024 * 1024, true, t0 + std::chrono::seconds(s))) + << "1 MB/s is not slow"; + const bool now = slow.observe(static_cast(s) * 20 * 1024, true, t0 + std::chrono::seconds(s)); + if (s < 30) expect(!now) << "a window shorter than 30 s is not judged (" << s << " s)"; + if (now) { expect(!said) << "slow is said once"; said = true; } + } + expect(said) << "20 KB/s over 30 s is slow"; + expect(slow.rate() < 100.0 * 1024) << slow.rate(); + mcpp::provider::network::SlowWatch idle; + for (int s = 0; s <= 40; ++s) + expect(!idle.observe(0, false, t0 + std::chrono::seconds(s))) << "nothing active, nothing judged"; +}};