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 index 74a7b0156..240c7c428 100644 --- 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 @@ -262,6 +262,15 @@ v3 的 R1 到 R4 与文本不变。变化:`conservative` 的描述,`check` 开关的"取值改变后第一次构建正确"需要它成立,因此一并修复:`toolchain_request_identity` 把这三个环境变量并入请求,未陈述时的标识与此前相同, 只有陈述时才附加。边的条目(`MCPP_BMI_CUTOFF`)在执行时读取,不并入。 +**发布后的更正(2026.11.27.1)。** 上述做法在 2026.11.26.1 中有一个缺口,由发布后的净室验证测出:`toolchain_request_identity` 属于构建的记录 +(`target/.build_cache`),记录只在构建成功时写下。带陈述的构建失败时,图已按陈述重写,记录仍是此前那次成功构建的;其后不带陈述的构建与记录相符, +快速路径重放了按陈述写的图。GCC 上提示所给的命令 `MCPP_PRIVATE_FRAGMENT=conservative mcpp build` 在片段之前有条件指令时必然失败 +(按原样构建,GCC 不支持),于是其后的 `mcpp build` 以 `module already declared` 失败,直到编辑源文件或清单。 + +更正:陈述并入图自身所记的请求(`request_tag`,`build.ninja` 首行的 `request=`),这是"A、B、A"问题已有的机制,所有快速路径在重放前比较它; +`toolchain_request_identity` 中的那一段删除,不留两处。未陈述时标签与此前相同。e2e 1162、1163 在核对之后增加一次不带陈述的构建, +单元测试 `GraphShape/TheRequestNamesAStatedSwitch` 固定哪些陈述改变标签、哪些不改变。原先的 e2e 1161 E 只覆盖了"带陈述的构建成功之后",没有覆盖失败之后。 + ## 8. 未决的测量 | 编号 | 问题 | 结论 | @@ -293,7 +302,7 @@ e2e:1161(条件放行、宏拒绝、`conservative`、取值改变后的第 | 正确性(B) | 条件内的 `#define` 是否生效不可知 | 只读文本,一律拒绝 | | 正确性(C) | 续行使物理行与逻辑行不同 | 模块声明与片段之间出现即按原样构建;GMF 中的宏续行不受影响 | | 开关 | GCC 上没有 `as-written` | `conservative`、`checkGcc` | -| 开关 | 取值改变后第一次构建(7.5) | 请求标识并入三个环境变量;e2e 1161 E | +| 开关 | 取值改变后第一次构建(7.5) | 图自身所记的请求并入三个环境变量(2026.11.27.1 起;此前在构建的记录里);e2e 1161 E,1162、1163 的核对之后一步 | | 提示 | 以"这次构建用过什么"为条件会在不相干的失败上出现 | 以失败的步骤为条件;e2e 的反例 | | 提示 | 失败的步骤取自输出格式 | 取不到按 R4,少说而不是多说;`progress` 已依赖同一格式 | | 提示 | 保留的记录在编译边结束时才写 | 7.3:并行失败的导入者不给 R2;只说已记录的事实 | diff --git a/.agents/docs/2026-11-27-stated-closure-single-reader-and-feature-designs.md b/.agents/docs/2026-11-27-stated-closure-single-reader-and-feature-designs.md new file mode 100644 index 000000000..5840856a9 --- /dev/null +++ b/.agents/docs/2026-11-27-stated-closure-single-reader-and-feature-designs.md @@ -0,0 +1,675 @@ +--- +subject: design +status: landed +--- + +# 陈述的闭包、单一读者与六项功能:十四项缺陷的收敛设计 + +**日期:** 2026-11-27 · **版本:** v3(已实施于 mcpp 2026.11.27.1;实施中的改动见 §13) · **基线:** mcpp 2026.11.26.1(`main` a5450eaf) · +**相关规范:** SPEC-002(目标侧)、SPEC-004(清单语义)、SPEC-012(面向人的输出)、SPEC-013(平台)、SPEC-014(打包) + +本文把 2026-11-27 仍开着的十四项缺陷与六项功能请求放在一起设计。它们分属运行期搜索、子进程环境、清单读写、扫描、 +缓存、路径与命令行七个子系统,但缺陷只有四个共同原因;六项功能请求各自落在一个已有机制上,不新增机制。 + +## 0. 结论 + +**四条规则。** + +- **规则一(陈述的闭包)。** 一次构建在链接期、加载期与子进程中看到的,是依赖图陈述的东西;环境中所有已安装内容的并集 + 只对陈述了自己环境的工程生效。`docs/23` 已为构建程序的 `PATH` 写下这条规则,本文把它用于另外两条通道。 +- **规则二(单一读者)。** 一件事实——清单里有哪些依赖项、一个源文件声明哪个模块、一个产物叫什么——只有一个读取或 + 命名的实现,其他位置调用它。 +- **规则三(知道即拒绝)。** 规划或链接已经掌握的矛盾,在那一步拒绝并给出补救,不留给编译器、加载器或运行期。 +- **规则四(身份与拼写、归属分开)。** 打开文件与启动程序使用给定的拼写;规范路径只用于比较与键。按内容寻址的条目, + 其归属是使用者的集合,不是写入者一人。 + +**缺陷(十四项)。** + +1. 宿主工具的存储条目包含它从自身目录加载的每个图内共享对象;现在只发布可执行文件一个(#535,§4.1)。 +2. 一条不变量:镜像的每个 `DT_NEEDED` 在加载期解析到的,是链接期为它读取的那个文件。找不到、被并集视图顶替、链接与 + 加载各取一份,是它被违反的三种形式,校验对三者同样拒绝。两侧的输入都已存在:链接的输入记录与校验的搜索闭包 + (#535、#537,§4.1)。 +3. mcpp 启动的三种子进程——构建程序、测试程序、`mcpp run` 的程序——的 `PATH` 由同一个函数组成:依赖图陈述的工具的 + 目录,工程陈述的环境的 `bin`,mcpp 启动时的 `PATH`,在每个宿主上相同。陈述的工具目录已为运行器查找按计划算出 + (#926,§4.2)。 +4. 环境的并集视图(库的 `subos/default/lib`、测试子进程的环境 `bin`)只对陈述了环境的工程进入搜索路径;对未陈述的工程, + 依赖并集才能满足的名字先以弃用项报告,再按弃用表的日期移除(§4.1、§4.2,决定 D1)。 +5. `mcpp add` 在基表已有点号键时写点号键;mcpp 的 TOML 读者报告重新打开点号键所建之表的表头(#964,§4.3)。 +6. 源文本的「代码文本」(去掉注释与字面量)只有一个实现;模块冲突检查与扫描器共用它(#963,§4.3)。 +7. 「一份清单的全部依赖项」只有一个枚举;加载、编辑与发布归一化共用它,`[feature-deps.*]` 因此不再被发布遗漏 + (#962,§4.3)。 +8. 依赖包的共享库以限定名命名,名字由对象目录已在使用的同一个规整函数给出(`libcompat_sdl3.so`);根包自己的产物保持 + 目标名(#975,§4.3)。 +9. 依赖图替换了 C 库而没有 C++ ABI 的供给者时,目标侧解析以已有的 `layer-requirement` 拒绝,给出两个补救(#898,§4.4)。 +10. 链接后的检查读出共享镜像的 `DF_STATIC_TLS` 与 TLS 段大小,超出该行的界限即报告最大的 TLS 符号(#907,§4.4)。 +11. 直接执行的产物以 `#!` 指名一个不存在的解释器时,执行之前给出原因与一行 `help:`(#621,§4.4)。 +12. 路径依赖与宿主工具的缓存条目记录每一棵使用它的源码树;一棵树被编辑只撤下自己的名字,名字为空才删除条目。两处 + 实现合为一个函数(#1025 第 1 项,§4.5)。 +13. home 的路径不再被规范化为物理路径;规范化只出现在比较与键中,由一项只减不增的检查守住(#1024,§4.6)。 +14. 两项原因未定的缺陷(#1008、#1015)先测量,不设计(§4.13)。 + +**功能(六项)。** + +15. 条件预处理块中的 `import` 不再被拒绝:该单元的导入取自编译器的依赖扫描,机制是已有的 `MCPP_SCANNER=p1689` 路径按 + 单元使用。头单元仍然拒绝(#1026,§4.7)。 +16. `exports` 中不含通配符的条目是精确名,必须有定义,否则链接失败;渲染方式与 `start` 相同,是行的数据(#982,§4.8)。 +17. `mcpp add --build` 把依赖写入 `[build-dependencies]`。一个包是不是构建插件,引擎已经从它的源文件得出(导入只存在于 + 构建程序中的模块),不为此新增清单键,也不按名字段推断;写错表的条目由已有的弃用项报告并给出这条命令 + (#993,§4.9)。 +18. `[profile.]` 接受 `dialect_cxxflags`,含义与 `[build] dialect_cxxflags` 相同;`cflags`、`cxxflags` 的作用域写进 + SPEC-004(#1025 第 2 项,§4.10)。 +19. 命令补全在 mcpplibs.cmdline 中实现为内建行为,mcpp 一侧是一次升级与若干回调(#794,§4.11)。 +20. feature 的 `description` 进入示例,并由一项测试核对三个来源一致(#1018,§4.12)。 + +不在本文之内:`mcpp doc`(#399,已标记 todo)、LLVM 的 ok 镜像(#880)、Clang 的反射行(#215)、上游缺陷登记册 +(#1027)、备忘类条目(#558、#973)。 + +第 10 节的十三项决定已按建议定下。第 12 节是定下之后的自审:它修改了其中两项建议本身(共享库名字的拼法、构建插件的 +陈述),并补上了六处 v1 没有写到的约束。 + +## 1. 来源与证据 + +| 项 | 来源 | 证据 | +|---|---|---| +| 宿主工具的共享依赖 | #535 | 读码确认(存储只发布一个文件);自 2026-08-30 起未重新复现 | +| 链接与加载不是同一份 | #537 | 2026-11-26 在 2026.11.26.1 上复现 | +| 运行层工具不在 `PATH` 上 | #926 | 读码确认(两处代码与报告一致);未重新运行四格矩阵 | +| `mcpp add` 写出非法 TOML | #964 | 2026-11-26 复现;读码确认写入路径 | +| 原始字符串中的模块声明 | #963 | 读码确认(按行匹配,无注释与字面量处理) | +| 发布遗漏 `[feature-deps.*]` | #962 | 读码确认(归一化只遍历三张表);「键以包自身名字开头」一条未读到原因 | +| 共享库重名 | #975 | 读码确认(共享输出只取目标名);未重新复现 | +| C++ ABI 无供给者 | #898 | 读码确认(无对应拒绝);未重新复现 | +| 共享镜像的静态 TLS | #907 | 未复现;产生它的运行时契约未确定(§9) | +| `#!` 解释器缺失 | #621 | 已有实现(PR #923),本地合入后 16 个单元用例通过,接线未端到端运行 | +| 共享条目被另一棵树的编辑删除 | #1025 第 1 项 | 读码确认两处实现;未重新运行报告中的脚本 | +| home 被规范化为物理路径 | #1024 | 2026-11-27 以符号链接的 home 在 Linux 上复现同一机制;Windows 沙箱部分未复现 | +| 路径依赖下 `std` 的 CRC 不符 | #1008 | 未复现,原因未定 | +| 无编辑的构建重编传递导入者 | #1015 | 未复现,原因未定 | +| 条件 `import` | #1026 | 2026-11-27 在 2026.11.26.1 上复现 | + +## 2. 实测与代码事实 + +### 2.1 运行期搜索路径 + +`mcpp.runtime.search`(`src/runtime/search.cppm`)是搜索顺序唯一的决定处。它给每个目录一个来源,顺序是不可变性递减: + +| 来源 | 含义 | 序 | +|---|---|---| +| `Payload` | 工具链载荷的目录,安装后不变 | 0 | +| `Package` | 包以 `[runtime]` 陈述的目录 | 1 | +| `Artifact` | 产物自己的目录(`$ORIGIN`) | 2 | +| `SubosFarm` | `/lib`:该环境中全部已安装内容的并集视图,任何一次安装都会改写 | 3 | +| `HostDefault` | 宿主加载器的缺省目录,仅当产物由宿主加载器运行 | 4 | + +- 并集视图在目标是本机时进入闭包(`runtime_search_closure`,`src/build/plan.cppm`),并作为 RPATH 的最后一项写进产物 + (`ldRuntimeFallback`,`src/build/flags.cppm`)。链接期同一个视图经 `--sysroot=` 生效。 +- 模块的注释写明它为何存在:只存在于环境中的库(`libGL`)曾经能链接而不能启动。它没有区分「工程陈述的环境」与 + 「机器上的缺省环境」。 +- 运行期闭包的校验(`src/build/runtime_validation.cppm`)把每个 `DT_NEEDED` 对着这份闭包解析,结果写入 + `.mcpp-runtime-verdicts.json` 并发布到 `resolution.json`。只在缺失时拒绝。 +- 链接已经记录它读取的文件:链接行带 `--dependency-file=$out.d`(`f.linkReport`,`src/build/flags.cppm`)。 +- 宿主工具的存储条目由一次 `stage_file(produced, ctx.binOut)` 发布(`src/build/prepare/features.cpp`),只有可执行文件。 + +### 2.2 子进程的 `PATH` + +| 子进程 | 现状 | 位置 | +|---|---|---| +| 构建程序 | 工程陈述了环境时,该环境的 `bin` 在前;未陈述时与 mcpp 启动时的 `PATH` 逐字节相同 | `src/build/build_program.cppm`;`docs/23` §2 | +| 测试程序 | 工具链所在环境的 `bin` 在前,不论工程是否陈述环境;Windows 上整段被编译掉 | `src/build/execute.cppm`(`sandboxBin`) | +| `mcpp run` 的程序 | 只设置运行期库路径(`compute_run_env`) | 同上 | + +依赖图陈述的工具所在的目录已经按计划算出:`ctx.xlingsDepBinDirs`(`src/build/prepare/plan.cpp`),含依赖构建出的程序 +(`rootTools`)、被覆盖的载荷与每个包的 `[xlings.workspace]` 条目;条目按 `toolPurpose` 取舍,运行层(`when = "run"`) +在会运行的动词下属于它。它现在只被运行器的查找读取。 + +`docs/23` §2 对构建程序写明了规则:把共享目录放在每个工程前面,会使一次构建看到的东西取决于这台机器上还装过什么; +陈述才使它出现。 + +### 2.3 同一事实的多个读者 + +| 事实 | 读者 | 差异 | +|---|---|---| +| 源文本中的代码 | `strip_noncode`(`src/modgraph/scanner.cppm`);片段拆分的读者(`modules/buildopt/src/source.cppm`);`declared_module_roots` 等四个按行匹配的函数(`modules/manifest/src/mangle.cppm`) | 前两者去掉注释与原始字符串;第三组不处理,注释中自述了这一限制 | +| 清单的依赖表 | 加载器(`modules/manifest/src/toml.cppm`);编辑器 `upsert_dependency_text`(同文件);发布归一化(`src/publish/normalize.cppm`) | 归一化只遍历 `dependencies`、`build-dependencies`、`dev-dependencies`;编辑器只认 `dependencies` 与 `dev-dependencies` | +| TOML 的表 | mcpp 的读者(`modules/libs/src/toml.cppm`);编辑器写出后用同一个读者复核 | 读者接受 TOML 1.0 禁止的重复定义,复核因此通过 | +| 库的文件名 | 静态库在 `obj/<拥有者>/` 下(#896 之后);共享库 `place(target_output(...))` 放在 `bin/` | 共享库的名字只取目标名 | +| 条目属于哪棵源码树 | `replace_tree_siblings`(`src/build/prepare/dependency_cache.cpp`);`tool_store::write_entry`(`modules/buildmcpp/src/tool_store.cppm`) | 同一规则写了两遍 | + +编辑器对非缺省命名空间总是写 `[<表>.]` 表头,代码注释称之为规范的命名空间子表;它不检查基表中是否已有 `.` 开头的 +点号键。 + +### 2.4 规划时已知而未拒绝 + +- 目标侧的报告为没有供给者的层打印「—」后继续;拒绝码中有 `layer-requirement`(包所要求的层没有被给出)与 + `layer-ordering`,没有覆盖「替换了 C 库而 C++ ABI 无人供给」。 +- C++ 运行时的契约按角色决定(`src/build/distribution.cppm`):共享库角色在 ELF 上的缺省是与工具链的共享运行时耦合, + 原因写在注释中。#907 的镜像没有 `libstdc++.so` 的 `DT_NEEDED`,说明那一行或那份清单给了共享库角色另一种契约; + 是哪一种未测定。 +- `start` 的要求已有渲染:`start_link_flags` 以 `--defsym` 把未定义的入口变成链接错误(`src/build/ninja_backend.cppm`)。 + `exports` 渲染为版本脚本、Mach-O 的导出列表或 PE 的 `.def`,条目是模式,不要求定义。 + +### 2.5 路径 + +`absolute_home`(`src/home.cppm`)以 `weakly_canonical` 处理 home。以 `MCPP_HOME=<符号链接>/home` 运行 `mcpp self env`, +home、xlings、配置与缓存的路径全部以物理路径打印(2026.11.26.1,Linux)。`src/` 与 `modules/*/src/` 的非测试代码中共有 +约九十处 `canonical(` 调用,其中 `src/build/` 四十处(含 `prepare/` 二十五处)、`src/toolchain/` 十一处、`src/pack/` 十处。 +`contains_path` 已经用 `std::filesystem::equivalent` 比较身份。 + +### 2.6 扫描 + +- 规划期的词法扫描在遇到条件块内的 `import` 时拒绝(`if_depth > 0`),遇到头单元时拒绝。 +- 扫描器自己的注释写明:它是这门语言的第二个读者,第一个是编译器,两者不一致时以编译器为准。 +- 规划期已有另一条扫描路径:`MCPP_SCANNER=p1689` 时 `scan_packages_p1689` 以编译器的依赖扫描代替词法扫描 + (`src/modgraph/p1689.cppm`,`src/build/prepare/scan.cpp`)。它是整次构建的开关。 +- 构建期每个单元的编译器扫描(`.ddi`)与 `scan_overrides` 的陈述逐次核对。 + +### 2.7 profile 的编译词 + +`state.profileCflags` 与 `state.profileCxxflags` 只追加给根与被选中的成员(`src/build/prepare/graph.cpp`,注释写明这是 +有意的)。`[build] dialect_cxxflags` 到达标准库模块的预编译、扫描与每个单元,但 `[profile.]` 不接受这个键。 +SPEC-004 §9 没有写出 profile 的 `cflags`、`cxxflags` 的作用域。 + +## 3. 概念与取舍 + +### 3.1 四条规则各自的来由 + +规则一来自 `docs/23`:它已经是构建程序 `PATH` 的规则,理由写在那里。并集视图本身不是缺陷——它是「环境是我的根」的 +运行期一半——缺陷在于它对从未陈述过环境的工程同样生效,而缺省环境为这台机器上的每个工程共享。#535 的「开发机通过、 +干净机器失败」、#537 的「链接一份、加载另一份」与 #926 的「Linux 上碰巧能找到」是这同一件事在三条通道上的表现。 + +规则二来自扫描器自己的注释与 #963、#962、#964、#975、#1025 第 1 项:每一项都是第二个实现与第一个不一致。 + +规则三是 `AGENTS.md` §2 的「做得更少不沉默」在时间上的一半:拒绝不仅要有原因与补救,还要发生在掌握事实的那一步。 + +规则四把两类混淆分开。路径的规范形式是身份,不是地址;内容摘要是身份,不是归属。 + +### 3.2 不采用的方案 + +| 方案 | 不采用的原因 | +|---|---| +| 为每个计划建一个只含陈述内容的目录,RPATH 与 `PATH` 指向它 | 陈述的库目录与工具目录已经是按计划算出的列表(`Package` 来源、`xlingsDepBinDirs`);再建目录是同一份事实的第二种表示,并且在 Windows 上需要链接或复制 | +| 宿主工具一律静态链接其依赖 | 依赖以何种形态被消费由消费者陈述(#519);引擎替工具改写它,会让同一个包在工具中与在程序中形态不同而无处陈述 | +| 在 `[build] ldflags` 中出现宿主目录时告警 | 判据落在拼写上而不是事实上;规则三要的比较(同一 soname 的两个文件)两侧输入都已存在 | +| 只在冲突时给共享库加限定名 | 产物的名字会随闭包中其他包而变,增加一个依赖就改名 | +| 让 `cxxflags` 到达图中每个单元 | 会把 `-Werror`、`-D` 之类的词送进索引中的第三方包,并使每个依赖按 profile 各编译一份;「整图的编译词」已有拼写 | +| 在词法扫描器中对条件求值 | 第三个不完整的预处理器实现;工具链内建宏只有编译器知道 | +| 为构建插件新增一个包级的陈述键 | 引擎已经从源文件得出这一事实(导入 `mcpp.core` 的包被记为构建插件),feature 的 `rule_module` 是它已有的陈述;再加一个键是同一事实的两种拼写。消费侧的 `host-module` 是边上的请求,不是包的性质 | +| 引擎按包名第二段是 `mplugin` 判定构建插件 | 把一个索引的命名约定写进引擎;该规则在提出时已有例外(冻结的旧名、`mcpp.plugins`、同目录的 `mcpp.platforms`),私有索引不必遵守 | +| 命令补全保留「生成各 shell 的完整脚本」作为可选后端 | 一个概念两套机制;每种 shell 一份命令行解析的副本 | +| 把 home 的规范化保留为一个开关 | 两种路径语义并存;给定拼写在每个宿主上都可用,规范形式只在比较时需要 | + +### 3.3 设计准则与本方案的对应 + +| 视角 | 准则 | 本方案中的体现 | +|---|---|---| +| 架构 | 机制在引擎,事实在数据 | 精确名的渲染、TLS 界限、库的前后缀都是行或包的数据;消息指名能力而不指名包 | +| 收敛 | 一个概念一种拼写,一个机制一处实现 | 不新增机制:搜索来源、链接输入记录、`xlingsDepBinDirs`、`MCPP_SCANNER=p1689`、`start_link_flags`、`dialect_cxxflags`、`layer-requirement`、弃用表都是已有的 | +| 封闭 | 宿主与环境只在数据或陈述允许处进入 | 并集视图只对陈述了环境的工程生效;缺省环境不再是每个工程的隐含输入 | +| 稳定 | 结果是陈述的函数,不是历史的函数 | 另一棵源码树的编辑、另一个工程的安装、home 的另一种拼写都不改变本次构建 | +| 兼容 | 已发布的键与行为经弃用表移除 | 四处行为变化各有弃用标识与日期(§6);不改名任何已发布的键 | +| 用户体验 | 拒绝给出原因与补救 | 六处新的拒绝或报告,每处一行 `help:`,补救是命令时写出完整命令 | +| 简洁 | 删除多于增加 | 删去两份重复的条目清理、四个按行匹配函数各自的缺陷、测试子进程的平台分支 | + +## 4. 设计 + +### 4.1 运行期库:不变量、发布、核对(#535、#537) + +**不变量。** 镜像的每个 `DT_NEEDED` 在加载期解析到的文件,就是链接期为它读取的那个文件。现有的校验只检查了它的一种 +违反形式(加载期找不到)。弃用表中已有同类的先例:`undeclared-cxx-runtime`——链接行上出现而没有包声明的 C++ 运行时, +2027.1 移除。本节把同一要求从 C++ 运行时推到每一个共享对象。 + +**发布。** 宿主工具是一个镜像,与其他镜像相同:它的存储条目是可执行文件,加上它的链接从子构建的 `bin/` 读取的每个图内 +共享对象(来自子构建计划的共享链接单元,与链接输入记录一致)。它们由同一个发布步骤放入条目,条目的有效性判断包含 +它们。工具的 RPATH 中已有 `$ORIGIN`,不需要新的搜索项。 + +**核对。** 校验为每个 `DT_NEEDED` 记录它解析到的文件及其来源;链接输入记录给出链接读取的共享对象。两侧按规范路径比较, +不同时再比较内容摘要,仍不同即拒绝,原因标记 `runtime-closure`。加载期找不到的既有拒绝取同一标记,它此前没有标记。 +比较的结果随校验的判定一起缓存,判定的指纹包含链接输入记录,没有变化的镜像不重新比较。消息的形状(包名为示意): + +``` +error: [runtime-closure] libgbm.so.1 is linked from one file and loaded from another + linked /usr/lib/x86_64-linux-gnu/libgbm.so.1 ([build] ldflags: -L/usr/lib/x86_64-linux-gnu) + loaded /registry/subos/default/lib/libgbm.so.1 (subos_farm) + help: declare the package that provides it instead of a host directory: [xlings.workspace] "xim:mesa" = "" +``` + +核对适用于每个带动态段的镜像:程序、共享库、测试、宿主工具。校验本来就跳过的交叉目标不在其内。它同时覆盖 #535 中被 +并集视图悄悄顶替的情形:图内包构建的共享对象在链接期来自 `bin/`,加载期若来自别处即是不一致。 + +**并集视图的范围。** 按规则一,`SubosFarm` 只在工程陈述了环境(`[xlings] subos`)时进入闭包与 RPATH;链接期的 +`--sysroot` 用同一条规则、同一个日期,否则会出现能链接而校验拒绝的中间状态。对未陈述的工程: + +- 陈述的库目录仍然在闭包中:`Payload`、`Package`(`[runtime]`)、`Artifact`,以及图中各包的 `[xlings.workspace]` 条目所 + 安装载荷的库目录——后者与 `xlingsDepBinDirs` 同源,按计划算出,来源记为 `Package`。 +- M1 若表明还需要这些载荷所声明依赖的闭包,该闭包取自提供者:存储回收已经按它计算引用集合,mcpp 经提供者的端口查询, + 不重算。 +- 只有并集视图能满足的 soname 由校验报告,补救是陈述该包,或以一行 `[xlings] subos = "default"` 显式陈述使用共享的缺省 + 环境——后者之后的行为与此前完全相同。 +- 过渡经弃用表:标识 `implicit-default-environment`,自实施版本起为未陈述工程中每个仅由并集视图满足的 soname 报告一次, + 移除月份不早于 2027.3,由 M12 的用量确定。 + +陈述了环境的工程行为不变:环境是它的陈述,并集是它自己的。 + +### 4.2 子进程的 `PATH`(#926) + +mcpp 启动三种子进程:构建程序、测试程序、`mcpp run` 的程序。它们的 `PATH` 由一个函数组成,三段依次是: + +1. 依赖图陈述的工具的目录(`xlingsDepBinDirs`); +2. 工程陈述的环境的 `bin`,仅当工程陈述了环境; +3. mcpp 启动时的 `PATH`。 + +- 测试与运行的程序经运行契约的环境(`run_contract_env`)得到它;快速路径随构建记录这份值,与契约中的其他变量相同。 +- 构建程序此前只有第 2、3 段。加入第 1 段之后,构建程序以裸名调用的工具若被依赖图陈述,取陈述的那一份。这是陈述的 + 含义,也是一处行为变化,记入 §6。 +- Windows 上不再有被编译掉的分支。llvm 在环境 `bin` 中登记的 `cl`、`link`、`lib`、`rc` 垫片不是陈述的工具,不在第 1 段 + (#726 保持修复)。该变量在 Windows 上不区分大小写,函数读写进程中既有的那个键。 +- 载荷的程序不在自身 `bin/` 下、而由索引以别名提供时(`[xlings.workspace] program =` 已能解析这种名字),第 1 段取别名 + 解析到的目录;`when = "run"` 的条目是否全部在列表中,与 #926 的两个包一起由 M2 核对。 +- 测试子进程现有的「环境 `bin` 在前」是第 2 段的无条件形式,改为有条件,经 `implicit-default-environment` 过渡。mcpp + 自己的测试所调用的 `ninja`、`patchelf` 在 mcpp 的清单中陈述为测试层的工具。 + +### 4.3 单一读者(#964、#963、#962、#975) + +**代码文本(#963)。** 「去掉注释与字面量之后的源文本」只有一个函数,取 `modules/buildopt/src/source.cppm` 的实现 +(它处理原始字符串、数字分隔符与续行),放在扫描器、buildopt 与 `mcpp.pm.mangle` 都能导入的最低一层包中。 +`strip_noncode` 与 `mangle.cppm` 的四个按行匹配函数改为在它的结果上匹配。`mangle.cppm` 注释中关于注释与字符串的 +限制说明随之删除。 + +**依赖项的枚举(#962)。** `modules/manifest` 提供一个枚举:给定清单,产出每个依赖项及其所在的表——`dependencies`、 +`build-dependencies`、`dev-dependencies`、每个 `feature-deps.`、每个 `target.<选择器>` 下的同名表。加载器的 +校验、`mcpp add` 与 `mcpp remove` 的编辑、发布归一化都经它遍历。归一化按依赖项的身份改写,不按 TOML 键的形状, +「键以包自身名字开头」的情形(`hanim.core`)因此与其他项同路径;它在归一化中的具体成因在实施时读出(§9)。 + +**依赖的写法(#964)。** 编辑器的规则:目标表中已有以 `.` 开头的点号键,或已有 `` 这个键时,新项写为该表下的 +点号键 `. = …`;已有 `[<表>.]` 表头时写进该节;两者都没有时写点号键。读者一侧,表头重新打开一个由 +点号键建立的表是 TOML 1.0 的错误;由于旧版 `mcpp add` 写出过这种文件,读者先以弃用项报告 +(`reopened-dotted-table`,`help:` 给出等价的点号键写法),编辑器在下一次编辑该表时改写为合法形式,到期后拒绝 +(决定 D4)。 + +**共享库的名字(#975)。** 依赖包的共享库文件名与 SONAME 取规整后的限定名。对象目录已经用 +`sanitize(qualified_package_name(…))` 区分包(`obj/compat_sdl3/`),共享库用同一个函数,得到 `libcompat_sdl3.so`、 +`libmcpplibs_mwrap_sdl3.so`;前后缀仍是行的数据。根包与被选中成员自己的产物保持目标名;目标陈述了 `soname` 时以陈述 +为准。两个包陈述了同一个 `soname` 时规划拒绝(`soname-collision`),指出两个包。静态库不变:它们已经在 +`obj/<拥有者>/` 下。这是文件名的变化,进入 CHANGELOG;mcpp 同时控制链接与搜索路径,链接与加载不受影响,打包的清单随 +名字变化。 + +### 4.4 知道即拒绝(#898、#907、#621) + +**C++ ABI 无供给者(#898)。** 目标侧解析在依赖解析之后进行一次。那时已知:`c-abi` 的供给者是否来自依赖图、`c++-abi` +有无供给者、计划是否编译 C++(任一 C++ 单元或标准库模块)。三者为「是、无、是」且清单没有陈述 `cxx_runtime` 时, +以 `layer-requirement` 拒绝,请求者是根包。消息的形状: + +``` +error: [layer-requirement] the graph supplies the C library (musl, openkal-musl@0.28.0) and no package supplies the C++ ABI + the host's C++ library is built against another C library + help: add a dependency that provides mcpp:c++-abi, or state [build] cxx_runtime = "host-coupled" +``` + +补救指名能力而不指名包:哪个包提供它是索引的事实,引擎不写包名,也不为一条消息遍历索引。 + +**共享镜像的静态 TLS(#907)。** 链接后的 ELF 检查(运行期校验所用的同一个读者)读出动态段的 `DF_STATIC_TLS` 与 +`PT_TLS` 的大小。共享库角色的镜像带有该标志且 TLS 段超过该行的界限时报告,列出最大的 TLS 符号及其所属对象;界限是 +C 库的数据,不是引擎的常数。带该标志的镜像在进程启动时随程序加载没有问题,失败只发生在 `dlopen` 时;链接时不知道 +镜像将如何被加载,因此缺省是经 `diag::degraded` 报告而不是拒绝;陈述了精确导出名的镜像(§4.8,由宿主按名字进入) +超界时拒绝,标记 `static-tls-image`。界限的取值在测定之后确定(§9)。产生该镜像的运行时契约若是某一行的 +缺省,修正那一行的数据是同一轮的工作。 + +**`#!` 的解释器(#621)。** 采用已有实现,改两处:补救行用 `help:`;命令写出本次构建所用的工具链,而不是占位符。 +`docs/20` 中「mcpp 尚未解释」的那句话随之改写。 + +### 4.5 缓存条目的归属(#1025 第 1 项) + +条目旁的 `source` 记录写入者一棵树。改为记录每一棵使用它的树: + +- 命中一个带树的条目时,把本树加入记录(已在其中则不写)。 +- 以新摘要写入条目时,在同包同树的其他摘要的条目中撤下本树;记录为空的条目删除。 +- 记录以替换写入(`write_replacing`),两个进程同时命中不丢失名字。 +- 这条规则只有一个函数,路径依赖的缓存与宿主工具的存储都调用它;它放在两者都依赖的包中(§7)。 +- 已删除的检出留下的名字不再被撤下,条目落到按最后使用时间的回收(`[cache] unused_days`),这是既有的兜底。 +- 记录是条目旁的新文件 `users`,每行一棵树。旧的 `source` 只读不写,读作第一棵树。原因是新旧版本的 mcpp 会共用一个 + home(自举版本与刚构建出的版本即是如此):旧版本在新条目中找不到它认识的 `source`,既不会删除新条目,也不会覆盖 + 新记录。旧版本写出的条目仍按旧规则被旧版本删除,这一点在旧版本退出使用之前不变。 + +`--cache local` 不把宿主工具移出共享存储:这是存储的性质(工具按内容与目标寻址,跨工程共享),写进 `docs/09`。 + +### 4.6 路径的拼写(#1024) + +- **规则。** 用户与环境给出的路径(`MCPP_HOME`、`MCPP_TOOLCHAIN`、参数、工作目录、`mcpp` 自己的位置)在打开文件与启动 + 程序时保持给定的拼写,只做绝对化与词法归一。规范路径只用于判断两个路径是否同一对象,以及需要与拼写无关的键。 +- **home。** `absolute_home` 改为 `absolute` 加 `lexically_normal`。`contains_path` 等比较已经使用 `equivalent`。 +- **其余约九十处。** 每一处归为「身份」或「地址」。身份的调用改经一个命名函数(放在 `mcpp.home` 或 `mcpplibs.os.fs` + 已有的路径工具旁),地址的调用去掉规范化。 +- **检查。** `.github/tools/check_path_identity.sh` 统计该命名函数之外的 `canonical(` 与 `weakly_canonical(`,逐文件 + 对照一份只减不增的基线,做法与 `check_waits.sh` 相同。 +- **键。** 以路径为输入的键(描述性计划的工作目录、条目的 `source` 记录)继续用给定拼写的词法归一形式:两种拼写得到 + 两个键,多一个缓存条目,不产生错误结果。 +- **比较失败时。** 规范化在受限环境中会失败(上级目录不可访问)。身份函数失败时退回词法比较,并经 `diag::degraded` + 报告一次,说明哪一项判断是在没有身份的情况下作出的。 +- **进程层。** 报告的第 3 节(以别名路径启动的工具仍报拒绝访问)指向进程层按规范路径启动镜像,属于 mcpplibs.os 与 + openkal-windows;在那里以替身环境测定后另行记录,不在 mcpp 中绕过。 + +### 4.7 条件 `import`(#1026) + +词法扫描在一个单元中遇到处于条件块内的 `import` 时不再拒绝,而是把该单元标记为「导入由编译器回答」: + +- 该单元的导入集合取自编译器的依赖扫描,传入该单元实际的编译词(含 `defines`、`dialect_cxxflags` 与目标的条件配置)。 +- 规划期已有的实现(`src/modgraph/p1689.cppm`)只构造 GCC 的命令;构建期的 dyndep 边已经为 GCC 与 Clang + (`clang-scan-deps`)构造同一种扫描。两处合为一个命令构造函数,规划期与构建期共用。 +- 工具链不提供依赖扫描的行保持拒绝,消息说明原因;各行的可用性由 M11 测定。 +- 模块声明仍由词法扫描读取;声明本身处于条件块内时,同样取编译器的结果。 +- 扫描结果随它读过的文件一起缓存:扫描写出的依赖文件列出该单元包含的头文件,条件可能取决于其中定义的宏,其中任何 + 一个变化都使结果失效。只按源文件与编译词缓存是不够的。 +- 不新增开关。作者对扫描结果的显式覆盖已有 `scan_overrides`,整次构建改用编译器扫描已有 `MCPP_SCANNER`。 +- 头单元仍然拒绝,消息不变;`scan_overrides` 与 `MCPP_SCANNER=p1689` 不变。 +- 构建期的 `.ddi` 核对对这些单元照常进行,规划期与构建期出自同一个读者。 + +代价是每个这样的单元在规划期多一次预处理。它只发生在含条件导入的单元上;一个工程有多少这样的单元,以 #421 中的 +工程为例是 17 个(共 322 个接口单元)。 + +### 4.8 宿主调用的名字(#982) + +`exports` 的条目分两种:含通配符的是模式,行为不变;不含通配符的是精确名,表示「宿主按这个名字进入镜像」,必须有定义。 + +- 渲染是行的数据,与 `start` 同一机制:ELF 上沿用 `start_link_flags` 的做法(未定义即链接错误);Web 行渲染为 + `-sEXPORTED_FUNCTIONS`,名字的前缀规则在该行的数据中;PE 与 Mach-O 各自的拼写在实施时测定(§9)。 +- 精确名是链接器层面的符号名。C++ 的名字由陈述者写出修饰后的形式,或以 `extern "C"` 导出。 +- Android 的 `JNI_OnLoad`、`ANativeActivity_onCreate` 由定义它们的入口包(`main = { from = … }` 所指的包)在自己的 + 目标上陈述;应用不重复陈述。一个名字在闭包中只被陈述一次,重复陈述相同的名字不是错误。 +- 这适用于每一个没有程序起点的镜像:Android、Web、Python 扩展(`PyInit_*`)、插件式共享库。 +- 兼容:现有清单中不匹配任何符号的精确名此前被无声忽略,此后是链接错误。经弃用表过渡(`unmatched-exact-export`), + 先报告后拒绝;只在部分目标上有定义的名字移到条件表 `[target.<选择器>…]` 下。 +- 到期之后的失败来自链接器。mcpp 以已有的「失败之后追加说明」的做法(协程限制的提示即是)补一行,指出该名字来自 + `exports`。 + +### 4.9 `mcpp add --build`(#993) + +引擎已经知道一个包是不是构建插件:它的单元导入只存在于构建程序中的模块(`mcpp.core`)时,规划把它记为构建插件,并在 +构建程序的配置下规划(`src/build/prepare/host_graph.cpp`);feature 的 `rule_module` 是同一事实已有的陈述。因此: + +- **不新增清单键或描述符键。**「这个库供构建程序使用」已经由源文件回答,再要包陈述一次是同一事实的两种拼写。消费侧的 + `host-module` 是一条边上的请求,不是包的性质,不借用它的名字。 +- **`mcpp add --build`。** 与 `--dev` 对称,写入 `[build-dependencies]`。编辑器的布尔 `dev` 换成表的枚举,与 §4.3 的 + 枚举同源。 +- **写错表的条目。** 构建插件被写进 `[dependencies]` 时,弃用表已有 `host-module-in-dependencies`(2027.1 移除):现在 + 按构建依赖读取并告警,到期拒绝。它的补救行改为写出完整的命令:`mcpp remove <包>`,然后 `mcpp add --build <包>`。 +- **`mcpp add` 不猜。** 它只有描述符,没有源文件;不带 `--build` 时写入 `[dependencies]`,由上一条在第一次规划时指出。 +- **命名约定。** `.mplugin.` 留在索引中,是给人读的约定,由索引自己的检查维护。引擎不读名字。 + +### 4.10 profile 的整图编译词(#1025 第 2 项) + +- `[profile.]` 接受 `dialect_cxxflags`,含义、到达范围与 `[build] dialect_cxxflags` 相同(标准库模块的预编译、 + 扫描、每个单元),在 `[build]` 的同名键之后追加。工作空间层的 profile 同样接受。 +- SPEC-004 §9 增加一条:profile 的 `cflags`、`cxxflags` 是根位置的键,到达根包与被选中成员的单元;`opt`、`debug`、 + `ndebug`、`dialect_cxxflags` 与 `ldflags` 到达整张图。`docs/04` §2.9 写明同一事实。 +- `-p <成员>` 与 `--workspace` 下同一个库的编译词不同,是这条规则的直接结果,文档以一个例子说明;需要整图一致的词 + 写进 `dialect_cxxflags`。 +- C 单元没有对应的键,本设计不增加。整图一致之所以是 C++ 单元的要求,是因为 BMI 与标准库模块必须以相同的方言编译; + C 单元之间没有这种耦合,包的 C 编译词是包自己的。SPEC-004 写明这一点。 +- 使用新键的清单陈述 mcpp 的下限:旧版本对未知的 profile 键只告警并忽略,没有下限的清单会被缺一半配置地构建。 + +### 4.11 命令补全(#794,mcpplibs/cmdline#9) + +设计在 cmdline 中,mcpp 是使用者。cmdline 一侧(六个讨论点已定): + +| 层 | 内容 | +|---|---| +| 事实 | 选项与位置参数上的可选值集合、文件或目录提示、候选回调;命令的隐藏标记;位置参数的可重复标记 | +| 引擎 | 一个纯函数:命令树与光标前的词 → 候选与一个指令。它与解析共用同一个「这个词是什么」的归类函数 | +| 入口 | 一个隐藏命令,结果按固定文本协议打印;走 `--help`、`--version` 的路径,返回「已处理、不是错误」 | +| 适配器 | bash、zsh、fish、PowerShell 各一段静态脚本,只依赖程序名与入口名 | + +- 开启是一个函数:`app.completion()`;带参数的形式决定是否自动加可见的 `completions ` 子命令与入口的名字。 + 缺省关闭,升级不改变行为。 +- 现有导出的签名全部保留;`App::completions(Shell)` 与 `generate_completions` 的输出从完整脚本变为适配器;三个生成器 + 分区删除。 +- 可选值集合同时用于解析校验、帮助文字与候选。 +- 入口不联网、不写文件;回调的行为由应用负责。 + +mcpp 一侧:升级 cmdline;`app.completion({.command = ""})`,脚本由 `mcpp self completion [shell]` 写到 +`/config/shell/`;为包名(本地索引缓存)、目标、工具链、profile、成员提供回调;独立安装器修改 shell 配置是显式 +选择;三个以描述中的「(internal)」标识的命令改用隐藏标记。入口在解析处返回,不应触发 home 的初始化,由 §8 的用例断言。 +入口的启动耗时设预算并在 CI 中测量(§9)。 + +### 4.12 feature 的描述(#1018) + +字段、`mcpp search` 与 `mcpp why features` 的机器输出已随 #992 实现,`docs/06` 已有说明。余下两项: +`examples/11-features` 的 feature 写出 `description`;一项测试核对同一个包的描述在清单、内联描述符与已安装载荷三个 +来源下相同。展示属于 mcpp-ide。 + +### 4.13 先测量的两项(#1008、#1015) + +两项的原因未定,不在本文中设计。各自的测量: + +- **#1008。** 在报告的构造下(mcpplibs.os 以路径依赖替代版本依赖),取出失败单元与其导入者的编译命令,比较两者得到 + `std` BMI 的路径与编译词;同时记录路径依赖的包是否收到了根位置的编译词(§2.7)。若两个单元对着两份 `std` BMI 编译, + 它与 §4.10 所写的作用域是同一件事,在那里解决。 +- **#1015。** 在 2026.11.26.1 上以 `--verbose` 与构建记录重复报告中的四步,确认是否仍然出现,并取出第二次构建中 + `main` 被判定为过期的 ninja 解释(`-d explain`)。 + +## 5. 跨平台 + +| 项 | Linux | macOS | Windows | 其他行 | +|---|---|---|---|---| +| 链接与加载的核对 | ELF:`DT_NEEDED` 与链接输入记录 | Mach-O:安装名与 `LC_RPATH`,同一比较 | PE 没有 RPATH,运行时 DLL 以部署解决;两侧各是什么由 M14 测定 | 静态镜像没有动态段,不适用 | +| 子进程 `PATH` | 相同代码 | 相同代码 | 相同代码,不含环境 `bin` 的垫片 | 由运行器启动的程序经运行契约的环境得到同一份值 | +| 共享库的限定名 | `libcompat_sdl3.so` | `libcompat_sdl3.dylib`,安装名随之 | `compat_sdl3.dll` 与其导入库 | Android 包内的名字同 Linux;没有共享库的行不适用 | +| 条件导入的扫描 | GCC 内建 | `clang-scan-deps` | `clang-scan-deps`;MSVC ABI 的行由 M11 测定 | 没有扫描器的行保持拒绝 | +| 精确名 | `--defsym` 的做法 | 链接器的未定义强制 | `/INCLUDE:` | Web:`-sEXPORTED_FUNCTIONS` | +| 路径拼写 | 符号链接的 home | 同 Linux | 盘符别名、`subst`、映射的网络盘、目录联接 | 不适用 | +| 静态 TLS | glibc 的界限来自数据 | 不适用(无此标志) | 不适用 | musl 与 openkal 的行各有数据或标记为不适用 | + +## 6. 兼容性 + +行为变化与各自的过渡: + +| 变化 | 影响 | 过渡 | +|---|---|---| +| 并集视图只对陈述了环境的工程生效(库、链接期的 `--sysroot`、测试子进程的 `PATH`) | 未陈述环境而依赖缺省环境中内容的工程 | 弃用表 `implicit-default-environment`:先逐项报告,到期移除;一行 `[xlings] subos = "default"` 保持原行为 | +| 构建程序的 `PATH` 前加入陈述的工具目录 | 以裸名调用工具、而该工具又被依赖图陈述的构建程序,此后取陈述的那一份 | 无过渡:陈述即是意图 | +| 条目的使用者记录改用新文件 `users` | 新旧版本共用的 home | 旧的 `source` 只读不写;旧版本不删除新条目 | +| `host-module-in-dependencies` 的补救行改为完整命令 | 无 | 已有的弃用项,日期不变(2027.1) | +| `[profile.] dialect_cxxflags` | 旧版本忽略该键 | 使用它的清单陈述 mcpp 的下限 | +| 读者报告重新打开的点号键表 | 旧版 `mcpp add` 写出的清单 | 弃用表 `reopened-dotted-table`:先报告,编辑器在下次编辑时改写,到期拒绝 | +| 三个新弃用项的移除月份 | — | 不早于 2027.3(弃用版本之后至少两个整月),由 M12 的用量确定 | +| 依赖包的共享库改用限定名 | 以 `--linkage shared` 打包的产物清单;按文件名引用依赖共享库的脚本 | CHANGELOG;陈述了 `soname` 的目标不变 | +| 精确的 `exports` 名必须有定义 | 列出不存在的精确名的清单 | 弃用表 `unmatched-exact-export`:先报告,到期为链接错误 | +| 链接与加载不一致即拒绝 | 以宿主 `-L` 链接而由环境满足加载的工程(#537 的构造) | 无过渡:这是此前未被发现的错误产物 | +| C++ ABI 无供给者即拒绝 | 此前在标准库模块预编译处失败的构造 | 无过渡:失败提前,并带补救 | +| home 不再规范化 | 输出中的路径与给定拼写一致;以路径为键的条目多出一个拼写 | 无过渡:旧条目按最后使用时间回收 | +| cmdline 的 `completions(Shell)` 输出改变 | 已安装旧脚本的用户继续可用;新脚本是适配器 | cmdline 的版本说明 | + +不变的:没有已发布的清单键被改名或移除;`scan_overrides`、`MCPP_SCANNER`、`[xlings] subos`、`host-module` 的现有含义 +不变;陈述了环境的工程的搜索路径不变。 + +## 7. 改动面 + +| 位置 | 改动 | +|---|---| +| `src/runtime/search.cppm`、`src/build/plan.cppm`、`src/build/flags.cppm` | 并集视图的进入条件;陈述载荷的库目录计入 `Package` | +| `src/build/runtime_validation.cppm`、`src/runtime/elf.cppm` | 每个 soname 的解析文件与来源;与链接输入记录的比较;`DF_STATIC_TLS` 与 TLS 段 | +| `src/build/prepare/features.cpp`、`modules/buildmcpp/src/tool_store.cppm` | 工具条目发布其共享对象;条目归属改为集合并调用共用函数 | +| `src/build/prepare/dependency_cache.cpp` | 删除 `replace_tree_siblings`,调用共用函数;命中时登记本树 | +| `src/build/execute.cppm` | 测试与运行的子进程环境由一段代码组成;删除平台分支;`#!` 的提示 | +| `modules/manifest/src/toml.cppm`、`src/publish/normalize.cppm`、`src/pm/commands.cppm` | 依赖项的枚举;编辑器的写法规则与表的枚举;归一化经枚举遍历;`mcpp add --build` | +| `modules/libs/src/toml.cppm` | 重新打开点号键表的报告 | +| `modules/buildopt/src/source.cppm`、`src/modgraph/scanner.cppm`、`modules/manifest/src/mangle.cppm` | 代码文本的单一实现及其两个调用方 | +| `src/build/plan.cppm`(`target_output`) | 依赖包共享库的限定名;重复 `soname` 的拒绝 | +| `src/build/prepare/target_side.cpp` | C++ ABI 无供给者的拒绝 | +| `src/home.cppm` 与约九十处调用 | 给定拼写;身份函数;`check_path_identity.sh` 与基线 | +| `src/modgraph/scanner.cppm`、`src/modgraph/p1689.cppm`、`src/build/prepare/scan.cpp` | 条件导入的单元取编译器的扫描;结果的缓存 | +| `src/build/ninja_backend.cppm`、`modules/toolchain-model/data/builtin.toml` | 精确名的渲染及各行的数据 | +| `modules/manifest/src/toml.cppm`、`modules/manifest/src/compat/registry.cppm` | profile 的 `dialect_cxxflags`;三个弃用项;`host-module-in-dependencies` 的补救行 | +| `modules/libs`(新增三个模块) | 代码文本;条目的使用者记录,连同自 `mcpp.home.files` 下沉的原子替换原语;路径身份。`src/` 中只增加调用 | +| `src/build/refusal.cppm`、`docs/50`(中英文) | 原因标记 `runtime-closure`、`soname-collision`、`static-tls-image` | +| `src/modgraph/p1689.cppm`、`src/build/ninja_backend.cppm` | 依赖扫描的命令只构造一处,规划期与构建期共用 | +| `src/cli.cppm` | cmdline 升级;补全开关与回调;`self completion`;隐藏命令 | +| `docs/`(中英文)、`docs/specs/` | SPEC-004 §9(profile 作用域、`exports` 精确名、依赖写法)、SPEC-002(层的拒绝)、`docs/04`、`05`、`06`、`09`、`20`、`22`、`23`、`51`(弃用表三项)、CHANGELOG | +| mcpplibs/cmdline | 补全的四层;删除三个生成器分区;文档与示例 | +| mcpplibs/mcpp-index | 按文件名引用依赖共享库之处、陈述了不存在的精确导出名之处(如有,M12、M13);命名约定的检查留在索引 | +| mcpplibs/os、openkal-windows | 进程层启动镜像所用的路径(测定后) | + +## 8. 验证 + +每项一个以行为命名的用例;不需要工具链的写成不带能力标记的 C++ 用例。 + +| 项 | 用例断言 | +|---|---| +| §4.1 发布 | 依赖共享包的宿主工具在全新 home 中由构建程序运行成功;条目中有该共享对象 | +| §4.1 核对 | 宿主 `-L` 链接而由环境满足加载的工程被拒绝,消息含两个文件;同一工程改为陈述该包后通过 | +| §4.1、§4.2 范围 | 未陈述环境的工程:产物的 RPATH 不含并集视图;弃用项对仅由并集满足的 soname 各报告一次 | +| §4.2 | 一个打印 `PATH` 并调用运行层工具的程序,在 `mcpp test` 与 `mcpp run` 下都找到它;构建程序的 `PATH` 与它们前两段相同;Windows 上 `PATH` 不含 `cl` 的垫片 | +| §4.3 | `mcpp add` 之后的清单被严格的 TOML 读者接受;原始字符串中的 `export module` 不构成冲突;发布归档的清单中 `[feature-deps.*]` 没有 `path`;两个短名相同的包以共享形态打包成功 | +| §4.4 | 替换 C 库而无 C++ ABI 的图在规划时被拒绝,消息含两个补救;带大 TLS 的共享镜像被报告并列出符号;`#!` 指向不存在程序的产物在执行前得到提示 | +| §4.5 | 两棵内容相同的树共用一个条目,一棵被编辑并构建后,另一棵的计划所指文件仍在;两棵都编辑后旧条目被删除 | +| §4.6 | 经符号链接给出的 home:`self env` 的每个路径都以给定拼写打印,构建成功;Windows 上以 `subst` 盘给出的 home 同样 | +| §4.7 | 宏未定义时条件块内的 `import` 不进入图;定义后进入;头单元仍被拒绝 | +| §4.8 | 列出未定义精确名的镜像链接失败并指名;含通配符的条目行为不变 | +| §4.9 | `mcpp add --build` 写入 `[build-dependencies]`;构建插件写在 `[dependencies]` 时的告警给出完整的两条命令 | +| §4.10 | profile 的 `dialect_cxxflags` 出现在 `-p <成员>` 下依赖成员的编译命令与标准库模块的预编译中 | +| §4.11 | cmdline:引擎的单元测试(嵌套子命令、全局选项、`--k=v`、`--` 之后、可选值、隐藏命令);每种 shell 一个冒烟测试。mcpp:`mcpp __complete` 对包名给出本地索引中的候选,且不创建 home | +| §4.12 | 三个来源的描述相同 | + +单元测试覆盖:代码文本的函数(原始字符串、注释、数字分隔符、续行);依赖项的枚举;条目归属的集合操作;链接与加载 +比较的判定;路径身份函数。 + +## 9. 实施时测定 + +| 编号 | 问题 | 方法 | +|---|---|---| +| M1 | 图中 `[xlings.workspace]` 条目所安装载荷的库目录是否足以满足现有示例与 mcpp-index 成员的加载,还是需要载荷所声明依赖的闭包 | 在全新 home 中以「不含并集视图」构建 `examples/` 与索引的图形类成员,列出未满足的 soname | +| M2 | #926 的两个包(esbuild、typescript)的程序目录与别名形态 | 在三个宿主上列出 `xlingsDepBinDirs` 与实际可执行文件的位置 | +| M3 | #907 的镜像由哪一种运行时契约产生;glibc 的静态 TLS 余量在各版本上的值 | 以报告的构造读出契约与 `readelf -d`;读 glibc 载荷的数据 | +| M4 | #962 中 `hanim.core` 被写成内联表的成因 | 以报告的清单运行 `publish --dry-run` 并读归一化的序列化路径 | +| M5 | 精确名在 PE 与 Mach-O 上的渲染,以及各链接器对未定义名的行为 | 每个链接器一个两文件的用例 | +| M6 | 规划期对一个单元做编译器扫描的耗时,GCC 与 Clang | 在 #421 的工程规模上测量 17 个单元的总耗时 | +| M7 | `mcpp __complete` 的启动耗时 | 三个宿主上各测一百次取中位数,定预算 | +| M8 | 约九十处规范化调用中「身份」与「地址」各多少 | 逐处归类,结果即基线 | +| M9 | 进程层是否以规范路径启动镜像 | 在 mcpplibs.os 的测试中以盘符别名启动一个程序 | +| M10 | #1008 与 #1015 | §4.13 | + +| M11 | 规划期的编译器扫描在 Clang 与 MSVC ABI 的行上是否可用 | 三个工具链各扫描一个含条件导入的单元 | +| M12 | 三个新弃用项在生态中的现有用量 | 以候选版本对 mcpp-index 的全部成员、mcpp-plugins 与已知的下游工程运行 `mcpp why compat`,统计每项的出现次数 | +| M13 | 共享库改名在索引中的影响 | 以候选版本对索引中以共享形态打包的成员运行构建与打包 | +| M14 | PE 上链接与加载比较的两侧 | 在 Windows 上对一个带 DLL 依赖的程序读出导入表与部署目录 | + +M1 决定 §4.1 中未陈述工程的库目录由什么构成。M12 决定三个弃用项的移除月份。这些测量在一次只跑 CI 的探测中完成, +先于各组的实施。 + +## 10. 已定的决定 + +十三项按建议定下。D3 与 D10 的内容经自审修改(§12),表中是修改后的结论。 + +| 编号 | 事项 | 结论 | +|---|---|---| +| D1 | 并集视图的范围 | 只对陈述了环境的工程生效:库的搜索路径、链接期的 `--sysroot`、测试子进程的 `PATH` 三处同一规则、同一日期,经 `implicit-default-environment` 过渡 | +| D2 | 宿主工具的共享依赖 | 发布进条目,不改写依赖的形态 | +| D3 | 共享库的命名 | 依赖包用规整后的限定名(与对象目录同一个函数),根包保持目标名;陈述的 `soname` 优先,重复即拒绝 | +| D4 | 重新打开的点号键表 | 经 `reopened-dotted-table` 先报告后拒绝;编辑器在没有既有形式时写点号键,并在下次编辑时修复非法形式 | +| D5 | 静态 TLS 超界 | 降级报告;陈述了精确导出名的镜像拒绝 | +| D6 | `--cache local` 与宿主工具 | 不改行为,写进文档 | +| D7 | 路径的键与检查 | 键按给定拼写;身份比较容忍失败并报告;检查用只减不增的基线 | +| D8 | 条件导入 | 缺省启用,不加开关 | +| D9 | 精确的导出名 | 同一个键,经 `unmatched-exact-export` 先报告后成为链接错误 | +| D10 | 构建插件 | 不新增陈述键;`mcpp add --build`;写错表的条目由已有的 `host-module-in-dependencies` 处理,日期 2027.1 | +| D11 | profile 的整图编译词 | `[profile.] dialect_cxxflags`;`cxxflags` 的作用域不变并写进规范;不为 C 单元加键 | +| D12 | 发布 | 三组各自一个发布,组间没有依赖 | +| D13 | 跨仓库的顺序 | cmdline 先于 mcpp 的补全;进程层的测定在 mcpplibs.os 中进行 | + +## 11. 任务与依赖 + +任务按依赖分为三组,组与组之间没有依赖,组内按箭头的顺序。 + +| 组 | 任务 | 依赖 | +|---|---|---| +| A 读者与归属 | A1 代码文本的单一实现(#963);A2 依赖项的枚举与编辑器、归一化(#962、#964、`--build`);A3 条目归属(#1025 第 1 项);A4 C++ ABI 的拒绝(#898);A5 `#!` 提示(#621);A6 profile 的 `dialect_cxxflags` 与 SPEC-004(#1025 第 2 项);A7 feature 描述(#1018) | A2 → `mcpp add --build`;其余互不依赖 | +| B 闭包与路径 | B1 测定 M1、M2、M3、M12、M13、M14;B2 工具条目的发布(#535);B3 链接与加载的核对(#537);B4 子进程 `PATH`(#926);B5 并集视图的范围与弃用项(D1);B6 共享库的限定名(#975);B7 静态 TLS(#907);B8 路径的拼写与检查(#1024) | B1 → B5、B7;B2、B3、B4 → B5;B8 独立 | +| C 扫描与命令行 | C1 条件导入(#1026);C2 精确名(#982);C3 cmdline 的补全;C4 mcpp 的补全 | C3 → C4;M5 → C2;M6、M11 → C1 | + +两项先测量的缺陷(#1008、#1015)不属于任何一组;#1008 的结果可能并入 A6。 + +## 12. 自审 + +决定定下之后,按十二个角度复查了全文。下表是每个角度的发现与处理;标「改」的已并入正文。 + +| 角度 | 发现 | 处理 | +|---|---|---| +| 设计规范 | v1 为构建插件建议新增一个包级的陈述键。引擎已从源文件得出这一事实,代码中称再陈述一次为「同一事实的第二种拼写」 | 改:不新增键(§4.9、D10) | +| 设计规范 | 拒绝须带原因标记。运行期闭包的既有拒绝没有标记,v1 的新拒绝也没有写 | 改:`runtime-closure`、`soname-collision`、`static-tls-image`(§4.1、§4.3、§4.4、§7) | +| 设计规范 | §4.4 的补救行写了一个包名,等于引擎知道索引的内容 | 改:补救指名能力(§4.4) | +| 架构 | 规则二没有用到本文自己身上:子进程的 `PATH` 仍是「构建程序一套、测试与运行一套」;依赖扫描的命令在规划期与构建期各构造一次 | 改:三种子进程一个函数(§4.2);扫描命令一处构造(§4.7) | +| 优雅 | 运行期的三项缺陷在 v1 中是三条措施 | 改:写成一条不变量与它的三种违反形式,并接上弃用表的先例 `undeclared-cxx-runtime`(§4.1) | +| 通用性 | 核对是否只对 #537 的构造成立 | 核对对每个带动态段的镜像成立,含宿主工具与测试;精确名适用于每个没有程序起点的镜像(§4.1、§4.8) | +| 生态验证 | v1 给四处行为变化配了弃用项,却没有测它们在生态中的用量,日期无从确定 | 改:M12、M13,在索引、插件仓库与下游工程上以候选版本统计,日期据此确定(§9) | +| 简洁 | 是否有可以不做的部分 | 不建闭包目录;不加扫描开关;不加 C 的整图键;不加插件陈述键;`mcpp add` 不猜。新增的记录文件与三个模块是替换重复实现所需的最少数量 | +| 语义一致 | v1 的共享库名用点号拼接限定名,而对象目录已经用规整函数(下划线)区分包 | 改:同一个函数(§4.3、D3) | +| 语义一致 | `dialect_cxxflags` 的名字是「方言」,用于整图的检测与体积选项是否越界 | 不改:该键的定义是「必须整图一致、到达标准库模块」的编译词,这些选项符合定义;文档以例子说明 | +| 跨平台 | 规划期的编译器扫描目前只有 GCC 的命令;PE 上「链接与加载」两侧是什么没有测过;`PATH` 的键在 Windows 上不区分大小写 | 改:M11、M14;§4.2 写明键的处理;没有扫描器的行保持拒绝 | +| 兼容性 | 新旧版本的 mcpp 共用一个 home 时,v1 的多行 `source` 会被旧版本截断为一行,旧版本随后可能删除别的树在用的条目 | 改:新文件 `users`,旧文件只读(§4.5) | +| 兼容性 | 旧版本对未知的 profile 键只告警并忽略 | 改:使用新键的清单陈述下限(§4.10) | +| 模块划分 | 宿主工具的存储在 `modules/buildmcpp`,不能导入 `src/` 的模块;v1 没有说共用函数放在哪里 | 改:三个新模块放在 `modules/libs`,原子替换的原语随之下沉;`src/` 只增加调用,方向与「缩小 `src/`」一致。新模块按四处接线,由已有的接线检查覆盖(§7) | +| 工程结构 | 守住规则的手段 | 路径规则有只减不增的基线检查;原因标记由已有的三方一致检查覆盖;弃用项到期由登记表的测试强制 | +| 性能 | 条件导入的扫描结果若只按源文件与编译词缓存,头文件中宏的变化不会使它失效 | 改:按扫描的依赖文件验证(§4.7) | +| 性能 | 各项的开销 | 核对只在镜像变化时进行,内容摘要只在路径不同时计算;使用者记录只在一棵树第一次命中时写;去掉规范化减少逐级的系统调用;补全入口设启动预算(M7);快速路径记录子进程的 `PATH` | + +**仍然存在的风险。** + +1. D1 的实现量取决于 M1。若陈述的载荷目录不足以满足加载,需要提供者给出依赖闭包的查询,这是跨仓库的工作。 +2. §4.4 的静态 TLS:产生该镜像的运行时契约没有定位(M3)。报告能指出问题,但不保证指出的是原因。 +3. #535、#926、#975、#898 的设计依据是读码而不是重新复现;实施的第一步是把各自的复现写成失败的用例。 +4. 三个弃用项同时进入,加上已有的两项在 2027.1 到期,一个工程在同一时期可能收到多条告警。M12 的用量若集中在少数包上, + 先修这些包再发布。 +5. 共享库改名没有过渡期。按文件名引用依赖共享库的外部脚本会在升级后失败,只有 CHANGELOG 告知。 + +## 13. 实施记录(v3) + +实施于 mcpp 2026.11.27.1,一个 PR(mcpp#1023),连同 mcpplibs/cmdline 0.0.6(cmdline#13)与 mcpp-index 的 +cmdline 0.0.6(mcpp-index#928)。下表是实施与 v2 不同之处及其原因;其余各节按 v2 实施。 + +| 项 | v2 | 实施 | 原因 | +|---|---|---|---| +| 使用者记录(§4.5) | 条目旁的文件 `users`,每行一棵树 | 条目旁的目录 `users/`,每棵树一个文件,文件名是树路径的 FNV-1a 摘要,先写临时文件再改名 | 加入一棵树是一次原子的创建,两个进程同时命中不需要读改写或锁;撤下是删除一个文件 | +| 撤下的时机(§4.5) | 以新摘要写入条目时撤下本树 | 写入或命中新摘要的条目时都撤下本树 | 两棵树被编辑为同一内容时,第二棵命中第一棵写入的条目而不写入;只在写入时撤下,旧条目会一直留着它的名字(e2e 1171 测出) | +| 条件导入的结果缓存(§4.7) | 扫描结果随它读过的文件缓存 | 不缓存;含条件导入的单元在每次规划时由编译器扫描一次 | 规划只在快速路径不成立时发生;按依赖文件验证的缓存是另一套失效机制。M6 未测,代价未定 | +| MSVC 上的条件导入(§4.7) | 由 M11 测定 | 规划期拒绝,消息说明 MSVC 没有规划期扫描 | 规划期的扫描命令只构造 GCC 与 Clang 两种;M11 未测 | +| 精确导出名(§4.8) | ELF、Web、PE、Mach-O 各自的渲染 | ELF 上链接后读动态符号表核对,未定义者以弃用项报告;Mach-O 由 ld64 自身拒绝;Web 的 `-sEXPORTED_FUNCTIONS` 与 PE 未实现 | M5 未测 | +| 静态 TLS(§4.4) | 列出最大的 TLS 符号及其对象 | 报告镜像的 TLS 段大小与界限,不列符号;界限是行的数据 `dlopen-static-tls`(SPEC-016 §2.1),内置 glibc 行为 512 | 原因与补救足以定位;符号的归属需要读符号表并按 TLS 段计算,留作改进 | +| 子进程 `PATH` 的过渡(§4.2) | 经 `implicit-default-environment` 逐项报告 | 测试保留旧行为(Windows 之外,环境 `bin` 在陈述的工具之后),不报告;`mcpp run` 的程序此前没有这一段,也不得到它;`mcpp run` 的快速路径按构建记录的目录组成同一个值 | 无法得知一个测试是否用到环境 `bin` 中的工具,报告无从产生;保留的是旧行为,不是更少的行为 | +| 链接期的 `--sysroot` 与并集视图(§4.1) | 未陈述环境的工程,闭包与 RPATH 不含并集视图,`--sysroot` 同一日期改变 | 两者不变;只由并集视图满足的 soname 每次构建报告(`implicit-default-environment`),到期移除 | 弃用项先报告后移除(D1);M1 未测,移除前需要用量 | +| 共享库的名字(§4.3) | 依赖包一律取限定名 | 缺省命名空间(`mcpplibs`)的包取包名,即它作为裸键的写法(`libdepShared.so`;与包不同名的目标接在包名之后,`libdep_depshared.so`);其他命名空间取限定名(`libcompat_sdl3.so`、`libmcpplibs_mwrap_sdl3.so`) | 缺省命名空间的包的限定名带 `mcpplibs_` 前缀,会无故改变每个此类库的名字(8 个既有用例因此失败);裸名与其依赖键的写法一致 | +| 补全的候选(§4.11) | 包名取自本地索引缓存,工具链取自 home | 工具链取自 home 的提供者的各个存储中载荷表可点名的条目,包取自配置给出的各索引目录,二者都经只读的配置读取(`Initialization::ReadOnly`);缺省命名空间的包给出裸名,所补全的词以 `mcpplibs.` 开头时给出限定名 | 存储与索引的位置是配置的回答:`[xlings] home` 与上游改变它们,按目录名拼写的读取是第二个读者;裸名是依赖键的写法,限定名是用户已经写出的前缀 | +| 三个内部命令(§4.11) | 改用隐藏标记 | 隐藏:不在帮助、补全与 `mcpp emit surface` 中;黄金表面随之去掉三项 | 隐藏的含义是不属于用户可见的表面 | +| 规划期扫描的启动(§4.7) | 与构建的扫描边是同一条命令 | 同一组词(`p1689::scan_words`):扫描边把它们连成命令,规划期的扫描把它们作为参数向量交给程序,中间没有 shell;标准与方言词另存为参数(`stdWords`),字符串保持原样 | 命令曾经以 POSIX 单引号拼成文本交给 shell;Windows 的 shell 是 cmd.exe,不认单引号,被引起来的程序名以错误 123 失败(Windows CI,e2e cli/05);参数向量没有引号问题 | +| C++ ABI 的拒绝与标准库模块的门(§4.4) | 扫描之后立即拒绝 | 在标准库模块的门之后,且只在工具链有标准库模块时;只要求配置时作为说明 | 工具链没有标准库模块时,目标自己的拒绝更具体(openkal 的行:程序内需要一个 C++ 运行时,e2e 942、951);`mcpp self env` 只描述配置 | +| 主线程的栈(Windows) | 未涉及 | mcpp 的 Windows 映像为主线程保留 8 MiB 的栈(`mcpp.toml` 中按环境写出 `/STACK` 与 `--stack`),与 Linux、macOS 给出的相同 | 一条命令在一个进程中嵌套整次构建:`mcpp pack` 依次准备程序、平台点名的宿主工具与该工具的构建程序,每层的帧有数百 KiB。Windows canary 的 openkal `mcpp pack` 以 `EXCEPTION_STACK_OVERFLOW` 失败;本地以 1 MiB 的栈复现,崩溃处栈深 1,046 KiB(`cli::run` 174 KiB、`prepare_group` 123 KiB、三层 `prepare_build` 各 62 KiB、清单读取两层各 44 KiB)。2026.11.26.1 在同一限制下通过,余量只有数 KiB;本轮新增的字段只有几个向量,帧原本就这么大 | +| 测定(§9) | M1–M14 在探测中先于实施完成 | 未运行;#1008 与 #1015 未测量 | 本轮在一个 PR 中实施;各项以本地构造与用例验证(下文) | + +**#1015 的测量(§4.13)。** 在 mcpp 2026.11.27.1 与 clang 23.1.3 上按报告的三个单元(`c` 一个文件,`b` 导入 `c`, +`main` 导入 `b`)复现:编辑 `c` 的函数体(长度不变)之后的构建编译 `c` 与 `b`,下一次无编辑的构建编译 `main`,再往后 +不编译。第二次构建之前 `ninja -n -d explain` 的解释: + +``` +ninja explain: recorded mtime of obj/main.o older than most recent input + /tmp/m1015/target/x86_64-linux-gnu//pcm.cache/c.pcm +``` + +`ninja -t deps obj/main.o` 列出的 `c.pcm` 与 `b.pcm` 是绝对路径:clang 按 `-fprebuilt-module-path=<构建目录>/pcm.cache` +找到它们,依赖文件照此书写;而图中 `c` 的边以相对路径 `pcm.cache/c.pcm` 声明这个输出。同一个文件在 ninja 中是两个 +节点:第一次构建中 `c` 的边重写了相对节点,`b.pcm` 的内容不变而被保留,`main.o` 因此不重编;绝对节点没有产生它的边, +ninja 在构建开始时读过它的时间,之后不再读,于是下一次构建才发现它比 `main.o` 新。原因成立,GCC 的依赖文件以相对的 +`gcm.cache/…` 书写,不受影响。路径是绝对的有它的原因(`compile_commands.json` 的 `directory` 是工程根,clangd 在那里 +解析该路径),因此不改编译命令,也不改写依赖文件(只有经执行器的边才能改写,且生成头文件的节点本是绝对路径): +写出 BMI 的每条边(编译、两段式的预编译、拆分调度的 BMI 边、`std` 与缓存条目的暂存)把绝对拼写一并声明为隐式输出, +ninja 由此知道两个拼写由同一条边写出(SPEC-018 §1 第 6 条)。修复后同一构造中,编辑之后的构建编译 `c`、`b` 与 +`main`,其后无编辑的构建不编译(e2e 1176,在 macOS 与 Windows 以缺省的 clang 运行)。#1008 本轮未测量。 + +本地验证(Linux x86_64,GCC 16.1、LLVM 23.1.3): + +- 条件导入:宏未定义时条件块中的 `import` 不进入图,定义后进入;头单元仍被拒绝(e2e 1172)。 +- 两个短名相同的包以共享形态链接,得到 `libacme_util.so` 与 `libbeta_util.so`,程序运行;陈述同一 `soname` 被拒绝(e2e 1167)。 +- 链接读 `a/libfoo.so`、运行路径给出 `b/libfoo.so` 的构建被拒绝并指名两个文件(e2e 1168);#537 的构造(宿主 + `/usr/lib` 的 zlib 链接,`xim-x-zlib` 载荷加载)同样被拒绝。 +- 4096 字节 initial-exec TLS 的共享镜像被报告,陈述精确导出名时被拒绝(e2e 1169);未定义的精确导出名被报告(e2e 1170)。 +- 两棵内容相同的树共用一个条目,一棵被编辑后另一棵的条目保留,两棵都编辑后旧条目被删除(e2e 1171)。 +- 重新打开的点号键表被读取、报告,`mcpp add` 之后的清单被 Python 的 `tomllib` 接受(e2e 1173)。 +- 依赖图提供 C 库而无 C++ ABI、导入 `std` 的计划在编译之前被拒绝(e2e 1174)。 +- `mcpp __complete` 每次约 1 ms,读取配置的候选(工具链、包)约 20 至 40 ms;不创建 home,不写入配置;隐藏命令不被补全;工具链与包的候选由用例自己写出的存储条目与索引副本核对(e2e 1175)。 diff --git a/.agents/docs/README.md b/.agents/docs/README.md index 3b13c724b..fd3643636 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 --- ``` -374 records. +375 records. ## By subject @@ -61,6 +61,7 @@ Records that declare one. Everything else is listed by date below. ### design +- [陈述的闭包、单一读者与六项功能:十四项缺陷的收敛设计](2026-11-27-stated-closure-single-reader-and-feature-designs.md) — landed - [生态级方案:内核接口的供给与能力,派生状态的核对,存储的引用](2026-11-22-kernel-interface-and-derived-state-ecosystem-design.md) — active - [程序起点模型:启动者、两层入口与 `main` 的三种陈述(mcpp#845、mcpp#981)](2026-11-20-program-start-model.md) — landed - [升级的连续性:打包修订不在使用路径上替换载荷、替换失败不拆掉可用状态、home 中的悬空记录自愈、真实的升级 lane](2026-10-17-upgrade-continuity-design.md) — active @@ -216,6 +217,7 @@ Records that declare one. Everything else is listed by date below. ### 2026-11 +- [陈述的闭包、单一读者与六项功能:十四项缺陷的收敛设计](2026-11-27-stated-closure-single-reader-and-feature-designs.md) — landed - [clang BMI 的截断与私有模块片段判定的收窄](2026-11-26-clang-bmi-cutoff-and-private-fragment-refinement-design.md) — active - [测试与 CI 一轮的收尾:平台列未命中的刷新条件(mcpp#996)、`i686-windows-msvc` 行、工作区索引与引号键的迁移、索引的全量验证](2026-11-22-test-round-wrap-up-plan.md) — active - [生态级方案:内核接口的供给与能力,派生状态的核对,存储的引用](2026-11-22-kernel-interface-and-derived-state-ecosystem-design.md) — active diff --git a/.github/tools/check_path_identity.sh b/.github/tools/check_path_identity.sh new file mode 100755 index 000000000..939a73a2a --- /dev/null +++ b/.github/tools/check_path_identity.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# The resolutions of a path to its canonical form only fall (design 2026-11-27 §4.6, mcpp#1024). +# +# A path the user or the environment gives is opened and handed to a program as it is spelled; its +# canonical form is an identity, asked of mcpp.libs.path_identity, which reports when it cannot be +# read. Each file's count of `canonical(` and `weakly_canonical(` called on std::filesystem is at +# most its line in path-identity.baseline; a file not listed has none. A line falls as its calls +# move to the identity module (an identity) or to the given spelling (an address). +set -u +cd "$(dirname "$0")/../.." + +baseline=.github/tools/path-identity.baseline +[ -f "$baseline" ] || { echo "::error::missing $baseline"; exit 1; } + +current=$(grep -rcE '(filesystem|fs)::(weakly_)?canonical\(' src modules \ + --include='*.cpp' --include='*.cppm' 2>/dev/null \ + | grep -v ':0$' | grep -v '^modules/libs/src/path_identity.cppm:' | grep -v '/tests/' \ + | sed 's/:/ /' | sort) + +rc=0 +while read -r file n; do + [ -n "$file" ] || continue + allowed=$(awk -v f="$file" '$1 == f { print $2 }' "$baseline") + if [ -z "$allowed" ]; then + echo "::error::$file resolves a path to its canonical form $n time(s); ask mcpp.libs.path_identity, or open the given spelling" + rc=1 + elif [ "$n" -gt "$allowed" ]; then + echo "::error::$file resolves a path to its canonical form $n times, more than the $allowed of $baseline" + rc=1 + elif [ "$n" -lt "$allowed" ]; then + echo "note: $file resolves $n times, fewer than the $allowed of $baseline; lower its line" + fi +done <<< "$current" +[ "$rc" = 0 ] && echo "OK: no file resolves a path to its canonical form more often than $baseline states" +exit "$rc" diff --git a/.github/tools/path-identity.baseline b/.github/tools/path-identity.baseline new file mode 100644 index 000000000..a18a43c99 --- /dev/null +++ b/.github/tools/path-identity.baseline @@ -0,0 +1,30 @@ +modules/manifest/src/glob.cppm 5 +src/build/engine_package.cppm 2 +src/build/hermetic.cppm 1 +src/build/plan.cppm 2 +src/build/prepare/features.cpp 4 +src/build/prepare/graph.cpp 3 +src/build/prepare/manifest.cpp 1 +src/build/prepare/plan.cpp 2 +src/build/prepare/platform.cpp 1 +src/build/prepare/state.cppm 1 +src/build/prepare/windows_resources.cpp 2 +src/build/resources.cppm 1 +src/build/runtime_validation.cppm 3 +src/build/schedule/compiler_transaction.cppm 2 +src/build/schedule/detach_codegen.cppm 2 +src/config.cppm 1 +src/home/files.cpp 1 +src/modgraph/scanner.cppm 1 +src/pack/distribution.cppm 2 +src/pack/pack.cppm 5 +src/pm/lock_io.cppm 1 +src/pm/patch.cppm 1 +src/project.cppm 3 +src/provider/xlings/xlings.cpp 1 +src/runtime/binding.cppm 4 +src/runtime/elf.cppm 2 +src/toolchain/base_probe.cppm 4 +src/toolchain/clang.cpp 2 +src/toolchain/post_install.cppm 3 +src/toolchain/registry.cppm 2 diff --git a/.github/tools/system-names.baseline b/.github/tools/system-names.baseline index 8f9fc7436..6f0c57d25 100644 --- a/.github/tools/system-names.baseline +++ b/.github/tools/system-names.baseline @@ -14,7 +14,7 @@ haiku 0 dos 0 uefi 0 is_linux 26 -is_windows 123 +is_windows 122 is_macos 28 is_apple 5 is_ios 7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1cf8bda1c..ac22c0520 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -276,6 +276,9 @@ jobs: - name: The tests wait for a time no more often than the baseline states run: bash .github/tools/check_waits.sh + - name: Paths are resolved to their canonical form no more often than the baseline states + run: bash .github/tools/check_path_identity.sh + - name: Only the adapter and the composition root name the provider run: python3 .github/tools/check_provider_boundary.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ec086971c..ab53861f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,137 @@ > 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.27.1] - 2026-11-27 + +### Changed + +- A dependency's shared library is named by its package. Its file and its SONAME take the + package's qualified name, made a file name by the function that names the package's object + directory: `compat.sdl3`'s target `sdl3` builds `libcompat_sdl3.so`, and a target named + otherwise than its package follows the package's name (`libcompat_sdl3_extra.so`). A package of + the default namespace is spelled by its bare name: a target named as its package keeps its + library's name, and one named otherwise follows the package's name (`libdep_depshared.so`). The + root package and a selected member keep their target's name, and a target that states `soname` + is loaded by the name it states. Two packages whose libraries would be loaded by one name are + refused at planning with `[soname-collision]`, naming both. Before, `compat.sdl3` and + `mcpplibs.mwrap.sdl3` both made `libsdl3.so`. A script outside mcpp that names a dependency's + shared library by its file name follows the change (docs/04, mcpp#975). +- The `PATH` of a build program, a test and the program of `mcpp run` is composed by one + function, the same on every host: the directories of the tools the graph states, then the + declared environment's `bin` when the project declares one, then the `PATH` mcpp was started + with. A build program that calls a tool the graph states by its bare name gets the stated one, + and a test finds a tool stated with `when = "run"` on Windows and macOS as on Linux. Before, a + build program's `PATH` had no stated tool, and a test's held the toolchain's environment `bin` + on Linux only (docs/23, mcpp#926). +- `mcpp add` writes the form the table already uses for the namespace: the short key in an + existing `[dependencies.]` section, else the dotted key `.` in `[dependencies]`; + a package of the default namespace is a bare key. Before, it could write a + `[dependencies.]` header after dotted keys had defined that table, which TOML 1.0 and every + strict reader refuse. `mcpp remove` takes `--dev` and `--build`, as `mcpp add` does + (docs/05, mcpp#964). +- The code text of a source, its text with comments and literals blanked, has one reader, shared + by the module scanner, the build optimizations and the check of module names a package + declares. An `export module` inside a raw string literal or a comment no longer declares a + module (mcpp#963). +- The cache entry of a `path` dependency or a `path` host tool records every tree that uses it, + one file per tree under the entry's `users/`. A tree that writes or hits the entry of an edited + content withdraws itself from the entries of its earlier contents, and an entry is removed when + no tree uses it. Before, an edit in one checkout removed the entry another checkout's plan named. The + `source` record of an earlier mcpp is read as the first user and is not written, so an earlier + mcpp that shares the home removes none of the new entries (docs/09, mcpp#1025). +- The home keeps the spelling it is given: a home named through a symbolic link is used under + that name in every path mcpp opens, starts or prints, and its physical path is used only to + decide whether two paths are one object. A comparison that cannot be made is made on the + spelling and reported as degraded. A check in CI holds the physical-path calls outside the + identity function to a baseline that only shrinks (docs/25, mcpp#1024). +- `mcpp publish` normalizes every dependency table, the tables under `[target.]` and + each `[feature-deps.]` included, through one enumeration of a manifest's dependency + tables, which the loader and the manifest editor also walk. A `path` dependency of a feature is + published by its version, and so is a workspace member that lies inside the package's directory + (mcpp#962). +- The `host-module-in-dependencies` warning names the two commands that move the entry: + `mcpp remove `, then `mcpp add --build @` (mcpp#993). +- mcpp's Windows images reserve 8 MiB of stack for the main thread, the size Linux and macOS give + it. A command nests whole builds in one process: `mcpp pack` prepares the program, a host tool + its platform names and that tool's build programs. Measured on the openkal canary, this held + about 1 MiB of frames, the whole of a PE image's default reserve. + +### Added + +- An `import` inside a conditional block (`#if`, `#ifdef`, ...) is read by the compiler's + dependency scan with the unit's own compile words, on GCC and on Clang (`clang-scan-deps`), and + the unit imports what the condition selects. Before, the lexical scan refused the unit. A module + declaration in a conditional block is read the same way; header units are still refused, and so + is such a unit under MSVC, which has no scan at planning (docs/04, mcpp#1026). +- `mcpp add --build` writes the dependency into `[build-dependencies]` (docs/05, mcpp#993). +- `[profile.] dialect_cxxflags`, with the meaning of `[build] dialect_cxxflags` and appended + after it: it reaches every unit of the graph and the `std` module. A workspace's profile takes + it too. SPEC-004 §9 states that a profile's `cflags` and `cxxflags` reach the root package and + the selected members, and its `opt`, `debug`, `ndebug`, `dialect_cxxflags` and `ldflags` the + whole graph. An unknown key in a profile is reported (docs/04, mcpp#1025). +- Shell completion. `mcpp self completion [bash|zsh|fish|powershell]` writes into + `/config/shell/` a script that passes the words before the cursor to `mcpp __complete`, + and prints the line that loads it. mcpp answers from its command tree, with the profiles, + members and dependencies of the manifest in the directory, its target rows, the installed + toolchains and the packages of the local index copies; a completion reads only what is on disk + and initializes no home. The engine is mcpplibs.cmdline 0.0.6 (docs/01, mcpp#794). +- A host tool's store entry holds, beside the executable, each shared object its link read from + its own build, and lists them; an entry without them is built again. Before, a tool that linked + a library of its graph shared failed to start from the store (docs/30, mcpp#535). +- The file a link reads for a `DT_NEEDED` is the file the loader loads. After an ELF image is + linked, the name is resolved over the image's search path and compared with the shared object + the link recorded reading (`--dependency-file`), as an object and then by content; another file + is refused with `[runtime-closure]`, naming both. A name nothing answers at load time carries + the same token. Under `MCPP_ALLOW_HOST_LIBS` a difference is inconclusive (docs/04, mcpp#537). +- An ELF shared image that asks for the static TLS block (`DF_STATIC_TLS`) with a TLS segment + larger than glibc serves an image loaded by `dlopen` (512 bytes) is reported; when its exact + `exports` say a host enters it by name, it is refused with `[static-tls-image]` (docs/04, + mcpp#907). +- A graph that supplies the C library and no C++ ABI, whose units import the `std` module, is + refused at planning with `[layer-requirement]` and two remedies, a dependency that provides + `mcpp:c++-abi` or `[build] cxx_runtime = "host-coupled"`. Before, the `std` module's precompile + failed inside the toolchain's headers (docs/22, SPEC-002 §3.11, mcpp#898). +- Before `mcpp run` and `mcpp test` execute an artefact whose `#!` line names a program that is + not on its `PATH`, a note names the program and gives the commands that install a toolchain + descriptor, with the toolchain the build used (docs/20, mcpp#621). +- A library a program finds only in the default environment's union view, for a project that + declares no environment, is reported, naming the program and the library (docs/23). +- The features of `examples/11-features` state their descriptions, and a test holds that a + package's descriptions are the same from its manifest, an inline descriptor and an installed + payload (mcpp#1018). + +### Deprecated + +- `reopened-dotted-table` (until 2027.3): a `[header]` that reopens a table dotted keys defined. + The two are read together and reported; the next `mcpp add` to that table writes the header's + entries as dotted keys (docs/51). +- `implicit-default-environment` (until 2027.3): for a project that declares no environment, the + default environment's union view on the run-time search path and the link's `--sysroot`, and + its `bin` on a test's `PATH` outside Windows (docs/23, docs/51). +- `unmatched-exact-export` (until 2027.3): an exact `exports` name the shared image does not + define, which was dropped from the published set without a word; it is reported (docs/04, + docs/51). + +### Fixed + +- A build with no edit after an edit of a module compiles nothing under clang. clang names every + BMI an importer read by the absolute path it finds it through (`-fprebuilt-module-path`), and the + graph names the BMI below the build directory; ninja held the two spellings as two files, so the + importer of an importer whose BMI an edit changed was compiled by the next build, which had no + edit. The edge that writes a BMI now states the absolute spelling as an implicit output too + (SPEC-018 §1 item 6, mcpp#1015). +- `examples/11-features/greeter` stated `opt_level` in a profile, which is no profile key, and + the profile built without it; it states `opt`. +- A build after a failed build that stated `MCPP_PRIVATE_FRAGMENT`, `MCPP_BMI_SCHEDULE` or + `MCPP_BUILDOPT` is the build before it. In 2026.11.26.1 the statement was part of the record of + a build, which a build writes when it succeeds: a build that stated one and failed left its + graph under the record of the build before, and a plain build then replayed that graph and + failed the same way until a source or the manifest was edited. On GCC that is the invocation a + failure's `tip:` gives (`MCPP_PRIVATE_FRAGMENT=conservative mcpp build`), which fails where the + purview before the fragment holds a condition. The statement is now part of the request the + graph itself names (`request=` on the first line of `build.ninja`), which every fast path + compares before replaying it (SPEC-019 §9 item 5). + ## [2026.11.26.1] - 2026-11-26 ### Changed diff --git a/docs/01-getting-started.md b/docs/01-getting-started.md index 66165d2a2..a464d423c 100644 --- a/docs/01-getting-started.md +++ b/docs/01-getting-started.md @@ -75,6 +75,32 @@ mcpp --version > rather than using `source`, and verify the active command with > `Get-Command mcpp.exe`. +### Shell completion (2026.11.27.1+) + +`mcpp self completion` writes the completion script of a shell -- `bash`, +`zsh`, `fish` or `powershell`, named as the argument, taken from `SHELL`, or +`powershell` where `SHELL` is unset and `PSModulePath` is set -- into +`/config/shell/`, and prints the line that loads it. That line goes +into the shell's own configuration, which mcpp does not edit: + +``` +$ mcpp self completion bash + Wrote /home/user/.mcpp/config/shell/mcpp.bash +source '/home/user/.mcpp/config/shell/mcpp.bash' # in ~/.bashrc +``` + +The script holds no command of mcpp's: it passes the words before the cursor to +`mcpp __complete`, and mcpp answers from its own command tree, so a later +release that adds a command or an option completes it with the same script. +Beside subcommands and options, the answer holds the profiles and members of +the manifest in the current directory, the dependencies `mcpp remove` takes, +the targets mcpp has rows for, the toolchains installed in the home +(`gcc@16.1.0`) and the packages of the local index copies, each spelled as a +dependency key spells it: a package of the default namespace by its bare name, +and by its qualified name once the word begins with `mcpplibs.`. A completion +reads only what is on disk: it initializes no home, writes nothing and fetches +nothing. `--print` writes the script to standard output instead of the home. + ## Creating a Project ```bash diff --git a/docs/04-mcpp-toml.md b/docs/04-mcpp-toml.md index f18f6b4e1..267ab4513 100644 --- a/docs/04-mcpp-toml.md +++ b/docs/04-mcpp-toml.md @@ -425,6 +425,28 @@ The file lists one symbol pattern per line, `#` starts a comment, and `*` is the only wildcard. The inline array says the same thing and is for the two or three entry points where a separate file would be ceremony. +**An entry without a wildcard is an exact name (2026.11.27.1+).** It states that a +host enters the image by that name (`JNI_OnLoad`, `PyInit_`, a plugin +host's entry point), so the image must define it; a pattern only narrows the +set and may match nothing. The name is the linker's: a C++ function is written +in its mangled form or defined `extern "C"`. On ELF the shared image's dynamic +symbol table is read after the link, and an exact name it does not define is +reported as the deprecation `unmatched-exact-export` +([docs/51](51-supported-versions.md)), a build error from its removal month; +ld64 already refuses such a name on Mach-O. A name only some targets define is +written under the `[target.]` that defines it. + +**A shared image that asks for the static TLS block is reported (2026.11.27.1+).** +An object compiled for the initial-exec TLS model marks the library +`DF_STATIC_TLS`. Loaded with the program at start-up it runs; loaded by +`dlopen`, the loader serves its thread-local storage from what is left of the +static block, which the target row states (`dlopen-static-tls`, [35](35-platforms.md); +512 bytes on the glibc rows, glibc's `glibc.rtld.optional_static_tls`). A +library above it is reported with its size; one whose exact `exports` say a +host loads it by name is refused (`static-tls-image`). A row that states no +bound is not checked. Code of a shared library is compiled with +`-ftls-model=global-dynamic`, the compilers' default for `-fPIC`. + One statement, three renderings: | Platform | Rendered as | @@ -843,6 +865,24 @@ relinked, whether something else in the process already provides that library. / the executable's own directory (PE) finding it again after the build directory moves. +**A dependency's shared library is named by its package** *(2026.11.27.1+)*. +Its file and its SONAME take the package's qualified name, made a file name by +the function that names the package's object directory: `compat.sdl3`'s target +`sdl3` builds `libcompat_sdl3.so` (`libcompat_sdl3.dylib`, `compat_sdl3.dll`), +and a target named otherwise than its package follows the package's name +(`libcompat_sdl3_extra.so`); the prefix and suffix are the target row's data. A +package of the default namespace is spelled by its name, its spelling as a bare +key: a target named as its package keeps the name its library had +(`libdepShared.so`), and a target named otherwise follows the package's name +(`libdep_depshared.so`). +The root package and a selected member keep their target's name, and a target +that states `soname` is loaded by what it states. Two packages whose libraries +would be loaded by one name are refused at planning with `[soname-collision]`, +naming both. Before, a dependency's shared library took its target's name +alone, and `compat.sdl3` and `mcpplibs.mwrap.sdl3` both made `libsdl3.so` +(mcpp#975). mcpp links and finds the library by the new name; a script outside +mcpp that names a dependency's library by its file name follows the change. + **This is not `[target.].linkage`** (§2.7.1). That key answers the same-sounding question about the **C library** (a musl `-static` link, MSVC's `/MT`). The two are not independent, and the direction matters: a fully static @@ -1713,11 +1753,12 @@ with `provides` / `requires` and `[feature-deps.]`. ### 2.8.3 `[scan_overrides.""]` — Author-Asserted Scan Results -The default module scanner is a text-level pass that (deliberately) rejects -`import` statements inside conditional preprocessor blocks. Some legitimate -module units carry them — e.g. fmt's official `src/fmt.cc` guards -`import std;` behind `#ifdef FMT_IMPORT_STD`. When the file's import set is -known and stable, declare it instead of scanning: +The default module scanner reads text. A unit whose `import` or module +declaration stands inside a preprocessor condition — fmt's official +`src/fmt.cc` guards `import std;` behind `#ifdef FMT_IMPORT_STD` — takes its +imports from the compiler's dependency scan, run while the graph is planned +with the unit's compile words (2026.11.27.1+; see §2.8.4). When the file's +import set is known and stable, it may still be declared instead of scanned: ```toml [modules] @@ -1759,6 +1800,23 @@ The default scanner reads each source file without expanding `#include`. Imports that it discovers belong in the scanned source file itself. A header containing `import` does not add an edge to this default module graph. +**What is code is read once.** Comments and the contents of string and character +literals, raw strings included, are not code, and a digit separator (`1'000`) +is part of a number; one reader decides it for the scanner, for the build's +source seam and for the functions that read module names from a package's +sources (2026.11.27.1+). `export module x;` inside a raw string declares nothing. + +**An import inside a condition is the compiler's to answer (2026.11.27.1+).** +Which branch of `#if`, `#ifdef` or `#ifndef` a unit takes depends on the +toolchain's predefined macros, the target, the defines and the headers it +includes. Where an `import` or a module declaration stands inside one, the unit +is scanned by the compiler while the graph is planned (GCC's `-fdeps-format=p1689r5`, +`clang-scan-deps` with Clang), with the standard, the graph's `dialect_cxxflags`, +the target's compile side and the package's include directories and words, by +the command the build's own scan edge runs. MSVC is not asked for such a scan +while planning, and such a unit is refused there with that reason; a header unit +(`import ;`) is refused wherever it stands. + The scanner answers two questions per file — what does this unit provide, and what does it require — and nothing else decides them. @@ -1811,7 +1869,24 @@ dependency_debug = "lines" # the store's and git's dependencies: true | false | cflags = ["-fno-plt"] cxxflags = ["-fno-plt"] ldflags = [] -``` +dialect_cxxflags = ["-fsanitize=address"] # every C++ unit of the graph and the std module (2026.11.27.1+) +``` + +**Which units the lists reach (2026.11.27.1+).** `cflags` and `cxxflags` are +root-position words, as `[build] cflags` and `cxxflags` are: they reach the units +of the build's roots — the root package and the selected members. A member or a +`path` dependency compiled as a dependency of the selection does not get them, +so `mcpp build -p app --profile small` compiles a library `app` depends on +without them, and `--workspace` compiles it with them. `opt`, `debug`, `ndebug` +and `ldflags` reach the whole graph. Words that must be the same for every unit — +a sanitizer, `-fno-asynchronous-unwind-tables` for a size profile — belong in +`dialect_cxxflags`, which means what `[build] dialect_cxxflags` means (the +standard library module, the scan and every C++ unit) and is appended after it; +a workspace's profile accepts it too. A manifest that writes it states +`mcpp = ">=2026.11.27.1"`: an earlier mcpp reports the key and ignores it. C +units have no such key: a C++ graph must agree on its dialect because of BMIs +and the standard library module, and C units are not bound that way. A key a +profile does not have is reported and ignored. **Debug information on cl.exe (2026.11.7.1+).** `debug = true` compiles with `/Z7`: each object carries its own debug information. `/Zi` and `/ZI` write @@ -1952,6 +2027,9 @@ cache = "global" # "global" (default) | "local" | "off" `local` builds every dependency inside this project's `target/` — useful to rule the cache out while diagnosing something, and to give CI a no-sharing baseline. +A host tool stays in the shared store under every mode: a tool is addressed by +its sources and the host, and one entry serves every project that builds it; +`local` applies to the dependencies its build compiles. `off` additionally clears this build's `target///` for a cold rebuild; `--no-cache` is a deprecated alias for it. @@ -1968,8 +2046,13 @@ relative path and content below the dependency's root, except `target/`, `mcpp.toml`. Two projects that reach one library through `path`, a clean build, and a CI run that restores `$MCPP_HOME/build-cache` reuse one entry while the library's sources are the same, wherever its tree is checked out; an edit is a -new key, and the entry built from the same tree under the previous digest is -removed as the new one is written. A `path` dependency's tree is read again +new key. An entry records the trees that use it *(2026.11.27.1+)*: a tree that +writes the entry or hits it is added. When an edited tree writes or hits the +entry of its new digest, it is withdrawn from the entries of the same package +under the previous digests, and an entry left with no user is removed; an entry another +tree still uses is kept. Before 2026.11.27.1 the entry recorded only the tree +that wrote it, and an edit in one checkout removed an entry another checkout's +plan still named (mcpp#1025). A `path` dependency's tree is read again before its entry is written, and a tree that changed while it compiled is not stored. An entry holds its own package's units *(2026.11.20.1+)*: a unit below a package nested in the dependency's tree belongs to that package -- a @@ -2107,6 +2190,30 @@ Link intent keeps discovery stages separate: | `deploy_files` | copy edge | copy edge | copy beside the output; never a linker flag | | `deploy` *(2026.9.12.2+)* | copy edge into `bin//` | copy edge into `bin//` | copy edge into `bin//`; never a linker flag | +**The file a link reads is the file the loader loads** *(2026.11.27.1+)*. After +an ELF image is linked, mcpp resolves each `DT_NEEDED` it names over the +image's search path, as the loader will, and compares the result with the +shared object the link read for that name, which the link records +(`--dependency-file`, kept by ninja). The two are compared as objects, one file +under any spelling, and then by content. A name the loader answers with another +file is refused with `[runtime-closure]`: + +``` +error: libz.so.1 is linked from one file and loaded from another + linked /usr/lib/x86_64-linux-gnu/libz.so.1 + loaded ~/.mcpp/registry/data/xpkgs/xim-x-zlib/1.3.1/lib/libz.so.1 + help: state the package that provides it rather than a directory that holds a copy, or remove the directory from the link +``` + +A name nothing answers is refused with the same token. The check applies to +every image the build validates -- programs, shared libraries, tests and host +tools -- except the libraries of the C library the build is bound to, and its +verdict is kept with the image's, so an image that did not change is not +compared again. Under `MCPP_ALLOW_HOST_LIBS` the link reads host directories by +consent, and a difference is reported as inconclusive rather than refused. +Before, an image linked against a host copy of a library ran against the +store's copy without a diagnostic (mcpp#537). + `deploy` lists the runtime files of a package: the files a program reads from its own directory when it runs. A loader that reads a fixed subdirectory needs them there: the Vulkan loader on macOS reads driver manifests from diff --git a/docs/05-dependencies.md b/docs/05-dependencies.md index 5d61caa16..f7bedca52 100644 --- a/docs/05-dependencies.md +++ b/docs/05-dependencies.md @@ -376,6 +376,19 @@ The third form fails with an error that names the exact `(mcpplibs, asio)` identity that was tried and, when the short name exists elsewhere, gives a copyable explicit selector. +**What `mcpp add` writes (2026.11.27.1+).** It writes into the form the table +already uses for the namespace: the short key under a `[dependencies.]` +header when there is one, and otherwise the dotted key `.` in +`[dependencies]`; a package of the default namespace is a bare key. `--dev` +writes `[dev-dependencies]` and `--build` writes `[build-dependencies]`; +`mcpp remove` takes the same flags and removes from `[dependencies]` without +them. A header that reopens a table dotted keys already defined — `compat.libpng` +under `[dependencies]`, then `[dependencies.compat]` — is a table defined twice, +which TOML 1.0 and every strict reader (toml++, Python's `tomllib`) refuse. +mcpp reads it as the union of the two and reports the deprecation +`reopened-dotted-table` ([docs/51](51-supported-versions.md)); the next `mcpp add` +to that table writes the header's entries as dotted keys. + #### Migration window for bare names (`2026.8.10.1` → removed in `2026.9`) Every published `compat.*` package and every manifest written before exact @@ -564,6 +577,14 @@ tomlplusplus = "3.4.0" # a library build.mcpp protobuf = { version = "35.1", tools = ["protoc"] } # a program the build runs ``` +`mcpp add --build @` writes an entry here (2026.11.27.1+). +Whether a package is a build plugin is answered by its sources — its library +imports `mcpp.core` — so `mcpp add`, which has only the package's descriptor, +does not guess: without `--build` it writes `[dependencies]`, and the first +build of a plugin written there says so (`host-module-in-dependencies`, below) +with the two commands that move it, `mcpp remove ` and +`mcpp add --build @`. + A dependency is described on two axes (mcpp 2026.10.11.1+, SPEC-004 §12), and each axis has its own place in the manifest. diff --git a/docs/06-features-and-capabilities.md b/docs/06-features-and-capabilities.md index 0ea1a6eaf..3377bab02 100644 --- a/docs/06-features-and-capabilities.md +++ b/docs/06-features-and-capabilities.md @@ -128,7 +128,8 @@ simd = { sources = ["src/simd/**"], flags = [ - `description` (mcpp 2026.11.21.1+) is one line for a reader of the package's features, as `[package] description` is for the package. It changes nothing in a build; an index descriptor's `features.` accepts it too. The array - shorthand has none. + shorthand has none. Every feature of + [`examples/11-features`](../examples/11-features/) states one. ### Reading a package's features (mcpp 2026.11.21.1+) diff --git a/docs/09-commands-by-scenario.md b/docs/09-commands-by-scenario.md index 575313d72..4536fb7af 100644 --- a/docs/09-commands-by-scenario.md +++ b/docs/09-commands-by-scenario.md @@ -102,10 +102,16 @@ cache gc`): an ok image's prepared copies and snapshots for another boot After a successful build, at most once a day, every entry -- package, host tool or `std` -- that no build has used for `[cache] unused_days` days (config.toml; default 30, `0` turns it off) is removed. A hit marks an entry used. A `path` -host tool's or `path` dependency's entry is replaced when its tree changes: the -entry built from the same tree under the previous digest of its content is -removed as the new one is written (host tools 2026.10.31.3+, dependencies and -the content digest 2026.11.19.1+). Before a build, mcpp warns when the file system it writes to +host tool's or `path` dependency's entry records the trees that use it, one +file per tree in the entry's `users/` (2026.11.27.1+). When a tree changes, the +build that writes or hits the entry of its new content withdraws the tree from +the entries of the same package under the previous digests, and removes an +entry left with no user; an entry another tree still uses is kept (host tools +2026.10.31.3+, dependencies and the content digest 2026.11.19.1+, the users +2026.11.27.1+). The `source` record an earlier mcpp wrote is read as the first +user and is not rewritten, so an earlier mcpp sharing the home removes none of +the new entries. A tree whose checkout is deleted is never withdrawn; its +entries go by last use. Before a build, mcpp warns when the file system it writes to has less free space than the larger of 2 GiB and 1.25 times what the configuration's last build wrote (recorded in `/.mcpp-written`); the warning states both (2026.11.8.1+). `mcpp cache prune` and `mcpp cache gc diff --git a/docs/20-toolchains.md b/docs/20-toolchains.md index 52b5c4472..f73695566 100644 --- a/docs/20-toolchains.md +++ b/docs/20-toolchains.md @@ -1002,7 +1002,10 @@ give such a payload a descriptor, refresh the index first and then reinstall: again, because the index is refreshed when a resolution misses and not because a recipe changed; measured in the sandbox verification of 2026.9.12.2. Until then the failure is the interpreter's own (`/usr/bin/env: 'node': No such file or -directory`), which mcpp does not yet explain (#621). +directory`). Before `mcpp run` and `mcpp test` execute an artefact directly, +they read its `#!` line, and when the program it names is not there (`node` on +no directory of the artefact's PATH) a note names that program and gives these +three steps as a `help:` line, with the spec of the toolchain the build used. For a target whose artifact runs elsewhere, the `runner` key is an argv prefix and the session belongs to a package rather than to the engine: @@ -1946,19 +1949,17 @@ toolchain's libraries first. both the C and C++ compile channels. It reaches every TU in the package — module interface units included — so it also reaches the compiler's own P1689 module scan. -> **It does not make a macro-guarded `import` acceptable.** mcpp runs its own -> lexical pre-scan before the compiler ever sees the file, and that scanner -> rejects an `import` inside **any** `#if` / `#ifdef` block without evaluating the -> condition: -> -> ``` -> error: import statement inside conditional preprocessor block (forbidden in M1) -> ``` -> -> So a `#ifdef FOO` / `import bar;` pair fails even when `FOO` is in `defines`. -> Put the conditional around an `#include` in the global module fragment instead. -> Tracked as mcpp-community/mcpp#421. Assembly units pick it up too. It is a -build input like any other, so `[target.'cfg(...)'.build]` can carry it: +> **A macro-guarded `import` follows its condition (2026.11.27.1+).** mcpp's +> lexical pre-scan marks a unit whose `import` stands inside an `#if` / `#ifdef` +> block, and that unit's imports are taken from the compiler's dependency scan, +> run with the unit's own compile words, `defines` included. A +> `#ifdef FOO` / `import bar;` pair therefore imports `bar` exactly when `FOO` +> is defined (on GCC, and on Clang through `clang-scan-deps`; refused under +> MSVC, which has no scan at planning). Header units are still refused. Before +> 2026.11.27.1 the pre-scan refused every such unit (mcpp#421, mcpp#1026). + +Assembly units pick `defines` up too. It is a build input like any other, so +`[target.'cfg(...)'.build]` can carry it: ```toml [build] diff --git a/docs/22-target-side.md b/docs/22-target-side.md index 037bca515..300e4a59b 100644 --- a/docs/22-target-side.md +++ b/docs/22-target-side.md @@ -92,6 +92,27 @@ when the C library is also the payload's. A compiler runtime must belong to the compiler's own family, since a build in which the two disagree resolves `__udivti3` differently from every other link in the same program. +A graph that supplies the C library and no C++ ABI is refused at planning +(2026.11.27.1+). When the `c-abi` supplier comes from the graph, no package +supplies `c++-abi`, a unit imports the standard library module, the toolchain +has one, and the manifest states no `[build] cxx_runtime`, the plan stops with +`[layer-requirement]` before anything is compiled: + +``` +error: the graph supplies the C library (musl, acme.musl@1.2.5) and no package supplies the C++ ABI. + The standard library module is compiled with the toolchain's C++ library, which is + built against another C library. + help: add a dependency that provides `mcpp:c++-abi`, or state [build] cxx_runtime = "host-coupled" +``` + +The remedy names the capability rather than a package: which package provides +it is a fact of the index. A toolchain with no standard library module for the +target is refused by the target's own reason instead (on a row whose loader +supplies the operating system: a C++ run-time inside the program). Before, the +standard library module's precompile failed inside the toolchain's headers +(`features.h` not found under GCC 16.1, `__config` under LLVM 23.1), and nothing +named the decision (mcpp#898). + ### Cross-Origin Wiring The engine wires two layers together only when they come from different diff --git a/docs/23-the-project-environment.md b/docs/23-the-project-environment.md index 087b53bd8..3f1a63e68 100644 --- a/docs/23-the-project-environment.md +++ b/docs/23-the-project-environment.md @@ -50,24 +50,47 @@ which one is a fact about the project rather than about the machine. Chapter 8 covers the binding, the degradation rules, and what a SubOS that does not describe itself does to them. -**The tools a build program sees** (mcpp 2026.8.25.1+). The declared -environment's `bin` goes to the front of the `PATH` that `build.mcpp` runs -with: +**The tools a child process sees** (mcpp 2026.8.25.1+; one composition for +every child 2026.11.27.1+). mcpp starts three kinds of child process -- a build +program, a test, the program of `mcpp run` -- and each receives a `PATH` +composed by one function, the same on every host: ``` -PATH=: +PATH=:: ``` -A build program that spells `qemu-system-riscv64` as a bare name therefore gets -the copy inside the declared environment. Chapter 7 covers the contract this -rides on. +The first part is the `bin` of each payload the graph's `[xlings.workspace]` +entries install, the project's and its dependencies'; the second is present +only when the project declares an environment. A build program that spells +`qemu-system-riscv64` as a bare name therefore gets the copy the graph or the +declared environment states, and a test that runs a tool stated with +`when = "run"` finds it on every host. Before 2026.11.27.1 a build program's +`PATH` had the last two parts only, and a test's had the toolchain's +environment `bin` in front, on Linux only (mcpp#926). Chapter 7 covers the +contract this rides on. **Only for projects that declare one.** A project with no `[xlings].subos` -gets the `PATH` mcpp was started with, byte for byte. Putting a shared -directory in front of every project would make what a build sees depend on what -else had been installed on that machine — two projects on one machine would -agree with each other, and the same project on two machines would not. -Declaring it is what puts it there. +gets no environment `bin`: what its children see is what its graph states, then +the `PATH` mcpp was started with. Putting a shared directory in front of every +project would make what a build sees depend on what else had been installed on +that machine -- two projects on one machine would agree with each other, and +the same project on two machines would not. Declaring it is what puts it there. +Outside Windows, a test of such a project keeps the `bin` of the environment +the toolchain is installed in behind the stated tools, as before 2026.11.27.1, +under the compatibility reading `implicit-default-environment` +([51](51-supported-versions.md)) until that row's floor; on Windows that +directory holds the toolchain's `cl` and `link` stand-ins, which are no tool of +the project, and it is never given (mcpp#726). + +**The libraries follow the same rule.** The union view of an environment +(`subos//lib`) holds whatever was ever installed in it; for a project that +declares no environment that is the machine's default one. A library an +artifact finds there and nowhere the plan states -- a payload, a package's +`[runtime]` directory, the build's own output -- is reported once per build as +`implicit-default-environment`, naming the artifact and the library, because +this machine has it and a clean one may not. The remedy is to state the package +that provides it, or to declare `subos = "default"`, after which the view is the +project's own and nothing is reported. **Prefixed, not replaced.** A build program legitimately calls `git`, `python3` or a shell, and none of those live in a SubOS. Front position makes diff --git a/docs/25-home-indices-and-store.md b/docs/25-home-indices-and-store.md index ea2e0e197..442827f10 100644 --- a/docs/25-home-indices-and-store.md +++ b/docs/25-home-indices-and-store.md @@ -98,6 +98,21 @@ For a redirected home it names the effective target before resetting it. `--system self init --home` is refused. The exact selection and persistence rules are in [SPEC-010](specs/home-initialization.md). +**The home keeps the spelling it is given (2026.11.27.1+).** A home named +through a symbolic link is used under that name: mcpp makes the path absolute +and lexically normal, and opens files and starts programs under it, so `mcpp +self env` and every path handed to a tool show the directory the user named. +The physical path decides only whether two paths are one object -- a home +borrowed from an upstream, a project inside the home. When that cannot be +decided, because a parent directory is not accessible, the comparison falls +back to the spelling and the build reports it as degraded, naming the +decision. A key built from a path (a cache entry's user, a plan's work +directory) uses the spelling too: two spellings of one tree make two keys, +which costs one more entry and gives no wrong result. Before, the home was +resolved to its physical path when it was read (mcpp#1024). A check in CI holds +the number of physical-path calls outside the one identity function to a +baseline that only shrinks. + ### Initialization and network diagnosis (2026.10.19.1+) `self env`, `self config`, `self doctor` and `toolchain list` read local state diff --git a/docs/30-build-mcpp.md b/docs/30-build-mcpp.md index 859065f93..cc983b47d 100644 --- a/docs/30-build-mcpp.md +++ b/docs/30-build-mcpp.md @@ -1883,9 +1883,24 @@ also after a checkout or a copy that changed every modification time. Measured on [`examples/12-a-new-device-language`](../examples/12-a-new-device-language/); before this rule the key held the version alone and a change to the emitter left `mcpp run` printing the previous answer until the version was bumped. -The entry built from the same tree under the previous digest is removed when -the new one is written; `mcpp cache clean` empties the store, which lives at -`/tool//@[+]/`. +An entry records the trees that use it, as a `path` dependency's entry does +([09](09-commands-by-scenario.md)): when an edited tree writes or hits the entry +of its new digest, it is withdrawn from the entries under the previous digests, and an +entry left with no user is removed *(2026.11.27.1+; before, the entry built from +the same tree under the previous digest was removed whoever used it)*. `mcpp +cache clean` empties the store, which lives at +`/tool//@[+]/`. The store is shared +under every `--cache` mode: `local` and `off` apply to the dependencies a tool's +build compiles, not to where the tool is kept. + +**An entry holds the tool and the shared objects it loads (2026.11.27.1+).** A +tool whose link reads a shared library its own build produced -- a package of +its graph linked `shared` -- loads that library from its own directory, which +its RPATH names as `$ORIGIN`. The entry holds the executable and each such +library with its aliases, published by one step, and lists them in the entry's +`shared-objects`; an entry that lacks one of them is not valid and is built +again. Before, the store published the executable alone, and such a tool failed +to start from the store (mcpp#535). **The paths a tool build writes are bounded (2026.9.15.2+).** The sub-build runs in `/tool/.build//`, a directory named by the entry diff --git a/docs/35-platforms.md b/docs/35-platforms.md index 012519117..31a78e28c 100644 --- a/docs/35-platforms.md +++ b/docs/35-platforms.md @@ -428,7 +428,12 @@ what precedes the suffix, and the name ends in it once. The built-in beside `app.wasm`. `link-without-main` (2026.11.20.1+) gives the link words of an executable with no program start (`main = false`, see 04 — `main = false`); a row that states none refuses `main = false` for its executables. The built-in -`wasm32-emscripten` row states `["--no-entry"]`. A machine +`wasm32-emscripten` row states `["--no-entry"]`. `dlopen-static-tls` +(2026.11.27.1+) is the number of bytes of the static TLS block the row's loader +serves an image loaded by `dlopen` whose objects use the initial-exec model +(`DF_STATIC_TLS`): a shared image above it is reported after the link, and +refused when its exact `exports` say a host loads it by name. A row that states +none is not checked; the built-in glibc rows state 512. A machine runs another architecture's programs only where the execution table states it (`[[platform.executes]]`, SPEC-016 §2.4); there a `same-arch` runner is built for the artifact's architecture and started on this machine. diff --git a/docs/50-machine-output.md b/docs/50-machine-output.md index f433b26bf..459a3e081 100644 --- a/docs/50-machine-output.md +++ b/docs/50-machine-output.md @@ -669,6 +669,9 @@ a program classifying the outcome reads `reason`: | `accel-backend-undeclared` | a `[build] sources` entry names a backend its own package does not list in `[package] accelerators` | | `device-source-unconsumed` | a device-kind source reached no action, so nothing compiles it | | `host-module-missing` | `build.mcpp` imports a module no dependency supplies as a host module | +| `runtime-closure` | an image's `DT_NEEDED` is not answered at load time by the file its link read for it: no file on the image's search path answers it, or another file of that name does (2026.11.27.1+) | +| `static-tls-image` | a shared image whose exact `exports` say a host loads it by `dlopen` asks for the static TLS block (`DF_STATIC_TLS`) with more than the C library serves to such an image (2026.11.27.1+) | +| `soname-collision` | two shared libraries of one build are loaded by one name, their file name or a stated `soname` (2026.11.27.1+) | | `build-program-unpublished-input` | `mcpp publish`: the package's build program reads a file its archive does not carry -- one outside the package's directory, or one HEAD does not track (2026.11.21.1+) | | `companion-too-old` | a companion stated beside the toolchain (`companions = { binutils = … }`) is older than the one the toolchain's payload declares (SPEC-006 §2.9) | | `tool-version-conflict` | two declarations name one xlings package at versions that cannot both hold | diff --git a/docs/51-supported-versions.md b/docs/51-supported-versions.md index 2d5273fee..6b46bac18 100644 --- a/docs/51-supported-versions.md +++ b/docs/51-supported-versions.md @@ -85,6 +85,9 @@ the rows of this table (mcpp 2026.10.11.1+). | `no-universal-flag`: `mcpp pack --no-universal`, which a pack of one target no longer needs (refused with a target set) | 2026.10.30.1 | 2027.1 | `--target -` (one leg) | | `quoted-dotted-dependency-key`: a quoted dependency key with dots (`"mcpplibs.cmdline" = "0.0.2"`), one TOML key read as the selector its dots spell; not where it is the only spelling of a package beside its parent or child (docs/05) | 2026.11.8.1 | 2027.2 | the selector unquoted, `mcpplibs.cmdline = "0.0.2"` | | `ambiguous-contract-name`: a build program's question (`dep_dir`, `dep_linkage`, `dep_bin`, `xpkg_dir`) by a name whose contract variable several dependencies or payloads answer, answered by the first | 2026.11.21.1 | 2027.2 | the exact spelling: a qualified name, or `xpkg_dir("", "")`; where no spelling tells them apart, one of the packages renamed | +| `reopened-dotted-table`: a table that a `[header]` reopens after dotted keys defined it (`[dependencies.compat]` after `compat.libpng = ...` under `[dependencies]`), which TOML 1.0 refuses | 2026.11.27.1 | 2027.3 | the header's entries as dotted keys of the table they extend, `compat.zlib = ...`; the next `mcpp add` to that table writes them so | +| `implicit-default-environment`: for a project that states no environment, the union of what the machine's default environment has installed: its libraries on the run-time search path and the link's `--sysroot`, its `bin` on a test's PATH outside Windows | 2026.11.27.1 | 2027.3 | a dependency on the package that provides the library or tool, or `[xlings] subos = "default"` to state the shared environment | +| `unmatched-exact-export`: an `exports` entry without a wildcard that names a symbol the shared image does not define, dropped from the published set without a word | 2026.11.27.1 | 2027.3 | the name the image defines (its mangled form for a C++ name, or the function declared `extern "C"`), or the entry under the `[target.]` that defines it | ## Reproducing a build diff --git a/docs/specs/README.md b/docs/specs/README.md index 34da95247..1db188936 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -31,9 +31,9 @@ | 编号 | 标题 | 状态 | 最后修改 | 对应实现 | |---|---|---|---|---| | [SPEC-001](package-identity.md) | 包身份(`package.namespace` / `package.name`)、`[dependencies]` 选择器与匹配机制 | 评审中 v1.13 | 2026-11-21 | mcpp >= 0.0.106;§3.5 与 §10.4 mcpp >= 2026.11.19.1;§4.5、§3.5 的 `installed_manifest` 与 §10.4 第 7 条 mcpp >= 2026.11.21.1 | -| [SPEC-002](target-side.md) | 目标侧模型与能力声明(`mcpp:` 保留命名空间、五层、三条规则、目标侧执行、一个进程一套 C++ 运行时) | 评审中 v1.12 | 2026-11-23 | mcpp >= 2026.8.24.2;§2.4 与 §6 mcpp >= 2026.10.24.1;§2.2 的对象形式与 §7 mcpp >= 2026.10.26.1;§2.5 与 §3.8 mcpp >= 2026.11.10.1;§3.6 以目标的解析判断 mcpp >= 2026.11.19.1;§3.9 与 §3.10 mcpp >= 2026.11.23.1 | +| [SPEC-002](target-side.md) | 目标侧模型与能力声明(`mcpp:` 保留命名空间、五层、三条规则、目标侧执行、一个进程一套 C++ 运行时) | 评审中 v1.13 | 2026-11-27 | mcpp >= 2026.8.24.2;§2.4 与 §6 mcpp >= 2026.10.24.1;§2.2 的对象形式与 §7 mcpp >= 2026.10.26.1;§2.5 与 §3.8 mcpp >= 2026.11.10.1;§3.6 以目标的解析判断 mcpp >= 2026.11.19.1;§3.9 与 §3.10 mcpp >= 2026.11.23.1;§3.11 mcpp >= 2026.11.27.1 | | [SPEC-003](exit-codes.md) | 退出码契约(分类、语义、稳定性承诺) | 评审中 v1.2 | 2026-10-26 | mcpp >= 2026.9.1.1;`5` 与信号 mcpp >= 2026.10.26.1 | -| [SPEC-004](manifest-semantics.md) | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | 草案 v1.29 | 2026-11-23 | 条件化形状 mcpp >= 2026.8.29.1;目标轴 mcpp >= 2026.9.6.4;`linkage` 默认值 mcpp >= 2026.9.15.2;链接 flag 的词读法 mcpp >= 2026.9.26.2;条件化的 `dialect_cxxflags` 与 `-p` 的包身份 mcpp >= 2026.9.28.1;条件表按具体程度生效 mcpp >= 2026.9.28.2;平台前缀规约 mcpp >= 2026.10.5.1;根包的继承、根位置的 profile、链接 flag 的作用域、链接期优化与导出发现 mcpp >= 2026.10.5.2;架构段的 `x86` 即 `i686` mcpp >= 2026.10.5.3;前缀即语义与工作空间层 mcpp >= 2026.10.10.1;依赖的库与配置(§12) mcpp >= 2026.10.11.1;值的四档层次与 `run_under` mcpp >= 2026.10.24.1;§12 第 3 条一个程序一个版本 mcpp >= 2026.11.19.1;§9 第 21 至 23 条与 §16 mcpp >= 2026.11.21.1;v1.29 条款 mcpp >= 2026.11.23.1 | +| [SPEC-004](manifest-semantics.md) | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | 草案 v1.30 | 2026-11-27 | 条件化形状 mcpp >= 2026.8.29.1;目标轴 mcpp >= 2026.9.6.4;`linkage` 默认值 mcpp >= 2026.9.15.2;链接 flag 的词读法 mcpp >= 2026.9.26.2;条件化的 `dialect_cxxflags` 与 `-p` 的包身份 mcpp >= 2026.9.28.1;条件表按具体程度生效 mcpp >= 2026.9.28.2;平台前缀规约 mcpp >= 2026.10.5.1;根包的继承、根位置的 profile、链接 flag 的作用域、链接期优化与导出发现 mcpp >= 2026.10.5.2;架构段的 `x86` 即 `i686` mcpp >= 2026.10.5.3;前缀即语义与工作空间层 mcpp >= 2026.10.10.1;依赖的库与配置(§12) mcpp >= 2026.10.11.1;值的四档层次与 `run_under` mcpp >= 2026.10.24.1;§12 第 3 条一个程序一个版本 mcpp >= 2026.11.19.1;§9 第 21 至 23 条与 §16 mcpp >= 2026.11.21.1;v1.29 条款 mcpp >= 2026.11.23.1;§9 第 24 条、§11 第 7 与 8 条、§17 mcpp >= 2026.11.27.1 | | [SPEC-005](build-database.md) | 构建数据库:`mcpp emit build-database` 的内容、取值规则与不写工程目录的保证 | 评审中 v1.10 | 2026-11-23 | mcpp >= 2026.9.15.1;v1.3 条款 mcpp >= 2026.9.26.2;v1.4 条款 mcpp >= 2026.9.27.1;v1.5 条款 mcpp >= 2026.9.28.1;v1.6 条款 mcpp >= 2026.9.29.5;v1.7 条款 mcpp >= 2026.9.30.2;v1.8 条款 mcpp >= 2026.10.11.1;v1.10 条款 mcpp >= 2026.11.23.1 | | [SPEC-006](toolchain-management.md) | 工具链管理:身份、来源、选择与载荷契约 | 草案 v0.14 | 2026-11-23 | 逐条标注;已实现条款 mcpp >= 2026.9.24.1;§3.7 mcpp >= 2026.9.28.1;§3.7.1 mcpp >= 2026.9.28.2;§2.2.1 与 §3.3 的非缺省来源 mcpp >= 2026.10.1.3;§3.8 mcpp >= 2026.10.8.1;§3.9 至 §3.11 mcpp >= 2026.10.24.1;v0.11 条款 mcpp >= 2026.11.10.1;v0.14 条款 mcpp >= 2026.11.23.1 | | [SPEC-007](build-plugins.md) | 构建插件:配置、施工与校验的分工,运行时与规划期的义务 | 草案 v0.16 | 2026-11-21 | 逐条标注;mcpp >= 2026.9.26.2;v0.3 条款 mcpp >= 2026.9.27.1;v0.4 条款 mcpp >= 2026.9.28.1;v0.5 条款 mcpp >= 2026.9.28.2;v0.6(§9)mcpp >= 2026.9.28.3;R3.9、R3.10 mcpp >= 2026.10.10.1;§10 mcpp >= 2026.10.11.1;§3.1 协议 18 mcpp >= 2026.11.5.1;协议 19 mcpp >= 2026.11.16.1;协议 20、R10.7 mcpp >= 2026.11.19.1;协议 21、R10.8–R10.10 mcpp >= 2026.11.21.1 | @@ -45,10 +45,10 @@ | [SPEC-013](platforms.md) | 平台:`[platform]` 的七组键、版本组与 `hosted`,三种写法与层次,目标图与宿主图的选择,`cfg(platform)`,依赖图的补全,链接、命名与封装,运行器与载体,平台阶段与协议 17 | 评审中 v1.17 | 2026-11-23 | mcpp >= 2026.10.27.1;§10 的执行宿主与 §11 的载体架构 mcpp >= 2026.10.29.1;§7.5 版本组参与解析与 §14 平台系列 mcpp >= 2026.11.7.1;§14 内置平台为确切版本 mcpp >= 2026.11.7.2;v1.7 条款 mcpp >= 2026.11.10.1;§14 索引的平台列 mcpp >= 2026.11.17.1;§14 系列取可用的最新版本与 §15.1 的 `+b` 条目 mcpp >= 2026.11.19.1;v1.17 条款 mcpp >= 2026.11.23.1 | | [SPEC-014](packaging.md) | 打包与分发:链接、闭包、容器三个维度与构建腿,腿的合并,暂存树与 `mcpp-package.json`,平台的树、运行覆盖、单文件、polyglot、容器列表、签名、压缩、合并与分发描述 | 评审中 v2.2 | 2026-11-10 | mcpp >= 2026.10.31.1;逐条标注;v2.2 条款 mcpp >= 2026.11.10.1 | | [SPEC-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-016](targets-and-providers.md) | 目标与提供者:行、提供者、选择规则、平台定义的行、C 环境与执行、报告、机器输出与锁 | 评审中 v1.10 | 2026-11-27 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.9 条款 mcpp >= 2026.11.23.1;v1.10 条款 mcpp >= 2026.11.27.1 | | [SPEC-017](test.md) | mcpp 测试规范:测试程序、测试协议、记录、存储、启动描述与框架声明;基础能力 B1–B6 与可选能力 O1–O12 | 评审中 v2.6 | 2026-11-21 | mcpp >= 2026.11.8.1;逐条标注;B5、B6 的新键、O3 的运行器一侧、O8 mcpp >= 2026.11.10.1;O9 mtest >= 0.6.0;O10 mcpp >= 2026.11.13.1;O11、O12 与 P5.6 mcpp >= 2026.11.21.1 | -| [SPEC-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 | +| [SPEC-018](module-rebuilds.md) | 模块的重编译:按 BMI 内容截断,GCC 的时间戳与行映射,`bmi_cutoff`,构建目录的记录 | 评审中 v1.2 | 2026-11-27 | mcpp >= 2026.11.17.2;§1 第 6 条 mcpp >= 2026.11.27.1 | +| [SPEC-019](build-optimizations.md) | 构建优化:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | 评审中 v1.2 | 2026-11-26 | mcpp >= 2026.11.17.2;§5、§9 的新增自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.1 | ## 文档约定 diff --git a/docs/specs/build-optimizations.md b/docs/specs/build-optimizations.md index b3cfc1588..4b42108c8 100644 --- a/docs/specs/build-optimizations.md +++ b/docs/specs/build-optimizations.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-019 | | 标题 | mcpp 在标准构建之外所做的事:登记表、级别、接缝、总开关,私有模块片段作为独立单元,构建后的建议,失败时的提示 | -| 状态 | 评审中 v1.1 | -| 版本 | 1.1 | +| 状态 | 评审中 v1.2 | +| 版本 | 1.2 | | 最后修改 | 2026-11-26 | -| 对应实现 | mcpp >= 2026.11.17.2;§5 第 4、7、8 条与 §9 自 2026.11.26.1 | +| 对应实现 | mcpp >= 2026.11.17.2;§5 第 4、7、8 条与 §9 自 2026.11.26.1;§9 第 5 条的后半自 2026.11.27.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) | @@ -172,7 +172,10 @@ int f() { return 1; } → module m; // 实现单元 (GCC 上为 `conservative`)、`MCPP_BMI_CUTOFF=exact mcpp build`;并写出 `MCPP_BUILDOPT=off` 是下一级。两步之后失败依旧,原因不在这些条目之中。 5. 构建图与此前的取值不同时,第一次构建**必须**按新的取值重新生成图:`MCPP_BUILDOPT`、 - `MCPP_PRIVATE_FRAGMENT`、`MCPP_BMI_SCHEDULE` 是快速路径所比较的请求的一部分。 + `MCPP_PRIVATE_FRAGMENT`、`MCPP_BMI_SCHEDULE` 的陈述是图自身所记的请求(`build.ninja` 首行的 + `request=`)的一部分,快速路径在重放之前比较它。这一陈述**禁止**只记在构建的记录里:记录由成功的 + 构建写下,而用来核对的陈述正是给失败的构建用的。核对的那一次构建无论成功还是失败,其后不带陈述、 + 没有编辑的构建**必须**与核对之前的那一次相同。 6. 提示所读的计划数据写在构建目录的 `buildopt-applied.tsv`,快速路径(没有计划)读同一个文件。 ## 变更记录 @@ -181,3 +184,4 @@ int f() { return 1; } → module m; // 实现单元 |---|---|---| | 1.0 | 2026-11-17 | 首版(mcpp 2026.11.17.2):登记表、级别、接缝、总开关;私有模块片段作为独立单元;构建后的建议;语义提供者的边界;四项已记录、未实现 | | 1.1 | 2026-11-26 | 私有片段的判定:条件指令与 `#error`、`#warning` 放行,条件须在声明与片段处闭合;词法修正(数字分隔符、原始字符串、`extern "C"`、行连接);取值 `conservative`;登记表的 `check`;新增 §9 失败时的提示;§8 记录 clang 读者的实测结论 | +| 1.2 | 2026-11-26 | §9 第 5 条:决定图的形态的陈述记在图自身的请求里,不记在构建的记录里;核对失败之后的构建与核对之前相同(mcpp 2026.11.27.1) | diff --git a/docs/specs/manifest-semantics.md b/docs/specs/manifest-semantics.md index bdcfa008d..5497d12e6 100644 --- a/docs/specs/manifest-semantics.md +++ b/docs/specs/manifest-semantics.md @@ -5,8 +5,8 @@ | **规范编号** | SPEC-004 | | **标题** | `mcpp.toml` 的平面划分、条件化形状、解析轴与命名规约 | | **状态** | **草案(Draft)** | -| **版本** | 1.29 | -| **最后修改** | 2026-11-23 | +| **版本** | 1.30 | +| **最后修改** | 2026-11-27 | | **最低实现版本** | 条件化形状:mcpp **2026.8.29.1**(`[target..build-dependencies]` 起齐备);目标轴:mcpp **2026.9.6.4** | | **作者/维护** | mcpp-community | | **相关设计文档** | `.agents/docs/2026-09-07-mcpp-toml-unified-semantics-design.md`
`.agents/docs/2026-06-04-manifest-schema-ownership.md`
`.agents/docs/2026-09-03-xlings-workspace-as-the-one-table.md`
`.agents/docs/2026-09-25-issue-690-workspace-build-inheritance-consistency.md`
`.agents/docs/2026-09-27-eight-reports-by-home-and-one-optimisation-plan.md`
`.agents/docs/2026-10-05-std-module-pair-msvc-lto-and-export-discovery-design.md`
`.agents/docs/2026-10-06-windows-x86-arch-vocabulary-and-rc-follow-ups-design.md`
`.agents/docs/2026-10-10-one-source-one-meaning-design.md`
`.agents/docs/2026-10-11-build-dependencies-one-pipeline-design.md`
`.agents/docs/2026-10-23-target-base-and-execution-host-design.md`
`.agents/docs/2026-10-26-control-contract-runtime-and-ide-ecosystem-design.md`(§24) | @@ -728,13 +728,21 @@ mcpp 2026.9.26.2,#703)。** `MCPP_ARCHIVES`(分隔方式与 `PATH` 相同)、清单的 `[xlings] archives`(相对于清单所在目录)、机器的 `config.toml` 的同名键(相对于该文件)、引擎的空列表;只读构建的根。清单写明的工程之外的目录是机器的事实, 在一个工程中提示一次(`machine-path-in-manifest`)。 +24. **profile 的编译词的作用域。** `[profile.<名>] cflags`、`cxxflags` 是根位置的键:到达构建的根(根包、被选中的 + 成员)的单元,与 `[build] cflags`、`cxxflags` 相同;作为依赖被编译的成员与路径依赖不收到它们。`opt`、`debug`、 + `ndebug` 与 `ldflags` 到达整张图。`[profile.<名>] dialect_cxxflags` 的含义与到达范围与 `[build] dialect_cxxflags` + 相同(标准库模块的预编译、扫描与每个 C++ 单元),在其后追加;工作空间层的 profile 同样接受,按第 12 条合并。 + 需要整图一致的词(检测器、体积选项)写进它。C 单元没有对应的键:整图一致是 BMI 与标准库模块对 C++ 单元的 + 要求,C 单元之间没有这种耦合,包的 C 编译词是包自己的。profile 中这些键与 `opt`、`debug`、`lto`、`strip`、 + `ndebug`、`trim_paths`、`bmi_cutoff`、`split_debuginfo`、`dependency_linkage`、`dependency_debug` 之外的键 + **必须**被报告并忽略。使用 `dialect_cxxflags` 的清单应当陈述 mcpp 下限:更早的版本不读这个键。 **状态:已实现(第 1 至 7 条 mcpp 2026.9.25.1;第 8 至 10 条 mcpp 2026.9.27.1,mcpp#713、 #714、#710;第 10 条的 `dialect_cxxflags` 为 mcpp 2026.9.28.1,#717;第 1 条的根包、第 10 条的 `[profile.]` 与第 11 条为 mcpp 2026.10.5.2,#771;第 7、8、10 条的工作空间层与第 12、13 条为 mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 mcpp 2026.10.11.1,#797; 第 17 条为 mcpp 2026.11.19.1,#953,其摘要为配置的函数与第 18 至 23 条为 2026.11.21.1,mcpp#986、 -#802、#927、#988、#990)。** +#802、#927、#988、#990;第 24 条为 mcpp 2026.11.27.1,mcpp#1025)。** ## 10. 依赖的程序 @@ -792,7 +800,18 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m 5. `[test] windows_code_page` 为所发现的每个测试程序陈述 Windows 代码页,取值与 target 键相同。 6. `windows_long_paths`(target 键与 `[test]` 键)陈述 PE 可执行文件是否声明 `longPathAware`;作为 host 工具构建的程序默认 `true`,其余默认不声明;写在库目标上被拒绝。 -**状态:已实现(mcpp 2026.10.5.2,#770)。** +7. **精确的导出名。** `exports` 中不含通配符(`*`、`?`、`[`)的条目是精确名,表示宿主按这个名字进入镜像(Java + 进程的 `JNI_OnLoad`、Python 的 `PyInit_<名>`、插件宿主的入口),它**必须**有定义;含通配符的条目是模式,只收窄 + 发布的集合,可以不匹配任何符号。精确名是链接器层面的符号名:C++ 的名字写修饰后的形式,或以 `extern "C"` 定义。 + ELF 的共享镜像在链接后读取其动态符号表核对;Mach-O 的链接器本身拒绝未定义的导出名;PE 的 `.def` 由对象定义的 + 符号写出。自 mcpp 2026.11.27.1 起,未定义的精确名以弃用项 `unmatched-exact-export` 报告(docs/51),到期之后是 + 构建错误。 +8. **依赖包的共享库的名字。** 依赖包的共享库以包的限定名命名,规整方式与对象目录相同(`.` 与 `/` 换为 `_`): + `compat.sdl3` 的目标 `sdl3` 是 `libcompat_sdl3.so`,名字与包不同的目标在包名之后加 `_<目标>`。缺省命名空间的包 + 以包名拼写,即它作为裸键的写法:与包同名的目标是 `libdepShared.so`,不同名的目标是 `libdep_depshared.so`。根包与被选中成员的共享库保持目标名。陈述的 `soname` 是它被加载的名字。一次构建中两个共享库以同一个名字加载时,规划**必须**拒绝 + (`soname-collision`)。 + +**状态:已实现(第 1 至 6 条 mcpp 2026.10.5.2,#770;第 7、8 条 mcpp 2026.11.27.1,mcpp#982、#975)。** ## 12. 依赖的库与配置 @@ -931,6 +950,25 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m **状态:已实现**(mcpp 2026.11.21.1,mcpp#992)。 +## 17. 依赖表与它们的写法 + +1. 一份清单在四种表中陈述依赖:`[dependencies]`、`[build-dependencies]`、`[dev-dependencies]`、 + `[feature-deps.<特性>]`,以及每种在 `[target.<选择器>]` 下的条件形式。加载、`mcpp add` 与 `mcpp remove` 的编辑、 + `mcpp publish` 的归一化读同一份枚举(`mcpp.manifest.dependency_tables`),三者**禁止**各自列出表。 +2. `mcpp add` 写入 `[dependencies]`;`--dev` 写入 `[dev-dependencies]`,`--build` 写入 `[build-dependencies]`。 + `mcpp remove` 以同样的旗标选择表,缺省为 `[dependencies]`。非缺省命名空间的条目:表中已有 `[<表>.<命名空间>]` + 表头时写为该节中的短键;否则写为 `[<表>]` 中的点号键 `<命名空间>.<名>`。缺省命名空间写裸键。 +3. 一个由点号键定义的表又被表头重新打开(或反之)是 TOML 1.0 的错误。mcpp 合并两者读取,并以弃用项 + `reopened-dotted-table` 报告(docs/51);编辑该表时,表头下的条目改写为点号键,表头移除。编辑**禁止**写出这种 + 重复定义。 +4. 发布的清单中,每一种表里离开包目录的 `path` 依赖由其版本代替;工作空间的成员无论目录在何处,都以它的版本发布, + 位于包目录内的成员同样如此。 +5. 一个包是不是构建插件由它的源文件回答(其库导入 `mcpp.core`,§12),不另设清单键。写在 `[dependencies]` 中的构建 + 插件按 §12 的兼容读法(`host-module-in-dependencies`)读作构建依赖,报告给出 `mcpp remove` 与 `mcpp add --build` + 两条命令。 + +**状态:已实现**(mcpp 2026.11.27.1,mcpp#962、#964、#993)。 + ## 变更记录 | 版本 | 日期 | 变更 | @@ -964,4 +1002,5 @@ mcpp 2026.10.10.1,#785、#786;第 14 至 16 条与第 13 条的依赖位置为 m | 1.26 | 2026-11-21 | mcpp 2026.11.21.1(mcpp#990,设计 2026-11-21 离线与缺省 §3.2):§9 第 22 条 `[build] offline` 与第 23 条 `[xlings] archives`,两者按 §2 的四层取值,一次运行陈述为一个变量。 | | 1.27 | 2026-11-21 | mcpp 2026.11.21.1(mcpp#992):新增 §16,特性的 `description`、一个目录项与查询回答的三种状态。 | | 1.28 | 2026-11-22 | mcpp 2026.11.22.1(设计 2026-11-22 §6.2):§9 第 12 条,生效的 `[indices]` 中一个位置只有一个名字,两项指向同一位置时拒绝(`index-location-named-twice`)。 | +| 1.30 | 2026-11-27 | mcpp 2026.11.27.1(设计 2026-11-27):§9 第 24 条 profile 的 `cflags`、`cxxflags` 的作用域与 `[profile.] dialect_cxxflags`,未知的 profile 键被报告(mcpp#1025);§11 第 7 条精确的导出名(mcpp#982)与第 8 条依赖包的共享库以限定名命名(mcpp#975);新增 §17 依赖表的单一枚举、`mcpp add --build` 与写法、重新打开的点号键表、发布对成员的改写(mcpp#962、#964、#993)。 | | 1.29 | 2026-11-23 | mcpp 2026.11.23.1(设计 2026-11-22 内核接口与派生状态 §3.1、§3.2):`layers.<层>` 的四种值,载荷与目录两种预制形式;平台键在没有平台的行上生效。 | diff --git a/docs/specs/module-rebuilds.md b/docs/specs/module-rebuilds.md index 59175b343..920783af4 100644 --- a/docs/specs/module-rebuilds.md +++ b/docs/specs/module-rebuilds.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-018 | | 标题 | 一次编辑之后哪些单元重新编译:按 BMI 内容截断、`bmi_cutoff`、构建目录的记录 | -| 状态 | 评审中 v1.1 | -| 版本 | 1.1 | -| 最后修改 | 2026-11-26 | -| 对应实现 | mcpp >= 2026.11.17.2;§2.1 的时间戳在 UTC 下自 2026.8 起成立 | +| 状态 | 评审中 v1.2 | +| 版本 | 1.2 | +| 最后修改 | 2026-11-27 | +| 对应实现 | mcpp >= 2026.11.17.2;§2.1 的时间戳在 UTC 下自 2026.8 起成立;§1 第 6 条 mcpp >= 2026.11.27.1 | | 相关设计文档 | `.agents/docs/2026-11-17-ninja-cascade-publish-supplement-design.md` §3 | | 相关 issue | #946 | | 使用文档 | [04 — mcpp.toml](../zh/04-mcpp-toml.md) 的 profile 一节 | @@ -34,6 +34,10 @@ ISO C++ 不定义 BMI,也不定义构建;一次编辑之后哪些单元重新编 影响:一个字节不同即为不同。 5. 工作区成员、`path` 依赖与 `git` 依赖在使用者的构建图中编译,截断对它们与对同一包的单元 相同;包不是编译边界。 +6. 一个 BMI 在构建图中是一个文件。编译器在依赖文件中以绝对路径书写它读过的 BMI 时(clang 经 + 绝对的 `-fprebuilt-module-path` 查找),写出该 BMI 的边(编译、预编译、暂存)**必须**同时以 + 这个拼写声明它为隐式输出,使导入者的依赖记录与图中的输出由同一条边写出、按同一个文件判定。 + 否则一次编辑改变了 BMI 之后,导入者的导入者要到下一次没有编辑的构建才重新编译(mcpp#1015)。 ## 2. 两个 BMI 的差别 @@ -129,3 +133,4 @@ BMI 中,函数的 32 位 ODR 哈希仍在,并随函数体变化;该哈希在记 |---|---|---| | 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 宽度翻转与偏移表) | +| 1.2 | 2026-11-27 | §1 第 6 条:一个 BMI 在图中是一个文件,依赖文件的绝对拼写由写出它的边一并声明(mcpp 2026.11.27.1,mcpp#1015) | diff --git a/docs/specs/target-side.md b/docs/specs/target-side.md index 063a97dea..f3864abbe 100644 --- a/docs/specs/target-side.md +++ b/docs/specs/target-side.md @@ -4,8 +4,8 @@ |---|---| | 规范编号 | SPEC-002 | | 标题 | 目标侧模型与能力声明(`mcpp:` 保留命名空间) | -| 状态 | 评审中 v1.12 | -| 最后修改 | 2026-11-23 | +| 状态 | 评审中 v1.13 | +| 最后修改 | 2026-11-27 | | 对应实现 | mcpp >= 2026.8.24.2;§2.2 的对象形式与 §7 mcpp >= 2026.10.26.1 | | 相关设计文档 | `.agents/docs/2026-08-24-target-side-design.md`、`.agents/docs/2026-10-23-target-base-and-execution-host-design.md`、`.agents/docs/2026-10-26-control-contract-runtime-and-ide-ecosystem-design.md` §6、`.agents/docs/2026-11-22-kernel-interface-and-derived-state-ecosystem-design.md` | | 使用文档 | [docs/22 - 目标侧](../zh/22-target-side.md) | @@ -267,6 +267,15 @@ hosted 与否是 C 环境的一个声明:提供 `hosted-standard-library` 的 sy 与构建程序的 `MCPP_KERNEL_ABI_INTERFACES`。接口在目标侧决定之后才可知,以该谓词选择依赖时按 §2.2 的层谓词 报告并忽略。 +### 3.11 依赖图换了 C 库而无人供给 C++ ABI 已实现(mcpp >= 2026.11.27.1) + +依赖图供给 `c-abi`、`c++-abi` 无人供给、某个单元导入标准库模块,且根的清单没有陈述 `cxx_runtime` 时,规划**必须** +在扫描之后、任何编译之前拒绝(`layer-requirement`):标准库模块以工具链的 C++ 库编译,而它建立在另一个 C 库之上, +否则失败发生在标准库头文件内部(GCC 16.1 的 `features.h`、LLVM 23.1 的 `__config`),不指出任何决定。补救有两个, +消息都写出:依赖一个提供 `mcpp:c++-abi` 的包,或陈述 `[build] cxx_runtime = "host-coupled"`。补救指名能力, +**禁止**指名包:哪个包提供它是索引的事实。工具链没有可导入的标准库模块时,这一条不适用,由目标自己的拒绝回答 +(例如操作系统由加载器提供的行:程序内需要一个 C++ 运行时)。只要求配置时,拒绝作为配置的说明给出,与源文件的其他拒绝相同。 + ### 3.5 目标表的约定何时生效 已实现 目标行的 `pin` 命名的是**供给该目标 C 库的载荷**,不是偏好的编译器。 @@ -457,3 +466,4 @@ hosted 与否是 C 环境的一个声明:提供 `hosted-standard-library` 的 sy | v1.10 | 2026-11-19 | 随 mcpp 2026.11.19.1:§2.5 基座的 C++ 层与依赖图供给的层的隔离词在每个宿主上写出,与载荷旁有无驱动的配置文件无关;`-stdlib=` 取该层的库名(mcpp#965)。 | | v1.11 | 2026-11-20 | 随 mcpp 2026.11.19.1:§3.6 缺省以目标的解析判断,只被构建程序持有的包不为目标提供能力(设计 2026-11-19 §21 A1)。 | | v1.12 | 2026-11-23 | 随 mcpp 2026.11.23.1(设计 2026-11-22):新增 §3.9 内核头文件(预制陈述、缺省的两个回答者、测量、接线、布局)与 §3.10 `kernel-abi` 的接口;§3.3 不再补上生态的内核头文件。 | +| v1.13 | 2026-11-27 | 随 mcpp 2026.11.27.1(设计 2026-11-27 §4.4):新增 §3.11,依赖图换了 C 库而无人供给 C++ ABI、又有单元导入标准库模块时,在规划期以 `layer-requirement` 拒绝(mcpp#898)。 | diff --git a/docs/specs/targets-and-providers.md b/docs/specs/targets-and-providers.md index 28e3cc16a..67d800382 100644 --- a/docs/specs/targets-and-providers.md +++ b/docs/specs/targets-and-providers.md @@ -4,10 +4,10 @@ |---|---| | 规范编号 | SPEC-016 | | 标题 | 目标与提供者:行、提供者、选择、平台定义的行、报告与锁 | -| 状态 | 评审中 v1.9 | -| 版本 | 1.9 | -| 最后修改 | 2026-11-23 | -| 对应实现 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.2 条款 mcpp >= 2026.11.12.1;v1.3 条款 mcpp >= 2026.11.16.1;v1.4 条款 mcpp >= 2026.11.17.1;v1.5 条款 mcpp >= 2026.11.18.1;v1.7 条款 mcpp >= 2026.11.20.1;v1.8 条款 mcpp >= 2026.11.22.1;v1.9 条款 mcpp >= 2026.11.23.1 | +| 状态 | 评审中 v1.10 | +| 版本 | 1.10 | +| 最后修改 | 2026-11-27 | +| 对应实现 | mcpp >= 2026.11.9.1;v1.1 条款 mcpp >= 2026.11.10.1;v1.2 条款 mcpp >= 2026.11.12.1;v1.3 条款 mcpp >= 2026.11.16.1;v1.4 条款 mcpp >= 2026.11.17.1;v1.5 条款 mcpp >= 2026.11.18.1;v1.7 条款 mcpp >= 2026.11.20.1;v1.8 条款 mcpp >= 2026.11.22.1;v1.9 条款 mcpp >= 2026.11.23.1;v1.10 条款 mcpp >= 2026.11.27.1 | | 相关设计文档 | `.agents/docs/2026-11-15-ecosystem-gap-supplement-design.md`、`.agents/docs/2026-11-09-target-model-design.md`、`.agents/docs/2026-11-10-cross-platform-ecosystem-design.md`、`.agents/docs/2026-11-12-ecosystem-architecture-optimization-design.md`、`.agents/docs/2026-11-22-kernel-interface-and-derived-state-ecosystem-design.md` | | 相关 issue | mcpp#911、mcpp#913 | | 相关规范 | [SPEC-001](package-identity.md)(引用文法)、[SPEC-002](target-side.md)(层与能力)、[SPEC-013](platforms.md)(平台的语句)、[SPEC-014](packaging.md)(打包)、[SPEC-015](target-sets.md)(目标集合) | @@ -37,7 +37,8 @@ 行的字段:`triple`(`-[-]`)、`tier`(verified、preview、planned)、`standard`、`exact`、`march`、`mabi`、 `code-model`、`multilib`、`flags`、`link-emulation`、`clang-triple`、`object-format`、`family`、`data-model`、`exe-suffix`、 -`shared-suffix`、`loader`、`execution`、`descriptor-keys`、`companions`、`exceptions`、`exe-suffix-fixed`、`link-without-main`。 +`shared-suffix`、`loader`、`execution`、`descriptor-keys`、`companions`、`exceptions`、`exe-suffix-fixed`、`link-without-main`、 +`dlopen-static-tls`。 - 一个系统可能用到两种以上 C 库时,身份**必须**含 env;env 即 C 库。业界原生标识无 env 段的系统,其原生身份为两段 (`aarch64-macos`),其余 C 库以 env 区分(`aarch64-macos-musl`)。 @@ -61,6 +62,11 @@ - `link-without-main` 是该行链接没有程序起点的可执行映像(`main = false`,SPEC-004 §14 第 6 条)时加入的链接词。 未写时该行的可执行映像有程序起点,`main = false` 被拒绝。内置的 `wasm32-emscripten` 行为 `["--no-entry"]`: 页面调用模块导出的函数,运行时不调用 `main`。程序形态为共享对象的行(Android 行上的 `app`)不读它(v1.7)。 +- `dlopen-static-tls` 是该行的加载器从静态 TLS 块中为一个以 `dlopen` 加载、其对象使用 initial-exec 模型(`DF_STATIC_TLS`) + 的映像提供的字节数,正整数。链接之后,TLS 段超过它的共享映像**必须**被报告;其精确 `exports`(SPEC-004 §11 第 7 条) + 表明宿主按名字进入它时**必须**被拒绝(`static-tls-image`)。未写时不检查。内置的 glibc 行(`x86_64-linux-gnu`、 + `aarch64-linux-gnu`、`i686-linux-gnu`)为 512,即 glibc 2.32 起 `glibc.rtld.optional_static_tls` 的缺省值。引擎不按 + C 库或系统的名字判断(v1.10)。 - `object-format`、`exe-suffix`、`shared-suffix` 按三级读取,先陈述者生效:行,行的系统(§2.3),对象格式的约定(v1.5)。 内置行与平台定义的行同一读法;引擎不按系统名判断,宿主的命名不为任何行作答。 @@ -279,4 +285,5 @@ | 1.6 | 2026-11-19 | mcpp 2026.11.19.1(mcpp#957):§6 执行可达性的谓词之前没有按系统的分支;Apple 的行由同一个谓词判定;系统名检查的词表含三元组的系统谓词 | | 1.7 | 2026-11-20 | mcpp 2026.11.20.1(mcpp#981):行的 `link-without-main`,没有程序起点的可执行映像的链接词;内置 `wasm32-emscripten` 行为 `--no-entry` | | 1.8 | 2026-11-22 | mcpp 2026.11.22.1(设计 2026-11-22 §4):`i686-windows-msvc` 为 preview 行;执行关系表中 `windows-x86_64` 执行 `i686`(§2.4)。 | +| 1.10 | 2026-11-27 | mcpp 2026.11.27.1(mcpp#907):行的 `dlopen-static-tls`;内置 glibc 行为 512 | | 1.9 | 2026-11-23 | mcpp 2026.11.23.1(设计 2026-11-22 §3.4、§3.17):系统表的 `kernel-abi`(测量、载荷布局、包)与 `interfaces`;`MCPP_KERNEL_ABI_INTERFACES` 在系统供给该层时取系统表的 `interfaces`;裸机行的 `--target` 取 `clang-triple`,平台定义的裸机行不写机器描述时也给出目标(mcpp#1006);平台定义的行取其提供者的 `linkage` | diff --git a/docs/zh/01-getting-started.md b/docs/zh/01-getting-started.md index 4b0e8bb08..dd06a0f27 100644 --- a/docs/zh/01-getting-started.md +++ b/docs/zh/01-getting-started.md @@ -70,6 +70,23 @@ mcpp --version > 命令安装,重启 PowerShell 而不是执行 `source`,并用 > `Get-Command mcpp.exe` 确认当前生效的命令。 +### Shell 补全(2026.11.27.1+) + +`mcpp self completion` 把一种 shell 的补全脚本——`bash`、`zsh`、`fish` 或 `powershell`,由参数指名、取自 +`SHELL`,或在 `SHELL` 未设置而 `PSModulePath` 已设置时为 `powershell`——写到 `/config/shell/`,并打印加载它的那一行。这一行写进 shell 自己的配置文件,mcpp 不修改该文件: + +``` +$ mcpp self completion bash + Wrote /home/user/.mcpp/config/shell/mcpp.bash +source '/home/user/.mcpp/config/shell/mcpp.bash' # in ~/.bashrc +``` + +脚本中没有 mcpp 的任何命令:它把光标之前的词交给 `mcpp __complete`,由 mcpp 按自己的命令树回答,因此之后的版本 +新增的命令或选项用同一个脚本即可补全。除子命令与选项之外,回答还包括当前目录清单中的 profile 与成员、`mcpp remove` +可接受的依赖、mcpp 有其行的目标、home 中已安装的工具链(`gcc@16.1.0`)以及本地索引副本中的包;包按依赖键的写法给出: +缺省命名空间的包给出裸名,所补全的词以 `mcpplibs.` 开头时给出限定名。补全只读取磁盘上已有的内容:不初始化 home, +不写入任何文件,也不下载任何东西。`--print` 把脚本写到标准输出而不是 home。 + ## 创建项目 ```bash diff --git a/docs/zh/04-mcpp-toml.md b/docs/zh/04-mcpp-toml.md index e296fef08..238990dca 100644 --- a/docs/zh/04-mcpp-toml.md +++ b/docs/zh/04-mcpp-toml.md @@ -395,6 +395,19 @@ loader 以及进程中的其它 ICD 相撞。 这个文件每行列一个符号模式,`#` 起一行注释,`*` 是唯一的通配符。内联 数组说的是同一件事,用于只有两三个入口点、单独开一个文件显得多余的场合。 +**不含通配符的条目是精确名(2026.11.27.1+)。** 它表示宿主按这个名字进入镜像(`JNI_OnLoad`、`PyInit_<名>`、 +插件宿主的入口),因此镜像必须定义它;模式只收窄集合,可以不匹配任何符号。名字是链接器层面的符号名: +C++ 函数写修饰后的形式,或以 `extern "C"` 定义。ELF 上,链接之后读取共享镜像的动态符号表,镜像未定义的 +精确名以弃用项 `unmatched-exact-export` 报告([docs/51](51-supported-versions.md)),到移除月份后是构建错误; +Mach-O 上 ld64 本身拒绝这种名字。只在部分目标上有定义的名字写在定义它的 `[target.]` 下。 + +**要求静态 TLS 块的共享镜像被报告(2026.11.27.1+)。** 以 initial-exec TLS 模型编译的对象使库带上 +`DF_STATIC_TLS`。随程序在启动时加载可以运行;以 `dlopen` 加载时,加载器从静态块的剩余部分为它分配线程局部存储, +剩余的大小由目标行陈述(`dlopen-static-tls`,[35](35-platforms.md);glibc 行为 512 字节,即 glibc 的 +`glibc.rtld.optional_static_tls`)。超过它的库连同其大小被报告;精确 `exports` 表明宿主按名字加载它的库被拒绝 +(`static-tls-image`)。未陈述界限的行不检查。共享库的代码以 `-ftls-model=global-dynamic` 编译, +这是编译器在 `-fPIC` 下的缺省。 + 一句陈述,三种渲染: | 平台 | 渲染为 | @@ -768,6 +781,15 @@ dependency_linkage = "shared" # per profile 通过 `$ORIGIN`(ELF)/ `@loader_path`(Mach-O)/ 可执行文件自己所在 的目录(PE)在构建目录被移动之后仍能重新找到它。 +**依赖包的共享库以包命名** *(2026.11.27.1+)*。它的文件名与 SONAME 取包的限定名,由命名包的对象目录的同一个函数 +变成文件名:`compat.sdl3` 的目标 `sdl3` 构建出 `libcompat_sdl3.so`(`libcompat_sdl3.dylib`、`compat_sdl3.dll`), +与包不同名的目标接在包名之后(`libcompat_sdl3_extra.so`);前缀与后缀是目标行的数据。缺省命名空间的包以包名拼写,即它 +作为裸键的写法:与包同名的目标保持其库原来的名字(`libdepShared.so`),与包不同名的目标接在包名之后 +(`libdep_depshared.so`)。根包与被选中的成员保持目标名, +陈述了 `soname` 的目标按陈述加载。两个包的库会以同一个名字加载时,规划以 `[soname-collision]` 拒绝并指出两个包。 +此前依赖包的共享库只取目标名,`compat.sdl3` 与 `mcpplibs.mwrap.sdl3` 都产出 `libsdl3.so`(mcpp#975)。mcpp 按新名字 +链接与查找该库;mcpp 之外按文件名引用依赖共享库的脚本随之改变。 + **这不是 `[target.].linkage`**(§2.7.1)。那个键回答的是一个 听起来相似、但关于 **C 库**的问题(musl 的 `-static` 链接、MSVC 的 `/MT`)。这两者不是独立的,而且方向很重要:一个完全静态的镜像没有 @@ -1539,10 +1561,10 @@ runner = { cmd = ["okrun", "{}"], host = "same-arch", exclusive = false } ### 2.8.3 `[scan_overrides.""]` —— 作者断言的扫描结果 -默认的模块扫描器是一趟文本层面的处理,它(刻意)拒绝条件预处理块内的 -`import` 语句。有些合法的模块单元里确实有这种写法——例如 fmt 官方的 -`src/fmt.cc` 把 `import std;` 保护在 `#ifdef FMT_IMPORT_STD` 之内。 -当一个文件的 import 集合已知且稳定时,声明它,而不是去扫描它: +默认的模块扫描器读取文本。一个单元的 `import` 或模块声明处于预处理条件之内时——例如 fmt 官方的 +`src/fmt.cc` 把 `import std;` 保护在 `#ifdef FMT_IMPORT_STD` 之内——它的导入取自编译器的依赖扫描,在规划依赖图 +时以该单元的编译词运行(2026.11.27.1+,见 §2.8.4)。当一个文件的 import 集合已知且稳定时,仍可以声明它, +而不是去扫描它: ```toml [modules] @@ -1581,6 +1603,16 @@ override),在生成构建时设置 `MCPP_VERIFY_MODGRAPH=1`。 默认扫描器逐个读取源文件,不展开 `#include`。需要由它发现的 import 写在被扫描的 源文件本身;头文件中的 `import` 不为默认模块图增加导入边。 +**什么是代码只读一次。** 注释与字符串、字符字面量(含原始字符串)的内容不是代码,数字分隔符(`1'000`)属于 +数字;扫描器、构建的源文件接缝与从包的源文件读取模块名的函数由同一个读者判定(2026.11.27.1+)。原始字符串中的 +`export module x;` 不声明任何模块。 + +**条件之内的 import 由编译器回答(2026.11.27.1+)。** 一个单元走 `#if`、`#ifdef` 或 `#ifndef` 的哪一个分支, +取决于工具链的预定义宏、目标、宏定义与它包含的头文件。`import` 或模块声明处于这样的条件之内时,该单元在规划 +依赖图时由编译器扫描(GCC 的 `-fdeps-format=p1689r5`,Clang 的 `clang-scan-deps`),传入标准、整图的 +`dialect_cxxflags`、目标的编译侧以及包的包含目录与编译词,命令与构建期扫描边所运行的相同。规划时不向 MSVC 请求 +这种扫描,这样的单元在 MSVC 上以此原因被拒绝;头单元(`import ;`)在任何位置都被拒绝。 + 扫描器为每个文件回答两个问题——这个单元提供什么、这个单元需要 什么——没有别的东西决定这两个答案。 @@ -1632,8 +1664,18 @@ dependency_debug = "lines" # 来自存储与 git 的依赖:true | false | "lines cflags = ["-fno-plt"] cxxflags = ["-fno-plt"] ldflags = [] +dialect_cxxflags = ["-fsanitize=address"] # every C++ unit of the graph and the std module (2026.11.27.1+) ``` +**这些列表到达哪些单元(2026.11.27.1+)。** `cflags` 与 `cxxflags` 是根位置的词,与 `[build] cflags`、`cxxflags` +相同:它们到达构建的根——根包与被选中的成员——的单元。作为所选内容的依赖被编译的成员或 `path` 依赖不收到它们, +因此 `mcpp build -p app --profile small` 编译 `app` 所依赖的库时不带它们,`--workspace` 时带上。`opt`、`debug`、 +`ndebug` 与 `ldflags` 到达整张图。必须对每个单元一致的词——检测器、体积 profile 的 +`-fno-asynchronous-unwind-tables`——写进 `dialect_cxxflags`:它与 `[build] dialect_cxxflags` 含义相同(标准库模块、 +扫描与每个 C++ 单元),追加在其后;工作空间的 profile 同样接受。写它的清单陈述 `mcpp = ">=2026.11.27.1"`:更早的 +mcpp 报告这个键并忽略它。C 单元没有这样的键:C++ 图因 BMI 与标准库模块而必须方言一致,C 单元之间没有这种约束。 +profile 中不存在的键被报告并忽略。 + **标志列表的顺序。** `cflags`、`cxxflags` 与 `ldflags` 各自按 `[build]` 的、profile 的、`[target..build]` 的 顺序进入命令:编译器或链接器取两个词中后者时,目标块的生效(2026.11.16.1 实测)。 @@ -1731,7 +1773,8 @@ cache = "global" # "global" (default) | "local" | "off" | `off` | 否 | 否 | 是 | `local` 让每个依赖都在这个工程自己的 `target/` 里构建——用于在排查 -某个问题时排除缓存因素,也用于给 CI 一条不共享的基线。`off` 还会额外 +某个问题时排除缓存因素,也用于给 CI 一条不共享的基线。宿主工具在每种模式下都留在共享存储中:工具按它的源码与宿主 +寻址,一个条目服务构建它的每个工程;`local` 作用于工具的构建所编译的依赖。`off` 还会额外 清空这次构建的 `target///` 以获得一次冷构建; `--no-cache` 是它的一个已废弃别名。 @@ -1743,8 +1786,10 @@ cache = "global" # "global" (default) | "local" | "off" `path` 依赖以其源码树内容的摘要,在 `mcpp cache list` 中写作 `+path.<摘要>`。摘要覆盖依赖根目录下 每个文件的相对路径与内容,不含 `target/`、`.git/`、`.mcpp/`、`compile_commands.json` 与含自己 `mcpp.toml` 的子目录。两个经 `path` 使用同一个库的工程、一次 clean 之后的构建、以及恢复 `$MCPP_HOME/build-cache` 的 -CI 运行,只要库的源码相同就复用同一个条目,与源码树检出在哪里无关;一次修改是一个新键,同一棵树在先前摘要下 -的条目在写入新条目时移除。`path` 依赖的条目在写入前重新读取源码树,编译期间改变了的树不写入。条目只含它的包 +CI 运行,只要库的源码相同就复用同一个条目,与源码树检出在哪里无关;一次修改是一个新键。条目记录使用它的每一棵树 +*(2026.11.27.1+)*:写入或命中条目的树被加入记录。一棵被编辑的树写入或命中新摘要的条目时,从同一个包在先前摘要下的条目中 +撤下自己,记录为空的条目被删除;另一棵树仍在使用的条目保留。2026.11.27.1 之前条目只记录写入它的那一棵树,一个检出中的 +编辑会删除另一个检出的计划仍然指向的条目(mcpp#1025)。`path` 依赖的条目在写入前重新读取源码树,编译期间改变了的树不写入。条目只含它的包 自己的单元 *(2026.11.20.1+)*:位于依赖树中嵌套的另一个包之下的单元属于那个包——位于仓库之下、成员的构建程序 导入仓库自身包的 workspace,其成员的单元仍属于成员,在原处构建。2026.11.19.1 下依赖的条目收入了这些单元, 自干净的 target 目录构建时把一个成员的目标文件链接进了另一个成员(mcpp#979)。 @@ -1867,6 +1912,23 @@ Link intent 把各个发现阶段分开处理: | `deploy_files` | 拷贝边 | 拷贝边 | 拷贝到输出旁边;从不是链接器旗标 | | `deploy` *(2026.9.12.2+)* | 拷贝边,进 `bin//` | 拷贝边,进 `bin//` | 拷贝边,进 `bin//`;从不是链接器旗标 | +**链接读取的文件就是加载器加载的文件** *(2026.11.27.1+)*。ELF 镜像链接之后,mcpp 按加载器的方式在镜像的搜索路径上 +解析它指名的每个 `DT_NEEDED`,并与链接为该名字读取的共享对象比较;后者由链接记录(`--dependency-file`,由 ninja +保存)。两者先按对象比较(任何拼写下的同一个文件),再按内容比较。加载器以另一个文件回答的名字以 `[runtime-closure]` +拒绝: + +``` +error: libz.so.1 is linked from one file and loaded from another + linked /usr/lib/x86_64-linux-gnu/libz.so.1 + loaded ~/.mcpp/registry/data/xpkgs/xim-x-zlib/1.3.1/lib/libz.so.1 + help: state the package that provides it rather than a directory that holds a copy, or remove the directory from the link +``` + +没有任何文件回答的名字以同一个标记拒绝。这项核对适用于构建所校验的每个镜像——程序、共享库、测试与宿主工具——构建 +所绑定的 C 库自己的库除外;判定随镜像的判定一起保存,没有变化的镜像不再比较。在 `MCPP_ALLOW_HOST_LIBS` 下,链接 +经同意读取宿主目录,差异报告为无法判定而不是拒绝。此前一个以宿主的库副本链接的镜像,在运行时加载的是 store 中的 +副本,没有任何诊断(mcpp#537)。 + `deploy` 列出包的运行时文件:程序运行时从自己所在目录读取的文件。读取固定子目录的加载器需要它们在那里: macOS 上的 Vulkan loader 从 `<可执行文件目录>/vulkan/icd.d` 读取驱动 manifest。条目是一个字符串或一张表 *(字符串形式、通配符与 `name`:2026.11.17.1+)*: diff --git a/docs/zh/05-dependencies.md b/docs/zh/05-dependencies.md index 018fcfb58..8bd53a5f5 100644 --- a/docs/zh/05-dependencies.md +++ b/docs/zh/05-dependencies.md @@ -308,6 +308,14 @@ asio = "1.38.1" 第三种写法会明确报错,指出实际尝试过的 `(mcpplibs, asio)` 身份;该短名若存在 于别处,错误信息会给出一个可直接复制的显式选择器。 +**`mcpp add` 写出的形式(2026.11.27.1+)。** 它按表中该命名空间已有的形式写入:已有 `[dependencies.]` 表头时, +写为该节中的短键;否则写为 `[dependencies]` 中的点号键 `.<名>`;缺省命名空间的包写裸键。`--dev` 写入 +`[dev-dependencies]`,`--build` 写入 `[build-dependencies]`;`mcpp remove` 接受同样的旗标,不带时从 +`[dependencies]` 移除。点号键已经定义了一个表之后又用表头重新打开它——`[dependencies]` 下有 `compat.libpng`, +其后又写 `[dependencies.compat]`——是同一个表定义了两次,TOML 1.0 与每个严格的读者(toml++、Python 的 +`tomllib`)都拒绝。mcpp 把两者合并读取,并报告弃用项 `reopened-dotted-table`([docs/51](51-supported-versions.md)); +下一次对该表执行 `mcpp add` 时,表头下的条目被改写为点号键。 + #### 裸名过渡期(`2026.8.10.1` 起,`2026.9` 移除) 索引里每一个已发布的 `compat.*` 包,以及精确身份出现之前写下的每一份 @@ -480,6 +488,11 @@ tomlplusplus = "3.4.0" # build.mcpp 导入的 protobuf = { version = "35.1", tools = ["protoc"] } # 构建期间运行的程序 ``` +`mcpp add --build <包>@<版本>` 在这里写入一条依赖(2026.11.27.1+)。一个包是不是构建插件由它的源文件回答——它的库 +导入 `mcpp.core`——而 `mcpp add` 手里只有包的描述符,因此它不猜:不带 `--build` 时写入 `[dependencies]`,写在那里的 +插件在第一次构建时被指出(下文的 `host-module-in-dependencies`),并给出移动它的两条命令 `mcpp remove <包>` 与 +`mcpp add --build <包>@<版本>`。 + 一条依赖由两条轴描述(mcpp 2026.10.11.1+,SPEC-004 §12),每条轴在清单中有自己的位置。 - **段**决定依赖服务的配置。`[dependencies]` 与 `[dev-dependencies]` 服务目标: diff --git a/docs/zh/06-features-and-capabilities.md b/docs/zh/06-features-and-capabilities.md index 406b674b9..f89dfe450 100644 --- a/docs/zh/06-features-and-capabilities.md +++ b/docs/zh/06-features-and-capabilities.md @@ -113,6 +113,7 @@ simd = { sources = ["src/simd/**"], flags = [ ([05,构建期依赖](05-dependencies.md));指名的不是本包的 `bin` 目标时,加载被拒绝。 - `description`(mcpp 2026.11.21.1+)是给读者的一行特性说明,与 `[package] description` 之于包相同。它不改变构建;索引描述符的 `features.` 同样接受。数组简写没有描述。 + [`examples/11-features`](../../examples/11-features/) 的每个 feature 都写出了描述。 ### 读取包的 feature(mcpp 2026.11.21.1+) diff --git a/docs/zh/09-commands-by-scenario.md b/docs/zh/09-commands-by-scenario.md index 339baa983..7c6df2c7c 100644 --- a/docs/zh/09-commands-by-scenario.md +++ b/docs/zh/09-commands-by-scenario.md @@ -85,8 +85,11 @@ host 工具条目。一份 `std` BMI 被机器上每个工程共享,实现以" 构建成功后,每天至多一次,移除 `[cache] unused_days` 天(config.toml;默认 30, `0` 关闭)内没有构建使用过的条目,包、host 工具与 `std` 均在其列;命中即记为使用。 -`path` host 工具或 `path` 依赖的源树变化时,写入新条目的同时移除同一源树在其内容先前摘要下的条目 -(host 工具 2026.10.31.3+,依赖与内容摘要 2026.11.19.1+)。构建前,若所写入的文件系统可用空间少于 2 GiB 与"该配置上一次构建写入量的 1.25 倍"中的较大者 +`path` host 工具或 `path` 依赖的条目记录使用它的每一棵源树,每棵树是条目 `users/` 下的一个文件(2026.11.27.1+)。 +源树变化时,写入或命中其新内容条目的构建从同一个包在先前摘要下的条目中撤下该树,并删除记录为空的条目;另一棵树仍在使用的 +条目保留(host 工具 2026.10.31.3+,依赖与内容摘要 2026.11.19.1+,使用者记录 2026.11.27.1+)。更早的 mcpp 写下的 +`source` 记录读作第一个使用者,不被改写,因此与之共用 home 的旧版本不会删除新条目。检出被删除的源树不会被撤下,它的 +条目按最后使用时间回收。构建前,若所写入的文件系统可用空间少于 2 GiB 与"该配置上一次构建写入量的 1.25 倍"中的较大者 (记录在 `<输出目录>/.mcpp-written`),mcpp 给出警告并说明两者(2026.11.8.1+)。`mcpp cache prune` 与 `mcpp cache gc --older-than` 也按年龄收集 `std` 模块条目;`gc --max-size` 只对包与宿主工具做 预算(2026.11.8.1+)。 diff --git a/docs/zh/20-toolchains.md b/docs/zh/20-toolchains.md index f6319c852..337dbbce0 100644 --- a/docs/zh/20-toolchains.md +++ b/docs/zh/20-toolchains.md @@ -871,8 +871,10 @@ runner 时,`mcpp run` 与 `mcpp test` 使用这个程序,因此不涉及 PAT 与 `mcpp toolchain install `。仅仅重装会再次按同一份配方安装,因为 索引只在解析未命中时刷新,而不因配方变化而刷新;这一点在 2026.9.12.2 的 沙箱验证中实测过。在此之前,失败信息来自解释器自身 -(`/usr/bin/env: 'node': No such file or directory`),mcpp 尚未对它作出解释 -(#621)。 +(`/usr/bin/env: 'node': No such file or directory`)。`mcpp run` 与 +`mcpp test` 在直接执行产物之前会读取它的 `#!` 行;这一行指名的程序不存在时 +(产物所得 PATH 的任何目录中都没有 `node`),一条 note 会指出这个程序,并以一行 +`help:` 给出上述三步,其中写出本次构建所用工具链的 spec。 对于产物在别处运行的 target,`runner` 键是一个 argv 前缀,而那个会话属于 一个**包**,不属于引擎: @@ -1722,18 +1724,13 @@ rpath——所以在 ELF 上,这类产物仍可能优先找到工具链自己 `-D`,同时作用于 C 与 C++ 两条编译通道。它覆盖包内每一个翻译 单元——包括模块接口单元——因此也会进入编译器自己的 P1689 模块扫描。 -> **但它不会让被宏保护的 `import` 变得可用。** mcpp 会在编译器看到文件 -> 之前先跑自己的词法预扫描,而那个扫描器对**任何** `#if` / `#ifdef` -> 块内的 `import` 一律拒绝,不会对条件求值: -> -> ``` -> error: import statement inside conditional preprocessor block (forbidden in M1) -> ``` -> -> 所以即使 `FOO` 写在 `defines` 里,`#ifdef FOO` / `import bar;` 这一对 -> 仍然会失败。替代写法是把条件放在全局模块片段里的一个 `#include` 上。 -> 跟踪于 mcpp-community/mcpp#421。汇编单元同样会拿到它。它是一个普通的 -构建输入,所以 `[target.'cfg(...)'.build]` 也能承载它: +> **被宏保护的 `import` 随其条件生效(2026.11.27.1+)。** mcpp 的词法预扫描把 `import` 位于 `#if` / `#ifdef` +> 块内的单元标记出来,这个单元的导入取自编译器的依赖扫描,扫描使用该单元自己的编译词,包括 `defines`。因此 +> `#ifdef FOO` / `import bar;` 这一对恰在 `FOO` 被定义时导入 `bar`(GCC 上如此,Clang 上经 `clang-scan-deps`; +> MSVC 没有规划期的扫描,这样的单元被拒绝)。头单元仍被拒绝。2026.11.27.1 之前,预扫描拒绝每一个这样的单元 +> (mcpp#421、mcpp#1026)。 + +汇编单元同样会拿到 `defines`。它是一个普通的构建输入,所以 `[target.'cfg(...)'.build]` 也能承载它: ```toml [build] diff --git a/docs/zh/22-target-side.md b/docs/zh/22-target-side.md index 67b0cfb28..bb9564cd9 100644 --- a/docs/zh/22-target-side.md +++ b/docs/zh/22-target-side.md @@ -80,6 +80,21 @@ C 库、平台接口与 C++ 运行时是互斥的选择,不是可叠加的贡 编译器运行时必须属于编译器自身所在的族,因为如果两者不一致,这次构建解析 `__udivti3` 的方式,会与同一程序中其它每一次链接不同。 +依赖图提供 C 库而没有提供 C++ ABI 时,规划拒绝(2026.11.27.1+)。`c-abi` 的供给者来自依赖图、没有包提供 +`c++-abi`、有单元导入标准库模块、工具链有这个模块、清单又没有陈述 `[build] cxx_runtime` 时,计划在任何编译之前以 +`[layer-requirement]` 停止: + +``` +error: the graph supplies the C library (musl, acme.musl@1.2.5) and no package supplies the C++ ABI. + The standard library module is compiled with the toolchain's C++ library, which is + built against another C library. + help: add a dependency that provides `mcpp:c++-abi`, or state [build] cxx_runtime = "host-coupled" +``` + +补救指名能力而不指名包:哪个包提供它是索引的事实。工具链没有该目标的标准库模块时,改由目标自己的理由拒绝 +(操作系统由加载器提供的行:程序内需要一个 C++ 运行时)。此前标准库模块的预编译在工具链的头文件中失败(GCC 16.1 下 +找不到 `features.h`,LLVM 23.1 下找不到 `__config`),没有任何信息指出是哪个决定造成的(mcpp#898)。 + ### 跨来源接线 引擎只在两层来自不同来源时才为它们接线。 diff --git a/docs/zh/23-the-project-environment.md b/docs/zh/23-the-project-environment.md index ecdb5b038..299b71523 100644 --- a/docs/zh/23-the-project-environment.md +++ b/docs/zh/23-the-project-environment.md @@ -46,20 +46,29 @@ SubOS 是一个承载用户空间的目录:它有自己的 `bin`、自己的 是哪一份是关于工程的事实,而不是关于机器的事实。第 8 章讲述这项绑定、 它的降级规则,以及一个不描述自身的 SubOS 对它们的影响。 -**构建程序能看到的工具**(mcpp 2026.8.25.1+)。声明的环境的 `bin` 被放到 -`build.mcpp` 运行时所用 `PATH` 的最前面: +**子进程能看到的工具**(mcpp 2026.8.25.1+;每种子进程同一个组成 2026.11.27.1+)。mcpp 启动三种子进程——构建程序、 +测试、`mcpp run` 的程序——每一种得到的 `PATH` 由同一个函数组成,在每个宿主上相同: ``` -PATH=: +PATH=:: ``` -因此,构建程序写下裸名 `qemu-system-riscv64` 时,拿到的是声明环境内的那一份。 -第 7 章讲述这一点所依赖的契约。 - -**只对声明了环境的工程生效。** 没有 `[xlings].subos` 的工程拿到的 `PATH` -与 mcpp 被启动时的 `PATH` 逐字节相同。把一个共享目录放在每个工程前面, -会让一次构建看到的内容取决于这台机器上还装了别的什么——同一机器上的两个工程 -会彼此一致,而同一个工程在两台机器上却不会一致。声明它,才会把它放到那个位置。 +第一段是依赖图的 `[xlings.workspace]` 条目(工程的与其依赖的)所安装的每个载荷的 `bin`;第二段只在工程声明了环境 +时存在。因此,构建程序写下裸名 `qemu-system-riscv64` 时,拿到的是依赖图或声明环境所陈述的那一份;测试运行一个以 +`when = "run"` 陈述的工具时,在每个宿主上都能找到它。2026.11.27.1 之前,构建程序的 `PATH` 只有后两段,测试的 +`PATH` 只在 Linux 上把工具链所在环境的 `bin` 放在最前面(mcpp#926)。第 7 章讲述这一点所依赖的契约。 + +**只对声明了环境的工程生效。** 没有 `[xlings].subos` 的工程不得到环境的 `bin`:它的子进程看到的是它的依赖图所陈述的 +工具,然后是 mcpp 被启动时的 `PATH`。把一个共享目录放在每个工程前面,会让一次构建看到的内容取决于这台机器上还装了 +别的什么——同一机器上的两个工程会彼此一致,而同一个工程在两台机器上却不会一致。声明它,才会把它放到那个位置。 +在 Windows 之外,这样的工程的测试仍在陈述的工具之后保留工具链所在环境的 `bin`,与 2026.11.27.1 之前相同, +按兼容读法 `implicit-default-environment`([51](51-supported-versions.md))保留到该行的下限;在 Windows 上该目录 +存放工具链的 `cl` 与 `link` 垫片,它们不是工程的工具,从不给出(mcpp#726)。 + +**库遵循同一条规则。** 环境的并集视图(`subos/<名>/lib`)包含其中安装过的一切;对没有声明环境的工程,它是这台机器的 +缺省环境。一个产物在那里找到、而在计划陈述的任何位置(载荷、包的 `[runtime]` 目录、构建自己的输出)都找不到的库, +每次构建以 `implicit-default-environment` 报告一次,指名产物与库:这台机器有它,干净的机器未必有。补救是陈述提供它的包, +或声明 `subos = "default"`,之后该视图是工程自己的,不再报告。 **是前置,不是替换。** 构建程序合理地会调用 `git`、`python3` 或某个 shell, 它们都不住在 SubOS 里。放在最前面只是让声明的环境成为默认答案; diff --git a/docs/zh/25-home-indices-and-store.md b/docs/zh/25-home-indices-and-store.md index 609200d2f..8590e0244 100644 --- a/docs/zh/25-home-indices-and-store.md +++ b/docs/zh/25-home-indices-and-store.md @@ -77,6 +77,13 @@ Windows 首次显式 `self init` 时,若 D 是可写的本地固定磁盘, 重定向场景会先标明实际目标。`--system self init --home` 被拒绝。 完整选择与持久化规则见 [SPEC-010](../specs/home-initialization.md)。 +**home 保持给定的拼写(2026.11.27.1+)。** 经符号链接给出的 home 按这个名字使用:mcpp 把路径绝对化并做词法归一, +在它之下打开文件、启动程序,因此 `mcpp self env` 与交给工具的每个路径显示的都是用户给出的目录。物理路径只用来判断 +两个路径是不是同一个对象——从上游借用的 home、位于 home 之内的工程。上级目录不可访问而无法判断时,比较退回到拼写, +构建以降级报告并指名这项判断。以路径为输入的键(缓存条目的使用者、计划的工作目录)同样用拼写:同一棵树的两种拼写 +得到两个键,多一个条目,不产生错误结果。此前 home 在读取时被解析为物理路径(mcpp#1024)。CI 中的一项检查把身份函数 +之外的物理路径调用数限制在一份只减不增的基线以内。 + ### 初始化与网络诊断(2026.10.19.1+) `self env`、`self config`、`self doctor` 和 `toolchain list` 读取本地状态,不安装工具。 diff --git a/docs/zh/30-build-mcpp.md b/docs/zh/30-build-mcpp.md index 60d14b477..4d1a5abb2 100644 --- a/docs/zh/30-build-mcpp.md +++ b/docs/zh/30-build-mcpp.md @@ -1555,8 +1555,16 @@ grpc = { version = "1.83.0", tools = ["grpc_cpp_plugin"] } store 命中、不重建,检出或复制改变了全部修改时间之后也是。在 [`examples/12-a-new-device-language`](../../examples/12-a-new-device-language/) 上实测;此前这个键只有版本,改动 emitter 之后 `mcpp run` 打印的是上一次的答案,直到 -版本被抬高。新条目写出时,同一棵树在先前摘要下的条目被删除;`mcpp cache clean` 清空 -store,路径是 `/tool//@[+]/`。 +版本被抬高。条目记录使用它的每一棵树,与 `path` 依赖的条目相同([09](09-commands-by-scenario.md)):一棵被编辑的 +树写入或命中新摘要的条目时,从先前摘要下的条目中撤下自己,记录为空的条目被删除 *(2026.11.27.1 起;此前同一棵树在先前 +摘要下的条目不论谁在使用都被删除)*。`mcpp cache clean` 清空 store,路径是 +`/tool//@[+]/`。store 在每种 `--cache` 模式下都是共享的:`local` 与 +`off` 作用于工具的构建所编译的依赖,不改变工具存放的位置。 + +**条目包含工具与它加载的共享对象(2026.11.27.1+)。** 工具的链接读取了它自己的构建产出的共享库——它的图中以 +`shared` 链接的包——时,它从自己所在的目录加载该库,RPATH 以 `$ORIGIN` 指名这个目录。条目包含可执行文件与每个这样的 +库及其别名,由同一个发布步骤写入,并在条目的 `shared-objects` 中列出;缺少其中之一的条目无效,重新构建。此前 store +只发布可执行文件,这样的工具从 store 启动时失败(mcpp#535)。 **工具构建写出的路径长度有界(2026.9.15.2+)。** 子构建在 `/tool/.build//` 中进行,这个目录由条目与消费工程命名,不嵌套在 diff --git a/docs/zh/35-platforms.md b/docs/zh/35-platforms.md index bdb8c3e28..cf40508ae 100644 --- a/docs/zh/35-platforms.md +++ b/docs/zh/35-platforms.md @@ -336,7 +336,10 @@ platform = { path = "../platforms" } (2026.11.17.1+)陈述行的可执行文件后缀是加载其程序的一部分:名字模板(`artifact_name("exe", "{name}")`、`link.exe`) 只决定后缀之前的部分,名字以该后缀结尾且只出现一次。内置的 `wasm32-emscripten` 行陈述它,所以命名为 `{name}` 的程序 仍是 `app.wasm` 旁的 `app.js`。`link-without-main`(2026.11.20.1+)给出没有程序起点的可执行映像(`main = false`,见 04 的 -`main = false`)的链接词;未陈述它的行拒绝其可执行映像的 `main = false`。内置的 `wasm32-emscripten` 行为 `["--no-entry"]`。机器只在执行关系表陈述时运行另一架构的程序(`[[platform.executes]]`, +`main = false`)的链接词;未陈述它的行拒绝其可执行映像的 `main = false`。内置的 `wasm32-emscripten` 行为 `["--no-entry"]`。 +`dlopen-static-tls`(2026.11.27.1+)是该行的加载器从静态 TLS 块中为以 `dlopen` 加载、其对象使用 initial-exec 模型 +(`DF_STATIC_TLS`)的映像提供的字节数:超过它的共享映像在链接之后被报告,精确 `exports` 表明宿主按名字加载它时被拒绝。 +未陈述的行不检查;内置的 glibc 行为 512。机器只在执行关系表陈述时运行另一架构的程序(`[[platform.executes]]`, SPEC-016 §2.4);此时 `same-arch` 的 runner 为产物的架构构建,在本机启动。 **定义的行与内置行同一读法(2026.11.10.1+)。** 它的 `march` 与 `link-emulation` 进入编译与 `ld.lld` 链接(`mcpp why flags` diff --git a/docs/zh/50-machine-output.md b/docs/zh/50-machine-output.md index 3febb1f6b..f9f237fc9 100644 --- a/docs/zh/50-machine-output.md +++ b/docs/zh/50-machine-output.md @@ -595,6 +595,9 @@ replaced}` —— `origin` 与构建的状态行使用的是同一句话 | `accel-backend-undeclared` | 一条 `[build] sources` 条目命名的后端,未出现在该包自己的 `[package] accelerators` 中 | | `device-source-unconsumed` | 一个设备类源文件没有到达任何 action,因此没有任何东西编译它 | | `host-module-missing` | `build.mcpp` 导入的模块,没有任何依赖以 host module 的形式提供 | +| `runtime-closure` | 镜像的某个 `DT_NEEDED` 在加载期没有由链接期为它读取的那个文件满足:镜像的搜索路径上没有文件满足它,或由另一个同名文件满足(2026.11.27.1+) | +| `static-tls-image` | 精确 `exports` 表明宿主以 `dlopen` 加载的共享镜像,以静态 TLS 块(`DF_STATIC_TLS`)占用的大小超过 C 库为这类镜像提供的余量(2026.11.27.1+) | +| `soname-collision` | 同一次构建的两个共享库以同一个名字加载,即文件名或陈述的 `soname` 相同(2026.11.27.1+) | | `build-program-unpublished-input` | `mcpp publish`:包的构建程序读到了包的归档不含的文件——包目录之外的文件,或 HEAD 未跟踪的文件(2026.11.21.1+) | | `companion-too-old` | 工具链旁写明的配套载荷(`companions = { binutils = … }`)低于工具链载荷声明的版本(SPEC-006 §2.9) | | `tool-version-conflict` | 两处声明把同一个 xlings 包定在不能同时成立的两个版本上 | diff --git a/docs/zh/51-supported-versions.md b/docs/zh/51-supported-versions.md index b5813e08a..6c9e28c21 100644 --- a/docs/zh/51-supported-versions.md +++ b/docs/zh/51-supported-versions.md @@ -72,6 +72,9 @@ schema,那是 [50 —— 机器可读输出](50-machine-output.md)。 | `no-universal-flag`:`mcpp pack --no-universal`,单目标打包不再需要它(与目标集合同用时拒绝) | 2026.10.30.1 | 2027.1 | `--target -`(一条腿) | | `quoted-dotted-dependency-key`:带点的加引号依赖键(`"mcpplibs.cmdline" = "0.0.2"`),即一个 TOML 键,按其中的点所拼写的选择器读取;它是一个包与其父包或子包并列时的唯一写法时除外(docs/05) | 2026.11.8.1 | 2027.2 | 不加引号的选择器 `mcpplibs.cmdline = "0.0.2"` | | `ambiguous-contract-name`:构建程序以一个名字提问(`dep_dir`、`dep_linkage`、`dep_bin`、`xpkg_dir`),该名字的契约变量由多个依赖或载荷回答,回答为其中的第一个 | 2026.11.21.1 | 2027.2 | 精确的拼写:限定名,或 `xpkg_dir("", "")`;没有可区分的拼写时,改名其中一个包 | +| `reopened-dotted-table`:点号键定义了一个表之后,又由 `[表头]` 重新打开它(`[dependencies]` 下写了 `compat.libpng = ...` 之后又写 `[dependencies.compat]`),TOML 1.0 不允许 | 2026.11.27.1 | 2027.3 | 把表头下的条目写成它所扩展的表中的点号键,`compat.zlib = ...`;下一次对该表执行 `mcpp add` 时即如此改写 | +| `implicit-default-environment`:未陈述环境的工程使用机器缺省环境中已安装内容的并集:其库进入运行期搜索路径与链接期的 `--sysroot`,其 `bin` 进入测试子进程的 PATH(Windows 除外) | 2026.11.27.1 | 2027.3 | 依赖提供该库或工具的包,或写 `[xlings] subos = "default"` 陈述使用共享环境 | +| `unmatched-exact-export`:`exports` 中不含通配符、却指名共享镜像未定义之符号的条目,被无声地从发布集合中去掉 | 2026.11.27.1 | 2027.3 | 镜像所定义的名字(C++ 名字写修饰后的形式,或以 `extern "C"` 声明该函数),或把该条目写到定义它的 `[target.]` 下 | ## 复现一次构建 diff --git a/examples/11-features/README.md b/examples/11-features/README.md index da8323dd1..4f054fd55 100644 --- a/examples/11-features/README.md +++ b/examples/11-features/README.md @@ -38,7 +38,7 @@ Two more keys are here because a library has them and no other example does: counters = { path = "../counters" } [profile.release] -opt_level = 3 +opt = 3 ``` ## The criterion diff --git a/examples/11-features/greeter/mcpp.toml b/examples/11-features/greeter/mcpp.toml index feae21def..78d236859 100644 --- a/examples/11-features/greeter/mcpp.toml +++ b/examples/11-features/greeter/mcpp.toml @@ -16,13 +16,15 @@ default = ["shout"] # A feature that only turns a compile macro on. Every active feature defines # `MCPP_FEATURE_`, so a source can branch without the manifest naming a -# file. -shout = {} +# file. `description` is one line for whoever chooses features (`mcpp search`, +# `mcpp why features`, an editor); it has no effect on the build. +shout = { description = "Prints the greeting in capitals." } # A feature that ADDS A SOURCE. The file is compiled only when the feature is # active, so a consumer that does not ask for it does not pay for it. [features.metrics] -sources = ["src/metrics.cpp"] +sources = ["src/metrics.cpp"] +description = "Counts the greetings, through the counters package." # ...AND PULLS A DEPENDENCY. `[feature-deps.]` is what makes an optional # backend optional: a build that does not name `metrics` resolves a graph in @@ -35,4 +37,4 @@ counters = { path = "../counters" } counters = { path = "../counters" } [profile.release] -opt_level = 3 +opt = 3 diff --git a/mcpp.toml b/mcpp.toml index 889e7490f..c13e46917 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,6 +1,6 @@ [package] name = "mcpp" -version = "2026.11.26.1" +version = "2026.11.27.1" description = "Modern C++ build & package management tool" license = "Apache-2.0" authors = ["mcpp-community"] @@ -106,11 +106,11 @@ linkage = "static" # Eat our own dog food: mcpp uses mcpplibs.cmdline for argument parsing. # TOML-native namespaced form: `mcpplibs.cmdline` is the dotted subtable -# `[dependencies.mcpplibs] cmdline = "0.0.5"` ⇒ identity (mcpplibs, cmdline). +# `[dependencies.mcpplibs] cmdline = "0.0.6"` ⇒ identity (mcpplibs, cmdline). # The bootstrap mcpp used by the self-host build (xlings install mcpp, well # past 0.0.6) understands this, so the legacy quoted form is no longer needed. [dependencies] -mcpplibs.cmdline = "0.0.5" +mcpplibs.cmdline = "0.0.6" # JSON for Modern C++, as the index's module package (no copied header). nlohmann.json = "3.12.0" # The C library's macros (`stdout`, `stderr`, `EOF`, `errno` …) as C++ names: @@ -167,6 +167,18 @@ sources = ["!src/native/windows/**"] [target.windows.build] sources = ["!src/native/posix/**"] +# THE MAIN THREAD'S STACK ON WINDOWS. A command nests whole builds in one process: `mcpp pack` +# prepares the program, a host tool its platform names, and that tool's build programs, and each +# pass holds a few hundred KiB of frames. A PE image's main thread has the 1 MiB its header +# reserves by default, where Linux and macOS give 8 MiB. Measured with 2026.11.27.1 on the +# openkal canary's `mcpp pack`: 1,046 KiB at the deepest manifest read, and an +# EXCEPTION_STACK_OVERFLOW on windows-x86_64. The image reserves what the other hosts give. +[target.'cfg(all(os = "windows", env = "msvc"))'.build] +ldflags = ["-Wl,/STACK:8388608"] + +[target.'cfg(all(os = "windows", env = "gnu"))'.build] +ldflags = ["-Wl,--stack,8388608"] + [workspace] members = [ "modules/invocation", diff --git a/modules/buildmcpp/src/tool_store.cppm b/modules/buildmcpp/src/tool_store.cppm index cc0c12391..2d5dbc06a 100644 --- a/modules/buildmcpp/src/tool_store.cppm +++ b/modules/buildmcpp/src/tool_store.cppm @@ -45,6 +45,7 @@ export module mcpp.build.tool_store; import std; import mcpp.invocation; +import mcpp.libs.entry_users; import nlohmann.json; import mcpp.manifest; import mcpp.toolchain.fingerprint; @@ -126,21 +127,34 @@ std::filesystem::path bin_path(const std::filesystem::path& entryDir, std::string_view exeSuffix); // A complete, verified entry? (bin present AND entry.json records the same key -// inputs — never just the hash.) +// inputs — never just the hash — AND every shared object the entry records is +// beside the tool.) bool entry_valid(const std::filesystem::path& entryDir, const Key& k, std::string_view toolName, std::string_view exeSuffix); +// The shared objects of the graph published beside the tool (mcpp#535), by +// file name under `bin/`; written before `write_entry`, read by `entry_valid`. +void record_shared_objects(const std::filesystem::path& entryDir, + const std::vector& names); + // Writes the entry's record. `source` is the tree a `path` package was -// built from: written beside the record, and an entry of the same package -// from the same tree under another stamp (`+path.`) is -// superseded and removed -- a path package's every edit was a new key, and -// none was ever collected (mcpp#874). +// built from: it becomes a user of the entry and stops being one of the +// entries of the same package it used under another stamp +// (`+path.`), which are removed when no tree uses them -- a +// path package's every edit was a new key, and none was ever collected +// (mcpp#874); another checkout's build may still read one (mcpp#1025). void write_entry(const std::filesystem::path& entryDir, const Key& k, const std::filesystem::path& source = {}); // Marks the entry used now: `mcpp cache` collects by last use, and the // record's time is that use (the record's content is the key, compared // field by field, and does not change). +// A hit of the entry for the `path` package at `source`: the tree becomes one +// of its users and leaves the entries of its earlier contents +// (mcpp.libs.entry_users). Nothing for an index package. +void add_user(const std::filesystem::path& entryDir, const Key& k, + const std::filesystem::path& source); + void touch(const std::filesystem::path& entryDir); // ── Overrides (the escape hatch every comparable system provides) ────────── @@ -238,10 +252,21 @@ fs::path bin_path(const fs::path& entryDir, std::string_view toolName, return entryDir / "bin" / (std::string(toolName) + std::string(exeSuffix)); } +void record_shared_objects(const fs::path& entryDir, const std::vector& names) { + std::error_code ec; + if (names.empty()) { fs::remove(entryDir / "shared-objects", ec); return; } + fs::create_directories(entryDir, ec); + std::ofstream os(entryDir / "shared-objects", std::ios::trunc); + for (auto const& n : names) os << n << '\n'; +} + bool entry_valid(const fs::path& entryDir, const Key& k, std::string_view toolName, std::string_view exeSuffix) { std::error_code ec; if (!fs::exists(bin_path(entryDir, toolName, exeSuffix), ec)) return false; + if (std::ifstream so(entryDir / "shared-objects"); so) + for (std::string name; std::getline(so, name);) + if (!name.empty() && !fs::exists(entryDir / "bin" / name, ec)) return false; std::ifstream is(entryDir / "entry.json"); if (!is) return false; try { @@ -265,27 +290,20 @@ void write_entry(const fs::path& entryDir, const Key& k, const fs::path& source) } const auto plus = k.version.find("+path."); if (source.empty() || plus == std::string::npos) return; - const auto origin = source.lexically_normal().generic_u8string(); - const std::string text(origin.begin(), origin.end()); - std::ofstream(entryDir / "source", std::ios::trunc) << text; - // `/@+path.//`: the siblings of this - // version directory that differ only in the stamp. - const auto versionDir = entryDir.parent_path(); - const auto prefix = std::format("{}@{}", k.packageName, k.version.substr(0, plus + 6)); - auto same_source = [&](const fs::path& keyDir) { - std::ifstream in(keyDir / "source"); - if (!in) return false; - const std::string was{std::istreambuf_iterator(in), {}}; - return was == text; - }; - for (auto const& v : fs::directory_iterator(versionDir.parent_path(), ec)) { - const auto name = v.path().filename().string(); - if (v.path() == versionDir || !name.starts_with(prefix)) continue; - std::error_code kec; - for (auto const& key : fs::directory_iterator(v.path(), kec)) - if (same_source(key.path())) fs::remove_all(key.path(), kec); - fs::remove(v.path(), kec); // only when nothing else is left in it - } + // The tree is a user of this entry and no longer of the ones it was built + // into before (mcpp.libs.entry_users, the rule the dependency cache holds). + mcpp::libs::entry_users::supersede( + entryDir, std::format("{}@{}", k.packageName, k.version.substr(0, plus + 6)), source); +} + +void add_user(const fs::path& entryDir, const Key& k, const fs::path& source) { + const auto plus = k.version.find("+path."); + if (source.empty() || plus == std::string::npos) return; + // A hit under another digest than the tree's last one moves the tree as a + // write does: a tree edited to the content another checkout stored hits + // that entry, and the entry of its previous content goes once no tree uses it. + mcpp::libs::entry_users::supersede( + entryDir, std::format("{}@{}", k.packageName, k.version.substr(0, plus + 6)), source); } // The rule of mcpp::home::mark_used, which this module cannot import: the diff --git a/modules/buildopt/mcpp.toml b/modules/buildopt/mcpp.toml index 273042507..6ff6b4427 100644 --- a/modules/buildopt/mcpp.toml +++ b/modules/buildopt/mcpp.toml @@ -17,6 +17,7 @@ license = "Apache-2.0" [dependencies] mcpp.invocation = { path = "../invocation" } +mcpp.libs = { path = "../libs" } mcpp.manifest = { path = "../manifest" } mcpp.toolchain-model = { path = "../toolchain-model" } diff --git a/modules/buildopt/src/registry.cppm b/modules/buildopt/src/registry.cppm index d4bff8eb2..28177adef 100644 --- a/modules/buildopt/src/registry.cppm +++ b/modules/buildopt/src/registry.cppm @@ -111,6 +111,13 @@ inline constexpr std::string_view kStandardEnv = "MCPP_BUILDOPT"; // The one impure function here: the statement is read in one place. bool standard_only(); +// What this invocation states of the entries that are decided when the graph +// is written: a source built as other units, a graph of another shape, and the +// standard build. Empty when it states none. A graph names it (`request_tag`), +// so one written under a statement is not replayed without it. An edge entry +// acts at run time and is read there. +std::string stated_shape(); + // The table as `mcpp explain` and the README print it: one row an entry. std::string table(); @@ -123,6 +130,15 @@ bool standard_only() { return stated && *stated == "off"; } +std::string stated_shape() { + std::string shape; + for (auto const& e : kEntries) + if (e.seam != 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(kStandardEnv)) shape += std::format("{}={};", kStandardEnv, *v); + return shape; +} + std::string table() { std::string out = "| Entry | Seam | Level | Default | Stated otherwise by | What |\n|---|---|---|---|---|---|\n"; for (auto const& e : kEntries) { diff --git a/modules/buildopt/src/source.cppm b/modules/buildopt/src/source.cppm index b57707bb5..2cc6b6bee 100644 --- a/modules/buildopt/src/source.cppm +++ b/modules/buildopt/src/source.cppm @@ -67,6 +67,7 @@ export module mcpp.buildopt.source; import std; import mcpp.invocation; +import mcpp.libs.code_text; import mcpp.manifest; import mcpp.buildopt.registry; @@ -120,158 +121,6 @@ bool has_word(std::string_view s, std::string_view word) { return false; } -// 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; - } - } - 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; - } - ++i; - } - 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. @@ -327,7 +176,7 @@ private_fragment(std::string_view text, std::string_view spelling, bool conserva if (end == std::string_view::npos) break; at = end + 1; } - const auto scanned = read_code(text); + const auto scanned = mcpp::libs::code_text::read(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())); diff --git a/modules/libs/mcpp.toml b/modules/libs/mcpp.toml index ee8fa54bf..05b1ae0c3 100644 --- a/modules/libs/mcpp.toml +++ b/modules/libs/mcpp.toml @@ -1,10 +1,13 @@ -# libs — text-format parsers written for mcpp: `toml`. It imports nothing from -# mcpp. JSON is nlohmann.json from the index (2026.11.7.1): no third-party -# source is copied into this tree. +# libs — the readers and small primitives every other package of mcpp may +# import: the TOML parser (`toml`) and what of a C++ source is code +# (`code_text`). It imports nothing from mcpp. JSON is nlohmann.json from the +# index (2026.11.7.1): no third-party source is copied into this tree. [package] name = "libs" namespace = "mcpp" version = "0.1.0" -description = "The TOML parser of mcpp, as a module" +description = "Readers and primitives below every other package of mcpp" license = "Apache-2.0" +[dev-dependencies] +mcpplibs.mtest = "0.11.3" diff --git a/modules/libs/src/code_text.cppm b/modules/libs/src/code_text.cppm new file mode 100644 index 000000000..11e1526f7 --- /dev/null +++ b/modules/libs/src/code_text.cppm @@ -0,0 +1,197 @@ +// mcpp.libs.code_text — a C++ source as the text of its code. +// +// ONE READER. Three parts of mcpp ask what a source says before a compiler has +// read it: the module scanner (which module a unit declares and imports), the +// source seam of the build optimizations (where a private module fragment +// starts), and the manifest's module-name functions (which roots a package +// declares, which it imports, which headers it includes). Each had a reader of +// its own, and they differed in what they took for code: one knew raw strings +// and block comments and nothing of a digit separator, one knew all three, and +// one read lines as they stood, so `export module x;` inside a raw string was a +// declaration to it (mcpp#963). The compiler reads the text one way; so does +// mcpp, here. +// +// The result has the length of the input, offset for offset: what is not code +// is blanked with spaces and the newlines stay, so a line of the result is the +// same line of the source and a column means the same in both. A caller that +// needs what a blanked region held (the name of an included header) reads it +// from the source at the offsets the code gave. +// +// It imports nothing of mcpp. + +export module mcpp.libs.code_text; + +import std; + +export namespace mcpp::libs::code_text { + +// The text with comments and the contents of string and character literals +// blanked (raw strings included), and the rest of a directive whose operand is +// not tokens (`#include `, `#error don't`). `joins` holds the offsets of a +// backslash that joins its line to the next. +struct Code { + std::string text; + std::vector joins; +}; + +Code read(std::string_view text); + +} // namespace mcpp::libs::code_text + +namespace mcpp::libs::code_text { + +namespace { + +bool ident_char(char c) { return std::isalnum(static_cast(c)) || c == '_'; } + +// 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 + +// 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; + } + } + 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"; +} + +} // namespace + +Code read(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; + } + ++i; + } + return r; +} + +} // namespace mcpp::libs::code_text diff --git a/modules/libs/src/entry_users.cppm b/modules/libs/src/entry_users.cppm new file mode 100644 index 000000000..96a1b19e0 --- /dev/null +++ b/modules/libs/src/entry_users.cppm @@ -0,0 +1,160 @@ +// mcpp.libs.entry_users — the source trees that use a stored entry. +// +// An entry of the build cache (a `path` dependency's objects) or of the tool +// store (a `path` host tool) is addressed by the content of the tree it was +// built from. Two checkouts of one commit have the same content and share the +// entry. An edit of one checkout gives that checkout a new entry, and its +// previous one is no longer needed by it -- but it may be by the other. +// +// The record was the one tree that wrote the entry (`source`), and the entry +// was removed when that tree was built under another digest: under a build of +// the other checkout that named the entry's files, which then failed at the +// next edge that read them (mcpp#1025). The two stores held the same rule in +// two places, each a copy of the other. +// +// THE RECORD IS A SET, ONE FILE PER TREE. `users/` holds the +// tree's path. A tree that hits or writes an entry adds its file there and +// removes it from the entries of the package's other digests it used before; +// an entry whose `users/` is then empty is removed. Each step is the creation or +// removal of one file, so two processes acting at once lose nothing: there is +// no file that both read and rewrite. +// +// THE FORMER RECORD IS READ, NEVER WRITTEN. An entry written before the set +// holds `source`, read as one user. The set is a directory of another name +// because releases before it share homes with releases after it (a project's +// bootstrap mcpp and the one it builds): an older release finds no `source` in +// an entry written now and leaves the entry alone, where a `source` of several +// lines would have been read as one path that matches no tree. +// +// A checkout that is deleted never removes its file; its entries are +// collected by the last-use rule of the stores (`[cache] unused_days`). +// +// It imports nothing of mcpp. + +export module mcpp.libs.entry_users; + +import std; + +export namespace mcpp::libs::entry_users { + +// The trees `entry` records, in no particular order: its `users/`, else its +// former `source`. +std::vector users(const std::filesystem::path& entry); + +// `tree` recorded as a user of `entry`; nothing is written when it is one. +void add(const std::filesystem::path& entry, const std::filesystem::path& tree); + +// `tree` uses `entry` (it wrote it or hit it), and no longer the entries of its +// package under another digest: `tree` is added to `entry` and taken from +// every sibling, and a sibling left with no user is removed. +// +// The siblings are the entries `/@+path.//` +// of the same package and version whose digest differs, the layout both stores +// share: `entry`'s grandparent holds them, and `versionPrefix` is +// `@+path.`. +void supersede(const std::filesystem::path& entry, std::string_view versionPrefix, + const std::filesystem::path& tree); + +} // namespace mcpp::libs::entry_users + +namespace mcpp::libs::entry_users { + +namespace { + +namespace fs = std::filesystem; + +std::string spelling(const fs::path& tree) { + const auto u8 = tree.lexically_normal().generic_u8string(); + return {u8.begin(), u8.end()}; +} + +// FNV-1a over the tree's spelling: a file name that every file system takes, +// stable across releases and compilers (std::hash is neither). +std::string file_of(std::string_view tree) { + std::uint64_t h = 1469598103934665603ull; + for (unsigned char c : tree) { + h ^= c; + h *= 1099511628211ull; + } + return std::format("{:016x}", h); +} + +std::optional read_text(const fs::path& file) { + std::ifstream in(file, std::ios::binary); + if (!in) return std::nullopt; + return std::string{std::istreambuf_iterator(in), {}}; +} + +// `tree` taken from `entry`; the entry removed when no user is left. +void take(const fs::path& entry, std::string_view tree) { + std::error_code ec; + const auto dir = entry / "users"; + if (fs::is_directory(dir, ec)) { + fs::remove(dir / file_of(tree), ec); + if (fs::is_empty(dir, ec) && !ec) fs::remove_all(entry, ec); + return; + } + // The former record: one tree. Removed as it was removed before the set. + if (auto was = read_text(entry / "source"); was && *was == tree) fs::remove_all(entry, ec); +} + +} // namespace + +std::vector users(const fs::path& entry) { + std::vector out; + std::error_code ec; + if (fs::is_directory(entry / "users", ec)) { + for (auto const& f : fs::directory_iterator(entry / "users", ec)) + if (auto text = read_text(f.path())) out.push_back(std::move(*text)); + return out; + } + if (auto was = read_text(entry / "source")) out.push_back(std::move(*was)); + return out; +} + +void add(const fs::path& entry, const fs::path& tree) { + const auto text = spelling(tree); + std::error_code ec; + const auto dir = entry / "users"; + const auto file = dir / file_of(text); + if (fs::exists(file, ec)) return; + // An entry with the former record keeps its tree as a user of the set. + if (!fs::is_directory(dir, ec)) + if (auto was = read_text(entry / "source"); was && *was != text) { + fs::create_directories(dir, ec); + std::ofstream(dir / file_of(*was), std::ios::binary) << *was; + } + fs::create_directories(dir, ec); + // Written under a name of its own and renamed: a reader never sees a part. + auto tmp = dir / std::format(".{}.{:x}.tmp", file_of(text), std::random_device{}()); + { + std::ofstream os(tmp, std::ios::binary); + os << text; + if (!os.flush()) { + os.close(); + fs::remove(tmp, ec); + return; + } + } + fs::rename(tmp, file, ec); + if (ec) fs::remove(tmp, ec); +} + +void supersede(const fs::path& entry, std::string_view versionPrefix, const fs::path& tree) { + const auto text = spelling(tree); + add(entry, tree); + const auto versionDir = entry.parent_path(); + std::error_code ec; + for (auto const& v : fs::directory_iterator(versionDir.parent_path(), ec)) { + const auto name = v.path().filename().u8string(); + if (v.path() == versionDir || !std::string(name.begin(), name.end()).starts_with(versionPrefix)) + continue; + std::error_code kec; + std::vector keys; + for (auto const& key : fs::directory_iterator(v.path(), kec)) keys.push_back(key.path()); + for (auto const& key : keys) take(key, text); + fs::remove(v.path(), kec); // only when nothing else is left in it + } +} + +} // namespace mcpp::libs::entry_users diff --git a/modules/libs/src/path_identity.cppm b/modules/libs/src/path_identity.cppm new file mode 100644 index 000000000..be6af4eba --- /dev/null +++ b/modules/libs/src/path_identity.cppm @@ -0,0 +1,71 @@ +// mcpp.libs.path_identity — whether two paths name one object, kept apart from +// the paths a program opens. +// +// A path the user or the environment gives (`MCPP_HOME`, `MCPP_TOOLCHAIN`, an +// argument, the working directory) is opened and handed to a program as it is +// spelled, made absolute and lexically normal and no more. Its canonical form +// is an identity: what two spellings have in common when they name one object. +// The two were one value: the home was resolved to its canonical form and every +// path derived from it was opened under that form. Under a sandbox that grants +// a tree through a drive alias (an AppContainer whose `Z:` names a directory +// whose ancestors it may not open), the canonical form leads through those +// ancestors, and the home could not be opened (mcpp#1024). On Linux the same +// conversion turned a home given through a symbolic link into its target. +// +// Identity is asked here. Resolving it reads every ancestor of the path, which +// a restricted process may not do; the answer is then absent, and the caller +// decides with the spelling and says that it did (`diag::degraded`). +// `.github/tools/check_path_identity.sh` counts the resolutions made anywhere +// else, against a baseline that only falls. +// +// It imports nothing of mcpp. + +export module mcpp.libs.path_identity; + +import std; + +export namespace mcpp::libs::path_identity { + +// The spelling a given path is opened under: absolute, lexically normal, every +// link and alias kept. +std::filesystem::path given(const std::filesystem::path& p); + +// The object `p` names, whatever its spelling: links resolved, and for a path +// whose last components do not exist yet, the existing part resolved and the +// rest appended. nullopt when it cannot be resolved (an ancestor this process +// may not read). +std::optional identity(const std::filesystem::path& p); + +// Whether `a` and `b` name one object. nullopt when either identity cannot be +// resolved; the caller compares the given spellings then, and says so. +std::optional same(const std::filesystem::path& a, const std::filesystem::path& b); + +} // namespace mcpp::libs::path_identity + +namespace mcpp::libs::path_identity { + +std::filesystem::path given(const std::filesystem::path& p) { + std::error_code ec; + auto abs = std::filesystem::absolute(p, ec); + return (ec ? p : abs).lexically_normal(); +} + +std::optional identity(const std::filesystem::path& p) { + std::error_code ec; + auto resolved = std::filesystem::weakly_canonical(given(p), ec); + if (ec) return std::nullopt; + return resolved; +} + +std::optional same(const std::filesystem::path& a, const std::filesystem::path& b) { + std::error_code ec; + if (std::filesystem::exists(a, ec) && std::filesystem::exists(b, ec)) { + const bool eq = std::filesystem::equivalent(a, b, ec); + if (!ec) return eq; + } + auto ia = identity(a), ib = identity(b); + if (!ia || !ib) return std::nullopt; + return *ia == *ib; +} + +} // namespace mcpp::libs::path_identity diff --git a/modules/libs/src/toml.cppm b/modules/libs/src/toml.cppm index 58d4c45b2..1620b780a 100644 --- a/modules/libs/src/toml.cppm +++ b/modules/libs/src/toml.cppm @@ -67,12 +67,25 @@ private: std::shared_ptr tab_; }; +// A table defined twice: once by a `[header]` and once by a dotted key +// (`a.b = 1` under `[t]` defines `t.a`). TOML 1.0 allows neither order; this +// reader took both, and the file it accepted is refused by every other reader +// (mcpp#964). It is recorded rather than refused here: what a caller does with +// it -- a deprecation for a manifest that an older `mcpp add` wrote, a refusal +// for the text an edit is about to write -- is the caller's. +struct TableRedefinition { + std::string path; // the table's dotted path + Position header; // where its `[header]` is + Position dotted; // where the first dotted key that defines it is +}; + class Document { public: explicit Document(Table root, std::set> explicitTables = {}, - std::map> headers = {}) + std::map> headers = {}, + std::vector redefinitions = {}) : root_(std::move(root)), explicitTables_(std::move(explicitTables)), - headers_(std::move(headers)) {} + headers_(std::move(headers)), redefinitions_(std::move(redefinitions)) {} const Table& root() const { return root_; } Table& root() { return root_; } @@ -108,10 +121,14 @@ public: return std::nullopt; } + // The tables a header and a dotted key both define, in the order met. + const std::vector& redefinitions() const { return redefinitions_; } + private: Table root_; std::set> explicitTables_; std::map> headers_; + std::vector redefinitions_; }; std::expected parse(std::string_view src); @@ -600,6 +617,16 @@ std::expected parse(std::string_view src) { std::set> explicitTables; std::map> headers; Table* current_table = &root; + // The table the next `key = value` lands in, as its dotted path; nullopt + // inside an array of tables, whose elements share one path and are each a + // table of their own. `dottedTables` holds the tables dotted keys defined. + std::optional currentPath = std::string{}; + std::map> dottedTables; + std::vector redefinitions; + auto redefined = [&](const std::string& path, Position header, Position dotted) { + if (std::ranges::none_of(redefinitions, [&](auto const& r) { return r.path == path; })) + redefinitions.push_back({path, header, dotted}); + }; while (true) { L.skip_whitespace_and_comments(); @@ -627,6 +654,7 @@ std::expected parse(std::string_view src) { explicitTables.insert(join_path(*path)); headers.emplace(join_path(*path), headerAt); current_table = *t; + currentPath.reset(); continue; } auto path = read_dotted_key(L); @@ -644,8 +672,12 @@ std::expected parse(std::string_view src) { explicitTables.insert(join_path(*path)); headers.emplace(join_path(*path), headerAt); current_table = t; + currentPath = join_path(*path); + if (auto d = dottedTables.find(*currentPath); d != dottedTables.end()) + redefined(*currentPath, headerAt, d->second); } else { // key = value + const auto keyAt = L.position(); auto path = read_dotted_key(L); if (!path) return std::unexpected(path.error()); L.skip_inline_whitespace(); @@ -662,12 +694,21 @@ std::expected parse(std::string_view src) { auto* t = dive(*current_table, parents); if (!t) return std::unexpected(ParseError{"key path conflict", L.position()}); target = t; + // Every table the key passes through is defined by it. + std::string defined = currentPath.value_or(std::string{}); + for (std::size_t i = 0; currentPath && i < parents.size(); ++i) { + defined += (defined.empty() ? "" : ".") + parents[i]; + dottedTables.emplace(defined, keyAt); + if (auto h = headers.find(defined); h != headers.end() && explicitTables.contains(defined)) + redefined(defined, h->second, keyAt); + } } (*target)[path->back()] = std::move(*v); } } - return Document{std::move(root), std::move(explicitTables), std::move(headers)}; + return Document{std::move(root), std::move(explicitTables), std::move(headers), + std::move(redefinitions)}; } std::expected parse_file(const std::filesystem::path& p) { diff --git a/modules/libs/tests/test_code_text.cpp b/modules/libs/tests/test_code_text.cpp new file mode 100644 index 000000000..2369593ee --- /dev/null +++ b/modules/libs/tests/test_code_text.cpp @@ -0,0 +1,55 @@ +import std; +import mcpplibs.mtest; +import mcpp.libs.code_text; + +using namespace mcpplibs::mtest; + +// SUBSYSTEM-LEVEL: what of a C++ source is code (design 2026-11-27 §4.3). One reader gives it to +// the module scanner, the source seam of the build optimizations and the manifest's module-name +// functions; that each of them reads its result is stated beside them. + +namespace { + +std::string code(std::string_view text) { return mcpp::libs::code_text::read(text).text; } + +} // namespace + +UTest the_result_has_the_offsets_of_the_text{"CodeText/TheResultHasTheOffsetsOfTheText", [] { + const std::string_view text = "int a; // tail\n/* block\n over */ int b;\n"; + const auto c = code(text); + expect(fatal(eq(c.size(), text.size()))); + expect(eq(c, std::string("int a; \n \n int b;\n"))); +}}; + +UTest a_raw_string_holds_no_code{"CodeText/ARawStringHoldsNoCode", [] { + const auto c = code("const char* s = R\"x(\nexport module hidden;\n)\" /* ) */ )x\";\nimport shown;\n"); + expect(!c.contains("hidden")); + expect(c.contains("import shown;")); +}}; + +UTest a_commented_raw_opener_opens_nothing{"CodeText/ACommentedRawOpenerOpensNothing", [] { + expect(code("// R\"(\nimport x;\n").contains("import x;")); +}}; + +UTest a_literal_holds_no_comment{"CodeText/ALiteralHoldsNoComment", [] { + expect(code("const char* s = \"a /* b\";\nimport x;\n").contains("import x;")); + expect(code("char c = '\"'; import y;\n").contains("import y;")); +}}; + +UTest a_digit_separator_is_part_of_a_number{"CodeText/ADigitSeparatorIsPartOfANumber", [] { + expect(code("int n = 1'000; import x; int m = 0x1'f;\n").contains("import x;")); +}}; + +UTest a_continued_comment_goes_on{"CodeText/AContinuedCommentGoesOn", [] { + const auto r = mcpp::libs::code_text::read("// a comment \\\nimport hidden;\nimport shown;\n"); + expect(!r.text.contains("hidden")); + expect(r.text.contains("import shown;")); + expect(eq(r.joins.size(), 1u)); +}}; + +UTest a_header_name_is_not_tokens{"CodeText/AHeaderNameIsNotTokens", [] { + const auto c = code("#include \n#error don't\nimport x;\n"); + expect(c.contains("#include")); + expect(!c.contains("a'b")); + expect(c.contains("import x;")); +}}; diff --git a/modules/libs/tests/test_entry_users.cpp b/modules/libs/tests/test_entry_users.cpp new file mode 100644 index 000000000..4a7d5090e --- /dev/null +++ b/modules/libs/tests/test_entry_users.cpp @@ -0,0 +1,108 @@ +import std; +import mcpplibs.mtest; +import mcpp.libs.entry_users; + +using namespace mcpplibs::mtest; + +// SUBSYSTEM-LEVEL: the trees that use a stored entry (design 2026-11-27 §4.5, mcpp#1025). That the +// dependency cache and the tool store keep the entries another checkout's plan names is stated by +// the e2e suite. + +namespace { + +namespace fs = std::filesystem; + +fs::path fresh(std::string_view name) { + auto root = fs::temp_directory_path() / std::format("mcpp-entry-users-{}-{}", name, + std::random_device{}()); + fs::remove_all(root); + fs::create_directories(root); + return root; +} + +// `/pkg@0.1.0+path.//` +fs::path entry(const fs::path& store, std::string_view digest, std::string_view key = "k") { + auto dir = store / std::format("pkg@0.1.0+path.{}", digest) / key; + fs::create_directories(dir); + std::ofstream(dir / "entry.json") << "{}"; + return dir; +} + +constexpr std::string_view kPrefix = "pkg@0.1.0+path."; + +} // namespace + +UTest an_entry_another_tree_uses_stays{"EntryUsers/AnEntryAnotherTreeUsesStays", [] { + const auto store = fresh("stays"); + const auto shared = entry(store, "aaaa"); + mcpp::libs::entry_users::supersede(shared, kPrefix, "/w/a/tool"); // a builds it + mcpp::libs::entry_users::add(shared, "/w/b/tool"); // b's plan hits it + expect(eq(mcpp::libs::entry_users::users(shared).size(), 2u)); + + const auto edited = entry(store, "bbbb"); // a is edited and built + mcpp::libs::entry_users::supersede(edited, kPrefix, "/w/a/tool"); + expect(fs::exists(shared / "entry.json")) << "the entry b uses was removed"; + expect(eq(mcpp::libs::entry_users::users(shared), std::vector{"/w/b/tool"})); + + const auto alsoEdited = entry(store, "cccc"); // b is edited and built + mcpp::libs::entry_users::supersede(alsoEdited, kPrefix, "/w/b/tool"); + expect(!fs::exists(shared)) << "an entry no tree uses is kept"; + expect(!fs::exists(shared.parent_path())) << "an empty version directory is kept"; + expect(fs::exists(edited / "entry.json")); + fs::remove_all(store); +}}; + +UTest a_tree_is_recorded_once{"EntryUsers/ATreeIsRecordedOnce", [] { + const auto store = fresh("once"); + const auto e = entry(store, "aaaa"); + mcpp::libs::entry_users::add(e, "/w/a/tool"); + mcpp::libs::entry_users::add(e, "/w/a/./tool"); + expect(eq(mcpp::libs::entry_users::users(e), std::vector{"/w/a/tool"})); + fs::remove_all(store); +}}; + +// An entry an earlier release wrote names its one tree in `source`: it is read as a user, kept as +// one when another tree hits it, and removed as before when its tree supersedes it. +UTest the_former_record_is_read_as_a_user{"EntryUsers/TheFormerRecordIsReadAsAUser", [] { + const auto store = fresh("former"); + const auto old = entry(store, "aaaa"); + std::ofstream(old / "source") << "/w/a/tool"; + expect(eq(mcpp::libs::entry_users::users(old), std::vector{"/w/a/tool"})); + + const auto alone = entry(store, "aaaa", "k2"); + std::ofstream(alone / "source") << "/w/a/tool"; + mcpp::libs::entry_users::add(old, "/w/b/tool"); + expect(eq(mcpp::libs::entry_users::users(old).size(), 2u)); + + mcpp::libs::entry_users::supersede(entry(store, "bbbb"), kPrefix, "/w/a/tool"); + expect(fs::exists(old / "entry.json")) << "the entry b hit was removed"; + expect(!fs::exists(alone)) << "an entry of the former record with no other user is kept"; + expect(!fs::exists(old / "source") || fs::exists(old / "users")); + fs::remove_all(store); +}}; + +UTest another_package_is_not_a_sibling{"EntryUsers/AnotherPackageIsNotASibling", [] { + const auto store = fresh("other"); + auto other = store / "pkgx@0.1.0+path.aaaa" / "k"; + fs::create_directories(other); + mcpp::libs::entry_users::add(other, "/w/a/tool"); + mcpp::libs::entry_users::supersede(entry(store, "bbbb"), kPrefix, "/w/a/tool"); + expect(fs::exists(other / "users")); + fs::remove_all(store); +}}; + +UTest a_tree_edited_to_another_trees_content_leaves_its_old_entry{"EntryUsers/ATreeEditedToAnotherTreesContentLeavesItsOldEntry", [] { + // Both checkouts at one content, then both edited to one new content: the first writes the + // new entry, the second hits it, and the entry of the old content has no user left. + const auto store = fresh("converge"); + const auto old = entry(store, "aaaa"); + mcpp::libs::entry_users::supersede(old, kPrefix, "/w/a/tool"); + mcpp::libs::entry_users::supersede(old, kPrefix, "/w/b/tool"); + const auto next = entry(store, "bbbb"); + mcpp::libs::entry_users::supersede(next, kPrefix, "/w/a/tool"); // a writes the new content + expect(fs::exists(old / "entry.json")) << "the entry b uses was removed"; + mcpp::libs::entry_users::supersede(next, kPrefix, "/w/b/tool"); // b hits it + expect(!fs::exists(old)) << "the entry neither tree uses is kept"; + expect(eq(mcpp::libs::entry_users::users(next).size(), 2u)); + fs::remove_all(store); +}}; diff --git a/modules/libs/tests/test_path_identity.cpp b/modules/libs/tests/test_path_identity.cpp new file mode 100644 index 000000000..fb146a8bb --- /dev/null +++ b/modules/libs/tests/test_path_identity.cpp @@ -0,0 +1,27 @@ +import std; +import mcpplibs.mtest; +import mcpp.libs.path_identity; + +using namespace mcpplibs::mtest; + +// SUBSYSTEM-LEVEL: a given path keeps its spelling, and identity is a question of its own +// (design 2026-11-27 §4.6, mcpp#1024). + +namespace pi = mcpp::libs::path_identity; + +UTest the_given_spelling_keeps_a_link{"PathIdentity/TheGivenSpellingKeepsALink", [] { + const auto base = std::filesystem::temp_directory_path() / std::format("mcpp-path-identity-{}", std::random_device{}()); + std::filesystem::create_directories(base / "real" / "x"); + std::error_code ec; + std::filesystem::create_directory_symlink(base / "real", base / "link", ec); + if (ec) { std::filesystem::remove_all(base); return; } // no privilege for a link here + const auto viaLink = base / "link" / "." / "x"; + expect(eq(pi::given(viaLink), (base / "link" / "x").lexically_normal())); + expect(fatal(pi::identity(viaLink).has_value())); + expect(eq(*pi::identity(viaLink), *pi::identity(base / "real" / "x"))); + expect(eq(pi::same(viaLink, base / "real" / "x"), std::optional{true})); + expect(eq(pi::same(viaLink, base / "real"), std::optional{false})); + // A path that does not exist yet is resolved as far as it exists. + expect(eq(pi::same(base / "link" / "new", base / "real" / "new"), std::optional{true})); + std::filesystem::remove_all(base); +}}; diff --git a/modules/manifest/src/compat/registry.cppm b/modules/manifest/src/compat/registry.cppm index 6d68a56b8..f01d17e73 100644 --- a/modules/manifest/src/compat/registry.cppm +++ b/modules/manifest/src/compat/registry.cppm @@ -109,6 +109,31 @@ inline constexpr Deprecation kDeprecations[] = { "spelling tells them apart, one of the packages renamed", "build-program/deprecated", "docs/30-build-mcpp.md", }, + { + "reopened-dotted-table", "2026.11.27.1", "2027.3", + "a table that a `[header]` reopens after dotted keys defined it (`[dependencies.compat]` " + "after `compat.libpng = ...` under `[dependencies]`), which TOML 1.0 refuses", + "the header's entries as dotted keys of the table they extend, `compat.zlib = ...`; " + "the next `mcpp add` to that table writes them so", + "manifest/deprecated", "docs/05-dependencies.md", + }, + { + "implicit-default-environment", "2026.11.27.1", "2027.3", + "for a project that states no environment, the union of what the machine's default environment " + "has installed: its libraries on the run-time search path and the link's `--sysroot`, its `bin` " + "on a test's PATH outside Windows", + "a dependency on the package that provides the library or tool, or `[xlings] subos = \"default\"` " + "to state the shared environment", + "manifest/deprecated", "docs/23-the-project-environment.md", + }, + { + "unmatched-exact-export", "2026.11.27.1", "2027.3", + "an `exports` entry without a wildcard that names a symbol the shared image does not define, " + "dropped from the published set without a word", + "the name the image defines (its mangled form for a C++ name, or the function declared " + "`extern \"C\"`), or the entry under the [target.] that defines it", + "manifest/deprecated", "docs/04-mcpp-toml.md", + }, { "no-universal-flag", "2026.10.30.1", kRemovalFloor, "`mcpp pack --no-universal`, which a pack of one target no longer needs (refused with a " diff --git a/modules/manifest/src/dependency_tables.cppm b/modules/manifest/src/dependency_tables.cppm new file mode 100644 index 000000000..bab5535dc --- /dev/null +++ b/modules/manifest/src/dependency_tables.cppm @@ -0,0 +1,131 @@ +// mcpp.manifest.dependency_tables — the tables of a manifest that hold +// dependencies, enumerated in one place. +// +// A manifest states dependencies in four kinds of table, each of them also +// under a condition: +// +// [dependencies] [target..dependencies] +// [build-dependencies] [target..build-dependencies] +// [dev-dependencies] [target..dev-dependencies] +// [feature-deps.] [target..feature-deps.] +// +// Three parts of mcpp walk them: the reader that loads a manifest, the editor +// behind `mcpp add` and `mcpp remove`, and the normalisation `mcpp publish` +// applies to the manifest an archive carries. Each named the tables itself, +// and the lists differed: the normalisation knew three of the four kinds, so a +// `path` dependency under `[feature-deps.]` was published as written +// and no consumer could reach it (mcpp#962); the editor knew two. The list is +// here, and the three walk it. + +export module mcpp.manifest.dependency_tables; + +import std; +import mcpp.libs.toml; + +export namespace mcpp::manifest { + +enum class DependencyTableKind { Normal, Build, Dev, Feature }; + +// The four kinds, in the order a manifest is read. +inline constexpr DependencyTableKind kDependencyTableKinds[] = { + DependencyTableKind::Normal, DependencyTableKind::Dev, DependencyTableKind::Build, + DependencyTableKind::Feature, +}; + +// The key a kind is written under: `dependencies`, `build-dependencies`, +// `dev-dependencies`, `feature-deps`. +constexpr std::string_view dependency_table_name(DependencyTableKind kind) { + switch (kind) { + case DependencyTableKind::Normal: return "dependencies"; + case DependencyTableKind::Build: return "build-dependencies"; + case DependencyTableKind::Dev: return "dev-dependencies"; + case DependencyTableKind::Feature: return "feature-deps"; + } + return "dependencies"; +} + +// One table of dependencies, where a document has it. +template +struct DependencyTableOf { + DependencyTableKind kind = DependencyTableKind::Normal; + std::string feature; // the feature of a `feature-deps` table; empty otherwise + std::string selector; // the `[target.]` it is under, as written; empty: none + TableT* table = nullptr; + + // The path below its scope, as a header spells it: `dependencies`, + // `feature-deps.`. + std::string section() const { + std::string out(dependency_table_name(kind)); + if (kind == DependencyTableKind::Feature) out += "." + feature; + return out; + } +}; +using DependencyTable = DependencyTableOf; +using ConstDependencyTable = DependencyTableOf; + +// The dependency tables written directly in `scope`: the document's root, or +// the table of one `[target.]`. +std::vector dependency_tables_in(mcpp::libs::toml::Table& scope, + std::string_view selector = {}); +std::vector dependency_tables_in(const mcpp::libs::toml::Table& scope, + std::string_view selector = {}); + +// Every dependency table of a document: the root's, then those of each +// `[target.]` in the order the document holds them. +std::vector dependency_tables(mcpp::libs::toml::Table& root); +std::vector dependency_tables(const mcpp::libs::toml::Table& root); + +} // namespace mcpp::manifest + +namespace mcpp::manifest { + +namespace { + +template +std::vector> tables_in(TableT& scope, std::string_view selector) { + std::vector> out; + for (auto kind : kDependencyTableKinds) { + auto it = scope.find(dependency_table_name(kind)); + if (it == scope.end() || !it->second.is_table()) continue; + auto& table = it->second.as_table(); + if (kind != DependencyTableKind::Feature) { + out.push_back({kind, {}, std::string(selector), &table}); + continue; + } + for (auto& [feature, deps] : table) + if (deps.is_table()) + out.push_back({kind, feature, std::string(selector), &deps.as_table()}); + } + return out; +} + +template +std::vector> all_tables(TableT& root) { + auto out = tables_in(root, {}); + auto target = root.find("target"); + if (target == root.end() || !target->second.is_table()) return out; + for (auto& [selector, row] : target->second.as_table()) { + if (!row.is_table()) continue; + for (auto& t : tables_in(row.as_table(), selector)) out.push_back(std::move(t)); + } + return out; +} + +} // namespace + +std::vector dependency_tables_in(mcpp::libs::toml::Table& scope, + std::string_view selector) { + return tables_in(scope, selector); +} +std::vector dependency_tables_in(const mcpp::libs::toml::Table& scope, + std::string_view selector) { + return tables_in(scope, selector); +} +std::vector dependency_tables(mcpp::libs::toml::Table& root) { + return all_tables(root); +} +std::vector dependency_tables(const mcpp::libs::toml::Table& root) { + return all_tables(root); +} + +} // namespace mcpp::manifest diff --git a/modules/manifest/src/mangle.cppm b/modules/manifest/src/mangle.cppm index 0922f8a6b..e174d116e 100644 --- a/modules/manifest/src/mangle.cppm +++ b/modules/manifest/src/mangle.cppm @@ -20,6 +20,7 @@ export module mcpp.pm.mangle; import std; +import mcpp.libs.code_text; export namespace mcpp::pm { @@ -36,7 +37,9 @@ std::string mangle_name(std::string_view base, std::string_view version); // Primary module roots declared by source text, in first-seen order. Partition // declarations return their owning root; imports, global module fragments and -// bare partition declarations are ignored. +// bare partition declarations are ignored. The text is read as code +// (mcpp.libs.code_text): `export module x;` inside a raw string or a comment +// declares nothing, as it declares nothing to the compiler (mcpp#963). std::vector declared_module_roots(std::string_view source); // The module names a source IMPORTS, in order of appearance, deduplicated. @@ -45,16 +48,14 @@ std::vector declared_module_roots(std::string_view source); // imports (`import :P;`) yield nothing, because none of them names a module // another package could provide. // -// Same line-based matcher as `declared_module_roots`, and the same limits: -// the keyword must open a logical line, so a declaration quoted inside a -// comment whose line starts with `import` is read as one. That is acceptable -// for its one caller -- a diagnostic that suggests a package, and suggests -// nothing when the name matches none. +// The same matcher as `declared_module_roots`, over the same code text: the +// keyword opens a line of code, so an `import` inside a comment or a literal is +// not one. std::vector imported_module_names(std::string_view source); // The headers a source includes, as written with their delimiters (``, `"emit.hpp"`), in -// order of appearance, deduplicated. The same line-based matcher: `#include` must open a logical -// line, so one behind `//` is not read; `#include MACRO` names nothing and yields nothing. +// order of appearance, deduplicated. The same matcher: `#include` opens a line of code, so one in +// a comment or a raw string is not read; `#include MACRO` names nothing and yields nothing. std::vector included_headers(std::string_view source); // Rewrite a single .cppm file's module / import declarations: @@ -68,10 +69,10 @@ std::vector included_headers(std::string_view source); // (`module ;`) are also left intact — they don't name the enclosing // module so they need no rewriting. // -// Single-line comments and string literals are not parsed: the -// matcher requires the keyword (`module` / `import`) to be at the -// start of a logical line (whitespace-only prefix). That covers -// every real-world declaration site without needing a full lexer. +// The keyword (`module` / `import`) opens a line of the code text +// (mcpp.libs.code_text), so a declaration spelled inside a comment or +// a literal is copied as it stands. What is written is the source: a +// comment before the keyword on its line is kept. std::string rewrite_module_decls( std::string_view source, const std::map& rename); @@ -129,7 +130,9 @@ read_name(std::string_view s, std::size_t i) } // namespace -std::vector declared_module_roots(std::string_view source) { +std::vector declared_module_roots(std::string_view text) { + const std::string code = mcpp::libs::code_text::read(text).text; + const std::string_view source = code; std::vector roots; std::size_t lineStart = 0; while (lineStart < source.size()) { @@ -159,7 +162,9 @@ std::vector declared_module_roots(std::string_view source) { return roots; } -std::vector imported_module_names(std::string_view source) { +std::vector imported_module_names(std::string_view text) { + const std::string code = mcpp::libs::code_text::read(text).text; + const std::string_view source = code; std::vector names; std::size_t lineStart = 0; while (lineStart < source.size()) { @@ -188,16 +193,21 @@ std::vector imported_module_names(std::string_view source) { } std::vector included_headers(std::string_view source) { + // The directive is matched in the code text, whose rest of an `#include` + // line is blanked (a header name is not tokens); the name is read from the + // source at the same offsets. + const std::string code = mcpp::libs::code_text::read(source).text; std::vector out; std::size_t lineStart = 0; while (lineStart < source.size()) { auto eol = source.find('\n', lineStart); if (eol == std::string_view::npos) eol = source.size(); auto line = source.substr(lineStart, eol - lineStart); - auto cur = skip_ws(line, 0); - if (cur < line.size() && line[cur] == '#') { - cur = skip_ws(line, cur + 1); - if (auto p = consume_keyword(line, cur, "include"); p != std::string::npos) { + const auto codeLine = std::string_view(code).substr(lineStart, eol - lineStart); + auto cur = skip_ws(codeLine, 0); + if (cur < codeLine.size() && codeLine[cur] == '#') { + cur = skip_ws(codeLine, cur + 1); + if (auto p = consume_keyword(codeLine, cur, "include"); p != std::string::npos) { cur = skip_ws(line, p); const char close = cur < line.size() ? (line[cur] == '<' ? '>' : line[cur] == '"' ? '"' : 0) : 0; if (const auto end = close ? line.find(close, cur + 1) : std::string_view::npos; @@ -219,6 +229,11 @@ std::string rewrite_module_decls( { if (rename.empty()) return std::string(source); + // Matched in the code text, written from the source: the two have the same + // offsets. + const std::string codeText = mcpp::libs::code_text::read(source).text; + const std::string_view code = codeText; + std::string out; out.reserve(source.size()); @@ -226,21 +241,21 @@ std::string rewrite_module_decls( while (i < source.size()) { // We're at the start of a logical line. Capture leading whitespace. std::size_t lineStart = i; - std::size_t afterWs = skip_ws(source, i); + std::size_t afterWs = skip_ws(code, i); // Try to recognize `(export )?(module|import) NAME[:PART][; or ws]`. // On any deviation, copy the line verbatim. std::size_t cur = afterWs; bool hasExport = false; - if (auto p = consume_keyword(source, cur, "export"); p != std::string::npos) { + if (auto p = consume_keyword(code, cur, "export"); p != std::string::npos) { hasExport = true; - cur = skip_ws(source, p); + cur = skip_ws(code, p); } std::string_view kw; - if (auto p = consume_keyword(source, cur, "module"); p != std::string::npos) { + if (auto p = consume_keyword(code, cur, "module"); p != std::string::npos) { kw = "module"; cur = p; - } else if (auto p = consume_keyword(source, cur, "import"); p != std::string::npos) { + } else if (auto p = consume_keyword(code, cur, "import"); p != std::string::npos) { kw = "import"; cur = p; } else { // Not a module/import line — emit the rest of the physical line. @@ -252,11 +267,11 @@ std::string rewrite_module_decls( continue; } - std::size_t afterKw = skip_ws(source, cur); + std::size_t afterKw = skip_ws(code, cur); // Bare partition import / global module fragment: `import :P;` / // `module ;` — no name to rename, copy verbatim. - if (afterKw < source.size() && (source[afterKw] == ':' || source[afterKw] == ';')) { + if (afterKw < code.size() && (code[afterKw] == ':' || code[afterKw] == ';')) { std::size_t eol = source.find('\n', lineStart); if (eol == std::string_view::npos) eol = source.size(); else ++eol; @@ -265,7 +280,7 @@ std::string rewrite_module_decls( continue; } - auto [nameEnd, name] = read_name(source, afterKw); + auto [nameEnd, name] = read_name(code, afterKw); if (nameEnd == std::string::npos) { // Not a recognized declaration. Verbatim. std::size_t eol = source.find('\n', lineStart); diff --git a/modules/manifest/src/manifest.cppm b/modules/manifest/src/manifest.cppm index fe4699884..c1c7d5387 100644 --- a/modules/manifest/src/manifest.cppm +++ b/modules/manifest/src/manifest.cppm @@ -26,5 +26,6 @@ export import mcpp.manifest.platform; export import mcpp.manifest.platform_toml; export import mcpp.manifest.platform_providers; export import mcpp.manifest.key_registry; +export import mcpp.manifest.dependency_tables; export import mcpp.pm.compat.workspace_position; export import mcpp.pm.compat.registry; diff --git a/modules/manifest/src/platform.cppm b/modules/manifest/src/platform.cppm index afd3949f4..9f258a711 100644 --- a/modules/manifest/src/platform.cppm +++ b/modules/manifest/src/platform.cppm @@ -272,6 +272,7 @@ struct RowSpec { std::string march, mabi, codeModel, multilib, linkEmulation; std::vector flags, descriptorKeys, companions, linkWithoutMain, interfaces; bool standard = true, exact = false, exeSuffixFixed = false, interfacesStated = false; + std::int64_t dlopenStaticTls = 0; // bytes; 0: unstated Origin origin; }; @@ -414,7 +415,7 @@ inline constexpr std::string_view kDefineKeys[] = { "triple", "tier", "note", "standard", "exact", "clang-triple", "gcc-triple", "object-format", "family", "data-model", "exe-suffix", "shared-suffix", "loader", "execution", "march", "mabi", "code-model", "multilib", "flags", "link-emulation", "descriptor-keys", "companions", "exceptions", - "exe-suffix-fixed", "link-without-main", "interfaces", + "exe-suffix-fixed", "link-without-main", "interfaces", "dlopen-static-tls", }; inline constexpr std::string_view kProviderKeys[] = { "name", "serves", "priority", "hosts", "pairs", "toolchain", "sysroot", "linkage", "base", diff --git a/modules/manifest/src/platform_toml.cppm b/modules/manifest/src/platform_toml.cppm index 32770f0a2..ced47f0c8 100644 --- a/modules/manifest/src/platform_toml.cppm +++ b/modules/manifest/src/platform_toml.cppm @@ -706,6 +706,11 @@ std::expected Reader::define(const toml::Table& t, std::st if (!it->second.is_bool()) return std::unexpected(std::format("{}.{} must be true or false", where, key)); *to = it->second.as_bool(); } + if (auto it = t.find("dlopen-static-tls"); it != t.end()) { + if (!it->second.is_int() || it->second.as_int() <= 0) + return std::unexpected(std::format("{}.dlopen-static-tls is a positive number of bytes", where)); + r.dlopenStaticTls = it->second.as_int(); + } // `arch-os` or `arch-os-env`, each segment of letters, digits, `_` and `.`. std::size_t segments = 1; for (char c : r.triple) segments += c == '-'; diff --git a/modules/manifest/src/toml.cppm b/modules/manifest/src/toml.cppm index 8a7625cd8..c1b82a619 100644 --- a/modules/manifest/src/toml.cppm +++ b/modules/manifest/src/toml.cppm @@ -4,6 +4,7 @@ export module mcpp.manifest.toml; import mcpp.manifest.types; import mcpp.manifest.key_registry; +import mcpp.manifest.dependency_tables; import mcpp.manifest.cfg_selector; import mcpp.manifest.platform; import mcpp.manifest.platform_toml; @@ -621,20 +622,42 @@ std::expected load(const std::filesystem::path& path, std::string default_template(std::string_view packageName); // Shared source-preserving editor used by both `mcpp add` and scaffold -// self-dependency injection. Identity is structured; formatting is emitted in -// the canonical default table / namespace-subtable form. +// self-dependency injection. Identity is structured; the entry is written in +// the form the table already uses for its namespace (SPEC-004 §9): +// +// a `[
.]` header exists the short key in that section +// otherwise the dotted key `.` in `[
]` +// +// A header that reopens a table dotted keys defined (TOML 1.0 forbids it; an +// older `mcpp add` wrote it, mcpp#964) is rewritten by the edit of that table +// as the dotted keys it holds. struct DependencyTextEdit { std::string namespace_; std::string shortName; std::string version; std::vector features; - bool dev = false; + DependencyTableKind table = DependencyTableKind::Normal; // not Feature }; std::expected upsert_dependency_text(std::string_view source, const DependencyTextEdit& edit); +// The removal `mcpp remove` makes: the entry of the exact PackageId in the one +// table `table` names, in each spelling the reader takes for it (a bare key of +// the default namespace, the dotted key, its quoted form, the short key under +// `[
.]`, an older `[
.]` block); a namespace header left +// with no entry goes with it. nullopt: the table holds no such entry. +std::expected, std::string> +remove_dependency_text(std::string_view source, std::string_view namespace_, + std::string_view shortName, DependencyTableKind table = DependencyTableKind::Normal); + +// The tables a header and a dotted key both define, as the deprecation +// `reopened-dotted-table` names them: `[dependencies.compat]`, with the +// dotted spelling that replaces it. Read from the text, so a manifest whose +// other keys fail still says it. +std::vector reopened_dotted_tables(std::string_view text); + // Where the `key = value` line that begins at `lineStart` ends: the newline // after its value, or the end of `text`. An inline table or an array may // continue over the following lines (TOML 1.1 inline tables, any array), so @@ -1127,9 +1150,18 @@ std::expected parse_string(std::string_view content, auto m = parse_document(*doc, origin, ctx); if (!m && m.error().line == 0) locate_named_key(m.error(), *doc); if (m) record_declared_keys(*doc); + if (m) + for (auto const& r : doc->redefinitions()) m->reopenedTables.push_back(r.path); return m; } +std::vector reopened_dotted_tables(std::string_view text) { + std::vector out; + if (auto doc = t::parse(text)) + for (auto const& r : doc->redefinitions()) out.push_back(r.path); + return out; +} + namespace { // The reader of one manifest document. `parse_string` gives it the text's // document; the workspace layer gives it the document under `workspace.` @@ -1367,9 +1399,24 @@ std::expected parse_document(const t::Document& documen // [profile.] — bundled build settings. if (auto* profile_table = doc->get_table("profile"); profile_table && !profile_table->empty()) { + // The keys a profile has. One outside them was dropped without a word + // (`opt_level = 3` in an example read as no key, the profile's `opt` + // its default). + static constexpr std::string_view kProfileKeys[] = { + "opt", "debug", "lto", "strip", "ndebug", "trim_paths", "bmi_cutoff", "split_debuginfo", + "dependency_linkage", "dependency_debug", "cflags", "cxxflags", "ldflags", "dialect_cxxflags", + }; for (auto& [pname, pval] : *profile_table) { if (!pval.is_table()) continue; auto& tt = pval.as_table(); + for (auto const& [key, _] : tt) + if (std::ranges::find(kProfileKeys, key) == std::end(kProfileKeys)) { + std::string supported; + for (auto k : kProfileKeys) supported += std::format("{}{}", supported.empty() ? "" : ", ", k); + m.schemaWarnings.push_back(std::format( + "[profile.{}] has unsupported key '{}' (ignored). Supported keys: {}.", + pname, key, supported)); + } Profile pr; if (auto it = tt.find("opt"); it != tt.end()) { if (it->second.is_string()) pr.optLevel = it->second.as_string(); @@ -1428,6 +1475,7 @@ std::expected parse_document(const t::Document& documen read_list("cflags", pr.cflags); read_list("cxxflags", pr.cxxflags); read_list("ldflags", pr.ldflags); + read_list("dialect_cxxflags", pr.dialectCxxflags); m.profiles[pname] = pr; } } @@ -3108,30 +3156,20 @@ std::expected parse_document(const t::Document& documen }); } }; - auto load_deps = [&](std::string_view section, std::map& out) - -> std::expected - { - auto* tt = doc->get_table(section); - if (!tt) return {}; - auto r = load_deps_table(section, *tt, out); - if (r) mark_required_quoting(out); - return r; - }; - if (auto r = load_deps("dependencies", m.dependencies); !r) return std::unexpected(r.error()); - if (auto r = load_deps("dev-dependencies", m.devDependencies); !r) return std::unexpected(r.error()); - if (auto r = load_deps("build-dependencies", m.buildDependencies); !r) return std::unexpected(r.error()); - - // [feature-deps.] — optional dependencies activated by a feature - // (Stage 2a). Each sub-table is loaded with the same dependency loader as - // [dependencies], keyed by the feature name. - if (auto* fdeps = doc->get_table("feature-deps")) { - for (auto& [fname, fval] : *fdeps) { - if (!fval.is_table()) continue; - if (auto r = load_deps("feature-deps." + std::string(fname), - m.featureDeps[fname]); !r) - return std::unexpected(r.error()); - m.featuresMap.try_emplace(fname, std::vector{}); // register - } + // Every unconditional table of dependencies, in the one enumeration the + // editor and the publish normalisation also walk + // (mcpp.manifest.dependency_tables). A `[feature-deps.]` table is + // loaded by the loader of `[dependencies]` and registers its feature + // (Stage 2a). + for (auto const& t : dependency_tables_in(std::as_const(doc->root()))) { + const bool feature = t.kind == DependencyTableKind::Feature; + auto& out = feature ? m.featureDeps[t.feature] + : t.kind == DependencyTableKind::Dev ? m.devDependencies + : t.kind == DependencyTableKind::Build ? m.buildDependencies + : m.dependencies; + if (auto r = load_deps_table(t.section(), *t.table, out); !r) return std::unexpected(r.error()); + mark_required_quoting(out); + if (feature) m.featuresMap.try_emplace(t.feature, std::vector{}); // register } // [toolchain] — platform → "pkg@version" map (docs/21) @@ -5113,18 +5151,6 @@ std::expected parse_document(const t::Document& documen // as the global [dependencies]) into the deferred config, under the // table's full name so that a message and the resolution record // name the conditional table rather than the unconditional one. - auto read_deps = [&](const char* key, std::map& out) - -> std::expected - { - if (auto f = body.find(key); f != body.end() && f->second.is_table()) { - auto r = load_deps_table( - std::format("target.{}.{}", toml_header_key(triple), key), - f->second.as_table(), out, key); - if (r) mark_required_quoting(out); - return r; - } - return {}; - }; // [target..test] (mcpp#942): the test programs of the // targets the predicate selects, appended to `[test] discover`. // Only `discover`: the other `[test]` keys shape the test build @@ -5159,30 +5185,35 @@ std::expected parse_document(const t::Document& documen for (auto& e : tv.as_array()) cc.testDiscover.push_back(e.as_string()); } } - if (auto r = read_deps("dependencies", cc.dependencies); !r) return std::unexpected(r.error()); - if (auto r = read_deps("dev-dependencies", cc.devDependencies); !r) return std::unexpected(r.error()); - if (auto r = read_deps("build-dependencies", cc.buildDependencies); !r) return std::unexpected(r.error()); + // The conditional tables of dependencies, by the same enumeration + // as the unconditional ones. + // // [target..feature-deps.] (#359). The feature // itself is registered UNCONDITIONALLY: whether the platform // matches decides what the feature pulls in, not whether the // feature exists. Otherwise requesting it on a non-matching - // platform would trip the unknown-feature diagnostic. - if (auto f = body.find("feature-deps"); - f != body.end() && f->second.is_table()) { - for (auto& [fname, fval] : f->second.as_table()) { - if (!fval.is_table()) continue; - // The lookup keeps the spelling this table has always - // been resolved against; only the name a reader sees - // changes, which used to arrive in double brackets. - if (auto r = load_deps_table( - std::format("target.{}.feature-deps.{}", - toml_header_key(triple), fname), - fval.as_table(), cc.featureDeps[std::string(fname)], - std::format("[target.{}.feature-deps.{}]", triple, fname)); !r) + // platform would trip the unknown-feature diagnostic. Its lookup + // keeps the spelling this table has always been resolved against; + // only the name a reader sees changes, which used to arrive in + // double brackets. + for (auto const& t : dependency_tables_in(std::as_const(body), triple)) { + const auto name = dependency_table_name(t.kind); + if (t.kind != DependencyTableKind::Feature) { + auto& out = t.kind == DependencyTableKind::Dev ? cc.devDependencies + : t.kind == DependencyTableKind::Build ? cc.buildDependencies + : cc.dependencies; + if (auto r = load_deps_table(std::format("target.{}.{}", toml_header_key(triple), name), + *t.table, out, name); !r) return std::unexpected(r.error()); - m.featuresMap.try_emplace(std::string(fname), - std::vector{}); + mark_required_quoting(out); + continue; } + if (auto r = load_deps_table( + std::format("target.{}.feature-deps.{}", toml_header_key(triple), t.feature), + *t.table, cc.featureDeps[t.feature], + std::format("[target.{}.feature-deps.{}]", triple, t.feature)); !r) + return std::unexpected(r.error()); + m.featuresMap.try_emplace(t.feature, std::vector{}); } // `[target..xlings.workspace]` and // `[target..feature-xlings.]` — the TARGET axis of the tool @@ -6092,6 +6123,101 @@ std::size_t assignment_end(std::string_view text, std::size_t lineStart) { return text.size(); } +namespace { + +// The text editor's view of a manifest: a section is a `[header]` line and +// the lines up to the next header; an entry is the `key = value` that begins a +// line of it and ends where its value closes (`assignment_end`). +struct SectionSpan { + std::size_t headerStart; + std::size_t headerEnd; + std::size_t bodyStart; + std::size_t sectionEnd; +}; + +std::string_view trim_line(std::string_view line) { + while (!line.empty() + && (line.front() == ' ' || line.front() == '\t')) { + line.remove_prefix(1); + } + while (!line.empty() + && (line.back() == ' ' || line.back() == '\t' + || line.back() == '\r')) { + line.remove_suffix(1); + } + return line; +} + +bool section_header_matches(std::string_view line, std::string_view header) { + line = trim_line(line); + if (!line.starts_with(header)) return false; + line.remove_prefix(header.size()); + line = trim_line(line); + return line.empty() || line.front() == '#'; +} + +std::optional find_section(std::string_view text, std::string_view header) { + std::optional result; + std::size_t lineStart = 0; + while (lineStart <= text.size()) { + auto newline = text.find('\n', lineStart); + auto lineEnd = newline == std::string_view::npos + ? text.size() : newline; + auto line = text.substr(lineStart, lineEnd - lineStart); + if (!result && section_header_matches(line, header)) { + result = SectionSpan{ + .headerStart = lineStart, + .headerEnd = lineEnd, + .bodyStart = newline == std::string_view::npos + ? lineEnd : lineEnd + 1, + .sectionEnd = text.size(), + }; + } else if (result) { + auto stripped = trim_line(line); + if (!stripped.empty() && stripped.front() == '[') { + result->sectionEnd = lineStart; + break; + } + } + if (newline == std::string_view::npos) break; + lineStart = newline + 1; + } + return result; +} + +std::optional> +key_line_span(std::string_view text, const SectionSpan& section, std::string_view key) { + const auto quotedKey = std::format("\"{}\"", key); + std::size_t lineStart = section.bodyStart; + while (lineStart < section.sectionEnd) { + auto newline = text.find('\n', lineStart); + auto lineEnd = newline == std::string_view::npos + ? text.size() : newline; + if (lineEnd > section.sectionEnd) lineEnd = section.sectionEnd; + auto line = trim_line(text.substr(lineStart, lineEnd - lineStart)); + auto assignment_for = [&](std::string_view candidate) { + if (!line.starts_with(candidate)) return false; + auto rest = line.substr(candidate.size()); + while (!rest.empty() + && (rest.front() == ' ' || rest.front() == '\t')) { + rest.remove_prefix(1); + } + return !rest.empty() && rest.front() == '='; + }; + if (!line.starts_with('#') + && (assignment_for(key) || assignment_for(quotedKey))) { + return std::pair{lineStart, assignment_end(text, lineStart)}; + } + if (newline == std::string_view::npos + || newline >= section.sectionEnd) break; + lineStart = newline + 1; + } + return std::nullopt; +} + + +} // namespace + std::expected upsert_dependency_text(std::string_view source, const DependencyTextEdit& edit) { @@ -6151,138 +6277,93 @@ upsert_dependency_text(std::string_view source, quoted_list(edit.features)); } - struct SectionSpan { - std::size_t headerStart; - std::size_t headerEnd; - std::size_t bodyStart; - std::size_t sectionEnd; - }; + if (edit.table == DependencyTableKind::Feature) + return std::unexpected("dependency edit names a feature table, which `mcpp add` does not write"); + std::string text(source); + const std::string table(dependency_table_name(edit.table)); + const std::string baseHeader = std::format("[{}]", table); + const bool defaultNamespace = edit.namespace_ == kDefaultNamespace; + const std::string subHeader = std::format("[{}.{}]", table, edit.namespace_); + const std::string dotted = std::format("{}.{}", edit.namespace_, edit.shortName); - auto trim = [](std::string_view line) { - while (!line.empty() - && (line.front() == ' ' || line.front() == '\t')) { - line.remove_prefix(1); - } - while (!line.empty() - && (line.back() == ' ' || line.back() == '\t' - || line.back() == '\r')) { - line.remove_suffix(1); - } - return line; + auto erase_span = [&](std::pair span) { + auto end = span.second; + if (end < text.size() && text[end] == '\n') ++end; + text.erase(span.first, end - span.first); }; - - auto section_header_matches = [&](std::string_view line, - std::string_view header) { - line = trim(line); - if (!line.starts_with(header)) return false; - line.remove_prefix(header.size()); - line = trim(line); - return line.empty() || line.front() == '#'; + auto insert_in = [&](const SectionSpan& section, const std::string& entry) { + if (section.bodyStart == section.headerEnd) text.insert(section.bodyStart, "\n" + entry); + else text.insert(section.bodyStart, entry + "\n"); }; - auto find_section = [&](std::string_view text, - std::string_view header) - -> std::optional { - std::optional result; - std::size_t lineStart = 0; - while (lineStart <= text.size()) { - auto newline = text.find('\n', lineStart); - auto lineEnd = newline == std::string_view::npos - ? text.size() : newline; - auto line = text.substr(lineStart, lineEnd - lineStart); - if (!result && section_header_matches(line, header)) { - result = SectionSpan{ - .headerStart = lineStart, - .headerEnd = lineEnd, - .bodyStart = newline == std::string_view::npos - ? lineEnd : lineEnd + 1, - .sectionEnd = text.size(), - }; - } else if (result) { - auto stripped = trim(line); - if (!stripped.empty() && stripped.front() == '[') { - result->sectionEnd = lineStart; - break; + // A HEADER THAT REOPENS THE DOTTED TABLE (mcpp#964). The entries of + // `[
.]` move into `[
]` as dotted keys, comments with them, + // and the header goes: the one form both TOML and this file then hold. + if (!defaultNamespace) { + auto doc = mcpp::libs::toml::parse(source); + const auto path = std::format("{}.{}", table, edit.namespace_); + if (doc && std::ranges::any_of(doc->redefinitions(), [&](auto const& r) { return r.path == path; })) + if (auto sub = find_section(text, subHeader)) { + std::string moved; + std::size_t at = sub->bodyStart; + while (at < sub->sectionEnd) { + const auto stripped = trim_line(std::string_view(text).substr(at, text.find('\n', at) - at)); + const auto end = std::min(stripped.empty() || stripped.front() == '#' + ? std::min(text.find('\n', at), text.size()) + : assignment_end(text, at), + sub->sectionEnd); + auto line = std::string(text.substr(at, end - at)); + if (!stripped.empty() && stripped.front() != '#') { + const auto lead = line.find_first_not_of(" \t"); + line = std::format("{}.{}", edit.namespace_, line.substr(lead)); + } + if (!trim_line(line).empty()) moved += line + "\n"; + at = end < text.size() ? end + 1 : end; } - } - if (newline == std::string_view::npos) break; - lineStart = newline + 1; - } - return result; - }; - - auto key_line_span = [&](std::string_view text, - const SectionSpan& section, - std::string_view key) - -> std::optional> { - const auto quotedKey = std::format("\"{}\"", key); - std::size_t lineStart = section.bodyStart; - while (lineStart < section.sectionEnd) { - auto newline = text.find('\n', lineStart); - auto lineEnd = newline == std::string_view::npos - ? text.size() : newline; - if (lineEnd > section.sectionEnd) lineEnd = section.sectionEnd; - auto line = trim(text.substr(lineStart, lineEnd - lineStart)); - auto assignment_for = [&](std::string_view candidate) { - if (!line.starts_with(candidate)) return false; - auto rest = line.substr(candidate.size()); - while (!rest.empty() - && (rest.front() == ' ' || rest.front() == '\t')) { - rest.remove_prefix(1); + text.erase(sub->headerStart, sub->sectionEnd - sub->headerStart); + while (text.ends_with("\n\n")) text.pop_back(); + if (auto base = find_section(text, baseHeader)) { + if (!moved.empty() && moved.back() == '\n') moved.pop_back(); + insert_in(*base, moved); } - return !rest.empty() && rest.front() == '='; - }; - if (!line.starts_with('#') - && (assignment_for(key) || assignment_for(quotedKey))) { - return std::pair{lineStart, assignment_end(text, lineStart)}; - } - if (newline == std::string_view::npos - || newline >= section.sectionEnd) break; - lineStart = newline + 1; - } - return std::nullopt; - }; - - std::string text(source); - const std::string table = edit.dev - ? "dev-dependencies" : "dependencies"; - const std::string baseHeader = std::format("[{}]", table); - const bool defaultNamespace = edit.namespace_ == kDefaultNamespace; - - // Retained flat dotted spellings are removed before canonical namespace - // subtable emission. The parsed identity gate above ensures this edits the - // exact PackageId, not a short-name substring match. - // The default namespace's dotted spelling (`mcpplibs.cmdline = ...`) is - // the same package as the bare one and is removed as well. - { - const std::string dotted = defaultNamespace - ? std::format("{}.{}", edit.namespace_, edit.shortName) : spelling; - if (auto base = find_section(text, baseHeader)) { - if (auto legacy = key_line_span(text, *base, dotted)) { - auto eraseEnd = legacy->second; - if (eraseEnd < text.size() && text[eraseEnd] == '\n') - ++eraseEnd; - text.erase(legacy->first, eraseEnd - legacy->first); } - } } - const std::string sectionHeader = defaultNamespace - ? baseHeader - : std::format("[{}.{}]", table, edit.namespace_); - const std::string line = std::format("{} = {}", edit.shortName, value); - if (auto section = find_section(text, sectionHeader)) { - if (auto existing = key_line_span(text, *section, edit.shortName)) { - text.replace(existing->first, existing->second - existing->first, - line); - } else if (section->bodyStart == section->headerEnd) { - text.insert(section->bodyStart, "\n" + line); + // The default namespace's dotted spelling (`mcpplibs.cmdline = ...`) is the + // same package as the bare one: it is replaced by the bare key. + const std::string line = std::format("{} = {}", defaultNamespace ? edit.shortName : dotted, value); + const std::string shortLine = std::format("{} = {}", edit.shortName, value); + if (defaultNamespace) { + auto base = find_section(text, baseHeader); + if (base) + if (auto legacy = key_line_span(text, *base, dotted)) erase_span(*legacy); + base = find_section(text, baseHeader); + if (!base) { + if (!text.empty() && text.back() != '\n') text += '\n'; + text += std::format("\n{}\n{}\n", baseHeader, line); + } else if (auto existing = key_line_span(text, *base, edit.shortName)) { + text.replace(existing->first, existing->second - existing->first, line); + } else { + insert_in(*base, line); + } + } else if (auto sub = find_section(text, subHeader)) { + // The namespace's own header: the short key there, and no dotted twin. + if (auto existing = key_line_span(text, *sub, edit.shortName)) { + text.replace(existing->first, existing->second - existing->first, shortLine); + } else { + insert_in(*sub, shortLine); + } + if (auto base = find_section(text, baseHeader)) + if (auto twin = key_line_span(text, *base, dotted)) erase_span(*twin); + } else if (auto base = find_section(text, baseHeader)) { + if (auto existing = key_line_span(text, *base, dotted)) { + text.replace(existing->first, existing->second - existing->first, line); } else { - text.insert(section->bodyStart, line + "\n"); + insert_in(*base, line); } } else { if (!text.empty() && text.back() != '\n') text += '\n'; - text += std::format("\n{}\n{}\n", sectionHeader, line); + text += std::format("\n{}\n{}\n", baseHeader, line); } auto reparsed = parse_string(text); @@ -6291,8 +6372,13 @@ upsert_dependency_text(std::string_view source, "dependency edit produced invalid manifest: {}", reparsed.error().format())); } - auto const& dependencies = edit.dev - ? reparsed->devDependencies : reparsed->dependencies; + auto const& dependencies = edit.table == DependencyTableKind::Dev ? reparsed->devDependencies + : edit.table == DependencyTableKind::Build ? reparsed->buildDependencies + : reparsed->dependencies; + if (auto doc = mcpp::libs::toml::parse(text); doc && !doc->redefinitions().empty()) + return std::unexpected(std::format( + "dependency edit would write the table '{}' twice, by a header and by dotted keys", + doc->redefinitions().front().path)); auto exact = std::ranges::find_if( dependencies, [&](auto const& item) { auto const& dep = item.second; @@ -6310,6 +6396,76 @@ upsert_dependency_text(std::string_view source, } +std::expected, std::string> +remove_dependency_text(std::string_view source, std::string_view namespace_, + std::string_view shortName, DependencyTableKind table) { + auto original = parse_string(source); + if (!original) + return std::unexpected(std::format("invalid manifest before dependency edit: {}", + original.error().format())); + if (table == DependencyTableKind::Feature) + return std::unexpected("dependency edit names a feature table, which `mcpp remove` does not edit"); + std::string text(source); + const std::string name(dependency_table_name(table)); + const bool defaultNamespace = namespace_ == kDefaultNamespace; + const auto dotted = std::format("{}.{}", namespace_, shortName); + bool changed = false; + auto erase_span = [&](std::pair span) { + auto end = span.second; + if (end < text.size() && text[end] == '\n') ++end; + text.erase(span.first, end - span.first); + changed = true; + }; + // A section with no entry left: only comments and blank lines. + auto empty_section = [&](const SectionSpan& sec) { + for (std::size_t at = sec.bodyStart; at < sec.sectionEnd;) { + const auto nl = std::min(text.find('\n', at), sec.sectionEnd); + const auto line = trim_line(std::string_view(text).substr(at, nl - at)); + if (!line.empty() && line.front() != '#') return false; + at = nl + 1; + } + return true; + }; + + if (auto base = find_section(text, std::format("[{}]", name))) { + if (auto span = key_line_span(text, *base, defaultNamespace ? std::string(shortName) : dotted)) + erase_span(*span); + else if (defaultNamespace) + if (auto legacy = key_line_span(text, *base, dotted)) erase_span(*legacy); + } + if (!defaultNamespace) + if (auto sub = find_section(text, std::format("[{}.{}]", name, namespace_))) + if (auto span = key_line_span(text, *sub, shortName)) { + erase_span(*span); + if (auto after = find_section(text, std::format("[{}.{}]", name, namespace_)); + after && empty_section(*after)) + text.erase(after->headerStart, after->sectionEnd - after->headerStart); + } + // An older shape: the default namespace's package as a block of its own, + // `[
.]` holding its source. + if (!changed && defaultNamespace) + if (auto block = find_section(text, std::format("[{}.{}]", name, shortName))) { + text.erase(block->headerStart, block->sectionEnd - block->headerStart); + changed = true; + } + if (!changed) return std::optional{}; + while (text.ends_with("\n\n")) text.pop_back(); + + auto reparsed = parse_string(text); + if (!reparsed) + return std::unexpected(std::format("dependency edit produced invalid manifest: {}", + reparsed.error().format())); + auto const& family = table == DependencyTableKind::Dev ? reparsed->devDependencies + : table == DependencyTableKind::Build ? reparsed->buildDependencies + : reparsed->dependencies; + if (std::ranges::any_of(family, [&](auto const& item) { + return item.second.namespace_ == namespace_ && item.second.shortName == shortName; + })) + return std::unexpected(std::format( + "dependency edit left the exact PackageId ({}, {}) in [{}]", namespace_, shortName, name)); + return std::optional{std::move(text)}; +} + // ── the lib root that actually exists ──────────────────────────────────── // // LIVES HERE, NOT IN mcpp.manifest.types, AND THE REASON IS MEASURED. diff --git a/modules/manifest/src/types.cppm b/modules/manifest/src/types.cppm index 3d8fdfcb1..f261e136e 100644 --- a/modules/manifest/src/types.cppm +++ b/modules/manifest/src/types.cppm @@ -2373,10 +2373,17 @@ struct Profile { // `dev` and `debug`, else the profile's `debug`. std::string dependencyDebug; bool dependencyDebugDeclared = false; - // Passthrough escape hatch (fixed keys, open values — I6 completeness): + // Passthrough escape hatch (fixed keys, open values — I6 completeness). + // `cflags` and `cxxflags` are root-position words: they reach the units of + // the build's roots (the root package, the selected members), as `[build] + // cflags` does (SPEC-004 §9). `ldflags` reaches every image. std::vector cflags; std::vector cxxflags; std::vector ldflags; + // The graph-wide words of the profile (mcpp#1025): `[build] + // dialect_cxxflags`'s meaning and reach -- the standard library module, + // the scan and every C++ unit of the graph -- after `[build]`'s own. + std::vector dialectCxxflags; }; struct Manifest { @@ -2795,6 +2802,13 @@ struct Manifest { // --strict, escalates them to errors — mirroring the feature/platform path. std::vector schemaWarnings; + // The tables the text defines by a `[header]` and by dotted keys both + // (`[dependencies.compat]` after `compat.libpng = ...` under + // `[dependencies]`), as dotted paths. TOML 1.0 refuses the file; mcpp reads + // it, which an older `mcpp add` relied on (mcpp#964), and reports it as + // COMPAT(reopened-dotted-table). + std::vector reopenedTables; + // `[package.metadata]`, as a JSON object text; empty when the manifest has // none (#647 E1). // diff --git a/modules/manifest/tests/test_feature_catalog.cpp b/modules/manifest/tests/test_feature_catalog.cpp index 3ec989e1e..532fcdb50 100644 --- a/modules/manifest/tests/test_feature_catalog.cpp +++ b/modules/manifest/tests/test_feature_catalog.cpp @@ -119,3 +119,22 @@ package = { expect(fatal(!bad.has_value())); expect(bad.error().format().contains("features.x.description must be a string")) << bad.error().format(); }}; + +// The third source (mcpp#1018): an installed payload answers from the `mcpp.toml` it carries, +// read from its directory, and states what the manifest and the descriptor state. +UTest an_installed_manifest_states_the_same_catalogue{"FeatureCatalog/InstalledManifestSameCatalogue", [] { + const auto dir = std::filesystem::temp_directory_path() + / std::format("mcpp-feature-catalog-{}", std::random_device{}()); + std::filesystem::create_directories(dir / "src"); + { std::ofstream(dir / "mcpp.toml") << kToml; } + { std::ofstream(dir / "src" / "widget.cppm") << "export module widget;\n"; } + auto installed = mm::load(dir / "mcpp.toml"); + std::filesystem::remove_all(dir); + if (auto&& failed = expect(fatal(installed.has_value())); !failed) failed << installed.error().format(); + auto fromToml = mm::parse_string(kToml); + expect(fatal(fromToml.has_value())); + const auto a = mm::feature_catalog(*installed); + const auto b = mm::feature_catalog(*fromToml); + expect(fatal(eq(a.size(), b.size()))); + for (std::size_t i = 0; i < a.size(); ++i) expect(eq(a[i].description, b[i].description)) << a[i].name; +}}; diff --git a/modules/manifest/tests/test_included_headers.cpp b/modules/manifest/tests/test_included_headers.cpp index c3976135f..c89c8ebcb 100644 --- a/modules/manifest/tests/test_included_headers.cpp +++ b/modules/manifest/tests/test_included_headers.cpp @@ -23,3 +23,41 @@ UTest a_commented_or_computed_include_names_nothing{"IncludedHeaders/CommentedOr expect(mcpp::pm::included_headers("// #include \n#include HEADER\n#include <>\n" "#includes \n#define include\n").empty()); }}; + +// mcpp#963: the functions read the code text, so a declaration spelled in a raw string, a comment +// or a literal is none. +UTest a_declaration_in_a_raw_string_declares_nothing{"ModuleNames/ADeclarationInARawStringDeclaresNothing", [] { + const std::string_view text = + "export module real;\n" + "const char* usage = R\"(\n" + "export module quoted;\n" + "import quoted.dep;\n" + "#include \n" + ")\";\n" + "/*\n" + "module commented;\n" + "*/\n" + "import real.dep;\n" + "#include \n"; + expect(eq(mcpp::pm::declared_module_roots(text), std::vector{"real"})); + expect(eq(mcpp::pm::imported_module_names(text), std::vector{"real.dep"})); + expect(eq(mcpp::pm::included_headers(text), std::vector{""})); +}}; + +UTest a_rename_leaves_what_is_not_code{"ModuleNames/ARenameLeavesWhatIsNotCode", [] { + const std::string_view text = + "/* the module */ export module lib;\n" + "const char* s = R\"(\n" + "import lib;\n" + ")\";\n" + "// import lib;\n" + "import lib;\n"; + const auto out = mcpp::pm::rewrite_module_decls(text, {{"lib", "lib__v1__mcpp"}}); + expect(eq(out, std::string( + "/* the module */ export module lib__v1__mcpp;\n" + "const char* s = R\"(\n" + "import lib;\n" + ")\";\n" + "// import lib;\n" + "import lib__v1__mcpp;\n"))); +}}; diff --git a/modules/toolchain-model/build.mcpp b/modules/toolchain-model/build.mcpp index 2a31aa4b8..469e769d2 100644 --- a/modules/toolchain-model/build.mcpp +++ b/modules/toolchain-model/build.mcpp @@ -18,7 +18,7 @@ constexpr std::string_view kRowKeys[] = { "triple", "tier", "note", "standard", "exact", "march", "mabi", "code-model", "multilib", "flags", "link-emulation", "clang-triple", "gcc-triple", "family", "object-format", "data-model", "exe-suffix", "shared-suffix", "loader", "execution", "companions", "exceptions", "exe-suffix-fixed", - "link-without-main", "interfaces", + "link-without-main", "interfaces", "dlopen-static-tls", }; constexpr std::string_view kProviderKeys[] = { "name", "serves", "priority", "hosts", "probe", "toolchain", "pairs", "sysroot", "linkage", @@ -141,13 +141,19 @@ std::string row_entry(const toml::Table& t, Arrays& arrays, std::setsecond.is_bool()) throw Failure{std::format("{}: `exe-suffix-fixed` is not a boolean", where)}; suffixFixed = it->second.as_bool(); } + std::int64_t dlopenStaticTls = 0; + if (auto it = t.find("dlopen-static-tls"); it != t.end()) { + if (!it->second.is_int() || it->second.as_int() <= 0) + throw Failure{std::format("{}: `dlopen-static-tls` is a positive number of bytes", where)}; + dlopenStaticTls = it->second.as_int(); + } return std::format( " {{ .triple = {}, .arch = {}, .os = {}, .env = {}, .tier = {}, .note = {}, .standard = {}, " ".exact = {}, .march = {}, .mabi = {}, " ".codeModel = {}, .multilib = {}, .flags = {}, .linkEmulation = {}, .clangTriple = {}, " ".gccTriple = {}, .objectFormat = {}, .family = {}, .dataModel = {}, .exeSuffix = {}, .sharedSuffix = {}, " ".loader = {}, .execution = {}, .companions = {}, .linkWithoutMain = {}, .exceptions = {}, " - ".exeSuffixFixed = {}, .interfaces = {}, .interfacesStated = {} }},\n", + ".exeSuffixFixed = {}, .interfaces = {}, .interfacesStated = {}, .dlopenStaticTls = {} }},\n", lit(triple), lit(seg[0]), lit(seg[1]), lit(seg.size() == 3 ? seg[2] : std::string{}), lit(tier), lit(text(t, "note", where)), standard ? "true" : "false", exact ? "true" : "false", lit(text(t, "march", where)), lit(text(t, "mabi", where)), @@ -159,7 +165,8 @@ std::string row_entry(const toml::Table& t, Arrays& arrays, std::set& rows) { diff --git a/modules/toolchain-model/data/builtin.toml b/modules/toolchain-model/data/builtin.toml index 255d5eeda..e5022dc4c 100644 --- a/modules/toolchain-model/data/builtin.toml +++ b/modules/toolchain-model/data/builtin.toml @@ -53,6 +53,12 @@ # the row's executable suffix is part of loading its # programs: a name template (`artifact_name`, `link.exe`) # decides what precedes it, and the name ends in it once +# dlopen-static-tls +# the bytes of the static TLS block the row's loader serves +# an image loaded by `dlopen` whose objects use the +# initial-exec model (`DF_STATIC_TLS`); a shared image above +# it is reported after the link, and refused when its exact +# `exports` say a host loads it by name. Unstated: not checked # # Provider keys # name the provider's name; `builtin:` selects it @@ -135,11 +141,15 @@ # ── Linux ──────────────────────────────────────────────────────────────────── +# glibc serves a library loaded by `dlopen` 512 bytes of static TLS, the +# default of its `glibc.rtld.optional_static_tls` since 2.32; above it, +# `dlopen` fails with "cannot allocate memory in static TLS block" (mcpp#907). [[platform.define]] triple = "x86_64-linux-gnu" loader = "/lib64/ld-linux-x86-64.so.2" tier = "verified" standard = true +dlopen-static-tls = 512 [[platform.define]] triple = "x86_64-linux-musl" @@ -156,6 +166,7 @@ triple = "aarch64-linux-gnu" loader = "/lib/ld-linux-aarch64.so.1" tier = "preview" standard = true +dlopen-static-tls = 512 [[platform.define]] triple = "aarch64-linux-musl" @@ -246,6 +257,7 @@ triple = "i686-linux-gnu" loader = "/lib/ld-linux.so.2" tier = "planned" standard = true +dlopen-static-tls = 512 [[platform.define]] triple = "i686-openkal" diff --git a/modules/toolchain-model/src/target_schema.cppm b/modules/toolchain-model/src/target_schema.cppm index 8ceaece3c..ef77aae0b 100644 --- a/modules/toolchain-model/src/target_schema.cppm +++ b/modules/toolchain-model/src/target_schema.cppm @@ -76,6 +76,11 @@ struct Row { // Read before the system's `interfaces`; unstated: the system's. std::span interfaces; bool interfacesStated = false; + // THE STATIC TLS THE ROW'S LOADER SERVES AN IMAGE LOADED BY `dlopen` + // (mcpp#907), in bytes: what is left of the static block for a library + // whose objects use the initial-exec model (`DF_STATIC_TLS`). A shared + // image above it is reported after the link. 0: unstated, not checked. + std::int64_t dlopenStaticTls = 0; bool defined = false; // stated by a platform package }; diff --git a/modules/toolchain-model/tests/test_dlopen_static_tls.cpp b/modules/toolchain-model/tests/test_dlopen_static_tls.cpp new file mode 100644 index 000000000..f36039916 --- /dev/null +++ b/modules/toolchain-model/tests/test_dlopen_static_tls.cpp @@ -0,0 +1,28 @@ +import std; +import mcpplibs.mtest; +import mcpp.toolchain.target_rows; +import mcpp.toolchain.target_schema; + +using namespace mcpplibs::mtest; + +// THE STATIC TLS A ROW'S LOADER SERVES AN IMAGE LOADED BY `dlopen` (mcpp#907). +// The check after the link is the engine's; how much the loader serves is the +// row's (`dlopen-static-tls`), so the engine names no C library for it. + +UTest the_glibc_rows_state_what_dlopen_serves{"DlopenStaticTls/TheGlibcRowsStateWhatDlopenServes", [] { + // glibc's `glibc.rtld.optional_static_tls`, 512 bytes since 2.32. + for (auto triple : { "x86_64-linux-gnu", "aarch64-linux-gnu", "i686-linux-gnu" }) { + auto const* row = mcpp::toolchain::target::find_row(triple); + expect(row != nullptr); + if (row) expect(eq(row->dlopenStaticTls, std::int64_t{512})); + } +}}; + +UTest a_row_that_states_no_bound_is_not_checked{"DlopenStaticTls/ARowThatStatesNoBoundIsNotChecked", [] { + // musl and the systems that are not glibc's state nothing: 0 is unstated. + for (auto triple : { "x86_64-linux-musl", "aarch64-macos", "x86_64-windows-msvc" }) { + auto const* row = mcpp::toolchain::target::find_row(triple); + expect(row != nullptr); + if (row) expect(eq(row->dlopenStaticTls, std::int64_t{0})); + } +}}; diff --git a/modules/versioning/src/version.cppm b/modules/versioning/src/version.cppm index b05b55474..447adb978 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.26.1"; +inline constexpr std::string_view MCPP_VERSION = "2026.11.27.1"; } // namespace mcpp diff --git a/src/build/build_program.cppm b/src/build/build_program.cppm index 4fe79fc3e..a0acce440 100644 --- a/src/build/build_program.cppm +++ b/src/build/build_program.cppm @@ -459,6 +459,10 @@ struct BuildProgramEnv { // PREPENDED, NOT SUBSTITUTED. A build program legitimately calls `git`, // `python3` or a shell, none of which arrive this way. std::string toolsBin; + // The directories of the tools the dependency graph states, ahead of + // `toolsBin` (design 2026-11-27 §4.2): the PATH of a build program is + // composed as a test's and a run's are (launch_env::child_path). + std::vector statedToolDirs; // THE PROGRAM, COMPILED (mcpp#797). The build programs' graph compiles // every build program of a build in one plan, with its libraries, and // hands each run its binary and the identity it was compiled from; the @@ -901,18 +905,11 @@ contract_env(const fs::path& root, const fs::path& outDir, const BuildProgramEnv // // See `BuildProgramEnv::toolsBin` for why this exists, why it is a prefix // rather than a replacement, and why the decision is not made here. - if (!env.toolsBin.empty()) { - std::string path = env.toolsBin; - // THE INHERITED VALUE IS READ HERE AND NOT ASSUMED. `extraEnv` - // replaces a variable outright in the child, so writing only the - // project's own directory would silently be the substitution this - // deliberately is not. - if (auto const& inherited = mcpp::runtime::launch_env::inherited_path(); !inherited.empty()) { - path += mcpp::runtime::launch_env::path_list_separator(); - path += inherited; - } + // THE INHERITED VALUE IS READ THERE AND NOT ASSUMED. `extraEnv` replaces + // a variable outright in the child, so writing only the stated directories + // would silently be the substitution this deliberately is not. + if (auto path = mcpp::runtime::launch_env::child_path(env.statedToolDirs, env.toolsBin); !path.empty()) e.emplace_back("PATH", path); - } publish_by_variable(e, env.toolPaths); return e; diff --git a/src/build/execute.cppm b/src/build/execute.cppm index e3499ed50..75b72e51f 100644 --- a/src/build/execute.cppm +++ b/src/build/execute.cppm @@ -36,7 +36,6 @@ 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) @@ -426,20 +425,10 @@ 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); + // (The register's switches that shape the graph are not here: this record + // is written by a build that succeeded, and a switch stated for a build + // that failed left its graph under the record of the one before. The graph + // names them itself -- `request_tag`.) if (overrides.empty() && targets.empty()) return std::format("cli={};default={}", cli, machineDefault); return std::format("cli={};default={};base={}{}", cli, machineDefault, overrides, targets); @@ -653,6 +642,14 @@ export struct BuildCacheEntry { // program includes was edited and the build replayed the old directives. std::vector programRecords; bool programRecordsRecorded = false; + // THE DIRECTORIES IN FRONT OF THE PATH OF THE PROGRAM `mcpp run` STARTS + // (design 2026-11-27 §4.2): the tools the graph states and the declared + // environment's `bin`, which the full path composes from the plan and the + // fast path has no plan to compose from. Recorded apart from the list + // because an empty list is an answer (nothing stated) and an absent one is + // an entry that predates the field, which declines once. + std::vector runPathDirs; + bool runPathRecorded = false; }; // One list of extensions as a line of the record carries it: joined by a unit @@ -889,6 +886,14 @@ export std::vector read_build_cache(const std::filesystem::path e.programRecordsRecorded = e.programRecords.size() == n; haveNextLine = static_cast(std::getline(f, line)); } + if (haveNextLine && line.starts_with("runPath=")) { + std::size_t n = 0; + try { n = std::stoul(line.substr(8)); } catch (...) { n = 0; } + for (std::size_t i = 0; i < n && std::getline(f, line); ++i) + e.runPathDirs.push_back(line); + e.runPathRecorded = e.runPathDirs.size() == n; + haveNextLine = static_cast(std::getline(f, line)); + } entries.push_back(std::move(e)); if (!haveNextLine || line.empty()) break; } @@ -940,7 +945,8 @@ void write_build_cache(const std::filesystem::path& projectRoot, std::vector xlingsPayloads = {}, const std::string& selection = {}, const std::string& group = {}, - const std::string& rootCompileDb = {}) { + const std::string& rootCompileDb = {}, + std::vector runPathDirs = {}) { // The configuration groups of one workspace command build at the same // time (workspace design 2026-09-29 §6) and record into one file; the // read, the edit and the write are one step -- within this process under @@ -984,6 +990,8 @@ void write_build_cache(const std::filesystem::path& projectRoot, newEntry.group = group; newEntry.rootCompileDb = rootCompileDb; newEntry.rootCompileDbRecorded = true; + newEntry.runPathDirs = std::move(runPathDirs); + newEntry.runPathRecorded = true; // The engine that wrote the graph is the one writing the record: both // happen in this process, after the graph was emitted. newEntry.engine = running_engine(); @@ -1077,6 +1085,13 @@ void write_build_cache_entries(const std::filesystem::path& path, f << "programRecords=" << e.programRecords.size() << '\n'; for (auto& r : e.programRecords) f << r << '\n'; } + // A directory that holds a line break cannot be a line of the record: + // the list is then left unrecorded, and the fast path declines. + if (e.runPathRecorded && std::ranges::none_of(e.runPathDirs, [](auto const& d) { + return d.find_first_of("\r\n") != std::string::npos; })) { + f << "runPath=" << e.runPathDirs.size() << '\n'; + for (auto& d : e.runPathDirs) f << d << '\n'; + } } } @@ -1146,6 +1161,38 @@ compute_run_targets(const mcpp::build::BuildPlan& plan) { return out; } +// THE PATH OF A TEST AND OF A RUN (design 2026-11-27 §4.2, mcpp#926): the +// directories of the tools the graph states, then the `bin` of the environment +// the project states, then the PATH mcpp was started with -- the composition a +// build program's PATH has (launch_env::child_path). A tool a test runs that +// the graph states (`[xlings.workspace] "xim:esbuild" = { when = "run" }`) is +// found on every host; before, a test found it only on Linux and only when it +// sat in the toolchain's environment. +// +// COMPAT(implicit-default-environment): a TEST of a project that states no +// environment keeps, outside Windows, the `bin` of the environment its +// toolchain is installed in, as before 2026.11.27.1, until the row's floor. A +// run never had it, and does not gain it. On Windows that directory holds the +// toolchain's `cl`/`link` stand-ins, which are no tool of the project (#726), +// and it was never given. +enum class Child { Test, Run }; + +std::vector child_path_dirs(const mcpp::build::BuildContext& ctx, Child child) { + auto dirs = ctx.xlingsDepBinDirs; + auto environmentBin = ctx.statedEnvironmentBin; + if constexpr (!mcpplibs::os::is_windows) + if (environmentBin.empty() && child == Child::Test) + if (auto environment = mcpp::provider::environment_of(ctx.tc.binaryPath)) + if (std::error_code ec; std::filesystem::exists(*environment / "bin", ec)) + environmentBin = *environment / "bin"; + if (!environmentBin.empty()) dirs.push_back(environmentBin); + return dirs; +} + +std::string child_path_of(const mcpp::build::BuildContext& ctx, Child child) { + return mcpp::runtime::launch_env::child_path(child_path_dirs(ctx, child), {}); +} + // mcpp#225 (E2): the process env needed to exec a run-target (e.g. // LD_LIBRARY_PATH for dep .so's not covered by the exe's own RUNPATH). // Shared between build_run_target's normal (prepare_build) path and its @@ -2370,7 +2417,14 @@ export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache, return v; }(), ctx.workspaceRequest, ctx.workspaceGroup, - ctx.plan.rootCompileDb); + ctx.plan.rootCompileDb, + // The front of the PATH `mcpp run` gives its program. + [&] { + std::vector v; + for (auto const& d : child_path_dirs(ctx, Child::Run)) + v.push_back(d.generic_string()); + return v; + }()); } // The one place the --strict policy is settled. Degradations reported by @@ -3475,6 +3529,25 @@ void yield_terminal() { mcpp::diag::print_closing(); } +// A SCRIPT WHOSE `#!` INTERPRETER IS NOT THERE (#621), said before the +// artefact is executed directly: the refusal is the interpreter's own and +// comes after mcpp has handed the process over, so nothing of mcpp follows it. +// The PATH searched is the one the artefact receives -- the last value +// `childEnv` gives it, else this invocation's -- since that is the one `env` +// searches. +void note_missing_interpreter(const mcpp::build::BuildContext& ctx, const std::filesystem::path& exe, + const std::vector>& childEnv) { + std::string path = mcpp::invocation::get("PATH").value_or(""); + for (auto const& [key, value] : childEnv) + if (key == "PATH") path = value; + // The managed spec the build used, which the remedy's commands name. + std::string toolchain; + for (auto const& s : ctx.sources) + if (s.subject == "toolchain.build" && s.cls == mcpp::build::SourceClass::Managed) toolchain = s.value; + if (auto note = mcpp::build::runner_lookup::missing_interpreter_note(exe, path, toolchain); !note.empty()) + mcpp::diag::note("run/missing-interpreter", note); +} + // mcpp#225 (E2): `mcpp run`'s fast path. Mirrors try_fast_build's // fingerprint/freshness gate against the SAME cache entry `mcpp build` // wrote (targetTriple == "" — a HOST build; see the precondition below), then @@ -3618,6 +3691,10 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, // installed less than a run needs, so taking it would execute with a // declared tool absent. prepare_build provisions the difference. if (match->runTierPending) return fast_path_declined("run", "the run tier is not yet decided"); + // The PATH is composed from what the build recorded (mcpp#926); an entry + // that cannot say it would start the program with another PATH than the + // full path gives. + if (!match->runPathRecorded) return fast_path_declined("run", "the recorded build predates the program's PATH"); // Locate the requested run-target before doing any filesystem freshness // work — an unrecognized name falls back to prepare_build, which gives @@ -3690,6 +3767,12 @@ std::optional try_fast_run(const std::filesystem::path& projectRoot, return mcpp::invocation::get(v); })) childEnv.push_back(std::move(kv)); + // ...and the PATH the full path composes, from the directories it recorded. + { + std::vector dirs(match->runPathDirs.begin(), match->runPathDirs.end()); + if (auto value = mcpp::runtime::launch_env::child_path(dirs, {}); !value.empty()) + childEnv.emplace_back("PATH", value); + } // `--print-launch`: the recorded launch, when it is the one this path executes. if (print_launch_flag()) { @@ -3970,7 +4053,6 @@ int run_artifact_via_runner(mcpp::build::BuildContext& ctx, } runClosure = *closure; } - run_separator(); std::vector> childEnv; auto [runEnvKey, runEnvValue] = compute_run_env(ctx.plan); @@ -3983,6 +4065,11 @@ int run_artifact_via_runner(mcpp::build::BuildContext& ctx, if (runClosure) for (auto& kv : run_contract_env(ctx, exe, "run", choice.tripleKey, *runClosure)) childEnv.push_back(std::move(kv)); + // The child's PATH, as a build program's and a test's (mcpp#926). + if (auto pathVal = child_path_of(ctx, Child::Run); !pathVal.empty()) childEnv.emplace_back("PATH", pathVal); + if (choice.tmpl.empty() && host.prefix.empty() && !print_launch_flag()) + note_missing_interpreter(ctx, exe, childEnv); + run_separator(); // Direct exec (no /bin/sh): the loader env reaches ONLY the target child, // never mcpp or a host shell. Fixes the bundled-glibc-vs-host-libtinfo @@ -5244,6 +5331,9 @@ struct TestBuild { // and each such result is NotRun, not RunFail. The reason is printed once. std::atomic hostCannotRun{false}; std::string hostCannotRunReason; + // The first test executed directly was read for a missing `#!` + // interpreter (#621); the note, if any, is printed once per build. + bool interpreterNoted = false; }; // Phase A goal set: every shared prerequisite — all package/dep compile @@ -6357,18 +6447,17 @@ static int test_run_member(TestBuild& tb, const TestOptions& testOpts, invocationNotRunReason = handoff.error(); } - // Prepend the toolchain's environment's bin to the CHILD PATH so test - // binaries that shell out to bootstrapped tools (patchelf, ninja) find - // them — applied to the child only, not via a leaky shell prefix. - if constexpr (!mcpplibs::os::is_windows) { - if (auto environment = mcpp::provider::environment_of(ctx->tc.binaryPath)) { - auto sandboxBin = *environment / "bin"; - if (std::filesystem::exists(sandboxBin)) { - std::array extra{sandboxBin}; - auto pathVal = mcpp::runtime::launch_env::prepend_path_list("PATH", extra); - if (!pathVal.empty()) childEnv.emplace_back("PATH", pathVal); - } - } + // The child's PATH, as a build program's and a run's (mcpp#926). + if (auto pathVal = child_path_of(*ctx, Child::Test); !pathVal.empty()) childEnv.emplace_back("PATH", pathVal); + + // Said once for the build, before any test runs: every test of one + // build is executed the same way, so one script's missing interpreter + // is every script's. + if (runnerTmpl.empty() && tb.runUnderPrefix.empty() && !tb.interpreterNoted && !json + && !print_launch_flag() && !testOpts.noRun && !tb.builtNotRunHere + && invocationNotRunReason.empty()) { + tb.interpreterNoted = true; + note_missing_interpreter(*ctx, exe, childEnv); } runnable.push_back({lu.targetName, std::move(argv), std::move(childEnv), @@ -7311,9 +7400,7 @@ void write_test_plan(const TestBuild& tb, std::string_view targetOverride) { json runtimeDirs = json::array(); for (auto const& d : ctx.plan.runtimeLibraryDirs) runtimeDirs.push_back(d.generic_string()); json pathDirs = json::array(); - if constexpr (!mcpplibs::os::is_windows) - if (auto environment = mcpp::provider::environment_of(ctx.tc.binaryPath)) - if (std::error_code ec; fs::exists(*environment / "bin", ec)) pathDirs.push_back((*environment / "bin").generic_string()); + for (auto const& d : child_path_dirs(ctx, Child::Test)) pathDirs.push_back(d.generic_string()); const json record{{"schema", "mcpp.test-plan/1"}, {"graph", ctx.plan.graphFile}, {"graph_stamp", test_graph_stamp(graph)}, {"tests", tests}, {"frameworks", frameworks}, {"runtime_dirs", runtimeDirs}, {"path_dirs", pathDirs}, @@ -7463,9 +7550,8 @@ fast_test_plan(const std::filesystem::path& projectRoot, const TestOptions& test { std::vector dirs; for (auto const& d : record["path_dirs"]) dirs.emplace_back(d.get()); - if (!dirs.empty()) - if (auto value = mcpp::runtime::launch_env::prepend_path_list("PATH", dirs); !value.empty()) - env.emplace_back("PATH", value); + if (auto value = mcpp::runtime::launch_env::child_path(dirs, {}); !value.empty()) + env.emplace_back("PATH", value); } for (auto& r : runs) r.env = env; diff --git a/src/build/graph_shape.cppm b/src/build/graph_shape.cppm index 6149ab713..a2a0c02fe 100644 --- a/src/build/graph_shape.cppm +++ b/src/build/graph_shape.cppm @@ -29,6 +29,7 @@ export module mcpp.build.graph_shape; import std; +import mcpp.buildopt.registry; export namespace mcpp::build { @@ -90,7 +91,15 @@ std::string header_line(GraphShape shape, std::string_view scheduleTag, // The tag of a request: the workspace members of the plan (their paths joined // by a unit separator; empty outside a workspace) and the requested features, -// normalised so that spelling and order do not change it. +// normalised so that spelling and order do not change it. And what the +// invocation states of the build-optimization register's entries that are +// decided when the graph is written (SPEC-019 §9 item 5): a graph written under +// `MCPP_PRIVATE_FRAGMENT=conservative` holds other units than the one a plain +// build writes. It is the graph that says so, not the record of the build: +// the record is written by a build that succeeded, and the statement is made +// to check a build that fails (measured: after one that failed, a plain build +// replayed its graph and failed the same way). Stated by none, the tag is the +// one it was. std::string request_tag(std::string_view group, std::string_view features) { std::vector toks; for (std::size_t i = 0; i < features.size();) { @@ -105,6 +114,10 @@ std::string request_tag(std::string_view group, std::string_view features) { std::string key(group); key += '\x1f'; for (auto const& t : toks) { key += t; key += ','; } + if (const auto shape = mcpp::buildopt::registry::stated_shape(); !shape.empty()) { + key += '\x1f'; + key += shape; + } std::uint64_t h = 0xcbf29ce484222325ull; for (unsigned char c : key) { h ^= c; h *= 0x100000001b3ull; } return std::format("{:016x}", h); diff --git a/src/build/ninja_backend.cppm b/src/build/ninja_backend.cppm index 1cf3878d2..4215c7852 100644 --- a/src/build/ninja_backend.cppm +++ b/src/build/ninja_backend.cppm @@ -34,6 +34,9 @@ import mcpp.diag; import mcpp.build.advice; import mcpp.dyndep; import mcpp.toolchain.detect; +import mcpp.build.refusal; +import mcpp.pm.compat.registry; +import mcpp.modgraph.p1689; import mcpp.toolchain.model; import mcpp.modgraph.glob; import mcpp.toolchain.dialect; @@ -999,6 +1002,127 @@ std::vector windows_executable_link_flags(const BuildPlan& plan, bo return out; } +// THE NAMES A HOST ENTERS AN IMAGE BY (mcpp#982). An `exports` entry without a +// wildcard is an exact name: the host (a Java process, a loader asking for +// `PyInit_x`, a plugin host) looks it up by that name, and an image that does +// not define it fails when it is looked up, after the build. A pattern narrows +// what is published and may match nothing; an exact name that matches nothing +// is a missing definition. +// +// Read from the image's dynamic symbol table after the link, on the object +// format whose linker takes a version script without asking whether its +// names exist (ELF; ld64 refuses an exported name nothing defines, and the PE +// `.def` is written from the symbols the objects define). +// +// COMPAT(unmatched-exact-export): such a name was dropped without a word +// before 2026.11.27.1. Until the row's floor it is reported, and from the floor +// it fails the build. +// WHAT EACH LINK READ (SPEC-004 §8.1), as ninja keeps it: the link's dependency +// file is read into `.ninja_deps` and removed, so it is asked of ninja, once, +// for the artifacts a build is about to validate. An artifact whose link +// reports nothing is absent. +mcpp::build::runtime_validation::LinkInputs +link_inputs(const BuildPlan& plan, const std::string& ninjaProgram, + const mcpp::build::runtime_validation::ArtifactSnapshot& artifacts) { + mcpp::build::runtime_validation::LinkInputs out; + if (artifacts.empty() || ninjaProgram.empty()) return out; + std::vector argv{ninjaProgram, "-C", plan.outputDir.string(), "-t", "deps"}; + for (auto const& [artifact, _] : artifacts) { + std::error_code ec; + auto rel = std::filesystem::relative(artifact, plan.outputDir, ec); + if (!ec && !rel.empty()) argv.push_back(rel.generic_string()); + } + if (argv.size() == 5) return out; + auto r = mcpp::run::capture_stdout(argv); + if (r.exit_code != 0) return out; + // `: #deps N, deps mtime T (VALID)` and then the inputs, indented. + std::vector* at = nullptr; + for (auto const lineRange : std::views::split(std::string_view(r.output), '\n')) { + std::string_view line(lineRange); + if (line.empty()) { at = nullptr; continue; } + if (line.front() != ' ') { + const auto colon = line.find(": #deps"); + at = colon == std::string_view::npos ? nullptr + : &out[(plan.outputDir / std::string(line.substr(0, colon))).lexically_normal()]; + continue; + } + if (!at) continue; + while (!line.empty() && line.front() == ' ') line.remove_prefix(1); + std::filesystem::path p{std::string(line)}; + at->push_back(p.is_absolute() ? p : plan.outputDir / p); + } + return out; +} + +// A SHARED IMAGE THAT ASKS FOR THE STATIC TLS BLOCK (mcpp#907). An object +// compiled for the initial-exec TLS model marks the library `DF_STATIC_TLS`. +// Loaded with the program at start-up it works; loaded by `dlopen` later, the +// loader serves its thread-local storage from what is left of the static +// block, and a library larger than that is refused at that moment ("cannot +// allocate memory in static TLS block"). How much is left is the row's loader's +// fact (`dlopen-static-tls`); a row that states none is not checked. Which way +// the image will be loaded is not known at the link, so it is reported; an +// image whose exact `exports` say a host enters it by name (a plugin, a Python +// extension, a JNI library) is one that `dlopen` loads, and is refused +// (`static-tls-image`). +std::optional refuse_static_tls_image(const BuildPlan& plan) { + std::uint64_t surplus = 0; + if (auto t = mcpp::toolchain::triple::parse(plan.toolchain.targetTriple)) + if (auto const* row = mcpp::toolchain::target::find_row(t->str()); row && row->dlopenStaticTls > 0) + surplus = static_cast(row->dlopenStaticTls); + if (surplus == 0) return std::nullopt; + for (auto const& lu : plan.linkUnits) { + if (lu.kind != LinkUnit::SharedLibrary) continue; + auto facts = mcpp::runtime::elf::inspect_elf_runtime(plan.outputDir / lu.output); + if (!facts || !facts->staticTls || facts->tlsSize <= surplus) continue; + const bool entered = std::ranges::any_of(lu.exportPatterns, [](auto const& p) { + return p.find_first_of("*?[") == std::string::npos; + }); + const auto what = std::format( + "{} uses the initial-exec TLS model for {} bytes of thread-local storage (DF_STATIC_TLS), and " + "the loader of {} serves an image loaded by dlopen {} bytes of it", + lu.output.filename().string(), facts->tlsSize, plan.toolchain.targetTriple, surplus); + const auto help = std::string( + "compile its objects with -ftls-model=global-dynamic (the model for code of a shared " + "library), or keep less in `thread_local`"); + if (entered) { + mcpp::build::refusal::record(mcpp::build::refusal::Code::StaticTlsImage); + return std::format("{}; its `exports` name the symbols a host loads it to call.\n" + " help: {}", what, help); + } + mcpp::diag::degraded("build/static-tls", what, + "a program that loads it at start-up runs; dlopen refuses it", help); + } + return std::nullopt; +} + +// An exact `exports` name the image does not define (mcpp#982), read from the +// image's dynamic symbol table. The reader reads ELF; another container gives +// no table, and nothing is claimed about it (ld64 refuses such a name itself). +void report_unmatched_exact_exports(const BuildPlan& plan) { + auto const* d = mcpp::pm::compat::find_deprecation("unmatched-exact-export"); + for (auto const& lu : plan.linkUnits) { + if (lu.kind != LinkUnit::SharedLibrary) continue; + std::vector exact; + for (auto const& p : lu.exportPatterns) + if (p.find_first_of("*?[") == std::string::npos) exact.push_back(p); + if (exact.empty()) continue; + auto symbols = mcpp::runtime::elf::inspect_dynamic_symbols(plan.outputDir / lu.output); + if (!symbols) continue; // not an ELF image this reader reads: nothing is claimed + for (auto const& name : exact) { + if (std::ranges::any_of(symbols->defined, [&](auto const& s) { return s.name == name; })) continue; + const auto detail = std::format("[targets.{}] exports \"{}\"", lu.targetName, name); + mcpp::pm::compat::record_use("unmatched-exact-export", lu.targetName, detail, true); + if (d) + mcpp::diag::warning(d->domain, std::format( + "{}: {} names a symbol the image does not define, so a host that looks it up does not " + "find it. Dropping it without a word is {}. Write {} instead.", + lu.output.filename().string(), detail, mcpp::pm::compat::deprecation_clause(*d), + d->canonical)); + } + } +} + std::vector start_link_flags(std::string_view start, bool direct) { if (start.empty()) return {}; if (direct) @@ -2991,11 +3115,10 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // nothing failed -- and the compile then had no previous object // to find its output equal to (mcpp#946 O5). What the dyndep file // names is `-fdeps-target`. - append(std::format(" command = {}$cxx_driver{} $cxxflags $unit_cxxflags -fmodules " - "-fdeps-format=p1689r5 " - "-fdeps-file=$out -fdeps-target=$deps_target " - "-M -MM -MF $out.dep $unit_lang -E $in -o $out.scan\n", - scanPrefix, rsp_ref(scanPayload))); + append(std::format(" command = {}\n", mcpp::modgraph::p1689::scan_command({ + .prefix = scanPrefix, .driver = "$cxx_driver" + rsp_ref(scanPayload), + .flags = {"$cxxflags", "$unit_cxxflags"}, .lang = {"$unit_lang"}, .in = "$in", .out = "$out", + .depsTarget = "$deps_target", .depFile = "$out.dep", .scratch = "$out.scan"}))); } else { // Clang path: clang-scan-deps writes the P1689 JSON itself via -o // (LLVM 17+), like the GCC and MSVC branches above write theirs @@ -3004,11 +3127,10 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // line at 8191 chars — a quarter of the 32767 ninja gets from // CreateProcess — which any package with a large include-dir list // overruns (#261: 48 -I entries at a deep consumer path). - append(std::format( - " command = {}$scan_deps -format=p1689 -o $out -- " - "$cxx_driver{} $cxxflags $unit_cxxflags $unit_lang -c $in " - "-o $compile_target\n", - scanPrefix, rsp_ref(scanPayload))); + append(std::format(" command = {}\n", mcpp::modgraph::p1689::scan_command({ + .prefix = scanPrefix, .driver = "$cxx_driver" + rsp_ref(scanPayload), + .scanDeps = "$scan_deps", .flags = {"$cxxflags", "$unit_cxxflags"}, .lang = {"$unit_lang"}, + .in = "$in", .out = "$out", .compileTarget = "$compile_target"}))); } append_rspfile(scanPayload); append(" description = SCAN $out\n\n"); @@ -3028,6 +3150,26 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // (ninja trims trailing whitespace in variable values, hence the space // lives in the rule's command string, not here) static constexpr std::string_view kHeldOpenVerify = " verify = --verify size\n"; + // A BMI IS ONE NODE IN BOTH ITS SPELLINGS (mcpp#1015). A compiler that + // finds BMIs through an absolute directory (`-fprebuilt-module-path= + // /pcm.cache`, absolute for compile_commands.json, flags.cppm) + // names every BMI an importer read by that path in the depfile ninja keeps, + // while the graph names the BMI below the build directory. ninja holds the + // two spellings as two files, and the absolute one had no edge: it was read + // when the build began and not again, so an importer of an importer whose + // BMI the edit changed was compiled by the next build, which had no edit + // (measured with clang 23.1.3: `c` edited, `b` kept its BMI, `main` was + // compiled one build later). The edge that writes a BMI states the + // absolute spelling as an implicit output too: ninja then knows one edge + // writes both, and restat judges both by one file. + auto also_absolute = [&](const std::filesystem::path& bmi) -> std::string { + if (!traits.needsPrebuiltModulePath || bmi.empty() || bmi.is_absolute()) return {}; + return " " + escape_ninja_path((plan.outputDir / bmi).lexically_normal()); + }; + auto with_absolute = [&](const std::filesystem::path& bmi) -> std::string { + const auto alias = also_absolute(bmi); + return alias.empty() ? std::string{} : " |" + alias; + }; auto std_bmi_dst = mcpp::toolchain::staged_std_bmi_path(plan.toolchain, {}); auto std_o_dst = std::filesystem::path("obj") / std::format("std{}", dial.objExt); @@ -3139,8 +3281,8 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, // The standard library module is a dependency of the build: `std`. attribute("std"); if (has_std_artifacts) { - append(std::format("build {} : stage_file {}\n", escape_ninja_path(std_bmi_dst), - escape_ninja_path(plan.stdBmiPath))); + append(std::format("build {}{} : stage_file {}\n", escape_ninja_path(std_bmi_dst), + with_absolute(std_bmi_dst), escape_ninja_path(plan.stdBmiPath))); append(std::string(kHeldOpenVerify)); append(std::format("build {} : stage_file {}\n", escape_ninja_path(std_o_dst), escape_ninja_path(plan.stdObjectPath))); @@ -3159,8 +3301,8 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, if (has_std_compat) { // std.compat.pcm depends on std.pcm — ensure std.pcm is staged first // so clang can resolve the transitive dependency when loading std.compat.pcm. - append(std::format("build {} : stage_file {} | {}\n", escape_ninja_path(compat_bmi_dst), - escape_ninja_path(plan.stdCompatBmiPath), + append(std::format("build {}{} : stage_file {} | {}\n", escape_ninja_path(compat_bmi_dst), + with_absolute(compat_bmi_dst), escape_ninja_path(plan.stdCompatBmiPath), escape_ninja_path(std_bmi_dst))); append(std::string(kHeldOpenVerify)); append(std::format("build {} : stage_file {}\n", escape_ninja_path(compat_o_dst), @@ -3333,7 +3475,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, for (auto& imp : cu.imports) if (auto const* p = provider_of(cu, imp); p && after_a_compile(*p)) waitsFor += " " + import_bmi(cu, imp); - append(std::format("build {} : stage_file {}{}\n", bmi, + append(std::format("build {}{} : stage_file {}{}\n", bmi, with_absolute(bmi), escape_ninja_path(cu.cachedBmi), waitsFor.empty() ? "" : " ||" + waitsFor)); append(" verify = --verify size\n"); @@ -3603,8 +3745,8 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, .string() + ".ddi"; auto it = ddi_to_dd.find(ddi); if (it != ddi_to_dd.end()) { - std::string e = std::format("build {} : cxx_module_bmi {} | {}", - bmi, escape_ninja_path(cu.source), + std::string e = std::format("build {}{} : cxx_module_bmi {} | {}", + bmi, with_absolute(bmi), escape_ninja_path(cu.source), it->second); e += order_only_for(cu); e += "\n dyndep = " + it->second + "\n"; @@ -3684,7 +3826,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, e += " unit_cxxflags =" + fl + "\n"; append(std::move(e)); }; - edge("cxx_precompile", bmi); + edge("cxx_precompile", bmi + with_absolute(bmi)); edge("cxx_module_object", obj); continue; } @@ -3692,7 +3834,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, std::string out_line = "build " + escape_ninja_path(cu.object); if (!cu.providesModule.empty()) { - out_line += " | " + unit_bmi(cu); + out_line += " | " + unit_bmi(cu) + also_absolute(unit_bmi(cu)); } out_line += std::format(" : {} {}", rule, escape_ninja_path(cu.source)); if (!is_scan_exempt(cu)) { @@ -3760,7 +3902,7 @@ std::string emit_ninja_string(const BuildPlan& plan, std::string* placements, if (!cu.providesModule.empty()) { // Use implicit output (|) so $out only contains the .o file. // GCC writes BMI implicitly; Clang uses -fmodule-output=$bmi_out. - out_line += " | " + unit_bmi(cu); + out_line += " | " + unit_bmi(cu) + also_absolute(unit_bmi(cu)); } out_line += std::format(" : {} {}", rule, escape_ninja_path(cu.source)); if (!implicit.empty()) @@ -5566,10 +5708,14 @@ std::expected NinjaBackend::build(const BuildPlan& plan // one reader both build paths call. if (ok) mcpp::build::advice::report_and_clear(plan.outputDir); + if (ok) report_unmatched_exact_exports(plan); + if (ok) + if (auto refused = refuse_static_tls_image(plan)) + return std::unexpected(BuildError{*refused, plan.outputDir / plan.graphFile, {}}); if (ok) { auto runtimeReport = mcpp::build::runtime_validation::validate_changed_artifacts( - plan, runtimeBefore); + plan, runtimeBefore, link_inputs(plan, ninjaProgram, runtimeBefore)); stage("runtime-validate"); std::string runtimeFailure; std::filesystem::path runtimeFailureArtifact; @@ -5580,6 +5726,10 @@ std::expected NinjaBackend::build(const BuildPlan& plan // and a DT_NEEDED the artifact's own loader will never find are // both "this artifact is known bad", and enumerating them here is // how one of them gets forgotten. + // A `DT_NEEDED` nothing answers is the closure's refusal as much + // as one another file answers (design 2026-11-27 §4.1). + if (checked.verdict.status == Status::Unresolvable) + mcpp::build::refusal::record(mcpp::build::refusal::Code::RuntimeClosure); if (checked.verdict.blocking()) { if (runtimeFailure.empty()) { runtimeFailureArtifact = checked.artifact; diff --git a/src/build/plan.cppm b/src/build/plan.cppm index 1e0b838e6..d7440e9ad 100644 --- a/src/build/plan.cppm +++ b/src/build/plan.cppm @@ -8,6 +8,7 @@ export module mcpp.build.plan; import std; import mcpp.pm.patch; // a variant's name (design 2026-11-02 §14.1) import mcpp.build.graph_shape; +import mcpp.build.refusal; import mcpp.targetside; import mcpp.build.loader_contract; import mcpp.manifest; @@ -727,6 +728,11 @@ struct BuildPlan { // `xdg-open`/`notify-send` outright when a private libc is on it. The farm // is reachable PER OBJECT (DT_RPATH) and must stay that way. std::vector runtimeSearch; + // The project states its environment (`[xlings] subos`): the union view of + // that environment is its own (design 2026-11-27 §4.1). False: the view is + // the machine's default environment, which the project reaches through + // COMPAT(implicit-default-environment) until the row's floor. + bool statedEnvironment = false; // Windows runtime-DLL deployment. On PE (`supports_rpath` is false) a // directly-launched .exe cannot RUNPATH-locate a dependency's DLL, so each // *.dll found in a dependency's [runtime] library_dir is copied beside the @@ -2973,8 +2979,12 @@ make_plan(const mcpp::manifest::Manifest& manifest, struct SharedDepTarget { std::size_t packageIndex = 0; std::string packageName; + // The target as its files are named: `name` is the file's stem + // (`compat_sdl3`), which `declaredName` (`sdl3`) is not for a + // dependency's library. mcpp::manifest::Target target; std::filesystem::path output; + std::string declaredName; }; std::vector sharedDepTargets; std::set sharedDepPackages; @@ -3020,15 +3030,52 @@ make_plan(const mcpp::manifest::Manifest& manifest, if (t.kind != mcpp::manifest::Target::SharedLibrary) continue; sharedDepPackages.insert(qname); const auto targetIndex = sharedDepTargets.size(); + // A DEPENDENCY'S SHARED LIBRARY IS NAMED BY ITS PACKAGE (mcpp#975), + // by the function that names its object directory: `compat.sdl3` + // and `mcpplibs.mwrap.sdl3` both made `libsdl3.so` from a target + // named `sdl3`, and the plan wrote two rules for one file. The + // package is spelled as a dependency key spells it: a package of + // the default namespace by its bare name, which is the name its + // library always had (`libdepShared.so`), another by its namespace + // and name (`libcompat_sdl3.so`). A target named otherwise than its + // package keeps its name after the package's + // (`libcompat_sdl3_extra.so`). A selected member's library is the + // build's own product and keeps its target's name; a stated + // `soname` is the name it is loaded by either way. + auto named = t; + if (!p.selectedMember) { + const auto& spelled = p.manifest.package.namespace_ == mcpp::manifest::kDefaultNamespace + ? p.manifest.package.name : qname; + named.name = t.name == p.manifest.package.name || t.name == qname + ? sanitize(spelled) : std::format("{}_{}", sanitize(spelled), t.name); + } sharedDepTargets.push_back(SharedDepTarget{ .packageIndex = i, .packageName = qname, - .target = t, - .output = target_output(t, naming), + .target = named, + .output = target_output(named, naming), + .declaredName = t.name, }); sharedTargetsByPackage[i].push_back(targetIndex); } } + // Two libraries loaded by one name are one library to the loader: the + // second a program finds is never loaded (`soname-collision`). + { + std::map bySoname; + for (auto const& dep : sharedDepTargets) { + const auto name = dep.target.soname.empty() ? dep.output.filename().string() : dep.target.soname; + auto [it, fresh] = bySoname.try_emplace(name, dep.packageName); + if (fresh || it->second == dep.packageName) continue; + mcpp::build::refusal::record(mcpp::build::refusal::Code::SonameCollision); + return std::unexpected(std::format( + "'{}' and '{}' both make a shared library loaded as '{}', and a loader loads one file " + "by one name.\n" + " help: give one of the targets another `soname`, or link one of the packages " + "statically (`linkage = \"static\"` on its dependency)", + it->second, dep.packageName, name)); + } + } // Dependency-provided optional entry objects (e.g. gtest's gtest_main.cc, // which defines its own `main`). A consumer must link such an object ONLY @@ -3430,7 +3477,7 @@ make_plan(const mcpp::manifest::Manifest& manifest, for (auto const& dep : sharedDepTargets) { LinkUnit lu; - lu.targetName = dep.target.name; + lu.targetName = dep.declaredName; lu.package = dep.packageName; lu.kind = LinkUnit::SharedLibrary; lu.dependencyOwned = true; diff --git a/src/build/prepare.cppm b/src/build/prepare.cppm index 4d86e2a76..38c34ad0f 100644 --- a/src/build/prepare.cppm +++ b/src/build/prepare.cppm @@ -577,6 +577,10 @@ export struct BuildContext { // declared but not installed contributes nothing, and the lookup then // continues to PATH. std::vector xlingsDepBinDirs; + // The `bin` of the environment the project states (`[xlings] subos`); + // empty when it states none. The second segment of a child's PATH + // (launch_env::child_path, design 2026-11-27 §4.2). + std::filesystem::path statedEnvironmentBin; // THE EXECUTION HOST'S WRAPPER (`run_under`, design 2026-10-23 §3.7): // decided once by prepare from the override, the project and this // machine's defaults, and composed in front of the runner by every verb diff --git a/src/build/prepare/build_programs.cpp b/src/build/prepare/build_programs.cpp index aa50b9538..29aeb6448 100644 --- a/src/build/prepare/build_programs.cpp +++ b/src/build/prepare/build_programs.cpp @@ -104,7 +104,7 @@ std::expected step9_root_build_program(PrepareState& state) { // toolchain. One call — see fill_target_build_env. fill_target_build_env(bpEnv, *state.m, state.tc ? &*state.tc : nullptr, state.cfg_opt ? &*state.cfg_opt : nullptr); apply_graph_cxx_abi(bpEnv, state.packages); - bpEnv.toolsBin = state.projectSubosBin; + set_build_program_path(bpEnv, state); bpEnv.profile = state.effectiveProfile; bpEnv.accel = state.resolvedAccel(); fill_package_build_env(bpEnv, *state.m); @@ -520,7 +520,7 @@ std::expected step9_member_build_programs(PrepareState& state fill_target_build_env(bpEnv, *state.m, state.tc ? &*state.tc : nullptr, state.cfg_opt ? &*state.cfg_opt : nullptr); apply_graph_cxx_abi(bpEnv, state.packages); - bpEnv.toolsBin = state.projectSubosBin; + set_build_program_path(bpEnv, state); bpEnv.profile = state.effectiveProfile; bpEnv.accel = state.resolvedAccel(); fill_package_build_env(bpEnv, pkg.manifest); diff --git a/src/build/prepare/dependency_cache.cpp b/src/build/prepare/dependency_cache.cpp index afc89eaaf..a987ba4c6 100644 --- a/src/build/prepare/dependency_cache.cpp +++ b/src/build/prepare/dependency_cache.cpp @@ -10,6 +10,7 @@ import :state; import std; import mcpp.diag; import mcpp.home; +import mcpp.libs.entry_users; import mcpp.log; import mcpp.build.source_digest; import nlohmann.json; @@ -319,6 +320,20 @@ static std::expected package_keys(PrepareState& state, return out; } +// AN EDITED TREE'S PREVIOUS ENTRY IS RELEASED (mcpp#974, mcpp#1025), as a +// `path` host tool's is: every edit of a `path` dependency is a new key, and +// none would be collected before `[cache] unused_days`. The entry records the +// trees that use it, and the tree that writes or hits this one is taken from +// the entries of the same package it used under other digests; an entry no +// tree uses is removed (mcpp.libs.entry_users). Another checkout of the +// package keeps the entries it uses. +static void supersede_tree_entries(const mcpp::bmi_cache::CacheKey& key, const std::filesystem::path& tree) { + const auto plus = key.version.find("+path."); + if (plus == std::string::npos) return; + mcpp::libs::entry_users::supersede(key.dir(), + std::format("{}@{}", key.packageName, key.version.substr(0, plus + 6)), tree); +} + // Why a package was not served, said once (design 2026-11-20 §5.4): kept for // the build record and printed under --verbose. static void not_served(BuildContext& ctx, const mcpp::modgraph::PackageRoot& pkg, @@ -503,6 +518,15 @@ static void serve_or_fill(PrepareState& state, BuildContext& ctx, std::size_t i, } } mcpp::bmi_cache::touch_accessed(key); + // The tree this build reads it for uses it, so an edit of another + // checkout of the package does not remove it, and no longer uses the + // entries of its earlier contents (mcpp#1025): a tree edited to the + // content another checkout already stored hits that entry, and the + // entry of its previous content goes once no other tree uses it. + if (depIdent->sourceKind == "path") + supersede_tree_entries(key, depIdent->sourceRef.empty() + ? pkgRoot.root + : std::filesystem::path(depIdent->sourceRef)); sup.of[i] = Supply::Served; sup.digest[i] = probe.bmiDigest; sup.key[i] = key; @@ -595,37 +619,6 @@ std::expected step13_dependency_cache(PrepareState& state, Bu return {}; } -// AN EDITED TREE'S PREVIOUS ENTRY IS REPLACED (mcpp#974), as a `path` host -// tool's is (tool_store::write_entry, mcpp#874). Every edit of a `path` -// dependency is a new key, and none would be collected before `[cache] -// unused_days`: the tree an entry was built from is written beside it, and an -// entry of the same package from the same tree under another digest is removed -// as this one is written. Another checkout of the package is another tree, and -// keeps its entries. -static void replace_tree_siblings(const mcpp::bmi_cache::CacheKey& key, const std::filesystem::path& tree) { - namespace fs = std::filesystem; - const auto plus = key.version.find("+path."); - if (plus == std::string::npos) return; - const auto origin = tree.lexically_normal().generic_u8string(); - const std::string text(origin.begin(), origin.end()); - std::error_code ec; - std::ofstream(key.dir() / "source", std::ios::binary | std::ios::trunc) << text; - const auto versionDir = key.dir().parent_path(); - const auto prefix = std::format("{}@{}", key.packageName, key.version.substr(0, plus + 6)); - auto from_this_tree = [&](const fs::path& entry) { - std::ifstream in(entry / "source", std::ios::binary); - return in && std::string{std::istreambuf_iterator(in), {}} == text; - }; - for (auto const& v : fs::directory_iterator(versionDir.parent_path(), ec)) { - const auto name = v.path().filename().u8string(); - if (v.path() == versionDir || !std::string(name.begin(), name.end()).starts_with(prefix)) continue; - std::error_code kec; - for (auto const& entry : fs::directory_iterator(v.path(), kec)) - if (from_this_tree(entry.path())) fs::remove_all(entry.path(), kec); - fs::remove(v.path(), kec); // only when nothing else is left in it - } -} - void populate_dependency_cache(BuildContext& ctx) { if (ctx.cacheMode != CacheMode::Global) ctx.depsToPopulate.clear(); for (auto& task : ctx.depsToPopulate) { @@ -645,7 +638,7 @@ void populate_dependency_cache(BuildContext& ctx) { for (auto const& up : task.interfaces) task.key.imports[up.keyHex] = mcpp::bmi_cache::entry_bmi_digest(up); auto pr = mcpp::bmi_cache::populate_from(task.key, ctx.outputDir, task.artifacts); - if (pr && !task.treeRoot.empty()) replace_tree_siblings(task.key, task.treeRoot); + if (pr && !task.treeRoot.empty()) supersede_tree_entries(task.key, task.treeRoot); if (!pr) { mcpp::diag::warning("build", std::format( "bmi cache populate failed for {}@{}: {}", diff --git a/src/build/prepare/features.cpp b/src/build/prepare/features.cpp index 0fd5b55ca..c7899c2da 100644 --- a/src/build/prepare/features.cpp +++ b/src/build/prepare/features.cpp @@ -1233,6 +1233,8 @@ static std::expected step6_xlings_workspace_from_graph(Prepar return std::unexpected(split.error()); } auto const& fromGraph = split->second; + state.statedXlingsSpecs = split->first; + state.statedXlingsSpecs.insert(state.statedXlingsSpecs.end(), fromGraph.begin(), fromGraph.end()); if (!fromGraph.empty()) { if (auto cfg = state.get_cfg(true)) { if (auto pv = provision_xlings_addresses( @@ -1386,6 +1388,9 @@ struct HostToolCtx { BuildOverrides sub; std::filesystem::path goal; std::filesystem::path subOutputDir; + // The shared objects of the graph the tool loads (relative to the + // sub-build's output directory), published beside it (mcpp#535). + std::vector sharedObjects; }; // The body of the `record` closure the single-function version of this step @@ -1650,6 +1655,7 @@ step6_resolve_tool_key(PrepareState& state, HostToolCtx& ctx) { if (mcpp::build::tool_store::entry_valid(ctx.entry, ctx.key, ctx.toolName, exeSuffix)) { mcpp::build::tool_store::touch(ctx.entry); + mcpp::build::tool_store::add_user(ctx.entry, ctx.key, tool_source_tree(state, ctx.depIdx)); state.usedCacheRecords.insert((ctx.entry / "entry.json").string()); step6_record_tool_provision(state, ctx, ctx.binOut); return true; @@ -1834,6 +1840,7 @@ step6_build_tool(PrepareState& state, HostToolCtx& ctx) { // function derived it the first time in the single-function version. ctx.goal = goal; ctx.subOutputDir = subCtx->plan.outputDir; + ctx.sharedObjects = tool_shared_objects(subCtx->plan, goal); return {}; } @@ -1865,15 +1872,18 @@ step6_publish_tool(PrepareState& state, HostToolCtx& ctx) { | std::filesystem::perms::group_exec | std::filesystem::perms::others_exec, std::filesystem::perm_options::add, cpEc); - // A path package's tree, so that its superseded entries are collected. - std::filesystem::path toolSource; - if (ctx.depIdx >= 1 && ctx.depIdx - 1 < state.dep_cache_identities.size() - && state.dep_cache_identities[ctx.depIdx - 1].sourceKind == "path") { - const auto& id = state.dep_cache_identities[ctx.depIdx - 1]; - toolSource = id.sourceRef.empty() ? state.packages[ctx.depIdx].root - : std::filesystem::path(id.sourceRef); + std::vector published; + for (auto const& so : ctx.sharedObjects) { + const auto into = ctx.binOut.parent_path() / so.filename(); + if (auto staged = mcpp::build::stage::stage_file(ctx.subOutputDir / so, into); !staged) + return std::unexpected(std::format( + "publishing host tool '{}:{}' failed: its shared library '{}': {}", + ctx.depName, ctx.toolName, so.filename().string(), staged.error().message)); + published.push_back(so.filename().string()); } - mcpp::build::tool_store::write_entry(ctx.entry, ctx.key, toolSource); + mcpp::build::tool_store::record_shared_objects(ctx.entry, published); + // A path package's tree, so that its superseded entries are collected. + mcpp::build::tool_store::write_entry(ctx.entry, ctx.key, tool_source_tree(state, ctx.depIdx)); state.usedCacheRecords.insert((ctx.entry / "entry.json").string()); // The sub-build tree is large (protoc is several hundred // objects) and the key covers every input, so a hit never @@ -2003,7 +2013,7 @@ static std::expected step6_dependency_build_programs(PrepareS // reaches every build program at once — see fill_target_build_env. fill_target_build_env(bpEnv, *state.m, state.tc ? &*state.tc : nullptr, state.cfg_opt ? &*state.cfg_opt : nullptr); apply_graph_cxx_abi(bpEnv, state.packages); - bpEnv.toolsBin = state.projectSubosBin; + set_build_program_path(bpEnv, state); bpEnv.profile = state.effectiveProfile; bpEnv.accel = state.resolvedAccel(); // The DECLARING package's setting, not the root project's: a rule diff --git a/src/build/prepare/graph_edges.cpp b/src/build/prepare/graph_edges.cpp index 4eedcf480..f1e5fac42 100644 --- a/src/build/prepare/graph_edges.cpp +++ b/src/build/prepare/graph_edges.cpp @@ -76,8 +76,18 @@ void recordDependencyEdge( if (!buildTable && !state.overrides.build_program_graph && ((spec.hostModuleDeclared && spec.hostModule) || ruleFeature)) { buildTable = true; - state.reportCompatUse("host-module-in-dependencies", consumerPackageIndex, - std::format("[dependencies] {}", writtenKey)); + // The remedy is the two commands that move it (#993): the entry is + // the user's, and `mcpp add` cannot tell a build plugin from its + // descriptor, so it is told which table to write. + const auto spelling = spec.namespace_.empty() || spec.namespace_ == mcpp::pm::kDefaultNamespace + ? spec.shortName.empty() ? writtenKey : spec.shortName + : std::format("{}.{}", spec.namespace_, spec.shortName); + state.reportCompatUseInstead("host-module-in-dependencies", consumerPackageIndex, + std::format("[dependencies] {}", writtenKey), + spec.isVersion() + ? std::format("it in [build-dependencies]: `mcpp remove {0}`, then " + "`mcpp add --build {0}@{1}`", spelling, spec.version) + : std::string("the same entry in [build-dependencies]")); } const bool wantsLibrary = buildTable && (ruleFeature diff --git a/src/build/prepare/host_tools.cpp b/src/build/prepare/host_tools.cpp new file mode 100644 index 000000000..e9b6901ae --- /dev/null +++ b/src/build/prepare/host_tools.cpp @@ -0,0 +1,52 @@ +// host_tools.cpp -- what a host tool's store entry holds besides the tool: the +// tree it was built from, a user of the entry (mcpp#1025), and the shared +// objects of the graph it loads (mcpp#535). Declared in `:state`; the steps +// that build and publish a tool are in features.cpp. + +module mcpp.build.prepare; +import :state; + +import std; +import mcpp.build.plan; + +namespace mcpp::build { + +std::filesystem::path tool_source_tree(const PrepareState& state, std::size_t depIdx) { + if (depIdx < 1 || depIdx - 1 >= state.dep_cache_identities.size() + || state.dep_cache_identities[depIdx - 1].sourceKind != "path") + return {}; + const auto& id = state.dep_cache_identities[depIdx - 1]; + return id.sourceRef.empty() ? state.packages[depIdx].root : std::filesystem::path(id.sourceRef); +} + +// THE TOOL IS AN IMAGE LIKE ANY OTHER (mcpp#535): what its link read from the +// sub-build's `bin/` it loads from beside itself (`$ORIGIN` is in its run +// path). The shared libraries of the graph it reaches -- through the link +// inputs of each, transitively -- and their run-time names are published with +// it. Before, the entry held the executable alone, and a tool over a `shared` +// package failed to start on a clean machine, or started with a library of the +// same name another installation had left in the environment. +std::vector tool_shared_objects(const mcpp::build::BuildPlan& plan, + const std::filesystem::path& goal) { + std::vector out; + std::vector work; + for (auto const& lu : plan.linkUnits) + if (lu.output == goal) work.push_back(&lu); + std::set seen; + while (!work.empty()) { + const auto* at = work.back(); + work.pop_back(); + for (auto const& input : at->implicitInputs) { + auto lu = std::ranges::find_if(plan.linkUnits, [&](const LinkUnit& u) { + return u.kind == LinkUnit::SharedLibrary && u.output == input; + }); + if (lu == plan.linkUnits.end() || !seen.insert(lu->output).second) continue; + out.push_back(lu->output); + for (auto const& alias : lu->runtimeAliases) out.push_back(alias); + work.push_back(&*lu); + } + } + return out; +} + +} // namespace mcpp::build diff --git a/src/build/prepare/local_toolchain.cpp b/src/build/prepare/local_toolchain.cpp index a1ce42728..c4416e02b 100644 --- a/src/build/prepare/local_toolchain.cpp +++ b/src/build/prepare/local_toolchain.cpp @@ -370,7 +370,7 @@ std::expected step6_toolchain_phase(PrepareState& state) { fill_target_build_env(bpEnv, *state.m, state.tc ? &*state.tc : nullptr, state.cfg_opt ? &*state.cfg_opt : nullptr); apply_graph_cxx_abi(bpEnv, state.packages); - bpEnv.toolsBin = state.projectSubosBin; + set_build_program_path(bpEnv, state); bpEnv.profile = state.effectiveProfile; fill_package_build_env(bpEnv, *state.m); bpEnv.languageModules = state.m->language.modules; diff --git a/src/build/prepare/plan.cpp b/src/build/prepare/plan.cpp index 241f174da..58e9b516c 100644 --- a/src/build/prepare/plan.cpp +++ b/src/build/prepare/plan.cpp @@ -221,15 +221,47 @@ static std::expected step13_source_packages(PrepareState& sta return {}; } -static std::expected step13_runner_and_xlings(PrepareState& state, BuildContext& ctx) { +std::vector stated_tool_dirs(PrepareState& state, + const std::vector& xlingsSpecs) { + std::vector dirs; + auto add = [&](std::filesystem::path d) { + if (std::ranges::find(dirs, d) == dirs.end()) dirs.push_back(std::move(d)); + }; // THE PROGRAMS THE GRAPH BUILT FOR THIS MACHINE COME FIRST. A runner a // dependency's `tools` built (`okrun` from `openkal-tools`) is the one the // project asked for by depending on it, ahead of a payload's and of PATH. - for (auto const& [name, path] : state.rootTools) { - auto dir = path.parent_path(); - if (std::ranges::find(ctx.xlingsDepBinDirs, dir) == ctx.xlingsDepBinDirs.end()) - ctx.xlingsDepBinDirs.push_back(std::move(dir)); + for (auto const& [name, path] : state.rootTools) add(path.parent_path()); + // An overridden payload's programs are looked up where the override + // put them (mcpp#755), first: the project said that is where they are. + for (auto const& key : state.xlingsOverridden) + if (auto ov = payload_override(state, key); ov && *ov) + for (auto& d : mcpp::build::runner_lookup::payload_search_dirs((*ov)->root)) add(std::move(d)); + if (xlingsSpecs.empty()) return dirs; + auto cfg = state.get_cfg(true); + if (!cfg) return dirs; + auto xlEnv = mcpp::config::make_xlings_env(**cfg); + for (auto const& spec : xlingsSpecs) { + auto ref = mcpp::provider::parse_ref(spec); + if (auto dir = mcpp::provider::payload(*mcpp::provider::open(xlEnv), ref)) + // `bin/`, then the payload root. The measurement that added the + // second entry is recorded with the rule, in + // runner_lookup::payload_search_dirs. + for (auto& d : mcpp::build::runner_lookup::payload_search_dirs(*dir)) add(std::move(d)); } + return dirs; +} + +void set_build_program_path(mcpp::build::BuildProgramEnv& env, PrepareState& state) { + env.toolsBin = state.projectSubosBin; + // Before the early pass (a toolchain's build program) no address is + // provisioned, and the stated directories are the tools already built. + env.statedToolDirs = stated_tool_dirs(state, state.statedXlingsSpecs); +} + +static std::expected step13_runner_and_xlings(PrepareState& state, BuildContext& ctx) { + ctx.statedEnvironmentBin = state.projectSubosBin; + ctx.plan.statedEnvironment = state.runtimeBindingSnapshot.selection.mode + == mcpp::provider::runtime::RuntimeSelection::Mode::NamedSubos; // Where a runner may find the programs this project declared (#544). The // same resolution `fillXpkgDirs` hands to build programs, kept as // directories rather than env vars because the reader is mcpp's own @@ -305,27 +337,16 @@ static std::expected step13_runner_and_xlings(PrepareState& s { ctx.runTierPending = true; break; } } } - // An overridden payload's programs are looked up where the override - // put them (mcpp#755), first: the project said that is where they are. - for (auto const& key : state.xlingsOverridden) - if (auto ov = payload_override(state, key); ov && *ov) - for (auto& d : mcpp::build::runner_lookup::payload_search_dirs((*ov)->root)) - ctx.xlingsDepBinDirs.push_back(std::move(d)); + for (auto& d : stated_tool_dirs(state, xlingsSpecs)) + if (std::ranges::find(ctx.xlingsDepBinDirs, d) == ctx.xlingsDepBinDirs.end()) + ctx.xlingsDepBinDirs.push_back(std::move(d)); if (!xlingsSpecs.empty()) { if (auto cfg = state.get_cfg(true)) { auto xlEnv = mcpp::config::make_xlings_env(**cfg); - for (auto const& spec : xlingsSpecs) { - auto ref = mcpp::provider::parse_ref(spec); - if (auto dir = mcpp::provider::payload(*mcpp::provider::open(xlEnv), ref)) { + for (auto const& spec : xlingsSpecs) + if (auto dir = mcpp::provider::payload(*mcpp::provider::open(xlEnv), + mcpp::provider::parse_ref(spec))) ctx.xlingsPayloads.push_back(*dir); - // `bin/`, then the payload root. The measurement that - // added the second entry is recorded with the rule, in - // runner_lookup::payload_search_dirs. - for (auto& d : - mcpp::build::runner_lookup::payload_search_dirs(*dir)) - ctx.xlingsDepBinDirs.push_back(std::move(d)); - } - } } } } diff --git a/src/build/prepare/platform.cpp b/src/build/prepare/platform.cpp index 91f8257e3..46639c925 100644 --- a/src/build/prepare/platform.cpp +++ b/src/build/prepare/platform.cpp @@ -220,6 +220,7 @@ void define_platform(const mp::Statement& s, std::string_view shortName, std::st r.interfacesStated = d.interfacesStated; r.exceptions = set.keep(d.exceptions); r.exeSuffixFixed = d.exeSuffixFixed; + r.dlopenStaticTls = d.dlopenStaticTls; r.execution = set.keep(d.execution.empty() ? seg[1] : d.execution); r.defined = true; set.rows.push_back(r); diff --git a/src/build/prepare/scan.cpp b/src/build/prepare/scan.cpp index 1e1e8f18c..d3cab2926 100644 --- a/src/build/prepare/scan.cpp +++ b/src/build/prepare/scan.cpp @@ -28,6 +28,8 @@ import mcpp.toolchain.model; // is_msvc_target — the MSVC-ABI default (#7 import mcpp.toolchain.fingerprint; import mcpp.toolchain.registry; import mcpp.toolchain.linkmodel; +import mcpp.toolchain.clang; +import mcpp.modgraph.p1689; // For `resolve_version_match` / `list_installed_versions`: a bare compiler // family named by the dependency graph resolves to a concrete version through // exactly the path `mcpp toolchain default ` uses. @@ -159,6 +161,55 @@ static void build_private_fragments_as_units(PrepareState& state, } } +// THE COMPILER'S ANSWER FOR A UNIT WHOSE IMPORTS STAND INSIDE A PREPROCESSOR +// CONDITION (mcpp#1026). The unit's declaration and imports under its compile: +// the standard and the graph's dialect words, the target's compile side, its +// package's include directories and words (defines, features, the conditional +// sections already merged). The scan command is the one the build's scan edge +// runs (p1689::scan_command); MSVC's `/scanDependencies` is not asked here, and +// such a unit is refused under it with that reason. +static std::expected +compiler_scan(PrepareState& state, const std::vector& packages, + const mcpp::modgraph::SourceUnit& u) { + const auto& tc = *state.tc; + if (tc.compiler == mcpp::toolchain::CompilerId::MSVC) + return std::unexpected(std::format( + "an import or a module declaration stands inside a preprocessor condition, which mcpp reads with " + "the compiler's dependency scan; {} is not asked for one while the graph is planned.\n" + " help: state the unit's modules in [build] scan_overrides, or move the condition out of " + "the import", tc.label())); + std::filesystem::path scanDeps; + if (mcpp::toolchain::is_clang(tc)) { + auto sd = mcpp::toolchain::clang::find_scan_deps(tc); + if (!sd) + return std::unexpected(std::format( + "an import or a module declaration stands inside a preprocessor condition, which mcpp reads " + "with the compiler's dependency scan, and {} has no clang-scan-deps", tc.label())); + scanDeps = *sd; + } + const mcpp::manifest::Manifest* owner = nullptr; + for (auto const& p : packages) + if (p.manifest.package.name == u.packageName) { owner = &p.manifest; break; } + const auto extTable = owner + ? mcpp::extension_table_for(owner->buildConfig.moduleExtensions, owner->buildConfig.deviceExtensions) + : mcpp::extension_table_for({}, {}); + std::vector words = state.m->buildConfig.dialectCxxflags; + for (auto const& d : u.localIncludeDirsAfter) { + words.push_back("-idirafter"); + words.push_back(d.string()); + } + words.insert(words.end(), u.packageCxxflags.begin(), u.packageCxxflags.end()); + // The scan's records are read once, here; a directory of this process's own. + static const auto tmp = std::filesystem::temp_directory_path() + / std::format("mcpp-scan-{:x}", std::random_device{}()); + auto scanned = mcpp::modgraph::p1689::scan_file(u.path, u.packageName, tc, tmp, u.localIncludeDirs, + state.stdWords, extTable, words, scanDeps); + if (!scanned) return std::unexpected(scanned.error()); + mcpp::log::info("scan", std::format("{}: imports read by the compiler's scan ({} module(s))", + u.path.generic_string(), scanned->requires_.size())); + return scanned; +} + static std::expected step11_scan_sources(PrepareState& state) { // mcpp#225 (E2): observability marker for the source-discovery phase — @@ -343,9 +394,12 @@ static std::expected step11_scan_sources(PrepareState& state) / std::format("mcpp_p1689_{}", std::random_device{}()); std::filesystem::create_directories(tmp); return mcpp::modgraph::scan_packages_p1689(scannedPackages, *state.tc, tmp, - state.stdFlagAndDialect, closures); + state.stdWords, closures); } - return mcpp::modgraph::scan_packages(scannedPackages, closures); + return mcpp::modgraph::scan_packages(scannedPackages, closures, + [&](const mcpp::modgraph::SourceUnit& u) { + return compiler_scan(state, scannedPackages, u); + }); }(); // A `sources` entry that names a file which is not there (#938) stops a // build of the tree it is written in, and is a warning in a package @@ -1385,7 +1439,38 @@ step11_cxx_compiler_gate(PrepareState& state) { return {}; } +// COMPAT(reopened-dotted-table): a manifest whose `[header]` reopens a table +// dotted keys defined is read as the union of the two (mcpp#964); reported where +// the manifest can be edited, until the row's floor. +static void report_reopened_tables(PrepareState& state) { + for (std::size_t i = 0; i < state.packages.size(); ++i) + for (auto const& path : state.packages[i].manifest.reopenedTables) + state.reportCompatUse("reopened-dotted-table", i, std::format("[{}]", path)); +} + +// A C LIBRARY FROM THE GRAPH AND NO C++ ABI (mcpp#898). The graph replaced the +// C library, no package supplies the C++ ABI, and a unit imports the standard +// library module: the toolchain's C++ library is built against another C +// library, and the std module's precompile failed inside its headers +// (`features.h` not found under GCC 16.1, `__config` under LLVM 23.1) with +// nothing that named the decision. Everything the refusal reads is known once +// the units are scanned. A stated `cxx_runtime` is the author's answer. +static std::expected step11_cxx_abi_supplier(PrepareState& state, bool needsStdModule) { + const auto& ts = state.resolvedTargetSide; + if (!needsStdModule || !state.tc->hasImportStd || !ts.cAbi.fromGraph() || !ts.cxx.absent()) return {}; + if (!state.m->buildConfig.cxxRuntime.empty()) return {}; + refusal::record(refusal::Code::LayerRequirement); + return std::unexpected(std::format( + "the graph supplies the C library ({}, {}) and no package supplies the C++ ABI.\n" + " The standard library module is compiled with the toolchain's C++ library, which is\n" + " built against another C library.\n" + " help: add a dependency that provides `mcpp:c++-abi`, or state " + "[build] cxx_runtime = \"host-coupled\"", + ts.cAbi.interfaceName.empty() ? std::string("c-abi") : ts.cAbi.interfaceName, ts.cAbi.impl)); +} + std::expected phase11_scan(PrepareState& state) { + report_reopened_tables(state); auto needsStdModule = step11_scan_sources(state); if (!needsStdModule) return std::unexpected(needsStdModule.error()); if (auto r = refuse_plugin_units_in_target(state); !r) return std::unexpected(r.error()); @@ -1407,15 +1492,24 @@ std::expected phase11_scan(PrepareState& state) { if (auto r = step11_apple_sdk_cxx_runtime(state, *needsStdModule); !r) return std::unexpected(r.error()); - if (auto r = step11_std_module_availability_gate(state, *needsStdModule); !r) { - if (!state.overrides.configures()) return std::unexpected(r.error()); - // The configuration is reported; the sources' refusal travels with it. + // A refusal of the sources: the configuration is reported, and the refusal + // travels with it, when only the configuration is asked for. + auto refuse_sources = [&](std::string why) -> std::expected { + if (!state.overrides.configures()) return std::unexpected(std::move(why)); PlanNote note; // a warning: the document is complete without the sources note.code = "MCPP_CONFIGURATION_SOURCES_REFUSED"; - note.message = r.error(); + note.message = std::move(why); state.planNotes.push_back(std::move(note)); *needsStdModule = false; - } + return {}; + }; + if (auto r = step11_std_module_availability_gate(state, *needsStdModule); !r) + if (auto refused = refuse_sources(r.error()); !refused) return refused; + // After the gate, which refuses a toolchain that has no std module with + // the reason of its target: this is the toolchain that has one, built + // against another C library than the graph's (mcpp#898). + if (auto r = step11_cxx_abi_supplier(state, *needsStdModule); !r) + if (auto refused = refuse_sources(r.error()); !refused) return refused; step11_compute_fingerprint(state); diff --git a/src/build/prepare/state.cppm b/src/build/prepare/state.cppm index b695ed662..368060e37 100644 --- a/src/build/prepare/state.cppm +++ b/src/build/prepare/state.cppm @@ -723,6 +723,10 @@ struct PrepareState { // feature declares serve this build in either instance. std::vector> buildProgramFeaturesByPackage; std::map xlingsWinner; + // The `[xlings.workspace]` addresses the early pass provisioned, the + // root's then the graph's: the payloads a build program's PATH states + // (set_build_program_path). + std::vector statedXlingsSpecs; // ── Sources (mcpp#755): see sources.cpp ───────────────────────────────── // The decision record, one entry per subject, and the subjects whose @@ -1103,6 +1107,9 @@ struct PrepareState { std::filesystem::path stdCompatObjectPath; std::optional describedStdModule; std::string stdFlagAndDialect; + // The same words, one argument each and unquoted: what a program mcpp starts + // with an argument vector is given (the planning scan of a unit, mcpp#1026). + std::vector stdWords; // The entry of package `i`; with `requesters`, only the requests made by // the packages it marks (a build program's closure). std::function*)> graph_package_entry; @@ -1359,6 +1366,24 @@ bool names_a_file_path(std::string_view v); // The override for a package key, resolved and cached; nullptr when none. std::expected payload_override(PrepareState& state, std::string_view key); + +// THE DIRECTORIES OF THE TOOLS THE GRAPH STATES (design 2026-11-27 §4.2): the +// programs its packages' `tools` built for this machine, then each overridden +// payload's, then each provisioned `[xlings.workspace]` payload's `bin/` and +// root, root package first. The first segment of a child's PATH +// (launch_env::child_path) and the runner lookup's directories; one list. +std::vector stated_tool_dirs(PrepareState& state, + const std::vector& xlingsSpecs); +// The tree a `path` tool package is read from, a user of its store entry +// (mcpp#1025); empty for any other package. +std::filesystem::path tool_source_tree(const PrepareState& state, std::size_t depIdx); +// The shared objects of the graph a tool sub-build's `goal` loads, relative to +// its output directory: published beside the tool (mcpp#535). +std::vector tool_shared_objects(const mcpp::build::BuildPlan& plan, + const std::filesystem::path& goal); +// A build program's PATH: the stated tool directories, then the project's +// stated environment's `bin` (launch_env::child_path). +void set_build_program_path(mcpp::build::BuildProgramEnv& env, PrepareState& state); // The winners of one unification that this build installs from the registry // now: overridden and deferred (`on-request`, not asked for) packages are left // out, recorded, and announced. `onRequest[i]` says whether claim `i` was diff --git a/src/build/prepare/target_side.cpp b/src/build/prepare/target_side.cpp index ac00fc34c..8c28b6277 100644 --- a/src/build/prepare/target_side.cpp +++ b/src/build/prepare/target_side.cpp @@ -2102,6 +2102,7 @@ static std::expected step9_rerun_input_prepare_dir(PrepareSta // c++latest/c++fly per-toolchain std spelling) stay graph-consistent. state.stdFlagAndDialect = mcpp::toolchain::cppfly::std_flag( *state.tc, state.m->cppStandard.canonical, state.m->cppStandard.level); + state.stdWords = {state.stdFlagAndDialect}; if (state.m->cppStandard.experimental) { // c++fly is best-effort by design: say exactly what this toolchain // got and what it lacks (the value's contract, design §5.4). @@ -2125,6 +2126,7 @@ static std::expected step9_rerun_input_prepare_dir(PrepareSta mcpp::manifest::dialect_flags(state.m->buildConfig))) { state.stdFlagAndDialect += ' '; state.stdFlagAndDialect += f; + state.stdWords.push_back(f); } // AND THE PLATFORM'S CONVENTIONS (SPEC-013 §2.5), which come before every // unit's own: the std module is a unit of the target side, whichever @@ -2138,6 +2140,7 @@ static std::expected step9_rerun_input_prepare_dir(PrepareSta for (auto const& w : platform_unit_cxxflags(state)) { state.stdFlagAndDialect += ' '; state.stdFlagAndDialect += mcpp::build::command_line::quote(w); + state.stdWords.push_back(w); } return {}; } diff --git a/src/build/prepare/toolchain.cpp b/src/build/prepare/toolchain.cpp index d5900a5fc..d82d2cdbd 100644 --- a/src/build/prepare/toolchain.cpp +++ b/src/build/prepare/toolchain.cpp @@ -90,6 +90,27 @@ static void warn_toolchain_override(const std::string& given, const std::string& given, declared, key, shown.generic_string())); } +// The selected profile's flag words, after the root's own: each list keeps +// the root's words first, so a profile adds to `[build]` and replaces nothing. +static void apply_profile_words(PrepareState& state, const mcpp::manifest::Profile& pr) { + auto append = [](std::vector& to, const std::vector& words) { + to.insert(to.end(), words.begin(), words.end()); + }; + auto& bc = state.m->buildConfig; + append(bc.cflags, pr.cflags); + append(bc.cxxflags, pr.cxxflags); + // A workspace plan's root compiles nothing; its selected members take + // these as they are loaded (graph.cpp). + state.profileCflags = pr.cflags; + state.profileCxxflags = pr.cxxflags; + append(bc.ldflags, pr.ldflags); + append(bc.graphLdflags, pr.ldflags); + // The profile's graph-wide words, after `[build] dialect_cxxflags`: the + // root's set is the one the standard library module, the scan and every + // C++ unit read (mcpp#1025). + append(bc.dialectCxxflags, pr.dialectCxxflags); +} + // STEP FUNCTIONS (mcpp#722 / T6), split at the points where phase1's // own banners mark a new concern: the closures phase1 assigns onto // `state` (each captures only `state`), the target/static override @@ -357,18 +378,7 @@ static std::expected step1_define_early_toolchain_closures(Pr std::ofstream(marker) << "2026.10.24.1\n"; } } - state.m->buildConfig.cflags.insert(state.m->buildConfig.cflags.end(), - pr.cflags.begin(), pr.cflags.end()); - state.m->buildConfig.cxxflags.insert(state.m->buildConfig.cxxflags.end(), - pr.cxxflags.begin(), pr.cxxflags.end()); - // A workspace plan's root compiles nothing; its selected members take - // these as they are loaded (graph.cpp). - state.profileCflags = pr.cflags; - state.profileCxxflags = pr.cxxflags; - state.m->buildConfig.ldflags.insert(state.m->buildConfig.ldflags.end(), - pr.ldflags.begin(), pr.ldflags.end()); - state.m->buildConfig.graphLdflags.insert(state.m->buildConfig.graphLdflags.end(), - pr.ldflags.begin(), pr.ldflags.end()); + apply_profile_words(state, pr); } // Every directory a package payload may legitimately have been INSTALLED diff --git a/src/build/refusal.cppm b/src/build/refusal.cppm index bae0fb2e7..015d17ef2 100644 --- a/src/build/refusal.cppm +++ b/src/build/refusal.cppm @@ -91,6 +91,18 @@ enum class Code { // the graph and reaching the target, and still not be compiled for the // build program, which is what `host-module = true` asks for. HostModuleMissing, + // Two shared libraries of one build are loaded by one name (their file + // name or a stated `soname`): the loader loads the first it finds for + // both (mcpp#975). + SonameCollision, + // An image's `DT_NEEDED` is not answered at load time by the file its link + // read for it: no file answers it, or another file of that name does + // (design 2026-11-27 §4.1, mcpp#537). + RuntimeClosure, + // A shared image that asks for the static TLS block holds more than the + // C library serves to an image `dlopen` loads, and its exact `exports` + // say a host loads it that way (mcpp#907). + StaticTlsImage, // Two declarations name one xlings package at versions that cannot both // hold. Distinct from VersionFloorUnmet, which is about the machine: this // one is about two manifests disagreeing over a tool. @@ -261,6 +273,9 @@ constexpr std::string_view name(Code c) { case Code::DeviceSourceUnconsumed: return "device-source-unconsumed"; case Code::HostModuleMissing: return "host-module-missing"; + case Code::SonameCollision: return "soname-collision"; + case Code::RuntimeClosure: return "runtime-closure"; + case Code::StaticTlsImage: return "static-tls-image"; case Code::ToolVersionConflict: return "tool-version-conflict"; case Code::SharedLibraryCxxRuntime: return "shared-library-cxx-runtime"; diff --git a/src/build/runner_lookup.cppm b/src/build/runner_lookup.cppm index fc252dc31..beaedb663 100644 --- a/src/build/runner_lookup.cppm +++ b/src/build/runner_lookup.cppm @@ -179,4 +179,100 @@ inline std::string unrunnable_message(std::string_view triple, artifact.string(), errno_text(e), e, triple, triple); } +// THE PROGRAM A SCRIPT'S `#!` LINE HANDS IT TO (#621). +// +// An artefact the run slot executes directly can be a script: emsdk's +// JavaScript launcher begins `#!/usr/bin/env node`. When that program is not +// there, the refusal comes after mcpp has handed the process over -- from the +// kernel, or from `env` once it has started (`/usr/bin/env: 'node': No such +// file or directory`) -- so none of the messages above applies. The line is +// read as the kernel reads it: the interpreter is the first word after `#!` +// and the rest is its argument; through `env`, that argument names the program +// `env` looks up on PATH. A form this does not read with certainty (an +// interpreter that is not an absolute path, an `env` option other than `-S`, +// `env` with no program) names no program, so a note built on it never names +// the wrong one. +struct ScriptInterpreter { + std::string line; // the `#!` line, without its line end + std::filesystem::path program; // what the kernel executes + std::string viaEnv; // what `program`, an `env`, looks up on PATH; empty otherwise +}; + +inline std::optional parse_script_interpreter(std::string_view head) { + if (!head.starts_with("#!")) return std::nullopt; + head = head.substr(0, head.find_first_of("\r\n")); + ScriptInterpreter out; + out.line = std::string(head); + constexpr std::string_view blanks = " \t"; + auto next_word = [&](std::string_view& rest) { + const auto from = std::min(rest.find_first_not_of(blanks), rest.size()); + rest.remove_prefix(from); + const auto to = std::min(rest.find_first_of(blanks), rest.size()); + auto word = rest.substr(0, to); + rest.remove_prefix(to); + return word; + }; + std::string_view rest = head.substr(2); + const auto program = next_word(rest); + if (!program.starts_with('/')) return std::nullopt; + out.program = std::filesystem::path(program); + if (out.program.filename() != "env") return out; + // `env [-S] [NAME=value]... []...` + for (auto word = next_word(rest); !word.empty(); word = next_word(rest)) { + if (word == "-S" || word == "--split-string") continue; + if (word.starts_with('-')) return std::nullopt; + if (word.find('=') != std::string_view::npos) continue; + out.viaEnv = std::string(word); + return out; + } + return std::nullopt; +} + +// The artefact's own `#!` line. Read on every host: where the system starts no +// file by it, the artefact is not started either, and the remedy -- a toolchain +// descriptor that names the runner -- is the same. +inline std::optional script_interpreter(const std::filesystem::path& artifact) { + std::ifstream in(artifact, std::ios::binary); + if (!in) return std::nullopt; + // The kernel reads no more of the line than this (BINPRM_BUF_SIZE). + std::string head(256, '\0'); + in.read(head.data(), static_cast(head.size())); + head.resize(static_cast(in.gcount())); + return parse_script_interpreter(head); +} + +// What `mcpp run` and `mcpp test` say before they execute `artifact` directly +// when the program its `#!` line names is not there; empty when it is, and +// when the artefact is no script this reads. `pathEnv` is the PATH the +// artefact receives, the one `env` searches. +// +// The remedy is the one an emsdk payload installed before its recipe wrote +// `.mcpp-toolchain.json` needs (docs/20, "Running what they produce"). Its +// commands name `toolchain`, the managed spec this build used (`emsdk@6.0.9`): +// the file's first line does not say which payload built it, the build does. +// Empty (a toolchain given by path, which mcpp does not install) leaves the +// spec to the reader. +inline std::string missing_interpreter_note(const std::filesystem::path& artifact, + std::string_view pathEnv, + std::string_view toolchain = {}) { + auto script = script_interpreter(artifact); + if (!script) return {}; + std::string missing; + if (!detail::executable_file(script->program)) + missing = std::format("'{}' is not an executable file", script->program.string()); + else if (!script->viaEnv.empty() && !locate(script->viaEnv, {}, pathEnv).program) + missing = std::format("'{}' is not on PATH", script->viaEnv); + if (missing.empty()) return {}; + return std::format( + "'{0}' runs through its first line, `{1}`, and {2}.\n" + " A toolchain payload names the program that runs its artefacts in\n" + " `.mcpp-toolchain.json`; one installed before its recipe wrote that file\n" + " names none, and its artefacts run through their `#!` line.\n" + " help: `mcpp index update`, then `mcpp toolchain remove {3}` and\n" + " `mcpp toolchain install {3}`{4}", + artifact.string(), script->line, missing, + toolchain.empty() ? std::string_view("") : toolchain, + toolchain.empty() ? " for the toolchain that built it" : ""); +} + } // namespace mcpp::build::runner_lookup diff --git a/src/build/runtime_validation.cppm b/src/build/runtime_validation.cppm index 9d92557f3..6586ff873 100644 --- a/src/build/runtime_validation.cppm +++ b/src/build/runtime_validation.cppm @@ -16,6 +16,9 @@ export module mcpp.build.runtime_validation; import std; +import mcpp.build.refusal; +import mcpp.libs.path_identity; +import mcpp.pm.compat.registry; import mcpp.provider; import mcpp.provider.select; import mcpp.build.loader_contract; @@ -51,6 +54,10 @@ struct ValidatedArtifact { // The required `dlopen` sonames the program cannot reach from the object // that loads them, one sentence each (dlopen_unreachable). std::vector dlopenUnreachable; + // The `DT_NEEDED` sonames only the union view of the default environment + // answers, for a project that states no environment + // (COMPAT(implicit-default-environment), design 2026-11-27 §4.1). + std::vector unionOnly; }; // THE REQUIRED `dlopen` SONAMES A PROGRAM CANNOT REACH (design 2026-11-21, @@ -84,9 +91,18 @@ struct StoredRuntimeSummary { ArtifactSnapshot snapshot_link_artifacts(const mcpp::build::BuildPlan& plan); +// What each link read, by artifact: the linker's own report (`--dependency-file`, +// SPEC-004 §8.1), as ninja keeps it. Empty for an artifact whose link reports +// nothing. +using LinkInputs = std::map>; + +// The closure rules, and (design 2026-11-27 §4.1, mcpp#537) the invariant they +// are forms of: every `DT_NEEDED` of an image resolves at load time to the file +// its link read for it. `linkInputs` gives the link's side. ValidationReport validate_changed_artifacts( const mcpp::build::BuildPlan& plan, - const ArtifactSnapshot& before); + const ArtifactSnapshot& before, + const LinkInputs& linkInputs = {}); std::optional latest_stored_verdict(const std::filesystem::path& targetRoot); @@ -531,12 +547,109 @@ std::optional cached_artifact( "diagnostics", std::vector{}); out.dlopenUnreachable = it->value( "dlopen_unreachable", std::vector{}); + out.unionOnly = it->value("union_only", std::vector{}); return out; } catch (...) { return std::nullopt; } } +// LINKED FROM ONE FILE, LOADED FROM ANOTHER (mcpp#537). The link read a +// shared object for a `DT_NEEDED` of the image, and the loader, searching the +// image's run path, finds another file of that name: a host directory on the +// link line (`-L/usr/lib/x86_64-linux-gnu`) and the environment's union view at +// load time answered `libgbm.so.1` with two builds of it, and the program +// crashed in the library it had not been linked against. The two are compared +// as objects (one file through any spelling) and then by content; a difference +// after both is the defect. The run-time payload's own libraries are rule B's, +// and are not compared here. +std::vector linked_and_loaded_apart(const mcpp::build::BuildPlan& plan, + const mcpp::runtime::elf::RuntimeResolution& resolution, + const std::vector& linked) { + std::vector out; + auto under_binding = [&](const std::filesystem::path& p) { + return std::ranges::any_of(plan.runtimeBinding.libraryDirs, [&](auto const& d) { + auto rel = p.lexically_normal().lexically_relative(d.lexically_normal()).generic_string(); + return !rel.empty() && !rel.starts_with(".."); + }); + }; + auto digest = [](const std::filesystem::path& p) -> std::optional { + std::ifstream in(p, std::ios::binary); + if (!in) return std::nullopt; + std::uint64_t h = 1469598103934665603ull; + for (std::istreambuf_iterator it(in), end; it != end; ++it) { + h ^= static_cast(*it); + h *= 1099511628211ull; + } + return std::format("{:016x}", h); + }; + const auto& needed = resolution.artifact.needed; + for (auto const& file : linked) { + // A link input that is a shared object, by the SONAME it carries. + auto facts = mcpp::runtime::elf::inspect_elf_runtime(file); + if (!facts || facts->soname.empty()) continue; + if (std::ranges::find(needed, facts->soname) == needed.end()) continue; + auto loaded = std::ranges::find_if(resolution.objects, [&](auto const& o) { + return o.soname == facts->soname || o.artifact.filename() == facts->soname; + }); + if (loaded == resolution.objects.end() || under_binding(loaded->artifact) || under_binding(file)) continue; + if (mcpp::libs::path_identity::same(file, loaded->artifact).value_or(false)) continue; + const auto a = digest(file), b = digest(loaded->artifact); + if (a && b && *a == *b) continue; + mcpp::build::refusal::record(mcpp::build::refusal::Code::RuntimeClosure); + out.push_back(std::format( + "{} is linked from one file and loaded from another\n" + " linked {}\n" + " loaded {}\n" + " help: state the package that provides it rather than a directory that holds a copy, " + "or remove the directory from the link", + facts->soname, file.string(), loaded->artifact.string())); + } + return out; +} + +// THE LIBRARIES ONLY THE DEFAULT ENVIRONMENT ANSWERS (design 2026-11-27 §4.1). +// The union view of an environment holds whatever was ever installed in it, +// and for a project that states no environment that is the machine's default +// one, shared by every project on the machine: a library found there is found +// on this machine and not on a clean one (#535, #537). The artifact is +// resolved again without the view; what it then lacks, it had only from there. +// +// COMPAT(implicit-default-environment): reported until the row's floor, from +// which the view is not searched for such a project. +std::vector union_only(const mcpp::build::BuildPlan& plan, const std::filesystem::path& artifact, + const mcpp::runtime::elf::RuntimeResolution& resolution, + const std::vector& searchDirs) { + if (plan.statedEnvironment) return {}; + std::vector farm; + for (auto const& dir : plan.runtimeSearch) + if (dir.origin == mcpp::runtime::search::Origin::SubosFarm) farm.push_back(dir.path); + if (farm.empty()) return {}; + std::vector without; + for (auto const& d : searchDirs) + if (std::ranges::find(farm, d) == farm.end()) without.push_back(d); + auto bare = mcpp::runtime::elf::resolve_runtime_closure(artifact, plan.runtimeBinding, without); + std::vector out; + for (auto const& soname : bare.unresolvedSonames) + if (std::ranges::find(resolution.unresolvedSonames, soname) == resolution.unresolvedSonames.end()) + out.push_back(soname); + return out; +} + +void report_union_only(const ValidatedArtifact& v) { + auto const* d = mcpp::pm::compat::find_deprecation("implicit-default-environment"); + if (!d) return; + for (auto const& soname : v.unionOnly) { + const auto detail = std::format("{} needs {}", v.artifact.filename().string(), soname); + mcpp::pm::compat::record_use("implicit-default-environment", "the project", detail, true); + mcpp::diag::warning(d->domain, std::format( + "{}, which only the default environment's union of installed packages provides; this " + "machine has it and a clean one may not. Reading it from there for a project that states " + "no environment is {}. Write {} instead.", + detail, mcpp::pm::compat::deprecation_clause(*d), d->canonical)); + } +} + // Said on every build, as the record keeps it: the program does not start // where it needs the library, whether or not this build linked it again. void report_dlopen_unreachable(const ValidatedArtifact& v) { @@ -558,6 +671,7 @@ void store_artifact(nlohmann::json& doc, {"status", status_name(value.verdict.status)}, {"diagnostics", value.verdict.diagnostics}, {"dlopen_unreachable", value.dlopenUnreachable}, + {"union_only", value.unionOnly}, }; } @@ -701,7 +815,8 @@ std::vector dlopen_unreachable(const mcpp::build::BuildPlan& plan, ValidationReport validate_changed_artifacts( const mcpp::build::BuildPlan& plan, - const ArtifactSnapshot& before) { + const ArtifactSnapshot& before, + const LinkInputs& linkInputs) { ValidationReport report; if constexpr (!mcpplibs::os::is_linux) { record_without_rules(plan, before); return report; } // Provider dispatch (see mcpp.runtime.binding): what follows is @@ -819,6 +934,7 @@ ValidationReport validate_changed_artifacts( auto fp = fingerprint(artifact, now, plan.runtimeBinding.contractHash); if (auto cached = cached_artifact(doc, key, fp, artifact)) { report_dlopen_unreachable(*cached); + report_union_only(*cached); // Same stat before/after and a current stored verdict is the hot // no-op: do not parse. Only PASS may also stay silent; a stored // mismatch must keep failing and an inconclusive result must keep @@ -840,8 +956,19 @@ ValidationReport validate_changed_artifacts( // run-time resolution, so mcpp reports rather than blocks. validated.verdict = mcpp::runtime::elf::validate_runtime_artifact( artifact, plan.runtimeBinding, resolution, host_libs_allowed(plan)); + // A build that states it reaches outside the sandbox on purpose + // (`MCPP_ALLOW_HOST_LIBS`) is told, not stopped, as for rule B. + if (auto it = linkInputs.find(artifact); it != linkInputs.end()) + for (auto& apart : linked_and_loaded_apart(plan, resolution, it->second)) { + using Status = mcpp::runtime::elf::RuntimeVerdict::Status; + if (!host_libs_allowed(plan)) validated.verdict.status = Status::ProvenMismatch; + else if (validated.verdict.status == Status::Pass) validated.verdict.status = Status::Inconclusive; + validated.verdict.diagnostics.push_back(std::move(apart)); + } validated.dlopenUnreachable = dlopen_unreachable(plan, resolution); + validated.unionOnly = union_only(plan, artifact, resolution, searchDirs); report_dlopen_unreachable(validated); + report_union_only(validated); store_artifact(doc, key, fp, validated); changedCache = true; report.artifacts.push_back(std::move(validated)); diff --git a/src/cli.cppm b/src/cli.cppm index 9a4cba48d..9adab8882 100644 --- a/src/cli.cppm +++ b/src/cli.cppm @@ -24,6 +24,7 @@ import mcpp.cli.cmd_publish; import mcpp.cli.cmd_xpkg; import mcpp.cli.cmd_registry; import mcpp.cli.cmd_self; +import mcpp.cli.complete; import mcpp.cli.cmd_toolchain; import mcpp.pm.commands; import mcpp.toolchain.fingerprint; // MCPP_VERSION @@ -671,6 +672,10 @@ int run(int argc, char** argv) { auto app = cl::App("mcpp") .version(std::string{mcpp::toolchain::MCPP_VERSION}) .description("modern C++ build tool") + // Completion is the library's (design 2026-11-27 §4.11): `mcpp + // __complete ` answers from this tree, and `mcpp self + // completion` writes the adapter a shell reads. + .completion({.command = ""}) .option(cl::Option("quiet").short_name('q') .help("Suppress status output").global()) .option(cl::Option("verbose").short_name('v') @@ -728,7 +733,7 @@ int run(int argc, char** argv) { .help("Global dependency cache: global (default) | local | off")) .option(cl::Option("jobs").short_name('j').takes_value().value_name("N") .help("Concurrent compiles: a number, or 'auto' to size from cores + free RAM")) - .option(cl::Option("toolchain").takes_value().value_name("SPEC") + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") .help("Build with this toolchain for one build, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) @@ -738,7 +743,7 @@ int run(int argc, char** argv) { .help("The host graph's platform for this invocation (= MCPP_HOST_PLATFORM)")) .option(cl::Option("no-cache") .help("Deprecated alias for --cache=off (also clears the build dir)")) - .option(cl::Option("target").takes_value().multiple().help( + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().help( "Build for (e.g. x86_64-linux-musl), or for a target set (e.g. openkal, " "linux-musl); repeatable: one leg per target")) .option(cl::Option("accel").takes_value().value_name("SPEC") @@ -747,9 +752,9 @@ int run(int argc, char** argv) { .help("Target no accelerator, ignoring [build] accel")) .option(cl::Option("static").help( "Force static linking (-static). On Linux, prefer pairing with --target -linux-musl")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Build the named workspace member (namespace.name or package name, then directory); repeat to build several")) - .option(cl::Option("profile").takes_value().value_name("NAME") + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") .help("Build profile: dev (default) | release | dist | <[profile.*] name>")) .option(cl::Option("release").help("Shorthand for --profile release")) .option(cl::Option("dev").help("Shorthand for --profile dev (-O0 -g)")) @@ -778,21 +783,21 @@ int run(int argc, char** argv) { .help("Then write what the build uses (payloads, index snapshots, git clones) into DIR")) .option(cl::Option("from").takes_value().value_name("DIR") .help("First take a directory `mcpp fetch --to` wrote into the home")) - .option(cl::Option("target").takes_value().multiple().help( + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().help( "Fetch for , or for a target set; repeatable: one leg per target")) - .option(cl::Option("toolchain").takes_value().value_name("SPEC") + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") .help("Fetch for this toolchain, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT)")) .option(cl::Option("platform").takes_value().value_name("SPEC") .help("The target's platform for this invocation (= MCPP_PLATFORM)")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Fetch for the named workspace member; repeat for several")) .option(cl::Option("workspace") .help("Fetch for all workspace members")) .option(cl::Option("exclude").takes_value().multiple().value_name("NAME") .help("With --workspace, leave the named member out; repeatable")) - .option(cl::Option("profile").takes_value().value_name("NAME") + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") .help("Build profile: dev (default) | release | dist | <[profile.*] name>")) .option(cl::Option("features").takes_value().value_name("LIST") .help("Activate root-package features, and a dependency's as /")) @@ -816,7 +821,7 @@ int run(int argc, char** argv) { // lets `run` spell the flag `--target` like every other // subcommand, instead of being the one command that cannot. .arg(cl::Arg("bin").help("Binary name (optional)")) - .option(cl::Option("target").takes_value().multiple().value_name("TRIPLE") + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().value_name("TRIPLE") .help("Cross target triple or target set (same axis as `mcpp build --target`); " "of several, the first this host reaches, its own architecture first")) .option(cl::Option("accel").takes_value().value_name("SPEC") @@ -827,7 +832,7 @@ int run(int argc, char** argv) { // `run` accepted, and scripts written against it must keep working. .option(cl::Option("target-triple").takes_value().value_name("TRIPLE") .help("Alias for --target")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Run only the named workspace member (namespace.name or package name, then directory; one member: a second -p is refused)")) // DECLARED ON THE THREE COMMANDS THAT BUILD BEFORE THEY ACT, AS ON // `build`. The value has always reached them: the pre-parse loop @@ -835,7 +840,7 @@ int run(int argc, char** argv) { // `MCPP_TOOLCHAIN=llvm@22.1.8 mcpp test` compiled with clang, while // the spelling the help of `build` teaches was refused here as an // unknown option (#634 A10). - .option(cl::Option("toolchain").takes_value().value_name("SPEC") + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") .help("Build with this toolchain for one invocation, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) @@ -863,7 +868,7 @@ int run(int argc, char** argv) { // actually run. .option(cl::Option("features").takes_value().value_name("LIST") .help("Activate features (comma/space separated), same axis as `mcpp build --features`")) - .option(cl::Option("profile").takes_value().value_name("NAME") + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") .help("Build profile to run (dev | release | )")) .option(cl::Option("release").help("Shorthand for --profile release")) .option(cl::Option("dev").help("Shorthand for --profile dev")) @@ -918,7 +923,7 @@ int run(int argc, char** argv) { .description("Build + run all tests/**/*.cpp (after `--`, args go to each test binary)") .arg(cl::Arg("pattern") .help("Run only tests whose name contains a PATTERN; several select every test one of them names (optional)")) - .option(cl::Option("target").takes_value().multiple().value_name("TRIPLE") + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().value_name("TRIPLE") .help("Cross target triple or target set (same axis as `mcpp build --target`); " "repeatable: every leg is built, and run where this host reaches it")) .option(cl::Option("accel").takes_value().value_name("SPEC") @@ -965,7 +970,7 @@ int run(int argc, char** argv) { .help("Kill a compile/link drive still running after SECS seconds (default 0 = no limit; POSIX only)")) .option(cl::Option("workspace-timeout").takes_value().value_name("SECS") .help("Start no further member's tests after SECS seconds since the command began, and report what did not run (default 0 = no limit); the build is bounded by --build-timeout")) - .option(cl::Option("profile").takes_value().value_name("NAME") + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") .help("Build profile for the test build: dev (default) | release | dist | <[profile.*] name>")) .option(cl::Option("features").takes_value().value_name("LIST") .help("Activate root-package features, and a dependency's as /, for the test build (comma-separated)")) @@ -973,9 +978,9 @@ int run(int argc, char** argv) { .help("Pin capability providers (e.g. blas=openblas,lapack=mkl)")) .option(cl::Option("strict") .help("Treat manifest schema warnings (unknown feature/platform) as errors")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Run the tests of the named workspace member (namespace.name or package name, then directory); repeat to test several")) - .option(cl::Option("toolchain").takes_value().value_name("SPEC") + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") .help("Build the tests with this toolchain for one invocation, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) @@ -1015,9 +1020,9 @@ int run(int argc, char** argv) { // report on the current directory's default: "what would a build // for THIS pair resolve to" is the question the target matrix asks // once per cell, and it builds nothing. - .option(cl::Option("target").takes_value() + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value() .help("Ask about this target instead of the project's default")) - .option(cl::Option("toolchain").takes_value() + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value() .help("Ask about this toolchain, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) @@ -1038,13 +1043,18 @@ int run(int argc, char** argv) { .description("Add a dependency to mcpp.toml") .arg(cl::Arg("pkg").help( "Exact package spec, e.g. foo@1.0.0 or compat.gtest@1.15.2") - .required()) + .required().complete(mcpp::cli::complete::index_packages)) .option(cl::Option("dev").help( "Add to [dev-dependencies] (test-only, e.g. compat.gtest)")) + .option(cl::Option("build").help( + "Add to [build-dependencies] (a build plugin or a tool the build runs)")) .action(mcpp::pm::commands::cmd_add)) .subcommand(cl::App("remove") .description("Remove a dependency from mcpp.toml") - .arg(cl::Arg("pkg").help("Exact package selector [ns.]name").required()) + .arg(cl::Arg("pkg").help("Exact package selector [ns.]name").required() + .complete(mcpp::cli::complete::dependencies)) + .option(cl::Option("dev").help("Remove from [dev-dependencies]")) + .option(cl::Option("build").help("Remove from [build-dependencies]")) .action(mcpp::pm::commands::cmd_remove)) .subcommand(cl::App("update") .description("Re-resolve dependencies and rewrite mcpp.lock") @@ -1064,7 +1074,7 @@ int run(int argc, char** argv) { .option(cl::Option("allow-dirty").help("Allow uncommitted changes")) .option(cl::Option("tag").takes_value().value_name("TEMPLATE") .help("The release's tag, of {version}, {name} and {namespace} (default: v{version})")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Publish the named workspace member; repeat to publish several under one tag")) .option(cl::Option("workspace") .help("Publish every workspace member: one archive and one descriptor each, and SHA256SUMS")) @@ -1096,7 +1106,7 @@ int run(int argc, char** argv) { .option(cl::Option("linkage").takes_value().value_name("static|shared") .help("The program's libraries in it (static) or beside it (shared); rebuilds " "with [build] dependency_linkage (default: as the project builds)")) - .option(cl::Option("target").takes_value().multiple() + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple() .help("A target (x86_64-linux-gnu) or a target set (openkal, linux-musl); " "repeatable: the legs")) .option(cl::Option("no-universal") @@ -1126,13 +1136,13 @@ int run(int argc, char** argv) { // Packaging builds RELEASE by default — the artifact leaves this // machine. `[build] default-profile` still wins when it is set; // this only replaces the "dev" fallback every other command uses. - .option(cl::Option("profile").takes_value() + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value() .help("Build profile (default: [build] default-profile, else release)")) // The shorthands `build` and `run` take, with their precedence: // `--profile` wins over either (#649 E9). .option(cl::Option("release").help("Shorthand for --profile release")) .option(cl::Option("dev").help("Shorthand for --profile dev")) - .option(cl::Option("toolchain").takes_value().value_name("SPEC") + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") .help("Build with this toolchain for one invocation, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) @@ -1152,7 +1162,7 @@ int run(int argc, char** argv) { .help("Ship the artifacts as built (default: strip debug info)")) .option(cl::Option("all-programs") .help("Ship every program of the package: the one named after it (or the named one) and the others beside it")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Pack the named workspace member (namespace.name or package name, then directory), as if run in its directory; repeat to pack several, planned and built once")) .option(cl::Option("workspace") .help("Pack every workspace member that has a program target, planned and built once")) @@ -1201,9 +1211,9 @@ int run(int argc, char** argv) { .help("Machine-readable output (enveloped; see docs/50-machine-output.md)")) .option(cl::Option("output").short_name('o').takes_value().value_name("FILE") .help("Write to file instead of stdout")) - .option(cl::Option("target").takes_value().value_name("TRIPLE") + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().value_name("TRIPLE") .help("Describe the build for (same axis as `mcpp build --target`)")) - .option(cl::Option("toolchain").takes_value().value_name("SPEC") + .option(cl::Option("toolchain").complete(mcpp::cli::complete::toolchains).takes_value().value_name("SPEC") .help("Describe the build with this toolchain, e.g. llvm@22.1.8")) .option(cl::Option("sysroot").takes_value().value_name("SYSROOT") .help("The target's base for this invocation (= MCPP_SYSROOT): a package, glibc@system, path:, none")) @@ -1216,9 +1226,9 @@ int run(int argc, char** argv) { .option(cl::Option("no-accel") .help("Describe the variant built for no accelerator")) .option(cl::Option("static").help("Describe the build with --static")) - .option(cl::Option("package").short_name('p').takes_value().multiple().value_name("NAME") + .option(cl::Option("package").complete(mcpp::cli::complete::members).short_name('p').takes_value().multiple().value_name("NAME") .help("Describe the named workspace member (namespace.name or package name, then directory); repeat to describe several")) - .option(cl::Option("profile").takes_value().value_name("NAME") + .option(cl::Option("profile").complete(mcpp::cli::complete::profiles).takes_value().value_name("NAME") .help("Build profile: dev (default) | release | dist | <[profile.*] name>")) .option(cl::Option("release").help("Shorthand for --profile release")) .option(cl::Option("dev").help("Shorthand for --profile dev")) @@ -1278,7 +1288,7 @@ int run(int argc, char** argv) { // mcpp toolchain install --target x86_64-windows-gnu .arg(cl::Arg("compiler").help("gcc | llvm | msvc | emsdk | android-ndk (or gcc@16.1.0; legacy aliases accepted)")) .arg(cl::Arg("version").help("e.g. 16.1.0, 15, 15.1")) - .option(cl::Option("target").takes_value().help( + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( "Install the toolchain payload for (e.g. x86_64-windows-gnu)")) .option(cl::Option("platform").takes_value().value_name("SPEC") .help("With --target: the target's platform for this invocation (= MCPP_PLATFORM)"))) @@ -1288,7 +1298,7 @@ int run(int argc, char** argv) { // partial versions allowed. .arg(cl::Arg("spec").help("[@] (version may be partial)").required()) .arg(cl::Arg("version").help("(optional, alternative to @-form)")) - .option(cl::Option("target").takes_value().help( + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( "Default build target (omit = host)"))) .subcommand(cl::App("remove") .description("Uninstall a toolchain") @@ -1300,7 +1310,7 @@ int run(int argc, char** argv) { .help("[@] (exact version)") .required()) .arg(cl::Arg("version").help("(optional, alternative to @-form)")) - .option(cl::Option("target").takes_value().help( + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().help( "Remove the payload for instead of the host one"))) .action(cmd_toolchain_any)) .subcommand(cl::App("cache") @@ -1403,7 +1413,7 @@ int run(int argc, char** argv) { .action(cmd_doctor)) .subcommand(cl::App("env") .description("Print mcpp paths and configuration; with --target, one configuration: toolchain, platform, tools, runner") - .option(cl::Option("target").takes_value().multiple().value_name("TRIPLE") + .option(cl::Option("target").complete(mcpp::cli::complete::targets).takes_value().multiple().value_name("TRIPLE") .help("Report this target's configuration (prepared, not built; the project's when run in one); " "a target set or several reports each leg")) .option(cl::Option("host") @@ -1427,6 +1437,12 @@ int run(int argc, char** argv) { .subcommand(cl::App("version") .description("Show mcpp version") .action(cmd_self_version)) + .subcommand(cl::App("completion") + .description("Write the completion script of a shell into the home and say how to load it") + .arg(cl::Arg("shell").values({"bash", "zsh", "fish", "powershell"}) + .help("bash, zsh, fish or powershell; the shell $SHELL names when absent")) + .option(cl::Option("print").help("Print the script instead of writing it")) + .action(cmd_self_completion)) .subcommand(cl::App("explain") .description("Show extended description for an error code") .arg(cl::Arg("code").help("Error code such as E0001, or a refusal's reason token such as platform-version-group").required()) @@ -1542,7 +1558,7 @@ int run(int argc, char** argv) { .action(cmd_coff_def)) // The three edges of the detach-codegen schedule. Internal, and named as // such: they are only ever invoked by a generated build.ninja. - .subcommand(cl::App("bmi-compile") + .subcommand(cl::App("bmi-compile").hidden() .description("(internal) Compile a module interface and return when its BMI is published") .option(cl::Option("bmi").takes_value().value_name("PATH").help("BMI this unit publishes")) .option(cl::Option("object").takes_value().value_name("PATH")) @@ -1555,7 +1571,7 @@ int run(int argc, char** argv) { .option(cl::Option("dep-to").takes_value().value_name("PATH").help("where ninja expects this edge's depfile")) .option(cl::Option("relocate").takes_value().value_name("NAMING").help("write below an attempt of its own and publish (design 2026-11-19 §10.6)")) .action(cmd_bmi_compile)) - .subcommand(cl::App("bmi-supervise") + .subcommand(cl::App("bmi-supervise").hidden() .description("(internal) Run a compiler to completion and record its status") .option(cl::Option("slot").takes_value().value_name("PATH")) .option(cl::Option("sem").takes_value().value_name("PATH")) @@ -1564,7 +1580,7 @@ int run(int argc, char** argv) { .option(cl::Option("command-file").takes_value().value_name("PATH")) .option(cl::Option("relocation").takes_value().value_name("DIR")) .action(cmd_bmi_supervise)) - .subcommand(cl::App("bmi-await") + .subcommand(cl::App("bmi-await").hidden() .description("(internal) Join a detached compiler and replay its diagnostics") .option(cl::Option("slot").takes_value().value_name("PATH")) .option(cl::Option("object").takes_value().value_name("PATH")) @@ -2016,7 +2032,7 @@ int run(int argc, char** argv) { "toolchain", "cache", "index", "self", "explain", "version", "dyndep", "why", "resolve", "stage", "write", "coff-def", "place-dlls", "link-output", "platform-step", - "bmi-compile", "bmi-supervise", "bmi-await", + "bmi-compile", "bmi-supervise", "bmi-await", "__complete", }); bool ok = false; for (auto k : known) if (k == first) { ok = true; break; } diff --git a/src/cli/cmd_self.cppm b/src/cli/cmd_self.cppm index 2294af22c..140ac10f6 100644 --- a/src/cli/cmd_self.cppm +++ b/src/cli/cmd_self.cppm @@ -22,6 +22,7 @@ import mcpp.wire; import nlohmann.json; import mcpp.toolchain.platform; import mcpp.invocation; +import mcpp.ui; namespace libc = mcpplibs::mwrap::libc::macros; @@ -159,6 +160,59 @@ export int cmd_self_version(const mcpplibs::cmdline::ParsedArgs& /*parsed*/) { return 0; } +// `mcpp self completion [shell]` (design 2026-11-27 §4.11): the adapter a shell +// reads to complete mcpp, written to `/config/shell/`, and the line that +// loads it. The adapter asks `mcpp __complete`, so it is written once: a +// release that adds a command completes it with the same file. The shell's own +// configuration is the user's, and is not edited. +export int cmd_self_completion(const mcpplibs::cmdline::ParsedArgs& parsed) { + namespace cmp = mcpplibs::cmdline::completions; + std::string name = parsed.positional(0); + if (name.empty()) + if (auto sh = mcpp::invocation::get("SHELL"); sh && !sh->empty()) + name = std::filesystem::path(*sh).filename().string(); + // Without `SHELL`, PowerShell is known by its module path: every session it + // starts states one, and Windows states one in every process. + if (name.empty()) + if (auto ps = mcpp::invocation::get("PSModulePath"); ps && !ps->empty()) name = "powershell"; + if (name == "pwsh") name = "powershell"; + auto shell = mcpplibs::cmdline::shell_from_string(name); + if (!shell) { + mcpp::ui::error(std::format( + "no completion for the shell '{}'\n help: name one: mcpp self completion bash|zsh|fish|powershell", + name.empty() ? std::string("(none)") : name)); + return 2; + } + const auto script = cmp::adapter(*shell, "mcpp", "__complete"); + if (parsed.is_flag_set("print")) { + std::print("{}", script); + return 0; + } + const auto ext = *shell == mcpplibs::cmdline::Shell::powershell ? std::string("ps1") : name; + const auto file = mcpp::home::root() / "config" / "shell" / std::format("mcpp.{}", ext); + std::error_code ec; + std::filesystem::create_directories(file.parent_path(), ec); + { + std::ofstream os(file, std::ios::binary | std::ios::trunc); + os << script; + if (!os) { + mcpp::ui::error(std::format("cannot write '{}'", mcpp::home::spelling(file))); + return 1; + } + } + // One spelling for every shell, forward slashes and UTF-8: the POSIX shells + // of a Windows machine (Git Bash, MSYS2) read `C:/...` and not `C:\...`, and + // PowerShell reads both. + const auto at = mcpp::home::spelling(file); + mcpp::ui::status("Wrote", at); + const auto load = *shell == mcpplibs::cmdline::Shell::bash ? std::format("source '{}' # in ~/.bashrc", at) + : *shell == mcpplibs::cmdline::Shell::zsh ? std::format("source '{}' # in ~/.zshrc, after compinit", at) + : *shell == mcpplibs::cmdline::Shell::fish ? std::format("source '{}' # in ~/.config/fish/config.fish", at) + : std::format(". '{}' # in $PROFILE", at); + std::println("{}", load); + return 0; +} + export int cmd_self_init(const mcpplibs::cmdline::ParsedArgs& parsed) { std::string target = parsed.option_or_empty("home").value(); if (parsed.value("home") && target.empty()) { diff --git a/src/cli/complete.cppm b/src/cli/complete.cppm new file mode 100644 index 000000000..d7b2d9e47 --- /dev/null +++ b/src/cli/complete.cppm @@ -0,0 +1,152 @@ +// mcpp.cli.complete — the candidates mcpp's command line completes from. +// +// Completion is mcpplibs.cmdline's (design 2026-11-27 §4.11): a shell's adapter +// passes the words before the cursor to `mcpp __complete`, and the library +// answers from the command tree by the rules its parse reads it by. What the +// tree cannot know is mcpp's, and is here: the profiles and the members the +// manifest in this directory states, the dependencies it lists, the targets +// the engine has rows for, the toolchains installed in the home, the packages +// of the local index copies. +// +// Each reads what is already on disk and nothing more: a completion runs at +// every press of a key, so it initialises no home, fetches no index and plans +// no build. A question it cannot answer gives no candidates. + +export module mcpp.cli.complete; + +import std; +import mcpp.manifest; +import mcpp.project; +import mcpp.home; +import mcpp.config; +import mcpp.provider; +import mcpp.provider.select; +import mcpp.toolchain.payloads; +import mcpp.toolchain.target_rows; + +export namespace mcpp::cli::complete { + +std::vector profiles(std::string_view prefix); +std::vector members(std::string_view prefix); +std::vector dependencies(std::string_view prefix); +std::vector targets(std::string_view prefix); +std::vector toolchains(std::string_view prefix); +std::vector index_packages(std::string_view prefix); + +} // namespace mcpp::cli::complete + +namespace mcpp::cli::complete { + +namespace { + +namespace fs = std::filesystem; + +std::optional here() { + std::error_code ec; + auto root = mcpp::project::find_manifest_root(fs::current_path(ec)); + if (!root) return std::nullopt; + auto m = mcpp::manifest::load(*root / "mcpp.toml"); + if (!m) return std::nullopt; + return std::move(*m); +} + +void keep(std::vector& out, std::string value, std::string_view prefix) { + if (value.starts_with(prefix) && std::ranges::find(out, value) == out.end()) out.push_back(std::move(value)); +} + +// The home as it is, when there is one: a completion does not make one. +std::optional existing_home() { + try { + auto home = mcpp::home::root(); + std::error_code ec; + if (fs::is_directory(home, ec)) return home; + } catch (...) { + } + return std::nullopt; +} + +// The home's configuration, read as every command reads it and with nothing +// written (`Initialization::ReadOnly`): where its provider's stores and its +// index copies are is the configuration's answer, not a spelling of this file. +std::optional existing_config() { + if (!existing_home()) return std::nullopt; + auto cfg = mcpp::config::load_or_init(/*quiet=*/true, {}, {}, mcpp::config::Initialization::ReadOnly); + if (!cfg) return std::nullopt; + return std::move(*cfg); +} + +} // namespace + +std::vector profiles(std::string_view prefix) { + std::vector out; + for (auto p : {"dev", "release", "dist"}) keep(out, p, prefix); + if (auto m = here()) + for (auto const& [name, _] : m->profiles) keep(out, name, prefix); + return out; +} + +std::vector members(std::string_view prefix) { + std::vector out; + if (auto m = here()) + for (auto const& member : m->workspace.members) keep(out, member, prefix); + return out; +} + +std::vector dependencies(std::string_view prefix) { + std::vector out; + if (auto m = here()) + for (auto const* family : {&m->dependencies, &m->devDependencies, &m->buildDependencies}) + for (auto const& [key, _] : *family) keep(out, key, prefix); + return out; +} + +std::vector targets(std::string_view prefix) { + std::vector out; + for (auto const* row : mcpp::toolchain::target::rows()) keep(out, std::string(row->triple), prefix); + return out; +} + +std::vector toolchains(std::string_view prefix) { + std::vector out; + auto cfg = existing_config(); + if (!cfg) return out; + // What `mcpp toolchain install` installed: the entries of the stores of the + // home's provider that a request may name (the payload table, + // mcpp.toolchain.payloads), as `@`. + for (auto const& store : mcpp::provider::open(mcpp::config::make_xlings_env(*cfg))->stores()) + for (auto const& entry : mcpp::provider::layout().entries(store)) + if (mcpp::toolchain::payloads::named(entry.name)) + keep(out, std::format("{}@{}", entry.name, entry.version), prefix); + return out; +} + +std::vector index_packages(std::string_view prefix) { + std::vector out; + auto cfg = existing_config(); + if (!cfg) return out; + std::error_code ec; + // The descriptors of the home's index copies (`/pkgs/`), each named as + // a dependency key spells it: the package's identity, read by the reader + // `mcpp add` uses. A package of the default namespace is offered by its bare + // name, and by its qualified one once the word names the namespace. + std::vector descriptors; + for (auto const& index : cfg->indexRepos) { + if (index.dir.empty()) continue; + for (auto it = fs::recursive_directory_iterator(index.dir / "pkgs", ec); + !ec && it != fs::recursive_directory_iterator{}; it.increment(ec)) + if (it->path().extension() == ".lua") descriptors.push_back(it->path()); + } + const std::string qualified = std::format("{}.", mcpp::manifest::kDefaultNamespace); + for (auto const& file : descriptors) { + std::ifstream in(file, std::ios::binary); + const std::string text{std::istreambuf_iterator(in), {}}; + const auto id = mcpp::manifest::canonical_xpkg_identity_from_lua(text); + if (id.name.empty()) continue; + const std::string ns = id.ns.empty() ? std::string(mcpp::manifest::kDefaultNamespace) : id.ns; + const bool bare = ns == mcpp::manifest::kDefaultNamespace && !prefix.starts_with(qualified); + keep(out, bare ? id.name : std::format("{}.{}", ns, id.name), prefix); + } + return out; +} + +} // namespace mcpp::cli::complete diff --git a/src/config.cppm b/src/config.cppm index 331a7739b..9da97d273 100644 --- a/src/config.cppm +++ b/src/config.cppm @@ -21,6 +21,7 @@ import mcpplibs.mwrap.libc; import mcpp.home; import mcpp.modgraph.glob; // try_narrow: the one UTF-8 spelling of a path import mcpp.libs.toml; +import mcpp.libs.path_identity; import mcpp.manifest.platform; import mcpp.manifest.platform_toml; import nlohmann.json; @@ -1287,11 +1288,16 @@ std::expected load_or_init( if (!std::filesystem::exists(mcpp::provider::open(make_xlings_env(cfg))->config_file(), ec)) return false; if (!cfg.xlingsHomeOverride.empty()) return !std::filesystem::equivalent(cfg.xlingsHomeOverride, cfg.registryDir, ec); - const auto real = std::filesystem::canonical(cfg.registryDir, ec); - if (ec) return false; - const auto home = std::filesystem::canonical(cfg.mcppHome, ec); - if (ec) return false; - const auto rel = real.lexically_relative(home); + const auto real = mcpp::libs::path_identity::identity(cfg.registryDir); + const auto home = mcpp::libs::path_identity::identity(cfg.mcppHome); + if (!real || !home) { + mcpp::diag::degraded("config", std::format( + "whether the registry {} is a link to another home's could not be read", + mcpp::home::spelling(cfg.registryDir)), + "it is taken as this home's own, as its spelling says"); + return false; + } + const auto rel = real->lexically_relative(*home); return rel.empty() || *rel.begin() == ".."; }(); for (auto& r : cfg.indexRepos) { diff --git a/src/home.cppm b/src/home.cppm index 1e2e65556..6b52ae395 100644 --- a/src/home.cppm +++ b/src/home.cppm @@ -191,11 +191,15 @@ std::filesystem::path from_utf8(std::string_view value) { namespace { std::optional selected_home; +// THE HOME AS IT IS GIVEN (mcpp#1024): absolute and lexically normal, its links +// and drive aliases kept. Every path derived from it is opened and handed to a +// program under that spelling; whether two homes are one is a question of +// identity (mcpp.libs.path_identity), asked where it is asked. std::expected absolute_home(const std::filesystem::path& path) { std::error_code ec; - auto result = std::filesystem::weakly_canonical(std::filesystem::absolute(path, ec), ec); + auto result = std::filesystem::absolute(path, ec); if (ec) return std::unexpected(std::format("cannot resolve home '{}': {}", spelling(path), ec.message())); - return result; + return result.lexically_normal(); } bool contains_path(const std::filesystem::path& parent, const std::filesystem::path& child) { diff --git a/src/modgraph/graph.cppm b/src/modgraph/graph.cppm index 9cd442b2f..b8ceb2bed 100644 --- a/src/modgraph/graph.cppm +++ b/src/modgraph/graph.cppm @@ -114,6 +114,13 @@ struct SourceUnit { // Unit built from a manifest scan_overrides declaration instead of a // real scan — plan-vs-ddi verification is mandatory for these. bool scanOverridden = false; + // An `import` or a module declaration of the unit stands inside a + // preprocessor condition (mcpp#1026): which of them the unit has depends + // on what the condition evaluates to under its compile, which only the + // compiler knows. The text scanner records the rest and marks the unit; + // its declarations and imports are then the compiler's scan's + // (`scan_packages`' `answer`). + bool importsFromCompiler = false; // The source file this unit is built from, when the unit is not that file: // a unit the source seam gave for it (a private module fragment as a unit // of its own, SPEC-019). Empty: `path` is the source as written. What diff --git a/src/modgraph/p1689.cppm b/src/modgraph/p1689.cppm index e11e0081a..884cf60b6 100644 --- a/src/modgraph/p1689.cppm +++ b/src/modgraph/p1689.cppm @@ -48,16 +48,49 @@ struct DdiRule { // Tolerates the slightly unstable GCC formatting (variable whitespace). std::expected parse_ddi(std::string_view body); -// Run g++ on `source` and return the populated SourceUnit. -// tmpDir : per-build scratch dir for .ddi/.dep/.o byproducts. +// THE DEPENDENCY SCAN OF ONE UNIT, ITS WORDS IN ORDER, CONSTRUCTED IN ONE +// PLACE for the two times it runs: the build's scan edge, whose words are +// ninja expressions (`$in`, `$out`, `$cxxflags`) joined into its command, and +// the plan, which asks the compiler for a unit whose imports stand inside a +// preprocessor condition and hands the words to the program as its arguments. +// No shell stands between: a shell's quoting is its host's (cmd.exe reads no +// single quotes, measured: Windows error 123 for the quoted program), and an +// argument vector has none. GCC scans with the compiler itself; Clang with +// clang-scan-deps, given the compile. +struct ScanWords { + std::string prefix; // the edge's launcher, with its space; not an argument + std::string driver; // the compiler + std::string scanDeps; // clang-scan-deps; empty: the compiler scans + std::vector flags; // the unit's compile words + std::vector lang; // the language flag of a module interface; may be empty + std::string in; // the source + std::string out; // the P1689 record written + std::string depsTarget; // GCC: the target the record names + std::string depFile; // GCC: the make-style list of the files the scan read + std::string scratch; // GCC: the `-o` the driver creates, which nothing reads + std::string compileTarget; // Clang: the object the compile it is given would write +}; +std::vector scan_words(const ScanWords& w); +// The words joined after the prefix: the build's scan edge. +std::string scan_command(const ScanWords& w); + +// Run the compiler's scan on `source` and return the populated SourceUnit. +// tmpDir : per-build scratch dir for .ddi/.dep/.o byproducts. +// stdWords : the standard and the graph's dialect words, one argument each +// (empty: -std=c++23) +// flags : the unit's own compile words, after the standard and the +// include directories (its package's, the graph's dialect words) +// scanDeps : clang-scan-deps for a Clang toolchain; empty for GCC std::expected scan_file(const std::filesystem::path& source, const std::string& packageName, const mcpp::toolchain::Toolchain& tc, const std::filesystem::path& tmpDir, const std::vector& includeDirs, - std::string_view cppStandardFlag, - const mcpp::ExtensionTable& extTable); + std::span stdWords, + const mcpp::ExtensionTable& extTable, + const std::vector& flags = {}, + const std::filesystem::path& scanDeps = {}); } // namespace mcpp::modgraph::p1689 @@ -303,26 +336,62 @@ std::expected parse_ddi(std::string_view body) { namespace { -// The scan command is composed as text, with the flags the link model renders -// for a shell, as the ninja scan edge is. -bool run_capturing(const std::string& cmd, std::string& out) { - auto r = mcpp::run::capture_shell(cmd); - out = r.output; - return r.exit_code == 0; -} +// A path as an argument of the scan: the spelling the old command line gave it, +// without the quoting a shell would have read. +std::string argument(const std::filesystem::path& p) { return p.string(); } -std::string shell_escape(const std::filesystem::path& p) { - std::string s = p.string(); - std::string out = "'"; - for (char c : s) { - if (c == '\'') out += "'\\''"; - else out.push_back(c); +} // namespace + +std::vector scan_words(const ScanWords& w) { + std::vector out; + auto add = [&](std::string_view word) { + if (!word.empty()) out.emplace_back(word); + }; + auto add_all = [&](const std::vector& words) { + for (auto const& word : words) add(word); + }; + if (w.scanDeps.empty()) { + add(w.driver); + add_all(w.flags); + add("-fmodules"); + add("-fdeps-format=p1689r5"); + add("-fdeps-file=" + w.out); + add("-fdeps-target=" + w.depsTarget); + add("-M"); + add("-MM"); + add("-MF"); + add(w.depFile); + add_all(w.lang); + add("-E"); + add(w.in); + add("-o"); + add(w.scratch); + return out; } - out += "'"; + add(w.scanDeps); + add("-format=p1689"); + add("-o"); + add(w.out); + add("--"); + add(w.driver); + add_all(w.flags); + add_all(w.lang); + add("-c"); + add(w.in); + add("-o"); + add(w.compileTarget); return out; } -} // namespace +std::string scan_command(const ScanWords& w) { + std::string out = w.prefix; + const auto words = scan_words(w); + for (std::size_t i = 0; i < words.size(); ++i) { + if (i > 0) out += ' '; + out += words[i]; + } + return out; +} std::expected scan_file(const std::filesystem::path& source, @@ -330,8 +399,10 @@ scan_file(const std::filesystem::path& source, const mcpp::toolchain::Toolchain& tc, const std::filesystem::path& tmpDir, const std::vector& includeDirs, - std::string_view cppStandardFlag, - const mcpp::ExtensionTable& extTable) + std::span stdWords, + const mcpp::ExtensionTable& extTable, + const std::vector& flags, + const std::filesystem::path& scanDeps) { std::error_code ec; std::filesystem::create_directories(tmpDir, ec); @@ -352,55 +423,49 @@ scan_file(const std::filesystem::path& source, auto dep = base; dep += ".dep"; auto obj = base; obj += ".o"; - std::string sysroot_flag; + std::vector words; + if (stdWords.empty()) words.emplace_back("-std=c++23"); + else words.assign(stdWords.begin(), stdWords.end()); if (tc.base.stated()) { // A stated target base: the compile side the link model renders for // it (its sysroot, multiarch, or payload headers), as every compile // of this build is given. - sysroot_flag = mcpp::toolchain::resolve_link_model(tc).compile_flags( - [](const std::filesystem::path& p) { return shell_escape(p); }); + for (auto& word : mcpp::toolchain::resolve_link_model(tc).compile_tokens( + [](const std::filesystem::path& p) { return argument(p); })) + words.push_back(std::move(word)); } else if (!tc.base.root.empty()) { - sysroot_flag = std::format(" --sysroot={}", shell_escape(tc.base.root)); - } - std::string std_flag = cppStandardFlag.empty() - ? std::string("-std=c++23") - : std::string(cppStandardFlag); - std::string include_flags; - for (auto const& dir : includeDirs) { - include_flags += " -I"; - include_flags += shell_escape(dir); + words.push_back("--sysroot=" + argument(tc.base.root)); } + for (auto const& dir : includeDirs) words.push_back("-I" + argument(dir)); + words.insert(words.end(), flags.begin(), flags.end()); // Same suffix-recognition problem the ninja scan edge has: a driver that // does not know this source's extension hands it to the linker and exits 0 // with no .ddi. Told explicitly for module interfaces, and only for them — // an implementation unit must not be scanned as an interface. - std::string lang_flag; + std::vector lang; if (mcpp::produces_bmi(mcpp::classify(source, extTable))) - lang_flag = std::string(mcpp::toolchain::bmi_traits(tc).moduleInterfaceLangFlag); - - std::string cmd = std::format( - "{} {} -fmodules{}{}{}" - " -fdeps-format=p1689r5" - " -fdeps-file={}" - " -fdeps-target={}" - " -M -MM -MF {}" - " -E {} -o {} 2>&1", - shell_escape(tc.binaryPath), - std_flag, - sysroot_flag, - include_flags, - lang_flag, - shell_escape(ddi), - shell_escape(obj), - shell_escape(dep), - shell_escape(source), - shell_escape(obj)); - - std::string output; - bool ok = run_capturing(cmd, output); - if (!ok || !std::filesystem::exists(ddi)) { + for (auto word : std::string_view(mcpp::toolchain::bmi_traits(tc).moduleInterfaceLangFlag) + | std::views::split(' ')) + if (!word.empty()) lang.emplace_back(word.begin(), word.end()); + auto scratch = base; scratch += ".scan"; + const auto argv = scan_words({ + .driver = argument(tc.binaryPath), + .scanDeps = scanDeps.empty() ? std::string{} : argument(scanDeps), + .flags = std::move(words), + .lang = std::move(lang), + .in = argument(source), + .out = argument(ddi), + .depsTarget = argument(obj), + .depFile = argument(dep), + .scratch = argument(scratch), + .compileTarget = argument(obj), + }); + + int spawnError = 0; + auto run = mcpp::run::capture_exec(argv, {}, {}, &spawnError); + if (spawnError != 0 || run.exit_code != 0 || !std::filesystem::exists(ddi)) { return std::unexpected(std::format( - "p1689 scan failed for '{}':\n{}", source.string(), output)); + "p1689 scan failed for '{}':\n{}", source.string(), run.output)); } std::ifstream is(ddi); diff --git a/src/modgraph/scanner.cppm b/src/modgraph/scanner.cppm index e5566800f..bfaf39284 100644 --- a/src/modgraph/scanner.cppm +++ b/src/modgraph/scanner.cppm @@ -1,15 +1,18 @@ // mcpp.modgraph.scanner — regex-based scan of .cppm/.cpp for module statements. // // Hard constraints (per docs/01 §4.2): -// not supported: #if/#ifdef-guarded import // not supported: header units (import "h" / import ) // not supported: files outside [modules].sources glob +// An import or a module declaration inside a preprocessor condition marks the +// unit, whose declarations and imports are then the compiler's dependency +// scan's (`scan_packages`' `answer`, mcpp#1026). // // Returns a Graph or a list of detailed errors. export module mcpp.modgraph.scanner; import std; +import mcpp.libs.code_text; import mcpp.manifest; import mcpp.modgraph.glob; import mcpp.modgraph.graph; @@ -186,10 +189,19 @@ struct PackageRoot { bool selectedMember = false; std::string memberProducts; }; +// The compiler's answer for a unit the text scanner marked +// (`importsFromCompiler`): the unit with its declaration and imports as the +// compiler's dependency scan reads them under the unit's compile, or why it +// could not be scanned. +using CompilerAnswer = std::function(const SourceUnit&)>; + // `closures` states each compiled package's closure (mcpp#732); a module name -// is then unique per closure, and without them in the whole graph. +// is then unique per closure, and without them in the whole graph. `answer` +// scans the units whose imports stand inside a preprocessor condition; without +// one, such a unit is an error naming it. ScanResult scan_packages(const std::vector& packages, - const Closures& closures = {}); + const Closures& closures = {}, + const CompilerAnswer& answer = {}); // Drop-in replacement that delegates per-file scanning to GCC's P1689r5 // (.ddi) output instead of regex parsing. Same ScanResult shape — used by @@ -197,7 +209,7 @@ ScanResult scan_packages(const std::vector& packages, ScanResult scan_packages_p1689(const std::vector& packages, const mcpp::toolchain::Toolchain& tc, const std::filesystem::path& tmpDir, - std::string_view cppStandardFlag, + std::span stdWords, const Closures& closures = {}); } // namespace mcpp::modgraph @@ -300,119 +312,19 @@ bool is_well_formed_module_name(std::string_view name) { return is_dotted(name.substr(0, colon)) && is_dotted(name.substr(colon + 1)); } -// Blank out everything on a line that is not code: block-comment bodies, line -// comment tails, and raw-string bodies. Removed characters become spaces, so a -// column reported against the result still points at the source. -// -// ONE PASS OVER THREE STATES, and that is the whole point of the function. -// Code, block comment and raw string are mutually exclusive and decided by -// whichever opener comes first, which no fixed order of separate passes can -// express. The scanner had two passes -- raw strings, then an unconditional -// `find("//")` -- and no block-comment state at all, which produced a wrong -// answer in BOTH directions (measured on 2026.9.10.2): -// -// /* the trimmed line IS `module (exe)`, so the matcher -// module (exe) fired inside a comment. With a well-formed name -// */ (`export module y;`) it was worse than an error: -// the graph recorded a plain .cpp as the producer of -// `y.gcm`, promised a BMI the compiler never writes, -// and a real importer of `y` was then told `imports -// must be built before being imported`. -// -// // R"( the raw-string pass ran first and did not know the -// import x; opener was commented out, so it entered raw mode -// and blanked every following line until a `)"` that -// never comes. `import x;` was invisible to the -// scanner and visible to the compiler -- a MISSING -// DEPENDENCY EDGE, which is a build-order race rather -// than a deterministic refusal, and therefore worse. -// -// /* */ import x; the matcher only fires on a line whose trimmed text -// starts with the keyword, and this one starts with -// `/*`. Also missed. -// -// The comment that admitted all of this is worth quoting, because the argument -// was sound and its enumeration was short by one: "Ordinary "..." strings are -// intentionally left as-is: the import/module matcher only fires on lines whose -// trimmed text *starts with* the keyword, which a string body can only do when -// it spans lines (i.e. a raw string)." A block comment can do it too. -// -// NOT A LEXER. Ordinary string and character literals are skipped over rather -// than tokenised -- their contents are left in place, because the only question -// asked of the result is whether the trimmed line starts with a keyword and a -// `"..."` body cannot begin a line with one. Skipping them is nonetheless -// required, so that `const char* s = "a /* b";` does not open a comment that -// swallows the rest of the file. Nesting is not stripped because `/*` does not -// nest in C++. -std::string strip_noncode(std::string_view line, bool& in_block, bool& in_raw, - std::string& raw_close) { - std::string out(line); - const std::size_t n = out.size(); - auto blank = [&](std::size_t from, std::size_t to) { - for (std::size_t k = from; k < to && k < n; ++k) out[k] = ' '; - }; - - std::size_t i = 0; - while (i < n) { - if (in_raw) { - auto p = line.find(raw_close, i); - if (p == std::string_view::npos) { blank(i, n); return out; } - blank(i, p + raw_close.size()); - i = p + raw_close.size(); - in_raw = false; - raw_close.clear(); - continue; - } - if (in_block) { - auto p = line.find("*/", i); - if (p == std::string_view::npos) { blank(i, n); return out; } - blank(i, p + 2); - i = p + 2; - in_block = false; - continue; - } - if (line[i] == '/' && i + 1 < n && line[i + 1] == '/') { - blank(i, n); - return out; - } - if (line[i] == '/' && i + 1 < n && line[i + 1] == '*') { - in_block = true; - blank(i, i + 2); - i += 2; - continue; - } - // Raw-string opener: R"delim( ... )delim" (delim is up to 16 chars, - // no '(' / whitespace per the standard). Optional u8/u/U/L prefixes - // precede the R; we only need to spot the R" boundary. - if (line[i] == 'R' && i + 1 < n && line[i + 1] == '"') { - std::size_t d = i + 2; - std::string delim; - while (d < n && line[d] != '(' && (d - (i + 2)) < 16) { - delim.push_back(line[d]); - ++d; - } - if (d < n && line[d] == '(') { - raw_close = ")" + delim + "\""; - in_raw = true; - blank(i, d + 1); - i = d + 1; - continue; - } - } - if (line[i] == '"' || line[i] == '\'') { - const char q = line[i]; - std::size_t k = i + 1; - while (k < n) { - if (line[k] == '\\') { k += 2; continue; } - if (line[k] == q) { ++k; break; } - ++k; - } - i = k; // contents kept; only the scan position moves past them - continue; - } - ++i; - } - return out; +// What is code in a source is read by one reader, mcpp.libs.code_text: it blanks +// comments and the contents of literals, to the length of the text, so a line +// of its result is the line of the source. The scanner had a reader of its own +// (`strip_noncode`: block comments and raw strings by lines, with the state +// carried from line to line), and before that two passes that gave a wrong +// answer in both directions (measured on 2026.9.10.2): a `module (exe)` line +// inside a block comment was a declaration, and `// R"(` hid every import +// after it, which is a missing edge and a build-order race. Three readers of +// one text differ; the module-name functions of the manifest read the same +// result (mcpp#963). +std::string code_text_of(std::istream& is) { + std::string text{std::istreambuf_iterator(is), std::istreambuf_iterator()}; + return mcpp::libs::code_text::read(text).text; } bool is_module_name_char(char c) { @@ -845,17 +757,12 @@ std::expected scan_file(const std::filesystem::path& file int if_depth = 0; // #if/#ifdef nesting std::size_t lineno = 0; - bool in_raw = false; // inside a multi-line raw string - std::string raw_close; // active )delim" terminator - bool in_block = false; // inside a /* ... */ block comment - std::string line; - while (std::getline(is, line)) { + // Comment bodies and the contents of literals are not code: see + // code_text_of. The lines below are lines of the source. + const std::string code = code_text_of(is); + for (auto const lineRange : std::views::split(std::string_view(code), '\n')) { ++lineno; - // Comment bodies, comment tails and raw-string bodies are not code. - // One pass, because the three states are decided by whichever opener - // comes first -- see strip_noncode. - std::string code = strip_noncode(line, in_block, in_raw, raw_close); - std::string_view sv = trim(code); + std::string_view sv = trim(std::string_view(lineRange)); if (sv.empty()) continue; // Track preprocessor depth (we only need to know if we're inside #if). @@ -889,6 +796,13 @@ std::expected scan_file(const std::filesystem::path& file if (r.empty() || r == ";") { continue; // global module fragment marker (`module;`) } + // A declaration inside a condition is the unit's only under the + // compile that takes the branch: the compiler's scan says which + // (mcpp#1026). + if (if_depth > 0) { + u.importsFromCompiler = true; + continue; + } // `module : private;` — the private module fragment // ([module.private.frag]), and a THIRD production, not a spelling // of the two below. @@ -1016,12 +930,10 @@ std::expected scan_file(const std::filesystem::path& file (r.size() == 6 || r[6] == ' ' || r[6] == '\t' || r[6] == '<' || r[6] == '"' || r[6] == ':')) { - if (if_depth > 0) { - return std::unexpected(ScanError{file, lineno, - "import statement inside conditional preprocessor block (forbidden in M1)"}); - } r = trim(r.substr(6)); if (r.empty()) continue; + // A HEADER UNIT is refused wherever it stands, a condition or not: + // mcpp builds no header unit (SPEC-008). if (r[0] == '<' || r[0] == '"') { return std::unexpected(ScanError{file, lineno, "header units (import \"h\" / import ) are forbidden in M1"}); @@ -1033,6 +945,17 @@ std::expected scan_file(const std::filesystem::path& file ++i; } if (name.empty()) continue; + // AN IMPORT INSIDE A PREPROCESSOR CONDITION (mcpp#1026) is the + // unit's under the compile that takes the branch, and which branch + // that is depends on the toolchain's predefined macros, the target, + // the defines and the headers the unit includes. The compiler's + // dependency scan answers it with the unit's compile; this reader + // would be a third, partial preprocessor. The unit is marked, and + // its imports are the scan's. + if (if_depth > 0) { + u.importsFromCompiler = true; + continue; + } // Partition import within the same module: prepend the *base* // module name. If the current TU itself owns a partition (e.g. // its `export module foo:http;`), `u.provides->logicalName` @@ -1058,7 +981,11 @@ SourceUnit scan_entry_file(const std::filesystem::path& file, const std::string& packageName, const mcpp::ExtensionTable& extTable) { - if (auto scanned = scan_file(file, packageName, extTable)) return std::move(*scanned); + // A unit whose imports are the compiler's to answer (mcpp#1026) has only a + // partial reading here, as a refused one has none: both keep their + // line-leading imports, and their form is not decided. + if (auto scanned = scan_file(file, packageName, extTable); scanned && !scanned->importsFromCompiler) + return std::move(*scanned); SourceUnit u; u.path = file; @@ -1066,11 +993,9 @@ SourceUnit scan_entry_file(const std::filesystem::path& file, u.kind = mcpp::classify(file, extTable); u.declaration = ModuleDeclaration::Unknown; std::ifstream is(file); - bool in_raw = false, in_block = false; - std::string raw_close, line; - while (std::getline(is, line)) { - const std::string code = strip_noncode(line, in_block, in_raw, raw_close); - std::string_view r = trim(code); + const std::string code = code_text_of(is); + for (auto const lineRange : std::views::split(std::string_view(code), '\n')) { + std::string_view r = trim(std::string_view(lineRange)); if (r.starts_with("export ") || r.starts_with("export\t")) r = trim(r.substr(6)); if (!r.starts_with("import ") && !r.starts_with("import\t")) continue; r = trim(r.substr(6)); @@ -1576,6 +1501,36 @@ void resolve_graph(ScanResult& result) { } // namespace +// The units the text scanner marked, given the compiler's declaration and +// imports (mcpp#1026). The text scanner's own reading of a marked unit is +// partial by construction, so a unit no answer covers is an error, not that +// reading. +void answer_from_compiler(ScanResult& result, const CompilerAnswer& answer) { + for (auto& u : result.graph.units) { + if (!u.importsFromCompiler) continue; + if (!answer) { + result.errors.push_back(ScanError{u.path, 0, + "an import or a module declaration stands inside a preprocessor condition; the " + "compiler's dependency scan reads it, and this reading of the sources runs none"}); + continue; + } + auto scanned = answer(u); + if (!scanned) { + result.errors.push_back(ScanError{u.path, 0, scanned.error()}); + continue; + } + u.provides = scanned->provides; + u.providesInterface = scanned->providesInterface; + u.declaration = scanned->declaration; + // A partition import is named by its module in a record (`m:part`); + // a re-export the text read stays one only where the scan imports it. + u.requires_ = scanned->requires_; + std::erase_if(u.reexports, [&](const ModuleId& r) { + return std::ranges::none_of(u.requires_, [&](auto const& q) { return q.logicalName == r.logicalName; }); + }); + } +} + ScanResult scan_package(const std::filesystem::path& root, const mcpp::manifest::Manifest& manifest) { @@ -1584,12 +1539,14 @@ ScanResult scan_package(const std::filesystem::path& root, auto localIncludeDirsAfter = local_include_dirs_after_for(root, manifest); scan_one_into(result, root, manifest, localIncludeDirs, localIncludeDirsAfter, manifest.buildConfig.cflags, manifest.buildConfig.cxxflags); + answer_from_compiler(result, {}); resolve_graph(result); return result; } ScanResult scan_packages(const std::vector& packages, - const Closures& closures) { + const Closures& closures, + const CompilerAnswer& answer) { ScanResult result; result.graph.closures = closures; for (auto const& p : packages) { @@ -1621,6 +1578,7 @@ ScanResult scan_packages(const std::vector& packages, localIncludeDirsAfter, packageCflags, packageCxxflags, packageAsmflags); } + answer_from_compiler(result, answer); resolve_graph(result); return result; } @@ -1628,7 +1586,7 @@ ScanResult scan_packages(const std::vector& packages, ScanResult scan_packages_p1689(const std::vector& packages, const mcpp::toolchain::Toolchain& tc, const std::filesystem::path& tmpDir, - std::string_view cppStandardFlag, + std::span stdWords, const Closures& closures) { ScanResult result; @@ -1651,7 +1609,7 @@ ScanResult scan_packages_p1689(const std::vector& packages, for (auto const& f : all_files) { auto r = mcpp::modgraph::p1689::scan_file( f, p.manifest.package.name, tc, tmpDir, - localIncludeDirs, cppStandardFlag, extTable); + localIncludeDirs, stdWords, extTable); if (!r) { result.errors.push_back(ScanError{ f, 0, r.error() }); continue; diff --git a/src/pm/commands.cppm b/src/pm/commands.cppm index 986a8e81a..f0bd18b84 100644 --- a/src/pm/commands.cppm +++ b/src/pm/commands.cppm @@ -329,13 +329,19 @@ inline int cmd_add(const mcpplibs::cmdline::ParsedArgs& parsed) { // `mcpp add` and scaffold injection share one structured, source-preserving // editor. Default identities go under [dependencies]; foreign/nested // identities use [dependencies.] with the short key. - const bool dev = parsed.is_flag_set("dev"); - const std::string table = dev ? "dev-dependencies" : "dependencies"; + if (parsed.is_flag_set("dev") && parsed.is_flag_set("build")) { + mcpp::ui::error("--dev and --build name two tables; give one"); + return 2; + } + const auto tableKind = parsed.is_flag_set("build") ? mcpp::manifest::DependencyTableKind::Build + : parsed.is_flag_set("dev") ? mcpp::manifest::DependencyTableKind::Dev + : mcpp::manifest::DependencyTableKind::Normal; + const std::string table(mcpp::manifest::dependency_table_name(tableKind)); auto edited = mcpp::manifest::upsert_dependency_text(ss.str(), { .namespace_ = ns, .shortName = shortName, .version = version, - .dev = dev, + .table = tableKind, }); if (!edited) { mcpp::ui::error(edited.error()); @@ -420,121 +426,30 @@ inline int cmd_remove(const mcpplibs::cmdline::ParsedArgs& parsed) { name, canonicalSelector)); } - bool changed = false; - // The entry's whole value goes: an inline table written over several - // lines (TOML 1.1) ends where its braces close, not at the first newline. - auto erase_line_at = [&](std::size_t p) { - auto bol = text.rfind('\n', p); - if (bol == std::string::npos) bol = 0; else ++bol; - const auto eol = mcpp::manifest::assignment_end(text, bol); - text.erase(bol, (eol - bol) + (eol < text.size() ? 1 : 0)); - changed = true; - }; - - // Try the flat form first: a bare default key or a retained quoted dotted - // key from an older manifest. Search only the exact [dependencies] body; - // a global line match can otherwise delete a same-name dev/build dep that - // happens to appear earlier in the file. - if (auto headerPos = text.find("[dependencies]"); - headerPos != std::string::npos) { - auto bodyStart = text.find('\n', headerPos); - if (bodyStart == std::string::npos) bodyStart = text.size(); - auto sectionEnd = text.find("\n[", bodyStart); - if (sectionEnd == std::string::npos) sectionEnd = text.size(); - for (const auto& needle : { - std::format("\n{} = ", singleTableKey), - std::format("\n\"{}\" = ", singleTableKey), - }) { - auto p = text.find(needle, bodyStart); - if (p == std::string::npos || p >= sectionEnd) continue; - erase_line_at(p + 1); - break; - } - } - - auto erase_from_subtable = [&](const std::string& tableNs, - const std::string& tableShort) { - auto sectHeader = std::format("[dependencies.{}]", tableNs); - if (auto sp = text.find(sectHeader); sp != std::string::npos) { - auto bodyStart = text.find('\n', sp); - if (bodyStart == std::string::npos) bodyStart = text.size(); - auto sectEnd = text.find("\n[", bodyStart); - if (sectEnd == std::string::npos) sectEnd = text.size(); - std::string section = text.substr(bodyStart, sectEnd - bodyStart); - for (const auto& needle : { - std::format("\n{} = ", tableShort), - std::format("\n\"{}\" = ", tableShort), - }) { - if (auto p = section.find(needle); p != std::string::npos) { - auto absStart = bodyStart + p + 1; - erase_line_at(absStart); - break; - } - } - // If the subtable now contains no `name = ...` lines, drop it. - auto headerPos = text.find(sectHeader); - if (changed && headerPos != std::string::npos) { - auto bodyAfter = text.find('\n', headerPos); - auto endAfter = text.find("\n[", bodyAfter == std::string::npos ? headerPos : bodyAfter); - if (endAfter == std::string::npos) endAfter = text.size(); - std::string body = text.substr(bodyAfter == std::string::npos ? headerPos : bodyAfter, - endAfter - (bodyAfter == std::string::npos ? headerPos : bodyAfter)); - bool hasEntry = false; - std::size_t i = 0; - while (i < body.size()) { - auto j = body.find('\n', i); - auto line = body.substr(i, (j == std::string::npos ? body.size() : j) - i); - auto first = line.find_first_not_of(" \t"); - if (first != std::string::npos - && line[first] != '#' && line[first] != '\n' - && line[first] != '[') { - hasEntry = true; break; - } - if (j == std::string::npos) break; - i = j + 1; - } - if (!hasEntry) { - auto headerLineStart = text.rfind('\n', headerPos); - if (headerLineStart == std::string::npos) headerLineStart = 0; - text.erase(headerLineStart, endAfter - headerLineStart); - } - } - } - }; - - // Try the namespaced subtable form `[dependencies.] = `. - // After deleting the dep line, prune the `[dependencies.]` header - // if no entries remain under it. - if (!isDefaultNs) { - erase_from_subtable(ns, shortName); + // The editor that `mcpp add` writes through, and the table the flags name. + if (parsed.is_flag_set("dev") && parsed.is_flag_set("build")) { + mcpp::ui::error("--dev and --build name two tables; give one"); + return 2; } - - // Legacy: `[dependencies.] ...` — pre-namespace inline-spec subtable - // shape (e.g. when path/git deps were authored as their own subtable). We - // only honour this for the default-ns input form to avoid colliding with - // the new `[dependencies.]` namespacing semantics. - if (!changed && isDefaultNs) { - auto block = std::format("[dependencies.{}]", shortName); - if (auto p = text.find(block); p != std::string::npos) { - auto bol = text.rfind('\n', p); - if (bol == std::string::npos) bol = 0; else ++bol; - auto end = text.find("\n[", p + block.size()); - if (end == std::string::npos) end = text.size(); - else end += 1; - text.erase(bol, end - bol); - changed = true; - } + const auto table = parsed.is_flag_set("build") ? mcpp::manifest::DependencyTableKind::Build + : parsed.is_flag_set("dev") ? mcpp::manifest::DependencyTableKind::Dev + : mcpp::manifest::DependencyTableKind::Normal; + const auto tableName = mcpp::manifest::dependency_table_name(table); + auto removed = mcpp::manifest::remove_dependency_text(text, ns, shortName, table); + if (!removed) { + mcpp::ui::error(removed.error()); + return 2; } - - if (!changed) { + if (!*removed) { mcpp::ui::error(std::format( - "no dependency '{}' in mcpp.toml", canonicalSelector)); + "no dependency '{}' in [{}] of mcpp.toml", canonicalSelector, tableName)); return 1; } + text = std::move(**removed); std::ofstream os(manifestPath); os << text; mcpp::ui::status("Removing", std::format( - "{} from dependencies", canonicalSelector)); + "{} from {}", canonicalSelector, tableName)); // Also clean lockfile entry if present auto lockPath = *root / "mcpp.lock"; if (std::filesystem::exists(lockPath)) { diff --git a/src/project.cppm b/src/project.cppm index a8bccef84..fc217058b 100644 --- a/src/project.cppm +++ b/src/project.cppm @@ -389,6 +389,8 @@ void merge_layer_root_position(mcpp::manifest::Manifest& member, to.cflags.insert(to.cflags.begin(), from.cflags.begin(), from.cflags.end()); to.cxxflags.insert(to.cxxflags.begin(), from.cxxflags.begin(), from.cxxflags.end()); to.ldflags.insert(to.ldflags.begin(), from.ldflags.begin(), from.ldflags.end()); + to.dialectCxxflags.insert(to.dialectCxxflags.begin(), from.dialectCxxflags.begin(), + from.dialectCxxflags.end()); } for (auto const& [triple, from] : layer.targetOverrides) { @@ -1189,6 +1191,7 @@ export std::string root_position_key( list("profile." + name + ".cflags", pr.cflags); list("profile." + name + ".cxxflags", pr.cxxflags); list("profile." + name + ".ldflags", pr.ldflags); + list("profile." + name + ".dialect_cxxflags", pr.dialectCxxflags); } for (auto const& [name, idx] : m.indices) field("index." + name, std::format("{}#{}#{}#{}#{}", idx.url, idx.rev, idx.tag, diff --git a/src/publish/normalize.cppm b/src/publish/normalize.cppm index 0606a776a..3bf0cfeef 100644 --- a/src/publish/normalize.cppm +++ b/src/publish/normalize.cppm @@ -121,13 +121,14 @@ struct Walk { // declares only this dependency, so the key rules (namespace tables, // dotted selectors, quoted legacy keys) are not restated here. std::expected - reader_key(std::string_view section, const std::vector& segs, + reader_key(const mcpp::manifest::DependencyTable& table, const std::vector& segs, const t::Value& leaf) const { + const auto section = table.section(); t::Table root; root["package"] = t::Value{t::Table{ {"name", t::Value{std::string("normalize")}}, {"version", t::Value{std::string("0.0.0")}}}}; - std::set> ex{ "package", std::string(section) }; + std::set> ex{ "package", section }; // Build the pruned subtree from the leaf upward. t::Value node = leaf; for (std::size_t i = segs.size(); i-- > 1;) { @@ -137,7 +138,10 @@ struct Walk { } t::Table sectionTable; sectionTable[segs[0]] = node; - root[std::string(section)] = t::Value{std::move(sectionTable)}; + if (table.kind == mcpp::manifest::DependencyTableKind::Feature) + root["feature-deps"] = t::Value{t::Table{{table.feature, t::Value{std::move(sectionTable)}}}}; + else + root[section] = t::Value{std::move(sectionTable)}; std::string prefix(section); for (std::size_t i = 0; i + 1 < segs.size(); ++i) { prefix += "." + segs[i]; @@ -146,9 +150,7 @@ struct Walk { auto text = t::serialize(t::Document{std::move(root), std::move(ex)}); auto m = mcpp::manifest::parse_string(text, manifestPath); if (!m) return std::unexpected(m.error().format()); - const auto& map = section == "dependencies" ? m->dependencies - : section == "build-dependencies" ? m->buildDependencies - : m->devDependencies; + const auto& map = family(*m, table); if (map.size() != 1) return std::unexpected(std::format( "internal error: the dependency at [{}] {} did not read back as " @@ -156,18 +158,26 @@ struct Walk { return map.begin()->first; } - const std::map& - effective_map(std::string_view section) const { - const auto& m = effective.manifest; - return section == "dependencies" ? m.dependencies - : section == "build-dependencies" ? m.buildDependencies - : m.devDependencies; + // The map of a manifest that a table's entries are read into. + static const std::map& + family(const mcpp::manifest::Manifest& m, const mcpp::manifest::DependencyTable& table) { + using K = mcpp::manifest::DependencyTableKind; + static const std::map none; + if (table.kind == K::Feature) { + auto it = m.featureDeps.find(table.feature); + return it == m.featureDeps.end() ? none : it->second; + } + return table.kind == K::Build ? m.buildDependencies + : table.kind == K::Dev ? m.devDependencies + : m.dependencies; } // Replace `workspace = true` by the source the workspace resolved. std::expected - resolve_workspace(t::Table& spec, std::string_view section, - const std::vector& segs, bool conditional) { + resolve_workspace(t::Table& spec, const mcpp::manifest::DependencyTable& table, + const std::vector& segs) { + const auto section = table.section(); + const bool conditional = !table.selector.empty(); auto it = spec.find("workspace"); if (it == spec.end() || !it->second.is_bool() || !it->second.as_bool()) return {}; @@ -179,9 +189,9 @@ struct Walk { "the member's manifest.", manifestPath.string(), section, join(segs))); if (!effective.member) return {}; - auto key = reader_key(section, segs, t::Value{spec}); + auto key = reader_key(table, segs, t::Value{spec}); if (!key) return std::unexpected(key.error()); - const auto& map = effective_map(section); + const auto& map = family(effective.manifest, table); auto found = map.find(*key); if (found == map.end() || found->second.inheritWorkspace) return std::unexpected(std::format( @@ -206,13 +216,24 @@ struct Walk { // Apply the path rule. Returns true when the entry is to be removed. std::expected - apply_path_rule(t::Table& spec, std::string_view section, - const std::vector& segs, bool dev) { + apply_path_rule(t::Table& spec, const mcpp::manifest::DependencyTable& table, + const std::vector& segs) { + const auto section = table.section(); + const bool dev = table.kind == mcpp::manifest::DependencyTableKind::Dev; auto it = spec.find("path"); if (it == spec.end() || !it->second.is_string()) return false; std::filesystem::path p(it->second.as_string()); auto target = p.is_absolute() ? p : packageDir / p; - if (inside(packageDir, target)) { + // A workspace member is published under its own version wherever its + // directory is, inside this package's included (mcpp#962: package + // `hanim` and its member `hanim.core` at `core/`). Kept as a path, the + // archive named the member by path while every other consumer named it + // by version, and a graph that held both refused the two sources. + const bool member = effective.member && effective.workspace + && target.lexically_normal() != packageDir.lexically_normal() + && mcpp::project::is_workspace_member(*effective.workspace, + effective.workspaceRoot, target); + if (inside(packageDir, target) && !member) { if (p.is_absolute()) { // Only reachable through `workspace = true`: the workspace // anchors the path, and an absolute path cannot be published. @@ -270,25 +291,24 @@ struct Walk { // Walk one dependency table. `segs` is the key path below the section. std::expected - deps(t::Table& table, std::string_view section, std::vector segs, - bool conditional, bool dev) { + deps(t::Table& node, const mcpp::manifest::DependencyTable& table, std::vector segs) { std::vector remove; - for (auto& [k, v] : table) { + for (auto& [k, v] : node) { auto here = segs; here.push_back(k); if (!v.is_table()) continue; // a version string auto& sub = v.as_table(); if (!names_a_source(sub)) { - if (auto r = deps(sub, section, here, conditional, dev); !r) return r; + if (auto r = deps(sub, table, here); !r) return r; continue; } - if (auto r = resolve_workspace(sub, section, here, conditional); !r) + if (auto r = resolve_workspace(sub, table, here); !r) return std::unexpected(r.error()); - auto drop = apply_path_rule(sub, section, here, dev); + auto drop = apply_path_rule(sub, table, here); if (!drop) return std::unexpected(drop.error()); if (*drop) remove.push_back(k); } - for (auto const& k : remove) table.erase(k); + for (auto const& k : remove) node.erase(k); return {}; } }; @@ -493,27 +513,13 @@ normalize_for_publish(const std::filesystem::path& packageDir, } } - // Dependencies: the unconditional sections and every conditional one. + // Dependencies: every table that holds them, conditional ones included, in + // the enumeration the manifest reader walks (mcpp#962: `[feature-deps.*]` + // was not among the tables this walk named). Walk walk{ packageDir, effective, *doc, manifestPath }; - for (auto section : {"dependencies", "build-dependencies", "dev-dependencies"}) { - auto it = root.find(section); - if (it == root.end() || !it->second.is_table()) continue; - if (auto r = walk.deps(it->second.as_table(), section, {}, false, - std::string_view(section) == "dev-dependencies"); !r) + for (auto const& table : mcpp::manifest::dependency_tables(root)) + if (auto r = walk.deps(*table.table, table, {}); !r) return std::unexpected(r.error()); - } - if (auto it = root.find("target"); it != root.end() && it->second.is_table()) { - for (auto& [selector, row] : it->second.as_table()) { - if (!row.is_table()) continue; - for (auto section : {"dependencies", "build-dependencies", "dev-dependencies"}) { - auto st = row.as_table().find(section); - if (st == row.as_table().end() || !st->second.is_table()) continue; - if (auto r = walk.deps(st->second.as_table(), section, {}, true, - std::string_view(section) == "dev-dependencies"); !r) - return std::unexpected(r.error()); - } - } - } changed = changed || walk.changed; out.changed = changed; diff --git a/src/runtime/elf.cppm b/src/runtime/elf.cppm index 3125a88be..a9843c3a4 100644 --- a/src/runtime/elf.cppm +++ b/src/runtime/elf.cppm @@ -68,6 +68,12 @@ struct ElfRuntimeFacts { // link in the farm, found its `libgcc_s.so.1` in the farm by `$ORIGIN`, // while a model that expanded `$ORIGIN` at the link's target refused it. std::filesystem::path origin; + // The image asks for the static TLS block (`DF_STATIC_TLS` in DT_FLAGS): + // its thread-local storage is reached by the initial-exec model, which a + // loader serves for an object loaded after the process started only from + // the block's surplus (mcpp#907). `tlsSize` is its PT_TLS segment's size. + bool staticTls = false; + std::uint64_t tlsSize = 0; // "Is this an executable" is PT_INTERP, not ET_EXEC: a PIE executable is // ET_DYN and therefore indistinguishable from a shared library by type @@ -337,6 +343,9 @@ constexpr std::uint64_t kDtStrsz = 10; constexpr std::uint64_t kDtRpath = 15; constexpr std::uint64_t kDtSoname = 14; constexpr std::uint64_t kDtRunpath = 29; +constexpr std::uint64_t kDtFlags = 30; +constexpr std::uint64_t kDfStaticTls = 0x10; +constexpr std::uint32_t kPtTls = 7; constexpr std::uint64_t kDtVerdef = 0x6ffffffc; constexpr std::uint64_t kDtVerdefnum = 0x6ffffffd; constexpr std::uint64_t kDtVerneed = 0x6ffffffe; @@ -1084,6 +1093,8 @@ inspect_elf_runtime(const std::filesystem::path& artifact) { detail::Segment segment{*ptype, *poff, *pvaddr, *pfilesz}; segments.push_back(segment); if (*ptype == detail::kPtDynamic) dynamic = segment; + if (*ptype == detail::kPtTls) + if (auto memsz = word(off + (wide ? 0x28 : 0x14))) out.tlsSize = *memsz; if (*ptype == detail::kPtInterp) { auto value = reader.cstr(*poff, *pfilesz); if (!value || value->empty()) return std::unexpected(std::format( @@ -1112,6 +1123,7 @@ inspect_elf_runtime(const std::filesystem::path& artifact) { if (candidate == tag) return value; return std::nullopt; }; + if (auto flags = first(detail::kDtFlags)) out.staticTls = (*flags & detail::kDfStaticTls) != 0; auto strtabAddr = first(detail::kDtStrtab); auto strtabSize = first(detail::kDtStrsz); if (!strtabAddr || !strtabSize) return std::unexpected(std::format( diff --git a/src/runtime/launch_env.cpp b/src/runtime/launch_env.cpp index b556f561a..23756fa05 100644 --- a/src/runtime/launch_env.cpp +++ b/src/runtime/launch_env.cpp @@ -63,4 +63,20 @@ std::string prepend_path_list(std::string_view key, std::span statedTools, + const std::filesystem::path& environmentBin) { + std::vector dirs; + for (auto const& d : statedTools) + if (!d.empty() && std::ranges::find(dirs, d) == dirs.end()) dirs.push_back(d); + if (!environmentBin.empty() && std::ranges::find(dirs, environmentBin) == dirs.end()) + dirs.push_back(environmentBin); + if (dirs.empty()) return ""; + std::string value = os::env::join_list(dirs); + if (auto const& inherited = inherited_path(); !inherited.empty()) { + value += path_list_separator(); + value += inherited; + } + return value; +} + } // namespace mcpp::runtime::launch_env diff --git a/src/runtime/launch_env.cppm b/src/runtime/launch_env.cppm index 95554796e..3c4f12065 100644 --- a/src/runtime/launch_env.cppm +++ b/src/runtime/launch_env.cppm @@ -42,4 +42,14 @@ std::string strip_private_glibc(std::string_view paths); std::string prepend_path_list(std::string_view key, std::span dirs); +// THE PATH OF A PROGRAM MCPP STARTS (design 2026-11-27 §4.2, mcpp#926): a build +// program, a test, the program `mcpp run` runs. Three segments, in this order, +// on every host: the directories of the tools the dependency graph states, the +// `bin` of the environment the project states, the PATH this invocation was +// started with. A child that asks for a tool by its bare name gets the one the +// build stated before the one the machine happens to have. "" when the first +// two are empty: the child's PATH is then the one mcpp received. +std::string child_path(std::span statedTools, + const std::filesystem::path& environmentBin); + } // namespace mcpp::runtime::launch_env diff --git a/tests/e2e/667_an_android_pack_stages_its_closure.sh b/tests/e2e/667_an_android_pack_stages_its_closure.sh index 143260bdd..b3efab19a 100755 --- a/tests/e2e/667_an_android_pack_stages_its_closure.sh +++ b/tests/e2e/667_an_android_pack_stages_its_closure.sh @@ -56,28 +56,28 @@ cd app tree=target/dist/app-0.1.0-x86_64-linux-android [ -d "$tree" ] || fail "no staged tree at $tree" dir.log got=$(cd "$tree/lib" && find . -type f | sort | tr '\n' ' ') -[ "$got" = "./libapp.so ./libc++_shared.so ./libfw.so " ] \ +[ "$got" = "./libapp.so ./libc++_shared.so ./libdemo_fw.so " ] \ || fail "lib/ holds '$got', not the object and its two libraries" dir.log manifest="$tree.stage-manifest" [ "$(sed -n '1p' "$manifest")" = "closure = walked" ] \ || fail "the manifest's first line is not 'closure = walked'" "$manifest" -for line in "needs${TAB}libfw.so${TAB}lib/libfw.so" \ +for line in "needs${TAB}libdemo_fw.so${TAB}lib/libdemo_fw.so" \ "needs${TAB}libc++_shared.so${TAB}lib/libc++_shared.so" \ "needs${TAB}libc.so${TAB}platform" \ "needs${TAB}libm.so${TAB}platform" \ "needs${TAB}libdl.so${TAB}platform"; do grep -qxF "$line" "$manifest" || fail "the manifest lacks the line '$line'" "$manifest" done -echo " ok: lib/ carries libfw.so and libc++_shared.so; the stubs are the platform's" +echo " ok: lib/ carries libdemo_fw.so and libc++_shared.so; the stubs are the platform's" -for so in libapp.so libfw.so; do +for so in libapp.so libdemo_fw.so; do soname=$(readelf -d "$tree/lib/$so" | sed -n 's/.*(SONAME).*\[\(.*\)\].*/\1/p') [ "$soname" = "$so" ] || fail "lib/$so carries SONAME '$soname'" dir.log done -readelf -d "$tree/lib/libapp.so" | grep -q 'NEEDED.*\[libfw.so\]' \ - || fail "libapp.so no longer needs libfw.so by its file name" dir.log -echo " ok: libapp.so and libfw.so carry their file names as SONAME" +readelf -d "$tree/lib/libapp.so" | grep -q 'NEEDED.*\[libdemo_fw.so\]' \ + || fail "libapp.so no longer needs libdemo_fw.so by its file name" dir.log +echo " ok: libapp.so and libdemo_fw.so carry their file names as SONAME" # ── 2. a prebuilt library the link named travels, and its absence refuses ── NDKCC=$(ls "$MCPP_HOME"/registry/data/xpkgs/xim-x-android-ndk/*/toolchains/llvm/prebuilt/*/bin/clang 2>/dev/null | head -1) @@ -165,7 +165,7 @@ seen=$(find target -name stage.txt | head -1) || fail "the provider did not receive 'closure = not-walked'" "$seen" grep -qxF "needs${TAB}libext.so${TAB}unresolved" "$seen" \ || fail "the provider did not receive libext.so as unresolved" "$seen" -grep -qxF "needs${TAB}libfw.so${TAB}lib/libfw.so" "$seen" \ +grep -qxF "needs${TAB}libdemo_fw.so${TAB}lib/libdemo_fw.so" "$seen" \ || fail "the provider lost the members that did resolve" "$seen" echo " ok: a dispatched format receives not-walked, the unresolved name and the members" rm -f build.mcpp dist.sh @@ -189,10 +189,10 @@ tree2=$(find target/dist -mindepth 1 -maxdepth 1 -type d | head -1) [ -n "$tree2" ] || fail "no staged tree for two triples" two.log for abi in x86_64 arm64-v8a; do got=$(cd "$tree2/lib/$abi" && find . -type f | sort | tr '\n' ' ') - [ "$got" = "./libapp.so ./libc++_shared.so ./libfw.so " ] \ + [ "$got" = "./libapp.so ./libc++_shared.so ./libdemo_fw.so " ] \ || fail "lib/$abi holds '$got'" two.log - grep -qxF "needs${TAB}libfw.so${TAB}lib/$abi/libfw.so" "$tree2.stage-manifest" \ - || fail "the manifest lacks lib/$abi/libfw.so" "$tree2.stage-manifest" + grep -qxF "needs${TAB}libdemo_fw.so${TAB}lib/$abi/libdemo_fw.so" "$tree2.stage-manifest" \ + || fail "the manifest lacks lib/$abi/libdemo_fw.so" "$tree2.stage-manifest" done file "$tree2/lib/arm64-v8a/libc++_shared.so" | grep -qi "aarch64" \ || fail "lib/arm64-v8a/libc++_shared.so is not the aarch64 runtime" two.log diff --git a/tests/e2e/android/rows.cpp b/tests/e2e/android/rows.cpp index 1ae012170..542155a50 100644 --- a/tests/e2e/android/rows.cpp +++ b/tests/e2e/android/rows.cpp @@ -316,7 +316,7 @@ int main() { }; "667 an android pack stages its closure"_test[s::elf][s::gcc][s::android_ndk] = [] { - // An app with a shared path dependency: lib/ holds the object, libfw.so and + // An app with a shared path dependency: lib/ holds the object, libdemo_fw.so and // libc++_shared.so, the stubs are the platform's (the stage manifest says so); the // libraries carry their file names as SONAME; a prebuilt library from [runtime] is // staged. A library the link read and that is gone is an input of the link that is gone @@ -334,16 +334,16 @@ int main() { expect(fatal(e2e::succeeded(r))) << "mcpp pack --pkg-format dir failed: " << s::text(r); const auto tree = app.at("target/dist/app-0.1.0-x86_64-linux-android"); expect(fatal(fs::is_directory(tree))) << "no staged tree at " << tree.string(); - const std::vector three{"libapp.so", "libc++_shared.so", "libfw.so"}; + const std::vector three{"libapp.so", "libc++_shared.so", "libdemo_fw.so"}; expect(fatal(files_in(tree / "lib") == three)) << "lib/ does not hold the object and its two libraries" << files_in(tree / "lib"); const auto stage_manifest = fs::path(tree.string() + ".stage-manifest"); auto m = s::read_file(stage_manifest); expect(fatal(first_line(m) == "closure = walked")) << "the manifest's first line is not 'closure = walked': " << m; - for (std::string_view line : {"needs\tlibfw.so\tlib/libfw.so", "needs\tlibc++_shared.so\tlib/libc++_shared.so", "needs\tlibc.so\tplatform", "needs\tlibm.so\tplatform", "needs\tlibdl.so\tplatform"}) + for (std::string_view line : {"needs\tlibdemo_fw.so\tlib/libdemo_fw.so", "needs\tlibc++_shared.so\tlib/libc++_shared.so", "needs\tlibc.so\tplatform", "needs\tlibm.so\tplatform", "needs\tlibdl.so\tplatform"}) expect(fatal(lines_contain(m, line))) << "the manifest lacks the line '" << line << "': " << m; - for (std::string_view so : {"libapp.so", "libfw.so"}) + for (std::string_view so : {"libapp.so", "libdemo_fw.so"}) expect(fatal(s::read_header(tree / "lib" / std::string(so)).soname == so)) << "lib/" << so << " carries SONAME '" << s::read_header(tree / "lib" / std::string(so)).soname << "'"; - expect(fatal(std::ranges::contains(s::read_header(tree / "lib/libapp.so").needed, std::string("libfw.so")))) << "libapp.so no longer needs libfw.so by its file name"; + expect(fatal(std::ranges::contains(s::read_header(tree / "lib/libapp.so").needed, std::string("libdemo_fw.so")))) << "libapp.so no longer needs libdemo_fw.so by its file name"; // A prebuilt library from [runtime] link_library_dirs. const auto cc = ndk_tool("clang"); app.write("ext/ext.c", "int ext_value(void) { return 1; }\n"); @@ -404,7 +404,7 @@ int main() { m = s::read_file(*seen); expect(fatal(first_line(m) == "closure = not-walked")) << "the provider did not receive 'closure = not-walked': " << m; expect(fatal(lines_contain(m, "needs\tlibext.so\tunresolved"))) << "the provider did not receive libext.so as unresolved: " << m; - expect(fatal(lines_contain(m, "needs\tlibfw.so\tlib/libfw.so"))) << "the provider lost the members that did resolve: " << m; + expect(fatal(lines_contain(m, "needs\tlibdemo_fw.so\tlib/libdemo_fw.so"))) << "the provider lost the members that did resolve: " << m; // Two triples: a closure each. app.remove("build.mcpp"); app.remove("dist.sh"); @@ -416,7 +416,7 @@ int main() { const auto tree2 = staged(app, ""); for (std::string_view abi : {"x86_64", "arm64-v8a"}) { expect(fatal(files_in(tree2 / "lib" / std::string(abi)) == three)) << "lib/" << abi << " does not hold the closure" << files_in(tree2 / "lib" / std::string(abi)); - expect(fatal(lines_contain(s::read_file(fs::path(tree2.string() + ".stage-manifest")), std::format("needs\tlibfw.so\tlib/{}/libfw.so", abi)))) << "the manifest lacks lib/" << abi << "/libfw.so"; + expect(fatal(lines_contain(s::read_file(fs::path(tree2.string() + ".stage-manifest")), std::format("needs\tlibdemo_fw.so\tlib/{}/libdemo_fw.so", abi)))) << "the manifest lacks lib/" << abi << "/libdemo_fw.so"; } expect(fatal(s::read_header(tree2 / "lib/arm64-v8a/libc++_shared.so").machine == s::elf_machine::aarch64)) << "lib/arm64-v8a/libc++_shared.so is not the aarch64 run-time"; }; diff --git a/tests/e2e/build/basics.cpp b/tests/e2e/build/basics.cpp index 0070270a6..3252e815a 100644 --- a/tests/e2e/build/basics.cpp +++ b/tests/e2e/build/basics.cpp @@ -56,6 +56,12 @@ void fragment_tip(const std::vector& toolchain, std::string_view ch 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); } + // The check is one invocation: the build after it, with no edit, is the one before it, + // whether the check built or failed. (A graph written by a build that failed was replayed + // under the record of the build before it, and failed the same way.) + r = p.mcpp(args({"build", "--verbose"})); + expect(fatal(e2e::succeeded(r))) << "D: the build after the check is not the one before it: " << s::text(r); + expect(e2e::contains(s::text(r), "c.private")) << "D: the build after the check left the source as the check built it: " << 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; }")); diff --git a/tests/e2e/cache/entries.cpp b/tests/e2e/cache/entries.cpp index b72a91721..4c9f70835 100644 --- a/tests/e2e/cache/entries.cpp +++ b/tests/e2e/cache/entries.cpp @@ -605,4 +605,42 @@ E2E entries{"entries", s::home_fixture, [] { expect(fatal(e2e::succeeded(r))) << s::text(r); expect(fatal(!fs::exists(old) && !fs::exists(fresh) && !fs::exists(legacy))) << "clean --all left a work directory\n" << s::text(r); }; + + "1171 an entry two trees use is kept for one when the other is edited"_test[s::gcc] = [] { + // mcpp#1025 item 1 (docs/09): two checkouts of one library share its entry; an edit in one + // writes a new entry and withdraws that checkout from the old one, which the other still + // uses and builds from; once both are edited, the old entry has no user and is removed. + const auto root = s::case_dir(); + // A package of this run's own name: the shared home keeps the entries of earlier runs. + const auto package = std::format("share1171x{:08x}", std::random_device{}()); + auto library = [&](std::string_view tree, int answer) { + s::project(root / tree, {{"mcpp.toml", std::format("[package]\nname = \"{0}\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cppm\"]\n\n[targets.{0}]\nkind = \"lib\"\n", package)}, + {"src/share1171.cppm", std::format("export module share1171;\nexport int answer() {{ return {}; }}\n", answer)}}); + }; + auto app = [&](std::string_view name, std::string_view tree) { + return s::project(root / name, {{"mcpp.toml", std::format("[package]\nname = \"{0}\"\nversion = \"0.1.0\"\n\n[dependencies]\n{2} = {{ path = \"../{1}\" }}\n\n" + "[targets.{0}]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n", name, tree, package)}, + {"src/main.cpp", "import share1171;\nint main() { return answer() > 0 ? 0 : 1; }\n"}}); + }; + library("one", 1); + library("two", 1); + auto a = app("appone", "one"); + auto b = app("apptwo", "two"); + auto dir = s::text(a.mcpp({"cache", "dir"})); + while (!dir.empty() && (dir.back() == '\n' || dir.back() == '\r')) dir.pop_back(); + const fs::path cache{dir}; + auto entries = [&] { return s::glob(cache, std::format("pkg/*/{}@0.1.0+path.*/*/entry.json", package)).size(); }; + expect(fatal(e2e::succeeded(a.mcpp({"build"})))) << "appone: build failed"; + expect(fatal(e2e::succeeded(b.mcpp({"build"})))) << "apptwo: build failed"; + expect(fatal(eq(entries(), std::size_t{1}))) << "two trees of one content did not share one entry under " << cache; + library("one", 2); + expect(fatal(e2e::succeeded(a.mcpp({"build"})))) << "appone: the build after the edit failed"; + expect(fatal(eq(entries(), std::size_t{2}))) << "the entry the other tree uses was removed by an edit of this one"; + b.remove("target"); + auto r = b.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "apptwo: a clean build from the kept entry failed\n" << s::text(r); + library("two", 2); + expect(fatal(e2e::succeeded(b.mcpp({"build"})))) << "apptwo: the build after the edit failed"; + expect(fatal(eq(entries(), std::size_t{1}))) << "the entry no tree uses was kept"; + }; }}; diff --git a/tests/e2e/cache/invariants.cpp b/tests/e2e/cache/invariants.cpp index 400dc02e3..79a370fc8 100644 --- a/tests/e2e/cache/invariants.cpp +++ b/tests/e2e/cache/invariants.cpp @@ -69,6 +69,33 @@ E2E invariants{"invariants", s::home_fixture, [] { metric("edges.compiled", static_cast(rebuilt.compiled), "edges"); }; + "1176 a build with no edit after an edit of a module compiles nothing"_test[at_most{"edges.compiled", 0}] = [] { + // mcpp#1015: `c` is one file, imported by `b`, imported by `main`. A build after an edit of + // `c`'s body compiles what the edit reaches, and the next build, which has no edit, + // compiles nothing. Under clang the importer of the importer was compiled one build late: + // its depfile names `c`'s BMI by the absolute path clang finds it through, which ninja held + // as another file than the graph's `pcm.cache/c.pcm`. The host's default toolchain: clang + // on macOS and Windows, where the defect was. + s::own_home(); + s::project p({{"mcpp.toml", "[package]\nname = \"cascade\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cppm\", \"src/*.cpp\"]\n\n" + "[targets.cascade]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n"}, + {"src/c.cppm", "export module c;\nexport int cv() { return 1; }\n"}, + {"src/b.cppm", "export module b;\nimport c;\nexport int bv() { return cv() + 1; }\n"}, + {"src/main.cpp", "import b;\nint main() { return bv() > 0 ? 0 : 1; }\n"}}); + auto [cold, built] = recorded(p, {"build"}, "cold"); + expect(fatal(e2e::succeeded(cold))) << s::text(cold); + p.write("src/c.cppm", "export module c;\nexport int cv() { return 3; }\n"); + auto [edit, edited] = recorded(p, {"build"}, "edit"); + expect(fatal(e2e::succeeded(edit))) << s::text(edit); + expect(fatal(gt(edited.compiled, std::size_t{0}))) << "the edit compiled nothing"; + auto [again, rebuilt] = recorded(p, {"build"}, "again"); + expect(fatal(e2e::succeeded(again))) << s::text(again); + std::string compiled; + for (auto const& o : rebuilt.compiledOutputs) compiled += "\n " + o; + expect(eq(rebuilt.compiled, std::size_t{0})) << "a build with no edit compiled:" << compiled; + metric("edges.compiled", static_cast(rebuilt.compiled), "edges"); + }; + "1122 a dev-dependency is served from the cache to a second project"_test[s::gcc][at_most{"edges.compiled.dependency", 1}] = [] { // 5.4: mcpplibs.mtest, a dev-dependency of every test, is compiled once per home, not once // per project. Its entry unit (`main`) is the one compile left: a package's entry unit is diff --git a/tests/e2e/cli/commands.cpp b/tests/e2e/cli/commands.cpp index d1eb36086..7e1789256 100644 --- a/tests/e2e/cli/commands.cpp +++ b/tests/e2e/cli/commands.cpp @@ -69,8 +69,9 @@ E2E commands{"commands", s::home_fixture, [] { }; "05 errors"_test = [] { - // No manifest, a missing version, a conditional import and a header unit are refused, - // each naming its cause; a module named outside the package's prefix builds. + // No manifest, a missing version and a header unit are refused, each naming its cause; a + // conditional import follows its condition (mcpp#1026); a module named outside the + // package's prefix builds. // A directory with no manifest above it either: the case's own directory lies inside the // repository, whose mcpp.toml mcpp would find. const auto empty = s::case_home() / "empty"; @@ -92,11 +93,10 @@ main = "src/main.cpp" expect(fatal(failed(r))) << "expected failure"; expect(fatal(e2e::contains(s::text(r), "package.version"))) << "wrong error: " << s::text(r); - auto cond = s::project::scaffold("bad-cond"); + auto cond = s::project::scaffold("cond-import"); cond.write("src/main.cpp", "import std;\n#ifdef WANT_FOO\nimport foo;\n#endif\nint main() {}\n"); r = cond.mcpp({"build"}); - expect(fatal(failed(r))) << "expected failure"; - expect(fatal(e2e::contains(s::text(r), "conditional preprocessor"))) << "wrong error: " << s::text(r); + expect(fatal(e2e::succeeded(r))) << "an import whose condition does not hold failed the build: " << s::text(r); auto header = s::project::scaffold("bad-header"); header.write("src/main.cpp", "import std;\nimport \"header.h\";\nint main() {}\n"); diff --git a/tests/e2e/cli/surface.cpp b/tests/e2e/cli/surface.cpp index c2cc98f00..1fa6bc3ef 100644 --- a/tests/e2e/cli/surface.cpp +++ b/tests/e2e/cli/surface.cpp @@ -12,6 +12,11 @@ namespace fs = std::filesystem; namespace { +void write(const fs::path& file, std::string_view content) { + fs::create_directories(file.parent_path()); + std::ofstream(file, std::ios::binary) << content; +} + E2E surface{"surface", s::home_fixture, [] { "1125 the maintenance commands answer"_test = [] { s::own_home(); @@ -185,6 +190,57 @@ archives = ["{}"] expect(fatal(e2e::succeeded(r))) << s::text(r); expect(e2e::contains(r.out, "name = \"a\"") && s::lacks(r.out, "name = \"b\"")) << "the excluded member was published\n" << r.out; }; + + "1175 completion answers from the command tree and makes no home"_test = [] { + // mcpp#794 (docs/01): `mcpp __complete` answers from the command tree and from what is on + // disk, and a home that does not exist is not made by it; `mcpp self completion` writes the + // adapter into the home, or prints it. + const auto dir = s::case_dir(); + const auto absent = dir / "no-home"; + const s::options nohome{.where = s::home::fresh, .env = {{"MCPP_HOME", absent.string()}}}; + auto r = s::mcpp({"__complete", "self", "comp"}, dir, nohome); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(s::has_line(r.out, "^completion\t")) << "the subcommand was not offered\n" << r.out; + expect(s::has_line(r.out, "^:0$")) << "the answer has no directive line\n" << r.out; + r = s::mcpp({"__complete", "build", "--profile", ""}, dir, nohome); + expect(e2e::contains(r.out, "release")) << "the profiles were not offered\n" << r.out; + r = s::mcpp({"__complete", "bmi"}, dir, nohome); + expect(s::lacks(r.out, "bmi-compile")) << "a hidden command was offered\n" << r.out; + r = s::mcpp({"__complete", "build", "--toolchain", ""}, dir, nohome); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(!fs::exists(absent)) << "a completion made a home"; + + // The installed toolchains and the index copies' packages, where the home's configuration + // places them: a store entry a request may name, and none it may not; a package named as a + // dependency key spells it, the default namespace's qualified once the word names it. + const auto home = s::another_home(s::home::fresh); + const s::options own{.where = s::home::fresh, .env = {{"MCPP_HOME", home.string()}}}; + fs::create_directories(home / "registry" / "data" / "xpkgs" / "xim-x-gcc" / "16.1.0"); + fs::create_directories(home / "registry" / "data" / "xpkgs" / "xim-x-ninja" / "1.12.1"); + write(home / "indices" / "mcpplibs" / "pkgs" / "w" / "widget.lua", + "package = {\n spec = \"1\",\n name = \"widget\",\n}\n"); + write(home / "indices" / "mcpplibs" / "pkgs" / "d" / "demo.lua", + "package = {\n spec = \"1\",\n namespace = \"acme\",\n name = \"demo\",\n}\n"); + r = s::mcpp({"__complete", "build", "--toolchain", ""}, dir, own); + expect(s::has_line(r.out, "^gcc@16\\.1\\.0$")) << "the installed toolchain was not offered\n" << r.out; + expect(s::lacks(r.out, "ninja@")) << "a store entry no request names was offered\n" << r.out; + r = s::mcpp({"__complete", "add", ""}, dir, own); + expect(s::has_line(r.out, "^widget$") && s::has_line(r.out, "^acme\\.demo$")) + << "the index copy's packages were not offered as keys spell them\n" << r.out; + r = s::mcpp({"__complete", "add", "mcpplibs."}, dir, own); + expect(s::has_line(r.out, "^mcpplibs\\.widget$")) << "the qualified spelling was not offered\n" << r.out; + expect(!fs::exists(home / "config.toml")) << "a completion wrote the home's configuration"; + s::own_home(); + r = s::mcpp({"self", "completion", "bash", "--print"}, dir); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(e2e::contains(r.out, "__complete")) << "the adapter does not ask the program\n" << r.out; + r = s::mcpp({"self", "completion", "fish"}, dir); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(e2e::contains(s::text(r), "config/shell/mcpp.fish")) << "the adapter's file is not named\n" << s::text(r); + r = s::mcpp({"self", "completion", "tcsh"}, dir); + expect(!e2e::succeeded(r)) << "an unknown shell was accepted"; + expect(e2e::contains(s::text(r), "takes one of bash, zsh, fish, powershell")) << s::text(r); + }; }}; } // namespace diff --git a/tests/e2e/cli/templates.cpp b/tests/e2e/cli/templates.cpp index fa72a8273..7a4d8141f 100644 --- a/tests/e2e/cli/templates.cpp +++ b/tests/e2e/cli/templates.cpp @@ -226,7 +226,7 @@ self = {{ features = ["alpha", "beta"] }} expect(fatal(e2e::succeeded(r))) << "exact acme template failed\n" << out; const auto acme = in("app-acme/mcpp.toml"); expect(fatal(e2e::contains(acme, "fixture-marker=acme-solo"))) << "default sibling stole acme selector\n" << acme; - expect(fatal(s::has_line(acme, R"(^\[dependencies\.acme\]$)") && s::has_line(acme, R"(^tpl-demo = "3\.0\.0"$)"))) << "canonical self dependency lost namespace\n" << acme; + expect(fatal(s::has_line(acme, R"(^acme\.tpl-demo = "3\.0\.0"$)"))) << "canonical self dependency lost namespace\n" << acme; expect(fatal(e2e::contains(out, "namespace=acme name=tpl-demo"))) << "resolved output lost PackageId\n" << out; expect(fatal(e2e::contains(out, "payload=digest-tpl-demo"))) << "resolved output lost payload provenance\n" << out; expect(fatal(e2e::contains(out, "acme.tpl-demo@3.0.0:solo"))) << "sole template did not become default\n" << out; @@ -237,7 +237,8 @@ self = {{ features = ["alpha", "beta"] }} expect(fatal(e2e::succeeded(r))) << "nested namespace template failed\n" << out; const auto lua = in("app-lua/mcpp.toml"); expect(fatal(e2e::contains(lua, "fixture-marker=nested-lua"))) << "nested template payload missing\n" << lua; - expect(fatal(s::has_line(lua, R"(^\[dependencies\.mcpplibs\.capi\]$)") && s::has_line(lua, R"(^lua = "5\.4\.7"$)"))) << "nested PackageId lost during injection\n" << lua; + // Written as `mcpp add` writes a key (mcpp#964): dotted, in a table that has no namespace section. + expect(fatal(s::has_line(lua, R"(^mcpplibs\.capi\.lua = "5\.4\.7"$)"))) << "nested PackageId lost during injection\n" << lua; expect(fatal(e2e::contains(out, "namespace=mcpplibs.capi name=lua"))) << "nested resolved identity missing\n" << out; // 10. Ambiguous, explicit, several defaults, no templates. @@ -372,7 +373,7 @@ tx-template = "1.0.0" expect(fatal(e2e::contains(m, "provider=acme/tx-template"))) << "provider PackageId was lost"; expect(fatal(e2e::contains(m, "selector=acme.tx-template version=2.0.0"))) << "resolved selector/version were lost"; expect(fatal(e2e::contains(m, "template=starter"))) << "implicit single-template selection was not rendered"; - expect(fatal(s::has_line(m, R"(^\[dependencies\.acme\]$)") && s::has_line(m, R"(^tx-template = \{ version = "2\.0\.0", features = \["gui"\] \}$)"))) << "exact self dependency missing\n" << m; + expect(fatal(s::has_line(m, R"(^acme\.tx-template = \{ version = "2\.0\.0", features = \["gui"\] \}$)"))) << "exact self dependency missing\n" << m; expect(fatal(s::has_line(m, R"(^tx-template = "1\.0\.0"$)"))) << "same-short compat dependency was overwritten"; no_stage(work); diff --git a/tests/e2e/deps/path.cpp b/tests/e2e/deps/path.cpp index d2ad536fd..6823dcce4 100644 --- a/tests/e2e/deps/path.cpp +++ b/tests/e2e/deps/path.cpp @@ -69,7 +69,8 @@ E2E path{"path", s::home_fixture, [] { "12 add command"_test = [] { // `mcpp add` writes [dependencies]: default-namespace packages as bare keys, `ns.name` as a - // subtable, `ns:name` only as a deprecated alias; a package no readable index serves is + // dotted key unless the table already has a `[dependencies.]` section (2026.11.27.1, + // #964), `ns:name` only as a deprecated alias; a package no readable index serves is // refused before mcpp.toml is touched (#305), where absence is provable; `mcpp remove` // stays within [dependencies]. auto app = s::project::scaffold("myapp"); @@ -90,9 +91,9 @@ E2E path{"path", s::home_fixture, [] { expect(eq(s::count_matching(manifest(), R"(^\[dependencies\]$)"), std::size_t{1})) << "[dependencies] header duplicated"; expect(s::has_line(manifest(), R"(^gadget = "0\.2\.0"$)")) << "gadget not set"; app.mcpp({"add", "acme.util@2.0.0"}); - expect(s::has_line(manifest(), R"(^\[dependencies\.acme\]$)")) << "missing [dependencies.acme] section"; - expect(s::has_line(manifest(), R"(^util = "2\.0\.0"$)")) << "util entry missing"; - expect(s::no_line(manifest(), R"(^acme\.util = )")) << "dotted selector must not be stored as an ambiguous flat key"; + expect(s::has_line(manifest(), R"(^acme\.util = "2\.0\.0"$)")) << "util entry missing"; + expect(s::no_line(manifest(), R"(^\[dependencies\.acme\]$)")) << "a section was opened where no section existed"; + expect(s::no_line(manifest(), R"(^"acme\.util")")) << "the dotted key must not be quoted"; const auto alias = s::text(app.mcpp({"add", "acme:util@2.0.0"})); expect(e2e::contains(alias, "deprecated")) << "missing migration warning"; expect(e2e::contains(alias, "acme.util@2.0.0")) << "warning lacks canonical replacement"; @@ -101,15 +102,26 @@ E2E path{"path", s::home_fixture, [] { expect(e2e::contains(exact, "mcpplibs.capi.lua")) << "migration warning lacks old selector"; expect(e2e::contains(exact, "capi.lua")) << "migration warning lacks new selector"; app.mcpp({"add", "capi.lua@5.4.7"}); - expect(s::has_line(manifest(), R"(^\[dependencies\.capi\]$)")) << "missing [dependencies.capi] section"; - expect(s::has_line(manifest(), R"(^lua = "5\.4\.7"$)")) << "exact capi.lua entry missing"; + expect(s::has_line(manifest(), R"(^capi\.lua = "5\.4\.7"$)")) << "exact capi.lua entry missing"; app.mcpp({"add", "mcpplibs.capi.lua@9.9.9"}); - expect(s::has_line(manifest(), R"(^\[dependencies\.mcpplibs\.capi\]$)")) << "nested namespace section missing"; + expect(s::has_line(manifest(), R"(^mcpplibs\.capi\.lua = "9\.9\.9"$)")) << "nested namespace entry missing"; app.mcpp({"remove", "mcpplibs.capi.lua"}); - expect(s::no_line(manifest(), R"(^lua = "9\.9\.9"$)")) << "nested exact remove failed"; + expect(s::no_line(manifest(), R"(^mcpplibs\.capi\.lua = )")) << "nested exact remove failed"; + expect(s::has_line(manifest(), R"(^capi\.lua = "5\.4\.7"$)")) << "the remove took the sibling"; app.write("mcpp.toml", manifest() + "\n[dependencies.legacy]\nold = \"0.1.0\"\n"); app.mcpp({"remove", "legacy.old"}); expect(s::no_line(manifest(), R"(^old = "0\.1\.0"$)")) << "legacy.old was not removed"; + // The table flags (mcpp#993): `--build` and `--dev` name the table each command edits, + // and both at once are refused. + expect(e2e::succeeded(app.mcpp({"add", "--build", "gadget@0.2.0"}))) << "add --build failed"; + expect(s::has_line(manifest(), R"(^\[build-dependencies\]$)")) << "add --build wrote no [build-dependencies]\n" << manifest(); + expect(e2e::succeeded(app.mcpp({"add", "--dev", "gadget@0.2.0"}))) << "add --dev failed"; + expect(s::has_line(manifest(), R"(^\[dev-dependencies\]$)")) << "add --dev wrote no [dev-dependencies]\n" << manifest(); + expect(failed(app.mcpp({"add", "--dev", "--build", "gadget@0.2.0"}))) << "--dev and --build together were accepted"; + expect(eq(s::count_matching(manifest(), R"(^gadget = "0\.2\.0"$)"), std::size_t{3})) << "the three tables do not each hold gadget\n" << manifest(); + expect(e2e::succeeded(app.mcpp({"remove", "--build", "gadget"}))) << "remove --build failed"; + expect(e2e::succeeded(app.mcpp({"remove", "--dev", "gadget"}))) << "remove --dev failed"; + expect(eq(s::count_matching(manifest(), R"(^gadget = "0\.2\.0"$)"), std::size_t{1})) << "remove --build/--dev did not take the entries out of their tables, or took [dependencies]'\n" << manifest(); auto bare = app.mcpp({"add", "bareword"}); expect(failed(bare)) << "expected error for missing version"; expect(e2e::contains(s::text(bare), "version required")) << "wrong error"; @@ -133,7 +145,7 @@ E2E path{"path", s::home_fixture, [] { expect(e2e::contains(s::text(nope), "route: local index 'acme': root present, pkgs present")) << "missing privacy-safe local-index route state"; expect(eq(manifest(), before)) << "mcpp.toml mutated for missing package"; app.mcpp({"add", "unknownidx.thing@1.0.0"}); - expect(s::has_line(manifest(), R"(^\[dependencies\.unknownidx\]$)")) << "unverifiable namespace should still be added"; + expect(s::has_line(manifest(), R"(^unknownidx\.thing = "1\.0\.0"$)")) << "unverifiable namespace should still be added"; auto avail = app.mcpp({"add", "widget@9.9.9"}); expect(e2e::contains(s::text(avail), "available: 0.1.0")) << "expected available-versions warning"; expect(s::has_line(manifest(), R"(^widget = "9\.9\.9"$)")) << "widget@9.9.9 should still be written"; @@ -147,7 +159,7 @@ E2E path{"path", s::home_fixture, [] { expect(fatal(e2e::succeeded(ws.mcpp({"new", "m1"})))); auto added = ws.mcpp_in("m1", {"add", "acme.util@2.0.0"}); expect(e2e::succeeded(added)) << "workspace member could not read its root-owned local index"; - expect(s::has_line(ws.read("m1/mcpp.toml"), R"(^util = "2\.0\.0"$)")) << "member should inherit workspace [indices]"; + expect(s::has_line(ws.read("m1/mcpp.toml"), R"(^acme\.util = "2\.0\.0"$)")) << "member should inherit workspace [indices]"; auto mnope = ws.mcpp_in("m1", {"add", "acme.nope@1.0.0"}); expect(failed(mnope)) << "expected error inside workspace member"; expect(e2e::contains(s::text(mnope), "(acme, nope)")) << "wrong error"; @@ -157,7 +169,7 @@ E2E path{"path", s::home_fixture, [] { upsert.write("mcpp.toml", std::format("[package]\nname = \"upsert\"\nversion = \"0.1.0\"\n\n[indices]\nacme = {{ path = \"{}\" }}\n\n[dependencies]\n\"acme.util\" = \"1.0.0\"\n", app.at("index").generic_string())); upsert.mcpp({"add", "acme.util@2.0.0"}); expect(s::no_line(upsert.read("mcpp.toml"), R"(^"acme\.util" = )")) << "legacy flat selector was duplicated instead of migrated"; - expect(eq(s::count_matching(upsert.read("mcpp.toml"), R"(^util = "2\.0\.0"$)"), std::size_t{1})) << "canonical exact selector was not upserted once"; + expect(eq(s::count_matching(upsert.read("mcpp.toml"), R"(^acme\.util = "2\.0\.0"$)"), std::size_t{1})) << "canonical exact selector was not upserted once"; // remove stays within [dependencies]. upsert.write("mcpp.toml", "[package]\nname = \"remove-scope\"\nversion = \"0.1.0\"\n\n[dev-dependencies]\nwidget = \"0.2.0\"\n\n[dependencies]\nwidget = \"0.1.0\"\n"); upsert.mcpp({"remove", "widget"}); @@ -165,6 +177,38 @@ E2E path{"path", s::home_fixture, [] { expect(s::no_line(upsert.read("mcpp.toml"), R"(^widget = "0\.1\.0"$)")) << "regular dependency was not removed"; }; + "1173 a reopened dependency table is read, reported and repaired"_test[s::python3] = [] { + // mcpp#964 (SPEC-004 §17, docs/05): a `[dependencies.]` header after dotted keys defined + // that table is read with them and reported; the next `mcpp add` to the table writes its + // entries as dotted keys, which a strict TOML reader accepts. + const auto python = s::on_path("python3"); + expect(fatal(python.has_value())) << "no python3 on PATH"; + if (!e2e::succeeded(s::run(*python, {"-c", "import tomllib"}))) + skip("python3 has no tomllib, the strict reader this case compares with"); + const auto root = s::case_dir(); + for (auto name : {"util", "extra"}) + s::project(root / name, {{"mcpp.toml", std::format("[package]\nnamespace = \"acme\"\nname = \"{0}\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cpp\"]\n\n[targets.{0}]\nkind = \"lib\"\n", name)}, + {"src/lib.cpp", std::format("int {}_value() {{ return 1; }}\n", name)}}); + s::project app(root / "app", {{"index/pkgs/a/acme.more.lua", index_package("acme", "more", "a package of the namespace", "1.0.0")}, + {"src/main.cpp", "int main() { return 0; }\n"}, + {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[indices]\nacme = { path = \"index\" }\n\n" + "[targets.app]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n\n[dependencies]\nacme.util = { path = \"../util\" }\n\n" + "[dependencies.acme]\nextra = { path = \"../extra\" }\n"}}); + const auto strict = [&] { return s::run(*python, {"-c", "import sys, tomllib; tomllib.load(open(sys.argv[1], 'rb'))", app.at("mcpp.toml").string()}); }; + expect(fatal(!e2e::succeeded(strict()))) << "the fixture is not the table TOML 1.0 refuses"; + auto r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "the reopened table was not read\n" << s::text(r); + expect(e2e::contains(s::text(r), "reopened-dotted-table") || e2e::contains(s::text(r), "[dependencies.acme]")) << "the reopened table was not reported\n" << s::text(r); + r = app.mcpp({"add", "acme.more@1.0.0"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + const auto repaired = app.read("mcpp.toml"); + expect(s::no_line(repaired, R"(^\[dependencies\.acme\]$)")) << "the reopening header was kept\n" << repaired; + expect(s::has_line(repaired, R"(^acme\.extra = \{ *path = "\.\./extra" *\}$)")) << "the header's entry was not written as a dotted key\n" << repaired; + expect(s::has_line(repaired, R"(^acme\.more = "1\.0\.0"$)")) << "the new entry is missing\n" << repaired; + auto checked = strict(); + expect(e2e::succeeded(checked)) << "a strict TOML reader refuses what mcpp add wrote\n" << s::text(checked) << repaired; + }; + "23 remove update"_test = [] { // `mcpp remove` deletes one entry of [dependencies], one written over several // lines too, and keeps the others, and exits 1 for a name the manifest does not hold; `mcpp update ` drops that entry of mcpp.lock; diff --git a/tests/e2e/deps/resolve.cpp b/tests/e2e/deps/resolve.cpp index dd9dbf985..a907ca132 100644 --- a/tests/e2e/deps/resolve.cpp +++ b/tests/e2e/deps/resolve.cpp @@ -147,10 +147,10 @@ E2E resolve{"resolve", s::home_fixture, [] { "79 gtest regular dep feature main"_test = [] { // #168: compat.gtest as a regular dependency (`mcpp add compat.gtest`) does not inject // gtest_main into an app with its own main; `features = ["main"]` does; `add --dev` - // writes [dev-dependencies.compat]. + // writes [dev-dependencies] (a dotted key since 2026.11.27.1, #964). auto app = s::project::scaffold("app"); app.mcpp({"add", "compat.gtest@1.15.2"}); - expect(fatal(s::has_line(app.read("mcpp.toml"), R"(^\[dependencies\.compat\])"))) << "add did not write [dependencies.compat]"; + expect(fatal(s::has_line(app.read("mcpp.toml"), R"(^compat\.gtest = "1\.15\.2"$)"))) << "add did not write compat.gtest"; expect(fatal(e2e::succeeded(app.mcpp({"build"})))) << "#168 — build with regular-dep gtest failed"; auto newest_graph = [&] { std::optional best; @@ -167,7 +167,8 @@ E2E resolve{"resolve", s::home_fixture, [] { expect(e2e::contains(newest_graph(), "gtest_main")) << "features=[main] did not link gtest_main"; auto lib = s::project::scaffold("libapp"); lib.mcpp({"add", "--dev", "compat.gtest@1.15.2"}); - expect(s::has_line(lib.read("mcpp.toml"), R"(^\[dev-dependencies\.compat\])")) << "add --dev did not write [dev-dependencies.compat]"; + expect(s::has_line(lib.read("mcpp.toml"), R"(^\[dev-dependencies\]$)")) << "add --dev did not write [dev-dependencies]"; + expect(s::has_line(lib.read("mcpp.toml"), R"(^compat\.gtest = "1\.15\.2"$)")) << "add --dev did not write compat.gtest"; }; }}; diff --git a/tests/e2e/features/activation.cpp b/tests/e2e/features/activation.cpp index 7aa43f03c..4f5a159b6 100644 --- a/tests/e2e/features/activation.cpp +++ b/tests/e2e/features/activation.cpp @@ -204,7 +204,7 @@ int dep_value(void); int main(void) { printf("%d\n", dep_value()); return 0; } )cpp"}}}; expect(fatal(e2e::succeeded(app.mcpp({"build"})))) << "the feature-off build failed"; - expect(fatal(s::find_files(app.at("target"), R"(libdepshared\.so)").empty())) << "a feature-gated dependency target was built with the feature off"; + expect(fatal(s::find_files(app.at("target"), R"(libdep_depshared\.so)").empty())) << "a feature-gated dependency target was built with the feature off"; const auto bin = s::find_file(app.at("target"), "app"); expect(fatal(bin.has_value())) << "no executable"; expect(fatal(s::has_line(s::run(*bin).out, "^5$"))) << "the gated-off build does not run"; @@ -220,7 +220,8 @@ main = "src/main.c" dep = { path = "../dep", features = ["plugin"] } )cpp"); expect(fatal(e2e::succeeded(app.mcpp({"build"})))) << "the feature-on build failed"; - expect(s::find_file(app.at("target"), "libdepshared.so").has_value()) << "requesting the feature did not build the gated target"; + // A target named otherwise than its package is named after the package (mcpp#975). + expect(s::find_file(app.at("target"), "libdep_depshared.so").has_value()) << "requesting the feature did not build the gated target"; }; "601 exclusive capability"_test = [] { diff --git a/tests/e2e/features/conditional.cpp b/tests/e2e/features/conditional.cpp index 9a7eb71d5..2561f640d 100644 --- a/tests/e2e/features/conditional.cpp +++ b/tests/e2e/features/conditional.cpp @@ -354,16 +354,16 @@ kind = "lib" }; auto matching = make_app("matching", "[dependencies]\ndemo.fw = { path = \"../fw\" }\n[target.'cfg(os = \"linux\")'.dependencies]\ndemo.fw = { path = \"../fw\", linkage = \"shared\" }\n"); expect(fatal(e2e::succeeded(matching.mcpp({"build"})))) << "A: build failed"; - expect(fatal(s::find_file(matching.at("target"), "libfw.so").has_value())) << "A: the conditional linkage did not produce libfw.so"; + expect(fatal(s::find_file(matching.at("target"), "libdemo_fw.so").has_value())) << "A: the conditional linkage did not produce libdemo_fw.so"; const auto exe = s::find_file(matching.at("target"), "matching"); expect(fatal(exe.has_value())) << "A: no program"; bool needs = false; - for (const auto& n : s::read_header(*exe).needed) needs = needs || n.find("libfw.so") != std::string::npos; - expect(fatal(needs)) << "A: the program does not NEED libfw.so"; + for (const auto& n : s::read_header(*exe).needed) needs = needs || n.find("libdemo_fw.so") != std::string::npos; + expect(fatal(needs)) << "A: the program does not NEED libdemo_fw.so"; expect(fatal(eq(table_of(matching, "demo.fw@0.1.0"), std::string{"[target.'cfg(os = \"linux\")'.dependencies]"}))) << "A: graph table"; auto other = make_app("other", "[dependencies]\ndemo.fw = { path = \"../fw\" }\n[target.'cfg(os = \"windows\")'.dependencies]\ndemo.fw = { path = \"../fw\", linkage = \"shared\" }\n"); expect(fatal(e2e::succeeded(other.mcpp({"build"})))) << "B: build failed"; - expect(fatal(!s::find_file(other.at("target"), "libfw.so").has_value())) << "B: a non-matching selector produced libfw.so"; + expect(fatal(!s::find_file(other.at("target"), "libdemo_fw.so").has_value())) << "B: a non-matching selector produced libdemo_fw.so"; expect(fatal(eq(table_of(other, "demo.fw@0.1.0"), std::string{"[dependencies]"}))) << "B: graph table"; auto modifier = make_app("modifier", "[dependencies]\ndemo.fw = { path = \"../fw\" }\n[target.'cfg(os = \"linux\")'.dependencies]\ndemo.fw = { linkage = \"shared\" }\n"); auto c = modifier.mcpp({"build"}); diff --git a/tests/e2e/golden/surface.txt b/tests/e2e/golden/surface.txt index e612cc1e3..6bcfe5068 100644 --- a/tests/e2e/golden/surface.txt +++ b/tests/e2e/golden/surface.txt @@ -1,7 +1,4 @@ command add -command bmi-await -command bmi-compile -command bmi-supervise command build command cache command cache clean @@ -40,6 +37,7 @@ command resolve command run command search command self +command self completion command self config command self doctor command self env @@ -71,25 +69,8 @@ flag --protocol-version flag --quiet flag --system flag --verbose +flag add --build flag add --dev -flag bmi-await --object -flag bmi-await --slot -flag bmi-compile --bmi -flag bmi-compile --cap -flag bmi-compile --command-file -flag bmi-compile --dep-from -flag bmi-compile --dep-to -flag bmi-compile --object -flag bmi-compile --relocate -flag bmi-compile --self -flag bmi-compile --sem -flag bmi-compile --slot -flag bmi-supervise --cap -flag bmi-supervise --command-file -flag bmi-supervise --object -flag bmi-supervise --relocation -flag bmi-supervise --sem -flag bmi-supervise --slot flag build --accel flag build --cache flag build --cap @@ -230,6 +211,8 @@ flag publish --exclude flag publish --package flag publish --tag flag publish --workspace +flag remove --build +flag remove --dev flag resolve --explain flag run --accel flag run --cache @@ -257,6 +240,7 @@ flag run --target-triple flag run --toolchain flag search --all-versions flag search --format +flag self completion --print flag self config --cache-unused-days flag self config --keep-days flag self config --mirror @@ -439,8 +423,11 @@ reason platform-target-unserved reason platform-tool-absent reason platform-version-group reason program-cxx-runtime-split +reason runtime-closure reason shared-library-cxx-runtime +reason soname-collision reason static-package-in-two-images +reason static-tls-image reason std-module-precompile reason target-base reason tier-planned diff --git a/tests/e2e/index/routes.cpp b/tests/e2e/index/routes.cpp index 7134b2477..df7c74550 100644 --- a/tests/e2e/index/routes.cpp +++ b/tests/e2e/index/routes.cpp @@ -288,7 +288,7 @@ E2E routes{"routes", s::home_fixture, [] { s::project abs(tmp / "abs-app", {{"mcpp.toml", std::format("[package]\nname = \"absapp\"\nversion = \"0.1.0\"\n\n[indices]\nacme = {{ path = \"{}\" }}\n", (tmp / "abs-index").generic_string())}}); auto r = abs.mcpp({"add", "acme.util@2.0.0"}); expect(fatal(e2e::succeeded(r))) << "an absolute local index path did not resolve on this host: " << s::text(r); - expect(fatal(s::has_line(abs.read("mcpp.toml"), R"(^util = "2\.0\.0"$)"))) << "the dependency was not written: " << abs.read("mcpp.toml"); + expect(fatal(s::has_line(abs.read("mcpp.toml"), R"(^acme\.util = "2\.0\.0"$)"))) << "the dependency was not written: " << abs.read("mcpp.toml"); r = abs.mcpp({"add", "acme.nope@1.0.0"}); expect(fatal(r.started && r.status != 0)) << "expected a miss for acme.nope"; expect(fatal(e2e::contains(s::text(r), route))) << "the absolute index is not addressed as a readable root: " << s::text(r); @@ -298,7 +298,7 @@ E2E routes{"routes", s::home_fixture, [] { {"m1/mcpp.toml", "[package]\nname = \"m1\"\nversion = \"0.1.0\"\n"}}); r = ws.mcpp_in("m1", {"add", "acme.util@2.0.0"}); expect(fatal(e2e::succeeded(r))) << "a workspace member could not read its root-owned local index: " << s::text(r); - expect(fatal(s::has_line(ws.read("m1/mcpp.toml"), R"(^util = "2\.0\.0"$)"))) << "the member did not inherit the workspace [indices]: " << ws.read("m1/mcpp.toml"); + expect(fatal(s::has_line(ws.read("m1/mcpp.toml"), R"(^acme\.util = "2\.0\.0"$)"))) << "the member did not inherit the workspace [indices]: " << ws.read("m1/mcpp.toml"); r = ws.mcpp_in("m1", {"add", "acme.nope@1.0.0"}); expect(fatal(r.started && r.status != 0)) << "expected a miss inside the workspace member"; expect(fatal(e2e::contains(s::text(r), route))) << "the inherited index was anchored somewhere unreadable: " << s::text(r); diff --git a/tests/e2e/macos/rows.cpp b/tests/e2e/macos/rows.cpp index a7b70f2e9..2909d3aa0 100644 --- a/tests/e2e/macos/rows.cpp +++ b/tests/e2e/macos/rows.cpp @@ -163,7 +163,7 @@ int main() { }; "668 a macho program is staged with its closure"_test[s::macos] = [] { - // A program with a shared path dependency: bin/libfw.dylib is staged beside it, the + // A program with a shared path dependency: bin/libdemo_fw.dylib is staged beside it, the // manifest names the dylib and libSystem as the platform's; the staged program runs with // the build tree deleted (exit 7) and stops with "Library not loaded" without the dylib; // the archive carries both. @@ -176,10 +176,10 @@ int main() { expect(fatal(e2e::succeeded(r))) << "mcpp pack --pkg-format dir failed: " << s::text(r); const auto tree = staged(app, "app-0.1.0-"); expect(fatal(fs::is_regular_file(tree / "bin/app"))) << "the staged tree has no bin/app"; - expect(fatal(fs::is_regular_file(tree / "bin/libfw.dylib"))) << "the staged tree has no bin/libfw.dylib beside the program"; + expect(fatal(fs::is_regular_file(tree / "bin/libdemo_fw.dylib"))) << "the staged tree has no bin/libdemo_fw.dylib beside the program"; const auto m = s::read_file(fs::path(tree.string() + ".stage-manifest")); expect(fatal(first_line(m) == "closure = walked")) << "the manifest's first line is not 'closure = walked': " << m; - expect(fatal(lines_contain(m, "needs\t@rpath/libfw.dylib\tbin/libfw.dylib"))) << "the manifest does not state the dylib beside the program: " << m; + expect(fatal(lines_contain(m, "needs\t@rpath/libdemo_fw.dylib\tbin/libdemo_fw.dylib"))) << "the manifest does not state the dylib beside the program: " << m; expect(fatal(lines_contain(m, "needs\t/usr/lib/libSystem.B.dylib\tplatform"))) << "the manifest does not state libSystem as the platform's: " << m; const auto installed = tmp / "installed" / tree.filename(); fs::create_directories(installed.parent_path()); @@ -188,7 +188,7 @@ int main() { auto ran = s::run(installed / "bin/app"); expect(fatal(ran.status == 7)) << "the staged program exited " << ran.status << ", not 7: " << s::text(ran); expect(fatal(s::has_line(ran.out, "^1-2-3$"))) << "the staged program did not print 1-2-3: " << s::text(ran); - fs::remove(installed / "bin/libfw.dylib"); + fs::remove(installed / "bin/libdemo_fw.dylib"); ran = s::run(installed / "bin/app"); expect(fatal(ran.status != 0 && ran.status != 7)) << "the program still ran without its staged dylib (exit " << ran.status << ")"; expect(fatal(e2e::contains(s::text(ran), "Library not loaded"))) << "the failure is not a missing library: " << s::text(ran); @@ -196,7 +196,7 @@ int main() { expect(fatal(e2e::succeeded(r))) << "mcpp pack (tar) failed: " << s::text(r); const auto members = s::tar_list(archive(app, "app-0.1.0-")); expect(fatal(lists(members, "/bin/app"))) << "the archive has no bin/app"; - expect(fatal(lists(members, "/bin/libfw.dylib"))) << "the archive has no bin/libfw.dylib"; + expect(fatal(lists(members, "/bin/libdemo_fw.dylib"))) << "the archive has no bin/libdemo_fw.dylib"; }; "721 an android row links on a macos host"_test[s::macos] = [] { diff --git a/tests/e2e/modules/bmi.cpp b/tests/e2e/modules/bmi.cpp index bf6c88508..470f0e6ce 100644 --- a/tests/e2e/modules/bmi.cpp +++ b/tests/e2e/modules/bmi.cpp @@ -64,11 +64,13 @@ std::vector words(std::string_view line) { return out; } -// The first `build : stage_file ... ` edge of a graph: (dst, src), unescaped. +// The first `build : stage_file ... ` edge of a graph: (dst, src), unescaped. A staged +// BMI also names its absolute spelling under clang (`build | : stage_file`, +// SPEC-018 §1 item 6); `dst` is the first output either way. std::pair first_stage(const std::string& graph) { const auto lines = s::lines_with(graph, " : stage_file "); for (const auto& l : lines) - if (std::regex_search(l, std::regex{R"(^build [^ ]+ : stage_file )"})) { + if (std::regex_search(l, std::regex{R"(^build [^ ]+( [|] .*)? : stage_file )"})) { const auto w = words(l); return {unescape_ninja(w[1]), unescape_ninja(w.back())}; } @@ -364,7 +366,7 @@ int main() { const auto graph = s::read_file(*n); std::string stage; for (const auto& l : s::lines_with(graph, " : stage_file ")) - if (std::regex_search(l, std::regex{R"(^build [a-z]+\.cache/[^ ]*gen\.dep\.[a-z]+ : stage_file )"})) stage = l; + if (std::regex_search(l, std::regex{R"(^build [a-z]+\.cache/[^ ]*gen\.dep\.[a-z]+( [|] .*)? : stage_file )"})) stage = l; expect(fatal(!stage.empty())) << "B: the cached BMI has no stage edge"; const auto bmi = words(stage)[1]; const auto ext = bmi.substr(bmi.rfind('.') + 1); diff --git a/tests/e2e/modules/programs.cpp b/tests/e2e/modules/programs.cpp index a4a7321bd..2e8d1a9e1 100644 --- a/tests/e2e/modules/programs.cpp +++ b/tests/e2e/modules/programs.cpp @@ -40,9 +40,11 @@ std::string host_graph(const fs::path& dir) { expect(fatal(!all.empty())) << "no build programs' graph under " << dir.string(); return s::read_file(all.front()); } -// The graph compiles `obj` (a pattern) with the module rule. +// The graph compiles `obj` (a pattern) with the module rule. Its implicit outputs are the +// unit's BMI and, under clang, the BMI's absolute spelling (`C$:/...` on Windows, an escaped +// colon), so they are read up to the rule's ` : `. bool compiles(const fs::path& dir, std::string_view obj) { - return static_cast(s::has_line(host_graph(dir), std::format(R"(^build obj/[^ ]*/{}( [|] [^:]*)? : cxx_module )", obj))); + return static_cast(s::has_line(host_graph(dir), std::format(R"(^build obj/[^ ]*/{}( [|] .*)? : cxx_module )", obj))); } // The graph stages `obj` from the build cache's `pkg/`. bool places(const fs::path& dir, std::string_view obj, std::string_view entry) { diff --git a/tests/e2e/modules/scanner.cpp b/tests/e2e/modules/scanner.cpp index e3a4ab9bf..faad1f678 100644 --- a/tests/e2e/modules/scanner.cpp +++ b/tests/e2e/modules/scanner.cpp @@ -312,6 +312,29 @@ sources = ["src/target/unix/target.cppm"] expect(e2e::contains(s::text(r), R"("src/absent.cpp" names no file)")) << "no warning names the entry\n" << s::text(r); }; + + "1172 a conditional import follows its condition"_test[s::gcc] = [] { + // mcpp#1026 (docs/04, docs/20): a unit whose `import` stands in an `#ifdef` block takes its + // imports from the compiler's scan with its own compile words. The macro undefined, the + // module is not imported and need not exist; defined, it is imported and the program uses + // it. A header unit in such a block is still refused. + s::project p({{"src/main.cpp", "#ifdef USE_LIB\nimport lib;\n#endif\nint main() {\n#ifdef USE_LIB\n return lib_value() == 42 ? 0 : 1;\n#else\n return 0;\n#endif\n}\n"}}); + auto manifest = [&](std::string_view build) { + p.write("mcpp.toml", std::format("[package]\nname = \"condimp\"\nversion = \"0.1.0\"\n\n[build]\n{}\n\n[targets.condimp]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n", build)); + }; + manifest("sources = [\"src/*.cpp\"]"); + auto r = p.mcpp({"run"}); + expect(fatal(e2e::succeeded(r))) << "the build with the macro undefined failed\n" << s::text(r); + p.write("src/lib.cppm", "export module lib;\nexport int lib_value() { return 42; }\n"); + manifest("sources = [\"src/*.cpp\", \"src/*.cppm\"]\ndefines = [\"USE_LIB\"]"); + r = p.mcpp({"run"}); + expect(fatal(e2e::succeeded(r))) << "the build with the macro defined failed\n" << s::text(r); + p.write("src/h.hpp", "#pragma once\n"); + p.write("src/main.cpp", "#ifdef USE_LIB\nimport \"h.hpp\";\n#endif\nint main() { return 0; }\n"); + r = p.mcpp({"build"}); + expect(fatal(!e2e::succeeded(r))) << "a header unit in a conditional block was accepted"; + expect(e2e::contains(s::text(r), "header units")) << s::text(r); + }; }}; } // namespace diff --git a/tests/e2e/pack/formats.cpp b/tests/e2e/pack/formats.cpp index 122996c1e..fa0ae7273 100644 --- a/tests/e2e/pack/formats.cpp +++ b/tests/e2e/pack/formats.cpp @@ -471,10 +471,11 @@ main = "src/main.cpp" expect(fatal(e2e::succeeded(r))) << "A: pack failed\n" << s::text(r); expect(fatal(e2e::contains(s::text(r), "Packing hostapp v0.1.0 (vendored, stripped)"))) << "A: the Packing line\n" << s::text(r); auto xa = unpack("xa"); - const auto fa = elf_facts(only(xa, "lib/libdep.so")); + // The library of `spike.dep` is named by its package (mcpp#975). + const auto fa = elf_facts(only(xa, "lib/libspike_dep.so")); const auto fp = elf_facts(only(xa, "bin/hostapp")); - expect(fatal(fa.symtab == 0 && fa.debug == 0)) << "A: lib/libdep.so is not stripped: symtab=" << fa.symtab << " debug=" << fa.debug; - expect(fatal(exports(fa, "dep_answer"))) << "A: lib/libdep.so lost its export"; + expect(fatal(fa.symtab == 0 && fa.debug == 0)) << "A: lib/libspike_dep.so is not stripped: symtab=" << fa.symtab << " debug=" << fa.debug; + expect(fatal(exports(fa, "dep_answer"))) << "A: lib/libspike_dep.so lost its export"; expect(fatal(fp.symtab == 0 && fp.debug == 0)) << "A: bin/hostapp is not stripped: symtab=" << fp.symtab << " debug=" << fp.debug; auto run = s::run(only(xa, "hostapp")); expect(fatal(e2e::succeeded(run))) << "A: the unpacked program does not run\n" << s::text(run); @@ -482,13 +483,13 @@ main = "src/main.cpp" r = host.mcpp({"pack", "--pkg-format", "tar", "--no-strip"}); expect(fatal(e2e::succeeded(r))) << "B: pack failed\n" << s::text(r); expect(fatal(e2e::contains(s::text(r), "Packing hostapp v0.1.0 (vendored)"))) << "B: the Packing line\n" << s::text(r); - const auto fb = elf_facts(only(unpack("xb"), "lib/libdep.so")); - expect(fatal(fb.symtab == 1)) << "B: --no-strip did not reach lib/libdep.so: symtab=" << fb.symtab; + const auto fb = elf_facts(only(unpack("xb"), "lib/libspike_dep.so")); + expect(fatal(fb.symtab == 1)) << "B: --no-strip did not reach lib/libspike_dep.so: symtab=" << fb.symtab; r = host.mcpp({"pack", "--pkg-format", "tar", "--debug-symbols", (tmp / "dbg").string()}); expect(fatal(e2e::succeeded(r))) << "C: pack failed\n" << s::text(r); - expect(fatal(fs::exists(tmp / "dbg/libdep.so.debug") && fs::file_size(tmp / "dbg/libdep.so.debug") > 0)) << "C: no libdep.so.debug\n" << s::text(r); - expect(fatal(elf_facts(only(unpack("xc"), "lib/libdep.so")).debuglink)) << "C: lib/libdep.so names no debug file"; + expect(fatal(fs::exists(tmp / "dbg/libspike_dep.so.debug") && fs::file_size(tmp / "dbg/libspike_dep.so.debug") > 0)) << "C: no libspike_dep.so.debug\n" << s::text(r); + expect(fatal(elf_facts(only(unpack("xc"), "lib/libspike_dep.so")).debuglink)) << "C: lib/libspike_dep.so names no debug file"; host.write("build.mcpp", R"cpp(import mcpp; #include @@ -544,12 +545,12 @@ int main() { return app_entry() == 43 ? 0 : 1; } expect(fatal(e2e::succeeded(r))) << "E: pack failed\n" << s::text(r); expect(fatal(e2e::contains(s::text(r), "Packing app v0.1.0 (vendored, stripped)"))) << "E: the Packing line\n" << s::text(r); s::tar_extract(app.at("target/dist/app-0.1.0-x86_64-linux-android.tar.gz"), app.at("xe")); - for (std::string_view f : {"libapp.so", "libdep.so", "libc++_shared.so"}) { + for (std::string_view f : {"libapp.so", "libspike_dep.so", "libc++_shared.so"}) { const auto fe = elf_facts(only(app.at("xe"), std::format("lib/{}", f))); expect(fatal(fe.symtab == 0 && fe.debug == 0)) << "E: lib/" << f << " is not stripped"; } expect(fatal(exports(elf_facts(only(app.at("xe"), "lib/libapp.so")), "app_entry"))) << "E: libapp.so lost app_entry"; - expect(exports(elf_facts(only(app.at("xe"), "lib/libdep.so")), "dep_answer")) << "E: libdep.so lost dep_answer"; + expect(exports(elf_facts(only(app.at("xe"), "lib/libspike_dep.so")), "dep_answer")) << "E: libspike_dep.so lost dep_answer"; }; "723 pack reports what it produced"_test[s::pack][s::python3] = [] { // `mcpp pack --message-format json` reports what it produced in one envelope on stdout diff --git a/tests/e2e/pack/modes.cpp b/tests/e2e/pack/modes.cpp index 3f1c2b26b..2c81b4e4d 100644 --- a/tests/e2e/pack/modes.cpp +++ b/tests/e2e/pack/modes.cpp @@ -526,11 +526,12 @@ int main() { std::puts("1-2-3"); return fw_anchor() == 41 && named_anchor() == 1 if (!exe && f.generic_string().ends_with("/bin/app")) exe = f; expect(fatal(exe.has_value())) << "no bin/app\n" << s::text(r); const auto bin = exe->parent_path(); - expect(fatal(fs::is_regular_file(bin / "libfw.so"))) << "no bin/libfw.so\n" << s::text(r); - expect(fatal(s::read_header(bin / "libfw.so").soname == "libfw.so")) << "libfw.so carries SONAME '" << s::read_header(bin / "libfw.so").soname << "', not its file name"; - expect(fatal(std::ranges::contains(s::read_header(*exe).needed, std::string("libfw.so")))) << "the consumer no longer needs libfw.so by its file name"; - expect(fatal(fs::is_regular_file(bin / "libnamed.so"))) << "no bin/libnamed.so"; - expect(fatal(s::read_header(bin / "libnamed.so").soname == "libnamed.so.1")) << "the declared soname became '" << s::read_header(bin / "libnamed.so").soname << "'"; + expect(fatal(fs::is_regular_file(bin / "libdemo_fw.so"))) << "no bin/libdemo_fw.so\n" << s::text(r); + expect(fatal(s::read_header(bin / "libdemo_fw.so").soname == "libdemo_fw.so")) << "libdemo_fw.so carries SONAME '" << s::read_header(bin / "libdemo_fw.so").soname << "', not its file name"; + expect(fatal(std::ranges::contains(s::read_header(*exe).needed, std::string("libdemo_fw.so")))) << "the consumer no longer needs libdemo_fw.so by its file name"; + // The file is named by the package (mcpp#975); the stated soname is the name it is loaded by. + expect(fatal(fs::is_regular_file(bin / "libdemo_named.so"))) << "no bin/libdemo_named.so"; + expect(fatal(s::read_header(bin / "libdemo_named.so").soname == "libnamed.so.1")) << "the declared soname became '" << s::read_header(bin / "libdemo_named.so").soname << "'"; r = app.mcpp({"pack", "--pkg-format", "dir"}); expect(fatal(e2e::succeeded(r))) << "mcpp pack --pkg-format dir failed\n" << s::text(r); @@ -539,8 +540,8 @@ int main() { std::puts("1-2-3"); return fw_anchor() == 41 && named_anchor() == 1 const fs::path manifest = tree->string() + ".stage-manifest"; const auto lines = file_lines(manifest); expect(fatal(!lines.empty() && lines.front() == "closure = walked")) << "the manifest's first line is not 'closure = walked'\n" << s::read_file(manifest); - expect(fatal(fs::is_regular_file(*tree / "lib/libfw.so"))) << "lib/libfw.so is not bundled"; - expect(fatal(has_exact_line(manifest, "needs\tlibfw.so\tlib/libfw.so"))) << "the manifest does not state libfw.so at lib/libfw.so\n" << s::read_file(manifest); + expect(fatal(fs::is_regular_file(*tree / "lib/libdemo_fw.so"))) << "lib/libdemo_fw.so is not bundled"; + expect(fatal(has_exact_line(manifest, "needs\tlibdemo_fw.so\tlib/libdemo_fw.so"))) << "the manifest does not state libdemo_fw.so at lib/libdemo_fw.so\n" << s::read_file(manifest); expect(fatal(has_exact_line(manifest, "needs\tlibc.so.6\tplatform"))) << "the manifest does not state libc.so.6 as the platform's\n" << s::read_file(manifest); bool files = false, bad = false; for (std::size_t i = 1; i < lines.size(); ++i) { diff --git a/tests/e2e/runtime/packages.cpp b/tests/e2e/runtime/packages.cpp index 3434ac729..87f3d86db 100644 --- a/tests/e2e/runtime/packages.cpp +++ b/tests/e2e/runtime/packages.cpp @@ -373,7 +373,8 @@ int main() { return r; }; auto log = [&](std::string_view dir) { return s::read_file(tmp / dir / "build.log"); }; - auto libfw = [&](std::string_view dir) { return !s::find_files(tmp / dir / "target", R"(libfw\.so)").empty(); }; + // `demo.fw`'s library is named by its package (mcpp#975): `libdemo_fw.so`. + auto libfw = [&](std::string_view dir) { return !s::find_files(tmp / dir / "target", R"(libdemo_fw\.so)").empty(); }; auto record_of = [&](std::string_view dir) { std::string out; for (const auto& res : s::find_files(tmp / dir / "target", R"(resolution\.json)")) { @@ -392,10 +393,10 @@ int main() { // A make_app("a", "fwdefault"); expect(fatal(e2e::succeeded(build("a", {"--strict"})))) << "A: build --strict failed: " << log("a"); - expect(fatal(libfw("a"))) << "A: no libfw.so for a silent consumer: " << log("a"); + expect(fatal(libfw("a"))) << "A: no libdemo_fw.so for a silent consumer: " << log("a"); const auto bin_a = named_within(tmp / "a/target", "a", "/bin/"); expect(fatal(bin_a.has_value())) << "A: no program"; - expect(fatal(needs_library(*bin_a, "libfw.so"))) << "A: the program does not NEED libfw.so"; + expect(fatal(needs_library(*bin_a, "libdemo_fw.so"))) << "A: the program does not NEED libdemo_fw.so"; auto r = record_of("a"); expect(fatal(r == "shared package-default")) << "A: link record is '" << r << "'"; expect(fatal(e2e::succeeded(s::run(*bin_a)))) << "A: the program did not run"; @@ -722,6 +723,96 @@ int main() { r = app.mcpp({"build"}, o); expect(fatal(e2e::succeeded(r))) << "C: the dependency's own search path did not fix the link: " << s::text(r); }; + + "1167 a dependency's shared library is named by its package"_test[s::elf] = [] { + // mcpp#975 (SPEC-004 §11 item 8, docs/04): two packages whose targets share a name, linked + // shared, make two libraries named by their packages, and the program loads both; two + // libraries stated with one soname are refused at planning, naming both packages. + const auto tmp = s::case_dir(); + auto library = [&](std::string_view ns, int value, std::string_view extra) { + s::project(tmp / ns, {{"mcpp.toml", std::format("[package]\nnamespace = \"{0}\"\nname = \"util\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cpp\"]\n\n[targets.util]\nkind = \"shared\"\n{1}", ns, extra)}, + {"src/util.cpp", std::format("extern \"C\" int {}_value() {{ return {}; }}\n", ns, value)}}); + }; + library("acme", 40, ""); + library("beta", 2, ""); + s::project app(tmp / "app", {{"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cpp\"]\n\n[targets.app]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n\n[dependencies]\nacme.util = { path = \"../acme\" }\nbeta.util = { path = \"../beta\" }\n"}, + {"src/main.cpp", "extern \"C\" int acme_value();\nextern \"C\" int beta_value();\nint main() { return acme_value() + beta_value() == 42 ? 0 : 1; }\n"}}); + auto r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "the build failed\n" << s::text(r); + expect(s::find_file(app.at("target"), "libacme_util.so").has_value()) << "no libacme_util.so"; + expect(s::find_file(app.at("target"), "libbeta_util.so").has_value()) << "no libbeta_util.so"; + expect(!s::find_file(app.at("target"), "libutil.so").has_value()) << "a dependency's library took its target's name"; + r = app.mcpp({"run"}); + expect(e2e::succeeded(r)) << "the program did not load both libraries\n" << s::text(r); + library("acme", 40, "soname = \"libsame.so\"\n"); + library("beta", 2, "soname = \"libsame.so\"\n"); + r = app.mcpp({"build"}); + expect(fatal(!e2e::succeeded(r))) << "two libraries loaded by one name were accepted"; + expect(e2e::contains(s::text(r), "both make a shared library loaded as 'libsame.so'")) << s::text(r); + }; + + "1168 a library linked from one file and loaded from another is refused"_test[s::elf][s::gcc] = [] { + // mcpp#537 (docs/04 §2.11): the link reads libfoo.so from one directory, and the image's + // run path finds another libfoo.so; the build is refused naming both files. With one + // directory for both, the build runs. + const auto gcc = s::host_cc(); + expect(fatal(gcc.has_value())) << "no host C compiler links a shared object"; + s::project app({{"a/foo.c", "int foo_answer(void) { return 1; }\n"}, + {"b/foo.c", "int foo_answer(void) { return 2; }\n"}, + {"src/main.cpp", "extern \"C\" int foo_answer();\nint main() { return foo_answer() > 0 ? 0 : 1; }\n"}, + {"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[targets.app]\nkind = \"bin\"\nmain = \"src/main.cpp\"\n"}}); + for (auto dir : {"a", "b"}) + expect(fatal(e2e::succeeded(s::run(*gcc, {"-shared", "-fPIC", "-Wl,-soname,libfoo.so", app.at(std::format("{}/foo.c", dir)).string(), + "-o", app.at(std::format("{}/libfoo.so", dir)).string()})))); + auto program = [&](std::string_view linked, std::string_view loaded) { + app.write("build.mcpp", std::format("import mcpp;\n#include \nint main() {{\n const std::string root = mcpp::manifest_dir();\n mcpp::link_lib(\"foo\");\n" + " mcpp::link_search((root + \"/{}\").c_str());\n mcpp::runtime_search_dir((root + \"/{}\").c_str());\n return 0;\n}}\n", linked, loaded)); + }; + program("a", "b"); + auto r = app.mcpp({"build"}); + expect(fatal(!e2e::succeeded(r))) << "a library linked from a/ and loaded from b/ was accepted\n" << s::text(r); + expect(e2e::contains(s::text(r), "libfoo.so is linked from one file and loaded from another")) << s::text(r); + expect(e2e::contains(s::text(r), "/a/libfoo.so") && e2e::contains(s::text(r), "/b/libfoo.so")) << "the refusal does not name both files\n" << s::text(r); + program("a", "a"); + r = app.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "the build that links and loads one file failed\n" << s::text(r); + expect(e2e::succeeded(app.mcpp({"run"}))) << "the program did not run"; + }; + + "1169 a shared image over the static TLS dlopen serves is reported"_test[s::elf][s::gcc] = [] { + // mcpp#907 (SPEC-016 §2.1 `dlopen-static-tls`, docs/04): a shared library whose objects use + // the initial-exec model for 4096 bytes is reported against the row's bound; with an exact + // `exports` name, which says a host loads it by name, it is refused. + s::project p({{"src/lib.cpp", "thread_local char big[4096];\nextern \"C\" int plugin_entry() { big[0] = 1; return big[0]; }\n"}}); + auto manifest = [&](std::string_view extra) { + p.write("mcpp.toml", std::format("[package]\nname = \"tlsimg\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cpp\"]\ncxxflags = [\"-ftls-model=initial-exec\"]\n\n" + "[targets.tlsimg]\nkind = \"shared\"\n{}", extra)); + }; + manifest(""); + auto r = p.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << "a library a program loads at start-up was refused\n" << s::text(r); + expect(e2e::contains(s::text(r), "bytes of thread-local storage (DF_STATIC_TLS)")) << "the image was not reported\n" << s::text(r); + manifest("exports = [\"plugin_entry\"]\n"); + r = p.mcpp({"build"}); + expect(fatal(!e2e::succeeded(r))) << "an image a host loads by name was not refused\n" << s::text(r); + expect(e2e::contains(s::text(r), "its `exports` name the symbols a host loads it to call")) << s::text(r); + expect(e2e::contains(s::text(r), "-ftls-model=global-dynamic")) << "the refusal gives no remedy\n" << s::text(r); + }; + + "1170 an exact export the image does not define is reported"_test[s::elf][s::gcc] = [] { + // mcpp#982 (SPEC-004 §11 item 7): an `exports` entry without a wildcard names a symbol a + // host looks up; one the image does not define is reported as `unmatched-exact-export`, + // and neither a defined name nor a pattern that matches nothing is. + s::project p({{"src/lib.cpp", "extern \"C\" int defined_entry() { return 1; }\n"}, + {"mcpp.toml", "[package]\nname = \"exactexp\"\nversion = \"0.1.0\"\n\n[build]\nsources = [\"src/*.cpp\"]\n\n" + "[targets.exactexp]\nkind = \"shared\"\nexports = [\"defined_entry\", \"missing_entry\", \"nomatch_*\"]\n"}}); + auto r = p.mcpp({"build"}); + expect(fatal(e2e::succeeded(r))) << s::text(r); + expect(e2e::contains(s::text(r), "[targets.exactexp] exports \"missing_entry\" names a symbol the image does not define")) << s::text(r); + expect(e2e::contains(s::text(r), "unmatched-exact-export") || e2e::contains(s::text(r), "2027.3")) << "the report names no deprecation\n" << s::text(r); + expect(s::lacks(s::text(r), "\"defined_entry\" names a symbol")) << "a defined name was reported"; + expect(s::lacks(s::text(r), "nomatch_")) << "a pattern was reported"; + }; }}; } // namespace diff --git a/tests/e2e/targets/abi.cpp b/tests/e2e/targets/abi.cpp index d11c4c284..9f2f7ac87 100644 --- a/tests/e2e/targets/abi.cpp +++ b/tests/e2e/targets/abi.cpp @@ -237,13 +237,13 @@ int main() { auto a = make_app("a", "fwlinux", ""); auto r = a.mcpp({"build"}); expect(fatal(e2e::succeeded(r))) << "FAIL: A: build failed: " << s::text(r); - expect(fatal(s::find_file(a.at("target"), "libfw.so").has_value())) << "FAIL: A: no libfw.so: " << s::text(r); + expect(fatal(s::find_file(a.at("target"), "libdemo_fw.so").has_value())) << "FAIL: A: no libdemo_fw.so: " << s::text(r); auto rec = reason_of(s::find_file(a.at("target"), "resolution.json").value_or(fs::path()), "demo.fw@0.1.0"); expect(fatal(rec == "shared row-kind")) << "FAIL: A: link record is '" << rec << "'"; auto b = make_app("b", "fwwin", ""); r = b.mcpp({"build"}); expect(fatal(e2e::succeeded(r))) << "FAIL: B: build failed: " << s::text(r); - expect(fatal(!s::find_file(b.at("target"), "libfw.so").has_value())) << "FAIL: B: a non-matching row built libfw.so"; + expect(fatal(!s::find_file(b.at("target"), "libdemo_fw.so").has_value())) << "FAIL: B: a non-matching row built libdemo_fw.so"; rec = reason_of(s::find_file(b.at("target"), "resolution.json").value_or(fs::path()), "demo.fw@0.1.0"); expect(fatal(rec == "static default")) << "FAIL: B: link record is '" << rec << "'"; auto c = make_app("c", "fwlinux", ", linkage = \"static\""); diff --git a/tests/e2e/targets/side.cpp b/tests/e2e/targets/side.cpp index 11ce029c7..fdf181ed1 100644 --- a/tests/e2e/targets/side.cpp +++ b/tests/e2e/targets/side.cpp @@ -431,6 +431,24 @@ int main() { << s::text(r); expect(fatal(s::has_line(s::text(r), R"(sizeof\(long\) +declared 8 +measured 4)"))) << "the refusal does not name the quantity and both values\n" << s::text(r); }; + + "1174 a graph C library without a C++ ABI is refused at planning"_test[s::gcc] = [] { + // mcpp#898 (SPEC-002 §3.11, docs/22): the graph supplies `c-abi`, no package supplies + // `c++-abi`, and a unit imports `std`; the plan stops with the two remedies before anything + // is compiled. A stated `cxx_runtime` is the author's answer, and this refusal leaves it. + const auto tmp = s::case_dir(); + s::project(tmp / "libc", {{"mcpp.toml", "[package]\nnamespace = \"probe\"\nname = \"tiny-musl\"\nversion = \"0.1.0\"\nprovides = [\"mcpp:c-abi=musl\"]\n\n[build]\nsources = []\n"}}); + s::project app(tmp / "app", {{"mcpp.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\ntiny-musl = { path = \"../libc\" }\n"}, + {"src/main.cpp", "import std;\nint main() { std::println(\"x\"); }\n"}}); + auto r = app.mcpp({"build"}); + expect(fatal(!e2e::succeeded(r))) << "the plan was not refused\n" << s::text(r); + expect(e2e::contains(s::text(r), "no package supplies the C++ ABI")) << s::text(r); + expect(e2e::contains(s::text(r), "add a dependency that provides `mcpp:c++-abi`, or state [build] cxx_runtime = \"host-coupled\"")) << s::text(r); + expect(s::lacks(s::text(r), "features.h")) << "the refusal came after the std module's precompile\n" << s::text(r); + app.write("mcpp.toml", app.read("mcpp.toml") + "\n[build]\ncxx_runtime = \"host-coupled\"\n"); + r = app.mcpp({"build"}); + expect(s::lacks(s::text(r), "no package supplies the C++ ABI")) << "a stated cxx_runtime was refused\n" << s::text(r); + }; }}; } // namespace diff --git a/tests/e2e/windows/resources.cpp b/tests/e2e/windows/resources.cpp index 287b73b5d..c1e0bf2d6 100644 --- a/tests/e2e/windows/resources.cpp +++ b/tests/e2e/windows/resources.cpp @@ -204,7 +204,9 @@ void own_resources(const fs::path& root) { std::set seen; for (auto it = fs::recursive_directory_iterator(root / "target"); it != fs::recursive_directory_iterator{}; ++it) { const auto name = it->path().filename().string(); - if (!it->is_regular_file() || (name != "image.exe" && name != "image.dll" && name != "libimage.dll" && name != "updater.exe")) continue; + // The library's DLL keeps its target's name where it is a selected member, and is named + // after its package where it is a dependency (`fixture_library_image.dll`, mcpp#975). + if (!it->is_regular_file() || (name != "image.exe" && !name.ends_with("image.dll") && name != "updater.exe")) continue; if (bytes_of(it->path()).substr(0, 2) != "MZ") continue; const auto data = rsrc_of(it->path()); const auto path = it->path().generic_string(); diff --git a/tests/unit/test_graph_shape.cpp b/tests/unit/test_graph_shape.cpp index cdc4ccef7..28465f23f 100644 --- a/tests/unit/test_graph_shape.cpp +++ b/tests/unit/test_graph_shape.cpp @@ -1,6 +1,7 @@ import std; import mcpplibs.mtest; import mcpp.build.graph_shape; +import mcpp.invocation; using namespace mcpplibs::mtest; @@ -61,6 +62,31 @@ UTest the_header_names_the_request{"GraphShape/TheHeaderNamesTheRequest", [] { expect(eq(read_request(write_graph("# mcpp:graph=normal;schedule=none;accel=default;dist=none")), "")); }}; +// SPEC-019 §9: a switch of the build-optimization register that is decided when the graph is +// written is part of the request the graph names. The record of a build cannot hold it: the record +// is written by a build that succeeded, and the switch is stated to check one that fails. An edge +// entry (`MCPP_BMI_CUTOFF`) is read when the edge runs, and is not part of it. +UTest the_request_names_a_stated_switch_that_shapes_the_graph{"GraphShape/TheRequestNamesAStatedSwitch", [] { + using namespace mcpp::build; + const mcpp::invocation::ScopedEnv none[]{{"MCPP_PRIVATE_FRAGMENT", std::nullopt}, {"MCPP_BMI_SCHEDULE", std::nullopt}, + {"MCPP_BUILDOPT", std::nullopt}, {"MCPP_BMI_CUTOFF", std::nullopt}}; + const auto plain = request_tag("", "a"); + { + const mcpp::invocation::ScopedEnv cutoff("MCPP_BMI_CUTOFF", "exact"); + expect(eq(request_tag("", "a"), plain)) << "an edge entry changed the request"; + } + std::vector tags{plain}; + for (auto const& [name, value] : std::initializer_list>{ + {"MCPP_PRIVATE_FRAGMENT", "conservative"}, {"MCPP_PRIVATE_FRAGMENT", "as-written"}, + {"MCPP_BMI_SCHEDULE", "off"}, {"MCPP_BUILDOPT", "off"}}) { + const mcpp::invocation::ScopedEnv stated(name, value); + tags.push_back(request_tag("", "a")); + } + std::ranges::sort(tags); + expect(std::ranges::adjacent_find(tags) == tags.end()) << "two statements name one request"; + expect(eq(request_tag("", "a"), plain)) << "a statement stayed after its scope"; +}}; + UTest only_a_plain_graph_with_the_manifests_variant_is_replayed{"GraphShape/OnlyAPlainGraphWithTheManifestsVariantIsReplayed", [] { using namespace mcpp::build; expect(is_plain_build_graph(write_graph(header_line(GraphShape::Normal, "none", false)))); diff --git a/tests/unit/test_home.cpp b/tests/unit/test_home.cpp index 690242c6d..2c50bbac4 100644 --- a/tests/unit/test_home.cpp +++ b/tests/unit/test_home.cpp @@ -23,11 +23,18 @@ class ScopedEnv { mcpp::invocation::ScopedEnv inner_; // stated for this invocation, as mcpp states its own }; +// The spelling a home is used under (mcpp#1024): absolute and lexically normal, +// its links kept. `/tmp` and a macOS temporary directory are links, so a +// resolved spelling would differ. +std::filesystem::path given(const std::filesystem::path& p) { + return std::filesystem::absolute(p).lexically_normal(); +} + } // namespace UTest explicit_mcpp_home_wins{"Home/ExplicitMcppHomeWins", [] { ScopedEnv home("MCPP_HOME", "/tmp/mcpp-home-test"); - const auto expected = std::filesystem::weakly_canonical(std::filesystem::absolute("/tmp/mcpp-home-test")); + const auto expected = given("/tmp/mcpp-home-test"); expect(eq(mcpp::home::root(), expected)); expect(eq(mcpp::home::cache_root(), expected / "build-cache" / "v1")); }}; @@ -110,7 +117,7 @@ UTest default_original_and_effective_are_identical{"HomeSelection/DefaultOrigina ~Case() { TearDown(); } void body() { const auto selected = mcpp::home::selection(); - expect(eq(selected.original, std::filesystem::weakly_canonical(original))); + expect(eq(selected.original, given(original))); expect(eq(selected.original, selected.effective)); expect(!selected.redirected); } @@ -128,8 +135,8 @@ UTest environment_selects_the_locator_and_only_one_hop_is_read{"HomeSelection/En locator(original, target); locator(target, third); const auto selected = mcpp::home::selection(); - expect(eq(selected.original, std::filesystem::weakly_canonical(original))); - expect(eq(selected.effective, std::filesystem::weakly_canonical(target))); + expect(eq(selected.original, given(original))); + expect(eq(selected.effective, given(target))); expect(eq(mcpp::home::cache_root(), selected.effective / "build-cache" / "v1")); expect(bool(selected.redirected)); } @@ -164,7 +171,7 @@ UTest force_can_repair_a_malformed_locator{"HomeSelection/ForceCanRepairAMalform expect(bool(mcpp::home::save(*selected))); const auto restored = mcpp::home::inspect(original); if (auto&& failed = expect(fatal(bool(restored))); !failed) failed << restored.error(); - expect(eq(restored->effective, std::filesystem::weakly_canonical(target))); + expect(eq(restored->effective, given(target))); } } fixture; fixture.body(); @@ -186,7 +193,7 @@ UTest existing_home_needs_force_and_changing_it_keeps_both_data_trees{"HomeSelec expect(eq(mcpp::invocation::get("MCPP_HOME").value_or(""), mcpp::home::spelling(original))); const auto restored = mcpp::home::inspect(original); expect(fatal(bool(restored))); - expect(eq(restored->previous, std::filesystem::weakly_canonical(original))); + expect(eq(restored->previous, given(original))); } } fixture; fixture.body(); @@ -204,7 +211,7 @@ UTest returning_to_original_removes_only_the_locator{"HomeSelection/ReturningToO expect(fatal(bool(mcpp::home::save(*selected)))); expect(!std::filesystem::exists(original / "home.toml")); expect(std::filesystem::exists(target / "config.toml")); - expect(eq(mcpp::home::root(), std::filesystem::weakly_canonical(original))); + expect(eq(mcpp::home::root(), given(original))); } } fixture; fixture.body(); @@ -231,7 +238,7 @@ UTest read_only_configuration_does_not_initialize_or_acquire_a_provider{"HomeSel ScopedEnv home("MCPP_HOME", mcpp::home::spelling(cold).c_str()); const auto config = mcpp::config::load_or_init(true, {}, {}, mcpp::config::Initialization::ReadOnly); if (auto&& failed = expect(fatal(bool(config))); !failed) failed << config.error().message; - expect(eq(config->mcppHome, std::filesystem::weakly_canonical(cold))); + expect(eq(config->mcppHome, given(cold))); expect(!std::filesystem::exists(cold)); } } fixture; @@ -294,9 +301,24 @@ UTest unicode_locator_round_trip_does_not_narrow_the_selected_path{"HomeSelectio expect(fatal(bool(mcpp::home::save(*selected)))); const auto restored = mcpp::home::inspect(original); if (auto&& failed = expect(fatal(bool(restored))); !failed) failed << restored.error(); - expect(eq(restored->effective, std::filesystem::weakly_canonical(unicode))); + expect(eq(restored->effective, given(unicode))); expect(eq(mcpp::home::from_utf8(mcpp::home::spelling(unicode)), unicode)); } } fixture; fixture.body(); }}; + +// mcpp#1024: a home given through a link is used under that spelling; whether two spellings are +// one home is a question of identity, which the selection asks. +UTest a_home_given_through_a_link_keeps_its_spelling{"Home/AHomeGivenThroughALinkKeepsItsSpelling", [] { + if constexpr (mcpplibs::os::is_windows) return; // a directory link needs a privilege there + const auto base = std::filesystem::temp_directory_path() / std::format("mcpp-home-link-{}", std::random_device{}()); + std::filesystem::create_directories(base / "real"); + std::filesystem::create_directory_symlink(base / "real", base / "link"); + { + ScopedEnv home("MCPP_HOME", (base / "link" / "home").string().c_str()); + expect(eq(mcpp::home::root(), given(base / "link" / "home"))); + expect(eq(mcpp::home::cache_root(), given(base / "link" / "home") / "build-cache" / "v1")); + } + std::filesystem::remove_all(base); +}}; diff --git a/tests/unit/test_manifest.cpp b/tests/unit/test_manifest.cpp index c8b6331e9..37533e4f9 100644 --- a/tests/unit/test_manifest.cpp +++ b/tests/unit/test_manifest.cpp @@ -435,7 +435,8 @@ widget = "1.0.0" .features = {"gui", "vulkan"}, }); if (auto&& failed = expect(fatal(edited.has_value())); !failed) failed << edited.error(); - expect(ne(edited->find("[dependencies.acme]\nwidget = { version = \"2.0.0\", features = [\"gui\", \"vulkan\"] }"), std::string::npos)); + // Neither a `[dependencies.acme]` header nor an `acme.` key: the dotted key. + expect(ne(edited->find("[dependencies]\nacme.widget = { version = \"2.0.0\", features = [\"gui\", \"vulkan\"] }"), std::string::npos)); auto parsed = mcpp::manifest::parse_string(*edited); if (auto&& failed = expect(fatal(parsed.has_value())); !failed) failed << parsed.error().format(); expect(fatal(eq(parsed->dependencies.size(), 2u))); @@ -475,6 +476,106 @@ widget = "1.0.0" expect(ne(invalid.error().find("invalid manifest"), std::string::npos)); }}; +// mcpp#964: a namespace already written as dotted keys under `[dependencies]` +// gets one more dotted key there. A `[dependencies.]` header after them is a +// table defined twice, which TOML 1.0 and every reader but mcpp's refused. +UTest writes_a_dotted_key_beside_dotted_keys{"ManifestEditor/WritesADottedKeyBesideDottedKeys", [] { + constexpr std::string_view source = R"([package] +name = "app" +version = "0.1.0" + +[dependencies] +compat.libpng = "1.6.43" +)"; + auto edited = mcpp::manifest::upsert_dependency_text(source, { + .namespace_ = "compat", .shortName = "zlib", .version = "1.3.2", + }); + if (auto&& failed = expect(fatal(edited.has_value())); !failed) failed << edited.error(); + expect(ne(edited->find("[dependencies]\ncompat.zlib = \"1.3.2\"\ncompat.libpng = \"1.6.43\"\n"), + std::string::npos)) << *edited; + expect(edited->find("[dependencies.compat]") == std::string::npos); + expect(mcpp::manifest::reopened_dotted_tables(*edited).empty()); +}}; + +// A manifest an older `mcpp add` wrote: the reader takes it and names the +// table; the next edit of that table writes the header's entries as dotted keys. +UTest repairs_a_header_that_reopens_dotted_keys{"ManifestEditor/RepairsAHeaderThatReopensDottedKeys", [] { + constexpr std::string_view source = R"([package] +name = "app" +version = "0.1.0" + +[dependencies] +compat.libpng = "1.6.43" + +[dependencies.compat] +# the codec +zlib = "1.3.2" +)"; + auto parsed = mcpp::manifest::parse_string(source); + if (auto&& failed = expect(fatal(parsed.has_value())); !failed) failed << parsed.error().format(); + expect(eq(parsed->reopenedTables, std::vector{"dependencies.compat"})); + expect(eq(parsed->dependencies.size(), 2u)); + + auto edited = mcpp::manifest::upsert_dependency_text(source, { + .namespace_ = "compat", .shortName = "zstd", .version = "1.5.7", + }); + if (auto&& failed = expect(fatal(edited.has_value())); !failed) failed << edited.error(); + expect(edited->find("[dependencies.compat]") == std::string::npos) << *edited; + expect(ne(edited->find("compat.zlib = \"1.3.2\""), std::string::npos)) << *edited; + expect(ne(edited->find("# the codec"), std::string::npos)) << *edited; + expect(mcpp::manifest::reopened_dotted_tables(*edited).empty()) << *edited; + auto reparsed = mcpp::manifest::parse_string(*edited); + if (auto&& failed = expect(fatal(reparsed.has_value())); !failed) failed << reparsed.error().format(); + expect(eq(reparsed->dependencies.size(), 3u)); +}}; + +// `mcpp add --build` and `mcpp remove --build`: the same editor, the table named. +UTest edits_the_table_it_is_given{"ManifestEditor/EditsTheTableItIsGiven", [] { + using mcpp::manifest::DependencyTableKind; + constexpr std::string_view source = R"([package] +name = "app" +version = "0.1.0" + +[dependencies] +acme.rules = "1.0.0" +)"; + auto added = mcpp::manifest::upsert_dependency_text(source, { + .namespace_ = "acme", .shortName = "rules", .version = "1.0.0", .table = DependencyTableKind::Build, + }); + if (auto&& failed = expect(fatal(added.has_value())); !failed) failed << added.error(); + expect(ne(added->find("[build-dependencies]\nacme.rules = \"1.0.0\""), std::string::npos)) << *added; + + auto removed = mcpp::manifest::remove_dependency_text(*added, "acme", "rules"); + if (auto&& failed = expect(fatal(removed.has_value() && removed->has_value())); !failed) + failed << (removed ? std::string("nothing removed") : removed.error()); + auto parsed = mcpp::manifest::parse_string(**removed); + if (auto&& failed = expect(fatal(parsed.has_value())); !failed) failed << parsed.error().format(); + expect(parsed->dependencies.empty()); + expect(eq(parsed->buildDependencies.size(), 1u)); + + auto none = mcpp::manifest::remove_dependency_text(**removed, "acme", "rules", DependencyTableKind::Dev); + expect(fatal(none.has_value())); + expect(!none->has_value()); +}}; + +// The header form, emptied by a removal, goes with its last entry. +UTest removes_an_emptied_namespace_header{"ManifestEditor/RemovesAnEmptiedNamespaceHeader", [] { + constexpr std::string_view source = R"([package] +name = "app" +version = "0.1.0" + +[dependencies.acme] +widget = "1.0.0" + +[build] +cxxflags = [] +)"; + auto removed = mcpp::manifest::remove_dependency_text(source, "acme", "widget"); + if (auto&& failed = expect(fatal(removed.has_value() && removed->has_value())); !failed) + failed << (removed ? std::string("nothing removed") : removed.error()); + expect(eq(**removed, std::string("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[build]\ncxxflags = []\n"))); +}}; + // An entry written as an inline table over several lines (TOML 1.1) is // replaced whole: replacing its first line alone left the rest of the old // value behind, and the edit was refused as an invalid manifest. diff --git a/tests/unit/test_modgraph.cpp b/tests/unit/test_modgraph.cpp index f66008feb..edae681bb 100644 --- a/tests/unit/test_modgraph.cpp +++ b/tests/unit/test_modgraph.cpp @@ -165,7 +165,11 @@ UTest an_entry_source_the_scanner_refuses_keeps_its_imports{"Scanner/AnEntrySour "#endif\n" "export import std;\n" "int main() {}\n"); - expect(fatal(!(scan_file(dir / "t.cpp", "pkg", mcpp::builtin_extension_table()).has_value()))); + // The conditional import is the compiler's to answer (mcpp#1026): the text + // scan marks the unit rather than refusing it, and its reading is partial. + auto scanned = scan_file(dir / "t.cpp", "pkg", mcpp::builtin_extension_table()); + expect(fatal(scanned.has_value())); + expect(scanned->importsFromCompiler); auto u = scan_entry_file(dir / "t.cpp", "pkg", mcpp::builtin_extension_table()); std::vector names; for (auto const& r : u.requires_) names.push_back(r.logicalName); @@ -636,17 +640,41 @@ UTest partition_import_with_dotted_module_name{"Scanner/PartitionImportWithDotte std::filesystem::remove_all(dir); }}; -UTest rejects_conditional_import{"Scanner/RejectsConditionalImport", [] { +// A CONDITIONAL IMPORT IS THE COMPILER'S TO ANSWER (mcpp#1026). The text scan +// marks the unit; the plan's answer gives its imports, and a scan with no +// answer names the unit rather than taking the text's partial reading. +UTest a_conditional_import_is_the_compilers_to_answer{"Scanner/AConditionalImportIsTheCompilersToAnswer", [] { auto dir = make_tempdir("mcpp-scanner"); - write(dir / "main.cpp", + write(dir / "src" / "main.cpp", "import std;\n" "#ifdef WANT_X\n" "import x;\n" "#endif\n" "int main(){}"); - auto r = scan_file(dir / "main.cpp", "pkg", mcpp::builtin_extension_table()); - expect(!r.has_value()); - expect(ne(r.error().message.find("conditional"), std::string::npos)); + auto r = scan_file(dir / "src" / "main.cpp", "pkg", mcpp::builtin_extension_table()); + expect(fatal(r.has_value())); + expect(r->importsFromCompiler); + + mcpp::manifest::Manifest m; + m.package.name = "pkg"; + m.modules.sources = {"src/*.cpp"}; + auto unanswered = scan_packages({PackageRoot{dir, m}}); + expect(fatal(eq(unanswered.errors.size(), 1u))); + expect(ne(unanswered.errors[0].message.find("preprocessor condition"), std::string::npos)); + + // The compiler's reading: `WANT_X` undefined, only `std`. + auto answered = scan_packages({PackageRoot{dir, m}}, {}, [](const SourceUnit& u) -> std::expected { + SourceUnit out = u; + out.requires_.erase(std::remove_if(out.requires_.begin(), out.requires_.end(), + [](auto const& q) { return q.logicalName == "x"; }), + out.requires_.end()); + return out; + }); + expect(fatal(answered.errors.empty())); + expect(fatal(eq(answered.graph.units.size(), 1u))); + std::vector names; + for (auto const& q : answered.graph.units[0].requires_) names.push_back(q.logicalName); + expect(eq(names, (std::vector{"std"}))); std::filesystem::remove_all(dir); }}; diff --git a/tests/unit/test_ninja_backend.cpp b/tests/unit/test_ninja_backend.cpp index c2c80b5c9..afa1a74b1 100644 --- a/tests/unit/test_ninja_backend.cpp +++ b/tests/unit/test_ninja_backend.cpp @@ -49,6 +49,17 @@ std::size_t count_words(std::string_view flags, std::string_view word) { return count; } +// A path as a node of the emitted graph: forward slashes; `$`, `:` and space escaped. +std::string ninja_node(const std::filesystem::path& path) { + std::string escaped; + for (char c : path.lexically_normal().generic_string()) { + if (c == ' ' || c == '$' || c == ':') + escaped.push_back('$'); + escaped.push_back(c); + } + return escaped; +} + std::string escaped_include_flag(const std::filesystem::path& path) { auto s = path.string(); std::string escaped; @@ -1280,14 +1291,16 @@ UTest std_artifacts_and_runtime_dlls_use_the_stage_rule{"NinjaBackend/StdArtifac // The std artifacts are fingerprint-scoped, so they carry the size-only // check: it needs no OPEN of the destination, which is what lets staging // survive a holder that denies reads (Windows FileShare.None). - expect(ne(ninja.find("build pcm.cache/std.pcm : stage_file " - "/cache/bmi/fp/pcm.cache/std.pcm\n" + // Each staged BMI also names its absolute spelling (SPEC-018 §1 item 6). + expect(ne(ninja.find("build pcm.cache/std.pcm | " + ninja_node(plan.outputDir / "pcm.cache/std.pcm") + + " : stage_file /cache/bmi/fp/pcm.cache/std.pcm\n" " verify = --verify size\n"), std::string::npos)) << ninja; expect(ne(ninja.find("build obj/std.o : stage_file /cache/bmi/fp/std.o\n" " verify = --verify size\n"), std::string::npos)) << ninja; // std.compat keeps its order-only dependency on the staged std BMI. - expect(ne(ninja.find("build pcm.cache/std.compat.pcm : stage_file " - "/cache/bmi/fp/pcm.cache/std.compat.pcm | pcm.cache/std.pcm"), std::string::npos)) << ninja; + expect(ne(ninja.find("build pcm.cache/std.compat.pcm | " + ninja_node(plan.outputDir / "pcm.cache/std.compat.pcm") + + " : stage_file /cache/bmi/fp/pcm.cache/std.compat.pcm | pcm.cache/std.pcm"), + std::string::npos)) << ninja; // Windows DLL deployment shares the rule — and therefore the // skip-if-equivalent behaviour that keeps a loaded DLL from failing a build. // But NOT the size-only shortcut: a rebuilt DLL keeps its size (PE sections @@ -1583,7 +1596,9 @@ UTest a_cache_fill_asks_for_every_bmi_of_its_package{"NinjaBackend/ACacheFillAsk }); auto ninja = emit_ninja_string(plan); - expect(fatal(ne(ninja.find("build pcm.cache/dep/0011aabb/dep.time.pcm : cxx_precompile"), std::string::npos))) + expect(fatal(ne(ninja.find("build pcm.cache/dep/0011aabb/dep.time.pcm | " + + ninja_node(plan.outputDir / "pcm.cache/dep/0011aabb/dep.time.pcm") + + " : cxx_precompile"), std::string::npos))) << "the fixture is not the two-phase shape\n" << ninja; auto at = ninja.rfind("\ndefault "); expect(fatal(ne(at, std::string::npos))) << ninja; @@ -1600,6 +1615,44 @@ UTest a_cache_fill_asks_for_every_bmi_of_its_package{"NinjaBackend/ACacheFillAsk expect(eq(line.find(" obj/main.o"), std::string::npos)) << "a unit that fills nothing is in the fills: " << line; }}; +// mcpp#1015: clang's depfile names a BMI by the absolute `-fprebuilt-module-path` +// and the graph by its relative path. Two nodes for one file let a build with no +// edit, after an edit, compile the importer of an importer. Under clang the edge +// that writes a BMI states both spellings; GCC's depfile names the relative one. +UTest a_bmi_is_one_node_in_both_its_spellings{"NinjaBackend/ABmiIsOneNodeInBothItsSpellings", [] { + auto edge_of = [](mcpp::toolchain::CompilerId compiler, const std::string& bmiFile, + std::filesystem::path& outputDir) { + auto plan = minimal_plan(); + plan.toolchain.compiler = compiler; + if (compiler == mcpp::toolchain::CompilerId::Clang) { + plan.toolchain.version = "23.1.3"; + plan.toolchain.binaryPath = "/usr/bin/clang++"; + plan.scanDepsPath = "/usr/bin/clang-scan-deps"; + } + plan.compileUnits.push_back({ + .source = "src/c.cppm", + .kind = mcpp::SourceKind::ModuleInterface, + .object = "obj/c.m.o", + .packageName = "objc_rule_test", + .providesModule = "c", + .bmiFile = bmiFile, + }); + outputDir = plan.outputDir; + auto ninja = emit_ninja_string(plan); + auto at = ninja.find("\nbuild obj/c.m.o "); + return at == std::string::npos ? ninja : ninja.substr(at + 1, ninja.find('\n', at + 1) - at - 1); + }; + + std::filesystem::path out; + auto clang = edge_of(mcpp::toolchain::CompilerId::Clang, "c.pcm", out); + expect(ne(clang.find("build obj/c.m.o | pcm.cache/c.pcm " + ninja_node(out / "pcm.cache/c.pcm") + " : "), + std::string::npos)) << clang; + + auto gcc = edge_of(mcpp::toolchain::CompilerId::GCC, "c.gcm", out); + expect(ne(gcc.find("build obj/c.m.o | gcm.cache/c.gcm : "), std::string::npos)) << gcc; + expect(eq(gcc.find(ninja_node(out)), std::string::npos)) << gcc; +}}; + // A cached unit whose cachedObject was never filled in is a bug upstream, not a // reason to emit a stage edge with an empty input — it must fall back to being // compiled rather than producing an unbuildable graph. diff --git a/tests/unit/test_p1689.cpp b/tests/unit/test_p1689.cpp index 75957b71b..a4dfa95d1 100644 --- a/tests/unit/test_p1689.cpp +++ b/tests/unit/test_p1689.cpp @@ -149,3 +149,35 @@ UTest rejects_missing_rules{"P1689Parse/RejectsMissingRules", [] { expect(!r); expect(ne(r.error().find("rules"), std::string::npos)); }}; + +// The scan's words are constructed once (mcpp#1026). The build's scan edge joins them, and its +// command is the text it was before the words became a list; the plan's scan of a unit hands +// them to the program as arguments, a path with a space one argument, no shell quoting in them. +UTest the_edge_joins_the_scan_words{"P1689Scan/TheEdgeJoinsTheScanWords", [] { + const auto gcc = scan_command({.prefix = "$launcher ", .driver = "$cxx_driver @$out.rsp", + .flags = {"$cxxflags", "$unit_cxxflags"}, .lang = {"$unit_lang"}, + .in = "$in", .out = "$out", .depsTarget = "$deps_target", + .depFile = "$out.dep", .scratch = "$out.scan"}); + expect(eq(gcc, std::string("$launcher $cxx_driver @$out.rsp $cxxflags $unit_cxxflags -fmodules " + "-fdeps-format=p1689r5 -fdeps-file=$out -fdeps-target=$deps_target " + "-M -MM -MF $out.dep $unit_lang -E $in -o $out.scan"))); + const auto clang = scan_command({.driver = "$cxx_driver", .scanDeps = "$scan_deps", + .flags = {"$cxxflags", "$unit_cxxflags"}, .lang = {"$unit_lang"}, + .in = "$in", .out = "$out", .compileTarget = "$compile_target"}); + expect(eq(clang, std::string("$scan_deps -format=p1689 -o $out -- $cxx_driver $cxxflags " + "$unit_cxxflags $unit_lang -c $in -o $compile_target"))); +}}; + +UTest the_plan_passes_the_scan_words_as_arguments{"P1689Scan/ThePlanPassesTheScanWordsAsArguments", [] { + const auto argv = scan_words({.driver = "C:/llvm/bin/clang++.exe", .scanDeps = "C:/llvm/bin/clang-scan-deps.exe", + .flags = {"-std=c++23", "-IC:/My Project/include"}, .lang = {"-x", "c++-module"}, + .in = "C:/My Project/src/m.cppm", .out = "C:/t/m.ddi", .compileTarget = "C:/t/m.o"}); + const std::vector expected{ + "C:/llvm/bin/clang-scan-deps.exe", "-format=p1689", "-o", "C:/t/m.ddi", "--", + "C:/llvm/bin/clang++.exe", "-std=c++23", "-IC:/My Project/include", "-x", "c++-module", + "-c", "C:/My Project/src/m.cppm", "-o", "C:/t/m.o"}; + std::string joined; + for (auto const& word : argv) joined += "[" + word + "]"; + expect(argv == expected) << joined; + for (auto const& word : argv) expect(eq(word.find('\''), std::string::npos)) << word; +}}; diff --git a/tests/unit/test_platform_env.cpp b/tests/unit/test_platform_env.cpp index 575a3180d..c492f543a 100644 --- a/tests/unit/test_platform_env.cpp +++ b/tests/unit/test_platform_env.cpp @@ -91,3 +91,20 @@ UTest prepend_path_list_with_no_inherited_value_is_just_the_dirs{"PlatformEnv/Pr std::vector dirs{"/a", "/b"}; expect(eq(mcpp::runtime::launch_env::prepend_path_list("LD_LIBRARY_PATH", dirs), join({host("/a"), host("/b")}))); }}; + +// THE PATH OF EVERY CHILD (mcpp#926, design 2026-11-27 §4.2): the tools the +// graph states, then the stated environment's `bin`, then the PATH this +// invocation was started with; a directory named twice is named once, and with +// nothing stated the child inherits the PATH as it is. +UTest child_path_puts_the_stated_tools_first{"PlatformEnv/ChildPathPutsTheStatedToolsFirst", [] { + const auto& inherited = mcpp::runtime::launch_env::inherited_path(); + std::vector tools{"/tools/a/bin", "/tools/b/bin", "/tools/a/bin"}; + const auto value = mcpp::runtime::launch_env::child_path(tools, "/env/bin"); + const auto stated = join({host("/tools/a/bin"), host("/tools/b/bin"), host("/env/bin")}); + expect(eq(value, inherited.empty() ? stated : stated + sep() + inherited)); + // The environment's `bin` is not named twice when a stated tool is there. + std::vector withEnv{"/env/bin"}; + const auto once = mcpp::runtime::launch_env::child_path(withEnv, "/env/bin"); + expect(eq(once, inherited.empty() ? host("/env/bin") : host("/env/bin") + sep() + inherited)); + expect(eq(mcpp::runtime::launch_env::child_path({}, {}), std::string())); +}}; diff --git a/tests/unit/test_runner_lookup.cpp b/tests/unit/test_runner_lookup.cpp index 8a3d24226..626cdcc9b 100644 --- a/tests/unit/test_runner_lookup.cpp +++ b/tests/unit/test_runner_lookup.cpp @@ -151,6 +151,83 @@ UTest spawn_failed_message_is_verbatim{"RunnerLookup/SpawnFailedMessageIsVerbati expect(eq(msg.find("runner = ["), std::string::npos)) << msg; // no runner advice }}; +// A SCRIPT'S `#!` LINE, READ AS THE KERNEL READS IT (#621). The interpreter is +// the first word; through `env`, the program is the first word that is neither +// `-S` nor an assignment. A form read without certainty names no program. +UTest a_shebang_names_its_interpreter{"RunnerLookup/AShebangNamesItsInterpreter", [] { + auto direct = parse_script_interpreter("#!/bin/sh -e\nexit 0\n"); + expect(fatal(direct.has_value())); + expect(eq(direct->program, std::filesystem::path("/bin/sh"))); + expect(eq(direct->viaEnv, std::string{})); + expect(eq(direct->line, std::string("#!/bin/sh -e"))); + + auto viaEnv = parse_script_interpreter("#!/usr/bin/env node\r\n// emsdk\n"); + expect(fatal(viaEnv.has_value())); + expect(eq(viaEnv->program, std::filesystem::path("/usr/bin/env"))); + expect(eq(viaEnv->viaEnv, std::string("node"))); + expect(eq(viaEnv->line, std::string("#!/usr/bin/env node"))); + + auto split = parse_script_interpreter("#! /usr/bin/env -S NODE_OPTIONS=x node --flag\n"); + expect(fatal(split.has_value())); + expect(eq(split->viaEnv, std::string("node"))); +}}; + +UTest an_uncertain_shebang_names_no_program{"RunnerLookup/AnUncertainShebangNamesNoProgram", [] { + expect(!parse_script_interpreter("\x7f" "ELF\x02\x01\x01").has_value()); + expect(!parse_script_interpreter("#!\n").has_value()); + expect(!parse_script_interpreter("#!node\n").has_value()); // not absolute + expect(!parse_script_interpreter("#!/usr/bin/env\n").has_value()); // no program + expect(!parse_script_interpreter("#!/usr/bin/env -i node\n").has_value()); + expect(!parse_script_interpreter("#!/usr/bin/env -u X node\n").has_value()); +}}; + +UTest a_script_whose_interpreter_is_missing_is_noted{"RunnerLookup/AScriptWhoseInterpreterIsMissingIsNoted", [] { + auto root = fresh_root("mcpp-runner-lookup-shebang-1"); + auto env = make_exe(root / "sys", "env"); + auto script = root / "app.js"; + { std::ofstream o(script); o << "#!" << env.string() << " node-absent\nconsole.log(1)\n"; } + auto note = missing_interpreter_note(script, (root / "path").string()); + expect(ne(note.find(script.string()), std::string::npos)) << note; + expect(ne(note.find("`#!" + env.string() + " node-absent`"), std::string::npos)) << note; + expect(ne(note.find("'node-absent' is not on PATH"), std::string::npos)) << note; + expect(ne(note.find(".mcpp-toolchain.json"), std::string::npos)) << note; + expect(ne(note.find("mcpp index update"), std::string::npos)) << note; + expect(ne(note.find("mcpp toolchain remove "), std::string::npos)) << note; + expect(ne(note.find("mcpp toolchain install "), std::string::npos)) << note; + expect(ne(note.find("help: "), std::string::npos)) << note; + + // The build's managed toolchain is what the commands name. + auto named = missing_interpreter_note(script, (root / "path").string(), "emsdk@6.0.9"); + expect(ne(named.find("`mcpp toolchain remove emsdk@6.0.9`"), std::string::npos)) << named; + expect(ne(named.find("`mcpp toolchain install emsdk@6.0.9`"), std::string::npos)) << named; + expect(named.find("") == std::string::npos) << named; + + // ...and once the program is on the PATH the artefact receives, nothing. + make_exe(root / "path", "node-absent"); + expect(eq(missing_interpreter_note(script, (root / "path").string()), std::string{})); +}}; + +UTest a_missing_interpreter_path_is_noted{"RunnerLookup/AMissingInterpreterPathIsNoted", [] { + auto root = fresh_root("mcpp-runner-lookup-shebang-2"); + auto script = root / "tool.sh"; + { std::ofstream o(script); o << "#!" << (root / "absent" / "sh").string() << "\n"; } + auto note = missing_interpreter_note(script, ""); + expect(ne(note.find("'" + (root / "absent" / "sh").string() + "' is not an executable file"), + std::string::npos)) << note; +}}; + +UTest a_program_or_a_found_interpreter_is_not_noted{"RunnerLookup/AProgramOrAFoundInterpreterIsNotNoted", [] { + auto root = fresh_root("mcpp-runner-lookup-shebang-3"); + auto sh = make_exe(root / "sys", "sh"); + auto found = root / "found.sh"; + { std::ofstream o(found); o << "#!" << sh.string() << "\nexit 0\n"; } + expect(eq(missing_interpreter_note(found, ""), std::string{})); + auto binary = root / "app"; + { std::ofstream o(binary, std::ios::binary); o << "\x7f" "ELF"; } + expect(eq(missing_interpreter_note(binary, ""), std::string{})); + expect(eq(missing_interpreter_note(root / "absent", ""), std::string{})); +}}; + #else namespace { diff --git a/tests/unit/test_scaffold.cpp b/tests/unit/test_scaffold.cpp index bba60497b..8698b4706 100644 --- a/tests/unit/test_scaffold.cpp +++ b/tests/unit/test_scaffold.cpp @@ -381,7 +381,8 @@ widget = "1.0.0" ss << is.rdbuf(); text = ss.str(); } - expect(ne(text.find("[dependencies.acme]\nwidget = { version = \"2.0.0\", features = [\"gui\"] }"), std::string::npos)); + // No form of the namespace yet: the dotted key (mcpp#964, SPEC-004 §17). + expect(ne(text.find("[dependencies]\nacme.widget = { version = \"2.0.0\", features = [\"gui\"] }"), std::string::npos)); expect(ne(text.find("[dependencies.compat]\nwidget = \"1.0.0\""), std::string::npos)); auto again = mcpp::scaffold::inject_self_dependency( diff --git a/tests/unit/test_target_scalar_keys.cpp b/tests/unit/test_target_scalar_keys.cpp index 197aefd6a..d31eeae1c 100644 --- a/tests/unit/test_target_scalar_keys.cpp +++ b/tests/unit/test_target_scalar_keys.cpp @@ -178,9 +178,29 @@ std::string target_loop_region(const std::string& source) { return source.substr(begin, end - begin); } +// The tables the one enumeration of dependency tables walks (mcpp#962, +// modules/manifest/src/dependency_tables.cppm): the names its +// `dependency_table_name` returns. +std::vector enumerated_dependency_tables() { + auto source = read_file(repo_root() / "modules" / "manifest" / "src" / "dependency_tables.cppm"); + std::vector out; + auto begin = source.find("constexpr std::string_view dependency_table_name("); + if (begin == std::string::npos) return out; + auto end = source.find("\n}\n", begin); + const std::string ret = "return \""; + for (auto pos = source.find(ret, begin); pos != std::string::npos && pos < end; pos = source.find(ret, pos)) { + const auto nameStart = pos + ret.size(); + const auto nameEnd = source.find('"', nameStart); + auto name = source.substr(nameStart, nameEnd - nameStart); + if (std::ranges::find(out, name) == out.end()) out.push_back(std::move(name)); + pos = nameEnd; + } + return out; +} + // Every sub-table the loop body reads: a `body.find("")` whose first type -// check is `is_table()`, and every `read_deps("", ...)`, the helper the -// three conditional dependency tables go through. +// check is `is_table()`, and every table the dependency enumeration walks when +// the body calls it (`dependency_tables_in`). std::vector parsed_target_tables(const std::string& region) { std::vector out; const std::string needle = "body.find(\""; @@ -196,13 +216,8 @@ std::vector parsed_target_tables(const std::string& region) { if (classify(region, hits[i].first, nextPos) == Kind::Table) out.push_back(hits[i].second); } - const std::string helper = "read_deps(\""; - for (std::size_t pos = 0; (pos = region.find(helper, pos)) != std::string::npos;) { - std::size_t nameStart = pos + helper.size(); - std::size_t nameEnd = region.find('"', nameStart); - out.push_back(region.substr(nameStart, nameEnd - nameStart)); - pos = nameEnd; - } + if (region.find("dependency_tables_in(") != std::string::npos) + for (auto& name : enumerated_dependency_tables()) out.push_back(std::move(name)); return out; }