1use std::any::{Any, TypeId};
14use std::cell::Cell;
15
16use anyhow::{Result, anyhow, ensure};
17
18use crate::canonical_operation::OperationPlan;
19use crate::container_execution::{ContainerPlan, ResultPlan, StackFramePlan, stack_position};
20use crate::host_value_bridge::HostValuePlan;
21use crate::owned_value::OwnedValue;
22use crate::{
23 AssociatedType, CNil, CStackList, CStackListHeadLimit, CStackListHeadPadded, IntoCStackList,
24 Leaf, List, RawSegment, RawStack, ReverseList, ValueKind, ValueRepr, ValueType,
25};
26
27thread_local! {
28 static ARGUMENTS: Cell<*const *const u8> = const { Cell::new(std::ptr::null()) };
30}
31
32struct ArgumentGuard(*const *const u8);
34
35impl ArgumentGuard {
36 fn install(arguments: &[*const u8]) -> Self {
38 Self(ARGUMENTS.with(|slot| slot.replace(arguments.as_ptr())))
39 }
40}
41
42impl Drop for ArgumentGuard {
43 fn drop(&mut self) {
45 ARGUMENTS.with(|slot| slot.set(self.0));
46 }
47}
48
49#[derive(Clone, Debug)]
51pub struct StackInfo {
52 pub padding: bool,
54 pub value_type: ValueType,
56}
57
58fn descriptor_name(ty: &ValueType) -> String {
63 let mut output = String::new();
64 append_descriptor_name(ty, &mut output);
65 output
66}
67
68fn append_descriptor_name(ty: &ValueType, output: &mut String) {
73 match ty.kind() {
74 ValueKind::Array(element) => {
75 output.push('[');
76 append_descriptor_name(element, output);
77 output.push(']');
78 }
79 ValueKind::Tuple(fields) => {
80 output.push('(');
81 for (index, field) in fields.iter().enumerate() {
82 if index != 0 {
83 output.push_str(", ");
84 }
85 append_descriptor_name(&field.value_type, output);
86 }
87 output.push(')');
88 }
89 _ => output.push_str(ty.type_name()),
90 }
91}
92
93pub trait ToTypeIdList: List {
95 fn to_stack_info_list() -> Vec<StackInfo>;
99}
100
101impl ToTypeIdList for CNil<()> {
102 fn to_stack_info_list() -> Vec<StackInfo> {
104 Vec::new()
105 }
106}
107
108impl<H: 'static, T: ToTypeIdList + 'static + CStackListHeadLimit> ToTypeIdList
109 for CStackList<H, T>
110{
111 fn to_stack_info_list() -> Vec<StackInfo> {
115 let mut result = T::to_stack_info_list();
116 result.push(StackInfo {
117 padding: Self::HEAD_PADDED,
118 value_type: ValueType::leaf::<H>(),
119 });
120 result
121 }
122}
123
124pub struct DynSegment {
129 pub(crate) segment: RawSegment,
131 pub(crate) argument_ids: Vec<TypeId>,
133 pub(crate) stack_ids: Vec<StackInfo>,
135 pub(crate) base_stack_index: usize,
137 pub(crate) argument_reads: Vec<(usize, ValueType)>,
139 stack_ends: Vec<usize>,
141}
142
143impl DynSegment {
144 pub fn new<Args: IntoCStackList>() -> Self
154 where
155 ReverseList<Args::Output>: ToTypeIdList,
156 {
157 let stack_ids = ReverseList::<Args::Output>::to_stack_info_list();
158 let mut segment = RawSegment::new();
159 segment.update_base_alignment(1);
160 for info in &stack_ids {
161 info.value_type
162 .validate_canonical()
163 .expect("preloaded dynamic arguments must be canonical or ordinary opaque leaves");
164 segment.update_base_alignment(info.value_type.align());
165 }
166 segment.set_frame(0, stack_ids.len());
167 let mut stack_ends = Vec::with_capacity(stack_ids.len() + 1);
168 stack_ends.push(0);
169 for info in &stack_ids {
170 stack_ends.push(
171 stack_position(*stack_ends.last().unwrap(), info.value_type.layout())
172 .expect("validated preloaded stack")
173 .1,
174 );
175 }
176 Self {
177 segment,
178 argument_ids: stack_ids
179 .iter()
180 .map(|info| info.value_type.type_id())
181 .collect(),
182 stack_ids,
183 base_stack_index: 0,
184 argument_reads: Vec::new(),
185 stack_ends,
186 }
187 }
188
189 pub fn new_fragment(&self) -> Self {
196 debug_assert!(!self.stack_ids.is_empty());
197 let mut result = Self::new::<()>();
198 result.base_stack_index = self.stack_offset_before_top(1).expect("condition present");
199 result.stack_ends[0] = result.base_stack_index;
200 result.segment.set_frame(result.base_stack_index, 0);
201 result
202 }
203
204 pub fn current_stack_offset(&self) -> usize {
211 self.offset_after(self.stack_ids.len())
212 }
213
214 pub fn stack_offset_before_top(&self, n: usize) -> Result<usize> {
224 let count = self
225 .stack_ids
226 .len()
227 .checked_sub(n)
228 .ok_or_else(|| anyhow!("not enough operands"))?;
229 Ok(self.offset_after(count))
230 }
231
232 fn offset_after(&self, count: usize) -> usize {
234 self.stack_ends[count]
235 }
236
237 fn operation(&self, arity: usize, result: ValueType) -> Result<OperationPlan> {
243 let first = self
244 .stack_ids
245 .len()
246 .checked_sub(arity)
247 .ok_or_else(|| anyhow!("not enough operands"))?;
248 let operands: Vec<_> = self.stack_ids[first..]
249 .iter()
250 .map(|info| info.value_type.clone())
251 .collect();
252 OperationPlan::at(
253 self.base_stack_index,
254 self.offset_after(first),
255 first,
256 &operands,
257 result,
258 )
259 }
260
261 fn replace(&mut self, arity: usize, result: ValueType) {
265 self.stack_ids.truncate(self.stack_ids.len() - arity);
266 self.stack_ends.truncate(self.stack_ids.len() + 1);
267 let before = self.current_stack_offset();
268 let (offset, end) = stack_position(before, result.layout()).expect("validated result");
269 self.segment.update_base_alignment(result.align());
270 self.stack_ids.push(StackInfo {
271 padding: offset != before,
272 value_type: result,
273 });
274 self.stack_ends.push(end);
275 }
276
277 pub fn peek_stack_infos(&self, n: usize) -> &[StackInfo] {
285 &self.stack_ids[self.stack_ids.len().saturating_sub(n)..]
286 }
287
288 pub fn peek_output_type_id(&self) -> Option<TypeId> {
295 Some(self.stack_ids.last()?.value_type.type_id())
296 }
297
298 pub fn peek_tuple_arity(&self) -> Option<usize> {
305 Some(self.stack_ids.last()?.value_type.tuple_elements()?.len())
306 }
307
308 pub fn op0<R: 'static, F: Fn() -> R + 'static>(&mut self, f: F) {
321 self.op0_repr::<Leaf<R>, _>(f)
322 .expect("opaque result fits raw frame");
323 }
324
325 pub fn op0r<R: 'static, F: Fn() -> Result<R> + 'static>(&mut self, f: F) {
336 self.op0r_repr::<Leaf<R>, _>(f)
337 .expect("opaque result fits raw frame");
338 }
339
340 pub fn op0_repr<R: ValueRepr, F: Fn() -> R::Value + 'static>(&mut self, f: F) -> Result<()> {
352 self.op0r_repr::<R, _>(move || Ok(f()))
353 }
354
355 pub fn op0r_repr<R: ValueRepr, F: Fn() -> Result<R::Value> + 'static>(
367 &mut self,
368 f: F,
369 ) -> Result<()> {
370 let result = R::value_type();
371 self.operation(0, result.clone())?
372 .emit0::<R, _>(&mut self.segment, f)?;
373 self.replace(0, result);
374 Ok(())
375 }
376
377 pub fn op1<A: 'static, R: 'static, F: Fn(A) -> R + 'static>(&mut self, f: F) -> Result<()> {
389 self.op1_repr::<Leaf<A>, Leaf<R>, _>(f)
390 }
391
392 pub fn op1r<A: 'static, R: 'static, F: Fn(A) -> Result<R> + 'static>(
404 &mut self,
405 f: F,
406 ) -> Result<()> {
407 self.op1r_repr::<Leaf<A>, Leaf<R>, _>(f)
408 }
409
410 pub fn op1_repr<A: ValueRepr, R: ValueRepr, F: Fn(A::Value) -> R::Value + 'static>(
423 &mut self,
424 f: F,
425 ) -> Result<()> {
426 self.op1r_repr::<A, R, _>(move |a| Ok(f(a)))
427 }
428
429 pub fn op1r_repr<A: ValueRepr, R: ValueRepr, F: Fn(A::Value) -> Result<R::Value> + 'static>(
442 &mut self,
443 f: F,
444 ) -> Result<()> {
445 let result = R::value_type();
446 self.operation(1, result.clone())?
447 .emit1::<A, R, _>(&mut self.segment, f)?;
448 self.replace(1, result);
449 Ok(())
450 }
451
452 pub fn op2<A: 'static, B: 'static, R: 'static, F: Fn(A, B) -> R + 'static>(
464 &mut self,
465 f: F,
466 ) -> Result<()> {
467 self.op2_repr::<Leaf<A>, Leaf<B>, Leaf<R>, _>(f)
468 }
469
470 pub fn op2r<A: 'static, B: 'static, R: 'static, F: Fn(A, B) -> Result<R> + 'static>(
485 &mut self,
486 f: F,
487 ) -> Result<()> {
488 self.op2r_repr::<Leaf<A>, Leaf<B>, Leaf<R>, _>(f)
489 }
490
491 pub fn op2_repr<
500 A: ValueRepr,
501 B: ValueRepr,
502 R: ValueRepr,
503 F: Fn(A::Value, B::Value) -> R::Value + 'static,
504 >(
505 &mut self,
506 f: F,
507 ) -> Result<()> {
508 self.op2r_repr::<A, B, R, _>(move |a, b| Ok(f(a, b)))
509 }
510
511 pub fn op2r_repr<
520 A: ValueRepr,
521 B: ValueRepr,
522 R: ValueRepr,
523 F: Fn(A::Value, B::Value) -> Result<R::Value> + 'static,
524 >(
525 &mut self,
526 f: F,
527 ) -> Result<()> {
528 let result = R::value_type();
529 self.operation(2, result.clone())?
530 .emit2::<A, B, R, _>(&mut self.segment, f)?;
531 self.replace(2, result);
532 Ok(())
533 }
534
535 pub fn op3<A: 'static, B: 'static, C: 'static, R: 'static, F: Fn(A, B, C) -> R + 'static>(
544 &mut self,
545 f: F,
546 ) -> Result<()> {
547 self.op3_repr::<Leaf<A>, Leaf<B>, Leaf<C>, Leaf<R>, _>(f)
548 }
549
550 pub fn op3r<
559 A: 'static,
560 B: 'static,
561 C: 'static,
562 R: 'static,
563 F: Fn(A, B, C) -> Result<R> + 'static,
564 >(
565 &mut self,
566 f: F,
567 ) -> Result<()> {
568 self.op3r_repr::<Leaf<A>, Leaf<B>, Leaf<C>, Leaf<R>, _>(f)
569 }
570
571 pub fn op3_repr<
580 A: ValueRepr,
581 B: ValueRepr,
582 C: ValueRepr,
583 R: ValueRepr,
584 F: Fn(A::Value, B::Value, C::Value) -> R::Value + 'static,
585 >(
586 &mut self,
587 f: F,
588 ) -> Result<()> {
589 self.op3r_repr::<A, B, C, R, _>(move |a, b, c| Ok(f(a, b, c)))
590 }
591
592 pub fn op3r_repr<
601 A: ValueRepr,
602 B: ValueRepr,
603 C: ValueRepr,
604 R: ValueRepr,
605 F: Fn(A::Value, B::Value, C::Value) -> Result<R::Value> + 'static,
606 >(
607 &mut self,
608 f: F,
609 ) -> Result<()> {
610 let result = R::value_type();
611 self.operation(3, result.clone())?
612 .emit3::<A, B, C, R, _>(&mut self.segment, f)?;
613 self.replace(3, result);
614 Ok(())
615 }
616
617 pub fn op1_vec<E: ValueRepr, R: ValueRepr, F: Fn(Vec<E::Value>) -> R::Value + 'static>(
626 &mut self,
627 f: F,
628 ) -> Result<()> {
629 self.op1r_vec::<E, R, _>(move |a| Ok(f(a)))
630 }
631
632 pub fn op1r_vec<
641 E: ValueRepr,
642 R: ValueRepr,
643 F: Fn(Vec<E::Value>) -> Result<R::Value> + 'static,
644 >(
645 &mut self,
646 f: F,
647 ) -> Result<()> {
648 let result = R::value_type();
649 self.operation(1, result.clone())?
650 .emit_vec::<E, R, _>(&mut self.segment, f)?;
651 self.replace(1, result);
652 Ok(())
653 }
654
655 pub fn op1_slice<E: ValueRepr, R: ValueRepr, F: Fn(&[E::Value]) -> R::Value + 'static>(
665 &mut self,
666 f: F,
667 ) -> Result<()> {
668 self.op1r_slice::<E, R, _>(move |a| Ok(f(a)))
669 }
670
671 pub fn op1r_slice<
680 E: ValueRepr,
681 R: ValueRepr,
682 F: Fn(&[E::Value]) -> Result<R::Value> + 'static,
683 >(
684 &mut self,
685 f: F,
686 ) -> Result<()> {
687 let result = R::value_type();
688 self.operation(1, result.clone())?
689 .emit_slice::<E, R, _>(&mut self.segment, f)?;
690 self.replace(1, result);
691 Ok(())
692 }
693
694 pub fn just<T: Clone + 'static>(&mut self, value: T) {
704 self.op0(move || value.clone());
705 self.replace(1, ValueType::cloneable_leaf::<T>());
706 }
707
708 pub fn just_external(&mut self, value_type: ValueType, value: Box<dyn Any>) -> Result<()> {
727 value_type.validate_canonical()?;
728 value_type.validate_clone()?;
729 let owner = HostValuePlan::new(value_type.clone())?.import_box(&mut Some(value))?;
730 let result = ResultPlan::new(self.current_stack_offset(), value_type.clone())?;
731 self.segment.update_base_alignment(value_type.align());
732 self.segment.raw0_(move |stack| {
733 unsafe {
736 result.clone_from(stack, owner.as_ptr());
737 }
738 Ok(())
739 });
740 self.replace(0, value_type);
741 Ok(())
742 }
743
744 pub fn push_arg<T: Clone + 'static>(&mut self, index: usize) {
753 self.push_argument(index, ValueType::cloneable_leaf::<T>())
754 .expect("cloneable leaf");
755 }
756
757 pub fn push_argument(&mut self, index: usize, value_type: ValueType) -> Result<()> {
771 value_type.validate_canonical()?;
772 ensure!(
773 value_type.can_clone(),
774 "argument clone capability unavailable"
775 );
776 let result = ResultPlan::new(self.current_stack_offset(), value_type.clone())?;
777 self.segment.update_base_alignment(value_type.align());
778 self.segment.raw0_(move |stack| {
779 unsafe {
782 let source = ARGUMENTS.with(|slot| *slot.get().add(index));
783 result.clone_from(stack, source);
784 }
785 Ok(())
786 });
787 self.argument_reads.push((index, value_type.clone()));
788 self.replace(0, value_type);
789 Ok(())
790 }
791
792 pub fn make_tuple(&mut self, n: usize, ambient_start: usize) -> Result<()> {
804 ensure!(
805 self.stack_offset_before_top(n)? == ambient_start,
806 "tuple ambient origin mismatch"
807 );
808 let fields = self
809 .peek_stack_infos(n)
810 .iter()
811 .map(|info| AssociatedType {
812 offset: 0,
813 value_type: info.value_type.clone(),
814 })
815 .collect();
816 let value_type = ValueType::tuple(fields)?;
817 let frame = StackFramePlan::new(ambient_start, value_type.clone())?;
818 let result = ResultPlan::new(ambient_start, value_type.clone())?;
819 self.segment.update_base_alignment(value_type.align());
820 self.segment.raw0_(move |stack| {
821 let mut owner = unsafe { frame.take(stack) };
823 unsafe { result.push(stack, &mut owner) };
824 Ok(())
825 });
826 self.replace(n, value_type);
827 Ok(())
828 }
829
830 pub fn make_array(&mut self, n: usize, ambient_start: usize) -> Result<()> {
843 ensure!(
844 n != 0,
845 "empty array requires an explicit complete element type"
846 );
847 self.stack_offset_before_top(n)?;
848 let element = self.peek_stack_infos(n)[0].value_type.clone();
849 self.make_typed_array(n, ambient_start, element)
850 }
851
852 pub fn make_typed_array(
865 &mut self,
866 n: usize,
867 ambient_start: usize,
868 element: ValueType,
869 ) -> Result<()> {
870 element.validate_canonical()?;
871 ensure!(
872 self.stack_offset_before_top(n)? == ambient_start,
873 "array ambient origin mismatch"
874 );
875 for (index, info) in self.peek_stack_infos(n).iter().enumerate() {
876 ensure!(
877 info.value_type.same_shape(&element),
878 "array element {index} has type {}, expected {}",
879 descriptor_name(&info.value_type),
880 descriptor_name(&element)
881 );
882 }
883 let container = ContainerPlan::array(element.clone(), n)?;
884 let result_type = ValueType::array(element.clone());
885 let result = ResultPlan::new(ambient_start, result_type.clone())?;
886 let mut end = ambient_start;
887 let offsets = (0..n)
888 .map(|_| {
889 let (offset, next) = stack_position(end, element.layout())?;
890 end = next;
891 Ok(offset)
892 })
893 .collect::<Result<Vec<_>>>()?;
894 self.segment.update_base_alignment(result_type.align());
895 self.segment.raw0_(move |stack| {
896 let mut owner = unsafe {
898 container.construct(|index, destination| {
899 stack.read_at(offsets[index], |source| {
900 std::ptr::copy_nonoverlapping(source, destination, element.size())
901 });
902 Ok(())
903 })?
904 };
905 unsafe {
908 stack.release_top(n);
909 stack.truncate_to(ambient_start, false);
910 result.push(stack, &mut owner);
911 }
912 Ok(())
913 });
914 self.replace(n, result_type);
915 Ok(())
916 }
917
918 pub fn tuple_index(&mut self, index: usize) -> Result<()> {
931 let ty = self
932 .stack_ids
933 .last()
934 .ok_or_else(|| anyhow!("missing tuple"))?
935 .value_type
936 .clone();
937 let fields = ty
938 .tuple_elements()
939 .ok_or_else(|| anyhow!("tuple required"))?;
940 let field = fields
941 .get(index)
942 .ok_or_else(|| anyhow!("tuple index out of range"))?
943 .value_type
944 .clone();
945 let ambient = self.stack_offset_before_top(1)?;
946 let input = ResultPlan::new(ambient, ty)?;
947 let output = ResultPlan::new(ambient, field.clone())?;
948 self.segment.raw0_(move |stack| {
949 let owner = unsafe { input.take(stack) };
950 let mut selected = unsafe { owner.take_field(index) };
951 unsafe { output.push(stack, &mut selected) };
952 Ok(())
953 });
954 self.replace(1, field);
955 Ok(())
956 }
957
958 pub fn array_index<I: TryInto<usize> + 'static>(&mut self) -> Result<()> {
976 let first = self
977 .stack_ids
978 .len()
979 .checked_sub(2)
980 .ok_or_else(|| anyhow!("array index requires two operands"))?;
981 self.stack_ids[first + 1]
982 .value_type
983 .validate_opaque_leaf(TypeId::of::<I>())?;
984 let array_type = self.stack_ids[first].value_type.clone();
985 let element = array_type
986 .array_element()
987 .ok_or_else(|| anyhow!("canonical array required"))?
988 .clone();
989 let ambient = self.offset_after(first);
990 let index = ResultPlan::new(self.offset_after(first + 1), ValueType::leaf::<I>())?;
991 let array = ResultPlan::new(ambient, array_type)?;
992 let output = ResultPlan::new(ambient, element.clone())?;
993 self.segment.update_base_alignment(element.align());
994 self.segment.raw0_(move |stack| {
995 let native = unsafe { index.take_typed::<I>(stack) };
997 let array_owner = unsafe { array.take(stack) };
998 let selected = native
999 .try_into()
1000 .map_err(|_| anyhow!("array index is negative or unrepresentable"))
1001 .and_then(|index| unsafe { array_owner.take_array_element(index) });
1002 match selected {
1003 Ok(mut value) => {
1004 unsafe { output.push(stack, &mut value) };
1005 Ok(())
1006 }
1007 Err(error) => Err(error),
1008 }
1009 });
1010 self.replace(2, element);
1011 Ok(())
1012 }
1013
1014 pub fn drop_value(&mut self) -> Result<()> {
1029 let first = self
1030 .stack_ids
1031 .len()
1032 .checked_sub(1)
1033 .ok_or_else(|| anyhow!("missing value"))?;
1034 self.segment.raw0_(|stack| {
1035 stack.drop_top();
1036 Ok(())
1037 });
1038 self.stack_ids.truncate(first);
1039 self.stack_ends.truncate(first + 1);
1040 Ok(())
1041 }
1042
1043 pub fn relabel_repr<R: ValueRepr>(&mut self) -> Result<()> {
1055 self.stack_ids
1056 .last()
1057 .ok_or_else(|| anyhow!("missing value"))?
1058 .value_type
1059 .validate::<R>()
1060 }
1061
1062 pub fn annotate_top(&mut self, value_type: ValueType) -> Result<()> {
1079 let info = self
1080 .stack_ids
1081 .last_mut()
1082 .ok_or_else(|| anyhow!("missing value"))?;
1083 ensure!(
1084 info.value_type.same_shape(&value_type),
1085 "top value annotation representation mismatch"
1086 );
1087 info.value_type = value_type;
1088 Ok(())
1089 }
1090
1091 pub fn pop_tuple_as<R: ValueRepr>(&mut self) -> Result<()> {
1106 let info = self
1107 .stack_ids
1108 .last_mut()
1109 .ok_or_else(|| anyhow!("missing tuple"))?;
1110 ensure!(
1111 info.value_type.tuple_elements().is_some(),
1112 "canonical tuple required"
1113 );
1114 info.value_type.validate::<R>()?;
1115 info.value_type = ValueType::leaf::<R::Value>();
1116 Ok(())
1117 }
1118
1119 pub fn push_tuple<R: ValueRepr>(&mut self) -> Result<()> {
1133 let value_type = R::value_type();
1134 ensure!(
1135 value_type.tuple_elements().is_some(),
1136 "canonical tuple witness required"
1137 );
1138 let info = self
1139 .stack_ids
1140 .last_mut()
1141 .ok_or_else(|| anyhow!("missing concrete list"))?;
1142 info.value_type
1143 .validate_opaque_leaf(TypeId::of::<R::Value>())?;
1144 debug_assert_eq!(info.value_type.layout(), value_type.layout());
1145 info.value_type = value_type;
1146 Ok(())
1147 }
1148
1149 pub(crate) fn validate_independent_body(&self) -> Result<()> {
1154 ensure!(
1155 self.argument_ids.is_empty(),
1156 "independent body must not require preloaded arguments"
1157 );
1158 ensure!(
1159 self.base_stack_index == 0,
1160 "independent body must not require a nonzero ambient stack origin"
1161 );
1162 Ok(())
1163 }
1164
1165 pub(crate) unsafe fn execute_raw(&mut self, arguments: &[*const u8]) -> Result<RawStack> {
1174 let _guard = ArgumentGuard::install(arguments);
1175 let mut output = RawStack::with_base_alignment(self.segment.base_alignment());
1176 unsafe { self.segment.call0_stack(&mut output)? };
1177 Ok(output)
1178 }
1179
1180 pub fn call_dyn<R: 'static>(&mut self, inputs: &[&dyn Any]) -> Result<R> {
1195 let result = self.result_type()?;
1196 match result.kind() {
1197 ValueKind::Tuple(fields)
1198 if fields.is_empty() && TypeId::of::<R>() == TypeId::of::<()>() =>
1199 {
1200 drop(self.call_dyn_value(inputs)?);
1201 let unit: Box<dyn Any> = Box::new(());
1202 return Ok(*unit.downcast::<R>().expect("checked host unit identity"));
1203 }
1204 ValueKind::Array(_) | ValueKind::Tuple(_) => {
1205 ensure!(
1206 TypeId::of::<R>() == TypeId::of::<OwnedValue>(),
1207 "canonical result owner required"
1208 );
1209 let owner: Box<dyn Any> = Box::new(self.call_dyn_value(inputs)?);
1210 return Ok(*owner
1211 .downcast::<R>()
1212 .map_err(|_| anyhow!("canonical result owner required"))?);
1213 }
1214 ValueKind::Callable { .. } => {
1215 ensure!(
1216 TypeId::of::<R>() == TypeId::of::<crate::DynClosure>(),
1217 "external callable result type mismatch"
1218 );
1219 }
1220 ValueKind::Leaf(_) => result.validate_opaque_leaf(TypeId::of::<R>())?,
1221 }
1222 let plan = ResultPlan::new(0, self.result_type()?.clone())?;
1223 let mut output = self.call_external(inputs)?;
1224 Ok(unsafe { plan.take_typed::<R>(&mut output) })
1225 }
1226
1227 pub fn call_dyn_value(&mut self, inputs: &[&dyn Any]) -> Result<OwnedValue> {
1241 let result = ResultPlan::new(0, self.result_type()?.clone())?;
1242 let mut output = self.call_external(inputs)?;
1243 Ok(unsafe { result.take(&mut output) })
1244 }
1245
1246 fn call_external(&mut self, inputs: &[&dyn Any]) -> Result<RawStack> {
1257 self.validate_independent_body()?;
1258 let mut first_reads: Vec<Option<&ValueType>> = vec![None; inputs.len()];
1259 for (index, ty) in &self.argument_reads {
1260 ensure!(*index < inputs.len(), "missing argument {index}");
1261 if let Some(first) = first_reads[*index] {
1262 ensure!(
1263 ty.same_shape(first),
1264 "inconsistent argument {index} representation"
1265 );
1266 } else {
1267 first_reads[*index] = Some(ty);
1268 }
1269 }
1270 let mut pointers = vec![std::ptr::null(); inputs.len()];
1271 for (index, ty) in first_reads.into_iter().enumerate() {
1272 if let Some(ty) = ty {
1273 pointers[index] = HostValuePlan::new(ty.clone())?.validate_any(inputs[index])?;
1274 }
1275 }
1276 unsafe { self.execute_raw(&pointers) }
1277 }
1278
1279 pub(crate) fn result_type(&self) -> Result<&ValueType> {
1284 ensure!(
1285 self.stack_ids.len() == 1,
1286 "body must produce exactly one value"
1287 );
1288 Ok(&self.stack_ids[0].value_type)
1289 }
1290
1291 pub fn call0<R: 'static>(&mut self) -> Result<R> {
1300 self.call_dyn(&[])
1301 }
1302
1303 pub fn call1<A: 'static, R: 'static>(&mut self, arg: A) -> Result<R> {
1316 ensure!(
1317 self.argument_ids == [TypeId::of::<A>()],
1318 "argument type mismatch"
1319 );
1320 ensure!(
1321 self.argument_reads.is_empty(),
1322 "preloaded call cannot use positional argument reads"
1323 );
1324 self.result_type()?
1325 .validate_opaque_leaf(TypeId::of::<R>())?;
1326 unsafe { self.segment.call1(arg) }
1327 }
1328
1329 pub fn prepare<A: ValueRepr, R: ValueRepr>(self) -> Result<crate::PreparedSegment<A, R>> {
1339 crate::PreparedSegment::new(self)
1340 }
1341
1342 pub fn push_closure(&mut self, closure: crate::DynClosure) -> Result<()> {
1351 let signature = closure
1352 .signature()
1353 .ok_or_else(|| anyhow!("closure signature metadata is unavailable"))?;
1354 closure.validate_body_signature()?;
1355 let ty = ValueType::callable(signature.parameters.clone(), signature.result.clone());
1356 let closure = closure.bind_canonical()?;
1358 self.segment.update_base_alignment(ty.align());
1359 self.segment.raw0_(move |stack| {
1360 stack.push(closure.clone());
1361 Ok(())
1362 });
1363 self.replace(0, ty);
1364 Ok(())
1365 }
1366
1367 pub fn invoke_closure(&mut self, arity: usize) -> Result<()> {
1387 ensure!(
1388 self.argument_ids.is_empty(),
1389 "closure invocation requires a positional body"
1390 );
1391 let operands = arity
1392 .checked_add(1)
1393 .ok_or_else(|| anyhow!("missing callee"))?;
1394 let first = self
1395 .stack_ids
1396 .len()
1397 .checked_sub(operands)
1398 .ok_or_else(|| anyhow!("missing callee"))?;
1399 let callee_type = self.stack_ids[first].value_type.clone();
1400 let ValueKind::Callable { parameters, result } = callee_type.kind() else {
1401 anyhow::bail!("callable signature required")
1402 };
1403 ensure!(parameters.len() == arity, "closure arity mismatch");
1404 ensure!(
1405 parameters
1406 .iter()
1407 .zip(&self.stack_ids[first + 1..])
1408 .all(|(expected, actual)| expected.same_shape(&actual.value_type)),
1409 "closure argument type mismatch"
1410 );
1411 let result_type = result.as_ref().clone();
1412 let ambient = self.offset_after(first);
1413 let argument_type = ValueType::tuple(
1414 parameters
1415 .iter()
1416 .map(|value_type| AssociatedType {
1417 offset: 0,
1418 value_type: value_type.clone(),
1419 })
1420 .collect(),
1421 )?;
1422 let arguments_start = self.offset_after(first + 1);
1423 let frame = StackFramePlan::new(arguments_start, argument_type.clone())?;
1424 let callee = ResultPlan::new(ambient, callee_type.clone())?;
1425 let destination = ResultPlan::new(ambient, result_type.clone())?;
1426 self.segment.update_base_alignment(result_type.align());
1427 let output_type = result_type.clone();
1428 self.segment.raw0_(move |stack| {
1429 let arguments = unsafe { frame.take(stack) };
1431 let closure = unsafe { callee.take_typed::<crate::DynClosure>(stack) };
1433 let allocation = crate::owned_value::Allocation::new(output_type.layout());
1436 let evaluated = unsafe {
1437 closure.call_frame_trusted(arguments.as_ptr(), allocation.pointer.as_ptr())
1438 };
1439 match evaluated {
1440 Ok(()) => {
1441 let mut result = unsafe {
1442 crate::OwnedValue::from_allocation(allocation, output_type.clone())
1443 };
1444 drop(arguments);
1445 drop(closure);
1446 unsafe { destination.push(stack, &mut result) };
1447 Ok(())
1448 }
1449 Err(error) => {
1450 drop(arguments);
1451 drop(closure);
1452 Err(error)
1453 }
1454 }
1455 });
1456 self.replace(operands, result_type);
1457 Ok(())
1458 }
1459
1460 pub fn join2(&mut self, yes: Self, no: Self) -> Result<()> {
1474 let origin = self.stack_offset_before_top(1)?;
1475 self.stack_ids
1476 .last()
1477 .unwrap()
1478 .value_type
1479 .validate_opaque_leaf(TypeId::of::<bool>())?;
1480 ensure!(
1481 yes.base_stack_index == origin && no.base_stack_index == origin,
1482 "fragment origins must match"
1483 );
1484 ensure!(
1485 yes.argument_ids.is_empty() && no.argument_ids.is_empty(),
1486 "fragments cannot take preloaded arguments"
1487 );
1488 let result = yes.result_type()?.clone();
1489 ensure!(
1490 result.same_shape(no.result_type()?),
1491 "fragment result types must match"
1492 );
1493 let condition = ResultPlan::new(origin, ValueType::leaf::<bool>())?;
1494 self.segment.update_base_alignment(
1495 yes.segment
1496 .base_alignment()
1497 .max(no.segment.base_alignment()),
1498 );
1499 self.argument_reads.extend(yes.argument_reads);
1500 self.argument_reads.extend(no.argument_reads);
1501 self.segment.raw0_(move |stack| {
1502 let value = unsafe { condition.take_typed::<bool>(stack) };
1505 let branch = if value { &yes.segment } else { &no.segment };
1506 unsafe { branch.call0_stack(stack) }
1507 });
1508 self.replace(1, result);
1509 Ok(())
1510 }
1511}
1512
1513#[cfg(test)]
1514mod performance_tests {
1515 use super::*;
1516 use crate::{Array, ArrayOf, Cons, IntoCStackList, Nil};
1517 use std::cell::RefCell;
1518 use std::panic::{AssertUnwindSafe, catch_unwind};
1519 use std::rc::Rc;
1520
1521 #[test]
1523 fn invocation_rejects_missing_callee_without_changing_body() {
1524 let mut body = DynSegment::new::<()>();
1525 body.just(7i32);
1526 for arity in [0, usize::MAX] {
1527 assert!(body.invoke_closure(arity).is_err());
1528 assert_eq!(body.call0::<i32>().unwrap(), 7);
1529 }
1530 }
1531
1532 #[test]
1534 fn diagnostic_names_preserve_recursive_shape() {
1535 assert_eq!(descriptor_name(&ValueType::tuple(vec![]).unwrap()), "()");
1536 assert_eq!(
1537 descriptor_name(&ValueType::leaf::<String>()),
1538 std::any::type_name::<String>()
1539 );
1540 let row = ValueType::tuple(vec![
1541 AssociatedType {
1542 offset: 0,
1543 value_type: ValueType::array(ValueType::leaf::<i32>()),
1544 },
1545 AssociatedType {
1546 offset: 0,
1547 value_type: ValueType::tuple(vec![AssociatedType {
1548 offset: 0,
1549 value_type: ValueType::leaf::<f64>(),
1550 }])
1551 .unwrap(),
1552 },
1553 ])
1554 .unwrap();
1555 assert_eq!(descriptor_name(&ValueType::array(row)), "[([i32], (f64))]");
1556 }
1557
1558 #[repr(align(128))]
1560 struct CloneDrop {
1561 name: &'static str,
1562 events: Rc<RefCell<Vec<&'static str>>>,
1563 fail: Rc<Cell<bool>>,
1564 owned: bool,
1565 }
1566
1567 impl Clone for CloneDrop {
1568 fn clone(&self) -> Self {
1570 assert!(!self.fail.get(), "deliberate clone panic");
1571 Self {
1572 name: self.name,
1573 events: self.events.clone(),
1574 fail: self.fail.clone(),
1575 owned: true,
1576 }
1577 }
1578 }
1579
1580 impl Drop for CloneDrop {
1581 fn drop(&mut self) {
1583 if self.owned {
1584 self.events.borrow_mut().push(self.name);
1585 }
1586 }
1587 }
1588
1589 #[test]
1591 fn direct_clone_panic_restores_branch_and_ambient_ownership() {
1592 type Pair = Cons<ArrayOf<Leaf<CloneDrop>>, Cons<Leaf<CloneDrop>, Nil>>;
1593 for external_constant in [false, true] {
1594 let events = Rc::new(RefCell::new(Vec::new()));
1595 let fail = Rc::new(Cell::new(true));
1596 let leaf = |name, fail: Rc<Cell<bool>>, owned| CloneDrop {
1597 name,
1598 events: events.clone(),
1599 fail,
1600 owned,
1601 };
1602 let descriptor = ValueType::tuple(vec![
1603 AssociatedType {
1604 offset: 0,
1605 value_type: ValueType::array(ValueType::cloneable_leaf::<CloneDrop>()),
1606 },
1607 AssociatedType {
1608 offset: 0,
1609 value_type: ValueType::cloneable_leaf::<CloneDrop>(),
1610 },
1611 ])
1612 .unwrap();
1613 let mut source = Some(
1614 OwnedValue::new::<Pair>(
1615 (
1616 Array::from_vec(vec![leaf("child", Rc::new(Cell::new(false)), false)]),
1617 leaf("panic", fail.clone(), false),
1618 )
1619 .into_c_stack_list(),
1620 )
1621 .with_value_type(descriptor.clone())
1622 .unwrap(),
1623 );
1624 let mut body = DynSegment::new::<()>();
1625 for name in ["outer-a", "outer-b"] {
1626 let log = events.clone();
1627 body.op0(move || CloneDrop {
1628 name,
1629 events: log.clone(),
1630 fail: Rc::new(Cell::new(false)),
1631 owned: true,
1632 });
1633 }
1634 body.just(true);
1635 let mut yes = body.new_fragment();
1636 let log = events.clone();
1637 yes.op0(move || CloneDrop {
1638 name: "branch",
1639 events: log.clone(),
1640 fail: Rc::new(Cell::new(false)),
1641 owned: true,
1642 });
1643 if external_constant {
1644 yes.just_external(descriptor, Box::new(source.take().unwrap()))
1645 .unwrap();
1646 } else {
1647 yes.push_argument(0, descriptor).unwrap();
1648 }
1649 yes.drop_value().unwrap();
1650 yes.drop_value().unwrap();
1651 yes.just(9u32);
1652 let mut no = body.new_fragment();
1653 no.just(3u32);
1654 body.join2(yes, no).unwrap();
1655 body.op3(|_: CloneDrop, _: CloneDrop, result: u32| result)
1656 .unwrap();
1657
1658 let pointers: Vec<_> = source.iter().map(OwnedValue::as_ptr).collect();
1659 for _ in 0..2 {
1660 let mut stack = RawStack::with_base_alignment(body.segment.base_alignment());
1661 let _arguments = ArgumentGuard::install(&pointers);
1662 assert!(
1664 catch_unwind(AssertUnwindSafe(|| unsafe {
1665 body.segment.call0_stack(&mut stack)
1666 }))
1667 .is_err()
1668 );
1669 assert_eq!(stack.len(), 0);
1670 assert_eq!(
1671 &*events.borrow(),
1672 &["child", "branch", "outer-b", "outer-a"]
1673 );
1674 events.borrow_mut().clear();
1675 }
1676 fail.set(false);
1677 let inputs: Vec<&dyn Any> = source.iter().map(|owner| owner as &dyn Any).collect();
1678 assert_eq!(body.call_dyn::<u32>(&inputs).unwrap(), 9);
1679 assert_eq!(
1680 events
1681 .borrow()
1682 .iter()
1683 .filter(|name| **name == "child")
1684 .count(),
1685 1
1686 );
1687 assert_eq!(
1688 events
1689 .borrow()
1690 .iter()
1691 .filter(|name| **name == "panic")
1692 .count(),
1693 1
1694 );
1695 }
1696 }
1697
1698 #[test]
1700 fn inconsistent_reads_precede_body_effects() {
1701 let effects = Rc::new(Cell::new(0));
1702 let counter = effects.clone();
1703 let mut body = DynSegment::new::<()>();
1704 body.op0(move || counter.set(counter.get() + 1));
1705 body.drop_value().unwrap();
1706 body.push_arg::<i32>(0);
1707 body.drop_value().unwrap();
1708 body.push_arg::<String>(0);
1709 body.drop_value().unwrap();
1710 body.just(7u32);
1711 for _ in 0..2 {
1712 let error = body.call_dyn::<u32>(&[&1i32]).unwrap_err();
1713 assert!(error.to_string().contains("inconsistent argument 0"));
1714 assert_eq!(effects.get(), 0);
1715 }
1716 }
1717
1718 #[test]
1720 fn captureless_operations_retain_no_instruction_state() {
1721 let mut body = DynSegment::new::<()>();
1722 body.just(1i32);
1723 let initial = body.segment.storage_size();
1724 for _ in 0..4_000 {
1725 body.op1(|value: i32| value).unwrap();
1726 }
1727 assert_eq!(body.segment.storage_size(), initial);
1728 assert_eq!(body.call0::<i32>().unwrap(), 1);
1729 }
1730
1731 #[test]
1733 fn large_literal_arrays_preserve_values() {
1734 for length in [1_000, 2_000, 4_000] {
1735 let mut body = DynSegment::new::<()>();
1736 for _ in 0..length {
1737 body.just(1i32);
1738 }
1739 body.make_array(length, 0).unwrap();
1740 let output = body.call_dyn_value(&[]).unwrap();
1741 assert_eq!(
1742 output
1743 .try_into_typed::<crate::ArrayOf<Leaf<i32>>>()
1744 .unwrap()
1745 .len(),
1746 length
1747 );
1748 }
1749 }
1750
1751 #[test]
1753 fn large_cloned_arrays_preserve_values() {
1754 for length in [1_000, 2_000, 4_000] {
1755 for external_constant in [false, true] {
1756 let mut body = DynSegment::new::<()>();
1757 for _ in 0..length {
1758 if external_constant {
1759 body.just_external(ValueType::cloneable_leaf::<i32>(), Box::new(1i32))
1760 .unwrap();
1761 } else {
1762 body.push_arg::<i32>(0);
1763 }
1764 }
1765 body.make_array(length, 0).unwrap();
1766 let result = body.call_dyn_value(&[&1i32]).unwrap();
1767 assert_eq!(
1768 result.try_into_typed::<ArrayOf<Leaf<i32>>>().unwrap().len(),
1769 length
1770 );
1771 }
1772 }
1773 }
1774
1775 #[test]
1777 fn prepared_callees_avoid_temporary_operand_allocations() {
1778 use crate::{Callable, FnOf};
1779
1780 type Args = Cons<Leaf<u64>, Nil>;
1781 type Function = FnOf<Args, Leaf<u64>>;
1782 fn increment(args: &<Args as ValueRepr>::Value) -> Result<u64> {
1784 args.1.checked_add(1).ok_or_else(|| anyhow!("overflow"))
1785 }
1786 let mut interpreted = DynSegment::new::<()>();
1787 interpreted.push_arg::<u64>(0);
1788 interpreted.just(1u64);
1789 interpreted
1790 .op2r(|a: u64, b: u64| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
1791 .unwrap();
1792 let interpreted =
1793 Callable::from_prepared(interpreted.prepare::<Args, Leaf<u64>>().unwrap());
1794 for function in [Callable::from_fn(increment), interpreted] {
1795 for calls in [1u64, 10, 100] {
1796 let mut body = DynSegment::new::<()>();
1797 body.just(17u64);
1798 for _ in 0..calls {
1799 let function = function.clone();
1800 body.op0_repr::<Function, _>(move || function.clone())
1801 .unwrap();
1802 body.push_arg::<u64>(0);
1803 body.invoke_closure(1).unwrap();
1804 body.op2r(|a: u64, b: u64| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
1805 .unwrap();
1806 }
1807 let mut prepared = body.prepare::<Args, Leaf<u64>>().unwrap();
1808 let args = (7u64,).into_c_stack_list();
1809 let expected = 17 + calls * 8;
1810 assert_eq!(prepared.call(&args).unwrap(), expected);
1811 crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
1812 for _ in 0..100 {
1813 assert_eq!(prepared.call(&args).unwrap(), expected);
1814 }
1815 let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
1816 assert_eq!(allocations, 200 * calls as usize, "{calls} calls");
1817 }
1818 }
1819 }
1820
1821 #[test]
1823 fn prepared_indices_avoid_temporary_operand_allocations() {
1824 for accesses in [1u64, 10, 100] {
1825 let mut body = DynSegment::new::<()>();
1826 body.just(17u64);
1827 for _ in 0..accesses {
1828 let array = Array::from_vec(vec![7u64]);
1829 body.op0_repr::<ArrayOf<Leaf<u64>>, _>(move || array.clone())
1830 .unwrap();
1831 body.push_arg::<i32>(0);
1832 body.array_index::<i32>().unwrap();
1833 body.op2r(|a: u64, b: u64| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
1834 .unwrap();
1835 }
1836 let mut prepared = body.prepare::<Cons<Leaf<i32>, Nil>, Leaf<u64>>().unwrap();
1837 let args = (0i32,).into_c_stack_list();
1838 let expected = 17 + accesses * 7;
1839 assert_eq!(prepared.call(&args).unwrap(), expected);
1840 crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
1841 for _ in 0..100 {
1842 assert_eq!(prepared.call(&args).unwrap(), expected);
1843 }
1844 let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
1845 assert_eq!(allocations, 200 * accesses as usize, "{accesses} accesses");
1846 }
1847 }
1848
1849 #[test]
1851 fn prepared_callee_moves_preserve_error_and_unwind_cleanup() {
1852 use crate::{Callable, FnOf};
1853
1854 type Args = Cons<Leaf<CloneDrop>, Nil>;
1855 type Function = FnOf<Args, Leaf<u64>>;
1856 let events = Rc::new(RefCell::new(Vec::new()));
1857 let mode = Rc::new(Cell::new(0u8));
1858 let leaf = |name| CloneDrop {
1859 name,
1860 events: events.clone(),
1861 fail: Rc::new(Cell::new(false)),
1862 owned: true,
1863 };
1864 let mut body = DynSegment::new::<()>();
1865 let ambient = leaf("ambient");
1866 body.op0(move || ambient.clone());
1867 body.just(9u8);
1868 let callee_events = events.clone();
1869 let callee_mode = mode.clone();
1870 body.op0_repr::<Function, _>(move || {
1871 let sentinel = CloneDrop {
1872 name: "callee",
1873 events: callee_events.clone(),
1874 fail: Rc::new(Cell::new(false)),
1875 owned: true,
1876 };
1877 let mode = callee_mode.clone();
1878 let mut inner = DynSegment::new::<()>();
1879 inner.push_arg::<CloneDrop>(0);
1880 inner
1881 .op1r(move |argument: CloneDrop| {
1882 let _sentinel = &sentinel;
1883 drop(argument);
1884 match mode.get() {
1885 0 => Ok(7u64),
1886 1 => Err(anyhow!("callee failure")),
1887 _ => panic!("callee panic"),
1888 }
1889 })
1890 .unwrap();
1891 Callable::from_prepared(inner.prepare::<Args, Leaf<u64>>().unwrap())
1892 })
1893 .unwrap();
1894 let argument = leaf("argument");
1895 body.op0(move || argument.clone());
1896 body.invoke_closure(1).unwrap();
1897 body.op3(|ambient: CloneDrop, marker: u8, value: u64| {
1898 assert_eq!(marker, 9);
1899 drop(ambient);
1900 value
1901 })
1902 .unwrap();
1903 let mut prepared = body.prepare::<Nil, Leaf<u64>>().unwrap();
1904 let args = ().into_c_stack_list();
1905 for _ in 0..2 {
1906 for next in [0, 1, 0, 2, 0] {
1907 mode.set(next);
1908 let result = catch_unwind(AssertUnwindSafe(|| prepared.call(&args)));
1909 match next {
1910 0 => assert_eq!(result.unwrap().unwrap(), 7),
1911 1 => assert_eq!(result.unwrap().unwrap_err().to_string(), "callee failure"),
1912 _ => assert!(result.is_err()),
1913 }
1914 let expected = if next == 2 {
1915 ["argument", "callee", "argument", "ambient"]
1916 } else {
1917 ["argument", "argument", "callee", "ambient"]
1918 };
1919 assert_eq!(&*events.borrow(), &expected);
1920 events.borrow_mut().clear();
1921 }
1922 }
1923 }
1924
1925 #[repr(align(128))]
1927 struct TrackedIndex {
1928 mode: u8,
1929 events: Rc<RefCell<Vec<&'static str>>>,
1930 }
1931
1932 impl TryFrom<TrackedIndex> for usize {
1933 type Error = ();
1934
1935 fn try_from(index: TrackedIndex) -> std::result::Result<Self, Self::Error> {
1937 match index.mode {
1938 0 => Ok(1),
1939 1 => Err(()),
1940 2 => panic!("index conversion panic"),
1941 _ => Ok(2),
1942 }
1943 }
1944 }
1945
1946 impl Drop for TrackedIndex {
1947 fn drop(&mut self) {
1949 self.events.borrow_mut().push("index");
1950 }
1951 }
1952
1953 #[test]
1955 fn prepared_index_moves_preserve_error_and_unwind_cleanup() {
1956 let events = Rc::new(RefCell::new(Vec::new()));
1957 let mode = Rc::new(Cell::new(0u8));
1958 let mut body = DynSegment::new::<()>();
1959 let log = events.clone();
1960 body.op0(move || CloneDrop {
1961 name: "ambient",
1962 events: log.clone(),
1963 fail: Rc::new(Cell::new(false)),
1964 owned: true,
1965 });
1966 body.just(9u8);
1967 let origin = body.current_stack_offset();
1968 for name in ["first", "last"] {
1969 let log = events.clone();
1970 body.op0(move || CloneDrop {
1971 name,
1972 events: log.clone(),
1973 fail: Rc::new(Cell::new(false)),
1974 owned: true,
1975 });
1976 }
1977 body.make_array(2, origin).unwrap();
1978 let index_events = events.clone();
1979 let index_mode = mode.clone();
1980 body.op0(move || TrackedIndex {
1981 mode: index_mode.get(),
1982 events: index_events.clone(),
1983 });
1984 body.array_index::<TrackedIndex>().unwrap();
1985 body.op3(|ambient: CloneDrop, marker: u8, value: CloneDrop| {
1986 assert_eq!(marker, 9);
1987 drop(ambient);
1988 value
1989 })
1990 .unwrap();
1991 let mut prepared = body.prepare::<Nil, Leaf<CloneDrop>>().unwrap();
1992 let args = ().into_c_stack_list();
1993 for _ in 0..2 {
1994 for next in [0, 1, 0, 2, 0, 3, 0] {
1995 mode.set(next);
1996 let result = catch_unwind(AssertUnwindSafe(|| prepared.call(&args)));
1997 match next {
1998 0 => drop(result.unwrap().unwrap()),
1999 1 => assert_eq!(
2000 result.unwrap().err().unwrap().to_string(),
2001 "array index is negative or unrepresentable"
2002 ),
2003 2 => assert!(result.is_err()),
2004 _ => assert!(
2005 result
2006 .unwrap()
2007 .err()
2008 .unwrap()
2009 .to_string()
2010 .contains("out of bounds")
2011 ),
2012 }
2013 let expected = if next == 0 {
2014 ["index", "first", "ambient", "last"]
2015 } else {
2016 ["index", "last", "first", "ambient"]
2017 };
2018 assert_eq!(&*events.borrow(), &expected);
2019 events.borrow_mut().clear();
2020 }
2021 }
2022 }
2023
2024 #[test]
2026 fn prepared_branches_avoid_temporary_allocations() {
2027 type Inputs = Cons<Leaf<bool>, Cons<Leaf<bool>, Nil>>;
2028 for kind in ["if", "&&", "||"] {
2029 for conditions in [1u64, 10, 100] {
2030 let mut body = DynSegment::new::<()>();
2031 body.just(17u64);
2032 for _ in 0..conditions {
2033 body.push_arg::<bool>(0);
2034 let mut yes = body.new_fragment();
2035 let mut no = body.new_fragment();
2036 match kind {
2037 "if" => {
2038 yes.push_arg::<bool>(1);
2039 no.push_arg::<bool>(1);
2040 no.op1(|value: bool| !value).unwrap();
2041 }
2042 "&&" => {
2043 yes.push_arg::<bool>(1);
2044 no.just(false);
2045 }
2046 "||" => {
2047 yes.just(true);
2048 no.push_arg::<bool>(1);
2049 }
2050 _ => unreachable!(),
2051 }
2052 body.join2(yes, no).unwrap();
2053 body.op2r(|total: u64, value: bool| {
2054 total
2055 .checked_add(u64::from(value))
2056 .ok_or_else(|| anyhow!("overflow"))
2057 })
2058 .unwrap();
2059 }
2060 let mut prepared = body.prepare::<Inputs, Leaf<u64>>().unwrap();
2061 for condition in [false, true] {
2062 for rhs in [false, true] {
2063 let value = match kind {
2064 "if" => {
2065 if condition {
2066 rhs
2067 } else {
2068 !rhs
2069 }
2070 }
2071 "&&" => condition && rhs,
2072 "||" => condition || rhs,
2073 _ => unreachable!(),
2074 };
2075 let expected = 17 + conditions * u64::from(value);
2076 let inputs = (condition, rhs).into_c_stack_list();
2077 assert_eq!(prepared.call(&inputs).unwrap(), expected);
2078 crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
2079 for _ in 0..100 {
2080 assert_eq!(prepared.call(&inputs).unwrap(), expected);
2081 }
2082 let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
2083 assert_eq!(allocations, 0, "{kind}, {conditions} conditions");
2084 }
2085 }
2086 }
2087 }
2088 }
2089
2090 #[test]
2092 fn scalar_cloning_avoids_temporary_allocations() {
2093 for reads in [1, 10, 100] {
2094 for external_constant in [false, true] {
2095 let mut body = DynSegment::new::<()>();
2096 for read in 0..reads {
2097 if external_constant {
2098 body.just_external(ValueType::cloneable_leaf::<i32>(), Box::new(1i32))
2099 .unwrap();
2100 } else {
2101 body.push_arg::<i32>(0);
2102 }
2103 if read != 0 {
2104 body.op2r(|a: i32, b: i32| {
2105 a.checked_add(b).ok_or_else(|| anyhow!("overflow"))
2106 })
2107 .unwrap();
2108 }
2109 }
2110 let mut prepared = body.prepare::<Cons<Leaf<i32>, Nil>, Leaf<i32>>().unwrap();
2111 let input = (1i32,).into_c_stack_list();
2112 assert_eq!(prepared.call(&input).unwrap(), reads);
2113 crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
2114 for _ in 0..100 {
2115 assert_eq!(prepared.call(&input).unwrap(), reads);
2116 }
2117 let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
2118 eprintln!(
2119 "{reads} reads, constant={external_constant}: {allocations} temporary allocations"
2120 );
2121 assert_eq!(allocations, 0);
2122 }
2123 }
2124 }
2125
2126 #[test]
2128 fn repeated_read_preflight_is_linear() {
2129 for reads in [1_000, 2_000, 4_000] {
2130 let mut body = DynSegment::new::<()>();
2131 body.push_arg::<i32>(0);
2132 for _ in 1..reads {
2133 body.push_arg::<i32>(0);
2134 body.op2r(|a: i32, b: i32| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
2135 .unwrap();
2136 }
2137 for _ in 0..2 {
2138 crate::value_type::SHAPE_COMPARISONS.with(|count| count.set(0));
2139 assert_eq!(body.call_dyn::<i32>(&[&1i32]).unwrap(), reads);
2140 let comparisons = crate::value_type::SHAPE_COMPARISONS.with(Cell::get);
2141 eprintln!("{reads} checked reads: {comparisons} descriptor comparisons");
2142 assert!(comparisons <= 4 * reads as usize + 16);
2143 assert!(body.call_dyn::<i32>(&[]).is_err());
2144 assert!(body.call_dyn::<i32>(&[&1u32]).is_err());
2145 }
2146 let mut prepared = body.prepare::<Cons<Leaf<i32>, Nil>, Leaf<i32>>().unwrap();
2147 crate::value_type::SHAPE_COMPARISONS.with(|count| count.set(0));
2148 assert_eq!(prepared.call(&(1i32,).into_c_stack_list()).unwrap(), reads);
2149 crate::value_type::SHAPE_COMPARISONS.with(|count| assert_eq!(count.get(), 0));
2150 }
2151 }
2152}