From 56e2cb049a21efa11ca490c42021d5b68395c666 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 15:44:33 +0800 Subject: [PATCH 01/18] docs/: a numbered layout with an index, and every cross-reference follows --- ...26-09-26-plugins-0.15-architecture-plan.md | 2 +- ...6-09-27-mcpp-2026.9.27.1-ecosystem-plan.md | 4 +- .../docs/2026-09-27-plugins-0.15.2-plan.md | 2 +- ...1-ecosystem-build-plugin-framework-plan.md | 6 +- .agents/docs/2026-11-24-rules-qml-design.md | 20 +++---- .github/CODEOWNERS | 14 +++++ .github/scripts/check-toolchain-lanes.sh | 2 +- .github/workflows/ci.yml | 6 +- deps/cmake.cppm | 4 +- deps/vcpkg.cppm | 2 +- ...ne-and-rules.md => 00-engine-and-rules.md} | 0 ...evelopment.md => 01-plugin-development.md} | 2 +- docs/{tool-sources.md => 02-tool-sources.md} | 0 docs/{rules.md => 10-rules.md} | 2 +- docs/{rules-qt.md => 11-rules-qt.md} | 2 +- docs/{rules-qml.md => 12-rules-qml.md} | 2 +- docs/{tools-embed.md => 20-tools-embed.md} | 2 +- docs/{tools-island.md => 21-tools-island.md} | 0 docs/{tools-steps.md => 22-tools-steps.md} | 0 docs/{dist.md => 30-dist.md} | 2 +- docs/{dist-apple.md => 31-dist-apple.md} | 2 +- docs/{dist-apk.md => 32-dist-apk.md} | 2 +- docs/{deps.md => 40-deps.md} | 0 docs/README.md | 56 +++++++++++++++++++ mcpp.toml | 6 +- rules/qt.cppm | 2 +- src/platform.cppm | 2 +- src/tool.cppm | 2 +- tests/qt-sdk-consumer/mcpp.toml | 2 +- 29 files changed, 109 insertions(+), 39 deletions(-) create mode 100644 .github/CODEOWNERS rename docs/{engine-and-rules.md => 00-engine-and-rules.md} (100%) rename docs/{plugin-development.md => 01-plugin-development.md} (99%) rename docs/{tool-sources.md => 02-tool-sources.md} (100%) rename docs/{rules.md => 10-rules.md} (99%) rename docs/{rules-qt.md => 11-rules-qt.md} (98%) rename docs/{rules-qml.md => 12-rules-qml.md} (96%) rename docs/{tools-embed.md => 20-tools-embed.md} (98%) rename docs/{tools-island.md => 21-tools-island.md} (100%) rename docs/{tools-steps.md => 22-tools-steps.md} (100%) rename docs/{dist.md => 30-dist.md} (98%) rename docs/{dist-apple.md => 31-dist-apple.md} (51%) rename docs/{dist-apk.md => 32-dist-apk.md} (99%) rename docs/{deps.md => 40-deps.md} (100%) create mode 100644 docs/README.md diff --git a/.agents/docs/2026-09-26-plugins-0.15-architecture-plan.md b/.agents/docs/2026-09-26-plugins-0.15-architecture-plan.md index 903b03a..356fd35 100644 --- a/.agents/docs/2026-09-26-plugins-0.15-architecture-plan.md +++ b/.agents/docs/2026-09-26-plugins-0.15-architecture-plan.md @@ -125,7 +125,7 @@ rules-qt 的 SDK 查找顺序为 `options::root` → `QT_ROOT_DIR`(不采用 ` ## 6. 规范与文档 - **README**:精简为约 100 行(原 1113 行),开篇陈述 §0 的总纲;各成员细节移至 `docs/<成员>.md`。 -- **`docs/plugin-development.md`(新增)**:包含职责分层表和十条规则: +- **`docs/01-plugin-development.md`(新增)**:包含职责分层表和十条规则: 1. 机制而非策略; 2. feature 只表达机制; 3. build.mcpp 为先的三级配置; diff --git a/.agents/docs/2026-09-27-mcpp-2026.9.27.1-ecosystem-plan.md b/.agents/docs/2026-09-27-mcpp-2026.9.27.1-ecosystem-plan.md index 45d4a95..5a3bfeb 100644 --- a/.agents/docs/2026-09-27-mcpp-2026.9.27.1-ecosystem-plan.md +++ b/.agents/docs/2026-09-27-mcpp-2026.9.27.1-ecosystem-plan.md @@ -144,11 +144,11 @@ A1 至 A4 可以并行。B3 不依赖 B2:旧版 xlings 忽略 revision 字段 - **C0 预验证:** `ci.yml` 的 `workflow_dispatch` 接受 mcpp 的分支名。在 B4a 之后以该分支运行 plugins 全部 CI,mcpp 发布前就能发现生态回归。 - **C1 内容:** - - 引擎最低版本改为 2026.9.27.1:`ci.yml:54`、README 功能表、`docs/deps.md` 与 `docs/rules-qt.md` 的版本说明。 + - 引擎最低版本改为 2026.9.27.1:`ci.yml:54`、README 功能表、`docs/40-deps.md` 与 `docs/11-rules-qt.md` 的版本说明。 - 删除 `rules/qt.cppm:365-374` 的静默分支:#715 修复后,引擎不再为这种包合成程序。fixture `qt-import-only` 改为断言"没有构建程序运行",作为引擎行为的回归测试。 - 四个 Qt fixture 的 `cxx_runtime = "toolchain-coupled"` 从 `[build]` 移到 `[target.x86_64-linux-gnu]` 与 `[target.aarch64-linux-gnu]`,同时成为 #704 的端到端验证。 - `check-deps-and-qt.sh` 中七处 `--profile dev` 是 #705 的规避手段。逐处去掉,并在三平台上确认第二次构建不重新安装。 - - `docs/rules-qt.md:62、98` 中关于 #715、#704 的规避说明改写为现行行为。 + - `docs/11-rules-qt.md:62、98` 中关于 #715、#704 的规避说明改写为现行行为。 - **发布:** 按 mcpp-plugins 发布流程:tag、GitCode 镜像、mcpp-index 登记。 ### 3.5 阶段 D:沙箱真实验证 diff --git a/.agents/docs/2026-09-27-plugins-0.15.2-plan.md b/.agents/docs/2026-09-27-plugins-0.15.2-plan.md index 950b2cf..f285fd4 100644 --- a/.agents/docs/2026-09-27-plugins-0.15.2-plan.md +++ b/.agents/docs/2026-09-27-plugins-0.15.2-plan.md @@ -41,7 +41,7 @@ D1 的索引改动只是删除冗余键;消费方的切换不依赖它先合 ### 2.3 mcpp-plugins 0.15.2:一个 PR - `rules/qt.cppm`:缺少 SDK 时的提示改为 `"xim:qt-base" = "6.11.1"`。 -- 测试 fixture(qt-consumer、qt-widgets-consumer)与 `docs/rules-qt.md`、README:版本改为 `6.11.1`。 +- 测试 fixture(qt-consumer、qt-widgets-consumer)与 `docs/11-rules-qt.md`、README:版本改为 `6.11.1`。 - `ci.yml`:沙箱缓存 key 的前缀加代次(`mcpp-sandbox-v2-…`),`restore-keys` 同步修改。仅 fixture 哈希变化不够:现有 `restore-keys` 前缀会恢复持有旧 6.11.1 的缓存。 - 验收:三平台 CI 全绿。其中 Linux 的 widgets 打包检查要确认新缓存下装出的 `6.11.1` 带有运行时闭包(libdbus、xkbcommon、fontconfig),这正是 D1 的实证。 - 发布:tag v0.15.2、GitCode 镜像(sha256 比对)、mcpp-index 登记。 diff --git a/.agents/docs/2026-10-01-ecosystem-build-plugin-framework-plan.md b/.agents/docs/2026-10-01-ecosystem-build-plugin-framework-plan.md index 21ae403..37fc250 100644 --- a/.agents/docs/2026-10-01-ecosystem-build-plugin-framework-plan.md +++ b/.agents/docs/2026-10-01-ecosystem-build-plugin-framework-plan.md @@ -216,8 +216,8 @@ sha256 `40b9fa16be5628a5d277824f961faa33dadbf84d9520cff9fe2aeb9b0b217ebf`(下载 ## 4.1 面向两类读者的参考文档(2026-10-02 追加) -`docs/tool-sources.md`(372 行,README 与 plugin-development.md 各有入口)。写它的理由是: -机制此前在三处分别被记下——引擎的键在 mcpp docs/23、模块的接口在 plugin-development.md、 +`docs/02-tool-sources.md`(372 行,README 与 01-plugin-development.md 各有入口)。写它的理由是: +机制此前在三处分别被记下——引擎的键在 mcpp docs/23、模块的接口在 01-plugin-development.md、 每个成员的选项在各自页面——而**没有一处说出必须同时成立的那两半**: `build.mcpp` 里的 `tool::choice` 只有在插件把该载荷声明为 `provision = "on-request"` 时才等于 「不下载」,因为 eager 的载荷在任何构建程序运行之前就已供给。这正是 mcpp#755 的原始症状, @@ -291,7 +291,7 @@ framework-lab 的 8 个用例在 ubuntu-24.04、macos-15、windows-2022 上全 | 用户体验 | 每个显式来源一行,带类与 `file:line`;每条拒绝都列出命名它的四种方式;`considered` 记下每一层问过什么、答了什么 | | 兼容性 | **未迁移的第三方插件无需改动即受益**(覆盖发生在引擎层,`xpkg_dir` 直接回答);成员的历史环境变量保留;地板不满足时的拒绝现在会点名地板与升级方式(第 7 处发现) | | 跨平台 | Linux / macOS / Windows 全绿。跨平台本身贡献了 5 处发现:响应文件的两种 tokenize 语法、Darwin 的 `environ`、宿主自己补的 `.exe` 后缀、Apple 链接形状拿不到 `--ld-path`、gcc 16 的 `always_inline` 拒绝 | -| 一致性 | 优先级只写两份(核心、L2);中英文档结构一一对应;`docs/tool-sources.md` 补上了此前三处分散记述都没说出的那一对条件 | +| 一致性 | 优先级只写两份(核心、L2);中英文档结构一一对应;`docs/02-tool-sources.md` 补上了此前三处分散记述都没说出的那一对条件 | | 无感升级 | 不写任何新键的工程行为与输出不变,由既有 e2e 与 framework-lab 的 `default` 用例断言;插件 0.19.0 的成员在默认路径上下载与输出不变 | | 测试覆盖 | 单测 144(新增 21);e2e 873-877 加 875 里 gcc 拒绝的反例;`plugin-logic` 29 例;framework-lab 10 例 × 3 平台;toolchain-lab 8 例 × 3 平台;CI 判据读 `resolution.json`,所以在已装载荷的 runner 上也能断言「这次没要求它」 | diff --git a/.agents/docs/2026-11-24-rules-qml-design.md b/.agents/docs/2026-11-24-rules-qml-design.md index 3b0f5fa..454fd24 100644 --- a/.agents/docs/2026-11-24-rules-qml-design.md +++ b/.agents/docs/2026-11-24-rules-qml-design.md @@ -178,7 +178,7 @@ Windows 与 macOS 没有实测机器:凡依赖它们的结论都标"推断", - QML:部署 `QtQuick/Layouts` 的插件后,包里没有 `libQt6QuickLayouts.so.6`;Controls 的 `libQt6QuickControls2Impl.so.6` 同样缺。 - **现有 `rules-qt` 的平台插件也有同一缺口**:对已部署 `platforms/` 的打包目录逐个读依赖,缺 `libQt6XcbQpa.so.6`(`libqxcb.so`)、`libQt6WaylandClient.so.6`(`libqwayland.so`)、`libQt6EglFSDeviceIntegration.so.6`(`libqeglfs.so`)。真实 X11 桌面上,xcb 平台插件会因缺 `libQt6XcbQpa` 加载失败;现有 CI 只在 offscreen 下运行,所以没发现。(我没有显示环境,只在静态依赖层面确认,运行层面的失败是推断。) -**与仓库规则的关系**:`docs/plugin-development.md` 的规则 4(运行时闭包属于提供二进制的包;插件只命名库目录)与规则 8(引擎缺口要报告,不要打补丁;已有的补丁要在文档里记录 issue 号并在引擎支持后移除)。因此: +**与仓库规则的关系**:`docs/01-plugin-development.md` 的规则 4(运行时闭包属于提供二进制的包;插件只命名库目录)与规则 8(引擎缺口要报告,不要打补丁;已有的补丁要在文档里记录 issue 号并在引擎支持后移除)。因此: 1. **向 mcpp 提 issue**(你同意后已提交):**mcpp-community/mcpp#1011**,建议能力是"`mcpp pack` 把 `role: library` 的已部署文件也作为闭包的根"。正文见 §15。提交前搜索过,没有重复(相关的 #615、#634、#630、#701 都是已关闭的、讨论别的缺口)。 2. **本 PR 带 `link_plugin_libs` 补丁,按规则 8 标注**(这是你的决定:先 workaround,用户与开发者层面无感,mcpp 修复后自动没问题): @@ -193,7 +193,7 @@ Windows 与 macOS 没有实测机器:凡依赖它们的结论都标"推断", // note: idempotent: linking a library the engine also stages changes nothing ``` - `docs/rules-qt.md`、`docs/rules-qml.md` 各有"引擎缺口"一节,写 mcpp#1011 与移除条件(规则 8);README 不提。 + `docs/11-rules-qt.md`、`docs/12-rules-qml.md` 各有"引擎缺口"一节,写 mcpp#1011 与移除条件(规则 8);README 不提。 - **自动退场**:补丁是幂等的——引擎一旦把已部署库的依赖纳入闭包,我们多链的同一批库对结果没有任何影响(同一个文件、同一个目的地)。引擎没有向 build 程序暴露版本接口(`hostprogram.cppm` 只有 `package_version` 等,已查),所以不做版本门;退场靠下一条。 - **金丝雀**:`qml-deploy` 的脚本多做一次构建:用环境变量让 fixture 的 `build.mcpp` 设 `plugin_closure = false`,打包,再用读取器检查闭包。若这次包里**已经**没有缺库,说明引擎修好了,脚本打印 `NOTICE: the engine now closes deployed libraries (mcpp#1011); remove the plugin_closure workaround` 并以成功退出(不失败,是提示);仍缺库则打印 `ok: the engine gap still exists (mcpp#1011)`。引擎修好后,CI 日志里会自动出现这条提示,不需要有人记得。 - **链接旗标要防"未引用的库被丢弃"**(评审指出的风险,已用 lld 实测):Linux 上 lld 默认保留按全路径给出的库(NEEDED 保留),但加 `--as-needed`(Ubuntu 的 gcc 默认就是)后被丢弃(NEEDED 为 0);用 `-Wl,--push-state,--no-as-needed <库> -Wl,--pop-state` 包住后保留(实测,且包外的库仍按 `--as-needed` 处理)。macOS:`ld64.lld` 默认保留,`-dead_strip_dylibs` 丢弃,`-needed_library <路径>` 保留(实测,直接用 `ld64.lld` 与手工构建的 dylib)。因此补库在 ELF 上用 push/pop 包住,在 Mach-O 上用 `-needed_library`。 @@ -437,7 +437,7 @@ Qml2Imports = qml Translations = # 仅在不是默认的 translations 时写出 ``` -并 `deploy` 到 `.`。检测到项目自己的 `qt.conf` 时不写(Q3)。副作用见 Q3,写进 `docs/rules-qml.md`。 +并 `deploy` 到 `.`。检测到项目自己的 `qt.conf` 时不写(Q3)。副作用见 Q3,写进 `docs/12-rules-qml.md`。 **Qt Quick 所需的插件目录**用一个独立字段 `options::quick_plugins`,与 `qt.deploy_plugins` 取并集,而不是"检测 `deploy_plugins` 是否为默认值再替换"(`std::vector` 分不清"没设置"和"设成了默认值",评审指出)。`quick_plugins` 的默认值:Linux `xcbglintegrations`、`platforminputcontexts`、`imageformats`;Windows/macOS `imageformats`、`platforminputcontexts`(目录不存在则只是 `rules-qt` 已有的警告)。用户把它设为空即不加。**这一项是推断**(真实 GL 窗口无法在无显示环境测试),由打包清单断言与 offscreen 运行约束,可按 CI 调整。`plugin_closure` 在两个规则里默认都是 `true`,不存在"未设置"问题。 @@ -547,10 +547,10 @@ PE 与 Mach-O **读取器**的正确性已用真实构建的样本验证(样 | `src/binary.cppm` | 新增(`mcpp.plugins.binary`) | | `rules/qt.cppm` | §7 的 a–f;头注释增加"见 `mcpp.rules.qml`" | | `mcpp.toml` | `version` 0.26.1 → 0.27.0;`[features.plugins-binary]`、`[features.rules-qml]`;`rules-qt` 的 `implies` 增加 `plugins-binary`;`src/plugins.cppm` 的版本常量同步 | -| `docs/rules-qml.md` | 新增:开头一段摘要,随后用法、选项表、动作清单、部署与闭包、`qt.conf` 副作用、限制(§1 非目标)、平台表、"引擎缺口"一节(同上);遵守 `plugin-development.md` 规则 10 | -| `docs/rules-qt.md` | `moc_json`、`moc_includes`、`compile_ex`、`i18n.extensions`、`plugin_closure`;新增"引擎缺口"一节(平台插件的闭包缺口、issue 号、移除条件、金丝雀);指向 `rules-qml` | -| `docs/engine-and-rules.md` | `rules-qml` 不认领扩展名、不写 `rule_module` 的原因 | -| `docs/plugin-development.md` | §3 的分层表加入 L2 单元 `mcpp.plugins.binary`;规则 8 的"已有补丁"一节指向 `check-engine-gaps.sh` | +| `docs/12-rules-qml.md` | 新增:开头一段摘要,随后用法、选项表、动作清单、部署与闭包、`qt.conf` 副作用、限制(§1 非目标)、平台表、"引擎缺口"一节(同上);遵守 `01-plugin-development.md` 规则 10 | +| `docs/11-rules-qt.md` | `moc_json`、`moc_includes`、`compile_ex`、`i18n.extensions`、`plugin_closure`;新增"引擎缺口"一节(平台插件的闭包缺口、issue 号、移除条件、金丝雀);指向 `rules-qml` | +| `docs/00-engine-and-rules.md` | `rules-qml` 不认领扩展名、不写 `rule_module` 的原因 | +| `docs/01-plugin-development.md` | §3 的分层表加入 L2 单元 `mcpp.plugins.binary`;规则 8 的"已有补丁"一节指向 `check-engine-gaps.sh` | | `.github/scripts/check-engine-gaps.sh` | 新增(Q9 的标记检查),并接入现有 `check-compat-retirement.sh` 所在的步骤 | | `README.md` | Members 表增加 `rules-qml`(mcpp 下限列 2026.10.1.3,注明整个包需要 2026.10.30.1、最低验证 2026.10.31.3);`plugins-binary` 进"通用库"一段;示例版本号 | | `tests/plugin-logic/…` | §10.1 | @@ -564,7 +564,7 @@ PE 与 Mach-O **读取器**的正确性已用真实构建的样本验证(样 1. `mcpp.plugins.binary` 与单测(合成样本、截断扫描)。 2. `rules-qt`:`moc_json`、`moc_includes`、`compile_ex`、导出函数,`plugin-logic` 的"现有 argv 不变"用例(先证明零回归)。 -3. `rules-qt`:`link_plugin_libs`、`plugin_closure`(默认开,带 `ENGINE-GAP WORKAROUND` 标记)、`check-engine-gaps.sh` 与对应单测(单独一个提交;`docs/rules-qt.md` 的"引擎缺口"一节随它提交,便于你单独审这一处行为变更)。 +3. `rules-qt`:`link_plugin_libs`、`plugin_closure`(默认开,带 `ENGINE-GAP WORKAROUND` 标记)、`check-engine-gaps.sh` 与对应单测(单独一个提交;`docs/11-rules-qt.md` 的"引擎缺口"一节随它提交,便于你单独审这一处行为变更)。 4. `rules-qml` 的模块链路(§6),及其 `plugin-logic` 用例。 5. 部署:文本闭包、`qt.conf`、补库(§8)及用例。 6. `qsb`、`qmllint`、`lupdate` 扩展。 @@ -616,14 +616,14 @@ PE 与 Mach-O **读取器**的正确性已用真实构建的样本验证(样 | # | 意见(摘要) | 核实 | 处理 | |---|---|---|---| -| 1 | 闭包补丁违反 `plugin-development.md` 规则 4、8;建议不打补丁、默认关或放进带到期日的 `compat/` | 属实:规则 8 原文是"引擎缺口要报告,不打补丁" | **你的决定**:先 workaround、默认开、无感、引擎修好后自动无事。我采纳了其中的"标注与强制移除"思想,做成与 `compat/` 同构的 `ENGINE-GAP` 标记 + `check-engine-gaps.sh`(因没有固定日期,不用到期日),并加金丝雀(Q9) | +| 1 | 闭包补丁违反 `01-plugin-development.md` 规则 4、8;建议不打补丁、默认关或放进带到期日的 `compat/` | 属实:规则 8 原文是"引擎缺口要报告,不打补丁" | **你的决定**:先 workaround、默认开、无感、引擎修好后自动无事。我采纳了其中的"标注与强制移除"思想,做成与 `compat/` 同构的 `ENGINE-GAP` 标记 + `check-engine-gaps.sh`(因没有固定日期,不用到期日),并加金丝雀(Q9) | | 2 | `plugin_closure`、`deploy_plugins` 用普通类型分不清"未设置"与"设成默认值" | 属实 | 采纳:`plugin_closure` 两处都默认 `true`;Quick 插件目录改用独立字段 `quick_plugins` 取并集(§8) | | 3 | `qt.conf` 固定文本,`deploy_to` 非默认会丢翻译;未处理项目自带 `qt.conf` | 属实 | 采纳(Q3):`Translations` 随 `deploy_to`;检测并警告用户自己的 `qt.conf`。内嵌到 qrc 的方案未采纳:文件方案已实测,内嵌的 `Prefix` 相对谁未验证 | | 4 | README 下限列语义;`action::env` 是否存在 | README 列语义属实;`action::env` 存在(`hostprogram.cppm:441`,协议 13) | 采纳(Q4):列写 2026.10.1.3 并注明;Q4 证据改为只声称验证过的 API | | 5 | §6 的"都跑通"过度概括:单模块、`qsb`/`qmllint` 未运行、G4/C++ 单例无证据;延迟导入等没有真实样本;`closure.py` 写死路径、只认整行 `import` | 属实 | 采纳:补做多模块(`sum=19`)、跨模块继承、C++ `QML_SINGLETON`、无 C++ 类型模块、`lupdate` 的 qml 提取;§6 标题如实写明;Q2 列出只有合成样本覆盖的路径;`closure.py` 容忍行尾 `;`(4 个样本仍与 scanner 一致)。"40 个模块的样本用的是 Qt 自己的文件而不是用户代码":属实,写在 Q1 的覆盖说明里,结论限于 SDK 内部的 import 图 | | 6 | 规则 9:`qml-shaders` 永远不会失败;G9 无 fixture;`aot=false`、`styles` 等无运行用例 | 属实 | 采纳:G9 加进 `qml-consumer`;加三个变体(§10.2);`qml-shaders` 的跳过用 `::notice::` 可见,并在限制里承认 G7 在 `xim:qt-addons` 修复前只有 argv 级覆盖 | | 7 | 计划期读 `.qml` 内容,只声明 glob 不够 | 属实(`rules/qt.cppm` 对读过的头文件逐个声明) | 采纳(§5.1) | -| 8 | 文档清单缺项:`plugin-development.md` L2 表、脚本的 usage/case;交叉引用错;`--format` 写法;`compile_ex`、`tool_path` 扩大契约;`rule_module` 的说法含糊 | 属实 | 采纳(§4.1、§7 e、§11、§15、spikes README) | +| 8 | 文档清单缺项:`01-plugin-development.md` L2 表、脚本的 usage/case;交叉引用错;`--format` 写法;`compile_ex`、`tool_path` 扩大契约;`rule_module` 的说法含糊 | 属实 | 采纳(§4.1、§7 e、§11、§15、spikes README) | | 9 | 测试:`env -i` 挡不住 RUNPATH;`.qmltypes` 文本非契约;mtime 粒度;`grep -a` 不证明 AOT;随机改字节无种子、sanitizer 与模块单元的组合;`dumpbin` 需要 VS | 属实 | 采纳(§10.1、§10.3):挪走 SDK 目录;运行时断言继承;`sleep 2.2`;`llvm-nm` 符号;固定种子、sanitizer 不进 CI;统一用 `llvm-readobj`(也是你关于 LLVM 的意见的落点) | | S1 | `link_flag` 的库可能被 `--as-needed` 丢弃 | **实测属实**(lld `--as-needed` 下 NEEDED 为 0) | 采纳(Q9、§7):push/pop 包住;Mach-O 用 `-needed_library` | | S2 | macOS bundle 里 `Prefix = .` 含义不同 | 无法验证 | 写入 Q3,归入 Q7 的范围,标明推断 | diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..156a1c6 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,14 @@ +# Default owner: every path needs the package owner's review. +* @Sunrisepeak + +# Per-area rows: review is routed by family, and a new maintainer +# takes a family by editing one line. +/mcpp.toml @Sunrisepeak +/src/ @Sunrisepeak +/rules/ @Sunrisepeak +/tools/ @Sunrisepeak +/dist/ @Sunrisepeak +/deps/ @Sunrisepeak +/tests/ @Sunrisepeak +/docs/ @Sunrisepeak +/.github/ @Sunrisepeak diff --git a/.github/scripts/check-toolchain-lanes.sh b/.github/scripts/check-toolchain-lanes.sh index a523d2f..f03c865 100755 --- a/.github/scripts/check-toolchain-lanes.sh +++ b/.github/scripts/check-toolchain-lanes.sh @@ -12,7 +12,7 @@ # built with GCC -- and no build ever compiled that combination, so a # `std::pair` inside `value` (0.19.1) failed only there: # every build passed and every build program in an editor showed a module that -# was "not found". docs/plugin-development.md §4 states the rule this enforces. +# was "not found". docs/01-plugin-development.md §4 states the rule this enforces. # # Environment: MCPP (llvm); MCPP_EDITOR and MCPPLS (editor). set -euo pipefail diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c7f523..c378214 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,7 +89,7 @@ env: # when the action runs, which a subproject that links an executable or a # shared library needs. The package floor stays 2026.10.30.1: every other # member, and a cross subproject that only builds archives, works on the - # older engine, and docs/deps.md states the requirement where cross builds + # older engine, and docs/40-deps.md states the requirement where cross builds # are described. So here, as for 0.20.0's SYCL lane, `MCPP_VERSION` is the # newest engine a lane needs and the floor the oldest the collection loads on. # @@ -236,7 +236,7 @@ jobs: fi echo "ok: one version, two files agreeing" - # NO HEADER AND NO PREPROCESSOR BRANCH (0.21.0, docs/plugin-development.md + # NO HEADER AND NO PREPROCESSOR BRANCH (0.21.0, docs/01-plugin-development.md # §4): the operating system is mcpplibs.os's, the C library std's, and a # platform difference of the building machine is `if constexpr`. - name: no unit includes a header or branches in the preprocessor @@ -1926,7 +1926,7 @@ jobs: # `std::pair` that only the last one rejects, so every # build passed while every build program showed a missing module in the # editor. `.github/scripts/check-toolchain-lanes.sh` states what each lane - # runs; docs/plugin-development.md §4 states the rule. + # runs; docs/01-plugin-development.md §4 states the rule. toolchain-llvm: name: llvm (linux x86_64, clang + libc++) runs-on: ubuntu-24.04 diff --git a/deps/cmake.cppm b/deps/cmake.cppm index c950f9b..37a1b57 100644 --- a/deps/cmake.cppm +++ b/deps/cmake.cppm @@ -99,7 +99,7 @@ struct options { // the toolset mcpp builds the program with, named by path, with the Ninja // generator and mcpp's own ninja. `detected` lets CMake find its own // toolset, as 0.16.0 did, until 2027-03-28. Compilers or a toolchain file - // in `cache_args` decide instead. See docs/deps.md. + // in `cache_args` decide instead. See docs/40-deps.md. mcpp::plugins::toolset::choice toolset; // Which generator (0.18.0). `default` is Ninja wherever the toolset is // named, a Visual Studio instance's included, as vcpkg builds its CMake @@ -118,7 +118,7 @@ struct options { // (`%LOCALAPPDATA%/mcpp-plugins/deps-cmake`, // `$XDG_CACHE_HOME/mcpp-plugins/deps-cmake` or // `~/.cache/mcpp-plugins/deps-cmake`). Read when the action runs; the place - // is no part of what is built. See docs/deps.md. + // is no part of what is built. See docs/40-deps.md. std::string cache; // `CMAKE_SYSTEM_NAME` of a build for another target (0.21.0). Empty // derives it from the target's system: Linux, Android, Darwin, iOS, diff --git a/deps/vcpkg.cppm b/deps/vcpkg.cppm index 7e3f1eb..73e6432 100644 --- a/deps/vcpkg.cppm +++ b/deps/vcpkg.cppm @@ -94,7 +94,7 @@ struct options { // other toolset is named in a derived triplet `-mcpp-` // (CMake and make ports build; an MSBuild port needs Visual Studio and is // refused by name). `detected` lets vcpkg find its own toolset, as 0.16.0 - // did, until 2027-03-28. See docs/deps.md. + // did, until 2027-03-28. See docs/40-deps.md. mcpp::plugins::toolset::choice toolset; // The C runtime linkage of the ports on the MSVC ABI, "static" or // "dynamic". Empty follows the program's C++ runtime contract diff --git a/docs/engine-and-rules.md b/docs/00-engine-and-rules.md similarity index 100% rename from docs/engine-and-rules.md rename to docs/00-engine-and-rules.md diff --git a/docs/plugin-development.md b/docs/01-plugin-development.md similarity index 99% rename from docs/plugin-development.md rename to docs/01-plugin-development.md index 1eba362..4e1a4fc 100644 --- a/docs/plugin-development.md +++ b/docs/01-plugin-development.md @@ -103,7 +103,7 @@ build reports. A choice alone does not prevent a download: an eagerly declared payload is provisioned before any build program runs. The pair that makes "named here, not downloaded" true, the scenarios on both sides of it, and how each official member -declares its tools are in [tool-sources.md](tool-sources.md). +declares its tools are in [02-tool-sources.md](02-tool-sources.md). **Stating the build toolchain.** `mcpp.plugins.toolchain` (feature `plugins-toolchain`) builds the statement a root build program makes in its diff --git a/docs/tool-sources.md b/docs/02-tool-sources.md similarity index 100% rename from docs/tool-sources.md rename to docs/02-tool-sources.md diff --git a/docs/rules.md b/docs/10-rules.md similarity index 99% rename from docs/rules.md rename to docs/10-rules.md index 0471dae..f8ac45b 100644 --- a/docs/rules.md +++ b/docs/10-rules.md @@ -1,6 +1,6 @@ # Device and language rules -The rules that compile one kind of translation unit with a compiler mcpp does not drive: GPU and accelerator languages (`rules-ascendc`, `rules-cuda`, `rules-hip`, `rules-sycl`), shader languages (`rules-spirv`, `rules-slang`, `rules-metal`) and Swift (`rules-swift`). Each section states the module, the engine floor, what the rule needs and how it compiles. The environment each rule brings and the extensions it claims are in [engine-and-rules.md](engine-and-rules.md). +The rules that compile one kind of translation unit with a compiler mcpp does not drive: GPU and accelerator languages (`rules-ascendc`, `rules-cuda`, `rules-hip`, `rules-sycl`), shader languages (`rules-spirv`, `rules-slang`, `rules-metal`) and Swift (`rules-swift`). Each section states the module, the engine floor, what the rule needs and how it compiles. The environment each rule brings and the extensions it claims are in [00-engine-and-rules.md](00-engine-and-rules.md). ## `rules-ascendc` diff --git a/docs/rules-qt.md b/docs/11-rules-qt.md similarity index 98% rename from docs/rules-qt.md rename to docs/11-rules-qt.md index 82d8490..f47f50a 100644 --- a/docs/rules-qt.md +++ b/docs/11-rules-qt.md @@ -1,6 +1,6 @@ # `rules-qt` -`mcpp.rules.qt` runs Qt's code generators (`moc`, `uic`, `rcc`) and Linguist tools (`lupdate`, `lrelease`, `lconvert`) as build actions, links the Qt modules and places their runtime beside the program. The rule declares no SDK and pins no version: the project names the Qt it builds with, in `build.mcpp` or in its own `[xlings]` table. Module `mcpp.rules.qt`; engine floor 2026.10.1.3 (mcpp#755) from 0.19.0 (0.27.0 adds `moc_json`, `moc_includes`, `i18n.extensions` and `compile_ex`; QML is [rules-qml](rules-qml.md)), 2026.9.27.1 (mcpp#704, mcpp#715) from 0.16.0, 2026.9.26.2 (mcpp#702) before; from 0.13.0. +`mcpp.rules.qt` runs Qt's code generators (`moc`, `uic`, `rcc`) and Linguist tools (`lupdate`, `lrelease`, `lconvert`) as build actions, links the Qt modules and places their runtime beside the program. The rule declares no SDK and pins no version: the project names the Qt it builds with, in `build.mcpp` or in its own `[xlings]` table. Module `mcpp.rules.qt`; engine floor 2026.10.1.3 (mcpp#755) from 0.19.0 (0.27.0 adds `moc_json`, `moc_includes`, `i18n.extensions` and `compile_ex`; QML is [rules-qml](12-rules-qml.md)), 2026.9.27.1 (mcpp#704, mcpp#715) from 0.16.0, 2026.9.26.2 (mcpp#702) before; from 0.13.0. ## Use diff --git a/docs/rules-qml.md b/docs/12-rules-qml.md similarity index 96% rename from docs/rules-qml.md rename to docs/12-rules-qml.md index 560d9ab..97766c7 100644 --- a/docs/rules-qml.md +++ b/docs/12-rules-qml.md @@ -1,6 +1,6 @@ # `rules-qml` -`mcpp.rules.qml` builds a QML application: for each QML module the project states, it declares the chain Qt's `qt_add_qml_module` runs (`moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc`, `qsb`) as actions, so the module is compiled into the executable and loaded with `loadFromModule`; it places the Qt QML modules the program imports beside it, and writes a `qt.conf` that points Qt at them. It builds on [rules-qt](rules-qt.md), which it implies, and takes its options. Module `mcpp.rules.qml`; engine floor 2026.10.1.3 (the floor of `rules-qt`; the package needs 2026.10.30.1, and the lowest release the fixtures were run on is 2026.10.31.3), and 2026.11.23.1 for a `mcpp pack` that carries the libraries the QML plugins load (mcpp#1011); from 0.27.0. +`mcpp.rules.qml` builds a QML application: for each QML module the project states, it declares the chain Qt's `qt_add_qml_module` runs (`moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc`, `qsb`) as actions, so the module is compiled into the executable and loaded with `loadFromModule`; it places the Qt QML modules the program imports beside it, and writes a `qt.conf` that points Qt at them. It builds on [rules-qt](11-rules-qt.md), which it implies, and takes its options. Module `mcpp.rules.qml`; engine floor 2026.10.1.3 (the floor of `rules-qt`; the package needs 2026.10.30.1, and the lowest release the fixtures were run on is 2026.10.31.3), and 2026.11.23.1 for a `mcpp pack` that carries the libraries the QML plugins load (mcpp#1011); from 0.27.0. ## Use diff --git a/docs/tools-embed.md b/docs/20-tools-embed.md similarity index 98% rename from docs/tools-embed.md rename to docs/20-tools-embed.md index 9f48ef5..5920274 100644 --- a/docs/tools-embed.md +++ b/docs/20-tools-embed.md @@ -14,7 +14,7 @@ Module `mcpp.tools.embed`; engine floor: 2026.9.5.4. |---|---|---|---| | `file()` | one | one header | one array, one `_size`, included by name | | `files()` | N | N headers | one `file()` call per input; `options::identifier` is refused, because it names one symbol and there are several | -| `group()` | N | N headers + one generated interface | the same N headers, handed to `mcpp::plugins::surface` so a consumer writes one `import` and names no generated file -- see [What a consumer names](engine-and-rules.md#what-a-consumer-names) | +| `group()` | N | N headers + one generated interface | the same N headers, handed to `mcpp::plugins::surface` so a consumer writes one `import` and names no generated file -- see [What a consumer names](00-engine-and-rules.md#what-a-consumer-names) | | `table()` | N | one header | one array of rows, each carrying its input's key beside its bytes; the consumer iterates or looks a row up by key | `table()` is for a set the consumer wants to walk rather than name member by diff --git a/docs/tools-island.md b/docs/21-tools-island.md similarity index 100% rename from docs/tools-island.md rename to docs/21-tools-island.md diff --git a/docs/tools-steps.md b/docs/22-tools-steps.md similarity index 100% rename from docs/tools-steps.md rename to docs/22-tools-steps.md diff --git a/docs/dist.md b/docs/30-dist.md similarity index 98% rename from docs/dist.md rename to docs/30-dist.md index 67d3ddf..fb9db06 100644 --- a/docs/dist.md +++ b/docs/30-dist.md @@ -1,6 +1,6 @@ # `dist-appimage`, `dist-deb`, `dist-rpm`, `dist-wix` and `dist-web` -Three `dist-*` members that turn the tree `mcpp pack` stages into an installable form: an AppImage on Linux, an MSI or a Burn bundle on Windows, and a web directory for `wasm32-emscripten`. `dist-apple` and `dist-apk` have pages of their own ([dist-apple.md](dist-apple.md), [dist-apk.md](dist-apk.md)). +Three `dist-*` members that turn the tree `mcpp pack` stages into an installable form: an AppImage on Linux, an MSI or a Burn bundle on Windows, and a web directory for `wasm32-emscripten`. `dist-apple` and `dist-apk` have pages of their own ([31-dist-apple.md](31-dist-apple.md), [32-dist-apk.md](32-dist-apk.md)). ## `dist-appimage` diff --git a/docs/dist-apple.md b/docs/31-dist-apple.md similarity index 51% rename from docs/dist-apple.md rename to docs/31-dist-apple.md index 68d8848..c73f375 100644 --- a/docs/dist-apple.md +++ b/docs/31-dist-apple.md @@ -6,7 +6,7 @@ Module `mcpp.dist.apple`; engine floor: 2026.9.14.2 (0.10.0); 2026.9.11.2 (macOS) and 2026.9.12.3 (iOS) before it. -**Needs and behaviour.** the base macOS install (`ditto`, `codesign`, `hdiutil`), `xim:macapp-run` for `mcpp run` on macOS, which this feature declares with `when = "run"`, and `xim:cmake` (0.25.0), asked for only when a plan copies a framework or stages a disk image: those steps are step programs ([`tools-steps`](tools-steps.md)), whose runner is `cmake` until mcpp runs them itself (mcpp-community/mcpp#955), and `options::cmake` names another `cmake`. macOS: `Contents/`-shaped, as always. iOS (`aarch64-ios-sim`, `aarch64-ios`): a flat bundle at the same call site -- no separate feature, no separate module -- with `MinimumOSVersion` from `mcpp::min_platform_version()` (#622 A11), `CFBundleSupportedPlatforms` read from `env == "sim"`, `UIDeviceFamily`, `LSRequiresIPhoneOS`, and a directory of flat PNGs listed under `CFBundleIcons` in place of macOS's single `.icns` file. Signing is skipped on the simulator row (`options::identity` is ignored, with a `mcpp::warning` naming why), and the device row signs only with an identity. The iOS row is measured end to end on `macos-15`: a real `mcpp build`, `mcpp pack --format app` and `mcpp run` against `aarch64-ios-sim`, through `xim:apple-simulator-tools`' `simctl-run`. **The macOS floor is one release higher than its siblings** and the reason is not this member: under 2026.9.11.1 `mcpp pack` staged before dispatching and let a staging failure fail the command, so on a Mach-O program -- which the built-in closure walk refuses, because it uses `LD_TRACE_LOADED_OBJECTS` and dyld answers that by running the program -- every dispatched format was unreachable, including one that reads no staged tree. 2026.9.11.2 makes staging a service to the provider. From 0.9.2 the staged tree's deployed files (`bin//...`, which the engine stages for a Mach-O program before the closure walk since the release for mcpp#630) land at the bundle's resource destination -- `Contents/Resources//...` on macOS, the bundle root on iOS -- and the launcher alone goes to the executable directory, so `CFBundleExecutable` names a file that is where it says. The iOS fixture declares `llvm.libcxx` and `llvm.compiler-rt-builtins` under `cfg(os = "ios")`, which is what an application that imports `std` on those rows declares. From 0.10.0, with mcpp 2026.9.14.2: the dylibs the engine stages beside a Mach-O program, which the stage manifest's `needs` lines name, go to `Contents/Frameworks/` (`Frameworks/` on iOS) and not to the resources; the program is linked with the rpath that finds them there (`@executable_path/../Frameworks`, `@executable_path/Frameworks` on iOS) through `mcpp::link_flag`, so no file is edited after the link; a macOS bundle without `options::identity` is signed ad hoc, frameworks first and the bundle second, which `codesign --verify --deep --strict` requires of a bundle that carries a framework; an incomplete closure is a `mcpp::warning` naming the unresolved libraries; every refusal is a `mcpp::warning` as well, because the engine discards a build program's output when it exits 0. On macOS the member supplies the runner named `app` (`macapp-run`), so `mcpp run --format app` runs the bundle's executable in the foreground and returns its status with no runner in the manifest; a manifest runner of that name wins. `--format dmg` stages the bundle beside an `Applications` link and writes a UDZO image with `hdiutil create` (`options::volume_name`, `options::dmg`); it is refused on iOS. An engine below 2026.9.14.2 stages no `needs` lines, so the bundle carries no framework, anchors the rpath to the package directory, and hands the bundle directory to the kernel under `mcpp run --format app` unless `--runner app` is typed. CI measures the bundle on `macos-15`: the load command, the signature, the program with and without its framework (exit 7, then "Library not loaded"), `mcpp run --format app` with and without `--runner app`, and `hdiutil verify` and an attached image. From 0.11.0: a project's own Info.plist entries (`options::info_plist`), an iOS device bundle's provisioning profile (`options::provisioning_profile`), and `devicectl-run` (`xim:apple-device-tools`) as the device row's runner named `app` -- see [`dist-apple`: a project's Info.plist, and an iOS device](#dist-apple-a-projects-infoplist-and-an-ios-device). From 0.12.0 `options::omit_keys` leaves out a key the member only defaults -- see [`dist-apple`: a project's Info.plist, and an iOS device](#dist-apple-a-projects-infoplist-and-an-ios-device). From 0.12.0 a package in the resolved graph contributes Info.plist entries through `[package.metadata.dist-apple]`, applied before the application's own +**Needs and behaviour.** the base macOS install (`ditto`, `codesign`, `hdiutil`), `xim:macapp-run` for `mcpp run` on macOS, which this feature declares with `when = "run"`, and `xim:cmake` (0.25.0), asked for only when a plan copies a framework or stages a disk image: those steps are step programs ([`tools-steps`](22-tools-steps.md)), whose runner is `cmake` until mcpp runs them itself (mcpp-community/mcpp#955), and `options::cmake` names another `cmake`. macOS: `Contents/`-shaped, as always. iOS (`aarch64-ios-sim`, `aarch64-ios`): a flat bundle at the same call site -- no separate feature, no separate module -- with `MinimumOSVersion` from `mcpp::min_platform_version()` (#622 A11), `CFBundleSupportedPlatforms` read from `env == "sim"`, `UIDeviceFamily`, `LSRequiresIPhoneOS`, and a directory of flat PNGs listed under `CFBundleIcons` in place of macOS's single `.icns` file. Signing is skipped on the simulator row (`options::identity` is ignored, with a `mcpp::warning` naming why), and the device row signs only with an identity. The iOS row is measured end to end on `macos-15`: a real `mcpp build`, `mcpp pack --format app` and `mcpp run` against `aarch64-ios-sim`, through `xim:apple-simulator-tools`' `simctl-run`. **The macOS floor is one release higher than its siblings** and the reason is not this member: under 2026.9.11.1 `mcpp pack` staged before dispatching and let a staging failure fail the command, so on a Mach-O program -- which the built-in closure walk refuses, because it uses `LD_TRACE_LOADED_OBJECTS` and dyld answers that by running the program -- every dispatched format was unreachable, including one that reads no staged tree. 2026.9.11.2 makes staging a service to the provider. From 0.9.2 the staged tree's deployed files (`bin//...`, which the engine stages for a Mach-O program before the closure walk since the release for mcpp#630) land at the bundle's resource destination -- `Contents/Resources//...` on macOS, the bundle root on iOS -- and the launcher alone goes to the executable directory, so `CFBundleExecutable` names a file that is where it says. The iOS fixture declares `llvm.libcxx` and `llvm.compiler-rt-builtins` under `cfg(os = "ios")`, which is what an application that imports `std` on those rows declares. From 0.10.0, with mcpp 2026.9.14.2: the dylibs the engine stages beside a Mach-O program, which the stage manifest's `needs` lines name, go to `Contents/Frameworks/` (`Frameworks/` on iOS) and not to the resources; the program is linked with the rpath that finds them there (`@executable_path/../Frameworks`, `@executable_path/Frameworks` on iOS) through `mcpp::link_flag`, so no file is edited after the link; a macOS bundle without `options::identity` is signed ad hoc, frameworks first and the bundle second, which `codesign --verify --deep --strict` requires of a bundle that carries a framework; an incomplete closure is a `mcpp::warning` naming the unresolved libraries; every refusal is a `mcpp::warning` as well, because the engine discards a build program's output when it exits 0. On macOS the member supplies the runner named `app` (`macapp-run`), so `mcpp run --format app` runs the bundle's executable in the foreground and returns its status with no runner in the manifest; a manifest runner of that name wins. `--format dmg` stages the bundle beside an `Applications` link and writes a UDZO image with `hdiutil create` (`options::volume_name`, `options::dmg`); it is refused on iOS. An engine below 2026.9.14.2 stages no `needs` lines, so the bundle carries no framework, anchors the rpath to the package directory, and hands the bundle directory to the kernel under `mcpp run --format app` unless `--runner app` is typed. CI measures the bundle on `macos-15`: the load command, the signature, the program with and without its framework (exit 7, then "Library not loaded"), `mcpp run --format app` with and without `--runner app`, and `hdiutil verify` and an attached image. From 0.11.0: a project's own Info.plist entries (`options::info_plist`), an iOS device bundle's provisioning profile (`options::provisioning_profile`), and `devicectl-run` (`xim:apple-device-tools`) as the device row's runner named `app` -- see [`dist-apple`: a project's Info.plist, and an iOS device](#dist-apple-a-projects-infoplist-and-an-ios-device). From 0.12.0 `options::omit_keys` leaves out a key the member only defaults -- see [`dist-apple`: a project's Info.plist, and an iOS device](#dist-apple-a-projects-infoplist-and-an-ios-device). From 0.12.0 a package in the resolved graph contributes Info.plist entries through `[package.metadata.dist-apple]`, applied before the application's own ## `dist-apple`: a project's Info.plist, and an iOS device diff --git a/docs/dist-apk.md b/docs/32-dist-apk.md similarity index 99% rename from docs/dist-apk.md rename to docs/32-dist-apk.md index 7097b0c..aae19ea 100644 --- a/docs/dist-apk.md +++ b/docs/32-dist-apk.md @@ -87,7 +87,7 @@ Anything beyond that belongs in the project's `manifest_template`. Kotlin compiler, coursier), and from 0.25.0 each step of more than one command (javac or kotlinc with its stamp, d8 over the classes it finds, the archive gaining its libraries, assets and dex, an App Bundle's base module) is a step -program ([`tools-steps`](tools-steps.md)), so no step needs a shell and a Windows +program ([`tools-steps`](22-tools-steps.md)), so no step needs a shell and a Windows host packs what a Linux host does. CI packs level 0 and level 1 on Linux, macOS and Windows hosts; the Kotlin, library, bundle and Maven criteria run on Linux. On Windows the NDK's libc++ module sources come from `xim:android-ndk-libcxx-modules`, which diff --git a/docs/deps.md b/docs/40-deps.md similarity index 100% rename from docs/deps.md rename to docs/40-deps.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..6b90d8b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,56 @@ +# mcpp-plugins Documentation + +This tree is the manual for the members of `mcpp:plugins` and for the +conventions a build plugin follows. Each page states what a member does, how a +consumer writes it, and what its current limits are. The reasoning behind a +design, and what was measured and refuted on the way, lives in the dated +records under [`../.agents/docs/`](../.agents/docs/) — a page cites no record. + +## Start here + +| To | Read | +|---|---| +| use a member | its page below, and the [quick start](../README.md#quick-start) in the README | +| write a plugin of your own | [01 — Plugin Development](01-plugin-development.md) | +| know why a name, a floor or a claim is what it is | [00 — How the Members Meet the Engine](00-engine-and-rules.md) | +| name a tool a member runs | [02 — Where a Tool Comes From](02-tool-sources.md) | + +## Pages + +The first digit is the part, so a number says where a page belongs: + +| | | +|---|---| +| `0x` | the framework: naming, conventions, where a tool comes from | +| `1x` | the rules: device and language compilation | +| `2x` | the tools: what the build program does itself | +| `3x` | the distribution: what comes out of the link | +| `4x` | the dependencies: where a library comes from | + +### 0x — The framework + +- [00 — How the Members Meet the Engine](00-engine-and-rules.md) — the families and their names, each rule's environment and claimed extensions, the engine floor, what a consumer names +- [01 — Plugin Development](01-plugin-development.md) — the conventions every plugin follows, the C++ a plugin is written in, a new member's checklist +- [02 — Where a Tool Comes From](02-tool-sources.md) — the one order every member resolves a tool in, and every way a project names its own + +### 1x — Rules + +- [10 — Device and Language Rules](10-rules.md) — `rules-ascendc`, `rules-cuda`, `rules-hip`, `rules-metal`, `rules-slang`, `rules-spirv`, `rules-swift`, `rules-sycl` +- [11 — `rules-qt`](11-rules-qt.md) — Qt's code generators, modules and runtime; Linguist tools +- [12 — `rules-qml`](12-rules-qml.md) — a QML application on `rules-qt` + +### 2x — Tools + +- [20 — `tools-embed`](20-tools-embed.md) — a data file compiled into the program +- [21 — `tools-island`](21-tools-island.md) — the `extern "C"` boundary and module of a code island +- [22 — `tools-steps`](22-tools-steps.md) — an action whose work is more than one command + +### 3x — Distribution + +- [30 — `dist-appimage`, `dist-deb`, `dist-rpm`, `dist-wix`, `dist-web`](30-dist.md) +- [31 — `dist-apple`](31-dist-apple.md) — a macOS or iOS bundle, signed, as a disk image +- [32 — `dist-apk`](32-dist-apk.md) — a signed APK or App Bundle, with Java, Kotlin and Maven libraries + +### 4x — Dependencies + +- [40 — `deps-vcpkg`, `deps-cmake`, `deps-archive`](40-deps.md) diff --git a/mcpp.toml b/mcpp.toml index 0b2fbfa..6e8f80d 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -98,7 +98,7 @@ sources = ["src/declare.cppm", "src/toolset.cppm", "src/fs.cppm", "src/tool.cppm # The operating system of every member: the programs a member asks for a fact # (`mcpp.plugins.tool::capture`), the libraries it opens and the platform it # builds on, through mcpplibs.os. No unit includes a system header (0.21.0, -# docs/plugin-development.md §4). 0.4.5 (0.26.1) accepts openkal 0.24 to 0.26, +# docs/01-plugin-development.md §4). 0.4.5 (0.26.1) accepts openkal 0.24 to 0.26, # so a graph whose openkal is 0.26 (openkal-platform 0.31's version group) holds # the plugins, and its start is bounded by the environment alone (mcpp#958); # 0.4.4 (0.22.1) accepted 0.24 and 0.25, and 0.4.0 named openkal 0.24.0 alone. @@ -225,8 +225,8 @@ device_extensions = [".ui", ".qrc", ".ts"] # WHERE QT COMES FROM IS THE PROJECT'S CHOICE, not a feature: `rules-qt` finds # the SDK from `options::root`, `QT_ROOT_DIR`, or a Qt payload the project # declares in its own `[xlings]` table at the version it chooses -# (docs/rules-qt.md). A feature states a mechanism and the tools that mechanism -# runs, never a library the program links (docs/plugin-development.md). 0.15.0 +# (docs/11-rules-qt.md). A feature states a mechanism and the tools that mechanism +# runs, never a library the program links (docs/01-plugin-development.md). 0.15.0 # removed `rules-qt-xim`, `rules-qt-xim-base` and `rules-qt-xim-addons`. # NOT device rules: these embed or declare things a project already has, so they diff --git a/rules/qt.cppm b/rules/qt.cppm index cb03444..929bca9 100644 --- a/rules/qt.cppm +++ b/rules/qt.cppm @@ -430,7 +430,7 @@ struct moc_unit { // What `compile_ex` decided, for the rule that builds on it. This is the // collaboration of two modules of one package at one version, not a contract -// for third parties (docs/plugin-development.md rule 5): `mcpp.rules.qml` uses +// for third parties (docs/01-plugin-development.md rule 5): `mcpp.rules.qml` uses // it, and a project calls `compile`. struct outcome { bool ok = false; diff --git a/src/platform.cppm b/src/platform.cppm index cc2aa19..c7b787f 100644 --- a/src/platform.cppm +++ b/src/platform.cppm @@ -89,7 +89,7 @@ inline bool engine_format(std::string_view n) { // A relative path is the platform package's own. Spelled on strings: a module // that instantiates `std::filesystem::path`'s iterator (`lexically_normal`) -// breaks every importer under MSVC 14.52 (docs/plugin-development.md §4). +// breaks every importer under MSVC 14.52 (docs/01-plugin-development.md §4). inline std::string absolute_in_package(std::string_view path) { const bool absolute = path.starts_with('/') || path.starts_with('\\') || (path.size() > 2 && path[1] == ':' && (path[2] == '/' || path[2] == '\\')); diff --git a/src/tool.cppm b/src/tool.cppm index 8bf2783..966818f 100644 --- a/src/tool.cppm +++ b/src/tool.cppm @@ -359,7 +359,7 @@ inline std::string describe_missing(const spec& s, const found& f) { // mcpplibs.os's types from another module's inline body: it cannot read the // module back ("failed to read compiled module cluster: Bad file data") or // leaves `std::optional>` unresolved at the link -// (`tests/metal-consumer`; docs/plugin-development.md §4). +// (`tests/metal-consumer`; docs/01-plugin-development.md §4). struct printed { int status = -1; std::string out; diff --git a/tests/qt-sdk-consumer/mcpp.toml b/tests/qt-sdk-consumer/mcpp.toml index 2a91af9..561eecc 100644 --- a/tests/qt-sdk-consumer/mcpp.toml +++ b/tests/qt-sdk-consumer/mcpp.toml @@ -1,5 +1,5 @@ # Fixture: the Qt SDK named by the project, at the levels `rules-qt` consults -# (docs/rules-qt.md, "The SDK"). The edge asks for `rules-qt` alone, which +# (docs/11-rules-qt.md, "The SDK"). The edge asks for `rules-qt` alone, which # declares no SDK; the project declares `xim:qt-base` at a version of its own # choosing. CI builds it so, then names a Qt through `QT_ROOT_DIR`, then # through `options::root` (the build program reads `QT_SDK_CONSUMER_ROOT`, a From 93dce6e783821af998079af73ae5a09f9f89cb34 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 15:44:33 +0800 Subject: [PATCH 02/18] AGENTS.md and CODEOWNERS: the repository's rules in their shortest form, and review routing --- AGENTS.md | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..fa1de07 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,85 @@ +# AGENTS.md + +`mcpp-plugins` is the package of official build plugins for mcpp +(`mcpp:plugins`). One member is one module file, one feature in `mcpp.toml`, +one consumer under `tests/`, one page under `docs/`. This file states the rules +that hold across the repository in their shortest form; each links to the +document that states it in full. Where this file and a linked document differ, +the linked document holds. + +## 1. Where a fact lives + +| Tree | States | +|---|---| +| [`docs/`](docs/README.md) | one page per member or family, and the plugin conventions ([01](docs/01-plugin-development.md)) | +| [`README.zh-CN.md`](README.zh-CN.md) | the README in Chinese; English is the source of truth, and a lagging section is stated in its header | +| [`mcpp.toml`](mcpp.toml) | the package: one feature per member, the declared payloads, the engine floor `[package] mcpp` | +| [`tests//`](tests/) | one consumer project per member; CI builds each and asserts on its output | +| [`tools/README.md`](tools/README.md) | the tools family's own account | +| [`.agents/docs/`](.agents/docs/) | design records: the reasoning, the measurements, what was refuted | + +A change of behaviour updates the member's page and its consumer in the same +pull request. + +## 2. Architecture + +- **A plugin provides a mechanism, not a policy.** No fixed version, path or + library list a project could reasonably choose. Configuration is `build.mcpp` + first ([01 §2](docs/01-plugin-development.md#2-rules)). +- **Four families answer four questions.** `rules-*` how a translation unit is + compiled by a compiler mcpp does not drive; `tools-*` what the build program + does itself; `dist-*` what comes out of the link, and in what form a user + installs it; `deps-*` where a library comes from. The prefix is load-bearing + ([00](docs/00-engine-and-rules.md)). +- **Names are three segments.** `mcpp..`; the second segments + `core`, `plugins`, `deps`, `rules`, `dist`, `tools` belong to the namespace, + and a third-party plugin names its modules `mcpp..*` + ([01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor)). +- **Three layers, one way down.** The engine's `mcpp` (L1), the general library + `mcpp.plugins.*` (L2, feature `plugins-core`; every member implies it), the + members (L3). A layer imports only lower layers. +- **Every member states an engine floor.** The collection's floor is + `[package] mcpp`; the index descriptor states the highest floor among the + members, so a project on an older engine is refused at resolution. +- **A tool resolves in one order, for every member:** the build program's + choice, the member's legacy variable, the engine's override, the declared + payload. A choice never asks for the payload — a build program that names its + own tool must not trigger a download + ([02](docs/02-tool-sources.md)). + +## 3. Code + +- C++23 modules: `import std;`, plus the module that defines a type. No unit + includes a header or branches on the platform in the preprocessor. +- The code compiles under the four lanes CI runs: GCC with libstdc++, clang + with libc++, clang with libstdc++'s `std` module (an editor's clangd), and + MSVC where a member claims Windows. No compiler's leniency is relied on; the + known differences and their workarounds are stated in + [01 §4](docs/01-plugin-development.md#4-the-c-a-plugin-is-written-in). +- A behaviour kept past the release that replaced it lives in `compat/`, one + unit per behaviour, with a retirement date six months on; + `.github/scripts/check-compat-retirement.sh` fails once a date has passed. + +## 4. Build and test + +- CI (`.github/workflows/ci.yml`) builds every fixture under `tests/` with the + pinned mcpp on the GCC lane (`consumers`), and adds `toolchain-llvm`, + `toolchain-editor`, `rules-cross-platform` and `deps-managed-msvc`. +- Every documented behaviour has a criterion: a CI check, on every platform the + member claims ([01 §2](docs/01-plugin-development.md#2-rules), rule 9). +- A change to a member builds its fixture, not only the package. + +## 5. Change workflow + +- Every change goes through a pull request; `main` is never pushed to directly. + Commits and pull-request text are English, declarative, without emoji or + attribution trailers. One pull request does one thing; all required checks + pass before merge. +- Review follows [`.github/CODEOWNERS`](.github/CODEOWNERS): the family rows + route it; a change to the feature set or the engine floor in `mcpp.toml` + needs the package owner. +- Adding a member is the checklist in + [01 §5](docs/01-plugin-development.md#5-a-new-plugin): a module file, a + feature, a consumer, a table row with its floor, a page, a version bump. +- A release changes the version in `mcpp.toml` and tags `v`; the tag + publishes the source archive the index descriptor names. From 0dad363f760661a427bddcbdcd3c6b4bdaa17ef7 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 15:44:33 +0800 Subject: [PATCH 03/18] README: the members table behind details, a maintainer column, and a Chinese mirror --- README.md | 169 +++++++++++++++++++++++------------------------- README.zh-CN.md | 140 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 220 insertions(+), 89 deletions(-) create mode 100644 README.zh-CN.md diff --git a/README.md b/README.md index b11fef3..459102a 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,23 @@ # mcpp-plugins -The build plugins the mcpp project maintains, published as one package, -`mcpp:plugins`. mcpp is a general engine with a framework for build plugins; -plugins come from this package, from third parties, or from the project -itself, and `build.mcpp` is where a project uses them. A consumer selects the -members it needs through features, imports each one from `build.mcpp` under the -module name the member declares, and configures it there. +> The official build plugins for mcpp — one member, one feature, one module. + +**English** | [简体中文](README.zh-CN.md) + +[![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) +[![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) + +mcpp is a general engine with a framework for build plugins; plugins come from +this package (`mcpp:plugins`), from third parties, or from the project itself, +and `build.mcpp` is where a project uses them: it imports the member's module +under the name the member declares, configures it, and calls it. The edge is a +`[build-dependencies]` entry, not a `[dependencies]` entry: `host-module = true` +states which build-time product is wanted, and the section states that the +package does not reach the target — a rule's library is never linked into the +artifact (mcpp docs/05 §2.6.1). + +## Quick start ```toml [build-dependencies.mcpp] @@ -25,12 +37,7 @@ int main() { } ``` -The edge is a `[build-dependencies]` entry, not a `[dependencies]` entry: -`host-module = true` states which build-time product is wanted, and the section -states that the package does not reach the target. A rule's library is never -linked into the artifact (mcpp docs/05 §2.6.1). - -## Naming +## Families | family | module | answers | |---|---|---| @@ -40,79 +47,65 @@ linked into the artifact (mcpp docs/05 §2.6.1). | deps | `mcpp.deps.` | where a library comes from | | identity | `mcpp.plugins` | the lib root, compiled before every member; it states the collection's version | -The second segments `core`, `plugins`, `deps`, `rules`, `dist` and `tools` of -`mcpp.` belong to this package and the engine; a third-party plugin names its -modules `mcpp..*` ([docs/plugin-development.md](docs/plugin-development.md#3-layers-names-and-the-engine-floor)). -The full account of the families, and of how the engine routes a file to a -rule, is in [docs/engine-and-rules.md](docs/engine-and-rules.md). Where the tool a -member runs comes from -- what a project can name, what a plugin must declare for -naming it to avoid a download, and the scenarios on both sides -- is in -[docs/tool-sources.md](docs/tool-sources.md). +A third-party plugin names its modules `mcpp..*`; the second +segments `core`, `plugins`, `deps`, `rules`, `dist`, `tools` belong to this +package and the engine. The full account of the families, and of how the engine +routes a file to a rule, is in [docs/00](docs/00-engine-and-rules.md); where a +tool a member runs comes from is in [docs/02](docs/02-tool-sources.md). ## Members -From 0.21.0 the package as a whole needs mcpp 2026.10.30.1 (`[package] mcpp`), -which writes the configuration's contract that `deps-cmake` compiles a cross -build from (0.20.0 needed 2026.10.27.1, whose protocol 17 states a platform's -fields and whose `mcpp pack` writes `mcpp-package.json` beside every staged -tree; 0.19.0 needed 2026.10.1.3, whose -protocol 15 states where each tool and payload comes from); the column states -the release each member's behaviour first needed. - -Cross CMake subprojects that link executables or shared libraries require -mcpp 2026.11.7.1 or later; cross configuration requires CMake 3.19 or later. - -| feature | module | mcpp floor | what it does | doc | -|---|---|---|---|---| -| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [rules](docs/rules.md#rules-ascendc) | -| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [rules](docs/rules.md#rules-cuda) | -| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [rules](docs/rules.md#rules-hip) | -| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](docs/rules.md#rules-metal) | -| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](docs/rules-qt.md) | -| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](docs/rules-qml.md) | -| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](docs/rules.md#rules-slang) | -| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](docs/rules.md#rules-spirv) | -| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](docs/rules.md#rules-swift) | -| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](docs/rules.md#rules-sycl) | -| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | Writes a data file into a header the program compiles in. | [tools-embed](docs/tools-embed.md) | -| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | Generates the `extern "C"` boundary and the C++ module of a code island. | [tools-island](docs/tools-island.md) | -| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [tools-steps](docs/tools-steps.md) | -| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [dist](docs/dist.md#dist-appimage) | -| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [dist](docs/dist.md#dist-deb-and-dist-rpm) | -| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | The same installation as an RPM package (Linux targets). | [dist](docs/dist.md#dist-deb-and-dist-rpm) | -| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [dist](docs/dist.md#dist-wix) | -| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [dist-apple](docs/dist-apple.md) | -| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [dist](docs/dist.md#dist-web) | -| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [dist-apk](docs/dist-apk.md) | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [deps](docs/deps.md#deps-vcpkg) | -| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3; a cross build 2026.10.30.1 | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved -- for another target, the compilers and words of the engine's contract -- keeps the installation for any build with the same key, and maps the prefix into the build. | [deps](docs/deps.md#deps-cmake) | -| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | Extracts a zip archive the project keeps and places its tree beside the program. | [deps](docs/deps.md#deps-archive) | +From 0.21.0 the package as a whole needs mcpp 2026.10.30.1 (`[package] mcpp`); +the column states the release each member's behaviour first needed. Cross CMake +subprojects that link executables or shared libraries require mcpp +2026.11.7.1 or later, and cross configuration requires CMake 3.19 or later. + +
+The 23 members — feature, module, mcpp floor, behaviour, doc, maintainer + +| feature | module | mcpp floor | what it does | doc | maintainer | +|---|---|---|---|---|---| +| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [rules](docs/10-rules.md#rules-ascendc) | @Sunrisepeak | +| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [rules](docs/10-rules.md#rules-cuda) | @Sunrisepeak | +| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [rules](docs/10-rules.md#rules-hip) | @Sunrisepeak | +| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](docs/10-rules.md#rules-metal) | @Sunrisepeak | +| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](docs/11-rules-qt.md) | @Sunrisepeak | +| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](docs/12-rules-qml.md) | @Sunrisepeak | +| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](docs/10-rules.md#rules-slang) | @Sunrisepeak | +| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](docs/10-rules.md#rules-spirv) | @Sunrisepeak | +| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](docs/10-rules.md#rules-swift) | @Sunrisepeak | +| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](docs/10-rules.md#rules-sycl) | @Sunrisepeak | +| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | Writes a data file into a header the program compiles in. | [tools-embed](docs/20-tools-embed.md) | @Sunrisepeak | +| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | Generates the `extern "C"` boundary and the C++ module of a code island. | [tools-island](docs/21-tools-island.md) | @Sunrisepeak | +| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [tools-steps](docs/22-tools-steps.md) | @Sunrisepeak | +| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [dist](docs/30-dist.md#dist-appimage) | @Sunrisepeak | +| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | +| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | The same installation as an RPM package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | +| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [dist](docs/30-dist.md#dist-wix) | @Sunrisepeak | +| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [dist-apple](docs/31-dist-apple.md) | @Sunrisepeak | +| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [dist](docs/30-dist.md#dist-web) | @Sunrisepeak | +| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [dist-apk](docs/32-dist-apk.md) | @Sunrisepeak | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-vcpkg) | @Sunrisepeak | +| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3; a cross build 2026.10.30.1 | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved -- for another target, the compilers and words of the engine's contract -- keeps the installation for any build with the same key, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-cmake) | @Sunrisepeak | +| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | Extracts a zip archive the project keeps and places its tree beside the program. | [deps](docs/40-deps.md#deps-archive) | @Sunrisepeak | Some features add a sub-capability to a member: `dist-apk-kotlin` and `dist-apk-maven` (Kotlin sources, a Maven graph), and `deps`, which the deps members imply. -**The general library (0.17.0).** `plugins-core` gives a build program -`mcpp.plugins.declare`, `mcpp.plugins.toolset` (the resolved toolchain, -translated for a foreign build system), `mcpp.plugins.fs` (deterministic file -generation and placement) and `mcpp.plugins.tool` (where a tool a member runs -comes from, one order for every member, 0.19.0). Every member implies it; a build program that uses -only these modules, and a third-party plugin built on them, name it on the -dependency edge. `plugins-testing` adds `mcpp.plugins.testing`, which runs a -plugin function against a stated build context and compares what it declared. -`plugins-toolchain` adds `mcpp.plugins.toolchain`, the builders a root build -program states the build toolchain with (0.19.0). -`plugins-platform` adds `mcpp.plugins.platform`, what a platform's plugin and a -package format's provider state -- the link, the artifacts' names, the seal, -where the runner runs, and `provide_format` -- and `mcpp.plugins` reads a staged -package's `mcpp-package.json` (`mcpp::plugins::package`), 0.20.0, mcpp -2026.10.27.1 ([plugin-development](docs/plugin-development.md#3-layers-names-and-the-engine-floor)). -The first three need mcpp 2026.10.1.3. `surface`, the name of `plugins-core` before -0.17.0, is kept until 2027-03-28. A feature states a mechanism and the tools that -mechanism runs; the libraries and SDKs a program links are the project's -declaration (0.15.0 removed `rules-qt-xim*`; see [rules-qt](docs/rules-qt.md)). - -`mcpp.plugins.accel` reads complete implementation-owned target requests; `mcpp.plugins.progress` enables optional action telemetry. Worker programs can select `plugins-progress` for `mcpp.plugins.progress.writer`, the atomic snapshot writer. See [plugin-development](docs/plugin-development.md#optional-action-progress). +**The general library.** `plugins-core` gives a build program +`mcpp.plugins.declare`, `mcpp.plugins.toolset`, `mcpp.plugins.fs` and +`mcpp.plugins.tool`; every member implies it, and a build program that uses +only these modules names it on the dependency edge. `plugins-testing`, +`plugins-toolchain` and `plugins-platform` add `mcpp.plugins.testing`, +`mcpp.plugins.toolchain` and `mcpp.plugins.platform` (with +`mcpp::plugins::package`); `plugins-progress` adds the optional action +telemetry and its atomic snapshot writer; `mcpp.plugins.accel` reads +implementation-owned target requests. The layers, names and the engine floor +are in [docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor). +`surface`, the name of `plugins-core` before 0.17.0, is kept until 2027-03-28. + +
## Layout @@ -133,25 +126,23 @@ tools/.cppm export module mcpp.tools.; dist/.cppm export module mcpp.dist.; deps/.cppm export module mcpp.deps.; deps/deps.cppm is shared tests// one project per member, built by CI with the pinned mcpp -docs/ one page per member or group of members +docs/ one page per member or group of members ([index](docs/README.md)) ``` ## Adding a member A member is one module file, one feature in `mcpp.toml`, a consumer under `tests/` that CI builds and asserts on, a row in the table above with its mcpp -floor, and a version bump. Its code is the C++23 that GCC with libstdc++, clang -with libc++ and an editor's clangd with libstdc++ all accept, and CI builds or -reads every fixture under each of the three -([docs/plugin-development.md](docs/plugin-development.md#4-the-c-a-plugin-is-written-in)). -The conventions a member follows -- the same for a -third-party or a project's own plugin -- are in -[docs/plugin-development.md](docs/plugin-development.md); the division between -what the engine owns and what the member owns is in -[docs/engine-and-rules.md](docs/engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns). +floor, a page under `docs/`, and a version bump. Its code is the C++23 that GCC +with libstdc++, clang with libc++ and an editor's clangd with libstdc++ all +accept, and CI builds or reads every fixture under each of the three. The +conventions a member follows are in +[docs/01](docs/01-plugin-development.md); the division between what the engine +owns and what the member owns is in +[docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns). ## Releases A tag `v` publishes the source archive; the index descriptor -(`mcpp-index/pkgs/mcpp/mcpp.plugins.lua`) names the GitHub archive and its GitCode -mirror with one sha256. +(`mcpp-index/pkgs/mcpp/mcpp.plugins.lua`) names the GitHub archive and its +GitCode mirror with one sha256. diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..e85c6cd --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,140 @@ +# mcpp-plugins + +> mcpp 的官方构建插件——一个成员,一个 feature,一个模块。 + +[English](README.md) | 简体中文 + +本文是 [README.md](README.md) 的中文镜像;英文为权威版本,两处不一致时以英文为准。 + +[![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) +[![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) + +mcpp 是一个带有构建插件框架的通用引擎;插件来自本包(`mcpp:plugins`)、来自 +第三方,或来自项目自身,而 `build.mcpp` 是项目使用它们的地方:它按成员声明 +的名字导入成员模块,配置并调用它。这条边是 `[build-dependencies]` 条目,而 +不是 `[dependencies]`:`host-module = true` 声明要的是哪个构建期产物,该小节 +声明这个包不抵达目标——rule 的库永远不会被链接进产物(mcpp docs/05 §2.6.1)。 + +## 快速开始 + +```toml +[build-dependencies.mcpp] +plugins = { version = "0.27.0", features = ["rules-spirv"], host-module = true } +``` + +```cpp +// build.mcpp +import std; +import mcpp; +import mcpp.rules.spirv; + +int main() { + mcpp::rules::spirv::options opt; + opt.includes = { "shaders" }; + return mcpp::rules::spirv::compile(opt) ? 0 : 1; +} +``` + +## 家族 + +| 家族 | 模块 | 回答的问题 | +|---|---|---| +| rules | `mcpp.rules.` | 一类翻译单元如何被一个 mcpp 不直接驱动的编译器编译 | +| tools | `mcpp.tools.` | 构建程序自己要做什么(见 [`tools/README.md`](tools/README.md)) | +| dist | `mcpp.dist.` | 链接产出什么,以及用户以什么形式安装它 | +| deps | `mcpp.deps.` | 一个库从哪里来 | +| identity | `mcpp.plugins` | 库根,先于每个成员编译;它声明这个集合的版本 | + +第三方插件把模块命名为 `mcpp.<它的 namespace>.*`;`core`、`plugins`、`deps`、 +`rules`、`dist`、`tools` 这几个第二段属于本包与引擎。家族的完整论述,以及 +引擎如何把文件路由给 rule,见 [docs/00](docs/00-engine-and-rules.md);成员 +运行的工具从哪里来,见 [docs/02](docs/02-tool-sources.md)。 + +## 成员 + +自 0.21.0 起整个包需要 mcpp 2026.10.30.1(`[package] mcpp`);列中给出每个 +成员的行为首次所需的发布版。链接可执行文件或共享库的交叉 CMake 子项目需要 +mcpp 2026.11.7.1 或更高,交叉配置需要 CMake 3.19 或更高。 + +
+23 个成员——feature、模块、mcpp 下限、行为、文档、维护者 + +| feature | 模块 | mcpp 下限 | 行为 | 文档 | 维护者 | +|---|---|---|---|---|---| +| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [rules](docs/10-rules.md#rules-ascendc) | @Sunrisepeak | +| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [rules](docs/10-rules.md#rules-cuda) | @Sunrisepeak | +| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [rules](docs/10-rules.md#rules-hip) | @Sunrisepeak | +| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [rules](docs/10-rules.md#rules-metal) | @Sunrisepeak | +| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [rules-qt](docs/11-rules-qt.md) | @Sunrisepeak | +| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3;携带 QML 插件库的包 2026.11.23.1 | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [rules-qml](docs/12-rules-qml.md) | @Sunrisepeak | +| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-slang) | @Sunrisepeak | +| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-spirv) | @Sunrisepeak | +| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [rules](docs/10-rules.md#rules-swift) | @Sunrisepeak | +| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [rules](docs/10-rules.md#rules-sycl) | @Sunrisepeak | +| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | 把数据文件写进程序编译内含的头文件。 | [tools-embed](docs/20-tools-embed.md) | @Sunrisepeak | +| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [tools-island](docs/21-tools-island.md) | @Sunrisepeak | +| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [tools-steps](docs/22-tools-steps.md) | @Sunrisepeak | +| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [dist](docs/30-dist.md#dist-appimage) | @Sunrisepeak | +| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | +| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | +| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [dist](docs/30-dist.md#dist-wix) | @Sunrisepeak | +| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [dist-apple](docs/31-dist-apple.md) | @Sunrisepeak | +| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [dist](docs/30-dist.md#dist-web) | @Sunrisepeak | +| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [dist-apk](docs/32-dist-apk.md) | @Sunrisepeak | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-vcpkg) | @Sunrisepeak | +| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3;交叉构建 2026.10.30.1 | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目——交叉目标时用引擎契约的编译器与措辞;同键的构建复用安装,并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-cmake) | @Sunrisepeak | +| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [deps](docs/40-deps.md#deps-archive) | @Sunrisepeak | + +一些 feature 为成员添加子能力:`dist-apk-kotlin` 与 `dist-apk-maven`(Kotlin +源码、一个 Maven 图),以及 `deps`(deps 成员隐含它)。 + +**通用库。** `plugins-core` 给构建程序 `mcpp.plugins.declare`、 +`mcpp.plugins.toolset`、`mcpp.plugins.fs` 与 `mcpp.plugins.tool`;每个成员都 +隐含它,只用这些模块的构建程序在依赖边上点名它。`plugins-testing`、 +`plugins-toolchain` 与 `plugins-platform` 添加 `mcpp.plugins.testing`、 +`mcpp.plugins.toolchain` 与 `mcpp.plugins.platform`(连同 +`mcpp::plugins::package`);`plugins-progress` 添加可选的 action 遥测及其原子 +快照写入器;`mcpp.plugins.accel` 读取实现自有的目标请求。分层、命名与引擎 +下限见 [docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor)。 +`surface`(`plugins-core` 在 0.17.0 之前的名字)保留至 2027-03-28。 + +
+ +## 布局 + +``` +mcpp.toml 这个包:每个成员一个 feature +src/plugins.cppm export module mcpp.plugins; 版本、mcpp::plugins::surface + (消费者点名的声明)、mcpp::plugins::xml 与 + mcpp::plugins::package(暂存包的元数据) +src/declare.cppm, 构建程序的通用库(`plugins-core`): +src/toolset.cppm, mcpp.plugins.declare、mcpp.plugins.toolset、mcpp.plugins.fs +src/fs.cppm +src/testing.cppm mcpp.plugins.testing(`plugins-testing`) +src/platform.cppm mcpp.plugins.platform(`plugins-platform`) +src/compat/, deps/compat/ + 兼容单元,各自在其头文件注明的日期退役 +rules/.cppm export module mcpp.rules.; +tools/.cppm export module mcpp.tools.; +dist/.cppm export module mcpp.dist.; +deps/.cppm export module mcpp.deps.; deps/deps.cppm 是共享单元 +tests// 每个成员一个项目,CI 用固定的 mcpp 构建 +docs/ 每个成员或成员组一页([索引](docs/README.md)) +``` + +## 添加一个成员 + +一个成员是:一个模块文件,`mcpp.toml` 里的一个 feature,`tests/` 下一个由 +CI 构建并断言的消费者,上表里带 mcpp 下限的一行,`docs/` 下的一页,以及一次 +版本提升。它的代码是 GCC 加 libstdc++、clang 加 libc++ 与编辑器 clangd 加 +libstdc++ 都接受的 C++23,CI 在三者之下构建或读取每个 fixture。成员遵循的 +约定见 [docs/01](docs/01-plugin-development.md);引擎拥有什么、成员拥有什么 +的划分见 +[docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns)。 + +## 发布 + +tag `v<版本号>` 发布源码归档;索引描述符 +(`mcpp-index/pkgs/mcpp/mcpp.plugins.lua`)以同一个 sha256 命名 GitHub 归档 +及其 GitCode 镜像。 From 85b8fd3aac115501022eccc37516fad1418cab4f Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 15:49:52 +0800 Subject: [PATCH 04/18] a member may be a directory, and a unit's private region is a private module fragment --- AGENTS.md | 8 +++++--- README.md | 3 +++ README.zh-CN.md | 2 ++ dist/{ => apple}/apple.cppm | 0 docs/01-plugin-development.md | 16 +++++++++++++++- 5 files changed, 25 insertions(+), 4 deletions(-) rename dist/{ => apple}/apple.cppm (100%) diff --git a/AGENTS.md b/AGENTS.md index fa1de07..8b83a5c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,9 +1,11 @@ # AGENTS.md `mcpp-plugins` is the package of official build plugins for mcpp -(`mcpp:plugins`). One member is one module file, one feature in `mcpp.toml`, -one consumer under `tests/`, one page under `docs/`. This file states the rules -that hold across the repository in their shortest form; each links to the +(`mcpp:plugins`). One member is one module — a single `.cppm`, or a directory +`//` whose `.cppm` keeps the module a consumer imports while +`internal/` holds the machinery — one feature in `mcpp.toml`, one consumer +under `tests/`, one page under `docs/`. This file states the rules that hold +across the repository in their shortest form; each links to the document that states it in full. Where this file and a linked document differ, the linked document holds. diff --git a/README.md b/README.md index 459102a..ab9e8c5 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,9 @@ rules/.cppm export module mcpp.rules.; tools/.cppm export module mcpp.tools.; dist/.cppm export module mcpp.dist.; deps/.cppm export module mcpp.deps.; deps/deps.cppm is shared +// a member that outgrew one file: .cppm keeps the module + a consumer imports, internal/ holds the machinery; the + module name does not change tests// one project per member, built by CI with the pinned mcpp docs/ one page per member or group of members ([index](docs/README.md)) ``` diff --git a/README.zh-CN.md b/README.zh-CN.md index e85c6cd..49b49b1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -119,6 +119,8 @@ rules/.cppm export module mcpp.rules.; tools/.cppm export module mcpp.tools.; dist/.cppm export module mcpp.dist.; deps/.cppm export module mcpp.deps.; deps/deps.cppm 是共享单元 +// 一个文件装不下的成员:.cppm 保留消费者导入的模块名, + internal/ 承载机制;模块名不变 tests// 每个成员一个项目,CI 用固定的 mcpp 构建 docs/ 每个成员或成员组一页([索引](docs/README.md)) ``` diff --git a/dist/apple.cppm b/dist/apple/apple.cppm similarity index 100% rename from dist/apple.cppm rename to dist/apple/apple.cppm diff --git a/docs/01-plugin-development.md b/docs/01-plugin-development.md index 4e1a4fc..be2fb13 100644 --- a/docs/01-plugin-development.md +++ b/docs/01-plugin-development.md @@ -206,10 +206,24 @@ Known differences, each one met in this package: - **A function that reaches mcpplibs.os is not `inline`.** A rule's helper that runs a program (`mcpp::plugins::tool::capture`) or opens a library is defined without `inline`, so it is compiled once in its module and an importer sees its declaration only. Under GCC 16 an importer that reads such a body from an inline function fails: "failed to read compiled module cluster: Bad file data", or an unresolved `std::optional>` at the link (`tests/metal-consumer`, 0.21.0). - **A module does not instantiate `std::filesystem::path`'s iterator.** Under MSVC 14.52 every importer that then touches `std::filesystem` fails inside the STL; `mcpp::plugins::names::components` splits a path as a string instead. +**The private region of a unit.** A member's file, and each unit of a directory +member, reads in three parts: the `export module` line with its imports, the +interface its importers see, and, last, the unit's own private region. In a +unit that is its module's only unit the private region is a private module +fragment — `module :private;` — and the declarations and definitions after it +are the unit's own, never visible to an importer. A unit that shares its module +with other units cannot carry a fragment: its private region is a +`namespace detail` block, and the names a sibling unit imports stay outside it. + ## 5. A new plugin A plugin in this package consists of: -- a module file under `rules/`, `tools/`, `dist/` or `deps/`; +- a module under `rules/`, `tools/`, `dist/` or `deps/` — one file + `/.cppm`, or a directory when the member outgrows one file: + `//.cppm` is the interface a consumer imports, and the units + under `//internal/` carry the machinery as modules named + `mcpp...internal.`. The module name a consumer imports + does not change, and the internals are not part of the contract (§2.5); - a feature in `mcpp.toml`; - a fixture under `tests/` that CI builds and asserts on; - a row in the README's member table with its mcpp floor; From 05a33579de96aaf51f973007f13c607f3f73dbfc Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 15:57:40 +0800 Subject: [PATCH 05/18] dist-apk, dist-apple and the lib root split to the member-directory form --- .github/workflows/ci.yml | 12 +- README.md | 6 +- README.zh-CN.md | 5 +- dist/{ => apk}/apk.cppm | 908 +---------------- dist/apk/internal/libraries.cppm | 232 +++++ dist/apk/internal/manifest.cppm | 467 +++++++++ dist/apk/internal/util.cppm | 277 +++++ dist/apple/apple.cppm | 385 +------ dist/apple/internal/layout.cppm | 91 ++ dist/apple/internal/plist.cppm | 236 +++++ dist/apple/internal/signing.cppm | 91 ++ docs/32-dist-apk.md | 2 +- mcpp.toml | 10 +- segs.json | 1 + src/plugins.cppm | 1645 ------------------------------ src/plugins/graph.cppm | 98 ++ src/plugins/json.cppm | 185 ++++ src/plugins/names.cppm | 207 ++++ src/plugins/package.cppm | 117 +++ src/plugins/plugins.cppm | 61 ++ src/plugins/stage.cppm | 48 + src/plugins/surface.cppm | 756 ++++++++++++++ src/plugins/tree.cppm | 48 + src/plugins/xml.cppm | 169 +++ 24 files changed, 3114 insertions(+), 2943 deletions(-) rename dist/{ => apk}/apk.cppm (68%) create mode 100644 dist/apk/internal/libraries.cppm create mode 100644 dist/apk/internal/manifest.cppm create mode 100644 dist/apk/internal/util.cppm create mode 100644 dist/apple/internal/layout.cppm create mode 100644 dist/apple/internal/plist.cppm create mode 100644 dist/apple/internal/signing.cppm create mode 100644 segs.json delete mode 100644 src/plugins.cppm create mode 100644 src/plugins/graph.cppm create mode 100644 src/plugins/json.cppm create mode 100644 src/plugins/names.cppm create mode 100644 src/plugins/package.cppm create mode 100644 src/plugins/plugins.cppm create mode 100644 src/plugins/stage.cppm create mode 100644 src/plugins/surface.cppm create mode 100644 src/plugins/tree.cppm create mode 100644 src/plugins/xml.cppm diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c378214..0da358e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -228,10 +228,10 @@ jobs: - name: the collection states its own version run: | declared=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' mcpp.toml | head -1) - insource=$(sed -n 's/.*version *= *"\(.*\)";.*/\1/p' src/plugins.cppm | head -1) - echo "mcpp.toml=$declared src/plugins.cppm=$insource" + insource=$(sed -n 's/.*version *= *"\(.*\)";.*/\1/p' src/plugins/plugins.cppm | head -1) + echo "mcpp.toml=$declared src/plugins/plugins.cppm=$insource" if [ "$declared" != "$insource" ]; then - echo "FAIL: mcpp.toml says '$declared' and src/plugins.cppm says '$insource'" + echo "FAIL: mcpp.toml says '$declared' and src/plugins/plugins.cppm says '$insource'" exit 1 fi echo "ok: one version, two files agreeing" @@ -266,8 +266,8 @@ jobs: echo "FAIL: a rule or tool defines its own copy of the derivation" grep -n '^inline std::vector namespace_of\|^inline std::string common_base_dir' rules/*.cppm tools/*.cppm exit 1; } - grep -q '^inline std::vector namespace_of' src/plugins.cppm - grep -q '^inline std::string common_base_dir' src/plugins.cppm + grep -q '^inline std::vector namespace_of' src/plugins/names.cppm + grep -q '^inline std::string common_base_dir' src/plugins/names.cppm echo "ok: one definition, in the lib root, for both lanes" - name: rules-spirv through a consumer @@ -2547,7 +2547,7 @@ jobs: # FLAT, NOT Contents/-SHAPED -- the one difference from the macOS # bundle above, and the whole reason iOS needed its own branch in - # `dist/apple.cppm`. + # `dist/apple/apple.cppm`. if [ -d "$app/Contents" ]; then echo "FAIL: the simulator bundle carries Contents/ -- not a flat iOS layout" exit 1 diff --git a/README.md b/README.md index ab9e8c5..f5f9ff6 100644 --- a/README.md +++ b/README.md @@ -111,9 +111,9 @@ are in [docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine ``` mcpp.toml the package: one feature per member -src/plugins.cppm export module mcpp.plugins; the version, mcpp::plugins::surface - (the declarations a consumer names), mcpp::plugins::xml and - mcpp::plugins::package (a staged package's metadata) +src/plugins/ the lib root: export module mcpp.plugins (the version, + mcpp::plugins::surface, mcpp::plugins::xml, + mcpp::plugins::package), its partitions beside it src/declare.cppm, the general library for build programs (`plugins-core`): src/toolset.cppm, mcpp.plugins.declare, mcpp.plugins.toolset, mcpp.plugins.fs src/fs.cppm diff --git a/README.zh-CN.md b/README.zh-CN.md index 49b49b1..222e99c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -105,9 +105,8 @@ mcpp 2026.11.7.1 或更高,交叉配置需要 CMake 3.19 或更高。 ``` mcpp.toml 这个包:每个成员一个 feature -src/plugins.cppm export module mcpp.plugins; 版本、mcpp::plugins::surface - (消费者点名的声明)、mcpp::plugins::xml 与 - mcpp::plugins::package(暂存包的元数据) +src/plugins/ 库根:export module mcpp.plugins(版本、mcpp::plugins::surface、 + mcpp::plugins::xml、mcpp::plugins::package),分区单元在其旁 src/declare.cppm, 构建程序的通用库(`plugins-core`): src/toolset.cppm, mcpp.plugins.declare、mcpp.plugins.toolset、mcpp.plugins.fs src/fs.cppm diff --git a/dist/apk.cppm b/dist/apk/apk.cppm similarity index 68% rename from dist/apk.cppm rename to dist/apk/apk.cppm index 5d9f785..0681cdd 100644 --- a/dist/apk.cppm +++ b/dist/apk/apk.cppm @@ -104,6 +104,10 @@ import mcpp.plugins; import mcpp.plugins.tool; import mcpp.tools.steps; +import mcpp.dist.apk.internal.util; +import mcpp.dist.apk.internal.manifest; +import mcpp.dist.apk.internal.libraries; + // `std::format` is header-only and used throughout; `std::println` is not -- // see `rules/spirv.cppm` for the libc++-on-macOS-14 measurement that this // collection's every member has followed since. @@ -329,127 +333,12 @@ struct plan { explicit operator bool() const { return applies; } }; -// ─── Internals ───────────────────────────────────────────────────────────── - -namespace fs = std::filesystem; - -inline bool is_file(const std::string& p) { - std::error_code ec; - return !p.empty() && fs::is_regular_file(p, ec); -} -inline bool is_dir(const std::string& p) { - std::error_code ec; - return !p.empty() && fs::is_directory(p, ec); -} - -// THE HOST, NOT THE TARGET: every tool here runs on the machine that builds. -// A Windows host names its programs `.exe` and separates a class path -// with `;`. -inline bool host_is_windows() { - return std::string_view(mcpp::host()).find("windows") != std::string_view::npos; -} -inline std::string host_program(const fs::path& dir, std::string_view name) { - return (dir / (std::string(name) + (host_is_windows() ? ".exe" : ""))).string(); -} -inline const char* class_path_separator() { return host_is_windows() ? ";" : ":"; } - - -// Is `root` under the package root, `mcpp::manifest_dir()`, and if so, what -// is its manifest-relative form? A project root is declared with -// `rerun_if_changed_glob` below (a file appearing there re-runs the build -// program); a dependency root is not -- its file set changes only with the -// dependency's version, already in the build's fingerprint, and the glob's -// own walk does not reach outside the package root regardless (design -// record §3.3). Same shape as `mcpp.tools.island`'s overlap check: -// `weakly_canonical` plus `lexically_relative`, never the iterator that -// poisons an importer under GCC 16 / MSVC (`mcpp::plugins::names:: -// relative_to`'s own header) -- safe here because this member is its own -// module and imports no sibling that would inherit the instantiation. -// -// THE RETURNED PATH IS MANIFEST-RELATIVE, NOT ABSOLUTE, BECAUSE THE GLOB -// PATTERN MUST BE. The engine matches a glob by comparing the CANDIDATE made -// relative to the package root against the pattern -// (`modules/manifest/src/glob.cppm`, `path_matches_glob`); an absolute -// pattern is compared against a relative candidate and never matches -// anything, so the fingerprint is always the empty set and a `.java` file -// appearing never changes it -- the criterion's "no" reading as silence -// (design record, rule 8). `opt.java_sources`'s own roots are absolute -// (`mcpp::manifest_dir()` composed with a subdirectory), so declaring the -// glob with `root` itself, not this function's return value, was exactly -// that defect. -// -// A root inside the build's output -- `mcpp::out_dir()`, or a directory the -// glob walk never enters (`target`, `.mcpp`, `.git`) -- is GENERATED: the -// build program that writes its files already runs on every build, and a glob -// there can never match anything, which the engine reports as a warning. It is -// answered as outside the project, so it is an action input and no glob. -inline std::optional root_in_project(const std::string& root) { - std::error_code ec; - const auto a = fs::weakly_canonical(root, ec); - if (ec) return std::nullopt; - const auto b = fs::weakly_canonical(mcpp::manifest_dir(), ec); - if (ec) return std::nullopt; - const auto rel = a.lexically_relative(b).generic_string(); - if (rel.empty() || rel.starts_with("..")) return std::nullopt; - const auto out = fs::weakly_canonical(std::string(mcpp::out_dir()), ec); - if (!ec) { - const auto inside = a.lexically_relative(out).generic_string(); - if (!inside.empty() && !inside.starts_with("..")) return std::nullopt; - } - const auto first = rel.substr(0, rel.find('/')); - if (first == "target" || first == ".mcpp" || first == ".git") return std::nullopt; - return rel; -} - -inline bool write_if_different(const fs::path& path, std::string_view bytes) { - std::error_code ec; - fs::create_directories(path.parent_path(), ec); - if (std::ifstream in(path, std::ios::binary); in) { - std::string old((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - if (old == bytes) return true; - } - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out) return false; - out.write(bytes.data(), static_cast(bytes.size())); - return static_cast(out); -} - inline std::string target_for(const options& opt) { if (!opt.target.empty()) return opt.target; const char* n = mcpp::package_name(); return (n && *n) ? std::string(n) : std::string(); } -// `/`, from the row's arch and no other input -- see `artifact_naming` -// for the engine's own row-decides-the-name principle, applied here to -// Android's own ABI vocabulary rather than a file suffix. -inline std::string abi_for() { - const std::string a = mcpp::target_arch(); - if (a == "aarch64") return "arm64-v8a"; - if (a == "x86_64") return "x86_64"; - return {}; -} - -// Index loop, not a range-for: GCC 16.1.0 refuses to inline -// `__normal_iterator>::operator*() const` when a -// module interface unit that imports `std` also range-for's (or otherwise -// takes `basic_string`'s own iterator over) a `std::string` or -// `std::filesystem::path` -- -// -// bits/stl_iterator.h:1089:7: error: inlining failed in call to -// 'always_inline' '... operator*() const' -// -// -- the same family of defect #18 met under MSVC's `_Path_iterator` (see -// `mcpp::plugins::names::relative_to` and `components()` in -// `src/plugins.cppm`), here on `libstdc++`'s `basic_string` iterator instead -// of the filesystem one. `s[i]` indexes the string directly and never forms -// that iterator, so it compiles under both. -inline std::string replace_dashes(std::string s) { - for (std::size_t i = 0; i < s.size(); ++i) if (s[i] == '-') s[i] = '_'; - return s; -} - inline std::string application_id_for(const options& opt, const std::string& target) { if (!opt.application_id.empty()) return opt.application_id; const char* ns = mcpp::package_namespace(); @@ -465,757 +354,6 @@ inline std::string label_for(const options& opt) { return (n && *n) ? std::string(n) : std::string("app"); } -// `xim:android-platform`'s own resolved directory is named after the -// version it resolved -- "36-r2", "35-r2", "34-r3" (`pkgs/a/android- -// platform.lua`'s own `extract_dir()` recovers the API level the identical -// way, from the leading digits of its OWN version string) -- so the level a -// project pinned is read back from the directory `xpkg_dir` already -// answered, rather than duplicated as a second option this member could -// disagree with. -inline std::string api_level_from_platform_dir(const std::string& dir) { - if (dir.empty()) return {}; - const std::string leaf = fs::path(dir).filename().string(); - std::string digits; - for (std::size_t i = 0; i < leaf.size(); ++i) { - if (leaf[i] >= '0' && leaf[i] <= '9') digits += leaf[i]; - else break; - } - return digits; -} - -inline std::string replace_all_copy(std::string s, std::string_view from, std::string_view to) { - if (from.empty()) return s; - std::size_t pos = 0; - while ((pos = s.find(from, pos)) != std::string::npos) { - s.replace(pos, from.size(), to); - pos += to.size(); - } - return s; -} - -// The eight tokens a manifest template may use. `version_name` is the -// package version as written; `version_code` is Android's monotonic integer -// derived from its leading numeric segments (`version_code_for`). -inline const std::vector& manifest_tokens() { - static const std::vector v = { - "application_id", "label", "activity", "lib_name", "min_sdk", "target_sdk", - "version_name", "version_code"}; - return v; -} - -// `android:versionCode` from a version string: major * 1000000 + minor * 1000 -// + patch over the first three dot-separated numeric segments, so that every -// release a project cuts orders after the one before it, and "1" when the -// string starts with no number at all -- Android refuses 0 and a manifest -// without the attribute installs but never updates. -inline std::string version_code_for(const std::string& version) { - long long code = 0, seg = 0; - int segments = 0; - bool digits = false; - const long long weights[3] = {1000000, 1000, 1}; - for (std::size_t i = 0; i <= version.size() && segments < 3; ++i) { - const char c = i < version.size() ? version[i] : '\0'; - if (c >= '0' && c <= '9') { seg = seg * 10 + (c - '0'); digits = true; continue; } - if (!digits) break; - code += std::min(seg, 999) * weights[segments] ; - ++segments; seg = 0; digits = false; - if (c != '.') break; - } - if (segments == 0) return "1"; - if (code <= 0) return "1"; - return std::to_string(code); -} - -// Every `{{...}}` a template names, in first-appearance order, duplicates -// dropped -- what both checks in `render_manifest` below read. -inline std::vector tokens_in(const std::string& text) { - std::vector out; - std::size_t i = 0; - while ((i = text.find("{{", i)) != std::string::npos) { - const auto close = text.find("}}", i + 2); - if (close == std::string::npos) break; - std::string name = text.substr(i + 2, close - (i + 2)); - if (std::ranges::find(out, name) == out.end()) out.push_back(std::move(name)); - i = close + 2; - } - return out; -} - -// The tokens `assets/mcpp-run.json` is ALSO written from -- a template that -// omits one silently ships a run sidecar the manifest disagrees with. -// `application_id` and `activity` are required unconditionally; `lib_name` -// joins them at level 0, where the manifest's own `` element is -// the only place the loaded library's name is recorded. -inline std::vector required_manifest_tokens(bool has_code, bool native_activity) { - static_cast(has_code); - std::vector v = {"application_id", "activity"}; - if (native_activity) v.push_back("lib_name"); - return v; -} -inline std::vector required_manifest_tokens(bool has_code) { - return required_manifest_tokens(has_code, !has_code); -} - -// THE BUILT-IN DEFAULT, EXPRESSED WITH THE TOKENS. This is `manifest_xml`'s -// 0.8.0 output verbatim, with every literal value it used to compute -// replaced by the token that value now comes through -- so level 0 with no -// project template renders byte-identical to what 0.8.0 wrote -// (`tests/apk-consumer`). `{{activity}}` carries the level-0 constant -// (`android.app.NativeActivity`) as well as a level-1 project's own class, -// because the run sidecar needs the activity name at both levels and the -// required-token check reads the TEMPLATE TEXT, not the level -- so the same -// token has to appear on both of this function's two branches. -// `{{lib_name}}`'s `` element exists only at level 0: it -// announces which shared object `NativeActivity` should load, and a -// Java-hosted activity finds its own native library another way. -// -// NO XML COMMENT MARKS THE THREE REQUIRED TOKENS IN THIS STRING, ON PURPOSE: -// this exact text is compared byte-for-byte against 0.8.0's output, which -// carried none, and a template with no author to read a comment gains -// nothing from one. The design record's "mark the required tokens" is done -// here instead, in the `REQUIRED` labels on the C++ lines that build them. -// A NATIVE ACTIVITY MAY STILL CARRY CODE (0.11.0): a level-0 application whose -// libraries or archives bring classes keeps `android.app.NativeActivity` and its -// `lib_name` element, with `android:hasCode="true"` so that the dex is loaded. -inline std::string default_manifest_template(bool has_code, bool native_activity) { - std::string a = - "\n" - "\n" // REQUIRED - " \n" - " \n" - " \n"; - if (native_activity) { - a += " \n"; // REQUIRED at level 0 - } - a += " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - "\n"; - return a; -} -inline std::string default_manifest_template(bool has_code) { - return default_manifest_template(has_code, !has_code); -} - -// Checks a manifest template and substitutes it, or refuses (returning -// `false` with `reason` and `message` set) naming exactly what is wrong; the -// caller reports `message` (see `refuse`). -// -// THIS CHECK IS `dist-apk`'S OWN, DELIBERATELY NOT `dist-web`'S. A manifest -// has a closed, six-token vocabulary this member itself defines; a web page -// template may legitimately carry `{{ }}` for a front-end framework (Vue, -// Mustache, ...) this member never reads, so `dist-web` leaves an unknown -// token literal for that project's own tooling to read. An unknown token -// here would otherwise reach `aapt2` unsubstituted and fail there with a -// worse message, and the refusal belongs where the name is known -- the same -// rule read against two different facts, not an inconsistency between the -// two members. -inline bool render_manifest(const std::string& templateText, bool has_code, bool native_activity, - const std::string& appId, const std::string& label, - const std::string& activityName, const std::string& libName, - const std::string& minSdk, const std::string& targetSdk, - const std::string& versionName, const std::string& versionCode, - std::string& out, std::string& reason, - std::string& message) { - for (auto const& tok : tokens_in(templateText)) { - if (std::ranges::find(manifest_tokens(), tok) == manifest_tokens().end()) { - message = "mcpp.dist.apk: the manifest template names an unknown " - "token '{{" + tok + "}}'; expected one of application_id, " - "label, activity, lib_name, min_sdk, target_sdk, " - "version_name, version_code."; - reason = "unknown manifest template token '" + tok + "'"; - return false; - } - } - for (auto const& tok : required_manifest_tokens(has_code, native_activity)) { - if (templateText.find("{{" + tok + "}}") == std::string::npos) { - message = "mcpp.dist.apk: the manifest template does not use '{{" + tok - + "}}', and assets/mcpp-run.json, which adb-run starts the " - "application from, is written from the same value: add {{" - + tok + "}} to the template."; - reason = "manifest template missing required token '" + tok + "'"; - return false; - } - } - out = templateText; - out = replace_all_copy(std::move(out), "{{application_id}}", appId); - out = replace_all_copy(std::move(out), "{{label}}", label); - out = replace_all_copy(std::move(out), "{{activity}}", activityName); - out = replace_all_copy(std::move(out), "{{lib_name}}", libName); - out = replace_all_copy(std::move(out), "{{min_sdk}}", minSdk); - out = replace_all_copy(std::move(out), "{{target_sdk}}", targetSdk); - out = replace_all_copy(std::move(out), "{{version_name}}", versionName); - out = replace_all_copy(std::move(out), "{{version_code}}", versionCode); - return true; -} -inline bool render_manifest(const std::string& templateText, bool has_code, - const std::string& appId, const std::string& label, - const std::string& activityName, const std::string& libName, - const std::string& minSdk, const std::string& targetSdk, - const std::string& versionName, const std::string& versionCode, - std::string& out, std::string& reason, - std::string& message) { - return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName, - minSdk, targetSdk, versionName, versionCode, out, reason, message); -} - -inline std::string run_json(const std::string& app_id, const std::string& activity_name) { - // Hand-built, not through a JSON library this collection does not - // depend on: two string fields, neither of which this member lets - // through unescaped input (`app_id` is derived from the package's own - // identifiers, `activity_name` is a Java class name or the literal - // `android.app.NativeActivity`). - return std::format("{{\"package\": \"{}\", \"activity\": \"{}\"}}\n", - app_id, activity_name); -} - -// Copies `src` (a file or a directory, recursively) into `dstRoot/relName`, -// listing every regular file it wrote -- so the caller can declare each one -// as an action input rather than the directory itself ("name the input; do -// not harvest a directory", docs/31). -inline void collect_tree(const fs::path& src, const fs::path& dst, - std::vector& out) { - std::error_code ec; - if (fs::is_regular_file(src, ec)) { - fs::create_directories(dst.parent_path(), ec); - fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec); - out.push_back(dst.string()); - return; - } - for (auto& e : fs::recursive_directory_iterator(src, ec)) { - if (ec) break; - if (!e.is_regular_file(ec)) continue; - auto rel = fs::relative(e.path(), src, ec); - auto to = dst / rel; - fs::create_directories(to.parent_path(), ec); - fs::copy_file(e.path(), to, fs::copy_options::overwrite_existing, ec); - out.push_back(to.string()); - } -} - -namespace xml = mcpp::plugins::xml; - -// ─── Paths a project names ───────────────────────────────────────────────── - -// A project names its directories relative to its manifest; the actions this -// member declares run later, from the build directory, where a relative path -// names nothing (the defect `dist/apple.cppm` measured with `ditto ios-icons`). -// Every path option is therefore resolved here, once, against -// `mcpp::manifest_dir()`; an absolute path is left alone. -inline std::string resolve_path(const std::string& p) { - if (p.empty()) return p; - const fs::path path(p); - if (path.is_absolute()) return p; - return (fs::path(mcpp::manifest_dir()) / path).lexically_normal().string(); -} - -inline void resolve_paths(std::vector& v) { - for (auto& p : v) p = resolve_path(p); -} - -// Every regular file under `root` whose extension is `ext`, sorted. -inline std::vector files_with_extension(const std::string& root, std::string_view ext) { - std::vector out; - std::error_code ec; - for (auto& e : fs::recursive_directory_iterator(root, ec)) { - if (ec) break; - if (e.is_regular_file(ec) && e.path().extension() == ext) - out.push_back(e.path().string()); - } - std::ranges::sort(out); - return out; -} - -inline bool dir_has_files(const std::string& root) { - std::error_code ec; - for (auto& e : fs::recursive_directory_iterator(root, ec)) { - if (ec) break; - if (e.is_regular_file(ec)) return true; - } - return false; -} - -inline std::string read_file(const std::string& path) { - std::ifstream in(path, std::ios::binary); - return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); -} - -inline std::string join(const std::vector& v, std::string_view sep) { - std::string out; - for (std::size_t i = 0; i < v.size(); ++i) { - if (i) out += sep; - out += v[i]; - } - return out; -} - -// ─── SHA-256 ─────────────────────────────────────────────────────────────── - -// FIPS 180-4, over bytes held in memory. Here for one purpose: a Maven lock -// records each artifact's digest, and a build that reads a cached artifact -// checks it against the lock before the file reaches a package. The inputs are -// libraries of a few megabytes, so reading a file whole is the simple choice. -inline std::string sha256_hex(std::string_view data) { - static constexpr std::uint32_t k[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; - std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; - std::string msg(data); - const std::uint64_t bits = static_cast(data.size()) * 8u; - msg.push_back(static_cast(0x80)); - while (msg.size() % 64 != 56) msg.push_back('\0'); - for (int i = 7; i >= 0; --i) msg.push_back(static_cast((bits >> (i * 8)) & 0xffu)); - const auto rotr = [](std::uint32_t x, int n) -> std::uint32_t { return (x >> n) | (x << (32 - n)); }; - for (std::size_t off = 0; off < msg.size(); off += 64) { - std::uint32_t w[64]; - for (int i = 0; i < 16; ++i) { - const auto byte = [&](int j) { - return static_cast(static_cast(msg[off + static_cast(i * 4 + j)])); - }; - w[i] = (byte(0) << 24) | (byte(1) << 16) | (byte(2) << 8) | byte(3); - } - for (int i = 16; i < 64; ++i) { - const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); - const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16] + s0 + w[i - 7] + s1; - } - std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; - for (int i = 0; i < 64; ++i) { - const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i]; - const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); - hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; - } - h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; - } - std::string hex; - hex.reserve(64); - for (int i = 0; i < 8; ++i) hex += std::format("{:08x}", h[i]); - return hex; -} - -inline std::string sha256_file(const std::string& path) { - return is_file(path) ? sha256_hex(read_file(path)) : std::string(); -} - -// ─── Running a tool at plan time ───────────────────────────────────────── - -// Runs `argv`, returning its exit status and its combined output, through -// `mcpp::plugins::tool::capture`: no shell between, so no argument is quoted. -// Only the explicit Maven modes and AAR extraction call it; an ordinary build -// of an unchanged project runs nothing here. -int run_capture(const std::vector& argv, std::string& output, - const std::filesystem::path& cwd = {}) { - auto r = mcpp::plugins::tool::capture(argv, /*with_errors=*/true, cwd); - output = std::move(r.out); - return r.status; -} - -// ─── Merging library manifests into the application's ──────────────────── - -// What `mcpp.dist.apk` merges, and the rules it applies. This is a SUBSET of -// the Android Gradle plugin's manifest merger, stated rather than implied: -// -// - ``, ``, ``, -// `` and the other children of `` are added when -// the application has no element of the same kind and `android:name`; -// `` children are unioned; -// - the children of a library's `` -- activities, aliases, -// services, receivers, providers, ``, `` -- are -// added the same way; a library's `` attribute the -// application does not state is added; -// - an identical element is not added twice; a DIFFERENT element under the -// same name is refused, naming it, unless the application's own element -// says `tools:node="replace"` (the application's wins) or -// `tools:node="remove"` (neither is kept); a differing `` -// attribute is refused unless the application lists it in `tools:replace`; -// - a library's `` above the application's -// floor is refused, as Gradle refuses it; -// - `${applicationId}` is substituted everywhere, and any other `${...}` -// placeholder is refused, naming it -- no placeholder source exists here; -// - every `tools:` attribute and the `xmlns:tools` declaration are removed -// from the result. -// -// Anything a project needs beyond that is stated in its own manifest template, -// which this member never edits except to add what the libraries declare. -struct manifest_source { - std::string label; // what a refusal names: a library, an AAR, a coordinate - std::string text; -}; - -inline std::string manifest_key(const xml::node& n) { - if (n.name == "uses-feature") { - const std::string nm = xml::attr_of(n, "android:name"); - return nm.empty() ? "uses-feature@glEsVersion=" + xml::attr_of(n, "android:glEsVersion") - : "uses-feature:" + nm; - } - return n.name + ":" + xml::attr_of(n, "android:name"); -} - -inline void strip_tools(xml::node& n) { - std::erase_if(n.attrs, [](const std::pair& a) { - return a.first.starts_with("tools:") || a.first == "xmlns:tools"; - }); - for (auto& c : n.children) strip_tools(c); -} - -inline std::string canonical_xml(xml::node n) { - strip_tools(n); - std::string out; - xml::write(n, out, 0); - return out; -} - -inline bool substitute_placeholders(xml::node& n, const std::string& appId, - const std::string& label, std::string& message) { - for (auto& a : n.attrs) { - a.second = replace_all_copy(a.second, "${applicationId}", appId); - const auto p = a.second.find("${"); - if (p != std::string::npos) { - const auto e = a.second.find('}', p); - message = std::format( - "mcpp.dist.apk: {} uses the manifest placeholder '{}' in {}=\"{}\"; " - "only ${{applicationId}} is substituted here.", label, - a.second.substr(p, e == std::string::npos ? std::string::npos : e - p + 1), - a.first, a.second); - return false; - } - } - for (auto& c : n.children) - if (!substitute_placeholders(c, appId, label, message)) return false; - return true; -} - -inline xml::node* find_child(xml::node& parent, std::string_view name) { - for (auto& c : parent.children) if (c.name == name) return &c; - return nullptr; -} - -// Removes every element the application marked `tools:node="remove"`: a marker -// that says "this is not wanted", not an element to ship. -inline void drop_removed(xml::node& n) { - std::erase_if(n.children, [](const xml::node& c) { return xml::attr_of(c, "tools:node") == "remove"; }); - for (auto& c : n.children) drop_removed(c); -} - -inline bool merge_manifests(std::string& appText, const std::vector& libs, - const std::string& appId, const std::string& minSdk, - std::string& reason, std::string& message) { - xml::node app; - std::string err; - if (!xml::parse(appText, app, err) || app.name != "manifest") { - reason = "the application manifest cannot be read"; - message = "mcpp.dist.apk: the application's manifest cannot be read for merging: " - + (err.empty() ? std::string("its root element is not ") : err); - return false; - } - if (!substitute_placeholders(app, appId, "the application's manifest", message)) { - reason = "unknown manifest placeholder"; - return false; - } - xml::node* application = find_child(app, "application"); - if (!application) { - app.children.push_back(xml::node{"application", {}, {}, {}}); - application = &app.children.back(); - } - const auto parse_number = [](const std::string& s) { - long v = 0; - for (std::size_t i = 0; i < s.size(); ++i) { - if (s[i] < '0' || s[i] > '9') return -1L; - v = v * 10 + (s[i] - '0'); - } - return s.empty() ? -1L : v; - }; - - for (auto const& lib : libs) { - xml::node m; - if (!xml::parse(lib.text, m, err) || m.name != "manifest") { - reason = "a library manifest cannot be read"; - message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", lib.label, - err.empty() ? std::string("its root element is not ") : err); - return false; - } - if (!substitute_placeholders(m, appId, lib.label, message)) { - reason = "unknown manifest placeholder"; - return false; - } - for (auto& c : m.children) { - if (c.name.empty()) continue; - if (c.name == "uses-sdk") { - const long want = parse_number(xml::attr_of(c, "android:minSdkVersion")); - const long have = parse_number(minSdk); - if (want > 0 && have > 0 && want > have) { - reason = "a library needs a higher minSdkVersion"; - message = std::format( - "mcpp.dist.apk: {} declares android:minSdkVersion {}, above this " - "application's floor {}. Raise the row's min_api_level, or do not " - "depend on it.", lib.label, want, have); - return false; - } - continue; - } - if (c.name == "application") { - const std::string replaced = xml::attr_of(*application, "tools:replace"); - for (auto const& a : c.attrs) { - if (a.first.starts_with("tools:")) continue; - const std::string mine = xml::attr_of(*application, a.first); - if (mine.empty()) { xml::set_attr(*application, a.first, a.second); continue; } - if (mine == a.second) continue; - bool listed = false; - std::size_t start = 0; - while (start <= replaced.size()) { - auto comma = replaced.find(',', start); - if (comma == std::string::npos) comma = replaced.size(); - if (xml::trim_copy(replaced.substr(start, comma - start)) == a.first) { listed = true; break; } - start = comma + 1; - } - if (!listed) { - reason = "conflicting attribute"; - message = std::format( - "mcpp.dist.apk: is \"{}\" in the application and " - "\"{}\" in {}. Add tools:replace=\"{}\" to the application's " - " to keep its value.", a.first, mine, a.second, lib.label, a.first); - return false; - } - } - for (auto& cc : c.children) { - if (cc.name.empty()) continue; - const std::string key = manifest_key(cc); - xml::node* mine = nullptr; - for (auto& x : application->children) - if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } - if (!mine) { application->children.push_back(cc); continue; } - const std::string node = xml::attr_of(*mine, "tools:node"); - if (node == "remove" || node == "replace") continue; - if (canonical_xml(*mine) == canonical_xml(cc)) continue; - reason = "conflicting manifest element"; - message = std::format( - "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application " - "and {}. State tools:node=\"replace\" on the application's element to keep " - "it, or tools:node=\"remove\" to drop both.", cc.name, - xml::attr_of(cc, "android:name"), lib.label); - return false; - } - continue; - } - if (c.name == "queries") { - xml::node* q = find_child(app, "queries"); - if (!q) { - auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); - q = &*app.children.insert(pos, xml::node{"queries", {}, {}, {}}); - application = find_child(app, "application"); - } - for (auto& qc : c.children) { - if (qc.name.empty()) continue; - const std::string canon = canonical_xml(qc); - const bool present = std::ranges::any_of(q->children, [&](const xml::node& x) { - return canonical_xml(x) == canon; - }); - if (!present) q->children.push_back(qc); - } - continue; - } - const std::string key = manifest_key(c); - xml::node* mine = nullptr; - for (auto& x : app.children) - if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } - if (mine) { - const std::string node = xml::attr_of(*mine, "tools:node"); - if (node == "remove" || node == "replace") continue; - if (canonical_xml(*mine) == canonical_xml(c)) continue; - reason = "conflicting manifest element"; - message = std::format( - "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application and " - "{}. State tools:node=\"replace\" on the application's element to keep it, or " - "tools:node=\"remove\" to drop both.", c.name, xml::attr_of(c, "android:name"), lib.label); - return false; - } - auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); - app.children.insert(pos, c); - application = find_child(app, "application"); - } - } - - drop_removed(app); - strip_tools(app); - appText = "\n"; - xml::write(app, appText, 0); - return true; -} - -// ─── JSON ───────────────────────────────────────────────────────────────── -// -// coursier's report is read with the collection's shared reader, the one -// `mcpp::plugins::graph` reads the engine's graph document with. -using json_value = mcpp::plugins::json::value; -using mcpp::plugins::json::parse_json; - -// ─── The Maven lock ─────────────────────────────────────────────────────── - -// One line per fact, sorted, so that a diff of a lock says what changed: -// -// request what the project asked for -// repository where resolution looked, in order -// artifact -// -// `` is relative to the cache root, which is where coursier keeps the -// file under `//` (`--cache` is always passed, so the root -// this member computes and the one coursier writes to are the same directory). -struct maven_artifact { - std::string coordinate; - std::string type; - std::string path; - std::string sha256; -}; - -struct maven_lock { - bool found = false; - std::vector requests; - std::vector repositories; - std::vector artifacts; -}; - -inline maven_lock read_maven_lock(const std::string& path) { - maven_lock lock; - if (!is_file(path)) return lock; - lock.found = true; - std::istringstream in(read_file(path)); - std::string line; - while (std::getline(in, line)) { - if (line.empty() || line[0] == '#') continue; - std::istringstream fields(line); - std::string kind; - fields >> kind; - if (kind == "request") { std::string v; fields >> v; lock.requests.push_back(v); } - else if (kind == "repository") { std::string v; fields >> v; lock.repositories.push_back(v); } - else if (kind == "artifact") { - maven_artifact a; - fields >> a.coordinate >> a.type >> a.path >> a.sha256; - lock.artifacts.push_back(std::move(a)); - } - } - return lock; -} - -inline std::string render_maven_lock(const maven_lock& lock) { - std::string out = - "# mcpp.dist.apk Maven lock. Written by MCPP_DIST_APK_MAVEN=update; commit it.\n" - "# An ordinary build reads only these artifacts, from the cache, and checks each digest.\n"; - for (auto const& r : lock.requests) out += "request " + r + "\n"; - for (auto const& r : lock.repositories) out += "repository " + r + "\n"; - for (auto const& a : lock.artifacts) - out += "artifact " + a.coordinate + " " + a.type + " " + a.path + " " + a.sha256 + "\n"; - return out; -} - -// Where coursier's cache is: the option, then `COURSIER_CACHE`, then coursier's -// own default on this host, so a developer's `cs` and this member share one. -inline std::string maven_cache_root(const std::string& option) { - if (!option.empty()) return option; - if (const char* env = std::getenv("COURSIER_CACHE"); env && *env) return env; - const char* home = std::getenv("HOME"); - const std::string h = home ? home : ""; - if (std::string(mcpp::host()).find("apple") != std::string::npos || - std::string(mcpp::host()).find("macos") != std::string::npos) - return h + "/Library/Caches/Coursier/v1"; - if (const char* xdg = std::getenv("XDG_CACHE_HOME"); xdg && *xdg) return std::string(xdg) + "/coursier/v1"; - return h + "/.cache/coursier/v1"; -} - -// `group:artifact:version`, three non-empty parts and a fixed version: a range -// would make the lock the only place the version is decided. -inline bool plain_coordinate(const std::string& c) { - int colons = 0; - for (std::size_t i = 0; i < c.size(); ++i) { - if (c[i] == ':') ++colons; - if (c[i] == '[' || c[i] == '(' || c[i] == ',' || c[i] == '+' || c[i] == ' ') return false; - } - return colons == 2 && !c.starts_with(":") && !c.ends_with(":") && c.find("::") == std::string::npos; -} - -// coursier names an AAR-packaged module `group:artifact:aar:version`; the lock -// records the coordinate a project writes. -inline std::string plain_form(const std::string& coord) { - return replace_all_copy(coord, ":aar:", ":"); -} - -// ─── An AAR, unpacked ───────────────────────────────────────────────────── - -// What an Android library archive contributes: its manifest (merged), its -// `res/` (linked under its own package), its classes (`classes.jar`, and any -// `libs/*.jar` it carries), its native libraries (`jni//`) and its -// `assets/`. `R.txt`, `proguard.txt`, `lint.jar` and `public.txt` are not -// read: this member does not shrink, lint or compute non-transitive R classes. -struct library_input { - std::string label; - std::string package; - std::string resources; - std::string manifest; - std::string assets; - std::string jni; - std::vector java; - std::vector kotlin; - std::vector jars; -}; - -// Unpacked with the JDK's `jar` at plan time, once per archive content: a stamp -// beside the tree records the archive's digest, and a matching stamp skips the -// work on the next plan. -inline bool unpack_aar(const std::string& aar, const fs::path& dest, const std::string& jarTool, - library_input& out, std::string& message) { - const std::string digest = sha256_file(aar); - if (digest.empty()) { - message = std::format("mcpp.dist.apk: the AAR {} was not found.", aar); - return false; - } - const fs::path stamp = dest / ".mcpp-aar-sha256"; - if (read_file(stamp.string()) != digest) { - std::error_code ec; - fs::remove_all(dest, ec); - fs::create_directories(dest, ec); - std::string output; - const int rc = run_capture({jarTool, "xf", aar}, output, dest); - if (rc != 0) { - message = std::format("mcpp.dist.apk: unpacking {} with {} failed ({}): {}", aar, jarTool, rc, output); - return false; - } - write_if_different(stamp, digest); - } - const std::string manifest = (dest / "AndroidManifest.xml").string(); - if (!is_file(manifest)) { - message = std::format("mcpp.dist.apk: {} carries no AndroidManifest.xml, so it is not an AAR.", aar); - return false; - } - xml::node m; - std::string err; - if (!xml::parse(read_file(manifest), m, err) || m.name != "manifest") { - message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", aar, err); - return false; - } - out.package = xml::attr_of(m, "package"); - out.manifest = manifest; - if (is_dir((dest / "res").string()) && dir_has_files((dest / "res").string())) out.resources = (dest / "res").string(); - if (is_dir((dest / "assets").string()) && dir_has_files((dest / "assets").string())) out.assets = (dest / "assets").string(); - if (is_dir((dest / "jni").string())) out.jni = (dest / "jni").string(); - if (is_file((dest / "classes.jar").string())) out.jars.push_back((dest / "classes.jar").string()); - for (auto const& j : files_with_extension((dest / "libs").string(), ".jar")) out.jars.push_back(j); - return true; -} - // ─── The staged tree ─────────────────────────────────────────────────────── // Records a refusal three ways, because each reaches a different reader. The @@ -1269,43 +407,6 @@ inline plan& refuse(plan& p, std::string reason, const std::string& message) { return p; } -// Android's own ABI names, the directory names a several-triple tree stages -// under (`lib//`) and an APK stores its native libraries under. -inline bool is_android_abi(std::string_view name) { - return name == "arm64-v8a" || name == "x86_64" || name == "armeabi-v7a" || name == "x86"; -} - -// One ABI's native libraries, as the staged tree carries them. -struct native_leg { - std::string abi; - std::vector libraries; // absolute paths, sorted -}; - -inline std::vector shared_objects_in(const fs::path& dir) { - std::vector out; - std::error_code ec; - for (auto& e : fs::directory_iterator(dir, ec)) { - if (ec) break; - if (e.is_regular_file(ec) && e.path().extension() == ".so") - out.push_back(e.path().string()); - } - std::ranges::sort(out); - return out; -} - -// Does the manifest ask for the native libraries to be loaded from the APK in -// place (``, 0.11.1)? The -// platform can map a library only from an entry stored uncompressed on a page -// boundary, so such a package is laid out that way; a compressed library in it -// fails to install. -inline bool loads_native_libraries_in_place(const std::string& manifest) { - xml::node root; - std::string error; - if (!xml::parse(manifest, root, error) || root.name != "manifest") return false; - const xml::node* application = find_child(root, "application"); - return application && xml::attr_of(*application, "android:extractNativeLibs") == "false"; -} - // ─── Plan ────────────────────────────────────────────────────────────────── inline plan plan_for(options opt = {}) { @@ -2726,3 +1827,4 @@ inline bool generate(options opt = {}) { } } // namespace mcpp::dist::apk + diff --git a/dist/apk/internal/libraries.cppm b/dist/apk/internal/libraries.cppm new file mode 100644 index 0000000..ce34e7d --- /dev/null +++ b/dist/apk/internal/libraries.cppm @@ -0,0 +1,232 @@ +// mcpp.dist.apk.internal.libraries -- digests, the Maven lock and AAR unpacking. + +export module mcpp.dist.apk.internal.libraries; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.dist.apk.internal.util; + +namespace mcpp::dist::apk { + +inline std::string sha256_hex(std::string_view data); + +inline std::string sha256_file(const std::string& path) { + return is_file(path) ? sha256_hex(read_file(path)) : std::string(); +} + +// ─── JSON ───────────────────────────────────────────────────────────────── +// +// coursier's report is read with the collection's shared reader, the one +// `mcpp::plugins::graph` reads the engine's graph document with. +using json_value = mcpp::plugins::json::value; +using mcpp::plugins::json::parse_json; + +// ─── The Maven lock ─────────────────────────────────────────────────────── + +// One line per fact, sorted, so that a diff of a lock says what changed: +// +// request what the project asked for +// repository where resolution looked, in order +// artifact +// +// `` is relative to the cache root, which is where coursier keeps the +// file under `//` (`--cache` is always passed, so the root +// this member computes and the one coursier writes to are the same directory). +struct maven_artifact { + std::string coordinate; + std::string type; + std::string path; + std::string sha256; +}; + +struct maven_lock { + bool found = false; + std::vector requests; + std::vector repositories; + std::vector artifacts; +}; + +inline maven_lock read_maven_lock(const std::string& path) { + maven_lock lock; + if (!is_file(path)) return lock; + lock.found = true; + std::istringstream in(read_file(path)); + std::string line; + while (std::getline(in, line)) { + if (line.empty() || line[0] == '#') continue; + std::istringstream fields(line); + std::string kind; + fields >> kind; + if (kind == "request") { std::string v; fields >> v; lock.requests.push_back(v); } + else if (kind == "repository") { std::string v; fields >> v; lock.repositories.push_back(v); } + else if (kind == "artifact") { + maven_artifact a; + fields >> a.coordinate >> a.type >> a.path >> a.sha256; + lock.artifacts.push_back(std::move(a)); + } + } + return lock; +} + +inline std::string render_maven_lock(const maven_lock& lock) { + std::string out = + "# mcpp.dist.apk Maven lock. Written by MCPP_DIST_APK_MAVEN=update; commit it.\n" + "# An ordinary build reads only these artifacts, from the cache, and checks each digest.\n"; + for (auto const& r : lock.requests) out += "request " + r + "\n"; + for (auto const& r : lock.repositories) out += "repository " + r + "\n"; + for (auto const& a : lock.artifacts) + out += "artifact " + a.coordinate + " " + a.type + " " + a.path + " " + a.sha256 + "\n"; + return out; +} + +// Where coursier's cache is: the option, then `COURSIER_CACHE`, then coursier's +// own default on this host, so a developer's `cs` and this member share one. +inline std::string maven_cache_root(const std::string& option) { + if (!option.empty()) return option; + if (const char* env = std::getenv("COURSIER_CACHE"); env && *env) return env; + const char* home = std::getenv("HOME"); + const std::string h = home ? home : ""; + if (std::string(mcpp::host()).find("apple") != std::string::npos || + std::string(mcpp::host()).find("macos") != std::string::npos) + return h + "/Library/Caches/Coursier/v1"; + if (const char* xdg = std::getenv("XDG_CACHE_HOME"); xdg && *xdg) return std::string(xdg) + "/coursier/v1"; + return h + "/.cache/coursier/v1"; +} + +// `group:artifact:version`, three non-empty parts and a fixed version: a range +// would make the lock the only place the version is decided. +inline bool plain_coordinate(const std::string& c) { + int colons = 0; + for (std::size_t i = 0; i < c.size(); ++i) { + if (c[i] == ':') ++colons; + if (c[i] == '[' || c[i] == '(' || c[i] == ',' || c[i] == '+' || c[i] == ' ') return false; + } + return colons == 2 && !c.starts_with(":") && !c.ends_with(":") && c.find("::") == std::string::npos; +} + +// coursier names an AAR-packaged module `group:artifact:aar:version`; the lock +// records the coordinate a project writes. +inline std::string plain_form(const std::string& coord) { + return replace_all_copy(coord, ":aar:", ":"); +} + +// ─── An AAR, unpacked ───────────────────────────────────────────────────── + +// What an Android library archive contributes: its manifest (merged), its +// `res/` (linked under its own package), its classes (`classes.jar`, and any +// `libs/*.jar` it carries), its native libraries (`jni//`) and its +// `assets/`. `R.txt`, `proguard.txt`, `lint.jar` and `public.txt` are not +// read: this member does not shrink, lint or compute non-transitive R classes. +struct library_input { + std::string label; + std::string package; + std::string resources; + std::string manifest; + std::string assets; + std::string jni; + std::vector java; + std::vector kotlin; + std::vector jars; +}; + +// Unpacked with the JDK's `jar` at plan time, once per archive content: a stamp +// beside the tree records the archive's digest, and a matching stamp skips the +// work on the next plan. +inline bool unpack_aar(const std::string& aar, const fs::path& dest, const std::string& jarTool, + library_input& out, std::string& message) { + const std::string digest = sha256_file(aar); + if (digest.empty()) { + message = std::format("mcpp.dist.apk: the AAR {} was not found.", aar); + return false; + } + const fs::path stamp = dest / ".mcpp-aar-sha256"; + if (read_file(stamp.string()) != digest) { + std::error_code ec; + fs::remove_all(dest, ec); + fs::create_directories(dest, ec); + std::string output; + const int rc = run_capture({jarTool, "xf", aar}, output, dest); + if (rc != 0) { + message = std::format("mcpp.dist.apk: unpacking {} with {} failed ({}): {}", aar, jarTool, rc, output); + return false; + } + write_if_different(stamp, digest); + } + const std::string manifest = (dest / "AndroidManifest.xml").string(); + if (!is_file(manifest)) { + message = std::format("mcpp.dist.apk: {} carries no AndroidManifest.xml, so it is not an AAR.", aar); + return false; + } + xml::node m; + std::string err; + if (!xml::parse(read_file(manifest), m, err) || m.name != "manifest") { + message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", aar, err); + return false; + } + out.package = xml::attr_of(m, "package"); + out.manifest = manifest; + if (is_dir((dest / "res").string()) && dir_has_files((dest / "res").string())) out.resources = (dest / "res").string(); + if (is_dir((dest / "assets").string()) && dir_has_files((dest / "assets").string())) out.assets = (dest / "assets").string(); + if (is_dir((dest / "jni").string())) out.jni = (dest / "jni").string(); + if (is_file((dest / "classes.jar").string())) out.jars.push_back((dest / "classes.jar").string()); + for (auto const& j : files_with_extension((dest / "libs").string(), ".jar")) out.jars.push_back(j); + return true; +} +} // namespace mcpp::dist::apk + +module :private; + +namespace mcpp::dist::apk { +// ─── SHA-256 ─────────────────────────────────────────────────────────────── + +// FIPS 180-4, over bytes held in memory. Here for one purpose: a Maven lock +// records each artifact's digest, and a build that reads a cached artifact +// checks it against the lock before the file reaches a package. The inputs are +// libraries of a few megabytes, so reading a file whole is the simple choice. +inline std::string sha256_hex(std::string_view data) { + static constexpr std::uint32_t k[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + std::string msg(data); + const std::uint64_t bits = static_cast(data.size()) * 8u; + msg.push_back(static_cast(0x80)); + while (msg.size() % 64 != 56) msg.push_back('\0'); + for (int i = 7; i >= 0; --i) msg.push_back(static_cast((bits >> (i * 8)) & 0xffu)); + const auto rotr = [](std::uint32_t x, int n) -> std::uint32_t { return (x >> n) | (x << (32 - n)); }; + for (std::size_t off = 0; off < msg.size(); off += 64) { + std::uint32_t w[64]; + for (int i = 0; i < 16; ++i) { + const auto byte = [&](int j) { + return static_cast(static_cast(msg[off + static_cast(i * 4 + j)])); + }; + w[i] = (byte(0) << 24) | (byte(1) << 16) | (byte(2) << 8) | byte(3); + } + for (int i = 16; i < 64; ++i) { + const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (int i = 0; i < 64; ++i) { + const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i]; + const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + std::string hex; + hex.reserve(64); + for (int i = 0; i < 8; ++i) hex += std::format("{:08x}", h[i]); + return hex; +} +} // namespace mcpp::dist::apk + diff --git a/dist/apk/internal/manifest.cppm b/dist/apk/internal/manifest.cppm new file mode 100644 index 0000000..a492958 --- /dev/null +++ b/dist/apk/internal/manifest.cppm @@ -0,0 +1,467 @@ +// mcpp.dist.apk.internal.manifest -- manifest templating, rendering and library-manifest merging. + +export module mcpp.dist.apk.internal.manifest; + +import std; +import mcpp.dist.apk.internal.util; + +namespace mcpp::dist::apk { + +inline const std::vector& manifest_tokens(); +inline std::vector tokens_in(const std::string& text); +inline std::vector required_manifest_tokens(bool has_code, bool native_activity); +inline std::string manifest_key(const xml::node& n); +inline void strip_tools(xml::node& n); +inline std::string canonical_xml(xml::node n); +inline bool substitute_placeholders(xml::node& n, const std::string& appId, + const std::string& label, std::string& message); +inline xml::node* find_child(xml::node& parent, std::string_view name); +inline void drop_removed(xml::node& n); + +// `android:versionCode` from a version string: major * 1000000 + minor * 1000 +// + patch over the first three dot-separated numeric segments, so that every +// release a project cuts orders after the one before it, and "1" when the +// string starts with no number at all -- Android refuses 0 and a manifest +// without the attribute installs but never updates. +inline std::string version_code_for(const std::string& version) { + long long code = 0, seg = 0; + int segments = 0; + bool digits = false; + const long long weights[3] = {1000000, 1000, 1}; + for (std::size_t i = 0; i <= version.size() && segments < 3; ++i) { + const char c = i < version.size() ? version[i] : '\0'; + if (c >= '0' && c <= '9') { seg = seg * 10 + (c - '0'); digits = true; continue; } + if (!digits) break; + code += std::min(seg, 999) * weights[segments] ; + ++segments; seg = 0; digits = false; + if (c != '.') break; + } + if (segments == 0) return "1"; + if (code <= 0) return "1"; + return std::to_string(code); +} + +// THE BUILT-IN DEFAULT, EXPRESSED WITH THE TOKENS. This is `manifest_xml`'s +// 0.8.0 output verbatim, with every literal value it used to compute +// replaced by the token that value now comes through -- so level 0 with no +// project template renders byte-identical to what 0.8.0 wrote +// (`tests/apk-consumer`). `{{activity}}` carries the level-0 constant +// (`android.app.NativeActivity`) as well as a level-1 project's own class, +// because the run sidecar needs the activity name at both levels and the +// required-token check reads the TEMPLATE TEXT, not the level -- so the same +// token has to appear on both of this function's two branches. +// `{{lib_name}}`'s `` element exists only at level 0: it +// announces which shared object `NativeActivity` should load, and a +// Java-hosted activity finds its own native library another way. +// +// NO XML COMMENT MARKS THE THREE REQUIRED TOKENS IN THIS STRING, ON PURPOSE: +// this exact text is compared byte-for-byte against 0.8.0's output, which +// carried none, and a template with no author to read a comment gains +// nothing from one. The design record's "mark the required tokens" is done +// here instead, in the `REQUIRED` labels on the C++ lines that build them. +// A NATIVE ACTIVITY MAY STILL CARRY CODE (0.11.0): a level-0 application whose +// libraries or archives bring classes keeps `android.app.NativeActivity` and its +// `lib_name` element, with `android:hasCode="true"` so that the dex is loaded. +inline std::string default_manifest_template(bool has_code, bool native_activity) { + std::string a = + "\n" + "\n" // REQUIRED + " \n" + " \n" + " \n"; + if (native_activity) { + a += " \n"; // REQUIRED at level 0 + } + a += " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"; + return a; +} + +// Checks a manifest template and substitutes it, or refuses (returning +// `false` with `reason` and `message` set) naming exactly what is wrong; the +// caller reports `message` (see `refuse`). +// +// THIS CHECK IS `dist-apk`'S OWN, DELIBERATELY NOT `dist-web`'S. A manifest +// has a closed, six-token vocabulary this member itself defines; a web page +// template may legitimately carry `{{ }}` for a front-end framework (Vue, +// Mustache, ...) this member never reads, so `dist-web` leaves an unknown +// token literal for that project's own tooling to read. An unknown token +// here would otherwise reach `aapt2` unsubstituted and fail there with a +// worse message, and the refusal belongs where the name is known -- the same +// rule read against two different facts, not an inconsistency between the +// two members. +inline bool render_manifest(const std::string& templateText, bool has_code, bool native_activity, + const std::string& appId, const std::string& label, + const std::string& activityName, const std::string& libName, + const std::string& minSdk, const std::string& targetSdk, + const std::string& versionName, const std::string& versionCode, + std::string& out, std::string& reason, + std::string& message) { + for (auto const& tok : tokens_in(templateText)) { + if (std::ranges::find(manifest_tokens(), tok) == manifest_tokens().end()) { + message = "mcpp.dist.apk: the manifest template names an unknown " + "token '{{" + tok + "}}'; expected one of application_id, " + "label, activity, lib_name, min_sdk, target_sdk, " + "version_name, version_code."; + reason = "unknown manifest template token '" + tok + "'"; + return false; + } + } + for (auto const& tok : required_manifest_tokens(has_code, native_activity)) { + if (templateText.find("{{" + tok + "}}") == std::string::npos) { + message = "mcpp.dist.apk: the manifest template does not use '{{" + tok + + "}}', and assets/mcpp-run.json, which adb-run starts the " + "application from, is written from the same value: add {{" + + tok + "}} to the template."; + reason = "manifest template missing required token '" + tok + "'"; + return false; + } + } + out = templateText; + out = replace_all_copy(std::move(out), "{{application_id}}", appId); + out = replace_all_copy(std::move(out), "{{label}}", label); + out = replace_all_copy(std::move(out), "{{activity}}", activityName); + out = replace_all_copy(std::move(out), "{{lib_name}}", libName); + out = replace_all_copy(std::move(out), "{{min_sdk}}", minSdk); + out = replace_all_copy(std::move(out), "{{target_sdk}}", targetSdk); + out = replace_all_copy(std::move(out), "{{version_name}}", versionName); + out = replace_all_copy(std::move(out), "{{version_code}}", versionCode); + return true; +} +inline bool render_manifest(const std::string& templateText, bool has_code, + const std::string& appId, const std::string& label, + const std::string& activityName, const std::string& libName, + const std::string& minSdk, const std::string& targetSdk, + const std::string& versionName, const std::string& versionCode, + std::string& out, std::string& reason, + std::string& message) { + return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName, + minSdk, targetSdk, versionName, versionCode, out, reason, message); +} + +inline std::string run_json(const std::string& app_id, const std::string& activity_name) { + // Hand-built, not through a JSON library this collection does not + // depend on: two string fields, neither of which this member lets + // through unescaped input (`app_id` is derived from the package's own + // identifiers, `activity_name` is a Java class name or the literal + // `android.app.NativeActivity`). + return std::format("{{\"package\": \"{}\", \"activity\": \"{}\"}}\n", + app_id, activity_name); +} + +// ─── Merging library manifests into the application's ──────────────────── + +// What `mcpp.dist.apk` merges, and the rules it applies. This is a SUBSET of +// the Android Gradle plugin's manifest merger, stated rather than implied: +// +// - ``, ``, ``, +// `` and the other children of `` are added when +// the application has no element of the same kind and `android:name`; +// `` children are unioned; +// - the children of a library's `` -- activities, aliases, +// services, receivers, providers, ``, `` -- are +// added the same way; a library's `` attribute the +// application does not state is added; +// - an identical element is not added twice; a DIFFERENT element under the +// same name is refused, naming it, unless the application's own element +// says `tools:node="replace"` (the application's wins) or +// `tools:node="remove"` (neither is kept); a differing `` +// attribute is refused unless the application lists it in `tools:replace`; +// - a library's `` above the application's +// floor is refused, as Gradle refuses it; +// - `${applicationId}` is substituted everywhere, and any other `${...}` +// placeholder is refused, naming it -- no placeholder source exists here; +// - every `tools:` attribute and the `xmlns:tools` declaration are removed +// from the result. +// +// Anything a project needs beyond that is stated in its own manifest template, +// which this member never edits except to add what the libraries declare. +struct manifest_source { + std::string label; // what a refusal names: a library, an AAR, a coordinate + std::string text; +}; + +inline bool merge_manifests(std::string& appText, const std::vector& libs, + const std::string& appId, const std::string& minSdk, + std::string& reason, std::string& message) { + xml::node app; + std::string err; + if (!xml::parse(appText, app, err) || app.name != "manifest") { + reason = "the application manifest cannot be read"; + message = "mcpp.dist.apk: the application's manifest cannot be read for merging: " + + (err.empty() ? std::string("its root element is not ") : err); + return false; + } + if (!substitute_placeholders(app, appId, "the application's manifest", message)) { + reason = "unknown manifest placeholder"; + return false; + } + xml::node* application = find_child(app, "application"); + if (!application) { + app.children.push_back(xml::node{"application", {}, {}, {}}); + application = &app.children.back(); + } + const auto parse_number = [](const std::string& s) { + long v = 0; + for (std::size_t i = 0; i < s.size(); ++i) { + if (s[i] < '0' || s[i] > '9') return -1L; + v = v * 10 + (s[i] - '0'); + } + return s.empty() ? -1L : v; + }; + + for (auto const& lib : libs) { + xml::node m; + if (!xml::parse(lib.text, m, err) || m.name != "manifest") { + reason = "a library manifest cannot be read"; + message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", lib.label, + err.empty() ? std::string("its root element is not ") : err); + return false; + } + if (!substitute_placeholders(m, appId, lib.label, message)) { + reason = "unknown manifest placeholder"; + return false; + } + for (auto& c : m.children) { + if (c.name.empty()) continue; + if (c.name == "uses-sdk") { + const long want = parse_number(xml::attr_of(c, "android:minSdkVersion")); + const long have = parse_number(minSdk); + if (want > 0 && have > 0 && want > have) { + reason = "a library needs a higher minSdkVersion"; + message = std::format( + "mcpp.dist.apk: {} declares android:minSdkVersion {}, above this " + "application's floor {}. Raise the row's min_api_level, or do not " + "depend on it.", lib.label, want, have); + return false; + } + continue; + } + if (c.name == "application") { + const std::string replaced = xml::attr_of(*application, "tools:replace"); + for (auto const& a : c.attrs) { + if (a.first.starts_with("tools:")) continue; + const std::string mine = xml::attr_of(*application, a.first); + if (mine.empty()) { xml::set_attr(*application, a.first, a.second); continue; } + if (mine == a.second) continue; + bool listed = false; + std::size_t start = 0; + while (start <= replaced.size()) { + auto comma = replaced.find(',', start); + if (comma == std::string::npos) comma = replaced.size(); + if (xml::trim_copy(replaced.substr(start, comma - start)) == a.first) { listed = true; break; } + start = comma + 1; + } + if (!listed) { + reason = "conflicting attribute"; + message = std::format( + "mcpp.dist.apk: is \"{}\" in the application and " + "\"{}\" in {}. Add tools:replace=\"{}\" to the application's " + " to keep its value.", a.first, mine, a.second, lib.label, a.first); + return false; + } + } + for (auto& cc : c.children) { + if (cc.name.empty()) continue; + const std::string key = manifest_key(cc); + xml::node* mine = nullptr; + for (auto& x : application->children) + if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } + if (!mine) { application->children.push_back(cc); continue; } + const std::string node = xml::attr_of(*mine, "tools:node"); + if (node == "remove" || node == "replace") continue; + if (canonical_xml(*mine) == canonical_xml(cc)) continue; + reason = "conflicting manifest element"; + message = std::format( + "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application " + "and {}. State tools:node=\"replace\" on the application's element to keep " + "it, or tools:node=\"remove\" to drop both.", cc.name, + xml::attr_of(cc, "android:name"), lib.label); + return false; + } + continue; + } + if (c.name == "queries") { + xml::node* q = find_child(app, "queries"); + if (!q) { + auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); + q = &*app.children.insert(pos, xml::node{"queries", {}, {}, {}}); + application = find_child(app, "application"); + } + for (auto& qc : c.children) { + if (qc.name.empty()) continue; + const std::string canon = canonical_xml(qc); + const bool present = std::ranges::any_of(q->children, [&](const xml::node& x) { + return canonical_xml(x) == canon; + }); + if (!present) q->children.push_back(qc); + } + continue; + } + const std::string key = manifest_key(c); + xml::node* mine = nullptr; + for (auto& x : app.children) + if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } + if (mine) { + const std::string node = xml::attr_of(*mine, "tools:node"); + if (node == "remove" || node == "replace") continue; + if (canonical_xml(*mine) == canonical_xml(c)) continue; + reason = "conflicting manifest element"; + message = std::format( + "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application and " + "{}. State tools:node=\"replace\" on the application's element to keep it, or " + "tools:node=\"remove\" to drop both.", c.name, xml::attr_of(c, "android:name"), lib.label); + return false; + } + auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); + app.children.insert(pos, c); + application = find_child(app, "application"); + } + } + + drop_removed(app); + strip_tools(app); + appText = "\n"; + xml::write(app, appText, 0); + return true; +} + +// Does the manifest ask for the native libraries to be loaded from the APK in +// place (``, 0.11.1)? The +// platform can map a library only from an entry stored uncompressed on a page +// boundary, so such a package is laid out that way; a compressed library in it +// fails to install. +inline bool loads_native_libraries_in_place(const std::string& manifest) { + xml::node root; + std::string error; + if (!xml::parse(manifest, root, error) || root.name != "manifest") return false; + const xml::node* application = find_child(root, "application"); + return application && xml::attr_of(*application, "android:extractNativeLibs") == "false"; +} + +} // namespace mcpp::dist::apk + +module :private; + +namespace mcpp::dist::apk { +// The eight tokens a manifest template may use. `version_name` is the +// package version as written; `version_code` is Android's monotonic integer +// derived from its leading numeric segments (`version_code_for`). +inline const std::vector& manifest_tokens() { + static const std::vector v = { + "application_id", "label", "activity", "lib_name", "min_sdk", "target_sdk", + "version_name", "version_code"}; + return v; +} + +// Every `{{...}}` a template names, in first-appearance order, duplicates +// dropped -- what both checks in `render_manifest` below read. +inline std::vector tokens_in(const std::string& text) { + std::vector out; + std::size_t i = 0; + while ((i = text.find("{{", i)) != std::string::npos) { + const auto close = text.find("}}", i + 2); + if (close == std::string::npos) break; + std::string name = text.substr(i + 2, close - (i + 2)); + if (std::ranges::find(out, name) == out.end()) out.push_back(std::move(name)); + i = close + 2; + } + return out; +} + +// The tokens `assets/mcpp-run.json` is ALSO written from -- a template that +// omits one silently ships a run sidecar the manifest disagrees with. +// `application_id` and `activity` are required unconditionally; `lib_name` +// joins them at level 0, where the manifest's own `` element is +// the only place the loaded library's name is recorded. +inline std::vector required_manifest_tokens(bool has_code, bool native_activity) { + static_cast(has_code); + std::vector v = {"application_id", "activity"}; + if (native_activity) v.push_back("lib_name"); + return v; +} +inline std::vector required_manifest_tokens(bool has_code) { + return required_manifest_tokens(has_code, !has_code); +} + +inline std::string default_manifest_template(bool has_code) { + return default_manifest_template(has_code, !has_code); +} + +inline bool render_manifest(const std::string& templateText, bool has_code, + const std::string& appId, const std::string& label, + const std::string& activityName, const std::string& libName, + const std::string& minSdk, const std::string& targetSdk, + const std::string& versionName, const std::string& versionCode, + std::string& out, std::string& reason, + std::string& message) { + return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName, + minSdk, targetSdk, versionName, versionCode, out, reason, message); +} + +inline std::string manifest_key(const xml::node& n) { + if (n.name == "uses-feature") { + const std::string nm = xml::attr_of(n, "android:name"); + return nm.empty() ? "uses-feature@glEsVersion=" + xml::attr_of(n, "android:glEsVersion") + : "uses-feature:" + nm; + } + return n.name + ":" + xml::attr_of(n, "android:name"); +} + +inline void strip_tools(xml::node& n) { + std::erase_if(n.attrs, [](const std::pair& a) { + return a.first.starts_with("tools:") || a.first == "xmlns:tools"; + }); + for (auto& c : n.children) strip_tools(c); +} + +inline std::string canonical_xml(xml::node n) { + strip_tools(n); + std::string out; + xml::write(n, out, 0); + return out; +} + +inline bool substitute_placeholders(xml::node& n, const std::string& appId, + const std::string& label, std::string& message) { + for (auto& a : n.attrs) { + a.second = replace_all_copy(a.second, "${applicationId}", appId); + const auto p = a.second.find("${"); + if (p != std::string::npos) { + const auto e = a.second.find('}', p); + message = std::format( + "mcpp.dist.apk: {} uses the manifest placeholder '{}' in {}=\"{}\"; " + "only ${{applicationId}} is substituted here.", label, + a.second.substr(p, e == std::string::npos ? std::string::npos : e - p + 1), + a.first, a.second); + return false; + } + } + for (auto& c : n.children) + if (!substitute_placeholders(c, appId, label, message)) return false; + return true; +} + +inline xml::node* find_child(xml::node& parent, std::string_view name) { + for (auto& c : parent.children) if (c.name == name) return &c; + return nullptr; +} + +// Removes every element the application marked `tools:node="remove"`: a marker +// that says "this is not wanted", not an element to ship. +inline void drop_removed(xml::node& n) { + std::erase_if(n.children, [](const xml::node& c) { return xml::attr_of(c, "tools:node") == "remove"; }); + for (auto& c : n.children) drop_removed(c); +} +} // namespace mcpp::dist::apk + diff --git a/dist/apk/internal/util.cppm b/dist/apk/internal/util.cppm new file mode 100644 index 0000000..953bc06 --- /dev/null +++ b/dist/apk/internal/util.cppm @@ -0,0 +1,277 @@ +// mcpp.dist.apk.internal.util -- the shared file, host and text helpers of dist/apk. + +export module mcpp.dist.apk.internal.util; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.plugins.tool; + +namespace mcpp::dist::apk { + +namespace fs = std::filesystem; + +inline bool is_file(const std::string& p) { + std::error_code ec; + return !p.empty() && fs::is_regular_file(p, ec); +} +inline bool is_dir(const std::string& p) { + std::error_code ec; + return !p.empty() && fs::is_directory(p, ec); +} + +inline bool host_is_windows(); + +inline std::string host_program(const fs::path& dir, std::string_view name) { + return (dir / (std::string(name) + (host_is_windows() ? ".exe" : ""))).string(); +} +inline const char* class_path_separator() { return host_is_windows() ? ";" : ":"; } + +// Is `root` under the package root, `mcpp::manifest_dir()`, and if so, what +// is its manifest-relative form? A project root is declared with +// `rerun_if_changed_glob` below (a file appearing there re-runs the build +// program); a dependency root is not -- its file set changes only with the +// dependency's version, already in the build's fingerprint, and the glob's +// own walk does not reach outside the package root regardless (design +// record §3.3). Same shape as `mcpp.tools.island`'s overlap check: +// `weakly_canonical` plus `lexically_relative`, never the iterator that +// poisons an importer under GCC 16 / MSVC (`mcpp::plugins::names:: +// relative_to`'s own header) -- safe here because this member is its own +// module and imports no sibling that would inherit the instantiation. +// +// THE RETURNED PATH IS MANIFEST-RELATIVE, NOT ABSOLUTE, BECAUSE THE GLOB +// PATTERN MUST BE. The engine matches a glob by comparing the CANDIDATE made +// relative to the package root against the pattern +// (`modules/manifest/src/glob.cppm`, `path_matches_glob`); an absolute +// pattern is compared against a relative candidate and never matches +// anything, so the fingerprint is always the empty set and a `.java` file +// appearing never changes it -- the criterion's "no" reading as silence +// (design record, rule 8). `opt.java_sources`'s own roots are absolute +// (`mcpp::manifest_dir()` composed with a subdirectory), so declaring the +// glob with `root` itself, not this function's return value, was exactly +// that defect. +// +// A root inside the build's output -- `mcpp::out_dir()`, or a directory the +// glob walk never enters (`target`, `.mcpp`, `.git`) -- is GENERATED: the +// build program that writes its files already runs on every build, and a glob +// there can never match anything, which the engine reports as a warning. It is +// answered as outside the project, so it is an action input and no glob. +inline std::optional root_in_project(const std::string& root) { + std::error_code ec; + const auto a = fs::weakly_canonical(root, ec); + if (ec) return std::nullopt; + const auto b = fs::weakly_canonical(mcpp::manifest_dir(), ec); + if (ec) return std::nullopt; + const auto rel = a.lexically_relative(b).generic_string(); + if (rel.empty() || rel.starts_with("..")) return std::nullopt; + const auto out = fs::weakly_canonical(std::string(mcpp::out_dir()), ec); + if (!ec) { + const auto inside = a.lexically_relative(out).generic_string(); + if (!inside.empty() && !inside.starts_with("..")) return std::nullopt; + } + const auto first = rel.substr(0, rel.find('/')); + if (first == "target" || first == ".mcpp" || first == ".git") return std::nullopt; + return rel; +} + +inline bool write_if_different(const fs::path& path, std::string_view bytes) { + std::error_code ec; + fs::create_directories(path.parent_path(), ec); + if (std::ifstream in(path, std::ios::binary); in) { + std::string old((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + if (old == bytes) return true; + } + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(bytes.data(), static_cast(bytes.size())); + return static_cast(out); +} + +// `/`, from the row's arch and no other input -- see `artifact_naming` +// for the engine's own row-decides-the-name principle, applied here to +// Android's own ABI vocabulary rather than a file suffix. +inline std::string abi_for() { + const std::string a = mcpp::target_arch(); + if (a == "aarch64") return "arm64-v8a"; + if (a == "x86_64") return "x86_64"; + return {}; +} + + +// Index loop, not a range-for: GCC 16.1.0 refuses to inline +// `__normal_iterator>::operator*() const` when a +// module interface unit that imports `std` also range-for's (or otherwise +// takes `basic_string`'s own iterator over) a `std::string` or +// `std::filesystem::path` -- +// +// bits/stl_iterator.h:1089:7: error: inlining failed in call to +// 'always_inline' '... operator*() const' +// +// -- the same family of defect #18 met under MSVC's `_Path_iterator` (see +// `mcpp::plugins::names::relative_to` and `components()` in +// `src/plugins.cppm`), here on `libstdc++`'s `basic_string` iterator instead +// of the filesystem one. `s[i]` indexes the string directly and never forms +// that iterator, so it compiles under both. +inline std::string replace_dashes(std::string s) { + for (std::size_t i = 0; i < s.size(); ++i) if (s[i] == '-') s[i] = '_'; + return s; +} + +// `xim:android-platform`'s own resolved directory is named after the +// version it resolved -- "36-r2", "35-r2", "34-r3" (`pkgs/a/android- +// platform.lua`'s own `extract_dir()` recovers the API level the identical +// way, from the leading digits of its OWN version string) -- so the level a +// project pinned is read back from the directory `xpkg_dir` already +// answered, rather than duplicated as a second option this member could +// disagree with. +inline std::string api_level_from_platform_dir(const std::string& dir) { + if (dir.empty()) return {}; + const std::string leaf = fs::path(dir).filename().string(); + std::string digits; + for (std::size_t i = 0; i < leaf.size(); ++i) { + if (leaf[i] >= '0' && leaf[i] <= '9') digits += leaf[i]; + else break; + } + return digits; +} + +inline std::string replace_all_copy(std::string s, std::string_view from, std::string_view to) { + if (from.empty()) return s; + std::size_t pos = 0; + while ((pos = s.find(from, pos)) != std::string::npos) { + s.replace(pos, from.size(), to); + pos += to.size(); + } + return s; +} + +// Copies `src` (a file or a directory, recursively) into `dstRoot/relName`, +// listing every regular file it wrote -- so the caller can declare each one +// as an action input rather than the directory itself ("name the input; do +// not harvest a directory", docs/31). +inline void collect_tree(const fs::path& src, const fs::path& dst, + std::vector& out) { + std::error_code ec; + if (fs::is_regular_file(src, ec)) { + fs::create_directories(dst.parent_path(), ec); + fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec); + out.push_back(dst.string()); + return; + } + for (auto& e : fs::recursive_directory_iterator(src, ec)) { + if (ec) break; + if (!e.is_regular_file(ec)) continue; + auto rel = fs::relative(e.path(), src, ec); + auto to = dst / rel; + fs::create_directories(to.parent_path(), ec); + fs::copy_file(e.path(), to, fs::copy_options::overwrite_existing, ec); + out.push_back(to.string()); + } +} + +namespace xml = mcpp::plugins::xml; + +// ─── Paths a project names ───────────────────────────────────────────────── + +// A project names its directories relative to its manifest; the actions this +// member declares run later, from the build directory, where a relative path +// names nothing (the defect `dist/apple.cppm` measured with `ditto ios-icons`). +// Every path option is therefore resolved here, once, against +// `mcpp::manifest_dir()`; an absolute path is left alone. +inline std::string resolve_path(const std::string& p) { + if (p.empty()) return p; + const fs::path path(p); + if (path.is_absolute()) return p; + return (fs::path(mcpp::manifest_dir()) / path).lexically_normal().string(); +} + +inline void resolve_paths(std::vector& v) { + for (auto& p : v) p = resolve_path(p); +} + +// Every regular file under `root` whose extension is `ext`, sorted. +inline std::vector files_with_extension(const std::string& root, std::string_view ext) { + std::vector out; + std::error_code ec; + for (auto& e : fs::recursive_directory_iterator(root, ec)) { + if (ec) break; + if (e.is_regular_file(ec) && e.path().extension() == ext) + out.push_back(e.path().string()); + } + std::ranges::sort(out); + return out; +} + +inline bool dir_has_files(const std::string& root) { + std::error_code ec; + for (auto& e : fs::recursive_directory_iterator(root, ec)) { + if (ec) break; + if (e.is_regular_file(ec)) return true; + } + return false; +} + +inline std::string read_file(const std::string& path) { + std::ifstream in(path, std::ios::binary); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +inline std::string join(const std::vector& v, std::string_view sep) { + std::string out; + for (std::size_t i = 0; i < v.size(); ++i) { + if (i) out += sep; + out += v[i]; + } + return out; +} + +// ─── Running a tool at plan time ───────────────────────────────────────── + +// Runs `argv`, returning its exit status and its combined output, through +// `mcpp::plugins::tool::capture`: no shell between, so no argument is quoted. +// Only the explicit Maven modes and AAR extraction call it; an ordinary build +// of an unchanged project runs nothing here. +int run_capture(const std::vector& argv, std::string& output, + const std::filesystem::path& cwd = {}) { + auto r = mcpp::plugins::tool::capture(argv, /*with_errors=*/true, cwd); + output = std::move(r.out); + return r.status; +} + +// Android's own ABI names, the directory names a several-triple tree stages +// under (`lib//`) and an APK stores its native libraries under. +inline bool is_android_abi(std::string_view name) { + return name == "arm64-v8a" || name == "x86_64" || name == "armeabi-v7a" || name == "x86"; +} + +// One ABI's native libraries, as the staged tree carries them. +struct native_leg { + std::string abi; + std::vector libraries; // absolute paths, sorted +}; + +inline std::vector shared_objects_in(const fs::path& dir) { + std::vector out; + std::error_code ec; + for (auto& e : fs::directory_iterator(dir, ec)) { + if (ec) break; + if (e.is_regular_file(ec) && e.path().extension() == ".so") + out.push_back(e.path().string()); + } + std::ranges::sort(out); + return out; +} +} // namespace mcpp::dist::apk + +module :private; + +namespace mcpp::dist::apk { +// THE HOST, NOT THE TARGET: every tool here runs on the machine that builds. +// A Windows host names its programs `.exe` and separates a class path +// with `;`. +inline bool host_is_windows() { + return std::string_view(mcpp::host()).find("windows") != std::string_view::npos; +} +} // namespace mcpp::dist::apk + diff --git a/dist/apple/apple.cppm b/dist/apple/apple.cppm index e2a9d75..4935a75 100644 --- a/dist/apple/apple.cppm +++ b/dist/apple/apple.cppm @@ -195,12 +195,18 @@ import mcpp.plugins; import mcpp.plugins.tool; import mcpp.tools.steps; +import mcpp.dist.apple.internal.layout; +import mcpp.dist.apple.internal.plist; +import mcpp.dist.apple.internal.signing; + + // Nothing here uses `std::println`, and that is not a style choice: both of // its overloads reach into the libc++ dylib for symbols macOS 14 does not // ship, so a member that printed with it compiled and then failed to link. // `std::format` is header-only. The full measurement is in `rules/spirv.cppm`. export namespace mcpp::dist::apple { + using namespace detail; // ─── Options ─────────────────────────────────────────────────────────────── @@ -383,30 +389,6 @@ struct plan { // ─── Internals ───────────────────────────────────────────────────────────── -inline bool is_file(const std::string& p) { - std::error_code ec; - return !p.empty() && std::filesystem::is_regular_file(p, ec); -} - -// Written only when the bytes differ, for the reason `dist/appimage.cppm` -// gives: rewriting identical bytes moves the mtime, and a moved mtime on a -// declared input is indistinguishable from a changed one -- so a second pack -// of an unchanged project would re-copy the bundle and re-sign it. -inline bool write_if_different(const std::filesystem::path& path, - std::string_view bytes) { - std::error_code ec; - std::filesystem::create_directories(path.parent_path(), ec); - if (std::ifstream in(path, std::ios::binary); in) { - std::string old((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - if (old == bytes) return true; - } - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out) return false; - out.write(bytes.data(), static_cast(bytes.size())); - return static_cast(out); -} - // Records a refusal on stderr and as a `mcpp::warning`. A member that refuses // submits no action and its build program exits 0, and the engine discards the // output of a build program that succeeded; its own error, "no action claimed @@ -463,53 +445,6 @@ inline std::string app_name_for(const options& opt) { return (n && *n) ? std::string(n) : std::string("app"); } -// The program a bundle executes, found in the staged tree: `bin/` -// first, then the tree's top-level entry, then `run.sh`. -// -// THE PROGRAM, NOT THE TREE'S ENTRY SCRIPT. From the release that reads a -// Mach-O program's closure (mcpp 2026.9.14.2), the engine also writes -// `/`, a shell script that executes `bin/` from the -// tree's root. The search used to take that root entry first, which is the -// order `dist/appimage.cppm` needs, and a bundle then executed the script, -// which executed `Contents/MacOS/bin/` -- a file no bundle carries: -// "cannot execute: No such file or directory", exit 126 (macos-15, run -// 34821164486). The script has no work to do inside a bundle, where -// `CFBundleExecutable` names the program directly, and the framework rpath -// `@executable_path/../Frameworks` resolves against the program's own -// directory, which has to be `Contents/MacOS/`. The root entry and `run.sh` -// remain for a tree that carries no `bin/`. -inline std::string launcher_in(const std::string& stage, const std::string& target) { - for (auto candidate : {stage + "/bin/" + target, - stage + "/" + target, - stage + "/run.sh"}) - if (is_file(candidate)) return candidate; - return {}; -} - -// CFBundleExecutable MUST BE A BARE FILENAME, NOT A PATH. -// -// Apple's own bundle documentation describes it as the executable's name -// within `Contents/MacOS/`, and real-world bundle tooling has hit this -// directly enough to be a filed CMake defect: "CFBundleExecutable path in a -// bundle should not be a relative path into bundle." So this member takes -// only the basename of whatever `launcher_in` finds, and the layout step -// copies that file to the top of the executable directory under that name, so -// the name and the file agree wherever in the staged tree it was found. -inline std::string bundle_executable_name(const std::string& launcher_path) { - return std::filesystem::path(launcher_path).filename().string(); -} - -inline std::string sanitize_bundle_id_component(std::string_view s) { - std::string out; - out.reserve(s.size()); - for (char c : s) { - bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') - || (c >= '0' && c <= '9') || c == '-' || c == '.'; - out += ok ? c : '-'; - } - return out; -} - // A reversed-DNS-SHAPED identifier, not a literal reversal of a domain -- // mcpp packages carry `(namespace, name)`, not a domain to reverse. Sanitised // to the character set Apple documents for `CFBundleIdentifier` @@ -527,312 +462,6 @@ inline std::string bundle_id_for(const options& opt) { return "app"; } -inline std::string plist_escape(std::string_view s) { - std::string out; - out.reserve(s.size()); - for (char c : s) { - switch (c) { - case '&': out += "&"; break; - case '<': out += "<"; break; - case '>': out += ">"; break; - default: out += c; - } - } - return out; -} - -// Written as XML text directly rather than by shelling out to `plutil`: the -// content is a handful of string keys this member already holds, and adding -// a second host tool to discover and invoke would buy nothing over -// formatting the lines by hand. `LSMinimumSystemVersion` / `MinimumOSVersion` -// and `CFBundleIconFile` are omitted rather than emitted empty when their -// inputs are empty -- an empty string in either key is a claim as -// unsupported as omitting the key, so omission is the honest one. -// -// `is_ios` AND `is_sim` DECIDE FOUR KEYS, NOT ONE BRANCH. `MinimumOSVersion` -// replaces `LSMinimumSystemVersion`; `CFBundleSupportedPlatforms`, -// `UIDeviceFamily` and `LSRequiresIPhoneOS` are iOS-only and absent from -// every macOS bundle this member has ever written, which is the -// byte-identical property the macOS fixture depends on; `NSHighResolutionCapable` -// is a macOS concept (Retina-aware drawing on a platform that also has -// non-Retina displays) with nothing to opt into on iOS, so it is macOS-only -// in the other direction. -inline std::string plist_document(const std::string& executable, const std::string& bundle_id, - const std::string& name, const std::string& version, - bool is_ios, bool is_sim, - const std::string& min_os_version, - // The project's own entries (0.11.0), already - // formatted, inserted before ``; and the - // defaulted keys they replace. - const std::string& extra_entries, - const std::vector& replaced_keys, - // macOS: the icon FILE's basename, extension - // included, exactly as `CFBundleIconFile` has - // always taken it. iOS: unused (see - // `ios_icon_stems`) and always empty. - const std::string& mac_icon_name, - // iOS: every PNG stem found in - // `options::icon`'s directory. macOS: unused - // and always empty. - const std::vector& ios_icon_stems) { - std::string doc; - doc += "\n"; - doc += "\n"; - doc += "\n\n"; - doc += std::format(" CFBundleExecutable\n {}\n", - plist_escape(executable)); - doc += std::format(" CFBundleIdentifier\n {}\n", - plist_escape(bundle_id)); - doc += std::format(" CFBundleName\n {}\n", - plist_escape(name)); - doc += std::format(" CFBundleShortVersionString\n {}\n", - plist_escape(version)); - doc += std::format(" CFBundleVersion\n {}\n", - plist_escape(version)); - doc += " CFBundlePackageType\n APPL\n"; - if (!min_os_version.empty()) - doc += std::format(" {}\n {}\n", - is_ios ? "MinimumOSVersion" : "LSMinimumSystemVersion", - plist_escape(min_os_version)); - if (is_ios) { - // `env == "sim"` is the engine's own distinction between the two - // rows (triple.cppm: "the simulator is deliberately not a row of - // its own identity... it has its own SDK"); this key is the one - // place a bundle has to restate it, because `simctl install` and a - // real device's installer both read it to refuse the other kind. - doc += std::format( - " CFBundleSupportedPlatforms\n \n" - " {}\n \n", - is_sim ? "iPhoneSimulator" : "iPhoneOS"); - // `[1, 2]`: iPhone and iPad. Nothing here narrows a project to one - // idiom -- that is a project decision (a size class, a storyboard) - // this member has no basis for making. - const auto replaced = [&](std::string_view k) { - return std::ranges::find(replaced_keys, k) != replaced_keys.end(); - }; - if (!replaced("UIDeviceFamily")) - doc += " UIDeviceFamily\n \n" - " 1\n 2\n \n"; - if (!replaced("LSRequiresIPhoneOS")) - doc += " LSRequiresIPhoneOS\n \n"; - if (!ios_icon_stems.empty()) { - doc += " CFBundleIcons\n \n" - " CFBundlePrimaryIcon\n \n" - " CFBundleIconFiles\n \n"; - for (auto const& stem : ios_icon_stems) - doc += std::format(" {}\n", plist_escape(stem)); - doc += " \n \n \n"; - } - } else { - if (std::ranges::find(replaced_keys, std::string_view("NSHighResolutionCapable")) == replaced_keys.end()) - doc += " NSHighResolutionCapable\n \n"; - // Not in the letter of this member's key list, but added - // deliberately: without it, an icon file this member went to the - // trouble of copying into `Contents/Resources/` is inert -- nothing - // in the bundle would ever reference it, and Finder would show the - // generic application icon regardless of `options::icon`. Wiring the - // file up once it exists is what makes the option do what its name - // says. - if (!mac_icon_name.empty()) - doc += std::format(" CFBundleIconFile\n {}\n", - plist_escape(mac_icon_name)); - } - doc += extra_entries; - doc += "\n\n"; - return doc; -} -inline std::string plist_document(const std::string& executable, const std::string& bundle_id, - const std::string& name, const std::string& version, - bool is_ios, bool is_sim, - const std::string& min_os_version, - const std::string& mac_icon_name, - const std::vector& ios_icon_stems) { - return plist_document(executable, bundle_id, name, version, is_ios, is_sim, min_os_version, - std::string(), std::vector(), mac_icon_name, ios_icon_stems); -} - -inline std::string read_text(const std::string& path) { - std::ifstream in(path, std::ios::binary); - return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); -} - -inline std::string resolve_path(const std::string& p) { - if (p.empty() || std::filesystem::path(p).is_absolute()) return p; - return (std::filesystem::path(mcpp::manifest_dir()) / p).lexically_normal().string(); -} - -// The keys `plist_document` derives, which a project's plist may not restate, -// and the keys it only defaults, which a project's plist replaces. -inline const std::vector& derived_plist_keys() { - static const std::vector v = { - "CFBundleExecutable", "CFBundleIdentifier", "CFBundleName", "CFBundleShortVersionString", - "CFBundleVersion", "CFBundlePackageType", "LSMinimumSystemVersion", "MinimumOSVersion", - "CFBundleSupportedPlatforms", "CFBundleIconFile", "CFBundleIcons"}; - return v; -} -inline const std::vector& defaulted_plist_keys() { - static const std::vector v = {"UIDeviceFamily", "LSRequiresIPhoneOS", "NSHighResolutionCapable"}; - return v; -} - -// The top-level `` of a property list, or null. A document whose root is -// `` itself is accepted as well as a full ``. -inline const mcpp::plugins::xml::node* top_dict(const mcpp::plugins::xml::node& root) { - if (root.name == "dict") return &root; - if (root.name != "plist") return nullptr; - for (auto const& c : root.children) if (c.name == "dict") return &c; - return nullptr; -} - -// The value element after each `` of a ``, as (key, value) pairs. -inline bool dict_entries(const mcpp::plugins::xml::node& dict, - std::vector>& out, - std::string& error) { - namespace xml = mcpp::plugins::xml; - for (std::size_t i = 0; i < dict.children.size(); ++i) { - const auto& k = dict.children[i]; - if (k.name.empty()) continue; - if (k.name != "key") { error = "<" + k.name + "> appears where a is expected"; return false; } - const std::string key = k.children.size() == 1 && k.children.front().name.empty() - ? xml::trim_copy(k.children.front().text) : std::string(); - std::size_t j = i + 1; - while (j < dict.children.size() && dict.children[j].name.empty()) ++j; - if (key.empty() || j >= dict.children.size()) { error = "a without a value"; return false; } - out.emplace_back(key, &dict.children[j]); - i = j; - } - return true; -} - -// One Info.plist entry a fragment states: its key and the plist text of the -// `` and its value, as `plist_document` inserts it. -struct plist_entry { - std::string key; - std::string text; -}; - -// Reads one plist fragment's entries. `who` is how a diagnostic names the -// fragment (`options::info_plist`, or a package's [package.metadata.dist-apple]). -inline bool read_plist_entries(const std::string& path, const std::string& who, - std::vector& out, std::string& message) { - namespace xml = mcpp::plugins::xml; - xml::node root; - std::string err; - if (!xml::parse(read_text(path), root, err)) { - message = std::format("mcpp.dist.apple: {} ({}) cannot be read: {}", who, path, err); - return false; - } - const xml::node* dict = top_dict(root); - if (!dict) { - message = std::format("mcpp.dist.apple: {} ({}) has no top-level .", who, path); - return false; - } - std::vector> pairs; - if (!dict_entries(*dict, pairs, err)) { - message = std::format("mcpp.dist.apple: {} ({}): {}", who, path, err); - return false; - } - std::vector seen; - for (auto const& [key, value] : pairs) { - if (std::ranges::find(derived_plist_keys(), key) != derived_plist_keys().end()) { - message = std::format( - "mcpp.dist.apple: {} ({}) sets {}, which this member derives " - "from its options and the engine; set the option instead.", who, path, key); - return false; - } - if (std::ranges::find(seen, key) != seen.end()) { - message = std::format("mcpp.dist.apple: {} ({}) sets {} twice.", who, path, key); - return false; - } - seen.push_back(key); - plist_entry e; - e.key = key; - e.text = " " + key + "\n"; - xml::write(*value, e.text, 1); - out.push_back(std::move(e)); - } - return true; -} - -// A provisioning profile is a CMS-signed property list. The plist is stored in -// the signed content as-is, so it is read from between its `` rather than through `security cms -D`, which exists only on macOS -// and would make a plan made elsewhere unable to check anything. The signature -// is the device's to verify, not this member's. -inline bool read_profile(const std::string& path, const std::string& bundleId, - std::string& entitlementsPlist, std::string& message) { - namespace xml = mcpp::plugins::xml; - const std::string bytes = read_text(path); - const auto b = bytes.find(""); - if (b == std::string::npos || e == std::string::npos || e < b) { - message = std::format( - "mcpp.dist.apple: `options::provisioning_profile` ({}) carries no property list, so " - "it is not a provisioning profile.", path); - return false; - } - xml::node root; - std::string err; - if (!xml::parse(std::string_view(bytes).substr(b, e + 8 - b), root, err)) { - message = std::format("mcpp.dist.apple: the property list in {} cannot be read: {}", path, err); - return false; - } - const xml::node* dict = top_dict(root); - std::vector> pairs; - if (!dict || !dict_entries(*dict, pairs, err)) { - message = std::format("mcpp.dist.apple: the property list in {} has no readable top-level .", path); - return false; - } - const xml::node* entitlements = nullptr; - for (auto const& [key, value] : pairs) if (key == "Entitlements" && value->name == "dict") entitlements = value; - std::vector> granted; - if (!entitlements || !dict_entries(*entitlements, granted, err)) { - message = std::format("mcpp.dist.apple: the provisioning profile {} states no Entitlements dictionary.", path); - return false; - } - std::string appIdentifier; - for (auto const& [key, value] : granted) - if (key == "application-identifier" && value->children.size() == 1 && value->children.front().name.empty()) - appIdentifier = xml::trim_copy(value->children.front().text); - const auto dot = appIdentifier.find('.'); - const std::string pattern = dot == std::string::npos ? std::string() : appIdentifier.substr(dot + 1); - const bool covers = !pattern.empty() && - (pattern == bundleId || pattern == "*" || - (pattern.ends_with(".*") && bundleId.starts_with(pattern.substr(0, pattern.size() - 1)))); - if (!covers) { - message = std::format( - "mcpp.dist.apple: the provisioning profile {} is for the application identifier '{}', " - "which does not cover the bundle identifier '{}'. Set `options::bundle_id` to match, " - "or use the profile made for it.", path, - appIdentifier.empty() ? std::string("(none)") : appIdentifier, bundleId); - return false; - } - // A WILDCARD PROFILE GRANTS `.*`, AND THE SIGNATURE STATES THE BUNDLE. - // Xcode signs with the application identifier the bundle is, which the - // wildcard covers, rather than with the wildcard itself; the other - // entitlements are the profile's as it states them. - xml::node signedWith = *entitlements; - if (pattern != bundleId) { - const std::string exact = appIdentifier.substr(0, dot + 1) + bundleId; - for (std::size_t k = 0; k + 1 < signedWith.children.size(); ++k) { - auto const& key = signedWith.children[k]; - auto& value = signedWith.children[k + 1]; - if (key.name == "key" && key.children.size() == 1 && - xml::trim_copy(key.children.front().text) == "application-identifier" && - value.name == "string" && value.children.size() == 1 && value.children.front().name.empty()) - value.children.front().text = exact; - } - } - entitlementsPlist = "\n" - "\n" - "\n"; - xml::write(signedWith, entitlementsPlist, 0); - entitlementsPlist += "\n"; - return true; -} - // ─── Plan ────────────────────────────────────────────────────────────────── inline plan plan_for(options opt = {}) { @@ -1604,4 +1233,4 @@ inline bool generate(options opt = {}) { return submit(plan_for(std::move(opt))); } -} // namespace mcpp::dist::apple +} // namespace mcpp::dist::apple \ No newline at end of file diff --git a/dist/apple/internal/layout.cppm b/dist/apple/internal/layout.cppm new file mode 100644 index 0000000..6488c03 --- /dev/null +++ b/dist/apple/internal/layout.cppm @@ -0,0 +1,91 @@ +// mcpp.dist.apple.internal.layout -- file, path and launcher-name helpers of mcpp.dist.apple. + +export module mcpp.dist.apple.internal.layout; + +import std; +import mcpp; + +namespace mcpp::dist::apple::detail { + +inline bool is_file(const std::string& p) { + std::error_code ec; + return !p.empty() && std::filesystem::is_regular_file(p, ec); +} + +// Written only when the bytes differ, for the reason `dist/appimage.cppm` +// gives: rewriting identical bytes moves the mtime, and a moved mtime on a +// declared input is indistinguishable from a changed one -- so a second pack +// of an unchanged project would re-copy the bundle and re-sign it. +inline bool write_if_different(const std::filesystem::path& path, + std::string_view bytes) { + std::error_code ec; + std::filesystem::create_directories(path.parent_path(), ec); + if (std::ifstream in(path, std::ios::binary); in) { + std::string old((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + if (old == bytes) return true; + } + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(bytes.data(), static_cast(bytes.size())); + return static_cast(out); +} + +inline std::string read_text(const std::string& path) { + std::ifstream in(path, std::ios::binary); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +inline std::string resolve_path(const std::string& p) { + if (p.empty() || std::filesystem::path(p).is_absolute()) return p; + return (std::filesystem::path(mcpp::manifest_dir()) / p).lexically_normal().string(); +} + +// The program a bundle executes, found in the staged tree: `bin/` +// first, then the tree's top-level entry, then `run.sh`. +// +// THE PROGRAM, NOT THE TREE'S ENTRY SCRIPT. From the release that reads a +// Mach-O program's closure (mcpp 2026.9.14.2), the engine also writes +// `/`, a shell script that executes `bin/` from the +// tree's root. The search used to take that root entry first, which is the +// order `dist/appimage.cppm` needs, and a bundle then executed the script, +// which executed `Contents/MacOS/bin/` -- a file no bundle carries: +// "cannot execute: No such file or directory", exit 126 (macos-15, run +// 34821164486). The script has no work to do inside a bundle, where +// `CFBundleExecutable` names the program directly, and the framework rpath +// `@executable_path/../Frameworks` resolves against the program's own +// directory, which has to be `Contents/MacOS/`. The root entry and `run.sh` +// remain for a tree that carries no `bin/`. +inline std::string launcher_in(const std::string& stage, const std::string& target) { + for (auto candidate : {stage + "/bin/" + target, + stage + "/" + target, + stage + "/run.sh"}) + if (is_file(candidate)) return candidate; + return {}; +} + +// CFBundleExecutable MUST BE A BARE FILENAME, NOT A PATH. +// +// Apple's own bundle documentation describes it as the executable's name +// within `Contents/MacOS/`, and real-world bundle tooling has hit this +// directly enough to be a filed CMake defect: "CFBundleExecutable path in a +// bundle should not be a relative path into bundle." So this member takes +// only the basename of whatever `launcher_in` finds, and the layout step +// copies that file to the top of the executable directory under that name, so +// the name and the file agree wherever in the staged tree it was found. +inline std::string bundle_executable_name(const std::string& launcher_path) { + return std::filesystem::path(launcher_path).filename().string(); +} + +inline std::string sanitize_bundle_id_component(std::string_view s) { + std::string out; + out.reserve(s.size()); + for (char c : s) { + bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9') || c == '-' || c == '.'; + out += ok ? c : '-'; + } + return out; +} + +} // namespace mcpp::dist::apple::detail diff --git a/dist/apple/internal/plist.cppm b/dist/apple/internal/plist.cppm new file mode 100644 index 0000000..6f97f6a --- /dev/null +++ b/dist/apple/internal/plist.cppm @@ -0,0 +1,236 @@ +// mcpp.dist.apple.internal.plist -- Info.plist generation and plist-fragment reading for mcpp.dist.apple. + +export module mcpp.dist.apple.internal.plist; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.dist.apple.internal.layout; + +namespace mcpp::dist::apple::detail { + +inline std::string plist_escape(std::string_view s) { + std::string out; + out.reserve(s.size()); + for (char c : s) { + switch (c) { + case '&': out += "&"; break; + case '<': out += "<"; break; + case '>': out += ">"; break; + default: out += c; + } + } + return out; +} + +// Written as XML text directly rather than by shelling out to `plutil`: the +// content is a handful of string keys this member already holds, and adding +// a second host tool to discover and invoke would buy nothing over +// formatting the lines by hand. `LSMinimumSystemVersion` / `MinimumOSVersion` +// and `CFBundleIconFile` are omitted rather than emitted empty when their +// inputs are empty -- an empty string in either key is a claim as +// unsupported as omitting the key, so omission is the honest one. +// +// `is_ios` AND `is_sim` DECIDE FOUR KEYS, NOT ONE BRANCH. `MinimumOSVersion` +// replaces `LSMinimumSystemVersion`; `CFBundleSupportedPlatforms`, +// `UIDeviceFamily` and `LSRequiresIPhoneOS` are iOS-only and absent from +// every macOS bundle this member has ever written, which is the +// byte-identical property the macOS fixture depends on; `NSHighResolutionCapable` +// is a macOS concept (Retina-aware drawing on a platform that also has +// non-Retina displays) with nothing to opt into on iOS, so it is macOS-only +// in the other direction. +inline std::string plist_document(const std::string& executable, const std::string& bundle_id, + const std::string& name, const std::string& version, + bool is_ios, bool is_sim, + const std::string& min_os_version, + // The project's own entries (0.11.0), already + // formatted, inserted before ``; and the + // defaulted keys they replace. + const std::string& extra_entries, + const std::vector& replaced_keys, + // macOS: the icon FILE's basename, extension + // included, exactly as `CFBundleIconFile` has + // always taken it. iOS: unused (see + // `ios_icon_stems`) and always empty. + const std::string& mac_icon_name, + // iOS: every PNG stem found in + // `options::icon`'s directory. macOS: unused + // and always empty. + const std::vector& ios_icon_stems) { + std::string doc; + doc += "\n"; + doc += "\n"; + doc += "\n\n"; + doc += std::format(" CFBundleExecutable\n {}\n", + plist_escape(executable)); + doc += std::format(" CFBundleIdentifier\n {}\n", + plist_escape(bundle_id)); + doc += std::format(" CFBundleName\n {}\n", + plist_escape(name)); + doc += std::format(" CFBundleShortVersionString\n {}\n", + plist_escape(version)); + doc += std::format(" CFBundleVersion\n {}\n", + plist_escape(version)); + doc += " CFBundlePackageType\n APPL\n"; + if (!min_os_version.empty()) + doc += std::format(" {}\n {}\n", + is_ios ? "MinimumOSVersion" : "LSMinimumSystemVersion", + plist_escape(min_os_version)); + if (is_ios) { + // `env == "sim"` is the engine's own distinction between the two + // rows (triple.cppm: "the simulator is deliberately not a row of + // its own identity... it has its own SDK"); this key is the one + // place a bundle has to restate it, because `simctl install` and a + // real device's installer both read it to refuse the other kind. + doc += std::format( + " CFBundleSupportedPlatforms\n \n" + " {}\n \n", + is_sim ? "iPhoneSimulator" : "iPhoneOS"); + // `[1, 2]`: iPhone and iPad. Nothing here narrows a project to one + // idiom -- that is a project decision (a size class, a storyboard) + // this member has no basis for making. + const auto replaced = [&](std::string_view k) { + return std::ranges::find(replaced_keys, k) != replaced_keys.end(); + }; + if (!replaced("UIDeviceFamily")) + doc += " UIDeviceFamily\n \n" + " 1\n 2\n \n"; + if (!replaced("LSRequiresIPhoneOS")) + doc += " LSRequiresIPhoneOS\n \n"; + if (!ios_icon_stems.empty()) { + doc += " CFBundleIcons\n \n" + " CFBundlePrimaryIcon\n \n" + " CFBundleIconFiles\n \n"; + for (auto const& stem : ios_icon_stems) + doc += std::format(" {}\n", plist_escape(stem)); + doc += " \n \n \n"; + } + } else { + if (std::ranges::find(replaced_keys, std::string_view("NSHighResolutionCapable")) == replaced_keys.end()) + doc += " NSHighResolutionCapable\n \n"; + // Not in the letter of this member's key list, but added + // deliberately: without it, an icon file this member went to the + // trouble of copying into `Contents/Resources/` is inert -- nothing + // in the bundle would ever reference it, and Finder would show the + // generic application icon regardless of `options::icon`. Wiring the + // file up once it exists is what makes the option do what its name + // says. + if (!mac_icon_name.empty()) + doc += std::format(" CFBundleIconFile\n {}\n", + plist_escape(mac_icon_name)); + } + doc += extra_entries; + doc += "\n\n"; + return doc; +} +// The keys `plist_document` derives, which a project's plist may not restate, +// and the keys it only defaults, which a project's plist replaces. +inline const std::vector& derived_plist_keys() { + static const std::vector v = { + "CFBundleExecutable", "CFBundleIdentifier", "CFBundleName", "CFBundleShortVersionString", + "CFBundleVersion", "CFBundlePackageType", "LSMinimumSystemVersion", "MinimumOSVersion", + "CFBundleSupportedPlatforms", "CFBundleIconFile", "CFBundleIcons"}; + return v; +} +inline const std::vector& defaulted_plist_keys() { + static const std::vector v = {"UIDeviceFamily", "LSRequiresIPhoneOS", "NSHighResolutionCapable"}; + return v; +} + +// The top-level `` of a property list, or null. A document whose root is +// `` itself is accepted as well as a full ``. +inline const mcpp::plugins::xml::node* top_dict(const mcpp::plugins::xml::node& root) { + if (root.name == "dict") return &root; + if (root.name != "plist") return nullptr; + for (auto const& c : root.children) if (c.name == "dict") return &c; + return nullptr; +} + +// The value element after each `` of a ``, as (key, value) pairs. +inline bool dict_entries(const mcpp::plugins::xml::node& dict, + std::vector>& out, + std::string& error) { + namespace xml = mcpp::plugins::xml; + for (std::size_t i = 0; i < dict.children.size(); ++i) { + const auto& k = dict.children[i]; + if (k.name.empty()) continue; + if (k.name != "key") { error = "<" + k.name + "> appears where a is expected"; return false; } + const std::string key = k.children.size() == 1 && k.children.front().name.empty() + ? xml::trim_copy(k.children.front().text) : std::string(); + std::size_t j = i + 1; + while (j < dict.children.size() && dict.children[j].name.empty()) ++j; + if (key.empty() || j >= dict.children.size()) { error = "a without a value"; return false; } + out.emplace_back(key, &dict.children[j]); + i = j; + } + return true; +} + +// One Info.plist entry a fragment states: its key and the plist text of the +// `` and its value, as `plist_document` inserts it. +struct plist_entry { + std::string key; + std::string text; +}; + +// Reads one plist fragment's entries. `who` is how a diagnostic names the +// fragment (`options::info_plist`, or a package's [package.metadata.dist-apple]). +inline bool read_plist_entries(const std::string& path, const std::string& who, + std::vector& out, std::string& message) { + namespace xml = mcpp::plugins::xml; + xml::node root; + std::string err; + if (!xml::parse(read_text(path), root, err)) { + message = std::format("mcpp.dist.apple: {} ({}) cannot be read: {}", who, path, err); + return false; + } + const xml::node* dict = top_dict(root); + if (!dict) { + message = std::format("mcpp.dist.apple: {} ({}) has no top-level .", who, path); + return false; + } + std::vector> pairs; + if (!dict_entries(*dict, pairs, err)) { + message = std::format("mcpp.dist.apple: {} ({}): {}", who, path, err); + return false; + } + std::vector seen; + for (auto const& [key, value] : pairs) { + if (std::ranges::find(derived_plist_keys(), key) != derived_plist_keys().end()) { + message = std::format( + "mcpp.dist.apple: {} ({}) sets {}, which this member derives " + "from its options and the engine; set the option instead.", who, path, key); + return false; + } + if (std::ranges::find(seen, key) != seen.end()) { + message = std::format("mcpp.dist.apple: {} ({}) sets {} twice.", who, path, key); + return false; + } + seen.push_back(key); + plist_entry e; + e.key = key; + e.text = " " + key + "\n"; + xml::write(*value, e.text, 1); + out.push_back(std::move(e)); + } + return true; +} + +} // namespace mcpp::dist::apple::detail + +module :private; + +namespace mcpp::dist::apple::detail { + +inline std::string plist_document(const std::string& executable, const std::string& bundle_id, + const std::string& name, const std::string& version, + bool is_ios, bool is_sim, + const std::string& min_os_version, + const std::string& mac_icon_name, + const std::vector& ios_icon_stems) { + return plist_document(executable, bundle_id, name, version, is_ios, is_sim, min_os_version, + std::string(), std::vector(), mac_icon_name, ios_icon_stems); +} + +} // namespace mcpp::dist::apple::detail diff --git a/dist/apple/internal/signing.cppm b/dist/apple/internal/signing.cppm new file mode 100644 index 0000000..d0bd7d4 --- /dev/null +++ b/dist/apple/internal/signing.cppm @@ -0,0 +1,91 @@ +// mcpp.dist.apple.internal.signing -- provisioning-profile reading for mcpp.dist.apple. + +export module mcpp.dist.apple.internal.signing; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.dist.apple.internal.layout; +import mcpp.dist.apple.internal.plist; + +namespace mcpp::dist::apple::detail { + +// A provisioning profile is a CMS-signed property list. The plist is stored in +// the signed content as-is, so it is read from between its `` rather than through `security cms -D`, which exists only on macOS +// and would make a plan made elsewhere unable to check anything. The signature +// is the device's to verify, not this member's. +inline bool read_profile(const std::string& path, const std::string& bundleId, + std::string& entitlementsPlist, std::string& message) { + namespace xml = mcpp::plugins::xml; + const std::string bytes = read_text(path); + const auto b = bytes.find(""); + if (b == std::string::npos || e == std::string::npos || e < b) { + message = std::format( + "mcpp.dist.apple: `options::provisioning_profile` ({}) carries no property list, so " + "it is not a provisioning profile.", path); + return false; + } + xml::node root; + std::string err; + if (!xml::parse(std::string_view(bytes).substr(b, e + 8 - b), root, err)) { + message = std::format("mcpp.dist.apple: the property list in {} cannot be read: {}", path, err); + return false; + } + const xml::node* dict = top_dict(root); + std::vector> pairs; + if (!dict || !dict_entries(*dict, pairs, err)) { + message = std::format("mcpp.dist.apple: the property list in {} has no readable top-level .", path); + return false; + } + const xml::node* entitlements = nullptr; + for (auto const& [key, value] : pairs) if (key == "Entitlements" && value->name == "dict") entitlements = value; + std::vector> granted; + if (!entitlements || !dict_entries(*entitlements, granted, err)) { + message = std::format("mcpp.dist.apple: the provisioning profile {} states no Entitlements dictionary.", path); + return false; + } + std::string appIdentifier; + for (auto const& [key, value] : granted) + if (key == "application-identifier" && value->children.size() == 1 && value->children.front().name.empty()) + appIdentifier = xml::trim_copy(value->children.front().text); + const auto dot = appIdentifier.find('.'); + const std::string pattern = dot == std::string::npos ? std::string() : appIdentifier.substr(dot + 1); + const bool covers = !pattern.empty() && + (pattern == bundleId || pattern == "*" || + (pattern.ends_with(".*") && bundleId.starts_with(pattern.substr(0, pattern.size() - 1)))); + if (!covers) { + message = std::format( + "mcpp.dist.apple: the provisioning profile {} is for the application identifier '{}', " + "which does not cover the bundle identifier '{}'. Set `options::bundle_id` to match, " + "or use the profile made for it.", path, + appIdentifier.empty() ? std::string("(none)") : appIdentifier, bundleId); + return false; + } + // A WILDCARD PROFILE GRANTS `.*`, AND THE SIGNATURE STATES THE BUNDLE. + // Xcode signs with the application identifier the bundle is, which the + // wildcard covers, rather than with the wildcard itself; the other + // entitlements are the profile's as it states them. + xml::node signedWith = *entitlements; + if (pattern != bundleId) { + const std::string exact = appIdentifier.substr(0, dot + 1) + bundleId; + for (std::size_t k = 0; k + 1 < signedWith.children.size(); ++k) { + auto const& key = signedWith.children[k]; + auto& value = signedWith.children[k + 1]; + if (key.name == "key" && key.children.size() == 1 && + xml::trim_copy(key.children.front().text) == "application-identifier" && + value.name == "string" && value.children.size() == 1 && value.children.front().name.empty()) + value.children.front().text = exact; + } + } + entitlementsPlist = "\n" + "\n" + "\n"; + xml::write(signedWith, entitlementsPlist, 0); + entitlementsPlist += "\n"; + return true; +} + +} // namespace mcpp::dist::apple::detail diff --git a/docs/32-dist-apk.md b/docs/32-dist-apk.md index aae19ea..abff3f8 100644 --- a/docs/32-dist-apk.md +++ b/docs/32-dist-apk.md @@ -52,7 +52,7 @@ Commit the lock. Nothing is shrunk or obfuscated, and an archive's ProGuard rules are ignored. **The manifest merge is a stated subset of the Android Gradle plugin's -merger** (`merge_manifests` in `dist/apk.cppm`): +merger** (`merge_manifests` in `dist/apk/internal/manifest.cppm`): - An element is added when the application has none of the same kind and `android:name`. This covers the children of `` diff --git a/mcpp.toml b/mcpp.toml index 6e8f80d..7d95f98 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -29,7 +29,7 @@ import_std = true # # The units divide by what they may import: # -# src/plugins.cppm `mcpp.plugins`, importing only `std`, so the same code +# src/plugins/ `mcpp.plugins`, importing only `std`, so the same code # compiles into `mcpp-embed` -- an ordinary program, which # is what lets the generation be an ACTION and a payload # be that action's declared input @@ -52,7 +52,9 @@ import_std = true # were ordered by PATH, so `rules/spirv.cppm` was compiled before # `src/declare.cppm` and importing it failed with "failed to read compiled # module". They are ordered by their import graph now. -sources = ["src/plugins.cppm"] +sources = ["src/plugins/plugins.cppm", "src/plugins/stage.cppm", "src/plugins/xml.cppm", + "src/plugins/json.cppm", "src/plugins/graph.cppm", "src/plugins/package.cppm", + "src/plugins/names.cppm", "src/plugins/surface.cppm", "src/plugins/tree.cppm"] # EACH RULE STATES WHAT IT COMPILES AND HOW TO REACH IT (mcpp 2026.9.7.1+). # @@ -275,7 +277,7 @@ sources = ["dist/wix.cppm"] implies = ["plugins-core"] [features.dist-apple] -sources = ["dist/apple.cppm"] +sources = ["dist/apple/apple.cppm", "dist/apple/internal/layout.cppm", "dist/apple/internal/plist.cppm", "dist/apple/internal/signing.cppm"] implies = ["plugins-core", "tools-steps"] [features.dist-web] @@ -283,7 +285,7 @@ sources = ["dist/web.cppm"] implies = ["plugins-core"] [features.dist-apk] -sources = ["dist/apk.cppm"] +sources = ["dist/apk/apk.cppm", "dist/apk/internal/util.cppm", "dist/apk/internal/manifest.cppm", "dist/apk/internal/libraries.cppm"] implies = ["plugins-core", "tools-steps"] # `dist-deb` AND `dist-rpm` (0.23.0) SHARE ONE UNIT AND ONE TOOL. Both install diff --git a/segs.json b/segs.json new file mode 100644 index 0000000..756dae0 --- /dev/null +++ b/segs.json @@ -0,0 +1 @@ +{"is_file": [385, 408], "refuse": [409, 433], "attach": [434, 451], "target_app": [452, 464], "launcher_exec": [465, 500], "sanitize": [501, 511], "bundle_id_for": [512, 528], "escape": [529, 542], "doc_big": [543, 643], "doc_small": [644, 653], "readtext_resolve": [654, 663], "plist_rest": [664, 756], "profile": [757, 382], "types": [204, 383], "body": [835, 1607]} \ No newline at end of file diff --git a/src/plugins.cppm b/src/plugins.cppm deleted file mode 100644 index 2bcf6c6..0000000 --- a/src/plugins.cppm +++ /dev/null @@ -1,1645 +0,0 @@ -// mcpp.plugins: the collection's shared library. -// -// Every member of this package is a module interface unit under rules/ or -// tools/, compiled as a host module of its own when the consumer's feature -// request names it. This unit is the lib root: it is compiled before every -// member, so a member may import it. -// -// IT HOLDS WHAT MORE THAN ONE MEMBER NEEDS, AND ONLY THAT. -// -// The lib root is the only unit every member can import. A second unit beside -// it in `[build] sources` is NOT compiled as a host module ahead of the -// members. Measured: a member importing a second lib-root unit failed with -// -// mcpp.plugins.surface: error: failed to read compiled module -// note: imports must be built before being imported -// -// because only the lib root is built first. So shared code lives here rather -// than in a file of its own, and a member that needs it writes -// `import mcpp.plugins;`. -export module mcpp.plugins; - -import std; - -// NO `import mcpp;`. That module exists only inside a build program, and this -// unit has to compile into an ordinary binary too: `mcpp.tools.embed`'s -// executable form is what lets a generated `.S` be an ACTION's output, which -// is the only way the payload it embeds can be a declared input of the edge -// that assembles it. Measured before this: an ordinary build of this package -// failed with `mcpp: failed to read compiled module`. -// -// Everything this unit used to read from that module -- the target OS, whether -// the toolchain has a GAS assembler, the package's name -- is now a parameter. -// The members under rules/ still import it; they are feature-gated, so the -// tool's own build never compiles them. - -export namespace mcpp::plugins { - -// THIS MUST EQUAL `[package] version` IN mcpp.toml, AND CI CHECKS THAT IT DOES. -// -// It was `0.1.1` while the package was `0.2.6`, which nothing noticed because -// nothing read it. A value that is recorded and never read cannot be wrong in a -// way anyone sees, so the fix is not only to correct it: every rule now states -// it with `mcpp::fact`, which makes a build log answer "which collection -// produced these actions" and makes a stale constant a visible defect rather -// than a dormant one. -// -// One package, one version: the number lives in mcpp.toml, and the CI step -// `the collection states its own version` compares the two. -inline constexpr std::string_view version = "0.27.0"; - -} // namespace mcpp::plugins - -// mcpp::plugins::stage -- what the engine wrote beside a staged tree. -// -// SHARED BECAUSE TWO DIST MEMBERS READ IT. `mcpp pack` writes -// `.stage-manifest` (mcpp's docs/50, "The stage manifest"): a -// header, one `needs` line per library name the closure read (mcpp -// 2026.9.14.2+), and the list of staged files. `dist-apk` reads it to trust the -// native libraries under `lib/`, and `dist-apple` reads it to tell the dylibs -// staged beside a program from the resources staged there. Only the header and -// the `needs` lines are parsed; the file list is not. -export namespace mcpp::plugins::stage { - -struct need { - std::string name; // as the needing object spells it - std::string where; // a staged path relative to the tree, `platform` or `unresolved` -}; - -struct manifest { - bool found = false; // the file exists beside the tree - bool walked = true; // `closure = walked` - std::string reason; // `reason = ...`, with `closure = not-walked` - std::vector needs; -}; - -inline manifest read_manifest(std::string tree) { - manifest m; - while (tree.size() > 1 && (tree.back() == '/' || tree.back() == '\\')) - tree.pop_back(); - std::ifstream in(tree + ".stage-manifest", std::ios::binary); - if (!in) return m; - m.found = true; - std::string line; - while (std::getline(in, line)) { - if (!line.empty() && line.back() == '\r') line.pop_back(); - if (line == "closure = not-walked") { m.walked = false; continue; } - if (line.starts_with("reason = ")) { m.reason = line.substr(9); continue; } - if (!line.starts_with("needs\t")) continue; - const auto second = line.find('\t', 6); - if (second == std::string::npos) continue; - m.needs.push_back({ line.substr(6, second - 6), line.substr(second + 1) }); - } - return m; -} - -} // namespace mcpp::plugins::stage - -// mcpp::plugins::xml -- the XML two dist members read and write. -// -// SHARED BECAUSE TWO DIST MEMBERS READ IT. `dist-apk` merges library manifests -// into an application's, and `dist-apple` adds a project's Info.plist entries -// and reads the plist a provisioning profile carries. Neither needs more than -// elements, attributes and text, and neither interprets an entity, so this is -// that much and no more: no namespaces resolved, no DTD read, no validation. -export namespace mcpp::plugins::xml { - -// A tree of elements and text. Comments, the XML declaration and a DOCTYPE are -// read and dropped: the documents this member writes from a tree are generated -// files, and a merged manifest carries no author to read a comment. Attribute -// values are kept exactly as written, entities included, because nothing here -// interprets them beyond comparing and substituting `${applicationId}`. -struct node { - std::string name; // empty: a text node - std::vector> attrs; - std::vector children; - std::string text; // a text node's characters -}; - -struct reader { - std::string_view s; - std::size_t i = 0; - std::string error; - - static bool space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } - bool starts(std::string_view t) const { return s.substr(i, t.size()) == t; } - void skip_space() { while (i < s.size() && space(s[i])) ++i; } - bool skip_past(std::string_view end) { - const auto p = s.find(end, i); - if (p == std::string_view::npos) { i = s.size(); return false; } - i = p + end.size(); - return true; - } - std::string name() { - const std::size_t b = i; - while (i < s.size() && !space(s[i]) && s[i] != '>' && s[i] != '/' && s[i] != '=') ++i; - return std::string(s.substr(b, i - b)); - } - - bool element(node& out) { - ++i; // '<' - out.name = name(); - if (out.name.empty()) { error = "an element without a name"; return false; } - for (;;) { - skip_space(); - if (i >= s.size()) { error = "<" + out.name + "> is not terminated"; return false; } - if (starts("/>")) { i += 2; return true; } - if (s[i] == '>') { ++i; break; } - std::string attr = name(); - skip_space(); - if (attr.empty() || i >= s.size() || s[i] != '=') { - error = "an attribute of <" + out.name + "> has no value"; - return false; - } - ++i; - skip_space(); - if (i >= s.size() || (s[i] != '"' && s[i] != '\'')) { - error = "attribute " + attr + " of <" + out.name + "> is not quoted"; - return false; - } - const char quote = s[i++]; - const auto end = s.find(quote, i); - if (end == std::string_view::npos) { error = "attribute " + attr + " is not terminated"; return false; } - out.attrs.emplace_back(std::move(attr), std::string(s.substr(i, end - i))); - i = end + 1; - } - for (;;) { - if (i >= s.size()) { error = "<" + out.name + "> is not closed"; return false; } - if (starts("= s.size() || s[i] != '>') { - error = " closes <" + out.name + ">"; - return false; - } - ++i; - return true; - } - if (starts("")) { error = "a comment is not terminated"; return false; } continue; } - if (starts("")) { error = "a processing instruction is not terminated"; return false; } continue; } - if (starts("")) { error = "a CDATA section is not terminated"; return false; } - node t; - t.text = std::string(s.substr(b, i - b)); - out.children.push_back(std::move(t)); - continue; - } - if (s[i] == '<') { - node child; - if (!element(child)) return false; - out.children.push_back(std::move(child)); - continue; - } - const std::size_t b = i; - auto end = s.find('<', i); - if (end == std::string_view::npos) end = s.size(); - i = end; - bool blank = true; - for (std::size_t j = b; j < end; ++j) if (!space(s[j])) { blank = false; break; } - if (!blank) { - node t; - t.text = std::string(s.substr(b, end - b)); - out.children.push_back(std::move(t)); - } - } - } - - bool document(node& root) { - for (;;) { - skip_space(); - if (starts(""); continue; } - if (starts(""); continue; } - if (starts(""); continue; } - break; - } - if (i >= s.size() || s[i] != '<') { error = "no root element"; return false; } - if (!element(root)) return false; - return true; - } -}; - -inline bool parse(std::string_view text, node& root, std::string& error) { - reader r{text}; - if (!r.document(root)) { error = r.error; return false; } - return true; -} - -inline std::string trim_copy(const std::string& s) { - std::size_t b = 0, e = s.size(); - while (b < e && reader::space(s[b])) ++b; - while (e > b && reader::space(s[e - 1])) --e; - return s.substr(b, e - b); -} - -inline void write(const node& n, std::string& out, int depth) { - const std::string pad(static_cast(depth) * 4, ' '); - if (n.name.empty()) { out += pad + trim_copy(n.text) + "\n"; return; } - out += pad + "<" + n.name; - for (auto const& a : n.attrs) out += " " + a.first + "=\"" + a.second + "\""; - if (n.children.empty()) { out += "/>\n"; return; } - if (n.children.size() == 1 && n.children.front().name.empty()) { - out += ">" + n.children.front().text + "\n"; - return; - } - out += ">\n"; - for (auto const& c : n.children) write(c, out, depth + 1); - out += pad + "\n"; -} - -inline std::string attr_of(const node& n, std::string_view key) { - for (auto const& a : n.attrs) if (a.first == key) return a.second; - return {}; -} - -inline void set_attr(node& n, const std::string& key, const std::string& value) { - for (auto& a : n.attrs) if (a.first == key) { a.second = value; return; } - n.attrs.emplace_back(key, value); -} - -} // namespace mcpp::plugins::xml - -// mcpp::plugins::json -- the JSON two dist members read. -// -// SHARED BECAUSE TWO DOCUMENTS ARE READ WITH IT. `dist-apk` reads coursier's -// resolution report, and `mcpp::plugins::graph` below reads the engine's graph -// document for `dist-apk` and `dist-apple`. A second parser for the second -// document is how two readers come to disagree about one file, so there is one. -// It reads objects, arrays, strings (with `\u` escapes, surrogate pairs -// included, and a refusal for a surrogate that is not part of one), numbers, -// `true`, `false` and `null`; a number keeps its spelling in `text`. -export namespace mcpp::plugins::json { - -// A MEMBER IS ITS OWN STRUCT, NOT `std::pair`. Under clang -// with libstdc++'s `std` module, `pair` inside `value` is -// instantiated while `value` is still incomplete -- its destructor needs the -// pair and the pair needs `value` -- and the unit fails with "incomplete type -// used in type trait expression". GCC accepts the pair and so does clang with -// libc++, so neither build lane saw it; clangd reading a GCC project in the -// editor is exactly that combination. A plain aggregate, with `get()` defined -// once both types are complete, compiles under all three. -struct member; - -struct value { - enum class kind { null, boolean, number, string, array, object }; - kind type = kind::null; - std::string text; // string, number or boolean spelling - std::vector items; - std::vector members; - - const value* get(std::string_view key) const; -}; - -struct member { - std::string first; - value second; -}; - -inline const value* value::get(std::string_view key) const { - for (auto const& m : members) if (m.first == key) return &m.second; - return nullptr; -} - -struct reader { - std::string_view s; - std::size_t i = 0; - - void skip_space() { - while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i; - } - // The four hexadecimal digits of one `\u` escape, `i` already past the `u`. - bool hex4(unsigned& cp) { - if (i + 4 > s.size()) return false; - cp = 0; - for (int k = 0; k < 4; ++k) { - const char h = s[i++]; - cp <<= 4; - if (h >= '0' && h <= '9') cp |= static_cast(h - '0'); - else if (h >= 'a' && h <= 'f') cp |= static_cast(h - 'a' + 10); - else if (h >= 'A' && h <= 'F') cp |= static_cast(h - 'A' + 10); - else return false; - } - return true; - } - bool string(std::string& out) { - if (i >= s.size() || s[i] != '"') return false; - ++i; - while (i < s.size() && s[i] != '"') { - if (s[i] != '\\') { out += s[i++]; continue; } - if (++i >= s.size()) return false; - const char e = s[i++]; - switch (e) { - case 'n': out += '\n'; break; - case 't': out += '\t'; break; - case 'r': out += '\r'; break; - case 'b': out += '\b'; break; - case 'f': out += '\f'; break; - case 'u': { - // A code point above U+FFFF reaches JSON as a surrogate - // PAIR, which is two `\u` escapes. Encoding each half on its - // own produces two three-byte sequences holding unpaired - // surrogates -- not UTF-8, and accepted by nothing that - // reads the manifest this value is written into. The pair is - // combined here, and a surrogate that is not part of one is - // refused, so a malformed document is a refusal rather than - // a silently corrupted string. - unsigned cp = 0; - if (!hex4(cp)) return false; - if (cp >= 0xd800 && cp <= 0xdbff) { - if (i + 6 > s.size() || s[i] != '\\' || s[i + 1] != 'u') return false; - i += 2; - unsigned lo = 0; - if (!hex4(lo)) return false; - if (lo < 0xdc00 || lo > 0xdfff) return false; - cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); - } else if (cp >= 0xdc00 && cp <= 0xdfff) { - return false; // a low surrogate with no high half - } - if (cp < 0x80) out += static_cast(cp); - else if (cp < 0x800) { out += static_cast(0xc0 | (cp >> 6)); out += static_cast(0x80 | (cp & 0x3f)); } - else if (cp < 0x10000) { out += static_cast(0xe0 | (cp >> 12)); out += static_cast(0x80 | ((cp >> 6) & 0x3f)); out += static_cast(0x80 | (cp & 0x3f)); } - else { - out += static_cast(0xf0 | (cp >> 18)); - out += static_cast(0x80 | ((cp >> 12) & 0x3f)); - out += static_cast(0x80 | ((cp >> 6) & 0x3f)); - out += static_cast(0x80 | (cp & 0x3f)); - } - break; - } - default: out += e; - } - } - if (i >= s.size()) return false; - ++i; - return true; - } - bool parse_value(value& out) { - skip_space(); - if (i >= s.size()) return false; - const char c = s[i]; - if (c == '"') { out.type = value::kind::string; return string(out.text); } - if (c == '{') { - out.type = value::kind::object; - ++i; - skip_space(); - if (i < s.size() && s[i] == '}') { ++i; return true; } - for (;;) { - skip_space(); - std::string key; - if (!string(key)) return false; - skip_space(); - if (i >= s.size() || s[i] != ':') return false; - ++i; - value v; - if (!parse_value(v)) return false; - out.members.emplace_back(std::move(key), std::move(v)); - skip_space(); - if (i < s.size() && s[i] == ',') { ++i; continue; } - if (i < s.size() && s[i] == '}') { ++i; return true; } - return false; - } - } - if (c == '[') { - out.type = value::kind::array; - ++i; - skip_space(); - if (i < s.size() && s[i] == ']') { ++i; return true; } - for (;;) { - value v; - if (!parse_value(v)) return false; - out.items.push_back(std::move(v)); - skip_space(); - if (i < s.size() && s[i] == ',') { ++i; continue; } - if (i < s.size() && s[i] == ']') { ++i; return true; } - return false; - } - } - const std::size_t b = i; - while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' && - s[i] != ' ' && s[i] != '\n' && s[i] != '\r' && s[i] != '\t') ++i; - out.text = std::string(s.substr(b, i - b)); - if (out.text == "null") out.type = value::kind::null; - else if (out.text == "true" || out.text == "false") out.type = value::kind::boolean; - else out.type = value::kind::number; - return !out.text.empty(); - } -}; - -// The whole text is one value, with nothing but white space after it. -inline bool parse_json(std::string_view text, value& out) { - reader r{text}; - if (!r.parse_value(out)) return false; - r.skip_space(); - return r.i == r.s.size(); -} - -// A string member of an object, or empty when absent or not a string. -inline std::string string_of(const value* v) { - return v && v->type == value::kind::string ? v->text : std::string(); -} - -} // namespace mcpp::plugins::json - -// mcpp::plugins::graph -- the resolved dependency graph the engine states. -// -// mcpp 2026.9.16.1 gives the ROOT project's build program `MCPP_GRAPH_FILE` -// (`mcpp::graph_file()`), a document naming every package of the resolved graph, -// dependencies before their requesters, each with its manifest directory and its -// `[package.metadata]` verbatim (mcpp docs/30, "Reading the resolved graph"). A -// member that merges what libraries contribute reads a table of its own out of -// that metadata: `[package.metadata.dist-apk]`, `[package.metadata.dist-apple]`. -// -// READ THROUGH THE ENVIRONMENT, NOT `mcpp::graph_file()`. This unit does not -// import `mcpp` (see the top of this file), and a member that called the -// accessor would not compile against an engine older than the one that added it. -// An unset or empty variable is an older engine, or a dependency's program, and -// reads as a graph with no packages, which leaves every member's behaviour as it -// was. -export namespace mcpp::plugins::graph { - -struct package { - std::string canonical; // `namespace.name@version` - std::string name; - std::string namespace_; - std::string version; - bool root = false; - std::string manifest_dir; // absolute - json::value metadata; // the package's [package.metadata], an object -}; - -struct document { - bool present = false; // MCPP_GRAPH_FILE named a file - std::string path; - std::vector packages; // dependencies before requesters -}; - -// The graph this build program was given, or the reason it cannot be read. A -// variable naming a file that is missing or not a `mcpp.graph` document is an -// error rather than an empty graph: the engine promised a document, and reading -// nothing would silently drop every contribution. -inline std::expected read() { - document d; - const char* env = std::getenv("MCPP_GRAPH_FILE"); - if (!env || !*env) return d; - d.present = true; - d.path = env; - std::ifstream in(d.path, std::ios::binary); - if (!in) - return std::unexpected(std::format("the graph document {} cannot be read", d.path)); - const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - json::value doc; - if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) - return std::unexpected(std::format("the graph document {} is not JSON", d.path)); - if (json::string_of(doc.get("kind")) != "mcpp.graph") - return std::unexpected(std::format("the graph document {} is not a mcpp.graph document", d.path)); - const json::value* list = doc.get("packages"); - if (!list || list->type != json::value::kind::array) - return std::unexpected(std::format("the graph document {} has no packages array", d.path)); - for (auto const& entry : list->items) { - if (entry.type != json::value::kind::object) continue; - package p; - if (const json::value* id = entry.get("package")) { - p.canonical = json::string_of(id->get("canonical")); - p.name = json::string_of(id->get("name")); - p.namespace_ = json::string_of(id->get("namespace")); - p.version = json::string_of(id->get("version")); - } - if (const json::value* r = entry.get("root")) - p.root = r->type == json::value::kind::boolean && r->text == "true"; - p.manifest_dir = json::string_of(entry.get("manifest_dir")); - if (const json::value* m = entry.get("metadata"); m && m->type == json::value::kind::object) - p.metadata = *m; - d.packages.push_back(std::move(p)); - } - return d; -} - -// The package's `[package.metadata.]` table, or null. -inline const json::value* table_of(const package& p, std::string_view tool) { - const json::value* t = p.metadata.get(tool); - return t && t->type == json::value::kind::object ? t : nullptr; -} - -// A path a package states, made absolute against its manifest directory. -inline std::string resolve(const package& p, const std::string& path) { - if (path.empty() || std::filesystem::path(path).is_absolute()) return path; - return (std::filesystem::path(p.manifest_dir) / path).lexically_normal().string(); -} - -// How a diagnostic names a package: its canonical identity, or its name. -inline std::string label_of(const package& p) { - return !p.canonical.empty() ? p.canonical : p.name; -} - -} // namespace mcpp::plugins::graph - -// mcpp::plugins::package -- the metadata of a staged package. -// -// `mcpp pack` (2026.10.27.1+, SPEC-014 §4.5) writes `mcpp-package.json` at the -// root of every staged tree: the package, its three axes, its legs, the systems -// whose loaders it carries, how it is started, and every file with its role, -// its leg and its digest. It is the input of a package format's provider, of -// `mcpp pack --merge` and of `mcpp emit xpkg`. A provider reads it here rather -// than walking the tree and deciding for itself which file is the program: the -// engine has already decided, once, for every format. -// -// SCHEMA 1 AND ONLY SCHEMA 1. A document of another schema is refused rather -// than read as far as it goes: a field whose meaning changed would be read -// with the old one. -export namespace mcpp::plugins::package { - -struct file { - std::string path; // relative to the tree's root, `/`-separated - std::string role; // program | image | library | loader | launcher | resource | metadata - std::string leg; // the leg's triple; empty when every leg shares the file - std::string sha256; -}; - -struct info { - int schema = 0; - std::string name; - std::string version; - std::string platform; // `@`; empty: none - std::string linkage; // static | shared | declared - std::string mode; // system | vendored | self-contained | static - std::vector legs; // canonical triples - std::vector systems; // `-` of the loaders under libexec/ - std::vector runner; // the platform's runner argv; empty: native - // The entry of each architecture (universal packages), in the document's - // order: architecture, then the entry's path in the tree. - std::vector> entry; - std::string program; // the program's path (one native leg) - std::vector files; - std::string root; // the tree the document was read from -}; - -namespace detail { - -inline std::vector strings_of(const json::value* v) { - std::vector out; - if (!v || v->type != json::value::kind::array) return out; - for (auto const& item : v->items) - if (item.type == json::value::kind::string) out.push_back(item.text); - return out; -} - -} // namespace detail - -// The document at `/mcpp-package.json`, or why it cannot be read. -inline std::expected read(std::string_view stage_dir) { - std::string root(stage_dir); - while (root.size() > 1 && (root.back() == '/' || root.back() == '\\')) root.pop_back(); - const std::string path = root + "/mcpp-package.json"; - std::ifstream in(path, std::ios::binary); - if (!in) return std::unexpected(std::format("{} cannot be read: the tree is not a staged package", path)); - const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - json::value doc; - if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) - return std::unexpected(std::format("{} is not a JSON object", path)); - info p; - p.root = root; - if (const json::value* s = doc.get("schema"); s && s->type == json::value::kind::number) - p.schema = std::atoi(s->text.c_str()); - if (p.schema != 1) - return std::unexpected(std::format( - "{} states schema {}; this collection reads schema 1 (mcpp SPEC-014 §4.5)", path, p.schema)); - p.name = json::string_of(doc.get("name")); - p.version = json::string_of(doc.get("version")); - p.platform = json::string_of(doc.get("platform")); - p.linkage = json::string_of(doc.get("linkage")); - p.mode = json::string_of(doc.get("mode")); - p.legs = detail::strings_of(doc.get("legs")); - p.systems = detail::strings_of(doc.get("systems")); - if (const json::value* launch = doc.get("launch"); launch && launch->type == json::value::kind::object) { - p.runner = detail::strings_of(launch->get("runner")); - p.program = json::string_of(launch->get("program")); - if (const json::value* e = launch->get("entry"); e && e->type == json::value::kind::object) - for (auto const& m : e->members) - if (m.second.type == json::value::kind::string) p.entry.emplace_back(m.first, m.second.text); - } - const json::value* files = doc.get("files"); - if (!files || files->type != json::value::kind::array) - return std::unexpected(std::format("{} has no files array", path)); - for (auto const& f : files->items) { - if (f.type != json::value::kind::object) continue; - p.files.push_back({ json::string_of(f.get("path")), json::string_of(f.get("role")), - json::string_of(f.get("leg")), json::string_of(f.get("sha256")) }); - } - return p; -} - -// The files of `p` with `role`, in the document's order. -inline std::vector files_with_role(const info& p, std::string_view role) { - std::vector out; - for (auto const& f : p.files) - if (f.role == role) out.push_back(f); - return out; -} - -// The entry of `arch`, or empty. -inline std::string entry_of(const info& p, std::string_view arch) { - for (auto const& [a, path] : p.entry) - if (a == arch) return path; - return {}; -} - -} // namespace mcpp::plugins::package - -// mcpp::plugins::names -- the derivations that turn a path into a C++ name. -// -// THESE ARE SHARED BECAUSE THEY WERE COPIED. `common_base_dir` and -// `namespace_of` were written in `rules/spirv.cppm` and written again in -// `rules/slang.cppm`, and `mcpp.tools.island` is the third caller needing the -// same answers. Two copies that agree today are still two copies: a directory -// named `default` or `2d` has to get ONE answer, and one function is how that -// is guaranteed rather than two files that happen to say the same thing. -export namespace mcpp::plugins::names { - -// `a` made relative to the directory `b`, as strings: separators unified, and -// the prefix stripped when `a` lies under `b`; `a` unchanged otherwise. -// -// NOTHING IN THIS PACKAGE INSTANTIATES `std::filesystem::path`'s ITERATOR -- -// see `components()` below for the compiler that refuses it. The members' -// relative-path arithmetic is this string function, defined once here. -inline std::string relative_to(std::string a, std::string b) { - for (auto& c : a) if (c == '\\') c = '/'; - for (auto& c : b) if (c == '\\') c = '/'; - while (!b.empty() && b.back() == '/') b.pop_back(); - if (!b.empty() && a.starts_with(b + "/")) return a.substr(b.size() + 1); - return a; -} - -// A GENERATED NAME THE C++ COMPILER WILL ACCEPT. -// -// Three transformations, and the third is the one every hand-rolled copy of -// this function was missing. Non-identifier characters become `_`; a leading -// digit gets a `_` in front; and a result that is a KEYWORD gets a trailing `_`. -// -// The keyword case is not hypothetical. The first two rules accept `default`, -// `template`, `operator`, `private` and `union` unchanged -- they are valid -// identifiers to a character filter and reserved to the compiler -- and -// `shaders/default/` is an ordinary name for a shader directory. What it -// produced was `namespace default {` in a generated file, and an error naming a -// line its author never wrote. -// -// TRAILING `_`, not a prefix: `_default` is reserved at namespace scope -// (a leading underscore in the global namespace), and prefixing would trade one -// reserved name for another. -// -// The list is the keywords of the standard this collection targets. A word that -// is contextual rather than reserved (`final`, `override`, `import`, `module`) -// is a legal identifier and is left alone. -inline bool is_cxx_keyword(std::string_view w) { - static constexpr std::string_view kWords[] = { - "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "char8_t", "char16_t", - "char32_t", "class", "compl", "concept", "const", "consteval", - "constexpr", "constinit", "const_cast", "continue", "co_await", - "co_return", "co_yield", "decltype", "default", "delete", "do", "double", - "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", - "float", "for", "friend", "goto", "if", "inline", "int", "long", - "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", - "operator", "or", "or_eq", "private", "protected", "public", "register", - "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", - "static", "static_assert", "static_cast", "struct", "switch", - "template", "this", "thread_local", "throw", "true", "try", "typedef", - "typeid", "typename", "union", "unsigned", "using", "virtual", "void", - "volatile", "wchar_t", "while", "xor", "xor_eq", - }; - for (auto k : kWords) if (k == w) return true; - return false; -} - -// `fallback` is used when the input sanitises to nothing, which a file named -// only in punctuation does. -// -// INDEXED RATHER THAN A RANGE-FOR over the string, for the reason recorded in -// `mcpp.tools.island`: iterating a `std::string` inside an exported inline -// function makes GCC 16 instantiate its iterator in this BMI, and a consumer's -// build program then fails to compile on `always_inline` in a header naming -// neither this file nor this loop. -inline std::string identifier(std::string_view raw, std::string_view fallback) { - std::string s; - for (std::size_t i = 0; i < raw.size(); ++i) { - const char c = raw[i]; - s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; - } - if (s.empty()) s = std::string(fallback); - if (!s.empty() && std::isdigit(static_cast(s.front()))) - s.insert(s.begin(), '_'); - if (is_cxx_keyword(s)) s += '_'; - return s; -} - - -// ---- internals ------------------------------------------------------------- - -inline std::vector split_module_name(std::string_view name) { - std::vector out; - for (std::size_t i = 0; i <= name.size();) { - auto dot = name.find('.', i); - auto one = dot == std::string_view::npos ? name.substr(i) : name.substr(i, dot - i); - if (!one.empty()) out.emplace_back(one); - if (dot == std::string_view::npos) break; - i = dot + 1; - } - return out; -} - -// THE BASE DIRECTORY IS DERIVED, NOT ASKED FOR. -// -// A payload's namespace comes from where it sits relative to the tree the -// project globbed, so something has to say where that tree starts. Asking the -// project would put a second spelling of the glob in the manifest, and the two -// would disagree the first time a glob moved. The shallowest directory every -// path shares is the same answer without the second spelling: for -// `shaders/*.comp` it is `shaders` and every namespace is empty; for -// `shaders/a/x.comp` and `shaders/b/y.comp` it is still `shaders`, and the two -// land in `::a` and `::b`. -// -// A single path has no common prefix with anything, so its own directory is the -// base and its namespace is empty -- which is the same answer the general case -// gives once a second file appears beside it. -// A path's components as strings: both separators split, empty and `.` -// components dropped. This is the one place the lib root reads a path apart, -// and it does so WITHOUT `std::filesystem::path`'s iterator on purpose: -// -// A MODULE THAT INSTANTIATES `_Path_iterator` POISONS ITS IMPORTERS UNDER MSVC -// 14.52. Measured on xrgui's CI (14.52.36629 and .36725): this unit compiled -// while it iterated paths, and every member importing it that then touched -// `std::filesystem` at all failed inside the STL -- -// -// include\filesystem(1572): error C2801: '..._Path_iterator<...>::operator ==' -// must be a non-static member -// -// -- the iterator's hidden-friend comparison, refused when the importer meets -// it both through `import std` and through this module's BMI. Removing the -// calls from the members changed nothing; the instantiation had to leave the -// lib root. Component comparison is what `lexically_relative` bought in 0.5.2 -// (a Windows separator bug), and splitting on both separators keeps that. -inline std::vector components(std::string_view path) { - std::vector out; - std::string cur; - auto flush = [&] { if (!cur.empty() && cur != ".") out.push_back(cur); cur.clear(); }; - for (char c : path) { if (c == '/' || c == '\\') flush(); else cur += c; } - flush(); - return out; -} - -// The directory part of a path, as written: everything before the last -// separator, or empty when there is none. -inline std::string_view parent_of(std::string_view path) { - const auto slash = path.find_last_of("/\\"); - return slash == std::string_view::npos ? std::string_view{} : path.substr(0, slash); -} - -inline std::string common_base_dir(std::span paths) { - std::vector prefix; - bool first = true; - for (auto const& src : paths) { - auto segs = components(parent_of(src)); - if (first) { prefix = std::move(segs); first = false; continue; } - std::size_t keep = 0; - while (keep < prefix.size() && keep < segs.size() && prefix[keep] == segs[keep]) ++keep; - prefix.resize(keep); - } - std::string out; - for (auto const& s : prefix) { if (!out.empty()) out += '/'; out += s; } - return out; -} - -// The namespace segments a file sits in, below the group's own: the path from -// the base directory to the file, sanitised one segment at a time. -// -// RELATIVE BY PATH ARITHMETIC, NOT BY STRING SURGERY, AND THAT IS A WINDOWS -// FIX. This trimmed `base` off the front of the directory as a STRING and -// iterated what was left. On Windows the two spellings differ even when the -// two paths are the same: a caller states a root with forward slashes, and -// `directory_iterator` appends with the preferred separator, so the leftover -// was `\image` rather than `image`. Iterating that yields the ROOT DIRECTORY -// as its first component, which sanitised to `_` -- and the payload landed in -// `myapp::shaders::_::image`, a namespace no consumer writes. Measured: the -// island fixture failed to compile on windows-2022 with `no member named -// 'image' in namespace 'island_interface::kernels'`, while the same fixture -// passed on Linux and macOS. -// -// COMPONENTS are compared, so the separator a caller happened to write is not -// part of the question -- `components()` splits on both. A base that is not a -// prefix is a caller error rather than a namespace; it answers with no -// segments rather than with the whole absolute path, which is what the first -// string form produced. (Through `components()` rather than -// `lexically_relative` for the reason stated on it.) -inline std::vector namespace_of(std::string_view src, std::string_view base) { - std::vector out; - auto dir = components(parent_of(src)); - if (!base.empty()) { - const auto b = components(base); - if (b.size() > dir.size()) return out; - for (std::size_t i = 0; i < b.size(); ++i) if (b[i] != dir[i]) return out; - dir.erase(dir.begin(), dir.begin() + static_cast(b.size())); - } - for (auto const& s : dir) { - if (s == "..") continue; - // `shaders/default/` is an ordinary directory name and - // `namespace default {` is not a namespace. - out.push_back(identifier(s, "dir")); - } - return out; -} -} // namespace mcpp::plugins::names - - -// mcpp.plugins.surface -- the interface a consumer names for an embedded payload. -// -// WHY THIS IS SHARED RATHER THAN PER-RULE. -// -// `mcpp.rules.spirv` and `mcpp.rules.slang` produce the same kind of thing: a -// block of bytes the program hands to a device API. `mcpp.tools.embed` produces -// it from a file that was already there. The three differ in who produces the -// bytes and disagree about nothing else, so the declaration a consumer reads is -// written once, here, and the shape is identical whichever produced it. A rule -// that wrote its own would be a second copy of a decision, and the two would -// drift the way the two shader compilers' headers drifted before 0.2.6. -// -// THE INTERFACE IS A FUNCTION, NOT A VARIABLE. -// -// A variable cannot keep one shape across the ways bytes can be stored, because -// `constexpr` and `extern` are mutually exclusive: an array compiled into a -// translation unit can be constant-evaluated and one living in a section cannot. -// A function can, so where the bytes live stays an option a project revises -// without touching a consumer. -// -// THE INTERFACE NAMES NO STANDARD-LIBRARY TYPE, AND THAT IS MEASURED. -// -// The same 1 MB payload, reached four ways, compiled with GCC 16.1: -// -// data in the module (`export inline constexpr`) BMI 6 282 240 B -// data in a header source 3 145 728 B -// data in an object, interface returns std::span BMI 1 313 968 B -// data in an object, interface returns a std-free POD BMI 1 808 B -// -// The third row is 727 times the fourth, and its cost is FIXED rather than -// proportional to the payload: the 1.28 MB is ``'s templates, present -// whether the payload is 16 KB or 16 MB. A consumer that wants a `std::span` -// constructs one from the two members, and `` is then included by the -// consumer that uses it rather than by every consumer that imports this. -// -// There is a second, independent reason for the same decision. `import std;` -// requires `std.gcm` to have been built, which a project with -// `modules = true, import_std = false` has not done. A std-free interface needs -// neither. -// -// WHY THE ACCESSORS HAVE C LANGUAGE LINKAGE. -// -// A function declared in a module interface has module linkage and can only be -// defined by a unit attached to that module. Defining them would therefore need -// a module implementation unit, and the definitions include the generated data -// headers -- which would put the arrays back into the interface's own -// compilation. Declaring the accessors `extern "C"` instead gives them external -// linkage, so an ordinary translation unit defines them, the module interface -// holds two declarations and one inline call per payload, and the bytes are -// never seen by the interface at all. -// -// It also removes a portability question: module implementation units are the -// least exercised corner of every implementation this package supports, and -// nothing here needs them. -// -// ONE COPY OF THE BYTES. -// -// A generated data header declares `static const uint32_t []`, so every -// translation unit that includes it gets its own copy. Under this surface -// exactly one translation unit includes it -- the generated implementation -- -// and every consumer reaches the same array through the accessor. -export namespace mcpp::plugins::surface { - -// The name derivations live in `mcpp::plugins::names`. They are reachable under -// this namespace as well, because every rule in this collection already spells -// them this way -- one definition under two spellings is not two definitions. -using names::identifier; -using names::split_module_name; -using names::common_base_dir; -using names::namespace_of; - -// How a consumer names the payloads. -// -// `module_` is the default where the project builds C++ modules, and -// `c_header` is what a project without them gets. The choice does not change -// any declaration's shape: the same struct, the same function names, the same -// namespaces. Only the file a consumer reaches them through differs. -enum class kind { module_, c_header }; - -// WHICH HALF OF THE SURFACE A CALL WRITES. -// -// The two are separate because their INPUTS are. The interface is a function of -// the item list: names, namespaces, the accessor declarations. The body is a -// function of the item list AND, under `storage::object`, of the payloads -// themselves -- the assembly names each one in `.incbin`, and the object it -// produces is those bytes. -// -// Declaring them as one action would make a payload change rewrite the -// interface too, and rebuild every BMI that imports it. Declaring them -// separately states what is true and costs a consumer nothing. -enum class half { interface_, body }; - -// The element the accessor hands back. `word32` is what an API taking -// `const uint32_t*` wants -- `vkCreateShaderModule` is the case this package -// has -- and asking for it here is cheaper than a reinterpret_cast at every -// call site, which is undefined behaviour on an under-aligned byte array. -enum class element { byte_, word32 }; - -// WHERE THE BYTES LIVE. Orthogonal to `kind`, which decides how a consumer -// NAMES them: the declarations are identical under all three, so a project -// changes this and no consumer changes. -// -// WHICH ONE TO USE IS A MEASUREMENT, NOT A PREFERENCE. With GCC 16.1 on this -// project's own fixtures, 100 payloads of 16 KB each: -// -// header route compile 0.64s + link 0.44s = 1.10s -// object route convert 1.28s + compile 0.44s + link 0.46s = 2.17s -// -// The header route is faster, because at a real shader's size neither route has -// a measurable marginal cost and the total is decided by how many processes -// start -- and one compiler invocation absorbs many headers. The crossover is -// the TOTAL embedded byte count, not the payload count: below about 1 MB the -// header route wins, and above about 4 MB the compiler's slightly superlinear -// curve loses by an order of magnitude (2.31s against 0.116s at 4 MB). Source -// expansion is a constant 2.75x, which is the second half of the same reason. -// -// So `header` is the default and `object` is what a project reaches for when it -// has more payload than that, not what it reaches for because objects sound -// tidier. -enum class storage { - // The payload is a C array in generated source, compiled into the program. - // No assembler involved, so it works on every toolchain including MSVC. - header, - // The payload is a section in an object, reached through `.incbin` in a - // generated `.S`. The bytes never pass through the C++ compiler. - // - // Requires a GAS-capable assembler. Every gcc and clang toolchain has one - // on all three platforms; MSVC does not, and mcpp refuses `.S` under it, so - // the emitter falls back to `header` there and says so once. - object, - // The payload is written beside the artifact and read at run time. The - // program's correctness then depends on its working directory, which is the - // reason this is not the default -- but it is what shader hot-reload needs, - // and what a payload too large to link needs. - sidecar, -}; - -// One payload in a group. -struct item { - // The C++ identifier, already sanitised by the caller: `blur_comp`. - std::string identifier; - // Namespace segments BELOW the group's own, from the payload's directory - // relative to its root: `{"post"}` for `shaders/post/tonemap.frag`. This is - // what keeps two payloads with one stem from colliding, and what makes the - // name a consumer writes say where the payload came from. - std::vector name_space; - // The generated data header this payload's bytes arrive in, AS AN - // `#include` WRITES IT -- relative to the directory the caller put on the - // include path, not an absolute path and not a bare file name. The - // generated tree mirrors the payload tree, so two payloads sharing a stem - // in different directories reach different headers, and a bare file name - // could not tell them apart. - std::string data_header; - // The array that header declares, qualified if it sits in a namespace. - // Unused under `storage::object`, where the linker symbol is derived from - // the accessor name instead, and under `storage::sidecar`. - std::string data_symbol; - // The payload file itself, as an absolute path. Required by `object`, whose - // generated `.S` names it in `.incbin`, and by `sidecar`, which copies it. - // The file need not exist yet: `.incbin` resolves its argument at assembly - // time, which is after the action that writes it has run, and that is what - // lets the whole surface be written at plan time. - std::string payload_path; - // Where a sidecar payload is found at run time, relative to the artifact. - std::string sidecar_name; - // The payload's size IN BYTES, as an expression valid where the generated - // implementation writes it. Empty means `sizeof `. - // - // IT EXISTS BECAUSE `sizeof` IS NOT ALWAYS THE ANSWER. `mcpp.tools.embed` - // can append a terminating zero byte that its own `_size` constant does not - // count, so `sizeof` and `_size` differ by one and only one of them is what - // the payload is. Measured: a group of null-terminated text payloads - // reported one byte too many and the fixture's comparison failed on a - // trailing NUL. A caller that knows the difference states it here rather - // than letting the generator guess. - std::string data_size_expr; -}; - -struct options { - kind surface = kind::module_; - storage store = storage::header; - element elem = element::word32; - // The module a consumer imports, e.g. `myapp.shaders`. The namespace is - // this name with `.` replaced by `::`, which is why there is no second - // field for it: two spellings of one identity drift. - std::string module_name; - // Where the generated interface and implementation are written. The caller - // adds this to the include path when the surface is `c_header`. - std::string out_dir; - // A short phrase naming what produced the payloads, for the generated - // files' first line: "mcpp.rules.spirv". - std::string produced_by; - - // ── What this generator is NOT allowed to find out for itself ─────────── - // - // THE TWO FIELDS BELOW ARE WHY THIS MODULE IMPORTS ONLY `std`. - // - // They were `mcpp::target_os()` and `mcpp::compiler()`, read here. That - // made the generator unusable anywhere except inside a build program -- - // which is the one place it must NOT be the only usable form, because a - // payload dependency can only enter the build graph if the generation is - // an ACTION, and an action's command is a binary. A binary cannot import - // the build-program module: measured, an ordinary build of this package - // fails with "mcpp: failed to read compiled module". - // - // So they are parameters. The caller has both answers already, and a - // generator that takes its inputs rather than reading its environment is - // the same code in a build program and in a tool. - - // The target's operating system, as mcpp spells it -- what decides the - // assembly dialect: the section directive and whether a symbol carries a - // leading underscore. Required under `storage::object`; ignored otherwise. - std::string target_os; - - // Whether a GAS-compatible assembler exists for this toolchain. False - // under MSVC, which has none, and where mcpp refuses `.S` outright. It is - // the CALLER's answer because the caller knows the compiler; this - // generator degrades `object` to `header` when it is false and reports - // that through `emitted::store` rather than by printing. - bool has_gas_assembler = true; -}; - -// What the caller hands back to mcpp. -struct emitted { - // The interface unit: a `.cppm` under `module_`, a `.h` under `c_header`. - std::string interface_file; - // The generated `.S` under `storage::object`, empty otherwise. The caller - // adds it to the build the same way it adds the implementation. - std::string assembly_file; - // The storage actually used. Differs from what was asked for when the - // toolchain cannot assemble: MSVC has no GAS, so `object` degrades to - // `header` and this says so rather than leaving the caller to assume. - storage store = storage::header; - // The translation unit defining the accessors. Always a plain `.cpp`. - std::string impl_file; - // Non-empty under `module_`: what the interface unit provides, which the - // caller declares with `mcpp::action::provides` or lets the scan find. - std::string module_name; - // Non-empty under `c_header`: the directory to put on the include path. - std::string include_dir; -}; - -// The linker symbol an accessor carries. It is derived from the module name and -// the payload's full namespace path rather than from the identifier alone, -// because two groups in one link unit -- a project with shaders and with -// embedded data -- would otherwise define the same symbol twice and the second -// definition would be the one nobody expected. -inline std::string accessor_base(const options& opt, const item& it) { - std::string s = "mcpp_embed"; - auto add = [&](std::string_view part) { - s += '_'; - for (char c : part) - s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; - }; - for (auto const& seg : split_module_name(opt.module_name)) add(seg); - for (auto const& seg : it.name_space) add(seg); - add(it.identifier); - return s; -} - -inline const char* element_type(element e) { - return e == element::word32 ? "unsigned int" : "unsigned char"; -} - -// `unsigned int` is 32 bits on every target this package supports, and the -// generated implementation asserts it rather than assuming it: a target where -// it is not would otherwise hand a Vulkan driver a pointer into misread data, -// and the failure would be a device error naming nothing. -inline const char* element_width_assertion(element e) { - return e == element::word32 - ? "static_assert(sizeof(unsigned int) == 4,\n" - " \"mcpp.plugins.surface: element::word32 assumes a 32-bit `unsigned int`\");\n" - : ""; -} - -inline bool write_if_different(const std::string& path, std::string_view text) { - std::error_code ec; - std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); - if (std::ifstream in(path, std::ios::binary); in) { - std::string old((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - if (old == text) return true; - } - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out) return false; - out.write(text.data(), static_cast(text.size())); - return static_cast(out); -} - -// Open and close the namespaces an item sits in, below the group's own. -inline std::string open_namespaces(const std::vector& segs) { - std::string s; - for (auto const& one : segs) s += "namespace " + one + " {\n"; - return s; -} -inline std::string close_namespaces(const std::vector& segs) { - std::string s; - for (auto i = segs.rbegin(); i != segs.rend(); ++i) s += "} // namespace " + *i + "\n"; - return s; -} - -// The declarations shared by both surfaces. What differs between a module -// interface and a header is the preamble and how the group's namespace is -// opened; the body below is byte-identical, which is what makes switching -// surfaces a change no consumer can observe. -// The accessor declarations, at GLOBAL scope. -// -// C language linkage makes a name the same entity whatever namespace declares -// it, so these would resolve from inside the group's namespace as well. They are -// written outside it because the generated implementation defines them at global -// scope, and a reader comparing the two files should not have to know that rule -// to see that they match. -inline std::string extern_c_declarations(std::span items, const options& opt) { - const char* elem = element_type(opt.elem); - std::string s = "extern \"C\" {\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - s += std::format("const {}* {}_data();\n", elem, base); - s += std::format("unsigned long {}_size();\n", base); - } - s += "}\n"; - return s; -} - -inline std::string declarations(std::span items, const options& opt) { - const char* elem = element_type(opt.elem); - std::string s; - - s += std::format( - "// The payload, as the device API wants it. Free of standard-library\n" - "// types on purpose: see mcpp.plugins.surface.\n" - "struct payload {{\n" - " const {}* code; // e.g. VkShaderModuleCreateInfo::pCode\n" - " unsigned long size_bytes; // e.g. VkShaderModuleCreateInfo::codeSize\n" - "}};\n\n", elem); - - // Grouped by namespace path so a directory's payloads are emitted together - // and each namespace is opened once. - std::vector openNow; - auto reopen = [&](const std::vector& want) { - if (openNow == want) return; - s += close_namespaces(openNow); - s += open_namespaces(want); - openNow = want; - }; - for (auto const& it : items) { - reopen(it.name_space); - const auto base = accessor_base(opt, it); - // THROUGH `identifier`, HERE RATHER THAN IN EACH PRODUCER. This is the - // one line that turns `item::identifier` into something a compiler - // parses, and a rule that builds the field from a file stem cannot know - // it has produced `my-shader_comp` or `default` until it gets here. - s += std::format("inline payload {}() {{ return {{ {}_data(), {}_size() }}; }}\n", - identifier(it.identifier, "payload"), base, base); - } - reopen({}); - return s; -} - -// ONE OBJECT FORMAT PER PLATFORM, AND THE DIFFERENCES ARE NOT COSMETIC. -// -// `.incbin` is the portable part: gas and clang's integrated assembler both -// accept it everywhere, and it resolves its argument at ASSEMBLY time, which is -// why this file can be written before the payload exists. What is not portable -// is the section directive and whether a C symbol carries a leading underscore. -// -// ELF `.section .rodata`, symbol as written -// Mach-O `.section __TEXT,__const`, symbol PREFIXED with `_` -// COFF `.section .rdata,"dr"`, symbol as written on x86_64 -// -// Mach-O's underscore is the one that fails quietly in the other direction: an -// assembly label without it defines a symbol the C++ side never resolves, and -// the link error names the accessor rather than the missing prefix. -struct asm_dialect { - std::string_view section; - std::string_view symbol_prefix; -}; - -inline asm_dialect dialect_for(std::string_view targetOs) { - if (targetOs == "macos" || targetOs == "macosx" || targetOs == "darwin") - return { ".section __TEXT,__const", "_" }; - if (targetOs == "windows") return { ".section .rdata,\"dr\"", "" }; - return { ".section .rodata", "" }; -} - -// `.balign 4` rather than nothing: `VkShaderModuleCreateInfo::pCode` requires -// four-byte alignment, and a section directive alone does not promise it. The -// header route gets alignment from the array's element type; this route has to -// ask for it. -inline std::string assembly_for(std::span items, const options& opt, - std::string_view targetOs) { - const auto d = dialect_for(targetOs); - std::string s = - "// Generated by mcpp.plugins.surface. Do not edit.\n" - "//\n" - "// The payloads, as sections rather than as C arrays. `.incbin` resolves\n" - "// its argument when this file is assembled, which is after the actions\n" - "// that write those files have run.\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - s += std::format("\n {}\n" - " .globl {}{}_begin\n" - " .balign 4\n" - "{}{}_begin:\n" - " .incbin \"{}\"\n" - " .globl {}{}_end\n" - "{}{}_end:\n", - d.section, - d.symbol_prefix, base, - d.symbol_prefix, base, - it.payload_path, - d.symbol_prefix, base, - d.symbol_prefix, base); - } - return s; -} - -// ---- the tool --------------------------------------------------------------- - -// EVERY FILE THIS SURFACE WILL PRODUCE, WITHOUT PRODUCING ANY OF THEM. -// -// A rule declares these as an action's outputs, and mcpp requires an output to -// be NAMED before the graph is built even though its content arrives later. So -// the names cannot come from having written the files -- which is the coupling -// that forced generation to happen at plan time, and with it the whole -// staleness this round removes. -// -// Pure: no items, no filesystem, no environment. The one decision it makes is -// the MSVC degradation, which is a property of the toolchain rather than of any -// payload, and `emitted::store` is where the caller reads the verdict. -inline emitted outputs(const options& opt) { - emitted out; - out.store = opt.store; - // MSVC HAS NO GAS, AND mcpp REFUSES `.S` UNDER IT. `src/build/prepare.cppm` - // says so outright: "GAS assembly sources (.S/.s) are not supported by the - // MSVC toolchain". Object storage degrades to header storage there rather - // than producing a file the build will refuse, and the SURFACE does not - // change -- the declarations are identical under both. - if (out.store == storage::object && !opt.has_gas_assembler) - out.store = storage::header; - - const auto dir = std::filesystem::path(opt.out_dir); - out.interface_file = (dir / (opt.module_name - + (opt.surface == kind::module_ ? ".cppm" : ".h"))).string(); - out.impl_file = (dir / (opt.module_name + ".impl.cpp")).string(); - // Named only under the storage that produces one, so a caller can test the - // string rather than having to test the storage a second time. - if (out.store == storage::object) - out.assembly_file = (dir / (opt.module_name + ".payload.S")).string(); - if (opt.surface == kind::module_) out.module_name = opt.module_name; - else out.include_dir = dir.string(); - return out; -} - - -// The assembly's meaning includes the bytes named by .incbin. Put a content -// checksum in its source so restat cannot prune the assembler after a payload -// changes while the .incbin path stays the same. This runs in the body action, -// after its declared payload inputs exist; planning still reads no payload. -inline std::optional payload_checksum(const std::string& file) { - std::ifstream input(file, std::ios::binary); - if (!input) return std::nullopt; - std::uint64_t sum = 14695981039346656037ULL; - std::array bytes; - while (input) { - input.read(bytes.data(), static_cast(bytes.size())); - for (std::streamsize i = 0; i < input.gcount(); ++i) { - sum ^= static_cast(bytes[static_cast(i)]); - sum *= 1099511628211ULL; - } - } - return input.bad() ? std::nullopt : std::optional(sum); -} - -// Writes ONE half of the surface. The names come from `outputs`, which the -// caller has already asked; this produces the content. -// -// The interface reads no payload. The object body runs after its declared -// payload inputs, records their content checksum and names them in .incbin; -// the assembler reads the bytes after that body action has completed. -inline bool write(std::span items, const options& opt, half which) { - if (items.empty()) return true; - if (opt.module_name.empty()) { - std::cerr << "mcpp.plugins.surface: options::module_name is required; it names both " - "the module a consumer imports and the namespace the declarations sit in\n"; - return false; - } - if (opt.out_dir.empty()) { - std::cerr << "mcpp.plugins.surface: options::out_dir is required\n"; - return false; - } - - const auto segs = split_module_name(opt.module_name); - // REFUSED HERE, NOT IN THE GENERATED FILE. The module name is the one part - // of this surface a project writes itself, and each of its segments becomes - // a namespace. A segment that is not an identifier -- empty, starting with - // a digit, carrying a `-`, or reserved -- produces a generated file that - // does not parse, and the error then names a line nobody wrote. - for (std::size_t i = 0; i < segs.size(); ++i) { - if (segs[i] == identifier(segs[i], "")) continue; - std::cerr << std::format( - "mcpp.plugins.surface: `{}` is not a usable module name: the segment `{}` " - "is not a C++ identifier.\n Each segment becomes a namespace, so it has " - "to be one; `{}` would work.\n", - opt.module_name, segs[i], identifier(segs[i], "part")); - return false; - } - const auto by = opt.produced_by.empty() ? std::string("mcpp.plugins.surface") - : opt.produced_by; - - // ONE derivation of the names, shared with the caller. Recomputing them - // here would be the second copy of a decision that this package has paid - // for before. - const emitted out = outputs(opt); - const auto dir = std::filesystem::path(opt.out_dir); - const auto body = declarations(items, opt); - - // ---- interface ---- - if (which == half::interface_) { - std::string iface; - iface += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); - if (opt.surface == kind::module_) - iface += std::format("export module {};\n\n", opt.module_name); - else - iface += "#pragma once\n\n"; - iface += extern_c_declarations(items, opt); - iface += "\n"; - // `export` on the opening namespace exports everything the block - // contains, including the nested namespaces a payload's directory - // produced. - if (opt.surface == kind::module_) iface += "export "; - iface += open_namespaces(segs); - iface += "\n" + body + "\n"; - iface += close_namespaces(segs); - if (!write_if_different(out.interface_file, iface)) { - std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", - out.interface_file); - return false; - } - return true; - } - - // ---- implementation ---- (half::body from here down) - // - // The one translation unit that defines the accessors. A plain `.cpp` under - // every surface and every storage, because the accessors have C language - // linkage and so need no attachment to the module. What differs between the - // three storages is only where it reads the bytes from. - const char* elem = element_type(opt.elem); - std::string impl; - impl += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); - - if (out.store == storage::header) { - impl += "//\n" - "// The only translation unit that includes the generated data headers.\n" - "// Each declares a `static` array, so this is also the only copy of the\n" - "// bytes in the program.\n"; - for (auto const& it : items) impl += std::format("#include \"{}\"\n", it.data_header); - impl += "\n"; - impl += element_width_assertion(opt.elem); - impl += "\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - const auto size = it.data_size_expr.empty() - ? std::format("sizeof {}", it.data_symbol) - : it.data_size_expr; - impl += std::format( - "extern \"C\" const {0}* {1}_data() {{ return {2}; }}\n" - "extern \"C\" unsigned long {1}_size() {{ return {3}; }}\n", - elem, base, it.data_symbol, size); - } - } else if (out.store == storage::object) { - impl += "//\n" - "// The bytes are in a section written by the generated `.S`. This file\n" - "// only names its two boundary symbols, so nothing here parses a payload\n" - "// and the C++ compiler never sees one.\n" - "//\n" - "// The symbols are declared as arrays of the element type rather than as\n" - "// `char`: the assembly aligned the section to four bytes, and a\n" - "// declaration that said `char` would let a consumer reach it through an\n" - "// under-aligned pointer with nothing to notice.\n"; - impl += "\n"; - impl += element_width_assertion(opt.elem); - impl += "\nextern \"C\" {\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - impl += std::format("extern const {0} {1}_begin[];\n" - "extern const {0} {1}_end[];\n", elem, base); - } - impl += "}\n\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - impl += std::format( - "extern \"C\" const {0}* {1}_data() {{ return {1}_begin; }}\n" - "extern \"C\" unsigned long {1}_size() {{\n" - " return static_cast(({1}_end - {1}_begin) * sizeof({0}));\n" - "}}\n", elem, base); - } - } else { - impl += "//\n" - "// The payloads are files beside the artifact, read on first use. The\n" - "// path is resolved against the WORKING DIRECTORY, which is the property\n" - "// that makes this storage the one a project opts into rather than the\n" - "// default: a program started from elsewhere finds nothing.\n" - "//\n" - "// Read once and kept: an accessor that reloaded would hand two callers\n" - "// two different pointers to the same payload, and a device API given\n" - "// the second after the first was freed is a defect with no message.\n"; - impl += "#include \n#include \n#include \n\n"; - impl += element_width_assertion(opt.elem); - impl += std::format(R"IMPL( -namespace {{ - -struct blob {{ {0}* data = nullptr; unsigned long size = 0; bool tried = false; }}; - -blob& load(const char* path, blob& b) {{ - if (b.tried) return b; - b.tried = true; - std::FILE* f = std::fopen(path, "rb"); - if (!f) {{ - std::fprintf(stderr, "mcpp.plugins.surface: cannot open %s\n", path); - return b; - }} - std::fseek(f, 0, SEEK_END); - const long n = std::ftell(f); - std::fseek(f, 0, SEEK_SET); - if (n > 0) {{ - b.data = static_cast<{0}*>(std::malloc(static_cast(n))); - if (b.data && std::fread(b.data, 1, static_cast(n), f) - == static_cast(n)) - b.size = static_cast(n); - else {{ std::free(b.data); b.data = nullptr; }} - }} - std::fclose(f); - return b; -}} - -}} // namespace -)IMPL", elem); - impl += "\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - impl += std::format( - "static blob {0}_blob;\n" - "extern \"C\" const {1}* {0}_data() {{\n" - " return load(\"{2}\", {0}_blob).data;\n" - "}}\n" - "extern \"C\" unsigned long {0}_size() {{\n" - " return load(\"{2}\", {0}_blob).size;\n" - "}}\n", base, elem, it.sidecar_name); - } - } - - if (!write_if_different(out.impl_file, impl)) { - std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", out.impl_file); - return false; - } - - if (out.store == storage::object) { - // A CALLER THAT ASKS FOR THIS STORAGE MUST HAVE SAID WHERE THE BYTES - // ARE, AND THE REFUSAL IS WHAT KEEPS THAT TRUE. - // - // `item::payload_path` is documented as required under `object`, and - // today only `mcpp.rules.spirv` reaches this storage and only it sets - // the field. That is a COINCIDENCE, not a guarantee: the first caller - // to give `rules-slang` or `tools-embed` a storage option would get an - // `.incbin ""` in a generated `.S`, and the declaration below would - // then name an empty dependency -- so the build would be wrong in - // exactly the silent way this whole change exists to remove. - // - // A constraint written only in a comment has nothing enforcing it, - // which is a shape this project has recorded before. This is the - // enforcement. - for (auto const& it : items) { - if (!it.payload_path.empty()) continue; - std::cerr << std::format( - "mcpp.plugins.surface: `{}` was given storage::object with no " - "payload_path.\n" - " Under this storage the generated assembly names the payload " - "in `.incbin`, so\n" - " the caller has to say where it is. Set `item::payload_path`, " - "or use storage::header.\n", - it.identifier); - return false; - } - auto assembly = assembly_for(items, opt, opt.target_os); - for (const auto& it : items) { - const auto checksum = payload_checksum(it.payload_path); - if (!checksum) { - std::cerr << std::format("mcpp.plugins.surface: cannot read payload {}\n", it.payload_path); - return false; - } - assembly += std::format("// payload content: {:016x}\n", *checksum); - } - if (!write_if_different(out.assembly_file, assembly)) { - std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", - out.assembly_file); - return false; - } - } - // `storage::sidecar` needs no counterpart, and that was checked rather than - // assumed. Its payload is never read by a compile: the accessor opens the - // file at RUN time, so a rebuilt payload is picked up by the next run with - // nothing in the build graph to keep current. - return true; -} - -// The surface a project gets when it asks for nothing. -// -// `MCPP_LANGUAGE_MODULES` is set by mcpp from `[language] modules`. An engine -// that does not set it leaves the variable absent, and the fallback is the -// header surface -- which is what every consumer of this package had before -// this module existed. An older engine therefore keeps its behaviour and a -// newer one gets the module surface without any project asking, which is the -// whole of the upgrade path. -inline kind default_surface() { - const char* v = std::getenv("MCPP_LANGUAGE_MODULES"); - return (v && (*v == '1' || *v == 't' || *v == 'T')) ? kind::module_ : kind::c_header; -} - -// `example:my-app` -> `my_app`. The module a rule names by default is this -// followed by the group's own segment, so two packages in one build cannot -// claim the same module. -// The default module root for a package that named none: its PACKAGE NAME, -// sanitised into an identifier. -// -// THE PACKAGE'S NAME. NOT ITS DIRECTORY'S. These are different questions and -// they give different answers whenever a project lays a package out under a -// generic directory. The first version asked the only question mcpp could -// answer -- the leaf of MCPP_MANIFEST_DIR -- so a package named `vulkan-saxpy` -// laid out as `vulkan/app/` generated `app.shaders`, and every -// `/app/` in a workspace claimed that same module. -// -// The name ARRIVES rather than being read, for the reason `options::target_os` -// records: this module must compile into a plain binary as well as into a -// build program, so it may not reach for `mcpp::package_name()` itself. The -// caller passes what mcpp told it. -// -// `fallback` covers the impossible case -- a manifest without a `[package] -// name` does not load, so an empty first argument would mean the contract -// changed underneath. A rule that wants neither passes `options::module_name`, -// and this is not consulted. -inline std::string module_root_for(std::string_view package_name, - std::string_view fallback = {}) { - std::string leaf{package_name}; - if (leaf.empty()) leaf = std::string(fallback); - return identifier(leaf, "app"); -} - -} // namespace mcpp::plugins::surface - -// mcpp::plugins::tree -- the directories a walk of a source tree leaves out. -// -// SHARED BECAUSE TWO MEMBERS WALK A SOURCE TREE BY DEFAULT. `rules-qt` finds -// the headers moc reads and the sources lupdate reads under the package, and -// `deps` takes every file of a subproject as an input of its installation, and -// `deps-cmake` as part of the installation's key. Neither may take what ANOTHER -// build system generated there: a Visual Studio project built in the same -// checkout leaves its moc and uic output under `x64/Release/`, and lupdate -// given those files rewrites the translations, and a CMake build directory an -// IDE made inside a subproject changes the key on every build. -// -// Such a directory is known by what its build system leaves in it, not by its -// name: `x64/` is as often a directory of architecture-specific sources. -export namespace mcpp::plugins::tree { - -// Whether `dir` is an output directory of another build system: -// -// CMakeCache.txt a CMake build tree (an IDE's `cmake-build-*`, `out/build/*`) -// .qmake.stash a qmake build tree -// CACHEDIR.TAG a directory its tool tags as a cache (https://bford.info/cachedir/) -// .tlog/ an MSBuild intermediate directory (`x64/Release/`), where a -// Visual Studio project writes the sources it generates -// -// A walk asks this of the directories under its root, never of the root: a -// subproject configured in its own source directory holds CMakeCache.txt too. -inline bool build_output(const std::filesystem::path& dir) { - namespace fs = std::filesystem; - std::error_code ec; - if (fs::is_regular_file(dir / "CMakeCache.txt", ec) || fs::is_regular_file(dir / ".qmake.stash", ec)) - return true; - if (fs::is_regular_file(dir / "CACHEDIR.TAG", ec)) { - std::ifstream in(dir / "CACHEDIR.TAG", std::ios::binary); - std::string head(43, '\0'); - in.read(head.data(), 43); - if (head == "Signature: 8a477f597d28d172789f06886806bc55") return true; - } - for (auto it = fs::directory_iterator(dir, fs::directory_options::skip_permission_denied, ec); - !ec && it != fs::directory_iterator(); it.increment(ec)) - if (it->path().extension() == ".tlog" && it->is_directory(ec)) return true; - return false; -} - -} // namespace mcpp::plugins::tree diff --git a/src/plugins/graph.cppm b/src/plugins/graph.cppm new file mode 100644 index 0000000..554d530 --- /dev/null +++ b/src/plugins/graph.cppm @@ -0,0 +1,98 @@ +export module mcpp.plugins:graph; + +import std; +import :json; + + +// mcpp::plugins::graph -- the resolved dependency graph the engine states. +// +// mcpp 2026.9.16.1 gives the ROOT project's build program `MCPP_GRAPH_FILE` +// (`mcpp::graph_file()`), a document naming every package of the resolved graph, +// dependencies before their requesters, each with its manifest directory and its +// `[package.metadata]` verbatim (mcpp docs/30, "Reading the resolved graph"). A +// member that merges what libraries contribute reads a table of its own out of +// that metadata: `[package.metadata.dist-apk]`, `[package.metadata.dist-apple]`. +// +// READ THROUGH THE ENVIRONMENT, NOT `mcpp::graph_file()`. This unit does not +// import `mcpp` (see the top of this file), and a member that called the +// accessor would not compile against an engine older than the one that added it. +// An unset or empty variable is an older engine, or a dependency's program, and +// reads as a graph with no packages, which leaves every member's behaviour as it +// was. +export namespace mcpp::plugins::graph { + +struct package { + std::string canonical; // `namespace.name@version` + std::string name; + std::string namespace_; + std::string version; + bool root = false; + std::string manifest_dir; // absolute + json::value metadata; // the package's [package.metadata], an object +}; + +struct document { + bool present = false; // MCPP_GRAPH_FILE named a file + std::string path; + std::vector packages; // dependencies before requesters +}; + +// The graph this build program was given, or the reason it cannot be read. A +// variable naming a file that is missing or not a `mcpp.graph` document is an +// error rather than an empty graph: the engine promised a document, and reading +// nothing would silently drop every contribution. +inline std::expected read() { + document d; + const char* env = std::getenv("MCPP_GRAPH_FILE"); + if (!env || !*env) return d; + d.present = true; + d.path = env; + std::ifstream in(d.path, std::ios::binary); + if (!in) + return std::unexpected(std::format("the graph document {} cannot be read", d.path)); + const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + json::value doc; + if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) + return std::unexpected(std::format("the graph document {} is not JSON", d.path)); + if (json::string_of(doc.get("kind")) != "mcpp.graph") + return std::unexpected(std::format("the graph document {} is not a mcpp.graph document", d.path)); + const json::value* list = doc.get("packages"); + if (!list || list->type != json::value::kind::array) + return std::unexpected(std::format("the graph document {} has no packages array", d.path)); + for (auto const& entry : list->items) { + if (entry.type != json::value::kind::object) continue; + package p; + if (const json::value* id = entry.get("package")) { + p.canonical = json::string_of(id->get("canonical")); + p.name = json::string_of(id->get("name")); + p.namespace_ = json::string_of(id->get("namespace")); + p.version = json::string_of(id->get("version")); + } + if (const json::value* r = entry.get("root")) + p.root = r->type == json::value::kind::boolean && r->text == "true"; + p.manifest_dir = json::string_of(entry.get("manifest_dir")); + if (const json::value* m = entry.get("metadata"); m && m->type == json::value::kind::object) + p.metadata = *m; + d.packages.push_back(std::move(p)); + } + return d; +} + +// The package's `[package.metadata.]` table, or null. +inline const json::value* table_of(const package& p, std::string_view tool) { + const json::value* t = p.metadata.get(tool); + return t && t->type == json::value::kind::object ? t : nullptr; +} + +// A path a package states, made absolute against its manifest directory. +inline std::string resolve(const package& p, const std::string& path) { + if (path.empty() || std::filesystem::path(path).is_absolute()) return path; + return (std::filesystem::path(p.manifest_dir) / path).lexically_normal().string(); +} + +// How a diagnostic names a package: its canonical identity, or its name. +inline std::string label_of(const package& p) { + return !p.canonical.empty() ? p.canonical : p.name; +} + +} // namespace mcpp::plugins::graph diff --git a/src/plugins/json.cppm b/src/plugins/json.cppm new file mode 100644 index 0000000..2fba2f4 --- /dev/null +++ b/src/plugins/json.cppm @@ -0,0 +1,185 @@ +export module mcpp.plugins:json; + +import std; + + +// mcpp::plugins::json -- the JSON two dist members read. +// +// SHARED BECAUSE TWO DOCUMENTS ARE READ WITH IT. `dist-apk` reads coursier's +// resolution report, and `mcpp::plugins::graph` below reads the engine's graph +// document for `dist-apk` and `dist-apple`. A second parser for the second +// document is how two readers come to disagree about one file, so there is one. +// It reads objects, arrays, strings (with `\u` escapes, surrogate pairs +// included, and a refusal for a surrogate that is not part of one), numbers, +// `true`, `false` and `null`; a number keeps its spelling in `text`. +export namespace mcpp::plugins::json { + +// A MEMBER IS ITS OWN STRUCT, NOT `std::pair`. Under clang +// with libstdc++'s `std` module, `pair` inside `value` is +// instantiated while `value` is still incomplete -- its destructor needs the +// pair and the pair needs `value` -- and the unit fails with "incomplete type +// used in type trait expression". GCC accepts the pair and so does clang with +// libc++, so neither build lane saw it; clangd reading a GCC project in the +// editor is exactly that combination. A plain aggregate, with `get()` defined +// once both types are complete, compiles under all three. +struct member; + +struct value { + enum class kind { null, boolean, number, string, array, object }; + kind type = kind::null; + std::string text; // string, number or boolean spelling + std::vector items; + std::vector members; + + const value* get(std::string_view key) const; +}; + +struct member { + std::string first; + value second; +}; + +inline const value* value::get(std::string_view key) const { + for (auto const& m : members) if (m.first == key) return &m.second; + return nullptr; +} + +struct reader { + std::string_view s; + std::size_t i = 0; + + void skip_space() { + while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i; + } + // The four hexadecimal digits of one `\u` escape, `i` already past the `u`. + bool hex4(unsigned& cp) { + if (i + 4 > s.size()) return false; + cp = 0; + for (int k = 0; k < 4; ++k) { + const char h = s[i++]; + cp <<= 4; + if (h >= '0' && h <= '9') cp |= static_cast(h - '0'); + else if (h >= 'a' && h <= 'f') cp |= static_cast(h - 'a' + 10); + else if (h >= 'A' && h <= 'F') cp |= static_cast(h - 'A' + 10); + else return false; + } + return true; + } + bool string(std::string& out) { + if (i >= s.size() || s[i] != '"') return false; + ++i; + while (i < s.size() && s[i] != '"') { + if (s[i] != '\\') { out += s[i++]; continue; } + if (++i >= s.size()) return false; + const char e = s[i++]; + switch (e) { + case 'n': out += '\n'; break; + case 't': out += '\t'; break; + case 'r': out += '\r'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'u': { + // A code point above U+FFFF reaches JSON as a surrogate + // PAIR, which is two `\u` escapes. Encoding each half on its + // own produces two three-byte sequences holding unpaired + // surrogates -- not UTF-8, and accepted by nothing that + // reads the manifest this value is written into. The pair is + // combined here, and a surrogate that is not part of one is + // refused, so a malformed document is a refusal rather than + // a silently corrupted string. + unsigned cp = 0; + if (!hex4(cp)) return false; + if (cp >= 0xd800 && cp <= 0xdbff) { + if (i + 6 > s.size() || s[i] != '\\' || s[i + 1] != 'u') return false; + i += 2; + unsigned lo = 0; + if (!hex4(lo)) return false; + if (lo < 0xdc00 || lo > 0xdfff) return false; + cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); + } else if (cp >= 0xdc00 && cp <= 0xdfff) { + return false; // a low surrogate with no high half + } + if (cp < 0x80) out += static_cast(cp); + else if (cp < 0x800) { out += static_cast(0xc0 | (cp >> 6)); out += static_cast(0x80 | (cp & 0x3f)); } + else if (cp < 0x10000) { out += static_cast(0xe0 | (cp >> 12)); out += static_cast(0x80 | ((cp >> 6) & 0x3f)); out += static_cast(0x80 | (cp & 0x3f)); } + else { + out += static_cast(0xf0 | (cp >> 18)); + out += static_cast(0x80 | ((cp >> 12) & 0x3f)); + out += static_cast(0x80 | ((cp >> 6) & 0x3f)); + out += static_cast(0x80 | (cp & 0x3f)); + } + break; + } + default: out += e; + } + } + if (i >= s.size()) return false; + ++i; + return true; + } + bool parse_value(value& out) { + skip_space(); + if (i >= s.size()) return false; + const char c = s[i]; + if (c == '"') { out.type = value::kind::string; return string(out.text); } + if (c == '{') { + out.type = value::kind::object; + ++i; + skip_space(); + if (i < s.size() && s[i] == '}') { ++i; return true; } + for (;;) { + skip_space(); + std::string key; + if (!string(key)) return false; + skip_space(); + if (i >= s.size() || s[i] != ':') return false; + ++i; + value v; + if (!parse_value(v)) return false; + out.members.emplace_back(std::move(key), std::move(v)); + skip_space(); + if (i < s.size() && s[i] == ',') { ++i; continue; } + if (i < s.size() && s[i] == '}') { ++i; return true; } + return false; + } + } + if (c == '[') { + out.type = value::kind::array; + ++i; + skip_space(); + if (i < s.size() && s[i] == ']') { ++i; return true; } + for (;;) { + value v; + if (!parse_value(v)) return false; + out.items.push_back(std::move(v)); + skip_space(); + if (i < s.size() && s[i] == ',') { ++i; continue; } + if (i < s.size() && s[i] == ']') { ++i; return true; } + return false; + } + } + const std::size_t b = i; + while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' && + s[i] != ' ' && s[i] != '\n' && s[i] != '\r' && s[i] != '\t') ++i; + out.text = std::string(s.substr(b, i - b)); + if (out.text == "null") out.type = value::kind::null; + else if (out.text == "true" || out.text == "false") out.type = value::kind::boolean; + else out.type = value::kind::number; + return !out.text.empty(); + } +}; + +// The whole text is one value, with nothing but white space after it. +inline bool parse_json(std::string_view text, value& out) { + reader r{text}; + if (!r.parse_value(out)) return false; + r.skip_space(); + return r.i == r.s.size(); +} + +// A string member of an object, or empty when absent or not a string. +inline std::string string_of(const value* v) { + return v && v->type == value::kind::string ? v->text : std::string(); +} + +} // namespace mcpp::plugins::json diff --git a/src/plugins/names.cppm b/src/plugins/names.cppm new file mode 100644 index 0000000..61fe040 --- /dev/null +++ b/src/plugins/names.cppm @@ -0,0 +1,207 @@ +export module mcpp.plugins:names; + +import std; + + +// mcpp::plugins::names -- the derivations that turn a path into a C++ name. +// +// THESE ARE SHARED BECAUSE THEY WERE COPIED. `common_base_dir` and +// `namespace_of` were written in `rules/spirv.cppm` and written again in +// `rules/slang.cppm`, and `mcpp.tools.island` is the third caller needing the +// same answers. Two copies that agree today are still two copies: a directory +// named `default` or `2d` has to get ONE answer, and one function is how that +// is guaranteed rather than two files that happen to say the same thing. +export namespace mcpp::plugins::names { + +// `a` made relative to the directory `b`, as strings: separators unified, and +// the prefix stripped when `a` lies under `b`; `a` unchanged otherwise. +// +// NOTHING IN THIS PACKAGE INSTANTIATES `std::filesystem::path`'s ITERATOR -- +// see `components()` below for the compiler that refuses it. The members' +// relative-path arithmetic is this string function, defined once here. +inline std::string relative_to(std::string a, std::string b) { + for (auto& c : a) if (c == '\\') c = '/'; + for (auto& c : b) if (c == '\\') c = '/'; + while (!b.empty() && b.back() == '/') b.pop_back(); + if (!b.empty() && a.starts_with(b + "/")) return a.substr(b.size() + 1); + return a; +} + +// A GENERATED NAME THE C++ COMPILER WILL ACCEPT. +// +// Three transformations, and the third is the one every hand-rolled copy of +// this function was missing. Non-identifier characters become `_`; a leading +// digit gets a `_` in front; and a result that is a KEYWORD gets a trailing `_`. +// +// The keyword case is not hypothetical. The first two rules accept `default`, +// `template`, `operator`, `private` and `union` unchanged -- they are valid +// identifiers to a character filter and reserved to the compiler -- and +// `shaders/default/` is an ordinary name for a shader directory. What it +// produced was `namespace default {` in a generated file, and an error naming a +// line its author never wrote. +// +// TRAILING `_`, not a prefix: `_default` is reserved at namespace scope +// (a leading underscore in the global namespace), and prefixing would trade one +// reserved name for another. +// +// The list is the keywords of the standard this collection targets. A word that +// is contextual rather than reserved (`final`, `override`, `import`, `module`) +// is a legal identifier and is left alone. +inline bool is_cxx_keyword(std::string_view w) { + static constexpr std::string_view kWords[] = { + "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", + "bool", "break", "case", "catch", "char", "char8_t", "char16_t", + "char32_t", "class", "compl", "concept", "const", "consteval", + "constexpr", "constinit", "const_cast", "continue", "co_await", + "co_return", "co_yield", "decltype", "default", "delete", "do", "double", + "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", + "float", "for", "friend", "goto", "if", "inline", "int", "long", + "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", + "operator", "or", "or_eq", "private", "protected", "public", "register", + "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", + "static", "static_assert", "static_cast", "struct", "switch", + "template", "this", "thread_local", "throw", "true", "try", "typedef", + "typeid", "typename", "union", "unsigned", "using", "virtual", "void", + "volatile", "wchar_t", "while", "xor", "xor_eq", + }; + for (auto k : kWords) if (k == w) return true; + return false; +} + +// `fallback` is used when the input sanitises to nothing, which a file named +// only in punctuation does. +// +// INDEXED RATHER THAN A RANGE-FOR over the string, for the reason recorded in +// `mcpp.tools.island`: iterating a `std::string` inside an exported inline +// function makes GCC 16 instantiate its iterator in this BMI, and a consumer's +// build program then fails to compile on `always_inline` in a header naming +// neither this file nor this loop. +inline std::string identifier(std::string_view raw, std::string_view fallback) { + std::string s; + for (std::size_t i = 0; i < raw.size(); ++i) { + const char c = raw[i]; + s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; + } + if (s.empty()) s = std::string(fallback); + if (!s.empty() && std::isdigit(static_cast(s.front()))) + s.insert(s.begin(), '_'); + if (is_cxx_keyword(s)) s += '_'; + return s; +} + + +// ---- internals ------------------------------------------------------------- + +inline std::vector split_module_name(std::string_view name) { + std::vector out; + for (std::size_t i = 0; i <= name.size();) { + auto dot = name.find('.', i); + auto one = dot == std::string_view::npos ? name.substr(i) : name.substr(i, dot - i); + if (!one.empty()) out.emplace_back(one); + if (dot == std::string_view::npos) break; + i = dot + 1; + } + return out; +} + +// THE BASE DIRECTORY IS DERIVED, NOT ASKED FOR. +// +// A payload's namespace comes from where it sits relative to the tree the +// project globbed, so something has to say where that tree starts. Asking the +// project would put a second spelling of the glob in the manifest, and the two +// would disagree the first time a glob moved. The shallowest directory every +// path shares is the same answer without the second spelling: for +// `shaders/*.comp` it is `shaders` and every namespace is empty; for +// `shaders/a/x.comp` and `shaders/b/y.comp` it is still `shaders`, and the two +// land in `::a` and `::b`. +// +// A single path has no common prefix with anything, so its own directory is the +// base and its namespace is empty -- which is the same answer the general case +// gives once a second file appears beside it. +// A path's components as strings: both separators split, empty and `.` +// components dropped. This is the one place the lib root reads a path apart, +// and it does so WITHOUT `std::filesystem::path`'s iterator on purpose: +// +// A MODULE THAT INSTANTIATES `_Path_iterator` POISONS ITS IMPORTERS UNDER MSVC +// 14.52. Measured on xrgui's CI (14.52.36629 and .36725): this unit compiled +// while it iterated paths, and every member importing it that then touched +// `std::filesystem` at all failed inside the STL -- +// +// include\filesystem(1572): error C2801: '..._Path_iterator<...>::operator ==' +// must be a non-static member +// +// -- the iterator's hidden-friend comparison, refused when the importer meets +// it both through `import std` and through this module's BMI. Removing the +// calls from the members changed nothing; the instantiation had to leave the +// lib root. Component comparison is what `lexically_relative` bought in 0.5.2 +// (a Windows separator bug), and splitting on both separators keeps that. +inline std::vector components(std::string_view path) { + std::vector out; + std::string cur; + auto flush = [&] { if (!cur.empty() && cur != ".") out.push_back(cur); cur.clear(); }; + for (char c : path) { if (c == '/' || c == '\\') flush(); else cur += c; } + flush(); + return out; +} + +// The directory part of a path, as written: everything before the last +// separator, or empty when there is none. +inline std::string_view parent_of(std::string_view path) { + const auto slash = path.find_last_of("/\\"); + return slash == std::string_view::npos ? std::string_view{} : path.substr(0, slash); +} + +inline std::string common_base_dir(std::span paths) { + std::vector prefix; + bool first = true; + for (auto const& src : paths) { + auto segs = components(parent_of(src)); + if (first) { prefix = std::move(segs); first = false; continue; } + std::size_t keep = 0; + while (keep < prefix.size() && keep < segs.size() && prefix[keep] == segs[keep]) ++keep; + prefix.resize(keep); + } + std::string out; + for (auto const& s : prefix) { if (!out.empty()) out += '/'; out += s; } + return out; +} + +// The namespace segments a file sits in, below the group's own: the path from +// the base directory to the file, sanitised one segment at a time. +// +// RELATIVE BY PATH ARITHMETIC, NOT BY STRING SURGERY, AND THAT IS A WINDOWS +// FIX. This trimmed `base` off the front of the directory as a STRING and +// iterated what was left. On Windows the two spellings differ even when the +// two paths are the same: a caller states a root with forward slashes, and +// `directory_iterator` appends with the preferred separator, so the leftover +// was `\image` rather than `image`. Iterating that yields the ROOT DIRECTORY +// as its first component, which sanitised to `_` -- and the payload landed in +// `myapp::shaders::_::image`, a namespace no consumer writes. Measured: the +// island fixture failed to compile on windows-2022 with `no member named +// 'image' in namespace 'island_interface::kernels'`, while the same fixture +// passed on Linux and macOS. +// +// COMPONENTS are compared, so the separator a caller happened to write is not +// part of the question -- `components()` splits on both. A base that is not a +// prefix is a caller error rather than a namespace; it answers with no +// segments rather than with the whole absolute path, which is what the first +// string form produced. (Through `components()` rather than +// `lexically_relative` for the reason stated on it.) +inline std::vector namespace_of(std::string_view src, std::string_view base) { + std::vector out; + auto dir = components(parent_of(src)); + if (!base.empty()) { + const auto b = components(base); + if (b.size() > dir.size()) return out; + for (std::size_t i = 0; i < b.size(); ++i) if (b[i] != dir[i]) return out; + dir.erase(dir.begin(), dir.begin() + static_cast(b.size())); + } + for (auto const& s : dir) { + if (s == "..") continue; + // `shaders/default/` is an ordinary directory name and + // `namespace default {` is not a namespace. + out.push_back(identifier(s, "dir")); + } + return out; +} +} // namespace mcpp::plugins::names diff --git a/src/plugins/package.cppm b/src/plugins/package.cppm new file mode 100644 index 0000000..94feb18 --- /dev/null +++ b/src/plugins/package.cppm @@ -0,0 +1,117 @@ +export module mcpp.plugins:package; + +import std; +import :json; + + +// mcpp::plugins::package -- the metadata of a staged package. +// +// `mcpp pack` (2026.10.27.1+, SPEC-014 §4.5) writes `mcpp-package.json` at the +// root of every staged tree: the package, its three axes, its legs, the systems +// whose loaders it carries, how it is started, and every file with its role, +// its leg and its digest. It is the input of a package format's provider, of +// `mcpp pack --merge` and of `mcpp emit xpkg`. A provider reads it here rather +// than walking the tree and deciding for itself which file is the program: the +// engine has already decided, once, for every format. +// +// SCHEMA 1 AND ONLY SCHEMA 1. A document of another schema is refused rather +// than read as far as it goes: a field whose meaning changed would be read +// with the old one. +export namespace mcpp::plugins::package { + +struct file { + std::string path; // relative to the tree's root, `/`-separated + std::string role; // program | image | library | loader | launcher | resource | metadata + std::string leg; // the leg's triple; empty when every leg shares the file + std::string sha256; +}; + +struct info { + int schema = 0; + std::string name; + std::string version; + std::string platform; // `@`; empty: none + std::string linkage; // static | shared | declared + std::string mode; // system | vendored | self-contained | static + std::vector legs; // canonical triples + std::vector systems; // `-` of the loaders under libexec/ + std::vector runner; // the platform's runner argv; empty: native + // The entry of each architecture (universal packages), in the document's + // order: architecture, then the entry's path in the tree. + std::vector> entry; + std::string program; // the program's path (one native leg) + std::vector files; + std::string root; // the tree the document was read from +}; + +namespace detail { + +inline std::vector strings_of(const json::value* v) { + std::vector out; + if (!v || v->type != json::value::kind::array) return out; + for (auto const& item : v->items) + if (item.type == json::value::kind::string) out.push_back(item.text); + return out; +} + +} // namespace detail + +// The document at `/mcpp-package.json`, or why it cannot be read. +inline std::expected read(std::string_view stage_dir) { + std::string root(stage_dir); + while (root.size() > 1 && (root.back() == '/' || root.back() == '\\')) root.pop_back(); + const std::string path = root + "/mcpp-package.json"; + std::ifstream in(path, std::ios::binary); + if (!in) return std::unexpected(std::format("{} cannot be read: the tree is not a staged package", path)); + const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + json::value doc; + if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) + return std::unexpected(std::format("{} is not a JSON object", path)); + info p; + p.root = root; + if (const json::value* s = doc.get("schema"); s && s->type == json::value::kind::number) + p.schema = std::atoi(s->text.c_str()); + if (p.schema != 1) + return std::unexpected(std::format( + "{} states schema {}; this collection reads schema 1 (mcpp SPEC-014 §4.5)", path, p.schema)); + p.name = json::string_of(doc.get("name")); + p.version = json::string_of(doc.get("version")); + p.platform = json::string_of(doc.get("platform")); + p.linkage = json::string_of(doc.get("linkage")); + p.mode = json::string_of(doc.get("mode")); + p.legs = detail::strings_of(doc.get("legs")); + p.systems = detail::strings_of(doc.get("systems")); + if (const json::value* launch = doc.get("launch"); launch && launch->type == json::value::kind::object) { + p.runner = detail::strings_of(launch->get("runner")); + p.program = json::string_of(launch->get("program")); + if (const json::value* e = launch->get("entry"); e && e->type == json::value::kind::object) + for (auto const& m : e->members) + if (m.second.type == json::value::kind::string) p.entry.emplace_back(m.first, m.second.text); + } + const json::value* files = doc.get("files"); + if (!files || files->type != json::value::kind::array) + return std::unexpected(std::format("{} has no files array", path)); + for (auto const& f : files->items) { + if (f.type != json::value::kind::object) continue; + p.files.push_back({ json::string_of(f.get("path")), json::string_of(f.get("role")), + json::string_of(f.get("leg")), json::string_of(f.get("sha256")) }); + } + return p; +} + +// The files of `p` with `role`, in the document's order. +inline std::vector files_with_role(const info& p, std::string_view role) { + std::vector out; + for (auto const& f : p.files) + if (f.role == role) out.push_back(f); + return out; +} + +// The entry of `arch`, or empty. +inline std::string entry_of(const info& p, std::string_view arch) { + for (auto const& [a, path] : p.entry) + if (a == arch) return path; + return {}; +} + +} // namespace mcpp::plugins::package diff --git a/src/plugins/plugins.cppm b/src/plugins/plugins.cppm new file mode 100644 index 0000000..0dd636b --- /dev/null +++ b/src/plugins/plugins.cppm @@ -0,0 +1,61 @@ +// mcpp.plugins: the collection's shared library. +// +// Every member of this package is a module interface unit under rules/ or +// tools/, compiled as a host module of its own when the consumer's feature +// request names it. This unit is the lib root: it is compiled before every +// member, so a member may import it. +// +// IT HOLDS WHAT MORE THAN ONE MEMBER NEEDS, AND ONLY THAT. +// +// The lib root is the only unit every member can import. A second unit beside +// it in `[build] sources` is NOT compiled as a host module ahead of the +// members. Measured: a member importing a second lib-root unit failed with +// +// mcpp.plugins.surface: error: failed to read compiled module +// note: imports must be built before being imported +// +// because only the lib root is built first. So shared code lives here rather +// than in a file of its own, and a member that needs it writes +// `import mcpp.plugins;`. +export module mcpp.plugins; + +import std; + +// NO `import mcpp;`. That module exists only inside a build program, and this +// unit has to compile into an ordinary binary too: `mcpp.tools.embed`'s +// executable form is what lets a generated `.S` be an ACTION's output, which +// is the only way the payload it embeds can be a declared input of the edge +// that assembles it. Measured before this: an ordinary build of this package +// failed with `mcpp: failed to read compiled module`. +// +// Everything this unit used to read from that module -- the target OS, whether +// the toolchain has a GAS assembler, the package's name -- is now a parameter. +// The members under rules/ still import it; they are feature-gated, so the +// tool's own build never compiles them. + +export namespace mcpp::plugins { + +// THIS MUST EQUAL `[package] version` IN mcpp.toml, AND CI CHECKS THAT IT DOES. +// +// It was `0.1.1` while the package was `0.2.6`, which nothing noticed because +// nothing read it. A value that is recorded and never read cannot be wrong in a +// way anyone sees, so the fix is not only to correct it: every rule now states +// it with `mcpp::fact`, which makes a build log answer "which collection +// produced these actions" and makes a stale constant a visible defect rather +// than a dormant one. +// +// One package, one version: the number lives in mcpp.toml, and the CI step +// `the collection states its own version` compares the two. +inline constexpr std::string_view version = "0.27.0"; + +} // namespace mcpp::plugins + + +export import :stage; +export import :xml; +export import :json; +export import :graph; +export import :package; +export import :names; +export import :surface; +export import :tree; diff --git a/src/plugins/stage.cppm b/src/plugins/stage.cppm new file mode 100644 index 0000000..8d1b324 --- /dev/null +++ b/src/plugins/stage.cppm @@ -0,0 +1,48 @@ +export module mcpp.plugins:stage; + +import std; + +// mcpp::plugins::stage -- what the engine wrote beside a staged tree. +// +// SHARED BECAUSE TWO DIST MEMBERS READ IT. `mcpp pack` writes +// `.stage-manifest` (mcpp's docs/50, "The stage manifest"): a +// header, one `needs` line per library name the closure read (mcpp +// 2026.9.14.2+), and the list of staged files. `dist-apk` reads it to trust the +// native libraries under `lib/`, and `dist-apple` reads it to tell the dylibs +// staged beside a program from the resources staged there. Only the header and +// the `needs` lines are parsed; the file list is not. +export namespace mcpp::plugins::stage { + +struct need { + std::string name; // as the needing object spells it + std::string where; // a staged path relative to the tree, `platform` or `unresolved` +}; + +struct manifest { + bool found = false; // the file exists beside the tree + bool walked = true; // `closure = walked` + std::string reason; // `reason = ...`, with `closure = not-walked` + std::vector needs; +}; + +inline manifest read_manifest(std::string tree) { + manifest m; + while (tree.size() > 1 && (tree.back() == '/' || tree.back() == '\\')) + tree.pop_back(); + std::ifstream in(tree + ".stage-manifest", std::ios::binary); + if (!in) return m; + m.found = true; + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line == "closure = not-walked") { m.walked = false; continue; } + if (line.starts_with("reason = ")) { m.reason = line.substr(9); continue; } + if (!line.starts_with("needs\t")) continue; + const auto second = line.find('\t', 6); + if (second == std::string::npos) continue; + m.needs.push_back({ line.substr(6, second - 6), line.substr(second + 1) }); + } + return m; +} + +} // namespace mcpp::plugins::stage diff --git a/src/plugins/surface.cppm b/src/plugins/surface.cppm new file mode 100644 index 0000000..df05d57 --- /dev/null +++ b/src/plugins/surface.cppm @@ -0,0 +1,756 @@ +export module mcpp.plugins:surface; + +import std; +import :names; + + + +// mcpp.plugins.surface -- the interface a consumer names for an embedded payload. +// +// WHY THIS IS SHARED RATHER THAN PER-RULE. +// +// `mcpp.rules.spirv` and `mcpp.rules.slang` produce the same kind of thing: a +// block of bytes the program hands to a device API. `mcpp.tools.embed` produces +// it from a file that was already there. The three differ in who produces the +// bytes and disagree about nothing else, so the declaration a consumer reads is +// written once, here, and the shape is identical whichever produced it. A rule +// that wrote its own would be a second copy of a decision, and the two would +// drift the way the two shader compilers' headers drifted before 0.2.6. +// +// THE INTERFACE IS A FUNCTION, NOT A VARIABLE. +// +// A variable cannot keep one shape across the ways bytes can be stored, because +// `constexpr` and `extern` are mutually exclusive: an array compiled into a +// translation unit can be constant-evaluated and one living in a section cannot. +// A function can, so where the bytes live stays an option a project revises +// without touching a consumer. +// +// THE INTERFACE NAMES NO STANDARD-LIBRARY TYPE, AND THAT IS MEASURED. +// +// The same 1 MB payload, reached four ways, compiled with GCC 16.1: +// +// data in the module (`export inline constexpr`) BMI 6 282 240 B +// data in a header source 3 145 728 B +// data in an object, interface returns std::span BMI 1 313 968 B +// data in an object, interface returns a std-free POD BMI 1 808 B +// +// The third row is 727 times the fourth, and its cost is FIXED rather than +// proportional to the payload: the 1.28 MB is ``'s templates, present +// whether the payload is 16 KB or 16 MB. A consumer that wants a `std::span` +// constructs one from the two members, and `` is then included by the +// consumer that uses it rather than by every consumer that imports this. +// +// There is a second, independent reason for the same decision. `import std;` +// requires `std.gcm` to have been built, which a project with +// `modules = true, import_std = false` has not done. A std-free interface needs +// neither. +// +// WHY THE ACCESSORS HAVE C LANGUAGE LINKAGE. +// +// A function declared in a module interface has module linkage and can only be +// defined by a unit attached to that module. Defining them would therefore need +// a module implementation unit, and the definitions include the generated data +// headers -- which would put the arrays back into the interface's own +// compilation. Declaring the accessors `extern "C"` instead gives them external +// linkage, so an ordinary translation unit defines them, the module interface +// holds two declarations and one inline call per payload, and the bytes are +// never seen by the interface at all. +// +// It also removes a portability question: module implementation units are the +// least exercised corner of every implementation this package supports, and +// nothing here needs them. +// +// ONE COPY OF THE BYTES. +// +// A generated data header declares `static const uint32_t []`, so every +// translation unit that includes it gets its own copy. Under this surface +// exactly one translation unit includes it -- the generated implementation -- +// and every consumer reaches the same array through the accessor. +export namespace mcpp::plugins::surface { + +// The name derivations live in `mcpp::plugins::names`. They are reachable under +// this namespace as well, because every rule in this collection already spells +// them this way -- one definition under two spellings is not two definitions. +using names::identifier; +using names::split_module_name; +using names::common_base_dir; +using names::namespace_of; + +// How a consumer names the payloads. +// +// `module_` is the default where the project builds C++ modules, and +// `c_header` is what a project without them gets. The choice does not change +// any declaration's shape: the same struct, the same function names, the same +// namespaces. Only the file a consumer reaches them through differs. +enum class kind { module_, c_header }; + +// WHICH HALF OF THE SURFACE A CALL WRITES. +// +// The two are separate because their INPUTS are. The interface is a function of +// the item list: names, namespaces, the accessor declarations. The body is a +// function of the item list AND, under `storage::object`, of the payloads +// themselves -- the assembly names each one in `.incbin`, and the object it +// produces is those bytes. +// +// Declaring them as one action would make a payload change rewrite the +// interface too, and rebuild every BMI that imports it. Declaring them +// separately states what is true and costs a consumer nothing. +enum class half { interface_, body }; + +// The element the accessor hands back. `word32` is what an API taking +// `const uint32_t*` wants -- `vkCreateShaderModule` is the case this package +// has -- and asking for it here is cheaper than a reinterpret_cast at every +// call site, which is undefined behaviour on an under-aligned byte array. +enum class element { byte_, word32 }; + +// WHERE THE BYTES LIVE. Orthogonal to `kind`, which decides how a consumer +// NAMES them: the declarations are identical under all three, so a project +// changes this and no consumer changes. +// +// WHICH ONE TO USE IS A MEASUREMENT, NOT A PREFERENCE. With GCC 16.1 on this +// project's own fixtures, 100 payloads of 16 KB each: +// +// header route compile 0.64s + link 0.44s = 1.10s +// object route convert 1.28s + compile 0.44s + link 0.46s = 2.17s +// +// The header route is faster, because at a real shader's size neither route has +// a measurable marginal cost and the total is decided by how many processes +// start -- and one compiler invocation absorbs many headers. The crossover is +// the TOTAL embedded byte count, not the payload count: below about 1 MB the +// header route wins, and above about 4 MB the compiler's slightly superlinear +// curve loses by an order of magnitude (2.31s against 0.116s at 4 MB). Source +// expansion is a constant 2.75x, which is the second half of the same reason. +// +// So `header` is the default and `object` is what a project reaches for when it +// has more payload than that, not what it reaches for because objects sound +// tidier. +enum class storage { + // The payload is a C array in generated source, compiled into the program. + // No assembler involved, so it works on every toolchain including MSVC. + header, + // The payload is a section in an object, reached through `.incbin` in a + // generated `.S`. The bytes never pass through the C++ compiler. + // + // Requires a GAS-capable assembler. Every gcc and clang toolchain has one + // on all three platforms; MSVC does not, and mcpp refuses `.S` under it, so + // the emitter falls back to `header` there and says so once. + object, + // The payload is written beside the artifact and read at run time. The + // program's correctness then depends on its working directory, which is the + // reason this is not the default -- but it is what shader hot-reload needs, + // and what a payload too large to link needs. + sidecar, +}; + +// One payload in a group. +struct item { + // The C++ identifier, already sanitised by the caller: `blur_comp`. + std::string identifier; + // Namespace segments BELOW the group's own, from the payload's directory + // relative to its root: `{"post"}` for `shaders/post/tonemap.frag`. This is + // what keeps two payloads with one stem from colliding, and what makes the + // name a consumer writes say where the payload came from. + std::vector name_space; + // The generated data header this payload's bytes arrive in, AS AN + // `#include` WRITES IT -- relative to the directory the caller put on the + // include path, not an absolute path and not a bare file name. The + // generated tree mirrors the payload tree, so two payloads sharing a stem + // in different directories reach different headers, and a bare file name + // could not tell them apart. + std::string data_header; + // The array that header declares, qualified if it sits in a namespace. + // Unused under `storage::object`, where the linker symbol is derived from + // the accessor name instead, and under `storage::sidecar`. + std::string data_symbol; + // The payload file itself, as an absolute path. Required by `object`, whose + // generated `.S` names it in `.incbin`, and by `sidecar`, which copies it. + // The file need not exist yet: `.incbin` resolves its argument at assembly + // time, which is after the action that writes it has run, and that is what + // lets the whole surface be written at plan time. + std::string payload_path; + // Where a sidecar payload is found at run time, relative to the artifact. + std::string sidecar_name; + // The payload's size IN BYTES, as an expression valid where the generated + // implementation writes it. Empty means `sizeof `. + // + // IT EXISTS BECAUSE `sizeof` IS NOT ALWAYS THE ANSWER. `mcpp.tools.embed` + // can append a terminating zero byte that its own `_size` constant does not + // count, so `sizeof` and `_size` differ by one and only one of them is what + // the payload is. Measured: a group of null-terminated text payloads + // reported one byte too many and the fixture's comparison failed on a + // trailing NUL. A caller that knows the difference states it here rather + // than letting the generator guess. + std::string data_size_expr; +}; + +struct options { + kind surface = kind::module_; + storage store = storage::header; + element elem = element::word32; + // The module a consumer imports, e.g. `myapp.shaders`. The namespace is + // this name with `.` replaced by `::`, which is why there is no second + // field for it: two spellings of one identity drift. + std::string module_name; + // Where the generated interface and implementation are written. The caller + // adds this to the include path when the surface is `c_header`. + std::string out_dir; + // A short phrase naming what produced the payloads, for the generated + // files' first line: "mcpp.rules.spirv". + std::string produced_by; + + // ── What this generator is NOT allowed to find out for itself ─────────── + // + // THE TWO FIELDS BELOW ARE WHY THIS MODULE IMPORTS ONLY `std`. + // + // They were `mcpp::target_os()` and `mcpp::compiler()`, read here. That + // made the generator unusable anywhere except inside a build program -- + // which is the one place it must NOT be the only usable form, because a + // payload dependency can only enter the build graph if the generation is + // an ACTION, and an action's command is a binary. A binary cannot import + // the build-program module: measured, an ordinary build of this package + // fails with "mcpp: failed to read compiled module". + // + // So they are parameters. The caller has both answers already, and a + // generator that takes its inputs rather than reading its environment is + // the same code in a build program and in a tool. + + // The target's operating system, as mcpp spells it -- what decides the + // assembly dialect: the section directive and whether a symbol carries a + // leading underscore. Required under `storage::object`; ignored otherwise. + std::string target_os; + + // Whether a GAS-compatible assembler exists for this toolchain. False + // under MSVC, which has none, and where mcpp refuses `.S` outright. It is + // the CALLER's answer because the caller knows the compiler; this + // generator degrades `object` to `header` when it is false and reports + // that through `emitted::store` rather than by printing. + bool has_gas_assembler = true; +}; + +// What the caller hands back to mcpp. +struct emitted { + // The interface unit: a `.cppm` under `module_`, a `.h` under `c_header`. + std::string interface_file; + // The generated `.S` under `storage::object`, empty otherwise. The caller + // adds it to the build the same way it adds the implementation. + std::string assembly_file; + // The storage actually used. Differs from what was asked for when the + // toolchain cannot assemble: MSVC has no GAS, so `object` degrades to + // `header` and this says so rather than leaving the caller to assume. + storage store = storage::header; + // The translation unit defining the accessors. Always a plain `.cpp`. + std::string impl_file; + // Non-empty under `module_`: what the interface unit provides, which the + // caller declares with `mcpp::action::provides` or lets the scan find. + std::string module_name; + // Non-empty under `c_header`: the directory to put on the include path. + std::string include_dir; +}; + +// The linker symbol an accessor carries. It is derived from the module name and +// the payload's full namespace path rather than from the identifier alone, +// because two groups in one link unit -- a project with shaders and with +// embedded data -- would otherwise define the same symbol twice and the second +// definition would be the one nobody expected. +inline std::string accessor_base(const options& opt, const item& it) { + std::string s = "mcpp_embed"; + auto add = [&](std::string_view part) { + s += '_'; + for (char c : part) + s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; + }; + for (auto const& seg : split_module_name(opt.module_name)) add(seg); + for (auto const& seg : it.name_space) add(seg); + add(it.identifier); + return s; +} + +inline const char* element_type(element e) { + return e == element::word32 ? "unsigned int" : "unsigned char"; +} + +// `unsigned int` is 32 bits on every target this package supports, and the +// generated implementation asserts it rather than assuming it: a target where +// it is not would otherwise hand a Vulkan driver a pointer into misread data, +// and the failure would be a device error naming nothing. +inline const char* element_width_assertion(element e) { + return e == element::word32 + ? "static_assert(sizeof(unsigned int) == 4,\n" + " \"mcpp.plugins.surface: element::word32 assumes a 32-bit `unsigned int`\");\n" + : ""; +} + +inline bool write_if_different(const std::string& path, std::string_view text) { + std::error_code ec; + std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); + if (std::ifstream in(path, std::ios::binary); in) { + std::string old((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + if (old == text) return true; + } + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(text.data(), static_cast(text.size())); + return static_cast(out); +} + +// Open and close the namespaces an item sits in, below the group's own. +inline std::string open_namespaces(const std::vector& segs) { + std::string s; + for (auto const& one : segs) s += "namespace " + one + " {\n"; + return s; +} +inline std::string close_namespaces(const std::vector& segs) { + std::string s; + for (auto i = segs.rbegin(); i != segs.rend(); ++i) s += "} // namespace " + *i + "\n"; + return s; +} + +// The declarations shared by both surfaces. What differs between a module +// interface and a header is the preamble and how the group's namespace is +// opened; the body below is byte-identical, which is what makes switching +// surfaces a change no consumer can observe. +// The accessor declarations, at GLOBAL scope. +// +// C language linkage makes a name the same entity whatever namespace declares +// it, so these would resolve from inside the group's namespace as well. They are +// written outside it because the generated implementation defines them at global +// scope, and a reader comparing the two files should not have to know that rule +// to see that they match. +inline std::string extern_c_declarations(std::span items, const options& opt) { + const char* elem = element_type(opt.elem); + std::string s = "extern \"C\" {\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + s += std::format("const {}* {}_data();\n", elem, base); + s += std::format("unsigned long {}_size();\n", base); + } + s += "}\n"; + return s; +} + +inline std::string declarations(std::span items, const options& opt) { + const char* elem = element_type(opt.elem); + std::string s; + + s += std::format( + "// The payload, as the device API wants it. Free of standard-library\n" + "// types on purpose: see mcpp.plugins.surface.\n" + "struct payload {{\n" + " const {}* code; // e.g. VkShaderModuleCreateInfo::pCode\n" + " unsigned long size_bytes; // e.g. VkShaderModuleCreateInfo::codeSize\n" + "}};\n\n", elem); + + // Grouped by namespace path so a directory's payloads are emitted together + // and each namespace is opened once. + std::vector openNow; + auto reopen = [&](const std::vector& want) { + if (openNow == want) return; + s += close_namespaces(openNow); + s += open_namespaces(want); + openNow = want; + }; + for (auto const& it : items) { + reopen(it.name_space); + const auto base = accessor_base(opt, it); + // THROUGH `identifier`, HERE RATHER THAN IN EACH PRODUCER. This is the + // one line that turns `item::identifier` into something a compiler + // parses, and a rule that builds the field from a file stem cannot know + // it has produced `my-shader_comp` or `default` until it gets here. + s += std::format("inline payload {}() {{ return {{ {}_data(), {}_size() }}; }}\n", + identifier(it.identifier, "payload"), base, base); + } + reopen({}); + return s; +} + +// ONE OBJECT FORMAT PER PLATFORM, AND THE DIFFERENCES ARE NOT COSMETIC. +// +// `.incbin` is the portable part: gas and clang's integrated assembler both +// accept it everywhere, and it resolves its argument at ASSEMBLY time, which is +// why this file can be written before the payload exists. What is not portable +// is the section directive and whether a C symbol carries a leading underscore. +// +// ELF `.section .rodata`, symbol as written +// Mach-O `.section __TEXT,__const`, symbol PREFIXED with `_` +// COFF `.section .rdata,"dr"`, symbol as written on x86_64 +// +// Mach-O's underscore is the one that fails quietly in the other direction: an +// assembly label without it defines a symbol the C++ side never resolves, and +// the link error names the accessor rather than the missing prefix. +struct asm_dialect { + std::string_view section; + std::string_view symbol_prefix; +}; + +inline asm_dialect dialect_for(std::string_view targetOs) { + if (targetOs == "macos" || targetOs == "macosx" || targetOs == "darwin") + return { ".section __TEXT,__const", "_" }; + if (targetOs == "windows") return { ".section .rdata,\"dr\"", "" }; + return { ".section .rodata", "" }; +} + +// `.balign 4` rather than nothing: `VkShaderModuleCreateInfo::pCode` requires +// four-byte alignment, and a section directive alone does not promise it. The +// header route gets alignment from the array's element type; this route has to +// ask for it. +inline std::string assembly_for(std::span items, const options& opt, + std::string_view targetOs) { + const auto d = dialect_for(targetOs); + std::string s = + "// Generated by mcpp.plugins.surface. Do not edit.\n" + "//\n" + "// The payloads, as sections rather than as C arrays. `.incbin` resolves\n" + "// its argument when this file is assembled, which is after the actions\n" + "// that write those files have run.\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + s += std::format("\n {}\n" + " .globl {}{}_begin\n" + " .balign 4\n" + "{}{}_begin:\n" + " .incbin \"{}\"\n" + " .globl {}{}_end\n" + "{}{}_end:\n", + d.section, + d.symbol_prefix, base, + d.symbol_prefix, base, + it.payload_path, + d.symbol_prefix, base, + d.symbol_prefix, base); + } + return s; +} + +// ---- the tool --------------------------------------------------------------- + +// EVERY FILE THIS SURFACE WILL PRODUCE, WITHOUT PRODUCING ANY OF THEM. +// +// A rule declares these as an action's outputs, and mcpp requires an output to +// be NAMED before the graph is built even though its content arrives later. So +// the names cannot come from having written the files -- which is the coupling +// that forced generation to happen at plan time, and with it the whole +// staleness this round removes. +// +// Pure: no items, no filesystem, no environment. The one decision it makes is +// the MSVC degradation, which is a property of the toolchain rather than of any +// payload, and `emitted::store` is where the caller reads the verdict. +inline emitted outputs(const options& opt) { + emitted out; + out.store = opt.store; + // MSVC HAS NO GAS, AND mcpp REFUSES `.S` UNDER IT. `src/build/prepare.cppm` + // says so outright: "GAS assembly sources (.S/.s) are not supported by the + // MSVC toolchain". Object storage degrades to header storage there rather + // than producing a file the build will refuse, and the SURFACE does not + // change -- the declarations are identical under both. + if (out.store == storage::object && !opt.has_gas_assembler) + out.store = storage::header; + + const auto dir = std::filesystem::path(opt.out_dir); + out.interface_file = (dir / (opt.module_name + + (opt.surface == kind::module_ ? ".cppm" : ".h"))).string(); + out.impl_file = (dir / (opt.module_name + ".impl.cpp")).string(); + // Named only under the storage that produces one, so a caller can test the + // string rather than having to test the storage a second time. + if (out.store == storage::object) + out.assembly_file = (dir / (opt.module_name + ".payload.S")).string(); + if (opt.surface == kind::module_) out.module_name = opt.module_name; + else out.include_dir = dir.string(); + return out; +} + + +// The assembly's meaning includes the bytes named by .incbin. Put a content +// checksum in its source so restat cannot prune the assembler after a payload +// changes while the .incbin path stays the same. This runs in the body action, +// after its declared payload inputs exist; planning still reads no payload. +inline std::optional payload_checksum(const std::string& file) { + std::ifstream input(file, std::ios::binary); + if (!input) return std::nullopt; + std::uint64_t sum = 14695981039346656037ULL; + std::array bytes; + while (input) { + input.read(bytes.data(), static_cast(bytes.size())); + for (std::streamsize i = 0; i < input.gcount(); ++i) { + sum ^= static_cast(bytes[static_cast(i)]); + sum *= 1099511628211ULL; + } + } + return input.bad() ? std::nullopt : std::optional(sum); +} + +// Writes ONE half of the surface. The names come from `outputs`, which the +// caller has already asked; this produces the content. +// +// The interface reads no payload. The object body runs after its declared +// payload inputs, records their content checksum and names them in .incbin; +// the assembler reads the bytes after that body action has completed. +inline bool write(std::span items, const options& opt, half which) { + if (items.empty()) return true; + if (opt.module_name.empty()) { + std::cerr << "mcpp.plugins.surface: options::module_name is required; it names both " + "the module a consumer imports and the namespace the declarations sit in\n"; + return false; + } + if (opt.out_dir.empty()) { + std::cerr << "mcpp.plugins.surface: options::out_dir is required\n"; + return false; + } + + const auto segs = split_module_name(opt.module_name); + // REFUSED HERE, NOT IN THE GENERATED FILE. The module name is the one part + // of this surface a project writes itself, and each of its segments becomes + // a namespace. A segment that is not an identifier -- empty, starting with + // a digit, carrying a `-`, or reserved -- produces a generated file that + // does not parse, and the error then names a line nobody wrote. + for (std::size_t i = 0; i < segs.size(); ++i) { + if (segs[i] == identifier(segs[i], "")) continue; + std::cerr << std::format( + "mcpp.plugins.surface: `{}` is not a usable module name: the segment `{}` " + "is not a C++ identifier.\n Each segment becomes a namespace, so it has " + "to be one; `{}` would work.\n", + opt.module_name, segs[i], identifier(segs[i], "part")); + return false; + } + const auto by = opt.produced_by.empty() ? std::string("mcpp.plugins.surface") + : opt.produced_by; + + // ONE derivation of the names, shared with the caller. Recomputing them + // here would be the second copy of a decision that this package has paid + // for before. + const emitted out = outputs(opt); + const auto dir = std::filesystem::path(opt.out_dir); + const auto body = declarations(items, opt); + + // ---- interface ---- + if (which == half::interface_) { + std::string iface; + iface += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); + if (opt.surface == kind::module_) + iface += std::format("export module {};\n\n", opt.module_name); + else + iface += "#pragma once\n\n"; + iface += extern_c_declarations(items, opt); + iface += "\n"; + // `export` on the opening namespace exports everything the block + // contains, including the nested namespaces a payload's directory + // produced. + if (opt.surface == kind::module_) iface += "export "; + iface += open_namespaces(segs); + iface += "\n" + body + "\n"; + iface += close_namespaces(segs); + if (!write_if_different(out.interface_file, iface)) { + std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", + out.interface_file); + return false; + } + return true; + } + + // ---- implementation ---- (half::body from here down) + // + // The one translation unit that defines the accessors. A plain `.cpp` under + // every surface and every storage, because the accessors have C language + // linkage and so need no attachment to the module. What differs between the + // three storages is only where it reads the bytes from. + const char* elem = element_type(opt.elem); + std::string impl; + impl += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); + + if (out.store == storage::header) { + impl += "//\n" + "// The only translation unit that includes the generated data headers.\n" + "// Each declares a `static` array, so this is also the only copy of the\n" + "// bytes in the program.\n"; + for (auto const& it : items) impl += std::format("#include \"{}\"\n", it.data_header); + impl += "\n"; + impl += element_width_assertion(opt.elem); + impl += "\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + const auto size = it.data_size_expr.empty() + ? std::format("sizeof {}", it.data_symbol) + : it.data_size_expr; + impl += std::format( + "extern \"C\" const {0}* {1}_data() {{ return {2}; }}\n" + "extern \"C\" unsigned long {1}_size() {{ return {3}; }}\n", + elem, base, it.data_symbol, size); + } + } else if (out.store == storage::object) { + impl += "//\n" + "// The bytes are in a section written by the generated `.S`. This file\n" + "// only names its two boundary symbols, so nothing here parses a payload\n" + "// and the C++ compiler never sees one.\n" + "//\n" + "// The symbols are declared as arrays of the element type rather than as\n" + "// `char`: the assembly aligned the section to four bytes, and a\n" + "// declaration that said `char` would let a consumer reach it through an\n" + "// under-aligned pointer with nothing to notice.\n"; + impl += "\n"; + impl += element_width_assertion(opt.elem); + impl += "\nextern \"C\" {\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + impl += std::format("extern const {0} {1}_begin[];\n" + "extern const {0} {1}_end[];\n", elem, base); + } + impl += "}\n\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + impl += std::format( + "extern \"C\" const {0}* {1}_data() {{ return {1}_begin; }}\n" + "extern \"C\" unsigned long {1}_size() {{\n" + " return static_cast(({1}_end - {1}_begin) * sizeof({0}));\n" + "}}\n", elem, base); + } + } else { + impl += "//\n" + "// The payloads are files beside the artifact, read on first use. The\n" + "// path is resolved against the WORKING DIRECTORY, which is the property\n" + "// that makes this storage the one a project opts into rather than the\n" + "// default: a program started from elsewhere finds nothing.\n" + "//\n" + "// Read once and kept: an accessor that reloaded would hand two callers\n" + "// two different pointers to the same payload, and a device API given\n" + "// the second after the first was freed is a defect with no message.\n"; + impl += "#include \n#include \n#include \n\n"; + impl += element_width_assertion(opt.elem); + impl += std::format(R"IMPL( +namespace {{ + +struct blob {{ {0}* data = nullptr; unsigned long size = 0; bool tried = false; }}; + +blob& load(const char* path, blob& b) {{ + if (b.tried) return b; + b.tried = true; + std::FILE* f = std::fopen(path, "rb"); + if (!f) {{ + std::fprintf(stderr, "mcpp.plugins.surface: cannot open %s\n", path); + return b; + }} + std::fseek(f, 0, SEEK_END); + const long n = std::ftell(f); + std::fseek(f, 0, SEEK_SET); + if (n > 0) {{ + b.data = static_cast<{0}*>(std::malloc(static_cast(n))); + if (b.data && std::fread(b.data, 1, static_cast(n), f) + == static_cast(n)) + b.size = static_cast(n); + else {{ std::free(b.data); b.data = nullptr; }} + }} + std::fclose(f); + return b; +}} + +}} // namespace +)IMPL", elem); + impl += "\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + impl += std::format( + "static blob {0}_blob;\n" + "extern \"C\" const {1}* {0}_data() {{\n" + " return load(\"{2}\", {0}_blob).data;\n" + "}}\n" + "extern \"C\" unsigned long {0}_size() {{\n" + " return load(\"{2}\", {0}_blob).size;\n" + "}}\n", base, elem, it.sidecar_name); + } + } + + if (!write_if_different(out.impl_file, impl)) { + std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", out.impl_file); + return false; + } + + if (out.store == storage::object) { + // A CALLER THAT ASKS FOR THIS STORAGE MUST HAVE SAID WHERE THE BYTES + // ARE, AND THE REFUSAL IS WHAT KEEPS THAT TRUE. + // + // `item::payload_path` is documented as required under `object`, and + // today only `mcpp.rules.spirv` reaches this storage and only it sets + // the field. That is a COINCIDENCE, not a guarantee: the first caller + // to give `rules-slang` or `tools-embed` a storage option would get an + // `.incbin ""` in a generated `.S`, and the declaration below would + // then name an empty dependency -- so the build would be wrong in + // exactly the silent way this whole change exists to remove. + // + // A constraint written only in a comment has nothing enforcing it, + // which is a shape this project has recorded before. This is the + // enforcement. + for (auto const& it : items) { + if (!it.payload_path.empty()) continue; + std::cerr << std::format( + "mcpp.plugins.surface: `{}` was given storage::object with no " + "payload_path.\n" + " Under this storage the generated assembly names the payload " + "in `.incbin`, so\n" + " the caller has to say where it is. Set `item::payload_path`, " + "or use storage::header.\n", + it.identifier); + return false; + } + auto assembly = assembly_for(items, opt, opt.target_os); + for (const auto& it : items) { + const auto checksum = payload_checksum(it.payload_path); + if (!checksum) { + std::cerr << std::format("mcpp.plugins.surface: cannot read payload {}\n", it.payload_path); + return false; + } + assembly += std::format("// payload content: {:016x}\n", *checksum); + } + if (!write_if_different(out.assembly_file, assembly)) { + std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", + out.assembly_file); + return false; + } + } + // `storage::sidecar` needs no counterpart, and that was checked rather than + // assumed. Its payload is never read by a compile: the accessor opens the + // file at RUN time, so a rebuilt payload is picked up by the next run with + // nothing in the build graph to keep current. + return true; +} + +// The surface a project gets when it asks for nothing. +// +// `MCPP_LANGUAGE_MODULES` is set by mcpp from `[language] modules`. An engine +// that does not set it leaves the variable absent, and the fallback is the +// header surface -- which is what every consumer of this package had before +// this module existed. An older engine therefore keeps its behaviour and a +// newer one gets the module surface without any project asking, which is the +// whole of the upgrade path. +inline kind default_surface() { + const char* v = std::getenv("MCPP_LANGUAGE_MODULES"); + return (v && (*v == '1' || *v == 't' || *v == 'T')) ? kind::module_ : kind::c_header; +} + +// `example:my-app` -> `my_app`. The module a rule names by default is this +// followed by the group's own segment, so two packages in one build cannot +// claim the same module. +// The default module root for a package that named none: its PACKAGE NAME, +// sanitised into an identifier. +// +// THE PACKAGE'S NAME. NOT ITS DIRECTORY'S. These are different questions and +// they give different answers whenever a project lays a package out under a +// generic directory. The first version asked the only question mcpp could +// answer -- the leaf of MCPP_MANIFEST_DIR -- so a package named `vulkan-saxpy` +// laid out as `vulkan/app/` generated `app.shaders`, and every +// `/app/` in a workspace claimed that same module. +// +// The name ARRIVES rather than being read, for the reason `options::target_os` +// records: this module must compile into a plain binary as well as into a +// build program, so it may not reach for `mcpp::package_name()` itself. The +// caller passes what mcpp told it. +// +// `fallback` covers the impossible case -- a manifest without a `[package] +// name` does not load, so an empty first argument would mean the contract +// changed underneath. A rule that wants neither passes `options::module_name`, +// and this is not consulted. +inline std::string module_root_for(std::string_view package_name, + std::string_view fallback = {}) { + std::string leaf{package_name}; + if (leaf.empty()) leaf = std::string(fallback); + return identifier(leaf, "app"); +} + +} // namespace mcpp::plugins::surface diff --git a/src/plugins/tree.cppm b/src/plugins/tree.cppm new file mode 100644 index 0000000..b14eea6 --- /dev/null +++ b/src/plugins/tree.cppm @@ -0,0 +1,48 @@ +export module mcpp.plugins:tree; + +import std; + + +// mcpp::plugins::tree -- the directories a walk of a source tree leaves out. +// +// SHARED BECAUSE TWO MEMBERS WALK A SOURCE TREE BY DEFAULT. `rules-qt` finds +// the headers moc reads and the sources lupdate reads under the package, and +// `deps` takes every file of a subproject as an input of its installation, and +// `deps-cmake` as part of the installation's key. Neither may take what ANOTHER +// build system generated there: a Visual Studio project built in the same +// checkout leaves its moc and uic output under `x64/Release/`, and lupdate +// given those files rewrites the translations, and a CMake build directory an +// IDE made inside a subproject changes the key on every build. +// +// Such a directory is known by what its build system leaves in it, not by its +// name: `x64/` is as often a directory of architecture-specific sources. +export namespace mcpp::plugins::tree { + +// Whether `dir` is an output directory of another build system: +// +// CMakeCache.txt a CMake build tree (an IDE's `cmake-build-*`, `out/build/*`) +// .qmake.stash a qmake build tree +// CACHEDIR.TAG a directory its tool tags as a cache (https://bford.info/cachedir/) +// .tlog/ an MSBuild intermediate directory (`x64/Release/`), where a +// Visual Studio project writes the sources it generates +// +// A walk asks this of the directories under its root, never of the root: a +// subproject configured in its own source directory holds CMakeCache.txt too. +inline bool build_output(const std::filesystem::path& dir) { + namespace fs = std::filesystem; + std::error_code ec; + if (fs::is_regular_file(dir / "CMakeCache.txt", ec) || fs::is_regular_file(dir / ".qmake.stash", ec)) + return true; + if (fs::is_regular_file(dir / "CACHEDIR.TAG", ec)) { + std::ifstream in(dir / "CACHEDIR.TAG", std::ios::binary); + std::string head(43, '\0'); + in.read(head.data(), 43); + if (head == "Signature: 8a477f597d28d172789f06886806bc55") return true; + } + for (auto it = fs::directory_iterator(dir, fs::directory_options::skip_permission_denied, ec); + !ec && it != fs::directory_iterator(); it.increment(ec)) + if (it->path().extension() == ".tlog" && it->is_directory(ec)) return true; + return false; +} + +} // namespace mcpp::plugins::tree diff --git a/src/plugins/xml.cppm b/src/plugins/xml.cppm new file mode 100644 index 0000000..1c34f7c --- /dev/null +++ b/src/plugins/xml.cppm @@ -0,0 +1,169 @@ +export module mcpp.plugins:xml; + +import std; + + +// mcpp::plugins::xml -- the XML two dist members read and write. +// +// SHARED BECAUSE TWO DIST MEMBERS READ IT. `dist-apk` merges library manifests +// into an application's, and `dist-apple` adds a project's Info.plist entries +// and reads the plist a provisioning profile carries. Neither needs more than +// elements, attributes and text, and neither interprets an entity, so this is +// that much and no more: no namespaces resolved, no DTD read, no validation. +export namespace mcpp::plugins::xml { + +// A tree of elements and text. Comments, the XML declaration and a DOCTYPE are +// read and dropped: the documents this member writes from a tree are generated +// files, and a merged manifest carries no author to read a comment. Attribute +// values are kept exactly as written, entities included, because nothing here +// interprets them beyond comparing and substituting `${applicationId}`. +struct node { + std::string name; // empty: a text node + std::vector> attrs; + std::vector children; + std::string text; // a text node's characters +}; + +struct reader { + std::string_view s; + std::size_t i = 0; + std::string error; + + static bool space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } + bool starts(std::string_view t) const { return s.substr(i, t.size()) == t; } + void skip_space() { while (i < s.size() && space(s[i])) ++i; } + bool skip_past(std::string_view end) { + const auto p = s.find(end, i); + if (p == std::string_view::npos) { i = s.size(); return false; } + i = p + end.size(); + return true; + } + std::string name() { + const std::size_t b = i; + while (i < s.size() && !space(s[i]) && s[i] != '>' && s[i] != '/' && s[i] != '=') ++i; + return std::string(s.substr(b, i - b)); + } + + bool element(node& out) { + ++i; // '<' + out.name = name(); + if (out.name.empty()) { error = "an element without a name"; return false; } + for (;;) { + skip_space(); + if (i >= s.size()) { error = "<" + out.name + "> is not terminated"; return false; } + if (starts("/>")) { i += 2; return true; } + if (s[i] == '>') { ++i; break; } + std::string attr = name(); + skip_space(); + if (attr.empty() || i >= s.size() || s[i] != '=') { + error = "an attribute of <" + out.name + "> has no value"; + return false; + } + ++i; + skip_space(); + if (i >= s.size() || (s[i] != '"' && s[i] != '\'')) { + error = "attribute " + attr + " of <" + out.name + "> is not quoted"; + return false; + } + const char quote = s[i++]; + const auto end = s.find(quote, i); + if (end == std::string_view::npos) { error = "attribute " + attr + " is not terminated"; return false; } + out.attrs.emplace_back(std::move(attr), std::string(s.substr(i, end - i))); + i = end + 1; + } + for (;;) { + if (i >= s.size()) { error = "<" + out.name + "> is not closed"; return false; } + if (starts("= s.size() || s[i] != '>') { + error = " closes <" + out.name + ">"; + return false; + } + ++i; + return true; + } + if (starts("")) { error = "a comment is not terminated"; return false; } continue; } + if (starts("")) { error = "a processing instruction is not terminated"; return false; } continue; } + if (starts("")) { error = "a CDATA section is not terminated"; return false; } + node t; + t.text = std::string(s.substr(b, i - b)); + out.children.push_back(std::move(t)); + continue; + } + if (s[i] == '<') { + node child; + if (!element(child)) return false; + out.children.push_back(std::move(child)); + continue; + } + const std::size_t b = i; + auto end = s.find('<', i); + if (end == std::string_view::npos) end = s.size(); + i = end; + bool blank = true; + for (std::size_t j = b; j < end; ++j) if (!space(s[j])) { blank = false; break; } + if (!blank) { + node t; + t.text = std::string(s.substr(b, end - b)); + out.children.push_back(std::move(t)); + } + } + } + + bool document(node& root) { + for (;;) { + skip_space(); + if (starts(""); continue; } + if (starts(""); continue; } + if (starts(""); continue; } + break; + } + if (i >= s.size() || s[i] != '<') { error = "no root element"; return false; } + if (!element(root)) return false; + return true; + } +}; + +inline bool parse(std::string_view text, node& root, std::string& error) { + reader r{text}; + if (!r.document(root)) { error = r.error; return false; } + return true; +} + +inline std::string trim_copy(const std::string& s) { + std::size_t b = 0, e = s.size(); + while (b < e && reader::space(s[b])) ++b; + while (e > b && reader::space(s[e - 1])) --e; + return s.substr(b, e - b); +} + +inline void write(const node& n, std::string& out, int depth) { + const std::string pad(static_cast(depth) * 4, ' '); + if (n.name.empty()) { out += pad + trim_copy(n.text) + "\n"; return; } + out += pad + "<" + n.name; + for (auto const& a : n.attrs) out += " " + a.first + "=\"" + a.second + "\""; + if (n.children.empty()) { out += "/>\n"; return; } + if (n.children.size() == 1 && n.children.front().name.empty()) { + out += ">" + n.children.front().text + "\n"; + return; + } + out += ">\n"; + for (auto const& c : n.children) write(c, out, depth + 1); + out += pad + "\n"; +} + +inline std::string attr_of(const node& n, std::string_view key) { + for (auto const& a : n.attrs) if (a.first == key) return a.second; + return {}; +} + +inline void set_attr(node& n, const std::string& key, const std::string& value) { + for (auto& a : n.attrs) if (a.first == key) { a.second = value; return; } + n.attrs.emplace_back(key, value); +} + +} // namespace mcpp::plugins::xml From 24a69bae090a3d70bb78f313987f20c90de97579 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 16:32:33 +0800 Subject: [PATCH 06/18] README: the common members first, a contributing-and-maintenance section, clickable maintainers, and no layout or releases section --- README.md | 164 ++++++++++++++++++++---------------------------- README.zh-CN.md | 145 ++++++++++++++++++------------------------ 2 files changed, 128 insertions(+), 181 deletions(-) diff --git a/README.md b/README.md index f5f9ff6..d42ee16 100644 --- a/README.md +++ b/README.md @@ -8,20 +8,20 @@ [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) +[Documentation](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [Package index](https://mcpplibs.github.io/mcpp-index/) · [Releases](https://github.com/mcpp-community/mcpp-plugins/releases) + mcpp is a general engine with a framework for build plugins; plugins come from this package (`mcpp:plugins`), from third parties, or from the project itself, and `build.mcpp` is where a project uses them: it imports the member's module under the name the member declares, configures it, and calls it. The edge is a -`[build-dependencies]` entry, not a `[dependencies]` entry: `host-module = true` -states which build-time product is wanted, and the section states that the -package does not reach the target — a rule's library is never linked into the -artifact (mcpp docs/05 §2.6.1). +`[build-dependencies]` entry — the library serves the build program, and the +package never reaches the target. ## Quick start ```toml [build-dependencies.mcpp] -plugins = { version = "0.27.0", features = ["rules-spirv"], host-module = true } +plugins = { version = "0.27.0", features = ["rules-spirv"] } ``` ```cpp @@ -47,105 +47,77 @@ int main() { | deps | `mcpp.deps.` | where a library comes from | | identity | `mcpp.plugins` | the lib root, compiled before every member; it states the collection's version | -A third-party plugin names its modules `mcpp..*`; the second -segments `core`, `plugins`, `deps`, `rules`, `dist`, `tools` belong to this -package and the engine. The full account of the families, and of how the engine -routes a file to a rule, is in [docs/00](docs/00-engine-and-rules.md); where a -tool a member runs comes from is in [docs/02](docs/02-tool-sources.md). +A third-party plugin names its modules `mcpp..*`; `core`, +`plugins`, `deps`, `rules`, `dist`, `tools` belong to this package and the +engine. The full account of the families, and of how the engine routes a file +to a rule, is in [docs/00](docs/00-engine-and-rules.md); where a tool a member +runs comes from is in [docs/02](docs/02-tool-sources.md). + +## Plugins -## Members +The most used: -From 0.21.0 the package as a whole needs mcpp 2026.10.30.1 (`[package] mcpp`); -the column states the release each member's behaviour first needed. Cross CMake -subprojects that link executables or shared libraries require mcpp -2026.11.7.1 or later, and cross configuration requires CMake 3.19 or later. +| member | module | what it does | doc | +|---|---|---|---| +| `rules-cuda` | `mcpp.rules.cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | +| `rules-sycl` | `mcpp.rules.sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | +| `rules-spirv` | `mcpp.rules.spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | +| `rules-qt` | `mcpp.rules.qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | +| `dist-apk` | `mcpp.dist.apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) |
-The 23 members — feature, module, mcpp floor, behaviour, doc, maintainer +All 23 members — feature, module, mcpp floor, behaviour, doc, maintainer | feature | module | mcpp floor | what it does | doc | maintainer | |---|---|---|---|---|---| -| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [rules](docs/10-rules.md#rules-ascendc) | @Sunrisepeak | -| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [rules](docs/10-rules.md#rules-cuda) | @Sunrisepeak | -| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [rules](docs/10-rules.md#rules-hip) | @Sunrisepeak | -| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](docs/10-rules.md#rules-metal) | @Sunrisepeak | -| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](docs/11-rules-qt.md) | @Sunrisepeak | -| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](docs/12-rules-qml.md) | @Sunrisepeak | -| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](docs/10-rules.md#rules-slang) | @Sunrisepeak | -| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](docs/10-rules.md#rules-spirv) | @Sunrisepeak | -| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](docs/10-rules.md#rules-swift) | @Sunrisepeak | -| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](docs/10-rules.md#rules-sycl) | @Sunrisepeak | -| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | Writes a data file into a header the program compiles in. | [tools-embed](docs/20-tools-embed.md) | @Sunrisepeak | -| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | Generates the `extern "C"` boundary and the C++ module of a code island. | [tools-island](docs/21-tools-island.md) | @Sunrisepeak | -| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [tools-steps](docs/22-tools-steps.md) | @Sunrisepeak | -| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [dist](docs/30-dist.md#dist-appimage) | @Sunrisepeak | -| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | -| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | The same installation as an RPM package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | -| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [dist](docs/30-dist.md#dist-wix) | @Sunrisepeak | -| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [dist-apple](docs/31-dist-apple.md) | @Sunrisepeak | -| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [dist](docs/30-dist.md#dist-web) | @Sunrisepeak | -| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [dist-apk](docs/32-dist-apk.md) | @Sunrisepeak | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-vcpkg) | @Sunrisepeak | -| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3; a cross build 2026.10.30.1 | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved -- for another target, the compilers and words of the engine's contract -- keeps the installation for any build with the same key, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-cmake) | @Sunrisepeak | -| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | Extracts a zip archive the project keeps and places its tree beside the program. | [deps](docs/40-deps.md#deps-archive) | @Sunrisepeak | - -Some features add a sub-capability to a member: `dist-apk-kotlin` and -`dist-apk-maven` (Kotlin sources, a Maven graph), and `deps`, which the deps -members imply. - -**The general library.** `plugins-core` gives a build program -`mcpp.plugins.declare`, `mcpp.plugins.toolset`, `mcpp.plugins.fs` and -`mcpp.plugins.tool`; every member implies it, and a build program that uses -only these modules names it on the dependency edge. `plugins-testing`, -`plugins-toolchain` and `plugins-platform` add `mcpp.plugins.testing`, -`mcpp.plugins.toolchain` and `mcpp.plugins.platform` (with -`mcpp::plugins::package`); `plugins-progress` adds the optional action -telemetry and its atomic snapshot writer; `mcpp.plugins.accel` reads -implementation-owned target requests. The layers, names and the engine floor -are in [docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor). -`surface`, the name of `plugins-core` before 0.17.0, is kept until 2027-03-28. +| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [rules](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [rules](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [rules](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | Writes a data file into a header the program compiles in. | [tools-embed](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | Generates the `extern "C"` boundary and the C++ module of a code island. | [tools-island](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [tools-steps](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [dist](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | The same installation as an RPM package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [dist](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [dist-apple](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [dist](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [dist-apk](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3; a cross build 2026.10.30.1 | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved -- for another target, the compilers and words of the engine's contract -- keeps the installation for any build with the same key, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | Extracts a zip archive the project keeps and places its tree beside the program. | [deps](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) | + +Some features add a sub-capability: `dist-apk-kotlin`, `dist-apk-maven`, and +`deps`, which the deps members imply. `plugins-core` — `mcpp.plugins.declare`, +`mcpp.plugins.toolset`, `mcpp.plugins.fs`, `mcpp.plugins.tool` — is the general +library every member implies; `plugins-testing`, `plugins-toolchain`, +`plugins-platform` and `plugins-progress` add their own modules. Their layers +and the engine floor are in +[docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor).
-## Layout - -``` -mcpp.toml the package: one feature per member -src/plugins/ the lib root: export module mcpp.plugins (the version, - mcpp::plugins::surface, mcpp::plugins::xml, - mcpp::plugins::package), its partitions beside it -src/declare.cppm, the general library for build programs (`plugins-core`): -src/toolset.cppm, mcpp.plugins.declare, mcpp.plugins.toolset, mcpp.plugins.fs -src/fs.cppm -src/testing.cppm mcpp.plugins.testing (`plugins-testing`) -src/platform.cppm mcpp.plugins.platform (`plugins-platform`) -src/compat/, deps/compat/ - compatibility units, each retired on the date its header states -rules/.cppm export module mcpp.rules.; -tools/.cppm export module mcpp.tools.; -dist/.cppm export module mcpp.dist.; -deps/.cppm export module mcpp.deps.; deps/deps.cppm is shared -// a member that outgrew one file: .cppm keeps the module - a consumer imports, internal/ holds the machinery; the - module name does not change -tests// one project per member, built by CI with the pinned mcpp -docs/ one page per member or group of members ([index](docs/README.md)) -``` - -## Adding a member - -A member is one module file, one feature in `mcpp.toml`, a consumer under -`tests/` that CI builds and asserts on, a row in the table above with its mcpp -floor, a page under `docs/`, and a version bump. Its code is the C++23 that GCC -with libstdc++, clang with libc++ and an editor's clangd with libstdc++ all -accept, and CI builds or reads every fixture under each of the three. The -conventions a member follows are in -[docs/01](docs/01-plugin-development.md); the division between what the engine -owns and what the member owns is in +## Contributing and maintenance + +**Maintainers.** The package and, today, every member: +[@Sunrisepeak](https://github.com/Sunrisepeak). Review routing by family: +[`.github/CODEOWNERS`](.github/CODEOWNERS) — a new maintainer takes a family +by editing one line. + +**Contributing.** A change goes through a pull request from a branch; one pull +request does one thing; commits and text are English. A new member is a module +(or a directory when it outgrows one file — [docs/01 +§5](docs/01-plugin-development.md#5-a-new-plugin)), a feature in `mcpp.toml`, +a consumer under `tests/` that CI builds and asserts on, a row in the table +above, a page under `docs/`, and a version bump. The conventions a member +follows are in [docs/01](docs/01-plugin-development.md); the division between +what the engine owns and what the member owns is in [docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns). - -## Releases - -A tag `v` publishes the source archive; the index descriptor -(`mcpp-index/pkgs/mcpp/mcpp.plugins.lua`) names the GitHub archive and its -GitCode mirror with one sha256. diff --git a/README.zh-CN.md b/README.zh-CN.md index 222e99c..b752a6b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,23 +4,22 @@ [English](README.md) | 简体中文 -本文是 [README.md](README.md) 的中文镜像;英文为权威版本,两处不一致时以英文为准。 - [![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) +[文档索引](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [包索引 mcpp-index](https://mcpplibs.github.io/mcpp-index/) · [发布](https://github.com/mcpp-community/mcpp-plugins/releases) + mcpp 是一个带有构建插件框架的通用引擎;插件来自本包(`mcpp:plugins`)、来自 第三方,或来自项目自身,而 `build.mcpp` 是项目使用它们的地方:它按成员声明 -的名字导入成员模块,配置并调用它。这条边是 `[build-dependencies]` 条目,而 -不是 `[dependencies]`:`host-module = true` 声明要的是哪个构建期产物,该小节 -声明这个包不抵达目标——rule 的库永远不会被链接进产物(mcpp docs/05 §2.6.1)。 +的名字导入成员模块,配置并调用它。这条边是 `[build-dependencies]` 条目—— +库服务于构建程序,本包永不抵达目标。 ## 快速开始 ```toml [build-dependencies.mcpp] -plugins = { version = "0.27.0", features = ["rules-spirv"], host-module = true } +plugins = { version = "0.27.0", features = ["rules-spirv"] } ``` ```cpp @@ -47,95 +46,71 @@ int main() { | identity | `mcpp.plugins` | 库根,先于每个成员编译;它声明这个集合的版本 | 第三方插件把模块命名为 `mcpp.<它的 namespace>.*`;`core`、`plugins`、`deps`、 -`rules`、`dist`、`tools` 这几个第二段属于本包与引擎。家族的完整论述,以及 -引擎如何把文件路由给 rule,见 [docs/00](docs/00-engine-and-rules.md);成员 -运行的工具从哪里来,见 [docs/02](docs/02-tool-sources.md)。 +`rules`、`dist`、`tools` 属于本包与引擎。家族的完整论述,以及引擎如何把文件 +路由给 rule,见 [docs/00](docs/00-engine-and-rules.md);成员运行的工具从哪里 +来,见 [docs/02](docs/02-tool-sources.md)。 -## 成员 +## 插件 -自 0.21.0 起整个包需要 mcpp 2026.10.30.1(`[package] mcpp`);列中给出每个 -成员的行为首次所需的发布版。链接可执行文件或共享库的交叉 CMake 子项目需要 -mcpp 2026.11.7.1 或更高,交叉配置需要 CMake 3.19 或更高。 +最常用的几个: + +| 成员 | 模块 | 行为 | 文档 | +|---|---|---|---| +| `rules-cuda` | `mcpp.rules.cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | +| `rules-sycl` | `mcpp.rules.sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | +| `rules-spirv` | `mcpp.rules.spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | +| `rules-qt` | `mcpp.rules.qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | +| `dist-apk` | `mcpp.dist.apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) |
-23 个成员——feature、模块、mcpp 下限、行为、文档、维护者 +全部 23 个成员——feature、模块、mcpp 下限、行为、文档、维护者 | feature | 模块 | mcpp 下限 | 行为 | 文档 | 维护者 | |---|---|---|---|---|---| -| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [rules](docs/10-rules.md#rules-ascendc) | @Sunrisepeak | -| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [rules](docs/10-rules.md#rules-cuda) | @Sunrisepeak | -| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [rules](docs/10-rules.md#rules-hip) | @Sunrisepeak | -| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [rules](docs/10-rules.md#rules-metal) | @Sunrisepeak | -| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [rules-qt](docs/11-rules-qt.md) | @Sunrisepeak | -| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3;携带 QML 插件库的包 2026.11.23.1 | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [rules-qml](docs/12-rules-qml.md) | @Sunrisepeak | -| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-slang) | @Sunrisepeak | -| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-spirv) | @Sunrisepeak | -| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [rules](docs/10-rules.md#rules-swift) | @Sunrisepeak | -| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [rules](docs/10-rules.md#rules-sycl) | @Sunrisepeak | -| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | 把数据文件写进程序编译内含的头文件。 | [tools-embed](docs/20-tools-embed.md) | @Sunrisepeak | -| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [tools-island](docs/21-tools-island.md) | @Sunrisepeak | -| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [tools-steps](docs/22-tools-steps.md) | @Sunrisepeak | -| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [dist](docs/30-dist.md#dist-appimage) | @Sunrisepeak | -| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | -| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | @Sunrisepeak | -| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [dist](docs/30-dist.md#dist-wix) | @Sunrisepeak | -| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [dist-apple](docs/31-dist-apple.md) | @Sunrisepeak | -| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [dist](docs/30-dist.md#dist-web) | @Sunrisepeak | -| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [dist-apk](docs/32-dist-apk.md) | @Sunrisepeak | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-vcpkg) | @Sunrisepeak | -| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3;交叉构建 2026.10.30.1 | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目——交叉目标时用引擎契约的编译器与措辞;同键的构建复用安装,并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-cmake) | @Sunrisepeak | -| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [deps](docs/40-deps.md#deps-archive) | @Sunrisepeak | - -一些 feature 为成员添加子能力:`dist-apk-kotlin` 与 `dist-apk-maven`(Kotlin -源码、一个 Maven 图),以及 `deps`(deps 成员隐含它)。 - -**通用库。** `plugins-core` 给构建程序 `mcpp.plugins.declare`、 -`mcpp.plugins.toolset`、`mcpp.plugins.fs` 与 `mcpp.plugins.tool`;每个成员都 -隐含它,只用这些模块的构建程序在依赖边上点名它。`plugins-testing`、 -`plugins-toolchain` 与 `plugins-platform` 添加 `mcpp.plugins.testing`、 -`mcpp.plugins.toolchain` 与 `mcpp.plugins.platform`(连同 -`mcpp::plugins::package`);`plugins-progress` 添加可选的 action 遥测及其原子 -快照写入器;`mcpp.plugins.accel` 读取实现自有的目标请求。分层、命名与引擎 +| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [rules](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [rules](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [rules](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [rules](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [rules-qt](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3;携带 QML 插件库的包 2026.11.23.1 | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [rules-qml](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [rules](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [rules](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | 把数据文件写进程序编译内含的头文件。 | [tools-embed](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [tools-island](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [tools-steps](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [dist](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [dist](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [dist-apple](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [dist](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [dist-apk](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3;交叉构建 2026.10.30.1 | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目——交叉目标时用引擎契约的编译器与措辞;同键的构建复用安装,并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [deps](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) | + +一些 feature 添加子能力:`dist-apk-kotlin`、`dist-apk-maven`,以及 deps 成员 +隐含的 `deps`。`plugins-core`——`mcpp.plugins.declare`、 +`mcpp.plugins.toolset`、`mcpp.plugins.fs`、`mcpp.plugins.tool`——是每个成员 +都隐含的通用库;`plugins-testing`、`plugins-toolchain`、 +`plugins-platform` 与 `plugins-progress` 各自添加自己的模块。分层与引擎 下限见 [docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor)。 -`surface`(`plugins-core` 在 0.17.0 之前的名字)保留至 2027-03-28。
-## 布局 - -``` -mcpp.toml 这个包:每个成员一个 feature -src/plugins/ 库根:export module mcpp.plugins(版本、mcpp::plugins::surface、 - mcpp::plugins::xml、mcpp::plugins::package),分区单元在其旁 -src/declare.cppm, 构建程序的通用库(`plugins-core`): -src/toolset.cppm, mcpp.plugins.declare、mcpp.plugins.toolset、mcpp.plugins.fs -src/fs.cppm -src/testing.cppm mcpp.plugins.testing(`plugins-testing`) -src/platform.cppm mcpp.plugins.platform(`plugins-platform`) -src/compat/, deps/compat/ - 兼容单元,各自在其头文件注明的日期退役 -rules/.cppm export module mcpp.rules.; -tools/.cppm export module mcpp.tools.; -dist/.cppm export module mcpp.dist.; -deps/.cppm export module mcpp.deps.; deps/deps.cppm 是共享单元 -// 一个文件装不下的成员:.cppm 保留消费者导入的模块名, - internal/ 承载机制;模块名不变 -tests// 每个成员一个项目,CI 用固定的 mcpp 构建 -docs/ 每个成员或成员组一页([索引](docs/README.md)) -``` - -## 添加一个成员 - -一个成员是:一个模块文件,`mcpp.toml` 里的一个 feature,`tests/` 下一个由 -CI 构建并断言的消费者,上表里带 mcpp 下限的一行,`docs/` 下的一页,以及一次 -版本提升。它的代码是 GCC 加 libstdc++、clang 加 libc++ 与编辑器 clangd 加 -libstdc++ 都接受的 C++23,CI 在三者之下构建或读取每个 fixture。成员遵循的 -约定见 [docs/01](docs/01-plugin-development.md);引擎拥有什么、成员拥有什么 -的划分见 -[docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns)。 +## 贡献与维护 -## 发布 +**维护者。** 本包以及今天每一个成员: +[@Sunrisepeak](https://github.com/Sunrisepeak)。按族的 review 路由: +[`.github/CODEOWNERS`](.github/CODEOWNERS)——新维护者改一行即可接管一个族。 -tag `v<版本号>` 发布源码归档;索引描述符 -(`mcpp-index/pkgs/mcpp/mcpp.plugins.lua`)以同一个 sha256 命名 GitHub 归档 -及其 GitCode 镜像。 +**贡献。** 变更经分支上的 pull request;一个 PR 只做一件事;提交与文字用 +英文。新成员 = 一个模块(长出一个文件时改为目录——[docs/01 +§5](docs/01-plugin-development.md#5-a-new-plugin))、`mcpp.toml` 里的一个 +feature、`tests/` 下一个由 CI 构建并断言的消费者、上表里的一行、`docs/` 下的 +一页、一次版本提升。成员遵循的约定见 +[docs/01](docs/01-plugin-development.md);引擎拥有什么、成员拥有什么的划分 +见 [docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns)。 From 64a8ef02795e37cf53448e1e6b26a1a822aac090 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 16:46:31 +0800 Subject: [PATCH 07/18] Revert "dist-apk, dist-apple and the lib root split to the member-directory form" This reverts commit 05a33579de96aaf51f973007f13c607f3f73dbfc. --- .github/workflows/ci.yml | 12 +- dist/{apk => }/apk.cppm | 908 ++++++++++++++++- dist/apk/internal/libraries.cppm | 232 ----- dist/apk/internal/manifest.cppm | 467 --------- dist/apk/internal/util.cppm | 277 ----- dist/{apple => }/apple.cppm | 385 ++++++- dist/apple/internal/layout.cppm | 91 -- dist/apple/internal/plist.cppm | 236 ----- dist/apple/internal/signing.cppm | 91 -- docs/32-dist-apk.md | 2 +- mcpp.toml | 10 +- segs.json | 1 - src/plugins.cppm | 1645 ++++++++++++++++++++++++++++++ src/plugins/graph.cppm | 98 -- src/plugins/json.cppm | 185 ---- src/plugins/names.cppm | 207 ---- src/plugins/package.cppm | 117 --- src/plugins/plugins.cppm | 61 -- src/plugins/stage.cppm | 48 - src/plugins/surface.cppm | 756 -------------- src/plugins/tree.cppm | 48 - src/plugins/xml.cppm | 169 --- 22 files changed, 2937 insertions(+), 3109 deletions(-) rename dist/{apk => }/apk.cppm (68%) delete mode 100644 dist/apk/internal/libraries.cppm delete mode 100644 dist/apk/internal/manifest.cppm delete mode 100644 dist/apk/internal/util.cppm rename dist/{apple => }/apple.cppm (77%) delete mode 100644 dist/apple/internal/layout.cppm delete mode 100644 dist/apple/internal/plist.cppm delete mode 100644 dist/apple/internal/signing.cppm delete mode 100644 segs.json create mode 100644 src/plugins.cppm delete mode 100644 src/plugins/graph.cppm delete mode 100644 src/plugins/json.cppm delete mode 100644 src/plugins/names.cppm delete mode 100644 src/plugins/package.cppm delete mode 100644 src/plugins/plugins.cppm delete mode 100644 src/plugins/stage.cppm delete mode 100644 src/plugins/surface.cppm delete mode 100644 src/plugins/tree.cppm delete mode 100644 src/plugins/xml.cppm diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0da358e..c378214 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -228,10 +228,10 @@ jobs: - name: the collection states its own version run: | declared=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' mcpp.toml | head -1) - insource=$(sed -n 's/.*version *= *"\(.*\)";.*/\1/p' src/plugins/plugins.cppm | head -1) - echo "mcpp.toml=$declared src/plugins/plugins.cppm=$insource" + insource=$(sed -n 's/.*version *= *"\(.*\)";.*/\1/p' src/plugins.cppm | head -1) + echo "mcpp.toml=$declared src/plugins.cppm=$insource" if [ "$declared" != "$insource" ]; then - echo "FAIL: mcpp.toml says '$declared' and src/plugins/plugins.cppm says '$insource'" + echo "FAIL: mcpp.toml says '$declared' and src/plugins.cppm says '$insource'" exit 1 fi echo "ok: one version, two files agreeing" @@ -266,8 +266,8 @@ jobs: echo "FAIL: a rule or tool defines its own copy of the derivation" grep -n '^inline std::vector namespace_of\|^inline std::string common_base_dir' rules/*.cppm tools/*.cppm exit 1; } - grep -q '^inline std::vector namespace_of' src/plugins/names.cppm - grep -q '^inline std::string common_base_dir' src/plugins/names.cppm + grep -q '^inline std::vector namespace_of' src/plugins.cppm + grep -q '^inline std::string common_base_dir' src/plugins.cppm echo "ok: one definition, in the lib root, for both lanes" - name: rules-spirv through a consumer @@ -2547,7 +2547,7 @@ jobs: # FLAT, NOT Contents/-SHAPED -- the one difference from the macOS # bundle above, and the whole reason iOS needed its own branch in - # `dist/apple/apple.cppm`. + # `dist/apple.cppm`. if [ -d "$app/Contents" ]; then echo "FAIL: the simulator bundle carries Contents/ -- not a flat iOS layout" exit 1 diff --git a/dist/apk/apk.cppm b/dist/apk.cppm similarity index 68% rename from dist/apk/apk.cppm rename to dist/apk.cppm index 0681cdd..5d9f785 100644 --- a/dist/apk/apk.cppm +++ b/dist/apk.cppm @@ -104,10 +104,6 @@ import mcpp.plugins; import mcpp.plugins.tool; import mcpp.tools.steps; -import mcpp.dist.apk.internal.util; -import mcpp.dist.apk.internal.manifest; -import mcpp.dist.apk.internal.libraries; - // `std::format` is header-only and used throughout; `std::println` is not -- // see `rules/spirv.cppm` for the libc++-on-macOS-14 measurement that this // collection's every member has followed since. @@ -333,12 +329,127 @@ struct plan { explicit operator bool() const { return applies; } }; +// ─── Internals ───────────────────────────────────────────────────────────── + +namespace fs = std::filesystem; + +inline bool is_file(const std::string& p) { + std::error_code ec; + return !p.empty() && fs::is_regular_file(p, ec); +} +inline bool is_dir(const std::string& p) { + std::error_code ec; + return !p.empty() && fs::is_directory(p, ec); +} + +// THE HOST, NOT THE TARGET: every tool here runs on the machine that builds. +// A Windows host names its programs `.exe` and separates a class path +// with `;`. +inline bool host_is_windows() { + return std::string_view(mcpp::host()).find("windows") != std::string_view::npos; +} +inline std::string host_program(const fs::path& dir, std::string_view name) { + return (dir / (std::string(name) + (host_is_windows() ? ".exe" : ""))).string(); +} +inline const char* class_path_separator() { return host_is_windows() ? ";" : ":"; } + + +// Is `root` under the package root, `mcpp::manifest_dir()`, and if so, what +// is its manifest-relative form? A project root is declared with +// `rerun_if_changed_glob` below (a file appearing there re-runs the build +// program); a dependency root is not -- its file set changes only with the +// dependency's version, already in the build's fingerprint, and the glob's +// own walk does not reach outside the package root regardless (design +// record §3.3). Same shape as `mcpp.tools.island`'s overlap check: +// `weakly_canonical` plus `lexically_relative`, never the iterator that +// poisons an importer under GCC 16 / MSVC (`mcpp::plugins::names:: +// relative_to`'s own header) -- safe here because this member is its own +// module and imports no sibling that would inherit the instantiation. +// +// THE RETURNED PATH IS MANIFEST-RELATIVE, NOT ABSOLUTE, BECAUSE THE GLOB +// PATTERN MUST BE. The engine matches a glob by comparing the CANDIDATE made +// relative to the package root against the pattern +// (`modules/manifest/src/glob.cppm`, `path_matches_glob`); an absolute +// pattern is compared against a relative candidate and never matches +// anything, so the fingerprint is always the empty set and a `.java` file +// appearing never changes it -- the criterion's "no" reading as silence +// (design record, rule 8). `opt.java_sources`'s own roots are absolute +// (`mcpp::manifest_dir()` composed with a subdirectory), so declaring the +// glob with `root` itself, not this function's return value, was exactly +// that defect. +// +// A root inside the build's output -- `mcpp::out_dir()`, or a directory the +// glob walk never enters (`target`, `.mcpp`, `.git`) -- is GENERATED: the +// build program that writes its files already runs on every build, and a glob +// there can never match anything, which the engine reports as a warning. It is +// answered as outside the project, so it is an action input and no glob. +inline std::optional root_in_project(const std::string& root) { + std::error_code ec; + const auto a = fs::weakly_canonical(root, ec); + if (ec) return std::nullopt; + const auto b = fs::weakly_canonical(mcpp::manifest_dir(), ec); + if (ec) return std::nullopt; + const auto rel = a.lexically_relative(b).generic_string(); + if (rel.empty() || rel.starts_with("..")) return std::nullopt; + const auto out = fs::weakly_canonical(std::string(mcpp::out_dir()), ec); + if (!ec) { + const auto inside = a.lexically_relative(out).generic_string(); + if (!inside.empty() && !inside.starts_with("..")) return std::nullopt; + } + const auto first = rel.substr(0, rel.find('/')); + if (first == "target" || first == ".mcpp" || first == ".git") return std::nullopt; + return rel; +} + +inline bool write_if_different(const fs::path& path, std::string_view bytes) { + std::error_code ec; + fs::create_directories(path.parent_path(), ec); + if (std::ifstream in(path, std::ios::binary); in) { + std::string old((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + if (old == bytes) return true; + } + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(bytes.data(), static_cast(bytes.size())); + return static_cast(out); +} + inline std::string target_for(const options& opt) { if (!opt.target.empty()) return opt.target; const char* n = mcpp::package_name(); return (n && *n) ? std::string(n) : std::string(); } +// `/`, from the row's arch and no other input -- see `artifact_naming` +// for the engine's own row-decides-the-name principle, applied here to +// Android's own ABI vocabulary rather than a file suffix. +inline std::string abi_for() { + const std::string a = mcpp::target_arch(); + if (a == "aarch64") return "arm64-v8a"; + if (a == "x86_64") return "x86_64"; + return {}; +} + +// Index loop, not a range-for: GCC 16.1.0 refuses to inline +// `__normal_iterator>::operator*() const` when a +// module interface unit that imports `std` also range-for's (or otherwise +// takes `basic_string`'s own iterator over) a `std::string` or +// `std::filesystem::path` -- +// +// bits/stl_iterator.h:1089:7: error: inlining failed in call to +// 'always_inline' '... operator*() const' +// +// -- the same family of defect #18 met under MSVC's `_Path_iterator` (see +// `mcpp::plugins::names::relative_to` and `components()` in +// `src/plugins.cppm`), here on `libstdc++`'s `basic_string` iterator instead +// of the filesystem one. `s[i]` indexes the string directly and never forms +// that iterator, so it compiles under both. +inline std::string replace_dashes(std::string s) { + for (std::size_t i = 0; i < s.size(); ++i) if (s[i] == '-') s[i] = '_'; + return s; +} + inline std::string application_id_for(const options& opt, const std::string& target) { if (!opt.application_id.empty()) return opt.application_id; const char* ns = mcpp::package_namespace(); @@ -354,6 +465,757 @@ inline std::string label_for(const options& opt) { return (n && *n) ? std::string(n) : std::string("app"); } +// `xim:android-platform`'s own resolved directory is named after the +// version it resolved -- "36-r2", "35-r2", "34-r3" (`pkgs/a/android- +// platform.lua`'s own `extract_dir()` recovers the API level the identical +// way, from the leading digits of its OWN version string) -- so the level a +// project pinned is read back from the directory `xpkg_dir` already +// answered, rather than duplicated as a second option this member could +// disagree with. +inline std::string api_level_from_platform_dir(const std::string& dir) { + if (dir.empty()) return {}; + const std::string leaf = fs::path(dir).filename().string(); + std::string digits; + for (std::size_t i = 0; i < leaf.size(); ++i) { + if (leaf[i] >= '0' && leaf[i] <= '9') digits += leaf[i]; + else break; + } + return digits; +} + +inline std::string replace_all_copy(std::string s, std::string_view from, std::string_view to) { + if (from.empty()) return s; + std::size_t pos = 0; + while ((pos = s.find(from, pos)) != std::string::npos) { + s.replace(pos, from.size(), to); + pos += to.size(); + } + return s; +} + +// The eight tokens a manifest template may use. `version_name` is the +// package version as written; `version_code` is Android's monotonic integer +// derived from its leading numeric segments (`version_code_for`). +inline const std::vector& manifest_tokens() { + static const std::vector v = { + "application_id", "label", "activity", "lib_name", "min_sdk", "target_sdk", + "version_name", "version_code"}; + return v; +} + +// `android:versionCode` from a version string: major * 1000000 + minor * 1000 +// + patch over the first three dot-separated numeric segments, so that every +// release a project cuts orders after the one before it, and "1" when the +// string starts with no number at all -- Android refuses 0 and a manifest +// without the attribute installs but never updates. +inline std::string version_code_for(const std::string& version) { + long long code = 0, seg = 0; + int segments = 0; + bool digits = false; + const long long weights[3] = {1000000, 1000, 1}; + for (std::size_t i = 0; i <= version.size() && segments < 3; ++i) { + const char c = i < version.size() ? version[i] : '\0'; + if (c >= '0' && c <= '9') { seg = seg * 10 + (c - '0'); digits = true; continue; } + if (!digits) break; + code += std::min(seg, 999) * weights[segments] ; + ++segments; seg = 0; digits = false; + if (c != '.') break; + } + if (segments == 0) return "1"; + if (code <= 0) return "1"; + return std::to_string(code); +} + +// Every `{{...}}` a template names, in first-appearance order, duplicates +// dropped -- what both checks in `render_manifest` below read. +inline std::vector tokens_in(const std::string& text) { + std::vector out; + std::size_t i = 0; + while ((i = text.find("{{", i)) != std::string::npos) { + const auto close = text.find("}}", i + 2); + if (close == std::string::npos) break; + std::string name = text.substr(i + 2, close - (i + 2)); + if (std::ranges::find(out, name) == out.end()) out.push_back(std::move(name)); + i = close + 2; + } + return out; +} + +// The tokens `assets/mcpp-run.json` is ALSO written from -- a template that +// omits one silently ships a run sidecar the manifest disagrees with. +// `application_id` and `activity` are required unconditionally; `lib_name` +// joins them at level 0, where the manifest's own `` element is +// the only place the loaded library's name is recorded. +inline std::vector required_manifest_tokens(bool has_code, bool native_activity) { + static_cast(has_code); + std::vector v = {"application_id", "activity"}; + if (native_activity) v.push_back("lib_name"); + return v; +} +inline std::vector required_manifest_tokens(bool has_code) { + return required_manifest_tokens(has_code, !has_code); +} + +// THE BUILT-IN DEFAULT, EXPRESSED WITH THE TOKENS. This is `manifest_xml`'s +// 0.8.0 output verbatim, with every literal value it used to compute +// replaced by the token that value now comes through -- so level 0 with no +// project template renders byte-identical to what 0.8.0 wrote +// (`tests/apk-consumer`). `{{activity}}` carries the level-0 constant +// (`android.app.NativeActivity`) as well as a level-1 project's own class, +// because the run sidecar needs the activity name at both levels and the +// required-token check reads the TEMPLATE TEXT, not the level -- so the same +// token has to appear on both of this function's two branches. +// `{{lib_name}}`'s `` element exists only at level 0: it +// announces which shared object `NativeActivity` should load, and a +// Java-hosted activity finds its own native library another way. +// +// NO XML COMMENT MARKS THE THREE REQUIRED TOKENS IN THIS STRING, ON PURPOSE: +// this exact text is compared byte-for-byte against 0.8.0's output, which +// carried none, and a template with no author to read a comment gains +// nothing from one. The design record's "mark the required tokens" is done +// here instead, in the `REQUIRED` labels on the C++ lines that build them. +// A NATIVE ACTIVITY MAY STILL CARRY CODE (0.11.0): a level-0 application whose +// libraries or archives bring classes keeps `android.app.NativeActivity` and its +// `lib_name` element, with `android:hasCode="true"` so that the dex is loaded. +inline std::string default_manifest_template(bool has_code, bool native_activity) { + std::string a = + "\n" + "\n" // REQUIRED + " \n" + " \n" + " \n"; + if (native_activity) { + a += " \n"; // REQUIRED at level 0 + } + a += " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"; + return a; +} +inline std::string default_manifest_template(bool has_code) { + return default_manifest_template(has_code, !has_code); +} + +// Checks a manifest template and substitutes it, or refuses (returning +// `false` with `reason` and `message` set) naming exactly what is wrong; the +// caller reports `message` (see `refuse`). +// +// THIS CHECK IS `dist-apk`'S OWN, DELIBERATELY NOT `dist-web`'S. A manifest +// has a closed, six-token vocabulary this member itself defines; a web page +// template may legitimately carry `{{ }}` for a front-end framework (Vue, +// Mustache, ...) this member never reads, so `dist-web` leaves an unknown +// token literal for that project's own tooling to read. An unknown token +// here would otherwise reach `aapt2` unsubstituted and fail there with a +// worse message, and the refusal belongs where the name is known -- the same +// rule read against two different facts, not an inconsistency between the +// two members. +inline bool render_manifest(const std::string& templateText, bool has_code, bool native_activity, + const std::string& appId, const std::string& label, + const std::string& activityName, const std::string& libName, + const std::string& minSdk, const std::string& targetSdk, + const std::string& versionName, const std::string& versionCode, + std::string& out, std::string& reason, + std::string& message) { + for (auto const& tok : tokens_in(templateText)) { + if (std::ranges::find(manifest_tokens(), tok) == manifest_tokens().end()) { + message = "mcpp.dist.apk: the manifest template names an unknown " + "token '{{" + tok + "}}'; expected one of application_id, " + "label, activity, lib_name, min_sdk, target_sdk, " + "version_name, version_code."; + reason = "unknown manifest template token '" + tok + "'"; + return false; + } + } + for (auto const& tok : required_manifest_tokens(has_code, native_activity)) { + if (templateText.find("{{" + tok + "}}") == std::string::npos) { + message = "mcpp.dist.apk: the manifest template does not use '{{" + tok + + "}}', and assets/mcpp-run.json, which adb-run starts the " + "application from, is written from the same value: add {{" + + tok + "}} to the template."; + reason = "manifest template missing required token '" + tok + "'"; + return false; + } + } + out = templateText; + out = replace_all_copy(std::move(out), "{{application_id}}", appId); + out = replace_all_copy(std::move(out), "{{label}}", label); + out = replace_all_copy(std::move(out), "{{activity}}", activityName); + out = replace_all_copy(std::move(out), "{{lib_name}}", libName); + out = replace_all_copy(std::move(out), "{{min_sdk}}", minSdk); + out = replace_all_copy(std::move(out), "{{target_sdk}}", targetSdk); + out = replace_all_copy(std::move(out), "{{version_name}}", versionName); + out = replace_all_copy(std::move(out), "{{version_code}}", versionCode); + return true; +} +inline bool render_manifest(const std::string& templateText, bool has_code, + const std::string& appId, const std::string& label, + const std::string& activityName, const std::string& libName, + const std::string& minSdk, const std::string& targetSdk, + const std::string& versionName, const std::string& versionCode, + std::string& out, std::string& reason, + std::string& message) { + return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName, + minSdk, targetSdk, versionName, versionCode, out, reason, message); +} + +inline std::string run_json(const std::string& app_id, const std::string& activity_name) { + // Hand-built, not through a JSON library this collection does not + // depend on: two string fields, neither of which this member lets + // through unescaped input (`app_id` is derived from the package's own + // identifiers, `activity_name` is a Java class name or the literal + // `android.app.NativeActivity`). + return std::format("{{\"package\": \"{}\", \"activity\": \"{}\"}}\n", + app_id, activity_name); +} + +// Copies `src` (a file or a directory, recursively) into `dstRoot/relName`, +// listing every regular file it wrote -- so the caller can declare each one +// as an action input rather than the directory itself ("name the input; do +// not harvest a directory", docs/31). +inline void collect_tree(const fs::path& src, const fs::path& dst, + std::vector& out) { + std::error_code ec; + if (fs::is_regular_file(src, ec)) { + fs::create_directories(dst.parent_path(), ec); + fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec); + out.push_back(dst.string()); + return; + } + for (auto& e : fs::recursive_directory_iterator(src, ec)) { + if (ec) break; + if (!e.is_regular_file(ec)) continue; + auto rel = fs::relative(e.path(), src, ec); + auto to = dst / rel; + fs::create_directories(to.parent_path(), ec); + fs::copy_file(e.path(), to, fs::copy_options::overwrite_existing, ec); + out.push_back(to.string()); + } +} + +namespace xml = mcpp::plugins::xml; + +// ─── Paths a project names ───────────────────────────────────────────────── + +// A project names its directories relative to its manifest; the actions this +// member declares run later, from the build directory, where a relative path +// names nothing (the defect `dist/apple.cppm` measured with `ditto ios-icons`). +// Every path option is therefore resolved here, once, against +// `mcpp::manifest_dir()`; an absolute path is left alone. +inline std::string resolve_path(const std::string& p) { + if (p.empty()) return p; + const fs::path path(p); + if (path.is_absolute()) return p; + return (fs::path(mcpp::manifest_dir()) / path).lexically_normal().string(); +} + +inline void resolve_paths(std::vector& v) { + for (auto& p : v) p = resolve_path(p); +} + +// Every regular file under `root` whose extension is `ext`, sorted. +inline std::vector files_with_extension(const std::string& root, std::string_view ext) { + std::vector out; + std::error_code ec; + for (auto& e : fs::recursive_directory_iterator(root, ec)) { + if (ec) break; + if (e.is_regular_file(ec) && e.path().extension() == ext) + out.push_back(e.path().string()); + } + std::ranges::sort(out); + return out; +} + +inline bool dir_has_files(const std::string& root) { + std::error_code ec; + for (auto& e : fs::recursive_directory_iterator(root, ec)) { + if (ec) break; + if (e.is_regular_file(ec)) return true; + } + return false; +} + +inline std::string read_file(const std::string& path) { + std::ifstream in(path, std::ios::binary); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +inline std::string join(const std::vector& v, std::string_view sep) { + std::string out; + for (std::size_t i = 0; i < v.size(); ++i) { + if (i) out += sep; + out += v[i]; + } + return out; +} + +// ─── SHA-256 ─────────────────────────────────────────────────────────────── + +// FIPS 180-4, over bytes held in memory. Here for one purpose: a Maven lock +// records each artifact's digest, and a build that reads a cached artifact +// checks it against the lock before the file reaches a package. The inputs are +// libraries of a few megabytes, so reading a file whole is the simple choice. +inline std::string sha256_hex(std::string_view data) { + static constexpr std::uint32_t k[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + std::string msg(data); + const std::uint64_t bits = static_cast(data.size()) * 8u; + msg.push_back(static_cast(0x80)); + while (msg.size() % 64 != 56) msg.push_back('\0'); + for (int i = 7; i >= 0; --i) msg.push_back(static_cast((bits >> (i * 8)) & 0xffu)); + const auto rotr = [](std::uint32_t x, int n) -> std::uint32_t { return (x >> n) | (x << (32 - n)); }; + for (std::size_t off = 0; off < msg.size(); off += 64) { + std::uint32_t w[64]; + for (int i = 0; i < 16; ++i) { + const auto byte = [&](int j) { + return static_cast(static_cast(msg[off + static_cast(i * 4 + j)])); + }; + w[i] = (byte(0) << 24) | (byte(1) << 16) | (byte(2) << 8) | byte(3); + } + for (int i = 16; i < 64; ++i) { + const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (int i = 0; i < 64; ++i) { + const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i]; + const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + std::string hex; + hex.reserve(64); + for (int i = 0; i < 8; ++i) hex += std::format("{:08x}", h[i]); + return hex; +} + +inline std::string sha256_file(const std::string& path) { + return is_file(path) ? sha256_hex(read_file(path)) : std::string(); +} + +// ─── Running a tool at plan time ───────────────────────────────────────── + +// Runs `argv`, returning its exit status and its combined output, through +// `mcpp::plugins::tool::capture`: no shell between, so no argument is quoted. +// Only the explicit Maven modes and AAR extraction call it; an ordinary build +// of an unchanged project runs nothing here. +int run_capture(const std::vector& argv, std::string& output, + const std::filesystem::path& cwd = {}) { + auto r = mcpp::plugins::tool::capture(argv, /*with_errors=*/true, cwd); + output = std::move(r.out); + return r.status; +} + +// ─── Merging library manifests into the application's ──────────────────── + +// What `mcpp.dist.apk` merges, and the rules it applies. This is a SUBSET of +// the Android Gradle plugin's manifest merger, stated rather than implied: +// +// - ``, ``, ``, +// `` and the other children of `` are added when +// the application has no element of the same kind and `android:name`; +// `` children are unioned; +// - the children of a library's `` -- activities, aliases, +// services, receivers, providers, ``, `` -- are +// added the same way; a library's `` attribute the +// application does not state is added; +// - an identical element is not added twice; a DIFFERENT element under the +// same name is refused, naming it, unless the application's own element +// says `tools:node="replace"` (the application's wins) or +// `tools:node="remove"` (neither is kept); a differing `` +// attribute is refused unless the application lists it in `tools:replace`; +// - a library's `` above the application's +// floor is refused, as Gradle refuses it; +// - `${applicationId}` is substituted everywhere, and any other `${...}` +// placeholder is refused, naming it -- no placeholder source exists here; +// - every `tools:` attribute and the `xmlns:tools` declaration are removed +// from the result. +// +// Anything a project needs beyond that is stated in its own manifest template, +// which this member never edits except to add what the libraries declare. +struct manifest_source { + std::string label; // what a refusal names: a library, an AAR, a coordinate + std::string text; +}; + +inline std::string manifest_key(const xml::node& n) { + if (n.name == "uses-feature") { + const std::string nm = xml::attr_of(n, "android:name"); + return nm.empty() ? "uses-feature@glEsVersion=" + xml::attr_of(n, "android:glEsVersion") + : "uses-feature:" + nm; + } + return n.name + ":" + xml::attr_of(n, "android:name"); +} + +inline void strip_tools(xml::node& n) { + std::erase_if(n.attrs, [](const std::pair& a) { + return a.first.starts_with("tools:") || a.first == "xmlns:tools"; + }); + for (auto& c : n.children) strip_tools(c); +} + +inline std::string canonical_xml(xml::node n) { + strip_tools(n); + std::string out; + xml::write(n, out, 0); + return out; +} + +inline bool substitute_placeholders(xml::node& n, const std::string& appId, + const std::string& label, std::string& message) { + for (auto& a : n.attrs) { + a.second = replace_all_copy(a.second, "${applicationId}", appId); + const auto p = a.second.find("${"); + if (p != std::string::npos) { + const auto e = a.second.find('}', p); + message = std::format( + "mcpp.dist.apk: {} uses the manifest placeholder '{}' in {}=\"{}\"; " + "only ${{applicationId}} is substituted here.", label, + a.second.substr(p, e == std::string::npos ? std::string::npos : e - p + 1), + a.first, a.second); + return false; + } + } + for (auto& c : n.children) + if (!substitute_placeholders(c, appId, label, message)) return false; + return true; +} + +inline xml::node* find_child(xml::node& parent, std::string_view name) { + for (auto& c : parent.children) if (c.name == name) return &c; + return nullptr; +} + +// Removes every element the application marked `tools:node="remove"`: a marker +// that says "this is not wanted", not an element to ship. +inline void drop_removed(xml::node& n) { + std::erase_if(n.children, [](const xml::node& c) { return xml::attr_of(c, "tools:node") == "remove"; }); + for (auto& c : n.children) drop_removed(c); +} + +inline bool merge_manifests(std::string& appText, const std::vector& libs, + const std::string& appId, const std::string& minSdk, + std::string& reason, std::string& message) { + xml::node app; + std::string err; + if (!xml::parse(appText, app, err) || app.name != "manifest") { + reason = "the application manifest cannot be read"; + message = "mcpp.dist.apk: the application's manifest cannot be read for merging: " + + (err.empty() ? std::string("its root element is not ") : err); + return false; + } + if (!substitute_placeholders(app, appId, "the application's manifest", message)) { + reason = "unknown manifest placeholder"; + return false; + } + xml::node* application = find_child(app, "application"); + if (!application) { + app.children.push_back(xml::node{"application", {}, {}, {}}); + application = &app.children.back(); + } + const auto parse_number = [](const std::string& s) { + long v = 0; + for (std::size_t i = 0; i < s.size(); ++i) { + if (s[i] < '0' || s[i] > '9') return -1L; + v = v * 10 + (s[i] - '0'); + } + return s.empty() ? -1L : v; + }; + + for (auto const& lib : libs) { + xml::node m; + if (!xml::parse(lib.text, m, err) || m.name != "manifest") { + reason = "a library manifest cannot be read"; + message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", lib.label, + err.empty() ? std::string("its root element is not ") : err); + return false; + } + if (!substitute_placeholders(m, appId, lib.label, message)) { + reason = "unknown manifest placeholder"; + return false; + } + for (auto& c : m.children) { + if (c.name.empty()) continue; + if (c.name == "uses-sdk") { + const long want = parse_number(xml::attr_of(c, "android:minSdkVersion")); + const long have = parse_number(minSdk); + if (want > 0 && have > 0 && want > have) { + reason = "a library needs a higher minSdkVersion"; + message = std::format( + "mcpp.dist.apk: {} declares android:minSdkVersion {}, above this " + "application's floor {}. Raise the row's min_api_level, or do not " + "depend on it.", lib.label, want, have); + return false; + } + continue; + } + if (c.name == "application") { + const std::string replaced = xml::attr_of(*application, "tools:replace"); + for (auto const& a : c.attrs) { + if (a.first.starts_with("tools:")) continue; + const std::string mine = xml::attr_of(*application, a.first); + if (mine.empty()) { xml::set_attr(*application, a.first, a.second); continue; } + if (mine == a.second) continue; + bool listed = false; + std::size_t start = 0; + while (start <= replaced.size()) { + auto comma = replaced.find(',', start); + if (comma == std::string::npos) comma = replaced.size(); + if (xml::trim_copy(replaced.substr(start, comma - start)) == a.first) { listed = true; break; } + start = comma + 1; + } + if (!listed) { + reason = "conflicting attribute"; + message = std::format( + "mcpp.dist.apk: is \"{}\" in the application and " + "\"{}\" in {}. Add tools:replace=\"{}\" to the application's " + " to keep its value.", a.first, mine, a.second, lib.label, a.first); + return false; + } + } + for (auto& cc : c.children) { + if (cc.name.empty()) continue; + const std::string key = manifest_key(cc); + xml::node* mine = nullptr; + for (auto& x : application->children) + if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } + if (!mine) { application->children.push_back(cc); continue; } + const std::string node = xml::attr_of(*mine, "tools:node"); + if (node == "remove" || node == "replace") continue; + if (canonical_xml(*mine) == canonical_xml(cc)) continue; + reason = "conflicting manifest element"; + message = std::format( + "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application " + "and {}. State tools:node=\"replace\" on the application's element to keep " + "it, or tools:node=\"remove\" to drop both.", cc.name, + xml::attr_of(cc, "android:name"), lib.label); + return false; + } + continue; + } + if (c.name == "queries") { + xml::node* q = find_child(app, "queries"); + if (!q) { + auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); + q = &*app.children.insert(pos, xml::node{"queries", {}, {}, {}}); + application = find_child(app, "application"); + } + for (auto& qc : c.children) { + if (qc.name.empty()) continue; + const std::string canon = canonical_xml(qc); + const bool present = std::ranges::any_of(q->children, [&](const xml::node& x) { + return canonical_xml(x) == canon; + }); + if (!present) q->children.push_back(qc); + } + continue; + } + const std::string key = manifest_key(c); + xml::node* mine = nullptr; + for (auto& x : app.children) + if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } + if (mine) { + const std::string node = xml::attr_of(*mine, "tools:node"); + if (node == "remove" || node == "replace") continue; + if (canonical_xml(*mine) == canonical_xml(c)) continue; + reason = "conflicting manifest element"; + message = std::format( + "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application and " + "{}. State tools:node=\"replace\" on the application's element to keep it, or " + "tools:node=\"remove\" to drop both.", c.name, xml::attr_of(c, "android:name"), lib.label); + return false; + } + auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); + app.children.insert(pos, c); + application = find_child(app, "application"); + } + } + + drop_removed(app); + strip_tools(app); + appText = "\n"; + xml::write(app, appText, 0); + return true; +} + +// ─── JSON ───────────────────────────────────────────────────────────────── +// +// coursier's report is read with the collection's shared reader, the one +// `mcpp::plugins::graph` reads the engine's graph document with. +using json_value = mcpp::plugins::json::value; +using mcpp::plugins::json::parse_json; + +// ─── The Maven lock ─────────────────────────────────────────────────────── + +// One line per fact, sorted, so that a diff of a lock says what changed: +// +// request what the project asked for +// repository where resolution looked, in order +// artifact +// +// `` is relative to the cache root, which is where coursier keeps the +// file under `//` (`--cache` is always passed, so the root +// this member computes and the one coursier writes to are the same directory). +struct maven_artifact { + std::string coordinate; + std::string type; + std::string path; + std::string sha256; +}; + +struct maven_lock { + bool found = false; + std::vector requests; + std::vector repositories; + std::vector artifacts; +}; + +inline maven_lock read_maven_lock(const std::string& path) { + maven_lock lock; + if (!is_file(path)) return lock; + lock.found = true; + std::istringstream in(read_file(path)); + std::string line; + while (std::getline(in, line)) { + if (line.empty() || line[0] == '#') continue; + std::istringstream fields(line); + std::string kind; + fields >> kind; + if (kind == "request") { std::string v; fields >> v; lock.requests.push_back(v); } + else if (kind == "repository") { std::string v; fields >> v; lock.repositories.push_back(v); } + else if (kind == "artifact") { + maven_artifact a; + fields >> a.coordinate >> a.type >> a.path >> a.sha256; + lock.artifacts.push_back(std::move(a)); + } + } + return lock; +} + +inline std::string render_maven_lock(const maven_lock& lock) { + std::string out = + "# mcpp.dist.apk Maven lock. Written by MCPP_DIST_APK_MAVEN=update; commit it.\n" + "# An ordinary build reads only these artifacts, from the cache, and checks each digest.\n"; + for (auto const& r : lock.requests) out += "request " + r + "\n"; + for (auto const& r : lock.repositories) out += "repository " + r + "\n"; + for (auto const& a : lock.artifacts) + out += "artifact " + a.coordinate + " " + a.type + " " + a.path + " " + a.sha256 + "\n"; + return out; +} + +// Where coursier's cache is: the option, then `COURSIER_CACHE`, then coursier's +// own default on this host, so a developer's `cs` and this member share one. +inline std::string maven_cache_root(const std::string& option) { + if (!option.empty()) return option; + if (const char* env = std::getenv("COURSIER_CACHE"); env && *env) return env; + const char* home = std::getenv("HOME"); + const std::string h = home ? home : ""; + if (std::string(mcpp::host()).find("apple") != std::string::npos || + std::string(mcpp::host()).find("macos") != std::string::npos) + return h + "/Library/Caches/Coursier/v1"; + if (const char* xdg = std::getenv("XDG_CACHE_HOME"); xdg && *xdg) return std::string(xdg) + "/coursier/v1"; + return h + "/.cache/coursier/v1"; +} + +// `group:artifact:version`, three non-empty parts and a fixed version: a range +// would make the lock the only place the version is decided. +inline bool plain_coordinate(const std::string& c) { + int colons = 0; + for (std::size_t i = 0; i < c.size(); ++i) { + if (c[i] == ':') ++colons; + if (c[i] == '[' || c[i] == '(' || c[i] == ',' || c[i] == '+' || c[i] == ' ') return false; + } + return colons == 2 && !c.starts_with(":") && !c.ends_with(":") && c.find("::") == std::string::npos; +} + +// coursier names an AAR-packaged module `group:artifact:aar:version`; the lock +// records the coordinate a project writes. +inline std::string plain_form(const std::string& coord) { + return replace_all_copy(coord, ":aar:", ":"); +} + +// ─── An AAR, unpacked ───────────────────────────────────────────────────── + +// What an Android library archive contributes: its manifest (merged), its +// `res/` (linked under its own package), its classes (`classes.jar`, and any +// `libs/*.jar` it carries), its native libraries (`jni//`) and its +// `assets/`. `R.txt`, `proguard.txt`, `lint.jar` and `public.txt` are not +// read: this member does not shrink, lint or compute non-transitive R classes. +struct library_input { + std::string label; + std::string package; + std::string resources; + std::string manifest; + std::string assets; + std::string jni; + std::vector java; + std::vector kotlin; + std::vector jars; +}; + +// Unpacked with the JDK's `jar` at plan time, once per archive content: a stamp +// beside the tree records the archive's digest, and a matching stamp skips the +// work on the next plan. +inline bool unpack_aar(const std::string& aar, const fs::path& dest, const std::string& jarTool, + library_input& out, std::string& message) { + const std::string digest = sha256_file(aar); + if (digest.empty()) { + message = std::format("mcpp.dist.apk: the AAR {} was not found.", aar); + return false; + } + const fs::path stamp = dest / ".mcpp-aar-sha256"; + if (read_file(stamp.string()) != digest) { + std::error_code ec; + fs::remove_all(dest, ec); + fs::create_directories(dest, ec); + std::string output; + const int rc = run_capture({jarTool, "xf", aar}, output, dest); + if (rc != 0) { + message = std::format("mcpp.dist.apk: unpacking {} with {} failed ({}): {}", aar, jarTool, rc, output); + return false; + } + write_if_different(stamp, digest); + } + const std::string manifest = (dest / "AndroidManifest.xml").string(); + if (!is_file(manifest)) { + message = std::format("mcpp.dist.apk: {} carries no AndroidManifest.xml, so it is not an AAR.", aar); + return false; + } + xml::node m; + std::string err; + if (!xml::parse(read_file(manifest), m, err) || m.name != "manifest") { + message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", aar, err); + return false; + } + out.package = xml::attr_of(m, "package"); + out.manifest = manifest; + if (is_dir((dest / "res").string()) && dir_has_files((dest / "res").string())) out.resources = (dest / "res").string(); + if (is_dir((dest / "assets").string()) && dir_has_files((dest / "assets").string())) out.assets = (dest / "assets").string(); + if (is_dir((dest / "jni").string())) out.jni = (dest / "jni").string(); + if (is_file((dest / "classes.jar").string())) out.jars.push_back((dest / "classes.jar").string()); + for (auto const& j : files_with_extension((dest / "libs").string(), ".jar")) out.jars.push_back(j); + return true; +} + // ─── The staged tree ─────────────────────────────────────────────────────── // Records a refusal three ways, because each reaches a different reader. The @@ -407,6 +1269,43 @@ inline plan& refuse(plan& p, std::string reason, const std::string& message) { return p; } +// Android's own ABI names, the directory names a several-triple tree stages +// under (`lib//`) and an APK stores its native libraries under. +inline bool is_android_abi(std::string_view name) { + return name == "arm64-v8a" || name == "x86_64" || name == "armeabi-v7a" || name == "x86"; +} + +// One ABI's native libraries, as the staged tree carries them. +struct native_leg { + std::string abi; + std::vector libraries; // absolute paths, sorted +}; + +inline std::vector shared_objects_in(const fs::path& dir) { + std::vector out; + std::error_code ec; + for (auto& e : fs::directory_iterator(dir, ec)) { + if (ec) break; + if (e.is_regular_file(ec) && e.path().extension() == ".so") + out.push_back(e.path().string()); + } + std::ranges::sort(out); + return out; +} + +// Does the manifest ask for the native libraries to be loaded from the APK in +// place (``, 0.11.1)? The +// platform can map a library only from an entry stored uncompressed on a page +// boundary, so such a package is laid out that way; a compressed library in it +// fails to install. +inline bool loads_native_libraries_in_place(const std::string& manifest) { + xml::node root; + std::string error; + if (!xml::parse(manifest, root, error) || root.name != "manifest") return false; + const xml::node* application = find_child(root, "application"); + return application && xml::attr_of(*application, "android:extractNativeLibs") == "false"; +} + // ─── Plan ────────────────────────────────────────────────────────────────── inline plan plan_for(options opt = {}) { @@ -1827,4 +2726,3 @@ inline bool generate(options opt = {}) { } } // namespace mcpp::dist::apk - diff --git a/dist/apk/internal/libraries.cppm b/dist/apk/internal/libraries.cppm deleted file mode 100644 index ce34e7d..0000000 --- a/dist/apk/internal/libraries.cppm +++ /dev/null @@ -1,232 +0,0 @@ -// mcpp.dist.apk.internal.libraries -- digests, the Maven lock and AAR unpacking. - -export module mcpp.dist.apk.internal.libraries; - -import std; -import mcpp; -import mcpp.plugins; -import mcpp.dist.apk.internal.util; - -namespace mcpp::dist::apk { - -inline std::string sha256_hex(std::string_view data); - -inline std::string sha256_file(const std::string& path) { - return is_file(path) ? sha256_hex(read_file(path)) : std::string(); -} - -// ─── JSON ───────────────────────────────────────────────────────────────── -// -// coursier's report is read with the collection's shared reader, the one -// `mcpp::plugins::graph` reads the engine's graph document with. -using json_value = mcpp::plugins::json::value; -using mcpp::plugins::json::parse_json; - -// ─── The Maven lock ─────────────────────────────────────────────────────── - -// One line per fact, sorted, so that a diff of a lock says what changed: -// -// request what the project asked for -// repository where resolution looked, in order -// artifact -// -// `` is relative to the cache root, which is where coursier keeps the -// file under `//` (`--cache` is always passed, so the root -// this member computes and the one coursier writes to are the same directory). -struct maven_artifact { - std::string coordinate; - std::string type; - std::string path; - std::string sha256; -}; - -struct maven_lock { - bool found = false; - std::vector requests; - std::vector repositories; - std::vector artifacts; -}; - -inline maven_lock read_maven_lock(const std::string& path) { - maven_lock lock; - if (!is_file(path)) return lock; - lock.found = true; - std::istringstream in(read_file(path)); - std::string line; - while (std::getline(in, line)) { - if (line.empty() || line[0] == '#') continue; - std::istringstream fields(line); - std::string kind; - fields >> kind; - if (kind == "request") { std::string v; fields >> v; lock.requests.push_back(v); } - else if (kind == "repository") { std::string v; fields >> v; lock.repositories.push_back(v); } - else if (kind == "artifact") { - maven_artifact a; - fields >> a.coordinate >> a.type >> a.path >> a.sha256; - lock.artifacts.push_back(std::move(a)); - } - } - return lock; -} - -inline std::string render_maven_lock(const maven_lock& lock) { - std::string out = - "# mcpp.dist.apk Maven lock. Written by MCPP_DIST_APK_MAVEN=update; commit it.\n" - "# An ordinary build reads only these artifacts, from the cache, and checks each digest.\n"; - for (auto const& r : lock.requests) out += "request " + r + "\n"; - for (auto const& r : lock.repositories) out += "repository " + r + "\n"; - for (auto const& a : lock.artifacts) - out += "artifact " + a.coordinate + " " + a.type + " " + a.path + " " + a.sha256 + "\n"; - return out; -} - -// Where coursier's cache is: the option, then `COURSIER_CACHE`, then coursier's -// own default on this host, so a developer's `cs` and this member share one. -inline std::string maven_cache_root(const std::string& option) { - if (!option.empty()) return option; - if (const char* env = std::getenv("COURSIER_CACHE"); env && *env) return env; - const char* home = std::getenv("HOME"); - const std::string h = home ? home : ""; - if (std::string(mcpp::host()).find("apple") != std::string::npos || - std::string(mcpp::host()).find("macos") != std::string::npos) - return h + "/Library/Caches/Coursier/v1"; - if (const char* xdg = std::getenv("XDG_CACHE_HOME"); xdg && *xdg) return std::string(xdg) + "/coursier/v1"; - return h + "/.cache/coursier/v1"; -} - -// `group:artifact:version`, three non-empty parts and a fixed version: a range -// would make the lock the only place the version is decided. -inline bool plain_coordinate(const std::string& c) { - int colons = 0; - for (std::size_t i = 0; i < c.size(); ++i) { - if (c[i] == ':') ++colons; - if (c[i] == '[' || c[i] == '(' || c[i] == ',' || c[i] == '+' || c[i] == ' ') return false; - } - return colons == 2 && !c.starts_with(":") && !c.ends_with(":") && c.find("::") == std::string::npos; -} - -// coursier names an AAR-packaged module `group:artifact:aar:version`; the lock -// records the coordinate a project writes. -inline std::string plain_form(const std::string& coord) { - return replace_all_copy(coord, ":aar:", ":"); -} - -// ─── An AAR, unpacked ───────────────────────────────────────────────────── - -// What an Android library archive contributes: its manifest (merged), its -// `res/` (linked under its own package), its classes (`classes.jar`, and any -// `libs/*.jar` it carries), its native libraries (`jni//`) and its -// `assets/`. `R.txt`, `proguard.txt`, `lint.jar` and `public.txt` are not -// read: this member does not shrink, lint or compute non-transitive R classes. -struct library_input { - std::string label; - std::string package; - std::string resources; - std::string manifest; - std::string assets; - std::string jni; - std::vector java; - std::vector kotlin; - std::vector jars; -}; - -// Unpacked with the JDK's `jar` at plan time, once per archive content: a stamp -// beside the tree records the archive's digest, and a matching stamp skips the -// work on the next plan. -inline bool unpack_aar(const std::string& aar, const fs::path& dest, const std::string& jarTool, - library_input& out, std::string& message) { - const std::string digest = sha256_file(aar); - if (digest.empty()) { - message = std::format("mcpp.dist.apk: the AAR {} was not found.", aar); - return false; - } - const fs::path stamp = dest / ".mcpp-aar-sha256"; - if (read_file(stamp.string()) != digest) { - std::error_code ec; - fs::remove_all(dest, ec); - fs::create_directories(dest, ec); - std::string output; - const int rc = run_capture({jarTool, "xf", aar}, output, dest); - if (rc != 0) { - message = std::format("mcpp.dist.apk: unpacking {} with {} failed ({}): {}", aar, jarTool, rc, output); - return false; - } - write_if_different(stamp, digest); - } - const std::string manifest = (dest / "AndroidManifest.xml").string(); - if (!is_file(manifest)) { - message = std::format("mcpp.dist.apk: {} carries no AndroidManifest.xml, so it is not an AAR.", aar); - return false; - } - xml::node m; - std::string err; - if (!xml::parse(read_file(manifest), m, err) || m.name != "manifest") { - message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", aar, err); - return false; - } - out.package = xml::attr_of(m, "package"); - out.manifest = manifest; - if (is_dir((dest / "res").string()) && dir_has_files((dest / "res").string())) out.resources = (dest / "res").string(); - if (is_dir((dest / "assets").string()) && dir_has_files((dest / "assets").string())) out.assets = (dest / "assets").string(); - if (is_dir((dest / "jni").string())) out.jni = (dest / "jni").string(); - if (is_file((dest / "classes.jar").string())) out.jars.push_back((dest / "classes.jar").string()); - for (auto const& j : files_with_extension((dest / "libs").string(), ".jar")) out.jars.push_back(j); - return true; -} -} // namespace mcpp::dist::apk - -module :private; - -namespace mcpp::dist::apk { -// ─── SHA-256 ─────────────────────────────────────────────────────────────── - -// FIPS 180-4, over bytes held in memory. Here for one purpose: a Maven lock -// records each artifact's digest, and a build that reads a cached artifact -// checks it against the lock before the file reaches a package. The inputs are -// libraries of a few megabytes, so reading a file whole is the simple choice. -inline std::string sha256_hex(std::string_view data) { - static constexpr std::uint32_t k[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; - std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; - std::string msg(data); - const std::uint64_t bits = static_cast(data.size()) * 8u; - msg.push_back(static_cast(0x80)); - while (msg.size() % 64 != 56) msg.push_back('\0'); - for (int i = 7; i >= 0; --i) msg.push_back(static_cast((bits >> (i * 8)) & 0xffu)); - const auto rotr = [](std::uint32_t x, int n) -> std::uint32_t { return (x >> n) | (x << (32 - n)); }; - for (std::size_t off = 0; off < msg.size(); off += 64) { - std::uint32_t w[64]; - for (int i = 0; i < 16; ++i) { - const auto byte = [&](int j) { - return static_cast(static_cast(msg[off + static_cast(i * 4 + j)])); - }; - w[i] = (byte(0) << 24) | (byte(1) << 16) | (byte(2) << 8) | byte(3); - } - for (int i = 16; i < 64; ++i) { - const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); - const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16] + s0 + w[i - 7] + s1; - } - std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; - for (int i = 0; i < 64; ++i) { - const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i]; - const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); - hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; - } - h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; - } - std::string hex; - hex.reserve(64); - for (int i = 0; i < 8; ++i) hex += std::format("{:08x}", h[i]); - return hex; -} -} // namespace mcpp::dist::apk - diff --git a/dist/apk/internal/manifest.cppm b/dist/apk/internal/manifest.cppm deleted file mode 100644 index a492958..0000000 --- a/dist/apk/internal/manifest.cppm +++ /dev/null @@ -1,467 +0,0 @@ -// mcpp.dist.apk.internal.manifest -- manifest templating, rendering and library-manifest merging. - -export module mcpp.dist.apk.internal.manifest; - -import std; -import mcpp.dist.apk.internal.util; - -namespace mcpp::dist::apk { - -inline const std::vector& manifest_tokens(); -inline std::vector tokens_in(const std::string& text); -inline std::vector required_manifest_tokens(bool has_code, bool native_activity); -inline std::string manifest_key(const xml::node& n); -inline void strip_tools(xml::node& n); -inline std::string canonical_xml(xml::node n); -inline bool substitute_placeholders(xml::node& n, const std::string& appId, - const std::string& label, std::string& message); -inline xml::node* find_child(xml::node& parent, std::string_view name); -inline void drop_removed(xml::node& n); - -// `android:versionCode` from a version string: major * 1000000 + minor * 1000 -// + patch over the first three dot-separated numeric segments, so that every -// release a project cuts orders after the one before it, and "1" when the -// string starts with no number at all -- Android refuses 0 and a manifest -// without the attribute installs but never updates. -inline std::string version_code_for(const std::string& version) { - long long code = 0, seg = 0; - int segments = 0; - bool digits = false; - const long long weights[3] = {1000000, 1000, 1}; - for (std::size_t i = 0; i <= version.size() && segments < 3; ++i) { - const char c = i < version.size() ? version[i] : '\0'; - if (c >= '0' && c <= '9') { seg = seg * 10 + (c - '0'); digits = true; continue; } - if (!digits) break; - code += std::min(seg, 999) * weights[segments] ; - ++segments; seg = 0; digits = false; - if (c != '.') break; - } - if (segments == 0) return "1"; - if (code <= 0) return "1"; - return std::to_string(code); -} - -// THE BUILT-IN DEFAULT, EXPRESSED WITH THE TOKENS. This is `manifest_xml`'s -// 0.8.0 output verbatim, with every literal value it used to compute -// replaced by the token that value now comes through -- so level 0 with no -// project template renders byte-identical to what 0.8.0 wrote -// (`tests/apk-consumer`). `{{activity}}` carries the level-0 constant -// (`android.app.NativeActivity`) as well as a level-1 project's own class, -// because the run sidecar needs the activity name at both levels and the -// required-token check reads the TEMPLATE TEXT, not the level -- so the same -// token has to appear on both of this function's two branches. -// `{{lib_name}}`'s `` element exists only at level 0: it -// announces which shared object `NativeActivity` should load, and a -// Java-hosted activity finds its own native library another way. -// -// NO XML COMMENT MARKS THE THREE REQUIRED TOKENS IN THIS STRING, ON PURPOSE: -// this exact text is compared byte-for-byte against 0.8.0's output, which -// carried none, and a template with no author to read a comment gains -// nothing from one. The design record's "mark the required tokens" is done -// here instead, in the `REQUIRED` labels on the C++ lines that build them. -// A NATIVE ACTIVITY MAY STILL CARRY CODE (0.11.0): a level-0 application whose -// libraries or archives bring classes keeps `android.app.NativeActivity` and its -// `lib_name` element, with `android:hasCode="true"` so that the dex is loaded. -inline std::string default_manifest_template(bool has_code, bool native_activity) { - std::string a = - "\n" - "\n" // REQUIRED - " \n" - " \n" - " \n"; - if (native_activity) { - a += " \n"; // REQUIRED at level 0 - } - a += " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - "\n"; - return a; -} - -// Checks a manifest template and substitutes it, or refuses (returning -// `false` with `reason` and `message` set) naming exactly what is wrong; the -// caller reports `message` (see `refuse`). -// -// THIS CHECK IS `dist-apk`'S OWN, DELIBERATELY NOT `dist-web`'S. A manifest -// has a closed, six-token vocabulary this member itself defines; a web page -// template may legitimately carry `{{ }}` for a front-end framework (Vue, -// Mustache, ...) this member never reads, so `dist-web` leaves an unknown -// token literal for that project's own tooling to read. An unknown token -// here would otherwise reach `aapt2` unsubstituted and fail there with a -// worse message, and the refusal belongs where the name is known -- the same -// rule read against two different facts, not an inconsistency between the -// two members. -inline bool render_manifest(const std::string& templateText, bool has_code, bool native_activity, - const std::string& appId, const std::string& label, - const std::string& activityName, const std::string& libName, - const std::string& minSdk, const std::string& targetSdk, - const std::string& versionName, const std::string& versionCode, - std::string& out, std::string& reason, - std::string& message) { - for (auto const& tok : tokens_in(templateText)) { - if (std::ranges::find(manifest_tokens(), tok) == manifest_tokens().end()) { - message = "mcpp.dist.apk: the manifest template names an unknown " - "token '{{" + tok + "}}'; expected one of application_id, " - "label, activity, lib_name, min_sdk, target_sdk, " - "version_name, version_code."; - reason = "unknown manifest template token '" + tok + "'"; - return false; - } - } - for (auto const& tok : required_manifest_tokens(has_code, native_activity)) { - if (templateText.find("{{" + tok + "}}") == std::string::npos) { - message = "mcpp.dist.apk: the manifest template does not use '{{" + tok - + "}}', and assets/mcpp-run.json, which adb-run starts the " - "application from, is written from the same value: add {{" - + tok + "}} to the template."; - reason = "manifest template missing required token '" + tok + "'"; - return false; - } - } - out = templateText; - out = replace_all_copy(std::move(out), "{{application_id}}", appId); - out = replace_all_copy(std::move(out), "{{label}}", label); - out = replace_all_copy(std::move(out), "{{activity}}", activityName); - out = replace_all_copy(std::move(out), "{{lib_name}}", libName); - out = replace_all_copy(std::move(out), "{{min_sdk}}", minSdk); - out = replace_all_copy(std::move(out), "{{target_sdk}}", targetSdk); - out = replace_all_copy(std::move(out), "{{version_name}}", versionName); - out = replace_all_copy(std::move(out), "{{version_code}}", versionCode); - return true; -} -inline bool render_manifest(const std::string& templateText, bool has_code, - const std::string& appId, const std::string& label, - const std::string& activityName, const std::string& libName, - const std::string& minSdk, const std::string& targetSdk, - const std::string& versionName, const std::string& versionCode, - std::string& out, std::string& reason, - std::string& message) { - return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName, - minSdk, targetSdk, versionName, versionCode, out, reason, message); -} - -inline std::string run_json(const std::string& app_id, const std::string& activity_name) { - // Hand-built, not through a JSON library this collection does not - // depend on: two string fields, neither of which this member lets - // through unescaped input (`app_id` is derived from the package's own - // identifiers, `activity_name` is a Java class name or the literal - // `android.app.NativeActivity`). - return std::format("{{\"package\": \"{}\", \"activity\": \"{}\"}}\n", - app_id, activity_name); -} - -// ─── Merging library manifests into the application's ──────────────────── - -// What `mcpp.dist.apk` merges, and the rules it applies. This is a SUBSET of -// the Android Gradle plugin's manifest merger, stated rather than implied: -// -// - ``, ``, ``, -// `` and the other children of `` are added when -// the application has no element of the same kind and `android:name`; -// `` children are unioned; -// - the children of a library's `` -- activities, aliases, -// services, receivers, providers, ``, `` -- are -// added the same way; a library's `` attribute the -// application does not state is added; -// - an identical element is not added twice; a DIFFERENT element under the -// same name is refused, naming it, unless the application's own element -// says `tools:node="replace"` (the application's wins) or -// `tools:node="remove"` (neither is kept); a differing `` -// attribute is refused unless the application lists it in `tools:replace`; -// - a library's `` above the application's -// floor is refused, as Gradle refuses it; -// - `${applicationId}` is substituted everywhere, and any other `${...}` -// placeholder is refused, naming it -- no placeholder source exists here; -// - every `tools:` attribute and the `xmlns:tools` declaration are removed -// from the result. -// -// Anything a project needs beyond that is stated in its own manifest template, -// which this member never edits except to add what the libraries declare. -struct manifest_source { - std::string label; // what a refusal names: a library, an AAR, a coordinate - std::string text; -}; - -inline bool merge_manifests(std::string& appText, const std::vector& libs, - const std::string& appId, const std::string& minSdk, - std::string& reason, std::string& message) { - xml::node app; - std::string err; - if (!xml::parse(appText, app, err) || app.name != "manifest") { - reason = "the application manifest cannot be read"; - message = "mcpp.dist.apk: the application's manifest cannot be read for merging: " - + (err.empty() ? std::string("its root element is not ") : err); - return false; - } - if (!substitute_placeholders(app, appId, "the application's manifest", message)) { - reason = "unknown manifest placeholder"; - return false; - } - xml::node* application = find_child(app, "application"); - if (!application) { - app.children.push_back(xml::node{"application", {}, {}, {}}); - application = &app.children.back(); - } - const auto parse_number = [](const std::string& s) { - long v = 0; - for (std::size_t i = 0; i < s.size(); ++i) { - if (s[i] < '0' || s[i] > '9') return -1L; - v = v * 10 + (s[i] - '0'); - } - return s.empty() ? -1L : v; - }; - - for (auto const& lib : libs) { - xml::node m; - if (!xml::parse(lib.text, m, err) || m.name != "manifest") { - reason = "a library manifest cannot be read"; - message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", lib.label, - err.empty() ? std::string("its root element is not ") : err); - return false; - } - if (!substitute_placeholders(m, appId, lib.label, message)) { - reason = "unknown manifest placeholder"; - return false; - } - for (auto& c : m.children) { - if (c.name.empty()) continue; - if (c.name == "uses-sdk") { - const long want = parse_number(xml::attr_of(c, "android:minSdkVersion")); - const long have = parse_number(minSdk); - if (want > 0 && have > 0 && want > have) { - reason = "a library needs a higher minSdkVersion"; - message = std::format( - "mcpp.dist.apk: {} declares android:minSdkVersion {}, above this " - "application's floor {}. Raise the row's min_api_level, or do not " - "depend on it.", lib.label, want, have); - return false; - } - continue; - } - if (c.name == "application") { - const std::string replaced = xml::attr_of(*application, "tools:replace"); - for (auto const& a : c.attrs) { - if (a.first.starts_with("tools:")) continue; - const std::string mine = xml::attr_of(*application, a.first); - if (mine.empty()) { xml::set_attr(*application, a.first, a.second); continue; } - if (mine == a.second) continue; - bool listed = false; - std::size_t start = 0; - while (start <= replaced.size()) { - auto comma = replaced.find(',', start); - if (comma == std::string::npos) comma = replaced.size(); - if (xml::trim_copy(replaced.substr(start, comma - start)) == a.first) { listed = true; break; } - start = comma + 1; - } - if (!listed) { - reason = "conflicting attribute"; - message = std::format( - "mcpp.dist.apk: is \"{}\" in the application and " - "\"{}\" in {}. Add tools:replace=\"{}\" to the application's " - " to keep its value.", a.first, mine, a.second, lib.label, a.first); - return false; - } - } - for (auto& cc : c.children) { - if (cc.name.empty()) continue; - const std::string key = manifest_key(cc); - xml::node* mine = nullptr; - for (auto& x : application->children) - if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } - if (!mine) { application->children.push_back(cc); continue; } - const std::string node = xml::attr_of(*mine, "tools:node"); - if (node == "remove" || node == "replace") continue; - if (canonical_xml(*mine) == canonical_xml(cc)) continue; - reason = "conflicting manifest element"; - message = std::format( - "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application " - "and {}. State tools:node=\"replace\" on the application's element to keep " - "it, or tools:node=\"remove\" to drop both.", cc.name, - xml::attr_of(cc, "android:name"), lib.label); - return false; - } - continue; - } - if (c.name == "queries") { - xml::node* q = find_child(app, "queries"); - if (!q) { - auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); - q = &*app.children.insert(pos, xml::node{"queries", {}, {}, {}}); - application = find_child(app, "application"); - } - for (auto& qc : c.children) { - if (qc.name.empty()) continue; - const std::string canon = canonical_xml(qc); - const bool present = std::ranges::any_of(q->children, [&](const xml::node& x) { - return canonical_xml(x) == canon; - }); - if (!present) q->children.push_back(qc); - } - continue; - } - const std::string key = manifest_key(c); - xml::node* mine = nullptr; - for (auto& x : app.children) - if (!x.name.empty() && manifest_key(x) == key) { mine = &x; break; } - if (mine) { - const std::string node = xml::attr_of(*mine, "tools:node"); - if (node == "remove" || node == "replace") continue; - if (canonical_xml(*mine) == canonical_xml(c)) continue; - reason = "conflicting manifest element"; - message = std::format( - "mcpp.dist.apk: <{} android:name=\"{}\"> differs between the application and " - "{}. State tools:node=\"replace\" on the application's element to keep it, or " - "tools:node=\"remove\" to drop both.", c.name, xml::attr_of(c, "android:name"), lib.label); - return false; - } - auto pos = std::ranges::find_if(app.children, [](const xml::node& x) { return x.name == "application"; }); - app.children.insert(pos, c); - application = find_child(app, "application"); - } - } - - drop_removed(app); - strip_tools(app); - appText = "\n"; - xml::write(app, appText, 0); - return true; -} - -// Does the manifest ask for the native libraries to be loaded from the APK in -// place (``, 0.11.1)? The -// platform can map a library only from an entry stored uncompressed on a page -// boundary, so such a package is laid out that way; a compressed library in it -// fails to install. -inline bool loads_native_libraries_in_place(const std::string& manifest) { - xml::node root; - std::string error; - if (!xml::parse(manifest, root, error) || root.name != "manifest") return false; - const xml::node* application = find_child(root, "application"); - return application && xml::attr_of(*application, "android:extractNativeLibs") == "false"; -} - -} // namespace mcpp::dist::apk - -module :private; - -namespace mcpp::dist::apk { -// The eight tokens a manifest template may use. `version_name` is the -// package version as written; `version_code` is Android's monotonic integer -// derived from its leading numeric segments (`version_code_for`). -inline const std::vector& manifest_tokens() { - static const std::vector v = { - "application_id", "label", "activity", "lib_name", "min_sdk", "target_sdk", - "version_name", "version_code"}; - return v; -} - -// Every `{{...}}` a template names, in first-appearance order, duplicates -// dropped -- what both checks in `render_manifest` below read. -inline std::vector tokens_in(const std::string& text) { - std::vector out; - std::size_t i = 0; - while ((i = text.find("{{", i)) != std::string::npos) { - const auto close = text.find("}}", i + 2); - if (close == std::string::npos) break; - std::string name = text.substr(i + 2, close - (i + 2)); - if (std::ranges::find(out, name) == out.end()) out.push_back(std::move(name)); - i = close + 2; - } - return out; -} - -// The tokens `assets/mcpp-run.json` is ALSO written from -- a template that -// omits one silently ships a run sidecar the manifest disagrees with. -// `application_id` and `activity` are required unconditionally; `lib_name` -// joins them at level 0, where the manifest's own `` element is -// the only place the loaded library's name is recorded. -inline std::vector required_manifest_tokens(bool has_code, bool native_activity) { - static_cast(has_code); - std::vector v = {"application_id", "activity"}; - if (native_activity) v.push_back("lib_name"); - return v; -} -inline std::vector required_manifest_tokens(bool has_code) { - return required_manifest_tokens(has_code, !has_code); -} - -inline std::string default_manifest_template(bool has_code) { - return default_manifest_template(has_code, !has_code); -} - -inline bool render_manifest(const std::string& templateText, bool has_code, - const std::string& appId, const std::string& label, - const std::string& activityName, const std::string& libName, - const std::string& minSdk, const std::string& targetSdk, - const std::string& versionName, const std::string& versionCode, - std::string& out, std::string& reason, - std::string& message) { - return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName, - minSdk, targetSdk, versionName, versionCode, out, reason, message); -} - -inline std::string manifest_key(const xml::node& n) { - if (n.name == "uses-feature") { - const std::string nm = xml::attr_of(n, "android:name"); - return nm.empty() ? "uses-feature@glEsVersion=" + xml::attr_of(n, "android:glEsVersion") - : "uses-feature:" + nm; - } - return n.name + ":" + xml::attr_of(n, "android:name"); -} - -inline void strip_tools(xml::node& n) { - std::erase_if(n.attrs, [](const std::pair& a) { - return a.first.starts_with("tools:") || a.first == "xmlns:tools"; - }); - for (auto& c : n.children) strip_tools(c); -} - -inline std::string canonical_xml(xml::node n) { - strip_tools(n); - std::string out; - xml::write(n, out, 0); - return out; -} - -inline bool substitute_placeholders(xml::node& n, const std::string& appId, - const std::string& label, std::string& message) { - for (auto& a : n.attrs) { - a.second = replace_all_copy(a.second, "${applicationId}", appId); - const auto p = a.second.find("${"); - if (p != std::string::npos) { - const auto e = a.second.find('}', p); - message = std::format( - "mcpp.dist.apk: {} uses the manifest placeholder '{}' in {}=\"{}\"; " - "only ${{applicationId}} is substituted here.", label, - a.second.substr(p, e == std::string::npos ? std::string::npos : e - p + 1), - a.first, a.second); - return false; - } - } - for (auto& c : n.children) - if (!substitute_placeholders(c, appId, label, message)) return false; - return true; -} - -inline xml::node* find_child(xml::node& parent, std::string_view name) { - for (auto& c : parent.children) if (c.name == name) return &c; - return nullptr; -} - -// Removes every element the application marked `tools:node="remove"`: a marker -// that says "this is not wanted", not an element to ship. -inline void drop_removed(xml::node& n) { - std::erase_if(n.children, [](const xml::node& c) { return xml::attr_of(c, "tools:node") == "remove"; }); - for (auto& c : n.children) drop_removed(c); -} -} // namespace mcpp::dist::apk - diff --git a/dist/apk/internal/util.cppm b/dist/apk/internal/util.cppm deleted file mode 100644 index 953bc06..0000000 --- a/dist/apk/internal/util.cppm +++ /dev/null @@ -1,277 +0,0 @@ -// mcpp.dist.apk.internal.util -- the shared file, host and text helpers of dist/apk. - -export module mcpp.dist.apk.internal.util; - -import std; -import mcpp; -import mcpp.plugins; -import mcpp.plugins.tool; - -namespace mcpp::dist::apk { - -namespace fs = std::filesystem; - -inline bool is_file(const std::string& p) { - std::error_code ec; - return !p.empty() && fs::is_regular_file(p, ec); -} -inline bool is_dir(const std::string& p) { - std::error_code ec; - return !p.empty() && fs::is_directory(p, ec); -} - -inline bool host_is_windows(); - -inline std::string host_program(const fs::path& dir, std::string_view name) { - return (dir / (std::string(name) + (host_is_windows() ? ".exe" : ""))).string(); -} -inline const char* class_path_separator() { return host_is_windows() ? ";" : ":"; } - -// Is `root` under the package root, `mcpp::manifest_dir()`, and if so, what -// is its manifest-relative form? A project root is declared with -// `rerun_if_changed_glob` below (a file appearing there re-runs the build -// program); a dependency root is not -- its file set changes only with the -// dependency's version, already in the build's fingerprint, and the glob's -// own walk does not reach outside the package root regardless (design -// record §3.3). Same shape as `mcpp.tools.island`'s overlap check: -// `weakly_canonical` plus `lexically_relative`, never the iterator that -// poisons an importer under GCC 16 / MSVC (`mcpp::plugins::names:: -// relative_to`'s own header) -- safe here because this member is its own -// module and imports no sibling that would inherit the instantiation. -// -// THE RETURNED PATH IS MANIFEST-RELATIVE, NOT ABSOLUTE, BECAUSE THE GLOB -// PATTERN MUST BE. The engine matches a glob by comparing the CANDIDATE made -// relative to the package root against the pattern -// (`modules/manifest/src/glob.cppm`, `path_matches_glob`); an absolute -// pattern is compared against a relative candidate and never matches -// anything, so the fingerprint is always the empty set and a `.java` file -// appearing never changes it -- the criterion's "no" reading as silence -// (design record, rule 8). `opt.java_sources`'s own roots are absolute -// (`mcpp::manifest_dir()` composed with a subdirectory), so declaring the -// glob with `root` itself, not this function's return value, was exactly -// that defect. -// -// A root inside the build's output -- `mcpp::out_dir()`, or a directory the -// glob walk never enters (`target`, `.mcpp`, `.git`) -- is GENERATED: the -// build program that writes its files already runs on every build, and a glob -// there can never match anything, which the engine reports as a warning. It is -// answered as outside the project, so it is an action input and no glob. -inline std::optional root_in_project(const std::string& root) { - std::error_code ec; - const auto a = fs::weakly_canonical(root, ec); - if (ec) return std::nullopt; - const auto b = fs::weakly_canonical(mcpp::manifest_dir(), ec); - if (ec) return std::nullopt; - const auto rel = a.lexically_relative(b).generic_string(); - if (rel.empty() || rel.starts_with("..")) return std::nullopt; - const auto out = fs::weakly_canonical(std::string(mcpp::out_dir()), ec); - if (!ec) { - const auto inside = a.lexically_relative(out).generic_string(); - if (!inside.empty() && !inside.starts_with("..")) return std::nullopt; - } - const auto first = rel.substr(0, rel.find('/')); - if (first == "target" || first == ".mcpp" || first == ".git") return std::nullopt; - return rel; -} - -inline bool write_if_different(const fs::path& path, std::string_view bytes) { - std::error_code ec; - fs::create_directories(path.parent_path(), ec); - if (std::ifstream in(path, std::ios::binary); in) { - std::string old((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - if (old == bytes) return true; - } - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out) return false; - out.write(bytes.data(), static_cast(bytes.size())); - return static_cast(out); -} - -// `/`, from the row's arch and no other input -- see `artifact_naming` -// for the engine's own row-decides-the-name principle, applied here to -// Android's own ABI vocabulary rather than a file suffix. -inline std::string abi_for() { - const std::string a = mcpp::target_arch(); - if (a == "aarch64") return "arm64-v8a"; - if (a == "x86_64") return "x86_64"; - return {}; -} - - -// Index loop, not a range-for: GCC 16.1.0 refuses to inline -// `__normal_iterator>::operator*() const` when a -// module interface unit that imports `std` also range-for's (or otherwise -// takes `basic_string`'s own iterator over) a `std::string` or -// `std::filesystem::path` -- -// -// bits/stl_iterator.h:1089:7: error: inlining failed in call to -// 'always_inline' '... operator*() const' -// -// -- the same family of defect #18 met under MSVC's `_Path_iterator` (see -// `mcpp::plugins::names::relative_to` and `components()` in -// `src/plugins.cppm`), here on `libstdc++`'s `basic_string` iterator instead -// of the filesystem one. `s[i]` indexes the string directly and never forms -// that iterator, so it compiles under both. -inline std::string replace_dashes(std::string s) { - for (std::size_t i = 0; i < s.size(); ++i) if (s[i] == '-') s[i] = '_'; - return s; -} - -// `xim:android-platform`'s own resolved directory is named after the -// version it resolved -- "36-r2", "35-r2", "34-r3" (`pkgs/a/android- -// platform.lua`'s own `extract_dir()` recovers the API level the identical -// way, from the leading digits of its OWN version string) -- so the level a -// project pinned is read back from the directory `xpkg_dir` already -// answered, rather than duplicated as a second option this member could -// disagree with. -inline std::string api_level_from_platform_dir(const std::string& dir) { - if (dir.empty()) return {}; - const std::string leaf = fs::path(dir).filename().string(); - std::string digits; - for (std::size_t i = 0; i < leaf.size(); ++i) { - if (leaf[i] >= '0' && leaf[i] <= '9') digits += leaf[i]; - else break; - } - return digits; -} - -inline std::string replace_all_copy(std::string s, std::string_view from, std::string_view to) { - if (from.empty()) return s; - std::size_t pos = 0; - while ((pos = s.find(from, pos)) != std::string::npos) { - s.replace(pos, from.size(), to); - pos += to.size(); - } - return s; -} - -// Copies `src` (a file or a directory, recursively) into `dstRoot/relName`, -// listing every regular file it wrote -- so the caller can declare each one -// as an action input rather than the directory itself ("name the input; do -// not harvest a directory", docs/31). -inline void collect_tree(const fs::path& src, const fs::path& dst, - std::vector& out) { - std::error_code ec; - if (fs::is_regular_file(src, ec)) { - fs::create_directories(dst.parent_path(), ec); - fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec); - out.push_back(dst.string()); - return; - } - for (auto& e : fs::recursive_directory_iterator(src, ec)) { - if (ec) break; - if (!e.is_regular_file(ec)) continue; - auto rel = fs::relative(e.path(), src, ec); - auto to = dst / rel; - fs::create_directories(to.parent_path(), ec); - fs::copy_file(e.path(), to, fs::copy_options::overwrite_existing, ec); - out.push_back(to.string()); - } -} - -namespace xml = mcpp::plugins::xml; - -// ─── Paths a project names ───────────────────────────────────────────────── - -// A project names its directories relative to its manifest; the actions this -// member declares run later, from the build directory, where a relative path -// names nothing (the defect `dist/apple.cppm` measured with `ditto ios-icons`). -// Every path option is therefore resolved here, once, against -// `mcpp::manifest_dir()`; an absolute path is left alone. -inline std::string resolve_path(const std::string& p) { - if (p.empty()) return p; - const fs::path path(p); - if (path.is_absolute()) return p; - return (fs::path(mcpp::manifest_dir()) / path).lexically_normal().string(); -} - -inline void resolve_paths(std::vector& v) { - for (auto& p : v) p = resolve_path(p); -} - -// Every regular file under `root` whose extension is `ext`, sorted. -inline std::vector files_with_extension(const std::string& root, std::string_view ext) { - std::vector out; - std::error_code ec; - for (auto& e : fs::recursive_directory_iterator(root, ec)) { - if (ec) break; - if (e.is_regular_file(ec) && e.path().extension() == ext) - out.push_back(e.path().string()); - } - std::ranges::sort(out); - return out; -} - -inline bool dir_has_files(const std::string& root) { - std::error_code ec; - for (auto& e : fs::recursive_directory_iterator(root, ec)) { - if (ec) break; - if (e.is_regular_file(ec)) return true; - } - return false; -} - -inline std::string read_file(const std::string& path) { - std::ifstream in(path, std::ios::binary); - return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); -} - -inline std::string join(const std::vector& v, std::string_view sep) { - std::string out; - for (std::size_t i = 0; i < v.size(); ++i) { - if (i) out += sep; - out += v[i]; - } - return out; -} - -// ─── Running a tool at plan time ───────────────────────────────────────── - -// Runs `argv`, returning its exit status and its combined output, through -// `mcpp::plugins::tool::capture`: no shell between, so no argument is quoted. -// Only the explicit Maven modes and AAR extraction call it; an ordinary build -// of an unchanged project runs nothing here. -int run_capture(const std::vector& argv, std::string& output, - const std::filesystem::path& cwd = {}) { - auto r = mcpp::plugins::tool::capture(argv, /*with_errors=*/true, cwd); - output = std::move(r.out); - return r.status; -} - -// Android's own ABI names, the directory names a several-triple tree stages -// under (`lib//`) and an APK stores its native libraries under. -inline bool is_android_abi(std::string_view name) { - return name == "arm64-v8a" || name == "x86_64" || name == "armeabi-v7a" || name == "x86"; -} - -// One ABI's native libraries, as the staged tree carries them. -struct native_leg { - std::string abi; - std::vector libraries; // absolute paths, sorted -}; - -inline std::vector shared_objects_in(const fs::path& dir) { - std::vector out; - std::error_code ec; - for (auto& e : fs::directory_iterator(dir, ec)) { - if (ec) break; - if (e.is_regular_file(ec) && e.path().extension() == ".so") - out.push_back(e.path().string()); - } - std::ranges::sort(out); - return out; -} -} // namespace mcpp::dist::apk - -module :private; - -namespace mcpp::dist::apk { -// THE HOST, NOT THE TARGET: every tool here runs on the machine that builds. -// A Windows host names its programs `.exe` and separates a class path -// with `;`. -inline bool host_is_windows() { - return std::string_view(mcpp::host()).find("windows") != std::string_view::npos; -} -} // namespace mcpp::dist::apk - diff --git a/dist/apple/apple.cppm b/dist/apple.cppm similarity index 77% rename from dist/apple/apple.cppm rename to dist/apple.cppm index 4935a75..e2a9d75 100644 --- a/dist/apple/apple.cppm +++ b/dist/apple.cppm @@ -195,18 +195,12 @@ import mcpp.plugins; import mcpp.plugins.tool; import mcpp.tools.steps; -import mcpp.dist.apple.internal.layout; -import mcpp.dist.apple.internal.plist; -import mcpp.dist.apple.internal.signing; - - // Nothing here uses `std::println`, and that is not a style choice: both of // its overloads reach into the libc++ dylib for symbols macOS 14 does not // ship, so a member that printed with it compiled and then failed to link. // `std::format` is header-only. The full measurement is in `rules/spirv.cppm`. export namespace mcpp::dist::apple { - using namespace detail; // ─── Options ─────────────────────────────────────────────────────────────── @@ -389,6 +383,30 @@ struct plan { // ─── Internals ───────────────────────────────────────────────────────────── +inline bool is_file(const std::string& p) { + std::error_code ec; + return !p.empty() && std::filesystem::is_regular_file(p, ec); +} + +// Written only when the bytes differ, for the reason `dist/appimage.cppm` +// gives: rewriting identical bytes moves the mtime, and a moved mtime on a +// declared input is indistinguishable from a changed one -- so a second pack +// of an unchanged project would re-copy the bundle and re-sign it. +inline bool write_if_different(const std::filesystem::path& path, + std::string_view bytes) { + std::error_code ec; + std::filesystem::create_directories(path.parent_path(), ec); + if (std::ifstream in(path, std::ios::binary); in) { + std::string old((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + if (old == bytes) return true; + } + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(bytes.data(), static_cast(bytes.size())); + return static_cast(out); +} + // Records a refusal on stderr and as a `mcpp::warning`. A member that refuses // submits no action and its build program exits 0, and the engine discards the // output of a build program that succeeded; its own error, "no action claimed @@ -445,6 +463,53 @@ inline std::string app_name_for(const options& opt) { return (n && *n) ? std::string(n) : std::string("app"); } +// The program a bundle executes, found in the staged tree: `bin/` +// first, then the tree's top-level entry, then `run.sh`. +// +// THE PROGRAM, NOT THE TREE'S ENTRY SCRIPT. From the release that reads a +// Mach-O program's closure (mcpp 2026.9.14.2), the engine also writes +// `/`, a shell script that executes `bin/` from the +// tree's root. The search used to take that root entry first, which is the +// order `dist/appimage.cppm` needs, and a bundle then executed the script, +// which executed `Contents/MacOS/bin/` -- a file no bundle carries: +// "cannot execute: No such file or directory", exit 126 (macos-15, run +// 34821164486). The script has no work to do inside a bundle, where +// `CFBundleExecutable` names the program directly, and the framework rpath +// `@executable_path/../Frameworks` resolves against the program's own +// directory, which has to be `Contents/MacOS/`. The root entry and `run.sh` +// remain for a tree that carries no `bin/`. +inline std::string launcher_in(const std::string& stage, const std::string& target) { + for (auto candidate : {stage + "/bin/" + target, + stage + "/" + target, + stage + "/run.sh"}) + if (is_file(candidate)) return candidate; + return {}; +} + +// CFBundleExecutable MUST BE A BARE FILENAME, NOT A PATH. +// +// Apple's own bundle documentation describes it as the executable's name +// within `Contents/MacOS/`, and real-world bundle tooling has hit this +// directly enough to be a filed CMake defect: "CFBundleExecutable path in a +// bundle should not be a relative path into bundle." So this member takes +// only the basename of whatever `launcher_in` finds, and the layout step +// copies that file to the top of the executable directory under that name, so +// the name and the file agree wherever in the staged tree it was found. +inline std::string bundle_executable_name(const std::string& launcher_path) { + return std::filesystem::path(launcher_path).filename().string(); +} + +inline std::string sanitize_bundle_id_component(std::string_view s) { + std::string out; + out.reserve(s.size()); + for (char c : s) { + bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') + || (c >= '0' && c <= '9') || c == '-' || c == '.'; + out += ok ? c : '-'; + } + return out; +} + // A reversed-DNS-SHAPED identifier, not a literal reversal of a domain -- // mcpp packages carry `(namespace, name)`, not a domain to reverse. Sanitised // to the character set Apple documents for `CFBundleIdentifier` @@ -462,6 +527,312 @@ inline std::string bundle_id_for(const options& opt) { return "app"; } +inline std::string plist_escape(std::string_view s) { + std::string out; + out.reserve(s.size()); + for (char c : s) { + switch (c) { + case '&': out += "&"; break; + case '<': out += "<"; break; + case '>': out += ">"; break; + default: out += c; + } + } + return out; +} + +// Written as XML text directly rather than by shelling out to `plutil`: the +// content is a handful of string keys this member already holds, and adding +// a second host tool to discover and invoke would buy nothing over +// formatting the lines by hand. `LSMinimumSystemVersion` / `MinimumOSVersion` +// and `CFBundleIconFile` are omitted rather than emitted empty when their +// inputs are empty -- an empty string in either key is a claim as +// unsupported as omitting the key, so omission is the honest one. +// +// `is_ios` AND `is_sim` DECIDE FOUR KEYS, NOT ONE BRANCH. `MinimumOSVersion` +// replaces `LSMinimumSystemVersion`; `CFBundleSupportedPlatforms`, +// `UIDeviceFamily` and `LSRequiresIPhoneOS` are iOS-only and absent from +// every macOS bundle this member has ever written, which is the +// byte-identical property the macOS fixture depends on; `NSHighResolutionCapable` +// is a macOS concept (Retina-aware drawing on a platform that also has +// non-Retina displays) with nothing to opt into on iOS, so it is macOS-only +// in the other direction. +inline std::string plist_document(const std::string& executable, const std::string& bundle_id, + const std::string& name, const std::string& version, + bool is_ios, bool is_sim, + const std::string& min_os_version, + // The project's own entries (0.11.0), already + // formatted, inserted before `
`; and the + // defaulted keys they replace. + const std::string& extra_entries, + const std::vector& replaced_keys, + // macOS: the icon FILE's basename, extension + // included, exactly as `CFBundleIconFile` has + // always taken it. iOS: unused (see + // `ios_icon_stems`) and always empty. + const std::string& mac_icon_name, + // iOS: every PNG stem found in + // `options::icon`'s directory. macOS: unused + // and always empty. + const std::vector& ios_icon_stems) { + std::string doc; + doc += "\n"; + doc += "\n"; + doc += "\n\n"; + doc += std::format(" CFBundleExecutable\n {}\n", + plist_escape(executable)); + doc += std::format(" CFBundleIdentifier\n {}\n", + plist_escape(bundle_id)); + doc += std::format(" CFBundleName\n {}\n", + plist_escape(name)); + doc += std::format(" CFBundleShortVersionString\n {}\n", + plist_escape(version)); + doc += std::format(" CFBundleVersion\n {}\n", + plist_escape(version)); + doc += " CFBundlePackageType\n APPL\n"; + if (!min_os_version.empty()) + doc += std::format(" {}\n {}\n", + is_ios ? "MinimumOSVersion" : "LSMinimumSystemVersion", + plist_escape(min_os_version)); + if (is_ios) { + // `env == "sim"` is the engine's own distinction between the two + // rows (triple.cppm: "the simulator is deliberately not a row of + // its own identity... it has its own SDK"); this key is the one + // place a bundle has to restate it, because `simctl install` and a + // real device's installer both read it to refuse the other kind. + doc += std::format( + " CFBundleSupportedPlatforms\n \n" + " {}\n \n", + is_sim ? "iPhoneSimulator" : "iPhoneOS"); + // `[1, 2]`: iPhone and iPad. Nothing here narrows a project to one + // idiom -- that is a project decision (a size class, a storyboard) + // this member has no basis for making. + const auto replaced = [&](std::string_view k) { + return std::ranges::find(replaced_keys, k) != replaced_keys.end(); + }; + if (!replaced("UIDeviceFamily")) + doc += " UIDeviceFamily\n \n" + " 1\n 2\n \n"; + if (!replaced("LSRequiresIPhoneOS")) + doc += " LSRequiresIPhoneOS\n \n"; + if (!ios_icon_stems.empty()) { + doc += " CFBundleIcons\n \n" + " CFBundlePrimaryIcon\n \n" + " CFBundleIconFiles\n \n"; + for (auto const& stem : ios_icon_stems) + doc += std::format(" {}\n", plist_escape(stem)); + doc += " \n \n \n"; + } + } else { + if (std::ranges::find(replaced_keys, std::string_view("NSHighResolutionCapable")) == replaced_keys.end()) + doc += " NSHighResolutionCapable\n \n"; + // Not in the letter of this member's key list, but added + // deliberately: without it, an icon file this member went to the + // trouble of copying into `Contents/Resources/` is inert -- nothing + // in the bundle would ever reference it, and Finder would show the + // generic application icon regardless of `options::icon`. Wiring the + // file up once it exists is what makes the option do what its name + // says. + if (!mac_icon_name.empty()) + doc += std::format(" CFBundleIconFile\n {}\n", + plist_escape(mac_icon_name)); + } + doc += extra_entries; + doc += "\n\n"; + return doc; +} +inline std::string plist_document(const std::string& executable, const std::string& bundle_id, + const std::string& name, const std::string& version, + bool is_ios, bool is_sim, + const std::string& min_os_version, + const std::string& mac_icon_name, + const std::vector& ios_icon_stems) { + return plist_document(executable, bundle_id, name, version, is_ios, is_sim, min_os_version, + std::string(), std::vector(), mac_icon_name, ios_icon_stems); +} + +inline std::string read_text(const std::string& path) { + std::ifstream in(path, std::ios::binary); + return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +} + +inline std::string resolve_path(const std::string& p) { + if (p.empty() || std::filesystem::path(p).is_absolute()) return p; + return (std::filesystem::path(mcpp::manifest_dir()) / p).lexically_normal().string(); +} + +// The keys `plist_document` derives, which a project's plist may not restate, +// and the keys it only defaults, which a project's plist replaces. +inline const std::vector& derived_plist_keys() { + static const std::vector v = { + "CFBundleExecutable", "CFBundleIdentifier", "CFBundleName", "CFBundleShortVersionString", + "CFBundleVersion", "CFBundlePackageType", "LSMinimumSystemVersion", "MinimumOSVersion", + "CFBundleSupportedPlatforms", "CFBundleIconFile", "CFBundleIcons"}; + return v; +} +inline const std::vector& defaulted_plist_keys() { + static const std::vector v = {"UIDeviceFamily", "LSRequiresIPhoneOS", "NSHighResolutionCapable"}; + return v; +} + +// The top-level `` of a property list, or null. A document whose root is +// `` itself is accepted as well as a full ``. +inline const mcpp::plugins::xml::node* top_dict(const mcpp::plugins::xml::node& root) { + if (root.name == "dict") return &root; + if (root.name != "plist") return nullptr; + for (auto const& c : root.children) if (c.name == "dict") return &c; + return nullptr; +} + +// The value element after each `` of a ``, as (key, value) pairs. +inline bool dict_entries(const mcpp::plugins::xml::node& dict, + std::vector>& out, + std::string& error) { + namespace xml = mcpp::plugins::xml; + for (std::size_t i = 0; i < dict.children.size(); ++i) { + const auto& k = dict.children[i]; + if (k.name.empty()) continue; + if (k.name != "key") { error = "<" + k.name + "> appears where a is expected"; return false; } + const std::string key = k.children.size() == 1 && k.children.front().name.empty() + ? xml::trim_copy(k.children.front().text) : std::string(); + std::size_t j = i + 1; + while (j < dict.children.size() && dict.children[j].name.empty()) ++j; + if (key.empty() || j >= dict.children.size()) { error = "a without a value"; return false; } + out.emplace_back(key, &dict.children[j]); + i = j; + } + return true; +} + +// One Info.plist entry a fragment states: its key and the plist text of the +// `` and its value, as `plist_document` inserts it. +struct plist_entry { + std::string key; + std::string text; +}; + +// Reads one plist fragment's entries. `who` is how a diagnostic names the +// fragment (`options::info_plist`, or a package's [package.metadata.dist-apple]). +inline bool read_plist_entries(const std::string& path, const std::string& who, + std::vector& out, std::string& message) { + namespace xml = mcpp::plugins::xml; + xml::node root; + std::string err; + if (!xml::parse(read_text(path), root, err)) { + message = std::format("mcpp.dist.apple: {} ({}) cannot be read: {}", who, path, err); + return false; + } + const xml::node* dict = top_dict(root); + if (!dict) { + message = std::format("mcpp.dist.apple: {} ({}) has no top-level .", who, path); + return false; + } + std::vector> pairs; + if (!dict_entries(*dict, pairs, err)) { + message = std::format("mcpp.dist.apple: {} ({}): {}", who, path, err); + return false; + } + std::vector seen; + for (auto const& [key, value] : pairs) { + if (std::ranges::find(derived_plist_keys(), key) != derived_plist_keys().end()) { + message = std::format( + "mcpp.dist.apple: {} ({}) sets {}, which this member derives " + "from its options and the engine; set the option instead.", who, path, key); + return false; + } + if (std::ranges::find(seen, key) != seen.end()) { + message = std::format("mcpp.dist.apple: {} ({}) sets {} twice.", who, path, key); + return false; + } + seen.push_back(key); + plist_entry e; + e.key = key; + e.text = " " + key + "\n"; + xml::write(*value, e.text, 1); + out.push_back(std::move(e)); + } + return true; +} + +// A provisioning profile is a CMS-signed property list. The plist is stored in +// the signed content as-is, so it is read from between its `` rather than through `security cms -D`, which exists only on macOS +// and would make a plan made elsewhere unable to check anything. The signature +// is the device's to verify, not this member's. +inline bool read_profile(const std::string& path, const std::string& bundleId, + std::string& entitlementsPlist, std::string& message) { + namespace xml = mcpp::plugins::xml; + const std::string bytes = read_text(path); + const auto b = bytes.find(""); + if (b == std::string::npos || e == std::string::npos || e < b) { + message = std::format( + "mcpp.dist.apple: `options::provisioning_profile` ({}) carries no property list, so " + "it is not a provisioning profile.", path); + return false; + } + xml::node root; + std::string err; + if (!xml::parse(std::string_view(bytes).substr(b, e + 8 - b), root, err)) { + message = std::format("mcpp.dist.apple: the property list in {} cannot be read: {}", path, err); + return false; + } + const xml::node* dict = top_dict(root); + std::vector> pairs; + if (!dict || !dict_entries(*dict, pairs, err)) { + message = std::format("mcpp.dist.apple: the property list in {} has no readable top-level .", path); + return false; + } + const xml::node* entitlements = nullptr; + for (auto const& [key, value] : pairs) if (key == "Entitlements" && value->name == "dict") entitlements = value; + std::vector> granted; + if (!entitlements || !dict_entries(*entitlements, granted, err)) { + message = std::format("mcpp.dist.apple: the provisioning profile {} states no Entitlements dictionary.", path); + return false; + } + std::string appIdentifier; + for (auto const& [key, value] : granted) + if (key == "application-identifier" && value->children.size() == 1 && value->children.front().name.empty()) + appIdentifier = xml::trim_copy(value->children.front().text); + const auto dot = appIdentifier.find('.'); + const std::string pattern = dot == std::string::npos ? std::string() : appIdentifier.substr(dot + 1); + const bool covers = !pattern.empty() && + (pattern == bundleId || pattern == "*" || + (pattern.ends_with(".*") && bundleId.starts_with(pattern.substr(0, pattern.size() - 1)))); + if (!covers) { + message = std::format( + "mcpp.dist.apple: the provisioning profile {} is for the application identifier '{}', " + "which does not cover the bundle identifier '{}'. Set `options::bundle_id` to match, " + "or use the profile made for it.", path, + appIdentifier.empty() ? std::string("(none)") : appIdentifier, bundleId); + return false; + } + // A WILDCARD PROFILE GRANTS `.*`, AND THE SIGNATURE STATES THE BUNDLE. + // Xcode signs with the application identifier the bundle is, which the + // wildcard covers, rather than with the wildcard itself; the other + // entitlements are the profile's as it states them. + xml::node signedWith = *entitlements; + if (pattern != bundleId) { + const std::string exact = appIdentifier.substr(0, dot + 1) + bundleId; + for (std::size_t k = 0; k + 1 < signedWith.children.size(); ++k) { + auto const& key = signedWith.children[k]; + auto& value = signedWith.children[k + 1]; + if (key.name == "key" && key.children.size() == 1 && + xml::trim_copy(key.children.front().text) == "application-identifier" && + value.name == "string" && value.children.size() == 1 && value.children.front().name.empty()) + value.children.front().text = exact; + } + } + entitlementsPlist = "\n" + "\n" + "\n"; + xml::write(signedWith, entitlementsPlist, 0); + entitlementsPlist += "\n"; + return true; +} + // ─── Plan ────────────────────────────────────────────────────────────────── inline plan plan_for(options opt = {}) { @@ -1233,4 +1604,4 @@ inline bool generate(options opt = {}) { return submit(plan_for(std::move(opt))); } -} // namespace mcpp::dist::apple \ No newline at end of file +} // namespace mcpp::dist::apple diff --git a/dist/apple/internal/layout.cppm b/dist/apple/internal/layout.cppm deleted file mode 100644 index 6488c03..0000000 --- a/dist/apple/internal/layout.cppm +++ /dev/null @@ -1,91 +0,0 @@ -// mcpp.dist.apple.internal.layout -- file, path and launcher-name helpers of mcpp.dist.apple. - -export module mcpp.dist.apple.internal.layout; - -import std; -import mcpp; - -namespace mcpp::dist::apple::detail { - -inline bool is_file(const std::string& p) { - std::error_code ec; - return !p.empty() && std::filesystem::is_regular_file(p, ec); -} - -// Written only when the bytes differ, for the reason `dist/appimage.cppm` -// gives: rewriting identical bytes moves the mtime, and a moved mtime on a -// declared input is indistinguishable from a changed one -- so a second pack -// of an unchanged project would re-copy the bundle and re-sign it. -inline bool write_if_different(const std::filesystem::path& path, - std::string_view bytes) { - std::error_code ec; - std::filesystem::create_directories(path.parent_path(), ec); - if (std::ifstream in(path, std::ios::binary); in) { - std::string old((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - if (old == bytes) return true; - } - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out) return false; - out.write(bytes.data(), static_cast(bytes.size())); - return static_cast(out); -} - -inline std::string read_text(const std::string& path) { - std::ifstream in(path, std::ios::binary); - return std::string((std::istreambuf_iterator(in)), std::istreambuf_iterator()); -} - -inline std::string resolve_path(const std::string& p) { - if (p.empty() || std::filesystem::path(p).is_absolute()) return p; - return (std::filesystem::path(mcpp::manifest_dir()) / p).lexically_normal().string(); -} - -// The program a bundle executes, found in the staged tree: `bin/` -// first, then the tree's top-level entry, then `run.sh`. -// -// THE PROGRAM, NOT THE TREE'S ENTRY SCRIPT. From the release that reads a -// Mach-O program's closure (mcpp 2026.9.14.2), the engine also writes -// `/`, a shell script that executes `bin/` from the -// tree's root. The search used to take that root entry first, which is the -// order `dist/appimage.cppm` needs, and a bundle then executed the script, -// which executed `Contents/MacOS/bin/` -- a file no bundle carries: -// "cannot execute: No such file or directory", exit 126 (macos-15, run -// 34821164486). The script has no work to do inside a bundle, where -// `CFBundleExecutable` names the program directly, and the framework rpath -// `@executable_path/../Frameworks` resolves against the program's own -// directory, which has to be `Contents/MacOS/`. The root entry and `run.sh` -// remain for a tree that carries no `bin/`. -inline std::string launcher_in(const std::string& stage, const std::string& target) { - for (auto candidate : {stage + "/bin/" + target, - stage + "/" + target, - stage + "/run.sh"}) - if (is_file(candidate)) return candidate; - return {}; -} - -// CFBundleExecutable MUST BE A BARE FILENAME, NOT A PATH. -// -// Apple's own bundle documentation describes it as the executable's name -// within `Contents/MacOS/`, and real-world bundle tooling has hit this -// directly enough to be a filed CMake defect: "CFBundleExecutable path in a -// bundle should not be a relative path into bundle." So this member takes -// only the basename of whatever `launcher_in` finds, and the layout step -// copies that file to the top of the executable directory under that name, so -// the name and the file agree wherever in the staged tree it was found. -inline std::string bundle_executable_name(const std::string& launcher_path) { - return std::filesystem::path(launcher_path).filename().string(); -} - -inline std::string sanitize_bundle_id_component(std::string_view s) { - std::string out; - out.reserve(s.size()); - for (char c : s) { - bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') - || (c >= '0' && c <= '9') || c == '-' || c == '.'; - out += ok ? c : '-'; - } - return out; -} - -} // namespace mcpp::dist::apple::detail diff --git a/dist/apple/internal/plist.cppm b/dist/apple/internal/plist.cppm deleted file mode 100644 index 6f97f6a..0000000 --- a/dist/apple/internal/plist.cppm +++ /dev/null @@ -1,236 +0,0 @@ -// mcpp.dist.apple.internal.plist -- Info.plist generation and plist-fragment reading for mcpp.dist.apple. - -export module mcpp.dist.apple.internal.plist; - -import std; -import mcpp; -import mcpp.plugins; -import mcpp.dist.apple.internal.layout; - -namespace mcpp::dist::apple::detail { - -inline std::string plist_escape(std::string_view s) { - std::string out; - out.reserve(s.size()); - for (char c : s) { - switch (c) { - case '&': out += "&"; break; - case '<': out += "<"; break; - case '>': out += ">"; break; - default: out += c; - } - } - return out; -} - -// Written as XML text directly rather than by shelling out to `plutil`: the -// content is a handful of string keys this member already holds, and adding -// a second host tool to discover and invoke would buy nothing over -// formatting the lines by hand. `LSMinimumSystemVersion` / `MinimumOSVersion` -// and `CFBundleIconFile` are omitted rather than emitted empty when their -// inputs are empty -- an empty string in either key is a claim as -// unsupported as omitting the key, so omission is the honest one. -// -// `is_ios` AND `is_sim` DECIDE FOUR KEYS, NOT ONE BRANCH. `MinimumOSVersion` -// replaces `LSMinimumSystemVersion`; `CFBundleSupportedPlatforms`, -// `UIDeviceFamily` and `LSRequiresIPhoneOS` are iOS-only and absent from -// every macOS bundle this member has ever written, which is the -// byte-identical property the macOS fixture depends on; `NSHighResolutionCapable` -// is a macOS concept (Retina-aware drawing on a platform that also has -// non-Retina displays) with nothing to opt into on iOS, so it is macOS-only -// in the other direction. -inline std::string plist_document(const std::string& executable, const std::string& bundle_id, - const std::string& name, const std::string& version, - bool is_ios, bool is_sim, - const std::string& min_os_version, - // The project's own entries (0.11.0), already - // formatted, inserted before ``; and the - // defaulted keys they replace. - const std::string& extra_entries, - const std::vector& replaced_keys, - // macOS: the icon FILE's basename, extension - // included, exactly as `CFBundleIconFile` has - // always taken it. iOS: unused (see - // `ios_icon_stems`) and always empty. - const std::string& mac_icon_name, - // iOS: every PNG stem found in - // `options::icon`'s directory. macOS: unused - // and always empty. - const std::vector& ios_icon_stems) { - std::string doc; - doc += "\n"; - doc += "\n"; - doc += "\n\n"; - doc += std::format(" CFBundleExecutable\n {}\n", - plist_escape(executable)); - doc += std::format(" CFBundleIdentifier\n {}\n", - plist_escape(bundle_id)); - doc += std::format(" CFBundleName\n {}\n", - plist_escape(name)); - doc += std::format(" CFBundleShortVersionString\n {}\n", - plist_escape(version)); - doc += std::format(" CFBundleVersion\n {}\n", - plist_escape(version)); - doc += " CFBundlePackageType\n APPL\n"; - if (!min_os_version.empty()) - doc += std::format(" {}\n {}\n", - is_ios ? "MinimumOSVersion" : "LSMinimumSystemVersion", - plist_escape(min_os_version)); - if (is_ios) { - // `env == "sim"` is the engine's own distinction between the two - // rows (triple.cppm: "the simulator is deliberately not a row of - // its own identity... it has its own SDK"); this key is the one - // place a bundle has to restate it, because `simctl install` and a - // real device's installer both read it to refuse the other kind. - doc += std::format( - " CFBundleSupportedPlatforms\n \n" - " {}\n \n", - is_sim ? "iPhoneSimulator" : "iPhoneOS"); - // `[1, 2]`: iPhone and iPad. Nothing here narrows a project to one - // idiom -- that is a project decision (a size class, a storyboard) - // this member has no basis for making. - const auto replaced = [&](std::string_view k) { - return std::ranges::find(replaced_keys, k) != replaced_keys.end(); - }; - if (!replaced("UIDeviceFamily")) - doc += " UIDeviceFamily\n \n" - " 1\n 2\n \n"; - if (!replaced("LSRequiresIPhoneOS")) - doc += " LSRequiresIPhoneOS\n \n"; - if (!ios_icon_stems.empty()) { - doc += " CFBundleIcons\n \n" - " CFBundlePrimaryIcon\n \n" - " CFBundleIconFiles\n \n"; - for (auto const& stem : ios_icon_stems) - doc += std::format(" {}\n", plist_escape(stem)); - doc += " \n \n \n"; - } - } else { - if (std::ranges::find(replaced_keys, std::string_view("NSHighResolutionCapable")) == replaced_keys.end()) - doc += " NSHighResolutionCapable\n \n"; - // Not in the letter of this member's key list, but added - // deliberately: without it, an icon file this member went to the - // trouble of copying into `Contents/Resources/` is inert -- nothing - // in the bundle would ever reference it, and Finder would show the - // generic application icon regardless of `options::icon`. Wiring the - // file up once it exists is what makes the option do what its name - // says. - if (!mac_icon_name.empty()) - doc += std::format(" CFBundleIconFile\n {}\n", - plist_escape(mac_icon_name)); - } - doc += extra_entries; - doc += "\n\n"; - return doc; -} -// The keys `plist_document` derives, which a project's plist may not restate, -// and the keys it only defaults, which a project's plist replaces. -inline const std::vector& derived_plist_keys() { - static const std::vector v = { - "CFBundleExecutable", "CFBundleIdentifier", "CFBundleName", "CFBundleShortVersionString", - "CFBundleVersion", "CFBundlePackageType", "LSMinimumSystemVersion", "MinimumOSVersion", - "CFBundleSupportedPlatforms", "CFBundleIconFile", "CFBundleIcons"}; - return v; -} -inline const std::vector& defaulted_plist_keys() { - static const std::vector v = {"UIDeviceFamily", "LSRequiresIPhoneOS", "NSHighResolutionCapable"}; - return v; -} - -// The top-level `` of a property list, or null. A document whose root is -// `` itself is accepted as well as a full ``. -inline const mcpp::plugins::xml::node* top_dict(const mcpp::plugins::xml::node& root) { - if (root.name == "dict") return &root; - if (root.name != "plist") return nullptr; - for (auto const& c : root.children) if (c.name == "dict") return &c; - return nullptr; -} - -// The value element after each `` of a ``, as (key, value) pairs. -inline bool dict_entries(const mcpp::plugins::xml::node& dict, - std::vector>& out, - std::string& error) { - namespace xml = mcpp::plugins::xml; - for (std::size_t i = 0; i < dict.children.size(); ++i) { - const auto& k = dict.children[i]; - if (k.name.empty()) continue; - if (k.name != "key") { error = "<" + k.name + "> appears where a is expected"; return false; } - const std::string key = k.children.size() == 1 && k.children.front().name.empty() - ? xml::trim_copy(k.children.front().text) : std::string(); - std::size_t j = i + 1; - while (j < dict.children.size() && dict.children[j].name.empty()) ++j; - if (key.empty() || j >= dict.children.size()) { error = "a without a value"; return false; } - out.emplace_back(key, &dict.children[j]); - i = j; - } - return true; -} - -// One Info.plist entry a fragment states: its key and the plist text of the -// `` and its value, as `plist_document` inserts it. -struct plist_entry { - std::string key; - std::string text; -}; - -// Reads one plist fragment's entries. `who` is how a diagnostic names the -// fragment (`options::info_plist`, or a package's [package.metadata.dist-apple]). -inline bool read_plist_entries(const std::string& path, const std::string& who, - std::vector& out, std::string& message) { - namespace xml = mcpp::plugins::xml; - xml::node root; - std::string err; - if (!xml::parse(read_text(path), root, err)) { - message = std::format("mcpp.dist.apple: {} ({}) cannot be read: {}", who, path, err); - return false; - } - const xml::node* dict = top_dict(root); - if (!dict) { - message = std::format("mcpp.dist.apple: {} ({}) has no top-level .", who, path); - return false; - } - std::vector> pairs; - if (!dict_entries(*dict, pairs, err)) { - message = std::format("mcpp.dist.apple: {} ({}): {}", who, path, err); - return false; - } - std::vector seen; - for (auto const& [key, value] : pairs) { - if (std::ranges::find(derived_plist_keys(), key) != derived_plist_keys().end()) { - message = std::format( - "mcpp.dist.apple: {} ({}) sets {}, which this member derives " - "from its options and the engine; set the option instead.", who, path, key); - return false; - } - if (std::ranges::find(seen, key) != seen.end()) { - message = std::format("mcpp.dist.apple: {} ({}) sets {} twice.", who, path, key); - return false; - } - seen.push_back(key); - plist_entry e; - e.key = key; - e.text = " " + key + "\n"; - xml::write(*value, e.text, 1); - out.push_back(std::move(e)); - } - return true; -} - -} // namespace mcpp::dist::apple::detail - -module :private; - -namespace mcpp::dist::apple::detail { - -inline std::string plist_document(const std::string& executable, const std::string& bundle_id, - const std::string& name, const std::string& version, - bool is_ios, bool is_sim, - const std::string& min_os_version, - const std::string& mac_icon_name, - const std::vector& ios_icon_stems) { - return plist_document(executable, bundle_id, name, version, is_ios, is_sim, min_os_version, - std::string(), std::vector(), mac_icon_name, ios_icon_stems); -} - -} // namespace mcpp::dist::apple::detail diff --git a/dist/apple/internal/signing.cppm b/dist/apple/internal/signing.cppm deleted file mode 100644 index d0bd7d4..0000000 --- a/dist/apple/internal/signing.cppm +++ /dev/null @@ -1,91 +0,0 @@ -// mcpp.dist.apple.internal.signing -- provisioning-profile reading for mcpp.dist.apple. - -export module mcpp.dist.apple.internal.signing; - -import std; -import mcpp; -import mcpp.plugins; -import mcpp.dist.apple.internal.layout; -import mcpp.dist.apple.internal.plist; - -namespace mcpp::dist::apple::detail { - -// A provisioning profile is a CMS-signed property list. The plist is stored in -// the signed content as-is, so it is read from between its `` rather than through `security cms -D`, which exists only on macOS -// and would make a plan made elsewhere unable to check anything. The signature -// is the device's to verify, not this member's. -inline bool read_profile(const std::string& path, const std::string& bundleId, - std::string& entitlementsPlist, std::string& message) { - namespace xml = mcpp::plugins::xml; - const std::string bytes = read_text(path); - const auto b = bytes.find(""); - if (b == std::string::npos || e == std::string::npos || e < b) { - message = std::format( - "mcpp.dist.apple: `options::provisioning_profile` ({}) carries no property list, so " - "it is not a provisioning profile.", path); - return false; - } - xml::node root; - std::string err; - if (!xml::parse(std::string_view(bytes).substr(b, e + 8 - b), root, err)) { - message = std::format("mcpp.dist.apple: the property list in {} cannot be read: {}", path, err); - return false; - } - const xml::node* dict = top_dict(root); - std::vector> pairs; - if (!dict || !dict_entries(*dict, pairs, err)) { - message = std::format("mcpp.dist.apple: the property list in {} has no readable top-level .", path); - return false; - } - const xml::node* entitlements = nullptr; - for (auto const& [key, value] : pairs) if (key == "Entitlements" && value->name == "dict") entitlements = value; - std::vector> granted; - if (!entitlements || !dict_entries(*entitlements, granted, err)) { - message = std::format("mcpp.dist.apple: the provisioning profile {} states no Entitlements dictionary.", path); - return false; - } - std::string appIdentifier; - for (auto const& [key, value] : granted) - if (key == "application-identifier" && value->children.size() == 1 && value->children.front().name.empty()) - appIdentifier = xml::trim_copy(value->children.front().text); - const auto dot = appIdentifier.find('.'); - const std::string pattern = dot == std::string::npos ? std::string() : appIdentifier.substr(dot + 1); - const bool covers = !pattern.empty() && - (pattern == bundleId || pattern == "*" || - (pattern.ends_with(".*") && bundleId.starts_with(pattern.substr(0, pattern.size() - 1)))); - if (!covers) { - message = std::format( - "mcpp.dist.apple: the provisioning profile {} is for the application identifier '{}', " - "which does not cover the bundle identifier '{}'. Set `options::bundle_id` to match, " - "or use the profile made for it.", path, - appIdentifier.empty() ? std::string("(none)") : appIdentifier, bundleId); - return false; - } - // A WILDCARD PROFILE GRANTS `.*`, AND THE SIGNATURE STATES THE BUNDLE. - // Xcode signs with the application identifier the bundle is, which the - // wildcard covers, rather than with the wildcard itself; the other - // entitlements are the profile's as it states them. - xml::node signedWith = *entitlements; - if (pattern != bundleId) { - const std::string exact = appIdentifier.substr(0, dot + 1) + bundleId; - for (std::size_t k = 0; k + 1 < signedWith.children.size(); ++k) { - auto const& key = signedWith.children[k]; - auto& value = signedWith.children[k + 1]; - if (key.name == "key" && key.children.size() == 1 && - xml::trim_copy(key.children.front().text) == "application-identifier" && - value.name == "string" && value.children.size() == 1 && value.children.front().name.empty()) - value.children.front().text = exact; - } - } - entitlementsPlist = "\n" - "\n" - "\n"; - xml::write(signedWith, entitlementsPlist, 0); - entitlementsPlist += "\n"; - return true; -} - -} // namespace mcpp::dist::apple::detail diff --git a/docs/32-dist-apk.md b/docs/32-dist-apk.md index abff3f8..aae19ea 100644 --- a/docs/32-dist-apk.md +++ b/docs/32-dist-apk.md @@ -52,7 +52,7 @@ Commit the lock. Nothing is shrunk or obfuscated, and an archive's ProGuard rules are ignored. **The manifest merge is a stated subset of the Android Gradle plugin's -merger** (`merge_manifests` in `dist/apk/internal/manifest.cppm`): +merger** (`merge_manifests` in `dist/apk.cppm`): - An element is added when the application has none of the same kind and `android:name`. This covers the children of `` diff --git a/mcpp.toml b/mcpp.toml index 7d95f98..6e8f80d 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -29,7 +29,7 @@ import_std = true # # The units divide by what they may import: # -# src/plugins/ `mcpp.plugins`, importing only `std`, so the same code +# src/plugins.cppm `mcpp.plugins`, importing only `std`, so the same code # compiles into `mcpp-embed` -- an ordinary program, which # is what lets the generation be an ACTION and a payload # be that action's declared input @@ -52,9 +52,7 @@ import_std = true # were ordered by PATH, so `rules/spirv.cppm` was compiled before # `src/declare.cppm` and importing it failed with "failed to read compiled # module". They are ordered by their import graph now. -sources = ["src/plugins/plugins.cppm", "src/plugins/stage.cppm", "src/plugins/xml.cppm", - "src/plugins/json.cppm", "src/plugins/graph.cppm", "src/plugins/package.cppm", - "src/plugins/names.cppm", "src/plugins/surface.cppm", "src/plugins/tree.cppm"] +sources = ["src/plugins.cppm"] # EACH RULE STATES WHAT IT COMPILES AND HOW TO REACH IT (mcpp 2026.9.7.1+). # @@ -277,7 +275,7 @@ sources = ["dist/wix.cppm"] implies = ["plugins-core"] [features.dist-apple] -sources = ["dist/apple/apple.cppm", "dist/apple/internal/layout.cppm", "dist/apple/internal/plist.cppm", "dist/apple/internal/signing.cppm"] +sources = ["dist/apple.cppm"] implies = ["plugins-core", "tools-steps"] [features.dist-web] @@ -285,7 +283,7 @@ sources = ["dist/web.cppm"] implies = ["plugins-core"] [features.dist-apk] -sources = ["dist/apk/apk.cppm", "dist/apk/internal/util.cppm", "dist/apk/internal/manifest.cppm", "dist/apk/internal/libraries.cppm"] +sources = ["dist/apk.cppm"] implies = ["plugins-core", "tools-steps"] # `dist-deb` AND `dist-rpm` (0.23.0) SHARE ONE UNIT AND ONE TOOL. Both install diff --git a/segs.json b/segs.json deleted file mode 100644 index 756dae0..0000000 --- a/segs.json +++ /dev/null @@ -1 +0,0 @@ -{"is_file": [385, 408], "refuse": [409, 433], "attach": [434, 451], "target_app": [452, 464], "launcher_exec": [465, 500], "sanitize": [501, 511], "bundle_id_for": [512, 528], "escape": [529, 542], "doc_big": [543, 643], "doc_small": [644, 653], "readtext_resolve": [654, 663], "plist_rest": [664, 756], "profile": [757, 382], "types": [204, 383], "body": [835, 1607]} \ No newline at end of file diff --git a/src/plugins.cppm b/src/plugins.cppm new file mode 100644 index 0000000..2bcf6c6 --- /dev/null +++ b/src/plugins.cppm @@ -0,0 +1,1645 @@ +// mcpp.plugins: the collection's shared library. +// +// Every member of this package is a module interface unit under rules/ or +// tools/, compiled as a host module of its own when the consumer's feature +// request names it. This unit is the lib root: it is compiled before every +// member, so a member may import it. +// +// IT HOLDS WHAT MORE THAN ONE MEMBER NEEDS, AND ONLY THAT. +// +// The lib root is the only unit every member can import. A second unit beside +// it in `[build] sources` is NOT compiled as a host module ahead of the +// members. Measured: a member importing a second lib-root unit failed with +// +// mcpp.plugins.surface: error: failed to read compiled module +// note: imports must be built before being imported +// +// because only the lib root is built first. So shared code lives here rather +// than in a file of its own, and a member that needs it writes +// `import mcpp.plugins;`. +export module mcpp.plugins; + +import std; + +// NO `import mcpp;`. That module exists only inside a build program, and this +// unit has to compile into an ordinary binary too: `mcpp.tools.embed`'s +// executable form is what lets a generated `.S` be an ACTION's output, which +// is the only way the payload it embeds can be a declared input of the edge +// that assembles it. Measured before this: an ordinary build of this package +// failed with `mcpp: failed to read compiled module`. +// +// Everything this unit used to read from that module -- the target OS, whether +// the toolchain has a GAS assembler, the package's name -- is now a parameter. +// The members under rules/ still import it; they are feature-gated, so the +// tool's own build never compiles them. + +export namespace mcpp::plugins { + +// THIS MUST EQUAL `[package] version` IN mcpp.toml, AND CI CHECKS THAT IT DOES. +// +// It was `0.1.1` while the package was `0.2.6`, which nothing noticed because +// nothing read it. A value that is recorded and never read cannot be wrong in a +// way anyone sees, so the fix is not only to correct it: every rule now states +// it with `mcpp::fact`, which makes a build log answer "which collection +// produced these actions" and makes a stale constant a visible defect rather +// than a dormant one. +// +// One package, one version: the number lives in mcpp.toml, and the CI step +// `the collection states its own version` compares the two. +inline constexpr std::string_view version = "0.27.0"; + +} // namespace mcpp::plugins + +// mcpp::plugins::stage -- what the engine wrote beside a staged tree. +// +// SHARED BECAUSE TWO DIST MEMBERS READ IT. `mcpp pack` writes +// `.stage-manifest` (mcpp's docs/50, "The stage manifest"): a +// header, one `needs` line per library name the closure read (mcpp +// 2026.9.14.2+), and the list of staged files. `dist-apk` reads it to trust the +// native libraries under `lib/`, and `dist-apple` reads it to tell the dylibs +// staged beside a program from the resources staged there. Only the header and +// the `needs` lines are parsed; the file list is not. +export namespace mcpp::plugins::stage { + +struct need { + std::string name; // as the needing object spells it + std::string where; // a staged path relative to the tree, `platform` or `unresolved` +}; + +struct manifest { + bool found = false; // the file exists beside the tree + bool walked = true; // `closure = walked` + std::string reason; // `reason = ...`, with `closure = not-walked` + std::vector needs; +}; + +inline manifest read_manifest(std::string tree) { + manifest m; + while (tree.size() > 1 && (tree.back() == '/' || tree.back() == '\\')) + tree.pop_back(); + std::ifstream in(tree + ".stage-manifest", std::ios::binary); + if (!in) return m; + m.found = true; + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line == "closure = not-walked") { m.walked = false; continue; } + if (line.starts_with("reason = ")) { m.reason = line.substr(9); continue; } + if (!line.starts_with("needs\t")) continue; + const auto second = line.find('\t', 6); + if (second == std::string::npos) continue; + m.needs.push_back({ line.substr(6, second - 6), line.substr(second + 1) }); + } + return m; +} + +} // namespace mcpp::plugins::stage + +// mcpp::plugins::xml -- the XML two dist members read and write. +// +// SHARED BECAUSE TWO DIST MEMBERS READ IT. `dist-apk` merges library manifests +// into an application's, and `dist-apple` adds a project's Info.plist entries +// and reads the plist a provisioning profile carries. Neither needs more than +// elements, attributes and text, and neither interprets an entity, so this is +// that much and no more: no namespaces resolved, no DTD read, no validation. +export namespace mcpp::plugins::xml { + +// A tree of elements and text. Comments, the XML declaration and a DOCTYPE are +// read and dropped: the documents this member writes from a tree are generated +// files, and a merged manifest carries no author to read a comment. Attribute +// values are kept exactly as written, entities included, because nothing here +// interprets them beyond comparing and substituting `${applicationId}`. +struct node { + std::string name; // empty: a text node + std::vector> attrs; + std::vector children; + std::string text; // a text node's characters +}; + +struct reader { + std::string_view s; + std::size_t i = 0; + std::string error; + + static bool space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } + bool starts(std::string_view t) const { return s.substr(i, t.size()) == t; } + void skip_space() { while (i < s.size() && space(s[i])) ++i; } + bool skip_past(std::string_view end) { + const auto p = s.find(end, i); + if (p == std::string_view::npos) { i = s.size(); return false; } + i = p + end.size(); + return true; + } + std::string name() { + const std::size_t b = i; + while (i < s.size() && !space(s[i]) && s[i] != '>' && s[i] != '/' && s[i] != '=') ++i; + return std::string(s.substr(b, i - b)); + } + + bool element(node& out) { + ++i; // '<' + out.name = name(); + if (out.name.empty()) { error = "an element without a name"; return false; } + for (;;) { + skip_space(); + if (i >= s.size()) { error = "<" + out.name + "> is not terminated"; return false; } + if (starts("/>")) { i += 2; return true; } + if (s[i] == '>') { ++i; break; } + std::string attr = name(); + skip_space(); + if (attr.empty() || i >= s.size() || s[i] != '=') { + error = "an attribute of <" + out.name + "> has no value"; + return false; + } + ++i; + skip_space(); + if (i >= s.size() || (s[i] != '"' && s[i] != '\'')) { + error = "attribute " + attr + " of <" + out.name + "> is not quoted"; + return false; + } + const char quote = s[i++]; + const auto end = s.find(quote, i); + if (end == std::string_view::npos) { error = "attribute " + attr + " is not terminated"; return false; } + out.attrs.emplace_back(std::move(attr), std::string(s.substr(i, end - i))); + i = end + 1; + } + for (;;) { + if (i >= s.size()) { error = "<" + out.name + "> is not closed"; return false; } + if (starts("= s.size() || s[i] != '>') { + error = " closes <" + out.name + ">"; + return false; + } + ++i; + return true; + } + if (starts("")) { error = "a comment is not terminated"; return false; } continue; } + if (starts("")) { error = "a processing instruction is not terminated"; return false; } continue; } + if (starts("")) { error = "a CDATA section is not terminated"; return false; } + node t; + t.text = std::string(s.substr(b, i - b)); + out.children.push_back(std::move(t)); + continue; + } + if (s[i] == '<') { + node child; + if (!element(child)) return false; + out.children.push_back(std::move(child)); + continue; + } + const std::size_t b = i; + auto end = s.find('<', i); + if (end == std::string_view::npos) end = s.size(); + i = end; + bool blank = true; + for (std::size_t j = b; j < end; ++j) if (!space(s[j])) { blank = false; break; } + if (!blank) { + node t; + t.text = std::string(s.substr(b, end - b)); + out.children.push_back(std::move(t)); + } + } + } + + bool document(node& root) { + for (;;) { + skip_space(); + if (starts(""); continue; } + if (starts(""); continue; } + if (starts(""); continue; } + break; + } + if (i >= s.size() || s[i] != '<') { error = "no root element"; return false; } + if (!element(root)) return false; + return true; + } +}; + +inline bool parse(std::string_view text, node& root, std::string& error) { + reader r{text}; + if (!r.document(root)) { error = r.error; return false; } + return true; +} + +inline std::string trim_copy(const std::string& s) { + std::size_t b = 0, e = s.size(); + while (b < e && reader::space(s[b])) ++b; + while (e > b && reader::space(s[e - 1])) --e; + return s.substr(b, e - b); +} + +inline void write(const node& n, std::string& out, int depth) { + const std::string pad(static_cast(depth) * 4, ' '); + if (n.name.empty()) { out += pad + trim_copy(n.text) + "\n"; return; } + out += pad + "<" + n.name; + for (auto const& a : n.attrs) out += " " + a.first + "=\"" + a.second + "\""; + if (n.children.empty()) { out += "/>\n"; return; } + if (n.children.size() == 1 && n.children.front().name.empty()) { + out += ">" + n.children.front().text + "\n"; + return; + } + out += ">\n"; + for (auto const& c : n.children) write(c, out, depth + 1); + out += pad + "\n"; +} + +inline std::string attr_of(const node& n, std::string_view key) { + for (auto const& a : n.attrs) if (a.first == key) return a.second; + return {}; +} + +inline void set_attr(node& n, const std::string& key, const std::string& value) { + for (auto& a : n.attrs) if (a.first == key) { a.second = value; return; } + n.attrs.emplace_back(key, value); +} + +} // namespace mcpp::plugins::xml + +// mcpp::plugins::json -- the JSON two dist members read. +// +// SHARED BECAUSE TWO DOCUMENTS ARE READ WITH IT. `dist-apk` reads coursier's +// resolution report, and `mcpp::plugins::graph` below reads the engine's graph +// document for `dist-apk` and `dist-apple`. A second parser for the second +// document is how two readers come to disagree about one file, so there is one. +// It reads objects, arrays, strings (with `\u` escapes, surrogate pairs +// included, and a refusal for a surrogate that is not part of one), numbers, +// `true`, `false` and `null`; a number keeps its spelling in `text`. +export namespace mcpp::plugins::json { + +// A MEMBER IS ITS OWN STRUCT, NOT `std::pair`. Under clang +// with libstdc++'s `std` module, `pair` inside `value` is +// instantiated while `value` is still incomplete -- its destructor needs the +// pair and the pair needs `value` -- and the unit fails with "incomplete type +// used in type trait expression". GCC accepts the pair and so does clang with +// libc++, so neither build lane saw it; clangd reading a GCC project in the +// editor is exactly that combination. A plain aggregate, with `get()` defined +// once both types are complete, compiles under all three. +struct member; + +struct value { + enum class kind { null, boolean, number, string, array, object }; + kind type = kind::null; + std::string text; // string, number or boolean spelling + std::vector items; + std::vector members; + + const value* get(std::string_view key) const; +}; + +struct member { + std::string first; + value second; +}; + +inline const value* value::get(std::string_view key) const { + for (auto const& m : members) if (m.first == key) return &m.second; + return nullptr; +} + +struct reader { + std::string_view s; + std::size_t i = 0; + + void skip_space() { + while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i; + } + // The four hexadecimal digits of one `\u` escape, `i` already past the `u`. + bool hex4(unsigned& cp) { + if (i + 4 > s.size()) return false; + cp = 0; + for (int k = 0; k < 4; ++k) { + const char h = s[i++]; + cp <<= 4; + if (h >= '0' && h <= '9') cp |= static_cast(h - '0'); + else if (h >= 'a' && h <= 'f') cp |= static_cast(h - 'a' + 10); + else if (h >= 'A' && h <= 'F') cp |= static_cast(h - 'A' + 10); + else return false; + } + return true; + } + bool string(std::string& out) { + if (i >= s.size() || s[i] != '"') return false; + ++i; + while (i < s.size() && s[i] != '"') { + if (s[i] != '\\') { out += s[i++]; continue; } + if (++i >= s.size()) return false; + const char e = s[i++]; + switch (e) { + case 'n': out += '\n'; break; + case 't': out += '\t'; break; + case 'r': out += '\r'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'u': { + // A code point above U+FFFF reaches JSON as a surrogate + // PAIR, which is two `\u` escapes. Encoding each half on its + // own produces two three-byte sequences holding unpaired + // surrogates -- not UTF-8, and accepted by nothing that + // reads the manifest this value is written into. The pair is + // combined here, and a surrogate that is not part of one is + // refused, so a malformed document is a refusal rather than + // a silently corrupted string. + unsigned cp = 0; + if (!hex4(cp)) return false; + if (cp >= 0xd800 && cp <= 0xdbff) { + if (i + 6 > s.size() || s[i] != '\\' || s[i + 1] != 'u') return false; + i += 2; + unsigned lo = 0; + if (!hex4(lo)) return false; + if (lo < 0xdc00 || lo > 0xdfff) return false; + cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); + } else if (cp >= 0xdc00 && cp <= 0xdfff) { + return false; // a low surrogate with no high half + } + if (cp < 0x80) out += static_cast(cp); + else if (cp < 0x800) { out += static_cast(0xc0 | (cp >> 6)); out += static_cast(0x80 | (cp & 0x3f)); } + else if (cp < 0x10000) { out += static_cast(0xe0 | (cp >> 12)); out += static_cast(0x80 | ((cp >> 6) & 0x3f)); out += static_cast(0x80 | (cp & 0x3f)); } + else { + out += static_cast(0xf0 | (cp >> 18)); + out += static_cast(0x80 | ((cp >> 12) & 0x3f)); + out += static_cast(0x80 | ((cp >> 6) & 0x3f)); + out += static_cast(0x80 | (cp & 0x3f)); + } + break; + } + default: out += e; + } + } + if (i >= s.size()) return false; + ++i; + return true; + } + bool parse_value(value& out) { + skip_space(); + if (i >= s.size()) return false; + const char c = s[i]; + if (c == '"') { out.type = value::kind::string; return string(out.text); } + if (c == '{') { + out.type = value::kind::object; + ++i; + skip_space(); + if (i < s.size() && s[i] == '}') { ++i; return true; } + for (;;) { + skip_space(); + std::string key; + if (!string(key)) return false; + skip_space(); + if (i >= s.size() || s[i] != ':') return false; + ++i; + value v; + if (!parse_value(v)) return false; + out.members.emplace_back(std::move(key), std::move(v)); + skip_space(); + if (i < s.size() && s[i] == ',') { ++i; continue; } + if (i < s.size() && s[i] == '}') { ++i; return true; } + return false; + } + } + if (c == '[') { + out.type = value::kind::array; + ++i; + skip_space(); + if (i < s.size() && s[i] == ']') { ++i; return true; } + for (;;) { + value v; + if (!parse_value(v)) return false; + out.items.push_back(std::move(v)); + skip_space(); + if (i < s.size() && s[i] == ',') { ++i; continue; } + if (i < s.size() && s[i] == ']') { ++i; return true; } + return false; + } + } + const std::size_t b = i; + while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' && + s[i] != ' ' && s[i] != '\n' && s[i] != '\r' && s[i] != '\t') ++i; + out.text = std::string(s.substr(b, i - b)); + if (out.text == "null") out.type = value::kind::null; + else if (out.text == "true" || out.text == "false") out.type = value::kind::boolean; + else out.type = value::kind::number; + return !out.text.empty(); + } +}; + +// The whole text is one value, with nothing but white space after it. +inline bool parse_json(std::string_view text, value& out) { + reader r{text}; + if (!r.parse_value(out)) return false; + r.skip_space(); + return r.i == r.s.size(); +} + +// A string member of an object, or empty when absent or not a string. +inline std::string string_of(const value* v) { + return v && v->type == value::kind::string ? v->text : std::string(); +} + +} // namespace mcpp::plugins::json + +// mcpp::plugins::graph -- the resolved dependency graph the engine states. +// +// mcpp 2026.9.16.1 gives the ROOT project's build program `MCPP_GRAPH_FILE` +// (`mcpp::graph_file()`), a document naming every package of the resolved graph, +// dependencies before their requesters, each with its manifest directory and its +// `[package.metadata]` verbatim (mcpp docs/30, "Reading the resolved graph"). A +// member that merges what libraries contribute reads a table of its own out of +// that metadata: `[package.metadata.dist-apk]`, `[package.metadata.dist-apple]`. +// +// READ THROUGH THE ENVIRONMENT, NOT `mcpp::graph_file()`. This unit does not +// import `mcpp` (see the top of this file), and a member that called the +// accessor would not compile against an engine older than the one that added it. +// An unset or empty variable is an older engine, or a dependency's program, and +// reads as a graph with no packages, which leaves every member's behaviour as it +// was. +export namespace mcpp::plugins::graph { + +struct package { + std::string canonical; // `namespace.name@version` + std::string name; + std::string namespace_; + std::string version; + bool root = false; + std::string manifest_dir; // absolute + json::value metadata; // the package's [package.metadata], an object +}; + +struct document { + bool present = false; // MCPP_GRAPH_FILE named a file + std::string path; + std::vector packages; // dependencies before requesters +}; + +// The graph this build program was given, or the reason it cannot be read. A +// variable naming a file that is missing or not a `mcpp.graph` document is an +// error rather than an empty graph: the engine promised a document, and reading +// nothing would silently drop every contribution. +inline std::expected read() { + document d; + const char* env = std::getenv("MCPP_GRAPH_FILE"); + if (!env || !*env) return d; + d.present = true; + d.path = env; + std::ifstream in(d.path, std::ios::binary); + if (!in) + return std::unexpected(std::format("the graph document {} cannot be read", d.path)); + const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + json::value doc; + if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) + return std::unexpected(std::format("the graph document {} is not JSON", d.path)); + if (json::string_of(doc.get("kind")) != "mcpp.graph") + return std::unexpected(std::format("the graph document {} is not a mcpp.graph document", d.path)); + const json::value* list = doc.get("packages"); + if (!list || list->type != json::value::kind::array) + return std::unexpected(std::format("the graph document {} has no packages array", d.path)); + for (auto const& entry : list->items) { + if (entry.type != json::value::kind::object) continue; + package p; + if (const json::value* id = entry.get("package")) { + p.canonical = json::string_of(id->get("canonical")); + p.name = json::string_of(id->get("name")); + p.namespace_ = json::string_of(id->get("namespace")); + p.version = json::string_of(id->get("version")); + } + if (const json::value* r = entry.get("root")) + p.root = r->type == json::value::kind::boolean && r->text == "true"; + p.manifest_dir = json::string_of(entry.get("manifest_dir")); + if (const json::value* m = entry.get("metadata"); m && m->type == json::value::kind::object) + p.metadata = *m; + d.packages.push_back(std::move(p)); + } + return d; +} + +// The package's `[package.metadata.]` table, or null. +inline const json::value* table_of(const package& p, std::string_view tool) { + const json::value* t = p.metadata.get(tool); + return t && t->type == json::value::kind::object ? t : nullptr; +} + +// A path a package states, made absolute against its manifest directory. +inline std::string resolve(const package& p, const std::string& path) { + if (path.empty() || std::filesystem::path(path).is_absolute()) return path; + return (std::filesystem::path(p.manifest_dir) / path).lexically_normal().string(); +} + +// How a diagnostic names a package: its canonical identity, or its name. +inline std::string label_of(const package& p) { + return !p.canonical.empty() ? p.canonical : p.name; +} + +} // namespace mcpp::plugins::graph + +// mcpp::plugins::package -- the metadata of a staged package. +// +// `mcpp pack` (2026.10.27.1+, SPEC-014 §4.5) writes `mcpp-package.json` at the +// root of every staged tree: the package, its three axes, its legs, the systems +// whose loaders it carries, how it is started, and every file with its role, +// its leg and its digest. It is the input of a package format's provider, of +// `mcpp pack --merge` and of `mcpp emit xpkg`. A provider reads it here rather +// than walking the tree and deciding for itself which file is the program: the +// engine has already decided, once, for every format. +// +// SCHEMA 1 AND ONLY SCHEMA 1. A document of another schema is refused rather +// than read as far as it goes: a field whose meaning changed would be read +// with the old one. +export namespace mcpp::plugins::package { + +struct file { + std::string path; // relative to the tree's root, `/`-separated + std::string role; // program | image | library | loader | launcher | resource | metadata + std::string leg; // the leg's triple; empty when every leg shares the file + std::string sha256; +}; + +struct info { + int schema = 0; + std::string name; + std::string version; + std::string platform; // `@`; empty: none + std::string linkage; // static | shared | declared + std::string mode; // system | vendored | self-contained | static + std::vector legs; // canonical triples + std::vector systems; // `-` of the loaders under libexec/ + std::vector runner; // the platform's runner argv; empty: native + // The entry of each architecture (universal packages), in the document's + // order: architecture, then the entry's path in the tree. + std::vector> entry; + std::string program; // the program's path (one native leg) + std::vector files; + std::string root; // the tree the document was read from +}; + +namespace detail { + +inline std::vector strings_of(const json::value* v) { + std::vector out; + if (!v || v->type != json::value::kind::array) return out; + for (auto const& item : v->items) + if (item.type == json::value::kind::string) out.push_back(item.text); + return out; +} + +} // namespace detail + +// The document at `/mcpp-package.json`, or why it cannot be read. +inline std::expected read(std::string_view stage_dir) { + std::string root(stage_dir); + while (root.size() > 1 && (root.back() == '/' || root.back() == '\\')) root.pop_back(); + const std::string path = root + "/mcpp-package.json"; + std::ifstream in(path, std::ios::binary); + if (!in) return std::unexpected(std::format("{} cannot be read: the tree is not a staged package", path)); + const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + json::value doc; + if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) + return std::unexpected(std::format("{} is not a JSON object", path)); + info p; + p.root = root; + if (const json::value* s = doc.get("schema"); s && s->type == json::value::kind::number) + p.schema = std::atoi(s->text.c_str()); + if (p.schema != 1) + return std::unexpected(std::format( + "{} states schema {}; this collection reads schema 1 (mcpp SPEC-014 §4.5)", path, p.schema)); + p.name = json::string_of(doc.get("name")); + p.version = json::string_of(doc.get("version")); + p.platform = json::string_of(doc.get("platform")); + p.linkage = json::string_of(doc.get("linkage")); + p.mode = json::string_of(doc.get("mode")); + p.legs = detail::strings_of(doc.get("legs")); + p.systems = detail::strings_of(doc.get("systems")); + if (const json::value* launch = doc.get("launch"); launch && launch->type == json::value::kind::object) { + p.runner = detail::strings_of(launch->get("runner")); + p.program = json::string_of(launch->get("program")); + if (const json::value* e = launch->get("entry"); e && e->type == json::value::kind::object) + for (auto const& m : e->members) + if (m.second.type == json::value::kind::string) p.entry.emplace_back(m.first, m.second.text); + } + const json::value* files = doc.get("files"); + if (!files || files->type != json::value::kind::array) + return std::unexpected(std::format("{} has no files array", path)); + for (auto const& f : files->items) { + if (f.type != json::value::kind::object) continue; + p.files.push_back({ json::string_of(f.get("path")), json::string_of(f.get("role")), + json::string_of(f.get("leg")), json::string_of(f.get("sha256")) }); + } + return p; +} + +// The files of `p` with `role`, in the document's order. +inline std::vector files_with_role(const info& p, std::string_view role) { + std::vector out; + for (auto const& f : p.files) + if (f.role == role) out.push_back(f); + return out; +} + +// The entry of `arch`, or empty. +inline std::string entry_of(const info& p, std::string_view arch) { + for (auto const& [a, path] : p.entry) + if (a == arch) return path; + return {}; +} + +} // namespace mcpp::plugins::package + +// mcpp::plugins::names -- the derivations that turn a path into a C++ name. +// +// THESE ARE SHARED BECAUSE THEY WERE COPIED. `common_base_dir` and +// `namespace_of` were written in `rules/spirv.cppm` and written again in +// `rules/slang.cppm`, and `mcpp.tools.island` is the third caller needing the +// same answers. Two copies that agree today are still two copies: a directory +// named `default` or `2d` has to get ONE answer, and one function is how that +// is guaranteed rather than two files that happen to say the same thing. +export namespace mcpp::plugins::names { + +// `a` made relative to the directory `b`, as strings: separators unified, and +// the prefix stripped when `a` lies under `b`; `a` unchanged otherwise. +// +// NOTHING IN THIS PACKAGE INSTANTIATES `std::filesystem::path`'s ITERATOR -- +// see `components()` below for the compiler that refuses it. The members' +// relative-path arithmetic is this string function, defined once here. +inline std::string relative_to(std::string a, std::string b) { + for (auto& c : a) if (c == '\\') c = '/'; + for (auto& c : b) if (c == '\\') c = '/'; + while (!b.empty() && b.back() == '/') b.pop_back(); + if (!b.empty() && a.starts_with(b + "/")) return a.substr(b.size() + 1); + return a; +} + +// A GENERATED NAME THE C++ COMPILER WILL ACCEPT. +// +// Three transformations, and the third is the one every hand-rolled copy of +// this function was missing. Non-identifier characters become `_`; a leading +// digit gets a `_` in front; and a result that is a KEYWORD gets a trailing `_`. +// +// The keyword case is not hypothetical. The first two rules accept `default`, +// `template`, `operator`, `private` and `union` unchanged -- they are valid +// identifiers to a character filter and reserved to the compiler -- and +// `shaders/default/` is an ordinary name for a shader directory. What it +// produced was `namespace default {` in a generated file, and an error naming a +// line its author never wrote. +// +// TRAILING `_`, not a prefix: `_default` is reserved at namespace scope +// (a leading underscore in the global namespace), and prefixing would trade one +// reserved name for another. +// +// The list is the keywords of the standard this collection targets. A word that +// is contextual rather than reserved (`final`, `override`, `import`, `module`) +// is a legal identifier and is left alone. +inline bool is_cxx_keyword(std::string_view w) { + static constexpr std::string_view kWords[] = { + "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", + "bool", "break", "case", "catch", "char", "char8_t", "char16_t", + "char32_t", "class", "compl", "concept", "const", "consteval", + "constexpr", "constinit", "const_cast", "continue", "co_await", + "co_return", "co_yield", "decltype", "default", "delete", "do", "double", + "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", + "float", "for", "friend", "goto", "if", "inline", "int", "long", + "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", + "operator", "or", "or_eq", "private", "protected", "public", "register", + "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", + "static", "static_assert", "static_cast", "struct", "switch", + "template", "this", "thread_local", "throw", "true", "try", "typedef", + "typeid", "typename", "union", "unsigned", "using", "virtual", "void", + "volatile", "wchar_t", "while", "xor", "xor_eq", + }; + for (auto k : kWords) if (k == w) return true; + return false; +} + +// `fallback` is used when the input sanitises to nothing, which a file named +// only in punctuation does. +// +// INDEXED RATHER THAN A RANGE-FOR over the string, for the reason recorded in +// `mcpp.tools.island`: iterating a `std::string` inside an exported inline +// function makes GCC 16 instantiate its iterator in this BMI, and a consumer's +// build program then fails to compile on `always_inline` in a header naming +// neither this file nor this loop. +inline std::string identifier(std::string_view raw, std::string_view fallback) { + std::string s; + for (std::size_t i = 0; i < raw.size(); ++i) { + const char c = raw[i]; + s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; + } + if (s.empty()) s = std::string(fallback); + if (!s.empty() && std::isdigit(static_cast(s.front()))) + s.insert(s.begin(), '_'); + if (is_cxx_keyword(s)) s += '_'; + return s; +} + + +// ---- internals ------------------------------------------------------------- + +inline std::vector split_module_name(std::string_view name) { + std::vector out; + for (std::size_t i = 0; i <= name.size();) { + auto dot = name.find('.', i); + auto one = dot == std::string_view::npos ? name.substr(i) : name.substr(i, dot - i); + if (!one.empty()) out.emplace_back(one); + if (dot == std::string_view::npos) break; + i = dot + 1; + } + return out; +} + +// THE BASE DIRECTORY IS DERIVED, NOT ASKED FOR. +// +// A payload's namespace comes from where it sits relative to the tree the +// project globbed, so something has to say where that tree starts. Asking the +// project would put a second spelling of the glob in the manifest, and the two +// would disagree the first time a glob moved. The shallowest directory every +// path shares is the same answer without the second spelling: for +// `shaders/*.comp` it is `shaders` and every namespace is empty; for +// `shaders/a/x.comp` and `shaders/b/y.comp` it is still `shaders`, and the two +// land in `::a` and `::b`. +// +// A single path has no common prefix with anything, so its own directory is the +// base and its namespace is empty -- which is the same answer the general case +// gives once a second file appears beside it. +// A path's components as strings: both separators split, empty and `.` +// components dropped. This is the one place the lib root reads a path apart, +// and it does so WITHOUT `std::filesystem::path`'s iterator on purpose: +// +// A MODULE THAT INSTANTIATES `_Path_iterator` POISONS ITS IMPORTERS UNDER MSVC +// 14.52. Measured on xrgui's CI (14.52.36629 and .36725): this unit compiled +// while it iterated paths, and every member importing it that then touched +// `std::filesystem` at all failed inside the STL -- +// +// include\filesystem(1572): error C2801: '..._Path_iterator<...>::operator ==' +// must be a non-static member +// +// -- the iterator's hidden-friend comparison, refused when the importer meets +// it both through `import std` and through this module's BMI. Removing the +// calls from the members changed nothing; the instantiation had to leave the +// lib root. Component comparison is what `lexically_relative` bought in 0.5.2 +// (a Windows separator bug), and splitting on both separators keeps that. +inline std::vector components(std::string_view path) { + std::vector out; + std::string cur; + auto flush = [&] { if (!cur.empty() && cur != ".") out.push_back(cur); cur.clear(); }; + for (char c : path) { if (c == '/' || c == '\\') flush(); else cur += c; } + flush(); + return out; +} + +// The directory part of a path, as written: everything before the last +// separator, or empty when there is none. +inline std::string_view parent_of(std::string_view path) { + const auto slash = path.find_last_of("/\\"); + return slash == std::string_view::npos ? std::string_view{} : path.substr(0, slash); +} + +inline std::string common_base_dir(std::span paths) { + std::vector prefix; + bool first = true; + for (auto const& src : paths) { + auto segs = components(parent_of(src)); + if (first) { prefix = std::move(segs); first = false; continue; } + std::size_t keep = 0; + while (keep < prefix.size() && keep < segs.size() && prefix[keep] == segs[keep]) ++keep; + prefix.resize(keep); + } + std::string out; + for (auto const& s : prefix) { if (!out.empty()) out += '/'; out += s; } + return out; +} + +// The namespace segments a file sits in, below the group's own: the path from +// the base directory to the file, sanitised one segment at a time. +// +// RELATIVE BY PATH ARITHMETIC, NOT BY STRING SURGERY, AND THAT IS A WINDOWS +// FIX. This trimmed `base` off the front of the directory as a STRING and +// iterated what was left. On Windows the two spellings differ even when the +// two paths are the same: a caller states a root with forward slashes, and +// `directory_iterator` appends with the preferred separator, so the leftover +// was `\image` rather than `image`. Iterating that yields the ROOT DIRECTORY +// as its first component, which sanitised to `_` -- and the payload landed in +// `myapp::shaders::_::image`, a namespace no consumer writes. Measured: the +// island fixture failed to compile on windows-2022 with `no member named +// 'image' in namespace 'island_interface::kernels'`, while the same fixture +// passed on Linux and macOS. +// +// COMPONENTS are compared, so the separator a caller happened to write is not +// part of the question -- `components()` splits on both. A base that is not a +// prefix is a caller error rather than a namespace; it answers with no +// segments rather than with the whole absolute path, which is what the first +// string form produced. (Through `components()` rather than +// `lexically_relative` for the reason stated on it.) +inline std::vector namespace_of(std::string_view src, std::string_view base) { + std::vector out; + auto dir = components(parent_of(src)); + if (!base.empty()) { + const auto b = components(base); + if (b.size() > dir.size()) return out; + for (std::size_t i = 0; i < b.size(); ++i) if (b[i] != dir[i]) return out; + dir.erase(dir.begin(), dir.begin() + static_cast(b.size())); + } + for (auto const& s : dir) { + if (s == "..") continue; + // `shaders/default/` is an ordinary directory name and + // `namespace default {` is not a namespace. + out.push_back(identifier(s, "dir")); + } + return out; +} +} // namespace mcpp::plugins::names + + +// mcpp.plugins.surface -- the interface a consumer names for an embedded payload. +// +// WHY THIS IS SHARED RATHER THAN PER-RULE. +// +// `mcpp.rules.spirv` and `mcpp.rules.slang` produce the same kind of thing: a +// block of bytes the program hands to a device API. `mcpp.tools.embed` produces +// it from a file that was already there. The three differ in who produces the +// bytes and disagree about nothing else, so the declaration a consumer reads is +// written once, here, and the shape is identical whichever produced it. A rule +// that wrote its own would be a second copy of a decision, and the two would +// drift the way the two shader compilers' headers drifted before 0.2.6. +// +// THE INTERFACE IS A FUNCTION, NOT A VARIABLE. +// +// A variable cannot keep one shape across the ways bytes can be stored, because +// `constexpr` and `extern` are mutually exclusive: an array compiled into a +// translation unit can be constant-evaluated and one living in a section cannot. +// A function can, so where the bytes live stays an option a project revises +// without touching a consumer. +// +// THE INTERFACE NAMES NO STANDARD-LIBRARY TYPE, AND THAT IS MEASURED. +// +// The same 1 MB payload, reached four ways, compiled with GCC 16.1: +// +// data in the module (`export inline constexpr`) BMI 6 282 240 B +// data in a header source 3 145 728 B +// data in an object, interface returns std::span BMI 1 313 968 B +// data in an object, interface returns a std-free POD BMI 1 808 B +// +// The third row is 727 times the fourth, and its cost is FIXED rather than +// proportional to the payload: the 1.28 MB is ``'s templates, present +// whether the payload is 16 KB or 16 MB. A consumer that wants a `std::span` +// constructs one from the two members, and `` is then included by the +// consumer that uses it rather than by every consumer that imports this. +// +// There is a second, independent reason for the same decision. `import std;` +// requires `std.gcm` to have been built, which a project with +// `modules = true, import_std = false` has not done. A std-free interface needs +// neither. +// +// WHY THE ACCESSORS HAVE C LANGUAGE LINKAGE. +// +// A function declared in a module interface has module linkage and can only be +// defined by a unit attached to that module. Defining them would therefore need +// a module implementation unit, and the definitions include the generated data +// headers -- which would put the arrays back into the interface's own +// compilation. Declaring the accessors `extern "C"` instead gives them external +// linkage, so an ordinary translation unit defines them, the module interface +// holds two declarations and one inline call per payload, and the bytes are +// never seen by the interface at all. +// +// It also removes a portability question: module implementation units are the +// least exercised corner of every implementation this package supports, and +// nothing here needs them. +// +// ONE COPY OF THE BYTES. +// +// A generated data header declares `static const uint32_t []`, so every +// translation unit that includes it gets its own copy. Under this surface +// exactly one translation unit includes it -- the generated implementation -- +// and every consumer reaches the same array through the accessor. +export namespace mcpp::plugins::surface { + +// The name derivations live in `mcpp::plugins::names`. They are reachable under +// this namespace as well, because every rule in this collection already spells +// them this way -- one definition under two spellings is not two definitions. +using names::identifier; +using names::split_module_name; +using names::common_base_dir; +using names::namespace_of; + +// How a consumer names the payloads. +// +// `module_` is the default where the project builds C++ modules, and +// `c_header` is what a project without them gets. The choice does not change +// any declaration's shape: the same struct, the same function names, the same +// namespaces. Only the file a consumer reaches them through differs. +enum class kind { module_, c_header }; + +// WHICH HALF OF THE SURFACE A CALL WRITES. +// +// The two are separate because their INPUTS are. The interface is a function of +// the item list: names, namespaces, the accessor declarations. The body is a +// function of the item list AND, under `storage::object`, of the payloads +// themselves -- the assembly names each one in `.incbin`, and the object it +// produces is those bytes. +// +// Declaring them as one action would make a payload change rewrite the +// interface too, and rebuild every BMI that imports it. Declaring them +// separately states what is true and costs a consumer nothing. +enum class half { interface_, body }; + +// The element the accessor hands back. `word32` is what an API taking +// `const uint32_t*` wants -- `vkCreateShaderModule` is the case this package +// has -- and asking for it here is cheaper than a reinterpret_cast at every +// call site, which is undefined behaviour on an under-aligned byte array. +enum class element { byte_, word32 }; + +// WHERE THE BYTES LIVE. Orthogonal to `kind`, which decides how a consumer +// NAMES them: the declarations are identical under all three, so a project +// changes this and no consumer changes. +// +// WHICH ONE TO USE IS A MEASUREMENT, NOT A PREFERENCE. With GCC 16.1 on this +// project's own fixtures, 100 payloads of 16 KB each: +// +// header route compile 0.64s + link 0.44s = 1.10s +// object route convert 1.28s + compile 0.44s + link 0.46s = 2.17s +// +// The header route is faster, because at a real shader's size neither route has +// a measurable marginal cost and the total is decided by how many processes +// start -- and one compiler invocation absorbs many headers. The crossover is +// the TOTAL embedded byte count, not the payload count: below about 1 MB the +// header route wins, and above about 4 MB the compiler's slightly superlinear +// curve loses by an order of magnitude (2.31s against 0.116s at 4 MB). Source +// expansion is a constant 2.75x, which is the second half of the same reason. +// +// So `header` is the default and `object` is what a project reaches for when it +// has more payload than that, not what it reaches for because objects sound +// tidier. +enum class storage { + // The payload is a C array in generated source, compiled into the program. + // No assembler involved, so it works on every toolchain including MSVC. + header, + // The payload is a section in an object, reached through `.incbin` in a + // generated `.S`. The bytes never pass through the C++ compiler. + // + // Requires a GAS-capable assembler. Every gcc and clang toolchain has one + // on all three platforms; MSVC does not, and mcpp refuses `.S` under it, so + // the emitter falls back to `header` there and says so once. + object, + // The payload is written beside the artifact and read at run time. The + // program's correctness then depends on its working directory, which is the + // reason this is not the default -- but it is what shader hot-reload needs, + // and what a payload too large to link needs. + sidecar, +}; + +// One payload in a group. +struct item { + // The C++ identifier, already sanitised by the caller: `blur_comp`. + std::string identifier; + // Namespace segments BELOW the group's own, from the payload's directory + // relative to its root: `{"post"}` for `shaders/post/tonemap.frag`. This is + // what keeps two payloads with one stem from colliding, and what makes the + // name a consumer writes say where the payload came from. + std::vector name_space; + // The generated data header this payload's bytes arrive in, AS AN + // `#include` WRITES IT -- relative to the directory the caller put on the + // include path, not an absolute path and not a bare file name. The + // generated tree mirrors the payload tree, so two payloads sharing a stem + // in different directories reach different headers, and a bare file name + // could not tell them apart. + std::string data_header; + // The array that header declares, qualified if it sits in a namespace. + // Unused under `storage::object`, where the linker symbol is derived from + // the accessor name instead, and under `storage::sidecar`. + std::string data_symbol; + // The payload file itself, as an absolute path. Required by `object`, whose + // generated `.S` names it in `.incbin`, and by `sidecar`, which copies it. + // The file need not exist yet: `.incbin` resolves its argument at assembly + // time, which is after the action that writes it has run, and that is what + // lets the whole surface be written at plan time. + std::string payload_path; + // Where a sidecar payload is found at run time, relative to the artifact. + std::string sidecar_name; + // The payload's size IN BYTES, as an expression valid where the generated + // implementation writes it. Empty means `sizeof `. + // + // IT EXISTS BECAUSE `sizeof` IS NOT ALWAYS THE ANSWER. `mcpp.tools.embed` + // can append a terminating zero byte that its own `_size` constant does not + // count, so `sizeof` and `_size` differ by one and only one of them is what + // the payload is. Measured: a group of null-terminated text payloads + // reported one byte too many and the fixture's comparison failed on a + // trailing NUL. A caller that knows the difference states it here rather + // than letting the generator guess. + std::string data_size_expr; +}; + +struct options { + kind surface = kind::module_; + storage store = storage::header; + element elem = element::word32; + // The module a consumer imports, e.g. `myapp.shaders`. The namespace is + // this name with `.` replaced by `::`, which is why there is no second + // field for it: two spellings of one identity drift. + std::string module_name; + // Where the generated interface and implementation are written. The caller + // adds this to the include path when the surface is `c_header`. + std::string out_dir; + // A short phrase naming what produced the payloads, for the generated + // files' first line: "mcpp.rules.spirv". + std::string produced_by; + + // ── What this generator is NOT allowed to find out for itself ─────────── + // + // THE TWO FIELDS BELOW ARE WHY THIS MODULE IMPORTS ONLY `std`. + // + // They were `mcpp::target_os()` and `mcpp::compiler()`, read here. That + // made the generator unusable anywhere except inside a build program -- + // which is the one place it must NOT be the only usable form, because a + // payload dependency can only enter the build graph if the generation is + // an ACTION, and an action's command is a binary. A binary cannot import + // the build-program module: measured, an ordinary build of this package + // fails with "mcpp: failed to read compiled module". + // + // So they are parameters. The caller has both answers already, and a + // generator that takes its inputs rather than reading its environment is + // the same code in a build program and in a tool. + + // The target's operating system, as mcpp spells it -- what decides the + // assembly dialect: the section directive and whether a symbol carries a + // leading underscore. Required under `storage::object`; ignored otherwise. + std::string target_os; + + // Whether a GAS-compatible assembler exists for this toolchain. False + // under MSVC, which has none, and where mcpp refuses `.S` outright. It is + // the CALLER's answer because the caller knows the compiler; this + // generator degrades `object` to `header` when it is false and reports + // that through `emitted::store` rather than by printing. + bool has_gas_assembler = true; +}; + +// What the caller hands back to mcpp. +struct emitted { + // The interface unit: a `.cppm` under `module_`, a `.h` under `c_header`. + std::string interface_file; + // The generated `.S` under `storage::object`, empty otherwise. The caller + // adds it to the build the same way it adds the implementation. + std::string assembly_file; + // The storage actually used. Differs from what was asked for when the + // toolchain cannot assemble: MSVC has no GAS, so `object` degrades to + // `header` and this says so rather than leaving the caller to assume. + storage store = storage::header; + // The translation unit defining the accessors. Always a plain `.cpp`. + std::string impl_file; + // Non-empty under `module_`: what the interface unit provides, which the + // caller declares with `mcpp::action::provides` or lets the scan find. + std::string module_name; + // Non-empty under `c_header`: the directory to put on the include path. + std::string include_dir; +}; + +// The linker symbol an accessor carries. It is derived from the module name and +// the payload's full namespace path rather than from the identifier alone, +// because two groups in one link unit -- a project with shaders and with +// embedded data -- would otherwise define the same symbol twice and the second +// definition would be the one nobody expected. +inline std::string accessor_base(const options& opt, const item& it) { + std::string s = "mcpp_embed"; + auto add = [&](std::string_view part) { + s += '_'; + for (char c : part) + s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; + }; + for (auto const& seg : split_module_name(opt.module_name)) add(seg); + for (auto const& seg : it.name_space) add(seg); + add(it.identifier); + return s; +} + +inline const char* element_type(element e) { + return e == element::word32 ? "unsigned int" : "unsigned char"; +} + +// `unsigned int` is 32 bits on every target this package supports, and the +// generated implementation asserts it rather than assuming it: a target where +// it is not would otherwise hand a Vulkan driver a pointer into misread data, +// and the failure would be a device error naming nothing. +inline const char* element_width_assertion(element e) { + return e == element::word32 + ? "static_assert(sizeof(unsigned int) == 4,\n" + " \"mcpp.plugins.surface: element::word32 assumes a 32-bit `unsigned int`\");\n" + : ""; +} + +inline bool write_if_different(const std::string& path, std::string_view text) { + std::error_code ec; + std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); + if (std::ifstream in(path, std::ios::binary); in) { + std::string old((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + if (old == text) return true; + } + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) return false; + out.write(text.data(), static_cast(text.size())); + return static_cast(out); +} + +// Open and close the namespaces an item sits in, below the group's own. +inline std::string open_namespaces(const std::vector& segs) { + std::string s; + for (auto const& one : segs) s += "namespace " + one + " {\n"; + return s; +} +inline std::string close_namespaces(const std::vector& segs) { + std::string s; + for (auto i = segs.rbegin(); i != segs.rend(); ++i) s += "} // namespace " + *i + "\n"; + return s; +} + +// The declarations shared by both surfaces. What differs between a module +// interface and a header is the preamble and how the group's namespace is +// opened; the body below is byte-identical, which is what makes switching +// surfaces a change no consumer can observe. +// The accessor declarations, at GLOBAL scope. +// +// C language linkage makes a name the same entity whatever namespace declares +// it, so these would resolve from inside the group's namespace as well. They are +// written outside it because the generated implementation defines them at global +// scope, and a reader comparing the two files should not have to know that rule +// to see that they match. +inline std::string extern_c_declarations(std::span items, const options& opt) { + const char* elem = element_type(opt.elem); + std::string s = "extern \"C\" {\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + s += std::format("const {}* {}_data();\n", elem, base); + s += std::format("unsigned long {}_size();\n", base); + } + s += "}\n"; + return s; +} + +inline std::string declarations(std::span items, const options& opt) { + const char* elem = element_type(opt.elem); + std::string s; + + s += std::format( + "// The payload, as the device API wants it. Free of standard-library\n" + "// types on purpose: see mcpp.plugins.surface.\n" + "struct payload {{\n" + " const {}* code; // e.g. VkShaderModuleCreateInfo::pCode\n" + " unsigned long size_bytes; // e.g. VkShaderModuleCreateInfo::codeSize\n" + "}};\n\n", elem); + + // Grouped by namespace path so a directory's payloads are emitted together + // and each namespace is opened once. + std::vector openNow; + auto reopen = [&](const std::vector& want) { + if (openNow == want) return; + s += close_namespaces(openNow); + s += open_namespaces(want); + openNow = want; + }; + for (auto const& it : items) { + reopen(it.name_space); + const auto base = accessor_base(opt, it); + // THROUGH `identifier`, HERE RATHER THAN IN EACH PRODUCER. This is the + // one line that turns `item::identifier` into something a compiler + // parses, and a rule that builds the field from a file stem cannot know + // it has produced `my-shader_comp` or `default` until it gets here. + s += std::format("inline payload {}() {{ return {{ {}_data(), {}_size() }}; }}\n", + identifier(it.identifier, "payload"), base, base); + } + reopen({}); + return s; +} + +// ONE OBJECT FORMAT PER PLATFORM, AND THE DIFFERENCES ARE NOT COSMETIC. +// +// `.incbin` is the portable part: gas and clang's integrated assembler both +// accept it everywhere, and it resolves its argument at ASSEMBLY time, which is +// why this file can be written before the payload exists. What is not portable +// is the section directive and whether a C symbol carries a leading underscore. +// +// ELF `.section .rodata`, symbol as written +// Mach-O `.section __TEXT,__const`, symbol PREFIXED with `_` +// COFF `.section .rdata,"dr"`, symbol as written on x86_64 +// +// Mach-O's underscore is the one that fails quietly in the other direction: an +// assembly label without it defines a symbol the C++ side never resolves, and +// the link error names the accessor rather than the missing prefix. +struct asm_dialect { + std::string_view section; + std::string_view symbol_prefix; +}; + +inline asm_dialect dialect_for(std::string_view targetOs) { + if (targetOs == "macos" || targetOs == "macosx" || targetOs == "darwin") + return { ".section __TEXT,__const", "_" }; + if (targetOs == "windows") return { ".section .rdata,\"dr\"", "" }; + return { ".section .rodata", "" }; +} + +// `.balign 4` rather than nothing: `VkShaderModuleCreateInfo::pCode` requires +// four-byte alignment, and a section directive alone does not promise it. The +// header route gets alignment from the array's element type; this route has to +// ask for it. +inline std::string assembly_for(std::span items, const options& opt, + std::string_view targetOs) { + const auto d = dialect_for(targetOs); + std::string s = + "// Generated by mcpp.plugins.surface. Do not edit.\n" + "//\n" + "// The payloads, as sections rather than as C arrays. `.incbin` resolves\n" + "// its argument when this file is assembled, which is after the actions\n" + "// that write those files have run.\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + s += std::format("\n {}\n" + " .globl {}{}_begin\n" + " .balign 4\n" + "{}{}_begin:\n" + " .incbin \"{}\"\n" + " .globl {}{}_end\n" + "{}{}_end:\n", + d.section, + d.symbol_prefix, base, + d.symbol_prefix, base, + it.payload_path, + d.symbol_prefix, base, + d.symbol_prefix, base); + } + return s; +} + +// ---- the tool --------------------------------------------------------------- + +// EVERY FILE THIS SURFACE WILL PRODUCE, WITHOUT PRODUCING ANY OF THEM. +// +// A rule declares these as an action's outputs, and mcpp requires an output to +// be NAMED before the graph is built even though its content arrives later. So +// the names cannot come from having written the files -- which is the coupling +// that forced generation to happen at plan time, and with it the whole +// staleness this round removes. +// +// Pure: no items, no filesystem, no environment. The one decision it makes is +// the MSVC degradation, which is a property of the toolchain rather than of any +// payload, and `emitted::store` is where the caller reads the verdict. +inline emitted outputs(const options& opt) { + emitted out; + out.store = opt.store; + // MSVC HAS NO GAS, AND mcpp REFUSES `.S` UNDER IT. `src/build/prepare.cppm` + // says so outright: "GAS assembly sources (.S/.s) are not supported by the + // MSVC toolchain". Object storage degrades to header storage there rather + // than producing a file the build will refuse, and the SURFACE does not + // change -- the declarations are identical under both. + if (out.store == storage::object && !opt.has_gas_assembler) + out.store = storage::header; + + const auto dir = std::filesystem::path(opt.out_dir); + out.interface_file = (dir / (opt.module_name + + (opt.surface == kind::module_ ? ".cppm" : ".h"))).string(); + out.impl_file = (dir / (opt.module_name + ".impl.cpp")).string(); + // Named only under the storage that produces one, so a caller can test the + // string rather than having to test the storage a second time. + if (out.store == storage::object) + out.assembly_file = (dir / (opt.module_name + ".payload.S")).string(); + if (opt.surface == kind::module_) out.module_name = opt.module_name; + else out.include_dir = dir.string(); + return out; +} + + +// The assembly's meaning includes the bytes named by .incbin. Put a content +// checksum in its source so restat cannot prune the assembler after a payload +// changes while the .incbin path stays the same. This runs in the body action, +// after its declared payload inputs exist; planning still reads no payload. +inline std::optional payload_checksum(const std::string& file) { + std::ifstream input(file, std::ios::binary); + if (!input) return std::nullopt; + std::uint64_t sum = 14695981039346656037ULL; + std::array bytes; + while (input) { + input.read(bytes.data(), static_cast(bytes.size())); + for (std::streamsize i = 0; i < input.gcount(); ++i) { + sum ^= static_cast(bytes[static_cast(i)]); + sum *= 1099511628211ULL; + } + } + return input.bad() ? std::nullopt : std::optional(sum); +} + +// Writes ONE half of the surface. The names come from `outputs`, which the +// caller has already asked; this produces the content. +// +// The interface reads no payload. The object body runs after its declared +// payload inputs, records their content checksum and names them in .incbin; +// the assembler reads the bytes after that body action has completed. +inline bool write(std::span items, const options& opt, half which) { + if (items.empty()) return true; + if (opt.module_name.empty()) { + std::cerr << "mcpp.plugins.surface: options::module_name is required; it names both " + "the module a consumer imports and the namespace the declarations sit in\n"; + return false; + } + if (opt.out_dir.empty()) { + std::cerr << "mcpp.plugins.surface: options::out_dir is required\n"; + return false; + } + + const auto segs = split_module_name(opt.module_name); + // REFUSED HERE, NOT IN THE GENERATED FILE. The module name is the one part + // of this surface a project writes itself, and each of its segments becomes + // a namespace. A segment that is not an identifier -- empty, starting with + // a digit, carrying a `-`, or reserved -- produces a generated file that + // does not parse, and the error then names a line nobody wrote. + for (std::size_t i = 0; i < segs.size(); ++i) { + if (segs[i] == identifier(segs[i], "")) continue; + std::cerr << std::format( + "mcpp.plugins.surface: `{}` is not a usable module name: the segment `{}` " + "is not a C++ identifier.\n Each segment becomes a namespace, so it has " + "to be one; `{}` would work.\n", + opt.module_name, segs[i], identifier(segs[i], "part")); + return false; + } + const auto by = opt.produced_by.empty() ? std::string("mcpp.plugins.surface") + : opt.produced_by; + + // ONE derivation of the names, shared with the caller. Recomputing them + // here would be the second copy of a decision that this package has paid + // for before. + const emitted out = outputs(opt); + const auto dir = std::filesystem::path(opt.out_dir); + const auto body = declarations(items, opt); + + // ---- interface ---- + if (which == half::interface_) { + std::string iface; + iface += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); + if (opt.surface == kind::module_) + iface += std::format("export module {};\n\n", opt.module_name); + else + iface += "#pragma once\n\n"; + iface += extern_c_declarations(items, opt); + iface += "\n"; + // `export` on the opening namespace exports everything the block + // contains, including the nested namespaces a payload's directory + // produced. + if (opt.surface == kind::module_) iface += "export "; + iface += open_namespaces(segs); + iface += "\n" + body + "\n"; + iface += close_namespaces(segs); + if (!write_if_different(out.interface_file, iface)) { + std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", + out.interface_file); + return false; + } + return true; + } + + // ---- implementation ---- (half::body from here down) + // + // The one translation unit that defines the accessors. A plain `.cpp` under + // every surface and every storage, because the accessors have C language + // linkage and so need no attachment to the module. What differs between the + // three storages is only where it reads the bytes from. + const char* elem = element_type(opt.elem); + std::string impl; + impl += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); + + if (out.store == storage::header) { + impl += "//\n" + "// The only translation unit that includes the generated data headers.\n" + "// Each declares a `static` array, so this is also the only copy of the\n" + "// bytes in the program.\n"; + for (auto const& it : items) impl += std::format("#include \"{}\"\n", it.data_header); + impl += "\n"; + impl += element_width_assertion(opt.elem); + impl += "\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + const auto size = it.data_size_expr.empty() + ? std::format("sizeof {}", it.data_symbol) + : it.data_size_expr; + impl += std::format( + "extern \"C\" const {0}* {1}_data() {{ return {2}; }}\n" + "extern \"C\" unsigned long {1}_size() {{ return {3}; }}\n", + elem, base, it.data_symbol, size); + } + } else if (out.store == storage::object) { + impl += "//\n" + "// The bytes are in a section written by the generated `.S`. This file\n" + "// only names its two boundary symbols, so nothing here parses a payload\n" + "// and the C++ compiler never sees one.\n" + "//\n" + "// The symbols are declared as arrays of the element type rather than as\n" + "// `char`: the assembly aligned the section to four bytes, and a\n" + "// declaration that said `char` would let a consumer reach it through an\n" + "// under-aligned pointer with nothing to notice.\n"; + impl += "\n"; + impl += element_width_assertion(opt.elem); + impl += "\nextern \"C\" {\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + impl += std::format("extern const {0} {1}_begin[];\n" + "extern const {0} {1}_end[];\n", elem, base); + } + impl += "}\n\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + impl += std::format( + "extern \"C\" const {0}* {1}_data() {{ return {1}_begin; }}\n" + "extern \"C\" unsigned long {1}_size() {{\n" + " return static_cast(({1}_end - {1}_begin) * sizeof({0}));\n" + "}}\n", elem, base); + } + } else { + impl += "//\n" + "// The payloads are files beside the artifact, read on first use. The\n" + "// path is resolved against the WORKING DIRECTORY, which is the property\n" + "// that makes this storage the one a project opts into rather than the\n" + "// default: a program started from elsewhere finds nothing.\n" + "//\n" + "// Read once and kept: an accessor that reloaded would hand two callers\n" + "// two different pointers to the same payload, and a device API given\n" + "// the second after the first was freed is a defect with no message.\n"; + impl += "#include \n#include \n#include \n\n"; + impl += element_width_assertion(opt.elem); + impl += std::format(R"IMPL( +namespace {{ + +struct blob {{ {0}* data = nullptr; unsigned long size = 0; bool tried = false; }}; + +blob& load(const char* path, blob& b) {{ + if (b.tried) return b; + b.tried = true; + std::FILE* f = std::fopen(path, "rb"); + if (!f) {{ + std::fprintf(stderr, "mcpp.plugins.surface: cannot open %s\n", path); + return b; + }} + std::fseek(f, 0, SEEK_END); + const long n = std::ftell(f); + std::fseek(f, 0, SEEK_SET); + if (n > 0) {{ + b.data = static_cast<{0}*>(std::malloc(static_cast(n))); + if (b.data && std::fread(b.data, 1, static_cast(n), f) + == static_cast(n)) + b.size = static_cast(n); + else {{ std::free(b.data); b.data = nullptr; }} + }} + std::fclose(f); + return b; +}} + +}} // namespace +)IMPL", elem); + impl += "\n"; + for (auto const& it : items) { + const auto base = accessor_base(opt, it); + impl += std::format( + "static blob {0}_blob;\n" + "extern \"C\" const {1}* {0}_data() {{\n" + " return load(\"{2}\", {0}_blob).data;\n" + "}}\n" + "extern \"C\" unsigned long {0}_size() {{\n" + " return load(\"{2}\", {0}_blob).size;\n" + "}}\n", base, elem, it.sidecar_name); + } + } + + if (!write_if_different(out.impl_file, impl)) { + std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", out.impl_file); + return false; + } + + if (out.store == storage::object) { + // A CALLER THAT ASKS FOR THIS STORAGE MUST HAVE SAID WHERE THE BYTES + // ARE, AND THE REFUSAL IS WHAT KEEPS THAT TRUE. + // + // `item::payload_path` is documented as required under `object`, and + // today only `mcpp.rules.spirv` reaches this storage and only it sets + // the field. That is a COINCIDENCE, not a guarantee: the first caller + // to give `rules-slang` or `tools-embed` a storage option would get an + // `.incbin ""` in a generated `.S`, and the declaration below would + // then name an empty dependency -- so the build would be wrong in + // exactly the silent way this whole change exists to remove. + // + // A constraint written only in a comment has nothing enforcing it, + // which is a shape this project has recorded before. This is the + // enforcement. + for (auto const& it : items) { + if (!it.payload_path.empty()) continue; + std::cerr << std::format( + "mcpp.plugins.surface: `{}` was given storage::object with no " + "payload_path.\n" + " Under this storage the generated assembly names the payload " + "in `.incbin`, so\n" + " the caller has to say where it is. Set `item::payload_path`, " + "or use storage::header.\n", + it.identifier); + return false; + } + auto assembly = assembly_for(items, opt, opt.target_os); + for (const auto& it : items) { + const auto checksum = payload_checksum(it.payload_path); + if (!checksum) { + std::cerr << std::format("mcpp.plugins.surface: cannot read payload {}\n", it.payload_path); + return false; + } + assembly += std::format("// payload content: {:016x}\n", *checksum); + } + if (!write_if_different(out.assembly_file, assembly)) { + std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", + out.assembly_file); + return false; + } + } + // `storage::sidecar` needs no counterpart, and that was checked rather than + // assumed. Its payload is never read by a compile: the accessor opens the + // file at RUN time, so a rebuilt payload is picked up by the next run with + // nothing in the build graph to keep current. + return true; +} + +// The surface a project gets when it asks for nothing. +// +// `MCPP_LANGUAGE_MODULES` is set by mcpp from `[language] modules`. An engine +// that does not set it leaves the variable absent, and the fallback is the +// header surface -- which is what every consumer of this package had before +// this module existed. An older engine therefore keeps its behaviour and a +// newer one gets the module surface without any project asking, which is the +// whole of the upgrade path. +inline kind default_surface() { + const char* v = std::getenv("MCPP_LANGUAGE_MODULES"); + return (v && (*v == '1' || *v == 't' || *v == 'T')) ? kind::module_ : kind::c_header; +} + +// `example:my-app` -> `my_app`. The module a rule names by default is this +// followed by the group's own segment, so two packages in one build cannot +// claim the same module. +// The default module root for a package that named none: its PACKAGE NAME, +// sanitised into an identifier. +// +// THE PACKAGE'S NAME. NOT ITS DIRECTORY'S. These are different questions and +// they give different answers whenever a project lays a package out under a +// generic directory. The first version asked the only question mcpp could +// answer -- the leaf of MCPP_MANIFEST_DIR -- so a package named `vulkan-saxpy` +// laid out as `vulkan/app/` generated `app.shaders`, and every +// `/app/` in a workspace claimed that same module. +// +// The name ARRIVES rather than being read, for the reason `options::target_os` +// records: this module must compile into a plain binary as well as into a +// build program, so it may not reach for `mcpp::package_name()` itself. The +// caller passes what mcpp told it. +// +// `fallback` covers the impossible case -- a manifest without a `[package] +// name` does not load, so an empty first argument would mean the contract +// changed underneath. A rule that wants neither passes `options::module_name`, +// and this is not consulted. +inline std::string module_root_for(std::string_view package_name, + std::string_view fallback = {}) { + std::string leaf{package_name}; + if (leaf.empty()) leaf = std::string(fallback); + return identifier(leaf, "app"); +} + +} // namespace mcpp::plugins::surface + +// mcpp::plugins::tree -- the directories a walk of a source tree leaves out. +// +// SHARED BECAUSE TWO MEMBERS WALK A SOURCE TREE BY DEFAULT. `rules-qt` finds +// the headers moc reads and the sources lupdate reads under the package, and +// `deps` takes every file of a subproject as an input of its installation, and +// `deps-cmake` as part of the installation's key. Neither may take what ANOTHER +// build system generated there: a Visual Studio project built in the same +// checkout leaves its moc and uic output under `x64/Release/`, and lupdate +// given those files rewrites the translations, and a CMake build directory an +// IDE made inside a subproject changes the key on every build. +// +// Such a directory is known by what its build system leaves in it, not by its +// name: `x64/` is as often a directory of architecture-specific sources. +export namespace mcpp::plugins::tree { + +// Whether `dir` is an output directory of another build system: +// +// CMakeCache.txt a CMake build tree (an IDE's `cmake-build-*`, `out/build/*`) +// .qmake.stash a qmake build tree +// CACHEDIR.TAG a directory its tool tags as a cache (https://bford.info/cachedir/) +// .tlog/ an MSBuild intermediate directory (`x64/Release/`), where a +// Visual Studio project writes the sources it generates +// +// A walk asks this of the directories under its root, never of the root: a +// subproject configured in its own source directory holds CMakeCache.txt too. +inline bool build_output(const std::filesystem::path& dir) { + namespace fs = std::filesystem; + std::error_code ec; + if (fs::is_regular_file(dir / "CMakeCache.txt", ec) || fs::is_regular_file(dir / ".qmake.stash", ec)) + return true; + if (fs::is_regular_file(dir / "CACHEDIR.TAG", ec)) { + std::ifstream in(dir / "CACHEDIR.TAG", std::ios::binary); + std::string head(43, '\0'); + in.read(head.data(), 43); + if (head == "Signature: 8a477f597d28d172789f06886806bc55") return true; + } + for (auto it = fs::directory_iterator(dir, fs::directory_options::skip_permission_denied, ec); + !ec && it != fs::directory_iterator(); it.increment(ec)) + if (it->path().extension() == ".tlog" && it->is_directory(ec)) return true; + return false; +} + +} // namespace mcpp::plugins::tree diff --git a/src/plugins/graph.cppm b/src/plugins/graph.cppm deleted file mode 100644 index 554d530..0000000 --- a/src/plugins/graph.cppm +++ /dev/null @@ -1,98 +0,0 @@ -export module mcpp.plugins:graph; - -import std; -import :json; - - -// mcpp::plugins::graph -- the resolved dependency graph the engine states. -// -// mcpp 2026.9.16.1 gives the ROOT project's build program `MCPP_GRAPH_FILE` -// (`mcpp::graph_file()`), a document naming every package of the resolved graph, -// dependencies before their requesters, each with its manifest directory and its -// `[package.metadata]` verbatim (mcpp docs/30, "Reading the resolved graph"). A -// member that merges what libraries contribute reads a table of its own out of -// that metadata: `[package.metadata.dist-apk]`, `[package.metadata.dist-apple]`. -// -// READ THROUGH THE ENVIRONMENT, NOT `mcpp::graph_file()`. This unit does not -// import `mcpp` (see the top of this file), and a member that called the -// accessor would not compile against an engine older than the one that added it. -// An unset or empty variable is an older engine, or a dependency's program, and -// reads as a graph with no packages, which leaves every member's behaviour as it -// was. -export namespace mcpp::plugins::graph { - -struct package { - std::string canonical; // `namespace.name@version` - std::string name; - std::string namespace_; - std::string version; - bool root = false; - std::string manifest_dir; // absolute - json::value metadata; // the package's [package.metadata], an object -}; - -struct document { - bool present = false; // MCPP_GRAPH_FILE named a file - std::string path; - std::vector packages; // dependencies before requesters -}; - -// The graph this build program was given, or the reason it cannot be read. A -// variable naming a file that is missing or not a `mcpp.graph` document is an -// error rather than an empty graph: the engine promised a document, and reading -// nothing would silently drop every contribution. -inline std::expected read() { - document d; - const char* env = std::getenv("MCPP_GRAPH_FILE"); - if (!env || !*env) return d; - d.present = true; - d.path = env; - std::ifstream in(d.path, std::ios::binary); - if (!in) - return std::unexpected(std::format("the graph document {} cannot be read", d.path)); - const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - json::value doc; - if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) - return std::unexpected(std::format("the graph document {} is not JSON", d.path)); - if (json::string_of(doc.get("kind")) != "mcpp.graph") - return std::unexpected(std::format("the graph document {} is not a mcpp.graph document", d.path)); - const json::value* list = doc.get("packages"); - if (!list || list->type != json::value::kind::array) - return std::unexpected(std::format("the graph document {} has no packages array", d.path)); - for (auto const& entry : list->items) { - if (entry.type != json::value::kind::object) continue; - package p; - if (const json::value* id = entry.get("package")) { - p.canonical = json::string_of(id->get("canonical")); - p.name = json::string_of(id->get("name")); - p.namespace_ = json::string_of(id->get("namespace")); - p.version = json::string_of(id->get("version")); - } - if (const json::value* r = entry.get("root")) - p.root = r->type == json::value::kind::boolean && r->text == "true"; - p.manifest_dir = json::string_of(entry.get("manifest_dir")); - if (const json::value* m = entry.get("metadata"); m && m->type == json::value::kind::object) - p.metadata = *m; - d.packages.push_back(std::move(p)); - } - return d; -} - -// The package's `[package.metadata.]` table, or null. -inline const json::value* table_of(const package& p, std::string_view tool) { - const json::value* t = p.metadata.get(tool); - return t && t->type == json::value::kind::object ? t : nullptr; -} - -// A path a package states, made absolute against its manifest directory. -inline std::string resolve(const package& p, const std::string& path) { - if (path.empty() || std::filesystem::path(path).is_absolute()) return path; - return (std::filesystem::path(p.manifest_dir) / path).lexically_normal().string(); -} - -// How a diagnostic names a package: its canonical identity, or its name. -inline std::string label_of(const package& p) { - return !p.canonical.empty() ? p.canonical : p.name; -} - -} // namespace mcpp::plugins::graph diff --git a/src/plugins/json.cppm b/src/plugins/json.cppm deleted file mode 100644 index 2fba2f4..0000000 --- a/src/plugins/json.cppm +++ /dev/null @@ -1,185 +0,0 @@ -export module mcpp.plugins:json; - -import std; - - -// mcpp::plugins::json -- the JSON two dist members read. -// -// SHARED BECAUSE TWO DOCUMENTS ARE READ WITH IT. `dist-apk` reads coursier's -// resolution report, and `mcpp::plugins::graph` below reads the engine's graph -// document for `dist-apk` and `dist-apple`. A second parser for the second -// document is how two readers come to disagree about one file, so there is one. -// It reads objects, arrays, strings (with `\u` escapes, surrogate pairs -// included, and a refusal for a surrogate that is not part of one), numbers, -// `true`, `false` and `null`; a number keeps its spelling in `text`. -export namespace mcpp::plugins::json { - -// A MEMBER IS ITS OWN STRUCT, NOT `std::pair`. Under clang -// with libstdc++'s `std` module, `pair` inside `value` is -// instantiated while `value` is still incomplete -- its destructor needs the -// pair and the pair needs `value` -- and the unit fails with "incomplete type -// used in type trait expression". GCC accepts the pair and so does clang with -// libc++, so neither build lane saw it; clangd reading a GCC project in the -// editor is exactly that combination. A plain aggregate, with `get()` defined -// once both types are complete, compiles under all three. -struct member; - -struct value { - enum class kind { null, boolean, number, string, array, object }; - kind type = kind::null; - std::string text; // string, number or boolean spelling - std::vector items; - std::vector members; - - const value* get(std::string_view key) const; -}; - -struct member { - std::string first; - value second; -}; - -inline const value* value::get(std::string_view key) const { - for (auto const& m : members) if (m.first == key) return &m.second; - return nullptr; -} - -struct reader { - std::string_view s; - std::size_t i = 0; - - void skip_space() { - while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i; - } - // The four hexadecimal digits of one `\u` escape, `i` already past the `u`. - bool hex4(unsigned& cp) { - if (i + 4 > s.size()) return false; - cp = 0; - for (int k = 0; k < 4; ++k) { - const char h = s[i++]; - cp <<= 4; - if (h >= '0' && h <= '9') cp |= static_cast(h - '0'); - else if (h >= 'a' && h <= 'f') cp |= static_cast(h - 'a' + 10); - else if (h >= 'A' && h <= 'F') cp |= static_cast(h - 'A' + 10); - else return false; - } - return true; - } - bool string(std::string& out) { - if (i >= s.size() || s[i] != '"') return false; - ++i; - while (i < s.size() && s[i] != '"') { - if (s[i] != '\\') { out += s[i++]; continue; } - if (++i >= s.size()) return false; - const char e = s[i++]; - switch (e) { - case 'n': out += '\n'; break; - case 't': out += '\t'; break; - case 'r': out += '\r'; break; - case 'b': out += '\b'; break; - case 'f': out += '\f'; break; - case 'u': { - // A code point above U+FFFF reaches JSON as a surrogate - // PAIR, which is two `\u` escapes. Encoding each half on its - // own produces two three-byte sequences holding unpaired - // surrogates -- not UTF-8, and accepted by nothing that - // reads the manifest this value is written into. The pair is - // combined here, and a surrogate that is not part of one is - // refused, so a malformed document is a refusal rather than - // a silently corrupted string. - unsigned cp = 0; - if (!hex4(cp)) return false; - if (cp >= 0xd800 && cp <= 0xdbff) { - if (i + 6 > s.size() || s[i] != '\\' || s[i + 1] != 'u') return false; - i += 2; - unsigned lo = 0; - if (!hex4(lo)) return false; - if (lo < 0xdc00 || lo > 0xdfff) return false; - cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); - } else if (cp >= 0xdc00 && cp <= 0xdfff) { - return false; // a low surrogate with no high half - } - if (cp < 0x80) out += static_cast(cp); - else if (cp < 0x800) { out += static_cast(0xc0 | (cp >> 6)); out += static_cast(0x80 | (cp & 0x3f)); } - else if (cp < 0x10000) { out += static_cast(0xe0 | (cp >> 12)); out += static_cast(0x80 | ((cp >> 6) & 0x3f)); out += static_cast(0x80 | (cp & 0x3f)); } - else { - out += static_cast(0xf0 | (cp >> 18)); - out += static_cast(0x80 | ((cp >> 12) & 0x3f)); - out += static_cast(0x80 | ((cp >> 6) & 0x3f)); - out += static_cast(0x80 | (cp & 0x3f)); - } - break; - } - default: out += e; - } - } - if (i >= s.size()) return false; - ++i; - return true; - } - bool parse_value(value& out) { - skip_space(); - if (i >= s.size()) return false; - const char c = s[i]; - if (c == '"') { out.type = value::kind::string; return string(out.text); } - if (c == '{') { - out.type = value::kind::object; - ++i; - skip_space(); - if (i < s.size() && s[i] == '}') { ++i; return true; } - for (;;) { - skip_space(); - std::string key; - if (!string(key)) return false; - skip_space(); - if (i >= s.size() || s[i] != ':') return false; - ++i; - value v; - if (!parse_value(v)) return false; - out.members.emplace_back(std::move(key), std::move(v)); - skip_space(); - if (i < s.size() && s[i] == ',') { ++i; continue; } - if (i < s.size() && s[i] == '}') { ++i; return true; } - return false; - } - } - if (c == '[') { - out.type = value::kind::array; - ++i; - skip_space(); - if (i < s.size() && s[i] == ']') { ++i; return true; } - for (;;) { - value v; - if (!parse_value(v)) return false; - out.items.push_back(std::move(v)); - skip_space(); - if (i < s.size() && s[i] == ',') { ++i; continue; } - if (i < s.size() && s[i] == ']') { ++i; return true; } - return false; - } - } - const std::size_t b = i; - while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' && - s[i] != ' ' && s[i] != '\n' && s[i] != '\r' && s[i] != '\t') ++i; - out.text = std::string(s.substr(b, i - b)); - if (out.text == "null") out.type = value::kind::null; - else if (out.text == "true" || out.text == "false") out.type = value::kind::boolean; - else out.type = value::kind::number; - return !out.text.empty(); - } -}; - -// The whole text is one value, with nothing but white space after it. -inline bool parse_json(std::string_view text, value& out) { - reader r{text}; - if (!r.parse_value(out)) return false; - r.skip_space(); - return r.i == r.s.size(); -} - -// A string member of an object, or empty when absent or not a string. -inline std::string string_of(const value* v) { - return v && v->type == value::kind::string ? v->text : std::string(); -} - -} // namespace mcpp::plugins::json diff --git a/src/plugins/names.cppm b/src/plugins/names.cppm deleted file mode 100644 index 61fe040..0000000 --- a/src/plugins/names.cppm +++ /dev/null @@ -1,207 +0,0 @@ -export module mcpp.plugins:names; - -import std; - - -// mcpp::plugins::names -- the derivations that turn a path into a C++ name. -// -// THESE ARE SHARED BECAUSE THEY WERE COPIED. `common_base_dir` and -// `namespace_of` were written in `rules/spirv.cppm` and written again in -// `rules/slang.cppm`, and `mcpp.tools.island` is the third caller needing the -// same answers. Two copies that agree today are still two copies: a directory -// named `default` or `2d` has to get ONE answer, and one function is how that -// is guaranteed rather than two files that happen to say the same thing. -export namespace mcpp::plugins::names { - -// `a` made relative to the directory `b`, as strings: separators unified, and -// the prefix stripped when `a` lies under `b`; `a` unchanged otherwise. -// -// NOTHING IN THIS PACKAGE INSTANTIATES `std::filesystem::path`'s ITERATOR -- -// see `components()` below for the compiler that refuses it. The members' -// relative-path arithmetic is this string function, defined once here. -inline std::string relative_to(std::string a, std::string b) { - for (auto& c : a) if (c == '\\') c = '/'; - for (auto& c : b) if (c == '\\') c = '/'; - while (!b.empty() && b.back() == '/') b.pop_back(); - if (!b.empty() && a.starts_with(b + "/")) return a.substr(b.size() + 1); - return a; -} - -// A GENERATED NAME THE C++ COMPILER WILL ACCEPT. -// -// Three transformations, and the third is the one every hand-rolled copy of -// this function was missing. Non-identifier characters become `_`; a leading -// digit gets a `_` in front; and a result that is a KEYWORD gets a trailing `_`. -// -// The keyword case is not hypothetical. The first two rules accept `default`, -// `template`, `operator`, `private` and `union` unchanged -- they are valid -// identifiers to a character filter and reserved to the compiler -- and -// `shaders/default/` is an ordinary name for a shader directory. What it -// produced was `namespace default {` in a generated file, and an error naming a -// line its author never wrote. -// -// TRAILING `_`, not a prefix: `_default` is reserved at namespace scope -// (a leading underscore in the global namespace), and prefixing would trade one -// reserved name for another. -// -// The list is the keywords of the standard this collection targets. A word that -// is contextual rather than reserved (`final`, `override`, `import`, `module`) -// is a legal identifier and is left alone. -inline bool is_cxx_keyword(std::string_view w) { - static constexpr std::string_view kWords[] = { - "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "char8_t", "char16_t", - "char32_t", "class", "compl", "concept", "const", "consteval", - "constexpr", "constinit", "const_cast", "continue", "co_await", - "co_return", "co_yield", "decltype", "default", "delete", "do", "double", - "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", - "float", "for", "friend", "goto", "if", "inline", "int", "long", - "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", - "operator", "or", "or_eq", "private", "protected", "public", "register", - "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", - "static", "static_assert", "static_cast", "struct", "switch", - "template", "this", "thread_local", "throw", "true", "try", "typedef", - "typeid", "typename", "union", "unsigned", "using", "virtual", "void", - "volatile", "wchar_t", "while", "xor", "xor_eq", - }; - for (auto k : kWords) if (k == w) return true; - return false; -} - -// `fallback` is used when the input sanitises to nothing, which a file named -// only in punctuation does. -// -// INDEXED RATHER THAN A RANGE-FOR over the string, for the reason recorded in -// `mcpp.tools.island`: iterating a `std::string` inside an exported inline -// function makes GCC 16 instantiate its iterator in this BMI, and a consumer's -// build program then fails to compile on `always_inline` in a header naming -// neither this file nor this loop. -inline std::string identifier(std::string_view raw, std::string_view fallback) { - std::string s; - for (std::size_t i = 0; i < raw.size(); ++i) { - const char c = raw[i]; - s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; - } - if (s.empty()) s = std::string(fallback); - if (!s.empty() && std::isdigit(static_cast(s.front()))) - s.insert(s.begin(), '_'); - if (is_cxx_keyword(s)) s += '_'; - return s; -} - - -// ---- internals ------------------------------------------------------------- - -inline std::vector split_module_name(std::string_view name) { - std::vector out; - for (std::size_t i = 0; i <= name.size();) { - auto dot = name.find('.', i); - auto one = dot == std::string_view::npos ? name.substr(i) : name.substr(i, dot - i); - if (!one.empty()) out.emplace_back(one); - if (dot == std::string_view::npos) break; - i = dot + 1; - } - return out; -} - -// THE BASE DIRECTORY IS DERIVED, NOT ASKED FOR. -// -// A payload's namespace comes from where it sits relative to the tree the -// project globbed, so something has to say where that tree starts. Asking the -// project would put a second spelling of the glob in the manifest, and the two -// would disagree the first time a glob moved. The shallowest directory every -// path shares is the same answer without the second spelling: for -// `shaders/*.comp` it is `shaders` and every namespace is empty; for -// `shaders/a/x.comp` and `shaders/b/y.comp` it is still `shaders`, and the two -// land in `::a` and `::b`. -// -// A single path has no common prefix with anything, so its own directory is the -// base and its namespace is empty -- which is the same answer the general case -// gives once a second file appears beside it. -// A path's components as strings: both separators split, empty and `.` -// components dropped. This is the one place the lib root reads a path apart, -// and it does so WITHOUT `std::filesystem::path`'s iterator on purpose: -// -// A MODULE THAT INSTANTIATES `_Path_iterator` POISONS ITS IMPORTERS UNDER MSVC -// 14.52. Measured on xrgui's CI (14.52.36629 and .36725): this unit compiled -// while it iterated paths, and every member importing it that then touched -// `std::filesystem` at all failed inside the STL -- -// -// include\filesystem(1572): error C2801: '..._Path_iterator<...>::operator ==' -// must be a non-static member -// -// -- the iterator's hidden-friend comparison, refused when the importer meets -// it both through `import std` and through this module's BMI. Removing the -// calls from the members changed nothing; the instantiation had to leave the -// lib root. Component comparison is what `lexically_relative` bought in 0.5.2 -// (a Windows separator bug), and splitting on both separators keeps that. -inline std::vector components(std::string_view path) { - std::vector out; - std::string cur; - auto flush = [&] { if (!cur.empty() && cur != ".") out.push_back(cur); cur.clear(); }; - for (char c : path) { if (c == '/' || c == '\\') flush(); else cur += c; } - flush(); - return out; -} - -// The directory part of a path, as written: everything before the last -// separator, or empty when there is none. -inline std::string_view parent_of(std::string_view path) { - const auto slash = path.find_last_of("/\\"); - return slash == std::string_view::npos ? std::string_view{} : path.substr(0, slash); -} - -inline std::string common_base_dir(std::span paths) { - std::vector prefix; - bool first = true; - for (auto const& src : paths) { - auto segs = components(parent_of(src)); - if (first) { prefix = std::move(segs); first = false; continue; } - std::size_t keep = 0; - while (keep < prefix.size() && keep < segs.size() && prefix[keep] == segs[keep]) ++keep; - prefix.resize(keep); - } - std::string out; - for (auto const& s : prefix) { if (!out.empty()) out += '/'; out += s; } - return out; -} - -// The namespace segments a file sits in, below the group's own: the path from -// the base directory to the file, sanitised one segment at a time. -// -// RELATIVE BY PATH ARITHMETIC, NOT BY STRING SURGERY, AND THAT IS A WINDOWS -// FIX. This trimmed `base` off the front of the directory as a STRING and -// iterated what was left. On Windows the two spellings differ even when the -// two paths are the same: a caller states a root with forward slashes, and -// `directory_iterator` appends with the preferred separator, so the leftover -// was `\image` rather than `image`. Iterating that yields the ROOT DIRECTORY -// as its first component, which sanitised to `_` -- and the payload landed in -// `myapp::shaders::_::image`, a namespace no consumer writes. Measured: the -// island fixture failed to compile on windows-2022 with `no member named -// 'image' in namespace 'island_interface::kernels'`, while the same fixture -// passed on Linux and macOS. -// -// COMPONENTS are compared, so the separator a caller happened to write is not -// part of the question -- `components()` splits on both. A base that is not a -// prefix is a caller error rather than a namespace; it answers with no -// segments rather than with the whole absolute path, which is what the first -// string form produced. (Through `components()` rather than -// `lexically_relative` for the reason stated on it.) -inline std::vector namespace_of(std::string_view src, std::string_view base) { - std::vector out; - auto dir = components(parent_of(src)); - if (!base.empty()) { - const auto b = components(base); - if (b.size() > dir.size()) return out; - for (std::size_t i = 0; i < b.size(); ++i) if (b[i] != dir[i]) return out; - dir.erase(dir.begin(), dir.begin() + static_cast(b.size())); - } - for (auto const& s : dir) { - if (s == "..") continue; - // `shaders/default/` is an ordinary directory name and - // `namespace default {` is not a namespace. - out.push_back(identifier(s, "dir")); - } - return out; -} -} // namespace mcpp::plugins::names diff --git a/src/plugins/package.cppm b/src/plugins/package.cppm deleted file mode 100644 index 94feb18..0000000 --- a/src/plugins/package.cppm +++ /dev/null @@ -1,117 +0,0 @@ -export module mcpp.plugins:package; - -import std; -import :json; - - -// mcpp::plugins::package -- the metadata of a staged package. -// -// `mcpp pack` (2026.10.27.1+, SPEC-014 §4.5) writes `mcpp-package.json` at the -// root of every staged tree: the package, its three axes, its legs, the systems -// whose loaders it carries, how it is started, and every file with its role, -// its leg and its digest. It is the input of a package format's provider, of -// `mcpp pack --merge` and of `mcpp emit xpkg`. A provider reads it here rather -// than walking the tree and deciding for itself which file is the program: the -// engine has already decided, once, for every format. -// -// SCHEMA 1 AND ONLY SCHEMA 1. A document of another schema is refused rather -// than read as far as it goes: a field whose meaning changed would be read -// with the old one. -export namespace mcpp::plugins::package { - -struct file { - std::string path; // relative to the tree's root, `/`-separated - std::string role; // program | image | library | loader | launcher | resource | metadata - std::string leg; // the leg's triple; empty when every leg shares the file - std::string sha256; -}; - -struct info { - int schema = 0; - std::string name; - std::string version; - std::string platform; // `@`; empty: none - std::string linkage; // static | shared | declared - std::string mode; // system | vendored | self-contained | static - std::vector legs; // canonical triples - std::vector systems; // `-` of the loaders under libexec/ - std::vector runner; // the platform's runner argv; empty: native - // The entry of each architecture (universal packages), in the document's - // order: architecture, then the entry's path in the tree. - std::vector> entry; - std::string program; // the program's path (one native leg) - std::vector files; - std::string root; // the tree the document was read from -}; - -namespace detail { - -inline std::vector strings_of(const json::value* v) { - std::vector out; - if (!v || v->type != json::value::kind::array) return out; - for (auto const& item : v->items) - if (item.type == json::value::kind::string) out.push_back(item.text); - return out; -} - -} // namespace detail - -// The document at `/mcpp-package.json`, or why it cannot be read. -inline std::expected read(std::string_view stage_dir) { - std::string root(stage_dir); - while (root.size() > 1 && (root.back() == '/' || root.back() == '\\')) root.pop_back(); - const std::string path = root + "/mcpp-package.json"; - std::ifstream in(path, std::ios::binary); - if (!in) return std::unexpected(std::format("{} cannot be read: the tree is not a staged package", path)); - const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - json::value doc; - if (!json::parse_json(text, doc) || doc.type != json::value::kind::object) - return std::unexpected(std::format("{} is not a JSON object", path)); - info p; - p.root = root; - if (const json::value* s = doc.get("schema"); s && s->type == json::value::kind::number) - p.schema = std::atoi(s->text.c_str()); - if (p.schema != 1) - return std::unexpected(std::format( - "{} states schema {}; this collection reads schema 1 (mcpp SPEC-014 §4.5)", path, p.schema)); - p.name = json::string_of(doc.get("name")); - p.version = json::string_of(doc.get("version")); - p.platform = json::string_of(doc.get("platform")); - p.linkage = json::string_of(doc.get("linkage")); - p.mode = json::string_of(doc.get("mode")); - p.legs = detail::strings_of(doc.get("legs")); - p.systems = detail::strings_of(doc.get("systems")); - if (const json::value* launch = doc.get("launch"); launch && launch->type == json::value::kind::object) { - p.runner = detail::strings_of(launch->get("runner")); - p.program = json::string_of(launch->get("program")); - if (const json::value* e = launch->get("entry"); e && e->type == json::value::kind::object) - for (auto const& m : e->members) - if (m.second.type == json::value::kind::string) p.entry.emplace_back(m.first, m.second.text); - } - const json::value* files = doc.get("files"); - if (!files || files->type != json::value::kind::array) - return std::unexpected(std::format("{} has no files array", path)); - for (auto const& f : files->items) { - if (f.type != json::value::kind::object) continue; - p.files.push_back({ json::string_of(f.get("path")), json::string_of(f.get("role")), - json::string_of(f.get("leg")), json::string_of(f.get("sha256")) }); - } - return p; -} - -// The files of `p` with `role`, in the document's order. -inline std::vector files_with_role(const info& p, std::string_view role) { - std::vector out; - for (auto const& f : p.files) - if (f.role == role) out.push_back(f); - return out; -} - -// The entry of `arch`, or empty. -inline std::string entry_of(const info& p, std::string_view arch) { - for (auto const& [a, path] : p.entry) - if (a == arch) return path; - return {}; -} - -} // namespace mcpp::plugins::package diff --git a/src/plugins/plugins.cppm b/src/plugins/plugins.cppm deleted file mode 100644 index 0dd636b..0000000 --- a/src/plugins/plugins.cppm +++ /dev/null @@ -1,61 +0,0 @@ -// mcpp.plugins: the collection's shared library. -// -// Every member of this package is a module interface unit under rules/ or -// tools/, compiled as a host module of its own when the consumer's feature -// request names it. This unit is the lib root: it is compiled before every -// member, so a member may import it. -// -// IT HOLDS WHAT MORE THAN ONE MEMBER NEEDS, AND ONLY THAT. -// -// The lib root is the only unit every member can import. A second unit beside -// it in `[build] sources` is NOT compiled as a host module ahead of the -// members. Measured: a member importing a second lib-root unit failed with -// -// mcpp.plugins.surface: error: failed to read compiled module -// note: imports must be built before being imported -// -// because only the lib root is built first. So shared code lives here rather -// than in a file of its own, and a member that needs it writes -// `import mcpp.plugins;`. -export module mcpp.plugins; - -import std; - -// NO `import mcpp;`. That module exists only inside a build program, and this -// unit has to compile into an ordinary binary too: `mcpp.tools.embed`'s -// executable form is what lets a generated `.S` be an ACTION's output, which -// is the only way the payload it embeds can be a declared input of the edge -// that assembles it. Measured before this: an ordinary build of this package -// failed with `mcpp: failed to read compiled module`. -// -// Everything this unit used to read from that module -- the target OS, whether -// the toolchain has a GAS assembler, the package's name -- is now a parameter. -// The members under rules/ still import it; they are feature-gated, so the -// tool's own build never compiles them. - -export namespace mcpp::plugins { - -// THIS MUST EQUAL `[package] version` IN mcpp.toml, AND CI CHECKS THAT IT DOES. -// -// It was `0.1.1` while the package was `0.2.6`, which nothing noticed because -// nothing read it. A value that is recorded and never read cannot be wrong in a -// way anyone sees, so the fix is not only to correct it: every rule now states -// it with `mcpp::fact`, which makes a build log answer "which collection -// produced these actions" and makes a stale constant a visible defect rather -// than a dormant one. -// -// One package, one version: the number lives in mcpp.toml, and the CI step -// `the collection states its own version` compares the two. -inline constexpr std::string_view version = "0.27.0"; - -} // namespace mcpp::plugins - - -export import :stage; -export import :xml; -export import :json; -export import :graph; -export import :package; -export import :names; -export import :surface; -export import :tree; diff --git a/src/plugins/stage.cppm b/src/plugins/stage.cppm deleted file mode 100644 index 8d1b324..0000000 --- a/src/plugins/stage.cppm +++ /dev/null @@ -1,48 +0,0 @@ -export module mcpp.plugins:stage; - -import std; - -// mcpp::plugins::stage -- what the engine wrote beside a staged tree. -// -// SHARED BECAUSE TWO DIST MEMBERS READ IT. `mcpp pack` writes -// `.stage-manifest` (mcpp's docs/50, "The stage manifest"): a -// header, one `needs` line per library name the closure read (mcpp -// 2026.9.14.2+), and the list of staged files. `dist-apk` reads it to trust the -// native libraries under `lib/`, and `dist-apple` reads it to tell the dylibs -// staged beside a program from the resources staged there. Only the header and -// the `needs` lines are parsed; the file list is not. -export namespace mcpp::plugins::stage { - -struct need { - std::string name; // as the needing object spells it - std::string where; // a staged path relative to the tree, `platform` or `unresolved` -}; - -struct manifest { - bool found = false; // the file exists beside the tree - bool walked = true; // `closure = walked` - std::string reason; // `reason = ...`, with `closure = not-walked` - std::vector needs; -}; - -inline manifest read_manifest(std::string tree) { - manifest m; - while (tree.size() > 1 && (tree.back() == '/' || tree.back() == '\\')) - tree.pop_back(); - std::ifstream in(tree + ".stage-manifest", std::ios::binary); - if (!in) return m; - m.found = true; - std::string line; - while (std::getline(in, line)) { - if (!line.empty() && line.back() == '\r') line.pop_back(); - if (line == "closure = not-walked") { m.walked = false; continue; } - if (line.starts_with("reason = ")) { m.reason = line.substr(9); continue; } - if (!line.starts_with("needs\t")) continue; - const auto second = line.find('\t', 6); - if (second == std::string::npos) continue; - m.needs.push_back({ line.substr(6, second - 6), line.substr(second + 1) }); - } - return m; -} - -} // namespace mcpp::plugins::stage diff --git a/src/plugins/surface.cppm b/src/plugins/surface.cppm deleted file mode 100644 index df05d57..0000000 --- a/src/plugins/surface.cppm +++ /dev/null @@ -1,756 +0,0 @@ -export module mcpp.plugins:surface; - -import std; -import :names; - - - -// mcpp.plugins.surface -- the interface a consumer names for an embedded payload. -// -// WHY THIS IS SHARED RATHER THAN PER-RULE. -// -// `mcpp.rules.spirv` and `mcpp.rules.slang` produce the same kind of thing: a -// block of bytes the program hands to a device API. `mcpp.tools.embed` produces -// it from a file that was already there. The three differ in who produces the -// bytes and disagree about nothing else, so the declaration a consumer reads is -// written once, here, and the shape is identical whichever produced it. A rule -// that wrote its own would be a second copy of a decision, and the two would -// drift the way the two shader compilers' headers drifted before 0.2.6. -// -// THE INTERFACE IS A FUNCTION, NOT A VARIABLE. -// -// A variable cannot keep one shape across the ways bytes can be stored, because -// `constexpr` and `extern` are mutually exclusive: an array compiled into a -// translation unit can be constant-evaluated and one living in a section cannot. -// A function can, so where the bytes live stays an option a project revises -// without touching a consumer. -// -// THE INTERFACE NAMES NO STANDARD-LIBRARY TYPE, AND THAT IS MEASURED. -// -// The same 1 MB payload, reached four ways, compiled with GCC 16.1: -// -// data in the module (`export inline constexpr`) BMI 6 282 240 B -// data in a header source 3 145 728 B -// data in an object, interface returns std::span BMI 1 313 968 B -// data in an object, interface returns a std-free POD BMI 1 808 B -// -// The third row is 727 times the fourth, and its cost is FIXED rather than -// proportional to the payload: the 1.28 MB is ``'s templates, present -// whether the payload is 16 KB or 16 MB. A consumer that wants a `std::span` -// constructs one from the two members, and `` is then included by the -// consumer that uses it rather than by every consumer that imports this. -// -// There is a second, independent reason for the same decision. `import std;` -// requires `std.gcm` to have been built, which a project with -// `modules = true, import_std = false` has not done. A std-free interface needs -// neither. -// -// WHY THE ACCESSORS HAVE C LANGUAGE LINKAGE. -// -// A function declared in a module interface has module linkage and can only be -// defined by a unit attached to that module. Defining them would therefore need -// a module implementation unit, and the definitions include the generated data -// headers -- which would put the arrays back into the interface's own -// compilation. Declaring the accessors `extern "C"` instead gives them external -// linkage, so an ordinary translation unit defines them, the module interface -// holds two declarations and one inline call per payload, and the bytes are -// never seen by the interface at all. -// -// It also removes a portability question: module implementation units are the -// least exercised corner of every implementation this package supports, and -// nothing here needs them. -// -// ONE COPY OF THE BYTES. -// -// A generated data header declares `static const uint32_t []`, so every -// translation unit that includes it gets its own copy. Under this surface -// exactly one translation unit includes it -- the generated implementation -- -// and every consumer reaches the same array through the accessor. -export namespace mcpp::plugins::surface { - -// The name derivations live in `mcpp::plugins::names`. They are reachable under -// this namespace as well, because every rule in this collection already spells -// them this way -- one definition under two spellings is not two definitions. -using names::identifier; -using names::split_module_name; -using names::common_base_dir; -using names::namespace_of; - -// How a consumer names the payloads. -// -// `module_` is the default where the project builds C++ modules, and -// `c_header` is what a project without them gets. The choice does not change -// any declaration's shape: the same struct, the same function names, the same -// namespaces. Only the file a consumer reaches them through differs. -enum class kind { module_, c_header }; - -// WHICH HALF OF THE SURFACE A CALL WRITES. -// -// The two are separate because their INPUTS are. The interface is a function of -// the item list: names, namespaces, the accessor declarations. The body is a -// function of the item list AND, under `storage::object`, of the payloads -// themselves -- the assembly names each one in `.incbin`, and the object it -// produces is those bytes. -// -// Declaring them as one action would make a payload change rewrite the -// interface too, and rebuild every BMI that imports it. Declaring them -// separately states what is true and costs a consumer nothing. -enum class half { interface_, body }; - -// The element the accessor hands back. `word32` is what an API taking -// `const uint32_t*` wants -- `vkCreateShaderModule` is the case this package -// has -- and asking for it here is cheaper than a reinterpret_cast at every -// call site, which is undefined behaviour on an under-aligned byte array. -enum class element { byte_, word32 }; - -// WHERE THE BYTES LIVE. Orthogonal to `kind`, which decides how a consumer -// NAMES them: the declarations are identical under all three, so a project -// changes this and no consumer changes. -// -// WHICH ONE TO USE IS A MEASUREMENT, NOT A PREFERENCE. With GCC 16.1 on this -// project's own fixtures, 100 payloads of 16 KB each: -// -// header route compile 0.64s + link 0.44s = 1.10s -// object route convert 1.28s + compile 0.44s + link 0.46s = 2.17s -// -// The header route is faster, because at a real shader's size neither route has -// a measurable marginal cost and the total is decided by how many processes -// start -- and one compiler invocation absorbs many headers. The crossover is -// the TOTAL embedded byte count, not the payload count: below about 1 MB the -// header route wins, and above about 4 MB the compiler's slightly superlinear -// curve loses by an order of magnitude (2.31s against 0.116s at 4 MB). Source -// expansion is a constant 2.75x, which is the second half of the same reason. -// -// So `header` is the default and `object` is what a project reaches for when it -// has more payload than that, not what it reaches for because objects sound -// tidier. -enum class storage { - // The payload is a C array in generated source, compiled into the program. - // No assembler involved, so it works on every toolchain including MSVC. - header, - // The payload is a section in an object, reached through `.incbin` in a - // generated `.S`. The bytes never pass through the C++ compiler. - // - // Requires a GAS-capable assembler. Every gcc and clang toolchain has one - // on all three platforms; MSVC does not, and mcpp refuses `.S` under it, so - // the emitter falls back to `header` there and says so once. - object, - // The payload is written beside the artifact and read at run time. The - // program's correctness then depends on its working directory, which is the - // reason this is not the default -- but it is what shader hot-reload needs, - // and what a payload too large to link needs. - sidecar, -}; - -// One payload in a group. -struct item { - // The C++ identifier, already sanitised by the caller: `blur_comp`. - std::string identifier; - // Namespace segments BELOW the group's own, from the payload's directory - // relative to its root: `{"post"}` for `shaders/post/tonemap.frag`. This is - // what keeps two payloads with one stem from colliding, and what makes the - // name a consumer writes say where the payload came from. - std::vector name_space; - // The generated data header this payload's bytes arrive in, AS AN - // `#include` WRITES IT -- relative to the directory the caller put on the - // include path, not an absolute path and not a bare file name. The - // generated tree mirrors the payload tree, so two payloads sharing a stem - // in different directories reach different headers, and a bare file name - // could not tell them apart. - std::string data_header; - // The array that header declares, qualified if it sits in a namespace. - // Unused under `storage::object`, where the linker symbol is derived from - // the accessor name instead, and under `storage::sidecar`. - std::string data_symbol; - // The payload file itself, as an absolute path. Required by `object`, whose - // generated `.S` names it in `.incbin`, and by `sidecar`, which copies it. - // The file need not exist yet: `.incbin` resolves its argument at assembly - // time, which is after the action that writes it has run, and that is what - // lets the whole surface be written at plan time. - std::string payload_path; - // Where a sidecar payload is found at run time, relative to the artifact. - std::string sidecar_name; - // The payload's size IN BYTES, as an expression valid where the generated - // implementation writes it. Empty means `sizeof `. - // - // IT EXISTS BECAUSE `sizeof` IS NOT ALWAYS THE ANSWER. `mcpp.tools.embed` - // can append a terminating zero byte that its own `_size` constant does not - // count, so `sizeof` and `_size` differ by one and only one of them is what - // the payload is. Measured: a group of null-terminated text payloads - // reported one byte too many and the fixture's comparison failed on a - // trailing NUL. A caller that knows the difference states it here rather - // than letting the generator guess. - std::string data_size_expr; -}; - -struct options { - kind surface = kind::module_; - storage store = storage::header; - element elem = element::word32; - // The module a consumer imports, e.g. `myapp.shaders`. The namespace is - // this name with `.` replaced by `::`, which is why there is no second - // field for it: two spellings of one identity drift. - std::string module_name; - // Where the generated interface and implementation are written. The caller - // adds this to the include path when the surface is `c_header`. - std::string out_dir; - // A short phrase naming what produced the payloads, for the generated - // files' first line: "mcpp.rules.spirv". - std::string produced_by; - - // ── What this generator is NOT allowed to find out for itself ─────────── - // - // THE TWO FIELDS BELOW ARE WHY THIS MODULE IMPORTS ONLY `std`. - // - // They were `mcpp::target_os()` and `mcpp::compiler()`, read here. That - // made the generator unusable anywhere except inside a build program -- - // which is the one place it must NOT be the only usable form, because a - // payload dependency can only enter the build graph if the generation is - // an ACTION, and an action's command is a binary. A binary cannot import - // the build-program module: measured, an ordinary build of this package - // fails with "mcpp: failed to read compiled module". - // - // So they are parameters. The caller has both answers already, and a - // generator that takes its inputs rather than reading its environment is - // the same code in a build program and in a tool. - - // The target's operating system, as mcpp spells it -- what decides the - // assembly dialect: the section directive and whether a symbol carries a - // leading underscore. Required under `storage::object`; ignored otherwise. - std::string target_os; - - // Whether a GAS-compatible assembler exists for this toolchain. False - // under MSVC, which has none, and where mcpp refuses `.S` outright. It is - // the CALLER's answer because the caller knows the compiler; this - // generator degrades `object` to `header` when it is false and reports - // that through `emitted::store` rather than by printing. - bool has_gas_assembler = true; -}; - -// What the caller hands back to mcpp. -struct emitted { - // The interface unit: a `.cppm` under `module_`, a `.h` under `c_header`. - std::string interface_file; - // The generated `.S` under `storage::object`, empty otherwise. The caller - // adds it to the build the same way it adds the implementation. - std::string assembly_file; - // The storage actually used. Differs from what was asked for when the - // toolchain cannot assemble: MSVC has no GAS, so `object` degrades to - // `header` and this says so rather than leaving the caller to assume. - storage store = storage::header; - // The translation unit defining the accessors. Always a plain `.cpp`. - std::string impl_file; - // Non-empty under `module_`: what the interface unit provides, which the - // caller declares with `mcpp::action::provides` or lets the scan find. - std::string module_name; - // Non-empty under `c_header`: the directory to put on the include path. - std::string include_dir; -}; - -// The linker symbol an accessor carries. It is derived from the module name and -// the payload's full namespace path rather than from the identifier alone, -// because two groups in one link unit -- a project with shaders and with -// embedded data -- would otherwise define the same symbol twice and the second -// definition would be the one nobody expected. -inline std::string accessor_base(const options& opt, const item& it) { - std::string s = "mcpp_embed"; - auto add = [&](std::string_view part) { - s += '_'; - for (char c : part) - s += (std::isalnum(static_cast(c)) || c == '_') ? c : '_'; - }; - for (auto const& seg : split_module_name(opt.module_name)) add(seg); - for (auto const& seg : it.name_space) add(seg); - add(it.identifier); - return s; -} - -inline const char* element_type(element e) { - return e == element::word32 ? "unsigned int" : "unsigned char"; -} - -// `unsigned int` is 32 bits on every target this package supports, and the -// generated implementation asserts it rather than assuming it: a target where -// it is not would otherwise hand a Vulkan driver a pointer into misread data, -// and the failure would be a device error naming nothing. -inline const char* element_width_assertion(element e) { - return e == element::word32 - ? "static_assert(sizeof(unsigned int) == 4,\n" - " \"mcpp.plugins.surface: element::word32 assumes a 32-bit `unsigned int`\");\n" - : ""; -} - -inline bool write_if_different(const std::string& path, std::string_view text) { - std::error_code ec; - std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); - if (std::ifstream in(path, std::ios::binary); in) { - std::string old((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - if (old == text) return true; - } - std::ofstream out(path, std::ios::binary | std::ios::trunc); - if (!out) return false; - out.write(text.data(), static_cast(text.size())); - return static_cast(out); -} - -// Open and close the namespaces an item sits in, below the group's own. -inline std::string open_namespaces(const std::vector& segs) { - std::string s; - for (auto const& one : segs) s += "namespace " + one + " {\n"; - return s; -} -inline std::string close_namespaces(const std::vector& segs) { - std::string s; - for (auto i = segs.rbegin(); i != segs.rend(); ++i) s += "} // namespace " + *i + "\n"; - return s; -} - -// The declarations shared by both surfaces. What differs between a module -// interface and a header is the preamble and how the group's namespace is -// opened; the body below is byte-identical, which is what makes switching -// surfaces a change no consumer can observe. -// The accessor declarations, at GLOBAL scope. -// -// C language linkage makes a name the same entity whatever namespace declares -// it, so these would resolve from inside the group's namespace as well. They are -// written outside it because the generated implementation defines them at global -// scope, and a reader comparing the two files should not have to know that rule -// to see that they match. -inline std::string extern_c_declarations(std::span items, const options& opt) { - const char* elem = element_type(opt.elem); - std::string s = "extern \"C\" {\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - s += std::format("const {}* {}_data();\n", elem, base); - s += std::format("unsigned long {}_size();\n", base); - } - s += "}\n"; - return s; -} - -inline std::string declarations(std::span items, const options& opt) { - const char* elem = element_type(opt.elem); - std::string s; - - s += std::format( - "// The payload, as the device API wants it. Free of standard-library\n" - "// types on purpose: see mcpp.plugins.surface.\n" - "struct payload {{\n" - " const {}* code; // e.g. VkShaderModuleCreateInfo::pCode\n" - " unsigned long size_bytes; // e.g. VkShaderModuleCreateInfo::codeSize\n" - "}};\n\n", elem); - - // Grouped by namespace path so a directory's payloads are emitted together - // and each namespace is opened once. - std::vector openNow; - auto reopen = [&](const std::vector& want) { - if (openNow == want) return; - s += close_namespaces(openNow); - s += open_namespaces(want); - openNow = want; - }; - for (auto const& it : items) { - reopen(it.name_space); - const auto base = accessor_base(opt, it); - // THROUGH `identifier`, HERE RATHER THAN IN EACH PRODUCER. This is the - // one line that turns `item::identifier` into something a compiler - // parses, and a rule that builds the field from a file stem cannot know - // it has produced `my-shader_comp` or `default` until it gets here. - s += std::format("inline payload {}() {{ return {{ {}_data(), {}_size() }}; }}\n", - identifier(it.identifier, "payload"), base, base); - } - reopen({}); - return s; -} - -// ONE OBJECT FORMAT PER PLATFORM, AND THE DIFFERENCES ARE NOT COSMETIC. -// -// `.incbin` is the portable part: gas and clang's integrated assembler both -// accept it everywhere, and it resolves its argument at ASSEMBLY time, which is -// why this file can be written before the payload exists. What is not portable -// is the section directive and whether a C symbol carries a leading underscore. -// -// ELF `.section .rodata`, symbol as written -// Mach-O `.section __TEXT,__const`, symbol PREFIXED with `_` -// COFF `.section .rdata,"dr"`, symbol as written on x86_64 -// -// Mach-O's underscore is the one that fails quietly in the other direction: an -// assembly label without it defines a symbol the C++ side never resolves, and -// the link error names the accessor rather than the missing prefix. -struct asm_dialect { - std::string_view section; - std::string_view symbol_prefix; -}; - -inline asm_dialect dialect_for(std::string_view targetOs) { - if (targetOs == "macos" || targetOs == "macosx" || targetOs == "darwin") - return { ".section __TEXT,__const", "_" }; - if (targetOs == "windows") return { ".section .rdata,\"dr\"", "" }; - return { ".section .rodata", "" }; -} - -// `.balign 4` rather than nothing: `VkShaderModuleCreateInfo::pCode` requires -// four-byte alignment, and a section directive alone does not promise it. The -// header route gets alignment from the array's element type; this route has to -// ask for it. -inline std::string assembly_for(std::span items, const options& opt, - std::string_view targetOs) { - const auto d = dialect_for(targetOs); - std::string s = - "// Generated by mcpp.plugins.surface. Do not edit.\n" - "//\n" - "// The payloads, as sections rather than as C arrays. `.incbin` resolves\n" - "// its argument when this file is assembled, which is after the actions\n" - "// that write those files have run.\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - s += std::format("\n {}\n" - " .globl {}{}_begin\n" - " .balign 4\n" - "{}{}_begin:\n" - " .incbin \"{}\"\n" - " .globl {}{}_end\n" - "{}{}_end:\n", - d.section, - d.symbol_prefix, base, - d.symbol_prefix, base, - it.payload_path, - d.symbol_prefix, base, - d.symbol_prefix, base); - } - return s; -} - -// ---- the tool --------------------------------------------------------------- - -// EVERY FILE THIS SURFACE WILL PRODUCE, WITHOUT PRODUCING ANY OF THEM. -// -// A rule declares these as an action's outputs, and mcpp requires an output to -// be NAMED before the graph is built even though its content arrives later. So -// the names cannot come from having written the files -- which is the coupling -// that forced generation to happen at plan time, and with it the whole -// staleness this round removes. -// -// Pure: no items, no filesystem, no environment. The one decision it makes is -// the MSVC degradation, which is a property of the toolchain rather than of any -// payload, and `emitted::store` is where the caller reads the verdict. -inline emitted outputs(const options& opt) { - emitted out; - out.store = opt.store; - // MSVC HAS NO GAS, AND mcpp REFUSES `.S` UNDER IT. `src/build/prepare.cppm` - // says so outright: "GAS assembly sources (.S/.s) are not supported by the - // MSVC toolchain". Object storage degrades to header storage there rather - // than producing a file the build will refuse, and the SURFACE does not - // change -- the declarations are identical under both. - if (out.store == storage::object && !opt.has_gas_assembler) - out.store = storage::header; - - const auto dir = std::filesystem::path(opt.out_dir); - out.interface_file = (dir / (opt.module_name - + (opt.surface == kind::module_ ? ".cppm" : ".h"))).string(); - out.impl_file = (dir / (opt.module_name + ".impl.cpp")).string(); - // Named only under the storage that produces one, so a caller can test the - // string rather than having to test the storage a second time. - if (out.store == storage::object) - out.assembly_file = (dir / (opt.module_name + ".payload.S")).string(); - if (opt.surface == kind::module_) out.module_name = opt.module_name; - else out.include_dir = dir.string(); - return out; -} - - -// The assembly's meaning includes the bytes named by .incbin. Put a content -// checksum in its source so restat cannot prune the assembler after a payload -// changes while the .incbin path stays the same. This runs in the body action, -// after its declared payload inputs exist; planning still reads no payload. -inline std::optional payload_checksum(const std::string& file) { - std::ifstream input(file, std::ios::binary); - if (!input) return std::nullopt; - std::uint64_t sum = 14695981039346656037ULL; - std::array bytes; - while (input) { - input.read(bytes.data(), static_cast(bytes.size())); - for (std::streamsize i = 0; i < input.gcount(); ++i) { - sum ^= static_cast(bytes[static_cast(i)]); - sum *= 1099511628211ULL; - } - } - return input.bad() ? std::nullopt : std::optional(sum); -} - -// Writes ONE half of the surface. The names come from `outputs`, which the -// caller has already asked; this produces the content. -// -// The interface reads no payload. The object body runs after its declared -// payload inputs, records their content checksum and names them in .incbin; -// the assembler reads the bytes after that body action has completed. -inline bool write(std::span items, const options& opt, half which) { - if (items.empty()) return true; - if (opt.module_name.empty()) { - std::cerr << "mcpp.plugins.surface: options::module_name is required; it names both " - "the module a consumer imports and the namespace the declarations sit in\n"; - return false; - } - if (opt.out_dir.empty()) { - std::cerr << "mcpp.plugins.surface: options::out_dir is required\n"; - return false; - } - - const auto segs = split_module_name(opt.module_name); - // REFUSED HERE, NOT IN THE GENERATED FILE. The module name is the one part - // of this surface a project writes itself, and each of its segments becomes - // a namespace. A segment that is not an identifier -- empty, starting with - // a digit, carrying a `-`, or reserved -- produces a generated file that - // does not parse, and the error then names a line nobody wrote. - for (std::size_t i = 0; i < segs.size(); ++i) { - if (segs[i] == identifier(segs[i], "")) continue; - std::cerr << std::format( - "mcpp.plugins.surface: `{}` is not a usable module name: the segment `{}` " - "is not a C++ identifier.\n Each segment becomes a namespace, so it has " - "to be one; `{}` would work.\n", - opt.module_name, segs[i], identifier(segs[i], "part")); - return false; - } - const auto by = opt.produced_by.empty() ? std::string("mcpp.plugins.surface") - : opt.produced_by; - - // ONE derivation of the names, shared with the caller. Recomputing them - // here would be the second copy of a decision that this package has paid - // for before. - const emitted out = outputs(opt); - const auto dir = std::filesystem::path(opt.out_dir); - const auto body = declarations(items, opt); - - // ---- interface ---- - if (which == half::interface_) { - std::string iface; - iface += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); - if (opt.surface == kind::module_) - iface += std::format("export module {};\n\n", opt.module_name); - else - iface += "#pragma once\n\n"; - iface += extern_c_declarations(items, opt); - iface += "\n"; - // `export` on the opening namespace exports everything the block - // contains, including the nested namespaces a payload's directory - // produced. - if (opt.surface == kind::module_) iface += "export "; - iface += open_namespaces(segs); - iface += "\n" + body + "\n"; - iface += close_namespaces(segs); - if (!write_if_different(out.interface_file, iface)) { - std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", - out.interface_file); - return false; - } - return true; - } - - // ---- implementation ---- (half::body from here down) - // - // The one translation unit that defines the accessors. A plain `.cpp` under - // every surface and every storage, because the accessors have C language - // linkage and so need no attachment to the module. What differs between the - // three storages is only where it reads the bytes from. - const char* elem = element_type(opt.elem); - std::string impl; - impl += std::format("// Generated by mcpp.plugins.surface for {}. Do not edit.\n", by); - - if (out.store == storage::header) { - impl += "//\n" - "// The only translation unit that includes the generated data headers.\n" - "// Each declares a `static` array, so this is also the only copy of the\n" - "// bytes in the program.\n"; - for (auto const& it : items) impl += std::format("#include \"{}\"\n", it.data_header); - impl += "\n"; - impl += element_width_assertion(opt.elem); - impl += "\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - const auto size = it.data_size_expr.empty() - ? std::format("sizeof {}", it.data_symbol) - : it.data_size_expr; - impl += std::format( - "extern \"C\" const {0}* {1}_data() {{ return {2}; }}\n" - "extern \"C\" unsigned long {1}_size() {{ return {3}; }}\n", - elem, base, it.data_symbol, size); - } - } else if (out.store == storage::object) { - impl += "//\n" - "// The bytes are in a section written by the generated `.S`. This file\n" - "// only names its two boundary symbols, so nothing here parses a payload\n" - "// and the C++ compiler never sees one.\n" - "//\n" - "// The symbols are declared as arrays of the element type rather than as\n" - "// `char`: the assembly aligned the section to four bytes, and a\n" - "// declaration that said `char` would let a consumer reach it through an\n" - "// under-aligned pointer with nothing to notice.\n"; - impl += "\n"; - impl += element_width_assertion(opt.elem); - impl += "\nextern \"C\" {\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - impl += std::format("extern const {0} {1}_begin[];\n" - "extern const {0} {1}_end[];\n", elem, base); - } - impl += "}\n\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - impl += std::format( - "extern \"C\" const {0}* {1}_data() {{ return {1}_begin; }}\n" - "extern \"C\" unsigned long {1}_size() {{\n" - " return static_cast(({1}_end - {1}_begin) * sizeof({0}));\n" - "}}\n", elem, base); - } - } else { - impl += "//\n" - "// The payloads are files beside the artifact, read on first use. The\n" - "// path is resolved against the WORKING DIRECTORY, which is the property\n" - "// that makes this storage the one a project opts into rather than the\n" - "// default: a program started from elsewhere finds nothing.\n" - "//\n" - "// Read once and kept: an accessor that reloaded would hand two callers\n" - "// two different pointers to the same payload, and a device API given\n" - "// the second after the first was freed is a defect with no message.\n"; - impl += "#include \n#include \n#include \n\n"; - impl += element_width_assertion(opt.elem); - impl += std::format(R"IMPL( -namespace {{ - -struct blob {{ {0}* data = nullptr; unsigned long size = 0; bool tried = false; }}; - -blob& load(const char* path, blob& b) {{ - if (b.tried) return b; - b.tried = true; - std::FILE* f = std::fopen(path, "rb"); - if (!f) {{ - std::fprintf(stderr, "mcpp.plugins.surface: cannot open %s\n", path); - return b; - }} - std::fseek(f, 0, SEEK_END); - const long n = std::ftell(f); - std::fseek(f, 0, SEEK_SET); - if (n > 0) {{ - b.data = static_cast<{0}*>(std::malloc(static_cast(n))); - if (b.data && std::fread(b.data, 1, static_cast(n), f) - == static_cast(n)) - b.size = static_cast(n); - else {{ std::free(b.data); b.data = nullptr; }} - }} - std::fclose(f); - return b; -}} - -}} // namespace -)IMPL", elem); - impl += "\n"; - for (auto const& it : items) { - const auto base = accessor_base(opt, it); - impl += std::format( - "static blob {0}_blob;\n" - "extern \"C\" const {1}* {0}_data() {{\n" - " return load(\"{2}\", {0}_blob).data;\n" - "}}\n" - "extern \"C\" unsigned long {0}_size() {{\n" - " return load(\"{2}\", {0}_blob).size;\n" - "}}\n", base, elem, it.sidecar_name); - } - } - - if (!write_if_different(out.impl_file, impl)) { - std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", out.impl_file); - return false; - } - - if (out.store == storage::object) { - // A CALLER THAT ASKS FOR THIS STORAGE MUST HAVE SAID WHERE THE BYTES - // ARE, AND THE REFUSAL IS WHAT KEEPS THAT TRUE. - // - // `item::payload_path` is documented as required under `object`, and - // today only `mcpp.rules.spirv` reaches this storage and only it sets - // the field. That is a COINCIDENCE, not a guarantee: the first caller - // to give `rules-slang` or `tools-embed` a storage option would get an - // `.incbin ""` in a generated `.S`, and the declaration below would - // then name an empty dependency -- so the build would be wrong in - // exactly the silent way this whole change exists to remove. - // - // A constraint written only in a comment has nothing enforcing it, - // which is a shape this project has recorded before. This is the - // enforcement. - for (auto const& it : items) { - if (!it.payload_path.empty()) continue; - std::cerr << std::format( - "mcpp.plugins.surface: `{}` was given storage::object with no " - "payload_path.\n" - " Under this storage the generated assembly names the payload " - "in `.incbin`, so\n" - " the caller has to say where it is. Set `item::payload_path`, " - "or use storage::header.\n", - it.identifier); - return false; - } - auto assembly = assembly_for(items, opt, opt.target_os); - for (const auto& it : items) { - const auto checksum = payload_checksum(it.payload_path); - if (!checksum) { - std::cerr << std::format("mcpp.plugins.surface: cannot read payload {}\n", it.payload_path); - return false; - } - assembly += std::format("// payload content: {:016x}\n", *checksum); - } - if (!write_if_different(out.assembly_file, assembly)) { - std::cerr << std::format("mcpp.plugins.surface: cannot write {}\n", - out.assembly_file); - return false; - } - } - // `storage::sidecar` needs no counterpart, and that was checked rather than - // assumed. Its payload is never read by a compile: the accessor opens the - // file at RUN time, so a rebuilt payload is picked up by the next run with - // nothing in the build graph to keep current. - return true; -} - -// The surface a project gets when it asks for nothing. -// -// `MCPP_LANGUAGE_MODULES` is set by mcpp from `[language] modules`. An engine -// that does not set it leaves the variable absent, and the fallback is the -// header surface -- which is what every consumer of this package had before -// this module existed. An older engine therefore keeps its behaviour and a -// newer one gets the module surface without any project asking, which is the -// whole of the upgrade path. -inline kind default_surface() { - const char* v = std::getenv("MCPP_LANGUAGE_MODULES"); - return (v && (*v == '1' || *v == 't' || *v == 'T')) ? kind::module_ : kind::c_header; -} - -// `example:my-app` -> `my_app`. The module a rule names by default is this -// followed by the group's own segment, so two packages in one build cannot -// claim the same module. -// The default module root for a package that named none: its PACKAGE NAME, -// sanitised into an identifier. -// -// THE PACKAGE'S NAME. NOT ITS DIRECTORY'S. These are different questions and -// they give different answers whenever a project lays a package out under a -// generic directory. The first version asked the only question mcpp could -// answer -- the leaf of MCPP_MANIFEST_DIR -- so a package named `vulkan-saxpy` -// laid out as `vulkan/app/` generated `app.shaders`, and every -// `/app/` in a workspace claimed that same module. -// -// The name ARRIVES rather than being read, for the reason `options::target_os` -// records: this module must compile into a plain binary as well as into a -// build program, so it may not reach for `mcpp::package_name()` itself. The -// caller passes what mcpp told it. -// -// `fallback` covers the impossible case -- a manifest without a `[package] -// name` does not load, so an empty first argument would mean the contract -// changed underneath. A rule that wants neither passes `options::module_name`, -// and this is not consulted. -inline std::string module_root_for(std::string_view package_name, - std::string_view fallback = {}) { - std::string leaf{package_name}; - if (leaf.empty()) leaf = std::string(fallback); - return identifier(leaf, "app"); -} - -} // namespace mcpp::plugins::surface diff --git a/src/plugins/tree.cppm b/src/plugins/tree.cppm deleted file mode 100644 index b14eea6..0000000 --- a/src/plugins/tree.cppm +++ /dev/null @@ -1,48 +0,0 @@ -export module mcpp.plugins:tree; - -import std; - - -// mcpp::plugins::tree -- the directories a walk of a source tree leaves out. -// -// SHARED BECAUSE TWO MEMBERS WALK A SOURCE TREE BY DEFAULT. `rules-qt` finds -// the headers moc reads and the sources lupdate reads under the package, and -// `deps` takes every file of a subproject as an input of its installation, and -// `deps-cmake` as part of the installation's key. Neither may take what ANOTHER -// build system generated there: a Visual Studio project built in the same -// checkout leaves its moc and uic output under `x64/Release/`, and lupdate -// given those files rewrites the translations, and a CMake build directory an -// IDE made inside a subproject changes the key on every build. -// -// Such a directory is known by what its build system leaves in it, not by its -// name: `x64/` is as often a directory of architecture-specific sources. -export namespace mcpp::plugins::tree { - -// Whether `dir` is an output directory of another build system: -// -// CMakeCache.txt a CMake build tree (an IDE's `cmake-build-*`, `out/build/*`) -// .qmake.stash a qmake build tree -// CACHEDIR.TAG a directory its tool tags as a cache (https://bford.info/cachedir/) -// .tlog/ an MSBuild intermediate directory (`x64/Release/`), where a -// Visual Studio project writes the sources it generates -// -// A walk asks this of the directories under its root, never of the root: a -// subproject configured in its own source directory holds CMakeCache.txt too. -inline bool build_output(const std::filesystem::path& dir) { - namespace fs = std::filesystem; - std::error_code ec; - if (fs::is_regular_file(dir / "CMakeCache.txt", ec) || fs::is_regular_file(dir / ".qmake.stash", ec)) - return true; - if (fs::is_regular_file(dir / "CACHEDIR.TAG", ec)) { - std::ifstream in(dir / "CACHEDIR.TAG", std::ios::binary); - std::string head(43, '\0'); - in.read(head.data(), 43); - if (head == "Signature: 8a477f597d28d172789f06886806bc55") return true; - } - for (auto it = fs::directory_iterator(dir, fs::directory_options::skip_permission_denied, ec); - !ec && it != fs::directory_iterator(); it.increment(ec)) - if (it->path().extension() == ".tlog" && it->is_directory(ec)) return true; - return false; -} - -} // namespace mcpp::plugins::tree diff --git a/src/plugins/xml.cppm b/src/plugins/xml.cppm deleted file mode 100644 index 1c34f7c..0000000 --- a/src/plugins/xml.cppm +++ /dev/null @@ -1,169 +0,0 @@ -export module mcpp.plugins:xml; - -import std; - - -// mcpp::plugins::xml -- the XML two dist members read and write. -// -// SHARED BECAUSE TWO DIST MEMBERS READ IT. `dist-apk` merges library manifests -// into an application's, and `dist-apple` adds a project's Info.plist entries -// and reads the plist a provisioning profile carries. Neither needs more than -// elements, attributes and text, and neither interprets an entity, so this is -// that much and no more: no namespaces resolved, no DTD read, no validation. -export namespace mcpp::plugins::xml { - -// A tree of elements and text. Comments, the XML declaration and a DOCTYPE are -// read and dropped: the documents this member writes from a tree are generated -// files, and a merged manifest carries no author to read a comment. Attribute -// values are kept exactly as written, entities included, because nothing here -// interprets them beyond comparing and substituting `${applicationId}`. -struct node { - std::string name; // empty: a text node - std::vector> attrs; - std::vector children; - std::string text; // a text node's characters -}; - -struct reader { - std::string_view s; - std::size_t i = 0; - std::string error; - - static bool space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } - bool starts(std::string_view t) const { return s.substr(i, t.size()) == t; } - void skip_space() { while (i < s.size() && space(s[i])) ++i; } - bool skip_past(std::string_view end) { - const auto p = s.find(end, i); - if (p == std::string_view::npos) { i = s.size(); return false; } - i = p + end.size(); - return true; - } - std::string name() { - const std::size_t b = i; - while (i < s.size() && !space(s[i]) && s[i] != '>' && s[i] != '/' && s[i] != '=') ++i; - return std::string(s.substr(b, i - b)); - } - - bool element(node& out) { - ++i; // '<' - out.name = name(); - if (out.name.empty()) { error = "an element without a name"; return false; } - for (;;) { - skip_space(); - if (i >= s.size()) { error = "<" + out.name + "> is not terminated"; return false; } - if (starts("/>")) { i += 2; return true; } - if (s[i] == '>') { ++i; break; } - std::string attr = name(); - skip_space(); - if (attr.empty() || i >= s.size() || s[i] != '=') { - error = "an attribute of <" + out.name + "> has no value"; - return false; - } - ++i; - skip_space(); - if (i >= s.size() || (s[i] != '"' && s[i] != '\'')) { - error = "attribute " + attr + " of <" + out.name + "> is not quoted"; - return false; - } - const char quote = s[i++]; - const auto end = s.find(quote, i); - if (end == std::string_view::npos) { error = "attribute " + attr + " is not terminated"; return false; } - out.attrs.emplace_back(std::move(attr), std::string(s.substr(i, end - i))); - i = end + 1; - } - for (;;) { - if (i >= s.size()) { error = "<" + out.name + "> is not closed"; return false; } - if (starts("= s.size() || s[i] != '>') { - error = " closes <" + out.name + ">"; - return false; - } - ++i; - return true; - } - if (starts("")) { error = "a comment is not terminated"; return false; } continue; } - if (starts("")) { error = "a processing instruction is not terminated"; return false; } continue; } - if (starts("")) { error = "a CDATA section is not terminated"; return false; } - node t; - t.text = std::string(s.substr(b, i - b)); - out.children.push_back(std::move(t)); - continue; - } - if (s[i] == '<') { - node child; - if (!element(child)) return false; - out.children.push_back(std::move(child)); - continue; - } - const std::size_t b = i; - auto end = s.find('<', i); - if (end == std::string_view::npos) end = s.size(); - i = end; - bool blank = true; - for (std::size_t j = b; j < end; ++j) if (!space(s[j])) { blank = false; break; } - if (!blank) { - node t; - t.text = std::string(s.substr(b, end - b)); - out.children.push_back(std::move(t)); - } - } - } - - bool document(node& root) { - for (;;) { - skip_space(); - if (starts(""); continue; } - if (starts(""); continue; } - if (starts(""); continue; } - break; - } - if (i >= s.size() || s[i] != '<') { error = "no root element"; return false; } - if (!element(root)) return false; - return true; - } -}; - -inline bool parse(std::string_view text, node& root, std::string& error) { - reader r{text}; - if (!r.document(root)) { error = r.error; return false; } - return true; -} - -inline std::string trim_copy(const std::string& s) { - std::size_t b = 0, e = s.size(); - while (b < e && reader::space(s[b])) ++b; - while (e > b && reader::space(s[e - 1])) --e; - return s.substr(b, e - b); -} - -inline void write(const node& n, std::string& out, int depth) { - const std::string pad(static_cast(depth) * 4, ' '); - if (n.name.empty()) { out += pad + trim_copy(n.text) + "\n"; return; } - out += pad + "<" + n.name; - for (auto const& a : n.attrs) out += " " + a.first + "=\"" + a.second + "\""; - if (n.children.empty()) { out += "/>\n"; return; } - if (n.children.size() == 1 && n.children.front().name.empty()) { - out += ">" + n.children.front().text + "\n"; - return; - } - out += ">\n"; - for (auto const& c : n.children) write(c, out, depth + 1); - out += pad + "\n"; -} - -inline std::string attr_of(const node& n, std::string_view key) { - for (auto const& a : n.attrs) if (a.first == key) return a.second; - return {}; -} - -inline void set_attr(node& n, const std::string& key, const std::string& value) { - for (auto& a : n.attrs) if (a.first == key) { a.second = value; return; } - n.attrs.emplace_back(key, value); -} - -} // namespace mcpp::plugins::xml From 7cd83767ca3893472a3508adb9b1ab53c6bd8609 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 16:48:33 +0800 Subject: [PATCH 08/18] README: four-column member tables and a contributing ladder; the module and floor columns live in the documentation index --- README.md | 110 +++++++++++++++------------------- README.zh-CN.md | 102 ++++++++++++++----------------- docs/01-plugin-development.md | 4 ++ docs/README.md | 48 +++++++++++++++ 4 files changed, 146 insertions(+), 118 deletions(-) diff --git a/README.md b/README.md index d42ee16..a828c87 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,11 @@ > The official build plugins for mcpp — one member, one feature, one module. -**English** | [简体中文](README.zh-CN.md) - [![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) -[Documentation](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [Package index](https://mcpplibs.github.io/mcpp-index/) · [Releases](https://github.com/mcpp-community/mcpp-plugins/releases) +**English** | [简体中文](README.zh-CN.md) · [Documentation](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [Package index](https://mcpplibs.github.io/mcpp-index/) · [Releases](https://github.com/mcpp-community/mcpp-plugins/releases) mcpp is a general engine with a framework for build plugins; plugins come from this package (`mcpp:plugins`), from third parties, or from the project itself, @@ -55,69 +53,59 @@ runs comes from is in [docs/02](docs/02-tool-sources.md). ## Plugins -The most used: - -| member | module | what it does | doc | +| feature | what it does | doc | maintainer | |---|---|---|---| -| `rules-cuda` | `mcpp.rules.cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | -| `rules-sycl` | `mcpp.rules.sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | -| `rules-spirv` | `mcpp.rules.spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | -| `rules-qt` | `mcpp.rules.qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | -| `dist-apk` | `mcpp.dist.apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) | +| `rules-cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) |
-All 23 members — feature, module, mcpp floor, behaviour, doc, maintainer - -| feature | module | mcpp floor | what it does | doc | maintainer | -|---|---|---|---|---|---| -| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [rules](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [rules](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [rules](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | Writes a data file into a header the program compiles in. | [tools-embed](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | Generates the `extern "C"` boundary and the C++ module of a code island. | [tools-island](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [tools-steps](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [dist](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | The same installation as an RPM package (Linux targets). | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [dist](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [dist-apple](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [dist](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [dist-apk](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3; a cross build 2026.10.30.1 | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved -- for another target, the compilers and words of the engine's contract -- keeps the installation for any build with the same key, and maps the prefix into the build. | [deps](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | Extracts a zip archive the project keeps and places its tree beside the program. | [deps](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) | - -Some features add a sub-capability: `dist-apk-kotlin`, `dist-apk-maven`, and -`deps`, which the deps members imply. `plugins-core` — `mcpp.plugins.declare`, -`mcpp.plugins.toolset`, `mcpp.plugins.fs`, `mcpp.plugins.tool` — is the general -library every member implies; `plugins-testing`, `plugins-toolchain`, -`plugins-platform` and `plugins-progress` add their own modules. Their layers -and the engine floor are in -[docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor). +All 23 members — feature, behaviour, doc, maintainer; the modules and engine floors are in the documentation index + +| feature | what it does | doc | maintainer | +|---|---|---|---| +| `rules-ascendc` | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [docs](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-hip` | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [docs](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-metal` | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [docs](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qml` | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [docs](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-slang` | Compiles Slang (`*.slang`) and embeds or places the result. | [docs](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-swift` | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [docs](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-embed` | Writes a data file into a header the program compiles in. | [docs](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-island` | Generates the `extern "C"` boundary and the C++ module of a code island. | [docs](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-steps` | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [docs](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-appimage` | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [docs](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-deb` | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-rpm` | The same installation as an RPM package (Linux targets). | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-wix` | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [docs](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apple` | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [docs](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-web` | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [docs](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-cmake` | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-archive` | Extracts a zip archive the project keeps and places its tree beside the program. | [docs](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) |
## Contributing and maintenance -**Maintainers.** The package and, today, every member: -[@Sunrisepeak](https://github.com/Sunrisepeak). Review routing by family: -[`.github/CODEOWNERS`](.github/CODEOWNERS) — a new maintainer takes a family -by editing one line. - -**Contributing.** A change goes through a pull request from a branch; one pull -request does one thing; commits and text are English. A new member is a module -(or a directory when it outgrows one file — [docs/01 -§5](docs/01-plugin-development.md#5-a-new-plugin)), a feature in `mcpp.toml`, -a consumer under `tests/` that CI builds and asserts on, a row in the table -above, a page under `docs/`, and a version bump. The conventions a member -follows are in [docs/01](docs/01-plugin-development.md); the division between -what the engine owns and what the member owns is in -[docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns). +1. **Submit a plugin** — a plugin ships in its own package + (`mcpp..*`); one accepted into this repository follows the + [new-member checklist](docs/01-plugin-development.md#5-a-new-plugin) and + the conventions in [docs/01](docs/01-plugin-development.md), and its + original author becomes the member's maintainer. +2. **Maintain and improve** — bug fixes and improvement suggestions go + through pull requests; every documented behaviour has a CI criterion + ([docs/01 §2](docs/01-plugin-development.md#2-rules)). +3. **Become a member's maintainer** — the ladder is submit, then maintain, + then take one: a maintainer carries a member's daily upkeep and its + teaching ([docs/](docs/README.md)), and should know the member's domain. + [@Sunrisepeak](https://github.com/Sunrisepeak) maintains the repository as + a whole, and some standalone members are looking for theirs — say so in an + issue. diff --git a/README.zh-CN.md b/README.zh-CN.md index b752a6b..fed1e74 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -2,13 +2,11 @@ > mcpp 的官方构建插件——一个成员,一个 feature,一个模块。 -[English](README.md) | 简体中文 - [![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) -[文档索引](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [包索引 mcpp-index](https://mcpplibs.github.io/mcpp-index/) · [发布](https://github.com/mcpp-community/mcpp-plugins/releases) +[English](README.md) | 简体中文 · [文档索引](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [包索引 mcpp-index](https://mcpplibs.github.io/mcpp-index/) · [发布](https://github.com/mcpp-community/mcpp-plugins/releases) mcpp 是一个带有构建插件框架的通用引擎;插件来自本包(`mcpp:plugins`)、来自 第三方,或来自项目自身,而 `build.mcpp` 是项目使用它们的地方:它按成员声明 @@ -52,65 +50,55 @@ int main() { ## 插件 -最常用的几个: - -| 成员 | 模块 | 行为 | 文档 | +| feature | 行为 | 文档 | 维护者 | |---|---|---|---| -| `rules-cuda` | `mcpp.rules.cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | -| `rules-sycl` | `mcpp.rules.sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | -| `rules-spirv` | `mcpp.rules.spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | -| `rules-qt` | `mcpp.rules.qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | -| `dist-apk` | `mcpp.dist.apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) | +| `rules-cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) |
-全部 23 个成员——feature、模块、mcpp 下限、行为、文档、维护者 - -| feature | 模块 | mcpp 下限 | 行为 | 文档 | 维护者 | -|---|---|---|---|---|---| -| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [rules](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [rules](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [rules](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [rules](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [rules-qt](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3;携带 QML 插件库的包 2026.11.23.1 | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [rules-qml](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [rules](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [rules](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [rules](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | 把数据文件写进程序编译内含的头文件。 | [tools-embed](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [tools-island](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [tools-steps](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [dist](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [dist](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [dist](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [dist-apple](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [dist](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [dist-apk](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3;交叉构建 2026.10.30.1 | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目——交叉目标时用引擎契约的编译器与措辞;同键的构建复用安装,并把前缀映射进构建。 | [deps](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [deps](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) | - -一些 feature 添加子能力:`dist-apk-kotlin`、`dist-apk-maven`,以及 deps 成员 -隐含的 `deps`。`plugins-core`——`mcpp.plugins.declare`、 -`mcpp.plugins.toolset`、`mcpp.plugins.fs`、`mcpp.plugins.tool`——是每个成员 -都隐含的通用库;`plugins-testing`、`plugins-toolchain`、 -`plugins-platform` 与 `plugins-progress` 各自添加自己的模块。分层与引擎 -下限见 [docs/01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor)。 +全部 23 个成员——feature、行为、文档、维护者;模块与引擎下限见文档索引 + +| feature | 行为 | 文档 | 维护者 | +|---|---|---|---| +| `rules-ascendc` | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [docs](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-hip` | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [docs](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-metal` | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [docs](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-qml` | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [docs](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-slang` | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-swift` | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [docs](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `rules-sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-embed` | 把数据文件写进程序编译内含的头文件。 | [docs](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-island` | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [docs](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `tools-steps` | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [docs](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-appimage` | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [docs](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-deb` | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-rpm` | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-wix` | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [docs](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apple` | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [docs](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-web` | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [docs](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-cmake` | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目,并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| `deps-archive` | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [docs](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) |
## 贡献与维护 -**维护者。** 本包以及今天每一个成员: -[@Sunrisepeak](https://github.com/Sunrisepeak)。按族的 review 路由: -[`.github/CODEOWNERS`](.github/CODEOWNERS)——新维护者改一行即可接管一个族。 - -**贡献。** 变更经分支上的 pull request;一个 PR 只做一件事;提交与文字用 -英文。新成员 = 一个模块(长出一个文件时改为目录——[docs/01 -§5](docs/01-plugin-development.md#5-a-new-plugin))、`mcpp.toml` 里的一个 -feature、`tests/` 下一个由 CI 构建并断言的消费者、上表里的一行、`docs/` 下的 -一页、一次版本提升。成员遵循的约定见 -[docs/01](docs/01-plugin-development.md);引擎拥有什么、成员拥有什么的划分 -见 [docs/00](docs/00-engine-and-rules.md#adding-a-member-what-the-engine-owns-and-what-the-member-owns)。 +1. **提交一个插件**——插件在自己的包里(`mcpp..*`);被本仓库 + 收录的插件遵循[新成员清单](docs/01-plugin-development.md#5-a-new-plugin) + 与 [docs/01](docs/01-plugin-development.md) 的约定,其原作者即成为该成员 + 的维护者。 +2. **参与维护与改进**——bug 修复与优化建议经 pull request;每一条文档化的 + 行为都有 CI 判据([docs/01 §2](docs/01-plugin-development.md#2-rules))。 +3. **申请成为某个成员的维护者**——阶梯是:提交、参与维护、接手一个成员: + 维护者承担成员的日常维护与教学([docs/](docs/README.md)),并熟悉该成员的 + 领域。[Sunrisepeak](https://github.com/Sunrisepeak) 维护仓库整体,部分 + 独立成员正在寻找维护者——在 issue 里说明即可。 diff --git a/docs/01-plugin-development.md b/docs/01-plugin-development.md index be2fb13..abb19db 100644 --- a/docs/01-plugin-development.md +++ b/docs/01-plugin-development.md @@ -215,6 +215,10 @@ are the unit's own, never visible to an importer. A unit that shares its module with other units cannot carry a fragment: its private region is a `namespace detail` block, and the names a sibling unit imports stay outside it. +The members this package ships today were written before the rule and are not +migrated: a member adopts the fragment as it is touched — noted here as a +TODO, not carried out wholesale. + ## 5. A new plugin A plugin in this package consists of: diff --git a/docs/README.md b/docs/README.md index 6b90d8b..456c8e3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,6 +15,54 @@ records under [`../.agents/docs/`](../.agents/docs/) — a page cites no record. | know why a name, a floor or a claim is what it is | [00 — How the Members Meet the Engine](00-engine-and-rules.md) | | name a tool a member runs | [02 — Where a Tool Comes From](02-tool-sources.md) | +## The members + +The README's tables carry feature, behaviour, doc and maintainer; this is the +same list with the module each feature compiles and the mcpp release its +behaviour first needed. From 0.21.0 the package as a whole needs mcpp +2026.10.30.1 (`[package] mcpp`); cross CMake subprojects that link executables +or shared libraries require mcpp 2026.11.7.1 or later, and cross configuration +requires CMake 3.19 or later. + +| feature | module | mcpp floor | what it does | doc | +|---|---|---|---|---| +| `rules-ascendc` | `mcpp.rules.ascendc` | 2026.10.1.3 | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [rules](10-rules.md#rules-ascendc) | +| `rules-cuda` | `mcpp.rules.cuda` | 2026.10.1.3 | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [rules](10-rules.md#rules-cuda) | +| `rules-hip` | `mcpp.rules.hip` | 2026.10.1.3 | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [rules](10-rules.md#rules-hip) | +| `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](10-rules.md#rules-metal) | +| `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](11-rules-qt.md) | +| `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](12-rules-qml.md) | +| `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](10-rules.md#rules-slang) | +| `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](10-rules.md#rules-spirv) | +| `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](10-rules.md#rules-swift) | +| `rules-sycl` | `mcpp.rules.sycl` | 2026.10.1.3 | Compiles SYCL (`*.sycl`) with DPC++. | [rules](10-rules.md#rules-sycl) | +| `tools-embed` | `mcpp.tools.embed` | 2026.9.5.4 | Writes a data file into a header the program compiles in. | [tools-embed](20-tools-embed.md) | +| `tools-island` | `mcpp.tools.island` | 2026.9.7.1 | Generates the `extern "C"` boundary and the C++ module of a code island. | [tools-island](21-tools-island.md) | +| `tools-steps` | `mcpp.tools.steps` | 2026.10.1.3 | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [tools-steps](22-tools-steps.md) | +| `dist-appimage` | `mcpp.dist.appimage` | 2026.10.1.3 | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [dist](30-dist.md#dist-appimage) | +| `dist-deb` | `mcpp.dist.deb` | 2026.10.30.1 | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [dist](30-dist.md#dist-deb-and-dist-rpm) | +| `dist-rpm` | `mcpp.dist.rpm` | 2026.10.30.1 | The same installation as an RPM package (Linux targets). | [dist](30-dist.md#dist-deb-and-dist-rpm) | +| `dist-wix` | `mcpp.dist.wix` | 2026.10.1.3 | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [dist](30-dist.md#dist-wix) | +| `dist-apple` | `mcpp.dist.apple` | 2026.9.14.2 | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [dist-apple](31-dist-apple.md) | +| `dist-web` | `mcpp.dist.web` | 2026.9.13.1 | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [dist](30-dist.md#dist-web) | +| `dist-apk` | `mcpp.dist.apk` | 2026.10.1.3 | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [dist-apk](32-dist-apk.md) | +| `deps-vcpkg` | `mcpp.deps.vcpkg` | 2026.10.1.3 | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [deps](40-deps.md#deps-vcpkg) | +| `deps-cmake` | `mcpp.deps.cmake` | 2026.10.1.3; a cross build 2026.10.30.1 | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved -- for another target, the compilers and words of the engine's contract -- keeps the installation for any build with the same key, and maps the prefix into the build. | [deps](40-deps.md#deps-cmake) | +| `deps-archive` | `mcpp.deps.archive` | 2026.10.1.3 | Extracts a zip archive the project keeps and places its tree beside the program. | [deps](40-deps.md#deps-archive) | + +Some features add a sub-capability: `dist-apk-kotlin` and `dist-apk-maven` +(Kotlin sources, a Maven graph), and `deps`, which the deps members imply. + +**The general library.** `plugins-core` — `mcpp.plugins.declare`, +`mcpp.plugins.toolset`, `mcpp.plugins.fs`, `mcpp.plugins.tool` — is the +general library every member implies, and the modules a third-party plugin +built on it names on its dependency edge; `plugins-testing`, +`plugins-toolchain`, `plugins-platform` and `plugins-progress` add their own. +The layers, names and the engine floor are in +[01 §3](01-plugin-development.md#3-layers-names-and-the-engine-floor); +`surface`, the name of `plugins-core` before 0.17.0, is kept until +2027-03-28. + ## Pages The first digit is the part, so a number says where a page belongs: From 907d3a6a46d8ee0697dc119b45d7fbbfdbd32136 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 17:07:59 +0800 Subject: [PATCH 09/18] README: the participation path, the maintainer requirements, a maintainers list, and a maintainer-application issue template --- .../ISSUE_TEMPLATE/maintainer-application.yml | 53 +++++++++ README.md | 108 ++++++++++-------- README.zh-CN.md | 100 ++++++++-------- 3 files changed, 167 insertions(+), 94 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/maintainer-application.yml diff --git a/.github/ISSUE_TEMPLATE/maintainer-application.yml b/.github/ISSUE_TEMPLATE/maintainer-application.yml new file mode 100644 index 0000000..2bcf1f8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/maintainer-application.yml @@ -0,0 +1,53 @@ +name: Member maintainer application +description: Apply to maintain one or more members of mcpp-plugins +labels: ["maintainer-application"] +body: + - type: markdown + attributes: + value: | + Thanks for wanting to take a member's maintainership. + + A maintainer knows the member deeply and its application domain, and + leads its popularization and ecosystem building — technical articles, + videos, tutorials. Development plus outreach is the core of the role. + + Starting simple is fine: the expected path is use it, introduce and + teach it, report issues, fix bugs, improve it — and then take one. + - type: input + id: members + attributes: + label: Member or members you apply for + placeholder: "rules-cuda, rules-sycl" + validations: + required: true + - type: textarea + id: familiarity + attributes: + label: Your familiarity with the member and its domain + description: What you build with it, the related field you work in, how long you have used it. + validations: + required: true + - type: textarea + id: contributions + attributes: + label: Contributions so far + description: Issues, fixes, improvements, documentation or tutorials — links welcome. A short history is fine; everyone starts there. + - type: textarea + id: maintenance-plan + attributes: + label: Maintenance plan + description: The daily upkeep you commit to — issue triage, fixes, fixture and CI care across the platforms the member claims. + validations: + required: true + - type: textarea + id: outreach-plan + attributes: + label: Popularization and outreach plan + description: The articles, videos, tutorials or examples you plan to write, and where you will publish them. + validations: + required: true + - type: textarea + id: where-to-find-you + attributes: + label: Where to find you + description: GitHub, blog, channel — anywhere your work and teaching live. diff --git a/README.md b/README.md index a828c87..616b549 100644 --- a/README.md +++ b/README.md @@ -53,59 +53,69 @@ runs comes from is in [docs/02](docs/02-tool-sources.md). ## Plugins -| feature | what it does | doc | maintainer | -|---|---|---|---| -| `rules-cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| feature | what it does | doc | +|---|---|---| +| `rules-cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | +| `rules-sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | +| `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | +| `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | +| `deps-vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | +| `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) |
-All 23 members — feature, behaviour, doc, maintainer; the modules and engine floors are in the documentation index - -| feature | what it does | doc | maintainer | -|---|---|---|---| -| `rules-ascendc` | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [docs](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-hip` | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [docs](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-metal` | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [docs](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qml` | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [docs](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-slang` | Compiles Slang (`*.slang`) and embeds or places the result. | [docs](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-swift` | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [docs](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-embed` | Writes a data file into a header the program compiles in. | [docs](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-island` | Generates the `extern "C"` boundary and the C++ module of a code island. | [docs](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-steps` | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [docs](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-appimage` | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [docs](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-deb` | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-rpm` | The same installation as an RPM package (Linux targets). | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-wix` | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [docs](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apple` | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [docs](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-web` | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [docs](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-cmake` | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-archive` | Extracts a zip archive the project keeps and places its tree beside the program. | [docs](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +All 23 members — feature, behaviour, doc; the modules and engine floors are in the documentation index + +| feature | what it does | doc | +|---|---|---| +| `rules-ascendc` | Compiles Ascend C (`*.asc`) with BiSheng in mixed mode, so the object joins the ordinary link. | [docs](docs/10-rules.md#rules-ascendc) | +| `rules-cuda` | Compiles CUDA (`*.cu`) through clang with an LLVM toolchain or nvcc with a GCC one. | [docs](docs/10-rules.md#rules-cuda) | +| `rules-hip` | Compiles HIP (`*.hip`) with the project's clang on the NVIDIA platform. | [docs](docs/10-rules.md#rules-hip) | +| `rules-metal` | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [docs](docs/10-rules.md#rules-metal) | +| `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | +| `rules-qml` | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [docs](docs/12-rules-qml.md) | +| `rules-slang` | Compiles Slang (`*.slang`) and embeds or places the result. | [docs](docs/10-rules.md#rules-slang) | +| `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | +| `rules-swift` | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [docs](docs/10-rules.md#rules-swift) | +| `rules-sycl` | Compiles SYCL (`*.sycl`) with DPC++. | [docs](docs/10-rules.md#rules-sycl) | +| `tools-embed` | Writes a data file into a header the program compiles in. | [docs](docs/20-tools-embed.md) | +| `tools-island` | Generates the `extern "C"` boundary and the C++ module of a code island. | [docs](docs/21-tools-island.md) | +| `tools-steps` | Describes an action whose work is more than one command as portable operations a backend runs; implied by `dist-apk` and `dist-apple`. | [docs](docs/22-tools-steps.md) | +| `dist-appimage` | Turns the tree `mcpp pack` stages into an AppImage (Linux). | [docs](docs/30-dist.md#dist-appimage) | +| `dist-deb` | Installs the staged tree under `/opt/` with a launcher, a desktop entry and an icon, as a Debian package (Linux targets). | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | +| `dist-rpm` | The same installation as an RPM package (Linux targets). | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | +| `dist-wix` | Builds an MSI of the staged tree, and a Burn bundle chaining it (Windows). | [docs](docs/30-dist.md#dist-wix) | +| `dist-apple` | Lays out a macOS or iOS application bundle, signs it and writes a disk image. | [docs](docs/31-dist-apple.md) | +| `dist-web` | Copies a `wasm32-emscripten` program and its files into a web directory with an `index.html`. | [docs](docs/30-dist.md#dist-web) | +| `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) | +| `deps-vcpkg` | Installs a `vcpkg.json` manifest as an action with the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-vcpkg) | +| `deps-cmake` | Builds and installs a CMake subproject as an action with Ninja and the toolset mcpp resolved, and maps the prefix into the build. | [docs](docs/40-deps.md#deps-cmake) | +| `deps-archive` | Extracts a zip archive the project keeps and places its tree beside the program. | [docs](docs/40-deps.md#deps-archive) |
## Contributing and maintenance -1. **Submit a plugin** — a plugin ships in its own package - (`mcpp..*`); one accepted into this repository follows the - [new-member checklist](docs/01-plugin-development.md#5-a-new-plugin) and - the conventions in [docs/01](docs/01-plugin-development.md), and its - original author becomes the member's maintainer. -2. **Maintain and improve** — bug fixes and improvement suggestions go - through pull requests; every documented behaviour has a CI criterion - ([docs/01 §2](docs/01-plugin-development.md#2-rules)). -3. **Become a member's maintainer** — the ladder is submit, then maintain, - then take one: a maintainer carries a member's daily upkeep and its - teaching ([docs/](docs/README.md)), and should know the member's domain. - [@Sunrisepeak](https://github.com/Sunrisepeak) maintains the repository as - a whole, and some standalone members are looking for theirs — say so in an - issue. +The repository and, today, every member are maintained by +[@Sunrisepeak](https://github.com/Sunrisepeak) — and more developers are +welcome: to contribute, to maintain, and to carry a member's tutorials and +outreach. Start from the simple and from what interests you, learn the member +as you go, and grow along the path: + +**use it → introduce and teach it → report issues → fix bugs → improve it → +maintain one or more members** + +A member's maintainer knows the member deeply and its application domain, and +leads its popularization and ecosystem building — technical articles, videos, +tutorials. Development plus outreach is the core of the role. Submitting a +plugin follows the [new-member +checklist](docs/01-plugin-development.md#5-a-new-plugin), and its original +author becomes the member's maintainer. Ready to take a member's +maintainership — or to start with bug fixes and improvements? Open it as an +issue; applications go through the [maintainer-application +template](.github/ISSUE_TEMPLATE/maintainer-application.yml). + +## Maintainers + +| maintainer | members primarily maintained | +|---|---| +| [@Sunrisepeak](https://github.com/Sunrisepeak) | the repository, and today every member | diff --git a/README.zh-CN.md b/README.zh-CN.md index fed1e74..0b90334 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -50,55 +50,65 @@ int main() { ## 插件 -| feature | 行为 | 文档 | 维护者 | -|---|---|---|---| -| `rules-cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +| feature | 行为 | 文档 | +|---|---|---| +| `rules-cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | +| `rules-sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | +| `rules-spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | +| `rules-qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | +| `deps-vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | +| `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) |
-全部 23 个成员——feature、行为、文档、维护者;模块与引擎下限见文档索引 - -| feature | 行为 | 文档 | 维护者 | -|---|---|---|---| -| `rules-ascendc` | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [docs](docs/10-rules.md#rules-ascendc) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-hip` | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [docs](docs/10-rules.md#rules-hip) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-metal` | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [docs](docs/10-rules.md#rules-metal) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-qml` | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [docs](docs/12-rules-qml.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-slang` | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-slang) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-swift` | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [docs](docs/10-rules.md#rules-swift) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `rules-sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-embed` | 把数据文件写进程序编译内含的头文件。 | [docs](docs/20-tools-embed.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-island` | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [docs](docs/21-tools-island.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `tools-steps` | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [docs](docs/22-tools-steps.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-appimage` | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [docs](docs/30-dist.md#dist-appimage) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-deb` | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-rpm` | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-wix` | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [docs](docs/30-dist.md#dist-wix) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apple` | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [docs](docs/31-dist-apple.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-web` | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [docs](docs/30-dist.md#dist-web) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-cmake` | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目,并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-cmake) | [@Sunrisepeak](https://github.com/Sunrisepeak) | -| `deps-archive` | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [docs](docs/40-deps.md#deps-archive) | [@Sunrisepeak](https://github.com/Sunrisepeak) | +全部 23 个成员——feature、行为、文档;模块与引擎下限见文档索引 + +| feature | 行为 | 文档 | +|---|---|---| +| `rules-ascendc` | 用 BiSheng 以混合模式编译 Ascend C(`*.asc`),目标文件并入普通链接。 | [docs](docs/10-rules.md#rules-ascendc) | +| `rules-cuda` | 经 clang(LLVM 工具链)或 nvcc(GCC 工具链)编译 CUDA(`*.cu`)。 | [docs](docs/10-rules.md#rules-cuda) | +| `rules-hip` | 在 NVIDIA 平台上用项目自带的 clang 编译 HIP(`*.hip`)。 | [docs](docs/10-rules.md#rules-hip) | +| `rules-metal` | 用宿主的 Xcode 把 `.metal` 着色器编成 Metal 库,并部署在程序旁。 | [docs](docs/10-rules.md#rules-metal) | +| `rules-qt` | 以 action 运行 `moc`、`uic`、`rcc` 与 Qt 的翻译工具,链接 Qt 模块并放置其运行时。 | [docs](docs/11-rules-qt.md) | +| `rules-qml` | 构建 QML 应用:各模块的 `moc`、`qmltyperegistrar`、`qmlcachegen`、`rcc`、`qsb` 链为 action,程序导入的 Qt QML 模块放在程序旁,并写 `qt.conf`。隐含 `rules-qt`。 | [docs](docs/12-rules-qml.md) | +| `rules-slang` | 编译 Slang(`*.slang`),结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-slang) | +| `rules-spirv` | 把 GLSL 与 HLSL 着色器阶段编译为 SPIR-V,结果可内嵌或放置。 | [docs](docs/10-rules.md#rules-spirv) | +| `rules-swift` | 把包的 `.swift` 源码编成一个模块,供 C 与 C++ 源码调用。 | [docs](docs/10-rules.md#rules-swift) | +| `rules-sycl` | 用 DPC++ 编译 SYCL(`*.sycl`)。 | [docs](docs/10-rules.md#rules-sycl) | +| `tools-embed` | 把数据文件写进程序编译内含的头文件。 | [docs](docs/20-tools-embed.md) | +| `tools-island` | 生成代码孤岛的 `extern "C"` 边界与 C++ 模块。 | [docs](docs/21-tools-island.md) | +| `tools-steps` | 把工作不止一条命令的 action 描述为后端运行的可移植操作;被 `dist-apk` 与 `dist-apple` 隐含。 | [docs](docs/22-tools-steps.md) | +| `dist-appimage` | 把 `mcpp pack` 暂存的树做成 AppImage(Linux)。 | [docs](docs/30-dist.md#dist-appimage) | +| `dist-deb` | 把暂存树安装在 `/opt/` 下,带启动器、桌面入口与图标,产出 Debian 包(Linux 目标)。 | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | +| `dist-rpm` | 同样的安装形态,产出 RPM 包(Linux 目标)。 | [docs](docs/30-dist.md#dist-deb-and-dist-rpm) | +| `dist-wix` | 用暂存树构建 MSI,以及串联它的 Burn bundle(Windows)。 | [docs](docs/30-dist.md#dist-wix) | +| `dist-apple` | 布置 macOS 或 iOS 应用 bundle,签名并写成磁盘映像。 | [docs](docs/31-dist-apple.md) | +| `dist-web` | 把 `wasm32-emscripten` 程序及其文件复制进带 `index.html` 的 web 目录。 | [docs](docs/30-dist.md#dist-web) | +| `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) | +| `deps-vcpkg` | 以 action 安装 `vcpkg.json` manifest(用 mcpp 解析的 toolset),并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-vcpkg) | +| `deps-cmake` | 以 action 用 Ninja 与 mcpp 解析的 toolset 构建并安装 CMake 子项目,并把前缀映射进构建。 | [docs](docs/40-deps.md#deps-cmake) | +| `deps-archive` | 解压项目自带的 zip 归档,把它的树放在程序旁。 | [docs](docs/40-deps.md#deps-archive) |
## 贡献与维护 -1. **提交一个插件**——插件在自己的包里(`mcpp..*`);被本仓库 - 收录的插件遵循[新成员清单](docs/01-plugin-development.md#5-a-new-plugin) - 与 [docs/01](docs/01-plugin-development.md) 的约定,其原作者即成为该成员 - 的维护者。 -2. **参与维护与改进**——bug 修复与优化建议经 pull request;每一条文档化的 - 行为都有 CI 判据([docs/01 §2](docs/01-plugin-development.md#2-rules))。 -3. **申请成为某个成员的维护者**——阶梯是:提交、参与维护、接手一个成员: - 维护者承担成员的日常维护与教学([docs/](docs/README.md)),并熟悉该成员的 - 领域。[Sunrisepeak](https://github.com/Sunrisepeak) 维护仓库整体,部分 - 独立成员正在寻找维护者——在 issue 里说明即可。 +仓库整体以及今天的每一个成员都由 +[Sunrisepeak](https://github.com/Sunrisepeak) 维护——期待更多开发者参与: +贡献、维护,以及成员的使用教学与推广。从简单的、自己感兴趣的方向开始,在 +过程中逐渐了解和熟悉,沿这条路径成长: + +**使用它 → 介绍与教学 → 反馈问题 → 修复 bug → 优化改进 → 维护一个或多个 +成员** + +一个成员的维护者:对该成员模块及其应用领域有深入的了解,并能带领它的普及 +与生态建设——技术文章、视频、教程。**技术开发 + 该插件的普及与技术传播**, +是维护者职责的核心。提交插件遵循[新成员 +清单](docs/01-plugin-development.md#5-a-new-plugin),其原作者即成为该成员的 +维护者。想接手某个成员的维护,或先从 bug 修复与优化做起?开 issue 说明; +维护者申请走[申请模板](.github/ISSUE_TEMPLATE/maintainer-application.yml)。 + +## 维护者 + +| 维护者 | 主要负责的成员 | +|---|---| +| [Sunrisepeak](https://github.com/Sunrisepeak) | 仓库整体,以及今天的每一个成员 | From 258a5274f078f6243efac54d4043e93cdfa6ea7b Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 17:24:19 +0800 Subject: [PATCH 10/18] a maintainers page in docs, a compact contributing section, and a per-member application with both contribution categories --- .../ISSUE_TEMPLATE/maintainer-application.yml | 44 ++++++++++--------- README.md | 28 +++++------- README.zh-CN.md | 28 +++++------- docs/03-maintainers.md | 38 ++++++++++++++++ docs/README.md | 2 + 5 files changed, 84 insertions(+), 56 deletions(-) create mode 100644 docs/03-maintainers.md diff --git a/.github/ISSUE_TEMPLATE/maintainer-application.yml b/.github/ISSUE_TEMPLATE/maintainer-application.yml index 2bcf1f8..3842815 100644 --- a/.github/ISSUE_TEMPLATE/maintainer-application.yml +++ b/.github/ISSUE_TEMPLATE/maintainer-application.yml @@ -1,23 +1,23 @@ name: Member maintainer application -description: Apply to maintain one or more members of mcpp-plugins +description: Apply to become the maintainer of one member of mcpp-plugins labels: ["maintainer-application"] body: - type: markdown attributes: value: | - Thanks for wanting to take a member's maintainership. + Thanks for wanting to take a member's maintainership. One application + covers one member. A maintainer knows the member deeply and its application domain, and leads its popularization and ecosystem building — technical articles, - videos, tutorials. Development plus outreach is the core of the role. - - Starting simple is fine: the expected path is use it, introduce and - teach it, report issues, fix bugs, improve it — and then take one. + videos, tutorials. Development plus outreach is the core of the role, + and the application states contributions in both categories. - type: input - id: members + id: member attributes: - label: Member or members you apply for - placeholder: "rules-cuda, rules-sycl" + label: The member you apply for + description: One member per application — for another, open another issue. + placeholder: "rules-cuda" validations: required: true - type: textarea @@ -28,26 +28,28 @@ body: validations: required: true - type: textarea - id: contributions + id: technical-contributions attributes: - label: Contributions so far - description: Issues, fixes, improvements, documentation or tutorials — links welcome. A short history is fine; everyone starts there. + label: Technical contributions to the member + description: Required. Fixes, features, fixture and CI care, documentation — links to your issues and pull requests. + validations: + required: true - type: textarea - id: maintenance-plan + id: outreach-contributions attributes: - label: Maintenance plan - description: The daily upkeep you commit to — issue triage, fixes, fixture and CI care across the platforms the member claims. + label: Technical outreach and promotion contributions + description: Required. The articles, videos, tutorials or examples you have written about the member or its domain — links welcome. validations: required: true - type: textarea - id: outreach-plan + id: maintenance-plan attributes: - label: Popularization and outreach plan - description: The articles, videos, tutorials or examples you plan to write, and where you will publish them. + label: Maintenance plan + description: Required, and both sides of the role — the daily technical upkeep you commit to (triage, fixes, fixture and CI care), and the ongoing popularization you plan to keep doing. validations: required: true - type: textarea - id: where-to-find-you + id: referrer attributes: - label: Where to find you - description: GitHub, blog, channel — anywhere your work and teaching live. + label: Referrer + description: An existing maintainer of a related member who supports this application, if one knows your work. diff --git a/README.md b/README.md index 616b549..3f2f723 100644 --- a/README.md +++ b/README.md @@ -95,24 +95,16 @@ runs comes from is in [docs/02](docs/02-tool-sources.md). ## Contributing and maintenance -The repository and, today, every member are maintained by -[@Sunrisepeak](https://github.com/Sunrisepeak) — and more developers are -welcome: to contribute, to maintain, and to carry a member's tutorials and -outreach. Start from the simple and from what interests you, learn the member -as you go, and grow along the path: - -**use it → introduce and teach it → report issues → fix bugs → improve it → -maintain one or more members** - -A member's maintainer knows the member deeply and its application domain, and -leads its popularization and ecosystem building — technical articles, videos, -tutorials. Development plus outreach is the core of the role. Submitting a -plugin follows the [new-member -checklist](docs/01-plugin-development.md#5-a-new-plugin), and its original -author becomes the member's maintainer. Ready to take a member's -maintainership — or to start with bug fixes and improvements? Open it as an -issue; applications go through the [maintainer-application -template](.github/ISSUE_TEMPLATE/maintainer-application.yml). +The project is maintained mainly by +[@Sunrisepeak](https://github.com/Sunrisepeak) — its upkeep and growth need +more contributors and maintainers. Start from the simple and from what +interests you: use it, introduce and teach it, report issues, fix bugs, +improve it, maintain one or more members. + +If you are interested in contributing to and maintaining some members: + +- [add a new member](docs/01-plugin-development.md#5-a-new-plugin) +- [become a member's maintainer](docs/03-maintainers.md) ## Maintainers diff --git a/README.zh-CN.md b/README.zh-CN.md index 0b90334..2f0e23a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,6 +1,6 @@ # mcpp-plugins -> mcpp 的官方构建插件——一个成员,一个 feature,一个模块。 +> mcpp 的官方构建插件——一个插件成员,一个 feature,一个模块。 [![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) @@ -41,7 +41,7 @@ int main() { | tools | `mcpp.tools.` | 构建程序自己要做什么(见 [`tools/README.md`](tools/README.md)) | | dist | `mcpp.dist.` | 链接产出什么,以及用户以什么形式安装它 | | deps | `mcpp.deps.` | 一个库从哪里来 | -| identity | `mcpp.plugins` | 库根,先于每个成员编译;它声明这个集合的版本 | +| identity | `mcpp.plugins` | 库根,先于每个插件成员编译;它声明这个集合的版本 | 第三方插件把模块命名为 `mcpp.<它的 namespace>.*`;`core`、`plugins`、`deps`、 `rules`、`dist`、`tools` 属于本包与引擎。家族的完整论述,以及引擎如何把文件 @@ -60,7 +60,7 @@ int main() { | `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) |
-全部 23 个成员——feature、行为、文档;模块与引擎下限见文档索引 +全部 23 个插件成员——feature、行为、文档;模块与引擎下限见文档索引 | feature | 行为 | 文档 | |---|---|---| @@ -92,23 +92,17 @@ int main() { ## 贡献与维护 -仓库整体以及今天的每一个成员都由 -[Sunrisepeak](https://github.com/Sunrisepeak) 维护——期待更多开发者参与: -贡献、维护,以及成员的使用教学与推广。从简单的、自己感兴趣的方向开始,在 -过程中逐渐了解和熟悉,沿这条路径成长: +项目目前主要由 [Sunrisepeak](https://github.com/Sunrisepeak) 维护——项目的 +维护和发展需要更多贡献者与维护者。从简单的、自己感兴趣的方向开始:使用它、 +介绍与教学、反馈问题、修复 bug、优化改进、维护一个或多个插件。 -**使用它 → 介绍与教学 → 反馈问题 → 修复 bug → 优化改进 → 维护一个或多个 -成员** +如果你对某些插件感兴趣,并期望参与贡献和维护: -一个成员的维护者:对该成员模块及其应用领域有深入的了解,并能带领它的普及 -与生态建设——技术文章、视频、教程。**技术开发 + 该插件的普及与技术传播**, -是维护者职责的核心。提交插件遵循[新成员 -清单](docs/01-plugin-development.md#5-a-new-plugin),其原作者即成为该成员的 -维护者。想接手某个成员的维护,或先从 bug 修复与优化做起?开 issue 说明; -维护者申请走[申请模板](.github/ISSUE_TEMPLATE/maintainer-application.yml)。 +- [添加一个新的插件](docs/01-plugin-development.md#5-a-new-plugin) +- [申请成为维护者](docs/03-maintainers.md) ## 维护者 -| 维护者 | 主要负责的成员 | +| 维护者 | 主要负责的插件成员 | |---|---| -| [Sunrisepeak](https://github.com/Sunrisepeak) | 仓库整体,以及今天的每一个成员 | +| [Sunrisepeak](https://github.com/Sunrisepeak) | 仓库整体,以及今天的每一个插件成员 | diff --git a/docs/03-maintainers.md b/docs/03-maintainers.md new file mode 100644 index 0000000..21ccb38 --- /dev/null +++ b/docs/03-maintainers.md @@ -0,0 +1,38 @@ +# Maintainers + +The repository is maintained mainly by +[@Sunrisepeak](https://github.com/Sunrisepeak); its upkeep and growth need +more contributors and maintainers. + +## The path + +Start from the simple and from what interests you, and learn a member as you +go: + +**use it → introduce and teach it → report issues → fix bugs → improve it → +maintain one or more members** + +## What a maintainer does + +A member's maintainer carries the member's daily upkeep — issue triage, fixes, +the fixture and CI care on every platform the member claims — and leads its +popularization and ecosystem building: technical articles, videos, tutorials. +Development plus outreach is the core of the role. + +## What a maintainer knows + +Deep familiarity with the member's module and its application domain. The +member's page in the [index](README.md) states what it does; the +[conventions](01-plugin-development.md) state what every plugin follows. + +## Applying + +Applications go through the +[maintainer-application template](../.github/ISSUE_TEMPLATE/maintainer-application.yml), +one member per application. An application states contributions to the member +in both categories — technical development, and technical outreach and +promotion — and a maintenance plan that covers both sides. A recommendation +from an existing maintainer of a related member supports it. The original +author of a member accepted into this repository becomes the member's +maintainer; bug fixes and improvements are always welcome before any +application. diff --git a/docs/README.md b/docs/README.md index 456c8e3..3a13f12 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ records under [`../.agents/docs/`](../.agents/docs/) — a page cites no record. |---|---| | use a member | its page below, and the [quick start](../README.md#quick-start) in the README | | write a plugin of your own | [01 — Plugin Development](01-plugin-development.md) | +| maintain or take a member | [03 — Maintainers](03-maintainers.md) | | know why a name, a floor or a claim is what it is | [00 — How the Members Meet the Engine](00-engine-and-rules.md) | | name a tool a member runs | [02 — Where a Tool Comes From](02-tool-sources.md) | @@ -80,6 +81,7 @@ The first digit is the part, so a number says where a page belongs: - [00 — How the Members Meet the Engine](00-engine-and-rules.md) — the families and their names, each rule's environment and claimed extensions, the engine floor, what a consumer names - [01 — Plugin Development](01-plugin-development.md) — the conventions every plugin follows, the C++ a plugin is written in, a new member's checklist - [02 — Where a Tool Comes From](02-tool-sources.md) — the one order every member resolves a tool in, and every way a project names its own +- [03 — Maintainers](03-maintainers.md) — the participation path, what a maintainer does and knows, how to apply ### 1x — Rules From 77920d1af43df6b830576d246fdeade04796b687 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 17:24:33 +0800 Subject: [PATCH 11/18] the application states its contribution hints: pull requests and commits, articles and videos on public platforms --- .github/ISSUE_TEMPLATE/maintainer-application.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/maintainer-application.yml b/.github/ISSUE_TEMPLATE/maintainer-application.yml index 3842815..b6ef7e0 100644 --- a/.github/ISSUE_TEMPLATE/maintainer-application.yml +++ b/.github/ISSUE_TEMPLATE/maintainer-application.yml @@ -31,14 +31,16 @@ body: id: technical-contributions attributes: label: Technical contributions to the member - description: Required. Fixes, features, fixture and CI care, documentation — links to your issues and pull requests. + description: Required. Pull requests or commits — fixes, features, fixture and CI care, documentation. Link them. + placeholder: "PR #12 — the manifest-merge fix; PR #18 — the min-sdk fixture" validations: required: true - type: textarea id: outreach-contributions attributes: label: Technical outreach and promotion contributions - description: Required. The articles, videos, tutorials or examples you have written about the member or its domain — links welcome. + description: Required. Technical articles, videos, blogs, tutorials or examples about the member or its domain, preferably published on a public platform. Link them. + placeholder: "a manifest-merger walkthrough on a blog; a getting-started video for the member" validations: required: true - type: textarea From adee446c8314985590bbec133d07c3191f98fb47 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 28 Nov 2026 17:43:08 +0800 Subject: [PATCH 12/18] plugins, not members: the terminology, a new-plugin template with an RFC stage, and the maintainer's two cores as a table --- .../ISSUE_TEMPLATE/maintainer-application.yml | 34 +++--- .github/ISSUE_TEMPLATE/new-plugin.yml | 56 +++++++++ .github/workflows/ci.yml | 110 +++++++++--------- AGENTS.md | 32 ++--- README.md | 26 ++--- README.zh-CN.md | 10 +- docs/00-engine-and-rules.md | 52 ++++----- docs/01-plugin-development.md | 26 ++--- docs/02-tool-sources.md | 56 ++++----- docs/03-maintainers.md | 35 +++--- docs/10-rules.md | 4 +- docs/20-tools-embed.md | 4 +- docs/21-tools-island.md | 2 +- docs/22-tools-steps.md | 6 +- docs/30-dist.md | 8 +- docs/31-dist-apple.md | 10 +- docs/32-dist-apk.md | 4 +- docs/40-deps.md | 28 ++--- docs/README.md | 24 ++-- tools/README.md | 8 +- 20 files changed, 299 insertions(+), 236 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/new-plugin.yml diff --git a/.github/ISSUE_TEMPLATE/maintainer-application.yml b/.github/ISSUE_TEMPLATE/maintainer-application.yml index b6ef7e0..c5cb85d 100644 --- a/.github/ISSUE_TEMPLATE/maintainer-application.yml +++ b/.github/ISSUE_TEMPLATE/maintainer-application.yml @@ -1,36 +1,38 @@ -name: Member maintainer application -description: Apply to become the maintainer of one member of mcpp-plugins +name: Plugin maintainer application +description: Apply to become the maintainer of one plugin of mcpp-plugins labels: ["maintainer-application"] body: - type: markdown attributes: value: | - Thanks for wanting to take a member's maintainership. One application - covers one member. + Thanks for wanting to take a plugin's maintainership. One application + covers one plugin. - A maintainer knows the member deeply and its application domain, and + A maintainer knows the plugin deeply and its application domain, and leads its popularization and ecosystem building — technical articles, videos, tutorials. Development plus outreach is the core of the role, - and the application states contributions in both categories. + and the application states contributions in both categories. What a + maintainer does and knows: + [docs/03 — Maintainers](https://github.com/mcpp-community/mcpp-plugins/blob/main/docs/03-maintainers.md). - type: input - id: member + id: plugin attributes: - label: The member you apply for - description: One member per application — for another, open another issue. + label: The plugin you apply for + description: One plugin per application — for another, open another issue. placeholder: "rules-cuda" validations: required: true - type: textarea id: familiarity attributes: - label: Your familiarity with the member and its domain + label: Your familiarity with the plugin and its domain description: What you build with it, the related field you work in, how long you have used it. validations: required: true - type: textarea id: technical-contributions attributes: - label: Technical contributions to the member + label: Technical contributions to the plugin description: Required. Pull requests or commits — fixes, features, fixture and CI care, documentation. Link them. placeholder: "PR #12 — the manifest-merge fix; PR #18 — the min-sdk fixture" validations: @@ -38,9 +40,9 @@ body: - type: textarea id: outreach-contributions attributes: - label: Technical outreach and promotion contributions - description: Required. Technical articles, videos, blogs, tutorials or examples about the member or its domain, preferably published on a public platform. Link them. - placeholder: "a manifest-merger walkthrough on a blog; a getting-started video for the member" + label: Ecosystem-building and technical outreach contributions + description: Required. Technical articles, videos, blogs, tutorials — and indirect ecosystem growth through real projects built on the plugin. Preferably public, and linked. + placeholder: "a manifest-merger walkthrough on a blog; a getting-started video for the plugin" validations: required: true - type: textarea @@ -53,5 +55,5 @@ body: - type: textarea id: referrer attributes: - label: Referrer - description: An existing maintainer of a related member who supports this application, if one knows your work. + label: Referrer (optional) + description: An existing maintainer of a related plugin who supports this application, if one knows your work. diff --git a/.github/ISSUE_TEMPLATE/new-plugin.yml b/.github/ISSUE_TEMPLATE/new-plugin.yml new file mode 100644 index 0000000..c0c20ce --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new-plugin.yml @@ -0,0 +1,56 @@ +name: New plugin +description: Propose a new plugin — an RFC for one not yet built, or one already built joining the official repository +labels: ["new-plugin"] +body: + - type: markdown + attributes: + value: | + A plugin is a mechanism: one kind of input turned into actions with + declared inputs and outputs, or a prefix or SDK mapped into the build + ([docs/01](../../docs/01-plugin-development.md)). The path this issue + takes depends on the stage below. + + The original author of a plugin accepted into this repository becomes + the plugin's maintainer + ([what a maintainer does](../../docs/03-maintainers.md)). + - type: dropdown + id: stage + attributes: + label: This plugin is + options: + - Not yet implemented — an RFC to discuss first + - Already implemented — applying to join the official repository + validations: + required: true + - type: input + id: name + attributes: + label: The plugin's name + description: A third-party plugin names its modules `mcpp..*` — state the namespace and the module family. + placeholder: "mcpp.acme.protobuf" + validations: + required: true + - type: textarea + id: mechanism + attributes: + label: Mechanism, tools and floor + description: What one kind of input it turns into what; the tools it drives; the engine floor it needs ([docs/02](../../docs/02-tool-sources.md) states how a plugin resolves a tool). + validations: + required: true + - type: textarea + id: rfc + attributes: + label: For an RFC — the design questions + description: The options, the actions it submits, what the engine already gives it, what you are unsure about. + - type: textarea + id: submission + attributes: + label: For a submission — where it lives today + description: Repository, documentation, a consumer fixture under tests/ that CI can build, and the platforms it claims. + - type: textarea + id: maintenance + attributes: + label: Who maintains it + description: The author, and both sides of the role they commit to — technical upkeep, and popularization and outreach (articles, videos, tutorials, use in real projects). + validations: + required: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c378214..62f7475 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,11 +13,11 @@ on: env: # The mcpp release the consumers build with. Raising it is what admits a - # member that relies on a newer engine; the README states each member's floor. + # plugin that relies on a newer engine; the README states each plugin's floor. # 2026.9.11.1 is what `dist-*` needs at the API level: # `mcpp::provides_pack_format`, `mcpp::pack_format`, `${mcpp.stage_dir}` and # `mcpp::package_version` all arrived in it. Raising this is what admits a - # member relying on a newer engine; the README states each member's floor, + # plugin relying on a newer engine; the README states each plugin's floor, # and the index descriptor's own `min_mcpp` is a different question -- it # bounds the DESCRIPTOR's syntax, and raising it would brick every older # client's whole index. @@ -46,7 +46,7 @@ env: # `dist-apk` refuses its tree naming this release. # # 2026.9.26.2 IS THE RELEASE THAT LANDS mcpp-community/mcpp#702, which the - # `deps-*` members and `rules-qt` (0.13.0) are written against (mcpp's + # `deps-*` plugins and `rules-qt` (0.13.0) are written against (mcpp's # SPEC-007): `mcpp::runtime_search_dir` for a prefix's shared-library # directory, the `prepare` role with `output_dir` for an installation, a # stamp moved past the inputs that changed, and on Windows the imported DLLs @@ -88,7 +88,7 @@ env: # completes a cross subproject's contract (its compilers, archiver and target) # when the action runs, which a subproject that links an executable or a # shared library needs. The package floor stays 2026.10.30.1: every other - # member, and a cross subproject that only builds archives, works on the + # plugin, and a cross subproject that only builds archives, works on the # older engine, and docs/40-deps.md states the requirement where cross builds # are described. So here, as for 0.20.0's SYCL lane, `MCPP_VERSION` is the # newest engine a lane needs and the floor the oldest the collection loads on. @@ -1212,10 +1212,10 @@ jobs: - name: dist-appimage produces an AppImage, and it runs working-directory: tests/appimage-consumer run: | - # A PLAIN BUILD HAS NO DISTRIBUTION EDGE. The member declares the + # A PLAIN BUILD HAS NO DISTRIBUTION EDGE. The plugin declares the # format unconditionally and submits only when asked, so this build # must produce no AppImage at all -- the half of the contract a - # member author is most likely to get wrong, and the half that still + # plugin author is most likely to get wrong, and the half that still # works for whoever wrote it. "$MCPP" build if find target -name '*.AppImage' | grep -q .; then @@ -1366,7 +1366,7 @@ jobs: # `2026-09-13-four-upstream-asks-from-a-ui-framework.md`, §4), which # `dist-web`'s two copy steps now use in place of `cp`. `mcpp toolchain # install` first, because this job's `~/.mcpp` cache does not carry - # the emsdk payload the way the local sandbox this member was + # the emsdk payload the way the local sandbox this plugin was # developed against does. - name: Install the emsdk payload for dist-web run: '"$MCPP" toolchain install emsdk 6.0.9' @@ -1463,7 +1463,7 @@ jobs: # THE CLOSURE THE ENGINE STAGED (mcpp#634, B5). A dependency linked as a # shared object on the Android row reaches `lib//` beside the app's # own because the engine stages the closure and names it in the stage - # manifest (2026.9.14.2+), and the member reads that tree. Five criteria: + # manifest (2026.9.14.2+), and the plugin reads that tree. Five criteria: # two packs in a row carry the dependency's library both times; two # triples give one signed APK listing both ABIs; `--format aab` gives an # App Bundle bundletool validates and jarsigner verifies, and a universal @@ -1585,7 +1585,7 @@ jobs: run: | set -e # THE FIXTURE'S OWN DENOMINATOR. It asserts "every rule compiles - # here", and "every" is a list it carries -- so a seventh member + # here", and "every" is a list it carries -- so a seventh plugin # added to this package would be covered by a step whose name says it # already is. The list is therefore compared against the package's # own `[features]` before the build, and the two must be equal. @@ -1596,49 +1596,49 @@ jobs: # ` = { ... }`. Reading keys out of the table BODY matched # `sources` once per feature and reported the fixture as # incomplete while the extractor was what broke. - # MEMBERS, NOT EVERY FEATURE. A member is a feature named for its + # MEMBERS, NOT EVERY FEATURE. A plugin is a feature named for its # family -- `rules-*`, `tools-*`, `dist-*`, the README's naming table # -- and a consumer names it. `plugins-core` is not one: it carries the - # build-program half of the generated surface, every member implies + # build-program half of the generated surface, every plugin implies # it, and a consumer never writes it. Keeping it out keeps this check - # meaning "the fixture names every member a consumer can activate"; + # meaning "the fixture names every plugin a consumer can activate"; # padding the fixture instead would make it mean less. # # BY NAME, NOT BY "NOTHING IMPLIES IT". That was the rule until 0.11.0, # when `dist-apk-kotlin` and `dist-apk-maven` came to imply `dist-apk`, # which a consumer still names. The rule is read out of the manifest, - # not listed here, so a new member is still caught. + # not listed here, so a new plugin is still caught. # A TEMP FILE, NOT `<(...)`. This step also runs on windows-2022 # through Git Bash, where process substitution is emulated and not # dependable -- and a check that behaves differently on one of the # three hosts is the exact class of difference this job exists to # catch, so it must not introduce one. # THE MEMBERS THAT CARRY SOURCES, READ OUT OF THE MANIFEST. From 0.13.0 a - # member family may hold features that add a payload and no source + # plugin family may hold features that add a payload and no source # (`dist-apk-kotlin`): they compile nothing this fixture # could miss, and naming them here would download an SDK on every host. - # So the requirement is one-sided -- every source-carrying member of the + # So the requirement is one-sided -- every source-carrying plugin of the # four families is named -- and the other side only checks spelling: # every name the fixture uses is a feature the package declares. awk '/^\[features\.[a-z0-9-]+\]/ { cur = $0; sub(/^\[features\./, "", cur); sub(/\]$/, "", cur); next } /^\[/ { cur = "" } /^sources[ \t]*=/ && cur ~ /^(rules|tools|dist|deps)-/ { print cur }' mcpp.toml \ - | sort -u > /tmp/members.txt + | sort -u > /tmp/plugins.txt grep -oE '^\[features\.[a-z0-9-]+\]' mcpp.toml \ | sed 's/^\[features\.//; s/\]$//' | sort > /tmp/declared.txt - feats=$(cat /tmp/members.txt) + feats=$(cat /tmp/plugins.txt) used=$(sed -n '/features = \[/,/\], host-module/p' tests/all-rules-compile/mcpp.toml \ | grep -oE '"[a-z-]+"' | tr -d '"' | sort) [ -n "$feats" ] || { - echo "FAIL: read no source-carrying members out of mcpp.toml. The" + echo "FAIL: read no source-carrying plugins out of mcpp.toml. The" echo " extractor above expects [features.] sections with a" echo " sources key and found none, so the manifest spelling changed." grep -n '^\[features' mcpp.toml | head exit 1; } for f in $feats; do echo "$used" | grep -qx "$f" || { - echo "FAIL: the fixture does not name the member $f" - echo " members: $(echo $feats)" + echo "FAIL: the fixture does not name the plugin $f" + echo " plugins: $(echo $feats)" echo " fixture: $(echo $used)" exit 1; } done @@ -1798,12 +1798,12 @@ jobs: # ── the general library and the test kit (0.17.0, mcpp#734) ─────────── # - # The deps members' decisions -- which mechanism reaches the foreign + # The deps plugins' decisions -- which mechanism reaches the foreign # system, which triplet, which C runtime -- tested against stated build # contexts (a Visual Studio row, a managed MSVC row, the Linux GCC and # libc++ rows) with nothing installed. The verdicts are counted against # the cases the fixture declares. - - name: the deps members' decisions hold against stated build contexts (mcpp.plugins.testing) + - name: the deps plugins' decisions hold against stated build contexts (mcpp.plugins.testing) run: bash .github/scripts/check-deps-and-qt.sh plugin-logic # A compatibility unit keeps a behaviour for six months after the release @@ -1816,7 +1816,7 @@ jobs: # # vcpkg keeps everything it reuses in one per-user directory -- its # binary cache (`archives/`), its registry cache (`registries/`) and, - # through the member's `--downloads-root`, its downloads -- so caching that directory is what + # through the plugin's `--downloads-root`, its downloads -- so caching that directory is what # makes the second run of a manifest a restore rather than a compile. - name: Cache vcpkg's per-user directory uses: actions/cache@v4 @@ -1838,7 +1838,7 @@ jobs: - name: deps-archive extracts a zip the project keeps and deploys its tree beside the program run: bash .github/scripts/check-deps-and-qt.sh archive-consumer - - name: deps-vcpkg in two workspace members that share no dependency + - name: deps-vcpkg in two workspace plugins that share no dependency run: bash .github/scripts/check-deps-and-qt.sh vcpkg-workspace - name: deps-cmake builds a CMake subproject as an action and links it @@ -2027,7 +2027,7 @@ jobs: # ── THE SAME RULE ON THE OTHER TWO PLATFORMS ──────────────────────────────── # - # `rules-spirv` is the only member whose payload this ecosystem publishes for + # `rules-spirv` is the only plugin whose payload this ecosystem publishes for # all three, so it is the only one that can be checked on all three. What this # job proves is the claim the per-platform declaration makes: a project writes # the rule edge and nothing else, and the compiler that arrives is whichever @@ -2168,13 +2168,13 @@ jobs: # and asks only whether all six modules COMPILE for this host -- which # is the half of a rule that a Linux-only CI never sees. Run after the # end-to-end step, its failure arrived as somebody else's build error: - # `no member named 'popen' in the global namespace`, reported against a + # `no plugin named 'popen' in the global namespace`, reported against a # consumer that had nothing to do with it. - name: every rule module compiles for this host run: | set -e # THE FIXTURE'S OWN DENOMINATOR. It asserts "every rule compiles - # here", and "every" is a list it carries -- so a seventh member + # here", and "every" is a list it carries -- so a seventh plugin # added to this package would be covered by a step whose name says it # already is. The list is therefore compared against the package's # own `[features]` before the build, and the two must be equal. @@ -2187,41 +2187,41 @@ jobs: # incomplete while the extractor was what broke. # MEMBERS, NOT EVERY FEATURE: a feature named for its family # (`rules-*`, `tools-*`, `dist-*`), which a consumer names; `plugins-core`, - # which every member implies and no consumer writes, is not one. By + # which every plugin implies and no consumer writes, is not one. By # name and not by "nothing implies it" since 0.11.0, when # `dist-apk-kotlin` and `dist-apk-maven` came to imply `dist-apk`. The - # rule is read out of the manifest, so a new member is still caught. + # rule is read out of the manifest, so a new plugin is still caught. # # A temp file, not `<(...)`: this step also runs on windows-2022 # through Git Bash, where process substitution is emulated and not # dependable -- and a check that behaves differently on one of the # three hosts is the class of difference this job exists to catch. # THE MEMBERS THAT CARRY SOURCES, READ OUT OF THE MANIFEST. From 0.13.0 a - # member family may hold features that add a payload and no source + # plugin family may hold features that add a payload and no source # (`dist-apk-kotlin`): they compile nothing this fixture # could miss, and naming them here would download an SDK on every host. - # So the requirement is one-sided -- every source-carrying member of the + # So the requirement is one-sided -- every source-carrying plugin of the # four families is named -- and the other side only checks spelling: # every name the fixture uses is a feature the package declares. awk '/^\[features\.[a-z0-9-]+\]/ { cur = $0; sub(/^\[features\./, "", cur); sub(/\]$/, "", cur); next } /^\[/ { cur = "" } /^sources[ \t]*=/ && cur ~ /^(rules|tools|dist|deps)-/ { print cur }' mcpp.toml \ - | sort -u > /tmp/members.txt + | sort -u > /tmp/plugins.txt grep -oE '^\[features\.[a-z0-9-]+\]' mcpp.toml \ | sed 's/^\[features\.//; s/\]$//' | sort > /tmp/declared.txt - feats=$(cat /tmp/members.txt) + feats=$(cat /tmp/plugins.txt) used=$(sed -n '/features = \[/,/\], host-module/p' tests/all-rules-compile/mcpp.toml \ | grep -oE '"[a-z-]+"' | tr -d '"' | sort) [ -n "$feats" ] || { - echo "FAIL: read no source-carrying members out of mcpp.toml. The" + echo "FAIL: read no source-carrying plugins out of mcpp.toml. The" echo " extractor above expects [features.] sections with a" echo " sources key and found none, so the manifest spelling changed." grep -n '^\[features' mcpp.toml | head exit 1; } for f in $feats; do echo "$used" | grep -qx "$f" || { - echo "FAIL: the fixture does not name the member $f" - echo " members: $(echo $feats)" + echo "FAIL: the fixture does not name the plugin $f" + echo " plugins: $(echo $feats)" echo " fixture: $(echo $used)" exit 1; } done @@ -2279,13 +2279,13 @@ jobs: fi echo "ok: the boundary is generated and namespaced on this host" - # ── dist, on the platform each member serves ──────────────────────── + # ── dist, on the platform each plugin serves ──────────────────────── # # A PLAN-LEVEL ASSERTION IS NOT A MEASUREMENT. `plan_for()` returning # `applies == false` on the wrong OS says the gate works; it says nothing - # about whether the tool accepts what the member renders. These two steps + # about whether the tool accepts what the plugin renders. These two steps # exist because that question is only answerable here, and because the - # members were written on a Linux host where neither tool can run. + # plugins were written on a Linux host where neither tool can run. # # THE FIRST THING EITHER ONE SETTLES IS A SPELLING. `dist-wix` writes # `$(Executable)` in its generated `.wxs`, taken from a working @@ -2301,9 +2301,9 @@ jobs: # THE TOOL COMES FROM THE PAYLOAD, NOT FROM THIS STEP. `dist-wix` # declares `xim:wix` under `[target.windows.feature-xlings.dist-wix]`, # so mcpp provisions it when the fixture activates the feature on a - # Windows target, and the member locates it through `xpkg_dir`. An + # Windows target, and the plugin locates it through `xpkg_dir`. An # earlier revision of this step installed WiX 6 with `dotnet tool` - # and the member searched PATH; the criterion below on the argv is + # and the plugin searched PATH; the criterion below on the argv is # what distinguishes the two, and a run that found a host `wix.exe` # would fail it. WiX 7 is not an option for the payload either: it # refuses to run until an OSMF licence is accepted out of band @@ -2319,7 +2319,7 @@ jobs: msi=$(find target -name '*.msi' | head -1) test -n "$msi" || { cat pack.log; echo "FAIL: no MSI"; exit 1; } # THE TOOL CAME FROM THE PAYLOAD BY CONSTRUCTION, and the criterion - # is the absence of any other: this step installs no WiX, the member + # is the absence of any other: this step installs no WiX, the plugin # has no PATH tier, and the runner image ships WiX 3 (candle/light) # but no `wix.exe`. An MSI therefore exists only if the payload's # `wix.exe` produced it. The engine prints the argv with the tool's @@ -2331,7 +2331,7 @@ jobs: fi # THE CRITERION IS THE `File` TABLE, NOT THE FILE'S EXISTENCE. The - # measured failure this member is shaped around is a VALID, EMPTY, + # measured failure this plugin is shaped around is a VALID, EMPTY, # 52 KB installer with no diagnostic, produced when a harvested bind # path resolved to nothing. An assertion that stops at "an .msi # exists" passes on exactly that artifact. @@ -2372,7 +2372,7 @@ jobs: # THE STAGED TREE IS INSTALLED, NOT ONLY THE PROGRAM (0.10.1). The # fixture deploys `share/greeting.txt` to `data/`; the engine stages - # it at `bin/data/greeting.txt` and the member names it in the + # it at `bin/data/greeting.txt` and the plugin names it in the # `StagedFiles` group, so the administrative image carries it at the # same path beside the program, byte-for-byte. data="$(dirname "$inside")/data/greeting.txt" @@ -2413,7 +2413,7 @@ jobs: test -n "$exe" || { echo "FAIL: Info.plist names no executable"; exit 1; } # `CFBundleExecutable` must be a BARE NAME, never a path: Apple's # loader resolves it against Contents/MacOS/ and a path there is not - # a launchable bundle. This is the assumption the member documents. + # a launchable bundle. This is the assumption the plugin documents. case "$exe" in */*) echo "FAIL: CFBundleExecutable is a path: $exe"; exit 1 ;; esac test -x "$app/Contents/MacOS/$exe" \ || { echo "FAIL: $app/Contents/MacOS/$exe is missing or not executable" @@ -2424,13 +2424,13 @@ jobs: "$app/Contents/MacOS/$exe" | tee run.log grep -q '^app-consumer ok' run.log \ || { echo "FAIL: the bundled program did not run"; exit 1; } - # `plutil -lint` is Apple's own parser: a plist this member wrote by + # `plutil -lint` is Apple's own parser: a plist this plugin wrote by # hand and got subtly wrong would otherwise fail at launch time on a # user's machine and nowhere here. plutil -lint "$app/Contents/Info.plist" # THE DEPLOYED FILE, AT THE RESOURCE DESTINATION AND NOT BESIDE THE # PROGRAM (mcpp#630, item 3a): the engine stages `bin/data/...` and - # this member places it under `Contents/Resources/`. + # this plugin places it under `Contents/Resources/`. test -f "$app/Contents/Resources/data/greeting.txt" \ || { echo "FAIL: the deployed file is not under Contents/Resources"; find "$app" -type f; exit 1; } if [ -e "$app/Contents/MacOS/bin" ]; then @@ -2440,10 +2440,10 @@ jobs: echo "ok: one bundle, a valid plist, it launches, and the resource is where NSBundle looks" # 0.11.0 (`options::info_plist`): a project's Info.plist entries join the - # generated plist of the real bundle, a key the member only defaults + # generated plist of the real bundle, a key the plugin only defaults # (`NSHighResolutionCapable`) takes the project's value, Apple's parser # accepts the result, and the bundle still launches. The refusal of a key - # the member derives is asserted at the plan level, in the Linux job. + # the plugin derives is asserted at the plan level, in the Linux job. - name: dist-apple carries a project's Info.plist entries, and the bundle launches if: ${{ !cancelled() && runner.os == 'macOS' }} working-directory: tests/app-consumer @@ -2465,7 +2465,7 @@ jobs: [ "$(grep -c 'NSHighResolutionCapable' "$plist")" -eq 1 ] \ || { echo "FAIL: NSHighResolutionCapable is stated twice"; cat "$plist"; exit 1; } [ "$(pb CFBundleExecutable)" = "app-consumer" ] \ - || { echo "FAIL: CFBundleExecutable is no longer the member's"; cat "$plist"; exit 1; } + || { echo "FAIL: CFBundleExecutable is no longer the plugin's"; cat "$plist"; exit 1; } "$app/Contents/MacOS/app-consumer" | grep -q '^app-consumer ok' \ || { echo "FAIL: the bundle does not launch with the project's entries"; exit 1; } echo "ok: the project's entries are in the bundle's Info.plist, plutil accepts it, and the bundle launches" @@ -2604,7 +2604,7 @@ jobs: # 0.11.0 (`options::info_plist`) on the iOS row: the project's entries # join the simulator bundle's Info.plist, its `UIDeviceFamily` replaces - # the member's default, and the simulator installs and runs the bundle. + # the plugin's default, and the simulator installs and runs the bundle. - name: dist-apple's iOS row carries a project's Info.plist entries, and the simulator runs the bundle if: ${{ !cancelled() && runner.os == 'macOS' }} working-directory: tests/ios-app-consumer @@ -2628,14 +2628,14 @@ jobs: [ "$(pb UIDeviceFamily:0)" = "1" ] && ! pb UIDeviceFamily:1 >/dev/null 2>&1 \ || { echo "FAIL: UIDeviceFamily is not the project's (1)"; cat "$plist"; exit 1; } [ "$(pb CFBundleSupportedPlatforms:0)" = "iPhoneSimulator" ] \ - || { echo "FAIL: CFBundleSupportedPlatforms is no longer the member's"; cat "$plist"; exit 1; } + || { echo "FAIL: CFBundleSupportedPlatforms is no longer the plugin's"; cat "$plist"; exit 1; } out=$("$MCPP" run --target aarch64-ios-sim --format app 2>&1) && rc=0 || rc=$? printf '%s\n' "$out" | tail -20 [ "$rc" -eq 7 ] \ || { echo "FAIL: mcpp run exited $rc with the project's entries, and the program exits 7"; exit 1; } echo "ok: the simulator bundle carries the project's entries, and the simulator ran it and returned 7" - # dist-apk ON A HOST THAT IS NOT LINUX (0.24.0). Every tool the member + # dist-apk ON A HOST THAT IS NOT LINUX (0.24.0). Every tool the plugin # runs is a native program (`aapt2`, `zipalign`) or a jar on the JDK's # `java`, and each step of more than one command is a step program # (0.25.0, `tools-steps`), so no step needs a shell and a Windows host @@ -2716,7 +2716,7 @@ jobs: working-directory: tests/progress-worker run: python3 verify.py "$MCPP" - - name: the deps members' decisions hold against stated build contexts (mcpp.plugins.testing) + - name: the deps plugins' decisions hold against stated build contexts (mcpp.plugins.testing) run: bash .github/scripts/check-deps-and-qt.sh plugin-logic # ── deps-vcpkg, deps-cmake and rules-qt (0.13.0) ────────────────────── @@ -2739,7 +2739,7 @@ jobs: - name: deps-archive extracts a zip the project keeps and deploys its tree beside the program run: bash .github/scripts/check-deps-and-qt.sh archive-consumer - - name: deps-vcpkg in two workspace members that share no dependency + - name: deps-vcpkg in two workspace plugins that share no dependency run: bash .github/scripts/check-deps-and-qt.sh vcpkg-workspace - name: deps-cmake builds a CMake subproject as an action and links it diff --git a/AGENTS.md b/AGENTS.md index 8b83a5c..46ca833 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md `mcpp-plugins` is the package of official build plugins for mcpp -(`mcpp:plugins`). One member is one module — a single `.cppm`, or a directory +(`mcpp:plugins`). One plugin is one module — a single `.cppm`, or a directory `//` whose `.cppm` keeps the module a consumer imports while `internal/` holds the machinery — one feature in `mcpp.toml`, one consumer under `tests/`, one page under `docs/`. This file states the rules that hold @@ -13,14 +13,14 @@ the linked document holds. | Tree | States | |---|---| -| [`docs/`](docs/README.md) | one page per member or family, and the plugin conventions ([01](docs/01-plugin-development.md)) | +| [`docs/`](docs/README.md) | one page per plugin or family, and the plugin conventions ([01](docs/01-plugin-development.md)) | | [`README.zh-CN.md`](README.zh-CN.md) | the README in Chinese; English is the source of truth, and a lagging section is stated in its header | -| [`mcpp.toml`](mcpp.toml) | the package: one feature per member, the declared payloads, the engine floor `[package] mcpp` | -| [`tests//`](tests/) | one consumer project per member; CI builds each and asserts on its output | +| [`mcpp.toml`](mcpp.toml) | the package: one feature per plugin, the declared payloads, the engine floor `[package] mcpp` | +| [`tests//`](tests/) | one consumer project per plugin; CI builds each and asserts on its output | | [`tools/README.md`](tools/README.md) | the tools family's own account | | [`.agents/docs/`](.agents/docs/) | design records: the reasoning, the measurements, what was refuted | -A change of behaviour updates the member's page and its consumer in the same +A change of behaviour updates the plugin's page and its consumer in the same pull request. ## 2. Architecture @@ -33,18 +33,18 @@ pull request. does itself; `dist-*` what comes out of the link, and in what form a user installs it; `deps-*` where a library comes from. The prefix is load-bearing ([00](docs/00-engine-and-rules.md)). -- **Names are three segments.** `mcpp..`; the second segments +- **Names are three segments.** `mcpp..`; the second segments `core`, `plugins`, `deps`, `rules`, `dist`, `tools` belong to the namespace, and a third-party plugin names its modules `mcpp..*` ([01 §3](docs/01-plugin-development.md#3-layers-names-and-the-engine-floor)). - **Three layers, one way down.** The engine's `mcpp` (L1), the general library - `mcpp.plugins.*` (L2, feature `plugins-core`; every member implies it), the - members (L3). A layer imports only lower layers. -- **Every member states an engine floor.** The collection's floor is + `mcpp.plugins.*` (L2, feature `plugins-core`; every plugin implies it), the + plugins (L3). A layer imports only lower layers. +- **Every plugin states an engine floor.** The collection's floor is `[package] mcpp`; the index descriptor states the highest floor among the - members, so a project on an older engine is refused at resolution. -- **A tool resolves in one order, for every member:** the build program's - choice, the member's legacy variable, the engine's override, the declared + plugins, so a project on an older engine is refused at resolution. +- **A tool resolves in one order, for every plugin:** the build program's + choice, the plugin's legacy variable, the engine's override, the declared payload. A choice never asks for the payload — a build program that names its own tool must not trigger a download ([02](docs/02-tool-sources.md)). @@ -55,7 +55,7 @@ pull request. includes a header or branches on the platform in the preprocessor. - The code compiles under the four lanes CI runs: GCC with libstdc++, clang with libc++, clang with libstdc++'s `std` module (an editor's clangd), and - MSVC where a member claims Windows. No compiler's leniency is relied on; the + MSVC where a plugin claims Windows. No compiler's leniency is relied on; the known differences and their workarounds are stated in [01 §4](docs/01-plugin-development.md#4-the-c-a-plugin-is-written-in). - A behaviour kept past the release that replaced it lives in `compat/`, one @@ -68,8 +68,8 @@ pull request. pinned mcpp on the GCC lane (`consumers`), and adds `toolchain-llvm`, `toolchain-editor`, `rules-cross-platform` and `deps-managed-msvc`. - Every documented behaviour has a criterion: a CI check, on every platform the - member claims ([01 §2](docs/01-plugin-development.md#2-rules), rule 9). -- A change to a member builds its fixture, not only the package. + plugin claims ([01 §2](docs/01-plugin-development.md#2-rules), rule 9). +- A change to a plugin builds its fixture, not only the package. ## 5. Change workflow @@ -80,7 +80,7 @@ pull request. - Review follows [`.github/CODEOWNERS`](.github/CODEOWNERS): the family rows route it; a change to the feature set or the engine floor in `mcpp.toml` needs the package owner. -- Adding a member is the checklist in +- Adding a plugin is the checklist in [01 §5](docs/01-plugin-development.md#5-a-new-plugin): a module file, a feature, a consumer, a table row with its floor, a page, a version bump. - A release changes the version in `mcpp.toml` and tags `v`; the tag diff --git a/README.md b/README.md index 3f2f723..0d0563f 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,17 @@ # mcpp-plugins -> The official build plugins for mcpp — one member, one feature, one module. +> The official build plugins for mcpp — one plugin, one feature, one module. [![ci](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/mcpp-community/mcpp-plugins/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) -**English** | [简体中文](README.zh-CN.md) · [Documentation](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [Package index](https://mcpplibs.github.io/mcpp-index/) · [Releases](https://github.com/mcpp-community/mcpp-plugins/releases) +**English** | [简体中文](README.zh-CN.md) · [Documentation](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [mcpp.plugins in the index](https://mcpp.index.xlings.org/packages/mcpp.plugins) · [Releases](https://github.com/mcpp-community/mcpp-plugins/releases) mcpp is a general engine with a framework for build plugins; plugins come from this package (`mcpp:plugins`), from third parties, or from the project itself, -and `build.mcpp` is where a project uses them: it imports the member's module -under the name the member declares, configures it, and calls it. The edge is a +and `build.mcpp` is where a project uses them: it imports the plugin's module +under the name the plugin declares, configures it, and calls it. The edge is a `[build-dependencies]` entry — the library serves the build program, and the package never reaches the target. @@ -43,12 +43,12 @@ int main() { | tools | `mcpp.tools.` | what the build program does itself (see [`tools/README.md`](tools/README.md)) | | dist | `mcpp.dist.` | what comes out of the link, and in what form a user installs it | | deps | `mcpp.deps.` | where a library comes from | -| identity | `mcpp.plugins` | the lib root, compiled before every member; it states the collection's version | +| identity | `mcpp.plugins` | the lib root, compiled before every plugin; it states the collection's version | A third-party plugin names its modules `mcpp..*`; `core`, `plugins`, `deps`, `rules`, `dist`, `tools` belong to this package and the engine. The full account of the families, and of how the engine routes a file -to a rule, is in [docs/00](docs/00-engine-and-rules.md); where a tool a member +to a rule, is in [docs/00](docs/00-engine-and-rules.md); where a tool a plugin runs comes from is in [docs/02](docs/02-tool-sources.md). ## Plugins @@ -63,7 +63,7 @@ runs comes from is in [docs/02](docs/02-tool-sources.md). | `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) |
-All 23 members — feature, behaviour, doc; the modules and engine floors are in the documentation index +All 23 plugins — feature, behaviour, doc; the modules and engine floors are in the documentation index | feature | what it does | doc | |---|---|---| @@ -99,15 +99,15 @@ The project is maintained mainly by [@Sunrisepeak](https://github.com/Sunrisepeak) — its upkeep and growth need more contributors and maintainers. Start from the simple and from what interests you: use it, introduce and teach it, report issues, fix bugs, -improve it, maintain one or more members. +improve it, maintain one or more plugins. -If you are interested in contributing to and maintaining some members: +If you are interested in contributing to and maintaining some plugins: -- [add a new member](docs/01-plugin-development.md#5-a-new-plugin) -- [become a member's maintainer](docs/03-maintainers.md) +- [propose or submit a new plugin](https://github.com/mcpp-community/mcpp-plugins/issues/new?template=new-plugin.yml) — [the checklist a plugin follows](docs/01-plugin-development.md#5-a-new-plugin) +- [apply to maintain one](https://github.com/mcpp-community/mcpp-plugins/issues/new?template=maintainer-application.yml) — [what a maintainer does](docs/03-maintainers.md) ## Maintainers -| maintainer | members primarily maintained | +| maintainer | plugins primarily maintained | |---|---| -| [@Sunrisepeak](https://github.com/Sunrisepeak) | the repository, and today every member | +| [@Sunrisepeak](https://github.com/Sunrisepeak) | primary maintainer of the project | diff --git a/README.zh-CN.md b/README.zh-CN.md index 2f0e23a..88d0bc2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,7 +6,7 @@ [![Release](https://img.shields.io/github/v/release/mcpp-community/mcpp-plugins)](https://github.com/mcpp-community/mcpp-plugins/releases) [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE) -[English](README.md) | 简体中文 · [文档索引](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [包索引 mcpp-index](https://mcpplibs.github.io/mcpp-index/) · [发布](https://github.com/mcpp-community/mcpp-plugins/releases) +[English](README.md) | 简体中文 · [文档索引](docs/README.md) · [mcpp](https://github.com/mcpp-community/mcpp) · [mcpp.plugins 索引页](https://mcpp.index.xlings.org/packages/mcpp.plugins) · [发布](https://github.com/mcpp-community/mcpp-plugins/releases) mcpp 是一个带有构建插件框架的通用引擎;插件来自本包(`mcpp:plugins`)、来自 第三方,或来自项目自身,而 `build.mcpp` 是项目使用它们的地方:它按成员声明 @@ -60,7 +60,7 @@ int main() { | `dist-apk` | 把原生闭包打成已签名的 APK 或 App Bundle,带 Java、Kotlin 与 Maven 库。 | [docs](docs/32-dist-apk.md) |
-全部 23 个插件成员——feature、行为、文档;模块与引擎下限见文档索引 +全部 23 个插件成员——feature、行为、文档;模块与引擎下限见文档索引 | feature | 行为 | 文档 | |---|---|---| @@ -98,11 +98,11 @@ int main() { 如果你对某些插件感兴趣,并期望参与贡献和维护: -- [添加一个新的插件](docs/01-plugin-development.md#5-a-new-plugin) -- [申请成为维护者](docs/03-maintainers.md) +- [提出或提交一个新插件](https://github.com/mcpp-community/mcpp-plugins/issues/new?template=new-plugin.yml)——[新插件成员清单](docs/01-plugin-development.md#5-a-new-plugin) +- [申请维护一个插件成员](https://github.com/mcpp-community/mcpp-plugins/issues/new?template=maintainer-application.yml)——[维护者做什么](docs/03-maintainers.md) ## 维护者 | 维护者 | 主要负责的插件成员 | |---|---| -| [Sunrisepeak](https://github.com/Sunrisepeak) | 仓库整体,以及今天的每一个插件成员 | +| [Sunrisepeak](https://github.com/Sunrisepeak) | 项目主要负责人 | diff --git a/docs/00-engine-and-rules.md b/docs/00-engine-and-rules.md index ec225b5..e2619c6 100644 --- a/docs/00-engine-and-rules.md +++ b/docs/00-engine-and-rules.md @@ -1,11 +1,11 @@ -# How the members meet the engine +# How the plugins meet the engine -How a rule reaches the engine: each rule declares its own environment and the file extensions it claims, a consumer names a member through features and the declarations a payload generates, and the engine compiles each member as a host module. The section on what a rule may drive states the one constraint every member shares: it drives only a compiler the ecosystem resolved. +How a rule reaches the engine: each rule declares its own environment and the file extensions it claims, a consumer names a plugin through features and the declarations a payload generates, and the engine compiles each plugin as a host module. The section on what a rule may drive states the one constraint every plugin shares: it drives only a compiler the ecosystem resolved. ## Naming, in full The four families answer four different questions, and the prefix is which -one a member answers: +one a plugin answers: ``` rules-* how is this translation unit compiled @@ -14,19 +14,19 @@ dist-* what comes out of the link, and in what form a user installs it deps-* where does a library come from ``` -A `dist-*` member fits neither of the first two definitions: it does not +A `dist-*` plugin fits neither of the first two definitions: it does not compile a translation unit and it does not do its work while the build program runs. It consumes **link outputs** through a `role = "artifact"` action, reached with `mcpp pack --format ` (mcpp 2026.9.11.1+). The prefix matters because the taxonomy is load-bearing -- a consumer reading `rules-wix` would expect a compiler it does not drive and a translation unit, and there is neither. -A `deps-*` member compiles none of the project's translation units and does not +A `deps-*` plugin compiles none of the project's translation units and does not do its work while the build program runs: the installation is a `prepare` action (mcpp's SPEC-007, docs/specs/build-plugins.md), which fills a declared output directory and which the package's compile and link edges wait for, and whose command is the installer itself -- `vcpkg`, or `cmake -P` over a script -the member writes -- so the package builds no program for it. The build +the plugin writes -- so the package builds no program for it. The build program refers to the prefix by name -- include directory, libraries by full path, runtime search directory -- and never by what is in it, so a plan made before the installation is the plan made after it. @@ -110,11 +110,11 @@ A device source that NO rule claims is not silently dropped: mcpp refuses a device source that reached no action, naming the file. That is the engine's half of this rule and it needs 2026.9.6.5. -The floor is the mcpp release whose engine carries what the member relies on. +The floor is the mcpp release whose engine carries what the plugin relies on. From 0.4.0 every rule shares one: **2026.9.8.1**, the release in which a package's host modules are ordered by their IMPORT GRAPH rather than by their -paths. This package needs that: `src/declare.cppm` is imported by every member, -and `rules/` sorts before `src/`, so before that release the members were +paths. This package needs that: `src/declare.cppm` is imported by every plugin, +and `rules/` sorts before `src/`, so before that release the plugins were compiled first and failed with "failed to read compiled module". **The floor could have been avoided, and was not.** `src/declare.cppm` sorts @@ -133,9 +133,9 @@ change to what this package generates, not to what it asks the engine for. under MSVC 14.52 (36629 and 36725, measured on xrgui's CI) a module that has instantiated `std::filesystem::path`'s iterator poisons every importer that touches `path` again -- `filesystem(1572): error C2801: '_Path_iterator<...>::operator ==' -must be a non-static member`. Nothing in this package instantiates that +must be a non-static plugin`. Nothing in this package instantiates that iterator now: the lib root reads paths apart as strings -(`mcpp::plugins::names::components`), and the members' relative-path +(`mcpp::plugins::names::components`), and the plugins' relative-path arithmetic is `mcpp::plugins::names::relative_to`. The previous shared floor was 2026.9.7.1, the release that reads @@ -150,20 +150,20 @@ The previous shared floor was 2026.9.6.6, the release in which a payload a DEPENDENCY declared is both installed and answerable. Before it a rule could declare `>=8.5.0`, have it installed, and still be told by `xpkg_dir` that nothing was there -- which is why each rule's list used to be repeated in every -project that used it. The earlier per-member floors are still the floors of the +project that used it. The earlier per-plugin floors are still the floors of the rules themselves (`rules-spirv` needs the shader extensions in the device-source table, 2026.9.5.3; `tools-embed` needs the fast path to compare a declared file input, 2026.9.5.4; `rules-sycl` needs `.sycl` in that table, 2026.9.6.1), and they are all below the shared one. -`rules-slang` is the member that does NOT appear in that list, and its absence +`rules-slang` is the plugin that does NOT appear in that list, and its absence is the point: `.slang` is in no engine table at any version. The feature declares the extension and the module that compiles it, so the release it needs is the one that reads those two keys rather than the one that would have carried its extension. 0.10.0 moves the collection's floor to **2026.9.14.2**, and the reason is two -members rather than the rules: `dist-apk` and `dist-apple` read the native +plugins rather than the rules: `dist-apk` and `dist-apple` read the native closure the engine stages and names in the stage manifest's `needs` lines, `dist-apple`'s framework rpath needs the engine to leave an `@executable_path` rpath as written, and `mcpp run --format app` reaches the runner named after the @@ -171,13 +171,13 @@ format only from that release. `rules-metal` itself needs nothing past 2026.9.8.1. An older engine is not left to fail silently: `dist-apk` refuses a stage without `needs` lines, naming the release. -The index descriptor states the highest floor among the members, so it is the +The index descriptor states the highest floor among the plugins, so it is the floor of the collection rather than of any one feature; a project on an older mcpp is refused at resolution rather than at the first shader. ## What a consumer names -A member that embeds a payload -- `rules-spirv`, `rules-slang`, `tools-embed` -- +A plugin that embeds a payload -- `rules-spirv`, `rules-slang`, `tools-embed` -- does not leave the consumer to include a generated header. All three hand their payloads to one generator, `mcpp::plugins::surface`, so what a consumer writes is the same whichever produced them: @@ -233,7 +233,7 @@ worse than it looks: measured with GCC 16.1 on a 1 MB payload, an interface returning `std::span` produced a 1 313 968-byte BMI against 1 808 bytes for the std-free equivalent, and that cost is fixed rather than proportional to the payload -- it is ``'s templates, present whether the payload is 16 KB or -16 MB. A consumer that wants a `std::span` constructs one from the two members. +16 MB. A consumer that wants a `std::span` constructs one from the two plugins. **Where the bytes live is a second, independent choice.** The surface decides how a consumer names a payload; `storage` decides where it sits. The declarations are @@ -313,7 +313,7 @@ the setting as `MCPP_LANGUAGE_MODULES`; an engine that does not report it leaves the header surface in place, so an older engine keeps the behaviour every consumer of this package had before the surface existed. -**The generator is not shader-specific, and three members already share it.** +**The generator is not shader-specific, and three plugins already share it.** `mcpp::plugins::surface` knows about a run of bytes, a name, where it lives and how it is reached; it does not know what SPIR-V is. `rules-spirv`, `rules-slang` and `tools-embed` all call it, which is what keeps their generated declarations @@ -335,17 +335,17 @@ now, and every consumer reaches the same array through the accessor. mcpp compiles every module interface unit among a host-module package's resolved sources as a host module of its own, the lib root first (2026.9.5.3+). -`[features.] sources` is what puts a member into that set, so the module set -a consumer can import is exactly its feature set. A member is compiled alone, +`[features.] sources` is what puts a plugin into that set, so the module set +a consumer can import is exactly its feature set. A plugin is compiled alone, in the same command as the consumer's `build.mcpp`, and may import `std`, `mcpp` and `mcpp.plugins`. ## What a rule may drive, and what it may not -A member drives a compiler the ecosystem resolved and no other. `xim:dpcpp` is +A plugin drives a compiler the ecosystem resolved and no other. `xim:dpcpp` is `mcpp.rules.sycl`'s compiler; `xim:gcc` is the C++ standard library it compiles against; `xim:cuda-nvcc` is the back end it emits for. None of the three is a -default: each is read from `mcpp::xpkg_dir`, and a member that cannot find one +default: each is read from `mcpp::xpkg_dir`, and a plugin that cannot find one refuses and prints the `[xlings.workspace]` line that would add it. Two of those three were added because a build that already worked was found to @@ -354,17 +354,17 @@ be reading the host. Without `--gcc-install-dir` the SYCL unit compiled against installation. Neither said anything: both are visible only in the compiler's own include search list, and only on a machine that has those directories. -## Adding a member: what the engine owns and what the member owns +## Adding a plugin: what the engine owns and what the plugin owns 1. One file, `rules/.cppm`, `tools/.cppm`, `dist/.cppm` or `deps/.cppm`, declaring its module name. The engine owns the graph — the accelerator axis, the constrained globs, - the action edges, the fingerprint — and the member owns the spelling: which - tool, which flags, what is generated. A member does not read `/usr`; a tool + the action edges, the fingerprint — and the plugin owns the spelling: which + tool, which flags, what is generated. A plugin does not read `/usr`; a tool comes from `mcpp::toolchain_dir()`, `mcpp::xpkg_dir()` or an explicit option, and a missing one is refused naming the `[xlings.workspace]` entry to add. 2. A feature in `mcpp.toml` adding that one source. 3. A consumer under `tests/` that builds through it and asserts on the - artefact, and a row in the README's members table with the mcpp floor. + artefact, and a row in the README's plugins table with the mcpp floor. 4. A version bump: mcpp identifies an installed package by `(name, version)`, so a changed payload under an unchanged version is not reinstalled. diff --git a/docs/01-plugin-development.md b/docs/01-plugin-development.md index abb19db..9a2f61a 100644 --- a/docs/01-plugin-development.md +++ b/docs/01-plugin-development.md @@ -65,19 +65,19 @@ speaks protocol 17 (the platform's directives and the `platform` phase, mcpp SPEC-013) and writes `mcpp-package.json` beside every staged tree (SPEC-014); it carries protocol 15, which states where each tool and payload comes from. -**Where a member's tool comes from.** A member that runs a program resolves it -through `mcpp.plugins.tool`, which answers in one order for every member: +**Where a plugin's tool comes from.** A plugin that runs a program resolves it +through `mcpp.plugins.tool`, which answers in one order for every plugin: 1. the build program's own choice — `o.cmake = "/usr/bin/cmake"`, or `tool::root(dir)`, `tool::on_path()`; -2. the variable that member has always read (`MCPP_SLANGC`), kept for the +2. the variable that plugin has always read (`MCPP_SLANGC`), kept for the projects that write it; 3. the engine's override (`[xlings.overrides]`, `MCPP_XLINGS_OVERRIDE_*`, `config.toml`) — the payload is then not installed at all; 4. the declared payload, asked for here when it is declared `provision = "on-request"`. -A member writes one `tool::spec` per tool (the package, the program names, the +A plugin writes one `tool::spec` per tool (the package, the program names, the directories under a root, the option's name, a legacy variable) and calls `resolve`: @@ -102,7 +102,7 @@ build reports. A choice alone does not prevent a download: an eagerly declared payload is provisioned before any build program runs. The pair that makes "named here, not -downloaded" true, the scenarios on both sides of it, and how each official member +downloaded" true, the scenarios on both sides of it, and how each official plugin declares its tools are in [02-tool-sources.md](02-tool-sources.md). **Stating the build toolchain.** `mcpp.plugins.toolchain` (feature @@ -195,19 +195,19 @@ A plugin is C++23 that three combinations of compiler and standard library accep | clang (LLVM 22) with libc++ | `mcpp build --toolchain llvm@22.1.8` on Linux, and every build on macOS | `toolchain-llvm`, `rules-cross-platform` | | clang with libstdc++'s `std` module | an editor's clangd (mcppls) reading a project built with GCC | `toolchain-editor` | -MSVC is a fourth for the members that claim Windows, checked by `rules-cross-platform` and `deps-managed-msvc`. The third combination is never used by a build, so only the editor lane sees what it rejects; it runs `mcppls diagnostics build.mcpp` on every fixture and fails on any error. +MSVC is a fourth for the plugins that claim Windows, checked by `rules-cross-platform` and `deps-managed-msvc`. The third combination is never used by a build, so only the editor lane sees what it rejects; it runs `mcppls diagnostics build.mcpp` on every fixture and fails on any error. Known differences, each one met in this package: - **A type that holds a container of itself does not use `std::pair` or `std::tuple` for the element.** Under clang with libstdc++'s `std` module, `std::vector>` inside `value` instantiates the pair while `value` is incomplete and fails with "incomplete type used in type trait expression"; GCC and clang with libc++ accept it. The element is a plain struct, and a member function that walks the container is defined after both types are complete (`mcpp::plugins::json::member`, 0.19.1). - **No compiler's leniency is relied on.** An extension, a missing `typename`, or a template accepted only because one compiler instantiates it later is a failure in another lane. - **A build program does not use `std::println`.** On macOS 14 the build program links the system libc++, which lacks a symbol it needs; `std::format` into a string and `std::cout` work everywhere. -- **No unit includes a header or branches on the platform in the preprocessor.** The C library comes from `std`, which exports the functions and types of ISO C (`std::isalnum`, `std::getenv`, `std::FILE`) but no macro; a macro of ISO C (`stdout`, `errno`, `SEEK_SET`) comes from `mcpplibs.mwrap.libc` under its own name (`mcpplibs::mwrap::libc::macros::stdout()`). The operating system comes from `mcpplibs.os`: a program a member asks for a fact runs through `mcpp::plugins::tool::capture` (its arguments as a vector, no shell, so nothing is quoted and no null device is named), a library opens through `mcpplibs::os::library::open`, and a child's environment is stated in its spawn options rather than written into this process's. A build program runs on the machine that builds, so a platform difference is a compile-time question of that machine: `if constexpr (mcpplibs::os::is_windows)`. CI refuses an `#include`, `#if` or `#ifdef` in a unit (0.21.0). +- **No unit includes a header or branches on the platform in the preprocessor.** The C library comes from `std`, which exports the functions and types of ISO C (`std::isalnum`, `std::getenv`, `std::FILE`) but no macro; a macro of ISO C (`stdout`, `errno`, `SEEK_SET`) comes from `mcpplibs.mwrap.libc` under its own name (`mcpplibs::mwrap::libc::macros::stdout()`). The operating system comes from `mcpplibs.os`: a program a plugin asks for a fact runs through `mcpp::plugins::tool::capture` (its arguments as a vector, no shell, so nothing is quoted and no null device is named), a library opens through `mcpplibs::os::library::open`, and a child's environment is stated in its spawn options rather than written into this process's. A build program runs on the machine that builds, so a platform difference is a compile-time question of that machine: `if constexpr (mcpplibs::os::is_windows)`. CI refuses an `#include`, `#if` or `#ifdef` in a unit (0.21.0). - **A function that reaches mcpplibs.os is not `inline`.** A rule's helper that runs a program (`mcpp::plugins::tool::capture`) or opens a library is defined without `inline`, so it is compiled once in its module and an importer sees its declaration only. Under GCC 16 an importer that reads such a body from an inline function fails: "failed to read compiled module cluster: Bad file data", or an unresolved `std::optional>` at the link (`tests/metal-consumer`, 0.21.0). - **A module does not instantiate `std::filesystem::path`'s iterator.** Under MSVC 14.52 every importer that then touches `std::filesystem` fails inside the STL; `mcpp::plugins::names::components` splits a path as a string instead. -**The private region of a unit.** A member's file, and each unit of a directory -member, reads in three parts: the `export module` line with its imports, the +**The private region of a unit.** A plugin's file, and each unit of a directory +plugin, reads in three parts: the `export module` line with its imports, the interface its importers see, and, last, the unit's own private region. In a unit that is its module's only unit the private region is a private module fragment — `module :private;` — and the declarations and definitions after it @@ -215,22 +215,22 @@ are the unit's own, never visible to an importer. A unit that shares its module with other units cannot carry a fragment: its private region is a `namespace detail` block, and the names a sibling unit imports stay outside it. -The members this package ships today were written before the rule and are not -migrated: a member adopts the fragment as it is touched — noted here as a +The plugins this package ships today were written before the rule and are not +migrated: a plugin adopts the fragment as it is touched — noted here as a TODO, not carried out wholesale. ## 5. A new plugin A plugin in this package consists of: - a module under `rules/`, `tools/`, `dist/` or `deps/` — one file - `/.cppm`, or a directory when the member outgrows one file: + `/.cppm`, or a directory when the plugin outgrows one file: `//.cppm` is the interface a consumer imports, and the units under `//internal/` carry the machinery as modules named `mcpp...internal.`. The module name a consumer imports does not change, and the internals are not part of the contract (§2.5); - a feature in `mcpp.toml`; - a fixture under `tests/` that CI builds and asserts on; -- a row in the README's member table with its mcpp floor; +- a row in the README's plugin table with its mcpp floor; - a page under `docs/`; - a version bump. diff --git a/docs/02-tool-sources.md b/docs/02-tool-sources.md index 48d2382..473f7d6 100644 --- a/docs/02-tool-sources.md +++ b/docs/02-tool-sources.md @@ -1,6 +1,6 @@ # Where a tool comes from -A member that runs a program — cmake, vcpkg, glslangValidator, nvcc, appimagetool +A plugin that runs a program — cmake, vcpkg, glslangValidator, nvcc, appimagetool — answers one question before it can plan anything: which program. This page is the account of that question for the three people it concerns: whoever writes a plugin, whoever designs one, and whoever uses one. It is written as scenarios, @@ -16,7 +16,7 @@ own account is mcpp `docs/23-the-project-environment.md`; the design record is 1. the build program's choice o.cmake = "/usr/bin/cmake" o.cmake = tool::root("/opt/cmake") o.cmake = tool::on_path() -2. the member's legacy variable MCPP_SLANGC, MCPP_GLSLC (kept, never extended) +2. the plugin's legacy variable MCPP_SLANGC, MCPP_GLSLC (kept, never extended) 3. the engine's override [xlings.overrides] in the root or workspace manifest MCPP_XLINGS_OVERRIDE__ ~/.mcpp/config.toml @@ -38,7 +38,7 @@ machine. Every level names itself in the output, so an environment variable quietly displacing a project's decision is not possible. An override is read from the root manifest only — or the workspace manifest, when -a member is built. A dependency that writes the table is refused and named: +a plugin is built. A dependency that writes the table is refused and named: **which payloads a package needs is its own statement; where they come from is the project's.** @@ -69,7 +69,7 @@ plugin declares, stated in the build program and nowhere else -- no ### 3.1 Four ways, each a whole build program -Every example here is a complete `build.mcpp` that compiles. A member reads one +Every example here is a complete `build.mcpp` that compiles. A plugin reads one option (section 3.6 is the index); what differs is what the project states. **A program this machine already has.** The plainest form: a string assigns to the @@ -89,8 +89,8 @@ int main() { } ``` -**A tree, with the member looking inside it.** `tool::root` states a directory and -lets the member apply its own layout: `deps-cmake` looks for `cmake` in `bin` and +**A tree, with the plugin looking inside it.** `tool::root` states a directory and +lets the plugin apply its own layout: `deps-cmake` looks for `cmake` in `bin` and in `CMake.app/Contents/bin`, `deps-vcpkg` directly under the root. ```cpp @@ -109,7 +109,7 @@ int main() { } ``` -**Whatever is on PATH, as a stated choice.** A member never falls back to PATH on +**Whatever is on PATH, as a stated choice.** A plugin never falls back to PATH on its own; `tool::on_path()` is how a project asks for that, so the log records that the build depends on the machine. @@ -220,7 +220,7 @@ same two lines as the `getenv` pair, for a project that already enables ### 3.4 A stated choice that fails is not replaced -The member +The plugin refuses and names what it consulted, rather than falling back to the payload: ``` @@ -238,7 +238,7 @@ to answer from the output. `deps-vcpkg` declares its payload `provision = "on-request"`, so the choice is read before anything is provisioned. -For a member whose payload is eager -- `rules-cuda`'s toolkit, which the plan +For a plugin whose payload is eager -- `rules-cuda`'s toolkit, which the plan reads a version out of -- naming the tool in `build.mcpp` does not prevent the download, and `[xlings.overrides]` is the way out. Section 5.2 is the table. @@ -264,10 +264,10 @@ a warm payload cache does not save this twice. ### 3.6 Which option, and what it looks for -Each member names its tool through one option, and states where it looks under a +Each plugin names its tool through one option, and states where it looks under a root. A path assigned as a string is taken as the program itself in every case. -| member | option | program names | under a root it looks in | variable it still reads | +| plugin | option | program names | under a root it looks in | variable it still reads | |---|---|---|---|---| | `deps-vcpkg` | `options::vcpkg` (and `options::vcpkg_root`) | `vcpkg` | the root itself | -- | | `deps-cmake`, `deps-archive` | `options::cmake` | `cmake` | `bin`, `CMake.app/Contents/bin` | -- | @@ -282,7 +282,7 @@ root. A path assigned as a string is taken as the program itself in every case. | `dist-wix` | `options::tool` | `wix` | `tool/tools/net6.0/any` | -- | | `dist-apk` | `options::build_tools`, `options::platform`, `options::jdk`, `options::bundletool_dir`, `options::kotlin`, `options::coursier` | roots, no program | -- | -- | -A member whose option names a **root rather than a program** -- `rules-qt`, +A plugin whose option names a **root rather than a program** -- `rules-qt`, `rules-ascendc`, `dist-apk` -- takes `tool::root(...)` or a plain directory path, because what it needs is the tree, not one executable. @@ -313,13 +313,13 @@ succeeded either way. plugins = { version = "0.19.0", features = ["deps-cmake"], host-module = true } ``` -The member resolves nothing stated, reaches the fourth level, finds `xim:cmake` +The plugin resolves nothing stated, reaches the fourth level, finds `xim:cmake` declared on request and not installed, asks for it, and the engine installs it and runs the program again. The output is byte-for-byte what it was before this mechanism existed. One difference from 0.18.1: **a payload declared and not used is not installed.** -A build that never reaches the member — because it compiles only its own modules, +A build that never reaches the plugin — because it compiles only its own modules, or because `--format` took another branch — downloads nothing for it. ### 4.2 State it in the manifest instead of the build program @@ -331,7 +331,7 @@ or because `--format` took another branch — downloads nothing for it. "xim:slang" = { program = "slangc", version = "2026.14.1" } # checked against every requirement ``` -This path needs no support from the member: the engine removes the payload from +This path needs no support from the plugin: the engine removes the payload from the provisioning set, `mcpp::xpkg_dir` answers the root the override implies, and `mcpp::xpkg_source` answers `override`. **A plugin that has not migrated to `mcpp.plugins.tool` benefits from it unchanged**, as long as it reads its @@ -397,7 +397,7 @@ bootstrap = "llvm@22.1.8" # the one that compiles build pr ## 5. For whoever writes a plugin -### 5.1 A member that runs a program +### 5.1 A plugin that runs a program Three pieces, written once per tool: @@ -407,7 +407,7 @@ struct options { mcpp::plugins::tool::choice cmake; }; -// 2. the spec: this member's own knowledge, and nothing else +// 2. the spec: this plugin's own knowledge, and nothing else inline mcpp::plugins::tool::spec cmake_spec(std::string who) { return { .who = std::move(who), .package = "cmake", .programs = {"cmake"}, .bin_dirs = {"bin", "CMake.app/Contents/bin"}, .option = "options::cmake" }; @@ -421,13 +421,13 @@ if (!t) { warn(mcpp::plugins::tool::describe_missing(cmake_spec("mcpp.deps.cmake run(t.program); ``` -`choice` is constructible from a string, so a member migrating from +`choice` is constructible from a string, so a plugin migrating from `std::string` costs its users nothing: `o.cmake = "/usr/bin/cmake"` still compiles, and the line that wrote it reaches the build's output and `mcpp why tool cmake`. `describe_missing` is the one refusal text, and it lists every way to name the -tool. A member does not write its own. +tool. A plugin does not write its own. ### 5.2 The pair that makes "named here, not downloaded" true @@ -446,7 +446,7 @@ The manifest half: So the author's decision is one question: -| when the member needs the tool | how to declare it | after a user names their own | +| when the plugin needs the tool | how to declare it | after a user names their own | |---|---|---| | while **planning** (it runs cmake, vcpkg, appimagetool, bundletool) | `provision = "on-request"` | nothing is downloaded | | **to plan at all** (it reads a version out of the toolkit's headers, an SDK file, an API level from a platform directory) | plainly, which is eager | still downloaded; the user skips it with `[xlings.overrides]` | @@ -464,7 +464,7 @@ the build program would make them fail to plan. "xim:bundletool" = { version = "1.18.3", provision = "on-request" } ``` -The member requests it while planning a bundle, so an ordinary `--format apk` +The plugin requests it while planning a bundle, so an ordinary `--format apk` build installs nothing for it. The engine installs every request of one invocation together and runs only the programs that asked; the asking run is discarded before its directives are applied, so there is no half-applied state. @@ -484,7 +484,7 @@ in `rules-sycl` while it took the payload directory and appended the SYCL consumer failed with `ld.lld: error: unable to find library -lsycl`. The whole collection was audited for that swap. -### 5.5 Keep the variable a member already read +### 5.5 Keep the variable a plugin already read ```cpp .legacy_env = "MCPP_SLANGC" @@ -494,16 +494,16 @@ It answers at the second level, before the engine's override. `rules-slang` also keeps its historical silent PATH fallback, with a warning that names the correct spelling (`options::compiler = tool::on_path()`) and the date it is removed. -### 5.6 A member that only looks +### 5.6 A plugin that only looks -A member that reports what a machine has, rather than running it, passes +A plugin that reports what a machine has, rather than running it, passes `.request = false`, so looking never pulls a payload down. `rules-qt` does this when it resolves an SDK root: it reports which of the three levels named one, and a report is not a reason to download anything. ### 5.7 Prove it, without installing anything -`mcpp.plugins.testing` runs a member against a stated context and compares the +`mcpp.plugins.testing` runs a plugin against a stated context and compares the directives it emitted: ```cpp @@ -543,7 +543,7 @@ refused in a dependency. **One answer, recorded once.** An explicit source produces exactly one `Using` line, one entry in the `Finished` summary, one record in `resolution.json`, and one section of `mcpp why`. All four read the same `SourceDecision`, so three -cannot agree while the fourth lags. A member contributes to it by calling +cannot agree while the fourth lags. A plugin contributes to it by calling `resolve`, which states `mcpp:decision=`; it does not print its own. **The default stays the default.** The ecosystem's path is the one a project @@ -566,9 +566,9 @@ tree that states it is refused where the declaration is read, because gcc select a linker by the name `ld` inside a `-B` directory and a stated tool that takes no part in the build is what this mechanism exists to prevent. -## 7. Every official member that drives a tool, and how it declares it +## 7. Every official plugin that drives a tool, and how it declares it -| member | tool | declaration | reason | +| plugin | tool | declaration | reason | |---|---|---|---| | `deps-vcpkg` | `xim:vcpkg` | on request | it runs vcpkg while planning | | `deps-cmake`, `deps-archive` | `xim:cmake` | on request | it runs cmake while planning | diff --git a/docs/03-maintainers.md b/docs/03-maintainers.md index 21ccb38..6bfefac 100644 --- a/docs/03-maintainers.md +++ b/docs/03-maintainers.md @@ -6,33 +6,38 @@ more contributors and maintainers. ## The path -Start from the simple and from what interests you, and learn a member as you +Start from the simple and from what interests you, and learn a plugin as you go: **use it → introduce and teach it → report issues → fix bugs → improve it → -maintain one or more members** +maintain one or more plugins** ## What a maintainer does -A member's maintainer carries the member's daily upkeep — issue triage, fixes, -the fixture and CI care on every platform the member claims — and leads its -popularization and ecosystem building: technical articles, videos, tutorials. -Development plus outreach is the core of the role. +Two core responsibilities, and both count: + +| core | the work | +|---|---| +| Technical development | issue triage, fixes, the fixture and CI care on every platform the plugin claims | +| Ecosystem building and technical outreach | technical articles, videos, tutorials — and indirect ecosystem growth: real projects built on the plugin | + +Development plus outreach is the core of the role; the second column is not +optional. ## What a maintainer knows -Deep familiarity with the member's module and its application domain. The -member's page in the [index](README.md) states what it does; the +Deep familiarity with the plugin's module and its application domain. The +plugin's page in the [index](README.md) states what it does; the [conventions](01-plugin-development.md) state what every plugin follows. ## Applying Applications go through the -[maintainer-application template](../.github/ISSUE_TEMPLATE/maintainer-application.yml), -one member per application. An application states contributions to the member -in both categories — technical development, and technical outreach and -promotion — and a maintenance plan that covers both sides. A recommendation -from an existing maintainer of a related member supports it. The original -author of a member accepted into this repository becomes the member's -maintainer; bug fixes and improvements are always welcome before any +[issue template](https://github.com/mcpp-community/mcpp-plugins/issues/new?template=maintainer-application.yml), +one plugin per application. An application states contributions to the plugin +in both categories — technical development, and ecosystem building and +technical outreach — and a maintenance plan that covers both sides. A +recommendation from an existing maintainer of a related plugin supports it. +The original author of a plugin accepted into this repository becomes the +plugin's maintainer; bug fixes and improvements are always welcome before any application. diff --git a/docs/10-rules.md b/docs/10-rules.md index f8ac45b..3d0120c 100644 --- a/docs/10-rules.md +++ b/docs/10-rules.md @@ -59,9 +59,9 @@ Module `mcpp.rules.sycl`; engine floor: 2026.10.1.3 (0.19.0, mcpp#755; 2026.9.6. Each selected implementation owns its targets. A repository may retain CUDA and SYCL source groups while selecting only `sycl+{nvptx64-sm_89}`; the CUDA group is excluded by its source constraint and the CUDA rule need not be imported. Selecting `cuda+{sm_90},sycl+{nvptx64-sm_89}` selects both implementations with different targets. The rule passes the same target vector to compilation and device linking. Its CUDA compiler payload is requested only for a SYCL NVIDIA target; `options::cuda` accepts the same explicit choice as other rule tools. -The older `sycl,cuda+{sm_89}` form still inherits CUDA targets when the SYCL member has no targets, with a migration warning. Both named implementations remain selected. Explicit SYCL targets are never replaced by a CUDA member. Move the device target to the SYCL member to select only SYCL. GPU execution still requires a compatible device and driver; CI verifies the emitted images and the CPU fallback separately. +The older `sycl,cuda+{sm_89}` form still inherits CUDA targets when the SYCL plugin has no targets, with a migration warning. Both named implementations remain selected. Explicit SYCL targets are never replaced by a CUDA plugin. Move the device target to the SYCL plugin to select only SYCL. GPU execution still requires a compatible device and driver; CI verifies the emitted images and the CPU fallback separately. -**Several NVIDIA architectures in a library.** Each package's device link reads that package's own objects (`-fsycl-link` over its `.sycl.o`), so a library's images are registered inside the library and a consumer's link never asks the SDK to unbundle an archive; a library of `sycl+{nvptx64-sm_89,nvptx64-sm_90}` links into a program with each image its own architecture's (`tests/sycl-library-consumer`). Not supported: handing the SDK an archive of several NVIDIA architectures to device-link (a prebuilt SYCL `.a`, or a kernel that calls a `SYCL_EXTERNAL` function of another package). DPC++ 7.1.0's `clang-offload-bundler` matches the five-part bundle IDs its driver writes (`sycl-nvptx64-nvidia-cuda-sm_89`) to every NVPTX request, so unbundling such an archive for one architecture yields the members of all of them and the device link reports duplicate definitions (mcpp#899, an SDK defect). There, build that archive for one architecture, or keep the device code of each architecture in the package that launches it. The rule keeps every requested architecture; it neither drops one nor reuses one architecture's code for another. +**Several NVIDIA architectures in a library.** Each package's device link reads that package's own objects (`-fsycl-link` over its `.sycl.o`), so a library's images are registered inside the library and a consumer's link never asks the SDK to unbundle an archive; a library of `sycl+{nvptx64-sm_89,nvptx64-sm_90}` links into a program with each image its own architecture's (`tests/sycl-library-consumer`). Not supported: handing the SDK an archive of several NVIDIA architectures to device-link (a prebuilt SYCL `.a`, or a kernel that calls a `SYCL_EXTERNAL` function of another package). DPC++ 7.1.0's `clang-offload-bundler` matches the five-part bundle IDs its driver writes (`sycl-nvptx64-nvidia-cuda-sm_89`) to every NVPTX request, so unbundling such an archive for one architecture yields the plugins of all of them and the device link reports duplicate definitions (mcpp#899, an SDK defect). There, build that archive for one architecture, or keep the device code of each architecture in the package that launches it. The rule keeps every requested architecture; it neither drops one nor reuses one architecture's code for another. The `tests/multi-accel-consumer` fixture selects `cuda+{sm_90},sycl+{nvptx64-sm_89}` and imports both rules. CI inspects each rule's actual image target and runs both host objects without submitting GPU work. This establishes build/link coexistence with one C++ runtime; device execution, interoperation and synchronization require their own runtime checks. diff --git a/docs/20-tools-embed.md b/docs/20-tools-embed.md index 5920274..fcef29a 100644 --- a/docs/20-tools-embed.md +++ b/docs/20-tools-embed.md @@ -17,8 +17,8 @@ Module `mcpp.tools.embed`; engine floor: 2026.9.5.4. | `group()` | N | N headers + one generated interface | the same N headers, handed to `mcpp::plugins::surface` so a consumer writes one `import` and names no generated file -- see [What a consumer names](00-engine-and-rules.md#what-a-consumer-names) | | `table()` | N | one header | one array of rows, each carrying its input's key beside its bytes; the consumer iterates or looks a row up by key | -`table()` is for a set the consumer wants to walk rather than name member by -member, where `files()`'s one accessor per input and `group()`'s one function +`table()` is for a set the consumer wants to walk rather than name plugin by +plugin, where `files()`'s one accessor per input and `group()`'s one function per input are both the wrong shape. The motivating case is a shader set: ```cpp diff --git a/docs/21-tools-island.md b/docs/21-tools-island.md index 41ee485..904be96 100644 --- a/docs/21-tools-island.md +++ b/docs/21-tools-island.md @@ -13,7 +13,7 @@ Module `mcpp.tools.island`; engine floor: 2026.9.7.1. `mcpp::plugins::surface` generates the whole interface for a **data** payload, because an address and a size are all there is to decide. `mcpp.tools.island` generates what is mechanical about a **code** island -- and -only that. It is a member like `tools-embed` rather than part of the lib root: +only that. It is a plugin like `tools-embed` rather than part of the lib root: nothing in this collection uses it, a project does. The entry points are marked where they are defined, and the signature exists diff --git a/docs/22-tools-steps.md b/docs/22-tools-steps.md index 40bdf13..5dccefe 100644 --- a/docs/22-tools-steps.md +++ b/docs/22-tools-steps.md @@ -1,12 +1,12 @@ # `tools-steps` -`mcpp.tools.steps` is how a member runs an action whose work is more than one command: the member describes the step as portable operations, and a backend runs it on every host, with no shell. +`mcpp.tools.steps` is how a plugin runs an action whose work is more than one command: the plugin describes the step as portable operations, and a backend runs it on every host, with no shell. ## `tools-steps` Module `mcpp.tools.steps`; engine floor: 2026.10.1.3; implied by `dist-apk` and `dist-apple`. -**Needs and behaviour.** A runner, resolved by the member with `runner_spec()` through `mcpp.plugins.tool`. Until mcpp runs step programs itself (mcpp-community/mcpp#955) the runner is `cmake` 3.31 or newer, which each member that runs steps declares on its own table as `"xim:cmake" = { version = ">=3.31", provision = "on-request" }`, so a plan that runs no step installs nothing. The operations run in order and the first that fails fails the step. `command` writes the program beside the path it is given only when its text changes, and returns the action's argument vector and the inputs it declares, the runner and the program, so a changed program or runner runs the action again and an unchanged one does not. +**Needs and behaviour.** A runner, resolved by the plugin with `runner_spec()` through `mcpp.plugins.tool`. Until mcpp runs step programs itself (mcpp-community/mcpp#955) the runner is `cmake` 3.31 or newer, which each plugin that runs steps declares on its own table as `"xim:cmake" = { version = ">=3.31", provision = "on-request" }`, so a plan that runs no step installs nothing. The operations run in order and the first that fails fails the step. `command` writes the program beside the path it is given only when its text changes, and returns the action's argument vector and the inputs it declares, the runner and the program, so a changed program or runner runs the action again and an unchanged one does not. | operation of `program` | what it does when the step runs | |---|---| @@ -19,4 +19,4 @@ Module `mcpp.tools.steps`; engine floor: 2026.10.1.3; implied by `dist-apk` and Every value is taken verbatim, so a path keeps its spaces, semicolons and backslashes. A list is named by letters, digits and `_`, and starts empty. A pattern's wildcards (`*`, `?`, `[...]`) apply to its last component, and `recursive` matches it in every subdirectory. -The backend is internal. Today it renders the program as a CMake script and the action runs `cmake -P` over it; when the engine runs step programs, `runner_spec` and `command` change and no member does. `cmake_backend::render` is exported so a test can read what a program becomes. +The backend is internal. Today it renders the program as a CMake script and the action runs `cmake -P` over it; when the engine runs step programs, `runner_spec` and `command` change and no plugin does. `cmake_backend::render` is exported so a test can read what a program becomes. diff --git a/docs/30-dist.md b/docs/30-dist.md index fb9db06..4b8b160 100644 --- a/docs/30-dist.md +++ b/docs/30-dist.md @@ -1,12 +1,12 @@ # `dist-appimage`, `dist-deb`, `dist-rpm`, `dist-wix` and `dist-web` -Three `dist-*` members that turn the tree `mcpp pack` stages into an installable form: an AppImage on Linux, an MSI or a Burn bundle on Windows, and a web directory for `wasm32-emscripten`. `dist-apple` and `dist-apk` have pages of their own ([31-dist-apple.md](31-dist-apple.md), [32-dist-apk.md](32-dist-apk.md)). +Three `dist-*` plugins that turn the tree `mcpp pack` stages into an installable form: an AppImage on Linux, an MSI or a Burn bundle on Windows, and a web directory for `wasm32-emscripten`. `dist-apple` and `dist-apk` have pages of their own ([31-dist-apple.md](31-dist-apple.md), [32-dist-apk.md](32-dist-apk.md)). ## `dist-appimage` Module `mcpp.dist.appimage`; engine floor: 2026.10.1.3 (0.19.0, mcpp#755; 2026.9.11.1 before). Its `xim:appimagetool` is installed when a pack asks for it (`provision = "on-request"`), so an ordinary Linux build downloads none. -**Needs and behaviour.** `xim:appimagetool`, which this feature declares on the `cfg(linux)` axis. Linux only. Turns the tree `mcpp pack` staged into one AppImage: the staged bundle is already an AppDir bar three files, so the member writes an `AppRun`, a `.desktop` entry and an icon into it and invokes one tool -- it never copies or re-lays-out a tree that can be hundreds of megabytes. From 0.11.1 `options::icon` may be an SVG as well as a PNG: the image carries `.svg`, because the desktop entry names the icon without an extension and a reader finds it by the file's, and any other format is refused by name +**Needs and behaviour.** `xim:appimagetool`, which this feature declares on the `cfg(linux)` axis. Linux only. Turns the tree `mcpp pack` staged into one AppImage: the staged bundle is already an AppDir bar three files, so the plugin writes an `AppRun`, a `.desktop` entry and an icon into it and invokes one tool -- it never copies or re-lays-out a tree that can be hundreds of megabytes. From 0.11.1 `options::icon` may be an SVG as well as a PNG: the image carries `.svg`, because the desktop entry names the icon without an extension and a reader finds it by the file's, and any other format is refused by name ## `dist-deb` and `dist-rpm` @@ -24,11 +24,11 @@ Module `mcpp.dist.wix`; engine floor: 2026.10.1.3 (0.19.0, mcpp#755; 2026.9.11.1 ## `dist-web` -Module `mcpp.dist.web`; engine floor: 2026.9.13.1, the release that carries `${mcpp.self}` and `mcpp stage`'s argument shape as an engine contract (`stage --verify content --output `) -- what lets this member's copy run on every host mcpp does, Windows included, in place of the `cp` this member used through 0.8.0. +Module `mcpp.dist.web`; engine floor: 2026.9.13.1, the release that carries `${mcpp.self}` and `mcpp stage`'s argument shape as an engine contract (`stage --verify content --output `) -- what lets this plugin's copy run on every host mcpp does, Windows included, in place of the `cp` this plugin used through 0.8.0. **Needs and behaviour.** nothing beyond mcpp: `wasm32-emscripten` only. Copies `${mcpp.stage_dir}/bin/` -- the `.js` launcher, the implicit `.wasm`, the `.data` when present, and every `mcpp::deploy`'d file, all of which #622 A5 and A4 already stage there -- to `/web/`, dropping the `bin/` prefix a browser has no use for, and writes an `index.html` rendered from a project template or a built-in default that loads the script with a plain `