diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3d75a70 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# Preserve upstream document bytes and original whitespace on every platform. +upstream/** -text -whitespace +# Keep the release archive free of local planning material. +.local/** export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8495255 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,96 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + mcpp: + name: mcpp (${{ matrix.os }}, ${{ matrix.toolchain }}) + strategy: + fail-fast: false + matrix: + include: + - { os: ubuntu-24.04, toolchain: 'gcc@16.1.0' } + - { os: ubuntu-24.04, toolchain: 'llvm@23.1.3' } + - { os: macos-15, toolchain: 'llvm@23.1.3' } + - { os: windows-2025, toolchain: 'llvm@23.1.3' } + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + defaults: + run: + shell: bash + env: + XLINGS_NON_INTERACTIVE: 1 + steps: + - uses: actions/checkout@v4 + + - name: Configure MCPP_HOME + run: echo "MCPP_HOME=${{ runner.temp }}/mcpp-home" >> "$GITHUB_ENV" + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Retained upstream document bytes + run: python3 tools/check_documents.py + + - name: Install Xlings (Linux/macOS) + if: runner.os != 'Windows' + run: | + curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/refs/heads/main/tools/other/quick_install.sh | bash + echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH" + + - name: Install Xlings (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + irm https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.ps1 | iex + "$env:USERPROFILE\.xlings\subos\current\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Install project tools (.xlings.json) + run: | + for attempt in 1 2 3; do + xlings update > /dev/null 2>&1 || true + if xlings install && (cd "$RUNNER_TEMP" && xlings install xim:mcpp@2026.11.22.1); then break; fi + [ "$attempt" = 3 ] && exit 1 + sleep 30 + done + (cd "$RUNNER_TEMP" && mcpp --version) + + - name: Select the toolchain + run: | + name="${{ matrix.toolchain }}" + mcpp toolchain install "${name%@*}" "${name#*@}" + mcpp toolchain default "$name" + + # compat.nanobind is supplied by PR 1. Once it is published this step is + # a no-op refresh of the same complete index. + - name: Candidate built-in index (compat.nanobind) + run: | + mcpp self init --home "$MCPP_HOME" || true + git clone --depth 1 https://github.com/mcpplibs/mcpp-index.git "$RUNNER_TEMP/mcpp-index" + python3 "$RUNNER_TEMP/mcpp-index/tests/prepare_builtin_index.py" --home "$MCPP_HOME" + sed -i 's/auto_refresh = true/auto_refresh = false/' "$MCPP_HOME/config.toml" || true + + - name: Build the modules + run: mcpp build --strict + + - name: Tests (core, side header, ndarray, operators, macros) + run: mcpp test + + - name: Tests, release profile + run: mcpp test --profile release + + - name: Installed template (mcpp new, --strict build, run) + run: python3 tools/test_template.py --index "$RUNNER_TEMP/mcpp-index" --toolchain "${{ matrix.toolchain }}" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba54d39 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +target/ +.mcpp/ +.xlings/ +mcpp.lock +compile_commands.json +__pycache__/ diff --git a/.xlings.json b/.xlings.json new file mode 100644 index 0000000..1af4f32 --- /dev/null +++ b/.xlings.json @@ -0,0 +1,5 @@ +{ + "workspace": { + "xim:mcpp": "2026.11.22.1" + } +} diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..5496653 --- /dev/null +++ b/NOTICE @@ -0,0 +1,17 @@ +nanobind-m: C++ module wrapper +Copyright (c) 2026 mcpp-community contributors + +The wrapper contributions are licensed under the Apache License, Version 2.0. +Upstream code, copied interfaces and dependencies retain their original +licenses and copyright notices. + +nanobind is Copyright (c) 2022 Wenzel Jakob and is distributed under the +BSD-3-Clause license. Its original README and LICENSE are retained byte for +byte in upstream/nanobind/. The implementation is built by compat.nanobind +from the same v3.1.0 release. + +compat.nanobind reaches its hash map through compat.robin-map, Copyright (c) +2018 Thibaut Goetghebuer-Planchon, distributed under the MIT license. + +Provenance and SHA256 checksums of the retained upstream documents are +recorded in upstream/documents.json. diff --git a/README.md b/README.md index 46e9344..4683a9a 100644 --- a/README.md +++ b/README.md @@ -1 +1,116 @@ -# nanobind-m \ No newline at end of file +# nanobind-m + +> nanobind 3.1.0 as C++23 modules: bind C++ to Python with no boilerplate headers to arrange. + +English · [简体中文](README.zh.md) · [Upstream](https://github.com/wjakob/nanobind) · [Releases](https://github.com/mcpplibs/nanobind-m/releases) · [mcpp](https://github.com/mcpp-community/mcpp) · [Index](https://github.com/mcpplibs/mcpp-index) + +[![CI](https://github.com/mcpplibs/nanobind-m/actions/workflows/ci.yml/badge.svg)](https://github.com/mcpplibs/nanobind-m/actions/workflows/ci.yml) +[![Wrapper license](https://img.shields.io/badge/wrapper-Apache--2.0-blue)](LICENSE) +[![Upstream license](https://img.shields.io/badge/nanobind-BSD--3--Clause-blue)](upstream/nanobind/LICENSE) + +This is a thin wrapper around [nanobind](https://github.com/wjakob/nanobind) +v3.1.0. The header API is exported unchanged: `import +mcpplibs.mwrap.nanobind;` gives you `nb::class_`, `nb::def`, `nb::cast`, the +exception types and the object wrappers, while the STL, ndarray and operator +helpers live in submodules. The implementation comes from `compat.nanobind` +3.1.0; no upstream C++ source is vendored here. + +The module interface and the runtime are compiled against the Python SDK on +``'s include path. That must be the same Python ABI the bindings run +in — version, free-threaded configuration and `Py_LIMITED_API`. The manifest +declares `xim:python` 3.13.12 as the default; a consumer's own declaration, or +`MCPP_PYTHON_INCLUDE_DIR`, takes precedence (see [Usage and API](docs/usage.md)). + +## Modules + +- `import mcpplibs.mwrap.nanobind;`: handles, objects, classes, functions, casts, exceptions and utilities. +- `import mcpplibs.mwrap.nanobind.stl;`: casters for `std::string`, containers, `std::optional`, `std::variant`, `std::function`, smart pointers, filesystem and chrono. +- `import mcpplibs.mwrap.nanobind.ndarray;`: `nb::ndarray`, DLPack types, device/order/framework tags and `nb::dtype`. +- `import mcpplibs.mwrap.nanobind.operators;`: `nb::self` and operator-binding helpers. +- `import mcpplibs.mwrap.nanobind.macros;`: `NB_VERSION_*` as `inline constexpr` constants. + +> More Modules API -> [Usage and API](docs/usage.md) + +`NB_MODULE`, `NB_TRAMPOLINE`, `NB_OVERRIDE*` and `NB_MAKE_OPAQUE` are macros and +cannot be exported by a named module. Include +`` **before** every import in that translation unit: + +```cpp +#include // first +import mcpplibs.mwrap.nanobind; // then +import mcpplibs.mwrap.nanobind.stl; +``` + +## Getting started + +A new project uses the default template: + +```sh +mcpp new pybind --template mcpplibs.mwrap.nanobind@3.1.0 +cd pybind +mcpp run +``` + +The generated program builds a Python module with `NB_MODULE`, registers it +with `PyImport_AppendInittab`, and imports it from the embedded interpreter. + +In an existing project: + +```toml +[dependencies] +mcpplibs.mwrap.nanobind = "3.1.0" + +[xlings.workspace] +"xim:python" = "3.13.12" +``` + +```cpp +#include + +import std; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.stl; + +using namespace nanobind::literals; + +NB_MODULE(example, m) { + m.def("add", [](int a, int b) { return a + b; }, "a"_a, "b"_a); +} +``` + +`xim:python` is the SDK used for both the module interface and the runtime. +If your application gets Python from `uv`, a virtual environment, or a custom +build, set `MCPP_PYTHON_INCLUDE_DIR` (and `MCPP_PYTHON_HOME` at run time for +an embedded interpreter). A system Python needs its development package. + +### Features + +| Feature | Default | Effect | +|---|---|---| +| `runtime` | yes | Compiles `src/nb_runtime.cpp` from compat.nanobind's forwarder, so one link of the module is enough. | +| `tests` | no | Links the Python embedding library into this package's own test executables only. | + +To supply the runtime yourself (for example with `NB_SHARED` or a custom +`Py_LIMITED_API` build), disable defaults: + +```toml +mcpplibs.mwrap.nanobind = { version = "3.1.0", default-features = false } +``` + +Then compile `` in exactly one translation unit of +your program, as `compat.nanobind` documents. + +## Platforms + +Linux (GCC 16, LLVM 23), macOS (LLVM 23) and Windows (LLVM 23) are covered by +CI. Linux CPython extension modules must not link `libpython`; this package +never adds that link to a consumer. The embedded test executables and the +default template do link it, because they host an interpreter themselves. + +## License + +The wrapper is Apache-2.0; see [LICENSE](LICENSE) and the attribution in +[NOTICE](NOTICE). Upstream nanobind remains BSD-3-Clause: its original +[LICENSE](upstream/nanobind/LICENSE) and [README](upstream/nanobind/README.md) +are retained byte for byte, with checksums in +[upstream/documents.json](upstream/documents.json). diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..40b6a0e --- /dev/null +++ b/README.zh.md @@ -0,0 +1,110 @@ +# nanobind-m + +> 将 nanobind 3.1.0 提供为 C++23 模块:用 Python 绑定 C++,无需安排样板头文件。 + +[English](README.md) · 简体中文 · [上游](https://github.com/wjakob/nanobind) · [发布](https://github.com/mcpplibs/nanobind-m/releases) · [mcpp](https://github.com/mcpp-community/mcpp) · [索引](https://github.com/mcpplibs/mcpp-index) + +[![CI](https://github.com/mcpplibs/nanobind-m/actions/workflows/ci.yml/badge.svg)](https://github.com/mcpplibs/nanobind-m/actions/workflows/ci.yml) +[![封装许可证](https://img.shields.io/badge/wrapper-Apache--2.0-blue)](LICENSE) +[![上游许可证](https://img.shields.io/badge/nanobind-BSD--3--Clause-blue)](upstream/nanobind/LICENSE) + +这是 [nanobind](https://github.com/wjakob/nanobind) v3.1.0 的薄封装。头文件 +API 原样导出:`import mcpplibs.mwrap.nanobind;` 即得到 `nb::class_`、 +`nb::def`、`nb::cast`、异常类型和对象包装;STL、ndarray 与运算符辅助位于 +子模块。实现来自 `compat.nanobind` 3.1.0,本仓库不 vendor 上游 C++ 源码。 + +模块接口与运行时都针对 `` 所在目录里的 Python SDK 编译。该 SDK +必须与绑定实际运行的 Python ABI 一致——版本、free-threaded 配置和 +`Py_LIMITED_API`。清单默认声明 `xim:python` 3.13.12;消费方自己的声明或 +`MCPP_PYTHON_INCLUDE_DIR` 优先(见[用法与 API](docs/usage.md))。 + +## 模块 + +- `import mcpplibs.mwrap.nanobind;`:句柄、对象、类、函数、转换、异常与工具。 +- `import mcpplibs.mwrap.nanobind.stl;`:`std::string`、容器、`std::optional`、`std::variant`、`std::function`、智能指针、filesystem 与 chrono 的 caster。 +- `import mcpplibs.mwrap.nanobind.ndarray;`:`nb::ndarray`、DLPack 类型、设备/顺序/框架标签和 `nb::dtype`。 +- `import mcpplibs.mwrap.nanobind.operators;`:`nb::self` 与运算符绑定辅助。 +- `import mcpplibs.mwrap.nanobind.macros;`:以 `inline constexpr` 导出的 `NB_VERSION_*` 常量。 + +> 更多模块 API -> [用法与 API](docs/usage.md) + +`NB_MODULE`、`NB_TRAMPOLINE`、`NB_OVERRIDE*` 和 `NB_MAKE_OPAQUE` 是宏,命名 +模块无法导出。在同一个翻译单元中,请把 +`` 放在**所有 import 之前**: + +```cpp +#include // 先 +import mcpplibs.mwrap.nanobind; // 后 +import mcpplibs.mwrap.nanobind.stl; +``` + +## 快速开始 + +新项目使用默认模板: + +```sh +mcpp new pybind --template mcpplibs.mwrap.nanobind@3.1.0 +cd pybind +mcpp run +``` + +生成的程序用 `NB_MODULE` 构建 Python 模块,通过 `PyImport_AppendInittab` +注册,并由同一进程内嵌的解释器导入。 + +已有项目: + +```toml +[dependencies] +mcpplibs.mwrap.nanobind = "3.1.0" + +[xlings.workspace] +"xim:python" = "3.13.12" +``` + +```cpp +#include + +import std; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.stl; + +using namespace nanobind::literals; + +NB_MODULE(example, m) { + m.def("add", [](int a, int b) { return a + b; }, "a"_a, "b"_a); +} +``` + +`xim:python` 同时用于模块接口和运行时。如果应用通过 `uv`、虚拟环境或自行 +构建的 Python 获得 SDK,请设置 `MCPP_PYTHON_INCLUDE_DIR`;内嵌解释器在运行 +时还需要 `MCPP_PYTHON_HOME`。系统 Python 需要安装开发包。 + +### Feature + +| Feature | 默认 | 作用 | +|---|---|---| +| `runtime` | 是 | 编译 compat.nanobind 转发器对应的 `src/nb_runtime.cpp`,链接一次即可使用模块。 | +| `tests` | 否 | 只为本包自己的测试可执行文件链接 Python 嵌入库。 | + +若要自行提供运行时(例如 `NB_SHARED` 或自定义 `Py_LIMITED_API`),关闭默认 +feature: + +```toml +mcpplibs.mwrap.nanobind = { version = "3.1.0", default-features = false } +``` + +然后按 `compat.nanobind` 的说明,在程序的恰好一个翻译单元中编译 +``。 + +## 平台 + +CI 覆盖 Linux(GCC 16、LLVM 23)、macOS(LLVM 23)和 Windows(LLVM 23)。 +Linux 上的 CPython 扩展模块不得链接 `libpython`;本包绝不会给消费方添加这条 +链接。内嵌测试可执行文件和默认模板会链接它,因为它们自己承载解释器。 + +## 许可证 + +封装采用 Apache-2.0;见 [LICENSE](LICENSE) 与 [NOTICE](NOTICE) 中的署名。 +上游 nanobind 仍为 BSD-3-Clause:原始 +[LICENSE](upstream/nanobind/LICENSE) 与 [README](upstream/nanobind/README.md) +按字节保留,校验和记录于 [upstream/documents.json](upstream/documents.json)。 diff --git a/build.mcpp b/build.mcpp new file mode 100644 index 0000000..e423165 --- /dev/null +++ b/build.mcpp @@ -0,0 +1,296 @@ +// build.mcpp — find and, for this package's own tests, link the +// Python embedding runtime. +// +// This program never links Python into a consumer: outside the `tests` +// feature it only adds a private include directory. A Linux CPython extension +// module must not link libpython. The executable tests in tests/ are embedded +// interpreters, so those link it — behind a feature no consumer activates. +// +// Resolution order for (docs/usage.md): +// 1. MCPP_PYTHON_INCLUDE_DIR +// 2. xim:python, as declared here or by a package in the graph +// 3. MCPP_PYTHON_EXECUTABLE, VIRTUAL_ENV, then python3/python on PATH +// 4. a non-zero exit naming every way to supply it +import std; +import mcpp; + +namespace { + +namespace fs = std::filesystem; + +struct Python { + fs::path include; + fs::path home; + fs::path library_dir; + std::string library; +}; + +bool has_python_h(const fs::path& dir) { + std::error_code ec; + return fs::is_regular_file(dir / "Python.h", ec); +} + +std::string trim(std::string text) { + while (!text.empty() && (text.back() == '\n' || text.back() == '\r' || text.back() == ' ' || text.back() == '\t')) + text.pop_back(); + return text; +} + +// The payload's include/Python.h (Windows) or include/python3.*/Python.h +// (Unix and macOS), preferring the highest version by numeric minor. +int python_minor(const fs::path& directory) { + const std::string name = directory.filename().string(); + if (name.rfind("python3.", 0) != 0) + return -1; + int value = 0; + for (char c : name.substr(8)) { + if (c < '0' || c > '9') + return -1; + value = value * 10 + (c - '0'); + } + return value; +} + +std::optional include_from_root(const fs::path& root) { + if (has_python_h(root / "include")) + return root / "include"; + + std::vector candidates; + std::error_code ec; + for (fs::directory_iterator it(root / "include", ec), end; !ec && it != end; it.increment(ec)) { + const auto name = it->path().filename().string(); + if (it->is_directory() && name.rfind("python3.", 0) == 0 && has_python_h(it->path())) + candidates.push_back(it->path()); + } + if (candidates.empty()) + return std::nullopt; + std::sort(candidates.begin(), candidates.end(), [](const fs::path& a, const fs::path& b) { + return python_minor(a) > python_minor(b); // python3.13 > python3.9, numerically + }); + return candidates.front(); +} + +std::optional include_from_prefix(const fs::path& prefix) { + if (const auto found = include_from_root(prefix)) + return found; + std::error_code ec; + for (fs::directory_iterator it(prefix / "include", ec), end; !ec && it != end; it.increment(ec)) { + if (it->is_directory() && has_python_h(it->path())) + return it->path(); + } + return std::nullopt; +} + +std::optional include_from_interpreter(const fs::path& executable) { + for (const fs::path& prefix : {executable.parent_path(), executable.parent_path().parent_path()}) { + if (const auto found = include_from_prefix(prefix)) + return found; + } + return std::nullopt; +} + +std::optional interpreter_on_path() { + const bool is_windows = std::string_view(mcpp::target_os()) == "windows"; + const char separator = is_windows ? ';' : ':'; + const std::vector names = is_windows + ? std::vector{"python.exe", "python3.exe"} + : std::vector{"python3", "python"}; + const char* path = std::getenv("PATH"); + if (!path) + return std::nullopt; + std::string_view text(path); + for (std::size_t begin = 0; begin <= text.size();) { + const std::size_t end = text.find(separator, begin); + const auto directory = text.substr(begin, end == std::string_view::npos ? text.size() - begin : end - begin); + for (const auto& name : names) { + std::error_code ec; + const fs::path candidate = fs::path(directory) / name; + if (fs::is_regular_file(candidate, ec)) + return candidate; + } + if (end == std::string_view::npos) + break; + begin = end + 1; + } + return std::nullopt; +} + +std::optional find_include() { + if (const char* value = std::getenv("MCPP_PYTHON_INCLUDE_DIR"); value && *value) { + const fs::path dir(value); + if (has_python_h(dir)) + return dir; + std::println(std::cerr, "nanobind-m: MCPP_PYTHON_INCLUDE_DIR={} has no Python.h", value); + } + + if (const char* value = mcpp::xpkg_dir("xim", "python"); value && *value) { + if (const auto found = include_from_root(value)) + return found; + } + + if (const char* value = std::getenv("MCPP_PYTHON_EXECUTABLE"); value && *value) { + if (const auto found = include_from_interpreter(fs::path(value))) + return found; + } + + if (const char* value = std::getenv("VIRTUAL_ENV"); value && *value) { + if (const auto found = include_from_prefix(value)) + return found; + } + + if (const auto interpreter = interpreter_on_path()) { + if (const auto found = include_from_interpreter(*interpreter)) + return found; + } + + return std::nullopt; +} + +fs::path root_of_include(const fs::path& include) { + fs::path directory = include; + if (directory.filename().string().rfind("python3.", 0) == 0) + directory = directory.parent_path(); + if (directory.filename() == "include") + directory = directory.parent_path(); + return directory; +} + +std::string version_suffix(const fs::path& include) { + const std::string name = include.filename().string(); + if (name.rfind("python3.", 0) == 0) + return name.substr(6); // "3.13" + return {}; +} + +std::string library_name(const fs::path& include, const fs::path& library_dir) { + if (const char* value = std::getenv("MCPP_PYTHON_LIBRARY"); value && *value) + return value; + + const std::string suffix = version_suffix(include); + const bool is_windows = std::string_view(mcpp::target_os()) == "windows"; + if (!suffix.empty()) { + if (!is_windows) + return "python" + suffix; + std::string compact; + for (char c : suffix) + if (c != '.') + compact.push_back(c); + return "python" + compact; + } + + // An include directory whose name does not carry the version (some + // distributions use include/ directly): ask the library directory. + std::error_code ec; + for (fs::directory_iterator it(library_dir, ec), end; !ec && it != end; it.increment(ec)) { + const std::string name = it->path().filename().string(); + if (name.rfind("libpython3.", 0) == 0) { + const auto dot = name.find('.', 11); + if (dot != std::string::npos) + return "python" + name.substr(9, dot - 9); + } + if (is_windows && it->path().extension() == ".lib") { + const std::string stem = it->path().stem().string(); + if (stem.size() > 7 && stem.rfind("python3", 0) == 0 && + std::all_of(stem.begin() + 7, stem.end(), [](char c) { return c >= '0' && c <= '9'; })) + return stem; + } + } + return {}; +} + +std::string escaped(std::string value) { + std::string out; + for (char c : value) { + if (c == '\\' || c == '"') + out.push_back('\\'); + out.push_back(c); + } + return out; +} + +void write_if_changed(const fs::path& path, const std::string& text) { + { + std::ifstream in(path, std::ios::binary); + if (in && std::string(std::istreambuf_iterator(in), {}) == text) + return; + } + std::ofstream(path, std::ios::binary | std::ios::trunc) << text; +} + +void rerun_inputs() { + for (const char* name : {"MCPP_PYTHON_INCLUDE_DIR", "MCPP_PYTHON_EXECUTABLE", "MCPP_PYTHON_HOME", + "MCPP_PYTHON_LIBRARY_DIR", "MCPP_PYTHON_LIBRARY", "VIRTUAL_ENV"}) + mcpp::rerun_if_env_changed(name); +} + +} // namespace + +int main() { + rerun_inputs(); + + const bool is_windows = std::string_view(mcpp::target_os()) == "windows"; + const std::optional include = find_include(); + if (!include) { + std::println(std::cerr, + "nanobind-m: no Python development headers found.\n" + " Declare the SDK in mcpp.toml:\n" + " [xlings.workspace]\n" + " \"xim:python\" = \"3.13.12\"\n" + " or point at an exact directory:\n" + " MCPP_PYTHON_INCLUDE_DIR=/path/to/include/python3.13 mcpp build\n" + " or point at an interpreter whose sysconfig include directory has Python.h:\n" + " MCPP_PYTHON_EXECUTABLE=/path/to/python3 mcpp build\n" + " A system Python needs its development package (python3-dev)."); + return 1; + } + + mcpp::include_dir(include->string().c_str()); + + if (!mcpp::has_feature("tests")) + return 0; + + Python python{*include, root_of_include(*include), {}, {}}; + if (const char* value = std::getenv("MCPP_PYTHON_HOME"); value && *value) + python.home = value; + if (const char* value = std::getenv("MCPP_PYTHON_LIBRARY_DIR"); value && *value) + python.library_dir = value; + + if (python.library_dir.empty()) { + if (is_windows) + python.library_dir = fs::exists(python.home / "libs") ? python.home / "libs" : python.home; + else + python.library_dir = python.home / "lib"; + } + python.library = library_name(python.include, python.library_dir); + + if (python.library.empty() || !fs::is_directory(python.library_dir)) { + std::println(std::cerr, + "nanobind-m: the embedded-Python tests need a Python library, but none was found\n" + " under {}. Set MCPP_PYTHON_LIBRARY_DIR and MCPP_PYTHON_LIBRARY.", + python.library_dir.string()); + return 1; + } + + const fs::path out = fs::path(mcpp::out_dir()) / "nanobind-tests"; + std::error_code ec; + fs::create_directories(out, ec); + write_if_changed(out / "python_sdk.h", + "#pragma once\n" + "// Written by nanobind-m's build.mcpp; private to the test configuration.\n" + "#define MCPP_PYTHON_HOME \"" + + escaped(python.home.generic_string()) + "\"\n" + + "#define MCPP_PYTHON_INCLUDE_DIR \"" + escaped(python.include.generic_string()) + "\"\n" + + "#define MCPP_PYTHON_LIBRARY \"" + escaped(python.library) + "\"\n"); + + mcpp::include_dir(out.string().c_str()); + mcpp::link_search(python.library_dir.string().c_str()); + if (is_windows) { + // python-build-standalone keeps python3XX.dll at the payload root and + // the import library in libs/. + mcpp::runtime_search_dir(python.home.string().c_str()); + } else { + mcpp::runtime_search_dir(python.library_dir.string().c_str()); + } + mcpp::link_lib(python.library.c_str()); + return 0; +} diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..363d379 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,248 @@ +# Usage and API + +`mcpplibs.mwrap.nanobind` exports nanobind 3.1.0's header API under the original +`nanobind` namespace. Submodules add the STL casters, ndarray/DLPack support, +operator helpers and the version macros. The implementation is +`compat.nanobind` 3.1.0; nothing from upstream's C++ sources is vendored. + +## Quick reference + +```toml +[dependencies] +mcpplibs.mwrap.nanobind = "3.1.0" + +[xlings.workspace] +"xim:python" = "3.13.12" +``` + +```cpp +#include // every #include first + +import std; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.stl; + +namespace nb = nanobind; +using namespace nb::literals; + +NB_MODULE(example, m) { + m.def("add", [](int a, int b) { return a + b; }, "a"_a, "b"_a); + m.def("words", [](const std::vector& words) { + return words.size(); + }); +} +``` + +## Python SDK resolution + +`build.mcpp` resolves the directory that contains `Python.h` in this order: + +1. `MCPP_PYTHON_INCLUDE_DIR`, which must contain `Python.h`. +2. `xim:python` from `[xlings.workspace]`, either this package's declaration or + one in the resolved graph. On Windows it uses `/include`; on Unix it + scans `/include/python3.*` and prefers the highest version. +3. `MCPP_PYTHON_EXECUTABLE`, then `VIRTUAL_ENV` (`bin/python3` or + `Scripts/python.exe`), then `python3` (Unix) / `python` (Windows) on `PATH`, + taking the include directory from the interpreter's prefix. +4. A non-zero configure that names the declaration, environment variables and + development-package options. + +The build adds only a private include directory. It never calls +`link_lib("python...")` for a normal build: a Linux CPython extension module +must not link `libpython`, and a dependency must not put Python on a consumer's +link line. + +The package's own tests are different. They are embedded interpreters, so the +`tests` feature (activated by `[test] features = ["tests"]`) links the Python +library and adds its run-time search directory. No consumer activates that +feature through a dependency edge. + +When the selected SDK is not a stock `xim:python` payload, these run-time +variables complete the picture: + +| Variable | Meaning | +|---|---| +| `MCPP_PYTHON_HOME` | Interpreter prefix (`PyConfig.home`). | +| `MCPP_PYTHON_LIBRARY_DIR` | Directory holding `libpython3.x.so`/`.dylib` or `python3xx.lib`. | +| `MCPP_PYTHON_LIBRARY` | Link name, for example `python3.13` or `python313`. | + +A consumer's nearer `[xlings.workspace]` entry wins over this package's default. +`MCPP_PYTHON_INCLUDE_DIR` wins over both, for `uv`, a custom build or a +`Py_LIMITED_API`/free-threaded interpreter. + +## The module surface + +`mcpplibs.mwrap.nanobind` exports the unchanged upstream entities, including: + +- Handles and objects: `handle`, `object`, `borrow`, `steal`, `none`, `ellipsis`, + `not_implemented`, `bool_`, `int_`, `float_`, `str`, `bytes`, `bytearray`, + `tuple`, `list`, `dict`, `set`, `frozenset`, `slice`, `capsule`, `module_`, + `weakref`, `memoryview`, `args`, `kwargs`, `type_object`, `type_object_t`, + `callable`, `iterable`, `iterator`, `sequence`, `mapping`, `fallback`, `typed`. +- Binding: `class_`, `enum_`, `init`, `init_implicit`, `new_`, `cpp_function`, + `def_visitor`, `arg`, `arg_v`, `scope`, `name`, `sig`, `call_guard`, + `call_policy`, `dynamic_attr`, `is_method`, `is_operator`, `is_getter`, + `is_implicit`, `is_arithmetic`, `is_flag`, `is_str`, `is_final`, `is_generic`, + `is_weak_referenceable`, `kw_only`, `lock_self`, `never_destruct`, `pooled`, + `keep_alive`, `supplement`, `intrusive_ptr`, `type_slots`, + `type_slots_callback`, `rv_policy`, `exception_type`. +- Conversion and utilities: `cast`, `try_cast`, `find`, `make_tuple`, + `isinstance`, `issubclass`, `hasattr`, `getattr`, `setattr`, `delattr`, `len`, + `repr`, `print`, `iter`, `hash`, `type`, `type_name`, `is_alive`, `globals`, + `builtins`, `register_module`, `implicitly_convertible`, the leak/implicit-cast + warning switches, `gil_scoped_acquire`, `gil_scoped_release`, `ft_mutex`, + `ft_lock_guard`, `ft_object_guard`, `ft_object2_guard` and `error_scope`. +- Exceptions: `python_error`, `builtin_exception`, `cast_error`, `exception`, + `stop_iteration`, `index_error`, `key_error`, `value_error`, `type_error`, + `buffer_error`, `import_error`, `attribute_error`, `next_overload`, `raise`, + `raise_from`, `chain_error`, `raise_type_error` and + `register_exception_translator`. +- Literals: `nanobind::literals::operator""_a` and `operator""_s`. + +The root also re-exports `mcpplibs.mwrap.nanobind.macros`, whose +`NB_VERSION_MAJOR`, `NB_VERSION_MINOR`, `NB_VERSION_PATCH` and `NB_VERSION_DEV` +are `inline constexpr` values. The real preprocessor macros remain available +through the side header. + +### STL casters + +`import mcpplibs.mwrap.nanobind.stl;` installs casters for `std::string`, +`std::string_view`, `std::wstring`, `std::vector`, `std::array`, `std::list`, +`std::set`, `std::unordered_set`, `std::map`, `std::unordered_map`, `std::pair`, +`std::tuple`, `std::optional`, `std::variant`, `std::function`, +`std::shared_ptr`, `std::unique_ptr`, `std::filesystem::path`, +`std::chrono` types and `std::complex`. No `` include is +needed in the consuming translation unit. + +The module is built by including the standard headers in its global module +fragment, then the upstream caster headers in its export block. Their include +guards make the repeated standard includes no-ops, so only nanobind's caster +specializations attach to the module. + +### ndarray and operators + +```cpp +import mcpplibs.mwrap.nanobind.ndarray; +import mcpplibs.mwrap.nanobind.operators; + +m.def("sum", [](nb::ndarray> a) { + float total = 0; + for (size_t i = 0; i < a.shape(0); ++i) total += a(i); + return total; +}); + +nb::class_(m, "Vec") + .def(nb::self + nb::self) // operator helpers + .def(nb::self == nb::self); +``` + +`ndarray.h` is not imported by the root module, so a program that never uses +arrays does not pay for DLPack declarations. `operators.h` is likewise its own +module. Clang requires the operators to be exported for argument-dependent +lookup to find them from an importing translation unit; `tests/operators.cpp` +is the audit. + +> GCC 16.1 and 16.2 ICE in `gen_enumeration_type_die` when a module-using +> translation unit *expands* one of nanobind's operator templates while debug +> info is enabled. The operators module itself builds, and the same code works +> with Clang 23 and with GCC at `-g0`. This is a GCC modules/debug-info defect, +> not an interface difference; use Clang for operator bindings until it is +> fixed upstream. + +## Include-before-import and macros + +`NB_MODULE`, `NB_TRAMPOLINE`, `NB_OVERRIDE`, `NB_OVERRIDE_NAME`, +`NB_OVERRIDE_PURE`, `NB_OVERRIDE_PURE_NAME` and `NB_MAKE_OPAQUE` are macros. +Include `` (which includes +`` and ``) before the first import: + +```cpp +#include + +import std; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.stl; +``` + +GCC rejects a header included after an import of a module that already declared +the same entities. Clang is stricter about operators: they must be exported, +which `mcpplibs.mwrap.nanobind.operators` does. + +## Custom runtime + +The default `runtime` feature compiles one translation unit: + +```cpp +#include +``` + +`compat.nanobind` generates that forwarder and points it at upstream's +`src/nb_combined.cpp`. This is the only supported way to obtain the runtime: +compile it exactly once per Python extension or embedding binary, with that +binary's Python SDK. + +For `NB_SHARED`, a custom `Py_LIMITED_API`, a free-threaded interpreter or your +own visibility/aliasing flags, disable the default runtime and compile the +forwarder yourself: + +```toml +mcpplibs.mwrap.nanobind = { version = "3.1.0", default-features = false } +``` + +```toml +[build] +cxxflags = ["-DNB_SHARED", "-fvisibility=hidden", "-fno-strict-aliasing"] +``` + +The module interface still needs ``; the SDK resolution above is +unchanged. + +## Embedded interpreters and the template + +`mcpp new --template mcpplibs.mwrap.nanobind@3.1.0` renders `templates/embed/`. +Its `build.mcpp` resolves `xim:python`, emits link/runtime intent and writes +`` with the payload's home. `src/main.cpp` registers an +`NB_MODULE` with `PyImport_AppendInittab`, initializes Python with +`PyConfig.home`, imports the module and asserts its results. + +If you embed Python yourself, do the same: take `MCPP_PYTHON_HOME` from the +SDK's payload and call `PyConfig_SetBytesString(&config, &config.home, ...)` +before `Py_InitializeFromConfig`. Without it a relocated interpreter may not +find its standard library. + +## Deployment + +The package declares `[[runtime.deploy]]` entries. A program built against it +receives, beside the executable: + +```text +licenses/nanobind/LICENSE +licenses/nanobind/NOTICE +licenses/nanobind/upstream/nanobind/LICENSE +licenses/nanobind/upstream/nanobind/README.md +``` + +The upstream files' bytes and SHA256 values are recorded in +`upstream/documents.json`; `.gitattributes` disables text conversion for +`upstream/**`, including checkout on Windows. + +## Tests + +`mcpp test` builds the package with the `tests` feature and the +`mcpplibs.mtest` development dependency. That feature links the selected Python +SDK into the test executables only; it never reaches a consumer. + +The test files declare `UTest` cases and define no `main`: mcpp starts them at +mtest's entry. `behavior`, `ndarray` and `side_header` import +`nanobind_test.embed`, a private support module under `tests/support/` that the +`tests` feature alone compiles; each initializes the embedded interpreter once +inside its `UTest` body, with an RAII guard calling `Py_Finalize()` when the +last case ends. `operators` runs no Python code and is a pure module test. +Covered: + +- `behavior`: core objects, classes, casts, exceptions and STL casters. +- `side_header`: the side header before imports, `NB_MODULE`, trampolines, + `NB_OVERRIDE`, `NB_MAKE_OPAQUE`. +- `ndarray`: native views, dtype/device tags and the Python buffer protocol. +- `operators`: the Clang ADL audit, the GCC import check and the `NB_VERSION_*` + constants (no `#include` at all). diff --git a/include/mwrap/nanobind/macros.hpp b/include/mwrap/nanobind/macros.hpp new file mode 100644 index 0000000..0ecc4f6 --- /dev/null +++ b/include/mwrap/nanobind/macros.hpp @@ -0,0 +1,10 @@ +// — the nanobind macros a named module cannot +// export: NB_MODULE, NB_TRAMPOLINE, NB_OVERRIDE*, NB_MAKE_OPAQUE and their +// relatives. +// +// Include this header BEFORE `import mcpplibs.mwrap.nanobind;`. A translation +// unit that puts an #include after an import of a module that already declared +// the same entities is rejected by GCC. +#pragma once +#include +#include diff --git a/mcpp.toml b/mcpp.toml new file mode 100644 index 0000000..d32f61b --- /dev/null +++ b/mcpp.toml @@ -0,0 +1,75 @@ +# Module wrapper; upstream API preserved. Policy: mcpp-index/docs/mwrap.md. +[package] +namespace = "mcpplibs.mwrap" +name = "nanobind" +version = "3.1.0" +description = "nanobind 3.1.0 C++ modules for mcpp (import mcpplibs.mwrap.nanobind;): the binding API, its STL casters, ndarray/DLPack support and operator helpers over compat.nanobind" +license = "Apache-2.0" +authors = ["mcpp-community"] +repo = "https://github.com/mcpplibs/nanobind-m" +platforms = ["linux", "macos", "windows"] + +[targets.nanobind] +kind = "lib" + +[modules] +exports = [ + "mcpplibs.mwrap.nanobind", + "mcpplibs.mwrap.nanobind._core", + "mcpplibs.mwrap.nanobind.macros", + "mcpplibs.mwrap.nanobind.stl", + "mcpplibs.mwrap.nanobind.ndarray", +] + +[features] +default = ["runtime"] +# The one translation unit compat.nanobind documents: its generated forwarder +# includes the matching upstream src/nb_combined.cpp. +runtime = { sources = ["src/nb_runtime.cpp"], description = "Compile the nanobind runtime into this package" } +# Compile-time only: the package's own tests are embedded executables, so they +# link the Python SDK here without ever adding a link edge to a consumer. The +# support module lives outside src/ so [build] sources never scans it. +tests = { sources = ["tests/support/python_embed.cppm"], description = "Build and link this package's embedded-Python tests" } + +[test] +features = ["tests"] + +[build] +sources = ["src/*.cppm"] +# : the upstream macros a named module cannot export. +include_dirs = ["include"] + +[dependencies] +compat.nanobind = "3.1.0" + +[dev-dependencies] +mcpplibs.mtest = "0.11.3" + +[package.metadata.mwrap] +upstream-version = "3.1.0" + +# The Python SDK used to compile the module interface and the runtime. A +# consumer's nearer declaration wins; MCPP_PYTHON_INCLUDE_DIR overrides this +# discovery entirely (see docs/usage.md). +[xlings.workspace] +"xim:python" = "3.13.12" + +[[runtime.deploy]] +from = "LICENSE" +to = "licenses/nanobind" + +[[runtime.deploy]] +from = "NOTICE" +to = "licenses/nanobind" + +[[runtime.deploy]] +from = "upstream/nanobind/README.md" +to = "licenses/nanobind/upstream/nanobind" + +[[runtime.deploy]] +from = "upstream/nanobind/LICENSE" +to = "licenses/nanobind/upstream/nanobind" + +# reaches the Python SDK headers with min/max macros otherwise. +[target.'cfg(windows)'.build] +cxxflags = ["-DNOMINMAX", "-DWIN32_LEAN_AND_MEAN"] diff --git a/src/_core.cppm b/src/_core.cppm new file mode 100644 index 0000000..d8c4c3b --- /dev/null +++ b/src/_core.cppm @@ -0,0 +1,166 @@ +// mcpplibs.mwrap.nanobind._core — the root API unit behind the public root. +// +// Every exported name is the upstream entity of , +// unchanged, in the nanobind namespace where upstream declares it. The +// implementation is compat.nanobind 3.1.0; this package compiles the runtime +// unit from the forwarder that package generates. Macros are in +// mcpplibs.mwrap.nanobind.macros and . +module; +#include + +export module mcpplibs.mwrap.nanobind._core; + +export namespace nanobind { + +// ── objects and handles ────────────────────────────────────────────────── +using ::nanobind::handle; +using ::nanobind::object; +using ::nanobind::borrow; +using ::nanobind::steal; + +using ::nanobind::none; +using ::nanobind::ellipsis; +using ::nanobind::not_implemented; +using ::nanobind::bool_; +using ::nanobind::int_; +using ::nanobind::float_; +using ::nanobind::str; +using ::nanobind::bytes; +using ::nanobind::bytearray; +using ::nanobind::tuple; +using ::nanobind::list; +using ::nanobind::dict; +using ::nanobind::set; +using ::nanobind::frozenset; +using ::nanobind::slice; +using ::nanobind::capsule; +using ::nanobind::type_object; +using ::nanobind::type_object_t; +using ::nanobind::callable; +using ::nanobind::iterable; +using ::nanobind::iterator; +using ::nanobind::sequence; +using ::nanobind::mapping; +using ::nanobind::module_; +using ::nanobind::weakref; +using ::nanobind::memoryview; +using ::nanobind::args; +using ::nanobind::kwargs; +using ::nanobind::fallback; +using ::nanobind::typed; +using ::nanobind::pointer_and_handle; +using ::nanobind::builder; +using ::nanobind::tuple_builder; +using ::nanobind::list_builder; + +// ── binding, classes and functions ─────────────────────────────────────── +using ::nanobind::class_; +using ::nanobind::enum_; +using ::nanobind::init; +using ::nanobind::init_implicit; +using ::nanobind::new_; +using ::nanobind::cpp_function; +using ::nanobind::cpp_function_def; +using ::nanobind::def_visitor; +using ::nanobind::for_getter; +using ::nanobind::for_setter; + +using ::nanobind::arg; +using ::nanobind::arg_t; +using ::nanobind::arg_v; +using ::nanobind::arg_v_t; +using ::nanobind::arg_locked; +using ::nanobind::arg_locked_v; +using ::nanobind::scope; +using ::nanobind::name; +using ::nanobind::sig; +using ::nanobind::call_guard; +using ::nanobind::call_policy; +using ::nanobind::dynamic_attr; +using ::nanobind::is_weak_referenceable; +using ::nanobind::is_method; +using ::nanobind::is_implicit; +using ::nanobind::is_operator; +using ::nanobind::is_arithmetic; +using ::nanobind::is_flag; +using ::nanobind::is_str; +using ::nanobind::is_final; +using ::nanobind::is_generic; +using ::nanobind::kw_only; +using ::nanobind::lock_self; +using ::nanobind::never_destruct; +using ::nanobind::pooled; +using ::nanobind::keep_alive; +using ::nanobind::supplement; +using ::nanobind::intrusive_ptr; +using ::nanobind::is_getter; +using ::nanobind::type_slots; +using ::nanobind::type_slots_callback; +using ::nanobind::rv_policy; +using ::nanobind::exception_type; + +// ── conversion and utilities ───────────────────────────────────────────── +using ::nanobind::cast; +using ::nanobind::try_cast; +using ::nanobind::find; +using ::nanobind::make_tuple; +using ::nanobind::isinstance; +using ::nanobind::issubclass; +using ::nanobind::hasattr; +using ::nanobind::getattr; +using ::nanobind::setattr; +using ::nanobind::delattr; +using ::nanobind::len; +using ::nanobind::repr; +using ::nanobind::print; +using ::nanobind::iter; +using ::nanobind::hash; +using ::nanobind::type; +using ::nanobind::type_name; +using ::nanobind::is_alive; +using ::nanobind::globals; +using ::nanobind::builtins; +using ::nanobind::register_module; +using ::nanobind::implicitly_convertible; +using ::nanobind::set_leak_warnings; +using ::nanobind::set_implicit_cast_warnings; +using ::nanobind::leak_warnings; +using ::nanobind::implicit_cast_warnings; + +using ::nanobind::gil_scoped_acquire; +using ::nanobind::gil_scoped_release; +using ::nanobind::ft_mutex; +using ::nanobind::ft_lock_guard; +using ::nanobind::ft_object_guard; +using ::nanobind::ft_object2_guard; +using ::nanobind::error_scope; + +// ── exceptions ─────────────────────────────────────────────────────────── +namespace NB_BACKEND_ABI_NS { +using ::nanobind::NB_BACKEND_ABI_NS::python_error; +using ::nanobind::NB_BACKEND_ABI_NS::builtin_exception; +} +using ::nanobind::cast_error; +using ::nanobind::exception; +using ::nanobind::stop_iteration; +using ::nanobind::index_error; +using ::nanobind::key_error; +using ::nanobind::value_error; +using ::nanobind::type_error; +using ::nanobind::buffer_error; +using ::nanobind::import_error; +using ::nanobind::attribute_error; +using ::nanobind::next_overload; +using ::nanobind::raise; +using ::nanobind::raise_from; +using ::nanobind::chain_error; +using ::nanobind::raise_type_error; +using ::nanobind::register_exception_translator; + +// ── literals (a named module can export the operator itself) ───────────── +namespace literals { +using ::nanobind::literals::operator""_a; +using ::nanobind::literals::operator""_s; +} + +} // namespace nanobind diff --git a/src/macros.cppm b/src/macros.cppm new file mode 100644 index 0000000..f2b94af --- /dev/null +++ b/src/macros.cppm @@ -0,0 +1,26 @@ +// mcpplibs.mwrap.nanobind.macros — the version macros of +// (a named module cannot export a macro), under their original names in +// mcpplibs::mwrap::nanobind::macros. +module; +#include + +namespace mwrap_nanobind_capture { +inline constexpr auto value_NB_VERSION_MAJOR = (NB_VERSION_MAJOR); +inline constexpr auto value_NB_VERSION_MINOR = (NB_VERSION_MINOR); +inline constexpr auto value_NB_VERSION_PATCH = (NB_VERSION_PATCH); +inline constexpr auto value_NB_VERSION_DEV = (NB_VERSION_DEV); +} // namespace mwrap_nanobind_capture + +#undef NB_VERSION_MAJOR +#undef NB_VERSION_MINOR +#undef NB_VERSION_PATCH +#undef NB_VERSION_DEV + +export module mcpplibs.mwrap.nanobind.macros; + +export namespace mcpplibs::mwrap::nanobind::macros { +inline constexpr auto NB_VERSION_MAJOR = mwrap_nanobind_capture::value_NB_VERSION_MAJOR; +inline constexpr auto NB_VERSION_MINOR = mwrap_nanobind_capture::value_NB_VERSION_MINOR; +inline constexpr auto NB_VERSION_PATCH = mwrap_nanobind_capture::value_NB_VERSION_PATCH; +inline constexpr auto NB_VERSION_DEV = mwrap_nanobind_capture::value_NB_VERSION_DEV; +} // namespace mcpplibs::mwrap::nanobind::macros diff --git a/src/nanobind.cppm b/src/nanobind.cppm new file mode 100644 index 0000000..2816b98 --- /dev/null +++ b/src/nanobind.cppm @@ -0,0 +1,13 @@ +// mcpplibs.mwrap.nanobind — nanobind 3.1.0 as a C++ module. +// +// The public root re-exports the core API, the version constants, the STL +// casters and ndarray support. The operators module is separate: on GCC 16 a +// translation unit that both uses a class_ and expands one of its operator +// templates currently trips a debug-info ICE, so a user of the core API does +// not import it implicitly. +export module mcpplibs.mwrap.nanobind; + +export import mcpplibs.mwrap.nanobind._core; +export import mcpplibs.mwrap.nanobind.macros; +export import mcpplibs.mwrap.nanobind.stl; +export import mcpplibs.mwrap.nanobind.ndarray; diff --git a/src/nb_runtime.cpp b/src/nb_runtime.cpp new file mode 100644 index 0000000..2f0aa67 --- /dev/null +++ b/src/nb_runtime.cpp @@ -0,0 +1,4 @@ +// The runtime unit compat.nanobind documents: compile its generated forwarder +// in exactly one translation unit, with this build's Python SDK on the include +// path. The package feature `runtime` adds this file to the build. +#include diff --git a/src/ndarray.cppm b/src/ndarray.cppm new file mode 100644 index 0000000..2f2a5c7 --- /dev/null +++ b/src/ndarray.cppm @@ -0,0 +1,57 @@ +// mcpplibs.mwrap.nanobind.ndarray — : ndarray, DLPack +// types, contiguity/device/framework tags and the dtype() query, under their +// upstream names. +module; +#include +#include + +export module mcpplibs.mwrap.nanobind.ndarray; + +export import mcpplibs.mwrap.nanobind._core; + +export namespace nanobind { + +using ::nanobind::ndarray; +using ::nanobind::ndarray_view; +using ::nanobind::ndarray_check; +using ::nanobind::ro; +using ::nanobind::shape; +using ::nanobind::ndim; +using ::nanobind::dtype; + +using ::nanobind::c_contig; +using ::nanobind::f_contig; +using ::nanobind::any_contig; + +using ::nanobind::no_framework; +using ::nanobind::numpy; +using ::nanobind::pytorch; +using ::nanobind::tensorflow; +using ::nanobind::jax; +using ::nanobind::cupy; +using ::nanobind::memview; +using ::nanobind::array_api; +using ::nanobind::mlx; + +namespace dlpack { +using ::nanobind::dlpack::dtype_code; +using ::nanobind::dlpack::device; +using ::nanobind::dlpack::dtype; +using ::nanobind::dlpack::dltensor; +} // namespace dlpack + +namespace device { +using ::nanobind::device::none; +using ::nanobind::device::cpu; +using ::nanobind::device::cuda; +using ::nanobind::device::cuda_host; +using ::nanobind::device::opencl; +using ::nanobind::device::vulkan; +using ::nanobind::device::metal; +using ::nanobind::device::rocm; +using ::nanobind::device::rocm_host; +using ::nanobind::device::cuda_managed; +using ::nanobind::device::oneapi; +} // namespace device + +} // namespace nanobind diff --git a/src/operators.cppm b/src/operators.cppm new file mode 100644 index 0000000..e4f9f76 --- /dev/null +++ b/src/operators.cppm @@ -0,0 +1,57 @@ +// mcpplibs.mwrap.nanobind.operators — : nb::self and +// the operator-binding helpers, under their upstream names. +// +// The header's `static const self_t self` has internal linkage and cannot be +// exported. The include below renames that object, and the module defines the +// exported nb::self with the same upstream type. The operator functions are +// named in nanobind::detail, where argument-dependent lookup finds them; each +// is re-exported so a Clang importer can resolve `nb::self + nb::self`. +module; +#include +#define self detail_self +#include +#undef self + +export module mcpplibs.mwrap.nanobind.operators; + +export import mcpplibs.mwrap.nanobind._core; + +export namespace nanobind { + +inline constexpr detail::self_t self{}; + +using ::nanobind::detail::hash; +using ::nanobind::detail::abs; + +namespace detail { +using ::nanobind::detail::operator-; +using ::nanobind::detail::operator+; +using ::nanobind::detail::operator*; +using ::nanobind::detail::operator/; +using ::nanobind::detail::operator%; +using ::nanobind::detail::operator<<; +using ::nanobind::detail::operator>>; +using ::nanobind::detail::operator&; +using ::nanobind::detail::operator^; +using ::nanobind::detail::operator|; +using ::nanobind::detail::operator>; +using ::nanobind::detail::operator>=; +using ::nanobind::detail::operator<; +using ::nanobind::detail::operator<=; +using ::nanobind::detail::operator==; +using ::nanobind::detail::operator!=; +using ::nanobind::detail::operator+=; +using ::nanobind::detail::operator-=; +using ::nanobind::detail::operator*=; +using ::nanobind::detail::operator/=; +using ::nanobind::detail::operator%=; +using ::nanobind::detail::operator<<=; +using ::nanobind::detail::operator>>=; +using ::nanobind::detail::operator&=; +using ::nanobind::detail::operator^=; +using ::nanobind::detail::operator|=; +using ::nanobind::detail::operator~; +using ::nanobind::detail::operator!; +} // namespace detail + +} // namespace nanobind diff --git a/src/stl.cppm b/src/stl.cppm new file mode 100644 index 0000000..c04a686 --- /dev/null +++ b/src/stl.cppm @@ -0,0 +1,56 @@ +// mcpplibs.mwrap.nanobind.stl — nanobind's STL casters. +// +// The standard library headers are included in the global module fragment +// first. Their include guards then make the same includes inside the +// headers no-ops below, so only the nanobind partial +// specializations of nanobind::detail::type_caster attach to (and are +// exported from) this module. Importing this module therefore makes +// std::string, std::vector, std::optional and friends bindable +// without including any header. +module; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +export module mcpplibs.mwrap.nanobind.stl; + +export import mcpplibs.mwrap.nanobind._core; + +export { +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +} diff --git a/templates/embed/build.mcpp b/templates/embed/build.mcpp new file mode 100644 index 0000000..51b37fc --- /dev/null +++ b/templates/embed/build.mcpp @@ -0,0 +1,241 @@ +// The default nanobind-m quickstart: a Python module built from C++, imported +// by the interpreter embedded in this same executable. +// [xlings.workspace] points at the SDK; build.mcpp resolves Python.h and the +// link/runtime directories from that payload. See docs/usage.md for the +// environment overrides. +import std; +import mcpp; + +namespace { +namespace fs = std::filesystem; + +bool has_python_h(const fs::path& dir) { + std::error_code ec; + return fs::is_regular_file(dir / "Python.h", ec); +} + +// The payload's include/Python.h (Windows) or include/python3.*/Python.h +// (Unix and macOS), preferring the highest version by numeric minor. +int python_minor(const fs::path& directory) { + const std::string name = directory.filename().string(); + if (name.rfind("python3.", 0) != 0) + return -1; + int value = 0; + for (char c : name.substr(8)) { + if (c < '0' || c > '9') + return -1; + value = value * 10 + (c - '0'); + } + return value; +} + +std::optional include_from_root(const fs::path& root) { + if (has_python_h(root / "include")) + return root / "include"; + std::vector candidates; + std::error_code ec; + for (fs::directory_iterator it(root / "include", ec), end; !ec && it != end; it.increment(ec)) { + const auto name = it->path().filename().string(); + if (it->is_directory() && name.rfind("python3.", 0) == 0 && has_python_h(it->path())) + candidates.push_back(it->path()); + } + if (candidates.empty()) + return std::nullopt; + std::sort(candidates.begin(), candidates.end(), [](const fs::path& a, const fs::path& b) { + return python_minor(a) > python_minor(b); // python3.13 > python3.9, numerically + }); + return candidates.front(); +} + +std::optional include_from_prefix(const fs::path& prefix) { + if (const auto found = include_from_root(prefix)) + return found; + std::error_code ec; + for (fs::directory_iterator it(prefix / "include", ec), end; !ec && it != end; it.increment(ec)) { + if (it->is_directory() && has_python_h(it->path())) + return it->path(); + } + return std::nullopt; +} + +std::optional include_from_interpreter(const fs::path& executable) { + for (const fs::path& prefix : {executable.parent_path(), executable.parent_path().parent_path()}) { + if (const auto found = include_from_prefix(prefix)) + return found; + } + return std::nullopt; +} + +std::optional interpreter_on_path() { + const bool is_windows = std::string_view(mcpp::target_os()) == "windows"; + const char separator = is_windows ? ';' : ':'; + const std::vector names = is_windows + ? std::vector{"python.exe", "python3.exe"} + : std::vector{"python3", "python"}; + const char* path = std::getenv("PATH"); + if (!path) + return std::nullopt; + std::string_view text(path); + for (std::size_t begin = 0; begin <= text.size();) { + const std::size_t end = text.find(separator, begin); + const auto directory = text.substr(begin, end == std::string_view::npos ? text.size() - begin : end - begin); + for (const auto& name : names) { + std::error_code ec; + const fs::path candidate = fs::path(directory) / name; + if (fs::is_regular_file(candidate, ec)) + return candidate; + } + if (end == std::string_view::npos) + break; + begin = end + 1; + } + return std::nullopt; +} + +std::optional find_include() { + if (const char* value = std::getenv("MCPP_PYTHON_INCLUDE_DIR"); value && *value) { + const fs::path dir(value); + if (has_python_h(dir)) + return dir; + std::println(std::cerr, "build.mcpp: MCPP_PYTHON_INCLUDE_DIR={} has no Python.h", value); + } + if (const char* value = mcpp::xpkg_dir("xim", "python"); value && *value) { + if (const auto found = include_from_root(value)) + return found; + } + if (const char* value = std::getenv("MCPP_PYTHON_EXECUTABLE"); value && *value) { + if (const auto found = include_from_interpreter(fs::path(value))) + return found; + } + if (const char* value = std::getenv("VIRTUAL_ENV"); value && *value) { + if (const auto found = include_from_prefix(value)) + return found; + } + if (const auto interpreter = interpreter_on_path()) { + if (const auto found = include_from_interpreter(*interpreter)) + return found; + } + return std::nullopt; +} + +fs::path root_of_include(const fs::path& include) { + fs::path directory = include; + if (directory.filename().string().rfind("python3.", 0) == 0) + directory = directory.parent_path(); + if (directory.filename() == "include") + directory = directory.parent_path(); + return directory; +} + +std::string version_suffix(const fs::path& include) { + const std::string name = include.filename().string(); + if (name.rfind("python3.", 0) == 0) + return name.substr(6); + return {}; +} + +std::string library_name(const fs::path& include, const fs::path& library_dir) { + if (const char* value = std::getenv("MCPP_PYTHON_LIBRARY"); value && *value) + return value; + const std::string suffix = version_suffix(include); + const bool is_windows = std::string_view(mcpp::target_os()) == "windows"; + if (!suffix.empty()) { + if (!is_windows) + return "python" + suffix; + std::string compact; + for (char c : suffix) + if (c != '.') + compact.push_back(c); + return "python" + compact; + } + std::error_code ec; + for (fs::directory_iterator it(library_dir, ec), end; !ec && it != end; it.increment(ec)) { + const std::string name = it->path().filename().string(); + if (name.rfind("libpython3.", 0) == 0) { + const auto dot = name.find('.', 11); + if (dot != std::string::npos) + return "python" + name.substr(9, dot - 9); + } + if (is_windows && it->path().extension() == ".lib") { + const std::string stem = it->path().stem().string(); + if (stem.size() > 7 && stem.rfind("python3", 0) == 0 && + std::all_of(stem.begin() + 7, stem.end(), [](char c) { return c >= '0' && c <= '9'; })) + return stem; + } + } + return {}; +} + +std::string escaped(std::string value) { + std::string out; + for (char c : value) { + if (c == '\\' || c == '"') + out.push_back('\\'); + out.push_back(c); + } + return out; +} + +void write_if_changed(const fs::path& path, const std::string& text) { + { + std::ifstream in(path, std::ios::binary); + if (in && std::string(std::istreambuf_iterator(in), {}) == text) + return; + } + std::ofstream(path, std::ios::binary | std::ios::trunc) << text; +} + +} // namespace + +int main() { + for (const char* name : {"MCPP_PYTHON_INCLUDE_DIR", "MCPP_PYTHON_EXECUTABLE", "MCPP_PYTHON_HOME", + "MCPP_PYTHON_LIBRARY_DIR", "MCPP_PYTHON_LIBRARY", "VIRTUAL_ENV"}) + mcpp::rerun_if_env_changed(name); + + const bool is_windows = std::string_view(mcpp::target_os()) == "windows"; + const std::optional include = find_include(); + if (!include) { + std::println(std::cerr, + "nanobind-m template: no Python development headers found.\n" + " Declare \"xim:python\" under [xlings.workspace] in mcpp.toml, or set\n" + " MCPP_PYTHON_INCLUDE_DIR to the directory containing Python.h."); + return 1; + } + + const fs::path home = [&] { + if (const char* value = std::getenv("MCPP_PYTHON_HOME"); value && *value) + return fs::path(value); + return root_of_include(*include); + }(); + const fs::path library_dir = [&] { + if (const char* value = std::getenv("MCPP_PYTHON_LIBRARY_DIR"); value && *value) + return fs::path(value); + if (is_windows) + return fs::exists(home / "libs") ? home / "libs" : home; + return home / "lib"; + }(); + const std::string library = library_name(*include, library_dir); + if (library.empty()) { + std::println(std::cerr, "nanobind-m template: no Python library under {}", library_dir.string()); + return 1; + } + + const fs::path out = fs::path(mcpp::out_dir()) / "python-sdk"; + std::error_code ec; + fs::create_directories(out, ec); + write_if_changed(out / "python_sdk.h", + "#pragma once\n" + "#define MCPP_PYTHON_HOME \"" + escaped(home.generic_string()) + "\"\n" + + "#define MCPP_PYTHON_INCLUDE_DIR \"" + escaped(include->generic_string()) + "\"\n" + + "#define MCPP_PYTHON_LIBRARY \"" + escaped(library) + "\"\n"); + + mcpp::include_dir(include->string().c_str()); + mcpp::include_dir(out.string().c_str()); + mcpp::link_search(library_dir.string().c_str()); + if (is_windows) + mcpp::runtime_search_dir(home.string().c_str()); + else + mcpp::runtime_search_dir(library_dir.string().c_str()); + mcpp::link_lib(library.c_str()); + return 0; +} diff --git a/templates/embed/mcpp.toml.in b/templates/embed/mcpp.toml.in new file mode 100644 index 0000000..ab9c342 --- /dev/null +++ b/templates/embed/mcpp.toml.in @@ -0,0 +1,13 @@ +[package] +name = "{{project.name}}" +version = "0.1.0" + +[targets.{{project.name}}] +kind = "bin" +main = "src/main.cpp" + +[dependencies] +{{self.name}} = "{{self.version}}" + +[xlings.workspace] +"xim:python" = "3.13.12" diff --git a/templates/embed/src/main.cpp.in b/templates/embed/src/main.cpp.in new file mode 100644 index 0000000..3718953 --- /dev/null +++ b/templates/embed/src/main.cpp.in @@ -0,0 +1,58 @@ +// {{project.name}} — a Python module written in C++ and imported by the +// interpreter embedded in this executable. +// +// Only two includes are needed: the side header supplies the macros +// (NB_MODULE cannot cross a named-module boundary), and python_sdk.h carries +// the payload's home that build.mcpp located. Everything else is import std. +#include +#include + +import std; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.stl; + +namespace nb = nanobind; + +NB_MODULE(embed_demo, m) { + m.def("add", [](int a, int b) { return a + b; }, nb::arg("a"), nb::arg("b")); + m.def("shout", [](std::string text) { + for (char& c : text) c = static_cast(std::toupper(static_cast(c))); + return text; + }); + m.def("total", [](const std::vector& values) { + int sum = 0; + for (int value : values) sum += value; + return sum; + }); + m.def("or_default", [](std::optional value) { return value.value_or(42); }); +} + +int main() { + PyImport_AppendInittab("embed_demo", PyInit_embed_demo); + + PyConfig config; + PyConfig_InitPythonConfig(&config); + PyStatus status = PyConfig_SetBytesString(&config, &config.home, MCPP_PYTHON_HOME); + if (!PyStatus_Exception(status)) { + config.parse_argv = 0; + status = Py_InitializeFromConfig(&config); + } + PyConfig_Clear(&config); + if (PyStatus_Exception(status)) { + std::println(std::cerr, "cannot initialize Python: {}", status.err_msg ? status.err_msg : "unknown PyStatus"); + return 1; + } + + const int rc = PyRun_SimpleString( + "import embed_demo as demo\n" + "assert demo.add(20, 22) == 42\n" + "assert demo.shout('nanobind') == 'NANOBIND'\n" + "assert demo.total([1, 2, 3, 4]) == 10\n" + "assert demo.or_default(None) == 42\n" + "print('embed_demo:', demo.add(20, 22), demo.shout('nanobind'))\n"); + + if (PyErr_Occurred()) + PyErr_Print(); + Py_Finalize(); + return rc; +} diff --git a/templates/embed/template.toml b/templates/embed/template.toml new file mode 100644 index 0000000..95e22ce --- /dev/null +++ b/templates/embed/template.toml @@ -0,0 +1,4 @@ +[template] +description = "A Python module written in C++ (NB_MODULE), imported by the interpreter embedded in the same executable" +default = true +post_message = "Run `mcpp run`: it builds the module and calls it from Python." diff --git a/tests/behavior.cpp b/tests/behavior.cpp new file mode 100644 index 0000000..e43342c --- /dev/null +++ b/tests/behavior.cpp @@ -0,0 +1,109 @@ +// The core module surface, the STL casters, exceptions and literals in one +// embedded interpreter. Python is initialized once, before the first case of +// this UTest and finalized by the guard when its last case ends. +#include // NB_MODULE cannot come from a module + +import std; +import nanobind_test.embed; +import mcpplibs.mtest; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.stl; + +using namespace mcpplibs::mtest; + +namespace nb = nanobind; + +namespace { + +struct Point { + double x = 0, y = 0; + double norm() const { return std::sqrt(x * x + y * y); } +}; + +bool raise_boom() { + throw nb::value_error("boom"); + return false; +} + +} // namespace + +NB_MODULE(nanobind_behavior, m) { + m.def("twice", [](int value) { return value * 2; }); + m.def("greet", [](const std::string& name) { return "hello, " + name; }); + m.def("total", [](const std::vector& values) { + int sum = 0; + for (int value : values) sum += value; + return sum; + }); + m.def("or_default", [](std::optional value) { return value.value_or(42); }); + m.def("lookup", [](const std::unordered_map& values) { + const auto found = values.find("answer"); + return found == values.end() ? -1 : found->second; + }); + m.def("fail", &raise_boom); + m.def("with_args", [](int a, int b) { return a - b; }, nb::arg("a"), nb::arg("b") = 1); + nb::class_(m, "Point") + .def(nb::init<>()) + .def(nb::init(), nb::arg("x"), nb::arg("y")) + .def_rw("x", &Point::x) + .def_rw("y", &Point::y) + .def("norm", &Point::norm); +} + +UTest behavior{"behavior", [] { + PyImport_AppendInittab("nanobind_behavior", PyInit_nanobind_behavior); + expect(fatal(nanobind_test::start())) << nanobind_test::start_error; + struct Guard { + ~Guard() { nanobind_test::finish(); } + } guard; + + "python assertions"_test = [] { + expect(eq(nanobind_test::run( + "import nanobind_behavior as b\n" + "assert b.twice(21) == 42\n" + "assert b.greet('world') == 'hello, world'\n" + "assert b.total([1, 2, 3, 4]) == 10\n" + "assert b.or_default(None) == 42 and b.or_default(7) == 7\n" + "assert b.lookup({'answer': 42}) == 42 and b.lookup({}) == -1\n" + "assert b.with_args(10) == 9 and b.with_args(10, 4) == 6\n" + "p = b.Point(3, 4)\n" + "assert abs(p.norm() - 5.0) < 1e-12 and p.x == 3 and p.y == 4\n" + "try:\n" + " b.fail()\n" + "except ValueError as e:\n" + " assert str(e) == 'boom'\n" + "else:\n" + " raise AssertionError('no exception')\n"), + 0)); + }; + + "cpp casts and stl"_test = [] { + nb::module_ mod = nb::module_::import_("nanobind_behavior"); + expect(eq(nb::cast(mod.attr("twice")(nb::int_(21))), 42)); + int parsed = 0; + expect(nb::try_cast(nb::int_(7), parsed)); + expect(eq(parsed, 7)); + expect(!nb::try_cast(nb::str("no"), parsed)); + nb::list values; + values.append(nb::int_(1)); + values.append(nb::int_(2)); + expect(eq(nb::cast>(values), std::vector{1, 2})); + expect(eq(nb::len(values), 2u)); + expect(eq(std::string(nb::repr(nb::str("x")).c_str()), std::string("'x'"))); + expect(nb::isinstance(values, nb::list().type())); + expect(throws([] { (void) nb::cast(nb::str("not an int")); })); + }; + + "cpp exceptions"_test = [] { + nb::module_ mod = nb::module_::import_("nanobind_behavior"); + bool matched = false; + try { + mod.attr("fail")(); + } catch (nb::python_error& error) { + matched = error.matches(PyExc_ValueError); + error.restore(); + PyErr_Clear(); + } + expect(matched); + }; +}}; diff --git a/tests/ndarray.cpp b/tests/ndarray.cpp new file mode 100644 index 0000000..c6033ed --- /dev/null +++ b/tests/ndarray.cpp @@ -0,0 +1,57 @@ +// The ndarray submodule: native views and the Python buffer protocol. NumPy is +// not required; the Python side supplies a standard array.array buffer. +#include // NB_MODULE cannot come from a module + +import std; +import nanobind_test.embed; +import mcpplibs.mtest; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.ndarray; + +using namespace mcpplibs::mtest; +namespace nb = nanobind; + +static_assert(nb::c_contig::value == 'C'); +static_assert(nb::f_contig::value == 'F'); +static_assert(nb::device::cpu::value == 1); +static_assert(nb::numpy::value == 1); +static_assert(nb::dtype().bits == 32); +static_assert(nb::dtype().bits == 64); + +NB_MODULE(nanobind_ndarray, m) { + m.def("sum", [](nb::ndarray> array) { + float sum = 0; + for (size_t i = 0; i < array.shape(0); ++i) sum += array(i); + return sum; + }); + m.def("shape", [](nb::ndarray> array) { return array.shape(0); }); +} + +UTest ndarray{"ndarray", [] { + PyImport_AppendInittab("nanobind_ndarray", PyInit_nanobind_ndarray); + expect(fatal(nanobind_test::start())) << nanobind_test::start_error; + struct Guard { + ~Guard() { nanobind_test::finish(); } + } guard; + + "native view"_test = [] { + std::vector data{1.0f, 2.0f, 3.0f}; + nb::ndarray> array(data.data(), {data.size()}, nb::none()); + expect(eq(array.ndim(), 1u)); + expect(eq(array.shape(0), 3u)); + expect(eq(array.dtype().bits, 32u)); + expect(eq(array.device_type(), nb::device::cpu::value)); + }; + + "python buffer"_test = [] { + nb::module_ mod = nb::module_::import_("nanobind_ndarray"); + nb::module_ array_module = nb::module_::import_("array"); + nb::object python_array = array_module.attr("array")( + nb::str("f"), nb::make_tuple(nb::float_(1.0), nb::float_(2.0), nb::float_(3.0))); + expect(eq(nb::cast(mod.attr("sum")(python_array)), 6.0f)); + expect(eq(nb::cast(mod.attr("shape")(python_array)), 3u)); + const auto roundtrip = nb::cast>>(python_array); + expect(eq(roundtrip.ndim(), 1u)); + expect(eq(roundtrip.shape(0), 3u)); + }; +}}; diff --git a/tests/operators.cpp b/tests/operators.cpp new file mode 100644 index 0000000..02912d5 --- /dev/null +++ b/tests/operators.cpp @@ -0,0 +1,52 @@ +// The operators module, with the Clang ADL audit docs/mwrap.md asks for, and +// the version constants asserted here because this file does not include the +// side header (so NB_VERSION_* are not live macros). +// +// GCC 16.1/16.2 currently ICE in gen_enumeration_type_die when a module-using +// translation unit *applies* one of these operator templates while debug info +// is enabled. The module itself builds; Clang is the authoritative ADL check +// and the GCC run still imports the module and checks the mapped constants. +import std; +import mcpplibs.mtest; +import mcpplibs.mwrap.nanobind; +import mcpplibs.mwrap.nanobind.macros; +import mcpplibs.mwrap.nanobind.operators; + +using namespace mcpplibs::mtest; +namespace nb = nanobind; +namespace m = mcpplibs::mwrap::nanobind::macros; + +static_assert(m::NB_VERSION_MAJOR == 3); +static_assert(m::NB_VERSION_MINOR == 1); +static_assert(m::NB_VERSION_PATCH == 0); +static_assert(m::NB_VERSION_DEV == 0); + +static_assert(std::is_class_v>); + +#if defined(__clang__) +using self_plus_self = decltype(nb::self + nb::self); +using scalar_plus_self = decltype(2 + nb::self); +using self_negated = decltype(-nb::self); +static_assert(!std::is_void_v); +static_assert(!std::is_void_v); +static_assert(!std::is_void_v); + +UTest clang_adl{"clang-adl", [] { + "clang adl"_test = [] { + // Instantiate the expressions, not merely their types, so Clang must + // find the exported detail::operator* through argument-dependent lookup. + (void) (nb::self + nb::self); + (void) (2 + nb::self); + (void) (-nb::self); + }; +}}; +#endif + +UTest operators{"operators", [] { + "version constants"_test = [] { + expect(eq(m::NB_VERSION_MAJOR, 3)); + expect(eq(m::NB_VERSION_MINOR, 1)); + expect(eq(m::NB_VERSION_PATCH, 0)); + expect(eq(m::NB_VERSION_DEV, 0)); + }; +}}; diff --git a/tests/side_header.cpp b/tests/side_header.cpp new file mode 100644 index 0000000..9c8aea3 --- /dev/null +++ b/tests/side_header.cpp @@ -0,0 +1,63 @@ +// The side header and the import in one translation unit: every include comes +// first, then the named-module imports (the order GCC requires), and the +// macros NB_MODULE, NB_TRAMPOLINE, NB_OVERRIDE and NB_MAKE_OPAQUE work beside +// the imported entities. +#include // the macros a module cannot export + +import std; +import nanobind_test.embed; +import mcpplibs.mtest; +import mcpplibs.mwrap.nanobind; + +using namespace mcpplibs::mtest; +namespace nb = nanobind; + +namespace { + +struct Animal { + virtual ~Animal() = default; + virtual std::string speak() const { return "animal"; } +}; + +struct PyAnimal : Animal { + NB_TRAMPOLINE(Animal); + std::string speak() const override { + NB_OVERRIDE(speak); + } +}; + +} // namespace + +struct Opaque { + int value = 7; +}; +NB_MAKE_OPAQUE(Opaque); + +NB_MODULE(nanobind_side_header, m) { + nb::class_(m, "Animal") + .def(nb::init<>()) + .def("speak", &Animal::speak); + m.def("speak_of", [](const Animal& animal) { return animal.speak(); }); + m.def("name", [] { return std::string("side-header"); }); +} + +UTest side_header{"side-header", [] { + PyImport_AppendInittab("nanobind_side_header", PyInit_nanobind_side_header); + expect(fatal(nanobind_test::start())) << nanobind_test::start_error; + struct Guard { + ~Guard() { nanobind_test::finish(); } + } guard; + + "python trampoline assertions"_test = [] { + expect(eq(nanobind_test::run( + "import nanobind_side_header as s\n" + "assert s.name() == 'side-header'\n" + "assert s.Animal().speak() == 'animal'\n" + "class Dog(s.Animal):\n" + " def speak(self): return 'woof'\n" + "d = Dog()\n" + "assert d.speak() == 'woof'\n" + "assert s.speak_of(d) == 'woof'\n"), + 0)); + }; +}}; diff --git a/tests/support/python_embed.cppm b/tests/support/python_embed.cppm new file mode 100644 index 0000000..cd7c5b1 --- /dev/null +++ b/tests/support/python_embed.cppm @@ -0,0 +1,47 @@ +// Embedded-Python start-up shared by this package's tests. +// +// This module is private to the `tests` feature: it is not in [modules] +// exports and is never part of a default build. The global module fragment +// wraps the CPython C API (PyConfig, Py_InitializeFromConfig, +// PyRun_SimpleString, Py_Finalize), which nanobind does not re-export, and +// , which build.mcpp writes for the selected SDK's home. +module; +#include +#include + +export module nanobind_test.embed; + +export namespace nanobind_test { + +inline const char* start_error = nullptr; + +inline bool start() { + PyConfig config; + PyConfig_InitPythonConfig(&config); + PyStatus status = PyConfig_SetBytesString(&config, &config.home, MCPP_PYTHON_HOME); + if (!PyStatus_Exception(status)) { + config.parse_argv = 0; + config.install_signal_handlers = 0; + status = Py_InitializeFromConfig(&config); + } + PyConfig_Clear(&config); + if (PyStatus_Exception(status)) { + start_error = status.err_msg ? status.err_msg : "unknown PyStatus"; + return false; + } + return true; +} + +inline int run(const char* source) { + return PyRun_SimpleString(source); +} + +inline void finish() { + if (Py_IsInitialized()) { + if (PyErr_Occurred()) + PyErr_Print(); + Py_Finalize(); + } +} + +} // namespace nanobind_test diff --git a/tools/check_documents.py b/tools/check_documents.py new file mode 100644 index 0000000..11602c9 --- /dev/null +++ b/tools/check_documents.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Verify the byte-pinned upstream documents against upstream/documents.json.""" +import hashlib +import json +from pathlib import Path + + +def main(): + root = Path(__file__).resolve().parents[1] + record = json.loads((root / "upstream/documents.json").read_text())["upstream"] + failures = [] + for document in record["documents"]: + path = root / document["path"] + digest = hashlib.sha256(path.read_bytes()).hexdigest() + status = "ok" if digest == document["sha256"] else "MISMATCH" + print(f"{status:8} {document['path']} {digest}") + if digest != document["sha256"]: + failures.append(document["path"]) + if record["tag"] != "v3.1.0" or record["version"] != "3.1.0": + failures.append("upstream identity") + return failures + + +if __name__ == "__main__": + raise SystemExit(1 if main() else 0) diff --git a/tools/test_template.py b/tools/test_template.py new file mode 100644 index 0000000..0d059df --- /dev/null +++ b/tools/test_template.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Render this checkout's default template as an installed candidate, build and run it.""" +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import tomllib + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mcpp", default="mcpp") + parser.add_argument("--toolchain", default="llvm@23.1.3") + parser.add_argument("--template") + parser.add_argument("--index", type=Path) + args = parser.parse_args() + + root = Path(__file__).resolve().parents[1] + metadata = tomllib.loads((root / "mcpp.toml").read_text())["package"] + namespace, name, version = metadata["namespace"], metadata["name"], metadata["version"] + identity = namespace + "." + name + home = Path(os.environ.get("MCPP_HOME", Path.home() / ".mcpp")).resolve() + + with tempfile.TemporaryDirectory(prefix=name + "-template-") as directory: + temporary = Path(directory) + package = home / "registry/data/xpkgs" / (namespace + "-x-" + name) / version + shutil.copytree(root, package, ignore=shutil.ignore_patterns( + ".git", ".local", "target", ".mcpp", ".xlings", ".candidate-index", "__pycache__", + "mcpp.lock", "compile_commands.json", "mcpp-2026.*")) + index = home / "indices/mcpplibs/pkgs/mwrap" + index.mkdir(parents=True, exist_ok=True) + entry = '{url="https://example.invalid/candidate.tar.gz",sha256="fixture"}' + descriptor = ('package={spec="1",namespace=' + json.dumps(namespace) + ',name=' + json.dumps(name) + + ',description="Installed template fixture",type="package",mcpp="mcpp.toml",xpm={') + descriptor += ",".join(platform + "={[" + json.dumps(version) + "]=" + entry + "}" + for platform in ("linux", "macosx", "windows")) + "}}\n" + (index / (identity + ".lua")).write_text(descriptor) + + env = dict(os.environ, MCPP_HOME=str(home)) + selector = identity + "@" + version + for command in ([args.mcpp, "new", "--list-templates", selector], + [args.mcpp, "new", "quickstart", "--template", + selector + (":" + args.template if args.template else "")]): + print("+", " ".join(command), flush=True) + subprocess.run(command, cwd=temporary, env=env, check=True) + + project = temporary / "quickstart" + manifest = project / "mcpp.toml" + text = manifest.read_text() + dependency = tomllib.loads(text)["dependencies"] + for segment in identity.split("."): + dependency = dependency[segment] + options = {"version": dependency} if isinstance(dependency, str) else dependency + assert options["version"] == version, options + replacement = '{ path = ' + json.dumps(package.as_posix()) + if options.get("features"): + replacement += ', features = ' + json.dumps(options["features"]) + replacement += ' }' + lines = text.splitlines() + matches = [i for i, line in enumerate(lines) if line.startswith(identity + " =")] + assert len(matches) == 1, "expected one unquoted qualified dependency from self.name" + lines[matches[0]] = identity + " = " + replacement + manifest.write_text("\n".join(lines) + "\n") + + for command in ([args.mcpp, "build", "--toolchain", args.toolchain, "--strict"], + [args.mcpp, "run", "--toolchain", args.toolchain]): + print("+", " ".join(command), flush=True) + subprocess.run(command, cwd=project, env=env, check=True) + + +if __name__ == "__main__": + main() diff --git a/upstream/documents.json b/upstream/documents.json new file mode 100644 index 0000000..7fccf15 --- /dev/null +++ b/upstream/documents.json @@ -0,0 +1,24 @@ +{ + "upstream": { + "name": "nanobind", + "repository": "https://github.com/wjakob/nanobind", + "tag": "v3.1.0", + "version": "3.1.0", + "archive": { + "url": "https://github.com/wjakob/nanobind/archive/refs/tags/v3.1.0.tar.gz", + "sha256": "39659890a112e84e7263e4a263c71dd2621f866f7a4386ce95ef410e6c0e5c2f" + }, + "documents": [ + { + "path": "upstream/nanobind/LICENSE", + "source": "https://github.com/wjakob/nanobind/blob/v3.1.0/LICENSE", + "sha256": "f305091a4e57805870b217a28ea4b1f16610eece8457d2370f822a9696b75836" + }, + { + "path": "upstream/nanobind/README.md", + "source": "https://github.com/wjakob/nanobind/blob/v3.1.0/README.md", + "sha256": "d924493dcd04dc8055ad55a8228ed82d130b35e90cd2481c090143848f57734c" + } + ] + } +} diff --git a/upstream/nanobind/LICENSE b/upstream/nanobind/LICENSE new file mode 100644 index 0000000..3d3426d --- /dev/null +++ b/upstream/nanobind/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2022 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/upstream/nanobind/README.md b/upstream/nanobind/README.md new file mode 100644 index 0000000..efff040 --- /dev/null +++ b/upstream/nanobind/README.md @@ -0,0 +1,117 @@ +# nanobind: tiny and efficient C++/Python bindings + +[![Documentation](https://img.shields.io/readthedocs/nanobind/latest)](https://nanobind.readthedocs.io/en/latest/) +[![Continuous Integration](https://img.shields.io/github/actions/workflow/status/wjakob/nanobind/ci.yml?label=tests)](https://github.com/wjakob/nanobind/actions/workflows/ci.yml) +[![](https://img.shields.io/pypi/v/nanobind.svg?color=brightgreen)](https://pypi.org/pypi/nanobind/) +![](https://img.shields.io/pypi/l/nanobind.svg?color=brightgreen) +[![](https://img.shields.io/badge/Example-Link-brightgreen)](https://github.com/wjakob/nanobind_example) +[![](https://img.shields.io/badge/Changelog-Link-brightgreen)](https://nanobind.readthedocs.io/en/latest/changelog.html) + +

