From a1bb90e28b5a3042f78e9ec0b52ef464b6590edf Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Tue, 24 Nov 2026 16:58:20 +0900 Subject: [PATCH 1/7] ci: mingw-cross takes Wine from the wine package the engine's runner names, not from apt The job installed Wine from apt: a closure of about 200 packages, i386 multiarch included, whose download depended on the runner's mirror and on a cache the repository's size limit evicts. On 2026-11-24 the step exceeded its 20 minutes three times in a row on main. The engine's Windows-on-Linux runner row already names xim:wine@11.0, one portable WoW64 archive; the job now installs that package through xlings and puts its bin directory on PATH. The runner-image key, the wine-debs cache and its save step are removed; the xlings cache key moves to v4 so the saved home carries the package. --- .github/workflows/cross-build-test.yml | 93 +++++--------------------- 1 file changed, 18 insertions(+), 75 deletions(-) diff --git a/.github/workflows/cross-build-test.yml b/.github/workflows/cross-build-test.yml index 6213ca5fb..14085c2ec 100644 --- a/.github/workflows/cross-build-test.yml +++ b/.github/workflows/cross-build-test.yml @@ -235,9 +235,7 @@ jobs: - uses: actions/checkout@v4 # Restored here and saved by this job alone, on main, after its last - # step (rule R3). The Wine packages were evicted with everything else - # while the repository's caches exceeded their limit, and `apt` then - # took 26 to 50 minutes (2026-10-01); with one writer per key they stay. + # step (rule R3). - name: Restore mcpp sandbox id: sandbox uses: actions/cache/restore@v4 @@ -252,72 +250,9 @@ jobs: uses: actions/cache/restore@v4 with: path: ~/.xlings - key: xlings-${{ runner.os }}-mingw-cross-v3-${{ hashFiles('.xlings.json') }} + key: xlings-${{ runner.os }}-mingw-cross-v4-${{ hashFiles('.xlings.json') }} restore-keys: | - xlings-${{ runner.os }}-mingw-cross-v3- - - # THE KEY NAMES THE RUNNER IMAGE, because the image is what the cached - # packages have to agree with. Wine's i386 closure is Multi-Arch: same - # with the amd64 libraries the image ships, and the two must be one - # version. Under the old fixed key (`-v1`) the cache was saved once and - # never again, the image moved on, and on 2026-10-15 (run 38695300904, - # a cache HIT) the cached libxml2:i386 3.9 met the image's - # libxml2:amd64 3.10: dpkg installed the stale i386 package, apt then - # upgraded it, and the upgrade's shared changelog was refused. A new - # image is a new key; until main has saved it, `restore-keys` hands back - # the previous image's packages, which the step below only uses where - # their version is still the one apt asks for. - - name: Runner image version - id: image - run: echo "version=${ImageVersion:-unknown}" >> "$GITHUB_OUTPUT" - - - name: Restore wine debs - id: wine - uses: actions/cache/restore@v4 - with: - path: ~/wine-debs - key: wine-debs-${{ runner.os }}-ubuntu24.04-${{ steps.image.outputs.version }} - restore-keys: | - wine-debs-${{ runner.os }}-ubuntu24.04- - - # APT INSTALLS, ALWAYS; THE CACHE ONLY SPARES IT THE DOWNLOAD. The cached - # packages are put where apt keeps what it downloaded, and apt then - # resolves wine against the image as it is today: a cached package whose - # version is still current is used as is, anything newer is fetched. - # Nothing older than the image is ever installed, which is what - # `dpkg -i` of the cached set did whenever the image had moved on. Cold - # (no cache at all), this is the plain install it always was. - - name: Install wine - timeout-minutes: 20 - run: | - sudo dpkg --add-architecture i386 || true - # The runner image carries third-party apt lists (Google Chrome - # among them) that this job does not use, and a transient - # `Hash Sum mismatch` on one of them fails the whole update -- which - # killed two cross-build jobs in setup, before a single byte was - # compiled. Dropping the lists this job has no use for is what makes - # the step's failure mean something about this job. - # - # BY CONTENT, NOT BY FILENAME. The first attempt removed - # `google-chrome.list` and the update failed on the same URL: on - # ubuntu-24.04 the runner writes deb822 `.sources` files, so the - # name was a guess and the guess was wrong. - sudo grep -rlE 'dl[.]google[.]com|packages[.]microsoft[.]com' \ - /etc/apt/sources.list.d/ 2>/dev/null | xargs -r sudo rm -f - if ls ~/wine-debs/*.deb >/dev/null 2>&1; then - sudo cp ~/wine-debs/*.deb /var/cache/apt/archives/ - fi - sudo apt-get update -qq - sudo apt-get install -y --download-only wine64 wine \ - || sudo apt-get install -y --download-only wine - # What main saves is what this image installs: packages no longer - # in any index (the previous image's, carried in by restore-keys) - # are dropped first, so the cache does not grow with every image. - sudo apt-get autoclean -qq - rm -rf ~/wine-debs && mkdir -p ~/wine-debs - cp /var/cache/apt/archives/*.deb ~/wine-debs/ 2>/dev/null || true - sudo apt-get install -y wine64 wine || sudo apt-get install -y wine - wine --version + xlings-${{ runner.os }}-mingw-cross-v4- - name: Bootstrap mcpp via xlings env: @@ -344,6 +279,21 @@ jobs: echo "XLINGS_BIN=$HOME/.xlings/subos/default/bin/xlings" >> "$GITHUB_ENV" echo "MCPP_BOOT=$MCPP_BOOT" >> "$GITHUB_ENV" + # Wine is the package the engine's Windows-on-Linux runner names + # (`xim:wine@11.0`, builtin.toml): one portable WoW64 tree, which runs + # 32- and 64-bit PE programs without the host's i386 architecture. Taken + # from apt, Wine was a closure of about 200 packages whose download + # depended on the runner's mirror and on a cache the repository's limit + # evicts; on 2026-11-24 it exceeded the step's 20 minutes three times in + # a row. The package is one archive, kept with the xlings cache. + - name: Install wine + run: | + "$XLINGS_BIN" install wine@11.0 -y + bin="$HOME/.xlings/data/xpkgs/xim-x-wine/11.0/bin" + test -x "$bin/wine" || { echo "::error::wine 11.0 is not at $bin"; exit 1; } + echo "$bin" >> "$GITHUB_PATH" + "$bin/wine" --version + - uses: ./.github/actions/use-built-mcpp with: host: linux-x86_64 @@ -466,13 +416,6 @@ jobs: path: ~/.xlings key: ${{ steps.xlings.outputs.cache-primary-key }} - - name: Save wine debs - if: ${{ github.event_name == 'push' && steps.wine.outputs.cache-hit != 'true' }} - uses: actions/cache/save@v4 - with: - path: ~/wine-debs - key: ${{ steps.wine.outputs.cache-primary-key }} - # ── windows → linux ─────────────────────────────────────────────────────── # The mirror of mingw-cross-wine. Two jobs because a Windows runner cannot # execute the ELF it produces; the artefact is handed to a Linux job and From d1fe87170fc5d600aa8c79de505c0c6e61ccadb7 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 26 Nov 2026 06:26:14 +0900 Subject: [PATCH 2/7] docs: design record for the private fragment's purview, the failure tip of an optimization, and why clang's BMI has no reader --- ...-and-private-fragment-refinement-design.md | 311 ++++++++++++++++++ .agents/docs/README.md | 4 +- 2 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 .agents/docs/2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md diff --git a/.agents/docs/2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md b/.agents/docs/2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md new file mode 100644 index 000000000..74a7b0156 --- /dev/null +++ b/.agents/docs/2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md @@ -0,0 +1,311 @@ +--- +subject: build +status: active +--- + +# clang BMI 的截断与私有模块片段判定的收窄 + +**日期:** 2026-11-26 · **版本:** v4(已实施,A 撤回) · **基线:** mcpp 2026.11.24.1 · **前文:** +[第二部分之后的补充方案](2026-11-17-ninja-cascade-publish-supplement-design.md)(第 3 节截断、第 11 节构建优化的架构)· +**相关规范:** SPEC-018(模块的重编译)、SPEC-019(构建优化) + +v3 到 v4 的变化:实施 A 之前的探测(第 2.8 节)推翻了 A 的前提——函数哈希的操作数下标随声明而异,哈希宽度翻转使位偏移与偏移表 +一起移动——A 不实现,原因与重新可行的条件记入第 3 节;B、C、D 按原计划实施,D 的失败提示读构建目录中的一个旁表, +实施时发现并修复了"开关的取值改变后快速路径重放旧图"(第 7.5 节)。GCC 读者的重构只为 A 服务,一并不做。 +v2 到 v3:模块命名、第 7 节、第 10 节的测试集。v1 到 v2:A 的共用内核、跨版本实测。 + +## 1. 来源与范围 + +SPEC-018 §2.2 记录 clang 的 BMI 没有读者:任何改变源文件字节的编辑都改变 `.pcm`,截断因此对 clang 不起作用;SPEC-019 §5 +的私有模块片段拆分是 clang 上止住级联的唯一办法,且它的判定有一处过宽、一处词法缺口。本文的四项: + +| 项 | 内容 | 状态 | +|---|---|---| +| A | clang `.pcm` 的读者,与 GCC 的读者共用比较内核 | **不实现**(第 2.8 节、第 3 节) | +| B | 私有片段的拆分判定收窄:只拒绝会改变片段含义的预处理指令,不再拒绝所有 `#` 行 | 已实施 | +| C | 同一判定的词法缺口:数字分隔符、原始字符串、`extern "C"` 块、行连接 | 已实施 | +| D | 每项优化都有控制开关(默认开启);构建失败而某项优化对失败的步骤生效时,给出验证提示 | 已实施 | + +**范围:** 不做无标记的语义拆分,不引入语义提供者;语言服务器一侧不在本文之内。 + +## 2. 实测 + +环境:clang 20.1.7、22.1.8、23.1.3、23.1.6(xim 索引的四个版本);GCC 16.1.0。命令与 mcpp 的 BMI 边相同: +`--precompile -Xclang -emit-reduced-module-interface`。所有比较在同一路径下进行(路径写在 BMI 的 `ORIGINAL_FILE` 与 +`INPUT_FILE` 中,不同路径会混入差异)。记录名取自 `llvm-bcanalyzer -dump`。 + +### 2.1 一个 BMI 随编辑的变化(clang 23.1.3) + +被测模块:`export module m;`,两个导出的非 inline 函数,定义在 `module :private;` 之后,仅 `import`。 + +| 编辑 | 差异字节 | 变化的记录 | +|---|---|---| +| 同一输入重编、`touch` 源文件 | 0 | — | +| 片段内函数体改一个字符,长度不变 | 25 | 该函数 `DECL_FUNCTION` 的一个 32 位操作数(函数哈希);一个 20 字节的高熵区 | +| 片段内函数体变长 4 字节 | 48 | 上一行;`INPUT_FILE` 的大小;`SOURCE_MANAGER_BLOCK` 内的偏移;`SOURCE_LOCATION_OFFSETS`;其后声明(`DECL_FUNCTION`、`DECL_PARM_VAR`)的位置操作数 | +| 文件末尾追加一行注释 | 30 | `INPUT_FILE` 的大小;`SOURCE_MANAGER_BLOCK` 内的偏移;`SOURCE_LOCATION_OFFSETS`;20 字节高熵区;无声明记录变化 | +| 文件开头插入一行注释 | 91 | 全部声明的位置操作数 | + +1. 函数哈希:reduced BMI 丢弃了非 inline 函数体,哈希仍覆盖函数体,因此函数体变化即使不进入 BMI 也使它变化。 +2. 20 字节高熵区:内容随源文件任何变化而变;候选是 `UNHASHED_CONTROL_BLOCK` 的 `SIGNATURE`(20 字节的 blob)。它在文件中的位置 + 与该块在文件头的位置不符,实施的第一步由解码器按位置确认。 +3. `CONTROL_BLOCK` 的 `METADATA` 记录给出格式版本与 clang 主版本:20.1.7 为 34/20,22.1.8 为 35/22,23.1.3 与 23.1.6 为 39/23。 + +### 2.2 跨版本与记录种类 + +同长度函数体编辑(片段内)与末尾追加注释,在四个版本上变化的记录: + +| clang | `DECL_FUNCTION` 哈希 | `DECL_CXX_METHOD` 哈希 | `DECL_CXX_CONVERSION` 哈希 | 末尾追加 | +|---|---|---|---|---| +| 20.1.7 | 操作数 17 | 25 | 32 | `SM_SLOC_BUFFER_ENTRY`、`SOURCE_LOCATION_OFFSETS` | +| 22.1.8 | 17 | 未测 | 未测 | 同 | +| 23.1.3、23.1.6 | 17 | 27 | 34 | 同 | + +1. 自由函数的哈希下标在四个版本上不变;成员函数的哈希下标在 20 与 23 之间移动了 2。**字段表必须按版本**,且必须覆盖每一种带哈希的记录。 +2. 构造函数与析构函数(23.1.3):同长度编辑后只有签名区不同,没有操作数变化;其他版本未测。 +3. 类模板的成员函数定义在片段内时(23.1.3):`DECL_CLASS_TEMPLATE` 的一个操作数随之变化(不是哈希:差值很小)。clang 的 BMI 保留了片段内 + 模板成员的定义,这类编辑判"变化",与语言规定(片段内容对导入者不可达)不同,但保守。 +4. 末尾追加在 20.1.7 上还有一条没有操作数差异的记录(未查明,可能是 blob)。实施的第一步查明。 + +### 2.3 含全局模块片段的 `#include` + +`module;` 之后 `#include "dep.h"`,头文件定义结构体、`inline` 函数与一个宏。 + +| 情形 | 末尾追加一行注释(23.1.3) | +|---|---| +| 头文件只在片段的函数体内使用 | 42 字节;变化的记录全在 `SOURCE_MANAGER_BLOCK`(`SM_SLOC_BUFFER_ENTRY`、`SM_SLOC_FILE_ENTRY`、`SM_SLOC_EXPANSION_ENTRY`,偏移加 Δ,展开位置加 2Δ)与 `SOURCE_LOCATION_OFFSETS`;无声明或表达式记录变化 | +| 头文件的结构体、`inline` 函数被导出声明或导出的 inline 函数使用 | 68 字节;除上一行外,被序列化的头文件声明与 inline 函数体中的表达式记录(`EXPR_INTEGER_LITERAL`、`EXPR_DECL_REF`)的位置操作数移位 | + +头文件的 `SourceLocation` 在主文件的范围之后分配,主文件大小变化使其整体移位;被序列化进 BMI 的头文件声明因此带着移位的位置。覆盖范围: + +- 只含 `import` 的模块:片段内与文件末尾的任意大小的编辑、同长度的编辑,均在覆盖之内。 +- 含 `#include`,但头文件的内容不进入 BMI:同上。 +- 含 `#include`,且其声明被序列化进 BMI:只有同长度的编辑在覆盖之内。 +- 编辑使其后的声明移位(函数体变长而后面还有声明、文件开头的编辑):不在覆盖之内。 + +### 2.4 导入者看到什么(clang 23.1.3) + +| 项 | 结果 | +|---|---| +| 无 `-g`,`-O2`,导入者对旧 BMI 与新 BMI | 目标文件逐字节相同 | +| `-g -O2` | 差 16 字节:DWARF 中被导入模块**源文件**的校验和(保留旧 BMI、替换源文件后同样出现) | +| 源文件已变、仍传旧 BMI | 无任何诊断地接受 | +| 导入者自己的 BMI(`b` 导入 `m`,`m` 的 BMI 为同长度编辑前后两版) | 逐字节相同:reduced BMI 不记录被导入 BMI 的签名 | + +保留旧 BMI 对程序的行为没有影响;可观察的差别限于调试信息(文件校验和、行号)与诊断中的行号,与 SPEC-018 §3.2 对 GCC 所述一致。 + +### 2.5 当前 mcpp 上的重编译(U1;mcpp 2026.11.22.1,clang 23.1.3,`c ← b ← main`,`c` 为单文件模块) + +每个情形从干净目录构建一次,编辑 `c`,再构建一次,记录该次构建编译了哪些单元: + +| 编辑 | 编译的单元 | +|---|---| +| 同长度函数体、变长函数体、末尾追加注释、开头插入注释(`c` 无片段) | `c`、`b`;`main` 未编译 | +| 片段按原样构建,变长或同长度编辑 | `c`、`b` | +| 片段拆为两个单元(默认),变长编辑 | 只有实现单元;接口单元、`b`、`main` 均未编译 | + +连续构建的序列:一次同长度编辑之后,**下一次没有任何编辑的构建重新编译了 `main`**,再下一次才是空操作: + +| 构建 | `c` | `b` | `main` | +|---|---|---|---| +| 编辑后第一次 | 编译 | 编译 | — | +| 无编辑的第二次 | — | — | **编译** | +| 无编辑的第三次、第四次 | — | — | — | + +1. `b` 的 BMI 在 `c` 的 BMI 变化后逐字节不变(2.4),所以 `keep-bmi` 在直接导入者处止住了本次构建的级联;这与第二部分第 11.2 节记录的 + "`c`、`b`、`main` 均编译"不符,后者对应的是更早的构建或另一种写法,不再作为依据。 +2. 传递导入者 `main` 并没有被省去:它在下一次构建中编译。原因没有查明(推测:`main` 的目标文件依赖 `c` 的 BMI,而 `c` 的 BMI 在本次构建中才被替换, + `main` 在计划时被判为最新)。这是现有行为:一次无编辑的构建不是空操作。 +3. A 在 `c` 处保留旧 BMI 及其修改时间,所以覆盖到的编辑既没有 `b` 的编译,也没有延后一次的 `main` 的编译。这比 v1 估计的"省去直接导入者一层"大。 +4. 第 2 条的延后编译单独记为一个 mcpp 问题,不并入本次改动(一个 PR 只做一件事;A、B、C 本身是用户决定的合并)。 + +### 2.6 解析成本 + +`llvm-bcanalyzer`(通用解析,无输出):28.5 MB 的 BMI 用 0.24 s,36 MB 用 0.29 s,约 120 MB/s;专用读者不会更慢,取此值为保守值。 +本机 4000 个项目模块 BMI(不含 `std`)的大小:p50 30 KB,p90 78 KB,p99 2.05 MB,最大 28.5 MB(一个第三方包,只构建一次,没有"此前的 BMI"可比)。 + +### 2.7 被否决的做法 + +`-Xclang -skip-function-bodies` 先出 BMI:同长度编辑得到字节相同的 BMI,但 reduced BMI 原本保留的 inline 函数体与模板体一并丢失。导入者调用 +`inline` 函数与函数模板时无诊断地通过编译,目标文件留下未定义符号,到链接才暴露。不采用。 + +### 2.8 A 的探测:哈希的位置与宽度(clang 20.1.7、22.1.8、23.1.3、23.1.6) + +实施 A 的第一步是用解码器与 `llvm-bcanalyzer` 对一个语料(自由函数、成员函数、运算符、构造与析构、转换运算符、静态成员、虚函数、 +命名空间内函数、枚举、各 10 个函数体的随机编辑)定位每个版本中变化的(块,记录码,操作数)。结果推翻了 2.2 的假设: + +1. **哈希的下标不由(记录码,版本)决定。** 23.1.3 的一个模块中,函数哈希(取值不小于 2^24、且随函数体变化的操作数)所在的下标: + `DECL_FUNCTION` 为 17、18、25;`DECL_CXX_METHOD` 为 17、19、26、27、29;`DECL_CXX_CONSTRUCTOR` 为 19、21、31;`DECL_CXX_DESTRUCTOR` 为 + 16、21、31;`DECL_CXX_CONVERSION` 为 24、34。同一记录码内的差别来自声明的形式:名字的种类、限定、是否虚函数、是在类内声明 + 还是在片段内作为类外定义的重声明(后者的记录更短)。该操作数之前的字段数因此不是常数,要定位它需要复刻 clang 序列化器的布局, + 而这个布局随版本移动(2.2 第 1 条)。 +2. **哈希随机,改变 VBR 宽度。** 32 位哈希在 VBR6 中占 6 或 7 个块;约三分之一的编辑改变宽度,其后同一块内的位偏移整体平移 6 位。 + 与之同时变化的还有三类值:`DECL_CXX_RECORD` 等声明上下文记录中的词法与可见偏移(23.1.3 的操作数 29)、`TYPE_OFFSET` 与 + `DECL_OFFSET` 两张偏移表(`AST_BLOCK` 内的 blob)。v3 的"区间之外逐位相等"因此对三分之一的编辑不成立,需要改为按记录比较, + 并再增加一张偏移表的事实表。 +3. **不屏蔽哈希的覆盖。** 只剩"最后一个声明之后的编辑":其他任何编辑都改变函数哈希或声明的位置操作数。 +4. **用"值很大且孤立"的启发式屏蔽哈希不可靠。** 位置操作数在含大头文件的 BMI 中同样可以超过 2^20,导入的声明号带有模块文件号而超过 + 2^32;把接口差异误判为哈希,后果是导入者静默使用旧接口,这是截断中最坏的一类错误。 + +## 3. A:不实现 + +A 的目标是 clang 上对"哈希、偏移与位置之外没有差异"的 BMI 保留旧文件。第 2.8 节的测量说明,达到这个目标需要: + +- 声明记录的布局模型(哈希的位置随声明的形式与版本而异),或 clang 提供不含函数哈希的 reduced BMI; +- 按记录而不是按位比较(宽度翻转),及偏移表与声明上下文偏移的事实表。 + +这超出了"按版本的操作数表,500 行以内"的前提,并且没有对"误屏蔽接口差异"的保证。GCC 读者的重构(共用比较内核、`format/` 目录) +只为 A 服务,随之不做:一个 PR 一件事,没有第二个使用者的抽象不引入。 + +**重新可行的条件**(任一):clang 的 reduced BMI 不再写入非 inline 函数的 ODR 哈希,或提供不含它的开关;LLVM 提供读取 `.pcm` 声明记录的 +稳定接口;或位置与哈希被集中在一处可按名定位的记录中。届时的做法仍是第 3.5 节(v3)的按块屏蔽,由真实编译器的差分用例校准。 + +**记录**:SPEC-019 §8 第二行、SPEC-018 §2.2、`modules/buildopt/README.md` 的"已记录、未实现"各增加一句测量结论。clang 上止住级联仍靠 +私有片段的拆分(B 使它适用于更多的清单)。 + +## 4. B:私有片段判定的收窄 + +### 4.1 现状 + +`source::private_fragment` 在片段之前、`export module` 之后遇到任何以 `#` 开头的行,即按原样构建。清单中常见的 `#if`/`#ifdef` 包着声明或 `import` +的写法因此全部失去拆分。 + +### 4.2 新规则 + +| 指令 | 处理 | 原因 | +|---|---|---| +| `#define`、`#undef` | 拒绝 | 宏状态不随 BMI 带入实现单元,片段中的 `#if` 会求出不同的值 | +| `#include` | 拒绝 | 它定义的宏同上 | +| `#pragma`、`_Pragma`、`__pragma` | 拒绝 | `pack`、诊断状态不随 BMI | +| `#line` | 拒绝 | 生成单元以物理行号写 `#line`,与自行写的 `#line` 冲突 | +| 其余未列出的指令(`#ident`、`# 12 "f"` 等) | 拒绝 | 没有把握时按原样构建 | +| `#if`、`#ifdef`、`#ifndef`、`#elif`、`#elifdef`、`#elifndef`、`#else`、`#endif`、空指令 | 放行;在 `export module` 声明所在行与片段所在行,条件的嵌套深度必须为 0 | 条件只决定哪些声明存在,实现单元经 BMI 取得声明;条件跨过声明或片段,两个单元不会闭合它 | +| `#error`、`#warning` | 放行,其余部分不作记号读取(`#warning don't`) | 与片段无关 | + +条件内部的 `#define` 等仍按上表拒绝,不论其分支是否生效:判定只读文本。取值 `conservative` 退回放宽之前的规则:片段之前出现任何指令即拒绝。 + +### 4.3 与匿名命名空间、`static` 的判定的关系 + +不变。clang 23 的实测(实现单元对接口 purview 中非导出声明的可见性):`constexpr`/`const` 变量、`inline constexpr`、别名、非导出结构体与函数、无名枚举、 +`typedef struct {…} T`、模块链接的变量,在拆分后的实现单元中均可见;`static` 函数在命名空间中不可见,报 `no member named …`。拒绝列表只含 TU 局部的两类,与此一致。 + +## 5. C:判定的词法缺口 + +旧的 `code_of` 逐行去注释与字符串。缺口及后果(后果是编译错误,不是静默的语义差异)与修正: + +| 缺口 | 现象 | 修正 | +|---|---|---| +| 数字分隔符 `1'000` 被当作字符字面量的起点,吞掉该行余下部分 | 同一行的 `static` 与花括号被漏判 | pp-number 内部的 `'`(其后是标识符字符)属于数字;指数符号与点属于数字 | +| 原始字符串 `R"d(…)d"` 跨行 | 其中的 `module :private;` 或引号被当作代码 | 一遍扫描全文,带原始字符串状态(前缀 `R`、`u8R`、`uR`、`UR`、`LR`,定界符至多 16 个字符) | +| `extern "C" {` 内的 `static` | 作用域被当作非命名空间 | 链接说明的块按命名空间处理 | +| 行末 `\` 连接 | 逻辑行与物理行不一致 | 模块声明与片段之间出现行连接即按原样构建;`//` 注释的续行按语言规则处理 | + +实现:`read_code` 对全文做一遍扫描,输出与原文同长、换行保留、注释与字面量内容替换为空格的文本,行号映射不变;`#include`、`#error`、`#warning` 之后的 +部分整行视为非记号。 + +## 6. 默认值的门槛 + +B 与 C 在判定只读文本、没有把握即按原样构建的前提下默认开启。两项不引入新的取值之外的行为;退回办法是 `conservative` 与 `as-written`。 +A 的门槛(原第 6 节)随 A 撤回。 + +## 7. 控制开关与失败时的验证提示 + +### 7.1 开关清单 + +| 优化 | 清单键 | 环境变量 | 取值(默认在前) | 检查值(`check`) | +|---|---|---|---|---| +| `gcm-locations` | `[profile.] bmi_cutoff` | `MCPP_BMI_CUTOFF` | `ignore-locations`、`exact` | `exact` | +| `private-fragment` | `[build] private_fragment` | `MCPP_PRIVATE_FRAGMENT` | `unit`、`conservative`(新)、`as-written` | `as-written`;GCC 上 `conservative` | +| 全部条目 | — | `MCPP_BUILDOPT=off` | — | — | + +1. `conservative`:仍把片段构建为独立单元,而判定回到放宽之前的规则。B 放宽了判定,GCC 不能把片段按原样构建,`as-written` 在 GCC 上不是可用的验证办法; + `conservative` 给两个编译器一个"只退回这一处放宽"的办法。 +2. C 的词法修正不设开关:它只把此前漏判的情形改为拒绝,后果是按原样构建,没有可关闭的行为。 +3. 严格级别的条目(`keep-bmi`、`keep-object`、`gcm-stamps`、`scan-pass`)产物与标准构建逐字节相同,只受总开关控制,没有 `check`。 +4. 登记表的行增加两个字段:`check` 与 `checkGcc`(编译器之间不同时的取值)。测试保证默认开启而有键的条目都有 `check`,且它是该行的取值之一、不是默认值。 + +### 7.2 验证的阶梯 + +1. 只关闭这一项,一次调用:`MCPP_PRIVATE_FRAGMENT=as-written mcpp build`、`MCPP_BMI_CUTOFF=exact mcpp build`。 +2. 关闭全部:`MCPP_BUILDOPT=off mcpp build`。 +3. 两步之后失败依旧:原因不在这些优化中。 + +### 7.3 失败时的提示 + +经 `diag::on_failure` 给出,在命令的输出之后,不改变退出状态,`--quiet` 下没有。(`diag::on_failure` 的记录不进入 `--format json` 的信封,这与已有的 +`platform/newer` 提示相同;v3 写成进入信封是错误的。)归属从失败的步骤出发: + +| 规则 | 失败的步骤 | 强度 | +|---|---|---| +| R1 | 源文件是私有片段拆出的单元 | 点名原文件 | +| R2 | 编译导入了一个当前以此前的位置保留着的 BMI(`bmi-kept.list`)的单元 | 点名模块 | +| R3 | 链接失败(链接器的措辞),且图中有拆出的片段或保留着的 BMI | 说明无法归属到单元 | +| R4 | 其他任何步骤 | 无 | + +失败的步骤由 ninja 的 `FAILED:` 行经步骤记录(`steps.tsv`)映射到源文件;取不到时按 R4。测试程序的运行失败不给出提示。 + +**实现。** `mcpp.buildopt.advice` 增加 `Applied`(计划写入的两张表)、`suspects`(纯函数)、`write_applied`/`read_applied`、`failed_outputs`、`linker_failed`; +`mcpp.buildopt.keep::kept`。计划在写图时把旁表写入 `buildopt-applied.tsv`(片段:原文件与生成的单元;导入关系;`check` 的取值,按编译器), +快速路径(没有计划)读同一个文件;两条路径的失败出口各调用一次 `report_buildopt_failure`(`ninja_backend.cppm`)。 + +**失败发生的时刻。** 一个 BMI 的"保留"在它的编译边结束时才记录。同一次构建中一个导入者与该 BMI 的编译并行而先失败时,记录尚不存在,R2 不给出; +给出的情形是"此前的构建保留了它,之后的构建中导入者失败"。这是现状,不是缺陷:只有已记录的事实才被说出。 + +### 7.4 与 v3 的差别 + +v3 的 R1 到 R4 与文本不变。变化:`conservative` 的描述,`check` 之外增加 `checkGcc`,JSON 信封一条删除,提示数据经旁表而不是计划对象(快速路径没有计划)。 + +### 7.5 实施中发现:开关的取值改变,快速路径重放旧图 + +对 `MCPP_PRIVATE_FRAGMENT`、`MCPP_BUILDOPT`、`MCPP_BMI_SCHEDULE`(决定图的形态的条目)只改取值而不改文件时,快速路径按"没有变化"重放上一次写的图, +第一次构建不是所要求的那一次(`as-written` 或 `conservative` 之后换回 `unit`,仍是按原样构建的图)。它在本次改动之前就存在,只是没有被测过; +开关的"取值改变后第一次构建正确"需要它成立,因此一并修复:`toolchain_request_identity` 把这三个环境变量并入请求,未陈述时的标识与此前相同, +只有陈述时才附加。边的条目(`MCPP_BMI_CUTOFF`)在执行时读取,不并入。 + +## 8. 未决的测量 + +| 编号 | 问题 | 结论 | +|---|---|---| +| U1 | clang 上单文件模块的编辑重编哪些单元 | 已测(2.5):直接导入者在本次构建、传递导入者在下一次构建编译。"无编辑的构建重新编译 `main`"另记一个问题,不并入本次 | +| U2 | 近期编辑按读者的判定分类 | 随 A 撤回 | +| U3 | VBR 宽度跨边界 | 已测(2.8):约三分之一的编辑;是 A 撤回的原因之一 | +| U4、U5 | 20.1.7 的一条记录;22.1.8 的成员函数哈希位置 | 随 A 撤回;2.8 已显示位置因声明而异 | + +## 9. 实施结果 + +| 范围 | 文件 | +|---|---| +| B、C、`conservative` | `modules/buildopt/src/source.cppm`(`read_code`、`directive_of`、`Fragment`、`private_fragment_policy`),`src/build/prepare/scan.cpp` | +| D | `modules/buildopt/src/registry.cppm`(`check`、`checkGcc`)、`advice.cppm`、`keep/keep.cppm`(`kept`),`src/build/ninja_backend.cppm`(旁表与失败出口)、`src/build/execute.cppm`(快速路径的失败出口与请求标识) | +| 规范 | SPEC-019 v1.1(§1、§5、§8、新增 §9)、SPEC-018 v1.1(§2.2) | +| 文档 | docs/26 与 docs/zh/26(条目表、片段一节、"检查一项优化是不是原因")、docs/04 与 docs/zh/04(`private_fragment` 的取值)、`modules/buildopt/README.md`、CHANGELOG | +| 测试 | `test_source.cpp`(约 55 条判定语料、重组性质、噪声不变性、400 个随机文本、`private_fragment_policy`)、`test_advice.cpp`(R1 至 R4、登记表的 `check`、`FAILED:` 解析、旁表往返)、`tests/e2e/build/basics.cpp` 的 1161 至 1164 | + +e2e:1161(条件放行、宏拒绝、`conservative`、取值改变后的第一次构建)、1162 与 1163(clang 与 GCC 的 R1、成功无提示、`--quiet` 无提示、检查值生效、不相干的失败无提示、R3)、 +1164(GCC 的 R2 与 `exact` 之后无提示)。 + +## 10. 自评审的结果 + +| 视角 | 发现 | 处理 | +|---|---|---| +| 正确性(A) | 屏蔽的字段位置随声明而异,宽度翻转移动偏移 | A 撤回(第 2.8、3 节);不以启发式代替模型 | +| 正确性(B) | `#if` 放行后,声明或片段可能位于条件之内 | 两处的嵌套深度必须为 0;`#endif` 多于 `#if` 同样拒绝 | +| 正确性(B) | 条件内的 `#define` 是否生效不可知 | 只读文本,一律拒绝 | +| 正确性(C) | 续行使物理行与逻辑行不同 | 模块声明与片段之间出现即按原样构建;GMF 中的宏续行不受影响 | +| 开关 | GCC 上没有 `as-written` | `conservative`、`checkGcc` | +| 开关 | 取值改变后第一次构建(7.5) | 请求标识并入三个环境变量;e2e 1161 E | +| 提示 | 以"这次构建用过什么"为条件会在不相干的失败上出现 | 以失败的步骤为条件;e2e 的反例 | +| 提示 | 失败的步骤取自输出格式 | 取不到按 R4,少说而不是多说;`progress` 已依赖同一格式 | +| 提示 | 保留的记录在编译边结束时才写 | 7.3:并行失败的导入者不给 R2;只说已记录的事实 | +| 范围 | GCC 读者的重构与 A 一起提出 | A 不做,重构随之不做 | +| 仓库规则 | 模块命名、新增条款带实现状态、循环不超过两层 | `source.cppm` 的扫描分为小函数;条款写入 SPEC-019 §5、§9 | + +## 11. 不在本文之内 + +- clang BMI 的读者(A):第 3 节。 +- 无标记地把单文件模块拆为接口与实现,及由语义提供者判定:SPEC-019 §8 第一行,仍未实施。 +- clang 之外的格式(MSVC 的 `.ifc`):不变,按字节比较。 +- 2.5 第 2 条的"一次无编辑的构建不是空操作":另记一个 mcpp 问题。 +- 测试程序运行失败时的提示:无法归属到优化,只在文档中给出阶梯。 +- `--format json` 的信封中的失败提示:`diag::on_failure` 的记录今天不进入信封,与 `platform/newer` 相同,另议。 +- 语言服务器一侧的联动。 diff --git a/.agents/docs/README.md b/.agents/docs/README.md index 4f606d77b..3b13c724b 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 --- ``` -373 records. +374 records. ## By subject @@ -30,6 +30,7 @@ Records that declare one. Everything else is listed by date below. ### build +- [clang BMI 的截断与私有模块片段判定的收窄](2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md) — active - [第二部分之后的补充方案:带修正的 ninja、模块重编译的级联、工作区发布与本轮遗留项](2026-11-17-ninja-cascade-publish-supplement-design.md) — active - [大型工作区的构建空间与复用(mcpp#874)](2026-10-31-workspace-space-and-reuse-design.md) — active - [依赖 image 的资源归属、模块扫描边界与锁文件稳定写入](2026-10-21-resource-ownership-module-scan-and-lock-write-design.md) — active @@ -215,6 +216,7 @@ Records that declare one. Everything else is listed by date below. ### 2026-11 +- [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 - [包的特性作为机器可读的回答:一个目录项,两种来源,三种状态(mcpp#992)](2026-11-21-package-features-query-design.md) — active From 40368cba937c05c85b3d67e30b375febd6775178 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 26 Nov 2026 06:26:14 +0900 Subject: [PATCH 3/7] buildopt: a private fragment is a unit of its own after conditions; the purview is read as C++ tokens; private_fragment = conservative --- modules/buildopt/src/source.cppm | 310 +++++++++++++++++++++---- modules/buildopt/tests/test_source.cpp | 206 +++++++++++++++- src/build/prepare/scan.cpp | 8 +- 3 files changed, 471 insertions(+), 53 deletions(-) diff --git a/modules/buildopt/src/source.cppm b/modules/buildopt/src/source.cppm index d6f926380..b57707bb5 100644 --- a/modules/buildopt/src/source.cppm +++ b/modules/buildopt/src/source.cppm @@ -31,15 +31,34 @@ // // WHAT MAKES A FRAGMENT NOT MOVABLE, AND IS THEREFORE LEFT AS WRITTEN. The // implementation unit sees what the interface declares in the module's -// purview; it does not see what is local to the interface's translation unit. -// Read from the text, with no semantic analysis, and refused when in doubt: +// purview; it does not see what is local to the interface's translation unit, +// nor what the preprocessor held there. Read from the text, with no semantic +// analysis, and refused when in doubt: // -// - a preprocessor directive in the purview before the fragment (a macro the -// fragment may use; the global module fragment is copied, and is not this) -// - an unnamed namespace, or `static` at namespace scope, before the fragment +// - a directive in the purview before the fragment that changes what the +// fragment means: `#define`, `#undef`, `#include`, `#pragma`, `#line`, and +// any not named below. The conditionals (`#if`, `#ifdef`, `#ifndef`, +// `#elif`, `#else`, `#endif`) and `#error`, `#warning` do not: a condition +// only decides which declarations exist, and the implementation unit +// receives them from the BMI. A condition that is open at the module +// declaration or at the fragment is refused, since the units would not +// close it. (The global module fragment is copied, and is not this.) +// - a use of `_Pragma` or `__pragma` there +// - an unnamed namespace, or `static` at namespace scope (a linkage +// specification `extern "C" { ... }` is namespace scope), before the +// fragment // - a using-directive at namespace scope before the fragment +// - a line continuation (`\` before a newline) from the module declaration +// to the fragment, where a physical line is not a logical one // - a module that is a partition, or no module declaration at all // +// The text is read once as C++ tokens: comments, string and character +// literals (raw strings included) are blanked, and a digit separator +// (`1'000`) is part of a number, not the start of a literal. With +// `private_fragment = "conservative"` any directive in that purview refuses, +// which is the rule before the narrowed one and the one a compiler that +// cannot build a fragment as written (GCC) is checked against. +// // A fragment that passes these and still does not build as a unit names its // own lines in the compiler's error; `private_fragment = "as-written"` builds // the source as it is. @@ -62,16 +81,18 @@ struct Units { // The units a source with a private module fragment is built as. nullopt: the // text has no private module fragment. An error: it has one that stays as // written, and why. `spelling` is the file's path as `#line` names it. +// `conservative`: any directive in the purview before the fragment refuses, +// as it did before the conditionals were let through. std::optional> -private_fragment(std::string_view text, std::string_view spelling); +private_fragment(std::string_view text, std::string_view spelling, bool conservative = false); -// Whether this build builds private module fragments as units: the entry's -// switch (`MCPP_PRIVATE_FRAGMENT`, then `[build] private_fragment`, then the +// How this build builds private module fragments: the entry's switch +// (`MCPP_PRIVATE_FRAGMENT`, then `[build] private_fragment`, then the // default, "unit"), under the statement that turns every entry off. A value -// that is neither "unit" nor "as-written" is handed to `onInvalid` and the -// default stands. -bool private_fragment_as_unit(const mcpp::manifest::Manifest& m, - const std::function& onInvalid = {}); +// that is none of the three is handed to `onInvalid` and the default stands. +enum class Fragment { AsWritten, Unit, Conservative }; +Fragment private_fragment_policy(const mcpp::manifest::Manifest& m, + const std::function& onInvalid = {}); } // namespace mcpp::buildopt::source @@ -85,11 +106,12 @@ std::string_view trim(std::string_view s) { return s; } +bool ident_char(char c) { return std::isalnum(static_cast(c)) || c == '_'; } + bool word_at(std::string_view s, std::size_t at, std::string_view word) { - auto ident = [](char c) { return std::isalnum(static_cast(c)) || c == '_'; }; if (s.substr(at, word.size()) != word) return false; - if (at > 0 && ident(s[at - 1])) return false; - return at + word.size() >= s.size() || !ident(s[at + word.size()]); + if (at > 0 && ident_char(s[at - 1])) return false; + return at + word.size() >= s.size() || !ident_char(s[at + word.size()]); } bool has_word(std::string_view s, std::string_view word) { @@ -98,28 +120,177 @@ bool has_word(std::string_view s, std::string_view word) { return false; } -// One line's code: comments removed, string and character literals blanked. -// `inBlock` carries a block comment over lines. -std::string code_of(std::string_view line, bool& inBlock) { - std::string out; - for (std::size_t i = 0; i < line.size(); ++i) { - if (inBlock) { - if (line.substr(i, 2) == "*/") { inBlock = false; ++i; } - continue; +// THE TEXT AS C++ TOKENS, to the length it has. Comments and the contents of +// string and character literals are blanked (the newlines stay, so a line is a +// line), and `joins` holds the offsets of a backslash that joins its line to +// the next. Three things a reader by lines gets wrong are read here: +// +// 1'000 a digit separator is part of a number; taken for the start of +// a character literal it hid the rest of the line, `;` and `{` +// R"d(...)d" a raw string runs over lines and holds anything, `"` and +// `module :private;` included +// \ a comment, a literal or a directive goes on to the next line +struct Code { + std::string text; + std::vector joins; +}; + +// The newline at `at` is joined to the next line by a backslash before it. +bool joined(std::string_view t, std::size_t at) { + if (at > 0 && t[at - 1] == '\r') --at; + return at > 0 && t[at - 1] == '\\'; +} + +// The end of the logical line that holds `from`: its newline, or the text's end. +std::size_t line_end(std::string_view t, std::size_t from, std::vector& joins) { + for (std::size_t j = from; j < t.size(); ++j) { + if (t[j] != '\n') continue; + if (!joined(t, j)) return j; + joins.push_back(j); + } + return t.size(); +} + +// A raw string opens at the quote at `at` when an `R` (with its encoding +// prefix, if any) stands before it as a word of its own. +bool raw_string_at(std::string_view t, std::size_t at) { + if (at == 0 || t[at - 1] != 'R') return false; + std::size_t from = at - 1; + while (from > 0 && ident_char(t[from - 1])) --from; + const auto prefix = t.substr(from, at - from); + return prefix == "R" || prefix == "u8R" || prefix == "uR" || prefix == "UR" || prefix == "LR"; +} + +// One past the end of the raw string opened at `at`; npos when it is not +// well formed (no `(`, a delimiter of more than 16 characters or with a +// character it may not have, no closing), and the compiler then says why. +std::size_t raw_string_end(std::string_view t, std::size_t at) { + const auto open = t.find('(', at + 1); + if (open == std::string_view::npos || open - at - 1 > 16) return std::string_view::npos; + const auto delimiter = t.substr(at + 1, open - at - 1); + if (delimiter.find_first_of(" ()\\\t\r\n") != std::string_view::npos) return std::string_view::npos; + const auto closing = std::format("){}\"", delimiter); + const auto end = t.find(closing, open + 1); + return end == std::string_view::npos ? end : end + closing.size(); +} + +// One past the closing quote of the literal opened by the quote at `at`; where +// a newline comes first the literal is not closed, and ends before it. +std::size_t quoted_end(std::string_view t, std::size_t at, std::vector& joins) { + const char quote = t[at]; + for (std::size_t j = at + 1; j < t.size(); ++j) { + if (t[j] == '\\') { + std::size_t next = j + 1; + if (next + 1 < t.size() && t[next] == '\r' && t[next + 1] == '\n') ++next; + if (next < t.size() && t[next] == '\n') joins.push_back(j); + j = next; + } else if (t[j] == quote) { + return j + 1; + } else if (t[j] == '\n') { + return j; } - if (line.substr(i, 2) == "//") break; - if (line.substr(i, 2) == "/*") { inBlock = true; ++i; continue; } - if (line[i] == '"' || line[i] == '\'') { - const char quote = line[i]; - out += quote; - for (++i; i < line.size() && line[i] != quote; ++i) - if (line[i] == '\\') ++i; - out += quote; + } + return t.size(); +} + +// One past the end of the pp-number that starts at `at`: identifier characters +// and dots, a sign after an exponent, and a `'` before one more of them. +std::size_t number_end(std::string_view t, std::size_t at) { + std::size_t j = at; + for (; j < t.size(); ++j) { + const char c = t[j]; + const bool sign = (c == '+' || c == '-') && j > at && std::string_view("eEpP").contains(t[j - 1]); + const bool separator = c == '\'' && j + 1 < t.size() && ident_char(t[j + 1]); + if (!(ident_char(c) || c == '.' || sign || separator)) break; + } + return j; +} + +// The directives whose rest of the line is not tokens (`#include `, +// `#error don't`). +bool text_directive(std::string_view word) { + return word == "include" || word == "include_next" || word == "import" || word == "error" || word == "warning"; +} + +Code read_code(std::string_view t) { + Code r{std::string(t), {}}; + auto blank = [&](std::size_t from, std::size_t to) { + for (; from < to && from < r.text.size(); ++from) + if (r.text[from] != '\n' && r.text[from] != '\r') r.text[from] = ' '; + }; + bool lineStart = true; + for (std::size_t i = 0; i < t.size();) { + const char c = t[i]; + if (c == '\n') { lineStart = true; ++i; continue; } + if (c == ' ' || c == '\t' || c == '\r') { ++i; continue; } + if (c == '\\') { + std::size_t next = i + 1; + if (next + 1 < t.size() && t[next] == '\r' && t[next + 1] == '\n') ++next; + if (next < t.size() && t[next] == '\n') { r.joins.push_back(i); i = next + 1; continue; } + } + const bool atLineStart = std::exchange(lineStart, false); + if (c == '#' && atLineStart) { + std::size_t w = i + 1; + while (w < t.size() && (t[w] == ' ' || t[w] == '\t')) ++w; + std::size_t e = w; + while (e < t.size() && ident_char(t[e])) ++e; + if (text_directive(t.substr(w, e - w))) { + const auto end = line_end(t, e, r.joins); + blank(e, end); + i = end; + continue; + } + } else if (t.substr(i, 2) == "//") { + const auto end = line_end(t, i, r.joins); + blank(i, end); + i = end; + continue; + } else if (t.substr(i, 2) == "/*") { + const auto close = t.find("*/", i + 2); + const auto end = close == std::string_view::npos ? t.size() : close + 2; + blank(i, end); + i = end; + continue; + } else if (c == '"' && raw_string_at(t, i) && raw_string_end(t, i) != std::string_view::npos) { + const auto end = raw_string_end(t, i); + blank(i + 1, end - 1); + i = end; + continue; + } else if (c == '"' || c == '\'') { + const auto end = quoted_end(t, i, r.joins); + blank(i + 1, end > i + 1 && t[end - 1] == c ? end - 1 : end); + i = end; + continue; + } else if ((std::isdigit(static_cast(c)) + || (c == '.' && i + 1 < t.size() && std::isdigit(static_cast(t[i + 1])))) + && (i == 0 || !ident_char(t[i - 1]))) { + i = number_end(t, i); continue; } - out += line[i]; + ++i; } - return out; + return r; +} + +// The word after the `#` of a directive line (empty for a line that is `#` +// alone, and for one whose next token is not a word: `# 12 "file"`); nullopt +// when the line is not a directive. +std::optional directive_of(std::string_view line) { + line = trim(line); + if (!line.starts_with('#')) return std::nullopt; + line = trim(line.substr(1)); + std::size_t n = 0; + while (n < line.size() && ident_char(line[n])) ++n; + return n == 0 && !line.empty() ? std::string_view("?") : line.substr(0, n); +} + +// What a directive does to the fragment's meaning. The conditionals only +// decide which declarations exist, and the implementation unit receives those +// from the interface; `#error` and `#warning` are said where they stand. +bool opens_condition(std::string_view w) { return w == "if" || w == "ifdef" || w == "ifndef"; } +bool leaves_meaning(std::string_view w) { + return w.empty() || opens_condition(w) || w == "endif" || w == "else" || w == "elif" || w == "elifdef" + || w == "elifndef" || w == "error" || w == "warning"; } std::string line_directive(std::size_t line, std::string_view spelling) { @@ -131,22 +302,35 @@ std::string line_directive(std::size_t line, std::string_view spelling) { return std::format("#line {} \"{}\"\n", line, quoted); } +// The conditional directives open at line `to` (not counting it). +int open_conditions(const std::vector& code, std::size_t to) { + int depth = 0; + for (std::size_t i = 0; i < to; ++i) { + const auto w = directive_of(code[i]); + if (!w) continue; + if (opens_condition(*w)) ++depth; + else if (*w == "endif") --depth; + } + return depth; +} + } // namespace std::optional> -private_fragment(std::string_view text, std::string_view spelling) { +private_fragment(std::string_view text, std::string_view spelling, bool conservative) { std::vector lines; + std::vector starts; for (std::size_t at = 0; at <= text.size();) { const auto end = text.find('\n', at); + starts.push_back(at); lines.push_back(text.substr(at, end == std::string_view::npos ? std::string_view::npos : end - at)); if (end == std::string_view::npos) break; at = end + 1; } - std::vector code(lines.size()); - { - bool inBlock = false; - for (std::size_t i = 0; i < lines.size(); ++i) code[i] = code_of(lines[i], inBlock); - } + const auto scanned = read_code(text); + std::vector code; + for (std::size_t i = 0; i < lines.size(); ++i) + code.emplace_back(std::string_view(scanned.text).substr(starts[i], lines[i].size())); auto compact = [](std::string_view s) { std::string c; for (char ch : s) @@ -176,15 +360,40 @@ private_fragment(std::string_view text, std::string_view spelling) { if (moduleName.find(':') != std::string::npos) return Result{std::unexpected("the unit is a partition")}; + // Where a physical line is not a logical one, the lines below are not the + // text the compiler reads. + for (auto at : scanned.joins) { + const auto line = static_cast(std::ranges::upper_bound(starts, at) - starts.begin()) - 1; + if (line >= *declared && line <= *fragment) + return Result{std::unexpected(std::format( + "line {}: a line continuation between the module declaration and the fragment", line + 1))}; + } + // A condition that holds the declaration or the fragment is not closed by + // the unit that ends before the one and begins at the other. + if (!conservative) { + if (open_conditions(code, *declared) != 0) + return Result{std::unexpected(std::format( + "line {}: a conditional directive is open at the module declaration", *declared + 1))}; + if (open_conditions(code, *fragment) != 0) + return Result{std::unexpected(std::format( + "line {}: a conditional directive is open at the fragment", *fragment + 1))}; + } + // The purview before the fragment: what is local to the interface's // translation unit, and so not seen by an implementation unit. std::vector scopes; // one a brace still open; true: a namespace's std::string statement; // the code since the last `;`, `{` or `}` for (std::size_t i = *declared + 1; i < *fragment; ++i) { const auto c = trim(code[i]); - if (c.starts_with("#")) + if (const auto word = directive_of(c)) { + if (conservative || !leaves_meaning(*word)) + return Result{std::unexpected(std::format( + "line {}: a preprocessor directive in the module's purview before the fragment", i + 1))}; + continue; + } + if (has_word(c, "_Pragma") || has_word(c, "__pragma")) return Result{std::unexpected(std::format( - "line {}: a preprocessor directive in the module's purview before the fragment", i + 1))}; + "line {}: a pragma in the module's purview before the fragment", i + 1))}; for (char ch : c) { if (ch == '{') { const bool ns = has_word(statement, "namespace") && statement.find('(') == std::string::npos; @@ -200,7 +409,11 @@ private_fragment(std::string_view text, std::string_view spelling) { && std::ranges::all_of(scopes, [](bool s) { return s; })) return Result{std::unexpected(std::format( "line {}: `static` at namespace scope before the fragment", i + 1))}; - scopes.push_back(ns); + // `extern "C" {` holds declarations of the scope it stands in. + const auto st = trim(statement); + const bool linkage = st.starts_with("extern") && word_at(st, 0, "extern") + && trim(st.substr(6)).starts_with('"') && trim(st.substr(6)).ends_with('"'); + scopes.push_back(ns || linkage); statement.clear(); } else if (ch == '}') { if (!scopes.empty()) scopes.pop_back(); @@ -245,16 +458,17 @@ private_fragment(std::string_view text, std::string_view spelling) { return Result{std::move(units)}; } -bool private_fragment_as_unit(const mcpp::manifest::Manifest& m, - const std::function& onInvalid) { - if (registry::standard_only()) return false; +Fragment private_fragment_policy(const mcpp::manifest::Manifest& m, + const std::function& onInvalid) { + if (registry::standard_only()) return Fragment::AsWritten; std::string v; if (auto e = mcpp::invocation::get("MCPP_PRIVATE_FRAGMENT")) v = *e; else v = m.buildConfig.privateFragment; - if (v.empty() || v == "unit") return true; - if (v == "as-written") return false; + if (v.empty() || v == "unit") return Fragment::Unit; + if (v == "conservative") return Fragment::Conservative; + if (v == "as-written") return Fragment::AsWritten; if (onInvalid) onInvalid(v); - return true; + return Fragment::Unit; } } // namespace mcpp::buildopt::source diff --git a/modules/buildopt/tests/test_source.cpp b/modules/buildopt/tests/test_source.cpp index 67b890ef0..5078c327f 100644 --- a/modules/buildopt/tests/test_source.cpp +++ b/modules/buildopt/tests/test_source.cpp @@ -1,11 +1,14 @@ // The source seam's one entry: a private module fragment as a unit of its own. // The text in, the two units out -- and every fragment that is left as written, -// with the line that says why. +// with the line that says why. The corpus below is the verdict for each kind of +// text before the fragment: the directives, the conditions, the lexical forms +// a reader by lines gets wrong, and `conservative`. import std; import mcpplibs.mtest; import mcpp.buildopt.source; import mcpp.buildopt.registry; +import mcpp.manifest; using namespace mcpplibs::mtest; namespace source = mcpp::buildopt::source; @@ -63,6 +66,207 @@ UTest members_are_not_namespace_scope{"Source/AStaticMemberAndANamedNamespaceAre expect(r->has_value()) << (r->has_value() ? std::string{} : r->error()); }}; +namespace { +// `split` or the reason the fragment stays as written. +std::string verdict(std::string_view text, bool conservative = false) { + const auto r = source::private_fragment(text, kFile, conservative); + if (!r) return "no-fragment"; + return *r ? std::string("split") : r->error(); +} +// The reason without its line number. +std::string kind_of(std::string_view v) { + if (v.starts_with("line ")) { + const auto colon = v.find(": "); + if (colon != std::string_view::npos) return std::string(v.substr(colon + 2)); + } + return std::string(v); +} +const std::string kHead = "export module c;\n"; +const std::string kTail = "module :private;\nint f() { return 1; }\n"; +std::string with(std::string_view purview, std::string_view head = "export module c;\n") { + return std::string(head) + std::string(purview) + kTail; +} +struct Case { + const char* name; + std::string text; + const char* want; // "split", "no-fragment" or a part of the reason + const char* wantConservative = nullptr; // when `conservative` differs +}; +} // namespace + +// THE DIRECTIVES. A directive that changes what the fragment means refuses: the +// macro or the pragma state is the interface unit's, and does not reach the +// implementation unit. A condition only decides which declarations exist. +UTest corpus{"Source/TheVerdictOfEachKindOfTextBeforeTheFragment", [] { + const std::vector cases{ + {"define", with("#define N 1\n"), "a preprocessor directive"}, + {"undef", with("#undef N\n"), "a preprocessor directive"}, + {"include", with("#include \n"), "a preprocessor directive"}, + {"pragma", with("#pragma once\n"), "a preprocessor directive"}, + {"line", with("#line 5\n"), "a preprocessor directive"}, + {"unknown", with("#ident \"x\"\n"), "a preprocessor directive"}, + {"marker", with("# 12 \"f.h\"\n"), "a preprocessor directive"}, + {"spaces", with(" # define N 1\n"), "a preprocessor directive"}, + {"_Pragma", with("_Pragma(\"once\") int x;\n"), "a pragma"}, + {"__pragma", with("__pragma(warning(disable: 1)) int x;\n"), "a pragma"}, + {"if", with("#if A\nexport int g();\n#endif\n"), "split", "a preprocessor directive"}, + {"ifdef-else", with("#ifdef A\nexport int g();\n#else\nexport int g(int);\n#endif\n"), "split", "a preprocessor directive"}, + {"ifndef-elif", with("#ifndef A\nexport int g();\n#elif B\nexport int h();\n#endif\n"), "split", "a preprocessor directive"}, + {"elifdef", with("#if A\n#elifdef B\nexport int g();\n#endif\n"), "split", "a preprocessor directive"}, + {"error", with("#if 0\n#error never\n#endif\n"), "split", "a preprocessor directive"}, + {"warning-with-quote", with("#warning don't\n"), "split", "a preprocessor directive"}, + {"null-directive", with("#\n"), "split", "a preprocessor directive"}, + {"define-in-condition", with("#if A\n#define N 1\n#endif\n"), "a preprocessor directive"}, + {"condition-spans-fragment", kHead + "#if A\nexport int g();\n" + kTail + "#endif\n", "open at the fragment", + "a preprocessor directive"}, + {"declaration-in-condition", "#if A\nexport module c;\n#endif\n" + kTail, "open at the module declaration", + "a preprocessor directive"}, + {"balanced-before-declaration", "module;\n#if A\n#include \n#endif\nexport module c;\nexport int g();\n" + kTail, "split"}, + {"stray-endif", with("#endif\n"), "open at the fragment", "a preprocessor directive"}, + {"global-fragment-define", "module;\n#define N 1\n#include \nexport module c;\nexport int g();\n" + kTail, "split"}, + // The scope the fragment cannot see. + {"unnamed-namespace", with("namespace {\nint h;\n}\n"), "an unnamed namespace"}, + {"static-variable", with("static int h = 1;\n"), "`static` at namespace scope"}, + {"static-in-named", with("namespace n {\nstatic int h() { return 1; }\n}\n"), "`static` at namespace scope"}, + {"using-directive", with("using namespace std;\n"), "a using-directive"}, + {"partition", "export module c:p;\n" + kTail, "a partition"}, + {"no-declaration", "int x;\n" + kTail, "no `export module` declaration"}, + {"no-fragment", "export module c;\nexport int g();\n", "no-fragment"}, + // What a reader by lines gets wrong. + {"digit-separator-hides-static", with("constexpr int k = 1'000; static int h = 2;\n"), "`static` at namespace scope"}, + {"digit-separator-hex", with("constexpr unsigned k = 0xFF'FFu; static int h = 2;\n"), "`static` at namespace scope"}, + {"digit-separator-binary", with("constexpr int k = 0b1'0; constexpr int j = 1'0'0;\n"), "split"}, + {"exponent-sign", with("constexpr double d = 1.5e+3; static int h;\n"), "`static` at namespace scope"}, + {"char-literal", with("constexpr char c = 'a'; constexpr char d = '\\'';\n"), "split"}, + {"u8-char", with("constexpr char8_t c = u8'a';\n"), "split"}, + {"string-with-brace", with("const char* s = \"{ static int\";\n"), "split"}, + {"raw-string-with-namespace", with("const char* s = R\"x(\nnamespace {\nstatic int h;\n)x\";\n"), "split"}, + {"raw-string-with-fragment-words", "export module c;\nconst char* s = R\"(\nmodule :private;\n)\";\n", "no-fragment"}, + {"raw-string-prefix", with("const char* s = u8R\"(namespace {)\";\n"), "split"}, + {"raw-string-delimiter", with("const char* s = R\"--(\")(namespace {)--\";\n"), "split"}, + {"not-a-raw-string", with("int xR = 1; const char* s = \"static\";\n"), "split"}, + {"extern-c-static", with("extern \"C\" {\nstatic int h();\n}\n"), "`static` at namespace scope"}, + {"extern-cxx-static", with("extern \"C++\" {\nstatic int h;\n}\n"), "`static` at namespace scope"}, + {"extern-c-plain", with("extern \"C\" {\nint g();\n}\n"), "split"}, + {"extern-c-in-function", with("void g() {\nextern \"C\" int h();\nstatic int n = 0;\n}\n"), "split"}, + {"continuation", with("constexpr int k = 1 + \\\n2;\n"), "a line continuation"}, + {"continuation-crlf", with("constexpr int k = 1 + \\\r\n2;\n"), "a line continuation"}, + {"continued-comment", with("// a comment \\\nstatic int h;\n"), "a line continuation"}, + {"continuation-in-global-fragment", "module;\n#define X \\\n 1\nexport module c;\nexport int g();\n" + kTail, "split"}, + {"comment-with-quote", with("// don't \"quote\nexport int g();\n"), "split"}, + {"block-comment-with-fragment", with("/* module :private;\nstatic int h; */\n"), "split"}, + }; + for (auto const& c : cases) { + const auto got = verdict(c.text); + expect(has(got, c.want)) << c.name << ": " << got; + const auto want = c.wantConservative ? c.wantConservative : c.want; + const auto conservative = verdict(c.text, true); + expect(has(conservative, want)) << c.name << " (conservative): " << conservative; + } +}}; + +// The two units hold the text between them: the interface unit the lines before +// the fragment, the implementation unit the lines after it, at the lines they +// had (its `#line` says so). +UTest units_hold_the_text{"Source/TheTwoUnitsHoldEveryLineOfTheText", [] { + const std::vector texts{ + "module;\n#include \nexport module a.b;\nexport int f();\nmodule : private ;\nint f() { return 1; }\n", + "export module c;\n#if A\nexport int g();\n#endif\nmodule :private;\nint g() { return 2; }\nint h() { return 3; }", + "export module c;\nmodule :private;\n", + "export module c;\r\nexport int g();\r\nmodule :private;\r\nint g() { return 1; }\r\n", + }; + auto lines_of = [](std::string_view u) { + std::vector out; + for (std::size_t at = 0; at <= u.size();) { + const auto end = u.find('\n', at); + auto l = std::string(u.substr(at, end == std::string_view::npos ? std::string_view::npos : end - at)); + if (!l.starts_with("#line ")) out.push_back(std::move(l)); + if (end == std::string_view::npos) break; + at = end + 1; + } + return out; + }; + for (auto const& text : texts) { + const auto r = source::private_fragment(text, kFile); + expect(fatal(r.has_value() && r->has_value())) << text; + const auto interfaceLines = lines_of((**r).interfaceUnit); + const auto implementationLines = lines_of((**r).implementation); + const auto original = lines_of(text); + expect(!implementationLines.empty()) << text; + const auto fragmentAt = std::ranges::find_if(original, [](const std::string& l) { + std::string c; + for (char ch : l) if (ch != ' ' && ch != '\t' && ch != '\r') c += ch; + return c == "module:private;"; + }); + expect(fragmentAt != original.end()) << text; + // The interface unit holds the lines before the fragment. + expect(std::ranges::equal(std::span(interfaceLines).first(static_cast(fragmentAt - original.begin())), + std::span(original).first(static_cast(fragmentAt - original.begin())))) << text; + // The implementation unit carries the lines after the fragment as they were. + const auto after = std::vector(fragmentAt + 1, original.end()); + expect(implementationLines.size() >= after.size()) << text; + expect(std::ranges::equal(std::span(implementationLines).last(after.size()), after)) << text; + } +}}; + +// A line that is only a comment or a digit separator in a literal changes no +// verdict: the reason is the same text, a line further. +UTest lexical_noise_changes_nothing{"Source/ACommentOrADigitSeparatorChangesNoVerdict", [] { + const std::vector purviews{ + "", "static int h = 1;\n", "namespace {\nint h;\n}\n", "#define N 1\n", "#if A\nexport int g();\n#endif\n", + "using namespace std;\n", "extern \"C\" {\nstatic int h;\n}\n", + }; + for (auto const& purview : purviews) { + const auto plain = verdict(with(purview)); + for (std::string_view noise : {"// don't \"quote \\'\n", "/* 1'000 \" */\n", "constexpr int n_ = 1'000'000;\n", + "const char* r_ = R\"(\" ' )\";\n"}) { + const auto got = verdict(with(std::string(noise) + purview)); + expect(eq(kind_of(plain), kind_of(got))) << purview << " + " << noise << ": " << got; + } + } +}}; + +// Whatever the text, the answer is a verdict, never a crash; a text of +// fragments of the language is read in the hundreds. +UTest any_text_has_a_verdict{"Source/AnyTextHasAVerdict", [] { + const std::vector pieces{ + "export module c;\n", "module :private;\n", "module;\n", "#if A\n", "#endif\n", "#define N 1\n", "namespace {\n", "}\n", + "static int h;\n", "'", "\"", "R\"x(", ")x\"", "\\\n", "/*", "*/", "//", "1'0", "extern \"C\" {\n", "using namespace s;\n", + "\r\n", "int f() { return 1; }\n", "export int g();\n", " ", "\t", "\n", "{", "}", ";", + }; + std::mt19937 gen(20261126); + for (int n = 0; n < 400; ++n) { + std::string text; + for (int k = std::uniform_int_distribution(1, 14)(gen); k > 0; --k) + text += pieces[std::uniform_int_distribution(0, pieces.size() - 1)(gen)]; + for (bool conservative : {false, true}) { + const auto r = source::private_fragment(text, kFile, conservative); + if (r && *r) { + // A split unit scans as the module it was: it still names it. + expect(has((**r).implementation, "module c;")) << text; + expect(has((**r).interfaceUnit, "export module c;")) << text; + } + } + } +}}; + +UTest policy_is_the_entrys_switch{"Source/TheFragmentPolicyIsTheEntrysSwitch", [] { + mcpp::manifest::Manifest m; + std::string invalid; + auto policy = [&] { return source::private_fragment_policy(m, [&](std::string_view v) { invalid = std::string(v); }); }; + expect(policy() == source::Fragment::Unit); + m.buildConfig.privateFragment = "unit"; + expect(policy() == source::Fragment::Unit); + m.buildConfig.privateFragment = "conservative"; + expect(policy() == source::Fragment::Conservative); + m.buildConfig.privateFragment = "as-written"; + expect(policy() == source::Fragment::AsWritten); + expect(invalid.empty()); + m.buildConfig.privateFragment = "split"; + expect(policy() == source::Fragment::Unit); + expect(eq(invalid, std::string("split"))); +}}; + UTest register_states_every_entry{"Registry/EveryEntryStatesItsDefaultAndWhatStatesOtherwise", [] { namespace registry = mcpp::buildopt::registry; std::set ids; diff --git a/src/build/prepare/scan.cpp b/src/build/prepare/scan.cpp index bfaecf2cf..1e1e8f18c 100644 --- a/src/build/prepare/scan.cpp +++ b/src/build/prepare/scan.cpp @@ -72,11 +72,11 @@ static void build_private_fragments_as_units(PrepareState& state, const std::vector& packages) { namespace fs = std::filesystem; namespace source = mcpp::buildopt::source; - const bool asUnit = source::private_fragment_as_unit(*state.m, [](std::string_view bad) { + const auto policy = source::private_fragment_policy(*state.m, [](std::string_view bad) { mcpp::diag::warning("build", std::format( - "ignoring invalid private_fragment '{}' (expected \"unit\" or \"as-written\")", bad)); + "ignoring invalid private_fragment '{}' (expected \"unit\", \"conservative\" or \"as-written\")", bad)); }); - if (!asUnit) return; + if (policy == source::Fragment::AsWritten) return; auto& units = state.scan.graph.units; const auto count = units.size(); for (std::size_t i = 0; i < count; ++i) { @@ -88,7 +88,7 @@ static void build_private_fragments_as_units(PrepareState& state, text.assign(std::istreambuf_iterator(in), {}); } if (text.find("private") == std::string::npos) continue; - auto split = source::private_fragment(text, written.generic_string()); + auto split = source::private_fragment(text, written.generic_string(), policy == source::Fragment::Conservative); if (!split) continue; if (!*split) { const auto why = std::format("{}: the private module fragment is built as written ({})", From 07d5b91c7185db121f6d11d00969d8ca797f307e Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 26 Nov 2026 06:26:14 +0900 Subject: [PATCH 4/7] build: a failure at a step an optimization acted on says how to check that entry alone; the graph-shaping switches are part of the replayed request --- modules/buildopt/src/advice.cppm | 206 +++++++++++++++++++++++++ modules/buildopt/src/keep/keep.cppm | 8 + modules/buildopt/src/registry.cppm | 13 +- modules/buildopt/tests/test_advice.cpp | 152 ++++++++++++++++++ src/build/execute.cppm | 17 ++ src/build/ninja_backend.cppm | 55 +++++++ tests/e2e/build/basics.cpp | 146 ++++++++++++++++++ 7 files changed, 595 insertions(+), 2 deletions(-) diff --git a/modules/buildopt/src/advice.cppm b/modules/buildopt/src/advice.cppm index 99f6c3ac0..baf792c4a 100644 --- a/modules/buildopt/src/advice.cppm +++ b/modules/buildopt/src/advice.cppm @@ -15,10 +15,21 @@ // module the rebuild started at, when the importers that followed are many, // and once a build directory: the developer who chose the shape is not told // on every edit. +// +// A SECOND ADVICE: WHEN A BUILD FAILS AT A STEP AN ENTRY ACTED ON (SPEC-019 +// §9). Most projects are right with every entry on; the few that are not need +// to learn, from the failure itself, how to find out whether an entry is the +// cause, without it being said on every failure. It reads the step that +// failed, not the entries that ran: a source built as two units that failed +// (R1), a unit that imports a BMI kept with the lines of an earlier source +// that failed (R2), a link that failed where either is in the graph (R3). Any +// other failure says nothing (R4). The text is made of the register's own key, +// environment name and `check` value: there is no second spelling of a switch. export module mcpp.buildopt.advice; import std; +import mcpp.buildopt.registry; export namespace mcpp::buildopt::advice { @@ -53,6 +64,46 @@ std::string line(const Cascade& c); // yet; saying it is recorded there (`buildopt-advice.list`). bool first_time(const std::filesystem::path& dir, std::string_view module); +// WHAT THE PLAN HOLDS THAT A FAILURE READS (SPEC-019 §9), kept beside +// build.ninja (`buildopt-applied.tsv`) because the fast path, which has no +// plan, reports a failure as well. +struct Fragment { + std::string written; // the source as it is written + std::vector units; // the files it is built as +}; +struct Importer { + std::string source; // a unit that imports a module + std::vector imports; // the modules it imports +}; +struct Applied { + std::vector fragments; + std::vector importers; + std::string fragmentCheck; // the `private_fragment` value that checks, for this compiler +}; +inline constexpr std::string_view kAppliedFile = "buildopt-applied.tsv"; +// Written when it differs from what is there. +void write_applied(const std::filesystem::path& dir, const Applied& applied); +Applied read_applied(const std::filesystem::path& dir); + +// The step that failed: the first input of each failed step (the source, for a +// compile), and whether the linker said a link failed. +struct Failed { + std::vector sources; + bool linked = false; +}; +// The outputs each `FAILED:` line of ninja's output names. +std::vector> failed_outputs(std::string_view ninjaOutput); +// Whether the output says a link failed, in either linker's words. +bool linker_failed(std::string_view ninjaOutput); + +struct Tip { + std::string domain; + std::string text; +}; +// The tips for a failure. `kept` names the BMIs the build directory keeps with +// the lines of an earlier source (`bmi-kept.list`). +std::vector suspects(const Applied& applied, const std::vector& kept, const Failed& failed); + } // namespace mcpp::buildopt::advice namespace mcpp::buildopt::advice { @@ -109,6 +160,29 @@ std::string line(const Cascade& c) { c.source, c.module, c.importers, c.importers); } +namespace { + +// A source as a step names it: relative to its package's root, or absolute. +// The plan's units are absolute, so one names the other when it is the tail. +bool names(std::string_view planned, std::string_view stated) { + if (stated.empty()) return false; + if (planned == stated) return true; + return planned.size() > stated.size() && planned.ends_with(stated) + && planned[planned.size() - stated.size() - 1] == '/'; +} + +std::string bmi_stem_of(std::string module) { + std::ranges::replace(module, ':', '-'); + return module; +} + +// The invocation that checks one entry, and the statement that keeps it. +std::string how_to_check(const registry::Entry& e, std::string_view check) { + return std::format("{}={} mcpp build ({} = \"{}\" keeps it)", e.env, check, e.key, check); +} + +} // namespace + bool first_time(const std::filesystem::path& dir, std::string_view module) { const auto file = dir / "buildopt-advice.list"; { @@ -121,4 +195,136 @@ bool first_time(const std::filesystem::path& dir, std::string_view module) { return true; } +void write_applied(const std::filesystem::path& dir, const Applied& applied) { + std::string text; + 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); + for (auto const& u : f.units) text += "\t" + u; + text += "\n"; + } + for (auto const& i : applied.importers) { + text += std::format("imports\t{}", i.source); + for (auto const& m : i.imports) text += "\t" + m; + text += "\n"; + } + const auto file = dir / kAppliedFile; + std::string have; + { + std::ifstream in(file, std::ios::binary); + have.assign(std::istreambuf_iterator(in), {}); + } + if (have == text) return; + std::ofstream(file, std::ios::binary | std::ios::trunc) << text; +} + +Applied read_applied(const std::filesystem::path& dir) { + Applied a; + std::ifstream in(dir / kAppliedFile, std::ios::binary); + for (std::string line; std::getline(in, line);) { + std::vector cells; + for (std::size_t at = 0;;) { + const auto tab = line.find('\t', at); + cells.push_back(line.substr(at, tab == std::string::npos ? tab : tab - at)); + if (tab == std::string::npos) break; + at = tab + 1; + } + if (cells.size() < 2) continue; + if (cells[0] == "check") a.fragmentCheck = cells[1]; + 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()}}); + } + return a; +} + +std::vector> failed_outputs(std::string_view output) { + std::vector> steps; + while (!output.empty()) { + const auto end = output.find('\n'); + auto line = output.substr(0, end); + output = end == std::string_view::npos ? std::string_view{} : output.substr(end + 1); + while (!line.empty() && (line.front() == ' ' || line.front() == '\t')) line.remove_prefix(1); + if (!line.starts_with("FAILED:")) continue; + line.remove_prefix(7); + if (line.find("[code=") != std::string_view::npos) line = line.substr(line.find(']') + 1); + std::vector outputs; + for (std::size_t at = 0; at < line.size();) { + const auto next = line.find(' ', at); + const auto word = line.substr(at, next == std::string_view::npos ? next : next - at); + if (!word.empty()) outputs.emplace_back(word); + if (next == std::string_view::npos) break; + at = next + 1; + } + if (!outputs.empty()) steps.push_back(std::move(outputs)); + } + return steps; +} + +bool linker_failed(std::string_view output) { + for (std::string_view words : {"undefined reference to", "undefined symbol", "multiple definition of", + "duplicate symbol", "ld returned", "ld.lld: error", "lld-link: error"}) + if (output.find(words) != std::string_view::npos) return true; + return false; +} + +std::vector suspects(const Applied& applied, const std::vector& kept, const Failed& failed) { + std::vector tips; + const auto* fragment = registry::find(registry::kPrivateFragment); + const auto* cutoff = registry::find(registry::kGcmLocations); + const std::string_view off = registry::kStandardEnv; + + // R1: the step that failed compiled a source built as units of its own. + for (auto const& f : applied.fragments) { + const bool hit = std::ranges::any_of(f.units, [&](const std::string& unit) { + return std::ranges::any_of(failed.sources, [&](const std::string& s) { return names(unit, s); }); + }); + if (!hit || !fragment) continue; + tips.push_back({"buildopt/private-fragment", std::format( + "{} was built as two units (private-fragment), and one of them failed.\n" + " To check whether that is the cause: {}\n" + " If it builds, report the file; {}=off turns every optimization off for one run.", + f.written, how_to_check(*fragment, applied.fragmentCheck.empty() ? fragment->check : applied.fragmentCheck), + off)}); + break; + } + + // R2: the step that failed compiled a unit that imports a BMI kept with the + // lines of an earlier source. + std::vector keptStems; + for (auto const& k : kept) keptStems.push_back(std::filesystem::path(k).stem().string()); + std::set modules; + for (auto const& i : applied.importers) { + if (!std::ranges::any_of(failed.sources, [&](const std::string& s) { return names(i.source, s); })) continue; + for (auto const& m : i.imports) + if (std::ranges::contains(keptStems, bmi_stem_of(m))) modules.insert(m); + } + if (!modules.empty() && cutoff) { + std::string list; + std::size_t shown = 0; + for (auto const& m : modules) { + if (shown++ == 3) { list += ", ..."; break; } + list += (list.empty() ? "" : ", ") + m; + } + tips.push_back({"buildopt/bmi-cutoff", std::format( + "the BMI of module {} was kept although its source changed (bmi_cutoff), and a unit that imports it failed.\n" + " To check whether that is the cause: {}\n" + " If it builds, report the module; {}=off turns every optimization off for one run.", + list, how_to_check(*cutoff, cutoff->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) + tips.push_back({"buildopt/private-fragment", std::format( + "the link failed, and {} source(s) of this build are built as two units (private-fragment); the link cannot say whether that is the cause.\n" + " To check: {}", applied.fragments.size(), + how_to_check(*fragment, applied.fragmentCheck.empty() ? fragment->check : applied.fragmentCheck))}); + if (!kept.empty() && cutoff) + tips.push_back({"buildopt/bmi-cutoff", std::format( + "the link failed, and {} BMI(s) of this build are kept with the lines of an earlier source (bmi_cutoff); the link cannot say whether that is the cause.\n" + " To check: {}", kept.size(), how_to_check(*cutoff, cutoff->check))}); + } + return tips; +} + } // namespace mcpp::buildopt::advice diff --git a/modules/buildopt/src/keep/keep.cppm b/modules/buildopt/src/keep/keep.cppm index 95fec6b0a..d38f3090e 100644 --- a/modules/buildopt/src/keep/keep.cppm +++ b/modules/buildopt/src/keep/keep.cppm @@ -83,6 +83,10 @@ struct Run { }; Run run_end(const std::filesystem::path& dir); +// The BMIs the directory keeps with the lines of an earlier source, as the +// record names them (`bmi-kept.list`); what a failed step is asked against. +std::vector kept(const std::filesystem::path& dir); + // What a run says of its BMIs after it, one line each; empty when none changed. // `the BMI of c.gcm changed: its importers were compiled again`, and for a // kept one what was not done and the key that states otherwise. @@ -169,6 +173,10 @@ void run_begin(const std::filesystem::path& dir, std::optional ignoreLocat std::filesystem::remove(keptFile, ec); } +std::vector kept(const std::filesystem::path& dir) { + return read_lines(dir / kKeptFile); +} + std::vector summary(const Run& run) { const auto names = [](const std::vector& v) { std::string s; diff --git a/modules/buildopt/src/registry.cppm b/modules/buildopt/src/registry.cppm index 8dd73ea13..d4bff8eb2 100644 --- a/modules/buildopt/src/registry.cppm +++ b/modules/buildopt/src/registry.cppm @@ -60,6 +60,15 @@ struct Entry { std::string_view key; // the manifest key that states otherwise; empty: none std::string_view env; // the same for one invocation std::string_view values; // the key's values, the default first + // The value that checks the entry: stated for one invocation, it turns this + // entry off and no other, so a failure that is the entry's goes with it. + // Empty: the entry has no value of its own to check with, and + // `MCPP_BUILDOPT=off` is the one statement (the failure advice reads it). + std::string_view check; + // The same on a compiler where `check` is not available: GCC cannot build a + // private module fragment as written, so the check there is the rule before + // the entry's narrowing (`conservative`). Empty: `check` holds everywhere. + std::string_view checkGcc; }; inline constexpr std::string_view kKeepBmi = "keep-bmi"; @@ -79,14 +88,14 @@ inline constexpr std::array kEntries{{ Seam::Edge, Level::Exact, true, {}, {}, {}}, {kGcmLocations, "a GCC BMI whose line maps alone moved is kept; its importers name the earlier lines", Seam::Edge, Level::Conditional, true, "[profile.] bmi_cutoff", "MCPP_BMI_CUTOFF", - "ignore-locations | exact"}, + "ignore-locations | exact", "exact"}, {kScanPass, "the scans of a graph run as a pass of their own before its compiles", Seam::Graph, Level::Exact, true, {}, {}, {}}, {kSplitSchedule, "importers start when a BMI exists, not when its compiler exits (two-phase, detached code generation)", Seam::Graph, Level::Shape, false, "[build] bmi_schedule", "MCPP_BMI_SCHEDULE", "auto | on | off"}, {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 | as-written"}, + "unit | conservative | as-written", "as-written", "conservative"}, }}; constexpr const Entry* find(std::string_view id) { diff --git a/modules/buildopt/tests/test_advice.cpp b/modules/buildopt/tests/test_advice.cpp index 80a0107e0..32e249b2d 100644 --- a/modules/buildopt/tests/test_advice.cpp +++ b/modules/buildopt/tests/test_advice.cpp @@ -4,6 +4,7 @@ import std; import mcpplibs.mtest; import mcpp.buildopt.advice; +import mcpp.buildopt.registry; using namespace mcpplibs::mtest; namespace advice = mcpp::buildopt::advice; @@ -56,3 +57,154 @@ UTest said_once{"Advice/AnAdviceIsSaidOnceABuildDirectory", [] { expect(advice::first_time(d, "other")); std::filesystem::remove_all(d); }}; + +// WHAT A FAILED BUILD SAYS (SPEC-019 §7): the step that failed decides, and a +// failure the entries did not touch says nothing. +namespace { +bool says(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } + +advice::Applied applied() { + advice::Applied a; + a.fragments.push_back({"/p/src/c.cppm", {"/p/target/.buildopt/private-fragment/p/src/c.cppm", + "/p/target/.buildopt/private-fragment/p/src/c.private.cpp"}}); + a.importers.push_back({"/p/src/b.cppm", {"c", "std"}}); + a.importers.push_back({"/p/src/main.cpp", {"b"}}); + a.fragmentCheck = "as-written"; + return a; +} +} // namespace + +UTest tip_for_a_fragment{"Advice/ASourceBuiltAsTwoUnitsThatFailedNamesTheCheck", [] { + // The step names the unit relative to its package root, or whole. + for (auto const& source : {std::string("target/.buildopt/private-fragment/p/src/c.private.cpp"), + std::string("/p/target/.buildopt/private-fragment/p/src/c.cppm")}) { + const auto tips = advice::suspects(applied(), {}, {{source}, false}); + expect(fatal(tips.size() == 1u)) << source; + expect(eq(tips[0].domain, std::string("buildopt/private-fragment"))); + expect(says(tips[0].text, "/p/src/c.cppm was built as two units (private-fragment)")) << tips[0].text; + expect(says(tips[0].text, "MCPP_PRIVATE_FRAGMENT=as-written mcpp build")) << tips[0].text; + expect(says(tips[0].text, "[build] private_fragment = \"as-written\" keeps it")) << tips[0].text; + expect(says(tips[0].text, "MCPP_BUILDOPT=off")) << tips[0].text; + } + // GCC cannot build the fragment as written: its check is the old rule. + auto gcc = applied(); + gcc.fragmentCheck = "conservative"; + const auto tips = advice::suspects(gcc, {}, {{"/p/target/.buildopt/private-fragment/p/src/c.cppm"}, false}); + expect(fatal(tips.size() == 1u)); + expect(says(tips[0].text, "MCPP_PRIVATE_FRAGMENT=conservative mcpp build")) << tips[0].text; + // A source the sidecar does not know (a sidecar from another run) gives the register's own value. + advice::Applied bare; + bare.fragments = applied().fragments; + const auto fallback = advice::suspects(bare, {}, {{"/p/target/.buildopt/private-fragment/p/src/c.cppm"}, false}); + expect(fatal(fallback.size() == 1u)); + expect(says(fallback[0].text, "MCPP_PRIVATE_FRAGMENT=as-written")) << fallback[0].text; +}}; + +UTest tip_for_a_kept_bmi{"Advice/AUnitThatImportsAKeptBmiAndFailedNamesTheCheck", [] { + const auto tips = advice::suspects(applied(), {"c.gcm"}, {{"src/b.cppm"}, false}); + expect(fatal(tips.size() == 1u)); + expect(eq(tips[0].domain, std::string("buildopt/bmi-cutoff"))); + expect(says(tips[0].text, "the BMI of module c was kept")) << tips[0].text; + expect(says(tips[0].text, "MCPP_BMI_CUTOFF=exact mcpp build")) << tips[0].text; + expect(says(tips[0].text, "[profile.] bmi_cutoff = \"exact\" keeps it")) << tips[0].text; + // A kept BMI under a directory, and a partition's name. + auto a = applied(); + a.importers.push_back({"/p/src/d.cppm", {"c:part"}}); + expect(advice::suspects(a, {"pkg/c-part.gcm"}, {{"/p/src/d.cppm"}, false}).size() == 1u); +}}; + +UTest no_tip_for_other_failures{"Advice/AFailureTheEntriesDidNotTouchSaysNothing", [] { + // R4: an unrelated file's compile error. + expect(advice::suspects(applied(), {"c.gcm"}, {{"/p/src/unrelated.cpp"}, false}).empty()); + // A unit that imports no kept BMI (main imports b, whose BMI was replaced). + expect(advice::suspects(applied(), {"c.gcm"}, {{"/p/src/main.cpp"}, false}).empty()); + // A kept BMI of a module the failed unit does not import. + expect(advice::suspects(applied(), {"other.gcm"}, {{"/p/src/b.cppm"}, false}).empty()); + // Nothing was applied. + expect(advice::suspects({}, {}, {{"/p/src/b.cppm"}, false}).empty()); + // A step that names no source. + expect(advice::suspects(applied(), {"c.gcm"}, {{}, false}).empty()); + // A source whose name is only the tail of another's, not a path tail. + expect(advice::suspects(applied(), {}, {{"rc.cppm"}, false}).empty()); +}}; + +UTest tip_for_a_link{"Advice/ALinkThatFailedWithEitherEntryInTheGraphSaysSoWeakly", [] { + const auto tips = advice::suspects(applied(), {"c.gcm"}, {{}, true}); + expect(fatal(tips.size() == 2u)); + expect(says(tips[0].text, "the link failed")) << tips[0].text; + expect(says(tips[0].text, "cannot say whether that is the cause")) << tips[0].text; + expect(says(tips[1].text, "MCPP_BMI_CUTOFF=exact")) << tips[1].text; + // Neither in the graph, or a compile that failed: nothing. + expect(advice::suspects({}, {}, {{}, true}).empty()); + // A compile failure that a linker's words follow is the compile's. + expect(advice::suspects(applied(), {}, {{"/p/src/unrelated.cpp"}, false}).empty()); +}}; + +UTest register_check{"Advice/EveryDefaultOnEntryWithAKeyHasAValueThatChecksIt", [] { + namespace registry = mcpp::buildopt::registry; + auto values_of = [](std::string_view values) { + std::vector out; + for (std::size_t at = 0; at < values.size();) { + auto end = values.find('|', at); + std::string v(values.substr(at, end == std::string_view::npos ? end : end - at)); + while (!v.empty() && v.front() == ' ') v.erase(v.begin()); + while (!v.empty() && v.back() == ' ') v.pop_back(); + out.push_back(v); + if (end == std::string_view::npos) break; + at = end + 1; + } + return out; + }; + for (auto const& e : registry::kEntries) { + if (e.key.empty() || !e.byDefault) { + expect(e.check.empty() && e.checkGcc.empty()) << e.id; + continue; + } + const auto values = values_of(e.values); + expect(!e.check.empty()) << e.id; + expect(std::ranges::contains(values, std::string(e.check))) << e.id; + // The check is never the default: it must turn the entry off. + expect(values.front() != std::string(e.check)) << e.id; + if (!e.checkGcc.empty()) { + expect(std::ranges::contains(values, std::string(e.checkGcc))) << e.id; + expect(values.front() != std::string(e.checkGcc)) << e.id; + } + } + expect(registry::find(registry::kPrivateFragment)->checkGcc == "conservative"); +}}; + +UTest failed_steps{"Advice/FailedOutputsAreReadFromNinjasOutput", [] { + const std::string out = + "[3/9] c++ x\nFAILED: obj/a.o obj/a.o.d\nc++ -c a.cpp\nerror: x\nFAILED: [code=1] pcm/b.gcm\n" + " FAILED: link/app\nninja: build stopped\n"; + const auto steps = advice::failed_outputs(out); + expect(fatal(steps.size() == 3u)); + expect(steps[0].size() == 2u && steps[0][0] == "obj/a.o"); + expect(eq(steps[1][0], std::string("pcm/b.gcm"))); + expect(eq(steps[2][0], std::string("link/app"))); + expect(advice::failed_outputs("nothing failed\n").empty()); + expect(advice::linker_failed("ld: x.o: undefined reference to `f()'\n")); + expect(advice::linker_failed("ld.lld: error: undefined symbol: f()\n")); + expect(!advice::linker_failed("error: expected ';'\n")); +}}; + +UTest applied_roundtrip{"Advice/TheAppliedTableIsWrittenBesideTheGraphAndReadBack", [] { + const auto d = std::filesystem::temp_directory_path() / std::format("mcpp-applied-{}", std::random_device{}()); + std::filesystem::create_directories(d); + expect(advice::read_applied(d).fragments.empty()); + advice::write_applied(d, applied()); + const auto back = advice::read_applied(d); + expect(fatal(back.fragments.size() == 1u && back.importers.size() == 2u)); + expect(eq(back.fragmentCheck, std::string("as-written"))); + expect(eq(back.fragments[0].written, std::string("/p/src/c.cppm"))); + expect(back.fragments[0].units.size() == 2u); + expect(back.importers[0].imports.size() == 2u); + // Written again with the same content: the file is left alone. + const auto before = std::filesystem::last_write_time(d / advice::kAppliedFile); + advice::write_applied(d, applied()); + expect(std::filesystem::last_write_time(d / advice::kAppliedFile) == before); + // A graph without a fragment states no check. + advice::write_applied(d, {}); + expect(advice::read_applied(d).fragmentCheck.empty()); + std::filesystem::remove_all(d); +}}; diff --git a/src/build/execute.cppm b/src/build/execute.cppm index 8b37f5bed..e3499ed50 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -36,6 +36,7 @@ import mcpp.build.graph_shape; // #407: which mode wrote this build.ninja import mcpp.build.backend; import mcpp.build.ninja; import mcpp.buildopt.keep; +import mcpp.buildopt.registry; import mcpp.build.dirlock; // the build directory's lock (mcpp#839) import mcpp.build.graph_engine; // the engine a graph names (2026-11-12 §17) import mcpplibs.os.process; // the identity of this invocation (its protocol directory) @@ -425,6 +426,20 @@ std::string toolchain_request_identity() { if (auto s = mcpp::invocation::get("MCPP_PLATFORM")) overrides += std::format("MCPP_PLATFORM={};", *s); if (auto s = mcpp::invocation::get("MCPP_HOST_PLATFORM")) overrides += std::format("MCPP_HOST_PLATFORM={};", *s); + // THE REGISTER'S SWITCHES THAT SHAPE THE GRAPH (SPEC-019). A source built as + // other units (`MCPP_PRIVATE_FRAGMENT`), a graph of another shape + // (`MCPP_BMI_SCHEDULE`) and the standard build (`MCPP_BUILDOPT=off`) are + // decided when the graph is written; replayed, the graph is the one the + // other statement wrote, and the first build after a switch is not the one + // asked for. An edge entry acts at run time and is read there. Written only + // when stated: a request without one is the identity it was before. + std::string shape; + for (auto const& e : mcpp::buildopt::registry::kEntries) + if (e.seam != mcpp::buildopt::registry::Seam::Edge && !e.env.empty()) + if (auto v = mcpp::invocation::get(e.env)) shape += std::format("{}={};", e.env, *v); + if (auto v = mcpp::invocation::get(mcpp::buildopt::registry::kStandardEnv)) + shape += std::format("{}={};", mcpp::buildopt::registry::kStandardEnv, *v); + if (!shape.empty()) targets += std::format("shape={}", shape); if (overrides.empty() && targets.empty()) return std::format("cli={};default={}", cli, machineDefault); return std::format("cli={};default={};base={}{}", cli, machineDefault, overrides, targets); @@ -2787,6 +2802,8 @@ std::optional run_ninja_fast(const std::string& ninjaProgram, out, cAbiName, absent); !advice.empty()) 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); return 1; } // Verbose ninja output is narration, so it goes to the narration stream, diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 265dd7346..4d34b6355 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -49,6 +49,7 @@ import mcpp.provider.select; import mcpp.provider.roots; import mcpp.buildopt.keep; import mcpp.buildopt.advice; +import mcpp.buildopt.registry; import mcpp.modgraph.graph; import mcpplibs.os.platform; import mcpplibs.os.windows; @@ -364,6 +365,15 @@ void write_unit_cache_sidecar(const std::filesystem::path& outputDir, const std: const std::vector& roots); std::vector> read_unit_cache_sidecar(const std::filesystem::path& outputDir); +// SPEC-019 §9: what the entries of the register acted on, beside build.ninja +// (`buildopt-applied.tsv`), for the tip a failure gives. The plan writes it; +// the fast path, which has no plan, reads it as well. +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); + // #693 (M4): whether a Ninja reads build.ninja in the encoding mcpp writes it. // // mcpp writes the file in UTF-8: every path in it has a UTF-8 spelling @@ -1321,6 +1331,49 @@ void write_unit_cache_sidecar(const std::filesystem::path& outputDir, const std: std::ofstream(outputDir / kUnitCacheSidecar, std::ios::binary | std::ios::trunc) << text; } +void write_buildopt_sidecar(const BuildPlan& plan) { + namespace advice = mcpp::buildopt::advice; + advice::Applied applied; + std::map fragments; + for (auto const& cu : plan.compileUnits) { + const auto source = mcpplibs::os::fs::utf8(cu.source); + if (!cu.writtenAs.empty()) { + auto& f = fragments[mcpplibs::os::fs::utf8(cu.writtenAs)]; + f.written = mcpplibs::os::fs::utf8(cu.writtenAs); + f.units.push_back(source); + } + if (!cu.imports.empty() && !cu.servedFromCache) applied.importers.push_back({source, cu.imports}); + } + for (auto& [written, f] : fragments) applied.fragments.push_back(std::move(f)); + 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); +} + +void report_buildopt_failure(const std::filesystem::path& outputDir, 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 kept = mcpp::buildopt::keep::kept(outputDir); + if (applied.fragments.empty() && kept.empty()) return; + advice::Failed failed; + failed.linked = advice::linker_failed(ninjaOutput); + // The step that failed, by the source it reads (the step record). + if (const auto record = mcpp::build::progress::read_record(outputDir)) { + for (auto const& outputs : advice::failed_outputs(ninjaOutput)) { + for (auto const& o : outputs) { + const auto step = record->step.find(mcpp::build::progress::normalise(o)); + if (step == record->step.end()) continue; + if (const auto source = record->sources.find(step->second); source != record->sources.end()) + failed.sources.push_back(source->second); + break; + } + } + } + for (auto const& tip : advice::suspects(applied, kept, failed)) mcpp::diag::on_failure(tip.domain, tip.text); +} + std::vector> read_unit_cache_sidecar(const std::filesystem::path& outputDir) { std::ifstream f(outputDir / kUnitCacheSidecar, std::ios::binary); std::string dir, roots; @@ -4953,6 +5006,7 @@ std::expected NinjaBackend::build(const BuildPlan& 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_buildopt_sidecar(plan); write_graph_c_library_sidecar(plan.outputDir, plan.targetSide.cAbi); std::string placements; mcpp::build::progress::Attribution attribution; @@ -5667,6 +5721,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); BuildError failure{"build failed", plan.outputDir / plan.graphFile, std::move(diagnostics)}; failure.reported = reported; diff --git a/tests/e2e/build/basics.cpp b/tests/e2e/build/basics.cpp index 4a306aa74..0070270a6 100644 --- a/tests/e2e/build/basics.cpp +++ b/tests/e2e/build/basics.cpp @@ -13,6 +13,66 @@ namespace fs = std::filesystem; namespace { +// SPEC-019 §9: the tip of a failure at a source built as two units. `toolchain` is the arguments +// that choose the compiler; `check` is the value of `private_fragment` that checks the entry there +// (GCC cannot build a fragment as written, so its check is the rule before the conditions). +void fragment_tip(const std::vector& toolchain, std::string_view check, bool gcc) { + auto p = s::project::scaffold("tipfrag"); + const auto args = [&](std::vector a) { + a.insert(a.end(), toolchain.begin(), toolchain.end()); + return a; + }; + // A condition before the fragment: only the rule before the conditions refuses it. + const auto unit = [](std::string_view fragment) { + return std::format("export module c;\n#ifndef NEVER_DEFINED\nexport int c_val();\n#endif\nmodule :private;\n{}\n", fragment); + }; + p.write("src/c.cppm", unit("int c_val() { return 1; }")); + p.write("src/b.cppm", "export module b;\nimport c;\nexport inline int b_inl() { return c_val(); }\n"); + p.write("src/main.cpp", "import std;\nimport b;\nint main() { std::println(\"value {}\", b_inl()); }\n"); + auto r = p.mcpp(args({"build"})); + expect(fatal(e2e::succeeded(r))) << "A: " << s::text(r); + expect(s::lacks(s::text(r), "was built as two units")) << "A: a build that succeeded gave a tip: " << s::text(r); + + p.write("src/c.cppm", unit("int c_val() { return undeclared_name; }")); + r = p.mcpp(args({"build"})); + expect(fatal(!e2e::succeeded(r))) << "B: a fragment that does not compile built"; + const auto text = s::text(r); + expect(e2e::contains(text, "c.cppm was built as two units (private-fragment), and one of them failed")) << "B: the failure gives no tip: " << text; + expect(e2e::contains(text, std::format("MCPP_PRIVATE_FRAGMENT={} mcpp build", check))) << "B: the tip does not give the check: " << text; + expect(e2e::contains(text, std::format("[build] private_fragment = \"{}\" keeps it", check))) << "B: " << text; + expect(e2e::contains(text, "MCPP_BUILDOPT=off turns every optimization off for one run")) << "B: " << text; + r = p.mcpp(args({"build", "--quiet"})); + expect(s::lacks(s::text(r), "was built as two units")) << "C: --quiet gave a tip: " << s::text(r); + + // The invocation the tip gives turns that entry off, and nothing else: the units are the + // source as written (clang), or the source under the rule before the conditions (GCC, which + // cannot build a fragment as written and says so). + p.write("src/c.cppm", unit("int c_val() { return 1; }")); + r = p.mcpp(args({"build", "--verbose"}), s::options{.env = {{"MCPP_PRIVATE_FRAGMENT", std::string(check)}}}); + if (gcc) { + expect(e2e::contains(s::text(r), "this compiler does not build one as written")) << "D: " << s::text(r); + expect(e2e::contains(s::text(r), "built as written (line 2: a preprocessor directive")) << "D: " << s::text(r); + } else { + expect(fatal(e2e::succeeded(r))) << "D: " << s::text(r); + expect(s::lacks(s::text(r), "c.private")) << "D: the check left the fragment a unit of its own: " << s::text(r); + } + + // An error of a file the entry did not act on says nothing of it. + p.write("src/c.cppm", unit("int c_val() { return 1; }")); + p.write("src/extra.cpp", "int broken( { }\n"); + r = p.mcpp(args({"build"})); + expect(fatal(!e2e::succeeded(r))) << "E: " << s::text(r); + expect(s::lacks(s::text(r), "was built as two units") && s::lacks(s::text(r), "MCPP_PRIVATE_FRAGMENT")) << "E: an unrelated failure gave the tip: " << s::text(r); + p.remove("src/extra.cpp"); + + // A link says so weakly: it cannot say which unit. + p.write("src/c.cppm", "export module c;\nexport int c_val();\nexport int missing();\nmodule :private;\nint c_val() { return 1; }\n"); + p.write("src/b.cppm", "export module b;\nimport c;\nexport inline int b_inl() { return c_val() + missing(); }\n"); + r = p.mcpp(args({"build"})); + expect(fatal(!e2e::succeeded(r))) << "F: " << s::text(r); + expect(e2e::contains(s::text(r), "the link failed, and 1 source(s) of this build are built as two units (private-fragment)")) << "F: " << s::text(r); +} + bool failed(const e2e::outcome& r) { return r.started && r.status != 0; } // The first build.ninja of the project's target, outside the build program's tree. @@ -290,6 +350,92 @@ E2E basics{"basics", s::home_fixture, [] { expect(fatal(e2e::contains(s::text(r), "value 2"))) << s::text(r); }; + "1161 the purview before a fragment holds conditions, and not what changes its meaning"_test[s::llvm] = [] { + // SPEC-019 §5. A condition only decides which declarations exist, and the + // implementation unit receives them from the BMI: the fragment is a unit of its own and an + // edit of it compiles that unit alone. A macro does not reach that unit: the source is + // built as written, and says why. `conservative` is the rule before the conditions were let + // through, and a value that changes the units changes the first build after it. + auto p = s::project::scaffold("cond"); + const std::string tc = "llvm@" + s::llvm_version(); + const std::string condition = "#ifndef NEVER_DEFINED\nexport inline int c_inl() { return 10; }\n#endif"; + const auto unit = [](std::string_view before, int body) { + return std::format("export module c;\n{}\nexport int c_val();\nmodule :private;\nint c_val() {{ return {}; }}\n", before, body); + }; + p.write("src/c.cppm", unit(condition, 1)); + p.write("src/b.cppm", "export module b;\nimport c;\nexport inline int b_inl() { return c_inl() + c_val(); }\n"); + p.write("src/main.cpp", "import std;\nimport b;\nint main() { std::println(\"value {}\", b_inl()); }\n"); + auto r = p.mcpp({"run", "--verbose", "--toolchain", tc}); + expect(fatal(e2e::contains(s::text(r), "value 11"))) << "A: " << s::text(r); + expect(e2e::contains(s::text(r), "the private module fragment is a unit of its own")) << "A: a condition kept the fragment from being a unit: " << s::text(r); + p.write("src/c.cppm", unit(condition, 2)); + r = p.mcpp({"build", "--verbose", "--toolchain", tc}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(e2e::contains(s::text(r), "c.private"))) << "B: the fragment's unit was not compiled: " << s::text(r); + expect(s::lacks(s::text(r), "--output obj/b.m.o")) << "B: an edit of the fragment compiled an importer: " << s::text(r); + + p.write("src/c.cppm", unit("#define K 5\nexport inline int c_inl() { return K; }", 1)); + r = p.mcpp({"run", "--verbose", "--toolchain", tc}); + expect(fatal(e2e::contains(s::text(r), "value 6"))) << "C: " << s::text(r); + expect(e2e::contains(s::text(r), "built as written (line 2: a preprocessor directive")) << "C: a macro did not keep the source as written: " << s::text(r); + + p.write("src/c.cppm", unit(condition, 3)); + r = p.mcpp({"run", "--verbose", "--toolchain", tc}, s::options{.env = {{"MCPP_PRIVATE_FRAGMENT", "conservative"}}}); + expect(fatal(e2e::contains(s::text(r), "value 13"))) << "D: " << s::text(r); + expect(e2e::contains(s::text(r), "built as written (line 2: a preprocessor directive")) << "D: `conservative` let a condition through: " << s::text(r); + expect(s::lacks(s::text(r), "invalid private_fragment")) << "D: `conservative` is not a value: " << s::text(r); + r = p.mcpp({"run", "--verbose", "--toolchain", tc}); + expect(fatal(e2e::contains(s::text(r), "value 13"))) << "E: " << s::text(r); + expect(e2e::contains(s::text(r), "the private module fragment is a unit of its own")) << "E: the first build after the value changed kept the units of the other: " << s::text(r); + }; + + "1162 a failure at a source built as two units says how to check that entry alone"_test[s::llvm] = [] { + fragment_tip({"--toolchain", "llvm@" + s::llvm_version()}, "as-written", false); + }; + + "1163 a failure at a source built as two units says how to check that entry alone on GCC"_test[s::gcc] = [] { + fragment_tip({}, "conservative", true); + }; + + "1164 a unit that imports a BMI kept with earlier lines says how to check the cutoff"_test[s::gcc] = [] { + // SPEC-019 §9. A line inserted in `c` moves its line maps alone, and its BMI is kept; `b` + // imports it and fails in a later build. The tip names the module and the one invocation + // that checks the cutoff. Under `exact` the BMI is replaced, nothing is kept, and a failure + // of `b` says nothing of the cutoff. + auto p = s::project::scaffold("tipkept"); + const auto c = [](std::string_view line) { + return std::format("export module c;\nexport int c_val();\nexport inline int c_inl() {{ return 10; }}\n" + "int c_val() {{\n int x = 1;\n{} return x;\n}}\nint c_other() {{ return 7; }}\n", line); + }; + const auto b = [](std::string_view body) { + return std::format("export module b;\nimport c;\nexport inline int b_inl() {{ return {}; }}\n", body); + }; + p.write("src/c.cppm", c("")); + p.write("src/b.cppm", b("c_inl() + c_val()")); + p.write("src/main.cpp", "import std;\nimport b;\nint main() { std::println(\"value {}\", b_inl()); }\n"); + auto r = p.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + p.write("src/c.cppm", c(" // a line\n")); + r = p.mcpp({"build", "--verbose"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(fatal(e2e::contains(s::text(r), "c.gcm changed in locations only and is kept"))) << "the BMI was not kept: " << s::text(r); + p.write("src/b.cppm", b("undeclared_name")); + r = p.mcpp({"build"}); + expect(fatal(!e2e::succeeded(r))) << "A: a unit that does not compile built"; + expect(e2e::contains(s::text(r), "the BMI of module c was kept although its source changed (bmi_cutoff), and a unit that imports it failed")) << "A: " << s::text(r); + expect(e2e::contains(s::text(r), "MCPP_BMI_CUTOFF=exact mcpp build")) << "A: " << s::text(r); + expect(e2e::contains(s::text(r), "[profile.] bmi_cutoff = \"exact\" keeps it")) << "A: " << s::text(r); + + r = p.mcpp({"build"}, s::options{.env = {{"MCPP_BMI_CUTOFF", "exact"}}}); + expect(fatal(!e2e::succeeded(r))) << "B: " << s::text(r); + expect(s::lacks(s::text(r), "the BMI of module c was kept")) << "B: a tip names a BMI the exact cutoff replaced: " << s::text(r); + + p.write("src/b.cppm", b("c_inl() + c_val()")); + r = p.mcpp({"run"}); + expect(fatal(e2e::contains(s::text(r), "value 11"))) << "C: " << s::text(r); + expect(s::lacks(s::text(r), "tip:")) << "C: a build that succeeded gave a tip: " << s::text(r); + }; + "07 static library"_test[s::elf] = [] { // A `kind = "lib"` target is archived (cxx_archive) into a non-empty libmathlib.a of objects. auto p = s::project::scaffold("mathlib"); From cfba00573a9691f6a10f0b47b2a48e671fcf9304 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 26 Nov 2026 06:26:14 +0900 Subject: [PATCH 5/7] 2026.11.26.1: specs, usage chapters, README, CHANGELOG, version --- CHANGELOG.md | 42 ++++++++++++++++++++ docs/04-mcpp-toml.md | 2 +- docs/26-build-optimizations.md | 46 +++++++++++++++++++--- docs/specs/build-optimizations.md | 60 +++++++++++++++++++++++------ docs/specs/module-rebuilds.md | 13 +++++-- docs/zh/04-mcpp-toml.md | 2 +- docs/zh/26-build-optimizations.md | 43 ++++++++++++++++++--- mcpp.toml | 2 +- modules/buildopt/README.md | 4 +- modules/versioning/src/version.cppm | 2 +- 10 files changed, 185 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 088502fff..ec086971c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,48 @@ > Each `## []` section is that release's notes. Entries are written in English > from 2026.9.28.3 on; earlier entries remain as written. +## [2026.11.26.1] - 2026-11-26 + +### Changed + +- A private module fragment is still a unit of its own when the purview before it holds + conditions (`#if`, `#ifdef`, `#ifndef`, `#elif`, `#else`, `#endif`) or `#error` and + `#warning`: a condition only decides which declarations exist, and the implementation unit + receives them from the interface. Before, any directive refused. A directive that changes what + the fragment means (`#define`, `#undef`, `#include`, `#pragma`, `#line`, `_Pragma`), and a + condition still open at the module declaration or at the fragment, still leave the source as + written, and `--verbose` names the line (SPEC-019 §5). +- The text before a fragment is read as C++ tokens. A digit separator (`1'000`) no longer hides + the rest of its line, a raw string literal may run over lines and hold `module :private;`, a + `static` inside `extern "C" { … }` is a `static` at namespace scope, and a line continuation + between the module declaration and the fragment leaves the source as written. Each of these + only makes more sources built as written (SPEC-019 §5 items 4 and 8). +- `MCPP_BUILDOPT`, `MCPP_PRIVATE_FRAGMENT` and `MCPP_BMI_SCHEDULE` are part of the request a + recorded build is replayed for: the first build after one of them changes writes the graph + again. Before, a build with no edit replayed the graph the other value had written. + +### Added + +- `[build] private_fragment = "conservative"` (and `MCPP_PRIVATE_FRAGMENT=conservative`): the + fragment is a unit of its own, and any directive in the purview before it leaves the source as + written, as before conditions were let through. It is the way to check the entry on GCC, which + cannot build a fragment as written. +- A build that fails at a step an optimization acted on ends with a `tip:` that names the entry + and the one invocation that checks it: a source built as two units that failed, a unit that + imports a BMI kept with the lines of an earlier source that failed, a link that failed where + either is in the graph. A failure of another step says nothing; `--quiet` gives none. The + register states, for each entry that is on and has a key, the value that checks it + (`check`), and the text is made of it (SPEC-019 §9, docs/26). + +### Recorded + +- A reader for clang's `.pcm`, which would keep a BMI when only the function hashes, offsets and + locations differ, is not implemented. Measured with clang 20.1.7 to 23.1.6: the operand that + holds a function's hash is at an index that varies with the declaration and the version, and a + third of the edits change the width of that 32-bit value in the stream, which moves the bit + offsets and three offset tables. Without a model of the declaration records, a reader cannot + tell the field from an interface change (SPEC-019 §8, SPEC-018 §2.2). + ## [2026.11.24.1] - 2026-11-24 ### Fixed diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index c1c11fff9..f18f6b4e1 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -684,7 +684,7 @@ dependency_linkage = "static" # How dependencies arrive: static (default) | cache = "global" # Global dependency cache: global (default) | local | off (§2.10) jobs = "auto" # Concurrent compiles: a positive number, or "auto" (§ below) bmi_schedule = "auto" # Module-edge scheduling: auto (= off) | on | off (§ below) -private_fragment = "unit" # A private module fragment: unit (built as a unit of its own, default) | as-written (chapter 26) +private_fragment = "unit" # A private module fragment: unit (default) | conservative (a unit; any purview directive refuses) | as-written (chapter 26) ``` A file a word of `[build] ldflags` names by absolute path is an input of every diff --git a/docs/26-build-optimizations.md b/docs/26-build-optimizations.md index 84de0de9c..4629001ad 100644 --- a/docs/26-build-optimizations.md +++ b/docs/26-build-optimizations.md @@ -27,7 +27,7 @@ by default; the others are stated by a parameter. | `gcm-locations` | on | `[profile.] bmi_cutoff`, `MCPP_BMI_CUTOFF` | GCC: a BMI whose line maps alone moved is kept; importers name the earlier lines | | `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`, `MCPP_PRIVATE_FRAGMENT` | A private module fragment is built as a unit of its own | +| `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 | `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 @@ -68,10 +68,20 @@ links; an edit above it reaches the importers, as it must. - GCC does not implement `module :private;`. Built as a unit of its own, the file builds with GCC as well. - A fragment that reads what is local to the interface's translation unit — a macro - defined in the module's purview, an unnamed namespace, a `static` at namespace scope, - a using-directive at namespace scope — is built as written, and `--verbose` says which - line decided it. With a compiler that builds no fragment as written, that is a warning. + defined in the module's purview (`#define`, `#undef`, `#include`, `#pragma`, `#line`), an + unnamed namespace, a `static` at namespace scope (`extern "C" { … }` is namespace scope), a + using-directive at namespace scope, a line continuation between the module declaration and + the fragment — is built as written, and `--verbose` says which line decided it. With a + compiler that builds no fragment as written, that is a warning. +- A condition (`#if`, `#ifdef`, `#ifndef`, `#elif`, `#else`, `#endif`) and `#error` or + `#warning` before the fragment do not keep it from being a unit: a condition only decides + which declarations exist, and the implementation unit receives them from the interface. A + condition still open at the module declaration or at the fragment does. +- The text is read as C++ tokens: comments and the contents of string, character and raw + string literals are not code, and a digit separator (`1'000`) is part of a number. - `[build] private_fragment = "as-written"` hands the file to the compiler unchanged. + `"conservative"` builds the fragment as a unit of its own and refuses any directive in the + purview, as before conditions were let through; it is the check available on GCC. ## The notes of a build @@ -86,6 +96,32 @@ The note is given when the rebuild started at a module of one file with at least importing units, once a build directory. Beside it, a build that replaced or kept BMIs states which ([04](04-mcpp-toml.md), `bmi_cutoff`). +## Checking whether an optimization is the cause + +Every entry is on because most projects build the same with it and sooner. When a build +fails at a step an entry acted on, it ends with a `tip:` that names the entry and the one +invocation that checks it: + +``` +tip: src/c.cppm was built as two units (private-fragment), and one of them failed. + To check whether that is the cause: MCPP_PRIVATE_FRAGMENT=as-written mcpp build ([build] private_fragment = "as-written" keeps it) + If it builds, report the file; MCPP_BUILDOPT=off turns every optimization off for one run. +``` + +The tip is given for the step that failed, so a failure of another file says nothing. The +ladder is the same for every entry: + +1. Turn off the one entry for one invocation: `MCPP_PRIVATE_FRAGMENT=as-written mcpp build` + (`conservative` on GCC), `MCPP_BMI_CUTOFF=exact mcpp build` (it removes the BMIs kept with + earlier lines first, so the products are those of a build from nothing). +2. Turn off every entry: `MCPP_BUILDOPT=off mcpp build`. +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. + ## What the home's cache places (2026.11.21.1+) Beside the entries, the home's build cache (`build-cache/v1/`, [25](25-home-indices-and-store.md)) @@ -125,7 +161,7 @@ run for a minute is named once on a `Running` line, with the package and source ```toml [build] -private_fragment = "as-written" # "unit" (default) | "as-written" +private_fragment = "as-written" # "unit" (default) | "conservative" | "as-written" bmi_schedule = "on" # "auto" (default, = off) | "on" | "off" [profile.dev] diff --git a/docs/specs/build-optimizations.md b/docs/specs/build-optimizations.md index 71a18d899..b3cfc1588 100644 --- a/docs/specs/build-optimizations.md +++ b/docs/specs/build-optimizations.md @@ -3,12 +3,12 @@ | 项 | 值 | |---|---| | 规范编号 | SPEC-019 | -| 标题 | mcpp 在标准构建之外所做的事:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议 | -| 状态 | 评审中 v1.0 | -| 版本 | 1.0 | -| 最后修改 | 2026-11-17 | -| 对应实现 | mcpp >= 2026.11.17.2 | -| 相关设计文档 | `.agents/docs/2026-11-17-ninja-cascade-publish-supplement-design.md` §11 | +| 标题 | mcpp 在标准构建之外所做的事:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | +| 状态 | 评审中 v1.1 | +| 版本 | 1.1 | +| 最后修改 | 2026-11-26 | +| 对应实现 | mcpp >= 2026.11.17.2;§5 第 4、7、8 条与 §9 自 2026.11.26.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) | @@ -26,7 +26,8 @@ 1. mcpp 在标准构建之外所做的每一项**必须**是登记表(`mcpp.buildopt.registry`)的一个条目; 表外**禁止**有这样的行为。 -2. 条目**必须**说明:标识、作用的接缝、级别、默认是否开启、改变它的清单键与环境变量。 +2. 条目**必须**说明:标识、作用的接缝、级别、默认是否开启、改变它的清单键与环境变量。默认开启而有清单键的条目**必须**另说明 + `check`:只关闭这一项以做验证的取值(§9);编译器之间不同时,另说明 GCC 上的取值。 3. 包的 README **必须**以表格列出全部条目及其默认值与参数;测试保证二者一致。 | 条目 | 接缝 | 级别 | 默认 | 参数 | 作用 | @@ -37,7 +38,7 @@ | `gcm-locations` | 边 | 有条件 | 开 | `[profile.] bmi_cutoff`,`MCPP_BMI_CUTOFF` | GCC BMI 只有行映射移动时保留(SPEC-018 §3) | | `scan-pass` | 图 | 严格 | 开 | — | 图的扫描先于编译,作为单独的一遍执行 | | `split-schedule` | 图 | 形态 | 关 | `[build] bmi_schedule`,`MCPP_BMI_SCHEDULE` | BMI 存在时导入者即开始,不等编译器退出(SPEC-011) | -| `private-fragment` | 源码 | 源码 | 开 | `[build] private_fragment`,`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元(§5) | +| `private-fragment` | 源码 | 源码 | 开 | `[build] private_fragment`(`unit`、`conservative`、`as-written`),`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元(§5) | ## 2. 级别 @@ -99,9 +100,16 @@ int f() { return 1; } → module m; // 实现单元 编译数据库除两个单元之外**必须**有原文件的一项(接口单元的命令作用于原文件),供语言服务器 查询;按改动选择测试时,原文件的改动等同于由它构建的单元的改动。 4. 下列情况**必须**按原样构建,并说明所在行与原因: - - 片段之前、模块范围之内有预处理指令(片段可能使用的宏); - - 片段之前有未命名的命名空间,或命名空间作用域的 `static`; + - 片段之前、模块范围之内有改变片段含义的预处理指令:`#define`、`#undef`、`#include`、 + `#pragma`、`#line`,以及下面没有列出的指令,或 `_Pragma`、`__pragma`(宏与编译状态不随 BMI + 进入实现单元)。条件指令(`#if`、`#ifdef`、`#ifndef`、`#elif`、`#elifdef`、`#elifndef`、 + `#else`、`#endif`)与 `#error`、`#warning` 不在此列:条件只决定哪些声明存在,实现单元 + 经 BMI 取得声明; + - 在 `export module` 声明所在行或片段所在行,条件指令尚未闭合(两个单元不会闭合它); + - 片段之前有未命名的命名空间,或命名空间作用域的 `static`(`extern "C" { … }` 与 + `extern "C++" { … }` 是命名空间作用域); - 片段之前有命名空间作用域的 using 指令; + - 自模块声明至片段之间有行连接(行末的 `\`); - 该单元是分区,或片段之前读不到 `export module` 声明。 编译器不支持按原样构建私有片段时,该说明为警告;否则只在 `--verbose` 中给出。 @@ -109,6 +117,12 @@ int f() { return 1; } → module m; // 实现单元 编译的片段,其错误由编译器给出并指向原文件;`private_fragment = "as-written"` 按原样构建。 6. 取值按层次:`MCPP_PRIVATE_FRAGMENT`、`[build] private_fragment`、默认值。其他取值 **必须**给出警告并取默认值。 +7. 取值 `conservative` 仍把片段构建为独立单元,而第 4 条的预处理指令一项回到放宽之前的规则: + 片段之前的模块范围内出现任何预处理指令即按原样构建。它是只退回这一处放宽的办法,在不能 + 按原样构建片段的编译器(GCC)上,`as-written` 不是可用的验证办法时由它代替。 +8. 判定读文本的记号而不是行:注释与字符串、字符、原始字符串字面量的内容不是代码;数字分隔符 + (`1'000`)属于数字,不是字符字面量的开始;原始字符串可以跨行并含任何文本。第 4 条的 + 词法修正不设开关:它只使更多的源文件按原样构建。 ## 6. 构建后的建议 @@ -134,12 +148,36 @@ int f() { return 1; } → module m; // 实现单元 | 项 | 预期收益 | 未实现的原因 | |---|---|---| | 无标记地把单文件模块拆为接口与实现 | 编辑函数体不达导入者,无需写 `module :private;` | 需要语义分析(§7 第 3 条);gcc 上编辑函数体本不级联,收益主要在 clang | -| clang:导入者可观察的接口不变时保留 BMI | clang 上函数体与注释的编辑止于该模块 | 需要两版接口的语义差异;clang 接受源文件已变的旧 BMI,仅在一个三单元的例子上测得 | +| clang:导入者可观察的接口不变时保留 BMI | clang 上函数体与注释的编辑止于该模块 | 2026-11-26 的实测(clang 20.1.7 至 23.1.6):非 inline 函数的哈希在记录中的下标随声明而不同(同一版本的成员函数在 26、27、29),需要复刻序列化器的布局;32 位哈希随机,约三分之一的编辑改变其 VBR 宽度,之后的位偏移与三类偏移表(声明上下文的词法偏移、`TYPE_OFFSET`、`DECL_OFFSET`)随之移动;不屏蔽哈希则只覆盖最后一个声明之后的编辑。没有误屏蔽接口差异的保证,不实现 | | 按符号计算受一次改动影响的测试 | `mcpp test --since` 运行更少的测试 | 需要跨导入的引用;动态分派可能遗漏测试 | | 同一程序中一个库的两个版本各自改名 | 依赖链指定两个版本时可以构建 | 只对纯模块的包可行;头文件、C 库与宏不能改名;出现的频率没有测量 | +## 9. 失败时的提示 + +默认开启的条目在绝大多数工程上正确;少数工程遇到预料之外的失败时,构建**必须**说明怎样只关闭 +这一项来判断它是不是原因,且**禁止**在与它无关的失败与成功的构建上说。 + +1. 提示以 `tip:` 行给出,在命令的输出之后,不改变退出状态,`--quiet` 下不给出(`diag::on_failure`)。 +2. 提示从失败的**步骤**出发,不从"这次构建用过哪些条目"出发: + + | 规则 | 失败的步骤 | 强度 | + |---|---|---| + | R1 | 源文件是私有片段拆出的单元 | 点名原文件 | + | R2 | 编译一个单元,它导入了当前以此前的行号保留着的 BMI | 点名模块 | + | R3 | 链接,而图中有拆出的片段或保留着的 BMI | 说明无法归属到单元 | + | R4 | 其他任何步骤 | 不给出 | + +3. 失败的步骤取自 ninja 的 `FAILED:` 行与步骤记录;取不到时按 R4。测试程序的运行失败不给出提示。 +4. 文本由登记表行的清单键、环境变量与 `check` 组成:`MCPP_PRIVATE_FRAGMENT=as-written mcpp build` + (GCC 上为 `conservative`)、`MCPP_BMI_CUTOFF=exact mcpp build`;并写出 `MCPP_BUILDOPT=off` + 是下一级。两步之后失败依旧,原因不在这些条目之中。 +5. 构建图与此前的取值不同时,第一次构建**必须**按新的取值重新生成图:`MCPP_BUILDOPT`、 + `MCPP_PRIVATE_FRAGMENT`、`MCPP_BMI_SCHEDULE` 是快速路径所比较的请求的一部分。 +6. 提示所读的计划数据写在构建目录的 `buildopt-applied.tsv`,快速路径(没有计划)读同一个文件。 + ## 变更记录 | 版本 | 日期 | 变更 | |---|---|---| | 1.0 | 2026-11-17 | 首版(mcpp 2026.11.17.2):登记表、级别、接缝、总开关;私有模块片段作为独立单元;构建后的建议;语义提供者的边界;四项已记录、未实现 | +| 1.1 | 2026-11-26 | 私有片段的判定:条件指令与 `#error`、`#warning` 放行,条件须在声明与片段处闭合;词法修正(数字分隔符、原始字符串、`extern "C"`、行连接);取值 `conservative`;登记表的 `check`;新增 §9 失败时的提示;§8 记录 clang 读者的实测结论 | diff --git a/docs/specs/module-rebuilds.md b/docs/specs/module-rebuilds.md index 5a1e603e8..59175b343 100644 --- a/docs/specs/module-rebuilds.md +++ b/docs/specs/module-rebuilds.md @@ -4,9 +4,9 @@ |---|---| | 规范编号 | SPEC-018 | | 标题 | 一次编辑之后哪些单元重新编译:按 BMI 内容截断、`bmi_cutoff`、构建目录的记录 | -| 状态 | 评审中 v1.0 | -| 版本 | 1.0 | -| 最后修改 | 2026-11-17 | +| 状态 | 评审中 v1.1 | +| 版本 | 1.1 | +| 最后修改 | 2026-11-26 | | 对应实现 | mcpp >= 2026.11.17.2;§2.1 的时间戳在 UTC 下自 2026.8 起成立 | | 相关设计文档 | `.agents/docs/2026-11-17-ninja-cascade-publish-supplement-design.md` §3 | | 相关 issue | #946 | @@ -71,6 +71,12 @@ mcpp 不认识的格式按字节比较,结果只有"相同"与"变化"。 没有读者。BMI 不含时间戳;改变文件字节的编辑(包括注释)即改变 BMI,且没有可按段隔离位置的 结构。`bmi_cutoff` 对它无效。 +2026-11-26 对 clang 20.1.7、22.1.8、23.1.3、23.1.6 的测量(SPEC-019 §8):非 inline 函数体不在 +BMI 中,函数的 32 位 ODR 哈希仍在,并随函数体变化;该哈希在记录中的下标随声明的形式而不同 +(同一版本的 `DECL_CXX_METHOD` 为 26、27、29),且随版本移动;哈希随机,约三分之一的编辑改变 +其 VBR 宽度,使其后的位偏移与偏移表同时变化。可靠地屏蔽它们需要声明记录的布局模型, +没有这个模型不能保证不遮住接口的差异,因此 clang 的 BMI 仍按字节比较。 + ## 3. `bmi_cutoff` | 取值 | "仅位置"的 BMI | @@ -122,3 +128,4 @@ mcpp 不认识的格式按字节比较,结果只有"相同"与"变化"。 | 版本 | 日期 | 变更 | |---|---|---| | 1.0 | 2026-11-17 | 首版(mcpp 2026.11.17.2,mcpp#946):按 BMI 内容截断;GCC 的时间戳屏蔽到终止符,"仅位置"的判定与两条排除;`bmi_cutoff`;构建目录的三个文件与运行结束时的两行;`mcpp.buildopt.keep` 与格式读者的分工;保留与比较由执行器完成,各宿主相同;对象按字节保留;判定登记于 SPEC-019 | +| 1.1 | 2026-11-26 | §2.2 记录 clang 的 BMI 为何仍无读者(哈希下标随声明而异、VBR 宽度翻转与偏移表) | diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index 7692c595d..e296fef08 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -634,7 +634,7 @@ dependency_linkage = "static" # How dependencies arrive: static (default) | cache = "global" # Global dependency cache: global (default) | local | off (§2.10) jobs = "auto" # Concurrent compiles: a positive number, or "auto" (§ below) bmi_schedule = "auto" # Module-edge scheduling: auto (= off) | on | off (§ below) -private_fragment = "unit" # A private module fragment: unit (built as a unit of its own, default) | as-written (chapter 26) +private_fragment = "unit" # A private module fragment: unit (default) | conservative (a unit; any purview directive refuses) | as-written (chapter 26) ``` `[build] ldflags` 的词以绝对路径点名的文件是带有它的每次链接的输入:整个词(预构建的归档、目标文件)、选项的值 diff --git a/docs/zh/26-build-optimizations.md b/docs/zh/26-build-optimizations.md index 5e3b438ff..9e15c2b0c 100644 --- a/docs/zh/26-build-optimizations.md +++ b/docs/zh/26-build-optimizations.md @@ -23,7 +23,7 @@ profile 的各个键,见 [04 —— mcpp.toml](04-mcpp-toml.md);精确规则,见 | `gcm-locations` | 开 | `[profile.] bmi_cutoff`,`MCPP_BMI_CUTOFF` | GCC:只有行映射移动的 BMI 被保留,导入者给出此前的行号 | | `scan-pass` | 开 | — | 图的扫描先于编译,作为单独的一遍执行 | | `split-schedule` | 关 | `[build] bmi_schedule`,`MCPP_BMI_SCHEDULE` | BMI 存在时导入者即开始,不等编译器退出 | -| `private-fragment` | 开 | `[build] private_fragment`,`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元 | +| `private-fragment` | 开 | `[build] private_fragment`(`unit`、`conservative`、`as-written`),`MCPP_PRIVATE_FRAGMENT` | 私有模块片段构建为独立单元 | `MCPP_BUILDOPT=off mcpp build` 对一次调用给出标准构建:全部条目关闭。没有参数的条目产出的字节与 标准构建相同,因此没有可选之处,只由这一条语句关闭。 @@ -58,10 +58,18 @@ int area(int w, int h) { return w * h; } - 诊断、调试信息与 `__FILE__` 给出原文件。 - GCC 未实现 `module :private;`。构建为独立单元之后,该文件在 GCC 上同样可以构建。 -- 片段读取对接口的翻译单元局部的内容时——模块范围内定义的宏、未命名的命名空间、命名空间作用域 - 的 `static`、命名空间作用域的 using 指令——按原样构建,`--verbose` 给出起决定作用的行。编译器 - 不能按原样构建片段时,该说明是警告。 -- `[build] private_fragment = "as-written"` 把文件原样交给编译器。 +- 片段读取对接口的翻译单元局部的内容时——模块范围内定义的宏(`#define`、`#undef`、`#include`、 + `#pragma`、`#line`)、未命名的命名空间、命名空间作用域的 `static`(`extern "C" { … }` 是命名空间 + 作用域)、命名空间作用域的 using 指令、模块声明与片段之间的行连接——按原样构建,`--verbose` 给出 + 起决定作用的行。编译器不能按原样构建片段时,该说明是警告。 +- 片段之前的条件指令(`#if`、`#ifdef`、`#ifndef`、`#elif`、`#else`、`#endif`)与 `#error`、`#warning` + 不妨碍它成为独立单元:条件只决定哪些声明存在,实现单元从接口取得声明。条件在模块声明或片段处 + 尚未闭合则妨碍。 +- 文本按 C++ 的记号读取:注释与字符串、字符、原始字符串字面量的内容不是代码,数字分隔符(`1'000`) + 属于数字。 +- `[build] private_fragment = "as-written"` 把文件原样交给编译器。`"conservative"` 仍把片段构建为 + 独立单元,而片段之前的模块范围内出现任何预处理指令即按原样构建(条件放行之前的规则),这是 + GCC 上可用的检查办法。 ## 构建给出的说明 @@ -75,6 +83,29 @@ note hub.cppm is the whole of module hub, which 46 units import: its function b 重编译的起点是一个只有一个文件的模块、且导入它的单元不少于 5 个时给出这条说明,每个构建目录一次。 此外,替换或保留了 BMI 的构建说明是哪些([04](04-mcpp-toml.md),`bmi_cutoff`)。 +## 检查一项优化是不是原因 + +每个条目默认开启,因为大多数工程用它构建的结果相同而更快。构建在条目作用过的步骤上失败时, +末尾给出一行 `tip:`,点名条目与只检查它的一次调用: + +``` +tip: src/c.cppm was built as two units (private-fragment), and one of them failed. + To check whether that is the cause: MCPP_PRIVATE_FRAGMENT=as-written mcpp build ([build] private_fragment = "as-written" keeps it) + If it builds, report the file; MCPP_BUILDOPT=off turns every optimization off for one run. +``` + +提示针对失败的那一步,因此另一个文件的失败不给出。阶梯对每个条目相同: + +1. 对一次调用关闭这一个条目:`MCPP_PRIVATE_FRAGMENT=as-written mcpp build`(GCC 上为 + `conservative`)、`MCPP_BMI_CUTOFF=exact mcpp build`(先移除以较早行号保留的 BMI,产物与从空 + 目录的构建相同)。 +2. 关闭全部条目:`MCPP_BUILDOPT=off mcpp build`。 +3. 两步之后失败依旧,原因不在条目之中。失败随其中一步消失时,请连同文件名报告;上文的清单键 + 使该取值持久。 + +提示有三种:拆为两个单元的源文件失败;导入了以较早行号保留的 BMI 的单元失败;链接失败而图中有 +其中之一(链接说不出是哪个单元)。测试程序运行时的失败不给出提示。 + ## home 的缓存放置的内容(2026.11.21.1+) 在各条目之外,`[build] cache` 为 home 的(缺省)时,home 的构建缓存(`build-cache/v1/`,[25](25-home-indices-and-store.md)) @@ -103,7 +134,7 @@ note hub.cppm is the whole of module hub, which 46 units import: its function b ```toml [build] -private_fragment = "as-written" # "unit"(默认)| "as-written" +private_fragment = "as-written" # "unit"(默认)| "conservative" | "as-written" bmi_schedule = "on" # "auto"(默认,即 off)| "on" | "off" [profile.dev] diff --git a/mcpp.toml b/mcpp.toml index 458d90296..889e7490f 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,6 +1,6 @@ [package] name = "mcpp" -version = "2026.11.24.1" +version = "2026.11.26.1" description = "Modern C++ build & package management tool" license = "Apache-2.0" authors = ["mcpp-community"] diff --git a/modules/buildopt/README.md b/modules/buildopt/README.md index 915a24780..7b54121cd 100644 --- a/modules/buildopt/README.md +++ b/modules/buildopt/README.md @@ -22,7 +22,7 @@ by a parameter. | `gcm-locations` | edge | conditional | on | `[profile.] bmi_cutoff = "ignore-locations" \| "exact"`, `MCPP_BMI_CUTOFF` | A GCC BMI whose line maps alone moved is kept; its importers name the earlier lines | | `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" \| "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 | +| `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 | `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. @@ -56,6 +56,6 @@ A reader of another compiler's format is one more file under the part it belongs | Optimization | Expected benefit | Why not yet | |---|---|---| | A one-file module split into interface and implementation with no marker in the source | An edit of a function body reaches no importer, without the developer writing `module :private;` | Needs semantic analysis (which definitions are inline, templates, constexpr; which bodies read what is local to the interface). A semantic provider can supply it through the source seam | -| Clang: a BMI kept when the interface an importer can observe is unchanged | With clang, any edit of a body or a comment stops at the module | Needs a semantic difference of two versions of an interface; measured on one three-unit case only | +| Clang: a BMI kept when the interface an importer can observe is unchanged | With clang, any edit of a body or a comment stops at the module | Measured 2026-11-26 on clang 20.1.7 to 23.1.6: the hash of a non-inline function (the one field that moves with its body) sits at an operand that varies with the declaration (26, 27 and 29 for member functions of one version) and with the version; a third of the edits change the width of the 32-bit hash in the stream, which moves the bit offsets and three offset tables after it. Without a model of the declaration records a reader cannot tell that field from an interface change | | The tests a change affects, by symbol | `mcpp test --since` runs fewer tests | Needs references across imports; dynamic dispatch can hide a test | | Two versions of one library in one program, renamed apart | A dependency chain that names two versions builds | Possible for module-only packages; headers, C libraries and macros are not renamed. No measurement of how often it occurs | diff --git a/modules/versioning/src/version.cppm b/modules/versioning/src/version.cppm index c8a0973fd..b05b55474 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.24.1"; +inline constexpr std::string_view MCPP_VERSION = "2026.11.26.1"; } // namespace mcpp From ecae4ffddeb825951088127ca1bbbde6d34264f2 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 26 Nov 2026 06:32:37 +0900 Subject: [PATCH 6/7] build: the applied table spells a source as the step record does, with forward slashes --- src/build/ninja_backend.cppm | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 4d34b6355..1cf3878d2 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -1335,11 +1335,17 @@ void write_buildopt_sidecar(const BuildPlan& plan) { namespace advice = mcpp::buildopt::advice; advice::Applied applied; std::map fragments; + // As the step record spells a source: with forward slashes, whatever the host. + const auto spelled = [](const std::filesystem::path& p) { + auto s = mcpplibs::os::fs::utf8(p); + std::ranges::replace(s, '\\', '/'); + return s; + }; for (auto const& cu : plan.compileUnits) { - const auto source = mcpplibs::os::fs::utf8(cu.source); + const auto source = spelled(cu.source); if (!cu.writtenAs.empty()) { - auto& f = fragments[mcpplibs::os::fs::utf8(cu.writtenAs)]; - f.written = mcpplibs::os::fs::utf8(cu.writtenAs); + auto& f = fragments[spelled(cu.writtenAs)]; + f.written = spelled(cu.writtenAs); f.units.push_back(source); } if (!cu.imports.empty() && !cu.servedFromCache) applied.importers.push_back({source, cu.imports}); From ab4de80a43b4785f5ae4cc5fe7601cdc3f64eec3 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 26 Nov 2026 06:33:43 +0900 Subject: [PATCH 7/7] docs: the spec index states SPEC-018 and SPEC-019 at 1.1 --- docs/specs/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/specs/README.md b/docs/specs/README.md index 2017cfb1a..34da95247 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -47,8 +47,8 @@ | [SPEC-015](target-sets.md) | 目标集合与腿:集合的写法与展开,命令对多条腿的语义,串行规划与一起构建,测试归档,机器输出 | 评审中 v1.0 | 2026-10-30 | mcpp >= 2026.10.30.1 | | [SPEC-016](targets-and-providers.md) | 目标与提供者:行、提供者、选择规则、平台定义的行、C 环境与执行、报告、机器输出与锁 | 评审中 v1.9 | 2026-11-23 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.9 条款 mcpp >= 2026.11.23.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-018](module-rebuilds.md) | 模块的重编译:按 BMI 内容截断,GCC 的时间戳与行映射,`bmi_cutoff`,构建目录的记录 | 评审中 v1.0 | 2026-11-17 | mcpp >= 2026.11.17.2 | -| [SPEC-019](build-optimizations.md) | 构建优化:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议 | 评审中 v1.0 | 2026-11-17 | mcpp >= 2026.11.17.2 | +| [SPEC-018](module-rebuilds.md) | 模块的重编译:按 BMI 内容截断,GCC 的时间戳与行映射,`bmi_cutoff`,构建目录的记录 | 评审中 v1.1 | 2026-11-26 | mcpp >= 2026.11.17.2 | +| [SPEC-019](build-optimizations.md) | 构建优化:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | 评审中 v1.1 | 2026-11-26 | mcpp >= 2026.11.17.2;§5、§9 的新增自 2026.11.26.1 | ## 文档约定