diff --git a/.agents/docs/2026-11-24-rules-qml-design.md b/.agents/docs/2026-11-24-rules-qml-design.md new file mode 100644 index 0000000..3b0f5fa --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-design.md @@ -0,0 +1,634 @@ +--- +subject: rules-qml +status: implemented in mcpp-plugins#66 (revision 5: the engine fixes mcpp#1011, so the plugin_closure workaround and mcpp.plugins.binary are not in the PR) +--- + +# `rules-qml`:mcpp 对 QML 的一等支持(单 PR、三平台、含测试) + +读者:本仓库维护者(review 用)。本文是设计,不含实现。 +证据来自 2026-11-24 在本机(Linux x86_64,`xim:qt` 6.11.1,gcc 16.1,LLVM 20.1.7 / 22.1.8 / 23.1.3 / 23.1.6,mcpp 2026.10.31.3 / 2026.11.7.2 / 2026.11.20.1)做的实验;原型代码在 +[`2026-11-24-rules-qml-spikes/`](2026-11-24-rules-qml-spikes/README.md)。 +Windows 与 macOS 没有实测机器:凡依赖它们的结论都标"推断",并各配一个 CI 断言(§10.3)。 + +修订记录:第 1 版把 8 个问题留给 review。第 2 版对每个问题做了决定并用实验验证;验证推翻了第 1 版的两处设计(文本闭包的算法、`mcpp_qml_keep()`),并发现了引擎的闭包缺口(Q9)。第 3 版:按你的意见补充 LLVM 验证(Q10),闭包补丁改为两个规则都默认开、无感、带标注与金丝雀;并处理了一次独立评审的全部意见(§16)。验证中纠正了我自己的一处错误:先前报告的"clang + libstdc++"其实用的是 libc++(Q10)。第 4 版:工具链与 `rules-qt` 对齐、Linux 不做 LLVM(Q10);引擎 issue 已提交(mcpp#1011);`qsb` 不可运行的根因是 `xim:qt-addons` 没声明 `xim:glibc`,已给 xim-pkgindex 提修复 PR(Q5)。 + +## 修订 5:实现时的变更(以此为准,下文 Q2、Q9、§7 `link_plugin_libs`、§10 中涉及它们的部分已被取代) + +- **mcpp#1011 已在引擎侧修复**(mcpp 分支 `feat/kernel-abi-supplier`,提交 `b31e1da2`:`mcpp::deploy` 放到程序旁的同格式对象成为 `mcpp pack` 闭包的根)。按你的意见,不再带 workaround:**`plugin_closure`、`link_plugin_libs`、`ENGINE-GAP` 标记与 `check-engine-gaps.sh`、金丝雀都不进本 PR**。唯一的读取依赖表的使用者随之消失,所以**`mcpp.plugins.binary`(含 `plugins-binary`、`binary-reader` fixture)也不进 PR**;它的实现与 180 个真实 ELF 对照的结果保留在 PR 的提交历史(`d0ae156` 等)与 `spikes/binary.hpp`。 +- 本机用该分支临时构建的 mcpp(2026.11.23.1,只读使用)验证:`qml-deploy` 打包后 1058 个依赖均在包内(含 `libQt6QuickLayouts.so.6`、`libQt6XcbQpa.so.6`),SDK 目录改名后打包程序能运行;`qt-widgets-consumer` 的包含 `libQt6XcbQpa.so.6`。 +- **合入条件**:该修复随 mcpp 发布后,把包的 mcpp 下限与 README 中 `rules-qml`、`rules-qt` 的下限列提到该版本,CI 的 `MCPP_BOOTSTRAP` 固定到它;此前 PR 保持 draft。 +- 其他与设计不同处:`qml::options` 没有自己的 `out_dir`(用 `qt.out_dir`);`rcc` 动作带 `--depfile`(仓库 CI 要求每个规则声明 depfile);`.qmltypes` 之外的非 SDK 插件依赖不再警告(随读取器一起去掉);Windows 上含 `<` `>` 的资源名用例改为运行时创建、主机不能创建则不断言。 + +## 0. 核心点(先看这里) + +1. **新增独立成员 `rules-qml`**(模块 `mcpp.rules.qml`),隐含 `rules-qt`,不并入。不认领 `.qml` 扩展名,因此和 `tools-*`、`dist-*` 一样**不写 `rule_module`**,消费者自己写 `host-module = true`(隐含的 `rules-qt` 仍有自己的 `rule_module` 并认领 `.ui/.qrc/.ts`,互不影响)。 +2. **一次 `qml::compile(options)` 完成整条链路**:moc(JSON) → `qmltyperegistrar` → `qmldir` → qrc → `rcc` → `qmlcachegen`(AOT) → 编进程序。等价于 `qt_add_qml_module`;应用自带模块静态链接进可执行文件,用 `loadFromModule` 加载。整条链路已在真实引擎里用原型跑通(点分 uri、C++ 类型、单例、`.js`、嵌套目录、资源文件,输出 `cpp=84 singleton=red js=42 nested=7 resource=hello-resource`)。 +3. **部署是难点**,设计由三部分组成,均已验证: + - **模块闭包**用计划期纯文本解析得到,规则是"qmldir 的 `import`/`default import`/`optional import`/`depends` 行 + 模块目录里所有 `.qml` 的 `import` 语句"。第一版漏了后一半,与 `qmlimportscanner` 差 16 个模块;修正后在 4 个样本(含 Qt 全部 40 个顶层模块)上与 scanner **完全一致**。 + - **补库**:读已部署插件的依赖表,把属于 SDK 的库链进程序(Linux 用 `--push-state,--no-as-needed` 包住以防被 `--as-needed` 丢弃,macOS 用 `-needed_library`),Windows 用 `deploy` 放到程序旁。读取器 `mcpp.plugins.binary` 对 180 个真实 ELF 与 `readelf` 一致,对 mingw 构建的 PE、lld 构建的 Mach-O(含 fat)与 `objdump`/`otool` 一致,1500 个截断/损坏输入无崩溃。 + - **`qt.conf`** 默认写入并部署(`Prefix = .`,`Qml2Imports = qml`)。 +4. **新发现的缺口(Q9):`mcpp pack` 的闭包只从程序本身出发,不带已部署插件的依赖。** 这既影响 QML 插件,也影响现有 `rules-qt` 的平台插件(`libqxcb.so` 需要的 `libQt6XcbQpa.so.6` 不在包里;现有 CI 只在 offscreen 下运行所以没发现)。处理方式:**规则里加一个对用户完全无感的临时补丁(`rules-qt` 与 `rules-qml` 都默认开,用户不用配置任何东西),源码与文档都醒目标注为"引擎缺口补丁";补丁是幂等的,引擎修好后它变成无影响的冗余;CI 里有一个"金丝雀",一旦引擎自己带上这些库就提示删除补丁。** 同时向 mcpp 提了 issue:**mcpp-community/mcpp#1011**(§15)。 +5. **测试**:`plugin-logic` 纯逻辑用例(含逐前缀截断的读取器用例);4 个三平台 fixture(`qml-consumer`、`qml-modules`、`qml-deploy`、`qml-import-only`)加 1 个仅 Linux 且带探测门的 `qml-shaders`;各平台用其默认工具链自带的工具(Linux `readelf`/`nm`,macOS 与 Windows `llvm-readobj`/`llvm-nm`)与 `qmlimportscanner` 对照;打包闭包用静态分析断言,并在**把 SDK 目录挪走**的条件下运行。 +6. **生态侧**:`xim:qt` 已含全部 QML 工具,不新增。`xim:qt-addons` 的 `qsb` 起不来是因为它的 Linux 条目没声明运行时依赖(所以没被 elfpatch);我查清根因、在隔离环境里真实安装验证后,给 xim-pkgindex 提了修复 PR(#1262,Q5)。合入并发布之前,`qsb` 的真实运行测试按探测门执行,之后自动翻转。 +7. **工具链与 `rules-qt` 对齐,不引入新的选择**:`rules-qt` 的 fixture 没有 `[toolchain]` 覆盖;Linux 只加 `cxx_runtime = "toolchain-coupled"`(Qt 官方 Linux 构建用共享 libstdc++,所以用 gcc),Windows、macOS 用引擎对该主机的默认工具链(mcpp 的 LLVM clang 等)。`rules-qml` 的 fixture 逐字沿用这几行。**Linux 不支持 clang + Qt**(引擎拒绝 libc++,`rules-qt` 已有警告),所以不在 Linux 上做 LLVM 的 CI;我本机做的 LLVM 验证(4 个版本编译、链接、运行生成的 C++ 通过)作为证据保留(Q10),不进 CI。 +8. **继承的限制(实测)**:项目路径含空格或非 ASCII 字符时,gcc 的模块依赖扫描失败,连现有 `qt-consumer` 也一样;与 QML 无关,写进限制,测试用 ASCII 路径。 + +## 1. 目标与非目标 + +目标(本 PR 全部实现): + +| # | 能力 | 对应 CMake | +|---|---|---| +| G1 | 应用自带 QML 模块(uri、版本、`.qml`/`.js`/`.mjs`、单例、资源文件、嵌套目录) | `qt_add_qml_module` | +| G2 | C++ 类型注册(`QML_ELEMENT` 等)与 `.qmltypes` | 同上 | +| G3 | AOT 编译(`qmlcachegen`)及加载器 | 同上,默认开 | +| G4 | 多模块、点分 uri、模块间依赖 | 多次调用 | +| G5 | Qt 自带 QML 模块的部署与打包闭包 | `windeployqt --qmldir` | +| G6 | `qt.conf` | `windeployqt` / 手写 | +| G7 | 着色器 `qsb` 并嵌入模块资源 | `qt_add_shaders` | +| G8 | `qmllint` 检查动作 | `_qmllint` | +| G9 | QML/JS 中 `qsTr` 的翻译提取 | 内置 | +| G10 | Linux / Windows / macOS 构建、运行、`mcpp pack --format dir` | — | +| G11 | 已部署插件(含 `rules-qt` 的平台插件)的闭包补全 | `windeployqt` 的依赖扫描 | + +非目标(文档的"限制"一节写明): + +- **`qmltc`**(QML 编成 C++ 类,可做 `import app.ui;`):覆盖的 QML 子集有限,另做。 +- **QML 插件做成独立共享库**(`qt_add_qml_plugin`):应用自带模块一律静态进可执行文件。 +- **来自依赖包的 QML 模块**:只提供 `import_paths` 入口。由此,**跨包静态库里的模块注册可能被链接器丢弃**(Q8),文档说明:在代码里引用生成的 `qml_register_types_`。 +- **macOS `.app` bundle 与 `dist-apple`** 的 QML 布局(Q7)。 +- **`.qmlls.ini` 生成**(mcpp-ide)、**`qmlformat`**、**`.qmllint.ini`**、**Qt 5**。 +- **Android、iOS、WebAssembly 目标**:QML 需要对应的 Qt SDK;`qml::compile` 在 `target_os` 不是 linux、windows、macos 时报一条警告并跳过,不声明任何动作。 +- **一个包里有多个目标**:生成的源文件会进入包的每个目标(实测:`kind = "lib"` 加 `bin` 时两者都编译这些对象)。文档要求 QML 模块只放在一个目标的包里,不构造反例。 +- **项目路径含空格或非 ASCII 字符**:gcc 的模块依赖扫描报 `cannot determine '#include' translation … malformed string 'ERROR … INCLUDE-TRANSLATE'`(实测,现有 `qt-consumer` 在 `/tmp/qtc-测试` 同样失败,在 ASCII 路径下成功;空格同样)。继承自工具链,不是本 PR 引入,也不在本 PR 修;文档写明,fixture 用 ASCII 路径。 +- **`.js` 里的 `.import`、`.mjs` 的 `import` 语句**:文本闭包不解析(`qmlimportscanner` 对它们的处理未验证),用 `options::imports` 补。 +- **`qtquickcontrols2.conf` / `QQuickStyle::setStyle` 选择的样式**:运行时才知道,所以默认部署全部样式;想缩小用 `styles`。 + +## 2. 决定与验证 + +| # | 决定 | 证据 | +|---|---|---| +| Q1 | 部署闭包用**计划期文本解析**;`qmlimportscanner` 只作 CI 对照基准 | 见下 | +| Q2 | 依赖表读取器做成**新通用模块** `mcpp.plugins.binary`(feature `plugins-binary`,纯 `std`),由 `rules-qt`、`rules-qml` 使用 | 见下 | +| Q3 | `write_qt_conf` **默认开**;`Translations` 随 `i18n.deploy_to` 生成;检测到用户自己的 `qt.conf` 则不写并警告 | 见下 | +| Q4 | 版本 **0.27.0**;README 的 mcpp 下限列写 **2026.10.1.3**(与 `rules-qt` 相同,列的语义是"该成员的行为最早需要的版本"),整个包仍是 2026.10.30.1 | 见下 | +| Q5 | `qsb` 实现;argv 由单元用例固定;真实运行放**带探测门**的 Linux fixture | 见下 | +| Q6 | `aot` **默认开** | 见下 | +| Q7 | macOS bundle(`dist-apple`)**不纳入**,本 PR 测 `pack --format dir` | 范围决定,无本机证据 | +| Q8 | **取消** `mcpp_qml_keep()`,限制写进文档 | 见下 | +| Q9(新) | 闭包缺口的根因在引擎(已提 mcpp#1011,§15);本 PR 带**对用户无感、两个规则都默认开、幂等、有标注与金丝雀**的临时补丁 `plugin_closure` | 见下 | +| Q10(新) | LLVM:生成的 C++ 在 4 个 LLVM 版本上编译并运行通过;macOS、Windows 的 clang 本身无法验证,由三平台 CI 覆盖 | 见下 | + +### Q1 证据:计划期能跑子进程,但不该用;文本闭包已与 scanner 对齐 + +- 在 `build.mcpp` 的 `main()` 里 `std::system` 运行 `qmlimportscanner` 可行(生成了 56 KB 的 JSON)。但 mcpp 自己的文档(`docs/30-build-mcpp.md`)明确建议:工具放进动作的命令里运行,不要在 `main()` 里运行,否则 `emit build-database` 在工具不可得时会让整个计划丢失这个包的指令。 +- 文本闭包的第一版(只读 qmldir 的 `import`/`depends`,不跟随 `optional`)与 scanner 比较:app1 少 16 个模块。原因两个:Qt 模块目录里的 `.qml` 文件自己也 `import` 别的模块;`optional import … auto`(样式)scanner 会跟随。 +- 修正后的算法(`spikes/closure.py`): + 1. 起点:用户所有 `.qml` 的 `import` 语句(去注释与字符串,不含应用自带模块的 uri)+ `options::imports`; + 2. 对每个 uri 找 `/qml//qmldir`(及 `import_paths`),跟随其中 `import`、`default import`、`optional import`、`depends`; + 3. 并读取该模块目录下**所有 `.qml`**(递归,但不进入自带 `qmldir` 的子目录,它们是别的模块)的 `import`。 +- 结果:4 个样本(Controls;Layouts/Window/Shapes/Dialogs 混合;Material+labs+Effects+Templates;Qt 全部 40 个顶层模块)上 `scanner-only` 与 `mine-only` 均为空(24/27/15/49 个模块)。 +- `import` 语句的识别:`import [版本] [as 名]`,允许行尾 `;`;一行里多条 `import` 不识别(QML 惯例是一行一条)。 +- 样式默认全部跟随(与 `windeployqt` 一致,保证运行时选任何样式都不缺);`options::styles` 非空时,`optional import` 只跟随其中列出的。实测规模(`QtQuick` + `QtQuick.Controls`): + + | 配置 | 模块 | 部署文件 | QML 体积 | 需补的 Qt 库 | + |---|---|---|---|---| + | 默认(全部样式) | 24 | 1231 | 6.8 MB | 30 个,99 MB | + | `styles = {"Material"}` | 15 | 173 | 0.7 MB | 22 个,91 MB | + | `styles = {"Basic"}`(只剩默认样式) | 12 | 100 | 0.4 MB | 20 个,89 MB | + +### Q2 证据:读取器正确,且可安全读不可信文件 + +`spikes/binary.hpp`(120 行,纯 `std`): + +| 格式 | 对照 | 结果 | +|---|---|---| +| ELF(`DT_NEEDED`) | `readelf -d`,SDK 里 `qml/`、`plugins/`、`lib/`、`libexec/` 的 180 个真实文件(全是 64 位小端) | 180/180 逐集合一致 | +| PE(导入表) | mingw 构建的 64 位 `a.dll`(导入 `b.dll`)、`b.dll`、`m.exe`,`x86_64-w64-mingw32-objdump -p` 与 `llvm-objdump -p` | 一致 | +| Mach-O(`LC_LOAD_DYLIB`;fat) | LLVM 的 `clang` + `ld64.lld` 构建 arm64、x86_64 的 dylib,手工拼 fat;`llvm-otool -L` | 一致。注意:`otool -L` 与 `llvm-readobj --needed-libs` 的结果都**含文件自己的 `LC_ID_DYLIB`**,读取器不返回它;用例与 CI 对照都要先把它去掉 | +| 健壮性 | 5 个样本各 300 次截断/随机改字节(共 1500 次),ASan + UBSan | 0 次崩溃,823 次报告错误 | + +**覆盖的边界**:真实样本只含 64 位 ELF、64 位 PE(普通导入表)、64 位 Mach-O 的 `LC_LOAD_DYLIB`(thin 与 fat)。**没有真实样本**、只由 `plugin-logic` 里合成的最小样本覆盖的有:32 位 ELF/PE/Mach-O、PE 的延迟导入表、Mach-O 的 weak/reexport/upward/lazy 命令、`FAT_MAGIC_64`;大端 ELF 不读,返回错误。**LLVM 的 `llvm-readobj --needed-libs` 对 ELF、PE、Mach-O(含 fat)都能给出依赖**(实测),所以三平台 CI 可以用同一个工具做对照基准(Q10)。读文件用 `std::filesystem::path` 打开(不用窄字符串路径),保证 Windows 上非 ASCII 路径可读。这些路径对 Qt 的桌面 SDK 都不会出现,所以不影响本设计,但文档不声称它们经过真实文件验证。 + +设计约束:读取器只返回文件里的名字,**调用方只接受**不含 `/`、`\`、`..` 且在 SDK 库目录里确有同名文件的名字;整个文件读入内存,上限 1 GiB,超过报错。 + +### Q3 证据:`qt.conf` 的真实效果 + +- 只要程序旁有 `qt.conf`,`Prefix` 就变成该目录,**无法省略**(试了只写 `Qml2Imports`、写 `./qml`、以及加 `Data`/`Settings` 覆盖,`Prefix` 都是程序目录)。同时被改变的有 `Data`、`Settings`、`Libraries`、`Translations`(变为 `<程序目录>/translations`,恰是 `rules-qt` 的 `i18n.deploy_to` 默认值)。`Plugins` 保持默认;程序目录仍在 `libraryPaths` 里,所以 `<程序目录>/platforms` 照常被找到。 +- 没有 `qt.conf` 时,开发树里 Qt 的路径指向 SDK,打包树里默认的 QML 路径是 `<包根>/qml`(实测:把 `qml/` 放在包根就能找到),而 `deploy` 只能放在程序目录之下,到不了包根。 +- 有 `qt.conf` 时开发树与打包树**行为一致**(都只用部署出来的 `qml/`):一份不完整的部署(实测:只部署了两个模块)在 `mcpp run` 时就失败(`roots=0`),而不是开发时靠 SDK 兜底、打包后才失败。完整闭包部署后 `mcpp run` 通过(`roots=1`)。 +- 替代方案"把模块直接放到程序目录"(也实测可行,不需要 `qt.conf`)被否决:程序目录会被 `QtQuick/`、`QtQml/` 等污染,且开发树会兜底到 SDK,掩盖闭包缺口。 +- 副作用写进文档;`write_qt_conf = false` 关闭。 +- `qt.conf` 的内容不是固定文本:`Translations` 取 `qt.i18n.deploy_to`(默认 `translations`,非默认值时写出,否则 Qt 会在 `<程序目录>/translations` 找而丢失翻译)。 +- 项目已有自己的 `qt.conf`(包根或 `res/` 下有 `qt.conf`,或 qrc 里含 `/qt/etc/qt.conf`——Qt 的内嵌 `qt.conf` 优先于文件):不写、不部署,打印一条警告说明由项目负责 `Qml2Imports`。 +- macOS `.app` bundle 里 `Prefix = .` 的含义不同(`dist-apple` 把部署文件放到 `Contents/Resources`,Qt 在 bundle 里读 `Resources/qt.conf`),**推断**它与 `qml/` 同落在 `Resources` 下因而仍然成立,未验证,属于 Q7 的范围。 + +### Q4 证据:下限与 README 的列 + +- README 的 mcpp 下限列含义是"该成员的行为最早需要的版本"(`rules-qt` 写 2026.10.1.3,低于包下限 2026.10.30.1)。`rules-qml` 自己只用 `rules-qt` 已需要的东西(`mcpp.plugins.tool`,协议 15,mcpp#755)和更早的 `action::env`(协议 13,`src/build/hostprogram.cppm:441`)、`deploy`、`link_flag`,所以该列写 **2026.10.1.3**;整个包仍需要 2026.10.30.1(README 已有这句话)。 +- 验证到的范围:spike 的动作链(`action`、`roles`、`include_dir`)在 mcpp 2026.10.31.3、2026.11.7.2、2026.11.20.1 上 `mcpp run` 都得到 `roots=1`;`deploy`、`link_flag`、`qt.conf` 的端到端原型只在 2026.11.20.1 上跑过(这些 API 早已存在,现有规则在更低版本上使用)。包下限 2026.10.30.1 本身与 2026.10.1.3 本机都没有,**已验证的最低版本是 2026.10.31.3**,README 注明。CI 固定版本 `MCPP_BOOTSTRAP = 2026.11.7.1`。 + +### Q5:`qsb` 在 `xim:qt-addons` 里不能运行——是包的依赖没配齐,已提修复 PR(openxlings/xim-pkgindex#1262,已合入) + +**回答你的问题:是,Linux 条目没有声明运行时依赖。** `pkgs/q/qt-addons.lua` 的 Linux 只有 `runtime = { "xim:qt@6.11.1" }` 和 `build = { "xim:7zip" }`。`docs/10-adding-a-package.md` 说明:声明 `xim:glibc`(loader 提供者)才会让 xlings 在 `install()` 之后做 elfpatch,把每个可执行文件的解释器和每个 ELF 的 RPATH 改成生态的。`qt.lua` 与 `qt-base.lua` 声明了,所以它们的 `moc` 等是补丁过的;`qt-addons` 没声明,它的 220 个 ELF 文件原样保留。 + +**症状与证据**(本机,已安装的 `xim:qt-addons` 6.11.1): +- `readelf -l bin/qsb`:解释器是系统的 `/lib64/ld-linux-x86-64.so.2`;`readelf -d`:`RUNPATH $ORIGIN/../lib`(对照 `xim:qt` 的 `moc`:解释器是 `…/abi/linux-x86_64-glibc/ld-linux-x86-64.so.2`,RPATH 是一串生态的库目录)。 +- 在 mcpp 动作里运行:`libQt6Core.so.6: version 'Qt_6.11' not found`(回落到发行版自己的 Qt)。把 `xim:qt` 的 lib 放进 `LD_LIBRARY_PATH` 后改为 `GLIBC_2.43 not found, required by xim:glib`。 + +**我的第一版修复不够**:只加 `xim:glibc`。在隔离的 `XLINGS_HOME` 里真实安装后,`readelf` 显示 RPATH 只含 `qt-addons/lib`、`xim:qt/lib`、glibc 的 abi 目录,`qsb` 报 `libxkbcommon.so.0: cannot open shared object file`。结论:**补丁写入的 RPATH 是本配方自己声明的包的库目录,不含 `xim:qt` 的传递依赖**,所以本包的 ELF 直接用到的库要在这里再声明一遍。我在 PR 的注释里写明了这一点。 + +**修复(只改 Linux)**,范围由实测决定: +- 对载荷的 220 个 ELF 逐个读 `DT_NEEDED`,找出不在本包 `lib/` 也不在 `xim:qt` 的 `lib/` 里的名字,映射到生态里提供它们的包:`xim:glibc`(libc、libm、ld-linux)、`xim:gcc-runtime`(libstdc++、libgcc_s)、`xim:libglvnd`(libGL、libEGL)、`xim:libxkbcommon`、`xim:libX11`、`xim:libXext`、`xim:libXrandr`(FFmpeg 后端)、`xim:libdrm`、`xim:wayland`(客户端、服务端、egl)、`xim:zlib`、`xim:glib`。 +- `exports.runtime.libdirs = { "lib" }`;Linux 的 6.11.1 条目 `revision = 1`(与 `qt-base.lua` 同,使机器上未补丁的 revision 0 被替换);`install()` 写、`installed()` 查 runtime 标记,**只在 Linux**,Windows 与 macOS 已装的 128–160 MB 载荷不会被判为过期。 +- 生态里没有的、所以没声明的:`libbz2`、`libpulse`、`libbluetooth`、`libpcsclite`、`libspeechd`,以及 `libtiff.so.5`(`xim:libtiff` 是 `.so.6`)。它们只被 Qt Multimedia 的 FFmpeg 后端、Qt NFC、Qt Connectivity 的 `sdpscanner`、Qt TextToSpeech、TIFF 图像插件用。 + +**验证**(隔离 `XLINGS_HOME`,真实安装 `xim:qt` 再安装修改后的 `xim:qt-addons`):解释器是生态的,RPATH 列出所有声明的包;`bin/qsb --version` 输出 `qsb 6.11.1`;`qsb --qt6 -o t.frag.qsb t.frag` 编出 1072 字节的 `.qsb`;20 个可执行文件里 19 个能启动,只有 `libexec/sdpscanner` 仍因缺 `libbluetooth.so.3` 起不来(生态没有这个包)。仓库自己的测试:新增 2 个静态测试(在旧配方上失败、新配方上通过)和 3 个 verify 测试;`pytest -m "static or isolation"` 6866 通过,`tests/n/test_node.py` 的 2 个失败在改动前后都存在(与本改动无关)。 + +**PR 状态**(#1262):CI 全部通过——`ci_xpkg_test` 的静态与隔离测试、`install` 作业在 Linux、macOS、Windows 三平台、`runtime_revision_gate`、`required`。Linux 的 `install` 作业用修改后的配方真实安装了 `xim:qt-addons`(40 个包),并运行了仓库自己的依赖闭包检查(`dep-closure-check.sh`):220 个 ELF,报告的 host 独有 SONAME 恰是我列出的那 8 个(`libbz2`、`libpulse`、`libbluetooth`、`libpcsclite`、`libspeechd`、`libtiff.so.5`、两个 WebEngine 库),与我独立统计的结果一致。**合入状态:已由你合入**(2026-11-23 19:06 UTC,合入提交 `53ddeb3`)。合入前被分支保护的"需要评审"拦住,我没有绕过保护。 +**我在 PR 里如实写了一个评审点**:该脚本的规则 D2 是"解释器指向生态 loader 的载荷,host 独有的 SONAME 是硬失败"。本修复让 `qt-addons` 用上生态 loader,仍有这 8 个无提供者的 SONAME。脚本之所以只当备注通过,是因为它用解释器路径含 `/xpkgs/` 来识别"生态 loader",而补丁后的路径是 `/abi/linux-x86_64-glibc/ld-linux-…`,不含 `/xpkgs/`——所以 D2 对任何这样打补丁的载荷都不生效(脚本的潜在缺陷,本 PR 不改)。受影响的只有需要这些库的可选功能(Qt Multimedia 的 PulseAudio/FFmpeg 后端、NFC、`sdpscanner`、speech-dispatcher 插件、TIFF 插件);mcpp 构建的程序本来就跑在生态 loader 下,所以预期它们之前也找不到 host 的库,但我没有运行过这些功能,这是预期,不是测量。 + +**对本设计的影响**(修复已合入,待索引发布到使用者): +- 规则侧不变:`qsb` 动作仍用 `action::env` 给出 SDK 库目录,`qml-shaders` 仍先探测 `qsb --version` 再决定真实断言还是 `::notice::` 跳过。**修复合入并发布到索引后,探测会自动通过,门自动翻转,不需要改规则**;CI 用的是已发布的索引,旧载荷(revision 0)会因 revision 1 被替换。 +- 之后可以把探测门删掉,让 `qml-shaders` 直接断言(后续项,见 §11)。 +- G7 在门翻转之前仍然只有命令行级覆盖(§10.3 如实写明)。 + +### Q6 证据:AOT 的代价与收益 + +40 个中等大小的 `.qml`(每个约 25 行,含绑定与函数): + +| | 构建(冷) | 可执行文件 | 目标文件数 | +|---|---|---|---| +| `aot = true` | 10.3 s | 4.3 MB | 145 | +| `aot = false` | 4.2 s | 0.1 MB | 103 | + +即每个文件约 +0.15 s、+105 KB。同时 AOT 把 QML 语法错误提前到构建期(`Error compiling qml file: …: Unexpected token`,构建失败并点名文件与位置),不开则要到运行时才看到。Qt 自己的 CMake 默认也开。默认开,`aot = false` 是逃生口;`rules-qml` 文档写明代价。 + +### Q8 证据:模块内无需保活 + +- 在同一个包里加一个 `kind = "lib"` 目标,生成的对象进了 `libmodlib.a`,但同包的可执行文件仍然直接编译了这些对象(`nm` 在可执行文件里找到 `qml_register_types_…`,运行 `cpp=84 …` 通过)。 +- 用普通 gcc 复现了归档成员被丢弃的工具链事实(引用才保留;直接传目标文件也保留):这只发生在**别的包**的静态库里,而那是非目标(§1)。 +- 因此第 1 版的 `/qml/mcpp_qml.h` 与 `mcpp_qml_keep()` 取消;文档的"限制"写明做法。 + +### Q9:闭包缺口的根因在引擎;本 PR 的补库是文档化的临时补丁 + +**根因(读了引擎代码确认)**:`mcpp pack` 的闭包只从**程序本身**的导入表出发(`src/pack/pack.cppm` 的 `read_closure` 以 `in.object = program` 为唯一根)。`mcpp::deploy` 放到程序旁的插件库(manifest 里记为 `role: library`)不是闭包的根,所以只被 `dlopen` 的插件所依赖的库不会被带上。 + +**症状**: +- 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 号并在引擎支持后移除)。因此: + +1. **向 mcpp 提 issue**(你同意后已提交):**mcpp-community/mcpp#1011**,建议能力是"`mcpp pack` 把 `role: library` 的已部署文件也作为闭包的根"。正文见 §15。提交前搜索过,没有重复(相关的 #615、#634、#630、#701 都是已关闭的、讨论别的缺口)。 +2. **本 PR 带 `link_plugin_libs` 补丁,按规则 8 标注**(这是你的决定:先 workaround,用户与开发者层面无感,mcpp 修复后自动没问题): + - **无感**:`rules-qt`、`rules-qml` 都默认开,不需要任何配置;补丁失败(读不了某个文件、平台读取器报错)只是 `mcpp::warning`,不让构建失败。字段 `plugin_closure` 保留,只在"引擎缺口"一节里出现,用于金丝雀与应急关闭。 + - **标注**:仓库已有同类机制——`compat/` 单元的 `COMPATIBILITY UNIT` 头与 `check-compat-retirement.sh`(到期未删则 CI 失败)。引擎缺口没有固定日期,所以不用日期,而是仿照它做一个**同构的标记与检查**:补丁代码整块以下面的头开头,`.github/scripts/check-engine-gaps.sh` 列出所有这样的块,要求每块都有 `issue:` 与 `remove when:`,缺任何一项则 CI 失败(和 compat 检查一样防止"标记拼错导致清单为空":凡含 `ENGINE-GAP` 字样而不合格式的也报错): + + ``` + // ENGINE-GAP WORKAROUND + // gap: mcpp pack's runtime closure starts at the program; deployed libraries are not roots + // issue: mcpp#1011 + // remove when: the engine takes deployed role=library files into the closure + // note: idempotent: linking a library the engine also stages changes nothing + ``` + + `docs/rules-qt.md`、`docs/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`。 + - 对现有 `rules-qt` 使用者的影响:链接行多出几个 SDK 库(Linux 上 `XcbQpa`、`WaylandClient`、`EglFSDeviceIntegration` 及其传递依赖)。实测多链 22 个 Qt 库对启动无可测影响(25 次平均 31 ms 对 31 ms)。Windows 上只是多放几个 DLL 到程序旁。回归防线:现有的 `qt-consumer`、`qt-widgets-consumer`(三平台 CI 都跑)。macOS、Windows 的补丁路径本身没有实测(§9),但失败只降级为警告。 +3. 回归断言放在 `qml-consumer`:Linux 步骤断言打包目录含 `libQt6XcbQpa.so.6`;`plugin-logic` 固定 `plugin_closure=false` 与旧链接行逐字节一致、`true` 时旧链接行是新链接行的子序列。 + +### Q10:工具链与 LLVM(与 `rules-qt` 对齐;Linux 不做 LLVM) + +**`rules-qt` 现在怎么做(已读它的 fixture、文档与 CI)**:三个 `qt-*` fixture 都没有 `[toolchain]`;唯一的平台差异是 Linux 的两行 `[target.x86_64-linux-gnu]`、`[target.aarch64-linux-gnu]` 里的 `cxx_runtime = "toolchain-coupled"`(Qt 官方 Linux 构建用共享 libstdc++,所以在 Linux 上用 gcc;换成 libc++ 工具链时规则会警告)。Windows 与 macOS 不写任何覆盖,用引擎对该主机的默认工具链(你说明是 mcpp 的 LLVM clang);规则对编译器的唯一分支是 `mcpp::compiler() == "msvc"` 时加 `/Zc:__cplusplus` 与 `/permissive-`,Linux 加 `-fPIC`,macOS 用 `-F`。**`rules-qml` 的 fixture 逐字沿用这几行,不新增任何工具链选择**,`rules-qml` 本身也不读 `compiler()`(它生成的 C++ 与编译器无关,下面的验证证明了这一点)。按你的意见,**Linux 不支持 LLVM + Qt 就不管**:不为它在 CI 里加步骤。 + +**不能整链用 clang 构建(Linux)**:`xim:qt` 是 libstdc++ 的官方 Linux 构建。`mcpp build --toolchain llvm@23.1.3` 对现有 `qt-consumer` 就报 `error: a type is caught or cast across C++ runtimes [cxx-runtime-collision]`,`rules-qt` 也有对应警告(既有行为,不是本设计引入)。所以 Linux 上无法通过 mcpp 验证"clang 编译整个 QML 程序"。 + +**因此直接验证生成的 C++ 在 clang 下的可编译性与行为**(`spikes/llvm-check.sh`): + +| 验证 | LLVM 版本 | 结果 | +|---|---|---| +| 8 个生成文件(moc 输出、类型注册、qrc、6 个 AOT 单元含 `.js`、加载器)`-fsyntax-only`,libc++ | 20.1.7、22.1.8、23.1.3、23.1.6 | 全部通过 | +| 同上,`-O1 -c` 真实代码生成,libc++ | 20.1.7、23.1.6 | 全部通过 | +| 9 个源文件(再加 `main.cpp`)用 clang + **libstdc++ 16.1 头文件**编译,lld 链接,**运行** | 20.1.7、22.1.8、23.1.3、23.1.6 | 0 个编译失败,输出 `cpp=84 singleton=red js=42 nested=7 resource=hello-resource`,与 gcc 构建逐字相同 | + +**纠正我自己的错误**:我最初报告的"libstdc++ 一组"其实用的是 libc++。原因是 mcpp 的 `clang++.cfg` 无条件追加 `-nostdinc++ -stdlib=libc++ -isystem …/c++/v1`,所以 `clang++ -stdlib=libstdc++ …` 静默地仍用 libc++(`#error` 探针与链接时的 `std::__1::cout` 暴露了它)。正确做法是用 C 驱动 `clang -x c++ --no-default-config`,显式给出 gcc 的 libstdc++ 头文件与 glibc 头文件,并先用 `_LIBCPP_VERSION`/`__GLIBCXX__` 探针证明运行库(脚本里有)。上表第三行是在证明过运行库之后的结果;第一、二行确是 libc++。这个陷阱写进 fixture 的注释,以免 CI 脚本重蹈覆辙。 + +**结论**:QML 生成的 C++(含 `qmlcachegen` 的 AOT 代码)对 clang 20 到 23、两种 C++ 运行库在 Linux 上都是可移植的。 + +**未验证**:macOS 的 clang + `ld64.lld` + Qt 框架(libc++ 是该平台原生运行库,Qt 官方 macOS 构建也是 libc++,**预期**比 Linux 更顺,但无实测);Windows 的 clang(MSVC ABI 或 MinGW)与 Qt 官方的 MSVC 构建 DLL。两者由三平台 CI 的 fixture 用各自的默认工具链覆盖。 + +**对设计的影响**: +- CI 的依赖对照基准**各平台用其默认工具链自带的工具**(与"工具链对齐 `rules-qt`"一致,不要求 Linux 装 LLVM):Linux 用 `readelf -d`(gcc 工具链带 binutils,本机实测 180/180);macOS 与 Windows 用 `llvm-readobj --needed-libs`(该平台的默认工具链是 LLVM,自带;ELF、PE、Mach-O 含 fat 都实测可用)。`llvm-readobj` 的归一化:去掉 ELF 输出里的 `LoadName` 噪声行、Mach-O 的自身 `LC_ID_DYLIB`、fat 的重复项。这也避开了 Windows 上 `dumpbin` 需要 VS 环境的问题。 +- AOT 生效的断言用符号:Linux `nm -C <可执行文件> | grep -c QmlCacheGeneratedCode`,macOS `llvm-nm -C`(实测 llvm-nm:AOT 构建 27 个符号,关闭 AOT 为 0);Windows 的发布版 PE 没有符号表,改为断言生成文件与其目标文件存在。 +- **不**新增 Linux 的 clang CI 步骤(上面的对齐决定)。`llvm-check.sh` 与上面的结果只作为设计证据保留在 spikes 里;Windows、macOS 上生成代码与它们的默认 clang 的兼容性由三平台 fixture 本身覆盖。 + +## 3. 其他实测发现(进入了设计) + +| 发现 | 影响 | +|---|---| +| `qmlcachegen` 靠**输出文件名以 `qmlcache_loader.cpp` 结尾**进入加载器模式;其他名字会被当作编译单个 `.qml`,报 `Too many input files` 或 `No resource path for file` | 加载器输出必须命名为 `_qmlcache_loader.cpp`,写入 §6 的约束,并由 `plugin-logic` 固定 | +| `moc` 不带 `-I` 时丢弃 `QML.Element`(警告 `Potential QML registration macro was found, but no header containing it was included`);带 `-I/include -I/include/QtCore -I/include/QtQml` 即可,不需要单独加 `QtQmlIntegration` | `rules-qt` 加 `moc_includes` | +| `moc --output-json` 写 `.json`(`moc_backend.cpp.json`) | moc 动作多声明一个输出 | +| `qmltyperegistrar` 不带 `--foreign-types` 会警告基类找不到 | 传 `/metatypes/qt6_metatypes.json` | +| 生成的 `.cpp` 作为 `role = "source"` 动作的输出,自动被编译并链接 | 链路无需引擎改动 | +| 同一个 `.qml`/`.js` 的 AOT 单元、`qrc`、`qmldir` 缺一不可:`qmlcachegen` 需要 `-i `、`--resource `、`--resource-path`、`-I /qml`、`-I <生成根>` | §6 | +| 嵌套文件在 `qmldir` 里写相对路径(`Inner 1.0 sub/Inner.qml`),`.js` 用 `import "Util.js" as U` | G1 | +| 多链 22 个 Qt 库:启动 31 ms 对 31 ms(25 次平均) | 补库用链接而非自写加载代码 | +| 按版本化文件名(`libQt6X.so.6`、`libicudata.so.73`)`link_flag` 可行,不依赖 `.so` 符号链接 | §7 `link_plugin_libs` | +| 改一个 `.qml`,只重新生成该文件的 `*_qml.cpp` 与 `qrc_*.cpp` | 增量断言用修改时间(§10.3) | +| 引擎的闭包只从程序出发,已部署的插件库不是根(`pack.cppm`) | Q9 | +| `qmlcachegen` 在语法错误时让构建失败并点名位置 | Q6 的收益 | +| `deploy` 逐文件;Controls 闭包 1231 个文件,规划与 5 秒内构建完成 | 递归由规则枚举,规模可接受 | +| 多模块:`app.ui` 的 `qmldir` 不写 `depends app.core` 也能解析并运行(`sum=19`);跨模块的 C++ 继承(`Derived : Base`,分属两个模块)在 `.qmltypes` 里是 `prototype: "Base"`,注册器无"找不到基类"警告 | 不自动生成 `depends`;`depends`、`imports` 只作显式字段;`--foreign-types` 含其他模块的 JSON | +| C++ `QML_SINGLETON` 类可用(`Theme.radius` 得 9),不需要 `qmldir` 条目 | 单例只有 `pragma Singleton` 的 `.qml` 才写 `singleton` 行 | +| `lupdate -extensions qml,js` 能从 `.qml`、`.js` 提取 `qsTr` 的 3 个字符串 | G9 可行,加 fixture(§10.2) | +| 生成的 `.cpp` 是否在可执行文件里可观察:AOT 构建有 27 个 `QmlCacheGeneratedCode` 符号,关闭 AOT 为 0;`QT_LOGGING_RULES` 的调试日志观察不到 | AOT 断言用符号(§10.3) | +| `mcpp` 的 `clang++.cfg` 无条件追加 libc++ 头文件 | Q10 的陷阱 | +| 项目路径含空格或非 ASCII:gcc 模块依赖扫描失败,现有 `qt-consumer` 同样 | §1 的继承限制 | + +## 4. 架构 + +### 4.1 在家族中的位置 + +`.qml` 是一种 C++ 编译器读不懂、要经 Qt 生成器处理的输入,属 `rules` 家族,与 `rules-qt` 并列。成员文件 `rules/qml.cppm`: + +```toml +[features.plugins-binary] +sources = ["src/binary.cppm"] # 纯 std,不依赖 mcpp;`plugins-core` 之外的独立单元 + +[features.rules-qml] +sources = ["rules/qml.cppm"] +implies = ["rules-qt", "plugins-core", "plugins-binary"] +# 不写 rule_module 与 device_extensions:见下 +``` + +`rules-qt` 也改为 `implies = ["plugins-core", "plugins-binary"]`(Q9 的补库用到读取器)。 + +不认领 `.qml`、不写 `rule_module`:现有成员里凡是不认领扩展名的(`tools-*`、`dist-*`)都不写 `rule_module`,由消费者在依赖上写 `host-module = true`。`rule_module` 的作用是"认领扩展名并让引擎自动路由,同时隐含 `host-module`",而 `.qml` 不适合认领:一个 QML 模块需要 uri、版本、单例,`[build] sources` 表达不了,必须在 `build.mcpp` 里声明。实际行为:`rules-qml` 隐含 `rules-qt`,后者仍带自己的 `rule_module = "mcpp.rules.qt"` 并认领 `.ui/.qrc/.ts`,所以只启用 `rules-qml` 的项目里这三类文件照常被路由到 `rules-qt`;消费者显式写 `host-module = true` 是约定,写了也不会与隐含的重复冲突(`tests/qml-import-only` 固定这一点)。 + +```toml +[build-dependencies.mcpp] +plugins = { version = "0.27.0", features = ["rules-qml"], host-module = true } +``` + +### 4.2 与 `rules-qt` 的关系:一次调用 + +`qml::options` 内嵌 `qt::options`。`qml::compile` 先调 `qt::compile_ex`(§7),拿到 SDK、moc 单元与输出目录,再声明 QML 部分。用户只写一个调用,不会出现两次 moc。 + +```cpp +import std; +import mcpp; +import mcpp.rules.qml; + +int main() { + mcpp::rules::qml::options o; + o.qt.modules = { "Core", "Gui", "Qml", "Quick", "QuickControls2" }; + o.modules = {{ .uri = "Probe", .sources = { "qml/Probe/*.qml" } }}; + return mcpp::rules::qml::compile(o) ? 0 : 1; +} +``` + +### 4.3 代码组织 + +| 文件 | 内容 | +|---|---| +| `rules/qml.cppm` | 成员本体,约 700–900 行(`qt.cppm` 为 773 行) | +| `src/binary.cppm` | `mcpp.plugins.binary`:`needed(path) -> result`(`names`、`error`),约 130 行,原型见 spikes | +| `rules/qt.cppm` | §7 的加法式改动 | + +## 5. 公开 API + +```cpp +export module mcpp.rules.qml; +import mcpp.rules.qt; + +export namespace mcpp::rules::qml { + +struct qml_module { + std::string uri; // 必填;"Probe"、"com.acme.ui" + std::string version = "1.0"; // "主.次" + std::vector sources; // .qml/.js/.mjs,文件或 glob,相对包根 + std::string root; // 映射到模块根的目录;空 = sources 的公共目录 + std::vector resources; // 其他文件(图片等),相对 root 嵌入 + std::vector headers; // 注册类型的头文件;空 = moc 扫描到、含 QML_* 宏的头文件 + std::vector depends; // qmldir 的 `depends` 行(工具与加载依赖),显式给出,默认无 + std::vector imports; // qmldir 的 `import` 行(使用本模块的人自动 import),显式给出,默认无 + std::vector shaders; // .vert/.frag/.comp,经 qsb 嵌入为 shaders/.qsb + std::vector qsb_args = { "--qt6" }; + bool aot = true; // qmlcachegen;false 只嵌入源文件 + std::string prefix = "/qt/qml"; // 资源前缀 +}; + +struct options { + std::vector modules; + qt::options qt; // modules、deploy_plugins、root、i18n、plugin_closure……同 rules-qt(plugin_closure 默认 true,两处一致) + std::vector quick_plugins = { /* Qt Quick 所需插件目录,见 §8 */ }; // 与 qt.deploy_plugins 取并集;用户设值则替换这个默认 + std::vector imports; // 额外部署的运行时 QML 模块(动态加载的,如 "QtQuick.Controls.Material") + std::vector styles; // 非空时,optional import 只跟随列出的样式("Material");空 = 全部 + std::vector import_paths; // 额外的 QML 模块目录(含 /qmldir);-I 与部署来源 + bool deploy_imports = true; // 部署运行时模块及其库 + bool write_qt_conf = true; // 写 qt.conf 并部署到程序旁 + bool lint = false; + bool lint_warnings_are_errors = false; + std::string out_dir = std::string(mcpp::out_dir()); +}; + +bool compile(options opt); +std::string import_root(const options&); // /qml +} +``` + +### 5.1 `qml_module` 的取值规则 + +- `sources` 的每个 glob 在计划期展开并排序,调 `rerun_if_changed_glob`;**计划期读过内容的每个文件**(`.qml` 的 import 与 `pragma Singleton`、qrc 引用的文件、qmldir)逐个调 `rerun_if_changed`,不能只靠 glob(`rules/qt.cppm` 对读过内容的头文件也逐个声明)。SDK 里为闭包读的 `qmldir` 与 `.qml` 不逐个声明(成千上万个且随 SDK 版本整体变化),改为 `mcpp::fact("rules-qml.sdk", <根>)` 记录 SDK 根,换 SDK 即重新计划。 +- 资源路径 = `prefix + "/" + uri 的 '.' 换 '/' + "/" + 相对 root 的路径`(点分 uri 与嵌套文件已实测)。 +- `qmldir` 类型表:首字母大写的 `.qml` 写成 `Name 版本 相对路径`,含 `pragma Singleton` 的写成 `singleton Name 版本 相对路径`;小写开头的不进表。 +- `uri` 不能与 SDK 里已有的模块 uri 相同(报错并点名);`uri` 与 `.qml` 文件名要匹配 §8 的文法,文件名含非 ASCII 字符时警告(`qmlcachegen` 的 `@rsp` 在 Windows 上对此未验证)。 +- **qrc 与 qmldir 里的路径要做 XML 转义与正斜杠规范化**(`&`、`<`、`>`、`"`);路径一律用 `generic_string()`,Windows 的反斜杠不进入生成文件。 +- 同一个头文件被分给两个模块 → 报错并点名。无 C++ 类型的模块(只有 `.qml`)不跑注册器,已实测可用(多模块原型里的 `app.ui`)。 +- `headers` 默认:moc 扫描结果里含 `QML_ELEMENT`、`QML_NAMED_ELEMENT`、`QML_SINGLETON`、`QML_ANONYMOUS`、`QML_FOREIGN`、`QML_UNCREATABLE`、`QML_EXTENDED` 之一的头文件。多模块时用 `headers` 显式分配;未分配的 QML 头文件**报错**,不默默归第一个模块。 + +### 5.2 生成物命名 + +按 `sanitize(uri)`(`.`→`_`)命名,全部经 `rules-qt` 的 `claim()` 查重名: + +``` +/qml//qmldir +/qml//.qmltypes +/qml//.qrc +/qml//qrc_.cpp +/qml//_qmltyperegistrations.cpp +/qml//_<相对路径展平>.cpp 每个 .qml/.js/.mjs 一个(AOT) +/qml//_qmlcache_loader.cpp 名字必须以 qmlcache_loader.cpp 结尾(§3) +``` + +`/qml` 是所有模块共享的导入根,`qmlcachegen` 的 `-I` 指向它。 + +### 5.3 缺少 Quick 时 + +`qt.modules` 含 `Quick`/`QuickControls2` 而 SDK 没有(`xim:qt-base`):沿用"缺模块是警告",并追加"QML 需要 `xim:qt`;`xim:qt-base` 只含 QtQml 库,没有 Quick"。缺 `qmlcachegen`/`qmltyperegistrar`/`rcc` 同样是警告并跳过对应步骤,计划不失败(`emit build-database` 要在没有 SDK 的机器上能计划)。 + +### 5.4 目标平台与目标数 + +`mcpp::target_os()` 不是 linux、windows、macos 时(Android、iOS、WebAssembly):一条警告,不声明任何动作,返回 true。一个包有多个目标时的行为见 §1 非目标。 + +## 6. 每个模块的动作(步骤 1–6 的命令行已在真实引擎里跑通,含两个互相依赖的模块;步骤 7、8 未能运行) + +| 序 | 动作 id | 命令(`` = SDK 根) | 输入 | 输出 | +|---|---|---|---|---| +| 1 | `qt:moc:`(`rules-qt`,`moc_json`、`moc_includes` 为真) | `moc -o moc_.cpp --output-json --output-dep-file … -I/include -I/include/Qt…` | 头文件 | `moc_.cpp`、`moc_.cpp.json` | +| 2 | `qml:registrar:` | `qmltyperegistrar --generate-qmltypes=<…>.qmltypes --import-name= --major-version=M --minor-version=m --foreign-types=/metatypes/qt6core_metatypes.json,…,<其他模块 json> -o <…>_qmltyperegistrations.cpp <本模块各 json>` | 本模块 moc json | 注册 cpp、`.qmltypes` | +| 3 | (计划期写文件,`fs::write_if_changed`) | `qmldir`、`.qrc`(`绝对路径`,前缀 `/qt/qml/`;XML 转义,正斜杠) | — | — | +| 4 | `qml:rcc:` | `rcc --name -o qrc_.cpp` | qrc、qmldir、全部源文件 | `qrc_.cpp` | +| 5 | `qml:cachegen::` ×N | `qmlcachegen --bare --resource-path <资源路径> -I /qml -I /qml -i --resource -o <…>.cpp ` | 源文件、**所有模块**的 qmldir 与 `.qmltypes`、qrc | 每文件一个 cpp | +| 6 | `qml:cachegen::loader` | `qmlcachegen --resource-name qmlcache_ -o <…>_qmlcache_loader.cpp @`;rsp:`--resource`、``,随后每个资源路径一行 | rsp、qrc | loader cpp | +| 7 | `qml:qsb::` ×M | `qsb -o <…>.qsb `,`action::env` 给 SDK 库目录 | 着色器 | `.qsb`,加入模块 qrc | +| 8 | `qml:lint::` ×N(`lint = true`) | `qmllint -I /qml -I /qml `;**每个文件一个动作**,避免 Windows 约 32K 的命令行上限 | 源文件、全部 qmldir 与 `.qmltypes` | 检查结果(`lint_warnings_are_errors` 时加 `--max-warnings 0`) | + +要点: + +- **全部是 `role = "source"`**;输出是 `.cpp` 的自动进入编译(已验证)。 +- 第 5 步把**所有模块**的 `qmldir`、`.qmltypes` 声明为输入(保守),多模块互相 `import` 才解析得了;任一模块变化,依赖它的缓存单元重新生成。 +- 无 C++ 类型的模块跳过 1、2;`aot = false` 跳过 5、6。 +- Windows:`qmlcachegen`、`qmltyperegistrar` 在 `/bin/*.exe`;`rules-qt` 的 `detail::tool` 同时搜 `bin` 与 `libexec`。每个 `qmlcachegen` 与 `qmllint` 动作各处理一个文件,只有加载器读一个 `@rsp`(行数等于文件数,不受命令行上限影响)。 +- 第 4 步输入含 qrc 引用的全部文件(同 `rules-qt::qrc_files`):改一个 `.qml` 只重跑它的 `qmlcachegen` 与 `rcc`。 + +## 7. `rules-qt` 的加法式改动(0.27.0) + +| # | 改动 | 默认 | 原因 | +|---|---|---|---| +| a | `options::moc_json` | `false`,现有 moc 动作 argv 不变 | §6 第 2 步需要 JSON;为真时 moc 追加 `--output-json` 并声明第二个输出 | +| b | `options::moc_includes` | `false` | 实测:不带 `-I` moc 丢 `QML.Element`。为真时传 `/include` 与各链接模块的 `include/Qt` | +| c | `compile_ex(options) -> result` | `compile` 内部调它并返回 `result.ok` | `result` 含 SDK、`gen` 目录、moc 单元(头文件、cpp、json)、已链接模块,供 `qml::compile` 复用 | +| d | `i18n.extensions`、`i18n.qml_sources` | 现状不变 | `lupdate` 的 `-extensions` 加 `qml,js`,扫描 `.qml`/`.js`(G9) | +| e | 把 `tool`、`project_files`、`claim` 等辅助函数留在 `detail`,`qml.cppm` 通过 `qt::detail` 使用 | 无新公共面 | 同一个包同一个版本内的协作,不是契约(规则 5);`compile_ex` 同样只在注释里标明"供 `mcpp.rules.qml` 使用,不是契约" | +| f | `options::plugin_closure`、导出 `link_plugin_libs(files)` | **`true`**(Q9,无感、幂等、带标注与金丝雀) | 引擎缺口补丁:补全已部署插件的 SDK 库依赖。源码用 `ENGINE-GAP WORKAROUND` 标记,文档记 issue 号与移除条件(规则 8) | + +a–e 是新字段与新函数,默认行为不变;f 默认开,只**增加**链接输入,不改变任何现有输入。`plugin-logic` 固定:`moc_json`、`moc_includes`、`plugin_closure` 为假时,moc、uic、rcc、lrelease 的动作 argv 与链接行和改动前字节一致;`plugin_closure` 为真时,旧链接行是新链接行的子序列。 + +`Qml` 模块在 SDK 里的头文件模块 `QmlIntegration` 无库文件,对它只加 include 目录,不进"缺模块"警告。 + +### `link_plugin_libs(files)` + +对一组已部署的插件库: + +1. 对每个文件调 `binary::needed`; +2. 只保留名字满足"不含 `/`、`\`、`..`,且 SDK 库目录里确有该文件"的项,对保留项**递归**求闭包(SDK 库的依赖也要); +3. 平台处理: + - Linux:`link_flag` 依次给 `-Wl,--push-state,--no-as-needed`、`/lib/<名字>`、`-Wl,--pop-state`(用 `needed` 给出的完整文件名,如 `libQt6QuickLayouts.so.6`、`libicudata.so.73`,不依赖 `.so` 符号链接;已实测:27 个 Qt 库按版本化文件名链接,可执行文件的 `NEEDED` 含它们,`mcpp pack` 带上,`roots=1`;push/pop 包法在 `--as-needed` 默认的链接下实测保留); + - macOS:Mach-O 名字形如 `@rpath/QtFoo.framework/Versions/A/QtFoo`,取框架名映射到 `/lib/QtFoo.framework/QtFoo`,`link_flag` 给 `-Wl,-needed_library,<路径>`(`ld64.lld` 直接实测保留;未经 clang 驱动与 mcpp 实测); + - Windows:`mcpp::deploy(/bin/<名字>, ".")`(引擎本来就会放程序直接导入的 DLL,插件独有的要规则放); +4. 已链接的模块不重复;读取失败是警告并说明包可能不完整。来自 `import_paths`(非 SDK)的插件的非 SDK 依赖不处理,**警告一次**"该插件依赖 X,不在 SDK 里,需要项目自己保证",不再默默忽略。 +5. 整个函数与调用点在 `ENGINE-GAP WORKAROUND` 标记之下(Q9)。 + +## 8. 运行时 QML 模块的部署 + +闭包算法见 Q1。部署文件:闭包内每个模块目录 `/qml//` 下的文件(递归,不进入自带 `qmldir` 的子目录、`designer/`),部署到 `qml//`;排除 `*.qmltypes`、`*.prl`、`*.debug`、`*.pdb`;Windows 上 `xxd.dll` 与 `xx.dll` 并存时取 release(规则同 `rules-qt` 的 `deploy_plugins`)。对所有部署的插件库调 `link_plugin_libs`。 + +写 `qt.conf` 到 `/qml/qt.conf`: + +``` +[Paths] +Prefix = . +Qml2Imports = qml +Translations = # 仅在不是默认的 translations 时写出 +``` + +并 `deploy` 到 `.`。检测到项目自己的 `qt.conf` 时不写(Q3)。副作用见 Q3,写进 `docs/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`,不存在"未设置"问题。 + +动态加载而 `import` 里看不到的模块,用 `options::imports` 补;这是文本闭包与 `qmlimportscanner` 共有的限制。 + +**输入校验与未解析的 import**: + +- 模块 `uri` 必须匹配 `[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*`,否则报错;`.qml` 里的 `import` 语句同一文法,所以由 `uri` 推出的目录与 `deploy` 的目标路径不会含 `..` 或绝对路径(`deploy` 要求 `to` 不含 `..`)。 +- `import` 的 uri 既不在 SDK、`import_paths`,也不是自带模块时(例如它由 `main()` 里的 `qmlRegisterType` 在运行时注册),**不是错误也不是每次一条警告**:汇总成一条普通信息("N 个 import 未在 SDK 或 import_paths 找到,未部署:…"),因为运行时注册的类型是合法用法;只有以 `Qt` 开头的 uri 找不到时升级为 `mcpp::warning`(多半是 SDK 缺模块,如 `xim:qt-base` 没有 Quick)。 + +## 9. 三平台 + +| 项 | Linux | Windows | macOS | +|---|---|---|---| +| 工具位置 | `libexec/`(moc、qmlcachegen、qmltyperegistrar)、`bin/`(qsb、qmllint) | 均在 `bin/*.exe` | `libexec/`,同 Linux | +| 链接 | `-fPIC`,`libQt6*.so` 全路径 | `Qt6*.lib` | `-F/lib` + 框架二进制全路径 | +| QML 插件库 | `libqtquick2plugin.so` | `qtquick2plugin.dll`(排除 `d` 版) | `libqtquick2plugin.dylib` | +| 补库 | `link_flag`(**已验证**) | `deploy(dll, ".")`(推断) | `link_flag` 框架(推断) | +| 工具链(与 `rules-qt` 一致) | gcc;fixture 加 `cxx_runtime = "toolchain-coupled"`(Linux 的两行) | 引擎的默认工具链,不覆盖(未验证,由 CI 覆盖) | 引擎的默认工具链(LLVM clang,libc++ 原生),不覆盖(未验证,由 CI 覆盖) | +| 依赖读取器 | ELF,180 个真实文件对照 `readelf`;CI 同 | PE,mingw 样本对照;CI 上对 SDK 的 DLL 用 `llvm-readobj --needed-libs` 对照 | Mach-O,lld 样本对照;CI 上对 SDK 的 dylib 用 `llvm-readobj --needed-libs` 对照 | +| 防止未引用的库被链接器丢弃 | `--push-state,--no-as-needed`(**已验证**) | 不适用(DLL 直接 `deploy`) | `-needed_library`(`ld64.lld` 直接验证,未经 mcpp) | +| `qt.conf` | **已验证** | 推断:Windows 把 DLL 放程序旁,`Prefix=.` 即程序目录 | 推断;`Prefix` 在 macOS 的处理由 CI 确认 | +| 运行测试 | `QT_QPA_PLATFORM=offscreen`、`QT_QUICK_BACKEND=software` | 同 | 同 | +| 风险 | 低 | 中 | 中高(Mach-O 补库、`qt.conf`、clang 与框架无实测) | + +PE 与 Mach-O **读取器**的正确性已用真实构建的样本验证(样本由 mingw 与 LLVM 在 Linux 上生成,不是 Windows/macOS 上的 Qt 产物);**未验证**的是它们与 `mcpp pack`、`link_flag`、`deploy` 的集成,以及 Windows/macOS 上 Qt 官方二进制的真实依赖。每个推断项在 §10.3 有断言,失败时设计不变,改平台分支细节。 + +## 10. 测试方案 + +### 10.1 `tests/plugin-logic`(三平台都跑,不装不跑任何东西) + +| 用例 | 断言 | +|---|---| +| 资源路径 | 点分 uri、`root`、前缀 → 期望资源路径;嵌套文件 | +| `qmldir` 文本 | 类型、单例、显式 `depends`/`imports`、小写文件不入表;不自动生成 `depends`;字节级确定(连跑两次不重写) | +| qrc 文本 | XML 转义(路径含 `&`、`<`)、正斜杠、`alias` 相对路径 | +| `qt.conf` | 内容;`deploy_to` 非默认时写 `Translations`;包根有自己的 `qt.conf` 时不写并警告;`write_qt_conf=false` 不写 | +| uri 与路径校验 | 非法 uri(`a..b`、`../x`、数字开头)报错;与 SDK 模块同名的 uri 报错;同一头文件分给两个模块报错 | +| 目标平台 | `target_os` 为 android/ios/emscripten 时一条警告、无动作 | +| `rerun_if_changed` | 计划期读过的每个 `.qml`、qrc 引用的文件都声明了 | +| `quick_plugins` | 与 `qt.deploy_plugins` 取并集;设为空则不加;`qt.deploy_plugins` 的用户值不被覆盖 | +| 动作清单 | 给定模块 → 期望动作 id 集合;`aot=false` 少 5、6;无 C++ 类型少 1、2;`shaders` 多 7;`lint` 多 8 | +| 命令行 | 第 2、5、6 步 argv 与 §6 一致(含 `--foreign-types` 文件集合与顺序、加载器输出文件名以 `qmlcache_loader.cpp` 结尾) | +| 重名与归属 | 两模块同 `sanitize(uri)`;两个同名 `.qml` 映射到同一资源路径;多模块未分配的 QML 头文件 → 报错并点名 | +| 缺工具/缺 Quick | 警告含"xim:qt",计划不失败,不声明对应动作 | +| 文本闭包 | 构造假 SDK 的 `qml/` 树:`default import`、`optional import … auto`、`depends`、目录里 `.qml` 的 import(含嵌套目录且不进入自带 qmldir 的子目录)、循环 import、注释与字符串里的 `import` 不算、`styles` 限制、自带模块 uri 不当运行时模块 | +| 部署清单 | 排除 `.qmltypes`、`.prl`、`designer/`;Windows 调试版去重 | +| `binary::needed`:合成样本 | 测试里用函数**在内存/临时文件中构造**最小的 ELF(32/64)、PE(32/64,含延迟导入)、Mach-O(thin、fat、`LC_ID_DYLIB` 不返回);不提交二进制样本 | +| `binary::needed`:截断扫描 | 对每个合成样本的**每个前缀长度**与一组**固定种子**的单字节改动调用,断言返回结果或错误、不崩溃(普通构建)。sanitizer 版不进 CI(评审指出模块单元与 sanitizer 驱动的组合不合 CI 的约定),1500 个输入的 ASan+UBSan 结果记录在 Q2,由原型复现 | +| `link_plugin_libs` | 假 SDK 库目录与假插件:名字过滤(`../x`、含 `/`)、递归闭包、已链接模块不重复、各平台的产出(ELF:push/pop 包住的 `link_flag`;Mach-O:`-needed_library`;PE:`deploy`)、非 SDK 依赖只警告一次 | +| `rules-qt` 不变性 | `moc_json`、`moc_includes` 为假时,现有 moc、uic、rcc、lrelease 动作 argv 与改动前一致;`plugin_closure=false` 与旧行为一致 | + +### 10.2 Fixture(每个一个 `tests//`,结构同现有 `tests/qt-*`) + +| fixture | 平台 | 内容 | 目的 | +|---|---|---|---| +| `qml-consumer` | 三平台 | 模块 `Probe`:`Main.qml`、`pragma Singleton` 的 `.qml`、C++ `QML_SINGLETON`、`QML_ELEMENT` 的 C++ 类(带 `Q_INVOKABLE`)、`.js`、嵌套 `.qml`、一个资源文件;`QtQuick` + `QtQuick.Controls`;一个带 `qsTr` 的 `.qml` 与 `.ts`(`i18n.update_sources = true`,断言 `.ts` 含该字符串,并有 `.qm` 部署);程序 offscreen 加载 `loadFromModule`,断言各项属性值 | G1–G4、G6、G9,同 `qml-feat` 原型 | +| `qml-modules` | 三平台 | `app.core`(C++ 类型 `Base`、`Card.qml`)与 `app.ui`(点分 uri,`C++ Derived : Base`,QML 里实例化 `Derived` 并读继承来的 `Base` 属性、使用 `Card`);一个无 C++ 类型的模块 | 多模块、`foreign-types`、缓存依赖(同 `multi-module` 原型,`sum=19`) | +| `qml-deploy` | 三平台 | `import` 了 `QtQuick.Layouts`、`QtQuick.Controls.Material`、`Qt.labs.*` 之类,不链接对应库;`mcpp pack --format dir` 后脱离 SDK 运行 | G5、G11 | +| `qml-import-only` | 三平台 | 只为 import `mcpp.rules.qml`,无 `build.mcpp`、无 QML | 同 `qt-import-only`:不报缺 SDK | +| `qml-shaders` | 仅 Linux,带探测门 | 编一个 `.frag`,断言 `.qsb` 被嵌入并被 `ShaderEffect` 加载 | G7 | + +**工具链**:fixture 的 `mcpp.toml` 沿用 `qt-consumer` 的写法:`[target.'cfg(any(windows, linux, macos))'.xlings.workspace] "xim:qt" = "6.11.1"`(QML 要 `xim:qt`,不是 `xim:qt-base`),Linux 的 `[target.x86_64-linux-gnu]` 与 `[target.aarch64-linux-gnu]` 两行 `cxx_runtime = "toolchain-coupled"`,没有 `[toolchain]`。 + +**变体**:`qml-consumer` 的脚本用环境变量让 `build.mcpp` 构建三个变体,各自断言一个行为:`noaot`(`aot = false`:无 `*_qml.cpp`、无 `QmlCacheGeneratedCode` 符号,程序仍能运行)、`styles`(`styles = {"Basic"}`:打包目录里没有 `QtQuick/Controls/Material`)、`noconf`(`write_qt_conf = false`:包里无 `qt.conf`)。`import_paths` 与 `imports` 由 `qml-deploy` 覆盖(`imports` 部署一个只在 C++ 里动态加载的模块)。 + +程序在 `main` 里缺省设置 `QT_QPA_PLATFORM=offscreen`、`QT_QUICK_BACKEND=software`,用具体属性值断言并打印固定格式的行;加载失败时非零退出并打印引擎的警告。 + +### 10.3 CI 断言(`.github/scripts/check-deps-and-qt.sh` 增加函数,三个 job 各接入) + +通用: + +1. `qml-consumer`:`mcpp build` + `mcpp run`,输出匹配固定行。 +2. AOT 生效:每个 `.qml`/`.js` 有对应生成的 `*.cpp` 与 `*_qmlcache_loader.cpp`;Linux、macOS 上 `llvm-nm -C <可执行文件> | grep -c QmlCacheGeneratedCode` 大于 0(原型实测 AOT 为 27,关闭为 0);Windows 的发布版没有符号表,改为断言生成的 `.cpp` 与对应目标文件存在。(评审指出"字符串存在"证明不了 AOT 被使用,符号才是。) +3. 增量:改一个 `.qml` 重建,用**生成文件的修改时间**断言(不读构建日志,其格式不是契约):该文件的 `*_qml.cpp` 与 `qrc_*.cpp` 变了,其余 `*_qml.cpp`、`*_qmltyperegistrations.cpp`、加载器没变(原型实测正是如此)。改文件前 `sleep 2.2`,以覆盖 HFS+(1 秒)与 NTFS/FAT(2 秒)的时间戳粒度。 +4. `qml-modules`:同 1,另在**运行时**断言继承:程序实例化 `app.ui` 的 `Derived` 并读继承来的 `Base` 属性,值正确(评审指出 `.qmltypes` 文本格式不是契约,所以不断言文本)。 +5. `qml-import-only`:构建,输出不含 "no Qt SDK"。 +6. `qml-deploy`: + - **scanner 对照**:运行 `qmlimportscanner -rootPath <模块目录> -importPath /qml`,取 JSON 中 `type=module` 的 `relativePath` 集合 S;断言打包目录 `bin/qml/

