Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions grunk/dynamic/ActionDynamic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
17 changes: 17 additions & 0 deletions grunk/dynamic/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand Down
25 changes: 21 additions & 4 deletions grunk/dynamic/DynamicFeature.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,28 @@ class Feature<object> : public FeatureBase<Feature<object>, 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<object> is a thin, cheaply-copyable handle around a shared
// parametric::param<T> 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<object> 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);
}
));
});
Expand Down
99 changes: 99 additions & 0 deletions grunk/dynamic/function_meta.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <typename F>
bool deduce_receiver_is_mutating() {
using DecayedF = std::decay_t<F>;
// Nested if constexpr blocks throughout, not conditions joined by &&:
// function_traits<DecayedF>::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<DecayedF> for a type like
// sol::overload_set that has_function_traits_v<DecayedF> 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<DecayedF>) {
if constexpr (function_traits<DecayedF>::arity >= 1) {
using Self = typename function_traits<DecayedF>::template argument<0>::type;
constexpr bool self_is_mutable_ref =
std::is_lvalue_reference_v<Self> && !std::is_const_v<std::remove_reference_t<Self>>;
if constexpr (self_is_mutable_ref) {
using R = typename function_traits<DecayedF>::return_type;
return std::is_void_v<R>;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}

} // namespace details

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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<std::type_index> 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};
};

/**
Expand Down
33 changes: 30 additions & 3 deletions grunk/dynamic/state.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<DynamicFeature>("Feature", g)
.add_constructors(
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading