Skip to content

Codegen fixes for geoml - #299

Merged
joergbrech merged 11 commits into
mainfrom
codegen-fixes-for-geoml
Oct 2, 2026
Merged

joergbrech merged 11 commits into
mainfrom
codegen-fixes-for-geoml

Conversation

@joergbrech

@joergbrech joergbrech commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Codegen correctness fixes + dynamic-dispatch safety hardening

Summary

This batch of 11 commits came out of using real downstream plugin development
(grunk-occt, then grunk-geoml) as a deliberate stress test of grunk core —
every fix here was found because a real plugin's real generated code hit it,
not from writing speculative new tests. They range from codegen correctness
issues (silently-rejected std::string/std::vector/array parameters) to
dynamic-dispatch memory-safety gaps (Handle(Derived)→Handle(Base)
conversion, mutating calls silently no-op'ing, a dangling-pointer segfault in
Feature::as(), and sol2's unchecked-by-default argument extraction).

Changes

Codegen (grunk.codegen.generate)

  1. expand_headers() broke on nested header layouts (125299f, 834eb97)
    — a glob spanning subdirectories (e.g. geoml/<module>/*.h) collapsed each
    match to its bare filename instead of its path relative to include_dir,
    silently reconstructing the wrong path for any non-flat layout (OCCT's own
    flat layout had hidden this). Now returns each match's relative_to(include_dir)
    spelling, rendered via .as_posix() so it doesn't vary with the host
    platform's path separator (confirmed broken on Windows).

  2. std::string/std::vector<T> were silently rejected (125299f, b836a65)
    — Param.kind()'s "object" fallback rejects any parameter whose canonical
    (typedef-resolved) spelling isn't a bare identifier. std::string's own
    canonical spelling (a full std::__cxx11::basic_string<...> instantiation)
    and std::vector<T>'s own surface spelling (angle brackets) both fail
    that check outright — found wrapping geoml (has_tag, nurbs_curve,
    interpolate_curves, every filename parameter, ...). Both are now
    recognized as "passthrough" unconditionally (sol2 already converts them
    natively) before the canonical-spelling check runs. Also narrowed that
    check itself: it used to reject any class whose canonical spelling isn't a
    bare identifier, when the only real hazard is a pointer spelling.

  3. classify_param()'s None vs. "rejected" ambiguity (2742afb) —
    returning None meant both "not my concern, use the generic fallback" and
    "I explicitly reject this," indistinguishable to the caller. Added a
    generate.REJECTED sentinel, distinct from None, that Param.kind() now
    respects. This uncovered a real, previously-silent correctness bug in
    grunk-occt's own generated bindings: several OCCT methods with a mutable
    NCollection_Array1/2 out-parameter (Geom_BSplineCurve::Poles, ::Weights,
    ::Knots, ...) were being silently accepted as a plain "object" parameter
    that sol2 can never correctly fill in place.

Handle(Derived) → Handle(Base) smart-pointer conversion

  1. sol2 never actually performed the upcast (d9b0799) — add_bases<...>()
    alone isn't enough for a unique usertype like opencascade::handle<T>;
    sol2's inheritance<T>::type_unique_cast only walks a base list when
    unique_usertype_traits<T>::rebind_actual_type<Base> exists (a plugin's own
    concern) and two compile-time macros per class exist (SOL_BASE_CLASSES/
    SOL_DERIVED_CLASSES), which the generator never emitted. Added
    render_sol_base_classes_header(), producing a new, run-wide
    sol_base_classes.hpp. Without this, any function accepting a base handle
    type (e.g. BRepBuilderAPI_MakeFace(Handle(Geom_Surface))) silently
    rejected every derived handle regardless of what add_bases declared.

  2. with_std_vector<VecElement>() excluded by-reference Handle(X) elements
    (13ab623) — a fourth manifestation of CI: Add builds and tests for Clang and MSVC #4's own underlying sol2 behavior:
    cast_to_element took its element VecElement const&, and sol2's
    base-aware unique-usertype checker excludes any by-reference parameter from
    a Derived→Base conversion attempt outright. Fixed by taking the element by
    value.

Dynamic dispatch / usability

  1. DynamicFeature had no __call metamethod (c0cc16d) — a Feature
    wrapping a type with its own bound operator() (e.g. geoml's Transform)
    couldn't be called as obj(args...) from inside a recipe's decorated
    environment ("attempt to call a sol.grunk::Feature<...> value"), even
    though the same call worked undecorated. Registered
    sol::meta_function::call, forwarded through the same make_dynamic_action
    machinery the arithmetic operators already use.

  2. Mutating calls inside a decorated/parametric environment silently no-op
    (40d8a1e) — grunk's evaluation is lazy and pull-based: a node's eval()
    only runs when its own output feature is explicitly read. A bare
    obj:Mutate(...) statement (the common setter pattern) never reads that
    result, so the mutation inside it silently never runs — a real trap, not a
    hypothetical one (it's what made an early wing_loft.grr.yml attempt at
    building three gp_GTrsf transforms via separate SetValue(...) calls
    silently produce three identical, untransformed results). Added
    function_meta::receiver_is_mutating() (non-const-reference receiver and
    void return — the narrowest signal a call's only purpose is the mutation)
    and a check in make_dynamic_action that now throws immediately instead of
    silently doing nothing. modules: script bodies (undecorated dispatch) are
    unaffected.

  3. DynamicFeature::as(Type) captured a dangling raw pointer (1566d74)
    — the proxy table :as() returns captured this instead of a copy. For
    the common case of calling :as() on the unnamed result of a
    module-function call, nothing else keeps that temporary's own Lua userdata
    reachable, so once Lua's GC collected it, the captured pointer dangled; the
    next method call through the proxy then read the wrapped type's internal
    state through garbage memory (found via grunk-geoml's airplane_seats.grr.yml,
    a real, reproducible segfault). Fixed by capturing a copy of *this instead
    (Feature<object> is a cheap, shared_ptr-backed handle), while still
    passing the Feature itself — not its already-evaluated value — into the
    wrapped call, so laziness/dependency-tracking is unaffected.

  4. sol2's unchecked-by-default argument extraction (de18b58) — sol2
    defaults to unchecked userdata extraction (SOL_ALL_SAFETIES_ON off
    outside a debug build): a Lua value of one registered usertype handed to a
    function expecting a different, unrelated usertype gets blindly
    reinterpreted as the target type instead of rejected, corrupting memory and
    segfaulting in unrelated code. Found via grunk-geoml's own generated code
    (a geoml::Shape passed where a TopoDS_Shape was expected).
    grunk::dynamic now defines SOL_ALL_SAFETIES_ON=1 as an INTERFACE
    compile definition, so every consumer — grunk's own code and any downstream
    plugin linking against grunk::dynamic — gets the checked getter
    consistently (this can't be a per-project opt-in: sol2 template
    instantiations for the same types must agree on this define across every
    translation unit that touches them). The same mismatch now throws a clear,
    catchable sol::error instead of crashing.

Docs

  1. docs/usage.rst's subrecipe example was missing a call (cdab46b) —
    multiplication = recipes.multiplication (a bare reference to the
    SubRecipe object) should have been recipes.multiplication() (invoking
    it to get a RecipeCaller). Fixed in both code examples in the doc.

Test plan

  • pixi run test_cpp: 198/198 passing — every fix above landed with its
    own new regression test(s) (dynamic_operators.cpp, dynamic_serialization.cpp,
    dynamic_state.cpp, dynamic_std_vector.cpp).
  • pixi run test_python: 97/97 passing (test_codegen.py gained coverage
    for the expand_headers path fix, the std::string/std::vector fix, and
    the REJECTED sentinel).
  • Verified against two real, independent downstream plugins, not just
    synthetic tests: grunk-occt (52/52 C++ tests, 21/21 Python tests, all
    4 example recipes) and grunk-geoml (23/23 C++ tests, 18/18 Python
    tests, all 4 example recipes — including a full, line-by-line re-port of a
    real, multi-sub-recipe airplane_seats model) both rebuilt against this
    branch's tip and re-verified end to end.

Known follow-ups (not blocking, tracked separately)

  • SOL_ALL_SAFETIES_ON's checked getter for unique usertypes (Handle(X))
    doesn't consult add_bases/rebind_actual_type at all (a real, narrow,
    pre-existing sol2 limitation) — only bites a Handle(Derived) value bound to
    a Handle(Base) const& by-reference parameter. Every generated
    Handle(X) parameter already uses pass-by-value (see CI: Add builds and tests for Clang and MSVC #4/Error handling #5's own
    convention), so generated code is unaffected; only hand-written escape
    hatches that drift from that convention can hit it (one found and fixed
    downstream, in grunk-occt).
  • docs/usage.rst's dot-notation subrecipe form (multiplication.x = a)
    still doesn't actually work against this branch — only
    recipes.name():get("output") / caller["input"] = value do. This fix only
    corrected the missing () call; the deeper doc/API mismatch is still open.

@joergbrech
joergbrech merged commit a78cfe2 into main Oct 2, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant