runtime 1.1.4
Checked CEL programs, owned values, and reusable execution stacks
Loading...
Searching...
No Matches
dyn_segment.hpp
1// SPDX-License-Identifier: BSL-1.0
2#ifndef CEL_RUNTIME_DYN_SEGMENT_HPP
3#define CEL_RUNTIME_DYN_SEGMENT_HPP
4#include <cel/runtime/detail/raw_segment.hpp>
5#include <concepts>
6#include <new>
7#include <optional>
8#include <vector>
9
10namespace cel {
13
21 std::size_t bytes = 0;
22 std::size_t depth = 0;
23};
24
27inline bool operator==(const stack_origin& left, const stack_origin& right) noexcept {
28 return left.bytes == right.bytes && left.depth == right.depth;
29}
30class compiled_segment;
31namespace detail {
32class prepared_raw_segment;
33}
34template <class R, class... Args>
36
44 std::size_t slots;
45};
46
56 std::size_t alignment = 1;
57 std::size_t frame_extent = 0;
58 std::size_t live_slots = 0;
59
72 stack_reservation for_prefix(std::size_t cursor, std::size_t depth) const;
73};
74
75namespace detail {
76struct frozen_program;
78template <class T>
79inline constexpr bool native_leaf = !nominal_record_adapter<T>;
81template <class T, class A>
82inline constexpr bool native_leaf<std::vector<T, A>> = false;
84template <class... T>
85inline constexpr bool native_leaf<std::tuple<T...>> = false;
87template <class T>
88struct callback_signature {};
90template <class R, class... A>
91struct callback_signature<R (*)(A...)> {
92 using arguments = std::tuple<std::remove_cvref_t<A>...>;
93};
95template <class R, class... A>
96struct callback_signature<R (*)(A...) noexcept> : callback_signature<R (*)(A...)> {};
98template <class C, class R, class... A>
99struct callback_signature<R (C::*)(A...) const> : callback_signature<R (*)(A...)> {};
101template <class C, class R, class... A>
102struct callback_signature<R (C::*)(A...) const noexcept> : callback_signature<R (*)(A...)> {};
104template <class C, class R, class... A>
105struct callback_signature<R (C::*)(A...) const&> : callback_signature<R (*)(A...)> {};
107template <class C, class R, class... A>
108struct callback_signature<R (C::*)(A...) const & noexcept> : callback_signature<R (*)(A...)> {};
113template <class F, class R, class... A>
114consteval auto generic_member() {
115 if constexpr (requires { static_cast<R (F::*)(A...) const>(&F::template operator()); })
116 return static_cast<R (F::*)(A...) const>(&F::template operator());
117 else if constexpr (requires { static_cast<R (F::*)(A...) const&>(&F::template operator()); })
118 return static_cast<R (F::*)(A...) const&>(&F::template operator());
119 else if constexpr (requires {
120 static_cast<R (F::*)(const A&...) const>(&F::template operator());
121 })
122 return static_cast<R (F::*)(const A&...) const>(&F::template operator());
123 else if constexpr (requires {
124 static_cast<R (F::*)(const A&...) const&>(&F::template operator());
125 })
126 return static_cast<R (F::*)(const A&...) const&>(&F::template operator());
127 else if constexpr (requires { static_cast<R (F::*)(A&&...) const>(&F::template operator()); })
128 return static_cast<R (F::*)(A&&...) const>(&F::template operator());
129 else if constexpr (requires { static_cast<R (F::*)(A&&...) const&>(&F::template operator()); })
130 return static_cast<R (F::*)(A&&...) const&>(&F::template operator());
131}
135template <class F, class R, class... A>
136consteval bool exact_callback() {
137 using callback_type = std::decay_t<F>;
138 if constexpr (!std::is_invocable_v<const callback_type&, A...>)
139 return false;
140 else {
141 constexpr bool result_matches =
142 std::same_as<R, std::remove_cvref_t<std::invoke_result_t<const callback_type&, A...>>>;
143 if constexpr (requires { typename callback_signature<callback_type>::arguments; })
144 return result_matches &&
145 std::same_as<typename callback_signature<callback_type>::arguments,
146 std::tuple<A...>>;
147 else if constexpr (requires {
148 typename callback_signature<
149 decltype(&callback_type::operator())>::arguments;
150 })
151 return result_matches &&
152 std::same_as<
153 typename callback_signature<decltype(&callback_type::operator())>::arguments,
154 std::tuple<A...>>;
155 else {
156 using member =
157 decltype(generic_member<callback_type,
158 std::invoke_result_t<const callback_type&, A...>, A...>());
159 if constexpr (std::is_void_v<member>)
160 return false;
161 else
162 return result_matches && std::is_invocable_v<member, const callback_type&, A...>;
163 }
164 }
165}
167template <class Signature, class F>
168struct signature_binding {
169 static constexpr bool available = false;
170};
172template <class R, class... A, class F>
173struct signature_binding<R(A...), F> {
175 static consteval auto select() {
176 if constexpr (requires { static_cast<R (F::*)(A...) const>(&F::operator()); })
177 return static_cast<R (F::*)(A...) const>(&F::operator());
178 else if constexpr (requires { static_cast<R (F::*)(A...) const&>(&F::operator()); })
179 return static_cast<R (F::*)(A...) const&>(&F::operator());
180 }
181 static constexpr bool available = !std::is_void_v<decltype(select())>;
183};
185template <class Signature, class F>
186class signature_callback;
188template <class R, class... A, class F>
189class signature_callback<R(A...), F> {
190 F _callback;
191
192public:
196 template <class G>
197 requires(!std::same_as<std::remove_cvref_t<G>, signature_callback> &&
198 std::constructible_from<F, G&&>) explicit signature_callback(G&& callback) :
199 _callback(std::forward<G>(callback)) {}
203 R operator()(A... arguments) const {
204 return std::invoke(signature_binding<R(A...), F>::select(), _callback,
205 std::forward<A>(arguments)...);
206 }
207};
209struct argument_read {
210 std::size_t index;
211 value_type type;
212};
214struct construction_effect {
215 std::size_t cursor;
216 stack_requirements requirements;
217};
218} // namespace detail
219
230template <class Signature, class F>
231requires(detail::signature_binding<Signature, std::decay_t<F>>::available) auto with_signature(
232 F&& callback) {
233 return detail::signature_callback<Signature, std::decay_t<F>>(std::forward<F>(callback));
234}
235
250 detail::raw_segment _body;
251 std::vector<value_type> _stack;
252 std::vector<detail::argument_read> _reads;
253 std::vector<std::size_t> _end_cursors; // Mirrors canonical cursor ends in _stack order.
254 stack_requirements _requirements; // Retains committed intermediate storage peaks.
255 stack_origin _origin; // Retains the ambient origin independently of local operands.
256 std::vector<std::optional<stack_requirements>> _known_calls; // Tracks direct frozen callees.
263 void pack(value_type type, std::span<const std::size_t> permutation, stack_origin ambient);
270 void project(std::size_t index, type_kind category);
280 detail::construction_effect check_operation(std::span<const value_type> inputs,
281 std::span<const value_type> outputs);
288 void apply_operation(std::size_t consumed,
289 std::span<const value_type> outputs,
290 const detail::construction_effect& effect) noexcept;
291
292public:
296 dyn_segment() = default;
304 explicit dyn_segment(stack_origin origin) : _origin(origin) {}
305 dyn_segment(const dyn_segment&) = delete;
306 dyn_segment& operator=(const dyn_segment&) = delete;
310 dyn_segment(dyn_segment&&) noexcept = default;
315 dyn_segment& operator=(dyn_segment&&) noexcept = default;
319 stack_origin origin() const noexcept { return _origin; }
329 std::span<const value_type> operand_types(std::size_t arity) const noexcept {
330 if (arity > _stack.size()) return {};
331 return std::span<const value_type>(_stack).last(arity);
332 }
333
346 stack_origin origin_below(std::size_t count) const;
365 void make_tuple(std::size_t count, stack_origin ambient);
378 void make_array(std::size_t count, value_type element, stack_origin ambient);
384 void make_record(value_type record, stack_origin ambient);
399 std::span<const std::size_t> permutation,
400 stack_origin ambient);
412 void project_tuple(std::size_t index);
425 void project_record(std::string_view name);
438 // [knowledge] Check representability before the size_t cast, then exact bounds before access.
467 void if_else(dyn_segment then_body, dyn_segment else_body);
496 void push_closure(compiled_segment body, std::span<const value_type> parameters);
515 void invoke_closure(std::size_t arity);
527 void push_argument(std::size_t index, value_type type);
539 void just(value literal);
562 template <class R, class... Args, class F>
563 requires(detail::exact_callback<F, R, Args...>()) void op(F&& callback) {
564 static_assert((std::same_as<Args, std::remove_cvref_t<Args>> && ...));
565 const std::array<value_type, sizeof...(Args)> inputs{
566 detail::boundary_adapter<Args>::type()...};
567 const auto outputs = [] {
568 if constexpr (std::is_void_v<R>)
569 return std::array<value_type, 0>{};
570 else
571 return std::array{detail::boundary_adapter<R>::type()};
572 }();
573 const auto effect = check_operation(inputs, outputs);
574 _body.template push_op<R, Args...>(
575 [callback = std::forward<F>(callback)](detail::frame&, Args&&... operands) -> R {
576 return std::invoke(callback, std::move(operands)...);
577 });
578 apply_operation(sizeof...(Args), outputs, effect);
579 }
580
585 template <class R, class F>
586 requires(detail::exact_callback<F, R>()) void op0(F&& callback) {
587 op<R>(std::forward<F>(callback));
588 }
589
594 template <class R, class A, class F>
595 requires(detail::exact_callback<F, R, A>()) void op1(F&& callback) {
596 op<R, A>(std::forward<F>(callback));
597 }
598
604 template <class R, class A, class B, class F>
605 requires(detail::exact_callback<F, R, A, B>()) void op2(F&& callback) {
606 op<R, A, B>(std::forward<F>(callback));
607 }
608
615 template <class R, class A, class B, class C, class F>
616 requires(detail::exact_callback<F, R, A, B, C>()) void op3(F&& callback) {
617 op<R, A, B, C>(std::forward<F>(callback));
618 }
619
630};
631
646class compiled_segment {
647 detail::retirement_ptr<const detail::frozen_program> _program;
648 friend class dyn_segment;
649 friend struct detail::segment_access;
651 explicit compiled_segment(
652 detail::retirement_ptr<const detail::frozen_program> program) noexcept;
653
665 detail::prepared_raw_segment prepare_raw(std::span<const value_type> arguments,
666 const value_type& result) const;
667
668public:
669 compiled_segment(const compiled_segment&) = delete;
670 compiled_segment& operator=(const compiled_segment&) = delete;
672 compiled_segment(compiled_segment&&) noexcept = default;
677 compiled_segment& operator=(compiled_segment&&) noexcept = default;
685 const value_type& result_type() const noexcept;
693 const stack_requirements& requirements() const noexcept;
711 value execute(raw_stack& stack, std::span<const value> arguments) const;
724 template <class R, class... Args>
725 prepared_segment<R, Args...> prepare() const;
726};
727
728namespace detail {
738class prepared_raw_segment {
739 detail::retirement_ptr<const detail::frozen_program> _program;
740 std::vector<value_type> _arguments;
741 value_type _result;
742 std::vector<bool> _used;
743 value_type _unit;
744 friend class cel::compiled_segment;
745 friend struct segment_access;
746 template <class R, class... Args>
747 friend class cel::prepared_segment;
753 prepared_raw_segment(detail::retirement_ptr<const detail::frozen_program> program,
754 std::span<const value_type> arguments,
755 value_type result);
756
757public:
758 prepared_raw_segment(const prepared_raw_segment&) = delete;
759 prepared_raw_segment& operator=(const prepared_raw_segment&) = delete;
761 prepared_raw_segment(prepared_raw_segment&&) noexcept = default;
765 prepared_raw_segment& operator=(prepared_raw_segment&&) noexcept = default;
771 std::span<const value_type> argument_types() const noexcept { return _arguments; }
777 const value_type& result_type() const noexcept { return _result; }
783 const stack_requirements& requirements() const noexcept;
805 void call_into(raw_stack& stack,
806 std::span<const borrowed_value> arguments,
807 std::byte* result_destination) const;
820 void destroy_result(std::byte* result) const noexcept;
821};
822
826const std::byte* canonical_data(const value& source) noexcept;
828template <class T>
829struct typed_input {
831 using storage = std::conditional_t<native_leaf<T>, std::reference_wrapper<const T>, value>;
832 storage source;
833
837 static storage bind(const T& input, bool used) {
838 if constexpr (native_leaf<T>) {
839 return std::cref(input);
840 } else {
841 return used ? value::from(input) : value{};
842 }
843 }
847 explicit typed_input(const T& input, bool used) : source(bind(input, used)) {}
851 borrowed_value borrow(const value_type& type) const noexcept {
852 if constexpr (native_leaf<T>) {
853 return {type, reinterpret_cast<const std::byte*>(&source.get())};
854 } else {
855 return {type, canonical_data(source)};
856 }
857 }
858};
862class result_storage {
863 const prepared_raw_segment& _binding;
864 std::byte* _data;
865 bool _initialized = false;
866
867public:
873 explicit result_storage(const prepared_raw_segment& binding);
877 ~result_storage();
878 result_storage(const result_storage&) = delete;
879 result_storage& operator=(const result_storage&) = delete;
881 std::byte* data() const noexcept { return _data; }
885 void initialized() noexcept { _initialized = true; }
886};
887} // namespace detail
888
902template <class R, class... Args>
903class prepared_segment {
904 detail::prepared_raw_segment _binding;
905 friend class compiled_segment;
907 explicit prepared_segment(detail::prepared_raw_segment binding) :
908 _binding(std::move(binding)) {}
912 template <std::size_t... I>
913 auto bind(const std::tuple<const Args&...>& inputs, std::index_sequence<I...>) const {
914 return std::tuple<detail::typed_input<Args>...>{
915 detail::typed_input<Args>(std::get<I>(inputs), _binding._used[I])...};
916 }
922 template <std::size_t... I>
923 auto borrow(const std::tuple<detail::typed_input<Args>...>& inputs,
924 std::index_sequence<I...>) const {
925 return std::array<detail::borrowed_value, sizeof...(Args)>{
926 (_binding._used[I] ? std::get<I>(inputs).borrow(_binding.argument_types()[I]) :
927 detail::borrowed_value{_binding._unit, nullptr})...};
928 }
929
930public:
931 prepared_segment(const prepared_segment&) = delete;
932 prepared_segment& operator=(const prepared_segment&) = delete;
934 prepared_segment(prepared_segment&&) noexcept = default;
938 prepared_segment& operator=(prepared_segment&&) noexcept = default;
946 const stack_requirements& requirements() const noexcept { return _binding.requirements(); }
960 R call(raw_stack& stack, const Args&... arguments) const {
961 const auto inputs = bind(std::tie(arguments...), std::index_sequence_for<Args...>{});
962 const auto views = borrow(inputs, std::index_sequence_for<Args...>{});
963 if constexpr (detail::native_leaf<R>) {
964 alignas(R) std::array<std::byte, sizeof(R)> bytes{};
965 _binding.call_into(stack, views, bytes.data());
966 return detail::boundary_adapter<R>::read(_binding.result_type(), bytes.data());
967 } else {
968 detail::result_storage result(_binding);
969 _binding.call_into(stack, views, result.data());
970 result.initialized();
971 return detail::boundary_adapter<R>::read(_binding.result_type(), result.data());
972 }
973 }
974};
975
976// Adapter construction and checked binding follow the declaration's prepare() contract.
977template <class R, class... Args>
979 static_assert(!std::is_void_v<R>, "use tuple<> for the source-unit result");
980 const std::array<value_type, sizeof...(Args)> types{detail::boundary_adapter<Args>::type()...};
981 return prepared_segment<R, Args...>(prepare_raw(types, detail::boundary_adapter<R>::type()));
982}
983
985} // namespace cel
986#endif
A move-only handle to immutable frozen code and its captures.
Definition dyn_segment.hpp:646
const value_type & result_type() const noexcept
Returns the complete frozen result descriptor.
compiled_segment(compiled_segment &&) noexcept=default
Transfers the frozen handle.
value execute(raw_stack &stack, std::span< const value > arguments) const
Executes checked positional inputs and returns one independent result owner.
const stack_requirements & requirements() const noexcept
Borrows frozen intermediate alignment, peak canonical extent, and live-slot depth.
A move-only builder of checked, source-ordered operations.
Definition dyn_segment.hpp:249
dyn_segment(dyn_segment &&) noexcept=default
Transfers construction ownership.
void op1(F &&callback)
Emits a unary operation that consumes one exact operand and produces R unless it is void.
Definition dyn_segment.hpp:595
void index_array()
Emits an operation that consumes an array and f64 index and transfers the selected element.
void make_record(value_type record, stack_origin ambient)
Emits a consuming record construction from schema-ordered operands.
compiled_segment finish() &&
Freezes exactly one result, mapping an empty final stack to source unit.
void make_tuple(std::size_t count, stack_origin ambient)
Emits an operation that consumes count source-ordered operands and returns a tuple.
void just(value literal)
Retains a literal owner and emits an independent clone on every execution.
void invoke_closure(std::size_t arity)
Emits an invocation consuming an installed callee and its source-ordered arguments.
void project_tuple(std::size_t index)
Emits an operation that consumes a tuple and transfers the selected field without cloning.
void make_array(std::size_t count, value_type element, stack_origin ambient)
Emits an operation that consumes count exact elements and returns an owning array.
dyn_segment(stack_origin origin)
Creates an empty dependent fragment at the supplied ambient origin.
Definition dyn_segment.hpp:304
void logical_and(dyn_segment rhs)
Emits a conjunction that consumes bool and executes bool rhs only when the left is true.
void make_record(value_type record, std::span< const std::size_t > permutation, stack_origin ambient)
Emits a consuming record construction from source-ordered fields and a schema permutation.
dyn_segment()=default
Creates an empty independent builder.
void push_closure(compiled_segment body, std::span< const value_type > parameters)
Emits an installed callable retaining explicit parameters and independent frozen code.
void push_argument(std::size_t index, value_type type)
Emits a read that clones a borrowed positional input when the program executes.
stack_origin before_top() const
Returns the origin immediately below the top local operand.
void make_range(range_kind kind)
Emits a range construction consuming its source-ordered f64 endpoints.
stack_origin origin_below(std::size_t count) const
Returns the absolute origin below count local operands.
stack_origin origin() const noexcept
Returns the retained ambient origin.
Definition dyn_segment.hpp:319
void if_else(dyn_segment then_body, dyn_segment else_body)
Emits a conditional that consumes bool and executes exactly one dependent body.
void op3(F &&callback)
Emits a ternary operation consuming source-ordered operands and producing R unless it is void.
Definition dyn_segment.hpp:616
void project_record(std::string_view name)
Emits an operation that consumes a record and transfers the named field without cloning.
void op2(F &&callback)
Emits a binary operation that consumes older-first operands and produces R unless it is void.
Definition dyn_segment.hpp:605
stack_origin snapshot() const
Returns the current absolute logical cursor and live-slot depth.
void op(F &&callback)
Emits an arbitrary-arity const callback with exact declared operands and result.
Definition dyn_segment.hpp:563
std::span< const value_type > operand_types(std::size_t arity) const noexcept
Borrows the requested local logical operand suffix in older-first order.
Definition dyn_segment.hpp:329
void logical_or(dyn_segment rhs)
Emits a disjunction that consumes bool and executes bool rhs only when the left is false.
void op0(F &&callback)
Emits a zero-operand callback; void produces no value, otherwise pushes one result.
Definition dyn_segment.hpp:586
A move-only typed binding that borrows inputs and returns concrete results.
Definition dyn_segment.hpp:903
R call(raw_stack &stack, const Args &... arguments) const
Executes borrowed inputs and returns an independent concrete result.
Definition dyn_segment.hpp:960
const stack_requirements & requirements() const noexcept
Borrows the frozen program's canonical frame reservation requirements.
Definition dyn_segment.hpp:946
prepared_segment(prepared_segment &&) noexcept=default
Transfers typed binding ownership.
An exclusive owner of reusable canonical operand storage.
Definition raw_stack.hpp:47
An immutable, shared semantic type with a canonical byte layout.
Definition value_type.hpp:65
Holds any type representable by CEL, including client-defined types.
Definition value.hpp:83
static value from(const T &source)
Copies a concrete leaf, nominal record adapter, or nested owning vector/tuple value.
Definition value.hpp:229
prepared_segment< R, Args... > prepare() const
Binds exact recursive concrete adapters once, admitting valid client leaves at roots.
Definition dyn_segment.hpp:978
auto with_signature(F &&callback)
Selects an exact const callback member from an ambiguous or uninspectable overload set.
Definition dyn_segment.hpp:231
bool operator==(const stack_origin &left, const stack_origin &right) noexcept
Compares both ambient coordinates exactly.
Definition dyn_segment.hpp:27
range_kind
Identifies every source range form independently of its endpoint layout.
Definition value_type.hpp:22
type_kind
Identifies a descriptor's structural category.
Definition value_type.hpp:34
Byte extents for stack reservation and type descriptors.
Definition callable.hpp:6
A byte extent and its requested alignment, both in bytes.
Definition layout.hpp:18
A byte cursor and live-slot depth below a fragment's local operands.
Definition dyn_segment.hpp:20
std::size_t depth
Gives the ambient live-slot count.
Definition dyn_segment.hpp:22
std::size_t bytes
Gives the ambient canonical cursor.
Definition dyn_segment.hpp:21
The statically known storage requirements of a frozen ordinary program.
Definition dyn_segment.hpp:55
std::size_t live_slots
Gives peak simultaneously live frame operands.
Definition dyn_segment.hpp:58
std::size_t frame_extent
Gives peak canonical extent for a zero-cursor frame.
Definition dyn_segment.hpp:57
std::size_t alignment
Gives maximum intermediate canonical alignment.
Definition dyn_segment.hpp:56
stack_reservation for_prefix(std::size_t cursor, std::size_t depth) const
Returns checked conservative total capacities for an existing caller prefix.
Total byte and slot capacities for one prefixed execution.
Definition dyn_segment.hpp:42
layout bytes
Gives total byte capacity and required alignment.
Definition dyn_segment.hpp:43
std::size_t slots
Gives total live-slot capacity, including the caller prefix.
Definition dyn_segment.hpp:44