diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b41b662..86e847a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,18 +56,17 @@ jobs: run: CLANG_FORMAT=clang-format src/cpp/tools/check_format.sh occt-guard: - # Lists builder constructions (boolean / fillet / offset) outside an occt_guard function. Non-blocking until the - # reported sites are fixed; then add --strict and drop continue-on-error. + # Every boolean / fillet / offset builder is constructed in a function that runs under occt_guard (or says, with + # `// occt_guard: the caller X ...`, that its one caller does). See src/cpp/tools/check_occt_guard.py. name: OCCT guard audit runs-on: ubuntu-latest timeout-minutes: 5 - continue-on-error: true steps: - name: Check out repository uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - name: Audit - run: python3 src/cpp/tools/check_occt_guard.py + run: python3 src/cpp/tools/check_occt_guard.py --strict sanitize: name: C++ tests (ASan + UBSan) diff --git a/src/cpp/AGENTS.md b/src/cpp/AGENTS.md deleted file mode 100644 index 655c4a2b..00000000 --- a/src/cpp/AGENTS.md +++ /dev/null @@ -1,74 +0,0 @@ -# Working rules (read before touching anything) - -These apply to every contributor, human or agent. The owner of this repo is asleep or away -while work happens, so decisions are yours to make; write down any that are not obvious. - -## Ownership - -Each area owns its directories and nothing else: - -| Area | Owns | -|---|---| -| semantic | `include/scad/semantic/`, `src/semantic/`, `tests/cpp/semantic/`, `bindings/python/bind_semantic.cpp`, `src/kernel/*` additions it needs | -| reactive | `include/scad/reactive/`, `src/reactive/`, `tests/cpp/reactive/`, `bindings/python/bind_reactive.cpp` | -| ql | `include/scad/ql/`, `src/ql/`, `tests/cpp/ql/`, `bindings/python/bind_ql.cpp` | -| io | `include/scad/io/`, `src/io/`, `tests/cpp/io/`, `bindings/python/bind_io.cpp` | -| sketch | `include/scad/sketch/`, `src/sketch/`, `tests/cpp/sketch/`, `bindings/python/bind_sketch.cpp` | -| surface | `include/scad/surface/`, `src/surface/`, `tests/cpp/surface/`, `bindings/python/bind_surface.cpp` | -| ops_geometry | `include/scad/ops/geometry/`, `src/ops/geometry/`, `tests/cpp/ops_geometry/`, `bindings/python/bind_ops_geometry.cpp` | -| ops_features | `include/scad/ops/features/`, `src/ops/features/`, `tests/cpp/ops_features/`, `bindings/python/bind_ops_features.cpp` | -| std | `include/scad/std/`, `src/std/`, `tests/cpp/std/`, `bindings/python/bind_std.cpp` | -| product | `include/scad/product/`, `src/product/`, `tests/cpp/product/`, `bindings/python/bind_product.cpp` | - -Shared, owned by the lead: `CMakeLists.txt`, `cmake/`, `include/scad/{core,topo,kernel}/`, -`src/{core,topo,kernel}/`, `bindings/python/{bindings.hpp,module.cpp,common.cpp,bind_core.cpp,bind_topo.cpp}`, -`python/`, `tests/python/{ref.py,conftest.py}`, docs. If you need a change there, make the -smallest additive edit (new function, new overload) with the Edit tool, never a rewrite, and -say so in your final report. Do not rename or reorder existing declarations: other areas are -compiling against them right now. - -Python tests live in `tests/python/test__*.py`. Golden files in `tests/golden/_*.json`. - -## Building (each person uses their own build directory) - -``` -# macOS arm64 (Homebrew OCCT 7.9.3) -cmake -S . -B build/ -G Ninja -DCMAKE_BUILD_TYPE=Debug \ - -DPython_EXECUTABLE=$PWD/.venv/bin/python \ - -Dpybind11_DIR=$($PWD/.venv/bin/python -m pybind11 --cmakedir) -DCMAKE_PREFIX_PATH=/opt/homebrew -ninja -C build/ scad_ test_ # only your area; never build "all" while others are mid-edit -./build//tests/cpp/test_ -ninja -C build/ _native # the Python module (needs every area to compile) -SCAD_BUILD_DIR=$PWD/build/ .venv/bin/python -m pytest tests/python -q -k -``` - -Build only your own targets; a sibling's half-written file must not stop you. Use a build -directory named after your area so builds never collide. - -Linux (OrbStack Ubuntu, **x86_64**; same checkout path). Shortcut: `scripts/linux.sh ...` builds and runs `test_` there (GCC 15 + libstdc++ assertions: it catches out-of-range reads, missing includes and deep-recursion overflows that macOS tolerates). Run it before you report. By hand: -`orb -m ubuntu bash -lc 'cd /Users/lildino/Project/ocws/SimpleCADAPI-native/cpp && cmake -S . -B build/linux- -G Ninja ... && ninja -C build/linux- test_'` -(`build/linux-*` and `build/mac*` are different trees on a shared filesystem: never mix them.) - -## Definition of done for an operator - -1. Same name, same keyword arguments, same defaults, same result as the Python SDK (golden test). -2. Errors are `scad::Error` with the same operation name and guidance structure. -3. A doctest case (C++) and a pytest case (Python module) each. -4. Builds warning-free with `-Wall -Wextra -Wpedantic -Wshadow -Wconversion` (already on). -5. `PORTING_STATUS.md` regenerates with it marked `done` (`tools/gen_status.py --cpp build//python`). - -## Style - -- Read the Python source of what you port *and its tests* in `../SimpleCADAPI/test/` first. -- No comments that restate the code. Comment the non-obvious: OCCT quirks, why a tolerance is what it is. -- Small files by capability; the Python files are huge, the C++ ones should not be. -- RAII, no raw owning pointers, no `new`/`delete`, no `using namespace` in headers, no macros - except include guards and test frameworks. OCCT `Handle(...)` only where OCCT demands it. -- `const` by default; `[[nodiscard]]` on functions whose result must not be dropped. -- Never swallow an exception silently. Catch at a boundary, add context, rethrow. -- Do not modify `../SimpleCADAPI` (the reference). Do not commit; do not push; do not touch git. - -## Reporting - -End your work with a short report: what is done (with test counts), what is not and why, -decisions you made, shared-file edits you made, and anything the next person must know. diff --git a/src/cpp/bindings/python/bind_reactive_graph.cpp b/src/cpp/bindings/python/bind_reactive_graph.cpp index d086576c..b1e2bc45 100644 --- a/src/cpp/bindings/python/bind_reactive_graph.cpp +++ b/src/cpp/bindings/python/bind_reactive_graph.cpp @@ -94,13 +94,15 @@ void bind_reactive_graph(py::module_& m) { py::dict scope; py::exec(kStaleSource, scope); m.attr("StaleLineageError") = scope["StaleLineageError"]; - py::register_exception_translator([](std::exception_ptr p) { + add_exception_handler(ExceptionPriority::Specific, [](std::exception_ptr p) { try { - if (p) - std::rethrow_exception(p); + std::rethrow_exception(p); } catch (const sr::StaleLineageError& e) { py::object cls = py::module_::import("simplecadapi._cpp._native").attr("StaleLineageError"); PyErr_SetObject(cls.ptr(), cls(e.node_id()).ptr()); + return true; + } catch (...) { // another type: the next handler + return false; } }); diff --git a/src/cpp/bindings/python/bind_reactive_units.cpp b/src/cpp/bindings/python/bind_reactive_units.cpp index 992a2ae4..27cf2d23 100644 --- a/src/cpp/bindings/python/bind_reactive_units.cpp +++ b/src/cpp/bindings/python/bind_reactive_units.cpp @@ -70,13 +70,15 @@ void bind_reactive_units(py::module_& m) { py::dict scope; py::exec(kUnitErrorSource, scope); m.attr("UnitValidationError") = scope["UnitValidationError"]; - py::register_exception_translator([](std::exception_ptr p) { + add_exception_handler(ExceptionPriority::Specific, [](std::exception_ptr p) { try { - if (p) - std::rethrow_exception(p); + std::rethrow_exception(p); } catch (const scad::reactive::UnitValidationError& e) { py::object cls = py::module_::import("simplecadapi._cpp._native").attr("UnitValidationError"); PyErr_SetObject(cls.ptr(), cls(e.guidance().what_happened).ptr()); + return true; + } catch (...) { // another type: the next handler + return false; } }); diff --git a/src/cpp/bindings/python/bindings.hpp b/src/cpp/bindings/python/bindings.hpp index 98498d46..352892b1 100644 --- a/src/cpp/bindings/python/bindings.hpp +++ b/src/cpp/bindings/python/bindings.hpp @@ -5,6 +5,8 @@ // call in module.cpp -- nothing else is shared. #pragma once +#include +#include #include #include #include @@ -12,6 +14,7 @@ #include #include +#include "exceptions.hpp" #include "scad/core/scalar.hpp" #include "scad/core/value.hpp" #include "scad/core/vec.hpp" @@ -42,8 +45,7 @@ struct PyVec3 { scad::Vec3 v; }; -// Installs the exception translator (scad::Error -> simplecadapi._cpp.SimpleCADError, -// plain scad exceptions -> the matching builtin, OCCT failures -> RuntimeError). +// Installs the module's exception translator and the General handler. void register_exceptions(py::module_& m); // Python value -> scad::Value (None, bool, int, float, str, list/tuple, dict). diff --git a/src/cpp/bindings/python/common.cpp b/src/cpp/bindings/python/common.cpp index 74259b74..442ad0f1 100644 --- a/src/cpp/bindings/python/common.cpp +++ b/src/cpp/bindings/python/common.cpp @@ -1,7 +1,9 @@ // Exception translation and Value <-> Python conversion. #include "bindings.hpp" +#include #include +#include #include @@ -90,33 +92,64 @@ void set_python_error(const Exception& e) { } // namespace -void register_exceptions(py::module_&) { - py::register_exception_translator([](std::exception_ptr p) { +namespace { + +struct Handler { + ExceptionPriority priority; + ExceptionHandler handle; +}; + +std::vector& handlers() { + static std::vector registered; + return registered; +} + +bool translate_general(std::exception_ptr p) { + try { + std::rethrow_exception(p); + } catch (const Error& e) { try { - if (p) - std::rethrow_exception(p); - } catch (const Error& e) { - try { - py::object errors = py::module_::import("simplecadapi._cpp.errors"); - // The message-first families are real classes in the SDK: which one this is travels with the error. - const char* family = ""; - if (dynamic_cast(&e) != nullptr) - family = "UnsupportedQueryCapabilityError"; - else if (dynamic_cast(&e) != nullptr) - family = "SemanticCapabilityError"; - else if (dynamic_cast(&e) != nullptr) - family = "TagValidationError"; - py::object exc = errors.attr("make_error")(e.operation(), guidance_to_dict(e), std::string(e.what()), family); - PyErr_SetObject(reinterpret_cast(Py_TYPE(exc.ptr())), exc.ptr()); - } catch (const py::error_already_set&) { - // errors.py unavailable (partial import): degrade to a plain ValueError with the same text. - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, e.what()); - } - } catch (const Exception& e) { - set_python_error(e); + py::object errors = py::module_::import("simplecadapi._cpp.errors"); + // The message-first families are real classes in the SDK: which one this is travels with the error. + const char* family = ""; + if (dynamic_cast(&e) != nullptr) + family = "UnsupportedQueryCapabilityError"; + else if (dynamic_cast(&e) != nullptr) + family = "SemanticCapabilityError"; + else if (dynamic_cast(&e) != nullptr) + family = "TagValidationError"; + py::object exc = errors.attr("make_error")(e.operation(), guidance_to_dict(e), std::string(e.what()), family); + PyErr_SetObject(reinterpret_cast(Py_TYPE(exc.ptr())), exc.ptr()); + } catch (const py::error_already_set&) { + // errors.py unavailable (partial import): degrade to a plain ValueError with the same text. + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, e.what()); } - // Anything else falls through to pybind11's built-in translators. + return true; + } catch (const Exception& e) { + set_python_error(e); + return true; + } catch (...) { // not a scad exception: the next handler, then pybind11's own translators + return false; + } +} + +} // namespace + +void add_exception_handler(ExceptionPriority priority, ExceptionHandler handler) { + auto& all = handlers(); + all.push_back({priority, std::move(handler)}); + std::stable_sort(all.begin(), all.end(), [](const Handler& a, const Handler& b) { return a.priority < b.priority; }); +} + +void register_exceptions(py::module_&) { + add_exception_handler(ExceptionPriority::General, translate_general); + py::register_exception_translator([](std::exception_ptr p) { + if (!p) + return; + for (const Handler& handler : handlers()) + if (handler.handle(p)) + return; }); } diff --git a/src/cpp/bindings/python/exceptions.hpp b/src/cpp/bindings/python/exceptions.hpp new file mode 100644 index 00000000..6623b03e --- /dev/null +++ b/src/cpp/bindings/python/exceptions.hpp @@ -0,0 +1,25 @@ +// The module's exception handlers (see common.cpp). Kept apart from bindings.hpp so that the raw-OCCT shim, which +// does not use the SDK types, can register its Standard_Failure handler. +#pragma once + +#include +#include + +namespace scad::pybind { + +// The module has ONE exception translator (installed by register_exceptions) that asks its handlers in priority +// order, most specific first, whatever the order the bindings were registered in. pybind11 itself asks translators +// newest first, which would make the result depend on import order wherever one exception type derives from another +// (UnitValidationError is an Error, StaleLineageError a ValueError). +enum class ExceptionPriority : int { + Specific = 0, // one named exception type of one area (reactive errors) + Occt = 10, // Standard_Failure: OCCT's exceptions are not std::exception + General = 20, // scad::Error -> simplecadapi._cpp.SimpleCADError, scad::Exception -> the matching builtin +}; + +// A handler rethrows `p`, and when it recognises the type sets the Python error and returns true; returning false +// means "not mine", and the next handler is asked. Anything no handler takes reaches pybind11's own translators. +using ExceptionHandler = std::function; +void add_exception_handler(ExceptionPriority priority, ExceptionHandler handler); + +} // namespace scad::pybind diff --git a/src/cpp/bindings/python/occt/bind_occt_query.cpp b/src/cpp/bindings/python/occt/bind_occt_query.cpp index 0c687066..8a8ecbbc 100644 --- a/src/cpp/bindings/python/occt/bind_occt_query.cpp +++ b/src/cpp/bindings/python/occt/bind_occt_query.cpp @@ -91,6 +91,7 @@ #include #include +#include "../exceptions.hpp" #include "occt.hpp" namespace scad::pybind::occt { @@ -244,16 +245,18 @@ void bind_query(py::module_& m) { PyErr_NewException("simplecadapi._cpp._native._occt.Standard_Failure", PyExc_Exception, nullptr); Py_INCREF(failure_type); m.attr("Standard_Failure") = py::reinterpret_borrow(failure_type); - py::register_exception_translator([](std::exception_ptr p) { + add_exception_handler(ExceptionPriority::Occt, [](std::exception_ptr p) { try { - if (p) - std::rethrow_exception(p); + std::rethrow_exception(p); } catch (const Standard_Failure& e) { const char* msg = e.GetMessageString(); std::string text = e.DynamicType()->Name(); if (msg != nullptr && *msg != '\0') text += std::string(": ") + msg; PyErr_SetString(failure_type, text.c_str()); + return true; + } catch (...) { // another type: the next handler + return false; } }); } diff --git a/src/cpp/docs/HANDOFF.md b/src/cpp/docs/HANDOFF.md deleted file mode 100644 index 8584d3cb..00000000 --- a/src/cpp/docs/HANDOFF.md +++ /dev/null @@ -1,73 +0,0 @@ -# Handoff (first written 2026-10-21 at a pause; status table updated after work resumed) - -Read this first when resuming. Everything here was checked by running it, except where marked -"agent-reported". - -## State - -Verified on macOS arm64 (Debug, stdlib bounds checks on): the whole tree builds including the -Python module; 10 C++ suites pass, 450 test cases / ~4,075 assertions; the Python suite passes -(325 tests) against the real `_native`. - -| Area | State | -|---|---| -| core, kernel, topo | done | -| semantic (tags, lineage, tracking, finalize) | done | -| reactive (Expr/Var, units, graph, recompute engine) | done; `tolerance.py` NOT ported | -| io (STEP/STL/OBJ/GLB/BREP, mesh, serialize) | done | -| ql (selector language) | done | -| sketch (42 operators, native solver) | done | -| surface (12 operators, Gordon vendored) | done | -| ops_geometry (33 operators + aliases) | done | -| ops_features (extrude, fillet, boolean, patterns, ...) | done: 32 C++ cases, 37 golden pytest parity tests; `render_screenshot_rpath` not ported (rendering out of scope) | -| product (parts, assemblies, constraints) | done: 28 operators + solver, 44 C++ cases, 28 goldens; `build/` (`@part`, `@assemble`) not ported (coupled to `artifacts/`, which stays Python) | -| std (gear, bearing, fastener) | done: 11 gears, ball bearing, roller-chain sprocket, bolt, nut; 33 C++ cases; 33 golden pytest parity tests pass (macOS). `build_ball_bearing` (needs the Python `build/` layer) not ported. KNOWN GAP: the plain cycloidal disc's face area differs from the reference by ~2e-5 (test tolerance loosened to 1e-4 with a comment); the spline fit itself matches the reference to 6e-14, so the cause is not found | - -Linux x86_64 (OrbStack Ubuntu, GCC 15, OCCT 7.9.2): C++ suites verified by me for core, kernel, -topo, semantic, reactive, io, ql, sketch, surface, ops_geometry, ops_features, product (same -case counts as macOS). Linux Python tests have NOT been run (no numpy in the VM: apt is broken -there; use a venv). Linux caught missing standard includes in ops/features: fixed. -Windows and Linux aarch64: never built. - -Speed (agent-reported, Release): `make_box_rsolid` 97 us vs 2225 us in the Python SDK (23x), -cylinder 14x. Bare OCCT is ~15 us, so the remaining cost is in tracking/finalize. -Baseline reproduction: `tools/bench/bench_reference.py`, `tools/bench/bench_native.py`. - -## Things running when work stopped - -- The product engineer has stopped (paused at the user's request). One engineer (ops_features) may still be mid-task in the background; check for files - changed in the last minutes before building (`find src include tests -mmin -10`). If the - build is broken in `ops/features` or `product`, that is probably a half-written file. -- A static OCCT 7.9.3 build in the Linux VM (`/tmp/occt-static` there, log: - `.setup/occt_static2.log`, ends with `script-exit N` and `occtdone2`). Purpose: prove the - release recipe (`tools/build_occt.py`) works; afterwards configure with - `-DSCAD_OCCT_PREFIX=/tmp/occt-static` and run the tests against it. - -## Not verified / known gaps - -- Std parts: Linux run and Release benchmark numbers pending when this line was written. - -- GitHub CI (`.github/workflows/`) and wheel packaging (`pyproject.toml`) were never run. -- `tools/build_occt.py` failed once on a flaky download inside the VM; retries were added; - the source was then fetched on the host (`.setup/occt/`) and the build started from it. -- `PORTING_STATUS.md` "done" means "name exported", not "aligned". Generated with a stub - package because the reference interpreter is Python 3.10 and the module 3.12. -- Python-side package parity (every name `simplecadapi` exports) is not complete. -- Nothing is committed to git. The repo has no history. - -## Decision pending: SMLib (NVIDIA usd-brep) - -Recommendation, with the evidence, is in `docs/research/smlib-usd-brep.md`: do not make it a -default dependency; at most an optional, default-OFF provider behind -`scad::surface::SurfaceFitter` after per-operation A/B tests. Not implemented. Untested areas -that could change the verdict: offset curves/surfaces, tolerance-driven approximation with -knot removal, constrained fitting, free-form deformation volumes, Linux/Windows builds. - -## How to resume - -1. Build and test: see README.md ("Build (development)") and `scripts/linux.sh `. -2. Per-area work orders: `docs/briefs.md`. Rules every contributor follows: `AGENTS.md`. -3. The API quota ("5-hour limit") was hit twice when many agents ran at once; stagger them. -4. Next steps in order: finish ops_features and product; start std; fix the status - generator; full Linux integration run; run the static-OCCT wheel build on each platform; - benchmark against the reference; decide SMLib; then commit. diff --git a/src/cpp/src/ops/features/extrude_until.cpp b/src/cpp/src/ops/features/extrude_until.cpp index 45d5d9ff..4563f63d 100644 --- a/src/cpp/src/ops/features/extrude_until.cpp +++ b/src/cpp/src/ops/features/extrude_until.cpp @@ -73,6 +73,7 @@ bool crosses_direction(const TopoDS_Face& face, const Vec3& axis) { } // The target's boundary faces the prism touches, sewn into surfaces. +// occt_guard: the caller extrude_until_rsolid runs this inside occt_guard. std::vector contact_surfaces(const TopoDS_Shape& target, const TopoDS_Shape& prism, const Vec3& axis) { BRepAlgoAPI_Common common(target, prism); common.Build(); @@ -118,6 +119,7 @@ std::vector contact_surfaces(const TopoDS_Shape& target, const Top } // The parts of the prism on one side of `surface`: the near (`keep_top`) or the far one. +// occt_guard: the caller extrude_until_rsolid runs this inside occt_guard. std::vector split_on_surface(const TopoDS_Shape& prism, const TopoDS_Shape& surface, bool keep_top) { TopTools_ListOfShape arguments, tools; arguments.Append(prism); diff --git a/src/cpp/src/ops/features/taper.cpp b/src/cpp/src/ops/features/taper.cpp index 4ae1dee2..cf8362ee 100644 --- a/src/cpp/src/ops/features/taper.cpp +++ b/src/cpp/src/ops/features/taper.cpp @@ -24,6 +24,7 @@ namespace scad { namespace { // The loft of `wire` to its planar offset moved by `move`: one tapered layer. +// occt_guard: the caller extrude_taper_rsolid runs this inside occt_guard. TopoDS_Shape tapered_layer(const TopoDS_Wire& wire, double offset, const gp_Trsf& move) { BRepOffsetAPI_MakeOffset offsetter(wire, GeomAbs_Intersection, false); offsetter.Perform(offset); diff --git a/src/cpp/src/surface/fitter.cpp b/src/cpp/src/surface/fitter.cpp index 995118b7..bfe34d63 100644 --- a/src/cpp/src/surface/fitter.cpp +++ b/src/cpp/src/surface/fitter.cpp @@ -52,6 +52,8 @@ class OcctSurfaceFitter final : public SurfaceFitter { return builder.Surface(); } + // occt_guard: the caller fill_face is only called from operator_scope bodies (faces_from_edges.cpp, shell_ops.cpp), + // which are guarded. TopoDS_Face fill(const FillingProblem& problem) const override { const SurfaceFillingSettings& s = problem.settings; BRepOffsetAPI_MakeFilling builder(s.degree, s.points_per_curve, s.iterations, s.anisotropic, s.tolerance_2d, diff --git a/src/cpp/src/surface/loft.cpp b/src/cpp/src/surface/loft.cpp index cf487fc0..37f15eff 100644 --- a/src/cpp/src/surface/loft.cpp +++ b/src/cpp/src/surface/loft.cpp @@ -56,6 +56,7 @@ void validate_sections(const std::vector& sections) { throw ValueError("loft_rshell allows Vertex sections only at the start or end"); } +// occt_guard: the caller loft_rshell runs this inside occt_guard. TopoDS_Shell make_loft_shell(const std::vector& sections, bool ruled) { BRepOffsetAPI_ThruSections builder(false, ruled); builder.CheckCompatibility(true); diff --git a/src/cpp/src/surface/trim.cpp b/src/cpp/src/surface/trim.cpp index 1bce5a00..20f9be27 100644 --- a/src/cpp/src/surface/trim.cpp +++ b/src/cpp/src/surface/trim.cpp @@ -222,6 +222,7 @@ TopoDS_Face single_trimmed_face(const TopoDS_Shape& shape, const std::string& de return faces.front(); } +// occt_guard: the caller trim_surface_rface runs this inside operator_scope (which is guarded + occt_guard). TopoDS_Face trim_surface_face(const TopoDS_Face& carrier, const TopoDS_Wire& outer, const std::vector& holes, double tolerance) { const Handle(Geom_Surface) surface = BRep_Tool::Surface(carrier); diff --git a/src/cpp/tests/python/test_exception_translation.py b/src/cpp/tests/python/test_exception_translation.py new file mode 100644 index 00000000..058ba1c5 --- /dev/null +++ b/src/cpp/tests/python/test_exception_translation.py @@ -0,0 +1,31 @@ +"""One exception translator asks its handlers most specific first, whatever the order the areas were bound in.""" + +from __future__ import annotations + +import pytest + +import simplecadapi._cpp._native as native +from simplecadapi._cpp._native import _occt + + +def test_an_occt_failure_is_the_modules_standard_failure() -> None: + with pytest.raises(_occt.Standard_Failure, match="Standard_ConstructionError"): + _occt.gp_Dir(0, 0, 0) + + +def test_a_unit_error_is_its_own_class_not_the_general_sdk_error() -> None: + """UnitValidationError derives from scad::Error in C++: the general handler would turn it into SimpleCADError.""" + with pytest.raises(native.UnitValidationError) as caught: + native.LENGTH.square_root() + assert type(caught.value) is native.UnitValidationError + + +def test_a_stale_lineage_error_is_its_own_class_not_a_plain_value_error() -> None: + """StaleLineageError derives from ValueError in C++, which the general handler would also take.""" + ours, theirs = native.OperationGraph("g"), native.OperationGraph("g") + first = ours.add_node("root", {"v": 1}, node_id="same") + theirs.add_node("root", {"v": 2}, node_id="same") + tip = ours.add_node("join", {}, inputs=[first]) + with pytest.raises(native.StaleLineageError) as caught: + theirs.adopt(tip) + assert type(caught.value) is native.StaleLineageError and caught.value.node_id == "same" diff --git a/src/cpp/tools/check_occt_guard.py b/src/cpp/tools/check_occt_guard.py index a02d80f7..58726d5c 100755 --- a/src/cpp/tools/check_occt_guard.py +++ b/src/cpp/tools/check_occt_guard.py @@ -6,7 +6,8 @@ Heuristic, not exact: the "function" is the outermost non-namespace, non-type brace block around the site, and the site passes if that block mentions occt_guard / rethrow_occt_failure. A function that is only ever called from inside -an occt_guard lambda is reported although it is fine (a false positive: wrap it anyway or note it). Exit status is 0 +an occt_guard lambda says so with a comment `// occt_guard: the caller runs this inside occt_guard` (above or +in the function); without it, it is reported. Exit status is 0 unless --strict is given and violations exist. """ from __future__ import annotations @@ -22,7 +23,10 @@ BUILDER = re.compile( CONSTRUCT = re.compile( r"(?:\bnew\s+|make_(?:unique|shared)\s*<\s*)?\b(?:BRepAlgoAPI_(?:Fuse|Cut|Common|Section)|BRepFilletAPI_\w+|" r"BRepOffsetAPI_\w+)\b(?:\s*>)?\s*(?:\w+\s*[({;=]|[({])") -GUARD = re.compile(r"\b(occt_guard|rethrow_occt_failure)\b") +GUARD = re.compile(r"\b(occt_guard|operator_scope|rethrow_occt_failure)\b") # operator_scope = guarded + occt_guard +# A helper that is only ever called from inside a guard says so, once, above (or in) the function; the audit takes +# the claim at its word, and a reviewer can check the one caller it names. +CALLER_GUARDS = re.compile(r"occt_guard:\s*the caller\b") SKIP_DIRS = {"build", "third_party", "occt_dev"} @@ -92,7 +96,8 @@ def scan(path: Path): span = next(((s, e) for s, e in spans if s <= m.start() <= e), None) if span is None: continue # declaration at class/namespace scope (member), not a call site - if not GUARD.search(code[span[0]:span[1]]): + claim = raw[max(0, span[0] - 400):span[1]] + if not GUARD.search(code[span[0]:span[1]]) and not CALLER_GUARDS.search(claim): hits.append((raw.count("\n", 0, m.start()) + 1, BUILDER.search(after).group(1))) return hits diff --git a/src/cpp/tools/landing_plan.py b/src/cpp/tools/landing_plan.py new file mode 100644 index 00000000..30762267 --- /dev/null +++ b/src/cpp/tools/landing_plan.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Print the landing plan: which files go into which pull request of the stack (see docs/LANDING_PLAN.md). + + python3 src/cpp/tools/landing_plan.py # summary table (files, lines), rule check + python3 src/cpp/tools/landing_plan.py --files # every file of every PR + python3 src/cpp/tools/landing_plan.py --pr 6 # the files of one PR + python3 src/cpp/tools/landing_plan.py --rev WORKTREE # the working tree (tracked + untracked, not ignored) + +By default the tree of HEAD is read (`git ls-tree -r --name-only HEAD`). The universe is every file below src/cpp plus the +Python files that exist only to drive the compiled module (src/simplecadapi/_cpp, src/simplecadapi/_glue, pyproject.toml, +.github/workflows). Each file is assigned by the longest matching prefix in PRS below; the script exits 1 if a file +matches no prefix (left over) or if a prefix matches nothing (a stale rule). Every file then belongs to exactly one PR +by construction. Nothing here creates branches or builds anything. +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from collections import Counter +from pathlib import Path + +C = "src/cpp/" + +# (title, [path prefixes]). A prefix matches a file when the file path starts with it; the longest prefix wins. +PRS: list[tuple[str, list[str]]] = [ + ("build, CI, format, docs", [ + C + "CMakeLists.txt", C + "src/CMakeLists.txt", C + "cmake/ScadCompile.cmake", C + "cmake/ScadOcct.cmake", + C + "tests/cpp/CMakeLists.txt", C + "tests/cpp/test_main.cpp", C + "third_party/doctest/", + C + ".clang-format", C + ".clang-tidy", C + ".gitignore", C + "tools/check_format.sh", C + "tools/build_occt.py", + C + "tools/check_occt_guard.py", C + "tools/lsan.supp", C + "tools/gen_stubs.sh", + C + "tools/landing_plan.py", C + "tools/gen_status.py", C + "scripts/", + C + "README.md", C + "CONTRIBUTING.md", C + "ARCHITECTURE.md", C + "AGENTS.md", C + "PORTING_STATUS.md", + C + "docs/READING_ORDER.md", C + "docs/LANDING_PLAN.md", C + "docs/DEVIATIONS.md", C + "docs/HANDOFF.md", + C + "docs/briefs.md", + ]), + ("core, topo, kernel", [ + C + "include/scad/core/", C + "include/scad/topo/", C + "include/scad/kernel/", + C + "src/core/", C + "src/topo/", C + "src/kernel/", + C + "tests/cpp/core/", C + "tests/cpp/topo/", C + "tests/cpp/kernel/", + C + "docs/memory.md", C + "tools/bench/", + ]), + ("semantic (tags, lineage, tracking, finalize)", [ + C + "include/scad/semantic/", C + "src/semantic/", C + "tests/cpp/semantic/", + ]), + ("reactive (expressions, units, graph, recompute)", [ + C + "include/scad/reactive/", C + "src/reactive/", C + "tests/cpp/reactive/", + ]), + ("io, render, ql", [ + C + "include/scad/io/", C + "src/io/", C + "tests/cpp/io/", C + "tests/golden/io_", C + "docs/io.md", + C + "include/scad/render/", C + "src/render/", C + "tests/cpp/render/", C + "docs/render.md", + C + "docs/render/", + C + "include/scad/ql/", C + "src/ql/", C + "tests/cpp/ql/", + ]), + ("ops_geometry, ops_features", [ + C + "include/scad/ops/", C + "src/ops/", C + "tests/cpp/ops_geometry/", C + "tests/cpp/ops_features/", + ]), + ("sketch, surface", [ + C + "include/scad/sketch/", C + "src/sketch/", C + "tests/cpp/sketch/", C + "docs/sketch-solver.md", + C + "include/scad/surface/", C + "src/surface/", C + "tests/cpp/surface/", + C + "cmake/ScadGordon.cmake", C + "third_party/occ_gordon/", + ]), + ("product, std", [ + C + "include/scad/product/", C + "src/product/", C + "tests/cpp/product/", + C + "include/scad/std/", C + "src/std/", C + "tests/cpp/std/", + ]), + ("python bindings, adapter, parity tests", [ + C + "bindings/python/", "src/simplecadapi/_cpp/", "src/simplecadapi/_glue/", + C + "tests/python/", C + "tests/golden/", + C + "tools/graph_parity/", C + "docs/NATIVE_INTEGRATION.md", C + "docs/NATIVE_PROGRESS.md", C + "docs/PERF.md", + ]), + ("OCCT shim, wheels, release, research", [ + C + "bindings/python/occt/", C + "occt_dev/", C + "docs/OCCT_BINDINGS.md", C + "tools/occt_usage_trace.json", + "src/simplecadapi/_cpp/occt.py", "src/simplecadapi/_cpp/_occt_layout.json", + "pyproject.toml", ".github/workflows/", C + ".github/", C + "tests/wheel_smoke.py", + C + "docs/research/", C + "tools/research/", + ]), +] +# Files the glob rules above would give to an earlier, broader prefix are overridden by the longest match; the golden +# files of tests/golden other than io_* therefore land in the bindings PR (the prefix C + "tests/golden/"). + + +def git(*args: str) -> str: + return subprocess.run(["git", *args], check=True, capture_output=True, text=True).stdout + + +def universe(rev: str) -> list[str]: + if rev == "WORKTREE": + names = git("ls-files", "--cached", "--others", "--exclude-standard").splitlines() + else: + names = git("ls-tree", "-r", "--name-only", rev).splitlines() + wanted = (C, "src/simplecadapi/_cpp/", "src/simplecadapi/_glue/", ".github/workflows/") + out = [n for n in names if n.startswith(wanted) or n == "pyproject.toml"] + if rev == "WORKTREE": + out = [n for n in out if Path(n).is_file()] + return sorted(out) + + +def is_data(path: str) -> bool: + """Vendored code, recorded goldens and binary/JSON data: counted apart, they are not reviewed line by line.""" + return (path.startswith(C + "third_party/") or path.startswith(C + "tests/golden/") or path.endswith(".png") + or path.endswith(".json") or path.endswith("tracking_golden.hpp")) + + +def line_counts(rev: str, files: list[str]) -> dict[str, int]: + counts: dict[str, int] = {} + if rev == "WORKTREE": + for f in files: + counts[f] = Path(f).read_bytes().count(b"\n") + return counts + proc = subprocess.run(["git", "cat-file", "--batch"], input="".join(f"{rev}:{f}\n" for f in files).encode(), + check=True, capture_output=True) + data, pos = proc.stdout, 0 + for f in files: + end = data.index(b"\n", pos) + _sha, _type, size = data[pos:end].decode().split() + pos = end + 1 + counts[f] = data[pos:pos + int(size)].count(b"\n") + pos += int(size) + 1 + return counts + + +def assign(files: list[str]) -> tuple[dict[int, list[str]], list[str], list[str]]: + rules = [(prefix, i) for i, (_title, prefixes) in enumerate(PRS, 1) for prefix in prefixes] + seen = Counter(prefix for prefix, _ in rules) + dup = [p for p, n in seen.items() if n > 1] + if dup: + sys.exit(f"duplicate prefixes: {dup}") + groups: dict[int, list[str]] = {i: [] for i in range(1, len(PRS) + 1)} + left_over: list[str] = [] + used: set[str] = set() + for f in files: + best = max((r for r in rules if f.startswith(r[0])), key=lambda r: len(r[0]), default=None) + if best is None: + left_over.append(f) + else: + groups[best[1]].append(f) + used.add(best[0]) + stale = sorted({p for p, _ in rules} - used) + return groups, left_over, stale + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--rev", default="HEAD", help="a git revision, or WORKTREE (default HEAD)") + ap.add_argument("--files", action="store_true", help="list every file") + ap.add_argument("--pr", type=int, help="list the files of this PR only") + args = ap.parse_args() + + root = Path(git("rev-parse", "--show-toplevel").strip()) + import os + os.chdir(root) + + files = universe(args.rev) + groups, left_over, stale = assign(files) + lines = line_counts(args.rev, files) + + if args.pr: + for f in groups[args.pr]: + print(f) + else: + total_f = total_l = 0 + total_d = 0 + print(f"{'PR':>2} {'files':>5} {'lines':>7} {'data':>7} title") + print(" lines = code, docs, scripts; data = vendored code, goldens, json (png files count as 0)") + for i, (title, _) in enumerate(PRS, 1): + n = len(groups[i]) + ln = sum(lines[f] for f in groups[i] if not is_data(f)) + dl = sum(lines[f] for f in groups[i] if is_data(f) and not f.endswith(".png")) + total_f, total_l, total_d = total_f + n, total_l + ln, total_d + dl + print(f"{i:>2} {n:>5} {ln:>7} {dl:>7} {title}") + print(f"{'':>2} {total_f:>5} {total_l:>7} {total_d:>7} total ({len(files)} files in the universe)") + if args.files: + for i, (title, _) in enumerate(PRS, 1): + print(f"\n== PR {i}: {title}") + for f in groups[i]: + print(f"{'-' if f.endswith('.png') else lines[f]:>7} {f}") + + ok = True + if left_over: + ok = False + print("\nLEFT OVER (matches no PR):", *left_over, sep="\n ", file=sys.stderr) + if stale: + ok = False + print("\nSTALE RULES (match no file):", *stale, sep="\n ", file=sys.stderr) + assigned = sum(len(g) for g in groups.values()) + if assigned != len(files): + ok = False + print(f"\nassigned {assigned} of {len(files)} files", file=sys.stderr) + if not args.pr: + print("\ncheck:", "every file in exactly one PR, no stale rule" if ok else "FAILED") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main())