/qmldir` 对每个 `p ∈ S` 都存在(允许多,不允许少;`styles` 非空时只对非样式模块断言)。 + - **打包闭包的静态分析**:对包内每个 ELF/PE/Mach-O 读依赖(Linux `readelf -d`,macOS 与 Windows `llvm-readobj --needed-libs`,归一化见 Q10),断言其依赖里凡是 SDK 提供的库,都在 `lib/`(Linux、macOS)或程序旁(Windows)。 + - **脱离 SDK 运行**:把**SDK 根目录改名挪走**再运行打包出来的程序,结束后改回(评审指出 `env -i` 挡不住写进 RUNPATH/rpath 的绝对路径,只有 SDK 真的不在才能证明闭包完整)。Linux 另需把程序的解释器指向生态 loader(`patchelf --set-interpreter`,做法见 spike),因为包的 libc 来自生态;Windows、macOS 直接运行。程序输出固定行即通过;任何一步在某平台无法执行时,降级为上一条的静态断言并打印 `::notice::`。 + - `bin/qt.conf` 存在且内容为 §8。 +7. 读取器对照(各平台用默认工具链自带的工具,见上):对 SDK 里的全部插件库与库,`binary::needed` 与它的依赖集合逐个一致(Linux 用 `readelf` 实测 180/180)。 +8. `check-engine-gaps.sh`:每个 `ENGINE-GAP` 块都有 `issue:` 与 `remove when:`(Q9)。 +9. Q9:`qml-consumer` 的 Linux 步骤断言打包目录含 `libQt6XcbQpa.so.6`;`qt-widgets-consumer` 的 Linux 步骤同样断言(现有 `rules-qt` 使用者的缺口因默认开而补上);金丝雀见 Q9(`qml-deploy` 脚本里,设 `plugin_closure=false` 再打包,已无缺库则打印 `NOTICE … remove the plugin_closure workaround`,否则打印 `ok: the engine gap still exists`,两种都成功退出)。 + +平台特有: + +- Linux:包里存在 `libQt6QuickLayouts.so.6`(原型里丢失的那个)。 +- Windows:`target/dist` 里存在 `Qt6QuickLayouts.dll` 与 `qml/QtQuick/Layouts/qquicklayoutsplugin.dll`;从构建目录直接运行也能找到(同 `qt-widgets-consumer`)。 +- macOS:包里存在 `qml/QtQuick/Layouts/libqquicklayoutsplugin.dylib`,`llvm-readobj --needed-libs` 看到的框架依赖都已满足。 + +`qml-shaders`(仅 Linux):先 `qsb --version` 在规则会使用的同一环境下探测;失败则打印 `::notice::SKIP qml-shaders: <原因>` 并成功退出,通过则做真实断言。G7 因此在 CI 中是"argv 已固定、真实运行带门",评审指出的"永远不会失败"在 `xim:qt-addons` 修复前成立,写进文档的限制。 + +### 10.4 CI 接入与耗时 + +- Linux `consumers` job:5 个 fixture(`xim:qt` 约 187 MB,job 已为 `qt-widgets-consumer` 下载;新 fixture 声明同一版本 `6.11.1` 即命中缓存)。`qml-shaders` 需要 `xim:qt-addons`(约 128 MB),只在 Linux 下载,探测失败时下载也已发生,所以该 fixture 放在 job 最后一步。 +- `rules-cross-platform` job 的 macOS、Windows:前 4 个 fixture,接在现有 `qt-*` 步骤之后。 +- `lint = true` 与 `qmllint`:Linux 上一个子用例,对故意写错的文件断言点名;macOS、Windows 只断言动作声明(`plugin-logic`)。`qmllint` 在 `xim:qt` 的 `bin/`,实测存在;未在本机运行过,是第一次 CI 才会验证的项。 +- 耗时**未测量**:原型一次构建约 5–10 秒,每个 fixture 还要打包、运行、读依赖;主要成本是 SDK 下载,缓存键含 `tests/*/mcpp.toml`,新 fixture 声明同一版本即命中。落地后以第一次 CI 的实际耗时为准,必要时调整 job 的 `timeout-minutes`。 + +## 11. 文件变更清单 + +| 文件 | 变更 | +|---|---| +| `rules/qml.cppm` | 新增 | +| `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` | +| `.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 | +| `tests/qml-consumer`、`qml-modules`、`qml-deploy`、`qml-import-only`、`qml-shaders` | §10.2 | +| `.github/scripts/check-deps-and-qt.sh` | 新函数,**以及**文件末尾的 `usage` 行和 `case` 分发(现有脚本两处都要改) | +| `.github/workflows/ci.yml` | §10.3、§10.4 | + +后续项(不在本 PR):`dist-apple` bundle 的 `Contents/Resources/qml`;`qmltc`;依赖包提供 QML 模块的贡献机制;`xim:qt-addons` 修复(xim-pkgindex#1262)发布后撤掉 `qml-shaders` 的探测门。 + +## 12. 单 PR 内的提交顺序 + +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` 的"引擎缺口"一节随它提交,便于你单独审这一处行为变更)。 +4. `rules-qml` 的模块链路(§6),及其 `plugin-logic` 用例。 +5. 部署:文本闭包、`qt.conf`、补库(§8)及用例。 +6. `qsb`、`qmllint`、`lupdate` 扩展。 +7. fixture 与 CI(含 `check-engine-gaps.sh` 接入)。 +8. 文档、README、版本号。 + +## 13. 风险与残余未知 + +| 风险 | 状态 | +|---|---| +| Windows、macOS 上补库、`qt.conf`、PE/Mach-O 与 `mcpp pack` 的集成 | 未验证;每项有 CI 断言;读取器本身已验证 | +| `deploy_plugins` 里 Quick 所需目录(`xcbglintegrations` 等) | 推断,无法在无显示环境验证 | +| Q9 的运行层面失败(缺 `libQt6XcbQpa` 的真实 X11 启动) | 只在静态依赖层面确认 | +| `plugin_closure` 是引擎缺口的补丁,违反"不打补丁"的字面要求 | 按规则 8 标注(issue、文档、`ENGINE-GAP WORKAROUND` 标记、移除条件);默认开且无感;幂等;金丝雀在引擎修好后自动提示;失败只降级为警告 | +| `rules-qt` 默认开补丁后,macOS/Windows 的补丁路径没有实测,却影响现有使用者 | 现有 `qt-consumer`、`qt-widgets-consumer` 在三平台 CI 都跑,构成回归防线;读取失败只是警告;`plugin_closure = false` 可应急关闭 | +| 文本闭包要读 SDK 里成千上万个 `.qml` 文件的 `import`(计划期) | 原型:Controls 闭包 1231 个文件、全部 40 个顶层模块的闭包都在秒级;落地时若计划变慢,改为只读目录里 `.qml` 的前若干行或缓存 | +| 测试里"脱离 SDK 运行"在 Windows/macOS 的做法 | 未验证(Windows 去掉 `PATH` 里的 SDK;macOS 去掉框架路径),失败时降级为静态依赖断言 | +| 文本闭包与 scanner 在 Qt 其他版本上的一致性 | 只验证了 6.11.1;CI 的 scanner 对照会在升级 Qt 时报警 | +| 动态加载的模块(`Qt.createComponent` 的字符串、运行时拼的 import) | 与 scanner 同样看不到;`options::imports` 补 | +| `qmlcachegen` 的参数随 Qt 版本变化(`--direct-calls`、`--module-id` 等 CMake 里的可选参数我们没传) | 只用了在 6.11.1 实测可用的最小集;升级 Qt 时由 fixture 发现 | +| `xim:qt-addons` 的 `qsb` 不可运行 | 根因已查明并提 PR(xim-pkgindex#1262);合入并发布前由探测门保护,发布后自动翻转 | +| 读取器读不可信文件 | 1500 次模糊输入无崩溃,名字由调用方过滤,大小上限 1 GiB | +| macOS、Windows 的 clang 本身(Q10) | 无法验证;与 `rules-qt` 一致地不覆盖工具链,由三平台 CI 的 fixture 用各自的默认工具链覆盖;Linux 上生成代码对 clang 的可移植性已验证(4 个 LLVM 版本,仅作证据) | +| `-needed_library` 经 clang 驱动与 mcpp 的行为 | `ld64.lld` 直接实测,未经驱动;CI 的静态闭包断言兜底 | +| 一个包多个目标、项目路径含空格/非 ASCII | 已写入非目标与限制,不处理 | +| 约 30 个库的链接在 Windows/macOS 上的影响 | Linux 上启动时间无可测差异;其他平台未测,因为 Windows 走 `deploy` 而非链接 | +| 25 次平均 31 ms 对 31 ms 只在一个平台、无方差 | 结论只是"无可测影响",不据此宣称零代价 | + +## 14. xlings 生态侧(不阻塞本 PR) + +- `xim:qt`:不需要新增工具。 +- **`xim:qt-addons`**:Linux 条目没有声明运行时依赖,所以可执行文件没被 elfpatch,`qsb` 等起不来。**已提修复 PR openxlings/xim-pkgindex#1262**(Q5);仍缺的 `libbz2`、`libpulse`、`libbluetooth`、`libpcsclite`、`libspeechd` 与 `libtiff.so.5` 需要生态先有对应的包,是后续项。 +- Qt Quick 在 Linux 需要 GL 驱动库:slint-m 已遇到同一问题(libglvnd 只是分发器),其解是依赖 `compat.glx-runtime`。建议在 `pkgs/q/qt.lua` 的 linux 运行时依赖里评估同样加入;本 PR 的 offscreen + software 渲染不依赖它。 +- `xim:qt-base` 只含 QtQml 库这一事实,已在 `rules-qml` 的警告与文档里说明。 + +## 15. 向 mcpp 提的 issue(已提交:mcpp-community/mcpp#1011) + +标题:`mcpp pack: take the dependencies of deployed shared libraries into the runtime closure`。正文要点: + +- **现象**:`mcpp::deploy` 放到程序旁的共享库(`mcpp-package.json` 里 `role: library`)自己依赖的库不会被 `mcpp pack` 带上;闭包读取以程序本身为唯一根(`src/pack/pack.cppm`)。 +- **复现**(Linux x86_64,`xim:qt` 6.11.1,mcpp 2026.11.20.1):部署 `qml/QtQuick/Layouts/libqquicklayoutsplugin.so` 与 `plugins/platforms/*.so` 后 `mcpp pack --format dir`,包里没有 `libQt6QuickLayouts.so.6`、`libQt6XcbQpa.so.6`、`libQt6WaylandClient.so.6`、`libQt6EglFSDeviceIntegration.so.6`;对照:程序自己按全路径链接 `libQt6QuickLayouts.so` 后就被带上。 +- **期望**:已部署的 `role: library` 文件也是闭包的根,或提供 `mcpp::runtime_closure_root(file)` 之类的指令。 +- **现在的绕过**:`plugin_closure`(幂等,源码有标记,CI 有金丝雀)。 +- 明确写了"xcb 平台插件在真实显示上加载失败是推断,没有观察到"。 + +## 16. 独立评审的处理 + +一次不受我先入为主影响的独立评审通读了本文与仓库规则,给出下列意见。我逐条核对了代码或做了实验,结论如下("采纳"指已改入正文)。 + +| # | 意见(摘要) | 核实 | 处理 | +|---|---|---|---| +| 1 | 闭包补丁违反 `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) | +| 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 的范围,标明推断 | +| S3 | `qmllint` 多文件超 Windows 命令行;非 ASCII 路径 | 合理 | 采纳:`qmllint` 每文件一个动作;加载器 rsp 的行数等于文件数;非 ASCII 文件名警告 | +| S4 | qrc 未做 XML 转义 | 合理 | 采纳(§5.1、§10.1) | +| S5 | `std::ifstream` 窄字符串路径在 Windows 上读不了非 ASCII | 合理 | 采纳(Q2):用 `std::filesystem::path` 打开 | +| S6 | 31 ms 对 31 ms 只在一个平台、无方差 | 属实 | 采纳(§13):只宣称"无可测影响" | +| 缺 | 多目标/`kind=lib` 的包;交叉目标;`qtquickcontrols2.conf`;无 C++ 类型模块;uri 与 SDK 模块同名;`depends` 含糊;两模块共用头文件;`import_paths` 的非 SDK 依赖;`qmlformat`、`.qmllint.ini`、`.js` 的 `.import` | 合理 | 采纳(§1 非目标、§5.1、§5.4、§7、Q-证据);其中一个包多目标实测确有影响(两个目标都编译生成的对象),写成限制 | diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/README.md b/.agents/docs/2026-11-24-rules-qml-spikes/README.md new file mode 100644 index 0000000..02f8568 --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/README.md @@ -0,0 +1,14 @@ +# rules-qml spikes (2026-11-24) + +Throwaway prototypes behind `../2026-11-24-rules-qml-design.md`. They are evidence, not the implementation: +the implementation is C++23 modules under `rules/` and `src/`. Section numbers refer to the design document. + +| file | what it proves | how it was run | +|---|---|---| +| `closure.py` | the runtime-module closure (design Q1, §8) equals `qmlimportscanner`'s on 4 samples, including all 40 top-level Qt modules (24/27/15/49 modules, both difference sets empty) | `python3 -I closure.py

` | +| `binary.hpp`, `needed_main.cpp` | `needed(path)` for ELF/PE/Mach-O (design Q2, §7): 180/180 SDK ELF files identical to `readelf -d`; mingw-built PE and lld-built Mach-O (thin and fat) identical to `objdump -p` / `llvm-otool -L`; 1500 truncated or corrupted inputs, no crash under ASan+UBSan | `g++ -std=c++23 -fsanitize=address,undefined needed_main.cpp -o needed` | +| `module-pipeline.build.mcpp`, `module-pipeline.Main.qml` | the per-module action chain (design §6 steps 1-6) for one dotted uri with a C++ type, a singleton, a `.js`, a nested file and a resource: `cpp=84 singleton=red js=42 nested=7 resource=hello-resource`; with a C++ `QML_SINGLETON` added: `theme=9` | a package whose `build.mcpp` is this file, `src/backend.h` with `QML_ELEMENT`, `qml/ui/*`, `xim:qt` 6.11.1, `mcpp run` | +| `multi-module.build.mcpp`, `multi-module.Main.qml` | two modules (`app.core` with C++ types and `Card.qml`, `app.ui` importing it); `--foreign-types` across modules gives `prototype: "Base"` for a class derived across modules; `sum=19`; the qmldir needs no `depends` line | same as above, ASCII path without spaces | +| `llvm-check.sh` | the generated sources compile with clang (20.1.7, 22.1.8, 23.1.3, 23.1.6) against the real libstdc++, link with lld and run with the same output as gcc | see the pitfall in the script header | + +Not covered by any spike: Windows, macOS, `qsb` (not runnable from `xim:qt-addons`), `qmllint`, `qt.conf` under a macOS bundle. diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/binary.hpp b/.agents/docs/2026-11-24-rules-qml-spikes/binary.hpp new file mode 100644 index 0000000..c5579eb --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/binary.hpp @@ -0,0 +1,120 @@ +// Prototype of mcpp.plugins.binary::needed -- std only. Returns the library names a +// shared library or program names as dependencies, or an error string. +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +namespace binary { +struct result { std::vector names; std::string error; bool ok() const { return error.empty(); } }; +namespace detail { +struct view { + const unsigned char* p; std::size_t n; + bool in(std::uint64_t off, std::uint64_t len) const { return off <= n && len <= n - off; } + template bool get(std::uint64_t off, T& out, bool big = false) const { + if (!in(off, sizeof(T))) return false; + unsigned char b[sizeof(T)]; std::memcpy(b, p + off, sizeof(T)); + if (big) std::reverse(b, b + sizeof(T)); + std::memcpy(&out, b, sizeof(T)); return true; // host is little-endian (x86-64, arm64) + } + bool cstr(std::uint64_t off, std::string& out, std::size_t max = 4096) const { + out.clear(); + for (std::size_t i = 0; i < max; ++i) { if (!in(off + i, 1)) return false; char c = char(p[off + i]); if (!c) return true; out += c; } + return false; + } +}; +inline void add(result& r, std::string s) { if (!s.empty() && std::ranges::find(r.names, s) == r.names.end()) r.names.push_back(std::move(s)); } + +inline result elf(const view& v) { + result r; const bool is64 = v.p[4] == 2; + if (v.p[5] != 1) { r.error = "big-endian ELF is not read"; return r; } + std::uint64_t phoff; std::uint16_t phentsize, phnum; + if (is64) { std::uint64_t o; if (!v.get(32, o)) { r.error = "truncated ELF header"; return r; } phoff = o; v.get(54, phentsize); v.get(56, phnum); } + else { std::uint32_t o; if (!v.get(28, o)) { r.error = "truncated ELF header"; return r; } phoff = o; v.get(42, phentsize); v.get(44, phnum); } + struct seg { std::uint64_t vaddr, off, filesz; }; + std::vector loads; std::uint64_t dynoff = 0, dynsz = 0; bool haveDyn = false; + for (unsigned i = 0; i < phnum; ++i) { + const std::uint64_t at = phoff + std::uint64_t(i) * phentsize; std::uint32_t type; + if (!v.get(at, type)) { r.error = "truncated program headers"; return r; } + std::uint64_t off, vaddr, filesz; + if (is64) { std::uint64_t a, b, c; if (!v.get(at + 8, a) || !v.get(at + 16, b) || !v.get(at + 32, c)) { r.error = "truncated program headers"; return r; } off = a; vaddr = b; filesz = c; } + else { std::uint32_t a, b, c; if (!v.get(at + 4, a) || !v.get(at + 8, b) || !v.get(at + 16, c)) { r.error = "truncated program headers"; return r; } off = a; vaddr = b; filesz = c; } + if (type == 1) loads.push_back({vaddr, off, filesz}); + if (type == 2) { dynoff = off; dynsz = filesz; haveDyn = true; } + } + if (!haveDyn) return r; // statically linked: no dependencies + auto to_off = [&](std::uint64_t va, std::uint64_t& out) { for (auto& s : loads) if (va >= s.vaddr && va < s.vaddr + s.filesz) { out = va - s.vaddr + s.off; return true; } return false; }; + std::uint64_t strtab = 0; std::vector needed; + const std::size_t esz = is64 ? 16 : 8; + for (std::uint64_t o = 0; o + esz <= dynsz; o += esz) { + std::uint64_t tag, val; + if (is64) { if (!v.get(dynoff + o, tag) || !v.get(dynoff + o + 8, val)) { r.error = "truncated dynamic section"; return r; } } + else { std::uint32_t a, b; if (!v.get(dynoff + o, a) || !v.get(dynoff + o + 4, b)) { r.error = "truncated dynamic section"; return r; } tag = a; val = b; } + if (tag == 0) break; if (tag == 1) needed.push_back(val); if (tag == 5) strtab = val; + } + std::uint64_t soff; if (needed.empty()) return r; + if (!to_off(strtab, soff)) { r.error = "dynamic string table is outside the file"; return r; } + for (auto n : needed) { std::string s; if (!v.cstr(soff + n, s)) { r.error = "bad dependency name"; return r; } add(r, s); } + return r; +} +inline result pe(const view& v) { + result r; std::uint32_t lfanew, sig; + if (!v.get(0x3c, lfanew) || !v.get(lfanew, sig) || sig != 0x00004550) { r.error = "not a PE file"; return r; } + std::uint16_t nsec, optsz, magic; + if (!v.get(lfanew + 6, nsec) || !v.get(lfanew + 20, optsz) || !v.get(lfanew + 24, magic)) { r.error = "truncated PE header"; return r; } + const std::uint64_t opt = lfanew + 24, dirs = opt + (magic == 0x20b ? 112 : 96); + if (magic != 0x20b && magic != 0x10b) { r.error = "unknown PE optional header"; return r; } + struct sec { std::uint32_t va, vsize, raw, rawsz; }; std::vector secs; const std::uint64_t st = opt + optsz; + for (unsigned i = 0; i < nsec; ++i) { sec s; const std::uint64_t a = st + std::uint64_t(i) * 40; + if (!v.get(a + 8, s.vsize) || !v.get(a + 12, s.va) || !v.get(a + 16, s.rawsz) || !v.get(a + 20, s.raw)) { r.error = "truncated section table"; return r; } secs.push_back(s); } + auto rva = [&](std::uint32_t x, std::uint64_t& out) { for (auto& s : secs) { const std::uint32_t len = std::max(s.vsize, s.rawsz); if (x >= s.va && x - s.va < len) { out = std::uint64_t(x - s.va) + s.raw; return true; } } return false; }; + auto walk = [&](unsigned index, std::size_t entry, std::size_t nameAt, bool delay) -> bool { + std::uint32_t dva, dsz; if (!v.get(dirs + std::uint64_t(index) * 8, dva) || !v.get(dirs + std::uint64_t(index) * 8 + 4, dsz)) return true; // no such directory + if (!dva) return true; std::uint64_t base; if (!rva(dva, base)) return false; + for (std::uint64_t o = 0;; o += entry) { + std::uint32_t nm = 0, probe = 0; if (!v.get(base + o + nameAt, nm) || !v.get(base + o, probe)) return false; + if (!nm && (!delay ? true : !probe)) break; if (!nm) break; + std::uint64_t so; std::string s; if (!rva(nm, so) || !v.cstr(so, s, 256)) return false; add(r, s); + } return true; }; + if (!walk(1, 20, 12, false) || !walk(13, 32, 4, true)) r.error = "import table is outside the file"; + return r; +} +inline result macho_one(const view& v, std::uint64_t base) { + result r; std::uint32_t magic; if (!v.get(base, magic)) { r.error = "truncated Mach-O header"; return r; } + const bool is64 = magic == 0xfeedfacf; if (!is64 && magic != 0xfeedface) { r.error = "not a little-endian Mach-O"; return r; } + std::uint32_t ncmds; if (!v.get(base + 16, ncmds)) { r.error = "truncated Mach-O header"; return r; } + std::uint64_t at = base + (is64 ? 32 : 28); + for (std::uint32_t i = 0; i < ncmds; ++i) { + std::uint32_t cmd, size; if (!v.get(at, cmd) || !v.get(at + 4, size) || size < 8) { r.error = "truncated load commands"; return r; } + if (cmd == 0xc || cmd == 0x80000018 || cmd == 0x8000001f || cmd == 0x80000023 || cmd == 0x20) { // not LC_ID_DYLIB (0xd): that is the file's own name + std::uint32_t nameoff; std::string s; + if (!v.get(at + 8, nameoff) || nameoff >= size || !v.cstr(at + nameoff, s)) { r.error = "bad dylib command"; return r; } add(r, s); } + at += size; + } + return r; +} +inline result macho(const view& v) { + std::uint32_t magic; v.get(0, magic, true); + if (magic != 0xcafebabe && magic != 0xcafebabf) return macho_one(v, 0); + const bool f64 = magic == 0xcafebabf; std::uint32_t n; if (!v.get(4, n, true) || n > 64) { result r; r.error = "bad fat header"; return r; } + result all; + for (std::uint32_t i = 0; i < n; ++i) { const std::uint64_t a = 8 + std::uint64_t(i) * (f64 ? 32 : 20); std::uint64_t off; + if (f64) { if (!v.get(a + 8, off, true)) { all.error = "truncated fat header"; return all; } } else { std::uint32_t o; if (!v.get(a + 8, o, true)) { all.error = "truncated fat header"; return all; } off = o; } + auto one = macho_one(v, off); if (!one.ok()) { all.error = one.error; return all; } for (auto& s : one.names) add(all, s); } + return all; +} +} // namespace detail +inline result needed(const std::string& path) { + std::ifstream in(path, std::ios::binary); if (!in) return {{}, "cannot open " + path}; + std::string data((std::istreambuf_iterator(in)), {}); detail::view v{reinterpret_cast(data.data()), data.size()}; + if (v.n >= 20 && std::memcmp(v.p, "\x7f""ELF", 4) == 0) return detail::elf(v); + if (v.n >= 2 && v.p[0] == 'M' && v.p[1] == 'Z') return detail::pe(v); + if (v.n >= 8) { std::uint32_t m; v.get(0, m); std::uint32_t mb; v.get(0, mb, true); + if (m == 0xfeedface || m == 0xfeedfacf || mb == 0xcafebabe || mb == 0xcafebabf) return detail::macho(v); } + return {{}, "unrecognised binary format"}; +} +} diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/closure.py b/.agents/docs/2026-11-24-rules-qml-spikes/closure.py new file mode 100644 index 0000000..2bc8a5c --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/closure.py @@ -0,0 +1,62 @@ +import re, sys, json, subprocess, os +Q = os.path.expanduser("~/.xlings/data/xpkgs/xim-x-qt/6.11.1") +IMP = re.compile(r'^\s*import\s+([A-Za-z_][\w.]*)(?:\s+[\d.]+)?(?:\s+as\s+\w+)?\s*;?\s*$', re.M) +def strip(text): + out=[];i=0 + while i=3 and t[1]=='import': deps.append(t[2]); continue + if t[0]=='import' and len(t)>=2: deps.append(t[1]); continue + if t[0]=='depends' and len(t)>=2: deps.append(t[1]) + # the module's own .qml files import further modules (the scanner reads them) + for dp,dns,fns in os.walk(d): + dns[:]=sorted(x for x in dns if not os.path.isfile(os.path.join(dp,x,'qmldir'))) # a nested module is its own module + for fn in sorted(fns): + if fn.endswith('.qml'): + deps.extend(file_imports(os.path.join(dp,fn))) + return rel, deps +def closure(roots, own=()): + seen={}; todo=list(roots) + while todo: + u=todo.pop() + if u in seen or u in own: continue + rel,deps=qmldir_follow(u,own) + if rel is None: seen[u]=None; continue + seen[u]=rel; todo.extend(deps) + return seen +def scanner(qmldir_root): + j=subprocess.run([Q+'/libexec/qmlimportscanner','-rootPath',qmldir_root,'-importPath',Q+'/qml'],capture_output=True,text=True,env={'LD_LIBRARY_PATH':Q+'/lib','LC_ALL':'C.UTF-8'}).stdout + return {e['name']:e.get('relativePath') for e in json.loads(j) if e.get('type')=='module'} +if __name__=='__main__': + root=sys.argv[1] + roots=set() + for dp,_,fs in os.walk(root): + for f in fs: + if f.endswith('.qml'): roots.update(file_imports(os.path.join(dp,f))) + mine=closure(roots) + sc=scanner(root) + mine_set={k for k,v in mine.items() if v is not None} + print("imports:",sorted(roots)) + print("mine=%d scanner=%d"%(len(mine_set),len(sc))) + print("scanner-only:",sorted(set(sc)-mine_set)) + print("mine-only :",sorted(mine_set-set(sc))) diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/llvm-check.sh b/.agents/docs/2026-11-24-rules-qml-spikes/llvm-check.sh new file mode 100755 index 0000000..c235c73 --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/llvm-check.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Compile, link and run the generated QML sources with clang and the REAL libstdc++ (Linux). +# usage: llvm-check.sh +# PITFALL: mcpp's `clang++.cfg` appends libc++ headers unconditionally, so `clang++ -stdlib=libstdc++` +# silently uses libc++. Use the C driver `clang -x c++ --no-default-config` and prove the runtime first. +set -euo pipefail +GEN=$1; GEN2=$2; MAIN=$3; SRC=$4 +LLVM=${LLVM:-$HOME/.mcpp/registry/data/xpkgs/xim-x-llvm/23.1.3}; GCC=$HOME/.mcpp/registry/data/xpkgs/xim-x-gcc/16.1.0 +GLD=$HOME/.mcpp/registry/data/xpkgs/xim-x-glibc/2.44.3; LH=$HOME/.mcpp/registry/data/xpkgs/xim-x-linux-headers/5.11.1/include +Q=${QT_ROOT_DIR:-$HOME/.xlings/data/xpkgs/xim-x-qt/6.11.1} +X="--no-default-config -x c++ -std=c++23 -nostdlibinc -nostdinc++ -isystem $GCC/include/c++/16.1.0 -isystem $GCC/include/c++/16.1.0/x86_64-linux-gnu -isystem $GLD/include -isystem $LH" +printf '#include \n#if defined(_LIBCPP_VERSION)\n#error RUNTIME=libc++\n#elif defined(__GLIBCXX__)\n#error RUNTIME=libstdc++\n#endif\n' > /tmp/rt.cpp +$LLVM/bin/clang $X -fsyntax-only /tmp/rt.cpp 2>&1 | grep -q 'RUNTIME=libstdc++' || { echo "not libstdc++"; exit 1; } +INC="-I$Q/include -I$Q/include/QtCore -I$Q/include/QtGui -I$Q/include/QtQml -I$Q/include/QtQuick -I$SRC -fPIC" +D=$(mktemp -d); cd "$D" +for f in $GEN/*.cpp $GEN2/*.cpp $MAIN; do $LLVM/bin/clang $X $INC -O1 -c -Wno-everything "$f" -o "$(basename "$f").o"; done +$LLVM/bin/clang --no-default-config -fuse-ld=lld --gcc-install-dir=$GCC/lib/gcc/x86_64-linux-gnu/16.1.0 -B$GLD/lib64 -L$GLD/lib64 \ + -Wl,--dynamic-linker=$GLD/lib64/ld-linux-x86-64.so.2 -Wl,-rpath,$GLD/lib64 *.o -o prog -L$Q/lib -lQt6Quick -lQt6Qml -lQt6Gui -lQt6Core \ + -L$GCC/lib64 -lstdc++ -lm -Wl,-rpath,$GCC/lib64 -Wl,-rpath,$Q/lib -Wl,-rpath-link,$Q/lib -Wl,--allow-shlib-undefined +QT_QPA_PLATFORM=offscreen LC_ALL=C.UTF-8 ./prog diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/module-pipeline.Main.qml b/.agents/docs/2026-11-24-rules-qml-spikes/module-pipeline.Main.qml new file mode 100644 index 0000000..ac9d2bd --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/module-pipeline.Main.qml @@ -0,0 +1,11 @@ +import QtQuick +import "Util.js" as U +import com.acme.ui +QtObject { + property Backend b: Backend {} + property QtObject inner: Inner { } + readonly property int viaCpp: b.twice(b.n) + readonly property string viaSingleton: Style.accent + readonly property int viaJs: U.add(40, 2) + readonly property int viaNested: inner.value +} diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/module-pipeline.build.mcpp b/.agents/docs/2026-11-24-rules-qml-spikes/module-pipeline.build.mcpp new file mode 100644 index 0000000..e5256b9 --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/module-pipeline.build.mcpp @@ -0,0 +1,56 @@ +import std; +import mcpp; +import mcpp.rules.qt; +namespace fs = std::filesystem; +static std::vector keep; +static void act(const std::string& id, std::vector argv, std::vector in, std::vector out) { + mcpp::action a; keep.push_back(id); a.id = keep.back().c_str(); a.role = mcpp::roles::source; + for (auto& s : argv) { keep.push_back(s); a.arg(keep.back().c_str()); } + for (auto& s : in) { keep.push_back(s); a.input(keep.back().c_str()); } + for (auto& s : out) { keep.push_back(s); a.output(keep.back().c_str()); } + a.submit(); +} +int main() { + mcpp::rules::qt::options o; + o.modules = { "Core", "Gui", "Qml", "Quick" }; o.deploy_plugins = { "platforms" }; + o.moc = mcpp::rules::qt::moc_scan::listed; + if (!mcpp::rules::qt::compile(o)) return 1; + fs::path Q = mcpp::rules::qt::roots(o).front(), root = mcpp::manifest_dir(); + auto g = [](fs::path p){ return p.generic_string(); }; + const std::string uri = "com.acme.ui", ver = "1.0", san = "com_acme_ui", upath = "com/acme/ui", prefix = "/qt/qml/" + upath; + fs::path gen = fs::path(std::string(mcpp::out_dir())) / "qml", mod = gen / upath, work = gen / san; + fs::create_directories(mod); fs::create_directories(work); + fs::path srcroot = root / "qml/ui"; + // moc (json) + registrar + std::string I1 = "-I" + g(Q/"include"), I2 = "-I" + g(Q/"include/QtCore"), I3 = "-I" + g(Q/"include/QtQml"); + act("qml:moc", { g(Q/"libexec/moc"), g(root/"src/backend.h"), "-o", g(work/"moc_backend.cpp"), "--output-json", I1, I2, I3 }, { g(root/"src/backend.h") }, { g(work/"moc_backend.cpp"), g(work/"moc_backend.cpp.json") }); + std::string M = g(Q/"metatypes"); + act("qml:registrar", { g(Q/"libexec/qmltyperegistrar"), "--generate-qmltypes=" + g(mod/(san+".qmltypes")), "--import-name=" + uri, "--major-version=1", "--minor-version=0", + "--foreign-types=" + M + "/qt6core_metatypes.json," + M + "/qt6gui_metatypes.json," + M + "/qt6qml_metatypes.json," + M + "/qt6quick_metatypes.json", + "-o", g(work/(san+"_qmltyperegistrations.cpp")), g(work/"moc_backend.cpp.json") }, { g(work/"moc_backend.cpp.json") }, { g(work/(san+"_qmltyperegistrations.cpp")), g(mod/(san+".qmltypes")) }); + // files: every file under srcroot + std::vector rel; for (auto& e : fs::recursive_directory_iterator(srcroot)) if (e.is_regular_file()) rel.push_back(fs::relative(e.path(), srcroot)); + std::ranges::sort(rel); + // qmldir + { std::ofstream f(mod/"qmldir"); f << "module " << uri << "\ntypeinfo " << san << ".qmltypes\nprefer :" << prefix << "/\n"; + for (auto& r : rel) { auto ext = r.extension().string(); if (ext != ".qml") continue; auto t = r.stem().string(); if (!std::isupper((unsigned char)t[0])) continue; + std::ifstream in(srcroot/r); std::string text((std::istreambuf_iterator(in)), {}); bool single = text.find("pragma Singleton") != std::string::npos; + f << (single ? "singleton " : "") << t << " " << ver << " " << g(r) << "\n"; } } + // qrc + { std::ofstream f(work/(san+".qrc")); f << "\n" << g(mod/"qmldir") << "\n"; + for (auto& r : rel) f << "" << g(srcroot/r) << "\n"; f << "\n"; } + std::vector in = { g(work/(san+".qrc")), g(mod/"qmldir") }; for (auto& r : rel) in.push_back(g(srcroot/r)); + act("qml:rcc", { g(Q/"libexec/rcc"), "--name", san, g(work/(san+".qrc")), "-o", g(work/("qrc_"+san+".cpp")) }, in, { g(work/("qrc_"+san+".cpp")) }); + // AOT for .qml/.js/.mjs + std::ofstream rsp(work/"loader.rsp"); rsp << "--resource\n" << g(work/(san+".qrc")) << "\n"; + for (auto& r : rel) { auto ext = r.extension().string(); if (ext != ".qml" && ext != ".js" && ext != ".mjs") continue; + std::string flat = g(r); std::ranges::replace(flat, '/', '_'); std::ranges::replace(flat, '.', '_'); + std::string out = g(work/(san + "_" + flat + ".cpp")); + act("qml:cachegen:" + g(r), { g(Q/"libexec/qmlcachegen"), "--bare", "--resource-path", prefix + "/" + g(r), "-I", g(Q/"qml"), "-I", g(gen), "-i", g(mod/"qmldir"), "--resource", g(work/(san+".qrc")), "-o", out, g(srcroot/r) }, + { g(srcroot/r), g(mod/"qmldir"), g(mod/(san+".qmltypes")), g(work/(san+".qrc")) }, { out }); + rsp << prefix << "/" << g(r) << "\n"; } + rsp.close(); + act("qml:loader", { g(Q/"libexec/qmlcachegen"), "--resource-name", "qmlcache_" + san, "-o", g(work/(san+"_qmlcache_loader.cpp")), "@" + g(work/"loader.rsp") }, { g(work/"loader.rsp"), g(work/(san+".qrc")) }, { g(work/(san+"_qmlcache_loader.cpp")) }); + mcpp::include_dir(g(root/"src").c_str()); + return 0; +} diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/multi-module.Main.qml b/.agents/docs/2026-11-24-rules-qml-spikes/multi-module.Main.qml new file mode 100644 index 0000000..3f998db --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/multi-module.Main.qml @@ -0,0 +1,7 @@ +import QtQuick +import app.core +QtObject { + property Derived d: Derived {} + property QtObject c: Card { size: 4 } + readonly property int sum: d.v + d.w + c.size +} diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/multi-module.build.mcpp b/.agents/docs/2026-11-24-rules-qml-spikes/multi-module.build.mcpp new file mode 100644 index 0000000..f3d0c43 --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/multi-module.build.mcpp @@ -0,0 +1,66 @@ +import std; +import mcpp; +import mcpp.rules.qt; +namespace fs = std::filesystem; +static std::deque keep; +static void act(const std::string& id, std::vector argv, std::vector in, std::vector out) { + mcpp::action a; keep.push_back(id); a.id = keep.back().c_str(); a.role = mcpp::roles::source; + for (auto& s : argv) { keep.push_back(s); a.arg(keep.back().c_str()); } + for (auto& s : in) { keep.push_back(s); a.input(keep.back().c_str()); } + for (auto& s : out) { keep.push_back(s); a.output(keep.back().c_str()); } + a.submit(); +} +struct mod { std::string uri, srcdir; std::vector headers; }; +int main() { + mcpp::rules::qt::options o; + o.modules = { "Core", "Gui", "Qml", "Quick" }; o.deploy_plugins = { "platforms" }; + o.moc = mcpp::rules::qt::moc_scan::listed; + if (!mcpp::rules::qt::compile(o)) return 1; + fs::path Q = mcpp::rules::qt::roots(o).front(), root = mcpp::manifest_dir(); + auto g = [](fs::path p){ return p.generic_string(); }; + fs::path gen = fs::path(std::string(mcpp::out_dir())) / "qml"; + std::vector mods = { {"app.core", "qml/core", {"src/base.h"}}, {"app.ui", "qml/ui", {"src/derived.h"}} }; + auto san = [](std::string u) { std::ranges::replace(u, '.', '_'); return u; }; + auto upath = [](std::string u) { std::ranges::replace(u, '.', '/'); return u; }; + std::string M = g(Q/"metatypes"), qtjson = M+"/qt6core_metatypes.json,"+M+"/qt6gui_metatypes.json,"+M+"/qt6qml_metatypes.json,"+M+"/qt6quick_metatypes.json"; + // every module's qmldir and qmltypes are inputs of every cachegen action (conservative) + std::vector allMeta; + for (auto& m : mods) { allMeta.push_back(g(gen/upath(m.uri)/"qmldir")); if (!m.headers.empty()) allMeta.push_back(g(gen/upath(m.uri)/(san(m.uri)+".qmltypes"))); } + for (auto& m : mods) { + const std::string s = san(m.uri), prefix = "/qt/qml/" + upath(m.uri); + fs::path mdir = gen/upath(m.uri), work = gen/s, srcroot = root/m.srcdir; + fs::create_directories(mdir); fs::create_directories(work); + std::vector jsons; + for (auto& h : m.headers) { // moc with json + std::string stem = fs::path(h).stem().string(); + act("qml:moc:"+stem, { g(Q/"libexec/moc"), g(root/h), "-o", g(work/("moc_"+stem+".cpp")), "--output-json", "-I"+g(Q/"include"), "-I"+g(Q/"include/QtCore"), "-I"+g(Q/"include/QtQml"), "-I"+g(root/"src") }, + { g(root/h) }, { g(work/("moc_"+stem+".cpp")), g(work/("moc_"+stem+".cpp.json")) }); + jsons.push_back(g(work/("moc_"+stem+".cpp.json"))); + } + std::vector foreign; // other modules' json as foreign types + for (auto& o2 : mods) if (o2.uri != m.uri) for (auto& h : o2.headers) foreign.push_back(g(gen/san(o2.uri)/("moc_"+fs::path(h).stem().string()+".cpp.json"))); + if (!jsons.empty()) { + std::string ft = qtjson; for (auto& f : foreign) ft += "," + f; + std::vector argv = { g(Q/"libexec/qmltyperegistrar"), "--generate-qmltypes="+g(mdir/(s+".qmltypes")), "--import-name="+m.uri, "--major-version=1", "--minor-version=0", "--foreign-types="+ft, "-o", g(work/(s+"_qmltyperegistrations.cpp")) }; + for (auto& j : jsons) argv.push_back(j); + act("qml:registrar:"+m.uri, argv, jsons, { g(work/(s+"_qmltyperegistrations.cpp")), g(mdir/(s+".qmltypes")) }); + } + std::vector rel; for (auto& e : fs::recursive_directory_iterator(srcroot)) if (e.is_regular_file()) rel.push_back(fs::relative(e.path(), srcroot)); std::ranges::sort(rel); + { std::ofstream f(mdir/"qmldir"); f << "module " << m.uri << "\n"; if (!jsons.empty()) f << "typeinfo " << s << ".qmltypes\n"; f << "prefer :" << prefix << "/\n"; + if (m.uri == "app.ui") f << "depends app.core\n"; + for (auto& r : rel) if (r.extension() == ".qml" && std::isupper((unsigned char)r.stem().string()[0])) f << r.stem().string() << " 1.0 " << g(r) << "\n"; } + { std::ofstream f(work/(s+".qrc")); f << "\n" << g(mdir/"qmldir") << "\n"; for (auto& r : rel) f << "" << g(srcroot/r) << "\n"; f << "\n"; } + std::vector in = { g(work/(s+".qrc")), g(mdir/"qmldir") }; for (auto& r : rel) in.push_back(g(srcroot/r)); + act("qml:rcc:"+m.uri, { g(Q/"libexec/rcc"), "--name", s, g(work/(s+".qrc")), "-o", g(work/("qrc_"+s+".cpp")) }, in, { g(work/("qrc_"+s+".cpp")) }); + std::ofstream rsp(work/"loader.rsp"); rsp << "--resource\n" << g(work/(s+".qrc")) << "\n"; + for (auto& r : rel) { if (r.extension() != ".qml") continue; std::string flat = g(r); std::ranges::replace(flat, '/', '_'); std::ranges::replace(flat, '.', '_'); + std::string out = g(work/(s+"_"+flat+".cpp")); + std::vector ins = { g(srcroot/r), g(work/(s+".qrc")) }; for (auto& x : allMeta) ins.push_back(x); + act("qml:cachegen:"+m.uri+":"+g(r), { g(Q/"libexec/qmlcachegen"), "--bare", "--resource-path", prefix+"/"+g(r), "-I", g(Q/"qml"), "-I", g(gen), "-i", g(mdir/"qmldir"), "--resource", g(work/(s+".qrc")), "-o", out, g(srcroot/r) }, ins, { out }); + rsp << prefix << "/" << g(r) << "\n"; } + rsp.close(); + act("qml:loader:"+m.uri, { g(Q/"libexec/qmlcachegen"), "--resource-name", "qmlcache_"+s, "-o", g(work/(s+"_qmlcache_loader.cpp")), "@"+g(work/"loader.rsp") }, { g(work/"loader.rsp"), g(work/(s+".qrc")) }, { g(work/(s+"_qmlcache_loader.cpp")) }); + } + mcpp::include_dir(g(root/"src").c_str()); + return 0; +} diff --git a/.agents/docs/2026-11-24-rules-qml-spikes/needed_main.cpp b/.agents/docs/2026-11-24-rules-qml-spikes/needed_main.cpp new file mode 100644 index 0000000..381bc67 --- /dev/null +++ b/.agents/docs/2026-11-24-rules-qml-spikes/needed_main.cpp @@ -0,0 +1,9 @@ +#include "binary.hpp" +#include +int main(int argc, char** argv) { + int rc = 0; + for (int i = 1; i < argc; ++i) { auto r = binary::needed(argv[i]); std::cout << argv[i] << "\n"; + if (!r.ok()) { std::cout << " ERROR " << r.error << "\n"; rc = 1; continue; } + for (auto& n : r.names) std::cout << " " << n << "\n"; } + return rc; +} diff --git a/.github/scripts/check-deps-and-qt.sh b/.github/scripts/check-deps-and-qt.sh index 20652ca..8503c6c 100644 --- a/.github/scripts/check-deps-and-qt.sh +++ b/.github/scripts/check-deps-and-qt.sh @@ -440,6 +440,12 @@ qt_widgets_consumer() { find target/dist -name "$so*" | grep -q . || fail "the packed tree carries no $so" done echo "ok: the packed tree carries Qt and QtGui's runtime closure" + # The platform plugin is opened at run time, and the library it loads + # is in no import table: the engine carries it, from mcpp's release that + # takes what is deployed beside the program as a root (mcpp#1011). + find target/dist -name 'libQt6XcbQpa.so.6' | grep -q . || + fail "the packed tree carries no libQt6XcbQpa.so.6, which the xcb platform plugin loads" + echo "ok: the packed tree carries the library the xcb platform plugin loads" fi } @@ -486,6 +492,322 @@ qt_import_only() { echo "ok: a package that enables rules-qt only for its module runs no build program and reports nothing" } +# ─── rules-qml (0.27.0) ────────────────────────────────────────────────────── + +# The SDK a fixture built with, from the fact `rules-qt` records. +qt_sdk_root() { + local fact + fact=$(grep -h -o 'rules-qt\.sdk=[^"]*' target/.build-mcpp/build.mcpp.cache | tail -1) + case "$fact" in + "rules-qt.sdk=xlings: "*) echo "${fact#rules-qt.sdk=xlings: }" ;; + *) fail "the fixture's SDK was not the payload it declares: $fact" ;; + esac +} + +# The program as the build left it (bin/, bin/.exe on Windows). +built_program() { + find target -path '*/bin/*' \( -name "$1" -o -name "$1.exe" \) -type f | head -1 +} + +# The directory `mcpp pack --format dir` wrote. +packed_tree() { + find target/dist -mindepth 1 -maxdepth 1 -type d | head -1 +} + +# The tree a QML program ships from: what `mcpp pack --format dir` wrote. On macOS +# `mcpp pack` does not stage Qt's frameworks yet (rules-qt's Widgets fixture does +# not pack there either), so the tree is the directory the program was built into, +# where the rule deploys qml/ and qt.conf beside it. +staged_tree() { + if is_macos; then + dirname "$(built_program "$1")" + return 0 + fi + "$MCPP" pack --format dir > target/ci/pack.log 2>&1 || { cat target/ci/pack.log >&2; return 1; } + cat target/ci/pack.log >&2 + packed_tree +} + +# A compiled file's dependencies, one per line, by the platform's own tool: the +# reference `mcpp.plugins.binary` is held to. Prints nothing and returns 1 where +# the platform has no tool in this job. +llvm_readobj() { + find "${MCPP_HOME:-$HOME/.mcpp}/registry/data/xpkgs" -path '*xim-x-llvm*' \( -name llvm-readobj -o -name llvm-readobj.exe \) 2>/dev/null | head -1 +} +needed_by_tool() { + local f="$1" id tool + if is_macos; then + id=$(otool -D "$f" 2>/dev/null | tail -n +2) + otool -L "$f" 2>/dev/null | tail -n +2 | awk '{print $1}' | while IFS= read -r n; do + [ "$n" = "$id" ] || echo "$n" + done + elif is_windows; then + tool=$(llvm_readobj); [ -n "$tool" ] || return 1 + "$tool" --needed-libs "$f" 2>/dev/null | tr -d '\r' | sed -n '/NeededLibraries \[/,/\]/p' | grep -v 'NeededLibraries\|^\]' | sed 's/^ *//' + else + readelf -d "$f" 2>/dev/null | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p' + fi +} + +# Every library a packed file needs and the SDK provides is in the packed tree: +# the closure `mcpp pack` computes from the program does not reach what a +# plugin loads (mcpp#1011), and the engine's closure from the deployed plugins does. +assert_packed_closure() { + local sdk="$1" tree="$2" f n missing=0 checked=0 + if is_windows && [ -z "$(llvm_readobj)" ]; then + echo "::notice::SKIP the packed-closure check: no llvm-readobj to read the imports with on this job" + return 0 + fi + while IFS= read -r f; do + if ! is_windows && ! is_macos; then + [ "$(head -c4 "$f" 2>/dev/null | tr -d '\0')" = "$(printf '\177ELF')" ] || continue + fi + for n in $({ needed_by_tool "$f" 2>/dev/null || true; } | tr -d '\r'); do + checked=$((checked + 1)) + if is_macos; then + case "$n" in + @rpath/*.framework/*) local fw=${n#@rpath/}; fw=${fw%%/*} + find "$tree" -path "*$fw/*" | grep -q . || { echo "missing: $fw (needed by $f)"; missing=$((missing + 1)); } ;; + esac + elif is_windows; then + if find "$sdk/bin" -maxdepth 1 -iname "$n" | grep -q .; then + find "$tree" -iname "$n" | grep -q . || { echo "missing: $n (needed by $f)"; missing=$((missing + 1)); } + fi + else + if [ -e "$sdk/lib/$n" ]; then + [ -e "$tree/lib/$n" ] || { echo "missing: $n (needed by $f)"; missing=$((missing + 1)); } + fi + fi + done + done < <(find "$tree" -type f \( -name '*.so' -o -name '*.so.*' -o -name '*.dll' -o -name '*.dylib' -o -perm -u+x \) 2>/dev/null) + [ "$missing" -eq 0 ] || fail "$missing libraries of the SDK that packed files load are not in the packed tree" + echo "ok: every SDK library the packed files load is in the packed tree ($checked dependencies read)" +} + +qml_consumer() { + cd "$ROOT/tests/qml-consumer" + rm -rf target + mkdir -p target/ci + "$MCPP" build 2>&1 | tee target/ci/build.log + "$MCPP" run | tr -d '\r' | tee target/ci/run.log + grep -q '^cpp=84 singleton=red js=42 nested=7 resource=hello-resource theme=9$' target/ci/run.log || + fail "the module's C++ type, singleton, script, nested file, resource or C++ singleton did not reach the program" + grep -q '^tr=Hallo controls=1$' target/ci/run.log || + fail "the qsTr translation or the Qt Quick Controls module did not reach the program" + echo "ok: the Probe module is in the program: C++ types, singletons, a script, a nested file, a resource, a translation" + + # AOT: a unit per file and the loader, compiled into the program. + local g + for g in Probe_Main_qml Probe_Style_qml Probe_Util_js Probe_sub_Inner_qml Probe_qmlcache_loader Probe_qmltyperegistrations qrc_Probe; do + find target -name "$g.cpp" | grep -q . || fail "no generated $g.cpp" + done + local exe; exe=$(built_program qml-consumer) + [ -n "$exe" ] || fail "no program under target/" + if ! is_windows; then + [ "$(nm "$exe" 2>/dev/null | grep -c QmlCacheGeneratedCode || true)" -gt 0 ] || + fail "the program holds no compiled QML (no QmlCacheGeneratedCode symbol)" + else + find target \( -name 'Probe_Main_qml*.obj' -o -name 'Probe_Main_qml*.o' \) | grep -q . || + fail "the compiled form of Main.qml was not compiled into the program" + fi + echo "ok: qmlcachegen's units and loader are generated and linked into the program" + + # `qsTr` is found in QML by lupdate, and the committed .ts is its output. + grep -q 'Hello' qml_consumer_de.ts || fail "the .ts has no string from the .qml file" + git -C "$ROOT" diff --quiet -- tests/qml-consumer/qml_consumer_de.ts || + fail "lupdate changed the committed .ts; commit its output" + echo "ok: lupdate read qsTr from the .qml file" + + # One .qml changed re-generates its own compiled unit and the resources, + # and nothing else. Time stamps, not the build's log, whose format is not a contract. + sleep 2.2 + touch target/ci/before-edit + sleep 2.2 + cp qml/Probe/Main.qml target/ci/Main.qml.orig + printf '// edited\n' >> qml/Probe/Main.qml + "$MCPP" build > target/ci/edit-build.log 2>&1 || { cat target/ci/edit-build.log; mv target/ci/Main.qml.orig qml/Probe/Main.qml; fail "the build after an edit failed"; } + mv target/ci/Main.qml.orig qml/Probe/Main.qml + local gen + for g in Probe_Main_qml qrc_Probe; do + gen=$(find target -name "$g.cpp" | head -1) + [ -n "$(find "$gen" -newer target/ci/before-edit)" ] || fail "$g.cpp was not regenerated after an edit of Main.qml" + done + for g in Probe_Style_qml Probe_Util_js Probe_sub_Inner_qml Probe_qmltyperegistrations Probe_qmlcache_loader; do + gen=$(find target -name "$g.cpp" | head -1) + [ -z "$(find "$gen" -newer target/ci/before-edit)" ] || fail "$g.cpp was regenerated although its input did not change" + done + echo "ok: an edit of one .qml regenerated its unit and the resources, and nothing else" + + # Packed: qt.conf, Qt's modules and the closure they need. + "$MCPP" build > target/ci/build2.log 2>&1 || fail "the build failed after the edit was undone" + local tree; tree=$(staged_tree qml-consumer) || fail "pack failed" + [ -n "$tree" ] || fail "no packed tree" + find "$tree" -name qt.conf | head -1 | xargs grep -q '^Qml2Imports = qml$' || fail "the packed tree has no qt.conf with Qml2Imports" + find "$tree" -path '*qml/QtQuick/Controls/qmldir' | grep -q . || fail "QtQuick.Controls is not in the packed tree" + if ! is_windows && ! is_macos; then + find "$tree" -name 'libQt6XcbQpa.so.6' | grep -q . || fail "the xcb platform plugin's library is not in the packed tree (mcpp#1011: needs an mcpp that closes over deployed libraries)" + fi + echo "ok: the packed tree has qt.conf, the Controls module and, on Linux, the xcb plugin's library" + + # Variants of the same project. + qml_variant noaot + qml_variant styles + qml_variant noconf +} + +# One project, built another way by MCPP_QML_VARIANT (see its build.mcpp). +qml_variant() { + local v="$1" tree + rm -rf target + mkdir -p target/ci + MCPP_QML_VARIANT="$v" "$MCPP" build > "target/ci/build-$v.log" 2>&1 || { cat "target/ci/build-$v.log"; fail "the $v variant did not build"; } + case "$v" in + noaot) + MCPP_QML_VARIANT="$v" "$MCPP" run | tr -d '\r' | grep -q '^cpp=84 singleton=red' || fail "noaot: the program did not run" + ! find target -name 'Probe_*_qml.cpp' | grep -q . || fail "noaot: a compiled unit was generated" + if ! is_windows; then + [ "$(nm "$(built_program qml-consumer)" 2>/dev/null | grep -c QmlCacheGeneratedCode || true)" -eq 0 ] || + fail "noaot: the program holds compiled QML" + fi + echo "ok: aot = false embeds the sources, generates no unit, and the program runs" ;; + styles) + tree=$(MCPP_QML_VARIANT="$v" staged_tree qml-consumer) || fail "styles: pack failed" + find "$tree" -path '*qml/QtQuick/Controls/Basic/qmldir' | grep -q . || fail "styles: the Basic style is not placed" + ! find "$tree" -path '*qml/QtQuick/Controls/Material/qmldir' | grep -q . || fail "styles: the Material style is placed" + echo "ok: styles = { Basic } places the Basic style and not the others" ;; + noconf) + tree=$(MCPP_QML_VARIANT="$v" staged_tree qml-consumer) || fail "noconf: pack failed" + ! find "$tree" -name qt.conf | grep -q . || fail "noconf: a qt.conf is in the packed tree" + echo "ok: write_qt_conf = false places no qt.conf" ;; + esac +} + +qml_modules() { + cd "$ROOT/tests/qml-modules" + rm -rf target + mkdir -p target/ci + "$MCPP" build 2>&1 | tee target/ci/build.log + "$MCPP" run | tr -d '\r' | tee target/ci/run.log + grep -q '^sum=19 viaBase=7 label=chip$' target/ci/run.log || + fail "a type derived across modules, a type of another module or a module with no C++ type did not work" + find target -name 'app_core_qmltyperegistrations.cpp' | grep -q . || fail "no registrations for app.core" + find target -name 'app_ui_qmltyperegistrations.cpp' | grep -q . || fail "no registrations for app.ui" + ! find target -name 'Plain_qmltyperegistrations.cpp' | grep -q . || fail "a module with no C++ type ran the registrar" + echo "ok: three modules, a C++ type derived from another module's, and one with no C++ type" +} + +qml_import_only() { + cd "$ROOT/tests/qml-import-only" + rm -rf target + mkdir -p target/ci + "$MCPP" build 2>&1 | tee target/ci/build.log + ! find target -name 'build.mcpp.bin' -o -name 'build.mcpp.exe' | grep -q . || + fail "mcpp synthesised a build program for a package with no QML source" + ! grep -q 'no Qt SDK' target/ci/build.log || + fail "a package with no QML source reported a missing SDK" + echo "ok: a package that enables rules-qml only for its module runs no build program and reports nothing" +} + +qml_deploy() { + cd "$ROOT/tests/qml-deploy" + rm -rf target + mkdir -p target/ci + "$MCPP" build 2>&1 | tee target/ci/build.log + "$MCPP" run | tr -d '\r' | tee target/ci/run.log + grep -q '^layout=47 gadget=42 shape=1 button=1$' target/ci/run.log || + fail "a Qt module, a module of import_paths or one named in imports did not load from the deployed qml/" + echo "ok: Layouts, Controls.Material, Shapes (named) and a module of import_paths load from the deployed qml/" + local sdk; sdk=$(qt_sdk_root) + local tree; tree=$(staged_tree qml-deploy) || fail "pack failed" + [ -n "$tree" ] || fail "no packed tree" + + # The deployed modules cover what qmlimportscanner finds: more is allowed, less is not. + local scanner="$sdk/libexec/qmlimportscanner" + is_windows && scanner="$sdk/bin/qmlimportscanner.exe" + "$scanner" -rootPath qml/App -importPath "$sdk/qml" -importPath extra > target/ci/scanner.json || + fail "qmlimportscanner failed" + local rel miss=0 n=0 + local py=python3 + command -v python3 > /dev/null 2>&1 || py=python + # Python writes `\r\n` on Windows; a module name with the `\r` matches no path. + for rel in $("$py" -I - target/ci/scanner.json <<'PY' | tr -d '\r' +import json, sys +for e in json.load(open(sys.argv[1], encoding="utf-8")): + if e.get("type") == "module" and e.get("relativePath"): + print(e["relativePath"]) +PY + ); do + n=$((n + 1)) + find "$tree" -path "*/qml/$rel/qmldir" | grep -q . || { echo "missing module: $rel"; miss=$((miss + 1)); } + done + [ "$n" -gt 5 ] || fail "the scanner found only $n modules" + [ "$miss" -eq 0 ] || fail "$miss modules the scanner finds are not in the packed tree" + echo "ok: the packed tree holds all $n modules qmlimportscanner finds" + + # The closure of the libraries is checked where mcpp packs them. + if ! is_macos; then assert_packed_closure "$sdk" "$tree"; fi + + # The packed program runs without the SDK: Linux only, where the packed + # program's loader is set to the ecosystem's, as `mcpp run` does. + if ! is_windows && ! is_macos; then + qml_deploy_without_sdk "$sdk" "$tree" + fi +} + +# Runs the packed program with the SDK's directory renamed away. The packed +# program is linked to the system's loader and its libraries are the ecosystem's, +# so its interpreter is set to the one the build used. +qml_deploy_without_sdk() { + local sdk="$1" tree="$2" interp copy + command -v patchelf > /dev/null 2>&1 || { echo "::notice::SKIP running the packed program without the SDK: no patchelf"; return 0; } + # The ecosystem's loader, whose directory also holds libstdc++ and libc: the + # libraries a packed program takes from its own tree are built against them. + interp=$(find "${XLINGS_HOME:-$HOME/.xlings}" -maxdepth 6 -path '*linux-x86_64-glibc/ld-linux-x86-64.so.2' 2>/dev/null | head -1 || true) + [ -n "$interp" ] || { echo "::notice::SKIP running the packed program without the SDK: no ecosystem loader found"; return 0; } + copy=$(mktemp -d) + cp -R "$tree" "$copy/pkg" + patchelf --set-interpreter "$interp" "$copy/pkg/bin/qml-deploy" || { echo "::notice::SKIP running without the SDK: patchelf failed"; return 0; } + if ! mv "$sdk" "$sdk.away" 2> /dev/null; then + echo "::notice::SKIP running the packed program without the SDK: its directory cannot be renamed" + rm -rf "$copy" + return 0 + fi + local status=0 out + out=$(cd "$copy" && env -i HOME="$HOME" PATH=/usr/bin:/bin "$copy/pkg/bin/qml-deploy" 2>&1) || status=$? + mv "$sdk.away" "$sdk" + rm -rf "$copy" + echo "$out" | tail -3 + [ "$status" -eq 0 ] && echo "$out" | grep -q '^layout=47 gadget=42 shape=1 button=1$' || + fail "the packed program did not run without the SDK (status $status)" + echo "ok: the packed program runs with the SDK's directory renamed away" +} + +# A shader compiled by `qsb` and embedded in a module (Linux). `qsb` is in +# `xim:qt-addons`; an index that publishes it before xim-pkgindex#1262 leaves it +# on the system's loader, so the fixture states that it is skipped. +qml_shaders() { + if is_windows || is_macos; then echo "skip: qml-shaders is a Linux fixture"; return 0; fi + cd "$ROOT/tests/qml-shaders" + rm -rf target + mkdir -p target/ci + if ! "$MCPP" build > target/ci/build.log 2>&1; then + local qsb + qsb=$(find "${XLINGS_HOME:-$HOME/.xlings}/data/xpkgs" -maxdepth 4 -path '*xim-x-qt-addons*/bin/qsb' 2>/dev/null | head -1 || true) + if [ -n "$qsb" ] && ! "$qsb" --version > target/ci/qsb-probe.log 2>&1; then + echo "::notice::SKIP qml-shaders: qsb does not start ($(head -c 200 target/ci/qsb-probe.log | tr '\n' ' '))" + return 0 + fi + cat target/ci/build.log + fail "the qml-shaders build failed" + fi + "$MCPP" run | tr -d '\r' | tee target/ci/run.log + # The resource is opened by path and read (`qsb=`); the url the component + # reports for it is relative when its code is compiled ahead of time. + grep -qE '^qsb=[1-9][0-9]* bytes shader=(qrc:/qt/qml/Shade/)?shaders/wave.frag.qsb$' target/ci/run.log || + fail "the compiled shader is not a resource of the module" + echo "ok: qsb compiled the shader and it is a resource of the module" +} + # THE TEST KIT (0.17.0). The deps members' decisions -- which mechanism, which # triplet, which C runtime -- tested against stated build contexts on every # host, with nothing installed. The build program is the test; the verdicts @@ -710,10 +1032,15 @@ case "${1:-}" in qt-widgets-consumer) qt_widgets_consumer ;; qt-sdk-consumer) qt_sdk_consumer ;; qt-import-only) qt_import_only ;; + qml-consumer) qml_consumer ;; + qml-modules) qml_modules ;; + qml-deploy) qml_deploy ;; + qml-import-only) qml_import_only ;; + qml-shaders) qml_shaders ;; plugin-logic) plugin_logic ;; vcpkg-crt) vcpkg_crt ;; vcpkg-managed) vcpkg_managed ;; vcpkg-msbuild-refused) vcpkg_msbuild_refused ;; vcpkg-make-port) vcpkg_make_port ;; - *) echo "usage: $0 vcpkg-consumer|vcpkg-libcxx|archive-consumer|vcpkg-workspace|cmake-consumer|cmake-cache|cmake-cross|qt-consumer|qt-widgets-consumer|qt-sdk-consumer|qt-import-only|plugin-logic|tool-sources|vcpkg-crt|vcpkg-managed|vcpkg-msbuild-refused|vcpkg-make-port"; exit 2 ;; + *) echo "usage: $0 vcpkg-consumer|vcpkg-libcxx|archive-consumer|vcpkg-workspace|cmake-consumer|cmake-cache|cmake-cross|qt-consumer|qt-widgets-consumer|qt-sdk-consumer|qt-import-only|qml-consumer|qml-modules|qml-deploy|qml-import-only|qml-shaders|plugin-logic|tool-sources|vcpkg-crt|vcpkg-managed|vcpkg-msbuild-refused|vcpkg-make-port"; exit 2 ;; esac diff --git a/.github/scripts/check-toolchain-lanes.sh b/.github/scripts/check-toolchain-lanes.sh index ab6b6fc..a523d2f 100755 --- a/.github/scripts/check-toolchain-lanes.sh +++ b/.github/scripts/check-toolchain-lanes.sh @@ -48,7 +48,7 @@ llvm_full=( "archive-consumer|^archive-consumer: 'greetings from the archive'" "spirv-module-consumer|^all ok" ) -llvm_configure_only=(qt-consumer qt-widgets-consumer qt-sdk-consumer qt-import-only) +llvm_configure_only=(qt-consumer qt-widgets-consumer qt-sdk-consumer qt-import-only qml-consumer qml-modules qml-deploy qml-shaders qml-import-only) llvm_lane() { : "${MCPP:?MCPP names the mcpp under test}" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e98e573..5c7f523 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -92,7 +92,12 @@ env: # older engine, and docs/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. - MCPP_VERSION: 2026.11.7.1 + # + # 2026.11.23.1 IS WHAT 0.27.0'S RULES-QML PACKS NEED (mcpp#1011): `mcpp pack` + # takes what the build deploys beside the program -- the QML plugins' libraries + # -- as roots of its runtime closure. The build itself, and the package floor, + # stay on the older engine, as for 0.21.0 above. + MCPP_VERSION: 2026.11.23.1 # THE RELEASE EVERY JOB FETCHES, WHICH IS NOT ALWAYS THE ONE UNDER TEST. # # `MCPP_VERSION` states the engine this collection's lanes need -- the package @@ -103,7 +108,7 @@ env: # # It moves to `MCPP_VERSION` once that release exists, so the ordinary path # runs the engine this collection states. - MCPP_BOOTSTRAP: 2026.11.7.1 + MCPP_BOOTSTRAP: 2026.11.23.1 # AN ENGINE BUILT FROM SOURCE, WHEN A DISPATCH NAMES ONE. # # Empty on every push and pull request, so the steps run the release above, @@ -126,7 +131,7 @@ env: # one-line change here. The mcpp is the bootstrap release, which also builds # the engine under review when `MCPP_SOURCE_REF` names one. MCPPLS_VERSION: 0.0.15 - MCPP_EDITOR_VERSION: 2026.11.7.1 + MCPP_EDITOR_VERSION: 2026.11.23.1 # PINNED, AND WITHOUT IT THE CACHE BELOW CACHED NOTHING. # # A released mcpp is self-contained: with no `MCPP_HOME`, `mcpp self env` @@ -1806,6 +1811,7 @@ jobs: - name: compatibility units retire themselves run: bash .github/scripts/check-compat-retirement.sh + # ── deps-vcpkg, deps-cmake and rules-qt (0.13.0) ────────────────────── # # vcpkg keeps everything it reuses in one per-user directory -- its @@ -1883,6 +1889,33 @@ jobs: - name: a package that enables rules-qt only for its module builds without a report run: bash .github/scripts/check-deps-and-qt.sh qt-import-only + # rules-qml (0.27.0). One module with C++ types, singletons, a script, a + # nested file and a resource, compiled ahead of time; then the same + # project as three variants; several modules with a type derived across + # them; the Qt modules a program loads at run time placed beside it, in a + # tree that runs without the SDK. + - name: rules-qml enables its module alone without a report + run: bash .github/scripts/check-deps-and-qt.sh qml-import-only + + - name: rules-qml builds a QML module with C++ types, compiles it ahead of time, and rebuilds only what an edit reaches + run: bash .github/scripts/check-deps-and-qt.sh qml-consumer + + - name: rules-qml builds several modules, one with a type derived from another's + run: bash .github/scripts/check-deps-and-qt.sh qml-modules + + # The patched loader of the packed tree is set with patchelf, and the + # SDK's directory is renamed away while it runs. + - name: patchelf, for running a packed program without the SDK + run: sudo apt-get install -y --no-install-recommends patchelf + + - name: rules-qml places Qt's QML modules and their libraries; the packed program runs without the SDK + run: bash .github/scripts/check-deps-and-qt.sh qml-deploy + + # `qsb` is in `xim:qt-addons`; the step says SKIP where the published + # payload's qsb does not start (xim-pkgindex#1262 fixes it). + - name: rules-qml compiles a shader with qsb and embeds it + run: bash .github/scripts/check-deps-and-qt.sh qml-shaders + # ── THE OTHER TWO WAYS THIS CODE IS COMPILED ON LINUX (0.19.1) ───────────── # # The consumers job builds with the default toolchain, GCC with libstdc++. @@ -2747,6 +2780,23 @@ jobs: - name: a package that enables rules-qt only for its module builds without a report run: bash .github/scripts/check-deps-and-qt.sh qt-import-only + # rules-qml (0.27.0). One module with C++ types, singletons, a script, a + # nested file and a resource, compiled ahead of time; then the same + # project as three variants; several modules with a type derived across + # them; the Qt modules a program loads at run time placed beside it, in a + # tree that runs without the SDK. + - name: rules-qml enables its module alone without a report + run: bash .github/scripts/check-deps-and-qt.sh qml-import-only + + - name: rules-qml builds a QML module with C++ types, compiles it ahead of time, and rebuilds only what an edit reaches + run: bash .github/scripts/check-deps-and-qt.sh qml-consumer + + - name: rules-qml builds several modules, one with a type derived from another's + run: bash .github/scripts/check-deps-and-qt.sh qml-modules + + - name: rules-qml places Qt's QML modules and their libraries + run: bash .github/scripts/check-deps-and-qt.sh qml-deploy + # ── deps WITHOUT VISUAL STUDIO (0.17.0, mcpp#734) ─────────────────────────── # # The managed toolset `xim:msvc@14.44.35207` on a runner whose Visual Studio diff --git a/README.md b/README.md index 0e0a964..b11fef3 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ module name the member declares, and configures it there. ```toml [build-dependencies.mcpp] -plugins = { version = "0.26.1", features = ["rules-spirv"], host-module = true } +plugins = { version = "0.27.0", features = ["rules-spirv"], host-module = true } ``` ```cpp @@ -69,6 +69,7 @@ mcpp 2026.11.7.1 or later; cross configuration requires CMake 3.19 or later. | `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) | diff --git a/docs/engine-and-rules.md b/docs/engine-and-rules.md index 28d25d5..ec225b5 100644 --- a/docs/engine-and-rules.md +++ b/docs/engine-and-rules.md @@ -96,6 +96,7 @@ Each rule therefore selects the extensions it claims and leaves the rest: | `rules-hip` | `.hip` | | `rules-metal` | `.metal` | | `rules-qt` | `.ui`, `.qrc`, `.ts`; a header is found by what it declares, since `.h` is already C++ | +| `rules-qml` | nothing: a `.qml` file needs a module uri and a version that `[build] sources` cannot state, so the project states its modules in `build.mcpp` and writes `host-module = true`; the `rules-qt` it implies keeps its claims | | `rules-slang` | `.slang` | | `rules-swift` | `.swift` | | `rules-sycl` | `.sycl` | diff --git a/docs/plugin-development.md b/docs/plugin-development.md index e42d03c..1eba362 100644 --- a/docs/plugin-development.md +++ b/docs/plugin-development.md @@ -52,7 +52,7 @@ mcpp-index refuses such a package. ```toml [build-dependencies.mcpp] -plugins = { version = "0.26.1", features = ["plugins-core"], host-module = true, reexport = true } +plugins = { version = "0.27.0", features = ["plugins-core"], host-module = true, reexport = true } ``` `reexport = true` is needed when the plugin's consumers import L2 modules in diff --git a/docs/rules-qml.md b/docs/rules-qml.md new file mode 100644 index 0000000..560d9ab --- /dev/null +++ b/docs/rules-qml.md @@ -0,0 +1,126 @@ +# `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. + +## Use + +```toml +[build-dependencies.mcpp] +plugins = { version = "0.27.0", features = ["rules-qml"], host-module = true } + +# QML needs Qt Quick, which `xim:qt` carries and `xim:qt-base` does not. +[target.'cfg(any(windows, linux, macos))'.xlings.workspace] +"xim:qt" = "6.11.1" + +[build] +sources = ["src/*.cpp"] +``` + +```cpp +// build.mcpp +import std; +import mcpp; +import mcpp.rules.qml; + +int main() { + namespace qml = mcpp::rules::qml; + qml::options o; + o.qt.modules = { "Core", "Gui", "Qml", "Quick" }; + + qml::qml_module probe; + probe.uri = "Probe"; + probe.root = "qml/Probe"; + probe.sources = { "qml/Probe/**/*.qml", "qml/Probe/**/*.js" }; + probe.resources = { "qml/Probe/data/*" }; + o.modules = { probe }; + return qml::compile(o) ? 0 : 1; +} +``` + +```cpp +// main.cpp +QQmlComponent component(&engine); +component.loadFromModule("Probe", "Main"); +``` + +`rules-qml` claims no file extension and names no `rule_module`: a `.qml` file needs a uri and a version that `[build] sources` cannot state, so the project writes `host-module = true` and states its modules in `build.mcpp`. The `rules-qt` it implies keeps its own claim of `.ui`, `.qrc` and `.ts`. One `qml::compile` call also runs what `qt::compile` runs, with `options::qt`; call one of them, not both. + +## A module + +| field | meaning | +|---|---| +| `uri` | `Probe`, `com.acme.ui`: identifiers joined by dots; the directory `com/acme/ui` in the resources | +| `version` | `major.minor`, default `1.0` | +| `sources` | `.qml`, `.js` and `.mjs` files, paths or globs (`*`, `?`, `**/`) relative to the package root; any other file is a resource | +| `root` | the directory the module's files are relative to; empty is the directory the sources share | +| `resources` | other files (images, data) | +| `headers` | the headers of the module's C++ types. Empty takes every header `moc` read that uses `QML_ELEMENT` or a related macro, when the project has one module; with several modules each header is listed in one, and a header nobody lists is refused | +| `depends`, `imports` | `depends` and `import` lines of the `qmldir`, as the project states them | +| `shaders`, `qsb_args` | `.vert`, `.frag`, `.comp` compiled by `qsb` (default `--qt6`) and embedded as `shaders/.qsb` | +| `aot` | default `true`: `qmlcachegen` compiles each file and a loader registers them; `false` embeds the sources only | +| `prefix` | resource prefix, default `/qt/qml`, where Qt's import path already looks | + +A `.qml` file whose name starts with a capital letter is a type of the module; one that contains `pragma Singleton` is a singleton. A C++ singleton (`QML_SINGLETON`) needs no line in the `qmldir`. + +## Options + +| option | meaning | +|---|---| +| `modules` | the QML modules of the application | +| `qt` | every option of `rules-qt`; `Qml` is always linked, and `moc` is given the SDK's include directories and writes the type description | +| `quick_plugins` | plugin directories a Qt Quick program needs (`xcbglintegrations`, `platforminputcontexts`, `imageformats`), placed with `qt.deploy_plugins`; only those the SDK has | +| `imports` | Qt modules the program loads and no `.qml` file imports (`Qt.createComponent` with a computed name) | +| `styles` | when not empty, an `optional import` of a Qt Quick Controls style is followed for these only; empty places every style | +| `import_paths` | directories of QML modules beyond the SDK's, each holding `/qmldir` | +| `deploy_imports` | default `true`: place the Qt modules the program imports | +| `write_qt_conf` | default `true`; see below | +| `lint`, `lint_warnings_are_errors` | run `qmllint` on every `.qml` file as a check | + +`qt.i18n.update_sources` also reads `qsTr` in `.qml` and `.js` files. + +## The actions + +For each module, in dependency order, all `role = "source"` with declared inputs and outputs, so an edited file re-runs only what reads it: + +| id | runs | writes | +|---|---|---| +| `qt:moc:
` | `moc --output-json` with the SDK's include directories | `moc_.cpp`, `moc_.cpp.json` | +| `qml:registrar:` | `qmltyperegistrar`, the SDK's and the other modules' type descriptions as foreign types, so a type may derive from a type of another module | `_qmltyperegistrations.cpp`, `.qmltypes` | +| `qml:qsb::` | `qsb` | `shaders/.qsb` | +| `qml:rcc:` | `rcc` over the qrc the rule writes (the files, the `qmldir`, the shaders) | `qrc_.cpp` | +| `qml:cachegen::` | `qmlcachegen`, one per `.qml`, `.js`, `.mjs` | `_.cpp` | +| `qml:cachegen::loader` | `qmlcachegen --resource-name`, writing the loader that registers the compiled files | `_qmlcache_loader.cpp` | +| `qml:lint::` | `qmllint`, role `check` | | + +The `qmldir`, the qrc and the loader's response file are written at plan time and only when their content changes. The generated `.cpp` files are compiled and linked into the program, so a module is static: nothing but the executable carries it. Generated names come from the uri (`.` becomes `_`); two modules or files that would write one name are refused. + +## What the program loads + +A Qt module (`QtQuick.Controls`, `QtQuick.Layouts`) is a directory of files and usually a plugin library, opened when a `.qml` file imports it. No import table names it. The rule reads the `import` statements of the project's `.qml` files (not those in comments or strings) and follows the SDK's `qmldir` files (`import`, `default import`, `optional import`, `depends`) and the `.qml` files of each module directory, which import further modules: the closure `qmlimportscanner` computes, read from text at plan time. On Qt 6.11.1 it equals the scanner's on four samples, among them all forty top-level modules. Each module is placed under `qml//`, without type descriptions, `designer/` and debug files, and a directory that is a module of its own is placed when it is imported. A `.qml` file imported only from another module is not the project's; `import "file.js"` and `import "dir"` name files and are not modules; a module registered by the program at run time (`qmlRegisterType`) is noted, not an error, and a `Qt*` module the SDK lacks is a warning. + +The sizes are worth knowing. `QtQuick` with `QtQuick.Controls` places 24 modules, 1231 files and 6.8 MB with every style; `styles = { "Material" }` places 15 modules and 173 files; `{ "Basic" }`, 12 modules and 100 files. The style a program uses is chosen at run time (`QQuickStyle`, `qtquickcontrols2.conf`), so the default places all of them. + +The plugin libraries of those modules load Qt libraries the program does not link (`libQt6QuickLayouts.so.6`). `mcpp pack` takes what the build deploys beside the program as a root of its runtime closure, so it carries them (mcpp#1011, from 2026.11.23.1; an older engine builds and runs the program, and its pack leaves those libraries out). On macOS `mcpp pack` does not stage Qt's frameworks yet, for `rules-qt` as well, so CI checks `qml/` and `qt.conf` in the directory the program is built into. + +## `qt.conf` + +A program found beside a `qt.conf` takes its `Prefix` from that file's directory, so the rule writes one with `Prefix = .` and `Qml2Imports = qml`, and places it beside the program. Three things follow. Qt's data, settings and library paths are rebased onto the program's directory as well; `Translations` is `/translations`, which is `i18n.deploy_to`, and a different `deploy_to` is written into the file. The program and the packed tree behave alike: with the file, Qt looks for QML modules only in the deployed `qml/`, so an incomplete closure fails in `mcpp run`, where it can be fixed, and not after packing. And the plugin directories stay where `rules-qt` places them, beside the program, which Qt searches as a library path. + +A project that has its own `qt.conf` (at the package root, in `res/`, or as `/qt/etc/qt.conf` in a resource file) keeps it: none is written, and a warning says what the file has to set. `write_qt_conf = false` writes none. + +## Limits + +- **Not planned for** `qmltc` (QML compiled to C++ classes), QML plugins as shared libraries (`qt_add_qml_plugin`), QML modules that come from a dependency package (`import_paths` takes their directory; a module in a static library of another package may be dropped by the linker, and a reference to its `qml_register_types_` keeps it), a macOS `.app` bundle's layout, Android, iOS and WebAssembly (the call warns and declares nothing), a package with more than one target (the generated sources go into each target), `qmlformat`, and Qt 5. +- **Paths with a space or a non-ASCII character** in the project's directory fail in gcc's module dependency scan; `qt-consumer` fails the same way. The fixtures use ASCII paths. +- `.js` files that `.import` another, and `.mjs` `import` statements, are not read by the closure; name the module in `imports`. Neither does it see a module whose name a program composes at run time. +- `qsb` is part of the additional libraries, `xim:qt-addons`, which the project declares beside `xim:qt`. A published `xim:qt-addons` older than xim-pkgindex#1262 leaves `qsb` on the system's loader, and it does not start; the fixture skips with a notice where it does not. +- The generated C++ builds with gcc 16 and with clang 20 to 23. On Linux `xim:qt` is built with libstdc++, so the build uses a gcc toolchain, as `rules-qt` states; Windows and macOS use the engine's default toolchain. + +## Platforms + +| | Linux | Windows | macOS | +|---|---|---|---| +| plugins | `libqtquick2plugin.so` | `qtquick2plugin.dll` (not the `d` build) | `libqtquick2plugin.dylib` | +| fixtures | built, run, packed, run without the SDK | built, run | built, run | + +The Windows and macOS paths are covered by CI. diff --git a/docs/rules-qt.md b/docs/rules-qt.md index dca5f1e..82d8490 100644 --- a/docs/rules-qt.md +++ b/docs/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, 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](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 @@ -76,8 +76,10 @@ A package that enables `rules-qt` only to import `mcpp.rules.qt`, and has no `bu | `private_modules` | modules whose private headers are included | | `moc`, `moc_headers` | `moc_scan::project_headers` (default) scans the package's headers by content; `moc_scan::listed` takes `moc_headers` only | | `forms`, `resources` | `.ui` and `.qrc` files beside those in `[build] sources` | -| `i18n` | `.ts` files beside those in `[build] sources`; `update_sources` runs `lupdate` as an action whose output is the `.ts` it rewrites, reading `sources`, or when that is empty the package's C++ sources and headers, found by the walk that finds moc's headers; `tr_function_alias`; `deploy_to` (default `translations`); `out_dir` (default `/qt/translations`); `qt_languages`: the linked modules' catalogs combined by `lconvert` into `qt_.qm`, the file windeployqt writes | +| `i18n` | `.ts` files beside those in `[build] sources`; `update_sources` runs `lupdate` as an action whose output is the `.ts` it rewrites, reading `sources`, or when that is empty the package's C++ sources and headers, found by the walk that finds moc's headers; `extensions` (default `cpp`, `h`, `hpp`, `ixx`, `cppm`: what `lupdate -extensions` reads and what the package walk collects; add `qml` and `js` for `qsTr` in QML); `tr_function_alias`; `deploy_to` (default `translations`); `out_dir` (default `/qt/translations`); `qt_languages`: the linked modules' catalogs combined by `lconvert` into `qt_.qm`, the file windeployqt writes | | `deploy_plugins` | plugin directories placed beside the program; default `platforms` | +| `moc_json` | `moc --output-json`: each `moc_.cpp` is accompanied by `moc_.cpp.json`, the type description `qmltyperegistrar` reads; default `false` | +| `moc_includes` | `moc` is given the SDK's include directories (`-I/include`, one `-I/include/Qt` per linked module, `-F/lib` on macOS, and there `-I/include` too, which the compiler is given as well: the header-only modules such as QtQmlIntegration are not frameworks), without which it drops `QML_ELEMENT` for want of the header that defines it; default `false` | | `deploy_software_gl` | Windows: `opengl32sw.dll` and `d3dcompiler_47.dll` beside the program | | `root`, `extra_roots` | level 1 of the SDK lookup | diff --git a/mcpp.toml b/mcpp.toml index be2f7bf..0b2fbfa 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] name = "plugins" namespace = "mcpp" -version = "0.26.1" +version = "0.27.0" # The first mcpp release that speaks protocol 17 (SPEC-013, mcpp#847): the # platform's directives `mcpp.plugins.platform` states (`link_driver`, # `link_input`, `artifact_name`, `seal`, `run_host`), the `platform` phase, and @@ -194,6 +194,16 @@ device_extensions = [".comp", ".vert", ".frag", ".geom", ".tesc", ".tese", ".mesh", ".task", ".rgen", ".rint", ".rahit", ".rchit", ".rmiss", ".rcall", ".glsl", ".hlsl"] +# `mcpp.rules.qml` -- QML applications on top of `rules-qt` (0.27.0): the +# chain `qt_add_qml_module` runs, Qt's own QML modules placed beside the program, +# `qt.conf`. It claims no file extension and names no `rule_module`: a `.qml` file +# needs a module URI and a version that `[build] sources` cannot state, so a +# project writes `host-module = true` and states its modules in `build.mcpp`. +# The implied `rules-qt` keeps its own `rule_module` for `.ui`, `.qrc` and `.ts`. +[features.rules-qml] +sources = ["rules/qml.cppm"] +implies = ["rules-qt", "plugins-core"] + [features.rules-sycl] sources = ["rules/sycl.cppm"] implies = ["plugins-core"] diff --git a/rules/qml.cppm b/rules/qml.cppm new file mode 100644 index 0000000..f77d086 --- /dev/null +++ b/rules/qml.cppm @@ -0,0 +1,1023 @@ +// mcpp.rules.qml -- how a QML application becomes part of a program. +// +// A Qt Quick program has inputs no C++ compiler reads, and a runtime that +// opens more than the program's import table names. `qml_module` is the unit a +// project states -- a URI, a version, the `.qml`/`.js` files, the headers of the +// C++ types it exposes -- and for each one the rule declares the chain Qt's +// `qt_add_qml_module` runs, as actions with declared inputs and outputs: +// +// header -> moc --output-json -> qmltyperegistrar -> registrations.cpp +// -> .qmltypes +// .qml .js .mjs -> qmlcachegen -> one .cpp each (the compiled form) +// qmldir, files -> rcc -> qrc_.cpp +// the files -> qmlcachegen loader -> _qmlcache_loader.cpp +// .vert .frag -> qsb -> embedded in the module's resources +// +// Every generated `.cpp` is a `role = "source"` action output, compiled and +// linked into the program, so a module of the application is static: it is in +// the executable and `QQmlEngine::loadFromModule("uri", "Type")` finds it. +// +// WHAT THE PROGRAM LOADS, THE RULE PLACES. A QML module of Qt itself +// (`QtQuick.Controls`, `QtQuick.Layouts`) is a directory of files and, usually, +// a plugin library, opened when a `.qml` file imports it. No import table names +// it, which is the job `windeployqt --qmldir` exists for. The rule reads the +// `import` statements of the project's `.qml` files and follows the SDK's +// `qmldir` files and the `.qml` files of the modules they name (the closure +// `qmlimportscanner` computes, by text, at plan time), then deploys each module +// under `qml/`, and a `qt.conf` that points Qt at them. The libraries a plugin +// loads are the engine's: `mcpp pack` takes what the build deploys beside the +// program as a root of its runtime closure. +// +// A MISSING SDK OR TOOL IS A WARNING, as in `mcpp.rules.qt`: the plan says what +// it could not find and declares what it can, so `mcpp emit build-database` +// plans a project on a machine that never built it. + +export module mcpp.rules.qml; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.plugins.fs; +import mcpp.rules.qt; + +export namespace mcpp::rules::qml { + +// One QML module of the application. +struct qml_module { + // `Probe`, `com.acme.ui`: required. + std::string uri; + // `major.minor`. + std::string version = "1.0"; + // The `.qml`, `.js` and `.mjs` files, as paths or globs relative to the + // package root. Any other file is a resource. + std::vector sources; + // The directory the module's files are relative to. Empty is the directory + // the sources have in common. + std::string root; + // Other files of the module (images, data), as paths or globs. + std::vector resources; + // The headers of the C++ types the module registers. Empty takes every + // header `moc` read that uses a `QML_*` macro, when the project has one + // module; with several, each header is assigned here. + std::vector headers; + // `depends` lines of the module's `qmldir`: modules it needs loaded. Stated, + // not derived. Empty by default. + std::vector depends; + // `import` lines of the module's `qmldir`: modules a user of this one gets + // imported with it. Stated, not derived. + std::vector imports; + // `.vert`, `.frag`, `.comp` files compiled by `qsb` and embedded as + // `shaders/.qsb`. + std::vector shaders; + std::vector qsb_args = { "--qt6" }; + // Compile the files ahead of time (`qmlcachegen`). `false` embeds the + // sources only. + bool aot = true; + // The resource prefix; the module's files are under `/`. + std::string prefix = "/qt/qml"; +}; + +struct options { + std::vector modules; + // Everything `mcpp.rules.qt` takes: the modules, the plugins, the SDK, the + // translations. `Qml` is always linked. + qt::options qt; + // Plugin directories a Qt Quick program needs, placed beside the program + // with `qt.deploy_plugins`. Only those the SDK has are placed. Set it empty + // to place none. + std::vector quick_plugins = { "xcbglintegrations", "platforminputcontexts", "imageformats" }; + // Qt modules the program loads that no `.qml` file imports (`Qt.createComponent` + // with a computed name): `"QtQuick.Controls.Material"`. + std::vector imports; + // When not empty, an `optional import` of a style is followed only for + // these (`"Material"`, `"Basic"`); empty follows every style, so any can be chosen. + std::vector styles; + // Directories of QML modules beyond the SDK's (each holds `/qmldir`). + std::vector import_paths; + // Place the Qt modules the program imports beside it (`qml/`). + bool deploy_imports = true; + // Write `qt.conf` and place it beside the program: `Prefix = .`, + // `Qml2Imports = qml`. Qt then takes its data, translations and QML modules + // from the program's directory. A project that has its own `qt.conf` keeps it. + bool write_qt_conf = true; + // Run `qmllint` on every `.qml` file as a check. + bool lint = false; + bool lint_warnings_are_errors = false; +}; + +// The directory holding every module's `qmldir`, the import root of the tools. +inline std::string import_root(const options& opt) { + return qt::detail::generic(std::filesystem::path(opt.qt.out_dir) / "qml"); +} + +namespace detail { + +namespace fs = std::filesystem; +using qt::detail::generic; +using qt::detail::warn; + +// ─── Text ────────────────────────────────────────────────────────────────── + +inline bool word_char(char c) { + return std::isalnum(static_cast(c)) || c == '_'; +} + +// `com.acme.ui`: identifiers joined by dots. A uri names a directory, so the +// grammar is also what keeps a path out of one. +inline bool valid_uri(const std::string& u) { + if (u.empty()) return false; + bool start = true; + for (std::size_t i = 0; i < u.size(); ++i) { + const char c = u[i]; + if (start) { + if (!(std::isalpha(static_cast(c)) || c == '_')) return false; + start = false; + } else if (c == '.') { + start = true; + } else if (!word_char(c)) { + return false; + } + } + return !start; +} + +inline std::string replaced(std::string s, char from, char to) { + for (std::size_t i = 0; i < s.size(); ++i) if (s[i] == from) s[i] = to; + return s; +} +inline std::string uri_path(const std::string& uri) { return replaced(uri, '.', '/'); } +inline std::string sanitize(const std::string& uri) { return replaced(uri, '.', '_'); } + +inline bool parse_version(const std::string& v, int& major, int& minor) { + const auto dot = v.find('.'); + if (dot == std::string::npos || dot == 0 || dot + 1 >= v.size()) return false; + int a = 0, b = 0; + for (std::size_t i = 0; i < v.size(); ++i) { + if (i == dot) continue; + if (!std::isdigit(static_cast(v[i]))) return false; + int& n = i < dot ? a : b; + n = n * 10 + (v[i] - '0'); + if (n > 65535) return false; + } + major = a; + minor = b; + return true; +} + +inline std::string xml_escape(const std::string& s) { + std::string out; + for (std::size_t i = 0; i < s.size(); ++i) { + switch (s[i]) { + case '&': out += "&"; break; + case '<': out += "<"; break; + case '>': out += ">"; break; + case '"': out += """; break; + default: out += s[i]; + } + } + return out; +} + +inline std::string trimmed(const std::string& s) { + std::size_t b = 0, e = s.size(); + while (b < e && std::isspace(static_cast(s[b]))) ++b; + while (e > b && std::isspace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +inline std::vector words(const std::string& s) { + std::vector out; + std::string cur; + for (std::size_t i = 0; i < s.size(); ++i) { + if (std::isspace(static_cast(s[i]))) { + if (!cur.empty()) { out.push_back(cur); cur.clear(); } + } else { + cur += s[i]; + } + } + if (!cur.empty()) out.push_back(cur); + return out; +} + +// A QML or JavaScript text without its comments and the contents of its +// strings, so an `import` inside either is not read as one. +inline std::string without_comments_and_strings(const std::string& t) { + std::string out; + std::size_t i = 0; + while (i < t.size()) { + const char c = t[i]; + if (c == '/' && i + 1 < t.size() && t[i + 1] == '/') { + while (i < t.size() && t[i] != '\n') ++i; + } else if (c == '/' && i + 1 < t.size() && t[i + 1] == '*') { + const auto end = t.find("*/", i + 2); + const std::size_t stop = end == std::string::npos ? t.size() : end + 2; + // A line break inside the comment stays one: `import` is read a line at a time. + out += ' '; + for (; i < stop; ++i) + if (t[i] == '\n') out += '\n'; + } else if (c == '"' || c == '\'' || c == '`') { + std::size_t j = i + 1; + // Only a template literal spans lines; a quote left open ends at the line. + while (j < t.size() && t[j] != c && (c == '`' || t[j] != '\n')) j += t[j] == '\\' ? 2 : 1; + out += c; + out += c; + i = j < t.size() && t[j] == c ? j + 1 : j; + } else { + out += c; + ++i; + } + } + return out; +} + +inline bool version_token(const std::string& s) { + if (s.empty() || !std::isdigit(static_cast(s[0]))) return false; + for (std::size_t i = 0; i < s.size(); ++i) + if (!std::isdigit(static_cast(s[i])) && s[i] != '.') return false; + return true; +} + +// The modules a `.qml` file imports: `import [version] [as Name]`, one +// per line, with an optional `;`. `import "dir"` and `import "File.js" as U` +// name files and are not modules. +inline std::vector imports_of(const std::string& text) { + std::vector out; + const std::string clean = without_comments_and_strings(text); + std::size_t at = 0; + while (at <= clean.size()) { + auto nl = clean.find('\n', at); + std::string line = clean.substr(at, nl == std::string::npos ? std::string::npos : nl - at); + at = nl == std::string::npos ? clean.size() + 1 : nl + 1; + line = trimmed(line); + if (!line.empty() && line.back() == ';') line.pop_back(); + const auto w = words(line); + if (w.size() < 2 || w[0] != "import" || !valid_uri(w[1])) continue; + bool shape = w.size() == 2 + || (w.size() == 3 && version_token(w[2])) + || (w.size() == 4 && w[2] == "as") + || (w.size() == 5 && version_token(w[2]) && w[3] == "as"); + if (shape) out.push_back(w[1]); + } + return out; +} + +inline bool declares_singleton(const std::string& text) { + const std::string clean = without_comments_and_strings(text); + for (std::size_t at = clean.find("pragma"); at != std::string::npos; at = clean.find("pragma", at + 1)) { + std::size_t i = at + 6; + while (i < clean.size() && (clean[i] == ' ' || clean[i] == '\t')) ++i; + if (clean.compare(i, 9, "Singleton") == 0 && (i + 9 >= clean.size() || !word_char(clean[i + 9]))) return true; + } + return false; +} + +// A header that uses one of the macros `qmltyperegistrar` reads. +inline bool declares_qml_types(const std::string& text) { + for (auto m : { "QML_ELEMENT", "QML_NAMED_ELEMENT", "QML_SINGLETON", "QML_ANONYMOUS", "QML_FOREIGN", + "QML_UNCREATABLE", "QML_EXTENDED", "QML_ATTACHED", "QML_VALUE_TYPE", "QML_INTERFACE" }) { + const std::size_t n = std::strlen(m); + for (std::size_t at = text.find(m); at != std::string::npos; at = text.find(m, at + 1)) { + const bool left = at == 0 || !word_char(text[at - 1]); + const bool right = at + n >= text.size() || !word_char(text[at + n]); + if (left && right) return true; + } + } + return false; +} + +// ─── Files ───────────────────────────────────────────────────────────────── + +inline bool has_wildcard(const std::string& s) { return s.find_first_of("*?") != std::string::npos; } + +// `*` and `?` do not cross a `/`; `**/` is any number of directories. +inline bool glob_match(std::string_view p, std::string_view t) { + if (p.empty()) return t.empty(); + if (p.starts_with("**")) { + std::string_view rest = p.substr(2); + const bool dirs = rest.starts_with("/"); + if (dirs) rest.remove_prefix(1); + for (std::size_t i = 0; i <= t.size(); ++i) { + if (dirs && !(i == 0 || t[i - 1] == '/')) continue; + if (glob_match(rest, t.substr(i))) return true; + } + return false; + } + if (p[0] == '*') { + for (std::size_t i = 0; i <= t.size(); ++i) { + if (glob_match(p.substr(1), t.substr(i))) return true; + if (i < t.size() && t[i] == '/') break; + } + return false; + } + if (t.empty()) return false; + if (p[0] == '?') return t[0] != '/' && glob_match(p.substr(1), t.substr(1)); + return p[0] == t[0] && glob_match(p.substr(1), t.substr(1)); +} + +inline bool skipped_directory(const fs::path& dir) { + const auto name = dir.filename().string(); + return name == "target" || name == ".git" || name == "mcpp-generated" || name == "vcpkg_installed" || + name == "node_modules" || mcpp::plugins::tree::build_output(dir); +} + +// The files a path or glob (relative to the package root) names, sorted. A file +// the plan reads is declared with `rerun_if_changed`; a glob, with the glob. +inline std::vector expand(const std::string& given) { + std::string pattern = given; + if (pattern.starts_with("./")) pattern.erase(0, 2); + std::vector out; + std::error_code ec; + if (!has_wildcard(pattern)) { + const auto p = qt::detail::absolute_from_root(pattern); + if (fs::is_regular_file(p, ec)) out.push_back(p); + return out; + } + mcpp::rerun_if_changed_glob(pattern.c_str()); + const auto first = pattern.find_first_of("*?"); + const auto slash = pattern.rfind('/', first); + const fs::path root = mcpp::manifest_dir(); + const fs::path base = slash == std::string::npos ? root : root / pattern.substr(0, slash); + for (auto it = fs::recursive_directory_iterator(base, fs::directory_options::skip_permission_denied, ec); + !ec && it != fs::recursive_directory_iterator(); it.increment(ec)) { + if (it->is_directory(ec)) { + if (skipped_directory(it->path())) it.disable_recursion_pending(); + continue; + } + if (!it->is_regular_file(ec)) continue; + if (glob_match(pattern, generic(it->path().lexically_relative(root)))) out.push_back(it->path()); + } + std::ranges::sort(out); + return out; +} + +inline std::vector expand_all(const std::vector& patterns, const std::string& who, + const std::string& what) { + std::vector out; + for (auto const& p : patterns) { + auto found = expand(p); + if (found.empty()) + warn(std::format("{}: `{}` of {} names no file.", who, p, what)); + for (auto const& f : found) + if (std::ranges::find(out, f) == out.end()) out.push_back(f); + } + std::ranges::sort(out); + return out; +} + +inline bool is_script(const fs::path& p) { + const auto e = p.extension().string(); + return e == ".qml" || e == ".js" || e == ".mjs"; +} + +// The directory the files have in common, by whole directory names. +inline fs::path common_directory(const std::vector& files) { + if (files.empty()) return {}; + auto parts = [](const fs::path& f) { + std::vector out; + const std::string g = generic(f.parent_path()); + std::size_t at = 0; + while (at <= g.size()) { + const auto slash = g.find('/', at); + out.push_back(g.substr(at, slash == std::string::npos ? std::string::npos : slash - at)); + at = slash == std::string::npos ? g.size() + 1 : slash + 1; + } + return out; + }; + std::vector common = parts(files.front()); + for (auto const& f : files) { + const auto d = parts(f); + std::size_t n = 0; + while (n < common.size() && n < d.size() && common[n] == d[n]) ++n; + common.resize(n); + } + std::string out; + for (std::size_t i = 0; i < common.size(); ++i) out += (i ? "/" : "") + common[i]; + return fs::path(out.empty() ? "/" : out); +} + +// ─── Qt's own modules: the import closure ────────────────────────────────── + +struct module_dir { + std::string uri; + fs::path dir; // holds the module's `qmldir` +}; + +struct imports_found { + std::vector modules; // in uri order + std::vector unresolved; // imported, and in no SDK or import path +}; + +inline bool is_style_import(const std::string& uri, const std::vector& styles) { + if (styles.empty()) return true; + const auto dot = uri.rfind('.'); + const std::string last = dot == std::string::npos ? uri : uri.substr(dot + 1); + return std::ranges::find(styles, last) != styles.end(); +} + +// The modules an import of `uri` brings: the `import`, `default import`, +// `optional import` and `depends` lines of its `qmldir`, and the `import` +// statements of the `.qml` files in its directory (not in a directory that is a +// module of its own). Measured equal to `qmlimportscanner`'s answer on Qt 6.11.1. +inline std::vector module_dependencies(const fs::path& dir, const std::vector& styles) { + std::vector deps; + std::istringstream in(qt::detail::read_file(dir / "qmldir")); + for (std::string line; std::getline(in, line); ) { + const auto w = words(line); + if (w.empty()) continue; + if ((w[0] == "optional" || w[0] == "default") && w.size() >= 3 && w[1] == "import") { + if (w[0] == "default" || is_style_import(w[2], styles)) deps.push_back(w[2]); + } else if ((w[0] == "import" || w[0] == "depends") && w.size() >= 2) { + deps.push_back(w[1]); + } + } + std::error_code ec; + std::vector pending = { dir }; + while (!pending.empty()) { + const fs::path d = pending.back(); + pending.pop_back(); + std::vector entries; + for (auto const& e : fs::directory_iterator(d, ec)) entries.push_back(e.path()); + std::ranges::sort(entries); + for (auto const& p : entries) { + if (fs::is_directory(p, ec)) { + if (!fs::exists(p / "qmldir", ec)) pending.push_back(p); + } else if (p.extension() == ".qml") { + for (auto const& i : imports_of(qt::detail::read_file(p))) deps.push_back(i); + } + } + } + return deps; +} + +inline imports_found import_closure(std::vector roots, const std::vector& own, + const std::vector& import_dirs, const std::vector& styles) { + imports_found out; + std::set seen; + std::error_code ec; + while (!roots.empty()) { + const std::string uri = roots.back(); + roots.pop_back(); + if (!seen.insert(uri).second || std::ranges::find(own, uri) != own.end()) continue; + fs::path dir; + for (auto const& d : import_dirs) + if (fs::is_regular_file(d / uri_path(uri) / "qmldir", ec)) { dir = d / uri_path(uri); break; } + if (dir.empty()) { out.unresolved.push_back(uri); continue; } + out.modules.push_back({ uri, dir }); + for (auto const& d : module_dependencies(dir, styles)) roots.push_back(d); + } + std::ranges::sort(out.modules, {}, &module_dir::uri); + std::ranges::sort(out.unresolved); + return out; +} + +// The files of a Qt module that go beside the program: everything in its +// directory except what is not run time (`qt_sdk`: and, as only Qt's own SDK +// does, the debug twin of a library), and except a directory that is a +// module of its own (it is deployed when it is imported). +inline std::vector module_files(const fs::path& dir, bool qt_sdk) { + std::vector out; + std::error_code ec; + std::vector pending = { dir }; + while (!pending.empty()) { + const fs::path d = pending.back(); + pending.pop_back(); + std::vector entries; + for (auto const& e : fs::directory_iterator(d, ec)) entries.push_back(e.path()); + std::ranges::sort(entries); + for (auto const& p : entries) { + if (fs::is_directory(p, ec)) { + if (p.filename() == "designer" || fs::exists(p / "qmldir", ec)) continue; + pending.push_back(p); + continue; + } + const auto ext = p.extension().string(); + if (ext == ".qmltypes" || ext == ".prl" || ext == ".debug" || ext == ".pdb") continue; + // The Windows SDK ships each plugin twice, `x.dll` and the debug `xd.dll`. + if (qt_sdk && qt::detail::is_windows() && ext == ".dll") { + const auto stem = p.stem().string(); + if (stem.ends_with("d") && fs::exists(p.parent_path() / (stem.substr(0, stem.size() - 1) + ".dll"), ec)) + continue; + } + out.push_back(p); + } + } + std::ranges::sort(out); + return out; +} + +// ─── Generated text ──────────────────────────────────────────────────────── + +inline std::string qmldir_text(const qml_module& m, bool types, const std::string& resource_dir, + const std::vector>& files) { + std::string t = "module " + m.uri + "\n"; + if (types) t += "typeinfo " + sanitize(m.uri) + ".qmltypes\n"; + t += "prefer :" + resource_dir + "/\n"; + for (auto const& d : m.depends) t += "depends " + d + "\n"; + for (auto const& i : m.imports) t += "import " + i + "\n"; + for (auto const& [file, rel] : files) { + if (file.extension() != ".qml") continue; + const std::string name = file.stem().string(); + if (name.empty() || !std::isupper(static_cast(name[0]))) continue; + t += (declares_singleton(qt::detail::read_file(file)) ? "singleton " : "") + name + " " + m.version + " " + rel + "\n"; + } + return t; +} + +inline std::string qrc_text(const std::string& resource_prefix, const std::string& qmldir, + const std::vector>& files /* alias, path */) { + std::string t = "\n \n"; + t += " " + xml_escape(qmldir) + "\n"; + for (auto const& [alias, path] : files) + t += " " + xml_escape(path) + "\n"; + t += " \n\n"; + return t; +} + +// ─── Actions ─────────────────────────────────────────────────────────────── + +struct step { + std::string id; + std::string description; + std::vector argv; + std::vector inputs; + std::vector outputs; + std::vector> env; + std::string depfile; // a Make-style file the command writes, when it can + const char* role = mcpp::roles::source; +}; + +inline void submit(const step& s) { + mcpp::action a; + a.id = s.id.c_str(); + a.role = s.role; + a.description = s.description.c_str(); + if (!s.depfile.empty()) a.depfile = s.depfile.c_str(); + for (auto const& x : s.argv) a.arg(x.c_str()); + for (auto const& x : s.inputs) a.input(x.c_str()); + for (auto const& x : s.outputs) a.output(x.c_str()); + for (auto const& [k, v] : s.env) a.env(k.c_str(), v.c_str()); + a.submit(); +} + +inline std::string flattened(const std::string& rel) { + return replaced(replaced(rel, '/', '_'), '.', '_'); +} + +// What a module is once its files and headers are known. +struct planned { + const qml_module* module = nullptr; + std::string san, upath, resource_dir; + int major = 1, minor = 0; + fs::path root; + std::vector> files; // scripts, then resources: file, relative path + std::vector shaders; + std::vector units; // its C++ types + fs::path dir, work, qmldir, qmltypes, qrc; +}; + +inline bool unsupported_target() { + const std::string_view os = mcpp::target_os(); + return os != "linux" && os != "windows" && os != "macos"; +} + +inline std::string joined(const std::vector& v, const char* sep) { + std::string out; + for (std::size_t i = 0; i < v.size(); ++i) out += (i ? sep : "") + v[i]; + return out; +} + +// A `qt.conf` the project carries itself: beside its sources, in `res/`, or as +// `/qt/etc/qt.conf` in a resource file (Qt reads that one before any file). +inline bool project_has_qt_conf(const qt::options& q) { + std::error_code ec; + const fs::path root = mcpp::manifest_dir(); + mcpp::rerun_if_changed_glob("**/qt.conf"); + for (auto const* p : { "qt.conf", "res/qt.conf", "resources/qt.conf" }) + if (fs::is_regular_file(root / p, ec)) return true; + std::vector qrcs = qt::detail::device(".qrc"); + for (auto const& r : q.resources) qrcs.push_back(r); + for (auto const& r : qrcs) + if (qt::detail::read_file(qt::detail::absolute_from_root(r)).find("prefix=\"/qt/etc\"") != std::string::npos) return true; + return false; +} + +} // namespace detail + +// ─── The rule ────────────────────────────────────────────────────────────── + +inline bool compile(options opt) { + namespace fs = std::filesystem; + using detail::generic; + constexpr std::string_view who = "mcpp.rules.qml"; + + if (detail::unsupported_target()) { + detail::warn(std::format("{}: QML is built for linux, windows and macos; {} is not planned.", who, + std::string(mcpp::target_os()))); + return true; + } + + // ── what the project states, checked before anything is declared ── + std::set uris, names; + for (auto const& m : opt.modules) { + int a, b; + if (!detail::valid_uri(m.uri)) { + std::cerr << std::format("{}: `{}` is not a module uri: identifiers joined by dots (`com.acme.ui`).\n", who, m.uri); + return false; + } + if (!detail::parse_version(m.version, a, b)) { + std::cerr << std::format("{}: the version `{}` of {} is not `major.minor`.\n", who, m.version, m.uri); + return false; + } + if (!uris.insert(m.uri).second || !names.insert(detail::sanitize(m.uri)).second) { + std::cerr << std::format("{}: the module {} is stated twice (or `a.b` and `a_b`, which name one generated file).\n", who, m.uri); + return false; + } + if (m.prefix.empty() || m.prefix.front() != '/' || m.prefix.back() == '/') { + std::cerr << std::format("{}: the prefix `{}` of {} is a resource path such as `/qt/qml`.\n", who, m.prefix, m.uri); + return false; + } + } + + // ── Qt: the generators, with the type description the registrar reads ── + if (std::ranges::find(opt.qt.modules, "Qml") == opt.qt.modules.end() && + std::ranges::find(opt.qt.modules, "QtQml") == opt.qt.modules.end() && + std::ranges::find(opt.qt.modules, "Qt6Qml") == opt.qt.modules.end()) + opt.qt.modules.push_back("Qml"); + opt.qt.moc_json = true; + opt.qt.moc_includes = true; + if (opt.qt.i18n.update_sources) + for (auto const* e : { "qml", "js" }) + if (std::ranges::find(opt.qt.i18n.extensions, std::string(e)) == opt.qt.i18n.extensions.end()) + opt.qt.i18n.extensions.push_back(e); + // The plugin directories a Qt Quick program needs, the ones the SDK has. + { + std::error_code ec; + const auto roots = qt::roots(opt.qt); + for (auto const& dir : opt.quick_plugins) { + if (std::ranges::find(opt.qt.deploy_plugins, dir) != opt.qt.deploy_plugins.end()) continue; + for (auto const& r : roots) + if (std::filesystem::is_directory(r / "plugins" / dir, ec)) { opt.qt.deploy_plugins.push_back(dir); break; } + } + } + qt::outcome built = qt::compile_ex(opt.qt); + if (!built.ok) return false; + const auto& sdks = built.source.roots; + if (sdks.empty()) return true; // `mcpp.rules.qt` has said so + mcpp::fact("rules-qml.sdk", generic(sdks.front()).c_str()); + + const fs::path main = sdks.front(); + const fs::path gen = fs::path(opt.qt.out_dir) / "qml"; + std::error_code ec; + fs::create_directories(gen, ec); + + // The import directories: the project's, then every SDK's `qml/`. + std::vector import_dirs; + for (auto const& p : opt.import_paths) import_dirs.push_back(qt::detail::absolute_from_root(p)); + for (auto const& r : sdks) + if (fs::is_directory(r / "qml", ec)) import_dirs.push_back(r / "qml"); + + const std::string rcc = qt::detail::tool(sdks, "rcc"); + const std::string registrar = qt::detail::tool(sdks, "qmltyperegistrar"); + const std::string cachegen = qt::detail::tool(sdks, "qmlcachegen"); + + // ── the modules: files, headers ── + std::vector plan; + for (auto const& m : opt.modules) { + for (auto const& r : sdks) + if (fs::is_regular_file(r / "qml" / detail::uri_path(m.uri) / "qmldir", ec)) { + std::cerr << std::format("{}: the module {} is a module of the Qt SDK at {}; name your own.\n", who, m.uri, + generic(r / "qml" / detail::uri_path(m.uri))); + return false; + } + detail::planned p; + p.module = &m; + p.san = detail::sanitize(m.uri); + p.upath = detail::uri_path(m.uri); + p.resource_dir = m.prefix + "/" + p.upath; + detail::parse_version(m.version, p.major, p.minor); + std::vector scripts, rest; + auto place = [&](const fs::path& f) { + auto& v = detail::is_script(f) ? scripts : rest; + if (std::ranges::find(v, f) == v.end()) v.push_back(f); + }; + for (auto const& f : detail::expand_all(m.sources, std::string(who), "module " + m.uri)) place(f); + for (auto const& f : detail::expand_all(m.resources, std::string(who), "module " + m.uri)) place(f); + std::ranges::sort(scripts); + std::ranges::sort(rest); + std::vector everything = scripts; + everything.insert(everything.end(), rest.begin(), rest.end()); + p.root = m.root.empty() ? detail::common_directory(everything) : qt::detail::absolute_from_root(m.root); + for (auto const& f : everything) { + const std::string rel = generic(f.lexically_relative(p.root)); + if (rel.empty() || rel.starts_with("..")) { + std::cerr << std::format("{}: {} is not under the root {} of module {}.\n", who, generic(f), generic(p.root), m.uri); + return false; + } + p.files.emplace_back(f, rel); + } + for (auto const& s : detail::expand_all(m.shaders, std::string(who), "module " + m.uri)) p.shaders.push_back(s); + p.dir = gen / p.upath; + p.work = gen / p.san; + p.qmldir = p.dir / "qmldir"; + p.qmltypes = p.dir / (p.san + ".qmltypes"); + p.qrc = p.work / (p.san + ".qrc"); + plan.push_back(std::move(p)); + } + + // Which header belongs to which module. Every header `moc` read that uses a + // QML macro belongs to exactly one. + { + std::map owner; // header -> uri + std::vector qml_units; + for (auto const& u : built.mocs) + if (detail::declares_qml_types(qt::detail::read_file(u.header))) qml_units.push_back(&u); + for (auto& p : plan) { + for (auto const& h : detail::expand_all(p.module->headers, std::string(who), "module " + p.module->uri)) { + const std::string g = generic(h); + const auto unit = std::ranges::find_if(built.mocs, [&](auto const& u) { return u.header == g; }); + if (unit == built.mocs.end()) { + detail::warn(std::format("{}: {} is listed for module {} and `moc` read no meta-object in it.", who, g, p.module->uri)); + continue; + } + if (auto [it, fresh] = owner.try_emplace(g, p.module->uri); !fresh) { + std::cerr << std::format("{}: {} is listed for both {} and {}.\n", who, g, it->second, p.module->uri); + return false; + } + p.units.push_back(*unit); + } + } + const bool explicit_headers = std::ranges::any_of(plan, [](auto const& p) { return !p.module->headers.empty(); }); + for (auto const* u : qml_units) { + if (owner.contains(u->header)) continue; + if (plan.size() == 1 && !explicit_headers) { + plan.front().units.push_back(*u); + } else { + std::cerr << std::format("{}: {} registers QML types and belongs to no module; list it in the `headers` of one.\n", + who, u->header); + return false; + } + } + } + + // ── the tools a module needs ── + const bool have_modules = !plan.empty(); + bool aot_possible = !cachegen.empty(); + if (have_modules && rcc.empty()) { + detail::warn(std::format("{}: `rcc` not found under {}; no QML module is built. QML needs the `xim:qt` payload: " + "`xim:qt-base` carries the QtQml library only, without Quick.", who, generic(main))); + plan.clear(); + } + if (have_modules && !plan.empty() && cachegen.empty()) + detail::warn(std::format("{}: `qmlcachegen` not found under {}; the files are embedded as source, not compiled.", who, generic(main))); + const bool can_register = !registrar.empty(); + if (have_modules && !plan.empty() && !can_register) + detail::warn(std::format("{}: `qmltyperegistrar` not found under {}; C++ types are not registered.", who, generic(main))); + + // Every module's metadata is an input of every other's compiled form. + std::vector metadata; + for (auto const& p : plan) { + metadata.push_back(generic(p.qmldir)); + if (!p.units.empty() && can_register) metadata.push_back(generic(p.qmltypes)); + } + std::string foreign_sdk; + { + std::vector sdk_json; + auto add_json = [&](const std::string& module) { + std::string lower = module; + for (std::size_t i = 0; i < lower.size(); ++i) lower[i] = char(std::tolower(static_cast(lower[i]))); + for (auto const& r : sdks) { + const fs::path f = r / "metatypes" / ("qt6" + lower + "_metatypes.json"); + if (fs::is_regular_file(f, ec)) { sdk_json.push_back(generic(f)); return; } + } + }; + add_json("Core"); + for (auto const& m : built.linked) if (m != "Core") add_json(m); + foreign_sdk = detail::joined(sdk_json, ","); + } + std::set include_dirs; + std::set claimed; + auto claim = [&](const std::string& name, const std::string& from) { + if (claimed.insert(name).second) return true; + std::cerr << std::format("{}: two files produce `{}` (one is {}); rename one.\n", who, name, from); + return false; + }; + + for (auto const& p : plan) { + const auto& m = *p.module; + fs::create_directories(p.dir, ec); + fs::create_directories(p.work, ec); + const bool types = !p.units.empty() && can_register; + + // The files the plan reads, and what it writes from them. + for (auto const& [file, rel] : p.files) + if (file.extension() == ".qml") mcpp::rerun_if_changed(generic(file).c_str()); + mcpp::plugins::fs::write_if_changed(p.qmldir, detail::qmldir_text(m, types, p.resource_dir, p.files)); + + std::vector> qrc_files; + for (auto const& [file, rel] : p.files) { + if (!claim(p.san + "/" + rel, generic(file))) return false; + qrc_files.emplace_back(rel, generic(file)); + } + // Shaders are compiled when `qsb` is there; without it they are left out of the + // resources, so the build still links and the warning says what is missing. + std::string qsb; + if (!p.shaders.empty()) { + qsb = qt::detail::tool(sdks, "qsb"); + if (qsb.empty()) + detail::warn(std::format("{}: `qsb` not found; it is part of the additional libraries (`xim:qt-addons`), and " + "the shaders of {} are not compiled.", who, m.uri)); + } + std::vector qsb_outputs; + if (!qsb.empty()) { + fs::create_directories(p.work / "shaders", ec); + for (auto const& s : p.shaders) { + const std::string name = s.filename().string() + ".qsb"; + if (!claim(p.san + "/shaders/" + name, generic(s))) return false; + const std::string out = generic(p.work / "shaders" / name); + qrc_files.emplace_back("shaders/" + name, out); + qsb_outputs.push_back(out); + } + } + mcpp::plugins::fs::write_if_changed(p.qrc, detail::qrc_text(p.resource_dir, generic(p.qmldir), qrc_files)); + + // C++ types: the type description, then the registrations. + if (types) { + // What the registrar reads as its own, and what it may only refer to: the + // SDK's types and every other moc'd header, a plain base class included. + std::vector jsons, foreign; + if (!foreign_sdk.empty()) foreign.push_back(foreign_sdk); + const std::size_t sdk_entries = foreign.size(); + for (auto const& u : p.units) jsons.push_back(u.json); + for (auto const& u : built.mocs) + if (!u.json.empty() && std::ranges::find(jsons, u.json) == jsons.end()) foreign.push_back(u.json); + const std::string regs = generic(p.work / (p.san + "_qmltyperegistrations.cpp")); + if (!claim(p.san + "_qmltyperegistrations.cpp", p.module->uri)) return false; + detail::step s; + s.id = "qml:registrar:" + m.uri; + s.description = "QMLTYPEREGISTRAR " + m.uri; + s.argv = { registrar, "--generate-qmltypes=" + generic(p.qmltypes), "--import-name=" + m.uri, + "--major-version=" + std::to_string(p.major), "--minor-version=" + std::to_string(p.minor), + "--foreign-types=" + detail::joined(foreign, ","), "-o", regs }; + for (auto const& j : jsons) s.argv.push_back(j); + s.inputs = jsons; + for (std::size_t i = sdk_entries; i < foreign.size(); ++i) s.inputs.push_back(foreign[i]); + s.outputs = { regs, generic(p.qmltypes) }; + detail::submit(s); + for (auto const& u : p.units) include_dirs.insert(generic(fs::path(u.header).parent_path())); + } + + // Shaders. + for (std::size_t i = 0; i < qsb_outputs.size(); ++i) { + detail::step s; + s.id = "qml:qsb:" + m.uri + ":" + p.shaders[i].filename().string(); + s.description = "QSB " + p.shaders[i].filename().string(); + s.argv = { qsb }; + for (auto const& a : m.qsb_args) s.argv.push_back(a); + s.argv.push_back("-o"); + s.argv.push_back(qsb_outputs[i]); + s.argv.push_back(generic(p.shaders[i])); + s.inputs = { generic(p.shaders[i]) }; + s.outputs = { qsb_outputs[i] }; + // A library directory the tool loads from, for an SDK whose tools are not + // already linked to it. + if (!qt::detail::is_windows() && !qt::detail::is_macos()) { + std::vector libs; + for (auto const& r : sdks) libs.push_back(generic(r / "lib")); + s.env.emplace_back("LD_LIBRARY_PATH", detail::joined(libs, ":")); + } + detail::submit(s); + } + + // The resources. + { + const std::string out = generic(p.work / ("qrc_" + p.san + ".cpp")); + if (!claim("qrc_" + p.san + ".cpp", m.uri)) return false; + detail::step s; + s.id = "qml:rcc:" + m.uri; + s.description = "RCC " + m.uri; + // `rcc --depfile` lists the files the qrc names: what the action reads + // beyond the inputs it declares (a file the qrc gains is one). + s.depfile = out + ".d"; + s.argv = { rcc, "--name", p.san, "--depfile", s.depfile, generic(p.qrc), "-o", out }; + s.inputs = { generic(p.qrc), generic(p.qmldir) }; + for (auto const& [file, rel] : p.files) s.inputs.push_back(generic(file)); + for (auto const& q : qsb_outputs) s.inputs.push_back(q); + s.outputs = { out }; + detail::submit(s); + } + + // The compiled form of each file, and the loader that registers them. + if (m.aot && aot_possible) { + std::string rsp = "--resource\n" + generic(p.qrc) + "\n"; + for (auto const& [file, rel] : p.files) { + if (!detail::is_script(file)) continue; + const std::string out = generic(p.work / (p.san + "_" + detail::flattened(rel) + ".cpp")); + if (!claim(p.san + "_" + detail::flattened(rel) + ".cpp", generic(file))) return false; + detail::step s; + s.id = "qml:cachegen:" + m.uri + ":" + rel; + s.description = "QMLCACHEGEN " + rel; + s.argv = { cachegen, "--bare", "--resource-path", p.resource_dir + "/" + rel }; + for (auto const& d : import_dirs) { s.argv.push_back("-I"); s.argv.push_back(generic(d)); } + s.argv.insert(s.argv.end(), { "-I", generic(gen), "-i", generic(p.qmldir), "--resource", generic(p.qrc), "-o", out, generic(file) }); + s.inputs = { generic(file), generic(p.qrc) }; + for (auto const& x : metadata) s.inputs.push_back(x); + s.outputs = { out }; + detail::submit(s); + rsp += p.resource_dir + "/" + rel + "\n"; + } + const fs::path rsp_file = p.work / "loader.rsp"; + mcpp::plugins::fs::write_if_changed(rsp_file, rsp); + const std::string loader = generic(p.work / (p.san + "_qmlcache_loader.cpp")); + if (!claim(p.san + "_qmlcache_loader.cpp", m.uri)) return false; + detail::step s; + s.id = "qml:cachegen:" + m.uri + ":loader"; + s.description = "QMLCACHEGEN " + m.uri + " loader"; + // The output must end in `qmlcache_loader.cpp`: that name is how + // `qmlcachegen` is told to write the loader and not one file. + s.argv = { cachegen, "--resource-name", "qmlcache_" + p.san, "-o", loader, "@" + generic(rsp_file) }; + s.inputs = { generic(rsp_file), generic(p.qrc) }; + s.outputs = { loader }; + detail::submit(s); + } + + // The check. + if (opt.lint) { + const std::string lint = qt::detail::tool(sdks, "qmllint"); + if (lint.empty()) { + detail::warn(std::format("{}: `qmllint` not found under {}; the files are not checked.", who, generic(main))); + } else { + for (auto const& [file, rel] : p.files) { + if (file.extension() != ".qml") continue; + detail::step s; + s.role = mcpp::roles::check; + s.id = "qml:lint:" + m.uri + ":" + rel; + s.description = "QMLLINT " + rel; + s.argv = { lint, "-I", generic(gen) }; + for (auto const& d : import_dirs) { s.argv.push_back("-I"); s.argv.push_back(generic(d)); } + if (opt.lint_warnings_are_errors) { s.argv.push_back("--max-warnings"); s.argv.push_back("0"); } + s.argv.push_back(generic(file)); + s.inputs = { generic(file) }; + for (auto const& x : metadata) s.inputs.push_back(x); + detail::submit(s); + } + } + } + } + for (auto const& d : include_dirs) mcpp::include_dir(d.c_str()); + + // ── Qt's own modules the program imports ── + if (opt.deploy_imports) { + std::vector roots = opt.imports, own; + for (auto const& p : plan) own.push_back(p.module->uri); + for (auto const& m : opt.modules) { + // A module whose tools did not run is still the project's. + if (std::ranges::find(own, m.uri) == own.end()) own.push_back(m.uri); + } + for (auto const& p : plan) + for (auto const& [file, rel] : p.files) + if (file.extension() == ".qml") + for (auto const& i : detail::imports_of(qt::detail::read_file(file))) roots.push_back(i); + const auto found = detail::import_closure(roots, own, import_dirs, opt.styles); + + std::vector notes, missing_qt; + for (auto const& u : found.unresolved) (u.starts_with("Qt") ? missing_qt : notes).push_back(u); + if (!missing_qt.empty()) + detail::warn(std::format("{}: the Qt module(s) {} are imported and not in the SDK ({}/qml); a program that loads " + "them will not find them. QML needs `xim:qt`; `xim:qt-base` carries the QtQml library only.", + who, detail::joined(missing_qt, ", "), generic(main))); + if (!notes.empty()) + std::cerr << std::format("{}: {} import(s) are in no SDK or import path and are not placed: {}. A type " + "registered by the program at run time is one.\n", who, notes.size(), detail::joined(notes, ", ")); + + for (auto const& mod : found.modules) { + const fs::path origin = [&] { + for (auto const& d : import_dirs) + if (fs::is_regular_file(d / detail::uri_path(mod.uri) / "qmldir", ec)) return d; + return fs::path(); + }(); + bool qt_sdk = false; + for (auto const& r : sdks) qt_sdk = qt_sdk || generic(origin) == generic(r / "qml"); + for (auto const& f : detail::module_files(mod.dir, qt_sdk)) { + const std::string to = "qml/" + generic(f.parent_path().lexically_relative(origin)); + mcpp::deploy(generic(f).c_str(), to.c_str()); + } + } + } + + // ── qt.conf ── + if (opt.write_qt_conf && (opt.deploy_imports || !plan.empty())) { + if (detail::project_has_qt_conf(opt.qt)) { + detail::warn(std::format("{}: the project has its own qt.conf, so none is written. Qt then finds the deployed QML " + "modules only if that file sets `Qml2Imports = qml` and `Prefix = .`.", who)); + } else { + std::string conf = "[Paths]\nPrefix = .\nQml2Imports = qml\n"; + if (opt.qt.i18n.deploy_to != "translations") conf += "Translations = " + opt.qt.i18n.deploy_to + "\n"; + const fs::path file = gen / "qt.conf"; + mcpp::plugins::fs::write_if_changed(file, conf); + mcpp::deploy(generic(file).c_str(), "."); + } + } + return true; +} + +} // namespace mcpp::rules::qml diff --git a/rules/qt.cppm b/rules/qt.cppm index 737a4a8..cb03444 100644 --- a/rules/qt.cppm +++ b/rules/qt.cppm @@ -71,6 +71,11 @@ struct translations { std::vector tr_function_alias; // The files `lupdate` reads. Empty takes the package's C++ files. std::vector sources; + // The file extensions `lupdate` reads, without the dot (`-extensions`), and + // the ones the package walk collects when `sources` is empty. A project + // whose QML and JavaScript hold `qsTr` adds `qml` and `js` (0.27.0; + // `mcpp.rules.qml` does it for `update_sources`). + std::vector extensions = { "cpp", "h", "hpp", "ixx", "cppm" }; // Where the `.qm` files are placed, relative to the program. std::string deploy_to = "translations"; // Where `lrelease` writes them. Empty is `/qt/translations`; a @@ -90,6 +95,17 @@ struct options { std::vector private_modules; moc_scan moc = moc_scan::project_headers; std::vector moc_headers; + // `moc --output-json`: the type description `qmltyperegistrar` reads + // (0.27.0, for `mcpp.rules.qml`). `moc` then also writes `.json`. + bool moc_json = false; + // Give `moc` the SDK's include directories (`-I/include`, one + // `-I/include/Qt` per linked module; `-F/lib` and `-I/include` + // on macOS, where the include directory holds the header-only modules, and where + // the compiler is given it as well). + // Without them `moc` drops `QML_ELEMENT` and its relatives for want of the + // header that defines them, so a type is described without its QML name. + // Off by default: a project's moc output does not change (0.27.0). + bool moc_includes = false; // `.ui` and `.qrc` files, beside those named in `[build] sources`. std::vector forms; std::vector resources; @@ -226,6 +242,19 @@ inline std::vector project_files(std::initializer_list project_files(const std::vector& exts) { + std::vector dotted; + for (std::size_t i = 0; i < exts.size(); ++i) dotted.push_back("." + exts[i]); + std::vector out; + for (auto const& e : dotted) { + auto part = project_files({ std::string_view(e) }); + out.insert(out.end(), part.begin(), part.end()); + } + std::ranges::sort(out); + out.erase(std::unique(out.begin(), out.end()), out.end()); + return out; +} + inline std::string read_file(const std::filesystem::path& p) { std::ifstream in(p, std::ios::binary); return std::string(std::istreambuf_iterator(in), {}); @@ -392,13 +421,36 @@ inline void runtime_directories(std::span roots) { // ─── The rule ────────────────────────────────────────────────────────────── -inline bool compile(options opt = {}) { +// One `moc` output, for a rule built on this one (`mcpp.rules.qml`). +struct moc_unit { + std::string header; // the header, or the source that includes its `.moc` + std::string cpp; // the generated file + std::string json; // `.json` when `options::moc_json`, else empty +}; + +// 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 +// it, and a project calls `compile`. +struct outcome { + bool ok = false; + sdk_source source; // empty `roots` when there is no SDK + std::string gen; // `/qt` + std::vector linked; // the modules found and linked, as `Core` + std::vector mocs; // headers only, in `moc_.cpp` order +}; + +inline bool compile(options opt = {}); + +inline outcome compile_ex(options opt = {}) { namespace fs = std::filesystem; using detail::generic; constexpr std::string_view who = "mcpp.rules.qt"; mcpp::fact("mcpp.plugins", std::string(mcpp::plugins::version).c_str()); + outcome res; const sdk_source source = locate(opt); + res.source = source; const auto& sdks = source.roots; if (sdks.empty()) { // Reached by a build program that asked for Qt: since mcpp 2026.9.27.1 @@ -412,7 +464,8 @@ inline bool compile(options opt = {}) { " \"xim:qt-base\" = \"6.11.1\"", who, source.level.empty() ? std::string() : " at the directory " + source.level + " names")); - return true; + res.ok = true; + return res; } mcpp::fact("rules-qt.sdk", std::format("{}: {}", source.level, generic(sdks.front())).c_str()); // Qt's official Linux binaries are built with GCC against libstdc++, and @@ -425,6 +478,7 @@ inline bool compile(options opt = {}) { "(`--toolchain gcc@`), or name a Qt built with libc++.", who)); const fs::path main = sdks.front(); const fs::path gen = fs::path(opt.out_dir) / "qt"; + res.gen = generic(gen); std::error_code ec; fs::create_directories(gen, ec); @@ -435,12 +489,21 @@ inline bool compile(options opt = {}) { if (std::ranges::find(modules, name) == modules.end()) modules.push_back(name); } std::vector missing; + std::vector mocInclude; // `moc`'s -I/-F arguments, when `moc_includes` asks for (auto const& r : sdks) { if (detail::is_macos()) { const std::string f = "-F" + generic(r / "lib"); mcpp::cxxflag(f.c_str()); + mocInclude.push_back(f); + // A module that is only headers (QtQmlIntegration, which QtQml's own header + // includes) is not a framework: its headers are in `include/`. + if (opt.moc_includes && fs::is_directory(r / "include", ec)) { + mcpp::include_dir(generic(r / "include").c_str()); + mocInclude.push_back("-I" + generic(r / "include")); + } } else { mcpp::include_dir(generic(r / "include").c_str()); + mocInclude.push_back("-I" + generic(r / "include")); } } for (auto const& m : modules) { @@ -462,6 +525,8 @@ inline bool compile(options opt = {}) { mcpp::link_flag(generic(lib).c_str()); const std::string def = "QT_" + detail::upper(m) + "_LIB"; mcpp::define(def.c_str()); + if (!detail::is_macos()) mocInclude.push_back("-I" + generic(headers)); + res.linked.push_back(m); found = true; break; } @@ -550,25 +615,35 @@ inline bool compile(options opt = {}) { }; auto mocOne = [&](const fs::path& in, const std::string& outName) -> bool { if (!claim(outName, in)) return false; - const std::string out = generic(gen / outName); - const std::string dep = out + ".d"; + const std::string outPath = generic(gen / outName); + const std::string dep = outPath + ".d"; const std::string src = generic(in); const std::string id = "qt:moc:" + outName; const std::string desc = "MOC " + in.filename().string(); + const std::string json = outPath + ".json"; mcpp::action a; a.id = id.c_str(); a.role = mcpp::roles::source; a.description = desc.c_str(); a.depfile = dep.c_str(); - a.arg(moc.c_str()).arg(src.c_str()).arg("-o").arg(out.c_str()) - .arg("--output-dep-file").arg("--dep-file-path").arg(dep.c_str()) - .input(src.c_str()).output(out.c_str()).submit(); + a.arg(moc.c_str()).arg(src.c_str()).arg("-o").arg(outPath.c_str()) + .arg("--output-dep-file").arg("--dep-file-path").arg(dep.c_str()); + if (opt.moc_json) a.arg("--output-json"); + if (opt.moc_includes) + for (auto const& i : mocInclude) a.arg(i.c_str()); + a.input(src.c_str()).output(outPath.c_str()); + if (opt.moc_json) a.output(json.c_str()); + a.submit(); return true; }; - for (auto const& h : headers) - if (!mocOne(h, "moc_" + h.stem().string() + ".cpp")) return false; + for (auto const& h : headers) { + const std::string name = "moc_" + h.stem().string() + ".cpp"; + if (!mocOne(h, name)) return res; + res.mocs.push_back({ generic(h), generic(gen / name), + opt.moc_json ? generic(gen / name) + ".json" : std::string() }); + } for (auto const& c : inlineMoc) - if (!mocOne(c, c.stem().string() + ".moc")) return false; + if (!mocOne(c, c.stem().string() + ".moc")) return res; // ── uic ── std::vector forms = detail::device(".ui"); @@ -580,7 +655,7 @@ inline bool compile(options opt = {}) { forms.clear(); } for (auto const& f : forms) { - if (!claim("ui_" + fs::path(f).stem().string() + ".h", detail::absolute_from_root(f))) return false; + if (!claim("ui_" + fs::path(f).stem().string() + ".h", detail::absolute_from_root(f))) return res; const std::string in = generic(detail::absolute_from_root(f)); const std::string out = generic(gen / ("ui_" + fs::path(f).stem().string() + ".h")); const std::string id = "qt:uic:" + fs::path(f).stem().string(); @@ -607,7 +682,7 @@ inline bool compile(options opt = {}) { for (auto const& r : resources) { const fs::path qrc = detail::absolute_from_root(r); const std::string stem = qrc.stem().string(); - if (!claim("qrc_" + stem + ".cpp", qrc)) return false; + if (!claim("qrc_" + stem + ".cpp", qrc)) return res; const std::string in = generic(qrc); const std::string out = generic(gen / ("qrc_" + stem + ".cpp")); const std::string id = "qt:rcc:" + stem; @@ -636,21 +711,25 @@ inline bool compile(options opt = {}) { who, lrelease.empty() ? "lrelease" : "lupdate", generic(main))); ts.clear(); } + std::string extensions; + for (auto const& e : opt.i18n.extensions) extensions += (extensions.empty() ? "" : ",") + e; std::vector sources; if (opt.i18n.update_sources) { if (!opt.i18n.sources.empty()) { for (auto const& s : opt.i18n.sources) sources.push_back(generic(detail::absolute_from_root(s))); } else { - for (auto const* g : { "**/*.cpp", "**/*.h", "**/*.hpp", "**/*.ixx", "**/*.cppm" }) - mcpp::rerun_if_changed_glob(g); - for (auto const& f : detail::project_files({ ".cpp", ".h", ".hpp", ".ixx", ".cppm" })) + for (auto const& e : opt.i18n.extensions) { + const std::string g = "**/*." + e; + mcpp::rerun_if_changed_glob(g.c_str()); + } + for (auto const& f : detail::project_files(opt.i18n.extensions)) sources.push_back(generic(f)); } } for (auto const& t : ts) { const fs::path file = detail::absolute_from_root(t); const std::string stem = file.stem().string(); - if (!claim(stem + ".qm", file)) return false; + if (!claim(stem + ".qm", file)) return res; const std::string in = generic(file); const fs::path qmDir = opt.i18n.out_dir.empty() ? gen / "translations" : detail::absolute_from_root(opt.i18n.out_dir); @@ -666,7 +745,7 @@ inline bool compile(options opt = {}) { // as its input, which orders the two. u.role = mcpp::roles::source; u.description = desc.c_str(); - u.arg(lupdate.c_str()).arg("-silent").arg("-extensions").arg("cpp,h,hpp,ixx,cppm"); + u.arg(lupdate.c_str()).arg("-silent").arg("-extensions").arg(extensions.c_str()); for (auto const& a : opt.i18n.tr_function_alias) u.arg("-tr-function-alias").arg(a.c_str()); for (auto const& s : sources) u.arg(s.c_str()).input(s.c_str()); u.arg("-ts").arg(in.c_str()).output(in.c_str()).submit(); @@ -711,7 +790,7 @@ inline bool compile(options opt = {}) { continue; } const std::string name = "qt_" + lang + ".qm"; - if (!claim(name, fs::path(inputs.front()))) return false; + if (!claim(name, fs::path(inputs.front()))) return res; const std::string out = generic(qmDir / name); const std::string id = "qt:lconvert:" + lang; const std::string desc = "LCONVERT " + name; @@ -767,7 +846,12 @@ inline bool compile(options opt = {}) { break; } } - return true; + res.ok = true; + return res; +} + +inline bool compile(options opt) { + return compile_ex(std::move(opt)).ok; } } // namespace mcpp::rules::qt diff --git a/src/plugins.cppm b/src/plugins.cppm index 5918df7..2bcf6c6 100644 --- a/src/plugins.cppm +++ b/src/plugins.cppm @@ -46,7 +46,7 @@ export namespace mcpp::plugins { // // 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.26.1"; +inline constexpr std::string_view version = "0.27.0"; } // namespace mcpp::plugins diff --git a/tests/all-rules-compile/build.mcpp b/tests/all-rules-compile/build.mcpp index bebcc60..4394b86 100644 --- a/tests/all-rules-compile/build.mcpp +++ b/tests/all-rules-compile/build.mcpp @@ -10,6 +10,7 @@ import mcpp.rules.cuda; import mcpp.rules.hip; import mcpp.rules.metal; import mcpp.rules.qt; +import mcpp.rules.qml; import mcpp.rules.slang; import mcpp.rules.spirv; import mcpp.rules.swift; @@ -118,6 +119,8 @@ int main() { // `rules-qt` declares no SDK and this fixture declares none, so the // question that plans nothing is where the SDK would be: nowhere. ok = ok && mcpp::rules::qt::roots({ .root = "no-such-qt-sdk" }).empty(); + // `rules-qml` states its generated files' directory without asking for an SDK. + ok = ok && !mcpp::rules::qml::import_root({}).empty(); // The `deps-*` members install through an action; asked only what they // derive without one -- the triplet this target defaults to, and the file // a library name denotes. diff --git a/tests/all-rules-compile/mcpp.toml b/tests/all-rules-compile/mcpp.toml index 3931f93..07683c9 100644 --- a/tests/all-rules-compile/mcpp.toml +++ b/tests/all-rules-compile/mcpp.toml @@ -39,7 +39,7 @@ import_std = true # list is one whose host-dependent code is compiled on one platform only. [build-dependencies.mcpp] plugins = { path = "../..", features = [ - "rules-ascendc", "rules-cuda", "rules-hip", "rules-metal", "rules-qt", "rules-slang", + "rules-ascendc", "rules-cuda", "rules-hip", "rules-metal", "rules-qt", "rules-qml", "rules-slang", "rules-spirv", "rules-swift", "rules-sycl", "tools-embed", "tools-island", "tools-steps", "dist-appimage", "dist-wix", "dist-apple", "dist-web", "dist-apk", diff --git a/tests/plugin-logic/build.mcpp b/tests/plugin-logic/build.mcpp index a7c1a03..0164f42 100644 --- a/tests/plugin-logic/build.mcpp +++ b/tests/plugin-logic/build.mcpp @@ -11,6 +11,7 @@ import mcpp.deps; // the 0.16.0 names, for the compatibility case import mcpp.deps.vcpkg; import mcpp.deps.cmake; import mcpp.rules.qt; +import mcpp.rules.qml; import mcpp.plugins.tool; import mcpp.plugins.platform; import mcpp.plugins; @@ -142,6 +143,125 @@ mcpp::plugins::tool::found tool_resolve(mcpp::plugins::tool::choice c = {}) { return mcpp::plugins::tool::resolve(mcpp::deps::cmake_spec("mcpp.deps.cmake"), c); } + +// A stand-in SDK with every tool rules-qt runs and one plugin directory. +t::context with_full_qt(t::context c) { + for (auto const* tool : { "moc", "uic", "rcc", "lupdate", "lrelease", "lconvert" }) + c = c.file(std::string("qt/bin/") + tool); + return c.file("qt/lib/libQt6Core.so").file("qt/include/QtCore/qobject.h") + .file("qt/plugins/platforms/libqxcb.so") + .file("pkg/widget.h", "class Widget { Q_OBJECT };\n") + .file("pkg/form.ui").file("pkg/res/app.qrc", "\n") + .file("pkg/app.ts"); +} + +// What a case printed that the engine would read: the directives, with the +// case's own directory replaced, so one text serves every host. +std::string directives(const t::result& r) { + std::string out; + const std::string root = r.root.generic_string(); + for (auto const& l : r.lines) { + if (!l.starts_with("mcpp:") || l.starts_with("mcpp:decision=") || l.starts_with("mcpp:fact=mcpp.plugins=") + || l.starts_with("mcpp:protocol=")) continue; + std::string x = l; + for (std::size_t at = x.find(root); at != std::string::npos; at = x.find(root, at + 6)) x.replace(at, root.size(), ""); + out += x + "\n"; + } + return out; +} + + +// ─── rules-qml: a stand-in SDK and the package it builds ──────────────────── + +// The SDK of a QML program: every tool rules-qml runs, two linked modules, and a +// tree of QML modules whose `qmldir` files and `.qml` files import one another +// the way Qt's do. +t::context with_qml_sdk(t::context c, bool with_qsb = true) { + for (auto const* tool : { "moc", "rcc", "qmltyperegistrar", "qmlcachegen" }) c = c.file(std::string("qt/libexec/") + tool); + c = c.file("qt/bin/qmllint"); + if (with_qsb) c = c.file("qt/bin/qsb"); + c = c.file("qt/lib/libQt6Core.so").file("qt/lib/libQt6Qml.so") + .file("qt/include/QtCore/qobject.h").file("qt/include/QtQml/qqmlregistration.h") + .file("qt/metatypes/qt6core_metatypes.json").file("qt/metatypes/qt6qml_metatypes.json") + .file("qt/plugins/platforms/libqoffscreen.so") + .file("qt/plugins/imageformats/libqpng.so"); + return c + .file("qt/qml/QtQuick/qmldir", "module QtQuick\nplugin qtquick2plugin\nimport QtQml\ndepends QtQml.Models 2.0\n") + .file("qt/qml/QtQuick/libqtquick2plugin.so") + .file("qt/qml/QtQuick/plugins.qmltypes", "Module {}\n") + .file("qt/qml/QtQuick/designer/Hidden.qml", "import QtQuick.Templates\nItem {}\n") + .file("qt/qml/QtQml/qmldir", "module QtQml\n") + .file("qt/qml/QtQml/Models/qmldir", "module QtQml.Models\n") + .file("qt/qml/QtQuick/Controls/qmldir", + "module QtQuick.Controls\ndefault import QtQuick.Controls.Basic\n" + "optional import QtQuick.Controls.Material auto\noptional import QtQuick.Controls.Fusion auto\n" + "import QtQuick.Templates\n") + .file("qt/qml/QtQuick/Controls/Button.qml", "import QtQuick\nItem {}\n") + .file("qt/qml/QtQuick/Controls/Basic/qmldir", "module QtQuick.Controls.Basic\n") + .file("qt/qml/QtQuick/Controls/Material/qmldir", "module QtQuick.Controls.Material\n") + .file("qt/qml/QtQuick/Controls/Material/Button.qml", + "import QtQuick.Templates as T // a comment: import NotAModule\nimport QtQuick.Controls.Material.impl;\nItem {}\n") + .file("qt/qml/QtQuick/Controls/Material/impl/qmldir", "module QtQuick.Controls.Material.impl\n") + .file("qt/qml/QtQuick/Controls/Material/impl/Ripple.qml", "import QtQuick\nimport QtQuick.Controls.Material\nItem {}\n") + .file("qt/qml/QtQuick/Controls/Fusion/qmldir", "module QtQuick.Controls.Fusion\n") + .file("qt/qml/QtQuick/Templates/qmldir", "module QtQuick.Templates\n"); +} + +// The `mcpp:deploy=` directives of a case, as `/`. +std::set deployed(const t::result& r) { + std::set out; + for (auto const& l : r.lines) { + if (!l.starts_with("mcpp:deploy=")) continue; + const auto tab = l.find('\t'); + const std::string file = l.substr(12, tab - 12), to = l.substr(tab + 1); + out.insert(to + "/" + file.substr(file.rfind('/') + 1)); + } + return out; +} + +// The action a case declared, by the start of its id, as JSON text. +std::string action_of(const t::result& r, const std::string& id) { + return r.line("mcpp:action=", {"\"id\":\"" + id}); +} + +bool mentions(const std::string& text, const std::string& part) { return text.find(part) != std::string::npos; } + +// A package with one module `Probe`: two QML types (one a singleton), a script, a +// nested file, a resource whose name needs XML escaping, and a header with a QML type. +t::context with_probe(t::context c) { + return c.file("pkg/qml/Probe/Main.qml", "import QtQuick\nimport QtQuick.Controls\nItem { }\n") + .file("pkg/qml/Probe/Style.qml", "pragma Singleton\nimport QtQuick\nQtObject { }\n") + .file("pkg/qml/Probe/helper.qml", "import QtQuick\nItem { }\n") + .file("pkg/qml/Probe/util.js", ".pragma library\nfunction f() {}\n") + .file("pkg/qml/Probe/sub/Inner.qml", "import QtQuick\nQtObject { }\n") + .file("pkg/qml/Probe/data/a&b.txt", "resource\n") + .file("pkg/src/thing.h", "#include \nclass Thing : public QObject { Q_OBJECT QML_ELEMENT };\n"); +} + +// A resource whose name has `<` and `>`, which XML must escape and a Windows host +// cannot create: made where it can be, and said. +void make_odd_resource() { + std::error_code ec; + const auto file = std::filesystem::path(mcpp::manifest_dir()) / "qml/Probe/data/c.txt"; + std::ofstream(file) << "resource\n"; + std::printf("odd=%d\n", std::filesystem::exists(file, ec)); +} + +mcpp::rules::qml::options probe_options() { + mcpp::rules::qml::options o; + o.qt.root = "../qt"; + o.qt.modules = {"Core"}; + o.qt.deploy_plugins = {"platforms"}; + mcpp::rules::qml::qml_module m; + m.uri = "Probe"; + m.version = "1.2"; + m.root = "qml/Probe"; + m.sources = {"qml/Probe/**/*.qml", "qml/Probe/**/*.js"}; + m.resources = {"qml/Probe/data/*"}; + o.modules = {m}; + return o; +} + } // namespace int main(int argc, char** argv) { @@ -953,6 +1073,407 @@ int main(int argc, char** argv) { "an executable's pattern begins with {name}"); } }, + + + { "qt: a project that names no 0.27 option gets the directives of 0.26", + with_full_qt(t::row::linux_gcc()), + [] { + mcpp::rules::qt::options o; + o.root = "../qt"; + o.modules = {"Core"}; + o.deploy_plugins = {"platforms"}; + o.forms = {"form.ui"}; + o.resources = {"res/app.qrc"}; + o.i18n.ts = {"app.ts"}; + o.i18n.update_sources = true; + return mcpp::rules::qt::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + // The text is the directives of 0.26.1 for these options, recorded before + // any 0.27 change: a later change that alters one fails here. + std::ifstream in(std::filesystem::path(mcpp::manifest_dir()) / "golden" / "qt-0.26.txt"); + const std::string golden{std::istreambuf_iterator(in), {}}; + c.expect(!golden.empty() && directives(r) == golden, "every directive is what 0.26 stated; got:\n" + directives(r)); + } }, + + + { "qt: moc_json and moc_includes add the type description and the SDK's include directories to moc", + with_full_qt(t::row::linux_gcc()).file("qt/lib/libQt6Qml.so"), + [] { + mcpp::rules::qt::options o; + o.root = "../qt"; + o.modules = {"Core", "Qml"}; + o.deploy_plugins = {}; + o.moc_json = true; + o.moc_includes = true; + const auto done = mcpp::rules::qt::compile_ex(o); + std::printf("ok=%d linked=%zu mocs=%zu\n", done.ok, done.linked.size(), done.mocs.size()); + for (auto const& m : done.mocs) + std::printf("unit=%s|%s|%s\n", std::filesystem::path(m.header).filename().string().c_str(), + std::filesystem::path(m.cpp).filename().string().c_str(), + std::filesystem::path(m.json).filename().string().c_str()); + return done.ok ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(r.has_line("ok=1 linked=2 mocs=1"), "compile_ex reports the modules it linked and the moc units"); + c.expect(r.has_line("unit=widget.h|moc_widget.cpp|moc_widget.cpp.json"), "a unit names its header, source and description"); + const auto a = r.line("mcpp:action=", {"qt:moc:moc_widget.cpp"}); + c.expect(a.find("\"--output-json\"") != std::string::npos, "moc writes the description"); + c.expect(a.find("moc_widget.cpp.json\"]") != std::string::npos, "the description is a declared output"); + c.expect(a.find("\"-I" + r.root.generic_string() + "/qt/include\"") != std::string::npos + && a.find("\"-I" + r.root.generic_string() + "/qt/include/QtCore\"") != std::string::npos + && a.find("\"-I" + r.root.generic_string() + "/qt/include/QtQml\"") != std::string::npos, + "moc is given the SDK's include directory and each linked module's"); + } }, + + { "qt: lupdate reads the extensions the project names", + with_full_qt(t::row::linux_gcc()).file("pkg/ui/Main.qml", "Text { text: qsTr(\"hi\") }\n").file("pkg/ui/util.js"), + [] { + mcpp::rules::qt::options o; + o.root = "../qt"; + o.modules = {"Core"}; + o.deploy_plugins = {}; + o.i18n.ts = {"app.ts"}; + o.i18n.update_sources = true; + o.i18n.extensions = {"cpp", "h", "qml", "js"}; + return mcpp::rules::qt::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + const auto u = r.line("mcpp:action=", {"qt:lupdate:app"}); + c.expect(u.find("\"-extensions\",\"cpp,h,qml,js\"") != std::string::npos, "the extensions reach lupdate"); + c.expect(u.find("pkg/ui/Main.qml") != std::string::npos && u.find("pkg/ui/util.js") != std::string::npos, + "the walk collects the files of those extensions"); + c.expect(r.has_line("mcpp:rerun-if-changed-glob=**/*.qml"), "a new file of one of them re-plans"); + } }, + + + // ── rules-qml ─────────────────────────────────────────────────────── + { "qml: a module's qmldir, qrc and resource paths", + with_probe(with_qml_sdk(t::row::linux_gcc())), + [] { make_odd_resource(); return mcpp::rules::qml::compile(probe_options()) ? 0 : 1; }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + const std::string dir = "out/qml/Probe/"; + c.expect(r.file(dir + "qmldir") == + "module Probe\ntypeinfo Probe.qmltypes\nprefer :/qt/qml/Probe/\n" + "Main 1.2 Main.qml\nsingleton Style 1.2 Style.qml\nInner 1.2 sub/Inner.qml\n", + "the qmldir: module, typeinfo, prefer, then a line per type; a singleton marked, a lowercase file and a script not listed; got:\n" + r.file(dir + "qmldir")); + const std::string qrc = r.file("out/qml/Probe/Probe.qrc"); + c.expect(mentions(qrc, "") && mentions(qrc, ""), + "the resources sit under the prefix and the uri as a path, beside the qmldir"); + c.expect(mentions(qrc, "") && mentions(qrc, ""), + "a nested file keeps its relative path"); + c.expect(mentions(qrc, "alias=\"data/a&b.txt\">") && mentions(qrc, "a&b.txt"), + "a name with & is escaped in the alias and the path"); + if (r.has_line("odd=1")) + c.expect(mentions(qrc, "alias=\"data/c<d>.txt\">") && mentions(qrc, "c<d>.txt"), + "so are < and >, where a host can name such a file"); + c.expect(!mentions(qrc, "\\"), "no backslash"); + c.expect(r.has_line("mcpp:rerun-if-changed=", {"qml/Probe/Main.qml"}) && r.has_line("mcpp:rerun-if-changed=", {"qml/Probe/sub/Inner.qml"}) + && r.has_line("mcpp:rerun-if-changed-glob=qml/Probe/**/*.qml"), + "every .qml file the plan read is declared, and the glob that found it"); + } }, + + { "qml: the actions of a module with C++ types, in order of their dependencies", + with_probe(with_qml_sdk(t::row::linux_gcc())), + [] { return mcpp::rules::qml::compile(probe_options()) ? 0 : 1; }, + [](const t::result& r, t::checker& c) { + const auto moc = action_of(r, "qt:moc:moc_thing.cpp"); + c.expect(mentions(moc, "\"--output-json\"") && mentions(moc, "moc_thing.cpp.json"), "moc writes the type description"); + const auto reg = action_of(r, "qml:registrar:Probe"); + c.expect(mentions(reg, "--generate-qmltypes=") && mentions(reg, "Probe.qmltypes") && mentions(reg, "\"--import-name=Probe\"") + && mentions(reg, "\"--major-version=1\"") && mentions(reg, "\"--minor-version=2\""), + "the registrar is told the uri and the version"); + c.expect(mentions(reg, "--foreign-types=") && mentions(reg, "/qt/metatypes/qt6core_metatypes.json"), + "the SDK's type descriptions are foreign types"); + c.expect(mentions(reg, "Probe_qmltyperegistrations.cpp") && mentions(reg, "moc_thing.cpp.json"), "its output and input"); + const auto rcc = action_of(r, "qml:rcc:Probe"); + c.expect(mentions(rcc, "qrc_Probe.cpp") && mentions(rcc, "qml/Probe/Main.qml") && mentions(rcc, "data/a&b.txt"), + "rcc reads every file of the module and writes qrc_.cpp"); + const auto cg = action_of(r, "qml:cachegen:Probe:sub/Inner.qml"); + c.expect(mentions(cg, "\"--bare\"") && mentions(cg, "\"--resource-path\",\"/qt/qml/Probe/sub/Inner.qml\"") + && mentions(cg, "\"--resource\"") && mentions(cg, "Probe_sub_Inner_qml.cpp"), + "a file is compiled under its resource path, into a name made from it"); + c.expect(mentions(cg, "Probe.qmltypes") && mentions(cg, "out/qml/Probe/qmldir"), + "and reads the module's type description and qmldir, which orders it after the registrar"); + c.expect(r.has_line("mcpp:action=", {"qml:cachegen:Probe:util.js"}), "a script is compiled too"); + const auto loader = action_of(r, "qml:cachegen:Probe:loader"); + c.expect(mentions(loader, "Probe_qmlcache_loader.cpp\",\"@") || mentions(loader, "Probe_qmlcache_loader.cpp\""), + "the loader's output ends in qmlcache_loader.cpp, the name that makes qmlcachegen write one"); + const std::string rsp = r.file("out/qml/Probe/loader.rsp"); + c.expect(rsp.starts_with("--resource\n") && mentions(rsp, "\n/qt/qml/Probe/Main.qml\n") && mentions(rsp, "\n/qt/qml/Probe/sub/Inner.qml\n") + && !mentions(rsp, "data/"), "the loader is given the resource paths of the compiled files and no resource"); + c.expect(r.has_line("mcpp:include-dir=", {"pkg/src"}), "the registrations can include the header"); + } }, + + { "qml: aot = false, no C++ types, shaders and lint change the set of actions", + with_probe(with_qml_sdk(t::row::linux_gcc())).file("pkg/shaders/a.frag", "#version 440\n"), + [] { + auto o = probe_options(); + o.modules[0].aot = false; + o.modules[0].shaders = {"shaders/a.frag"}; + o.lint = true; + o.lint_warnings_are_errors = true; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(!r.has_line("mcpp:action=", {"qml:cachegen:"}), "aot = false declares no cachegen action"); + c.expect(r.has_line("mcpp:action=", {"qml:rcc:Probe"}) && r.has_line("mcpp:action=", {"qml:registrar:Probe"}), + "the sources are still embedded and the types registered"); + const auto qsb = action_of(r, "qml:qsb:Probe:a.frag"); + c.expect(mentions(qsb, "\"--qt6\"") && mentions(qsb, "a.frag.qsb") && mentions(qsb, "LD_LIBRARY_PATH"), + "qsb is given its arguments, writes .qsb and gets the SDK's library directory"); + c.expect(mentions(r.file("out/qml/Probe/Probe.qrc"), "alias=\"shaders/a.frag.qsb\""), "the shader is a resource of the module"); + c.expect(mentions(action_of(r, "qml:rcc:Probe"), "a.frag.qsb"), "rcc waits for the shader"); + const auto lint = action_of(r, "qml:lint:Probe:Main.qml"); + c.expect(mentions(lint, "\"role\":\"check\"") && mentions(lint, "\"--max-warnings\",\"0\""), + "lint is a check, one per file, that fails on a warning when asked"); + c.expect(!r.has_line("mcpp:action=", {"qml:lint:Probe:util.js"}), "a script is not linted"); + } }, + + { "qml: shaders without qsb are a warning, and the resources do not name a file nobody builds", + with_probe(with_qml_sdk(t::row::linux_gcc(), false)).file("pkg/shaders/a.frag", "#version 440\n"), + [] { + auto o = probe_options(); + o.modules[0].shaders = {"shaders/a.frag"}; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(r.has_line("mcpp:warning=", {"`qsb` not found", "xim:qt-addons"}), "the warning says which payload carries qsb"); + c.expect(!r.has_line("mcpp:action=", {"qml:qsb:"}), "no qsb action is declared"); + c.expect(!mentions(r.file("out/qml/Probe/Probe.qrc"), ".qsb") && !mentions(action_of(r, "qml:rcc:Probe"), ".qsb"), + "neither the qrc nor rcc's inputs name a shader that is not built"); + } }, + + { "qml: a module with no C++ type runs no registrar and its qmldir names no typeinfo", + with_qml_sdk(t::row::linux_gcc()).file("pkg/q/Chip.qml", "import QtQuick\nItem { }\n"), + [] { + mcpp::rules::qml::options o; + o.qt.root = "../qt"; + o.qt.modules = {"Core"}; + o.qt.deploy_plugins = {}; + mcpp::rules::qml::qml_module m; + m.uri = "Plain"; + m.sources = {"q/*.qml"}; + o.modules = {m}; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(!r.has_line("mcpp:action=", {"qml:registrar:"}), "no registrar"); + c.expect(r.file("out/qml/Plain/qmldir") == "module Plain\nprefer :/qt/qml/Plain/\nChip 1.0 Chip.qml\n", + "no typeinfo line; the root is the directory the sources share; got:\n" + r.file("out/qml/Plain/qmldir")); + c.expect(r.has_line("mcpp:action=", {"qml:cachegen:Plain:Chip.qml"}), "the file is compiled"); + } }, + + + { "qml: what is stated wrongly is refused, naming it, before any action is declared", + with_probe(with_qml_sdk(t::row::linux_gcc())).file("pkg/qml/Probe/Extra.qml", "Item {}\n"), + [] { + using namespace mcpp::rules::qml; + int refused = 0; + auto base = [] { return probe_options(); }; + { auto o = base(); o.modules[0].uri = "a..b"; refused += !compile(o); } + { auto o = base(); o.modules[0].uri = "../x"; refused += !compile(o); } + { auto o = base(); o.modules[0].uri = "9lives"; refused += !compile(o); } + { auto o = base(); o.modules[0].version = "1"; refused += !compile(o); } + { auto o = base(); o.modules[0].version = "1.x"; refused += !compile(o); } + { auto o = base(); o.modules[0].prefix = "qt/qml"; refused += !compile(o); } + { auto o = base(); o.modules.push_back(o.modules[0]); refused += !compile(o); } + { auto o = base(); o.modules[0].uri = "QtQuick"; refused += !compile(o); } + { auto o = base(); o.modules.push_back(o.modules[0]); o.modules[1].uri = "Probe_2"; + o.modules[0].uri = "a.b"; o.modules[1].uri = "a_b"; refused += !compile(o); } + std::printf("refused=%d\n", refused); + return 0; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.has_line("refused=9"), "all nine are refused"); + c.expect(mentions(r.errors, "`a..b` is not a module uri") && mentions(r.errors, "`../x` is not a module uri") + && mentions(r.errors, "`9lives` is not a module uri"), "an invalid uri is named"); + c.expect(mentions(r.errors, "the version `1` of Probe") && mentions(r.errors, "the version `1.x` of Probe"), "an invalid version is named"); + c.expect(mentions(r.errors, "the prefix `qt/qml`"), "an invalid prefix is named"); + c.expect(mentions(r.errors, "is stated twice"), "a module stated twice, or two that name one file, is refused"); + c.expect(mentions(r.errors, "module of the Qt SDK"), "a uri the SDK already has is refused"); + } }, + + { "qml: headers belong to one module each, and a header nobody lists is not guessed when there are several", + with_qml_sdk(t::row::linux_gcc()) + .file("pkg/a/A.qml", "Item {}\n").file("pkg/b/B.qml", "Item {}\n") + .file("pkg/src/one.h", "class One { Q_OBJECT QML_ELEMENT };\n") + .file("pkg/src/two.h", "class Two { Q_OBJECT QML_ELEMENT };\n") + .file("pkg/src/plain.h", "class Plain { Q_OBJECT };\n"), + [] { + using namespace mcpp::rules::qml; + auto make = [] { + options o; + o.qt.root = "../qt"; + o.qt.modules = {"Core"}; + o.qt.deploy_plugins = {}; + qml_module a, b; + a.uri = "m.a"; a.sources = {"a/*.qml"}; + b.uri = "m.b"; b.sources = {"b/*.qml"}; + o.modules = {a, b}; + return o; + }; + int refused = 0; + { auto o = make(); refused += !compile(o); } // two QML headers, none assigned + { auto o = make(); o.modules[0].headers = {"src/one.h"}; refused += !compile(o); } // `two.h` still belongs to nobody + { auto o = make(); o.modules[0].headers = {"src/one.h", "src/two.h"}; o.modules[1].headers = {"src/two.h"}; refused += !compile(o); } + std::printf("refused=%d\n", refused); + auto o = make(); + o.modules[0].headers = {"src/one.h"}; + o.modules[1].headers = {"src/two.h"}; + return compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "with each header listed the member succeeds"); + c.expect(r.has_line("refused=3"), "an unassigned header, a header left over, a header listed twice are each refused"); + c.expect(mentions(r.errors, "registers QML types and belongs to no module") && mentions(r.errors, "is listed for both m.a and m.b"), + "the refusals name the header and the modules"); + const auto a = action_of(r, "qml:registrar:m.a"); + c.expect(mentions(a, "moc_one.cpp.json") && mentions(a, "moc_two.cpp.json") && a.find("--foreign-types=") != std::string::npos, + "m.a's registrar reads its own description and is given m.b's as foreign types"); + c.expect(r.count("mcpp:action={\"id\":\"qml:registrar:") == 2, "a header with no QML macro registers nothing"); + c.expect(mentions(a, "--foreign-types=") && mentions(a, "moc_plain.cpp.json"), + "it is known to the registrar all the same, as a base class a type may derive from"); + } }, + + { "qml: a target that is not linux, windows or macos is one warning and no action", + with_probe(with_qml_sdk(t::row::linux_gcc())).set("MCPP_TARGET_OS", "android"), + [] { return mcpp::rules::qml::compile(probe_options()) ? 0 : 1; }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(r.count("mcpp:action=") == 0 && r.count("mcpp:deploy=") == 0, "nothing is declared"); + c.expect(r.has_line("mcpp:warning=", {"QML is built for linux, windows and macos", "android"}), "the warning names the target"); + } }, + + { "qml: a missing tool or Quick library is a warning, and the plan succeeds", + t::row::linux_gcc().file("qt/lib/libQt6Core.so").file("qt/libexec/moc") + .file("pkg/qml/Probe/Main.qml", "Item {}\n"), + [] { + auto o = probe_options(); + o.modules[0].sources = {"qml/Probe/*.qml"}; + o.modules[0].resources = {}; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(r.has_line("mcpp:warning=", {"`rcc` not found", "xim:qt", "QtQml library only"}), "the warning says which payload carries Quick"); + c.expect(r.count("mcpp:action=") == 0, "no QML action is declared for a module that cannot be built"); + } }, + + { "qml: no SDK is the warning rules-qt gives, and the member succeeds", + t::row::linux_gcc(), + [] { + mcpp::rules::qml::options o; + mcpp::rules::qml::qml_module m; + m.uri = "Probe"; + o.modules = {m}; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0 && r.count("mcpp:action=") == 0, "nothing is declared, nothing fails"); + c.expect(r.has_line("mcpp:warning=", {"no Qt SDK"}), "the SDK's absence is said once"); + } }, + + { "qml: Qt's own modules the program imports are placed under qml/, by the imports of the SDK's own files", + with_probe(with_qml_sdk(t::row::linux_gcc())), + [] { return mcpp::rules::qml::compile(probe_options()) ? 0 : 1; }, + [](const t::result& r, t::checker& c) { + const auto d = deployed(r); + auto has = [&](const std::string& f) { return d.contains(f); }; + c.expect(has("qml/QtQuick/Controls/qmldir") && has("qml/QtQuick/Controls/Button.qml"), "the module the project imports"); + c.expect(has("qml/QtQuick/qmldir") && has("qml/QtQuick/libqtquick2plugin.so"), "QtQuick, which a .qml file of Controls imports, with its plugin"); + c.expect(has("qml/QtQml/qmldir") && has("qml/QtQml/Models/qmldir"), "an `import` and a `depends` line of a qmldir are followed"); + c.expect(has("qml/QtQuick/Controls/Basic/qmldir"), "a `default import` is followed"); + c.expect(has("qml/QtQuick/Controls/Material/qmldir") && has("qml/QtQuick/Controls/Fusion/qmldir"), + "an `optional import` is followed: any style can be chosen at run time"); + c.expect(has("qml/QtQuick/Controls/Material/impl/qmldir") && has("qml/QtQuick/Controls/Material/impl/Ripple.qml"), + "a nested module is found through an import in a .qml file and placed on its own, with a `;` after the import"); + c.expect(has("qml/QtQuick/Templates/qmldir"), "an `import` line of a qmldir"); + c.expect(!has("qml/QtQuick/plugins.qmltypes") && !has("qml/QtQuick/designer/Hidden.qml"), "type descriptions and designer files are not run time"); + std::size_t files = 0, qmldirs = 0; + for (auto const& f : d) { + if (!f.starts_with("qml/")) continue; + ++files; + if (f.ends_with("/qmldir")) ++qmldirs; + } + c.expect(files == 13, "exactly the 13 files of those modules, and no qt.conf or plugin among them; got " + std::to_string(files)); + c.expect(qmldirs == 9, "nine modules; got " + std::to_string(qmldirs)); + c.expect(!mentions(r.errors, "NotAModule") && !r.has_line("mcpp:warning=", {"NotAModule"}), + "an import in a comment is not an import"); + } }, + + { "qml: styles limits the optional imports, imports and import_paths add modules, an unknown Qt module is a warning", + with_probe(with_qml_sdk(t::row::linux_gcc())) + .file("pkg/extra/Acme/Gadget/qmldir", "module Acme.Gadget\nimport QtQuick\n") + .file("pkg/extra/Acme/Gadget/Gadget.qml", "Item {}\n") + .file("pkg/qml/Probe/User.qml", "import Acme.Gadget\nimport Probe\nimport QtQuick.Nothing\nimport Dynamic.Thing\nItem {}\n"), + [] { + auto o = probe_options(); + o.styles = {"Basic"}; + o.imports = {"QtQml.Models"}; + o.import_paths = {"extra"}; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + const auto d = deployed(r); + c.expect(d.contains("qml/QtQuick/Controls/Basic/qmldir") && !d.contains("qml/QtQuick/Controls/Material/qmldir") + && !d.contains("qml/QtQuick/Controls/Fusion/qmldir"), "only the listed style is followed"); + c.expect(!d.contains("qml/QtQuick/Controls/Material/impl/qmldir"), "and what only the other styles import is not placed"); + c.expect(d.contains("qml/Acme/Gadget/qmldir") && d.contains("qml/Acme/Gadget/Gadget.qml"), "a module of import_paths is placed under qml/ by its uri"); + c.expect(!d.contains("qml/Probe/qmldir"), "the project's own module is not a Qt module"); + c.expect(r.has_line("mcpp:warning=", {"QtQuick.Nothing", "xim:qt"}), "a Qt module the SDK lacks is a warning that names the payload"); + c.expect(!r.has_line("mcpp:warning=", {"Dynamic.Thing"}) && mentions(r.errors, "Dynamic.Thing"), + "a module in no SDK is a note, not a warning: a program registers types at run time"); + } }, + + { "qml: qt.conf is written, follows the translations directory, and yields to the project's own", + with_probe(with_qml_sdk(t::row::linux_gcc())), + [] { + auto o = probe_options(); + if (!mcpp::rules::qml::compile(o)) return 1; + o.qt.i18n.deploy_to = "i18n"; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(r.file("out/qml/qt.conf") == "[Paths]\nPrefix = .\nQml2Imports = qml\nTranslations = i18n\n", + "the second run's file names the translations directory; got:\n" + r.file("out/qml/qt.conf")); + std::size_t placed = 0; + for (auto const& l : r.lines) if (l.starts_with("mcpp:deploy=") && l.find("/out/qml/qt.conf\t.") != std::string::npos) ++placed; + c.expect(placed == 2, "it is placed beside the program"); + } }, + + { "qml: a project's own qt.conf is kept; write_qt_conf = false writes none", + with_probe(with_qml_sdk(t::row::linux_gcc())).file("pkg/res/qt.conf", "[Paths]\nPrefix = x\n"), + [] { return mcpp::rules::qml::compile(probe_options()) ? 0 : 1; }, + [](const t::result& r, t::checker& c) { + c.expect(r.exit_code == 0, "the member succeeds"); + c.expect(r.file("out/qml/qt.conf").empty() && r.count("mcpp:deploy=") > 0, "none is written"); + c.expect(!r.has_line("mcpp:deploy=", {"out/qml/qt.conf"}), "none is placed"); + c.expect(r.has_line("mcpp:warning=", {"has its own qt.conf", "Qml2Imports"}), "the warning says what the project's file must set"); + } }, + + { "qml: write_qt_conf = false, and quick_plugins adds only the directories the SDK has", + with_probe(with_qml_sdk(t::row::linux_gcc())), + [] { + auto o = probe_options(); + o.write_qt_conf = false; + o.quick_plugins = {"imageformats", "xcbglintegrations"}; + return mcpp::rules::qml::compile(o) ? 0 : 1; + }, + [](const t::result& r, t::checker& c) { + c.expect(r.file("out/qml/qt.conf").empty() && !r.has_line("mcpp:deploy=", {"qt.conf"}), "no qt.conf"); + const auto d = deployed(r); + c.expect(d.contains("imageformats/libqpng.so") && d.contains("platforms/libqoffscreen.so"), "the directory the SDK has is placed beside platforms/"); + c.expect(!r.has_line("mcpp:warning=", {"xcbglintegrations"}), "a directory the SDK lacks is not a warning"); + } }, + // ── compatibility ─────────────────────────────────────────────────── { "compat: program_compilers keeps its 0.16.0 answer and says until when", t::row::linux_libcxx().file("llvm/bin/clang").file("llvm/bin/clang++"), diff --git a/tests/plugin-logic/golden/qt-0.26.txt b/tests/plugin-logic/golden/qt-0.26.txt new file mode 100644 index 0000000..190b8b0 --- /dev/null +++ b/tests/plugin-logic/golden/qt-0.26.txt @@ -0,0 +1,28 @@ +mcpp:fact=rules-qt.sdk=options: /qt +mcpp:include-dir=/qt/include +mcpp:include-dir=/qt/include/QtCore +mcpp:link-flag=/qt/lib/libQt6Core.so +mcpp:cfg=QT_CORE_LIB +mcpp:cxxflag=-fPIC +mcpp:runtime-search-dir=/qt/lib +mcpp:rerun-if-changed-glob=**/*.h +mcpp:rerun-if-changed-glob=**/*.hpp +mcpp:rerun-if-changed-glob=**/*.hxx +mcpp:rerun-if-changed=/pkg/widget.h +mcpp:rerun-if-changed-glob=**/*.cpp +mcpp:rerun-if-changed-glob=**/*.cc +mcpp:rerun-if-changed-glob=**/*.cxx +mcpp:action={"id":"qt:moc:moc_widget.cpp","role":"source","description":"MOC widget.h","blocking":false,"depfile":"/out/qt/moc_widget.cpp.d","inputs":["/pkg/widget.h"],"outputs":["/out/qt/moc_widget.cpp"],"command":["/qt/bin/moc","/pkg/widget.h","-o","/out/qt/moc_widget.cpp","--output-dep-file","--dep-file-path","/out/qt/moc_widget.cpp.d"],"provides":[],"imports":[],"targets":[]} +mcpp:action={"id":"qt:uic:form","role":"source","description":"UIC form.ui","blocking":false,"inputs":["/pkg/form.ui"],"outputs":["/out/qt/ui_form.h"],"command":["/qt/bin/uic","/pkg/form.ui","-o","/out/qt/ui_form.h"],"provides":[],"imports":[],"targets":[]} +mcpp:include-dir=/out/qt +mcpp:rerun-if-changed=/pkg/res/app.qrc +mcpp:action={"id":"qt:rcc:app","role":"source","description":"RCC app.qrc","blocking":false,"inputs":["/pkg/res/app.qrc"],"outputs":["/out/qt/qrc_app.cpp"],"command":["/qt/bin/rcc","--name","app","/pkg/res/app.qrc","-o","/out/qt/qrc_app.cpp"],"provides":[],"imports":[],"targets":[]} +mcpp:rerun-if-changed-glob=**/*.cpp +mcpp:rerun-if-changed-glob=**/*.h +mcpp:rerun-if-changed-glob=**/*.hpp +mcpp:rerun-if-changed-glob=**/*.ixx +mcpp:rerun-if-changed-glob=**/*.cppm +mcpp:action={"id":"qt:lupdate:app","role":"source","description":"LUPDATE app.ts","blocking":false,"inputs":["/pkg/widget.h"],"outputs":["/pkg/app.ts"],"command":["/qt/bin/lupdate","-silent","-extensions","cpp,h,hpp,ixx,cppm","/pkg/widget.h","-ts","/pkg/app.ts"],"provides":[],"imports":[],"targets":[]} +mcpp:action={"id":"qt:lrelease:app","role":"source","description":"LRELEASE app.ts","blocking":false,"inputs":["/pkg/app.ts"],"outputs":["/out/qt/translations/app.qm"],"command":["/qt/bin/lrelease","-silent","/pkg/app.ts","-qm","/out/qt/translations/app.qm"],"provides":[],"imports":[],"targets":[]} +mcpp:deploy=/out/qt/translations/app.qm translations +mcpp:deploy=/qt/plugins/platforms/libqxcb.so platforms diff --git a/tests/plugin-logic/mcpp.toml b/tests/plugin-logic/mcpp.toml index 9474215..30d82d7 100644 --- a/tests/plugin-logic/mcpp.toml +++ b/tests/plugin-logic/mcpp.toml @@ -18,7 +18,7 @@ modules = true import_std = true [build-dependencies.mcpp] -plugins = { path = "../..", features = ["plugins-progress", "deps-vcpkg", "deps-cmake", "rules-qt", "plugins-platform", "plugins-testing", "rules-cuda", "rules-sycl", "rules-hip", "rules-spirv"], host-module = true } +plugins = { path = "../..", features = ["plugins-progress", "deps-vcpkg", "deps-cmake", "rules-qt", "rules-qml", "plugins-platform", "plugins-testing", "rules-cuda", "rules-sycl", "rules-hip", "rules-spirv"], host-module = true } [targets.plugin-logic] kind = "bin" diff --git a/tests/qml-consumer/build.mcpp b/tests/qml-consumer/build.mcpp new file mode 100644 index 0000000..e7cf0d7 --- /dev/null +++ b/tests/qml-consumer/build.mcpp @@ -0,0 +1,32 @@ +// The Probe module: its files, its C++ types, the Qt Quick libraries, and `qsTr` +// strings that `lupdate` keeps in qml_consumer_de.ts. A variant is chosen by +// MCPP_QML_VARIANT, which the CI script sets to build the same project three +// more ways: `noaot` (sources embedded, not compiled), `styles` (only the Basic +// style is placed) and `noconf` (no qt.conf). +import std; +import mcpp; +import mcpp.rules.qml; + +int main() { + namespace qml = mcpp::rules::qml; + mcpp::rerun_if_env_changed("MCPP_QML_VARIANT"); + const char* v = std::getenv("MCPP_QML_VARIANT"); + const std::string variant = v ? v : ""; + + qml::options o; + o.qt.modules = { "Core", "Gui", "Qml", "Quick" }; + o.qt.deploy_plugins = { "platforms" }; + o.qt.i18n.update_sources = true; + + qml::qml_module probe; + probe.uri = "Probe"; + probe.root = "qml/Probe"; + probe.sources = { "qml/Probe/**/*.qml", "qml/Probe/**/*.js" }; + probe.resources = { "qml/Probe/data/*" }; + probe.aot = variant != "noaot"; + o.modules = { probe }; + + if (variant == "styles") o.styles = { "Basic" }; + if (variant == "noconf") o.write_qt_conf = false; + return qml::compile(o) ? 0 : 1; +} diff --git a/tests/qml-consumer/mcpp.toml b/tests/qml-consumer/mcpp.toml new file mode 100644 index 0000000..df48115 --- /dev/null +++ b/tests/qml-consumer/mcpp.toml @@ -0,0 +1,49 @@ +# Fixture: a QML application built through rules-qml, with the SDK from `xim:qt` +# (qtbase, qtdeclarative with Qt Quick and Quick Controls, qttools). +# +# One QML module, `Probe`, in qml/Probe/: +# +# Main.qml the component the program loads with `loadFromModule` +# Style.qml `pragma Singleton`, listed in the qmldir as a singleton +# Util.js a JavaScript library the module imports +# sub/Inner.qml a file in a nested directory +# data/hello.txt a resource, read through `:/qt/qml/Probe/data/hello.txt` +# src/backend.h a C++ type with `QML_ELEMENT`, `src/theme.h` one with `QML_SINGLETON` +# +# The program runs headless: the platform plugin `offscreen` and Qt Quick's +# software renderer, so the same program is built and RUN on every host in the +# matrix and prints what each part of the module produced. +[package] +name = "qml-consumer" +version = "0.1.0" +description = "Fixture: a QML application built through rules-qml" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-qml"], host-module = true } + +# QML needs the Quick libraries, which `xim:qt-base` does not carry. +[target.'cfg(any(windows, linux, macos))'.xlings.workspace] +"xim:qt" = "6.11.1" + +[build] +sources = ["src/*.cpp", "*.ts"] + +[targets.qml-consumer] +kind = "bin" +main = "src/main.cpp" + +# As tests/qt-consumer: Qt's Linux libraries load the shared libstdc++, so on +# Linux the program uses the toolchain's shared C++ runtime (mcpp's docs/20). +# Windows and macOS keep the engine's default toolchain. +[target.x86_64-linux-gnu] +cxx_runtime = "toolchain-coupled" + +[target.aarch64-linux-gnu] +cxx_runtime = "toolchain-coupled" diff --git a/tests/qml-consumer/qml/Probe/Main.qml b/tests/qml-consumer/qml/Probe/Main.qml new file mode 100644 index 0000000..e16af73 --- /dev/null +++ b/tests/qml-consumer/qml/Probe/Main.qml @@ -0,0 +1,17 @@ +import QtQuick +import QtQuick.Controls +import "Util.js" as U +import Probe + +QtObject { + property Backend b: Backend {} + property QtObject inner: Inner { } + // A Qt Quick Controls type: the module `QtQuick.Controls` is Qt's, found at run time. + property Item controls: Item { Button { text: "ok" } } + readonly property int viaCpp: b.twice(b.n) + readonly property string viaSingleton: Style.accent + readonly property int viaJs: U.add(40, 2) + readonly property int viaNested: inner.value + readonly property int viaTheme: Theme.radius + readonly property string viaTr: qsTr("Hello") +} diff --git a/tests/qml-consumer/qml/Probe/Style.qml b/tests/qml-consumer/qml/Probe/Style.qml new file mode 100644 index 0000000..bbe08db --- /dev/null +++ b/tests/qml-consumer/qml/Probe/Style.qml @@ -0,0 +1,6 @@ +pragma Singleton +import QtQuick + +QtObject { + readonly property string accent: "red" +} diff --git a/tests/qml-consumer/qml/Probe/Util.js b/tests/qml-consumer/qml/Probe/Util.js new file mode 100644 index 0000000..80ea43a --- /dev/null +++ b/tests/qml-consumer/qml/Probe/Util.js @@ -0,0 +1,5 @@ +.pragma library + +function add(a, b) { + return a + b; +} diff --git a/tests/qml-consumer/qml/Probe/data/hello.txt b/tests/qml-consumer/qml/Probe/data/hello.txt new file mode 100644 index 0000000..777859a --- /dev/null +++ b/tests/qml-consumer/qml/Probe/data/hello.txt @@ -0,0 +1 @@ +hello-resource diff --git a/tests/qml-consumer/qml/Probe/sub/Inner.qml b/tests/qml-consumer/qml/Probe/sub/Inner.qml new file mode 100644 index 0000000..9bc0e3e --- /dev/null +++ b/tests/qml-consumer/qml/Probe/sub/Inner.qml @@ -0,0 +1,5 @@ +import QtQuick + +QtObject { + readonly property int value: 7 +} diff --git a/tests/qml-consumer/qml_consumer_de.ts b/tests/qml-consumer/qml_consumer_de.ts new file mode 100644 index 0000000..69d2ec1 --- /dev/null +++ b/tests/qml-consumer/qml_consumer_de.ts @@ -0,0 +1,12 @@ + + + + + Main + + + Hello + Hallo + + + diff --git a/tests/qml-consumer/src/backend.h b/tests/qml-consumer/src/backend.h new file mode 100644 index 0000000..3233e72 --- /dev/null +++ b/tests/qml-consumer/src/backend.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +// A C++ type of the Probe module: registered by `qmltyperegistrar` from the +// description `moc --output-json` wrote. +class Backend : public QObject { + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(int n READ n CONSTANT) +public: + explicit Backend(QObject* parent = nullptr) : QObject(parent) {} + int n() const { return 42; } + Q_INVOKABLE int twice(int v) const { return 2 * v; } +}; diff --git a/tests/qml-consumer/src/main.cpp b/tests/qml-consumer/src/main.cpp new file mode 100644 index 0000000..0bda361 --- /dev/null +++ b/tests/qml-consumer/src/main.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include +#include + +#include + +int main(int argc, char** argv) { + // Headless on every host, unless a caller asks for something else. + if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) qputenv("QT_QPA_PLATFORM", "offscreen"); + if (!qEnvironmentVariableIsSet("QT_QUICK_BACKEND")) qputenv("QT_QUICK_BACKEND", "software"); + QGuiApplication app(argc, argv); + + QTranslator translator; + translator.load("qml_consumer_de", QCoreApplication::applicationDirPath() + "/translations"); + QCoreApplication::installTranslator(&translator); + + QFile resource(":/qt/qml/Probe/data/hello.txt"); + if (!resource.open(QIODevice::ReadOnly)) { + std::puts("qml-consumer: the resource :/qt/qml/Probe/data/hello.txt is missing"); + return 1; + } + + QQmlEngine engine; + QQmlComponent component(&engine); + component.loadFromModule("Probe", "Main"); + if (component.isError()) { + for (const auto& e : component.errors()) std::printf("qml-consumer: %s\n", qPrintable(e.toString())); + return 1; + } + QObject* root = component.create(); + if (!root) { + std::puts("qml-consumer: the component did not instantiate"); + return 1; + } + std::printf("cpp=%d singleton=%s js=%d nested=%d resource=%s theme=%d\n", + root->property("viaCpp").toInt(), qPrintable(root->property("viaSingleton").toString()), + root->property("viaJs").toInt(), root->property("viaNested").toInt(), + resource.readAll().trimmed().constData(), root->property("viaTheme").toInt()); + std::printf("tr=%s controls=%d\n", qPrintable(root->property("viaTr").toString()), + root->property("controls").value() != nullptr); + return 0; +} diff --git a/tests/qml-consumer/src/theme.h b/tests/qml-consumer/src/theme.h new file mode 100644 index 0000000..580c861 --- /dev/null +++ b/tests/qml-consumer/src/theme.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +// A singleton declared in C++: it needs no line in the qmldir. +class Theme : public QObject { + Q_OBJECT + QML_ELEMENT + QML_SINGLETON + Q_PROPERTY(int radius READ radius CONSTANT) +public: + explicit Theme(QObject* parent = nullptr) : QObject(parent) {} + int radius() const { return 9; } +}; diff --git a/tests/qml-deploy/build.mcpp b/tests/qml-deploy/build.mcpp new file mode 100644 index 0000000..64adda2 --- /dev/null +++ b/tests/qml-deploy/build.mcpp @@ -0,0 +1,19 @@ +import std; +import mcpp; +import mcpp.rules.qml; + +int main() { + namespace qml = mcpp::rules::qml; + qml::options o; + o.qt.modules = { "Core", "Gui", "Qml", "Quick" }; + o.qt.deploy_plugins = { "platforms" }; + o.imports = { "QtQuick.Shapes" }; + o.import_paths = { "extra" }; + + qml::qml_module app; + app.uri = "App"; + app.root = "qml/App"; + app.sources = { "qml/App/*.qml" }; + o.modules = { app }; + return qml::compile(o) ? 0 : 1; +} diff --git a/tests/qml-deploy/extra/Acme/Gadget/Gadget.qml b/tests/qml-deploy/extra/Acme/Gadget/Gadget.qml new file mode 100644 index 0000000..15ce1ca --- /dev/null +++ b/tests/qml-deploy/extra/Acme/Gadget/Gadget.qml @@ -0,0 +1,6 @@ +pragma Singleton +import QtQuick + +QtObject { + readonly property int answer: 42 +} diff --git a/tests/qml-deploy/extra/Acme/Gadget/qmldir b/tests/qml-deploy/extra/Acme/Gadget/qmldir new file mode 100644 index 0000000..e04129f --- /dev/null +++ b/tests/qml-deploy/extra/Acme/Gadget/qmldir @@ -0,0 +1,2 @@ +module Acme.Gadget +singleton Gadget 1.0 Gadget.qml diff --git a/tests/qml-deploy/mcpp.toml b/tests/qml-deploy/mcpp.toml new file mode 100644 index 0000000..8728763 --- /dev/null +++ b/tests/qml-deploy/mcpp.toml @@ -0,0 +1,44 @@ +# Fixture: the Qt modules a program loads at run time, placed beside it. +# +# `qml/App/Main.qml` imports QtQuick.Layouts, QtQuick.Controls and +# QtQuick.Controls.Material, which the program does not link: Qt opens their +# plugin libraries when the engine reads the imports. The program also creates a +# `QtQuick.Shapes` object from text, which no `import` statement shows, so the +# build program names it (`options::imports`), and imports a module that lives +# in this project (`extra/Acme/Gadget`, `options::import_paths`). `mcpp pack` +# then has to carry the plugins, the libraries they load, and qt.conf, and +# the packed program has to run without the SDK. +[package] +name = "qml-deploy" +version = "0.1.0" +description = "Fixture: Qt modules placed beside a QML program" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-qml"], host-module = true } + +# QML needs the Quick libraries, which `xim:qt-base` does not carry. +[target.'cfg(any(windows, linux, macos))'.xlings.workspace] +"xim:qt" = "6.11.1" + +[build] +sources = ["src/*.cpp"] + +[targets.qml-deploy] +kind = "bin" +main = "src/main.cpp" + +# As tests/qt-consumer: Qt's Linux libraries load the shared libstdc++, so on +# Linux the program uses the toolchain's shared C++ runtime (mcpp's docs/20). +# Windows and macOS keep the engine's default toolchain. +[target.x86_64-linux-gnu] +cxx_runtime = "toolchain-coupled" + +[target.aarch64-linux-gnu] +cxx_runtime = "toolchain-coupled" diff --git a/tests/qml-deploy/qml/App/Main.qml b/tests/qml-deploy/qml/App/Main.qml new file mode 100644 index 0000000..4bf3954 --- /dev/null +++ b/tests/qml-deploy/qml/App/Main.qml @@ -0,0 +1,19 @@ +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls +import QtQuick.Controls.Material +import Acme.Gadget + +Item { + // Layouts: a plugin Qt opens, and a library only that plugin links. + property Item row: RowLayout { + Rectangle { implicitWidth: 30; implicitHeight: 10 } + Rectangle { implicitWidth: 12; implicitHeight: 10 } + } + readonly property int layoutWidth: row.implicitWidth + // Controls with the Material style, chosen by the environment. + property Item button: Button { text: "ok"; Material.accent: Material.Red } + // Created from text: no import statement shows QtQuick.Shapes to the closure. + property Item shape: Qt.createQmlObject("import QtQuick.Shapes; Shape { }", this, "shape") + readonly property int gadget: Gadget.answer +} diff --git a/tests/qml-deploy/src/main.cpp b/tests/qml-deploy/src/main.cpp new file mode 100644 index 0000000..ef0bb8c --- /dev/null +++ b/tests/qml-deploy/src/main.cpp @@ -0,0 +1,29 @@ +#include +#include +#include + +#include + +int main(int argc, char** argv) { + if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) qputenv("QT_QPA_PLATFORM", "offscreen"); + if (!qEnvironmentVariableIsSet("QT_QUICK_BACKEND")) qputenv("QT_QUICK_BACKEND", "software"); + if (!qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_STYLE")) qputenv("QT_QUICK_CONTROLS_STYLE", "Material"); + QGuiApplication app(argc, argv); + + QQmlEngine engine; + QQmlComponent component(&engine); + component.loadFromModule("App", "Main"); + if (component.isError()) { + for (const auto& e : component.errors()) std::printf("qml-deploy: %s\n", qPrintable(e.toString())); + return 1; + } + QObject* root = component.create(); + if (!root) { + for (const auto& e : component.errors()) std::printf("qml-deploy: %s\n", qPrintable(e.toString())); + return 1; + } + std::printf("layout=%d gadget=%d shape=%d button=%d\n", root->property("layoutWidth").toInt(), + root->property("gadget").toInt(), root->property("shape").value() != nullptr, + root->property("button").value() != nullptr); + return 0; +} diff --git a/tests/qml-import-only/mcpp.toml b/tests/qml-import-only/mcpp.toml new file mode 100644 index 0000000..4333e92 --- /dev/null +++ b/tests/qml-import-only/mcpp.toml @@ -0,0 +1,28 @@ +# Fixture: a package that enables `rules-qml` only to import `mcpp.rules.qml`, +# the shape of a library of build logic that other packages' build programs +# import. As tests/qt-import-only: no `build.mcpp`, no `.ui`, `.qrc` or `.ts`, and +# no Qt declared, so mcpp synthesises no build program and nothing reports a +# missing SDK. The consumer writes `host-module = true`; the feature names no +# `rule_module` (a `.qml` file needs a uri and a version that `[build] sources` +# cannot state), and the `rules-qt` it implies keeps its own. +[package] +name = "qml-import-only" +version = "0.1.0" +description = "Fixture: rules-qml enabled only for its module" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-qml"], host-module = true } + +[build] +sources = ["src/*.cpp"] + +[targets.qml-import-only] +kind = "bin" +main = "src/main.cpp" diff --git a/tests/qml-import-only/src/main.cpp b/tests/qml-import-only/src/main.cpp new file mode 100644 index 0000000..76e8197 --- /dev/null +++ b/tests/qml-import-only/src/main.cpp @@ -0,0 +1 @@ +int main() { return 0; } diff --git a/tests/qml-modules/build.mcpp b/tests/qml-modules/build.mcpp new file mode 100644 index 0000000..ce3795a --- /dev/null +++ b/tests/qml-modules/build.mcpp @@ -0,0 +1,33 @@ +// Three modules. `app.ui`'s C++ type derives from `app.core`'s, so each header is +// assigned to its module explicitly: with more than one module the rule does not +// guess. +import std; +import mcpp; +import mcpp.rules.qml; + +int main() { + namespace qml = mcpp::rules::qml; + qml::options o; + o.qt.modules = { "Core", "Gui", "Qml", "Quick" }; + o.qt.deploy_plugins = { "platforms" }; + + qml::qml_module core; + core.uri = "app.core"; + core.root = "qml/core"; + core.sources = { "qml/core/*.qml" }; + core.headers = { "src/core/base.h" }; + + qml::qml_module ui; + ui.uri = "app.ui"; + ui.root = "qml/ui"; + ui.sources = { "qml/ui/*.qml" }; + ui.headers = { "src/ui/derived.h" }; + + qml::qml_module plain; + plain.uri = "Plain"; + plain.root = "qml/plain"; + plain.sources = { "qml/plain/*.qml" }; + + o.modules = { core, ui, plain }; + return qml::compile(o) ? 0 : 1; +} diff --git a/tests/qml-modules/mcpp.toml b/tests/qml-modules/mcpp.toml new file mode 100644 index 0000000..c28422d --- /dev/null +++ b/tests/qml-modules/mcpp.toml @@ -0,0 +1,43 @@ +# Fixture: several QML modules in one program, through rules-qml. +# +# app.core C++ type `Base`, and `Card.qml` +# app.ui a dotted uri; C++ type `Derived`, derived from `app.core`'s `Base`, +# so its type description names a base class of another module +# Plain no C++ type: only `Chip.qml`, so no registrar runs for it +# +# The program loads `app.ui`'s Main, which uses all three, and prints what the +# inheritance across modules and the QML types of the others produced. +[package] +name = "qml-modules" +version = "0.1.0" +description = "Fixture: Three QML modules built through rules-qml" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-qml"], host-module = true } + +# QML needs the Quick libraries, which `xim:qt-base` does not carry. +[target.'cfg(any(windows, linux, macos))'.xlings.workspace] +"xim:qt" = "6.11.1" + +[build] +sources = ["src/*.cpp"] + +[targets.qml-modules] +kind = "bin" +main = "src/main.cpp" + +# As tests/qt-consumer: Qt's Linux libraries load the shared libstdc++, so on +# Linux the program uses the toolchain's shared C++ runtime (mcpp's docs/20). +# Windows and macOS keep the engine's default toolchain. +[target.x86_64-linux-gnu] +cxx_runtime = "toolchain-coupled" + +[target.aarch64-linux-gnu] +cxx_runtime = "toolchain-coupled" diff --git a/tests/qml-modules/qml/core/Card.qml b/tests/qml-modules/qml/core/Card.qml new file mode 100644 index 0000000..acd1e07 --- /dev/null +++ b/tests/qml-modules/qml/core/Card.qml @@ -0,0 +1,5 @@ +import QtQuick + +QtObject { + property int size: 1 +} diff --git a/tests/qml-modules/qml/plain/Chip.qml b/tests/qml-modules/qml/plain/Chip.qml new file mode 100644 index 0000000..bd1111e --- /dev/null +++ b/tests/qml-modules/qml/plain/Chip.qml @@ -0,0 +1,5 @@ +import QtQuick + +QtObject { + readonly property string label: "chip" +} diff --git a/tests/qml-modules/qml/ui/Main.qml b/tests/qml-modules/qml/ui/Main.qml new file mode 100644 index 0000000..ef2e06b --- /dev/null +++ b/tests/qml-modules/qml/ui/Main.qml @@ -0,0 +1,12 @@ +import QtQuick +import app.core +import Plain + +QtObject { + property Derived d: Derived {} + property QtObject c: Card { size: 4 } + property QtObject chip: Chip {} + readonly property int viaBase: d.v + readonly property int sum: d.v + d.w + c.size + readonly property string label: chip.label +} diff --git a/tests/qml-modules/src/core/base.h b/tests/qml-modules/src/core/base.h new file mode 100644 index 0000000..adb7d43 --- /dev/null +++ b/tests/qml-modules/src/core/base.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include + +class Base : public QObject { + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(int v READ v CONSTANT) +public: + explicit Base(QObject* parent = nullptr) : QObject(parent) {} + int v() const { return 7; } +}; diff --git a/tests/qml-modules/src/main.cpp b/tests/qml-modules/src/main.cpp new file mode 100644 index 0000000..eee5d1b --- /dev/null +++ b/tests/qml-modules/src/main.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +#include + +int main(int argc, char** argv) { + if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) qputenv("QT_QPA_PLATFORM", "offscreen"); + if (!qEnvironmentVariableIsSet("QT_QUICK_BACKEND")) qputenv("QT_QUICK_BACKEND", "software"); + QGuiApplication app(argc, argv); + + QQmlEngine engine; + QQmlComponent component(&engine); + component.loadFromModule("app.ui", "Main"); + if (component.isError()) { + for (const auto& e : component.errors()) std::printf("qml-modules: %s\n", qPrintable(e.toString())); + return 1; + } + QObject* root = component.create(); + if (!root) return 1; + // `viaBase` reads a property declared in the other module's C++ base class. + std::printf("sum=%d viaBase=%d label=%s\n", root->property("sum").toInt(), root->property("viaBase").toInt(), + qPrintable(root->property("label").toString())); + return 0; +} diff --git a/tests/qml-modules/src/ui/derived.h b/tests/qml-modules/src/ui/derived.h new file mode 100644 index 0000000..d0e9f16 --- /dev/null +++ b/tests/qml-modules/src/ui/derived.h @@ -0,0 +1,14 @@ +#pragma once + +#include "../core/base.h" + +// Derived from a type of another module: `qmltyperegistrar` is given the other +// module's type description as foreign types, so the base class is found. +class Derived : public Base { + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(int w READ w CONSTANT) +public: + explicit Derived(QObject* parent = nullptr) : Base(parent) {} + int w() const { return 8; } +}; diff --git a/tests/qml-shaders/build.mcpp b/tests/qml-shaders/build.mcpp new file mode 100644 index 0000000..a8b26da --- /dev/null +++ b/tests/qml-shaders/build.mcpp @@ -0,0 +1,18 @@ +import std; +import mcpp; +import mcpp.rules.qml; + +int main() { + namespace qml = mcpp::rules::qml; + qml::options o; + o.qt.modules = { "Core", "Gui", "Qml", "Quick" }; + o.qt.deploy_plugins = { "platforms" }; + + qml::qml_module shade; + shade.uri = "Shade"; + shade.root = "qml/Shade"; + shade.sources = { "qml/Shade/*.qml" }; + shade.shaders = { "shaders/wave.frag" }; + o.modules = { shade }; + return qml::compile(o) ? 0 : 1; +} diff --git a/tests/qml-shaders/mcpp.toml b/tests/qml-shaders/mcpp.toml new file mode 100644 index 0000000..ba83d7b --- /dev/null +++ b/tests/qml-shaders/mcpp.toml @@ -0,0 +1,47 @@ +# Fixture: a shader compiled by `qsb` and embedded in a QML module (Linux). +# +# `shaders/wave.frag` becomes `shaders/wave.frag.qsb` in the module's resources; +# the program reads it through `:/qt/qml/Shade/shaders/wave.frag.qsb`, and +# `Main.qml` names it as a ShaderEffect's `fragmentShader`. `qsb` is part of the +# additional libraries, `xim:qt-addons`, which the project declares beside +# `xim:qt` (a second SDK prefix: both are searched for tools). +# +# The check script runs `qsb --version` first, under the environment the rule +# runs it with, and skips this fixture with a notice where it does not start: +# an `xim:qt-addons` published before openxlings/xim-pkgindex#1262 left `qsb` +# on the system's loader, and it then fails with the distribution's Qt. +[package] +name = "qml-shaders" +version = "0.1.0" +description = "Fixture: A shader compiled by qsb and embedded through rules-qml" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = false + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-qml"], host-module = true } + +# QML needs the Quick libraries, which `xim:qt-base` does not carry. +[target.'cfg(any(windows, linux, macos))'.xlings.workspace] +"xim:qt" = "6.11.1" +"xim:qt-addons" = "6.11.1" + +[build] +sources = ["src/*.cpp"] + +[targets.qml-shaders] +kind = "bin" +main = "src/main.cpp" + +# As tests/qt-consumer: Qt's Linux libraries load the shared libstdc++, so on +# Linux the program uses the toolchain's shared C++ runtime (mcpp's docs/20). +# Windows and macOS keep the engine's default toolchain. +[target.x86_64-linux-gnu] +cxx_runtime = "toolchain-coupled" + +[target.aarch64-linux-gnu] +cxx_runtime = "toolchain-coupled" diff --git a/tests/qml-shaders/qml/Shade/Main.qml b/tests/qml-shaders/qml/Shade/Main.qml new file mode 100644 index 0000000..406d04f --- /dev/null +++ b/tests/qml-shaders/qml/Shade/Main.qml @@ -0,0 +1,13 @@ +import QtQuick + +Item { + width: 64 + height: 64 + // The compiled shader is a resource of this module, beside this file. + property Item effect: ShaderEffect { + width: 64 + height: 64 + fragmentShader: "shaders/wave.frag.qsb" + } + readonly property url shader: effect.fragmentShader +} diff --git a/tests/qml-shaders/shaders/wave.frag b/tests/qml-shaders/shaders/wave.frag new file mode 100644 index 0000000..6c94680 --- /dev/null +++ b/tests/qml-shaders/shaders/wave.frag @@ -0,0 +1,13 @@ +#version 440 + +layout(location = 0) in vec2 qt_TexCoord0; +layout(location = 0) out vec4 fragColor; + +layout(std140, binding = 0) uniform buf { + mat4 qt_Matrix; + float qt_Opacity; +}; + +void main() { + fragColor = vec4(qt_TexCoord0, 0.5, 1.0) * qt_Opacity; +} diff --git a/tests/qml-shaders/src/main.cpp b/tests/qml-shaders/src/main.cpp new file mode 100644 index 0000000..0a7d045 --- /dev/null +++ b/tests/qml-shaders/src/main.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include + +#include + +int main(int argc, char** argv) { + if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) qputenv("QT_QPA_PLATFORM", "offscreen"); + if (!qEnvironmentVariableIsSet("QT_QUICK_BACKEND")) qputenv("QT_QUICK_BACKEND", "software"); + QGuiApplication app(argc, argv); + + // The .qsb `qsb` wrote is in the module's resources. + QFile qsb(":/qt/qml/Shade/shaders/wave.frag.qsb"); + if (!qsb.open(QIODevice::ReadOnly)) { + std::puts("qml-shaders: the resource :/qt/qml/Shade/shaders/wave.frag.qsb is missing"); + return 1; + } + const QByteArray bytes = qsb.readAll(); + + QQmlEngine engine; + QQmlComponent component(&engine); + component.loadFromModule("Shade", "Main"); + if (component.isError()) { + for (const auto& e : component.errors()) std::printf("qml-shaders: %s\n", qPrintable(e.toString())); + return 1; + } + QObject* root = component.create(); + if (!root) return 1; + std::printf("qsb=%lld bytes shader=%s\n", static_cast(bytes.size()), + qPrintable(root->property("shader").toUrl().toString())); + return 0; +}