From 125299fa62c75e1351adfdabd80e92a1d296bb33 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Mon, 28 Sep 2026 09:54:54 +0200 Subject: [PATCH 01/11] fix two issues in geoml: Repair std::string/std::vector binding in sol2 and prperly expand headers --- python/grunk/codegen/generate.py | 105 +++++++++++++++++++++++++++++-- 1 file changed, 101 insertions(+), 4 deletions(-) diff --git a/python/grunk/codegen/generate.py b/python/grunk/codegen/generate.py index 4b940a5..16536e3 100644 --- a/python/grunk/codegen/generate.py +++ b/python/grunk/codegen/generate.py @@ -107,7 +107,26 @@ def expand_headers(patterns: list[str], include_dir: Path, exclude_headers: list for pattern in patterns: is_glob = any(ch in pattern for ch in "*?[") if is_glob: - matches = sorted(p.name for p in include_dir.glob(pattern) if p.name not in excluded) + # Path.relative_to(include_dir), not the bare basename (p.name): a glob + # like "gp_*.hxx" against a flat include_dir (OCCT's own layout) makes no + # difference here (a flat file's relative path already equals its + # basename), but a glob spanning subdirectories - e.g. "geoml//*.h" + # - previously collapsed to just the trailing filename, which + # process_module then re-joined onto include_dir directly + # (include_dir / header), silently reconstructing the WRONG path for + # anything not sitting flat under include_dir (confirmed the hard way + # against a real nested-header library: a TranslationUnitLoadError trying + # to parse "/surfaces.h", which doesn't exist - the real file + # was "/geoml/surfaces/surfaces.h"). exclude_headers is + # matched against this same relative-path spelling, so a nested-layout + # plugin's own exclude_headers entries should be relative-path spelled too + # (a flat-layout plugin's existing bare-filename entries are unaffected, + # since relative path and basename coincide there). + matches = sorted( + str(p.relative_to(include_dir)) + for p in include_dir.glob(pattern) + if str(p.relative_to(include_dir)) not in excluded + ) if not matches: raise RuntimeError(f"header glob {pattern!r} matched no files in {include_dir}") else: @@ -162,6 +181,57 @@ def expand_headers(patterns: list[str], include_dir: Path, exclude_headers: list # "object" rather than rejected. BARE_TYPE_NAME = re.compile(r"[A-Za-z_]\w*(::[A-Za-z_]\w*)*") +# std::string - sol2 converts a Lua string to/from std::string automatically, no +# wrapping needed, exactly like a bare fundamental (hence "passthrough", not +# "object" - it behaves like a value, not a Lua-side-identity usertype). Needs this +# explicit, unconditional built-in rather than falling through to the "object" +# fallback below: std::string's *surface* spelling ("std::string") matches +# BARE_TYPE_NAME fine, but its *canonical* (typedef-resolved) spelling is whichever +# standard library implementation's own real template instantiation (libstdc++'s +# std::__cxx11::basic_string, std::allocator>), +# which does not match BARE_TYPE_NAME (angle brackets, commas) - the "object" +# fallback's own canonical cross-check (see Param.kind()) used to reject on this +# basis alone, silently rejecting every std::string parameter/return of any plugin +# wrapping any library that uses std::string directly (found the hard way wrapping +# geoml: has_tag, every exporter/importer's filename parameter, ... all silently +# rejected until this became a built-in). Genuinely library-agnostic - not an idiom +# of any one third-party library, so belongs here rather than behind a +# CodeGenerator.classify_param() override. +CXX_STD_STRING = "std::string" + +# std::vector - sol2 already converts a Lua table to/from std::vector natively +# (its own generic container support) whenever T itself is push/gettable, with zero +# wrapping code needed in the emitted lambda body, as long as this generator +# classifies the *whole* std::vector as a plain "passthrough"-shaped parameter +# rather than rejecting it. Like std::string above, this needs its own built-in +# rather than the "object" fallback: a parameter/return spelled directly as +# "std::vector" (as opposed to hidden behind a library's own typedef, e.g. +# OCCT's TColgp_Array1OfPnt-style indirection - not this pattern's concern, see a +# CodeGenerator subclass's own classify_param() for that) fails even the *surface* +# BARE_TYPE_NAME check (angle brackets), let alone the canonical one - rejected +# outright before a subclass's own classify_param() ever gets a chance to special- +# case it (found the hard way wrapping geoml: nurbs_curve, interpolate_curves, +# translate, every extract_control_point_* accessor, ... all silently rejected). +# Deliberately permissive about the *element* type T - any CXX_FUNDAMENTAL_TYPES +# member, std::string itself, or any other plausible bare class name (registered by +# this run or not - exactly Param.kind()'s own "object" fallback logic for a +# standalone parameter, reapplied here to one vector element) is accepted, since +# none of those need any manual per-element conversion for sol2 to already handle a +# std::vector of them correctly. +STD_VECTOR_PATTERN = re.compile(r"^std::vector<\s*(.+?)\s*>$") + + +def _std_vector_element_supported(elem: str, registered_types: set[str], registered_enums: set[str]) -> bool: + """Whether `elem` (a std::vector's own T, already stripped of surrounding + whitespace) is a type sol2 can already push/get on its own, needing no manual + conversion - see STD_VECTOR_PATTERN's own comment for the full rationale.""" + if elem in CXX_FUNDAMENTAL_TYPES or elem == CXX_STD_STRING: + return True + if elem in registered_types or elem in registered_enums: + return True + return bool(BARE_TYPE_NAME.fullmatch(elem)) + + # Operator overloads (see python/grunk/codegen/README.md's "Operator overloads and # friend free functions"): C++ operator token -> sol2 meta_function name. # Deliberately a small subset of what C++ allows overloading, not "every operator @@ -309,6 +379,20 @@ class - registered by this run or not, see below) need zero # fundamental above - reuses the "passthrough" kind rather than a new one. if self.base in registered_enums: return None if self.is_mutable_ref else "passthrough" + # std::string/std::vector - see their own module-level comments for why + # these need to be unconditional built-ins (ahead of registered_types/ + # classify_param, exactly like the fundamentals/enum checks above) rather + # than falling through to the "object" fallback below or being left to each + # plugin's own classify_param() override: both are genuinely library- + # agnostic (pure standard-library idioms, not any one third-party library's + # own convention), and the "object" fallback's own canonical/bare-type-name + # checks reject both outright regardless (std::string's canonical spelling, + # and std::vector's own *surface* spelling, both contain angle brackets). + if self.base == CXX_STD_STRING: + return None if self.is_mutable_ref else "passthrough" + m_vec = STD_VECTOR_PATTERN.fullmatch(self.base) + if m_vec and _std_vector_element_supported(m_vec.group(1), registered_types, registered_enums): + return None if self.is_mutable_ref else "passthrough" if self.base in registered_types: return "object" kind = hooks.classify_param(self, registered_types, registered_enums) @@ -325,16 +409,29 @@ class - registered by this run or not, see below) need zero # to notice it's secretly a pointer, but self.canonical can (found # the hard way: silently pushing a raw pointer as if it were a plain # object is a different, riskier shape than this fallback is meant - # to cover). + # to cover). Deliberately checks for a *pointer* spelling specifically + # (trailing "*"), not "canonical_base doesn't look like a bare type name" in + # general - that broader check used to reject any class whose canonical + # spelling happens to be a template instantiation (std::string's own + # standard-library implementation, or any other class template used + # directly), even though a template instantiation is exactly as safe a + # "genuine, stable-identity class" as a plain class name is; only a pointer + # canonical is the actual, documented hazard this check exists to catch. canonical_base = strip_type(self.canonical) if self.canonical else None - if canonical_base is not None and not BARE_TYPE_NAME.fullmatch(canonical_base): + canonical_is_pointer = canonical_base is not None and canonical_base.endswith("*") + if canonical_is_pointer: return None if self.is_mutable_ref: # Safe (a mutable reference to a genuine, stable-identity class - # same as an in-run registered class already supports) only when # the canonical spelling positively confirms this isn't secretly # a fundamental; unavailable (a return-type check) or actually - # fundamental both stay conservative and rejected. + # fundamental both stay conservative and rejected. canonical_base + # need not itself be a "bare type name" here - a template + # instantiation (std::vector, a real class with its own + # stable identity) is exactly as safe as a bare class name for this + # purpose, so only an actual CXX_FUNDAMENTAL_TYPES match (or no + # canonical spelling at all) is disqualifying. if canonical_base is None or canonical_base in CXX_FUNDAMENTAL_TYPES: return None return "object" From b836a656f97765f0b48f7a527cf977454a830873 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Mon, 28 Sep 2026 09:57:48 +0200 Subject: [PATCH 02/11] add unit tests for expanded headers and std::string/std::vector fix --- tests/python/test_codegen.py | 126 +++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/tests/python/test_codegen.py b/tests/python/test_codegen.py index 8a9b65e..9c5f2dd 100644 --- a/tests/python/test_codegen.py +++ b/tests/python/test_codegen.py @@ -133,6 +133,79 @@ def test_param_kind_typedef_hiding_a_pointer_stays_rejected(): assert generate.Param("WidgetAlias", "x", canonical="Widget").kind(set(), set(), _hooks) == "object" +def test_param_kind_canonical_template_instantiation_does_not_reject(): + # Regression test: the canonical-spelling cross-check used to reject + # *any* class whose canonical spelling isn't itself a bare type name + # (BARE_TYPE_NAME.fullmatch), not just a pointer - which silently broke + # every std::string parameter of any plugin using it directly (found + # wrapping geoml: std::string's own canonical spelling is libstdc++'s real + # template instantiation, std::__cxx11::basic_string, which + # doesn't match BARE_TYPE_NAME at all - angle brackets, commas). "Widget" + # here plays the role of any class whose canonical spelling happens to be + # a template instantiation (its own standard-library implementation, or + # any other class template used directly) - exactly as safe a "genuine, + # stable-identity class" as a plain class name, and must classify as + # "object" here, the same as a plain canonical spelling already does two + # tests up. Only a *pointer* canonical spelling (previous test) is the + # actual, documented hazard this cross-check exists to catch. + assert generate.Param("Widget", "x", canonical="ns::Widget>").kind( + set(), set(), _hooks + ) == "object" + # Same, but as a confirmed-safe mutable "out" parameter (the other branch + # this cross-check feeds into) - a template-instantiated canonical is not + # a fundamental, so this should be accepted exactly like a plain-class + # canonical mutable ref already is. + assert generate.Param("Widget &", "x", canonical="ns::Widget>").kind( + set(), set(), _hooks + ) == "object" + + +# --------------------------------------------------------------------------- +# Param.kind() - std::string/std::vector built-ins. Genuinely library- +# agnostic (pure standard-library idioms, not any one third-party library's +# own convention) - see CXX_STD_STRING/STD_VECTOR_PATTERN's own module-level +# comments for the full rationale and the real-world symptom (every +# std::string/std::vector-taking geoml function silently rejected until +# these became built-ins). +# --------------------------------------------------------------------------- + +def test_param_kind_std_string_passthrough(): + assert generate.Param("std::string", "x").kind(set(), set(), _hooks) == "passthrough" + assert generate.Param("const std::string &", "x").kind(set(), set(), _hooks) == "passthrough" + # Mutable out-param stays rejected - same reasoning as a bare fundamental's + # own mutable reference (no Lua-side identity to mutate a temporary + # std::string through). + assert generate.Param("std::string &", "x").kind(set(), set(), _hooks) is None + + +def test_param_kind_std_vector_of_fundamental_passthrough(): + assert generate.Param("std::vector", "x").kind(set(), set(), _hooks) == "passthrough" + assert generate.Param("const std::vector &", "x").kind(set(), set(), _hooks) == "passthrough" + assert generate.Param("std::vector &", "x").kind(set(), set(), _hooks) is None + + +def test_param_kind_std_vector_of_std_string_passthrough(): + assert generate.Param("const std::vector &", "x").kind(set(), set(), _hooks) == "passthrough" + + +def test_param_kind_std_vector_of_registered_type_passthrough(): + assert generate.Param("const std::vector &", "x").kind({"Widget"}, set(), _hooks) == "passthrough" + + +def test_param_kind_std_vector_of_plausible_bare_class_passthrough(): + # Not registered by this run at all - exactly Param.kind()'s own "object" + # fallback logic for a standalone parameter, reapplied here to one vector + # element (most commonly a type registered by a *different* plugin this + # one depends on). + assert generate.Param("const std::vector &", "x").kind(set(), set(), _hooks) == "passthrough" + + +def test_param_kind_std_vector_of_unsupported_element_is_rejected(): + # A pointer-shaped element is not a plausible bare type name - the whole + # vector stays rejected, same conservatism as a bare pointer parameter. + assert generate.Param("const std::vector &", "x").kind(set(), set(), _hooks) is None + + def test_param_kind_falls_through_to_hooks_classify_param(): class _RecognizesEverything(generate.CodeGenerator): def classify_param(self, param, registered_types, registered_enums): @@ -518,6 +591,59 @@ def test_expand_headers_dedups_across_overlapping_patterns(tmp_path): assert headers == ["widget_a.hxx"] +def test_expand_headers_glob_preserves_nested_relative_path(tmp_path): + # Regression test: a glob match used to be reduced to its bare basename + # (p.name) before being handed back to parse_headers(), which then + # reconstructs the path as include_dir / header - silently correct for a + # flat header layout (OCCT's own), but silently WRONG for any nested one + # (a real library like geoml, headers under geoml//*.h) - found + # the hard way, a TranslationUnitLoadError trying to parse + # "/widget.hpp", which never existed; the real file was + # "/nested/widget.hpp". The returned path must be relative to + # include_dir (nested/widget.hpp), not just the trailing filename. + (tmp_path / "nested").mkdir() + (tmp_path / "nested" / "widget.hpp").write_text("") + headers, glob_matched = generate.expand_headers(["nested/*.hpp"], tmp_path) + assert headers == ["nested/widget.hpp"] + assert glob_matched == {"nested/widget.hpp"} + assert (tmp_path / headers[0]).exists() + + +def test_expand_headers_glob_disambiguates_same_basename_in_different_dirs(tmp_path): + # A real basename collision a basename-only glob would have mishandled + # silently (found wrapping geoml: geoml/boolean_ops/modeling.hpp and + # geoml/primitives/modeling.hpp share the exact same filename) - both must + # survive, distinguished by their own relative path. + (tmp_path / "a").mkdir() + (tmp_path / "b").mkdir() + (tmp_path / "a" / "modeling.hpp").write_text("") + (tmp_path / "b" / "modeling.hpp").write_text("") + headers, _ = generate.expand_headers(["a/*.hpp", "b/*.hpp"], tmp_path) + assert headers == ["a/modeling.hpp", "b/modeling.hpp"] + + +def test_expand_headers_exclude_headers_drops_nested_glob_matches(tmp_path): + # exclude_headers is matched against the same relative-path spelling + # expand_headers now returns for a nested glob, not the bare basename. + (tmp_path / "nested").mkdir() + (tmp_path / "nested" / "widget_a.hpp").write_text("") + (tmp_path / "nested" / "widget_bad.hpp").write_text("") + headers, _ = generate.expand_headers( + ["nested/*.hpp"], tmp_path, exclude_headers=["nested/widget_bad.hpp"] + ) + assert headers == ["nested/widget_a.hpp"] + + +def test_expand_headers_flat_layout_glob_unaffected_by_relative_path_change(tmp_path): + # A flat file's relative path already equals its basename, so a + # flat-layout plugin (grunk-occt's own OCCT headers) sees no behavior + # change at all from the relative-path fix above. + (tmp_path / "widget_a.hxx").write_text("") + headers, glob_matched = generate.expand_headers(["widget_*.hxx"], tmp_path) + assert headers == ["widget_a.hxx"] + assert glob_matched == {"widget_a.hxx"} + + # --------------------------------------------------------------------------- # Integration: parse and generate registration code from a real, synthetic # header via libclang, end-to-end through run() - the pure-logic tests above From 834eb973e87324597b9ca46f27b7a63e5eccd796 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Mon, 28 Sep 2026 11:36:35 +0200 Subject: [PATCH 03/11] make expand_headers platform independent (fowarward slashes on win) --- python/grunk/codegen/generate.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/python/grunk/codegen/generate.py b/python/grunk/codegen/generate.py index 16536e3..73986b7 100644 --- a/python/grunk/codegen/generate.py +++ b/python/grunk/codegen/generate.py @@ -121,11 +121,26 @@ def expand_headers(patterns: list[str], include_dir: Path, exclude_headers: list # matched against this same relative-path spelling, so a nested-layout # plugin's own exclude_headers entries should be relative-path spelled too # (a flat-layout plugin's existing bare-filename entries are unaffected, - # since relative path and basename coincide there). + # since relative path and basename coincide there). .as_posix(), not + # plain str(): Path.relative_to() renders with the *native* separator + # on the platform the generator itself happens to be running on - + # backslash on Windows - so a plain str() would make this glob's own + # returned header spelling (and therefore config.yml's own + # exclude_headers matching, and translation_units.txt/generated + # filenames wherever a header's own relative path feeds into one) + # silently platform-dependent, breaking reproducibility and any + # config.yml exclude_headers entry authored (as every one in this + # codebase already is) with forward slashes - found via a real CI + # failure on Windows, not just reasoned about. include_dir / header + # reconstruction (parse_headers, elsewhere) still resolves correctly + # from a forward-slash string on Windows either way - pathlib's own + # Windows path flavour accepts '/' as a separator natively - so this + # is purely about keeping the *returned spelling* canonical, not a + # second, different path-reconstruction bug. matches = sorted( - str(p.relative_to(include_dir)) + p.relative_to(include_dir).as_posix() for p in include_dir.glob(pattern) - if str(p.relative_to(include_dir)) not in excluded + if p.relative_to(include_dir).as_posix() not in excluded ) if not matches: raise RuntimeError(f"header glob {pattern!r} matched no files in {include_dir}") From cdab46bf4c315e4f5e7004bd32c44b01b8566bf2 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Mon, 28 Sep 2026 13:37:52 +0200 Subject: [PATCH 04/11] fixed subrecipes example in doc --- docs/usage.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/usage.rst b/docs/usage.rst index 4d69524..23ae033 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -1340,7 +1340,7 @@ Exporting the recipe will result in the following yaml-representation: b: PluginA.Scalar(15) steps: | c = PluginA.add(a, b) - multiplication = recipes.multiplication + multiplication = recipes.multiplication() multiplication.x = a multiplication.y = b d = multiplication.z @@ -1433,7 +1433,7 @@ A ``grunk::Feature`` does not have to have a value. The only use-case of this ar b: PluginA.Scalar(15) steps: | c = PluginA.add(a, b) - multiplication = recipes.multiplication + multiplication = recipes.multiplication() multiplication.x = a multiplication.y = b d = multiplication.z From c0cc16d83437811b0868ea78a04dbeafeaa0f57e Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Mon, 28 Sep 2026 16:44:06 +0200 Subject: [PATCH 05/11] register __call method in parametric env --- grunk/dynamic/state.hpp | 33 +++++++++++++++++++-- tests/cpp/dynamic_operators.cpp | 51 +++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/grunk/dynamic/state.hpp b/grunk/dynamic/state.hpp index 1a6f5d4..c45c217 100644 --- a/grunk/dynamic/state.hpp +++ b/grunk/dynamic/state.hpp @@ -1091,12 +1091,38 @@ class state lua.script("function grunk.__dynamic_unm(v) return -v end"); sol::protected_function _unmfun = g["__dynamic_unm"]; g["_dynamic_unm"] = create_function_meta( - lua, - "grunk._dynamic_unm", + lua, + "grunk._dynamic_unm", {Parameter{"value", }}, _unmfun ); - function_meta const& _unm = g["_dynamic_unm"]; + function_meta const& _unm = g["_dynamic_unm"]; + + // Forwards a Feature's own sol::meta_function::call (Lua obj(...) syntax) the + // same way the arithmetic operators above are forwarded: a small generic Lua + // closure invokes the *raw*, unwrapped self value as a function (Lua's own + // __call protocol passes self as the first argument, exactly like __add/__sub + // above receive lhs/rhs - no "duplicated self" quirk here the way __unm's HACK + // works around, since Lua only calls __call once per invocation), and + // make_dynamic_action wraps that into a properly dependency-tracked action, so + // self and every call argument become genuine inputs of the resulting Feature. + // This is what makes a DynamicFeature wrapping a type with its own bound + // operator() (e.g. geoml's Transform, see grunk-geoml's transform_extras.hpp) + // callable as obj(args...) from inside a real recipe's decorated/parametric + // environment - previously this failed with "attempt to call a + // sol.grunk::Feature<...> value", since DynamicFeature's own usertype never + // registered sol::meta_function::call at all (a plain, undecorated + // environment already worked, since there self is the raw type directly and + // Lua finds that type's own __call binding with no Feature wrapper involved). + lua.script("function grunk.__dynamic_call(self, ...) return self(...) end"); + sol::protected_function _callfun = g["__dynamic_call"]; + g["_dynamic_call"] = create_function_meta( + lua, + "grunk._dynamic_call", + {Parameter{"self", }}, + _callfun + ); + function_meta const& _call = g["_dynamic_call"]; register_type("Feature", g) .add_constructors( @@ -1132,6 +1158,7 @@ class state .add_member_function(sol::meta_function::modulus, details::make_dynamic_action(_mod), {Parameter{"lhs", }, Parameter{"rhs",} }) .add_member_function(sol::meta_function::power_of, details::make_dynamic_action(_pow), {Parameter{"base", }, Parameter{"exponent",} }) .add_member_function(sol::meta_function::unary_minus, details::make_dynamic_action(_unm), {Parameter{"value",} }) + .add_member_function(sol::meta_function::call, details::make_dynamic_action(_call), {}) .set(sol::meta_function::index, [this](DynamicFeature const& self, std::string const& key) -> sol::object { // Native colon-call dispatch fallback: sol2 checks Feature's own members // (value, set_value, id, ..., as) before this ever runs, so those always win diff --git a/tests/cpp/dynamic_operators.cpp b/tests/cpp/dynamic_operators.cpp index 853fd8f..366a7e7 100644 --- a/tests/cpp/dynamic_operators.cpp +++ b/tests/cpp/dynamic_operators.cpp @@ -676,3 +676,54 @@ TEST(operators, usertype_addition_lua) EXPECT_NEAR(env.get("z1").value(), 5., 1e-14); EXPECT_NEAR(env.get("z2").value(), 42., 1e-14); } + +namespace { + +// A usertype whose own operator() is bound to Lua via sol::meta_function::call - +// the shape geoml's Transform (grunk-geoml's src/transform_extras.hpp) uses for its +// own value-transformation call. Exercises DynamicFeature's own sol::meta_function::call +// forwarding (state.hpp): before this existed, calling a Feature-wrapped Doubler as +// Lua obj(...) failed with "attempt to call a sol.grunk::Feature<...> value", even +// though the very same call worked fine on a raw, unwrapped Doubler. +class Doubler { +public: + Doubler() = default; + double operator()(double v) const { return v * m_factor; } + void set_factor(double f) { m_factor = f; } + +private: + double m_factor {2.0}; +}; + +} // namespace + +TEST(operators, usertype_call_lua) +{ + grunk::state grunk; + + grunk.register_type("Doubler") + .add_constructors( + []() { return Doubler(); } + ) + .add_member_function("set_factor", &Doubler::set_factor) + .set(sol::meta_function::call, [](Doubler const& self, double v) { return self(v); }); + + auto env = grunk.create_parametric_env(); + env.eval(R"( + local d = Doubler.new_feature() + local x = 3. + local z = d(x) + + z1 = z:value() + + d:change_value():set_factor(10.) + + z2 = z:value() + )"); + + // Confirms both that the call itself succeeds (the actual bug) and that the + // result is a genuinely dependency-tracked Feature, not a one-shot eager call - + // z2 must reflect d's new factor without re-evaluating z from scratch. + EXPECT_NEAR(env.get("z1"), 6., 1e-14); + EXPECT_NEAR(env.get("z2"), 30., 1e-14); +} From d9b079905d4eccaa08d51265ab2f6ef6b76786cd Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Tue, 29 Sep 2026 08:33:54 +0200 Subject: [PATCH 06/11] fix inheritence through smart pointer --- python/grunk/codegen/generate.py | 121 +++++++++++++++++++++++++++++++ tests/python/test_codegen.py | 61 ++++++++++++++++ 2 files changed, 182 insertions(+) diff --git a/python/grunk/codegen/generate.py b/python/grunk/codegen/generate.py index 73986b7..8ba12af 100644 --- a/python/grunk/codegen/generate.py +++ b/python/grunk/codegen/generate.py @@ -1466,6 +1466,106 @@ def process_module(module: dict, cache: dict[str, ParsedHeader], registered_type return result +def render_sol_base_classes_header(all_bases: dict[str, list[str]], all_namespace_of: dict[str, str], + class_to_header: dict[str, str], hooks: CodeGenerator, + banner: str = DEFAULT_GENERATED_BANNER) -> str: + """Renders sol_base_classes.hpp: one SOL_BASE_CLASSES(...)/SOL_DERIVED_CLASSES(...) + macro pair per class with a non-empty base chain, aggregated across *every* + module in this run (not just one) - see this generator's own module-level + docstring/README for why this needs to be global rather than per-module. + + This is a *separate*, compile-time-only mechanism from the ordinary + `.add_bases<...>()` runtime call render_module() already emits per class + (usertype_proxy::add_bases, a Lua-visible metatable property used for plain + reference-based up/downcasting and colon-call method lookup): sol2's own + Handle(Derived)->Handle(Base) *unique-usertype* conversion + (sol::detail::inheritance::type_unique_cast, consulted when a + Handle(Geom_BSplineSurface)-shaped value needs to satisfy a Handle(Geom_Surface) + parameter/overload-candidate, say) instead requires two explicit compile-time + template specializations - SOL_BASE_CLASSES(Derived, Base...) (the "upward" + direction, giving `sol::base` its own bases) and + SOL_DERIVED_CLASSES(Base, Derived...) (the "downward" direction, giving + `sol::derive` the set of classes that might actually be stored where a + Base is asked for) - without *both*, sol2 unconditionally treats the + relevant list as empty and the conversion silently never happens, regardless + of what add_bases<...>() declares. Confirmed empirically (a live spike + against real OCCT classes) that adding both macros, plus a + unique_usertype_traits>::rebind_actual_type member (the plugin's + own responsibility, not this generator's - see the consuming plugin's own + sol traits header), is sufficient to make the conversion work correctly, + including in an OCCT build without OCCT_HANDLE_NOCAST (no value-constructing + handle converting constructor, only an implicit reference-conversion + operator) - the actual assignment this triggers binds through that operator + and then runs the target handle's own ordinary, always-available + same-type copy-assignment, with correct reference counting. + + A *derived* class's own SOL_BASE_CLASSES bases come from hooks.emit_bases() + (the same override point/filtering a plugin's hooks.py already uses for + add_bases<...>()), so a plugin that truncates or filters its own class + hierarchy there (e.g. stopping short of a deep, Lua-irrelevant ancestor + chain) gets the identical chain reflected here - the two mechanisms should + always agree on "what is this class's base, as far as Lua is concerned". + SOL_DERIVED_CLASSES's own "downward" lists are then just this same + information inverted globally across every class in the run. + + Names are emitted fully-qualified (via all_namespace_of, ModuleResult's own + per-module namespace_of aggregated across the whole run) since, unlike each + module's own generated .cpp, this shared header has no per-module `using + ns::Name;` declarations to rely on. class_to_header maps every class name in + all_bases (bases and classes-with-bases alike) to the literal header it was + discovered in (built by run() from the same parse cache every module's own + processing already reads), so this header is self-contained regardless of + which module's .cpp happens to include it first - a class mentioned here + only as *someone else's* base (never itself explicitly processed as this + run's own primary subject) still needs its own #include for its name to be + resolvable at all. + + usertype_traits::qualified_name() (what SOL_BASE_CLASSES/ + SOL_DERIVED_CLASSES ultimately compare at runtime) is a compile-time-type- + derived (RTTI demangle-based) string, entirely independent of whether + register_type(...) was ever called for T at runtime - so a base class + that is itself never registered as a Lua-visible usertype (a pure + implementation-detail intermediate ancestor, say) can still appear here + without issue.""" + def qualify(name: str) -> str: + ns = all_namespace_of.get(name) + return f"{ns}::{name}" if ns else name + + # Every class name this header will ever mention, on either side of a + # SOL_BASE_CLASSES/SOL_DERIVED_CLASSES pair - collected first so each one's + # own header is included exactly once, in a stable (sorted) order. + all_names: set[str] = set(all_bases.keys()) + for bases in all_bases.values(): + all_names.update(bases) + + header_lines = sorted({ + f"#include <{class_to_header[name]}>" for name in all_names if name in class_to_header + }) + + derived_of: dict[str, list[str]] = {} + base_lines: list[str] = [] + for name in sorted(all_bases.keys()): + bases = hooks.emit_bases(name, all_bases[name]) + if not bases: + continue + base_lines.append(f"SOL_BASE_CLASSES({qualify(name)}, {', '.join(qualify(b) for b in bases)});") + for base in bases: + derived_of.setdefault(base, []).append(name) + + derived_lines = [ + f"SOL_DERIVED_CLASSES({qualify(base)}, {', '.join(qualify(d) for d in sorted(derived))});" + for base, derived in sorted(derived_of.items()) + ] + + body = "\n".join(header_lines) + "\n\n" + "\n".join(base_lines) + "\n\n" + "\n".join(derived_lines) + "\n" + return banner + f""" +#pragma once + +#include + +{body}""" + + def render_module(result: ModuleResult, hooks: CodeGenerator, includes_for_kinds: dict[str, list[str]], includes_for_ctor_modes: dict[str, list[str]], @@ -1687,6 +1787,7 @@ def render_module(result: ModuleResult, hooks: CodeGenerator, cpp_source = banner + f""" #include "{result.name}.hpp" +#include "sol_base_classes.hpp" {includes} @@ -1857,11 +1958,20 @@ def run(args: argparse.Namespace) -> int: e.name for p in cache.values() for e in p.entities if e.kind == "enum" } - blacklisted_names + # Aggregated across *every* module (not reset per module) so + # render_sol_base_classes_header() below can see the whole class hierarchy + # this run knows about, however many modules a given base/derived pair's + # two ends happen to be split across - see that function's own docstring. + all_bases: dict[str, list[str]] = {} + all_namespace_of: dict[str, str] = {} + for module in config["modules"]: result = process_module(module, cache, registered_types, registered_enums, hooks) header_source, cpp_source = render_module(result, hooks, includes_for_kinds, includes_for_ctor_modes, banner) (args.output_dir / f"{result.name}.hpp").write_text(header_source) (args.output_dir / f"{result.name}.cpp").write_text(cpp_source) + all_bases.update(result.bases) + all_namespace_of.update(result.namespace_of) n_accepted = sum(len(v) for v in result.accepted_ctors.values()) + sum( len(o) for m in result.accepted_methods.values() for o in m.values() @@ -1873,6 +1983,17 @@ def run(args: argparse.Namespace) -> int: for c in result.blacklisted: print(f" blacklisted {c.class_name}::{c.cpp_name}", file=sys.stderr) + # class name -> the literal header it was discovered in, built from the same + # whole-config parse cache used for registered_types/registered_enums above - + # see render_sol_base_classes_header()'s own docstring for why this shared + # header needs it (a class mentioned there only as someone else's base may + # never have been this run's own primary subject in any one module). + class_to_header: dict[str, str] = { + e.name: header for header, parsed in cache.items() for e in parsed.entities if e.kind == "class" + } + sol_base_classes_source = render_sol_base_classes_header(all_bases, all_namespace_of, class_to_header, hooks, banner) + (args.output_dir / "sol_base_classes.hpp").write_text(sol_base_classes_source) + # See the consuming CMakeLists.txt's own comment on reading this file: one # line per translation unit, each a space-separated list of module names # (generated/.cpp) to compile together, or a single line "*" meaning diff --git a/tests/python/test_codegen.py b/tests/python/test_codegen.py index 9c5f2dd..8fa576a 100644 --- a/tests/python/test_codegen.py +++ b/tests/python/test_codegen.py @@ -383,6 +383,67 @@ def test_code_generator_emit_return_type_default_is_none(): assert generate.CodeGenerator().emit_return_type("Widget") is None +def test_render_sol_base_classes_header_emits_transitive_bases_and_derived(): + # Base <- Middle <- Derived, Middle <- OtherDerived (a diamond-free, simple + # three-generation hierarchy) - see render_sol_base_classes_header's own + # docstring for why both directions (SOL_BASE_CLASSES: Derived's own full + # ancestor chain; SOL_DERIVED_CLASSES: every class that transitively derives + # from a given base) are needed, and why they must be computed globally + # across every module in one run, not per-module. + all_bases = { + "Derived": ["Middle", "Base"], + "OtherDerived": ["Middle", "Base"], + "Middle": ["Base"], + "Base": [], + } + class_to_header = {name: "widgets.hpp" for name in all_bases} + source = generate.render_sol_base_classes_header(all_bases, {}, class_to_header, generate.CodeGenerator()) + + assert "#include " in source + assert "SOL_BASE_CLASSES(Derived, Middle, Base);" in source + assert "SOL_BASE_CLASSES(Middle, Base);" in source + assert "SOL_BASE_CLASSES(OtherDerived, Middle, Base);" in source + # Base has no bases of its own - no SOL_BASE_CLASSES(Base, ...) line. + assert "SOL_BASE_CLASSES(Base," not in source + assert "SOL_DERIVED_CLASSES(Base, Derived, Middle, OtherDerived);" in source + assert "SOL_DERIVED_CLASSES(Middle, Derived, OtherDerived);" in source + + +def test_render_sol_base_classes_header_qualifies_namespaced_names(): + # Unlike each module's own generated .cpp (which gets a `using ns::Name;` for + # every namespaced entity it discovers), this shared header has no such + # declarations - a namespaced class must be spelled out fully qualified for + # its name to resolve regardless of which module's .cpp includes this + # header first. + all_bases = {"Derived": ["Base"]} + all_namespace_of = {"Derived": "mylib", "Base": "mylib"} + class_to_header = {"Derived": "widgets.hpp", "Base": "widgets.hpp"} + source = generate.render_sol_base_classes_header(all_bases, all_namespace_of, class_to_header, generate.CodeGenerator()) + + assert "SOL_BASE_CLASSES(mylib::Derived, mylib::Base);" in source + assert "SOL_DERIVED_CLASSES(mylib::Base, mylib::Derived);" in source + + +def test_render_sol_base_classes_header_respects_hooks_emit_bases_override(): + # A plugin's own emit_bases() override (e.g. truncating a chain at a + # library-specific root, exactly like grunk-occt's own Standard_Transient + # truncation) must be reflected here identically to how it's reflected in + # each class's own .add_bases<...>() call - the two mechanisms should never + # disagree about "what is this class's base, as far as Lua is concerned". + class TruncateAtMiddle(generate.CodeGenerator): + def emit_bases(self, class_name, chain): + return chain[:1] # only the direct parent, never further + + all_bases = {"Derived": ["Middle", "Base"]} + class_to_header = {"Derived": "widgets.hpp", "Middle": "widgets.hpp", "Base": "widgets.hpp"} + source = generate.render_sol_base_classes_header(all_bases, {}, class_to_header, TruncateAtMiddle()) + + assert "SOL_BASE_CLASSES(Derived, Middle);" in source + assert "SOL_BASE_CLASSES(Derived, Middle, Base);" not in source + assert "SOL_DERIVED_CLASSES(Middle, Derived);" in source + assert "SOL_DERIVED_CLASSES(Base, Derived);" not in source + + def test_emit_callable_plain_passthrough_needs_no_conversion(): c = _callable([generate.Param("double", "x")], return_spelling="double") src = generate.CodeGenerator().emit_callable(c, ["passthrough"], "value") From 13ab6232fdcd7b7e20a916392cfbb607417fb143 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Tue, 29 Sep 2026 10:36:23 +0200 Subject: [PATCH 07/11] fix conversion in with_std_vector --- grunk/dynamic/usertype_proxy.hpp | 45 ++++++++--- tests/cpp/dynamic_std_vector.cpp | 128 +++++++++++++++++++++++++------ 2 files changed, 141 insertions(+), 32 deletions(-) diff --git a/grunk/dynamic/usertype_proxy.hpp b/grunk/dynamic/usertype_proxy.hpp index db4e283..c5de5f2 100644 --- a/grunk/dynamic/usertype_proxy.hpp +++ b/grunk/dynamic/usertype_proxy.hpp @@ -200,10 +200,33 @@ struct usertype_proxy { * unique-usertype-aware cast (type_unique_cast) that already lets a single * Handle(Derived)-returning function argument bind correctly to a * Handle(Base) const& parameter applies per-element here too, once the - * identity function below is itself typed as VecElement(VecElement const&) - * rather than T(T const&). Call e.g. `.with_std_vector>()` on T's own - * usertype_proxy to get `T.as_vec(...)` producing std::vector> - * instead of std::vector. + * identity function below is itself typed as VecElement(VecElement) - BY VALUE, + * not VecElement(VecElement const&) - rather than T(T const&). The by-value + * parameter matters specifically for a unique-usertype VecElement: sol2's own + * unique-usertype-aware checker/getter (qualified_checker/qualified_getter, + * the path that actually consults rebind_actual_type/SOL_BASE_CLASSES to walk + * a Handle(Derived)->Handle(Base) conversion) excludes REFERENCE parameters + * outright (gated by !std::is_reference_v) - the exact same constraint that + * forces generated Handle(X) function parameters elsewhere in this ecosystem + * (grunk-occt/grunk-geoml's own codegen hooks) to be emitted by value instead + * of by reference. A VecElement const& parameter here silently falls back to a + * DIFFERENT, non-base-aware getter that rejects any Handle(Derived) argument + * with "unrecognized userdata (not pushed by sol?)" even when add_bases<...>() + * and rebind_actual_type are both registered correctly. Ordinary (non-unique) + * VecElement types are unaffected either way - their inheritance-aware binding + * goes through the regular, reference-tolerant add_bases path instead. + * + * Separately: whichever translation unit instantiates + * with_std_vector>() for a given T must itself have T's + * SOL_BASE_CLASSES(T, ...)/SOL_DERIVED_CLASSES(T, ...) declarations (see + * sol/forward.hpp) visible via #include - these specialize the compile-time + * sol::base/sol::derive traits sol2's checker consults, and an + * unspecialized primary template (silently, with no compile error) means "T + * has no known bases" from that TU's point of view, independent of whatever + * add_bases<...>() registered at runtime elsewhere. + * + * Call e.g. `.with_std_vector>()` on T's own usertype_proxy to get + * `T.as_vec(...)` producing std::vector> instead of std::vector. * * @tparam VecElement the std::vector element type - T itself by default, or a * smart-pointer-like wrapper around T (see above). @@ -215,11 +238,15 @@ struct usertype_proxy { std::string ud_name = name; sol::state_view lua(ut.lua_state()); - // A trivial real function VecElement(VecElement const&) - calling it forces - // sol2's ordinary, inheritance-aware argument-binding path onto whatever - // value is passed in, rather than the generic (and not inheritance-aware) - // sol::object::as(). - sol::protected_function cast_to_element = sol::make_object(lua, [](VecElement const& x) -> VecElement { return x; }); + // A trivial real function VecElement(VecElement) - BY VALUE, not + // VecElement(VecElement const&) - calling it forces sol2's ordinary, + // inheritance-aware argument-binding path onto whatever value is passed + // in, rather than the generic (and not inheritance-aware) + // sol::object::as(). The by-value parameter is required for a + // unique-usertype VecElement (e.g. Handle) - see this method's own doc + // comment above for why a by-reference parameter silently takes a + // different, non-base-aware path instead. + sol::protected_function cast_to_element = sol::make_object(lua, [](VecElement x) -> VecElement { return x; }); // convert_one is a generic lambda (not sol::object const&) for two reasons: // (1) portability - table iteration (from_table below) yields sol::object diff --git a/tests/cpp/dynamic_std_vector.cpp b/tests/cpp/dynamic_std_vector.cpp index f9218eb..de1b371 100644 --- a/tests/cpp/dynamic_std_vector.cpp +++ b/tests/cpp/dynamic_std_vector.cpp @@ -197,27 +197,109 @@ l = Base.as_vec(d1, d2, b1) // sol::unique_usertype_traits-wrapped smart pointer around T too - the motivating // case being OCCT's Handle(T)/opencascade::handle, where a function expects // std::vector and Lua passes several Handle(Derived)-backed features. -// This is confirmed working end-to-end against real OCCT types in grunk-occt -// (Geom_Line/Geom_Geometry, both Handle-based with add_bases<...>() already -// registered): `Geom_Geometry.as_vec(line1, line2)` (two Handle(Geom_Line) values) -// correctly builds a std::vector, and a function taking that -// vector reports the right size - see grunk-occt's tests/test_geom.cpp and -// docs/step5-investigation/ for the full writeup. // -// A *self-contained* minimal repro of this specific case was attempted here (a -// small Handle stand-in matching opencascade::handle's own shape, including -// its rebind_actual_type and upcast converting constructor) but did not reproduce -// the working behavior - it fails at sol2's own argument-checking step -// ("unrecognized userdata (not pushed by sol?)") even though the real OCCT case -// (structurally identical as far as could be determined: same automagic_flags, -// same add_bases usage, same registration order, tried both a plain registered -// constructor function and a real .add_constructors()-based one, tried a 2-level -// and a 3-level base chain) does not hit this failure. The exact discrepancy -// between the minimal stand-in and opencascade::handle was not found despite a -// real debugging attempt (traced into sol2's stack_check_unqualified.hpp/ -// stack_get_unqualified.hpp/inheritance.hpp - the regular, non-unique inheritance -// path is confirmed gated by weak_derive, set correctly by add_bases; the -// unique-usertype path's own checker did not appear to consult it, in the -// stand-in's case). Filed as a follow-up rather than blocking this fix - see the -// grunk-occt writeup for the full trace. If you find the actual discrepancy, a -// `std_vector.with_bases_unique_usertype`-shaped test belongs here. \ No newline at end of file +// A prior version of this fix claimed this was "confirmed working end-to-end +// against real OCCT types in grunk-occt" but a self-contained minimal Handle +// stand-in reproduced a failure ("unrecognized userdata (not pushed by sol?)") +// that could not be explained at the time. Root-caused for real since then, against +// grunk-geoml's own real OCCT Handle(Geom_Curve)/Handle(Geom_BSplineCurve) case +// (occt.Geom_Curve.as_vec(...) previously failed identically) - two independent, +// jointly-necessary causes, both fixed/documented now: +// +// 1. cast_to_element's parameter was VecElement const& (a reference). sol2's +// unique-usertype-aware checker/getter (the path that actually consults +// rebind_actual_type/SOL_BASE_CLASSES to walk a Handle(Derived)->Handle(Base) +// conversion) excludes reference parameters outright - the identical +// !std::is_reference_v gate that already forced grunk-occt/grunk-geoml's own +// codegen to emit Handle(X) function parameters by value. Fixed above: +// cast_to_element now takes VecElement by value. +// 2. SOL_BASE_CLASSES(T, ...)/SOL_DERIVED_CLASSES(T, ...) (sol/forward.hpp) +// specialize the compile-time sol::base/sol::derive traits - visible only +// via #include, per ordinary C++ template-specialization rules, independent of +// whatever add_bases<...>() registered at runtime. The original stand-in +// attempt registered add_bases() (the runtime side) but never declared +// SOL_BASE_CLASSES/SOL_DERIVED_CLASSES (the compile-time side) in its own TU - +// an unspecialized primary template silently means "no known bases" to sol2's +// checker, with no compile error, which is exactly the discrepancy that could +// not be found before: grunk-occt's own occt_plugin.cpp registers Geom_Curve's +// bases AND declares its own generated SOL_BASE_CLASSES/SOL_DERIVED_CLASSES in +// the same translation unit, but a foreign test TU (like the original stand-in, +// or any plugin consuming grunk-occt's registrations from a different .cpp) +// does not get that visibility for free. +// +// The test below reproduces cause 2 explicitly by only declaring SOL_BASE_CLASSES/ +// SOL_DERIVED_CLASSES for HandleDerived/HandleBase right here, matching what any +// real caller must also do for its own Handle(X) hierarchy. +namespace { + + struct HandleBase { int i; }; + struct HandleDerived : HandleBase {}; + + // A minimal opencascade::handle-shaped smart pointer: a bare owning + // pointer plus an implicit upcast converting constructor from Handle + // to Handle (mirroring Standard_Handle.hxx's own reference-conversion + // operator) - deliberately not reference-counted, since ownership semantics + // are irrelevant to the sol2 binding behavior under test. + template + struct Handle { + T* ptr = nullptr; + Handle() = default; + explicit Handle(T* p) : ptr(p) {} + template >> + Handle(Handle const& other) : ptr(other.ptr) {} + bool IsNull() const { return ptr == nullptr; } + T* get() const { return ptr; } + }; + +} // anonymous namespace + +namespace sol { + template + struct unique_usertype_traits> { + using type = T; + using actual_type = Handle; + static const bool value = true; + + template + using rebind_actual_type = Handle; + + static bool is_null(actual_type const& p) { return p.IsNull(); } + static type* get(actual_type const& p) { return p.get(); } + }; +} // namespace sol + +SOL_BASE_CLASSES(HandleDerived, HandleBase); +SOL_DERIVED_CLASSES(HandleBase, HandleDerived); + +TEST(std_vector, with_bases_unique_usertype) +{ + grunk::state grunk; + + grunk.register_type("HandleBase") + .add_constructors([](int i){ return Handle(new HandleBase{i}); }) + .with_std_vector>(); + + grunk.register_type("HandleDerived") + .add_constructors([](int i){ return Handle(new HandleDerived{HandleBase{i}}); }) + .add_bases(); + + auto env = grunk.create_env(); + env.eval(R"( +d1 = HandleDerived.new(5) +d2 = HandleDerived.new(7) +b1 = HandleBase.new(9) + +l = HandleBase.as_vec(d1, d2, b1) +)"); + + sol::object l = env["l"]; + ASSERT_TRUE(l.is>>()); + auto lv = l.as>>(); + ASSERT_EQ(lv.size(), 3u); + ASSERT_FALSE(lv[0].IsNull()); + ASSERT_FALSE(lv[1].IsNull()); + ASSERT_FALSE(lv[2].IsNull()); + EXPECT_EQ(lv[0].get()->i, 5); + EXPECT_EQ(lv[1].get()->i, 7); + EXPECT_EQ(lv[2].get()->i, 9); +} \ No newline at end of file From 40d8a1ebd9f020ba3481b9949437d2aafe95425a Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Tue, 29 Sep 2026 13:29:45 +0200 Subject: [PATCH 08/11] safeguard against mutable arguments in parametric environment --- grunk/dynamic/ActionDynamic.hpp | 34 +++++++ grunk/dynamic/function_meta.hpp | 99 +++++++++++++++++++ grunk/dynamic/usertype_proxy.hpp | 6 ++ tests/cpp/dynamic_serialization.cpp | 26 ++++- tests/cpp/dynamic_state.cpp | 142 +++++++++++++++++++++++++--- 5 files changed, 291 insertions(+), 16 deletions(-) diff --git a/grunk/dynamic/ActionDynamic.hpp b/grunk/dynamic/ActionDynamic.hpp index f86e999..faaeb4a 100644 --- a/grunk/dynamic/ActionDynamic.hpp +++ b/grunk/dynamic/ActionDynamic.hpp @@ -518,6 +518,40 @@ inline auto make_dynamic_action(function_meta const& func) } ); + // A mutating member function (non-const `self` - see + // function_meta::receiver_is_mutating/details::deduce_receiver_is_mutating) + // dispatched through this decorated/parametric path is never actually safe: + // grunk::action builds a real compute node here, but grunk's own evaluation + // (a thin wrapper over the external `parametric` library's own DAG engine) + // is lazy and strictly pull-based - a node's eval() only ever runs when its + // own output feature is explicitly read. A bare `self:Mutate(...)` statement + // never assigns or otherwise reads that output, so the node - and the real + // C++ mutation inside it - silently never runs at all, regardless of + // whether it's one call or a whole sequence of them. This is exactly the + // failure this check exists to catch: fail loudly and immediately, rather + // than let the caller discover much later that `self` was never actually + // mutated. `modules:` scripts (state::run_module_script) never reach this + // code at all - their own bodies resolve against the undecorated + // original_env directly, so a mutating call there dispatches to plain, + // synchronous C++ with no ActionDynamic/DynamicFeature involved - which is + // why this check can fire unconditionally here without breaking that + // legitimate use case. + if (func.receiver_is_mutating() && func.receiver_type_hint()) { + throw std::runtime_error( + "grunk: '" + func.get_name() + "' mutates its own receiver (a non-const " + "`self`), but this call is happening inside a decorated/parametric " + "environment (a recipe's `steps:` block, or any other create_parametric_env() " + "script), where evaluation is lazy and pull-based - a mutating call whose " + "own result is never explicitly read (the common case for a bare " + "`obj:Mutate(...)` statement) silently never executes at all, so the " + "mutation you're expecting never happens. Wrap this call - and any other " + "mutating call on the same object - in a `modules:` function instead (see " + "grunk::state::run_module_script's own documentation): statements inside a " + "module function run outside the decorated environment, so non-const " + "setters work exactly as they would in plain C++." + ); + } + return grunk::action(func, args); }; return decorated_function; diff --git a/grunk/dynamic/function_meta.hpp b/grunk/dynamic/function_meta.hpp index c64011d..a29d3ca 100644 --- a/grunk/dynamic/function_meta.hpp +++ b/grunk/dynamic/function_meta.hpp @@ -114,6 +114,79 @@ namespace details { } } + /** + * @brief Deduces, at registration time, whether a callable is a genuine + * mutator in the sense that matters for decorated/parametric dispatch (see + * ActionDynamic.hpp's make_dynamic_action): evaluation there is lazy and + * pull-based (grunk wraps the external `parametric` library's own DAG + * engine), so a mutating call's own result feature, if never explicitly + * read, is simply never evaluated at all - the underlying C++ mutation + * never happens, silently. + * + * Deliberately requires BOTH of: + * 1. a non-const lvalue-reference receiver ("self") - the call can + * actually write through it at all, and + * 2. a `void` return type - the call has no OTHER possible reason to + * exist than that mutation, since there's nothing else to read. + * Checking only (1) produces real false positives: plenty of ordinary, + * non-mutating methods simply aren't marked `const` (this project's own + * MyScalar::pow test fixture is exactly such a case - non-const, returns a + * new MyScalar, mutates nothing) - flagging those would reject entirely + * safe, already-working code. A non-const method that also returns + * something meaningful gets no protection from this check at all (a real, + * accepted gap, not an oversight): if that return value is itself read, + * the call evaluates correctly regardless of what self-mutation may also + * have happened, so there's no reliable way to tell "self-mutation was + * this call's only point" apart from "the return value just wasn't read + * this time" without knowing the future. A void-returning, non-const call + * has no such ambiguity - it can only ever have been made for its side + * effect - so this is the narrowest condition that reliably captures the + * genuinely broken case without rejecting merely-not-const-qualified pure + * methods. + * + * Same introspection limits as deduce_return_type_hint: only meaningful for + * a callable shape function_traits.hpp can introspect (a function pointer, + * member pointer, or a concrete, non-generic functor/lambda) with at least + * one parameter. Returns false (i.e. "not detected as mutating", the + * conservative/permissive default) for anything else - notably a + * sol::overload_set (used pervasively by generated bindings for any + * overloaded method), which has no single introspectable operator() at + * all. An overloaded mutating method therefore currently gets no + * protection from this mechanism at all; only a single, non-overloaded + * mutating registration does. + */ + template + bool deduce_receiver_is_mutating() { + using DecayedF = std::decay_t; + // Nested if constexpr blocks throughout, not conditions joined by &&: + // function_traits::arity/return_type/argument<0> all have to be + // named to even form a combined condition's own type, which would + // force-instantiate function_traits for a type like + // sol::overload_set that has_function_traits_v is specifically + // there to rule out first - the exact hazard has_return_type's own doc + // comment above already warns about, hit for real (a hard compile error, + // not a SFINAE failure) when this was first written with joined + // conditions. Nesting keeps each subsequent check's own body + // uninstantiated whenever an earlier branch is false. + if constexpr (has_function_traits_v) { + if constexpr (function_traits::arity >= 1) { + using Self = typename function_traits::template argument<0>::type; + constexpr bool self_is_mutable_ref = + std::is_lvalue_reference_v && !std::is_const_v>; + if constexpr (self_is_mutable_ref) { + using R = typename function_traits::return_type; + return std::is_void_v; + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + } // namespace details /** @@ -251,6 +324,29 @@ class function_meta m_receiver_type_hint = type; } + /** + * @brief whether this function's own receiver ("self") is mutated by the call - + * see details::deduce_receiver_is_mutating for the full explanation of why this + * matters (a mutating call dispatched through the decorated/parametric + * environment's lazy, pull-based evaluation silently never runs at all unless + * its own result is explicitly read) and its own documented false-negative gap + * for overloaded (sol::overload_set) registrations. Defaults to false (not + * mutating) for any function_meta not built via usertype_proxy::add_member_function, + * the only place this gets stamped. + */ + bool receiver_is_mutating() const { + return m_receiver_is_mutating; + } + + /** + * @brief sets whether this function's receiver is mutating - see + * receiver_is_mutating(). Used exclusively by usertype_proxy::add_member_function, + * right after construction, the same way set_receiver_type_hint is. + */ + void set_receiver_is_mutating(bool mutating) { + m_receiver_is_mutating = mutating; + } + private: ///@brief the name of the function std::string name; @@ -266,6 +362,9 @@ class function_meta ///@brief the C++ type this is a registered member function of, if any - see receiver_type_hint() std::optional m_receiver_type_hint; + + ///@brief whether this function's receiver is mutated by the call - see receiver_is_mutating() + bool m_receiver_is_mutating {false}; }; /** diff --git a/grunk/dynamic/usertype_proxy.hpp b/grunk/dynamic/usertype_proxy.hpp index c5de5f2..51b7818 100644 --- a/grunk/dynamic/usertype_proxy.hpp +++ b/grunk/dynamic/usertype_proxy.hpp @@ -119,6 +119,12 @@ struct usertype_proxy { // its own return type hint, so ActionDynamic::serialize() can recognize this // call as a genuine method call later (see function_meta::receiver_type_hint). func.as().set_receiver_type_hint(std::type_index(typeid(T))); + // Whether calling fun actually mutates its own receiver - see + // function_meta::receiver_is_mutating and details::deduce_receiver_is_mutating + // for why this matters (make_dynamic_action uses it to reject a mutating call + // made through the decorated/parametric environment, where such a call would + // otherwise silently never execute at all). + func.as().set_receiver_is_mutating(details::deduce_receiver_is_mutating()); ut.set(std::forward(key), func); return *this; diff --git a/tests/cpp/dynamic_serialization.cpp b/tests/cpp/dynamic_serialization.cpp index 12522e3..53649aa 100644 --- a/tests/cpp/dynamic_serialization.cpp +++ b/tests/cpp/dynamic_serialization.cpp @@ -503,6 +503,19 @@ TEST(serialization, member_function_action_cpp) EXPECT_EQ(ret_y, "y = Dummy.value(a)"); } +// Dummy::set_value (void-returning, non-const self) called from Lua now hits +// ActionDynamic.hpp's make_dynamic_action mutating-receiver check (see +// state.mutating_member_function_direct_call_in_decorated_env_throws in +// dynamic_state.cpp) - even for a call whose only purpose here was building an +// action to serialize, never to actually evaluate. That's deliberate: from +// Lua's own point of view there's no way to distinguish "I only want this for +// serialization" from "I actually want this to run" - both go through the +// exact same decorated-dispatch call. member_function_action_cpp above still +// covers set_value's own serialization directly via grunk::action(...) (the +// lower-level C++ API make_dynamic_action's check does not intercept at all, +// since it's not Lua-dispatched) - this Lua-facing test now only exercises the +// non-mutating half (Dummy::value) directly from Lua, plus confirms the +// mutating half is rejected loudly rather than silently misbehaving. TEST(serialization, member_function_action_lua) { grunk::state grunk; @@ -517,17 +530,20 @@ TEST(serialization, member_function_action_lua) auto env = grunk.create_parametric_env(); env.eval(R"( a = Dummy.new_feature():with_id("a") - - x = Dummy.set_value(a, 4.):with_id("x") y = Dummy.value(a):with_id("y") )"); - auto x = env.get_feature("x"); - auto ret_x = x.compute_node()->serialize(); - EXPECT_EQ(ret_x, "x = Dummy.set_value(a, 4.0)"); auto y = env.get_feature("y"); auto ret_y = y.compute_node()->serialize(); EXPECT_EQ(ret_y, "y = Dummy.value(a)"); + + try { + env.eval(R"(x = Dummy.set_value(a, 4.):with_id("x"))"); + FAIL() << "expected the mutating call to throw"; + } catch (sol::error const& err) { + std::string what = err.what(); + EXPECT_NE(what.find("mutates its own receiver"), std::string::npos); + } } TEST(serialization, ctor_action_cpp) diff --git a/tests/cpp/dynamic_state.cpp b/tests/cpp/dynamic_state.cpp index 75da5ac..5d59bc8 100644 --- a/tests/cpp/dynamic_state.cpp +++ b/tests/cpp/dynamic_state.cpp @@ -466,6 +466,105 @@ TEST(state, usertype_method_as_action_lua) EXPECT_NEAR(env.get("z2").value(), 8, 1e-14); // 2^3 } +// A mutating method (MyScalar::set, non-const `self`) called directly on a +// Feature from a decorated/parametric environment (`x:set(3)`, not routed +// through `x:change_value():set(3)` the way usertype_method_as_action_lua +// above does) used to silently never execute at all: make_dynamic_action builds +// a real compute node for the call, but grunk's evaluation is lazy/pull-based +// (a thin wrapper over the external `parametric` library's own DAG engine) - a +// bare `obj:Mutate(...)` statement never reads that node's own output feature, +// so it's simply never eval()'d, and the real C++ mutation inside it never runs. +// Now rejected loudly and immediately instead - see ActionDynamic.hpp's +// make_dynamic_action. +TEST(state, mutating_member_function_direct_call_in_decorated_env_throws) +{ + grunk::state grunk; + + grunk.register_type("MyScalar") + .add_constructors( + [](double v) { return MyScalar(v); } + ) + .add_member_function("set", &MyScalar::set); + + auto env = grunk.create_parametric_env(); + try { + env.eval(R"( + local x = MyScalar.new_feature(2) + x:set(3) + )"); + FAIL() << "expected the mutating call to throw"; + } catch (sol::error const& err) { + std::string what = err.what(); + EXPECT_NE(what.find("mutates its own receiver"), std::string::npos); + EXPECT_NE(what.find("modules:"), std::string::npos); + } +} + +// The same mutating call, wrapped in a `modules:`-equivalent module script +// (state::run_module_script), works exactly as plain C++ would - a module +// function's own body resolves against the undecorated original_env directly, +// so it never reaches make_dynamic_action's own check at all (nor the bug it +// guards against). This is the fix the thrown error above actually points users +// at - confirmed here that it's real, not just an escape hatch mentioned in an +// error message. +TEST(state, mutating_member_function_inside_module_script_works) +{ + grunk::state grunk; + + grunk.register_type("MyScalar") + .add_constructors( + [](double v) { return MyScalar(v); } + ) + .add_member_function("set", &MyScalar::set) + .add_member_function("value", &MyScalar::value); + + grunk.run_module_script("helpers", R"( + function make_scalar_set_to(v) + local s = MyScalar.new(0) + s:set(v) + return s + end + )"); + + auto env = grunk.create_parametric_env(); + auto res = env.eval(R"( + result = helpers.make_scalar_set_to(42) + )"); + ASSERT_TRUE(res.valid()); + // Calling INTO a module function from decorated code still goes through + // make_dynamic_action once, for the module function call itself - so its + // result is a DynamicFeature wrapping the returned MyScalar, not a raw + // MyScalar directly. + EXPECT_NEAR(env.get_feature("result").value().as().value(), 42, 1e-14); +} + +// MyScalar::pow has a non-const `self` too (it isn't marked `const`, even +// though it mutates nothing - a common, entirely legitimate real-world shape: +// plenty of methods just never got the `const` they could have) but returns a +// real value (MyScalar), not void - must NOT be affected by the new check, +// which deliberately requires BOTH a non-const self AND a void return type +// (see details::deduce_receiver_is_mutating's own doc comment for why +// non-const alone is not a safe-enough signal on its own - this exact method +// is the concrete counterexample that proved it). +TEST(state, non_const_but_non_void_member_function_direct_call_in_decorated_env_does_not_throw) +{ + grunk::state grunk; + + grunk.register_type("MyScalar") + .add_constructors( + [](double v) { return MyScalar(v); } + ) + .add_member_function("pow", &MyScalar::pow); + + auto env = grunk.create_parametric_env(); + auto res = env.eval(R"( + local x = MyScalar.new_feature(2) + result = x:pow(3) + )"); + ASSERT_TRUE(res.valid()); + EXPECT_NEAR(env.get_feature("result").value().as().value(), 8, 1e-14); +} + // usertype_method_as_action_lua above only ever calls :as() on a "root" feature // (MyScalar.new_feature(2), constructed directly from an object - see DynamicFeature's // Feature(object const&) ctor, which knows its lua state up front). A feature that is @@ -841,7 +940,23 @@ TEST(state, native_colon_call_reserved_name_shadowing) EXPECT_NEAR(result.as().value(), 2., 1e-14); } -TEST(state, native_colon_call_void_return_no_hint) +// void-returning + non-const `self` (MyScalar::set) is exactly the shape +// make_dynamic_action's own mutating-receiver check now rejects (see +// ActionDynamic.hpp) - this test used to assert the call succeeded silently +// (EXPECT_NO_THROW(y.value())), without ever checking whether `x` itself was +// actually mutated by it (it is, if - and only if - `y`'s own result feature +// is explicitly forced, e.g. via y.value(), exactly as done here; a bare +// `x:set(5.)` statement with no assignment at all never runs the mutation, an +// even more broken variant of the same hazard). That "safe if you remember to +// force the result" pattern is fragile precisely because it's easy to get +// wrong - see mutating_member_function_direct_call_in_decorated_env_throws +// below for the far more common, silently-broken bare-statement shape this +// project actually hit in production (grunk-geoml's wing_loft.grr.yml, an +// occt.gp_GTrsf built via 3 separate bare SetValue(...) statements, each +// silently a no-op). Rejecting unconditionally, rather than only the +// definitely-discarded case, is deliberate: whether a given call's result will +// ever be read isn't knowable at the point the call is dispatched at all. +TEST(state, mutating_member_function_via_assign_and_force_read_also_throws) { grunk::state grunk; @@ -849,16 +964,18 @@ TEST(state, native_colon_call_void_return_no_hint) .add_constructors( [](double v) { return MyScalar(v); } ) - .add_member_function("set", &MyScalar::set); // void-returning + .add_member_function("set", &MyScalar::set); // void-returning, non-const self auto x = grunk.feature(MyScalar(2.)); auto env = grunk.create_parametric_env(); env["x"] = x; - env.eval("y = x:set(5.)"); - - grunk::DynamicFeature y = env.get_feature("y"); - EXPECT_FALSE(y.type_hint().has_value()); - EXPECT_NO_THROW(y.value()); + try { + env.eval("y = x:set(5.)"); + FAIL() << "expected the mutating call to throw"; + } catch (sol::error const& err) { + std::string what = err.what(); + EXPECT_NE(what.find("mutates its own receiver"), std::string::npos); + } } TEST(state, deduce_return_type_hint_tuple_return_is_safe) @@ -1216,10 +1333,13 @@ TEST(state, usertype_nonconst_method_as_action_lua) TO DO - test (nested) enums - test data member as action (read-only) in LUA and C++ - - idea to prevent non-const member functions: - - wrap registration of method in TypeFactory like in reflect, with a add_member_function method - - use metaprogramming alchemistry to determine if argument to add_member_function is non-const member function - - if yes, register a method that throws an exception or returns an invalid sol::protected_function_result + - DONE: prevent non-const member functions from silently doing nothing under + decorated/parametric dispatch - see function_meta::receiver_is_mutating / + details::deduce_receiver_is_mutating (function_meta.hpp) and the check in + ActionDynamic.hpp's make_dynamic_action. Narrower than the original idea + above: non-const alone is not a safe signal (MyScalar::pow is non-const but + mutates nothing - see the non_const_but_non_void_... test above), so this + additionally requires a void return type. - docstrings + documentation - copy potentially missing tests from main branch - think about good syntax for scripts and expressions (having mixed yaml-lua in mind) From 2742afb12c65efc0e6587c2198609e6463ddea4b Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Wed, 30 Sep 2026 09:06:16 +0200 Subject: [PATCH 09/11] disambiguate not-my-concern from rejected in classify_param --- python/grunk/codegen/generate.py | 67 ++++++++++++++++++++++++-------- tests/python/test_codegen.py | 36 +++++++++++++++++ 2 files changed, 87 insertions(+), 16 deletions(-) diff --git a/python/grunk/codegen/generate.py b/python/grunk/codegen/generate.py index 8ba12af..6f50981 100644 --- a/python/grunk/codegen/generate.py +++ b/python/grunk/codegen/generate.py @@ -196,6 +196,29 @@ def expand_headers(patterns: list[str], include_dir: Path, exclude_headers: list # "object" rather than rejected. BARE_TYPE_NAME = re.compile(r"[A-Za-z_]\w*(::[A-Za-z_]\w*)*") +class _Rejected: + """Sentinel type for REJECTED below - a dedicated type (not e.g. a string + constant) so `is REJECTED` can never collide with a legitimate kind name a + CodeGenerator subclass happens to choose.""" + def __repr__(self) -> str: + return "REJECTED" + +# Returned by CodeGenerator.classify_param() to definitively reject a parameter - +# distinct from None, which means "not one of my own library's idioms, let +# Param.kind()'s own unregistered-class fallback have a look instead" (see +# classify_param()'s own docstring). Needed because a hook can recognize a +# parameter's *shape* (e.g. "this canonical spelling is an NCollection_Array1") +# and, having recognized it, positively determine it's unsupported for a reason +# specific to that shape (X itself isn't a supported element type) - falling +# through to None in that case used to let the *surface* spelling (often a +# library's own bare-identifier typedef, e.g. "TColgp_Array1OfPnt" for +# "NCollection_Array1") pass Param.kind()'s own generic BARE_TYPE_NAME +# fallback and get silently accepted as a plain "object" anyway - the exact bug +# this sentinel exists to let a subclass avoid (confirmed happening for real: an +# NCollection_Array1 parameter with an unregistered element type, found via +# grunk-occt's own test_hooks.py::test_classify_param_array1_array2). +REJECTED = _Rejected() + # std::string - sol2 converts a Lua string to/from std::string automatically, no # wrapping needed, exactly like a bare fundamental (hence "passthrough", not # "object" - it behaves like a value, not a Lua-side-identity usertype). Needs this @@ -345,9 +368,12 @@ class - registered by this run or not, see below) need zero customization from any plugin; anything else - a smart-pointer wrapper, a fixed-size array/container type, a type with more than one possible C++ representation, or any other library-specific idiom - is - delegated to hooks.classify_param(), which returns None (still - unsupported) unless the plugin's own CodeGenerator subclass - recognizes it. + delegated to hooks.classify_param(). A None result there means "not one + of my own library's idioms" and still falls through to this method's + own unregistered-class fallback below; REJECTED means the hook + positively recognized param's shape and determined it's unsupported - + skip the fallback and reject outright (see REJECTED's own module-level + docstring for why this distinction is needed). Non-const-reference ("out") parameters ARE supported for an object (Lua/sol2 userdata for a class already has stable, mutable identity - @@ -411,6 +437,8 @@ class - registered by this run or not, see below) need zero if self.base in registered_types: return "object" kind = hooks.classify_param(self, registered_types, registered_enums) + if kind is REJECTED: + return None if kind is not None: return kind if not BARE_TYPE_NAME.fullmatch(self.base): @@ -1064,19 +1092,26 @@ def classify_param(self, param: Param, registered_types: set[str], registered_en enum passthrough, already-registered class) fail to classify param.base. Returns any kind name this subclass chooses (a plain string, not drawn from a fixed enum this generator defines) for emit_param()/ - emit_constructor() to later recognize by that same name, or None to - leave param unclassified here - NOT necessarily rejected outright: - Param.kind() still tries its own unregistered-class fallback afterward - (see its own docstring) before actually giving up, so returning None - only means "this isn't one of my own library's special idioms," not - "this parameter is unsupported." Receives the full Param (not just its - spelling) so a subclass can use param.canonical (typedef-resolved - spelling - needed to see through a library's own container/template - typedefs) and param.is_mutable_ref (a mutable reference to a value with - no stable Lua-side identity to mutate in place, e.g. a bare number or a - by-value container, is usually not supported - see Param.kind's own - docstring for the built-in kinds' own version of this rule). Default: - always None.""" + emit_constructor() to later recognize by that same name; None to leave + param unclassified here - NOT rejected outright: Param.kind() still + tries its own unregistered-class fallback afterward (see its own + docstring) before actually giving up, so returning None only means + "this isn't one of my own library's special idioms," not "this + parameter is unsupported"; or REJECTED (module-level sentinel, see its + own docstring) when this method positively recognizes param's *shape* + as belonging to its own library's idiom and, having recognized it, + determines it's unsupported for a reason specific to that shape (e.g. a + container type whose element type isn't itself supported) - this skips + Param.kind()'s own fallback entirely, unlike None, since that fallback + would otherwise happily accept the param's surface spelling as a plain + unregistered "object" even though this method already knows better. + Receives the full Param (not just its spelling) so a subclass can use + param.canonical (typedef-resolved spelling - needed to see through a + library's own container/template typedefs) and param.is_mutable_ref (a + mutable reference to a value with no stable Lua-side identity to mutate + in place, e.g. a bare number or a by-value container, is usually not + supported - see Param.kind's own docstring for the built-in kinds' own + version of this rule). Default: always None.""" return None def classify_ctor_mode(self, class_name: str, base_chain: list[str]) -> str | None: diff --git a/tests/python/test_codegen.py b/tests/python/test_codegen.py index 8fa576a..7cfcfbf 100644 --- a/tests/python/test_codegen.py +++ b/tests/python/test_codegen.py @@ -214,6 +214,42 @@ def classify_param(self, param, registered_types, registered_enums): assert generate.Param("SomeExoticType *", "x").kind(set(), set(), generate.CodeGenerator()) is None +def test_param_kind_hooks_rejected_skips_unregistered_class_fallback(): + # A plain, bare-identifier surface spelling ("SomeExoticType") is exactly + # the shape Param.kind()'s own unregistered-class fallback would otherwise + # happily accept as "object" - the whole point of REJECTED is to let a + # CodeGenerator subclass that positively recognizes this param's shape (and + # has positively determined it's unsupported for a reason specific to that + # shape) skip that fallback entirely, unlike returning plain None. This is + # the exact bug class test_classify_param_array1_array2 (grunk-occt's own + # tests/python/test_hooks.py) surfaced: an NCollection_Array1 parameter + # with an unregistered element T, whose *surface* spelling is a bare + # OCCT typedef (e.g. "TColgp_Array1OfPnt"), used to be silently accepted as + # a plain "object" once its own hook returned None instead of REJECTED. + class _RejectsBySpelling(generate.CodeGenerator): + def classify_param(self, param, registered_types, registered_enums): + if param.base == "SomeExoticType": + return generate.REJECTED + return None + p = generate.Param("SomeExoticType", "x") + # Without the hook (or with a hook returning plain None for this type), + # this exact same Param would classify as "object" via the fallback - + # confirm that baseline first, so the REJECTED case below is a genuine + # contrast, not a param that was already rejected for some other reason. + assert p.kind(set(), set(), generate.CodeGenerator()) == "object" + assert p.kind(set(), set(), _RejectsBySpelling()) is None + + +def test_code_generator_classify_param_rejected_is_distinct_from_none(): + # REJECTED and None must never compare equal to each other, and REJECTED + # must not collide with a legitimate string kind name a subclass might + # choose - see REJECTED's own module-level docstring for why this needs to + # be a dedicated sentinel type rather than e.g. a string constant. + assert generate.REJECTED is not None + assert generate.REJECTED != None # noqa: E711 - deliberately testing __eq__, not identity twice + assert generate.REJECTED != "rejected" + + # --------------------------------------------------------------------------- # Callable.rejection_reason() / accepted_arities() # --------------------------------------------------------------------------- From 1566d7459acfbc42db74b43517267143bf48d438 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Wed, 30 Sep 2026 14:30:44 +0200 Subject: [PATCH 10/11] fix dangling pointer when combining module return value with as(Type) syntax --- grunk/dynamic/DynamicFeature.hpp | 25 ++++++++++-- tests/cpp/dynamic_state.cpp | 65 ++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/grunk/dynamic/DynamicFeature.hpp b/grunk/dynamic/DynamicFeature.hpp index 446deec..922d3bd 100644 --- a/grunk/dynamic/DynamicFeature.hpp +++ b/grunk/dynamic/DynamicFeature.hpp @@ -85,11 +85,28 @@ class Feature : public FeatureBase, object> sol::state_view l(lua); sol::table method_table = l.create_table(); sol::table mt = l.create_table(); - mt.set_function("__index", [this, usertype](sol::table, std::string const& method) -> sol::object { + // Capture a COPY of *this (self), not `this` (a raw pointer to it) - a + // Feature is a thin, cheaply-copyable handle around a shared + // parametric::param node (see FeatureBase), so copying it keeps the + // underlying feature alive via its own reference counting, independent of + // Lua's garbage collector, while still passing `func` an actual Feature + // (not its evaluated value) so dependency tracking/laziness works exactly + // as it does everywhere else (func's own decorated dispatch evaluates it + // when it needs to, not before). The DynamicFeature this method is called + // on is typically a short-lived Lua temporary (e.g. the unnamed result of + // a module-function call, as in `helpers.foo(...):as(SomeType)`) with no + // other Lua-side reference keeping it alive past this expression - a + // captured `this` pointer can go stale (the original userdata collected) + // long before these closures are actually invoked, since grunk's own + // evaluation is lazy/pull-based. Confirmed the hard way: a real, + // reproducible segfault once the original temporary had been garbage + // collected (see the as_on_module_function_result_survives_gc... test). + Feature self = *this; + mt.set_function("__index", [self, usertype](sol::table, std::string const& method) -> sol::object { sol::protected_function func = usertype[method]; - return sol::make_object(lua, sol::as_function( - [this, func](sol::variadic_args va){ - return func(*this, va); + return sol::make_object(self.lua, sol::as_function( + [self, func](sol::variadic_args va){ + return func(self, va); } )); }); diff --git a/tests/cpp/dynamic_state.cpp b/tests/cpp/dynamic_state.cpp index 5d59bc8..31cbd97 100644 --- a/tests/cpp/dynamic_state.cpp +++ b/tests/cpp/dynamic_state.cpp @@ -466,6 +466,71 @@ TEST(state, usertype_method_as_action_lua) EXPECT_NEAR(env.get("z2").value(), 8, 1e-14); // 2^3 } +// A pImpl/shared_ptr-backed type (unlike MyScalar's plain double), used to +// reproduce a real, previously-silent crash: DynamicFeature::as()'s returned +// proxy used to capture `this` (a raw pointer to the DynamicFeature it was +// called on) and pass it straight through to the wrapped type's own method, +// instead of a copy of the feature's own *evaluated value*. For a plain +// double-backed type like MyScalar this happened to not crash (misinterpreting +// unrelated memory as a double is harmless UB), but for a type whose method +// actually dereferences an internal pointer, it segfaults - found the hard way +// via grunk-geoml's own geoml::Shape (also pImpl/shared_ptr-backed). +namespace { + +struct PimplWidget +{ + struct Data { double value; }; + std::shared_ptr data; + + explicit PimplWidget(double v) : data(std::make_shared(Data{v})) {} + double get() const { return data->value; } +}; + +} // anonymous namespace + +// Reproduces the exact real-world shape of the bug: an *unnamed* DynamicFeature +// (the result of a `modules:` script function call, which - unlike a plain +// registered constructor/member-function call - carries no static return type +// hint, see run_module_script's own doc comment) has :as(Type) called on it +// directly, with nothing else keeping the original, wrapper-less temporary +// feature reachable from Lua. A forced full GC between :as() and the first use +// of its returned proxy used to leave the captured `this` pointer dangling +// (the temporary's own userdata having been collected) - now the proxy holds +// its own copy of the feature (a cheap, shared_ptr-backed handle), independent +// of Lua's GC. +TEST(state, as_on_module_function_result_survives_gc_and_uses_real_value) +{ + grunk::state grunk; + + grunk.register_type("PimplWidget") + .add_constructors( + [](double v) { return PimplWidget(v); } + ) + .add_member_function("get", &PimplWidget::get); + + grunk.run_module_script("helpers", R"( + function make_widget(v) + return PimplWidget.new(v) + end + )"); + + auto env = grunk.create_parametric_env(); + env.eval(R"( + w = helpers.make_widget(5.):as(PimplWidget) + )"); + + // Nothing but `w`'s own captured copy of the original module-function + // result keeps that temporary feature alive at this point - a full, + // forced collection is the most direct way to prove that. + env.eval(R"(collectgarbage("collect"))"); + + env.eval(R"( + result = w.get():value() + )"); + + EXPECT_NEAR(env.get("result"), 5., 1e-14); +} + // A mutating method (MyScalar::set, non-const `self`) called directly on a // Feature from a decorated/parametric environment (`x:set(3)`, not routed // through `x:change_value():set(3)` the way usertype_method_as_action_lua From de18b58e7a7ce793b30d0a1b9223f11a4e4de824 Mon Sep 17 00:00:00 2001 From: Jan Kleinert Date: Fri, 2 Oct 2026 08:42:59 +0200 Subject: [PATCH 11/11] add SOL_ALL_SAFETIES_ON, enforcing stricter checked getters --- grunk/dynamic/CMakeLists.txt | 17 +++++++++++ tests/cpp/dynamic_state.cpp | 58 ++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/grunk/dynamic/CMakeLists.txt b/grunk/dynamic/CMakeLists.txt index 5e0ab7a..479eb8a 100644 --- a/grunk/dynamic/CMakeLists.txt +++ b/grunk/dynamic/CMakeLists.txt @@ -13,6 +13,23 @@ if (GRUNK_WITH_RECIPE) target_compile_definitions(grunk_dynamic INTERFACE GRUNK_WITH_RECIPE) endif() +# sol2 defaults to UNCHECKED argument/userdata extraction (SOL_ALL_SAFETIES_ON +# off unless this is a debug build) - a Lua value of one registered usertype +# passed where a *different* usertype is expected (e.g. a plugin's own +# implicitly-convertible wrapper type passed where the type it converts to is +# expected) is blindly reinterpreted as the target type instead of being +# rejected, corrupting memory and segfaulting deep inside unrelated code +# instead of failing at the call site with a clear error - found the hard way +# via grunk-geoml's own airplane_seats.grr.yml (geoml::Shape passed directly +# where a TopoDS_Shape was expected). Propagated as an INTERFACE compile +# definition (not just set for grunk's own sources) so every downstream +# consumer that links against grunk::dynamic - directly or transitively, e.g. +# a plugin's own generated registration code - gets the same, consistent +# define: sol2 template instantiations must agree on this across every +# translation unit that touches the same types, so this cannot be a +# per-project opt-in without risking ODR/ABI mismatches. +target_compile_definitions(grunk_dynamic INTERFACE SOL_ALL_SAFETIES_ON=1) + target_compile_features(grunk_dynamic INTERFACE cxx_std_17) target_link_libraries(grunk_dynamic INTERFACE grunk::core sol2::sol2 ${LUA_LIBRARIES}) diff --git a/tests/cpp/dynamic_state.cpp b/tests/cpp/dynamic_state.cpp index 31cbd97..02e4b19 100644 --- a/tests/cpp/dynamic_state.cpp +++ b/tests/cpp/dynamic_state.cpp @@ -356,6 +356,64 @@ TEST(state, usertype_ctor_as_action_lua) EXPECT_EQ(env.get_feature("x").value().as().value(), 4.); } +// Passing a value of one registered usertype where a *different*, unrelated +// registered usertype is expected used to be a real, reproducible segfault +// instead of a catchable error: sol2 defaults to unchecked argument +// extraction (SOL_ALL_SAFETIES_ON off unless this is a debug build), which +// blindly reinterprets a mismatched userdata's memory as the target type +// rather than rejecting it - found via grunk-geoml's own airplane_seats.grr.yml +// (a geoml::Shape passed directly where a TopoDS_Shape was expected). Fixed by +// grunk/dynamic/CMakeLists.txt now defining SOL_ALL_SAFETIES_ON=1 as an +// INTERFACE compile definition on grunk::dynamic, so every consumer - grunk's +// own code and any downstream plugin linking against it - gets the checked +// getter consistently. TypeA/TypeB here are two intentionally unrelated +// (non-inheriting) registered types, the same shape as the real bug. +namespace { + +struct TypeA +{ + explicit TypeA(double v) : value(v) {} + double value; +}; + +struct TypeB +{ + explicit TypeB(double v) : value(v) {} + double value; +}; + +} // anonymous namespace + +TEST(state, mismatched_usertype_argument_throws_instead_of_crashing) +{ + grunk::state grunk; + + grunk.register_type("TypeA") + .add_constructors( + [](double v) { return TypeA(v); } + ); + grunk.register_type("TypeB") + .add_constructors( + [](double v) { return TypeB(v); } + ); + grunk.register_function( + "takes_a", + [](TypeA const& a) -> double { return a.value; } + ); + + auto env = grunk.create_parametric_env(); + try { + env.eval(R"( + b = TypeB.new(3.) + x = takes_a(b) + result = x:value() + )"); + FAIL() << "expected a catchable error, not a successful (or crashing) call"; + } catch (sol::error const& e) { + EXPECT_NE(std::string(e.what()).find("TypeA"), std::string::npos); + } +} + TEST(state, usertype_operators_as_action_lua) { grunk::state grunk;