Skip to content

0.28.0: rules-python, Python bindings for C++23 modules - #72

Open
Shinonome-Ryoko14 wants to merge 1 commit into
mcpp-community:mainfrom
Shinonome-Ryoko14:feat/rules-python
Open

Shinonome-Ryoko14 wants to merge 1 commit into
mcpp-community:mainfrom
Shinonome-Ryoko14:feat/rules-python

Conversation

@Shinonome-Ryoko14

@Shinonome-Ryoko14 Shinonome-Ryoko14 commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Adds mcpp.rules.python (features = ["rules-python"]), binding a C++23 module's surface to Python from build.mcpp without modifying the C++ module source.

Part of #71 (M1 slice: mcpp.rules.python core with ctypes, nanobind, and explicit GCC 16 reflect backends).

Summary

  • Two backends under one declaration (rules/python.cppm):
    • binding::nanobind: generates the NB_MODULE translation unit over mcpplibs.mwrap.nanobind (published in mcpplibs/mcpp-index as 3.1.0), resolves the Python SDK (python_include_dir / env overrides / xim:python / uv / host), emits host link directives, stages <module><EXT_SUFFIX>, and optionally emits <module>.pyi. Supports discovery::explicit_list, discovery::reflect (GCC 16 C++26 P2996 -freflection), and discovery::manual.
    • binding::ctypes: zero-Python-build-dependency path generating an extern "C" bridge and a typed .py wrapper beside the shared library so C++ and Python consumers share the same artifact.
  • Fixtures and CI:
    • tests/all-rules-compile: exercises all pure renderers and validate paths.
    • tests/python-consumer: end-to-end ctypes fixture with an unchanged C++ consumer (cpp-app) and Python round-trip checks on Linux, macOS, and Windows.
    • tests/python-nanobind-consumer: end-to-end native CPython extension fixture (discovery::explicit_list) enabled on Linux, macOS, and Windows against published mcpplibs.mwrap.nanobind 3.1.0.
    • tests/python-reflect-consumer: end-to-end P2996 reflection fixture (discovery::reflect) enabled on Linux GCC 16.
  • Docs and metadata:
    • Bumps package version 0.27.0 -> 0.28.0 (mcpp.toml, src/plugins.cppm).
    • Adds docs/13-rules-python.md and updates docs/README.md, docs/00-engine-and-rules.md, docs/10-rules.md, README.md, and README.zh-CN.md.

Comment thread docs/13-rules-python.md Resolved
Comment thread docs/13-rules-python.md Resolved
@speak-agent

Copy link
Copy Markdown
Member

Review: rules-python (0.28.0)

CI is green (6/6) and this is a strong first slice: the two backends are cleanly separated, the source module stays untouched, reflection syntax stays out of the plugin source, and the fixtures cover ctypes, nanobind, reflection, a C++ consumer and the exception path.

I recommend request changes before merge.

Blocking

  1. The Python SDK is not provisioned by the feature, and discovery bypasses the collection's tool model. python_spec and uv_spec use request = false; find_xim_python reads xpkg_dir directly; find_uv and find_host_python pass on_path as a stated choice, so MCPP_UV, the engine override and the declared payload are never reached, no pending or mcpp::decision is recorded, and a failed explicit choice silently falls through. The fixtures only pass because they declare [xlings.workspace] "xim:python". Add [feature-xlings.rules-python] with provision = "on-request", route discovery through tool::resolve, handle pending, record the source, and remove the workspace declarations from the docs and fixtures. The documented overrides MCPP_PYTHON_LIBRARY_DIR, MCPP_PYTHON_LIBRARY and VIRTUAL_ENV are not read today, and MCPP_PYTHON_INCLUDE_DIR can be overwritten by the interpreter probe; implement or remove them.
  2. host-module = true is obsolete on [build-dependencies] at the supported floor (>= 2026.10.30.1): a plain entry already asks for the library. Remove it from docs/13 (both sites), docs/00, docs/10 and the three fixtures.
  3. The cross-compilation path contradicts the docs. docs/13 says python_include_dir plus ext_suffix run no interpreter, but the artifact action runs sdk.executable with -c and shutil.copy2, falling back to python3; a headers-only cross build still needs a host Python, and options::python = tool::root(...) would try to run a directory. Use the engine copy primitive (mcpp stage --output, as mcpp.plugins.fs::deploy_after does) and fix emitted.python_executable, which is assigned before the fallback.
  4. This is a slice of [RFC] rules-python / dist-wheel: C++23 模块 → Python 扩展全链路闭环(架构、生态包与 M0–M3 里程碑) #71, not its completion: there is no venv install, no uv default, no mcpp run format, no mtest/pytest fixture, no templates, no dist-wheel/publish/ABI matrix, and reflection is explicit rather than auto-probed. State "Part of [RFC] rules-python / dist-wheel: C++23 模块 → Python 扩展全链路闭环(架构、生态包与 M0–M3 里程碑) #71" and either merge as an explicit M1 slice or add the missing milestones.

