From af30e4dd3f659c45b576904d572b1e457d3041d5 Mon Sep 17 00:00:00 2001 From: Shinonome-Ryoko14 Date: Thu, 3 Dec 2026 12:21:41 +0800 Subject: [PATCH] 0.28.0: rules-python, Python bindings for C++23 modules --- .github/scripts/verify-python-extension.sh | 48 + .github/workflows/ci.yml | 268 ++- README.md | 3 +- README.zh-CN.md | 3 +- docs/00-engine-and-rules.md | 1 + docs/10-rules.md | 8 +- docs/13-rules-python.md | 283 +++ docs/README.md | 2 + mcpp.toml | 19 +- rules/python.cppm | 1537 +++++++++++++++++ src/plugins.cppm | 2 +- tests/all-rules-compile/build.mcpp | 238 +++ tests/all-rules-compile/mcpp.toml | 2 +- tests/python-consumer/build.mcpp | 46 + tests/python-consumer/cpp-app/mcpp.toml | 26 + tests/python-consumer/cpp-app/src/main.cpp | 21 + tests/python-consumer/mcpp.toml | 31 + tests/python-consumer/src/mathlib.cppm | 64 + tests/python-nanobind-consumer/build.mcpp | 35 + tests/python-nanobind-consumer/mcpp.toml | 40 + .../src/fast-ops.cppm | 40 + tests/python-nanobind-consumer/verify.py | 25 + tests/python-reflect-consumer/build.mcpp | 28 + tests/python-reflect-consumer/mcpp.toml | 37 + .../src/fast-ops-reflect.cppm | 32 + tests/python-reflect-consumer/verify.py | 25 + 26 files changed, 2845 insertions(+), 19 deletions(-) create mode 100755 .github/scripts/verify-python-extension.sh create mode 100644 docs/13-rules-python.md create mode 100644 rules/python.cppm create mode 100644 tests/python-consumer/build.mcpp create mode 100644 tests/python-consumer/cpp-app/mcpp.toml create mode 100644 tests/python-consumer/cpp-app/src/main.cpp create mode 100644 tests/python-consumer/mcpp.toml create mode 100644 tests/python-consumer/src/mathlib.cppm create mode 100644 tests/python-nanobind-consumer/build.mcpp create mode 100644 tests/python-nanobind-consumer/mcpp.toml create mode 100644 tests/python-nanobind-consumer/src/fast-ops.cppm create mode 100644 tests/python-nanobind-consumer/verify.py create mode 100644 tests/python-reflect-consumer/build.mcpp create mode 100644 tests/python-reflect-consumer/mcpp.toml create mode 100644 tests/python-reflect-consumer/src/fast-ops-reflect.cppm create mode 100644 tests/python-reflect-consumer/verify.py diff --git a/.github/scripts/verify-python-extension.sh b/.github/scripts/verify-python-extension.sh new file mode 100755 index 0000000..c4a5ad3 --- /dev/null +++ b/.github/scripts/verify-python-extension.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Import the native extension a rules-python fixture built and run its verifier. +# +# usage: verify-python-extension.sh +# +# The interpreter MUST be the one the rule built against: Ubuntu's python3 is +# too old for a cpython-313 extension. The rule records it as a +# `python.executable` fact, which is the first answer. The payload glob is a +# fallback for a cold build-program cache and names no version, so a future +# xim:python release does not require editing this script. +set -eu + +repo=$(cd "$(dirname "$0")/../.." && pwd) +fixture=${1:?usage: verify-python-extension.sh } +case "$fixture" in + /*) ;; + *) fixture="$repo/$fixture" ;; +esac +cd "$fixture" + +py= +if [ -f target/.build-mcpp/build.mcpp.cache ]; then + py=$(sed -n 's/^d fact python\.executable=//p' target/.build-mcpp/build.mcpp.cache \ + | tr -d '\r' | head -1) +fi +if [ -z "$py" ]; then + for root in "${XLINGS_HOME:-}" "${MCPP_HOME:-}" "$HOME/.xlings" "$HOME/.mcpp"; do + [ -n "$root" ] || continue + for cand in \ + "$root"/registry/data/xpkgs/xim-x-python/*/bin/python3 \ + "$root"/registry/data/xpkgs/xim-x-python/*/python.exe \ + "$root"/data/xpkgs/xim-x-python/*/bin/python3 \ + "$root"/data/xpkgs/xim-x-python/*/python.exe; do + if [ -f "$cand" ]; then py=$cand; break 2; fi + done + done +fi +py=${py:-${MCPP_PYTHON_EXECUTABLE:-$(command -v python3 || command -v python || true)}} +test -n "$py" || { echo "FAIL: no Python interpreter to run verify.py"; exit 1; } +if command -v cygpath >/dev/null 2>&1; then + py=$(cygpath -u "$py") +fi + +echo "python: $("$py" -c 'import sys; print(sys.version.split()[0], sys.executable)')" +ext=$(find target \( -name 'fast_ops.cpython-*.so' -o -name 'fast_ops.cp*.pyd' \) -type f \ + | { grep -v '/\.build-mcpp/' || true; } | head -1) +test -n "$ext" || { echo "FAIL: no native extension"; find target -name 'fast_ops*' | head; exit 1; } +"$py" verify.py "$(dirname "$ext")" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 62f7475..c1e8fe2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -781,6 +781,139 @@ jobs: rm -f neg.log restored.log cpu.log cpurun.log echo "ok: and it builds again once the two agree" + # THE PYTHON FFI, END TO END, WITH NO PYTHON BUILD TOOLCHAIN. + # + # `rules-python`'s ctypes backend writes the `extern "C"` glue and + # `mathlib.py` while the build program plans. The criteria are all + # observable in one run -- the generated texts, the C ABI symbols in the + # shared library, the `.py` placed beside that library, the untouched C++ + # consumer and the system `python3` importing the result. + - name: rules-python (ctypes) generates the glue and the wrapper + working-directory: tests/python-consumer + run: | + set -e + "$MCPP" build + d=$(sh "$GITHUB_WORKSPACE/tests/out-dir.sh")/python + test -f "$d/mathlib_pybridge.cpp" + test -f "$d/mathlib.py" + grep -q 'extern "C"' "$d/mathlib_pybridge.cpp" + grep -q 'mcpp_py_mathlib_free_string' "$d/mathlib_pybridge.cpp" + so=$(find target -name 'libmathlib.so' -type f | head -1) + test -n "$so" || { echo "FAIL: no shared library"; exit 1; } + art_dir=$(dirname "$so") + test -f "$art_dir/mathlib.py" + nm -D --defined-only "$so" | grep -q ' mcpp_py_mathlib_add$' + nm -D --defined-only "$so" | grep -q ' mcpp_py_mathlib_greet$' + nm -D --defined-only "$so" | grep -q ' mcpp_py_mathlib_free_string$' + # The source module carries no FFI trace, which is what "zero + # intrusion" means here. + if grep -rnE 'extern "C"|Python\.h|MCPP_PY_EXPORT' src/ \ + | grep -vE '^[^:]+:[0-9]+:[[:space:]]*//'; then + echo "FAIL: the C++ module has FFI traces"; exit 1 + fi + echo "ok: glue, wrapper, symbols and deployment" + + - name: the C++ consumer imports the same module unchanged + working-directory: tests/python-consumer/cpp-app + run: | + set -e + "$MCPP" build + "$MCPP" run | tee run.log + grep -q '^cpp-app ok' run.log + + - name: python3 imports the generated wrapper and every base type round-trips + working-directory: tests/python-consumer + run: | + set -e + so=$(find target -name 'libmathlib.so' -type f | head -1) + art_dir=$(dirname "$so") + PYTHONPATH="$art_dir" python3 -c ' + import inspect, mathlib + + assert mathlib.add(17, 25) == 42 + assert mathlib.add.__doc__ == "Return the \"sum\"" + assert mathlib.mul_i64(10**12, 3) == 3 * 10**12 + assert abs(mathlib.hypotenuse(3.0, 4.0) - 5.0) < 1e-12 + assert mathlib.is_even(42) is True + assert mathlib.is_even(41) is False + assert mathlib.toggle(True) is False + assert mathlib.toggle(False) is True + + assert mathlib.greet("mcpp") == "Hello, mcpp!" + assert mathlib.greet("ไธ–็•Œ๐Ÿš€") == "Hello, ไธ–็•Œ๐Ÿš€!" + assert mathlib.greet("") == "Hello, !" + assert mathlib.join("a", "b") == "ab" + assert mathlib.noop() is None + # A C++ exception at the extern "C" boundary returns the zero sentinel. + assert mathlib.checked_div(10, 2) == 5 + assert mathlib.checked_div(1, 0) == 0 + + for i in range(1000): + assert mathlib.greet(f"user-{i}") == f"Hello, user-{i}!" + + sig = inspect.signature(mathlib.greet) + assert sig.parameters["name"].annotation in ("str", str) + assert sig.return_annotation in ("str", str) + print("python-consumer ok") + ' + + # THE PRECEDENCE CONTRACT, WITH BOTH SIDES PRESENT. + # + # The shared environment names one headers pair and the build program + # states a different one. `rules-python` must take the explicit pair, + # and a failing stated interpreter must not fall back to the shared one. + # `MCPP_NO_AUTO_INSTALL=1` proves the rule requested no payload: it reads + # `xim:python` only when the graph installed it. + - name: rules-python takes a stated SDK over the shared environment, without a payload request + working-directory: tests/all-rules-compile + run: | + set -e + env_dir="$RUNNER_TEMP/python-env/include" + stated_dir="$RUNNER_TEMP/python-stated/include" + mkdir -p "$env_dir" "$stated_dir" + : > "$env_dir/Python.h" + : > "$stated_dir/Python.h" + rm -rf target + MCPP_NO_AUTO_INSTALL=1 \ + MCPP_TEST_PYTHON_PRECEDENCE=1 \ + MCPP_TEST_PYTHON_INCLUDE_DIR="$stated_dir" \ + MCPP_PYTHON_INCLUDE_DIR="$env_dir" \ + MCPP_PYTHON_EXT_SUFFIX=.cpython-313-x86_64-linux-gnu.so \ + "$MCPP" build --configure-only + echo "ok: the stated pair won over the shared environment" + + # And a failing MCPP_PYTHON_EXECUTABLE is strict: it is refused, not + # replaced by xim:python, uv or PATH. + rm -rf target + MCPP_NO_AUTO_INSTALL=1 \ + MCPP_TEST_PYTHON_STRICT_ENV=1 \ + MCPP_PYTHON_EXECUTABLE=/definitely/not/a/python \ + "$MCPP" build --configure-only + echo "ok: a stated environment interpreter is strict" + + # THE NANOBIND BACKEND, AGAINST THE PUBLISHED INDEX. + # + # `mcpplibs.mwrap.nanobind` 3.1.0 is in mcpplibs/mcpp-index, so this + # fixture resolves it from the real index, like every other consumer. + # The interpreter is NOT the host's python3: Ubuntu 24.04 ships 3.12, + # and a `cpython-313` extension cannot be imported by it. The rule + # records the interpreter it built against as `python.executable`, so + # that fact is the first answer, and the other paths are fallbacks for a + # cold or partial build-program cache. + - name: rules-python (nanobind explicit_list) builds and imports a native extension + working-directory: tests/python-nanobind-consumer + run: | + set -e + "$MCPP" build + bash "$GITHUB_WORKSPACE/.github/scripts/verify-python-extension.sh" tests/python-nanobind-consumer + + - name: rules-python (nanobind reflect) binds the exported namespace on GCC 16 + working-directory: tests/python-reflect-consumer + run: | + set -e + "$MCPP" build + bash "$GITHUB_WORKSPACE/.github/scripts/verify-python-extension.sh" tests/python-reflect-consumer + # NO BUILD PROGRAM AT ALL, WHICH IS WHAT THE TWO KEYS BUY. # # `spirv-consumer` and `spirv-module-consumer` both write a `build.mcpp`, @@ -1004,24 +1137,38 @@ jobs: # EVERY RULE PASSES A DEPFILE, AND THE DENOMINATOR IS THE RULE COUNT. # # The step above proves the channel works for the one lane CI can run. - # The other four compile for accelerators no runner has, so what can be + # The other rules compile for accelerators no runner has, so what can be # asserted about them is that each one declares the field -- read from the - # code rather than from a list written here, so a seventh rule is counted - # the day it is added and not the day someone remembers this step. - - name: every rule declares a depfile + # code rather than from a list written here, so a new rule is counted the + # day it is added and not the day someone remembers this step. + # + # `rules-python` is the exception: it drives no compiler of its own. Its + # generated translation unit is compiled by the engine, whose compile edge + # already carries the scanner's depfile, and its only action is the + # artifact copy after the link. A rule that adds a compiler action must + # still declare `depfile`; this member claims no source extension and + # therefore has none to declare. + - name: every rule that compiles a translation unit declares a depfile run: | set -u cd "$GITHUB_WORKSPACE" - rules=$(ls rules/*.cppm | wc -l) - withdep=$(grep -l 'depfile' rules/*.cppm | wc -l) + rules=0 + withdep=0 + missing=0 + for f in rules/*.cppm; do + # rules-python compiles no translation unit of its own: its only + # action is the artifact copy after the engine's link. + [ "${f##*/}" = "python.cppm" ] && continue + rules=$((rules + 1)) + if grep -q 'depfile' "$f"; then + withdep=$((withdep + 1)) + else + echo "FAIL: $f passes no depfile" + missing=1 + fi + done echo "rules with a depfile: $withdep of $rules" - if [ "$withdep" -ne "$rules" ]; then - echo "FAIL: these rules pass no depfile:" - for f in rules/*.cppm; do - grep -q 'depfile' "$f" || echo " $f" - done - exit 1 - fi + [ "$missing" -eq 0 ] || exit 1 # SLANG: A DIFFERENT LANGUAGE, THE SAME SURFACE. # @@ -2235,6 +2382,23 @@ jobs: "$MCPP" run | tee run.log grep -q '^all-rules-compile ok' run.log + # THE NATIVE EXTENSION ON THE TWO HOSTS THE LINUX JOB DOES NOT COVER. + # + # The fixture pins `xim:python` 3.13.12, so the extension is + # `fast_ops.cpython-313-*.so` on macOS and `fast_ops.cp313-*.pyd` on + # Windows. Both are located the same way; `stage` is the directory the + # engine placed the linked library in, which is also where the fixture's + # dependent library sits. The interpreter comes from the rule's + # `python.executable` fact first, because it is the one the extension was + # built against; the payload paths are the fallback, never the host's + # `python3` when that is a different minor version. + - name: rules-python (nanobind explicit_list) builds and imports a native extension on this host + working-directory: tests/python-nanobind-consumer + run: | + set -e + "$MCPP" build + bash "$GITHUB_WORKSPACE/.github/scripts/verify-python-extension.sh" tests/python-nanobind-consumer + - name: rules-spirv through a consumer working-directory: tests/spirv-consumer run: | @@ -2279,6 +2443,84 @@ jobs: fi echo "ok: the boundary is generated and namespaced on this host" + # THE PYTHON FFI, ON THE TWO HOSTS WHERE ITS PLATFORM BRANCHES RUN. + # + # The `consumers` job closes the Linux half with `nm -D` and + # `libmathlib.so` for `rules-python`'s ctypes backend. What only this + # matrix can answer is the rest of the generated wrapper: `__declspec(dllexport)` and the `.dll` candidate + # list, `os.add_dll_directory` and the handle it must keep alive, the + # 16-byte `_McppBytes` returned by value under the MSVC ABI, and macOS's + # `.dylib` spelling. The fixture is ordinary C++23 and needs no payload. + # + # `sys.path` is seeded from the argument rather than `PYTHONPATH`: Git + # Bash translates a POSIX `PYTHONPATH` entry before Python sees it, and + # the imported module's own directory is the only one that matters. The + # UTF-8 sample is written as escapes so a non-UTF-8 console locale + # cannot corrupt the source of this step. + - name: rules-python (ctypes) generates the glue, shared library and wrapper on this host + working-directory: tests/python-consumer + run: | + set -e + "$MCPP" build + d=$(sh "$GITHUB_WORKSPACE/tests/out-dir.sh")/python + test -f "$d/mathlib_pybridge.cpp" + test -f "$d/mathlib.py" + if [ "$RUNNER_OS" = "macOS" ]; then + lib=$(find target -name 'libmathlib.dylib' -type f | head -1) + elif [ "$RUNNER_OS" = "Windows" ]; then + lib=$(find target \( -name 'mathlib.dll' -o -name 'libmathlib.dll' \) -type f | head -1) + else + lib=$(find target -name 'libmathlib.so' -type f | head -1) + fi + test -n "$lib" || { echo "FAIL: no shared library"; exit 1; } + art_dir=$(dirname "$lib") + test -f "$art_dir/mathlib.py" + py=$(command -v python3 || command -v python) + "$py" - "$art_dir" <<'PY' + import inspect + import sys + sys.path.insert(0, sys.argv[1]) + import mathlib + + assert mathlib.add(17, 25) == 42 + assert mathlib.add.__doc__ == "Return the \"sum\"" + assert mathlib.mul_i64(10**12, 3) == 3 * 10**12 + assert abs(mathlib.hypotenuse(3.0, 4.0) - 5.0) < 1e-12 + assert mathlib.is_even(42) is True + assert mathlib.is_even(41) is False + assert mathlib.toggle(True) is False + assert mathlib.toggle(False) is True + + assert mathlib.greet("mcpp") == "Hello, mcpp!" + assert mathlib.greet("\u4e16\u754c\U0001f680") == "Hello, \u4e16\u754c\U0001f680!" + assert mathlib.greet("") == "Hello, !" + assert mathlib.join("a", "b") == "ab" + assert mathlib.join("a\x00b", "c") == "a\x00bc" + assert mathlib.noop() is None + # A C++ exception at the extern "C" boundary returns the zero sentinel. + assert mathlib.checked_div(10, 2) == 5 + assert mathlib.checked_div(1, 0) == 0 + + if sys.platform == "win32": + assert len(mathlib._DLL_DIR_HANDLES) >= 1 + + for i in range(1000): + assert mathlib.greet(f"user-{i}") == f"Hello, user-{i}!" + + sig = inspect.signature(mathlib.greet) + assert sig.parameters["name"].annotation in ("str", str) + assert sig.return_annotation in ("str", str) + print("python-consumer ok") + PY + + - name: the C++ consumer imports the same module unchanged on this host + working-directory: tests/python-consumer/cpp-app + run: | + set -e + "$MCPP" build + "$MCPP" run | tee run.log + grep -q '^cpp-app ok' run.log + # โ”€โ”€ dist, on the platform each plugin serves โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # # A PLAN-LEVEL ASSERTION IS NOT A MEASUREMENT. `plan_for()` returning diff --git a/README.md b/README.md index b824648..9a0cfda 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ runs comes from is in [docs/02](docs/02-tool-sources.md). | `dist-apk` | Packs the native closure into a signed APK or App Bundle, with Java, Kotlin and Maven libraries. | [docs](docs/32-dist-apk.md) |
-All 23 plugins โ€” feature, behaviour, doc; the modules and engine floors are in the documentation index +All 24 plugins โ€” feature, behaviour, doc; the modules and engine floors are in the documentation index | feature | what it does | doc | |---|---|---| @@ -73,6 +73,7 @@ runs comes from is in [docs/02](docs/02-tool-sources.md). | `rules-metal` | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [docs](docs/10-rules.md#rules-metal) | | `rules-qt` | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [docs](docs/11-rules-qt.md) | | `rules-qml` | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [docs](docs/12-rules-qml.md) | +| `rules-python` | Binds a C++23 module's surface to Python as a native CPython extension with nanobind, or as `extern "C"` glue and a `ctypes` wrapper with no Python build dependency. | [docs](docs/13-rules-python.md) | | `rules-slang` | Compiles Slang (`*.slang`) and embeds or places the result. | [docs](docs/10-rules.md#rules-slang) | | `rules-spirv` | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [docs](docs/10-rules.md#rules-spirv) | | `rules-swift` | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [docs](docs/10-rules.md#rules-swift) | diff --git a/README.zh-CN.md b/README.zh-CN.md index ddec89f..cfb45a2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -60,7 +60,7 @@ int main() { | `dist-apk` | ๆŠŠๅŽŸ็”Ÿ้—ญๅŒ…ๆ‰“ๆˆๅทฒ็ญพๅ็š„ APK ๆˆ– App Bundle,ๅธฆ Javaใ€Kotlin ไธŽ Maven ๅบ“ใ€‚ | [docs](docs/32-dist-apk.md) |
-ๅ…จ้ƒจ 23 ไธชๆ’ไปถๆˆๅ‘˜โ€”โ€”featureใ€่กŒไธบใ€ๆ–‡ๆกฃ;ๆจกๅ—ไธŽๅผ•ๆ“Žไธ‹้™่งๆ–‡ๆกฃ็ดขๅผ• +ๅ…จ้ƒจ 24 ไธชๆ’ไปถๆˆๅ‘˜โ€”โ€”featureใ€่กŒไธบใ€ๆ–‡ๆกฃ;ๆจกๅ—ไธŽๅผ•ๆ“Žไธ‹้™่งๆ–‡ๆกฃ็ดขๅผ• | feature | ่กŒไธบ | ๆ–‡ๆกฃ | |---|---|---| @@ -70,6 +70,7 @@ int main() { | `rules-metal` | ็”จๅฎฟไธป็š„ Xcode ๆŠŠ `.metal` ็€่‰ฒๅ™จ็ผ–ๆˆ Metal ๅบ“,ๅนถ้ƒจ็ฝฒๅœจ็จ‹ๅบๆ—ใ€‚ | [docs](docs/10-rules.md#rules-metal) | | `rules-qt` | ไปฅ action ่ฟ่กŒ `moc`ใ€`uic`ใ€`rcc` ไธŽ Qt ็š„็ฟป่ฏ‘ๅทฅๅ…ท,้“พๆŽฅ Qt ๆจกๅ—ๅนถๆ”พ็ฝฎๅ…ถ่ฟ่กŒๆ—ถใ€‚ | [docs](docs/11-rules-qt.md) | | `rules-qml` | ๆž„ๅปบ QML ๅบ”็”จ:ๅ„ๆจกๅ—็š„ `moc`ใ€`qmltyperegistrar`ใ€`qmlcachegen`ใ€`rcc`ใ€`qsb` ้“พไธบ action,็จ‹ๅบๅฏผๅ…ฅ็š„ Qt QML ๆจกๅ—ๆ”พๅœจ็จ‹ๅบๆ—,ๅนถๅ†™ `qt.conf`ใ€‚้šๅซ `rules-qt`ใ€‚ | [docs](docs/12-rules-qml.md) | +| `rules-python` | ๆŠŠ C++23 ๆจกๅ—็š„่กจ้ข็ป‘ๅฎšๅˆฐ Python:็ป nanobind ไบงๅ‡บๅŽŸ็”Ÿ CPython ๆ‰ฉๅฑ•,ๆˆ–ไปฅ `extern "C"` ่ƒถๆฐดๅŠ  `ctypes` ๅŒ…่ฃ…,ๆž„ๅปบๆœŸๆ— ้œ€ Python ๅทฅๅ…ท้“พใ€‚ | [docs](docs/13-rules-python.md) | | `rules-slang` | ็ผ–่ฏ‘ Slang(`*.slang`),็ป“ๆžœๅฏๅ†…ๅตŒๆˆ–ๆ”พ็ฝฎใ€‚ | [docs](docs/10-rules.md#rules-slang) | | `rules-spirv` | ๆŠŠ GLSL ไธŽ HLSL ็€่‰ฒๅ™จ้˜ถๆฎต็ผ–่ฏ‘ไธบ SPIR-V,็ป“ๆžœๅฏๅ†…ๅตŒๆˆ–ๆ”พ็ฝฎใ€‚ | [docs](docs/10-rules.md#rules-spirv) | | `rules-swift` | ๆŠŠๅŒ…็š„ `.swift` ๆบ็ ็ผ–ๆˆไธ€ไธชๆจกๅ—,ไพ› C ไธŽ C++ ๆบ็ ่ฐƒ็”จใ€‚ | [docs](docs/10-rules.md#rules-swift) | diff --git a/docs/00-engine-and-rules.md b/docs/00-engine-and-rules.md index e2619c6..ab43389 100644 --- a/docs/00-engine-and-rules.md +++ b/docs/00-engine-and-rules.md @@ -97,6 +97,7 @@ Each rule therefore selects the extensions it claims and leaves the rest: | `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-python` | nothing: the module, the exports or the reflected namespace are stated in `build.mcpp` | | `rules-slang` | `.slang` | | `rules-swift` | `.swift` | | `rules-sycl` | `.sycl` | diff --git a/docs/10-rules.md b/docs/10-rules.md index 3d0120c..567e12b 100644 --- a/docs/10-rules.md +++ b/docs/10-rules.md @@ -1,6 +1,6 @@ # Device and language rules -The rules that compile one kind of translation unit with a compiler mcpp does not drive: GPU and accelerator languages (`rules-ascendc`, `rules-cuda`, `rules-hip`, `rules-sycl`), shader languages (`rules-spirv`, `rules-slang`, `rules-metal`) and Swift (`rules-swift`). Each section states the module, the engine floor, what the rule needs and how it compiles. The environment each rule brings and the extensions it claims are in [00-engine-and-rules.md](00-engine-and-rules.md). +The rules that compile one kind of translation unit with a compiler mcpp does not drive: GPU and accelerator languages (`rules-ascendc`, `rules-cuda`, `rules-hip`, `rules-sycl`), shader languages (`rules-spirv`, `rules-slang`, `rules-metal`), Swift (`rules-swift`) and Python bindings (`rules-python`). Each section states the module, the engine floor, what the rule needs and how it compiles. The environment each rule brings and the extensions it claims are in [00-engine-and-rules.md](00-engine-and-rules.md). ## `rules-ascendc` @@ -65,3 +65,9 @@ The older `sycl,cuda+{sm_89}` form still inherits CUDA targets when the SYCL plu The `tests/multi-accel-consumer` fixture selects `cuda+{sm_90},sycl+{nvptx64-sm_89}` and imports both rules. CI inspects each rule's actual image target and runs both host objects without submitting GPU work. This establishes build/link coexistence with one C++ runtime; device execution, interoperation and synchronization require their own runtime checks. + +## `rules-python` + +Module `mcpp.rules.python`; engine floor 2026.10.30.1; from 0.28.0. + +Binds a C++23 module's surface to Python from one declaration in `build.mcpp`: a native CPython extension over `mcpplibs.mwrap.nanobind`, or `extern "C"` glue and a `ctypes` wrapper with no Python build dependency. The rule claims no extension and names no `rule_module`; the project states the module and its exports in `build.mcpp`. See [rules-python](13-rules-python.md). diff --git a/docs/13-rules-python.md b/docs/13-rules-python.md new file mode 100644 index 0000000..2dcb3f8 --- /dev/null +++ b/docs/13-rules-python.md @@ -0,0 +1,283 @@ +# `rules-python` + +`mcpp.rules.python` binds a C++23 module's surface to Python from one declaration in `build.mcpp`. +The module itself is untouched: no Python header, no marker macro, no +visibility attribute, and no `#include` in the source a C++ consumer imports. +Module `mcpp.rules.python`; engine floor 2026.10.30.1; from 0.28.0. + +Two backends share the same declaration: + +- **`binding::nanobind`** builds a native CPython extension over + `mcpplibs.mwrap.nanobind`. The rule writes the one translation unit + `NB_MODULE` lives in, adds the Python SDK's include directory, and copies the + linked shared library to `` in a staging directory. +- **`binding::ctypes`** builds the zero-Python-build-dependency path: an + `extern "C"` glue translation unit plus a `ctypes` wrapper with type hints. + No `Python.h`, no `uv` and no nanobind are needed at build time. + +## Use + +The module is an ordinary C++23 module: + +```cpp +export module fast_ops; +import std; + +export namespace fast_ops { +inline int add(int a, int b) { return a + b; } +inline std::string greet(std::string_view name) { + return "Hello, " + std::string(name) + "!"; +} +} +``` + +### Native extension (`binding::nanobind`) + +```toml +[dependencies] +mcpplibs.mwrap.nanobind = "3.1.0" + +[build-dependencies.mcpp] +plugins = { version = "0.28.0", features = ["rules-python"] } + +# The SDK the project builds against. `rules-python` reads the payload and never +# requests one; a nanobind-m release with the `python-sdk` feature supplies the +# same default. +[xlings.workspace] +"xim:python" = "3.13.12" + +[build] +sources = ["src/*.cppm"] + +[targets.fast_ops] +kind = "shared" +``` + +```cpp +// build.mcpp +import std; +import mcpp; +import mcpp.rules.python; + +namespace py = mcpp::rules::python; + +int main() { + py::options opt; + opt.mode = py::binding::nanobind; + opt.surface = py::discovery::explicit_list; + opt.module_name = "fast_ops"; + opt.cpp_module = "fast_ops"; + opt.cpp_namespace = "fast_ops"; + opt.exports = { + { "add", "", "Add two integers.", { "a", "b" } }, + { "greet", "", "Greet a name (UTF-8).", { "name" } }, + }; + return py::emit(opt).ok ? 0 : 1; +} +``` + +`emit` adds the generated entry to the build graph, adds the Python SDK's +include directory, emits the link rules for the host, and submits an +`role = "artifact"` action that copies the linked file to +`/` with the engine's own +`${mcpp.self} stage --output`. No Python interpreter, shell or extra build +tool is involved, so headers-only cross compilation needs no host Python. + +### Reflected surface (`discovery::reflect`, GCC 16) + +```cpp +py::options opt; +opt.mode = py::binding::nanobind; +opt.surface = py::discovery::reflect; // no export list +opt.module_name = "fast_ops"; +opt.cpp_module = "fast_ops"; +return py::emit(opt).ok ? 0 : 1; +``` + +The generated entry walks `std::meta::members_of(^^, ...)` and +binds every exported free function. `cpp_namespace` defaults to the final +segment of `cpp_module`. This path emits `-std=c++26 -freflection` and requires +GCC 16 or newer; another compiler, including GCC 15, is refused with a warning. +The surface is explicit: this M1 slice does not probe a compiler for reflection +support automatically. + +### ctypes backend + +```toml +[build-dependencies.mcpp] +plugins = { version = "0.28.0", features = ["rules-python"] } + +[targets.mathlib] +kind = "shared" +``` + +```cpp +py::options opt; +opt.mode = py::binding::ctypes; +opt.python_env = py::env::none; +opt.module_name = "mathlib"; +opt.cpp_module = "mathlib"; +opt.cpp_namespace = "mathlib"; +opt.functions = { + { "add", "", { { "a", py::type_kind::i32 }, { "b", py::type_kind::i32 } }, + py::type_kind::i32, "Return the sum." }, +}; +return py::emit(opt).ok ? 0 : 1; +``` + +The generated `.py` loads the project's own shared library beside itself, so +the C++ consumer in the same project links exactly the artifact Python loads. +It searches the wrapper's own directory and every directory between it and the +artifact, so `deploy_to = "pkg/sub"` still finds `lib.so` / +`.dll` at the artifact root. + +## Options + +| field | default | meaning | +|---|---|---| +| `module_name` | required | Python module name; also the generated file's stem | +| `cpp_module` | required for ctypes, explicit_list and reflect | the C++23 module the entry imports | +| `cpp_namespace` | final segment of `cpp_module` for reflect; empty otherwise | namespace exports are resolved in | +| `target_name` | `module_name` | shared-library target for `${mcpp.target_file:}` | +| `library_name` | `module_name` | ctypes library base name | +| `symbol_prefix` | `mcpp_py__` | ctypes C symbol prefix | +| `out_dir` | `mcpp::out_dir() + "/python"` | generated source and wrapper directory | +| `stage_dir` | `out_dir + "/pkg"` | native extension and `.pyi` staging directory | +| `deploy_to` | `"."` | placement relative to the artifact | +| `mode` | `binding::nanobind` | `nanobind` or `ctypes` | +| `python_env` | `env::auto_` | `auto_`, `uv`, `xim`, `host`, `none` | +| `surface` | `discovery::auto_` | `auto_`, `explicit_list`, `reflect`, `manual` | +| `python` | empty | explicit interpreter (`tool::choice`); a failed choice is not replaced by another source | +| `uv` | empty | explicit uv program (`tool::choice`) | +| `python_include_dir` | empty | override `` directory | +| `python_library_dir` | empty | override the Windows `libs/` directory | +| `python_library` | empty | override the Windows import library | +| `ext_suffix` | empty | override the interpreter's `EXT_SUFFIX` | +| `manual_entry` | empty | project-written NB_MODULE translation unit | +| `functions` | empty | ctypes declarations | +| `exports` | empty | nanobind explicit export declarations | +| `import_stl` | `true` | import `mcpplibs.mwrap.nanobind.stl` in the entry | +| `emit_stub` | `true` | write `.pyi` for explicit exports | +| `register_with_build` | `true` | false writes files and leaves the graph alone | + +`export_decl` is `{ name, cpp_expr, doc, arg_names }`. An empty `cpp_expr` +means `cpp_namespace::name`, or `name` when there is no namespace. +`function_decl` is `{ name, cpp_expr, params, ret, doc }`. `discovery::manual` +compiles `manual_entry` directly and generates no entry file of its own. + +## Python SDK discovery + +`binding::nanobind` takes the SDK from the first level that answers, in this +order. A level that answers is final; the levels below it are not consulted. +(`binding::ctypes` needs none of this and states `env::none`.) + +1. **Explicit `build.mcpp` options โ€” strict, never replaced.** + - `python_include_dir` **and** `ext_suffix` together are headers-only cross + compilation: no interpreter runs, and `python_library_dir` / + `python_library` are applied as stated (with their environment fallbacks + only when the option is empty). + - Otherwise `options::python` โ€” a program path, `tool::program(...)` or + `tool::root(...)` โ€” is resolved once through the tool model and probed. A + choice that fails, or is not a Python SDK, refuses with a warning; it is + **never** replaced by a lower level. +2. **Shared environment and virtual environment** (`python_env != env::none`): + - `MCPP_PYTHON_INCLUDE_DIR` + `MCPP_PYTHON_EXT_SUFFIX`: the headers-only + pair; no interpreter runs. + - `MCPP_PYTHON_EXECUTABLE`: strict and probed once. If it is set and is not + a Python SDK, the build is refused rather than falling through to + `xim:python`, `uv` or `PATH`. + - `VIRTUAL_ENV`: its `bin/python3`, `bin/python`, + `Scripts/python.exe` or `python.exe` is probed before the graph's payload. +3. **Graph `xim:python`** (`env::auto_` or `env::xim`): the payload the project + declared โ€” `[xlings.workspace] "xim:python" = "3.13.12"`, as above โ€” or the + one a build-dependency's `python-sdk` feature declares. + `rules-python` reads `mcpp::xpkg_dir("xim", "python")`; it never requests the + payload, so a build that names its own SDK downloads nothing for this rule. +4. **`uv` and the host `PATH`** (`env::auto_`, `env::uv`, `env::host`): + `uv python find` through `options::uv` -> `MCPP_UV` -> `PATH`, then + `python3`/`python` on `PATH`. + +Partial environment overrides (`MCPP_PYTHON_INCLUDE_DIR`, +`MCPP_PYTHON_LIBRARY_DIR`, `MCPP_PYTHON_LIBRARY`, `MCPP_PYTHON_EXT_SUFFIX`) are +applied after a probe, so an interpreter's `sysconfig` can never overwrite a +stated value. + +### One SDK for the whole extension + +`mcpplibs.mwrap.nanobind` compiles `nb_runtime.cpp` in its own build program, +where the extension's `build.mcpp` options do not reach. Its `python-sdk` +feature (`default = ["runtime", "python-sdk"]`; 3.1.0 states the same version +under `[xlings.workspace]`) provisions `xim:python` 3.13.12, so the extension +and the runtime share one SDK when the extension also takes `xim:python` +(level 3) or the shared environment (level 2). Declaring the payload in the +consumer's own `[xlings.workspace]` is also what makes it visible to the +extension's build program. When `rules-python` selects a consumer-local SDK +(level 1, `uv` or the host) while the graph also installed `xim:python`, it +prints an actionable `mcpp::warning`: the two halves would be built against +different headers. To choose your own SDK, share it with the dependency: + +- set `MCPP_PYTHON_EXECUTABLE`, `VIRTUAL_ENV` or `MCPP_PYTHON_INCLUDE_DIR` โ€” + the environment both build programs read โ€” or +- declare `[xlings.workspace] "xim:python" = "3.13.12"` in the consumer, or +- disable the dependency's default SDK: + + ```toml + [dependencies] + mcpplibs.mwrap.nanobind = { version = "3.1.0", default-features = false, features = ["runtime"] } + ``` + +The interpreter that answers is asked once for `sysconfig.get_path('include')`, +`sysconfig.get_path('platinclude')`, `EXT_SUFFIX`, `LIBDIR`, the Python library +name and its major/minor version. The answers are recorded as +`python.executable`, `python.include` and `python.ext_suffix` facts. Debian and +Ubuntu keep `Python.h` and its architecture-specific companions in different +directories; when `platinclude` differs from `include`, the rule adds both. + +On Linux and macOS the extension does not link `libpython`: a CPython +extension resolves the interpreter's symbols from the process that loaded it. +macOS adds `-undefined dynamic_lookup`. Windows links the exact versioned +import library (`python313`, never `python3.lib` or `python313_d.lib`) and +refuses a static CRT, which cannot be mixed with the interpreter's dynamic CRT. +That refusal is checked before anything is written or registered, so a refused +build leaves no side effect. + +## Limits + +- `include_dir`, `cxxflag` and the `link_*` directives are package-wide in the + engine today. A `binding::nanobind` (or `discovery::reflect`) package is + therefore assumed to own a single shared-library extension target; the + artifact copy also leaves the original linked shared library in `target/`. +- `reflect` is a GCC 16 or newer path and is explicit: this M1 slice does not + probe a compiler for reflection support automatically. Clang and MSVC users + state `explicit_list` or `manual`. +- An overloaded C++ function needs an explicit `cpp_expr` (for example a cast) + in `explicit_list`; reflection binds each non-overloaded exported function. +- The `ctypes` backend carries only the value types in `type_kind`. Classes, + keyword arguments and zero-copy buffers belong to the nanobind backend. +- The `ctypes` bridge catches C++ exceptions at the `extern "C"` boundary and + returns the zero/empty sentinel (`0`, `false` or `""`). A caller that needs + rich Python exception translation uses `binding::nanobind`. +- `register_with_build = false` writes the entry, the stub and the wrapper and + changes nothing else: no `cxxflag`, no `rerun_if_env_changed`, no link input, + no artifact action and no deployment. A headers-only `emit` with that setting + runs no interpreter and leaves `python_executable` empty. +- A reflected export list is discovered from the exported namespace only; + unexported helpers are not bound. + +## Criteria + +- `tests/all-rules-compile` compiles the package and calls every pure renderer + and both answers of `validate` on GCC and LLVM. It also asserts the + `_mcpp_res` bridge local, the `deploy_to` parent search, an overloaded + `cpp_expr` without a doubled `&`, the `.pyi` content, and a headers-only + `emit` with `register_with_build = false` (no interpreter run). +- `tests/python-consumer` builds the `ctypes` backend with `env::none`, runs + the unchanged C++ consumer, imports the generated wrapper from a real + Python process, and asserts the exception sentinel. +- `tests/python-nanobind-consumer` builds a native `.cpython-*.so` and `.pyi` + from an explicit export list and asserts the bound surface. +- `tests/python-reflect-consumer` builds the same surface with no export list + on GCC 16 and asserts the reflected bindings. +- A CI step runs `tests/all-rules-compile` with `MCPP_NO_AUTO_INSTALL=1` and a + fake headers pair, asserting that an explicit interpreter is not replaced by + the shared environment. diff --git a/docs/README.md b/docs/README.md index 3c3fbd6..38da96c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -33,6 +33,7 @@ requires CMake 3.19 or later. | `rules-metal` | `mcpp.rules.metal` | 2026.9.8.1 | Compiles `.metal` shaders into Metal libraries with the host's Xcode and deploys them beside the program. | [rules](10-rules.md#rules-metal) | | `rules-qt` | `mcpp.rules.qt` | 2026.10.1.3 | Runs `moc`, `uic`, `rcc` and Qt's Linguist tools as actions, links the Qt modules and places their runtime. | [rules-qt](11-rules-qt.md) | | `rules-qml` | `mcpp.rules.qml` | 2026.10.1.3; a pack that carries the QML plugins' libraries 2026.11.23.1 | Builds a QML application: each module's `moc`, `qmltyperegistrar`, `qmlcachegen`, `rcc` and `qsb` chain as actions, Qt's QML modules the program imports placed beside it, and a `qt.conf`. Implies `rules-qt`. | [rules-qml](12-rules-qml.md) | +| `rules-python` | `mcpp.rules.python` | 2026.10.30.1 | Binds a C++23 module's surface to Python as a native CPython extension with nanobind, or as `extern "C"` glue and a `ctypes` wrapper with no Python build dependency. | [rules-python](13-rules-python.md) | | `rules-slang` | `mcpp.rules.slang` | 2026.10.1.3 | Compiles Slang (`*.slang`) and embeds or places the result. | [rules](10-rules.md#rules-slang) | | `rules-spirv` | `mcpp.rules.spirv` | 2026.10.1.3 | Compiles GLSL and HLSL shader stages to SPIR-V and embeds or places the result. | [rules](10-rules.md#rules-spirv) | | `rules-swift` | `mcpp.rules.swift` | 2026.9.8.1 | Compiles a package's `.swift` sources into one module the C and C++ sources call. | [rules](10-rules.md#rules-swift) | @@ -88,6 +89,7 @@ The first digit is the part, so a number says where a page belongs: - [10 โ€” Device and Language Rules](10-rules.md) โ€” `rules-ascendc`, `rules-cuda`, `rules-hip`, `rules-metal`, `rules-slang`, `rules-spirv`, `rules-swift`, `rules-sycl` - [11 โ€” `rules-qt`](11-rules-qt.md) โ€” Qt's code generators, modules and runtime; Linguist tools - [12 โ€” `rules-qml`](12-rules-qml.md) โ€” a QML application on `rules-qt` +- [13 โ€” `rules-python`](13-rules-python.md) โ€” a C++23 module's surface reached from Python ### 2x โ€” Tools diff --git a/mcpp.toml b/mcpp.toml index 6e8f80d..ba1173b 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] name = "plugins" namespace = "mcpp" -version = "0.27.0" +version = "0.28.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 @@ -204,6 +204,23 @@ device_extensions = [".comp", ".vert", ".frag", ".geom", ".tesc", ".tese", sources = ["rules/qml.cppm"] implies = ["rules-qt", "plugins-core"] +# `mcpp.rules.python` -- a C++23 module's surface reached from Python. It is a +# family member in the shape of `rules-qml`: it claims no file extension and +# names no `rule_module`, because what it builds is stated by a consumer's +# `build.mcpp` (the module, the exports or the reflected namespace) rather than +# by an extension in `[build] sources`. +# +# binding::nanobind a native CPython extension over mcpplibs.mwrap.nanobind +# binding::ctypes the zero-Python-build-dependency extern "C" + ctypes +# +# It declares no payload: the Python SDK belongs to the graph, through +# `mcpplibs.mwrap.nanobind`'s SDK feature or the consumer's own +# `[xlings.workspace]`. This rule reads `mcpp::xpkg_dir("xim", "python")` and +# never asks the engine to install it. +[features.rules-python] +sources = ["rules/python.cppm"] +implies = ["plugins-core"] + [features.rules-sycl] sources = ["rules/sycl.cppm"] implies = ["plugins-core"] diff --git a/rules/python.cppm b/rules/python.cppm new file mode 100644 index 0000000..5aba993 --- /dev/null +++ b/rules/python.cppm @@ -0,0 +1,1537 @@ +// mcpp.rules.python -- a C++23 module's surface, reached from Python. +// +// TWO BACKENDS, ONE DECLARATION. +// +// binding::nanobind A native CPython extension. The rule writes the one +// translation unit NB_MODULE lives in, adds the Python +// SDK's include directory, and places the linked shared +// library under the interpreter's EXT_SUFFIX through an +// artifact action. The binding library itself is +// mcpplibs.mwrap.nanobind, a dependency the project +// declares. +// +// binding::ctypes The zero-Python-build-dependency backend. The rule +// writes an `extern "C"` glue TU and a `ctypes` wrapper +// with type hints; no Python headers, no `uv`, no +// nanobind. The shared library the project already builds +// is loaded by the generated `.py`. +// +// THE SOURCE MODULE IS UNTOUCHED in both cases. It is an ordinary C++23 module +// with `export module`, `import std;` and exported declarations; it carries no +// marker macro, no include, no visibility attribute. Discovery is a statement +// in `build.mcpp`, not an edit to the module. +// +// THE GENERATED ENTRY NEVER CARRIES REFLECTION SYNTAX INTO THIS FILE. Every +// `^^`, `members_of` and `template for` below is a string literal that becomes +// `py_entry.cpp`; this module is plain C++23, so the editor lane (clangd with +// libstdc++'s `std` module) compiles it like every other rule. +// +// WHAT THE RULE DOES NOT DO: it does not choose the Python interpreter for a +// project, does not link libpython into a Linux/macOS extension (CPython owns +// that symbol table), and does not put anything Python-specific into the user's +// module. It asks the options, the shared environment, the graph and finally +// uv or the host in one stated order (see `emit`), records the answer with +// `mcpp::fact`, and refuses by name when it cannot. It never requests +// `xim:python`: the graph owns that payload, through +// `mcpplibs.mwrap.nanobind`'s SDK feature or the consumer's own +// `[xlings.workspace]`. +export module mcpp.rules.python; + +import std; +import mcpp; +import mcpp.plugins; +import mcpp.plugins.fs; +import mcpp.plugins.tool; + +export namespace mcpp::rules::python { + +// The two Python bridging mechanisms this rule implements. +enum class binding { + nanobind, // native CPython extension over mcpplibs.mwrap.nanobind + ctypes, // zero-Python-build-dependency extern "C" + ctypes +}; + +// Where a Python SDK comes from for the nanobind backend. The order in `emit` +// is: explicit `options`, the shared environment, the graph's `xim:python`, +// then uv and the host. +enum class env { + auto_, // ctypes -> none; nanobind -> shared env, xim:python, uv, host + uv, // `uv python find` + xim, // the `xim:python` payload the graph declared + host, // a host interpreter on PATH + none, // do not look for a Python SDK +}; + +// How the bound surface is stated. +enum class discovery { + auto_, // exports -> explicit_list; manual_entry -> manual + explicit_list, // nanobind: `exports`; ctypes: `functions` + reflect, // P2996 reflection over the exported namespace (GCC 16) + manual, // the project writes the NB_MODULE TU itself +}; + +// The value types the ctypes backend crosses the boundary with. +enum class type_kind { + void_, // return value only + i32, // std::int32_t <-> ctypes.c_int32 <-> int + i64, // std::int64_t <-> ctypes.c_int64 <-> int + f64, // double <-> ctypes.c_double <-> float + bool_, // bool <-> ctypes.c_uint8 <-> bool + string, // std::string <-> UTF-8 ptr+len <-> str +}; + +struct param { + std::string name; + type_kind type = type_kind::i32; +}; + +struct function_decl { + std::string name; + std::string cpp_expr; + std::vector params; + type_kind ret = type_kind::void_; + std::string doc; +}; + +// A nanobind export. The argument types are deduced by the C++ template, so +// only the Python name and optional argument names are stated here. +struct export_decl { + std::string name; + std::string cpp_expr; // empty: cpp_namespace::name, or name + std::string doc; + std::vector arg_names; // nb::arg("...") in order +}; + +struct options { + // Required: the Python module name. It is also the generated file's stem. + std::string module_name; + // Required for ctypes and for nanobind's explicit_list/reflect: the C++23 + // module the generated translation unit imports. + std::string cpp_module; + // Optional: the namespace the exports are resolved in. For reflect it is + // the namespace passed to `^^`; empty derives it from cpp_module's last + // segment. + std::string cpp_namespace; + // Optional: the shared-library target whose linked file is copied to + // `/`. Empty is module_name. + std::string target_name; + // Optional: the base name the ctypes wrapper loads. Empty is module_name. + std::string library_name; + // Optional: the C symbol prefix used by ctypes. Empty is + // `mcpp_py__`. + std::string symbol_prefix; + // Optional: where generated sources and wrappers are written. Empty is + // `mcpp::out_dir() + "/python"`. + std::string out_dir; + // Optional: where the native extension and its `.pyi` are staged. Empty is + // `out_dir + "/pkg"`. + std::string stage_dir; + // Optional: where the deployable files are placed beside the artifact. + std::string deploy_to = "."; + binding mode = binding::nanobind; + env python_env = env::auto_; + discovery surface = discovery::auto_; + // Optional explicit interpreter and uv program. + mcpp::plugins::tool::choice python; + mcpp::plugins::tool::choice uv; + // Optional overrides, for cross compilation or a non-standard SDK. + std::string python_include_dir; + std::string python_library_dir; + std::string python_library; + std::string ext_suffix; + // Required for discovery::manual: the project's own NB_MODULE TU. + std::string manual_entry; + // ctypes declarations. + std::vector functions; + // nanobind explicit_list declarations. + std::vector exports; + // Whether the generated nanobind entry imports the STL casters. + bool import_stl = true; + // Whether explicit_list writes a `.pyi` beside the extension. + bool emit_stub = true; + // False writes the files but leaves the build graph alone. + bool register_with_build = true; +}; + +struct emitted { + std::string entry_cpp; // ctypes bridge or nanobind py_entry.cpp + std::string python_file; // ctypes .py or nanobind .pyi + std::string extension_file; // nanobind / + std::string ext_suffix; + std::string python_executable; + std::string python_include_dir; + std::string symbol_prefix; + bool ok = false; +}; + +// โ”€โ”€โ”€ pure helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +namespace detail { + +inline bool is_c_identifier(std::string_view s) { + if (s.empty()) return false; + const char c0 = s[0]; + if (!(std::isalpha(static_cast(c0)) || c0 == '_')) return false; + for (std::size_t i = 1; i < s.size(); ++i) { + const char c = s[i]; + if (!(std::isalnum(static_cast(c)) || c == '_')) return false; + } + return true; +} + +inline bool is_python_keyword(std::string_view w) { + static constexpr std::string_view kWords[] = { + "False", "None", "True", "and", "as", "assert", "async", "await", + "break", "class", "continue", "def", "del", "elif", "else", "except", + "finally", "for", "from", "global", "if", "import", "in", "is", + "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", + "while", "with", "yield", + }; + for (auto k : kWords) if (k == w) return true; + return false; +} + +inline std::vector split_double_colon(std::string_view s) { + std::vector out; + std::size_t i = 0; + while (i <= s.size()) { + const auto p = s.find("::", i); + const auto part = p == std::string_view::npos ? s.substr(i) : s.substr(i, p - i); + if (!part.empty()) out.emplace_back(part); + if (p == std::string_view::npos) break; + i = p + 2; + } + return out; +} + +inline std::string default_symbol_prefix(const std::string& module_name) { + return "mcpp_py_" + mcpp::plugins::names::identifier(module_name, "module") + "_"; +} + +inline std::string resolved_prefix(const options& opt) { + return opt.symbol_prefix.empty() ? default_symbol_prefix(opt.module_name) + : opt.symbol_prefix; +} + +inline std::string resolved_library(const options& opt) { + return opt.library_name.empty() ? opt.module_name : opt.library_name; +} + +inline std::string resolved_target(const options& opt) { + return opt.target_name.empty() ? opt.module_name : opt.target_name; +} + +inline std::string resolved_cpp_expr(const options& opt, const function_decl& fn) { + if (!fn.cpp_expr.empty()) return fn.cpp_expr; + if (opt.cpp_namespace.empty()) return fn.name; + return opt.cpp_namespace + "::" + fn.name; +} + +inline std::string resolved_export_expr(const options& opt, const export_decl& ex) { + if (!ex.cpp_expr.empty()) return ex.cpp_expr; + if (opt.cpp_namespace.empty()) return ex.name; + return opt.cpp_namespace + "::" + ex.name; +} + +// The namespace `^^` names in reflect mode: options::cpp_namespace, otherwise +// the last segment of the C++ module. +inline std::string resolved_namespace(const options& opt) { + if (!opt.cpp_namespace.empty()) return opt.cpp_namespace; + const auto segs = mcpp::plugins::names::split_module_name(opt.cpp_module); + return segs.empty() ? std::string() : segs.back(); +} + +inline discovery resolved_surface(const options& opt) { + if (opt.surface != discovery::auto_) return opt.surface; + if (opt.mode == binding::ctypes) + return opt.functions.empty() ? discovery::auto_ : discovery::explicit_list; + if (!opt.exports.empty()) return discovery::explicit_list; + if (!opt.manual_entry.empty()) return discovery::manual; + return discovery::auto_; +} + +inline std::string_view c_type_name(type_kind t) { + switch (t) { + case type_kind::i32: return "std::int32_t"; + case type_kind::i64: return "std::int64_t"; + case type_kind::f64: return "double"; + case type_kind::bool_: return "std::uint8_t"; + case type_kind::string: return "mcpp_py_bytes"; + case type_kind::void_: break; + } + return "void"; +} + +inline std::string_view python_hint(type_kind t) { + switch (t) { + case type_kind::void_: return "None"; + case type_kind::i32: return "int"; + case type_kind::i64: return "int"; + case type_kind::f64: return "float"; + case type_kind::bool_: return "bool"; + case type_kind::string: return "str"; + } + return "None"; +} + +inline std::string_view python_restype(type_kind t) { + switch (t) { + case type_kind::void_: return "None"; + case type_kind::i32: return "_mcpp_ctypes.c_int32"; + case type_kind::i64: return "_mcpp_ctypes.c_int64"; + case type_kind::f64: return "_mcpp_ctypes.c_double"; + case type_kind::bool_: return "_mcpp_ctypes.c_uint8"; + case type_kind::string: return "_McppBytes"; + } + return "None"; +} + +inline std::string_view python_cast(type_kind t) { + switch (t) { + case type_kind::i32: return "static_cast"; + case type_kind::i64: return "static_cast"; + case type_kind::f64: return "static_cast"; + case type_kind::bool_: return "static_cast"; + case type_kind::string: + case type_kind::void_: break; + } + return ""; +} + +inline std::string escaped_python_doc(std::string_view doc) { + std::string s; + for (std::size_t i = 0; i < doc.size(); ++i) { + const char c = doc[i]; + if (c == '\\') { s += "\\\\"; continue; } + if (c == '"') { s += "\\\""; continue; } + s += c; + } + return s; +} + +// A C++ string literal with the two characters that can end it escaped. +inline std::string escaped_cpp_string(std::string_view text) { + std::string s; + for (std::size_t i = 0; i < text.size(); ++i) { + const char c = text[i]; + if (c == '\\' || c == '"') { s += '\\'; s += c; continue; } + if (c == '\n') { s += "\\n"; continue; } + if (c == '\r') { s += "\\r"; continue; } + s += c; + } + return s; +} + +inline bool has_path_escape(std::string_view value) { + for (std::size_t i = 0; i < value.size(); ++i) + if (value[i] == '\0' || value[i] == '\n' || value[i] == '\r') return true; + return false; +} + +// NOT INLINE, for the reason docs/01-plugin-development.md ยง4 gives: `emit` is +// inline and instantiated in a consumer's build program, and a path comparison +// that walks `std::filesystem` in that instantiation hits GCC 16's +// "function body not available" for the standard library's own iterators. The +// body is compiled once, in this unit, and the importer sees the declaration. +bool path_below(const std::string& value, const std::string& root); + +// The sources a consumer states for this one build. A mismatch between one of +// these and the graph's `xim:python` is the cross-package warning `emit` +// prints; the shared environment and a virtual environment are deliberately +// not local, because they are what the recommendation asks the user to use. +inline bool sdk_is_consumer_local(std::string_view source) { + return source == "options" || source == "options::python" + || source == "uv" || source == "host"; +} + +} // namespace detail + +// โ”€โ”€โ”€ validate โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +inline std::expected validate(const options& opt) { + if (opt.module_name.empty()) + return std::unexpected("options::module_name is empty; it names the generated Python file"); + if (mcpp::plugins::names::identifier(opt.module_name, "module") != opt.module_name) + return std::unexpected(std::format( + "options::module_name `{}` is not a Python identifier " + "(letters, digits and `_`, not starting with a digit)", + opt.module_name)); + if (detail::is_python_keyword(opt.module_name)) + return std::unexpected(std::format("options::module_name `{}` is a Python keyword", + opt.module_name)); + + const auto surface = detail::resolved_surface(opt); + const bool needs_module = opt.mode == binding::ctypes + || surface == discovery::explicit_list + || surface == discovery::reflect; + if (needs_module && opt.cpp_module.empty()) + return std::unexpected("options::cpp_module is empty; it is the C++23 module the generated entry imports"); + if (!opt.cpp_module.empty()) { + const auto segs = mcpp::plugins::names::split_module_name(opt.cpp_module); + if (segs.empty()) + return std::unexpected(std::format("options::cpp_module `{}` is empty", opt.cpp_module)); + for (std::size_t i = 0; i < segs.size(); ++i) { + if (mcpp::plugins::names::identifier(segs[i], "x") != segs[i]) + return std::unexpected(std::format( + "options::cpp_module `{}` has the segment `{}`, which is not a C++ identifier", + opt.cpp_module, segs[i])); + } + } + + if (!opt.cpp_namespace.empty()) { + const auto segs = detail::split_double_colon(opt.cpp_namespace); + if (segs.empty()) + return std::unexpected(std::format("options::cpp_namespace `{}` has no namespace segment", + opt.cpp_namespace)); + for (std::size_t i = 0; i < segs.size(); ++i) { + if (mcpp::plugins::names::identifier(segs[i], "x") != segs[i]) + return std::unexpected(std::format( + "options::cpp_namespace `{}` has the segment `{}`, which is not a C++ " + "identifier (separate namespaces with `::`)", + opt.cpp_namespace, segs[i])); + } + } + + const auto target = detail::resolved_target(opt); + if (target.empty()) + return std::unexpected("options::target_name is empty; it names the linked shared-library target"); + if (detail::has_path_escape(target)) + return std::unexpected(std::format("options::target_name `{}` contains a control character", target)); + + if (!opt.ext_suffix.empty()) { + if (opt.ext_suffix[0] != '.') + return std::unexpected(std::format( + "options::ext_suffix `{}` must begin with `.` (for example `.cpython-313-x86_64-linux-gnu.so`)", + opt.ext_suffix)); + if (opt.ext_suffix.find('/') != std::string::npos + || opt.ext_suffix.find('\\') != std::string::npos) + return std::unexpected(std::format( + "options::ext_suffix `{}` contains a path separator; it is a suffix, not a path", + opt.ext_suffix)); + } + + if (!opt.deploy_to.empty()) { + if (opt.deploy_to[0] == '/' || opt.deploy_to[0] == '\\') + return std::unexpected(std::format( + "options::deploy_to `{}` is absolute; it is relative to the artifact's directory", + opt.deploy_to)); + const auto segs = mcpp::plugins::names::components(opt.deploy_to); + for (std::size_t i = 0; i < segs.size(); ++i) + if (segs[i] == "..") + return std::unexpected(std::format( + "options::deploy_to `{}` walks out of the artifact's directory with `..`", + opt.deploy_to)); + } + + if (opt.mode == binding::ctypes) { + const auto library = detail::resolved_library(opt); + if (library.empty()) + return std::unexpected("options::library_name is empty; it names the shared library base name"); + if (library == "." || library == "..") + return std::unexpected(std::format("options::library_name `{}` is not a file name", library)); + if (library[0] == '.') + return std::unexpected(std::format( + "options::library_name `{}` is not a file name; it may not begin with `.`", library)); + for (std::size_t i = 0; i < library.size(); ++i) { + const char c = library[i]; + if (c == '/' || c == '\\' || c == ':' || c == '"' || c == '\0' + || c == '\n' || c == '\r') + return std::unexpected(std::format( + "options::library_name `{}` contains `{}`, which cannot be part of a file name", + library, c)); + } + + const auto prefix = detail::resolved_prefix(opt); + if (!detail::is_c_identifier(prefix)) + return std::unexpected(std::format( + "options::symbol_prefix `{}` is not a C identifier prefix " + "(letters, digits and `_`, not starting with a digit)", prefix)); + + if (opt.functions.empty()) + return std::unexpected("options::functions is empty; at least one function is required"); + + for (std::size_t fi = 0; fi < opt.functions.size(); ++fi) { + const auto& fn = opt.functions[fi]; + if (fn.name.empty()) + return std::unexpected(std::format("options::functions[{}] has an empty name", fi)); + if (mcpp::plugins::names::identifier(fn.name, "fn") != fn.name) + return std::unexpected(std::format( + "options::functions[{}] name `{}` is not a Python identifier", fi, fn.name)); + if (detail::is_python_keyword(fn.name)) + return std::unexpected(std::format( + "options::functions[{}] name `{}` is a Python keyword", fi, fn.name)); + if (fn.name[0] == '_') + return std::unexpected(std::format( + "options::functions[{}] name `{}` begins with `_`; this module's own helpers live there", + fi, fn.name)); + if (fn.name == "free_string") + return std::unexpected(std::format( + "options::functions[{}] name `{}` collides with the generated release function", + fi, fn.name)); + for (std::size_t j = 0; j < fi; ++j) { + if (opt.functions[j].name == fn.name) + return std::unexpected(std::format( + "two functions are both named `{}`; the Python module and the C symbols would collide", + fn.name)); + } + const auto expr = detail::resolved_cpp_expr(opt, fn); + if (expr.empty()) + return std::unexpected(std::format( + "options::functions[{}] (`{}`) has no C++ call target", fi, fn.name)); + for (std::size_t k = 0; k < expr.size(); ++k) { + const char c = expr[k]; + if (c == ';' || c == '{' || c == '}' || c == '"' || c == '\n' || c == '\r') + return std::unexpected(std::format( + "options::functions[{}] C++ call target `{}` contains `{}`; " + "it is a qualified function name, not a statement", + fi, expr, c)); + } + for (std::size_t pi = 0; pi < fn.params.size(); ++pi) { + const auto& p = fn.params[pi]; + if (p.type == type_kind::void_) + return std::unexpected(std::format( + "`{}`'s parameter `{}` has type void; void is a return type only", + fn.name, p.name)); + if (p.name.empty()) + return std::unexpected(std::format( + "`{}`'s parameter {} has an empty name", fn.name, pi)); + if (mcpp::plugins::names::identifier(p.name, "arg") != p.name) + return std::unexpected(std::format( + "`{}`'s parameter `{}` is not an identifier", fn.name, p.name)); + if (detail::is_python_keyword(p.name)) + return std::unexpected(std::format( + "`{}`'s parameter `{}` is a Python keyword", fn.name, p.name)); + if (p.name[0] == '_') + return std::unexpected(std::format( + "`{}`'s parameter `{}` begins with `_`; this module's own locals live there", + fn.name, p.name)); + for (std::size_t pj = 0; pj < pi; ++pj) { + if (fn.params[pj].name == p.name) + return std::unexpected(std::format( + "`{}` has two parameters named `{}`", fn.name, p.name)); + } + } + + } + + return {}; + } + + // โ”€โ”€ binding::nanobind โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + if (surface == discovery::auto_) + return std::unexpected( + "options::surface is auto but the declaration states neither `exports` nor " + "`manual_entry`; set `surface = discovery::reflect` for a reflected namespace, " + "`discovery::explicit_list` with `exports`, or `discovery::manual` with `manual_entry`"); + if (surface == discovery::reflect) { + const auto ns = detail::resolved_namespace(opt); + if (ns.empty()) + return std::unexpected( + "options::surface is reflect but no namespace can be derived; set " + "`cpp_namespace` or name a C++ module with a final segment"); + } + if (surface == discovery::manual && opt.manual_entry.empty()) + return std::unexpected( + "options::surface is manual but `manual_entry` is empty; it names the project's NB_MODULE TU"); + if (surface == discovery::explicit_list) { + if (opt.exports.empty()) + return std::unexpected( + "options::surface is explicit_list but `exports` is empty; name at least one export"); + for (std::size_t i = 0; i < opt.exports.size(); ++i) { + const auto& ex = opt.exports[i]; + if (ex.name.empty()) + return std::unexpected(std::format("options::exports[{}] has an empty name", i)); + if (mcpp::plugins::names::identifier(ex.name, "fn") != ex.name) + return std::unexpected(std::format( + "options::exports[{}] name `{}` is not a Python identifier", i, ex.name)); + if (detail::is_python_keyword(ex.name)) + return std::unexpected(std::format( + "options::exports[{}] name `{}` is a Python keyword", i, ex.name)); + if (ex.name[0] == '_') + return std::unexpected(std::format( + "options::exports[{}] name `{}` begins with `_`", i, ex.name)); + for (std::size_t j = 0; j < i; ++j) + if (opt.exports[j].name == ex.name) + return std::unexpected(std::format( + "two exports are both named `{}`", ex.name)); + const auto expr = detail::resolved_export_expr(opt, ex); + if (expr.empty()) + return std::unexpected(std::format( + "options::exports[{}] (`{}`) has no C++ call target", i, ex.name)); + for (std::size_t k = 0; k < expr.size(); ++k) { + const char c = expr[k]; + if (c == ';' || c == '{' || c == '}' || c == '"' || c == '\n' || c == '\r') + return std::unexpected(std::format( + "options::exports[{}] C++ call target `{}` contains `{}`; " + "it is a qualified function name, not a statement", i, expr, c)); + } + for (std::size_t ai = 0; ai < ex.arg_names.size(); ++ai) { + const auto& arg = ex.arg_names[ai]; + if (mcpp::plugins::names::identifier(arg, "arg") != arg) + return std::unexpected(std::format( + "options::exports[{}] argument name `{}` is not an identifier", i, arg)); + if (detail::is_python_keyword(arg)) + return std::unexpected(std::format( + "options::exports[{}] argument name `{}` is a Python keyword", i, arg)); + for (std::size_t aj = 0; aj < ai; ++aj) + if (ex.arg_names[aj] == arg) + return std::unexpected(std::format( + "options::exports[{}] has two argument names `{}`", i, arg)); + } + } + } + return {}; +} + +// โ”€โ”€โ”€ ctypes emission โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +namespace detail { + +inline void emit_bridge_function(std::string& cpp, const options& opt, + const function_decl& fn) { + const std::string sym = std::string(detail::resolved_prefix(opt)) + fn.name; + const std::string call = detail::resolved_cpp_expr(opt, fn); + + cpp += "MCPP_PY_EXPORT "; + cpp += detail::c_type_name(fn.ret); + cpp += " "; + cpp += sym; + cpp += "("; + bool first = true; + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + const std::string pname = "_mcpp_p" + std::to_string(i); + if (!first) cpp += ", "; + first = false; + if (p.type == type_kind::string) { + cpp += "const char* "; + cpp += pname; + cpp += "_ptr, std::size_t "; + cpp += pname; + cpp += "_len"; + } else { + cpp += detail::c_type_name(p.type); + cpp += " "; + cpp += pname; + } + } + if (fn.params.empty()) cpp += "void"; + cpp += ") noexcept {\n"; + cpp += " try {\n"; + + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + if (p.type != type_kind::string) continue; + const std::string pname = "_mcpp_p" + std::to_string(i); + cpp += " const std::string "; + cpp += pname; + cpp += "_arg = "; + cpp += pname; + cpp += "_ptr ? std::string("; + cpp += pname; + cpp += "_ptr, "; + cpp += pname; + cpp += "_len) : std::string();\n"; + } + + std::string args; + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + const std::string pname = "_mcpp_p" + std::to_string(i); + if (!args.empty()) args += ", "; + if (p.type == type_kind::string) { + args += pname; + args += "_arg"; + } else if (p.type == type_kind::bool_) { + args += pname; + args += " != 0"; + } else { + args += pname; + } + } + const std::string invocation = call + "(" + args + ")"; + + if (fn.ret == type_kind::void_) { + cpp += " "; + cpp += invocation; + cpp += ";\n"; + } else if (fn.ret == type_kind::string) { + // `_mcpp_res`, not `res`: a user function may itself be named `res`, + // and `const std::string res = res(...)` would shadow the call target. + cpp += " const std::string _mcpp_res = "; + cpp += invocation; + cpp += ";\n"; + cpp += " return mcpp_py_make_bytes(_mcpp_res);\n"; + } else { + cpp += " return "; + cpp += detail::python_cast(fn.ret); + cpp += "("; + cpp += invocation; + cpp += ");\n"; + } + + cpp += " } catch (...) {\n"; + if (fn.ret == type_kind::string) cpp += " return { nullptr, 0 };\n"; + else if (fn.ret != type_kind::void_) cpp += " return 0;\n"; + cpp += " }\n}\n\n"; +} + +inline void emit_python_function(std::string& py, const options& opt, + const function_decl& fn) { + const std::string sym = std::string(detail::resolved_prefix(opt)) + fn.name; + + py += "_lib."; + py += sym; + py += ".argtypes = ["; + bool first = true; + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + if (!first) py += ", "; + first = false; + if (p.type == type_kind::string) py += "_mcpp_ctypes.c_char_p, _mcpp_ctypes.c_size_t"; + else if (p.type == type_kind::i32) py += "_mcpp_ctypes.c_int32"; + else if (p.type == type_kind::i64) py += "_mcpp_ctypes.c_int64"; + else if (p.type == type_kind::f64) py += "_mcpp_ctypes.c_double"; + else if (p.type == type_kind::bool_) py += "_mcpp_ctypes.c_uint8"; + } + py += "]\n_lib."; + py += sym; + py += ".restype = "; + py += detail::python_restype(fn.ret); + py += "\n\n\n"; + + py += "def "; + py += fn.name; + py += "("; + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + if (i != 0) py += ", "; + py += p.name; + py += ": "; + py += detail::python_hint(p.type); + } + py += ") -> "; + py += detail::python_hint(fn.ret); + py += ":\n"; + if (!fn.doc.empty()) { + py += " \"\"\""; + py += detail::escaped_python_doc(fn.doc); + py += "\"\"\"\n"; + } + + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + if (p.type != type_kind::string) continue; + py += " _mcpp_"; + py += p.name; + py += "_bytes = "; + py += p.name; + py += ".encode(\"utf-8\")\n"; + } + + std::string args; + for (std::size_t i = 0; i < fn.params.size(); ++i) { + const auto& p = fn.params[i]; + if (!args.empty()) args += ", "; + if (p.type == type_kind::string) { + args += "_mcpp_"; + args += p.name; + args += "_bytes, _mcpp_builtins.len(_mcpp_"; + args += p.name; + args += "_bytes)"; + } else if (p.type == type_kind::bool_) { + args += "1 if "; + args += p.name; + args += " else 0"; + } else { + args += p.name; + } + } + + if (fn.ret == type_kind::void_) { + py += " _lib."; + py += sym; + py += "("; + py += args; + py += ")\n"; + } else if (fn.ret == type_kind::string) { + py += " return _take_string(_lib."; + py += sym; + py += "("; + py += args; + py += "))\n"; + } else if (fn.ret == type_kind::bool_) { + py += " return _mcpp_builtins.bool(_lib."; + py += sym; + py += "("; + py += args; + py += "))\n"; + } else { + py += " return _lib."; + py += sym; + py += "("; + py += args; + py += ")\n"; + } + py += "\n\n"; +} + +} // namespace detail + +inline std::string render_ctypes_bridge(const options& opt) { + const std::string prefix = detail::resolved_prefix(opt); + std::string cpp; + cpp += "// Generated by mcpp.rules.python for "; + cpp += opt.module_name; + cpp += ". Do not edit.\n"; + cpp += "//\n"; + cpp += "// The `extern \"C\"` boundary Python reaches. The C++ module it wraps is\n"; + cpp += "// untouched: no macro, no include, no visibility attribute there.\n"; + cpp += "\n"; + cpp += "import std;\n"; + cpp += "import "; + cpp += opt.cpp_module; + cpp += ";\n\n"; + + cpp += "#if defined(_WIN32)\n"; + cpp += "# define MCPP_PY_EXPORT __declspec(dllexport)\n"; + cpp += "#else\n"; + cpp += "# define MCPP_PY_EXPORT __attribute__((visibility(\"default\")))\n"; + cpp += "#endif\n\n"; + + cpp += "namespace {\n\n"; + cpp += "// Two words: a borrowed pointer and a length. A returned string is a\n"; + cpp += "// heap block this library allocated, and `free_string` is the only\n"; + cpp += "// function that releases it -- so Windows never asks Python's CRT to free\n"; + cpp += "// memory this DLL's CRT allocated.\n"; + cpp += "struct mcpp_py_bytes {\n"; + cpp += " char* data;\n"; + cpp += " std::size_t len;\n"; + cpp += "};\n\n"; + cpp += "mcpp_py_bytes mcpp_py_make_bytes(std::string_view s) noexcept {\n"; + cpp += " if (s.empty()) return { nullptr, 0 };\n"; + cpp += " char* buf = new (std::nothrow) char[s.size()];\n"; + cpp += " if (!buf) return { nullptr, 0 };\n"; + cpp += " std::memcpy(buf, s.data(), s.size());\n"; + cpp += " return { buf, s.size() };\n"; + cpp += "}\n\n"; + cpp += "} // namespace\n\n"; + + cpp += "extern \"C\" {\n\n"; + cpp += "MCPP_PY_EXPORT void "; + cpp += prefix; + cpp += "free_string(char* ptr) noexcept {\n"; + cpp += " delete[] ptr;\n"; + cpp += "}\n\n"; + for (std::size_t i = 0; i < opt.functions.size(); ++i) + detail::emit_bridge_function(cpp, opt, opt.functions[i]); + cpp += "} // extern \"C\"\n"; + return cpp; +} + +inline std::string render_ctypes_wrapper(const options& opt) { + const std::string prefix = detail::resolved_prefix(opt); + const std::string library = detail::resolved_library(opt); + std::string py; + py += "# Generated by mcpp.rules.python for "; + py += opt.module_name; + py += ". Do not edit.\n"; + py += "#\n"; + py += "# A ctypes view of the C ABI `"; + py += opt.cpp_module; + py += "` was compiled behind. Nothing here needs a Python toolchain at\n"; + py += "# build time; the library is the project's own artifact.\n"; + py += "\n"; + py += "from __future__ import annotations\n\n"; + py += "import builtins as _mcpp_builtins\n"; + py += "import ctypes as _mcpp_ctypes\n"; + py += "import os as _mcpp_os\n"; + py += "from pathlib import Path as _mcpp_Path\n"; + py += "import sys as _mcpp_sys\n\n"; + py += "_HERE = _mcpp_Path(__file__).resolve().parent\n"; + // A wrapper deployed into `deploy_to = "pkg/sub"` sits two directories + // below the artifact, so the library is looked for beside it and in every + // directory between it and the artifact. + const auto depth = mcpp::plugins::names::components(opt.deploy_to).size(); + py += "_ROOTS = [_HERE"; + for (std::size_t i = 1; i <= depth; ++i) { + py += ", _HERE"; + for (std::size_t k = 0; k < i; ++k) py += " / \"..\""; + } + py += "]\n"; + py += "_DLL_DIR_HANDLES: list[object] = []\n\n\n"; + py += "def _load_library(base_name: str) -> _mcpp_ctypes.CDLL:\n"; + py += " if _mcpp_sys.platform == \"win32\":\n"; + py += " candidates = [f\"{base_name}.dll\", f\"lib{base_name}.dll\"]\n"; + py += " if hasattr(_mcpp_os, \"add_dll_directory\"):\n"; + py += " for _mcpp_root in _ROOTS:\n"; + py += " if _mcpp_root.is_dir():\n"; + py += " _DLL_DIR_HANDLES.append(\n"; + py += " _mcpp_os.add_dll_directory(str(_mcpp_root)))\n"; + py += " elif _mcpp_sys.platform == \"darwin\":\n"; + py += " candidates = [f\"lib{base_name}.dylib\", f\"{base_name}.dylib\"]\n"; + py += " else:\n"; + py += " candidates = [f\"lib{base_name}.so\", f\"{base_name}.so\"]\n"; + py += "\n"; + py += " for _mcpp_root in _ROOTS:\n"; + py += " for name in candidates:\n"; + py += " path = _mcpp_root / name\n"; + py += " if path.is_file():\n"; + py += " return _mcpp_ctypes.CDLL(str(path))\n"; + py += "\n"; + py += " tried = \", \".join(\n"; + py += " str(_mcpp_root / c) for _mcpp_root in _ROOTS for c in candidates)\n"; + py += " raise FileNotFoundError(\n"; + py += " f\"mcpp.rules.python: shared library for '{base_name}' not found \"\n"; + py += " f\"(tried: {tried})\"\n"; + py += " )\n\n\n"; + py += "_lib = _load_library(\""; + py += library; + py += "\")\n\n\n"; + py += "class _McppBytes(_mcpp_ctypes.Structure):\n"; + py += " _fields_ = [(\"data\", _mcpp_ctypes.c_void_p), (\"len\", _mcpp_ctypes.c_size_t)]\n\n\n"; + py += "_lib."; + py += prefix; + py += "free_string.argtypes = [_mcpp_ctypes.c_void_p]\n"; + py += "_lib."; + py += prefix; + py += "free_string.restype = None\n\n\n"; + py += "def _take_string(raw: _McppBytes) -> str:\n"; + py += " try:\n"; + py += " if not raw.data or raw.len == 0:\n"; + py += " return \"\"\n"; + py += " return _mcpp_ctypes.string_at(raw.data, raw.len).decode(\"utf-8\")\n"; + py += " finally:\n"; + py += " if raw.data:\n"; + py += " _lib."; + py += prefix; + py += "free_string(raw.data)\n\n\n"; + for (std::size_t i = 0; i < opt.functions.size(); ++i) + detail::emit_python_function(py, opt, opt.functions[i]); + return py; +} + +// โ”€โ”€โ”€ nanobind emission โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +inline std::string render_nanobind_entry(const options& opt) { + const auto surface = detail::resolved_surface(opt); + std::string cpp; + cpp += "// Generated by mcpp.rules.python for "; + cpp += opt.module_name; + cpp += ". Do not edit.\n"; + cpp += "//\n"; + cpp += "// Every #include is before the first import: GCC rejects a header\n"; + cpp += "// included after an import of a module that declared the same entities,\n"; + cpp += "// and the mixed TU that includes must stay on that side.\n"; + cpp += "\n"; + cpp += "#include \n"; + if (surface == discovery::reflect) cpp += "#include \n"; + cpp += "\n"; + cpp += "import mcpplibs.mwrap.nanobind;\n"; + if (opt.import_stl) cpp += "import mcpplibs.mwrap.nanobind.stl;\n"; + if (!opt.cpp_module.empty()) { + cpp += "import "; + cpp += opt.cpp_module; + cpp += ";\n"; + } + if (surface == discovery::manual) { + // `discovery::manual` compiles `options::manual_entry` directly and + // generates no entry file, so there is nothing to render here. + return {}; + } + + cpp += "\nNB_MODULE("; + cpp += opt.module_name; + cpp += ", m) {\n"; + + if (surface == discovery::reflect) { + const std::string ns = detail::resolved_namespace(opt); + cpp += " constexpr auto context = std::meta::access_context::current();\n"; + cpp += " static constexpr auto members = std::define_static_array(\n"; + cpp += " std::meta::members_of(^^"; + cpp += ns; + cpp += ", context));\n"; + cpp += " template for (constexpr auto member : members) {\n"; + cpp += " if constexpr (std::meta::is_function(member)\n"; + cpp += " && std::meta::has_identifier(member)) {\n"; + cpp += " m.def(std::meta::identifier_of(member).data(), &[:member:]);\n"; + cpp += " }\n"; + cpp += " }\n"; + } else { + for (std::size_t i = 0; i < opt.exports.size(); ++i) { + const auto& ex = opt.exports[i]; + const auto expr = detail::resolved_export_expr(opt, ex); + // A plain name needs its address; an overload cast, a lambda or an + // expression that already takes one must not get a second `&`. + const auto lead = ex.cpp_expr.find_first_not_of(" \t"); + const std::string_view head = + lead == std::string::npos ? std::string_view() + : std::string_view(ex.cpp_expr).substr(lead); + const bool already_addressed = !head.empty() + && (head.starts_with("&") || head.starts_with("static_cast<") + || head.starts_with("reinterpret_cast<") + || head.starts_with("(") || head.starts_with("[")); + cpp += " m.def(\""; + cpp += detail::escaped_cpp_string(ex.name); + cpp += "\", "; + if (!already_addressed) cpp += "&"; + cpp += expr; + for (std::size_t a = 0; a < ex.arg_names.size(); ++a) { + cpp += ", nanobind::arg(\""; + cpp += detail::escaped_cpp_string(ex.arg_names[a]); + cpp += "\")"; + } + if (!ex.doc.empty()) { + cpp += ", \""; + cpp += detail::escaped_cpp_string(ex.doc); + cpp += "\""; + } + cpp += ");\n"; + } + if (opt.exports.empty()) + cpp += " // No explicit exports; the project states discovery::manual for its own TU.\n"; + } + cpp += "}\n"; + return cpp; +} + +inline std::string render_pyi_stub(const options& opt) { + std::string py; + py += "# Generated by mcpp.rules.python for "; + py += opt.module_name; + py += ". Do not edit.\n"; + py += "\n"; + py += "from typing import Any\n\n"; + for (std::size_t i = 0; i < opt.exports.size(); ++i) { + const auto& ex = opt.exports[i]; + py += "def "; + py += ex.name; + py += "("; + for (std::size_t a = 0; a < ex.arg_names.size(); ++a) { + if (a != 0) py += ", "; + py += ex.arg_names[a]; + py += ": Any"; + } + py += ") -> Any: ...\n"; + } + return py; +} + +// โ”€โ”€โ”€ Python SDK discovery โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +namespace detail { + +struct python_sdk { + std::string executable; + std::string include_dir; + std::string platinclude_dir; // Debian/Ubuntu's architecture-specific headers + std::string library_dir; + std::string library; + std::string ext_suffix; + std::string version; // "313" on Windows, "3.13" elsewhere + std::string source; + bool found = false; +}; + +// Runs one interpreter and reads the values the rule needs. NOT INLINE, for +// the reason docs/01-plugin-development.md ยง4 gives: the body reaches +// mcpplibs.os through tool::capture, and GCC 16 cannot carry it through an +// importer's inline instantiation. +python_sdk probe_interpreter(const std::string& program, std::string_view source); + +// The resolved C++ compiler's major version, or 0 when it cannot be read. NOT +// INLINE for the same reason as `probe_interpreter`: the body runs a program +// through `tool::capture`, which reaches mcpplibs.os. +int compiler_major(); + +inline const mcpp::plugins::tool::spec& uv_spec() { + static const mcpp::plugins::tool::spec s{ + .who = "mcpp.rules.python", + .ns = "xim", + .package = "uv", + .programs = {"uv"}, + .bin_dirs = {"bin", ""}, + .option = "options::uv", + .legacy_env = "MCPP_UV", + .request = false, + }; + return s; +} + +inline const mcpp::plugins::tool::spec& python_spec() { + // `request = false`: this rule never asks for `xim:python`. The payload is + // owned by the graph -- `mcpplibs.mwrap.nanobind`'s SDK feature, or the + // consumer's own `[xlings.workspace]` -- and this rule only reads what the + // graph already installed. + static const mcpp::plugins::tool::spec s{ + .who = "mcpp.rules.python", + .ns = "xim", + .package = "python", + .programs = {"python3", "python"}, + .bin_dirs = {"bin", ""}, + .option = "options::python", + .legacy_env = "MCPP_PYTHON_EXECUTABLE", + .request = false, + }; + return s; +} + +// NOT INLINE: this body runs a program through mcpp::plugins::tool::capture, +// which reaches mcpplibs.os. docs/01-plugin-development.md ยง4 makes such a +// function compiled once in this module, with an importer seeing its +// declaration only; an inline body would be instantiated in an importer's BMI +// and GCC 16 fails to read the cluster back. +std::string find_uv_python(const options& opt); + +inline std::string find_uv(const options& opt) { + // A stated choice is the first answer and is not replaced. Otherwise + // resolve() reads MCPP_UV and `[xlings.overrides]` before PATH is tried; + // passing `on_path` as the choice would skip both. + auto stated = mcpp::plugins::tool::resolve(uv_spec(), opt.uv); + if (stated) return stated.program; + if (!opt.uv.is_default()) return {}; + auto path = mcpp::plugins::tool::resolve(uv_spec(), mcpp::plugins::tool::on_path("uv")); + return path ? path.program : std::string(); +} + +// The interpreter a virtual environment carries, or empty. `bin/python` is +// what a POSIX venv has and `Scripts/python.exe` is what a Windows one does. +inline std::string venv_python(const std::string& venv) { + namespace fs = std::filesystem; + for (const char* rel : {"bin/python3", "bin/python", "Scripts/python.exe", "python.exe"}) { + std::error_code ec; + const auto p = fs::path(venv) / rel; + if (fs::is_regular_file(p, ec)) return mcpp::plugins::fs::generic(p); + } + return {}; +} + +// A host interpreter on PATH. The stated choice and the shared environment are +// answered before this in `emit`; this is the last source of the host level. +inline std::string find_host_python() { + auto path = mcpp::plugins::tool::resolve(python_spec(), mcpp::plugins::tool::on_path()); + return path ? path.program : std::string(); +} + +// The graph's `xim:python` payload: READ, NEVER REQUESTED. `tool::resolve` +// would ask the engine for a payload declared `provision = "on-request"` (and +// report `pending`); this rule does not own that payload, so it reads +// `mcpp::xpkg_dir` directly and finds the interpreter the graph installed. +inline detail::python_sdk find_xim_python() { + const std::string root = mcpp::xpkg_dir("xim", "python"); + if (root.empty()) return {}; + const std::string program = mcpp::plugins::tool::program_in_root(python_spec(), root); + if (program.empty()) return {}; + return probe_interpreter(program, "xim:python"); +} + +std::string find_uv_python(const options& opt) { + const std::string uv = find_uv(opt); + if (uv.empty()) return {}; + const auto printed = mcpp::plugins::tool::capture({uv, "python", "find"}); + if (printed.status != 0) return {}; + std::string path = printed.out; + while (!path.empty() && (path.back() == '\n' || path.back() == '\r' || path.back() == ' ')) + path.pop_back(); + // uv prints "cpython-3.13..." when it resolved a request; `python find` + // prints the executable path when one is installed. + std::error_code ec; + if (!path.empty() && std::filesystem::is_regular_file(path, ec)) return path; + return {}; +} + +inline std::string value_of_line(const std::string& text, std::string_view key) { + std::size_t i = 0; + while (i <= text.size()) { + const auto nl = text.find('\n', i); + std::string line = text.substr(i, nl == std::string::npos ? std::string::npos : nl - i); + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.starts_with(key) && line.size() > key.size() && line[key.size()] == '=') + return line.substr(key.size() + 1); + if (nl == std::string::npos) break; + i = nl + 1; + } + return {}; +} + +int compiler_major() { + const char* cxx = mcpp::tool("cxx"); + if (cxx == nullptr || *cxx == '\0') return 0; + const auto printed = mcpp::plugins::tool::capture({cxx, "-dumpversion"}, true); + if (printed.status != 0) return 0; + int major = 0; + for (char c : printed.out) { + if (c < '0' || c > '9') break; + major = major * 10 + (c - '0'); + } + return major; +} + +python_sdk probe_interpreter(const std::string& program, std::string_view source) { + python_sdk sdk; + if (program.empty()) return sdk; + static constexpr std::string_view script = + "import os, sys, sysconfig\n" + "print('include=' + (sysconfig.get_path('include') or ''))\n" + "print('platinclude=' + (sysconfig.get_path('platinclude') or ''))\n" + "print('ext_suffix=' + (sysconfig.get_config_var('EXT_SUFFIX') or ('.pyd' if os.name == 'nt' else '.so')))\n" + "print('libdir=' + (sysconfig.get_config_var('LIBDIR') or (os.path.join(sys.base_prefix, 'libs') if os.name == 'nt' else '')))\n" + "print('library=' + ('python%d%d' % (sys.version_info.major, sys.version_info.minor) if os.name == 'nt' else 'python%d.%d' % (sys.version_info.major, sys.version_info.minor)))\n" + "print('version=%d%d' % (sys.version_info.major, sys.version_info.minor))\n" + "print('executable=' + sys.executable)\n"; + const auto printed = mcpp::plugins::tool::capture({program, "-c", std::string(script)}, true); + if (printed.status != 0) return sdk; + sdk.include_dir = value_of_line(printed.out, "include"); + sdk.platinclude_dir = value_of_line(printed.out, "platinclude"); + sdk.ext_suffix = value_of_line(printed.out, "ext_suffix"); + sdk.library_dir = value_of_line(printed.out, "libdir"); + sdk.library = value_of_line(printed.out, "library"); + sdk.version = value_of_line(printed.out, "version"); + sdk.executable = value_of_line(printed.out, "executable"); + if (sdk.executable.empty()) sdk.executable = program; + sdk.source = std::string(source); + std::error_code ec; + sdk.found = !sdk.include_dir.empty() + && std::filesystem::is_regular_file(std::filesystem::path(sdk.include_dir) / "Python.h", ec) + && !sdk.ext_suffix.empty(); + return sdk; +} + +bool path_below(const std::string& value, const std::string& root) { + if (value.empty() || root.empty()) return false; + const auto normalise = [](const std::string& p) { + std::error_code ec; + const auto canonical = std::filesystem::weakly_canonical(std::filesystem::path(p), ec); + return ec ? std::filesystem::path(p).lexically_normal() : canonical; + }; + const auto p = normalise(value); + const auto r = normalise(root); + const bool windows = std::string_view(mcpp::target_os()) == "windows"; + const auto equal = [windows](const std::filesystem::path& a, + const std::filesystem::path& b) { + if (!windows) return a == b; + std::string x = a.string(); + std::string y = b.string(); + for (std::size_t i = 0; i < x.size(); ++i) + if (x[i] >= 'A' && x[i] <= 'Z') x[i] = static_cast(x[i] - 'A' + 'a'); + for (std::size_t i = 0; i < y.size(); ++i) + if (y[i] >= 'A' && y[i] <= 'Z') y[i] = static_cast(y[i] - 'A' + 'a'); + return x == y; + }; + auto pi = p.begin(); + for (auto ri = r.begin(); ri != r.end(); ++ri, ++pi) { + if (pi == p.end() || !equal(*pi, *ri)) return false; + } + return true; +} + +} // namespace detail + +// โ”€โ”€โ”€ emit โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +inline emitted emit(const options& opt) { + emitted out; + const auto problem = validate(opt); + if (!problem) { + std::cerr << "mcpp.rules.python: " << problem.error() << "\n"; + return out; + } + + options o = opt; + if (o.out_dir.empty()) o.out_dir = std::string(mcpp::out_dir()) + "/python"; + if (o.stage_dir.empty()) o.stage_dir = o.out_dir + "/pkg"; + if (o.deploy_to.empty()) o.deploy_to = "."; + + if (o.mode == binding::ctypes) { + const std::string cpp = render_ctypes_bridge(o); + const std::string py = render_ctypes_wrapper(o); + const std::string bridge_path = o.out_dir + "/" + o.module_name + "_pybridge.cpp"; + const std::string py_path = o.out_dir + "/" + o.module_name + ".py"; + mcpp::plugins::fs::write_if_changed(bridge_path, cpp); + mcpp::plugins::fs::write_if_changed(py_path, py); + std::error_code ec; + if (!std::filesystem::is_regular_file(bridge_path, ec) + || !std::filesystem::is_regular_file(py_path, ec)) { + std::cerr << "mcpp.rules.python: cannot write " << bridge_path + << " or " << py_path << "\n"; + return out; + } + out.entry_cpp = mcpp::plugins::fs::generic(bridge_path); + out.python_file = mcpp::plugins::fs::generic(py_path); + out.symbol_prefix = detail::resolved_prefix(o); + out.ok = true; + if (o.register_with_build) { + mcpp::generated(out.entry_cpp.c_str()); + mcpp::deploy(out.python_file.c_str(), o.deploy_to.c_str()); + } + mcpp::fact("mcpp.plugins.version", std::string(mcpp::plugins::version).c_str()); + mcpp::fact("mcpp.rules.python.backend", "ctypes"); + mcpp::fact("mcpp.rules.python.module", o.module_name.c_str()); + return out; + } + + // โ”€โ”€ binding::nanobind โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + const auto surface = detail::resolved_surface(o); + + // THE STATIC CRT IS REFUSED BEFORE ANYTHING IS WRITTEN OR REGISTERED. + // CPython uses the dynamic CRT, and a `/MT` extension would allocate on a + // heap the interpreter does not share. Checking here rather than after the + // entry and stub were written means a refused build leaves no side effect. + if (o.register_with_build + && std::string_view(mcpp::target_os()) == "windows" + && std::string_view(mcpp::msvc_crt_linkage()) == "static") { + mcpp::warning("mcpp.rules.python: the MSVC CRT is static; CPython uses the " + "dynamic CRT and a statically linked extension is refused. " + "Set the project's CRT to dynamic or use binding::ctypes."); + return out; + } + + if (surface == discovery::reflect) { + const std::string compiler = mcpp::compiler(); + const int major = compiler.starts_with("gcc") ? detail::compiler_major() : 0; + if (!compiler.starts_with("gcc") || major < 16) { + mcpp::warning(std::format( + "mcpp.rules.python: discovery::reflect requires GCC 16 or newer with " + "-std=c++26 -freflection; this build uses `{}` major {}, and no " + "binding was generated. State discovery::explicit_list or " + "discovery::manual instead.", + compiler.empty() ? "an unknown compiler" : compiler, major).c_str()); + return out; + } + if (o.register_with_build) { + mcpp::cxxflag("-std=c++26"); + mcpp::cxxflag("-freflection"); + } + } + + // A build program that asked for the files only leaves the graph alone: + // no flag, no link input, no action, and no environment dependency. + if (o.register_with_build) { + mcpp::rerun_if_env_changed("MCPP_PYTHON_INCLUDE_DIR"); + mcpp::rerun_if_env_changed("MCPP_PYTHON_EXECUTABLE"); + mcpp::rerun_if_env_changed("MCPP_PYTHON_LIBRARY_DIR"); + mcpp::rerun_if_env_changed("MCPP_PYTHON_LIBRARY"); + mcpp::rerun_if_env_changed("MCPP_PYTHON_EXT_SUFFIX"); + mcpp::rerun_if_env_changed("VIRTUAL_ENV"); + mcpp::rerun_if_env_changed("MCPP_UV"); + } + + const char* env_include = std::getenv("MCPP_PYTHON_INCLUDE_DIR"); + const char* env_ext_suffix = std::getenv("MCPP_PYTHON_EXT_SUFFIX"); + const char* env_executable = std::getenv("MCPP_PYTHON_EXECUTABLE"); + const char* env_venv = std::getenv("VIRTUAL_ENV"); + + detail::python_sdk sdk; + + // โ”€โ”€ 1. Explicit build.mcpp options, strict and never replaced โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + if (!o.python_include_dir.empty() && !o.ext_suffix.empty()) { + // Headers-only cross compilation: no interpreter is run, here or in + // the artifact action below. + sdk.include_dir = o.python_include_dir; + sdk.ext_suffix = o.ext_suffix; + sdk.source = "options"; + sdk.found = true; + } else if (!o.python.is_default()) { + // A stated choice is resolved once, through the tool model, and is + // never replaced by another source when it fails. This is what makes + // `tool::root(...)` work and a typo fail by name. + const auto found = mcpp::plugins::tool::resolve(detail::python_spec(), o.python); + if (!found) { + mcpp::warning(mcpp::plugins::tool::describe_missing( + detail::python_spec(), found).c_str()); + return out; + } + sdk = detail::probe_interpreter(found.program, "options::python"); + if (!sdk.found) { + mcpp::warning(std::format( + "mcpp.rules.python: options::python resolved to `{}`, but it is not a " + "Python SDK (no Python.h or EXT_SUFFIX); a stated choice is not " + "replaced by the shared environment, xim:python, uv or a host " + "interpreter.", + found.program).c_str()); + return out; + } + } else if (o.python_env != env::none) { + const bool allow_xim = o.python_env == env::auto_ || o.python_env == env::xim; + const bool allow_uv = o.python_env == env::auto_ || o.python_env == env::uv; + const bool allow_host = o.python_env == env::auto_ || o.python_env == env::host; + + // โ”€โ”€ 2. Shared environment and virtual environment โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + // The same SDK `mcpplibs.mwrap.nanobind` compiles its runtime against. + if (env_include && *env_include && env_ext_suffix && *env_ext_suffix) { + sdk.include_dir = env_include; + sdk.ext_suffix = env_ext_suffix; + sdk.source = "env"; + sdk.found = true; + } + if (!sdk.found && env_executable && *env_executable) { + // STRICT: a stated interpreter is probed once. If it is not a + // Python SDK, the build is refused rather than silently moved to + // xim:python, uv or PATH. + sdk = detail::probe_interpreter( + mcpp::plugins::fs::generic(env_executable), "MCPP_PYTHON_EXECUTABLE"); + if (!sdk.found) { + mcpp::warning(std::format( + "mcpp.rules.python: MCPP_PYTHON_EXECUTABLE=`{}` is set, but it is " + "not a Python SDK (no Python.h or EXT_SUFFIX). A stated environment " + "interpreter is not replaced by xim:python, uv or PATH; unset it or " + "point it at a development interpreter.", + env_executable).c_str()); + return out; + } + } + if (!sdk.found && env_venv && *env_venv) { + const std::string program = detail::venv_python(env_venv); + if (!program.empty()) sdk = detail::probe_interpreter(program, "VIRTUAL_ENV"); + } + + // โ”€โ”€ 3. The graph's xim:python payload, read but never requested โ”€โ”€โ”€โ”€ + if (!sdk.found && allow_xim) sdk = detail::find_xim_python(); + + // โ”€โ”€ 4. uv, then the host's PATH โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + if (!sdk.found && allow_uv) + sdk = detail::probe_interpreter(detail::find_uv_python(o), "uv"); + if (!sdk.found && allow_host) + sdk = detail::probe_interpreter(detail::find_host_python(), "host"); + } + + // Environment overrides are applied AFTER a probe, so an interpreter's + // sysconfig can never overwrite an explicitly stated directory. + if (!o.python_include_dir.empty()) sdk.include_dir = o.python_include_dir; + else if (const char* v = std::getenv("MCPP_PYTHON_INCLUDE_DIR"); v && *v) sdk.include_dir = v; + if (!o.python_library_dir.empty()) sdk.library_dir = o.python_library_dir; + else if (const char* v = std::getenv("MCPP_PYTHON_LIBRARY_DIR"); v && *v) sdk.library_dir = v; + if (!o.python_library.empty()) sdk.library = o.python_library; + else if (const char* v = std::getenv("MCPP_PYTHON_LIBRARY"); v && *v) sdk.library = v; + if (!o.ext_suffix.empty()) sdk.ext_suffix = o.ext_suffix; + else if (const char* v = std::getenv("MCPP_PYTHON_EXT_SUFFIX"); v && *v) sdk.ext_suffix = v; + + if (!sdk.include_dir.empty() && !sdk.ext_suffix.empty()) { + std::error_code ec; + sdk.found = std::filesystem::is_regular_file( + std::filesystem::path(sdk.include_dir) / "Python.h", ec); + } else { + sdk.found = false; + } + + if (!sdk.found) { + mcpp::warning("mcpp.rules.python: no Python development headers were found. " + "State python_include_dir + ext_suffix, set " + "MCPP_PYTHON_INCLUDE_DIR/MCPP_PYTHON_EXECUTABLE/" + "MCPP_PYTHON_EXT_SUFFIX or VIRTUAL_ENV, declare " + "`[xlings.workspace] \"xim:python\" = \"3.13.12\"` (the SDK " + "mcpplibs.mwrap.nanobind provides by default), or install uv. " + "No native extension was generated."); + return out; + } + + // The extension and the dependency's runtime must share one SDK. A local + // selection while the graph also installed `xim:python` is the one case + // neither package can see on its own: `build.mcpp` options do not reach + // `mcpplibs.mwrap.nanobind`'s build program. + if (detail::sdk_is_consumer_local(sdk.source)) { + const std::string xpkg = mcpp::xpkg_dir("xim", "python"); + if (!xpkg.empty() && !detail::path_below(sdk.include_dir, xpkg)) { + mcpp::warning(std::format( + "mcpp.rules.python: this extension targets the Python SDK at `{}` " + "({}), but mcpplibs.mwrap.nanobind builds its runtime against " + "`xim:python` at `{}`. Build-program options do not propagate to that " + "dependency's own build program, so the two halves of the extension " + "would use different headers. Share one SDK instead: set " + "MCPP_PYTHON_EXECUTABLE, VIRTUAL_ENV or MCPP_PYTHON_INCLUDE_DIR, or " + "declare `[xlings.workspace] \"xim:python\" = \"3.13.12\"`; or disable " + "the dependency's default SDK with `mcpplibs.mwrap.nanobind = {{ " + "version = \"3.1.0\", default-features = false, features = [\"runtime\"] }}`.", + sdk.include_dir, sdk.source, xpkg).c_str()); + } + } + + std::error_code ec; + if (surface == discovery::manual) { + // The project writes its own NB_MODULE TU. The rule still owns the SDK, + // the link, the suffix and the placement. + out.entry_cpp = o.manual_entry; + } else { + const std::string entry = render_nanobind_entry(o); + const std::string entry_path = o.out_dir + "/" + o.module_name + "_py_entry.cpp"; + mcpp::plugins::fs::write_if_changed(entry_path, entry); + if (!std::filesystem::is_regular_file(entry_path, ec)) { + std::cerr << "mcpp.rules.python: cannot write " << entry_path << "\n"; + return out; + } + out.entry_cpp = mcpp::plugins::fs::generic(entry_path); + } + out.ext_suffix = sdk.ext_suffix; + out.python_executable = sdk.executable; + out.python_include_dir = sdk.include_dir; + + std::string pyi_path; + if (surface == discovery::explicit_list && o.emit_stub) { + std::filesystem::create_directories(o.stage_dir, ec); + pyi_path = o.stage_dir + "/" + o.module_name + ".pyi"; + mcpp::plugins::fs::write_if_changed(pyi_path, render_pyi_stub(o)); + out.python_file = mcpp::plugins::fs::generic(pyi_path); + } + + if (!o.register_with_build) { + out.ok = true; + return out; + } + + mcpp::include_dir(sdk.include_dir.c_str()); + if (!sdk.platinclude_dir.empty() && sdk.platinclude_dir != sdk.include_dir) + mcpp::include_dir(sdk.platinclude_dir.c_str()); + if (surface == discovery::manual) mcpp::source(out.entry_cpp.c_str()); + else mcpp::generated(out.entry_cpp.c_str()); + + if (std::string_view(mcpp::target_os()) == "windows") { + mcpp::cxxflag("-DNOMINMAX"); + mcpp::cxxflag("-DWIN32_LEAN_AND_MEAN"); + if (!sdk.library_dir.empty()) mcpp::link_search(sdk.library_dir.c_str()); + if (!sdk.library.empty()) mcpp::link_lib(sdk.library.c_str()); + } else if (std::string_view(mcpp::target_os()) == "macos") { + mcpp::link_flag("-undefined"); + mcpp::link_flag("dynamic_lookup"); + } + // Linux deliberately links no libpython: a CPython extension resolves the + // interpreter's symbols from the process that loaded it. + + std::filesystem::create_directories(o.stage_dir, ec); + const std::string extension = o.stage_dir + "/" + o.module_name + sdk.ext_suffix; + { + const std::string id = "python-extension:" + o.module_name; + const std::string desc = "PYTHON EXTENSION " + o.module_name; + const std::string target_token = std::format("${{mcpp.target_file:{}}}", + detail::resolved_target(o)); + mcpp::action a; + a.id = id.c_str(); + a.role = mcpp::roles::artifact; + a.description = desc.c_str(); + // The engine copies the linked file itself: no shell and no host + // Python, which is what headers-only cross compilation needs. + a.arg("${mcpp.self}").arg("stage").arg("--output") + .arg(extension.c_str()).arg(target_token.c_str()); + a.input(target_token.c_str()); + a.output(extension.c_str()); + a.submit(); + } + out.extension_file = mcpp::plugins::fs::generic(extension); + + if (!out.python_file.empty()) + mcpp::deploy(out.python_file.c_str(), o.deploy_to.c_str()); + mcpp::deploy(out.extension_file.c_str(), o.deploy_to.c_str()); + + mcpp::fact("mcpp.plugins.version", std::string(mcpp::plugins::version).c_str()); + mcpp::fact("python.executable", sdk.executable.c_str()); + mcpp::fact("python.include", sdk.include_dir.c_str()); + mcpp::fact("python.ext_suffix", sdk.ext_suffix.c_str()); + mcpp::fact("mcpp.rules.python.backend", "nanobind"); + mcpp::fact("mcpp.rules.python.surface", + surface == discovery::reflect ? "reflect" + : surface == discovery::manual ? "manual" : "explicit_list"); + mcpp::fact("mcpp.rules.python.module", o.module_name.c_str()); + out.ok = true; + return out; +} + +} // namespace mcpp::rules::python diff --git a/src/plugins.cppm b/src/plugins.cppm index 2bcf6c6..cac330d 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.27.0"; +inline constexpr std::string_view version = "0.28.0"; } // namespace mcpp::plugins diff --git a/tests/all-rules-compile/build.mcpp b/tests/all-rules-compile/build.mcpp index 4394b86..56360d8 100644 --- a/tests/all-rules-compile/build.mcpp +++ b/tests/all-rules-compile/build.mcpp @@ -18,6 +18,8 @@ import mcpp.rules.sycl; import mcpp.tools.embed; import mcpp.tools.island; import mcpp.tools.steps; +import mcpp.rules.python; +import mcpp.plugins.tool; import mcpp.dist.appimage; import mcpp.dist.wix; import mcpp.dist.apple; @@ -60,6 +62,242 @@ int main() { // Same question of the island generator: the one call that writes // nothing. `entry_name` is where its only parsing lives. ok = ok && mcpp::tools::island::entry_name("int f(int a)") == "f"; + // And of the Python rule: every pure renderer and both answers of + // `validate`, with no disk and no Python SDK. The three declarations are + // the two nanobind discovery modes and the ctypes backend. + { + namespace rp = mcpp::rules::python; + + rp::options ctypes; + ctypes.mode = rp::binding::ctypes; + ctypes.python_env = rp::env::none; + ctypes.module_name = "probe"; + ctypes.cpp_module = "probe"; + ctypes.cpp_namespace = "probe"; + ctypes.functions = { + { "add", "", { { "a", rp::type_kind::i32 }, { "b", rp::type_kind::i32 } }, + rp::type_kind::i32, "sum" }, + { "greet", "", { { "name", rp::type_kind::string } }, + rp::type_kind::string, "" }, + // A function NAMED `res` returning a string: the generated local + // must be `_mcpp_res`, or the call target is shadowed. + { "res", "", {}, rp::type_kind::string, "" }, + }; + ok = ok && rp::validate(ctypes).has_value(); + const auto bridge = rp::render_ctypes_bridge(ctypes); + const auto wrapper = rp::render_ctypes_wrapper(ctypes); + ok = ok && bridge.find("mcpp_py_probe_add") != std::string::npos + && bridge.find("extern \"C\"") != std::string::npos + && bridge.find("const std::string _mcpp_res =") != std::string::npos + && bridge.find("mcpp_py_make_bytes(_mcpp_res)") != std::string::npos + && bridge.find("const std::string res =") == std::string::npos + && wrapper.find("def add(a: int, b: int) -> int:") != std::string::npos + && wrapper.find("def greet(name: str) -> str:") != std::string::npos; + ctypes.functions[0].params[1].type = rp::type_kind::void_; + ok = ok && !rp::validate(ctypes).has_value(); + ctypes.functions[0].params[1].type = rp::type_kind::i32; + + rp::options listed; + listed.mode = rp::binding::nanobind; + listed.python_env = rp::env::none; + listed.surface = rp::discovery::explicit_list; + listed.module_name = "probe"; + listed.cpp_module = "probe"; + listed.cpp_namespace = "probe"; + listed.exports = { + { "add", "", "sum", { "a", "b" } }, + { "greet", "", "", { "name" } }, + }; + ok = ok && rp::validate(listed).has_value(); + const auto entry = rp::render_nanobind_entry(listed); + ok = ok && entry.find("#include ") != std::string::npos + && entry.find("import mcpplibs.mwrap.nanobind.stl;") != std::string::npos + && entry.find("NB_MODULE(probe, m)") != std::string::npos + && entry.find("m.def(\"add\", &probe::add, nanobind::arg(\"a\"), " + "nanobind::arg(\"b\"), \"sum\");") != std::string::npos + && entry.find("import std;") == std::string::npos; + // An overloaded function is named by a cast, which already takes an + // address: no `&static_cast<`. + rp::options overloaded = listed; + overloaded.exports = { + { "add_as_int", "static_cast(&probe::add)", "", {} }, + }; + ok = ok && rp::validate(overloaded).has_value(); + const auto overloaded_entry = rp::render_nanobind_entry(overloaded); + ok = ok && overloaded_entry.find( + "m.def(\"add_as_int\", static_cast(&probe::add));") + != std::string::npos + && overloaded_entry.find("&static_cast<") == std::string::npos; + const auto stub = rp::render_pyi_stub(listed); + ok = ok && stub.find("def add(a: Any, b: Any) -> Any: ...") != std::string::npos + && stub.find("def greet(name: Any) -> Any: ...") != std::string::npos; + listed.exports.clear(); + ok = ok && !rp::validate(listed).has_value(); + listed.exports = { { "add", "", "", { "a", "b" } } }; + + rp::options reflected; + reflected.mode = rp::binding::nanobind; + reflected.python_env = rp::env::none; + reflected.surface = rp::discovery::reflect; + reflected.module_name = "probe"; + reflected.cpp_module = "example.probe"; + ok = ok && rp::validate(reflected).has_value(); + const auto reflected_entry = rp::render_nanobind_entry(reflected); + ok = ok && reflected_entry.find("#include ") != std::string::npos + && reflected_entry.find("std::meta::members_of(^^probe") != std::string::npos + && reflected_entry.find("template for (constexpr auto member : members)") != std::string::npos + && reflected_entry.find("&[:member:]") != std::string::npos; + reflected.cpp_module.clear(); + reflected.cpp_namespace.clear(); + ok = ok && !rp::validate(reflected).has_value(); + + // Names that are valid Python but would shadow the wrapper's imports, + // builtins or the bridge's C++ parameters are safe by construction. + rp::options collision = ctypes; + collision.module_name = "collision"; + collision.library_name = "collision_core"; + collision.symbol_prefix = "acme_"; + collision.deploy_to = "pkg/sub"; + collision.functions = { + { "collide", "", { + { "len", rp::type_kind::i32 }, + { "ctypes", rp::type_kind::string }, + { "res", rp::type_kind::i32 }, + { "sys", rp::type_kind::i32 }, + }, rp::type_kind::i32, "" }, + }; + ok = ok && rp::validate(collision).has_value(); + const auto collision_bridge = rp::render_ctypes_bridge(collision); + const auto collision_wrapper = rp::render_ctypes_wrapper(collision); + ok = ok && collision_bridge.find("acme_collide") != std::string::npos + && collision_bridge.find("_mcpp_p0") != std::string::npos + && collision_bridge.find("_mcpp_p3") != std::string::npos + && collision_wrapper.find("import ctypes as _mcpp_ctypes") != std::string::npos + && collision_wrapper.find("import builtins as _mcpp_builtins") != std::string::npos + && collision_wrapper.find("_mcpp_builtins.len") != std::string::npos + && collision_wrapper.find("_mcpp_ctypes.c_int32") != std::string::npos + && collision_wrapper.find("_load_library(\"collision_core\")") != std::string::npos + // Deployed two directories below the artifact, the wrapper + // searches the directories that lead back to the library. + && collision_wrapper.find("_HERE / \"..\" / \"..\"") != std::string::npos; + collision.deploy_to = "../outside"; + ok = ok && !rp::validate(collision).has_value(); + collision.deploy_to = "pkg"; + collision.functions[0].params[0].name = "class"; + ok = ok && !rp::validate(collision).has_value(); + collision.functions[0].params[0].name = "template"; + ok = ok && !rp::validate(collision).has_value(); + collision.functions[0].params[0].name = "len"; + collision.functions[0].name = "return"; + ok = ok && !rp::validate(collision).has_value(); + + // Every stated option is part of the plan-time contract. + rp::options manual; + manual.mode = rp::binding::nanobind; + manual.python_env = rp::env::none; + manual.surface = rp::discovery::manual; + manual.module_name = "probe"; + manual.manual_entry = "entry.cpp"; + ok = ok && rp::validate(manual).has_value(); + ok = ok && rp::render_nanobind_entry(manual).empty(); + manual.manual_entry.clear(); + ok = ok && !rp::validate(manual).has_value(); + + rp::options cross = listed; + cross.python_env = rp::env::none; + cross.python_include_dir = "/opt/python/include/python3.13"; + cross.ext_suffix = ".cpython-313-x86_64-linux-gnu.so"; + ok = ok && rp::validate(cross).has_value(); + + rp::options stubbed = listed; + stubbed.import_stl = false; + stubbed.emit_stub = false; + ok = ok && rp::validate(stubbed).has_value(); + const auto stubbed_entry = rp::render_nanobind_entry(stubbed); + ok = ok && stubbed_entry.find("mcpplibs.mwrap.nanobind.stl") == std::string::npos; + + rp::options invalid = listed; + invalid.module_name = "1bad"; + ok = ok && !rp::validate(invalid).has_value(); + invalid = listed; + invalid.ext_suffix = "so"; + ok = ok && !rp::validate(invalid).has_value(); + + // A stated interpreter is resolved once and is never replaced by the + // shared environment, xim:python, uv or PATH when it fails. There is + // no request pass: `rules-python` never asks for `xim:python`. + rp::options explicit_bad = listed; + explicit_bad.python_env = rp::env::auto_; + explicit_bad.python = mcpp::plugins::tool::program("/definitely/not/a/python"); + explicit_bad.register_with_build = false; + const auto explicit_out = rp::emit(explicit_bad); + ok = ok && !explicit_out.ok; + + // Headers-only cross compilation writes its files, runs no + // interpreter and registers nothing. + const std::string fake_include = + std::string(mcpp::out_dir()) + "/fake-python/include"; + std::error_code fake_ec; + std::filesystem::create_directories(fake_include, fake_ec); + std::ofstream(fake_include + "/Python.h") << "/* a stub for emit() */\n"; + rp::options headers = listed; + headers.module_name = "headers_only"; + headers.python_include_dir = fake_include; + headers.ext_suffix = ".cpython-313-x86_64-linux-gnu.so"; + headers.register_with_build = false; + headers.emit_stub = false; + const auto headers_out = rp::emit(headers); + ok = ok && headers_out.ok + && headers_out.python_executable.empty() + && headers_out.python_include_dir == fake_include + && !headers_out.entry_cpp.empty() + && headers_out.python_file.empty() + && headers_out.extension_file.empty(); + + // The CI precedence step states both a shared pair and a distinct + // explicit pair. An explicit pair wins; a failing stated interpreter + // does not fall back to the shared one. A second run states only a + // failing `MCPP_PYTHON_EXECUTABLE`, which must be refused rather than + // replaced by xim:python, uv or PATH. + if (const char* flag = std::getenv("MCPP_TEST_PYTHON_PRECEDENCE"); flag && *flag) { + if (const char* stated = std::getenv("MCPP_TEST_PYTHON_INCLUDE_DIR"); stated && *stated) { + const char* shared_include = std::getenv("MCPP_PYTHON_INCLUDE_DIR"); + if (shared_include && *shared_include) { + rp::options shared = listed; + shared.python_env = rp::env::auto_; + shared.python_include_dir = stated; + shared.ext_suffix = ".cpython-313-x86_64-linux-gnu.so"; + shared.register_with_build = false; + const auto shared_out = rp::emit(shared); + ok = ok && shared_out.ok + && shared_out.python_include_dir == stated; + + rp::options refused = listed; + refused.python_env = rp::env::auto_; + refused.python = mcpp::plugins::tool::program("/definitely/not/a/python"); + refused.register_with_build = false; + const auto refused_out = rp::emit(refused); + ok = ok && !refused_out.ok; + + // With no stated option, the shared pair is headers-only: + // it must succeed without an interpreter. + rp::options from_env = listed; + from_env.python_env = rp::env::auto_; + from_env.register_with_build = false; + const auto from_env_out = rp::emit(from_env); + ok = ok && from_env_out.ok + && from_env_out.python_executable.empty() + && from_env_out.python_include_dir == shared_include; + } + } + } + if (const char* strict = std::getenv("MCPP_TEST_PYTHON_STRICT_ENV"); strict && *strict) { + rp::options from_env = listed; + from_env.python_env = rp::env::auto_; + from_env.register_with_build = false; + ok = ok && !rp::emit(from_env).ok; + } + } // And of the step programs: what the backend renders, which writes // nothing itself. A value keeps its space and semicolon, and a list built // when the step runs follows the command's own arguments. diff --git a/tests/all-rules-compile/mcpp.toml b/tests/all-rules-compile/mcpp.toml index 07683c9..10df761 100644 --- a/tests/all-rules-compile/mcpp.toml +++ b/tests/all-rules-compile/mcpp.toml @@ -40,7 +40,7 @@ import_std = true [build-dependencies.mcpp] plugins = { path = "../..", features = [ "rules-ascendc", "rules-cuda", "rules-hip", "rules-metal", "rules-qt", "rules-qml", "rules-slang", - "rules-spirv", "rules-swift", "rules-sycl", + "rules-spirv", "rules-swift", "rules-sycl", "rules-python", "tools-embed", "tools-island", "tools-steps", "dist-appimage", "dist-wix", "dist-apple", "dist-web", "dist-apk", "dist-apk-kotlin", "dist-apk-maven", "dist-linux-package", "dist-deb", "dist-rpm", diff --git a/tests/python-consumer/build.mcpp b/tests/python-consumer/build.mcpp new file mode 100644 index 0000000..2279ab2 --- /dev/null +++ b/tests/python-consumer/build.mcpp @@ -0,0 +1,46 @@ +// Fixture build program: one declaration per Python function. +// +// The declaration is the only place a signature is stated for the boundary; +// the plugin renders both the C++ glue and `mathlib.py` from it. The C++ +// module is not named here beyond `cpp_module`, because it is not changed: +// `src/mathlib.cppm` is an ordinary module. +import std; +import mcpp; +import mcpp.rules.python; + +namespace py = mcpp::rules::python; + +int main() { + py::options opt; + opt.mode = py::binding::ctypes; + opt.python_env = py::env::none; + opt.module_name = "mathlib"; + opt.cpp_module = "mathlib"; + opt.cpp_namespace = "mathlib"; + + opt.functions = { + { "add", "", { { "a", py::type_kind::i32 }, { "b", py::type_kind::i32 } }, + py::type_kind::i32, "Return the \"sum\"" }, + { "mul_i64", "", { { "a", py::type_kind::i64 }, { "b", py::type_kind::i64 } }, + py::type_kind::i64, "Multiply two 64-bit integers." }, + { "hypotenuse", "", { { "a", py::type_kind::f64 }, { "b", py::type_kind::f64 } }, + py::type_kind::f64, "The hypotenuse of a right triangle." }, + { "is_even", "", { { "n", py::type_kind::i32 } }, + py::type_kind::bool_, "Whether an integer is even." }, + { "toggle", "", { { "value", py::type_kind::bool_ } }, + py::type_kind::bool_, "The boolean negation of the argument." }, + { "greet", "", { { "name", py::type_kind::string } }, + py::type_kind::string, "Greet a name (UTF-8)." }, + { "join", "", { { "a", py::type_kind::string }, { "b", py::type_kind::string } }, + py::type_kind::string, "Concatenate two UTF-8 strings." }, + { "noop", "", {}, py::type_kind::void_, "Does nothing." }, + { "checked_div", "", { { "a", py::type_kind::i32 }, { "b", py::type_kind::i32 } }, + py::type_kind::i32, "Divide, returning 0 when the divisor is 0." }, + }; + + const auto out = py::emit(opt); + if (!out.ok) return 1; + // The default prefix is part of the contract the generated .py names. + if (out.symbol_prefix != "mcpp_py_mathlib_") return 1; + return 0; +} diff --git a/tests/python-consumer/cpp-app/mcpp.toml b/tests/python-consumer/cpp-app/mcpp.toml new file mode 100644 index 0000000..3ffc004 --- /dev/null +++ b/tests/python-consumer/cpp-app/mcpp.toml @@ -0,0 +1,26 @@ +# Fixture: the C++ side of `tests/python-consumer`, unchanged. +# +# It imports the same module a Python program reaches through the generated +# glue and links the same shared library. That the source below has no FFI +# trace is the property the plugin promises. +[package] +name = "cpp-app" +namespace = "example" +version = "0.1.0" +description = "Fixture: an ordinary C++23 consumer of the module Python reaches" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = true + +[targets.cpp-app] +kind = "bin" +main = "src/main.cpp" + +# `linkage = "shared"` on the edge matches the library's `kind = "shared"`: +# the program loads the same image Python does. +[dependencies.example] +mathlib = { path = "../", linkage = "shared" } diff --git a/tests/python-consumer/cpp-app/src/main.cpp b/tests/python-consumer/cpp-app/src/main.cpp new file mode 100644 index 0000000..2acd75c --- /dev/null +++ b/tests/python-consumer/cpp-app/src/main.cpp @@ -0,0 +1,21 @@ +// Fixture: the C++ consumer of `mathlib`, with no FFI in sight. +// +// It imports the module directly and links the shared library the Python +// wrapper also loads. Every assertion below is about the module's own +// interface, so a regression in the generated glue cannot hide behind it. +import std; +import mathlib; + +int main() { + if (mathlib::add(17, 25) != 42) return 1; + if (mathlib::mul_i64(1'000'000'000'000LL, 3) != 3'000'000'000'000LL) return 2; + if (std::abs(mathlib::hypotenuse(3.0, 4.0) - 5.0) > 1e-12) return 3; + if (!mathlib::is_even(42)) return 4; + if (mathlib::is_even(41)) return 5; + if (mathlib::toggle(true) != false) return 6; + if (mathlib::greet("mcpp") != "Hello, mcpp!") return 7; + if (mathlib::join("a", "b") != "ab") return 8; + mathlib::noop(); + std::cout << "cpp-app ok\n"; + return 0; +} diff --git a/tests/python-consumer/mcpp.toml b/tests/python-consumer/mcpp.toml new file mode 100644 index 0000000..376265f --- /dev/null +++ b/tests/python-consumer/mcpp.toml @@ -0,0 +1,31 @@ +# Fixture: `mcpp.rules.python`'s ctypes backend end to end, with no Python +# build dependency. +# +# `src/mathlib.cppm` is an ordinary C++23 module; `build.mcpp` declares the +# Python-facing functions once, and the plugin writes the `extern "C"` glue +# and `mathlib.py`. The library is built SHARED because Python loads it with +# `dlopen`; nothing about that changes the module a C++ consumer imports. +[package] +name = "mathlib" +namespace = "example" +version = "0.1.0" +description = "Fixture: a C++23 module reached from Python through generated ctypes glue" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = true + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-python"] } + +[build] +sources = ["src/*.cppm"] + +# `kind = "shared"` rather than `kind = "lib"`: the artifact has to be a real +# `libmathlib.so`/`mathlib.dll` for `ctypes` to load, and it must be the one +# image in the process, which `kind = "shared"` states. +[targets.mathlib] +kind = "shared" diff --git a/tests/python-consumer/src/mathlib.cppm b/tests/python-consumer/src/mathlib.cppm new file mode 100644 index 0000000..72559f1 --- /dev/null +++ b/tests/python-consumer/src/mathlib.cppm @@ -0,0 +1,64 @@ +// Fixture: a plain C++23 module reached from Python through +// `mcpp.rules.python` (binding::ctypes). +// +// THE LIBRARY ITSELF IS THE ORDINARY ONE. Nothing in this file is for the +// FFI: no macro, no annotation, no Python header, no `extern "C"`. The +// generated glue imports this module and calls its exported functions, and +// `cpp-app/` imports it directly. That is the claim the fixture makes, and +// `ci.yml` greps this file for FFI traces to keep it true. +export module mathlib; + +import std; + +export namespace mathlib { + +// i32 in, i32 out. +inline std::int32_t add(std::int32_t a, std::int32_t b) { + return a + b; +} + +// i64 in, i64 out: the width that is a different C type on Windows. +inline std::int64_t mul_i64(std::int64_t a, std::int64_t b) { + return a * b; +} + +// f64 in, f64 out. +inline double hypotenuse(double a, double b) { + return std::sqrt(a * a + b * b); +} + +// bool out. +inline bool is_even(std::int32_t n) { + return n % 2 == 0; +} + +// bool in, bool out. +inline bool toggle(bool value) { + return !value; +} + +// string_view in (the borrowed form), string out (the allocated form). +inline std::string greet(std::string_view name) { + std::string out = "Hello, "; + out += name; + out += "!"; + return out; +} + +// string in by value, twice, so two parameters are expanded in one call. +inline std::string join(std::string a, std::string b) { + return a + b; +} + +// void return, and no parameters. +inline void noop() {} + +// Throws inside the library, never at the boundary. The generated `ctypes` +// glue catches it at the `extern "C"` edge and returns the zero sentinel, which +// is the documented contract for this backend. +inline std::int32_t checked_div(std::int32_t a, std::int32_t b) { + if (b == 0) throw std::domain_error("division by zero"); + return a / b; +} + +} // namespace mathlib diff --git a/tests/python-nanobind-consumer/build.mcpp b/tests/python-nanobind-consumer/build.mcpp new file mode 100644 index 0000000..d6e219c --- /dev/null +++ b/tests/python-nanobind-consumer/build.mcpp @@ -0,0 +1,35 @@ +// Fixture build program: the explicit export list, no changes to the module. +import std; +import mcpp; +import mcpp.rules.python; + +namespace py = mcpp::rules::python; + +int main() { + py::options opt; + opt.mode = py::binding::nanobind; + opt.python_env = py::env::auto_; + opt.surface = py::discovery::explicit_list; + opt.module_name = "fast_ops"; + opt.cpp_module = "fast_ops"; + opt.cpp_namespace = "fast_ops"; + + opt.exports = { + { "add", "", "Add two integers.", { "a", "b" } }, + { "mul", "", "Multiply two doubles.", { "a", "b" } }, + { "is_even", "", "Whether an integer is even.", { "n" } }, + { "greet", "", "Greet a name (UTF-8).", { "name" } }, + { "doubled", "", "Double every element of a list.", { "values" } }, + { "raise_if_negative", "", "Raise ValueError for a negative value.", { "value" } }, + }; + + const auto out = py::emit(opt); + if (!out.ok) return 1; + // The project declares `[xlings.workspace] "xim:python"`; this rule reads + // that payload and never requests one itself, so there is no request pass + // and no `pending` pass to return from. + if (out.extension_file.empty()) return 1; + if (out.python_file.empty()) return 1; + std::cout << out.extension_file << "\n" << out.python_file << "\n"; + return 0; +} diff --git a/tests/python-nanobind-consumer/mcpp.toml b/tests/python-nanobind-consumer/mcpp.toml new file mode 100644 index 0000000..4e8cd23 --- /dev/null +++ b/tests/python-nanobind-consumer/mcpp.toml @@ -0,0 +1,40 @@ +# Fixture: `mcpp.rules.python`'s nanobind backend, end to end. +# +# `src/fast_ops.cppm` is an ordinary C++23 module. `build.mcpp` states the +# exports once; the rule writes the NB_MODULE entry, adds the Python SDK's +# include directory, and copies the linked shared library to the interpreter's +# EXT_SUFFIX in the staging directory. The dependency's runtime feature compiles +# nanobind's one runtime translation unit. +[package] +name = "fast-ops" +namespace = "example" +version = "0.1.0" +description = "Fixture: a C++23 module bound as a native CPython extension through mcpp.rules.python" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++23" +modules = true +import_std = true + +[dependencies] +mcpplibs.mwrap.nanobind = "3.1.0" + +# The Python SDK is the project's declaration: this rule reads the +# payload the graph installed and never requests one itself. A +# nanobind-m release with the `python-sdk` feature supplies the same +# default; a nearer statement here keeps the fixture self-contained. +[xlings.workspace] +"xim:python" = "3.13.12" + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-python"] } + +[build] +sources = ["src/*.cppm"] + +# The extension is linked as an ordinary shared library; the rule's artifact +# action copies it to `fast_ops`. +[targets.fast_ops] +kind = "shared" diff --git a/tests/python-nanobind-consumer/src/fast-ops.cppm b/tests/python-nanobind-consumer/src/fast-ops.cppm new file mode 100644 index 0000000..402edc0 --- /dev/null +++ b/tests/python-nanobind-consumer/src/fast-ops.cppm @@ -0,0 +1,40 @@ +export module fast_ops; + +import std; + +// A zero-intrusion C++23 module: no Python header, no marker macro, no +// visibility attribute, no include. The same functions are importable from C++ +// and bound by mcpp.rules.python's nanobind backend. +export namespace fast_ops { + +inline int add(int a, int b) { return a + b; } + +inline double mul(double a, double b) { return a * b; } + +inline bool is_even(int n) { return n % 2 == 0; } + +inline std::string greet(std::string_view name) { + std::string out = "Hello, "; + out += name; + out += "!"; + return out; +} + +inline std::vector doubled(std::vector values) { + for (auto& value : values) value *= 2; + return values; +} + +// nanobind turns a std::exception-derived error into a Python exception at the +// boundary; the module itself knows nothing about Python. +// +// DELIBERATELY NOT INLINE. On Windows, Clang 23 + MSVC with `import std` and a +// mixed entry TU (Python.h before the module imports) inline this throw and its +// exception machinery into the consumer, and the process dies with 0xC0000374 +// (heap corruption). One out-of-line definition keeps the unwind path in the +// module's own object file, where the mixed TU never sees it. +void raise_if_negative(int value) { + if (value < 0) throw std::invalid_argument("negative value"); +} + +} // namespace fast_ops diff --git a/tests/python-nanobind-consumer/verify.py b/tests/python-nanobind-consumer/verify.py new file mode 100644 index 0000000..982c956 --- /dev/null +++ b/tests/python-nanobind-consumer/verify.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Import the extension the fixture built and assert the bound surface.""" +import pathlib +import sys + +stage = pathlib.Path(sys.argv[1]) +sys.path.insert(0, str(stage)) + +import fast_ops + +assert fast_ops.add(17, 25) == 42 +assert fast_ops.mul(2.5, 4.0) == 10.0 +assert fast_ops.is_even(42) is True +assert fast_ops.is_even(41) is False +assert fast_ops.greet("mcpp") == "Hello, mcpp!" +assert fast_ops.doubled([1, 2, 3]) == [2, 4, 6] + +try: + fast_ops.raise_if_negative(-1) +except Exception as exc: + assert isinstance(exc, (ValueError, RuntimeError)), type(exc) +else: + raise AssertionError("a negative value did not raise") + +print("python-nanobind-consumer ok") diff --git a/tests/python-reflect-consumer/build.mcpp b/tests/python-reflect-consumer/build.mcpp new file mode 100644 index 0000000..7e5a8c2 --- /dev/null +++ b/tests/python-reflect-consumer/build.mcpp @@ -0,0 +1,28 @@ +// Fixture build program: no export list at all. `discovery::reflect` walks the +// exported namespace of `fast_ops` and binds each free function. +import std; +import mcpp; +import mcpp.rules.python; + +namespace py = mcpp::rules::python; + +int main() { + py::options opt; + opt.mode = py::binding::nanobind; + opt.python_env = py::env::auto_; + opt.surface = py::discovery::reflect; + opt.module_name = "fast_ops"; + opt.cpp_module = "fast_ops"; + // cpp_namespace is deliberately empty: the rule derives `fast_ops` from + // the C++ module's final segment. + + const auto out = py::emit(opt); + if (!out.ok) return 1; + // The SDK comes from the graph, through `mcpplibs.mwrap.nanobind`; this + // rule never requests `xim:python` itself. + if (out.extension_file.empty()) return 1; + // A reflected surface states no export names, so no .pyi is generated. + if (!out.python_file.empty()) return 1; + std::cout << out.extension_file << "\n"; + return 0; +} diff --git a/tests/python-reflect-consumer/mcpp.toml b/tests/python-reflect-consumer/mcpp.toml new file mode 100644 index 0000000..4189f94 --- /dev/null +++ b/tests/python-reflect-consumer/mcpp.toml @@ -0,0 +1,37 @@ +# Fixture: `mcpp.rules.python`'s reflection discovery, end to end, on GCC 16. +# +# No export list is stated. The generated py_entry.cpp walks +# `std::meta::members_of(^^fast_ops)` and binds every exported free function. +# The C++26 standard is what GCC 16 needs for P2996; the rule adds +# `-freflection` while planning. +[package] +name = "fast-ops-reflect" +namespace = "example" +version = "0.1.0" +description = "Fixture: a C++23 module reflected into a CPython extension by mcpp.rules.python" +license = "Apache-2.0" +authors = ["mcpp-community"] + +[language] +standard = "c++26" +modules = true +import_std = true + +[dependencies] +mcpplibs.mwrap.nanobind = "3.1.0" + +# The Python SDK is the project's declaration: this rule reads the +# payload the graph installed and never requests one itself. A +# nanobind-m release with the `python-sdk` feature supplies the same +# default; a nearer statement here keeps the fixture self-contained. +[xlings.workspace] +"xim:python" = "3.13.12" + +[build-dependencies.mcpp] +plugins = { path = "../..", features = ["rules-python"] } + +[build] +sources = ["src/*.cppm"] + +[targets.fast_ops] +kind = "shared" diff --git a/tests/python-reflect-consumer/src/fast-ops-reflect.cppm b/tests/python-reflect-consumer/src/fast-ops-reflect.cppm new file mode 100644 index 0000000..c5cb72e --- /dev/null +++ b/tests/python-reflect-consumer/src/fast-ops-reflect.cppm @@ -0,0 +1,32 @@ +export module fast_ops; + +import std; + +// The same zero-intrusion module as the explicit_list fixture. Nothing here +// names Python, nanobind or reflection; the binding is entirely the consumer's +// generated entry. +export namespace fast_ops { + +inline int add(int a, int b) { return a + b; } + +inline double mul(double a, double b) { return a * b; } + +inline bool is_even(int n) { return n % 2 == 0; } + +inline std::string greet(std::string_view name) { + std::string out = "Hello, "; + out += name; + out += "!"; + return out; +} + +inline std::vector doubled(std::vector values) { + for (auto& value : values) value *= 2; + return values; +} + +inline void raise_if_negative(int value) { + if (value < 0) throw std::invalid_argument("negative value"); +} + +} // namespace fast_ops diff --git a/tests/python-reflect-consumer/verify.py b/tests/python-reflect-consumer/verify.py new file mode 100644 index 0000000..2e0e874 --- /dev/null +++ b/tests/python-reflect-consumer/verify.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Import the reflected extension and assert the automatically bound surface.""" +import pathlib +import sys + +stage = pathlib.Path(sys.argv[1]) +sys.path.insert(0, str(stage)) + +import fast_ops + +assert fast_ops.add(17, 25) == 42 +assert fast_ops.mul(2.5, 4.0) == 10.0 +assert fast_ops.is_even(42) is True +assert fast_ops.is_even(41) is False +assert fast_ops.greet("mcpp") == "Hello, mcpp!" +assert fast_ops.doubled([1, 2, 3]) == [2, 4, 6] + +try: + fast_ops.raise_if_negative(-1) +except Exception as exc: + assert isinstance(exc, (ValueError, RuntimeError)), type(exc) +else: + raise AssertionError("a negative value did not raise") + +print("python-reflect-consumer ok")