+ + + + nanobind logo + +

+ +_nanobind_ is a small binding library that exposes C++ types in Python and vice +versa. It is reminiscent of +[Boost.Python](https://www.boost.org/doc/libs/1_64_0/libs/python/doc/html) and +[pybind11](https://github.com/pybind/pybind11) and uses near-identical syntax. +In contrast to these existing tools, nanobind is more efficient: bindings +compile in a shorter amount of time, produce smaller binaries, and have better +runtime performance. + +More concretely, +[benchmarks](https://nanobind.readthedocs.io/en/latest/benchmark.html) show up +to **~4× faster** compile time, **~5× smaller** binaries, and **~10× lower** +runtime overheads compared to pybind11. nanobind also outperforms Cython in +important metrics (**3-12×** binary size reduction, **1.6-4×** compilation time +reduction, similar runtime performance). + +## Testimonials + +A selection of testimonials from projects that migrated from pybind11 to nanobind. + + + + + + + + +
+ +**IREE** · [LLVM Discourse](https://discourse.llvm.org/t/nanobind-for-mlir-python-bindings/83511/5) + +> *"IREE and its derivatives switched 1.5 years ago. It has been one of the single best dep decisions I've made. Not only is it much-much faster to compile, it produces smaller binaries and has a much more lean interface to the underlying Python machinery that all adds up to significant performance improvements. Worked exactly like it said on the tin."* + +— **Stella Laurenzo**, Google + +
+ +**XLA/MLIR** · [GitHub PR](https://github.com/llvm/llvm-project/pull/118583) + +> *"For a complicated Google-internal LLM model in JAX, this change improves the MLIR lowering time by around 5s (out of around 30s), which is a significant speedup for simply switching binding frameworks."* + +— **Peter Hawkins**, Google + +
+ +**Apple MLX** · [X](https://x.com/awnihannun/status/1890495434021326974) + +> *"MLX uses nanobind to bind C++ to Python. It's a critical piece of MLX infra and is why running Python code is nearly the same speed as running C++ directly. Also makes it super easy to move arrays between frameworks."* + +— **Awni Hannun**, Apple + +
+ +**JAX** · [GitHub](https://github.com/jax-ml/jax/commit/70b7d501816c6e9f131a0a8b3e4a527e53eeebd7) + +> *"nanobind has a number of [advantages](https://nanobind.readthedocs.io/en/latest/why.html), notably speed of compilation and dispatch, but the main reason to do this for these bindings is because nanobind can target the Python Stable ABI starting with Python 3.12. This means that we will not need to ship per-Python version CUDA plugins starting with Python 3.12."* + +— **Peter Hawkins**, Google + +
+ +**FEniCS / DOLFINx** · [GitHub](https://github.com/FEniCS/dolfinx/pull/2820) + +> *"nanobind is smaller than pybind11, the wrappers build faster and it has significantly improved support for wrapping multi-dimensional arrays, which we use heavily. The nanobind docs are easier to follow on the low-level details, which makes understanding the memory management in the wrapper layer easier."* + +— **Garth N. Wells** +
+ +**PennyLane** · [Release notes](https://docs.pennylane.ai/projects/catalyst/en/stable/dev/release_notes.html) + +> *"Nanobind has been developed as a natural successor to the pybind11 library and offers a number of advantages like its ability to target Python's Stable ABI."* + +
+ +## Documentation + +Please see the following links for tutorial and reference documentation in +[HTML](https://nanobind.readthedocs.io/en/latest/) and +[PDF](https://nanobind.readthedocs.io/_/downloads/en/latest/pdf/) formats. + +## License and attribution + +All material in this repository is licensed under a three-clause [BSD +license](LICENSE). + +Please use the following BibTeX template to cite nanobind in scientific +discourse: + +```bibtex +@misc{nanobind, + author = {Wenzel Jakob}, + year = {2022}, + note = {https://github.com/wjakob/nanobind}, + title = {nanobind: tiny and efficient C++/Python bindings} +} +``` + +The nanobind logo was designed by [AndoTwin Studio](https://andotwinstudio.com) +(high-resolution download: +[light](https://d38rqfq1h7iukm.cloudfront.net/media/uploads/wjakob/2023/03/27/nanobind_logo.jpg), +[dark](https://d38rqfq1h7iukm.cloudfront.net/media/uploads/wjakob/2023/03/28/nanobind_logo_dark_1.png)).