Important

  1. target_name only feeds the artifact copy; include_dir, cxxflag and link_* are package-wide. A package with an app and an extension gets the Python headers and libpython (and on macOS -undefined dynamic_lookup) on every link; reflect sets C++26 for the whole package. Document the one-shared-target limit and file the per-target engine gap; the artifact copy also leaves the original library behind.
  2. ctypes swallows exceptions into 0 or "" with no way to distinguish a real result; document that or provide an error channel. User names ctypes, len and bool (function or parameter) can break the generated wrapper, and C++ keyword parameter names break the bridge; alias the internals and prefix generated C++ parameters, or validate the names.
  3. starts_with("gcc") accepts GCC 15 and then fails at compile time, though the docs promise a named refusal. Check the toolset version; also state whether auto-reflection probing is in scope.
  4. Documented behaviour without criteria: discovery::manual, explicit env::uv/xim, cross compilation, library_name/symbol_prefix/deploy_to/emit_stub=false/import_stl=false, and the static-CRT refusal. manual is currently dead code in render_nanobind_entry. Add at least manual and one cross or negative fixture, or trim the docs.

Nits

  • Move [features.rules-python] next to the other rules; 1390 lines may warrant rules/python/ with internal units.
  • The ctypes and reflect examples do not call emit; "crate" in Criteria; dead include_under/source/reflect .pyi branch.
  • CI repeats the interpreter lookup three times, parses the internal .build-mcpp/build.mcpp.cache, and hard-codes 3.13.12; factor a helper.
  • Add Part of #71 to the PR body.

I did not rerun the matrix locally; the six CI checks are green and this review is from the diff plus the engine and tool conventions.

@Shinonome-Ryoko14

Copy link
Copy Markdown
Member Author

Addressed all blocking, important, and nit items in 43ec744:

@speak-agent

Copy link
Copy Markdown
Member

Re-review: 43ec744

CI is green (6/6), and the iteration fixed the concrete blockers from the previous review: host-module is gone, the artifact copy uses ${mcpp.self} stage --output with no host Python, explicit options::python no longer falls back silently, ctypes generated names are protected, and reflection now checks GCC >= 16. I also built the ctypes and default nanobind fixtures locally after clearing an unrelated mcpp std-cache lock: both build and import.

I recommend request changes for three points, one of which is a design decision rather than a defect.

1. The default SDK should be opt-in and owned by mcpplibs.mwrap.nanobind

The default itself is reasonable: zero-config nanobind is a real use case, and 3.13.12 matches the 3.1.0 runtime. The problem is the layer and the precedence, not the existence of a default.

The clean design, since both packages are maintained here, is:

  • remove the always-on [feature-xlings.rules-python] from this package;
  • remove nanobind-m's unconditional [xlings.workspace] "xim:python";
  • add a non-default python-sdk feature to nanobind-m, whose [feature-xlings.python-sdk] declares xim:python = "3.13.12" eagerly when selected;
  • consumers opt in with mcpplibs.mwrap.nanobind = { features = ["python-sdk"] };
  • rules-python keeps python_spec.request = false and reads the payload already declared in the graph.

Then runtime and entry share the same xpkg_dir("xim","python"), the default is not forced on every project, and ctypes does not request it. If nanobind-m cannot change in this PR, the same default must at least be the lowest-priority fallback, target-scoped, and covered by a test where a project [xlings.workspace] or venv selects 3.12.

2. env::auto_ still requests the payload before the environment sources

rules/python.cppm:1282-1285 calls try_xim_python() before find_uv_python/find_host_python, and find_xim_python reaches the pending request. With a valid VIRTUAL_ENV or MCPP_UV and no installed payload, the build requests xim:python and returns pending; the venv/uv source is never used. MCPP_PYTHON_INCLUDE_DIR/EXT_SUFFIX can also take precedence over an explicit options::python (:1218-1237 before :1238), and a bad MCPP_PYTHON_EXECUTABLE is probed twice and silently replaced by uv/PATH.

