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

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

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