Please make the order explicit (options, then env/venv, then project/dependency payload, then uv/PATH) and test it with MCPP_NO_AUTO_INSTALL=1, a fake venv, and an explicit option plus an environment pair.

3. Non-default SDK sources can split entry and runtime

The default 3.13.12 path is coherent. But mcpplibs.mwrap.nanobind resolves its own SDK, while python_env=uv/host, options::python, or options-only headers can select another one. That is a cross-package ABI issue whose durable fix belongs in nanobind-m (compile nb_runtime.cpp with the extension's SDK, or expose a shared SDK contract). In this PR, either gate those modes for nanobind or document MCPP_PYTHON_INCLUDE_DIR + MCPP_PYTHON_EXT_SUFFIX as the only shared custom path.

Other issues to address before merge

  • ctypes deploy_to other than ".": only the .py is deployed under the subdirectory, while the library stays in the artifact directory, so _load_library cannot find it.
  • a ctypes function named res with a string return emits const std::string res = res(...), which is invalid C++; rename the local or reject it.
  • explicit_list prepends & to cpp_expr, so the documented "cast for an overload" workaround is not expressible; either accept a complete expression or state that overloads are unsupported.
  • register_with_build = false still adds reflect flags/rerun inputs, and the static-CRT refusal writes the entry and registers the graph before returning ok = false.
  • Debian/Ubuntu host Python 3.12 fails on x86_64-linux-gnu/python3.12/pyconfig.h because only sysconfig.get_path('include') is added and mcpp uses -nostdinc; cover platinclude or narrow the host path.
  • The criteria still do not cover headers-only emit, pending, static CRT, .pyi content, manual, ctypes exception sentinels, or host Python.

The scan hang I reported earlier is mcpp issue #1040 (a stale std-module lock owner), not this PR.

I am happy to re-review once the SDK ownership/precedence decision is settled.

@Shinonome-Ryoko14

Copy link
Copy Markdown
Member Author

@Sunrisepeak 感谢建议,关于三层分层设计和对应的tradeoff我这边梳理了一套统一方案,麻烦跟我对齐一下标准,确认下是否按这个方向落地:

1. SDK 归属与开关(收口到 nanobind-m)

  • mcpp-plugins 移除 [feature-xlings.rules-python],rules-python 保持 python_spec.request = false,只消费图里已有的 xim:python(ctypes 完全不沾 Python SDK)。
  • nanobind-m 移除无条件 [xlings.workspace] "xim:python",改为 [feature-xlings.python-sdk] "xim:python" = "3.13.12",由 nanobind-m 作为唯一的 SDK 真相源,保证 nb_runtime.cpp 与扩展入口天然共享同一份 payload。

这里有个核心 tradeoff —— python-sdk 默认开还是默认关:

  • 方案 A(我个人倾向于这个):默认开启、可关闭(default = ["runtime", "python-sdk"])
    • 优点:新手只写 mcpplibs.mwrap.nanobind = "3.1.0" 即可零配置开箱即用,且对 mcpp-index 已合入的 nanobind-embed 零破坏;自定义开发者写 default-features = false, features = ["runtime"] 可彻底关闭拉取。
    • 代价:如果开发者用了自己的 VIRTUAL_ENV 但没关默认 feature,构建前仍可能先下载一份 xim:python 3.13.12(尽管最终编译会被环境变量覆盖)。
  • 方案 B(speak-agent 建议的方案):默认关闭、按需开启(default = ["runtime"])
    • 优点:绝不隐式下载,用本地 venv / 宿主 Python 时零冗余拉取;需要默认 SDK 时显式写 features = ["python-sdk"]。
    • 代价:默认不再零配置,且需同步更新 mcpp-index 的 nanobind-embed 与本 PR 的 fixture。

2. 开发者自定义层与优先级统一

  • nanobind-m/build.mcpp 与 rules/python.cppm 统一解析顺序:
    1. build.mcpp 显式选项(仅 rules-python,严格不兜底)
    2. 共享环境变量 / 虚拟环境(MCPP_PYTHON_INCLUDE_DIR+EXT_SUFFIX、严格 MCPP_PYTHON_EXECUTABLE、VIRTUAL_ENV)
    3. 图内 xim:python payload
    4. uv / 宿主 PATH(补齐 Debian/Ubuntu platinclude)
  • tradeoff:环境变量 / VIRTUAL_ENV / xim:python 在两仓自动 ABI 一致;但保留 options::python / options::python_include_dir(nanobind-m 不可见)意味着仍存在误用导致 entry/runtime ABI 错配的可能。本 M1 阶段计划保留这些选项以支持交叉编译和高级定制,并在文档中明确约定“跨包自定义 SDK 须走共享环境变量或关闭 python-sdk 保持一致”(而非在 rules-python 里硬门禁封死,留给开发者自行控制)。

3. 其余实现细节

speak-agent 提到的 6 项具体问题(ctypes 非 "." 的 deploy_to、_mcpp_res 冲突、cpp_expr 重载 static_cast、register_with_build = false 与静态 CRT 校验顺序、platinclude、以及优先级/边界测试补齐)会随本 PR 一并修复。

麻烦与我对齐一下颗粒度,确认后我就同步推进 nanobind-m + mcpp-index 小更新并更新本 PR。

@Sunrisepeak

Copy link
Copy Markdown
Member
  • 1.方案A没有问题
  • 2.开发者自定义层 优先级OK, 但是需要在文档里备注或提示 在build.mcpp 自定义时 建议关闭 nanobind-m 的默认sdk, 以及 插件里是否可以检查 当使用 插件自定义的时候 打印提示 或 有没有更好的方法 build.mcpp 自定义的时候 处理逻辑可以自动覆盖nanobind-m 的sdk

整体方向没有问题, 可能技术实现上 要深度分析 实现的策略 以及 问题 能不能通过设计 优雅的解决, 默认尽量减少开发者的负担,又能支持自定义的控制, 且有明确的优先级处理关系

@Shinonome-Ryoko14

Copy link
Copy Markdown
Member Author

@Sunrisepeak 已按敲定的三层分层方案在 af30e4d 完成更新,并同步提交了 nanobind-m 的配套 PR(feat/python-sdk-feature)。下面是设计说明,你看看如何:


一、设计动机

Python 扩展构建涉及两个独立编译单元:上游 mcpplibs.mwrap.nanobind(编译模块 BMI 与 nb_runtime.cpp)和下游用户包(经 mcpp.rules.python 生成并编译 NB_MODULE 入口)。两者必须针对同一份 CPython ABI / 头文件编译。

在原实现中,nanobind-m(无条件 [xlings.workspace])与 mcpp-plugins([feature-xlings.rules-python])两侧同时声明 xim:python,且查找优先级不一致,容易带来三个问题:

  1. 默认 SDK 归属分裂,ctypes 后端不需要 Python SDK 却与插件 feature 耦合;
  2. 下游 build.mcpp 或环境变量覆盖时,可能只改了入口侧而上游 nb_runtime.cpp 仍命中 xim:python,造成静默 ABI 分裂;
  3. 无法只通过 manifest 干净地关闭默认 SDK。

因此将 SDK 生命周期与默认开关统一收口到 nanobind-m 层,rules-python 只做消费、校验与构建编排,并让两仓共享完全一致的优先级 Spec。


二、分层 Spec 与优先级契约

1. 三层控制模型

层级 归属与写法 行为
默认层(零负担开箱即用) nanobind-m:default = ["runtime", "python-sdk"] + [feature-xlings.python-sdk] "xim:python" = "3.13.12" 用户只写 mcpplibs.mwrap.nanobind = "3.1.0" 即可零配置构建;nb_runtime.cpp 与扩展入口天然共享同一份 xim:python。mcpp-plugins 移除 [feature-xlings.rules-python] 且 python_spec().request = false,ctypes 零依赖零下载。
开关控制层(显式关闭默认) nanobind-m:mcpplibs.mwrap.nanobind = { version = "3.1.0", default-features = false, features = ["runtime"] } 完全不拉取 xim:python,由开发者通过环境变量 / venv / 项目 [xlings.workspace] / 宿主 Python 接管。
开发者自定义层 共享环境变量 / [xlings.workspace](跨包生效)或 build.mcpp options::*(仅插件侧局部生效) 按下方统一 4 级优先级解析。

2. 统一 4 级解析优先级(nanobind-m/build.mcpp 与 rules/python.cppm 对齐)

  1. build.mcpp 显式选项(仅 rules-python:options::python_include_dir + ext_suffix 或 options::python)—— 严格模式:解析或探测失败直接报错,绝不静默回退,且不被环境变量覆盖。
  2. 共享环境变量 / 虚拟环境(两仓同时读取,自动保持 ABI 一致):
    • MCPP_PYTHON_INCLUDE_DIR(+ MCPP_PYTHON_EXT_SUFFIX,无解释器交叉编译);
    • MCPP_PYTHON_EXECUTABLE —— 严格模式:只探测一次,无效直接报错,不回退到 xim:python/uv/PATH;
    • VIRTUAL_ENV。
  3. 图内 xim:python payload(nanobind-m 的 python-sdk feature 或用户项目更近的 [xlings.workspace])—— rules-python 仅读取 mcpp::xpkg_dir("xim", "python"),永不触发安装请求。
  4. uv / 宿主 PATH(支持 Debian/Ubuntu sysconfig.get_path('platinclude'))。

三、关键 Trade-off(取舍与权衡)

  1. 为什么 build.mcpp 自定义无法自动覆盖 nanobind-m 的 SDK,以及如何兜底?

    • 引擎约束:nanobind-m 的 .cppm BMI 与 nb_runtime.cpp 是在上游独立 build.mcpp 进程中编译的,当前 mcpp 协议没有“下游 build.mcpp 向上游依赖注入 env/include”的通道。
    • 取舍:不在插件层做脆弱的跨包 hack,而是采用 “共享通道优先 + 局部冲突自动检测”:
      • 跨包自定义推荐走共享环境变量(MCPP_PYTHON_EXECUTABLE / VIRTUAL_ENV / MCPP_PYTHON_INCLUDE_DIR+EXT_SUFFIX)或项目 [xlings.workspace],两仓自动命中同一 SDK;
      • 当开发者在 build.mcpp 用局部选项(options::python / options::python_include_dir / uv / host)选中了与图内 xim:python 不同路径的 SDK 时,rules/python.cppm 自动检测并输出 mcpp::warning,提示关闭 nanobind-m 的默认 python-sdk 或改用共享通道,并在 docs/13-rules-python.md 写明建议;
      • 未来若引擎补充包间配置/fact 传递机制,可在不破坏现有 API 的前提下自然升级为自动对齐。
  2. 为什么 python-sdk 选“默认开启、可关闭”而非“默认关闭、按需开启”?

    • 收益:保住“新手只写 mcpplibs.mwrap.nanobind = "3.1.0" 零配置跑通”的体验,且完全向后兼容 mcpp-index 已合入的 tests/mwrap/nanobind-embed;需要完全脱离默认 SDK 的高级用户用 default-features = false, features = ["runtime"] 一行即可关闭,配合更高的环境变量优先级,既不增加默认负担也不阻挡自定义。
    • 代价:未关闭默认 feature 且仅用环境变量覆盖时,仍会存在一次 xim:python payload 声明;已在文档与警告中明确提示通过 default-features = false 消除。
  3. 为什么 PR 0.28.0: rules-python, Python bindings for C++23 modules #72 的两个 fixture 暂留 [xlings.workspace] "xim:python" = "3.13.12"?

    • 当前已发布的 mcpp-index 中 nanobind-m@3.1.0 尚未包含新合入的 python-sdk feature 变更。在两个 fixture 中保留就近声明可保证本 PR 与 nanobind-m 更新解耦、独立通过 CI;待新版 nanobind-m 发布到 mcpp-index 后,用户与 fixture 均可直接省去该声明。

四、同步修复的其余 6 项实现细节与验证

  • ctypes 非 . 的 deploy_to:生成的 _load_library 增加 _ROOTS 多级父目录回溯,子目录部署的 .py 可正确找到共享库;
  • ctypes 函数名为 res 返回 std::string:桥接局部变量改名为 _mcpp_res,消除名称遮蔽;
  • explicit_list 重载表达式:cpp_expr 已含 & / static_cast< / reinterpret_cast< / ( / [ 时不再重复拼接 &;
  • register_with_build = false 与静态 CRT 拒绝:register_with_build = false 不再注册 flag/rerun,Windows 静态 CRT 拒绝提前到写文件与图注册之前,零副作用;
  • Debian/Ubuntu 宿主 Python:探测并注入 sysconfig.get_path('platinclude');
  • 测试与 CI:tests/python-consumer 补 checked_div 异常哨兵验证,tests/all-rules-compile 与 ci.yml 补 MCPP_NO_AUTO_INSTALL=1 优先级、严格 MCPP_PYTHON_EXECUTABLE、headers-only emit、.pyi、_mcpp_res、deploy_to 与重载表达式测试。

@Sunrisepeak

Copy link
Copy Markdown
Member

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants