1use std::collections::HashMap;
16
17use crate::ast::SlotShape;
18use crate::ast::{PolydatNode, PortType};
19use crate::compile::closures::{
20 CompiledKernelPull, CompiledKernelPush, CompiledKernelPushPull, CompiledKernelRaw,
21};
22use crate::compile::select::{self, ProvMode};
23use crate::kernel::{PolydatKernel, PolydatProgram, WireSource};
24use crate::library::convert::{F64ToString, U64ToF64, U64ToString};
25use crate::library::json::JsonToStr;
26
27#[derive(Debug, Clone)]
30pub enum WireRef {
31 Input(String),
33 Node(String, usize),
35}
36
37impl WireRef {
38 pub fn node(name: impl Into<String>) -> Self {
40 WireRef::Node(name.into(), 0)
41 }
42
43 pub fn node_port(name: impl Into<String>, port: usize) -> Self {
45 WireRef::Node(name.into(), port)
46 }
47
48 pub fn input(name: impl Into<String>) -> Self {
50 WireRef::Input(name.into())
51 }
52}
53
54struct PendingNode {
55 name: String,
56 node: Box<dyn PolydatNode>,
57 inputs: Vec<WireRef>,
58 strict_values: Option<bool>,
64}
65
66#[derive(Debug)]
68pub enum AssemblyError {
69 UnknownWire(String),
71 TypeMismatch {
73 from_node: String,
75 from_port: usize,
77 from_type: PortType,
79 to_node: String,
81 to_port: usize,
83 to_type: PortType,
85 },
86 DuplicateNode(String),
88 CycleDetected,
90 ArityMismatch {
92 node_name: String,
94 expected: usize,
96 got: usize,
98 },
99 ConstantFold(String),
105 ConstInit {
109 name: String,
111 reason: String,
113 },
114 OpenInputs(Vec<(String, PortType)>),
118 NativeCone {
122 cone: String,
124 reason: String,
126 },
127 Other(String),
129}
130
131impl std::fmt::Display for AssemblyError {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 match self {
134 AssemblyError::UnknownWire(name) => {
135 write!(f, "unknown wire: '{name}'\n\n")?;
136 writeln!(f, " No node output or coordinate named '{name}' exists.")?;
137 write!(
138 f,
139 " Check spelling, or add a node that produces this output."
140 )
141 }
142 AssemblyError::TypeMismatch {
143 from_node,
144 from_port,
145 from_type,
146 to_node,
147 to_port,
148 to_type,
149 } => {
150 writeln!(
151 f,
152 "type mismatch: cannot connect {from_type} output to {to_type} input"
153 )?;
154 writeln!(f)?;
155 writeln!(
156 f,
157 " {from_node} [{from_port}] ──({from_type})──▶ {to_node} [{to_port}] expects {to_type}"
158 )?;
159 writeln!(f)?;
160 let suggestion = match (from_type, to_type) {
162 (PortType::U64, PortType::Str) => {
163 Some("This should auto-convert. If you see this, file a bug.")
164 }
165 (PortType::F64, PortType::Str) => {
166 Some("This should auto-convert. If you see this, file a bug.")
167 }
168 (PortType::U64, PortType::F64) => {
169 Some("This should auto-convert. If you see this, file a bug.")
170 }
171 (PortType::U64, PortType::Bytes) => {
172 Some("Add u64_to_bytes() between them to convert.")
173 }
174 (PortType::Str, PortType::Bytes) => {
175 Some("String cannot be directly used as bytes.")
176 }
177 (PortType::U64, PortType::Json) => {
178 Some("Add to_json() between them to wrap as JSON.")
179 }
180 (PortType::Str, PortType::Json) => {
181 Some("Add str_to_json() to parse the string as JSON.")
182 }
183 (PortType::Bytes, PortType::Str) => {
184 Some("Add to_hex() or to_base64() to convert bytes to string.")
185 }
186 (PortType::Bytes, PortType::U64) => {
187 Some("Bytes cannot be directly converted to u64.")
188 }
189 _ => None,
190 };
191 if let Some(hint) = suggestion {
192 write!(f, " Hint: {hint}")?;
193 }
194 Ok(())
195 }
196 AssemblyError::DuplicateNode(name) => {
197 write!(f, "duplicate node name: '{name}'\n\n")?;
198 write!(f, " Two nodes cannot share the same name.")
199 }
200 AssemblyError::CycleDetected => {
201 write!(f, "cycle detected in DAG\n\n")?;
202 writeln!(
203 f,
204 " The graph contains a loop. Polydat graphs must be acyclic"
205 )?;
206 write!(f, " (data flows in one direction only).")
207 }
208 AssemblyError::ArityMismatch {
209 node_name,
210 expected,
211 got,
212 } => {
213 write!(f, "wrong number of inputs for '{node_name}'\n\n")?;
214 writeln!(f, " Expected {expected} input(s), but got {got}.")?;
215 if *got < *expected {
216 write!(f, " Connect more wires to this node's input ports.")
217 } else {
218 write!(f, " Disconnect extra wires from this node.")
219 }
220 }
221 AssemblyError::ConstantFold(msg) => write!(
222 f,
223 "a value this program computes at build could not be computed: {msg}"
224 ),
225 AssemblyError::ConstInit { name, reason } => write!(
226 f,
227 "the const '{name}' could not be computed when the kernel was initialized: {reason}"
228 ),
229 AssemblyError::OpenInputs(inputs) => {
230 writeln!(
231 f,
232 "these inputs' types were inferred, not declared, and input variance \
233 is set to refuse them:"
234 )?;
235 for (name, ty) in inputs {
236 writeln!(f, " {name} (inferred {ty})")?;
237 }
238 write!(
239 f,
240 "Declare each one's type (`extern name: <type>`), or set \
241 `input_variance` to `Warn` or `Info` to convert what is written to them."
242 )
243 }
244 AssemblyError::NativeCone { cone, reason } => write!(
245 f,
246 "native code generation failed for cone {cone} under JitMode::Force: {reason}"
247 ),
248 AssemblyError::Other(msg) => write!(f, "{msg}"),
249 }
250 }
251}
252
253impl std::error::Error for AssemblyError {}
254
255fn dataset_sources_of_outputs(
260 resolved: &ResolvedDag,
261) -> HashMap<String, crate::kernel::DatasetSources> {
262 let carries_datasets = |typ: PortType| matches!(typ, PortType::Forms | PortType::Fragment);
263 let any = resolved.nodes.iter().any(|node| {
264 node.meta()
265 .outs
266 .iter()
267 .any(|port| carries_datasets(port.typ))
268 }) || resolved
269 .input_defs
270 .iter()
271 .any(|input| carries_datasets(input.port_type));
272 resolved
273 .output_map
274 .iter()
275 .map(|(name, (node, _))| {
276 let sources = if any {
277 crate::kernel::dataset_sources_of(
278 &resolved.nodes,
279 &resolved.wiring,
280 &resolved.input_defs,
281 *node,
282 )
283 } else {
284 Default::default()
285 };
286 (name.clone(), sources)
287 })
288 .collect()
289}
290
291pub(crate) struct ResolvedDag {
293 pub(crate) nodes: Vec<Box<dyn PolydatNode>>,
295 pub(crate) wiring: Vec<Vec<WireSource>>,
297 pub(crate) input_defs: Vec<crate::kernel::InputDef>,
299 pub(crate) coord_count: usize,
301 pub(crate) output_map: HashMap<String, (usize, usize)>,
303 pub(crate) output_order: Vec<String>,
305 pub(crate) source: String,
307 pub(crate) context: String,
309 pub(crate) output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
311 pub(crate) const_outputs: std::collections::HashSet<String>,
314 pub(crate) const_inits: Vec<crate::kernel::ConstInit>,
316 pub(crate) cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
318 pub(crate) ledger: std::sync::Arc<crate::kernel::CompileLedger>,
320 pub(crate) resources: crate::resource::ResourceScope,
323}
324
325impl ResolvedDag {
326 fn input_names(&self) -> Vec<String> {
328 self.input_defs[..self.coord_count]
329 .iter()
330 .map(|d| d.name.clone())
331 .collect()
332 }
333
334 pub(crate) fn graph_identity(&self) -> [u8; 32] {
338 crate::kernel::IdentityGraph {
339 nodes: &self.nodes,
340 wiring: &self.wiring,
341 input_defs: &self.input_defs,
342 outputs: self
343 .output_map
344 .iter()
345 .map(|(n, &(ni, pi))| (n.as_str(), ni, pi))
346 .collect(),
347 output_modifiers: &self.output_modifiers,
348 const_outputs: &self.const_outputs,
349 }
350 .digest()
351 }
352}
353
354struct SlotLayout {
359 input_starts: Vec<usize>,
361 coord_slots: usize,
363 port_offsets: Vec<Vec<usize>>,
365 total_slots: usize,
367}
368
369fn slot_layout(resolved: &ResolvedDag) -> SlotLayout {
370 let mut input_starts = Vec::with_capacity(resolved.coord_count);
371 let mut next = 0usize;
372 for d in &resolved.input_defs {
373 input_starts.push(next);
374 next += d.port_type.slot_width();
375 }
376 let coord_slots = next;
377 let mut port_offsets: Vec<Vec<usize>> = Vec::with_capacity(resolved.nodes.len());
378 for node in &resolved.nodes {
379 let mut po = Vec::with_capacity(node.meta().outs.len());
380 for out in &node.meta().outs {
381 po.push(next);
382 next += out.typ.slot_width();
383 }
384 port_offsets.push(po);
385 }
386 SlotLayout {
387 input_starts,
388 coord_slots,
389 port_offsets,
390 total_slots: next,
391 }
392}
393
394fn node_step_op(
400 node: &dyn crate::ast::PolydatNode,
401 wire_types: &[PortType],
402) -> Option<(
403 crate::compile::closures::StepOp,
404 Vec<crate::ast::ScratchElem>,
405)> {
406 let meta = node.meta();
410 if (meta.name == "identity" || meta.name.starts_with("__port_")) && meta.outs.len() == 1 {
411 return Some(match meta.outs[0].typ.slot_color() {
412 crate::ast::SlotColor::Ref2 => {
413 let kit = ref_copy_kit(meta.outs[0].typ)?;
414 (crate::compile::closures::StepOp::Slot(kit.op), kit.scratch)
415 }
416 _ => (crate::compile::closures::StepOp::Copy, Vec::new()),
417 });
418 }
419 if let Some(op) = node.compiled_u64() {
420 return Some((crate::compile::closures::StepOp::U64(op), Vec::new()));
421 }
422 node.compiled_slot(
423 wire_types,
424 crate::compile::select::Engine::Closures(crate::compile::select::Provenance::Auto),
425 )
426 .map(|kit| (crate::compile::closures::StepOp::Slot(kit.op), kit.scratch))
427}
428
429pub(crate) fn scratch_pairs(
440 name: &str,
441 ref_starts: &[usize],
442 scratch: &[crate::ast::ScratchElem],
443 base: usize,
444) -> Vec<(usize, usize)> {
445 use crate::ast::ScratchElem;
446 let publishing: Vec<usize> = scratch
447 .iter()
448 .enumerate()
449 .filter(|(_, e)| {
450 !matches!(
451 e,
452 ScratchElem::Slots | ScratchElem::Kernels | ScratchElem::State
453 )
454 })
455 .map(|(k, _)| base + k)
456 .collect();
457 assert!(
458 publishing.len() <= ref_starts.len(),
459 "slot-op step '{name}' declares {} publishing scratch entries for {} Ref output ports",
460 publishing.len(),
461 ref_starts.len()
462 );
463 ref_starts.iter().copied().zip(publishing).collect()
464}
465
466pub(crate) fn ref_copy_kit(ty: PortType) -> Option<crate::ast::CompiledSlotKit> {
472 use crate::ast::ScratchBuf;
473 let elem = ty.scratch_elem()?;
474 Some(crate::ast::CompiledSlotKit {
475 scratch: vec![elem],
476 op: Box::new(
477 move |inputs: &[u64], outputs: &mut [u64], scratch: &mut [ScratchBuf]| {
478 let (p, n) = (inputs[0] as usize, inputs[1] as usize);
479 macro_rules! copy_into {
480 ($v:expr, $t:ty) => {{
481 $v.clear();
482 $v.extend_from_slice(unsafe {
486 std::slice::from_raw_parts(p as *const $t, n)
487 });
488 }};
489 }
490 match &mut scratch[0] {
491 ScratchBuf::Str(v) | ScratchBuf::Bytes(v) => copy_into!(v, u8),
492 ScratchBuf::F32(v) => copy_into!(v, f32),
493 ScratchBuf::F64(v) => copy_into!(v, f64),
494 ScratchBuf::F16(v) => copy_into!(v, half::f16),
495 ScratchBuf::I8(v) => copy_into!(v, i8),
496 ScratchBuf::I16(v) => copy_into!(v, i16),
497 ScratchBuf::I32(v) => copy_into!(v, i32),
498 ScratchBuf::I64(v) => copy_into!(v, i64),
499 ScratchBuf::Value(v) => {
500 v.clear();
501 if n > 0 {
502 v.push(unsafe { (*(p as *const crate::ast::Value)).clone() });
504 }
505 }
506 ScratchBuf::Slots(_) | ScratchBuf::Kernels(_) | ScratchBuf::State(_) => {
507 unreachable!("a copy owns only a value entry")
508 }
509 }
510 let (ptr, len) = scratch[0].ptr_len();
511 outputs[0] = ptr;
512 outputs[1] = len;
513 },
514 ),
515 })
516}
517
518pub(crate) fn identity_op(node: &dyn crate::ast::PolydatNode) -> Option<crate::ast::CompiledU64Op> {
524 let meta = node.meta();
525 if meta.name != "identity" || meta.outs.len() != 1 {
526 return None;
527 }
528 if meta.outs[0].typ.slot_color() == crate::ast::SlotColor::Ref2 {
529 return None;
530 }
531 Some(Box::new(|inputs: &[u64], outputs: &mut [u64]| {
532 outputs.copy_from_slice(inputs)
533 }))
534}
535
536impl SlotLayout {
537 fn input_slots(&self, resolved: &ResolvedDag, node_idx: usize) -> Vec<usize> {
540 let mut slots = Vec::new();
541 for source in &resolved.wiring[node_idx] {
542 let (start, w) = match source {
543 WireSource::Input(c) => (
544 self.input_starts.get(*c).copied().unwrap_or(*c),
545 resolved
546 .input_defs
547 .get(*c)
548 .map(|d| d.port_type.slot_width())
549 .unwrap_or(1),
550 ),
551 WireSource::NodeOutput(u, p) => (
552 self.port_offsets[*u][*p],
553 resolved.nodes[*u].meta().outs[*p].typ.slot_width(),
554 ),
555 };
556 slots.extend(start..start + w);
557 }
558 slots
559 }
560
561 fn output_slots(&self, resolved: &ResolvedDag, node_idx: usize) -> Vec<usize> {
563 let mut slots = Vec::new();
564 for (p, out) in resolved.nodes[node_idx].meta().outs.iter().enumerate() {
565 let start = self.port_offsets[node_idx][p];
566 slots.extend(start..start + out.typ.slot_width());
567 }
568 slots
569 }
570
571 fn named_outputs(&self, resolved: &ResolvedDag) -> HashMap<String, usize> {
573 resolved
574 .output_map
575 .iter()
576 .map(|(name, (n, p))| (name.clone(), self.port_offsets[*n][*p]))
577 .collect()
578 }
579
580 fn ref_slot_mask(&self, resolved: &ResolvedDag) -> Vec<bool> {
586 use crate::ast::SlotColor;
587 let mut mask = vec![false; self.total_slots];
588 let mut mark = |start: usize, color: SlotColor| match color {
589 SlotColor::Ref2 => {
590 mask[start] = true;
591 mask[start + 1] = true;
592 }
593 SlotColor::Imm1 | SlotColor::Imm2 => {}
594 };
595 for (i, d) in resolved.input_defs.iter().enumerate() {
596 mark(self.input_starts[i], d.port_type.slot_color());
597 }
598 for (n, node) in resolved.nodes.iter().enumerate() {
599 for (p, out) in node.meta().outs.iter().enumerate() {
600 mark(self.port_offsets[n][p], out.typ.slot_color());
601 }
602 }
603 mask
604 }
605
606 fn ref_output_starts(&self, resolved: &ResolvedDag, node_idx: usize) -> Vec<usize> {
610 resolved.nodes[node_idx]
611 .meta()
612 .outs
613 .iter()
614 .enumerate()
615 .filter(|(_, out)| out.typ.slot_color() == crate::ast::SlotColor::Ref2)
616 .map(|(p, _)| self.port_offsets[node_idx][p])
617 .collect()
618 }
619
620 fn expand_dependents(&self, resolved: &ResolvedDag, deps: &[Vec<usize>]) -> Vec<Vec<usize>> {
626 let mut out = Vec::with_capacity(self.coord_slots);
627 for (i, d) in resolved.input_defs.iter().enumerate() {
628 for _ in 0..d.port_type.slot_width() {
629 out.push(deps.get(i).cloned().unwrap_or_default());
630 }
631 }
632 out
633 }
634}
635
636pub struct PolydatAssembler {
638 input_defs: Vec<crate::kernel::InputDef>,
640 coord_count: usize,
642 nodes: Vec<PendingNode>,
643 output_order: Vec<String>,
645 outputs: HashMap<String, WireRef>,
646 source: String,
648 context: String,
650 output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
652 const_inits: Vec<crate::kernel::ConstInit>,
654 shared_starts: Vec<(String, String)>,
657 pub(crate) template: bool,
660 const_outputs: std::collections::HashSet<String>,
664 pub(crate) strict_values: bool,
670 scope_strict_values: Option<bool>,
673 pub(crate) strict: bool,
678 input_variance: crate::dsl::compile::InputVariance,
681 pub(crate) jit_mode: Option<crate::compile::cone::JitMode>,
686 pub(crate) ledger: std::sync::Arc<crate::kernel::CompileLedger>,
690 pub(crate) resources: crate::resource::ResourceScope,
694 cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
698}
699
700type P2Layout = (
704 usize,
705 usize,
706 Vec<crate::compile::closures::P2Step>,
707 HashMap<String, usize>,
708 Vec<bool>,
709 crate::compile::closures::P2Extras,
710);
711
712#[cfg(feature = "jit")]
718type JitLayout = (
719 usize,
720 usize,
721 Vec<(crate::compile::jit::JitOp, Vec<usize>, Vec<usize>)>,
722 HashMap<String, usize>,
723 crate::compile::jit::ScratchPlan,
724 Vec<usize>,
725);
726
727impl PolydatAssembler {
728 pub fn new(input_names: Vec<String>) -> Self {
730 let coord_count = input_names.len();
731 let input_defs: Vec<crate::kernel::InputDef> = input_names
732 .into_iter()
733 .map(|name| crate::kernel::InputDef {
734 name,
735 default: crate::ast::Value::U64(0),
736 port_type: crate::ast::PortType::U64,
737 kind: crate::kernel::InputKind::Coordinate,
738 type_origin: crate::kernel::TypeOrigin::Inferred,
740 converts_to: None,
741 })
742 .collect();
743 Self {
744 input_defs,
745 coord_count,
746 nodes: Vec::new(),
747 output_order: Vec::new(),
748 outputs: HashMap::new(),
749 source: String::new(),
750 context: "(assembler)".into(),
751 output_modifiers: HashMap::new(),
752 const_inits: Vec::new(),
753 shared_starts: Vec::new(),
754 template: false,
755 const_outputs: std::collections::HashSet::new(),
756 strict_values: false,
757 scope_strict_values: None,
758 strict: false,
759 input_variance: crate::dsl::compile::InputVariance::Fixed,
760 jit_mode: None,
761 cursor_schemas: Vec::new(),
762 ledger: crate::kernel::CompileLedger::new(),
763 resources: crate::resource::ResourceScope::new(),
764 }
765 }
766
767 pub fn set_resources(&mut self, resources: crate::resource::ResourceScope) {
773 self.resources = resources;
774 }
775
776 pub fn set_cursor_schemas(&mut self, schemas: Vec<crate::iteration::source::SourceSchema>) {
781 self.cursor_schemas = schemas;
782 }
783
784 pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
786 &self.cursor_schemas
787 }
788
789 pub fn set_strict_wires(&mut self, _strict_types: bool, strict_values: bool) {
796 self.strict_values = strict_values;
797 }
798
799 pub fn set_strict(&mut self, strict: bool) {
805 self.strict = strict;
806 }
807
808 pub fn set_jit_mode(&mut self, mode: crate::compile::cone::JitMode) {
812 self.jit_mode = Some(mode);
813 }
814
815 pub fn set_context(&mut self, source: &str, context: &str) {
818 self.source = source.to_string();
819 self.context = context.to_string();
820 }
821
822 pub fn add_node(
824 &mut self,
825 name: impl Into<String>,
826 node: Box<dyn PolydatNode>,
827 inputs: Vec<WireRef>,
828 ) -> &mut Self {
829 self.nodes.push(PendingNode {
830 name: name.into(),
831 node,
832 inputs,
833 strict_values: self.scope_strict_values,
834 });
835 self
836 }
837
838 pub(crate) fn set_scope_strict_values(&mut self, mark: Option<bool>) -> Option<bool> {
846 std::mem::replace(&mut self.scope_strict_values, mark)
847 }
848
849 pub fn set_output_modifier(&mut self, name: &str, modifier: crate::dsl::ast::BindingModifier) {
851 if modifier != crate::dsl::ast::BindingModifier::NONE {
852 self.output_modifiers.insert(name.to_string(), modifier);
853 }
854 }
855
856 pub fn mark_const_output(&mut self, name: &str) {
867 self.const_outputs.insert(name.to_string());
868 }
869
870 pub(crate) fn mark_shared_start(&mut self, name: &str, source: &str) {
876 self.shared_starts
877 .push((name.to_string(), source.to_string()));
878 }
879
880 fn capture_consts(&mut self) -> Result<(), AssemblyError> {
898 use crate::dsl::ast::BindingModifier;
899 use crate::kernel::{InputKind, TypeOrigin};
900
901 let node_of = |nodes: &[PendingNode], name: &str| nodes.iter().position(|n| n.name == name);
902 let cone = |nodes: &[PendingNode], start: &str| -> (Vec<String>, bool) {
906 let by_name: HashMap<&str, usize> = nodes
907 .iter()
908 .enumerate()
909 .rev()
910 .map(|(i, n)| (n.name.as_str(), i))
911 .collect();
912 let mut inputs: Vec<String> = Vec::new();
913 let mut runtime = false;
914 let mut seen = vec![false; nodes.len()];
915 let first = by_name.get(start).copied();
916 let mut stack: Vec<usize> = first.into_iter().collect();
917 while let Some(i) = stack.pop() {
918 if std::mem::replace(&mut seen[i], true) {
919 if Some(i) == first {
922 runtime = true;
923 }
924 continue;
925 }
926 if matches!(
927 nodes[i].node.purity(),
928 crate::ast::Purity::Nondeterministic { .. }
929 ) {
930 runtime = true;
931 }
932 for wire in &nodes[i].inputs {
933 match wire {
934 WireRef::Input(name) => {
935 if !inputs.contains(name) {
936 inputs.push(name.clone());
937 }
938 }
939 WireRef::Node(name, _) => stack.extend(by_name.get(name.as_str())),
940 }
941 }
942 }
943 (inputs, runtime)
944 };
945
946 let mut captured: Vec<(usize, String, String, usize)> = Vec::new();
949 for name in &self.const_outputs {
950 let (node, port) = match self.outputs.get(name) {
951 Some(WireRef::Node(node, port)) => (node.clone(), *port),
952 Some(WireRef::Input(_)) => continue,
953 None if node_of(&self.nodes, name).is_some() => (name.clone(), 0),
954 None => continue,
955 };
956 let Some(order) = node_of(&self.nodes, &node) else {
957 continue;
958 };
959 let (inputs, runtime) = cone(&self.nodes, &node);
960 if inputs.is_empty() && !runtime {
961 continue;
962 }
963 captured.push((order, name.clone(), node, port));
964 }
965 captured.sort();
966
967 let mut records: Vec<(String, String, String, PortType, bool)> = Vec::new();
970 for (_, name, node, port) in captured {
971 let Some(index) = node_of(&self.nodes, &node) else {
972 continue;
973 };
974 let Some(ty) = self.nodes[index].node.meta().outs.get(port).map(|p| p.typ) else {
975 return Err(AssemblyError::UnknownWire(format!("{node}[{port}]")));
976 };
977 let source = format!("__init_{name}");
978 let slot = format!("__const_{name}");
979 let renamed = node == name;
982 let root = if renamed {
983 source.clone()
984 } else {
985 node.clone()
986 };
987 let passthrough = if renamed || node_of(&self.nodes, &name).is_none() {
988 name.clone()
989 } else {
990 slot.clone()
991 };
992 if renamed {
993 self.nodes[index].name = source.clone();
994 }
995 let redirect = |wire: &mut WireRef| {
996 if let WireRef::Node(n, p) = wire
997 && *n == node
998 {
999 if *p == port {
1000 *wire = WireRef::node(passthrough.clone());
1001 } else {
1002 *n = root.clone();
1003 }
1004 }
1005 };
1006 for pending in &mut self.nodes {
1007 pending.inputs.iter_mut().for_each(redirect);
1008 }
1009 self.outputs.values_mut().for_each(redirect);
1010 self.add_input(&slot, crate::ast::Value::None, ty, InputKind::Const);
1011 self.add_node(
1012 &passthrough,
1013 Box::new(crate::library::identity::PortPassthrough::new(&slot, ty)),
1014 vec![WireRef::input(&slot)],
1015 );
1016 self.add_output(&source, WireRef::node_port(&root, port));
1017 let modifier = *self
1021 .output_modifiers
1022 .entry(name.clone())
1023 .or_insert(BindingModifier::CONST);
1024 self.set_output_modifier(&source, modifier);
1025 records.push((name, slot, source, ty, false));
1026 }
1027 for (name, source) in std::mem::take(&mut self.shared_starts) {
1031 let Some(ty) = self.input_type(&name) else {
1032 return Err(AssemblyError::UnknownWire(name));
1033 };
1034 records.push((name.clone(), name, source, ty, true));
1035 }
1036
1037 let slot_owner: HashMap<String, String> = records
1040 .iter()
1041 .map(|(name, slot, _, _, _)| (slot.clone(), name.clone()))
1042 .collect();
1043 let mut pending: Vec<(crate::kernel::ConstInit, Vec<String>)> = Vec::new();
1044 for (name, slot, source, ty, register) in records {
1045 let root = match self.outputs.get(&source) {
1046 Some(WireRef::Node(n, _)) => n.clone(),
1047 _ => return Err(AssemblyError::UnknownWire(source)),
1048 };
1049 let (inputs, _) = cone(&self.nodes, &root);
1050 if let Some(coord) = inputs.iter().find(|i| {
1051 self.input_defs
1052 .iter()
1053 .any(|d| &d.name == *i && d.kind == InputKind::Coordinate)
1054 }) {
1055 let what = if register {
1056 format!("the starting value of shared '{name}'")
1057 } else {
1058 format!("const '{name}'")
1059 };
1060 return Err(AssemblyError::Other(format!(
1061 "{what} reads the coordinate '{coord}': it is evaluated once when the \
1062 kernel is initialized, and a coordinate advances every cycle. Read an \
1063 extern or a const instead."
1064 )));
1065 }
1066 let deps: Vec<String> = inputs
1067 .iter()
1068 .filter_map(|i| slot_owner.get(i))
1069 .filter(|owner| **owner != name)
1070 .cloned()
1071 .collect();
1072 if !register && !inputs.is_empty() && self.input_type(&name).is_none() {
1073 self.add_input(
1074 &name,
1075 crate::ast::Value::None,
1076 ty,
1077 InputKind::IterationExtern,
1078 );
1079 self.set_input_origin(&name, TypeOrigin::Inferred);
1080 }
1081 let fallback = (!register && self.input_type(&name).is_some()).then(|| name.clone());
1082 pending.push((
1083 crate::kernel::ConstInit {
1084 name,
1085 slot,
1086 source,
1087 fallback,
1088 register,
1089 slot_index: 0,
1090 source_index: 0,
1091 fallback_index: None,
1092 },
1093 deps,
1094 ));
1095 }
1096
1097 let mut ordered: Vec<crate::kernel::ConstInit> = Vec::with_capacity(pending.len());
1099 while !pending.is_empty() {
1100 let (ready, rest): (Vec<_>, Vec<_>) = pending.into_iter().partition(|(_, deps)| {
1101 deps.iter().all(|d| {
1102 ordered
1103 .iter()
1104 .any(|c: &crate::kernel::ConstInit| &c.name == d)
1105 })
1106 });
1107 if ready.is_empty() {
1108 let names: Vec<&str> = rest.iter().map(|(c, _)| c.name.as_str()).collect();
1109 return Err(AssemblyError::Other(format!(
1110 "the consts {names:?} read each other in a cycle, so none can be evaluated \
1111 first"
1112 )));
1113 }
1114 ordered.extend(ready.into_iter().map(|(c, _)| c));
1115 pending = rest;
1116 }
1117 let input_index = |name: &str| self.input_defs.iter().position(|d| d.name == name);
1118 for c in &mut ordered {
1119 c.slot_index = input_index(&c.slot).expect("the const's slot was just added");
1120 c.source_index = self
1121 .output_order
1122 .iter()
1123 .position(|n| n == &c.source)
1124 .expect("the const's source output was just added");
1125 c.fallback_index = c.fallback.as_deref().and_then(input_index);
1126 }
1127 self.const_inits = ordered;
1128 Ok(())
1129 }
1130
1131 pub fn node_count(&self) -> usize {
1133 self.nodes.len()
1134 }
1135
1136 pub fn add_output(&mut self, name: impl Into<String>, wire: WireRef) -> &mut Self {
1138 let name = name.into();
1139 if !self.outputs.contains_key(&name) {
1140 self.output_order.push(name.clone());
1141 }
1142 self.outputs.insert(name, wire);
1143 self
1144 }
1145
1146 pub fn add_input(
1157 &mut self,
1158 name: impl Into<String>,
1159 default: crate::ast::Value,
1160 port_type: crate::ast::PortType,
1161 kind: crate::kernel::InputKind,
1162 ) -> &mut Self {
1163 self.input_defs.push(crate::kernel::InputDef {
1164 name: name.into(),
1165 default,
1166 port_type,
1167 kind,
1168 type_origin: crate::kernel::TypeOrigin::Declared,
1169 converts_to: None,
1170 });
1171 self
1172 }
1173
1174 pub fn set_input_type(&mut self, name: &str, port_type: crate::ast::PortType) {
1179 if let Some(d) = self.input_defs.iter_mut().find(|d| d.name == name) {
1180 d.port_type = port_type;
1181 d.type_origin = crate::kernel::TypeOrigin::Declared;
1182 }
1183 }
1184
1185 pub fn set_input_origin(&mut self, name: &str, origin: crate::kernel::TypeOrigin) {
1189 if let Some(d) = self.input_defs.iter_mut().find(|d| d.name == name) {
1190 d.type_origin = origin;
1191 }
1192 }
1193
1194 pub fn set_input_variance(&mut self, variance: crate::dsl::compile::InputVariance) {
1196 self.input_variance = variance;
1197 }
1198
1199 pub fn input_names(&self) -> Vec<&str> {
1201 self.input_defs.iter().map(|d| d.name.as_str()).collect()
1202 }
1203
1204 pub fn node_output_type(&self, name: &str) -> Option<crate::ast::PortType> {
1209 self.nodes
1210 .iter()
1211 .find(|n| n.name == name)
1212 .and_then(|n| n.node.meta().outs.first())
1213 .map(|p| p.typ)
1214 }
1215
1216 pub fn output_names(&self) -> Vec<&str> {
1218 self.outputs.keys().map(|s| s.as_str()).collect()
1219 }
1220
1221 pub fn node_type_of(&self, name: &str) -> Option<String> {
1223 self.nodes
1224 .iter()
1225 .find(|pn| pn.name == name)
1226 .map(|pn| pn.node.meta().name.clone())
1227 }
1228
1229 pub fn output_type(&self, name: &str) -> Option<PortType> {
1233 self.nodes
1234 .iter()
1235 .find(|pn| pn.name == name)
1236 .and_then(|pn| pn.node.meta().outs.first())
1237 .map(|port| port.typ)
1238 }
1239
1240 pub fn input_type(&self, name: &str) -> Option<PortType> {
1242 self.input_defs
1243 .iter()
1244 .find(|d| d.name == name)
1245 .map(|d| d.port_type)
1246 }
1247
1248 pub fn wire_type(&self, wire: &WireRef) -> Option<PortType> {
1253 match wire {
1254 WireRef::Input(name) => self.input_type(name),
1255 WireRef::Node(name, port_idx) => self
1256 .nodes
1257 .iter()
1258 .find(|pn| &pn.name == name)
1259 .and_then(|pn| pn.node.meta().outs.get(*port_idx))
1260 .map(|p| p.typ),
1261 }
1262 }
1263
1264 pub fn compile(self) -> Result<PolydatKernel, AssemblyError> {
1266 self.compile_with_log(None)
1267 }
1268
1269 pub fn compile_with_log(
1271 self,
1272 mut log: Option<&mut crate::dsl::events::CompileEventLog>,
1273 ) -> Result<PolydatKernel, AssemblyError> {
1274 let jit_mode = self.jit_mode.unwrap_or_default();
1275 let strict = self.strict;
1276 let template = self.template;
1277 let mut resolved = self.resolve_with_log(log.as_deref_mut())?;
1278 let (node_total, output_total) = (resolved.nodes.len(), resolved.output_order.len());
1279 let identity = resolved.graph_identity();
1280 crate::compile::cone::extract_jit_cones(&mut resolved, jit_mode)?;
1281 let _coord_names = resolved.input_names();
1282 let modifiers = resolved.output_modifiers.clone();
1283 let cursors = std::mem::take(&mut resolved.cursor_schemas);
1284 let mut kernel = PolydatKernel::new_with_inputs(
1285 resolved.nodes,
1286 resolved.wiring,
1287 resolved.input_defs,
1288 resolved.coord_count,
1289 resolved.output_map,
1290 resolved.output_order,
1291 resolved.const_outputs,
1292 modifiers,
1293 &resolved.source,
1294 &resolved.context,
1295 log.as_deref_mut(),
1296 strict,
1297 resolved.ledger.clone(),
1298 )?;
1299 kernel.set_resources(resolved.resources.clone());
1300 kernel.set_graph_identity(identity);
1301 if !cursors.is_empty() {
1302 kernel.set_cursor_schemas(cursors);
1303 }
1304 kernel.set_cone_mode(jit_mode);
1305 kernel.set_const_inits(resolved.const_inits);
1306 Self::log_summary(log, node_total, output_total);
1307 if template {
1308 return Ok(kernel);
1309 }
1310 crate::kernel::Kernel::init(&mut kernel).map_err(|e| match e {
1311 KernelError::ConstInit { name, reason } => AssemblyError::ConstInit { name, reason },
1312 other => AssemblyError::ConstInit {
1313 name: String::new(),
1314 reason: other.to_string(),
1315 },
1316 })?;
1317 Ok(kernel)
1318 }
1319
1320 fn refuse_strict(resolved: &ResolvedDag) -> Result<(), AssemblyError> {
1324 let classes = PolydatProgram::classify_lifecycle(
1325 &resolved.nodes,
1326 &resolved.wiring,
1327 &resolved.input_defs,
1328 &resolved.output_map,
1329 &resolved.output_modifiers,
1330 );
1331 let is_init: Vec<bool> = classes
1332 .lifecycle
1333 .iter()
1334 .map(|lc| *lc == crate::kernel::EvalLifecycle::CompileConst)
1335 .collect();
1336 match PolydatProgram::strict_violation(
1337 &resolved.nodes,
1338 &resolved.wiring,
1339 &is_init,
1340 &resolved.output_map,
1341 &resolved.output_modifiers,
1342 ) {
1343 Some(violation) => Err(AssemblyError::Other(violation)),
1344 None => Ok(()),
1345 }
1346 }
1347
1348 fn refused_by_closures(reason: String) -> KernelError {
1351 KernelError::Refused {
1352 engine: Engine::Closures(Provenance::Auto),
1353 reason,
1354 }
1355 }
1356
1357 fn refused_by_native(reason: String) -> KernelError {
1360 KernelError::Refused {
1361 engine: Engine::Native(Provenance::Auto),
1362 reason,
1363 }
1364 }
1365
1366 #[cfg_attr(not(feature = "jit"), allow(dead_code))]
1371 fn refused_by_pure_native(reason: String) -> KernelError {
1372 KernelError::Refused {
1373 engine: Engine::PureNative(Provenance::Auto),
1374 reason,
1375 }
1376 }
1377
1378 fn build_p2_layout(resolved: &ResolvedDag) -> Result<P2Layout, String> {
1381 let layout = slot_layout(resolved);
1382
1383 let mut compiled_ops = Vec::with_capacity(resolved.nodes.len());
1384 let mut extras = crate::compile::closures::P2Extras::default();
1385 for (node_idx, node) in resolved.nodes.iter().enumerate() {
1386 compiled_ops.push(
1387 node_step_op(node.as_ref(), &wire_types_of(resolved, node_idx)).ok_or_else(
1388 || {
1389 format!(
1390 "node '{}' has no compiled form (docs/design/engines.md §8)",
1391 node.meta().name
1392 )
1393 },
1394 )?,
1395 );
1396 }
1397 extras.externs = crate::compile::externs::Externs::new(
1398 &resolved.input_defs,
1399 resolved.coord_count,
1400 &layout.input_starts,
1401 &resolved.cursor_schemas,
1402 &shared_outputs_of(resolved),
1403 resolved.ledger.clone(),
1404 )?;
1405 extras.externs.set_resources(resolved.resources.clone());
1406 extras.externs.set_graph_identity(resolved.graph_identity());
1407 extras.externs.set_output_names(&resolved.output_order);
1408 extras
1409 .externs
1410 .set_dataset_sources(dataset_sources_of_outputs(resolved));
1411 extras
1412 .externs
1413 .set_output_modifiers(&resolved.output_modifiers);
1414 extras.externs.set_const_inits(&resolved.const_inits);
1415 extras.externs.set_fixed_outputs(fixed_outputs(resolved));
1416 extras.output_types = resolved
1417 .output_map
1418 .iter()
1419 .map(|(name, (n, p))| (name.clone(), resolved.nodes[*n].meta().outs[*p].typ))
1420 .collect();
1421
1422 let classes = PolydatProgram::classify_lifecycle(
1426 &resolved.nodes,
1427 &resolved.wiring,
1428 &resolved.input_defs,
1429 &resolved.output_map,
1430 &resolved.output_modifiers,
1431 );
1432 let inventory = PolydatProgram::compute_node_inventory(&resolved.nodes, &resolved.wiring);
1433 let per_input = PolydatProgram::compute_dependents(
1434 &inventory.input_provenance,
1435 resolved.input_defs.len(),
1436 );
1437 extras.input_dependents = layout.expand_dependents(resolved, &per_input);
1438 extras.attribution = std::sync::Arc::new(Self::attribution_of(resolved));
1439
1440 let mut steps = Vec::with_capacity(resolved.nodes.len());
1441 for (node_idx, (op, scratch)) in compiled_ops.into_iter().enumerate() {
1442 steps.push(crate::compile::closures::P2Step {
1443 name: resolved.nodes[node_idx].meta().name.clone(),
1444 op,
1445 input_slots: layout.input_slots(resolved, node_idx),
1446 output_slots: layout.output_slots(resolved, node_idx),
1447 ref_output_starts: layout.ref_output_starts(resolved, node_idx),
1448 scratch,
1449 accepts_none: resolved.nodes[node_idx].accepts_none_inputs(),
1450 volatile: classes.nondeterministic[node_idx],
1451 constant: classes.lifecycle[node_idx] == crate::kernel::EvalLifecycle::CompileConst,
1452 side: matches!(
1453 resolved.nodes[node_idx].purity(),
1454 crate::ast::Purity::SideChannel { .. }
1455 ),
1456 });
1457 }
1458 let output_map = layout.named_outputs(resolved);
1459 let ref_slots = layout.ref_slot_mask(resolved);
1460
1461 Ok((
1462 layout.coord_slots,
1463 layout.total_slots,
1464 steps,
1465 output_map,
1466 ref_slots,
1467 extras,
1468 ))
1469 }
1470
1471 #[cfg(feature = "jit")]
1473 pub(crate) fn build_jit_layout(resolved: &ResolvedDag) -> Result<JitLayout, String> {
1474 let layout = slot_layout(resolved);
1475
1476 let mut scratch = crate::compile::jit::ScratchPlan::default();
1480 let mut jit_steps = Vec::new();
1481 for (node_idx, node) in resolved.nodes.iter().enumerate() {
1482 let mut jit_op = crate::compile::jit::classify_node_typed(
1483 node.as_ref(),
1484 &wire_types_of(resolved, node_idx),
1485 );
1486 if matches!(jit_op, crate::compile::jit::JitOp::Fallback) {
1487 return Err(format!(
1488 "node '{}' has no native form and no kit; pure native code cannot run it",
1489 node.meta().name
1490 ));
1491 }
1492 let base = scratch.elems.len();
1493 jit_op.place_scratch(base);
1494 let elems = jit_op.scratch_elems().to_vec();
1495 scratch.refs.extend(scratch_pairs(
1496 &node.meta().name,
1497 &layout.ref_output_starts(resolved, node_idx),
1498 &elems,
1499 base,
1500 ));
1501 scratch.elems.extend(elems);
1502 jit_steps.push((
1503 jit_op,
1504 layout.input_slots(resolved, node_idx),
1505 layout.output_slots(resolved, node_idx),
1506 ));
1507 }
1508
1509 let output_map = layout.named_outputs(resolved);
1510 let classes = PolydatProgram::classify_lifecycle(
1514 &resolved.nodes,
1515 &resolved.wiring,
1516 &resolved.input_defs,
1517 &resolved.output_map,
1518 &resolved.output_modifiers,
1519 );
1520 let volatile: Vec<usize> = (0..resolved.nodes.len())
1521 .filter(|&i| classes.nondeterministic[i])
1522 .collect();
1523 Ok((
1524 layout.coord_slots,
1525 layout.total_slots,
1526 jit_steps,
1527 output_map,
1528 scratch,
1529 volatile,
1530 ))
1531 }
1532
1533 #[cfg(feature = "jit")]
1537 fn jit_slot_info(resolved: &ResolvedDag) -> (Vec<bool>, HashMap<String, PortType>) {
1538 let layout = slot_layout(resolved);
1539 let guard = layout.ref_slot_mask(resolved);
1540 let types = resolved
1541 .output_map
1542 .iter()
1543 .map(|(name, (n, p))| (name.clone(), resolved.nodes[*n].meta().outs[*p].typ))
1544 .collect();
1545 (guard, types)
1546 }
1547
1548 #[cfg(feature = "jit")]
1549 fn jit_push_pull_from(
1550 resolved: ResolvedDag,
1551 ) -> Result<crate::compile::jit::JitKernelPushPull, KernelError> {
1552 let _coord_names = resolved.input_names();
1553 let (coord_count, total_slots, jit_steps, output_map, scratch, volatile) =
1554 Self::build_jit_layout(&resolved).map_err(Self::refused_by_pure_native)?;
1555 let (guard, types) = Self::jit_slot_info(&resolved);
1556 let deps = slot_layout(&resolved).expand_dependents(
1557 &resolved,
1558 &PolydatProgram::compute_dependents(
1559 &PolydatProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
1560 resolved.input_defs.len(),
1561 ),
1562 );
1563 let externs = Self::externs_of(&resolved).map_err(Self::refused_by_pure_native)?;
1564 let attribution = std::sync::Arc::new(Self::attribution_of(&resolved));
1565 let (folded, origin) = Self::constant_steps(&resolved, &jit_steps);
1566 let alone = Self::side_channels(&resolved);
1567 let mut k = crate::compile::jit::compile_jit_push_pull(
1568 coord_count,
1569 total_slots,
1570 jit_steps,
1571 output_map,
1572 resolved.nodes,
1573 deps,
1574 externs,
1575 scratch,
1576 volatile,
1577 alone,
1578 )
1579 .map_err(Self::refused_by_pure_native)?;
1580 k.set_slot_info(guard, types);
1581 k.set_attribution(attribution);
1582 k.fold_constants(&folded, &origin, total_slots)?;
1585 Ok(k)
1586 }
1587
1588 #[cfg(feature = "jit")]
1596 #[allow(clippy::type_complexity)]
1597 fn constant_steps(
1598 resolved: &ResolvedDag,
1599 jit_steps: &[(crate::compile::jit::JitOp, Vec<usize>, Vec<usize>)],
1600 ) -> (
1601 Vec<(crate::compile::jit::JitOp, Vec<usize>, Vec<usize>)>,
1602 Vec<usize>,
1603 ) {
1604 let classes = PolydatProgram::classify_lifecycle(
1605 &resolved.nodes,
1606 &resolved.wiring,
1607 &resolved.input_defs,
1608 &resolved.output_map,
1609 &resolved.output_modifiers,
1610 );
1611 jit_steps
1614 .iter()
1615 .enumerate()
1616 .filter(|(i, _)| {
1617 classes.lifecycle.get(*i) == Some(&crate::kernel::EvalLifecycle::CompileConst)
1618 })
1619 .map(|(i, s)| (s.clone(), i))
1620 .unzip()
1621 }
1622
1623 #[cfg(feature = "jit")]
1627 fn side_channels(resolved: &ResolvedDag) -> Vec<bool> {
1628 resolved
1629 .nodes
1630 .iter()
1631 .map(|n| matches!(n.purity(), crate::ast::Purity::SideChannel { .. }))
1632 .collect()
1633 }
1634
1635 fn externs_of(resolved: &ResolvedDag) -> Result<crate::compile::externs::Externs, String> {
1640 let layout = slot_layout(resolved);
1641 let mut externs = crate::compile::externs::Externs::new(
1642 &resolved.input_defs,
1643 resolved.coord_count,
1644 &layout.input_starts,
1645 &resolved.cursor_schemas,
1646 &shared_outputs_of(resolved),
1647 resolved.ledger.clone(),
1648 )?;
1649 externs.set_resources(resolved.resources.clone());
1650 externs.set_graph_identity(resolved.graph_identity());
1651 externs.set_output_names(&resolved.output_order);
1652 externs.set_dataset_sources(dataset_sources_of_outputs(resolved));
1653 externs.set_output_modifiers(&resolved.output_modifiers);
1654 externs.set_const_inits(&resolved.const_inits);
1655 externs.set_fixed_outputs(fixed_outputs(resolved));
1656 Ok(externs)
1657 }
1658
1659 #[doc(hidden)]
1661 #[cfg(feature = "jit")]
1662 pub(crate) fn try_compile_pure_jit_raw(
1663 self,
1664 ) -> Result<crate::compile::jit::JitKernelRaw, KernelError> {
1665 let resolved = self.resolve().map_err(KernelError::Assembly)?;
1666 Self::jit_raw_from(resolved)
1667 }
1668
1669 #[cfg(feature = "bench-tiers")]
1694 pub fn compile_closures_raw(
1695 self,
1696 ) -> Result<crate::compile::closures::CompiledKernelRaw, KernelError> {
1697 let resolved = self.resolve_with_log(None)?;
1698 let (coord_count, total_slots, steps, output_map, ref_slots, extras) =
1699 Self::build_p2_layout(&resolved).map_err(Self::refused_by_closures)?;
1700 crate::compile::closures::CompiledKernelRaw::new(
1701 coord_count,
1702 total_slots,
1703 steps,
1704 output_map,
1705 ref_slots,
1706 extras,
1707 )
1708 }
1709
1710 #[cfg(all(feature = "bench-tiers", feature = "jit"))]
1712 pub fn compile_native_raw(
1713 self,
1714 ) -> Result<crate::compile::hybrid::HybridKernelRaw, KernelError> {
1715 let resolved = self.resolve_with_log(None)?;
1716 Ok(Self::hybrid_from(resolved)?.into_raw())
1717 }
1718
1719 #[cfg(all(feature = "bench-tiers", feature = "jit"))]
1721 pub fn compile_pure_native_raw(self) -> Result<crate::compile::jit::JitKernelRaw, KernelError> {
1722 self.try_compile_pure_jit_raw()
1723 }
1724
1725 pub(crate) fn attribution_of(resolved: &ResolvedDag) -> crate::compile::Attribution {
1730 let layout = slot_layout(resolved);
1731 let sites = resolved
1732 .nodes
1733 .iter()
1734 .enumerate()
1735 .map(|(node_idx, node)| {
1736 let mut outputs: Vec<String> = resolved
1737 .output_map
1738 .iter()
1739 .filter(|(_, (n, _))| *n == node_idx)
1740 .map(|(name, _)| name.clone())
1741 .collect();
1742 outputs.sort();
1743 let inputs = resolved.wiring[node_idx]
1744 .iter()
1745 .map(|source| match source {
1746 WireSource::Input(c) => (
1747 layout.input_starts.get(*c).copied().unwrap_or(*c),
1748 resolved
1749 .input_defs
1750 .get(*c)
1751 .map(|d| d.port_type)
1752 .unwrap_or(PortType::U64),
1753 ),
1754 WireSource::NodeOutput(u, p) => (
1755 layout.port_offsets[*u][*p],
1756 resolved.nodes[*u].meta().outs[*p].typ,
1757 ),
1758 })
1759 .collect();
1760 crate::compile::NodeSite {
1761 name: node.meta().name.to_string(),
1762 outputs,
1763 inputs,
1764 }
1765 })
1766 .collect();
1767 crate::compile::Attribution {
1768 sites,
1769 context: resolved.context.clone(),
1770 }
1771 }
1772
1773 #[cfg(feature = "jit")]
1774 fn jit_raw_from(
1775 resolved: ResolvedDag,
1776 ) -> Result<crate::compile::jit::JitKernelRaw, KernelError> {
1777 let _coord_names = resolved.input_names();
1778 let (coord_count, total_slots, jit_steps, output_map, scratch, volatile) =
1779 Self::build_jit_layout(&resolved).map_err(Self::refused_by_pure_native)?;
1780 let (guard, types) = Self::jit_slot_info(&resolved);
1781 let externs = Self::externs_of(&resolved).map_err(Self::refused_by_pure_native)?;
1782 let attribution = std::sync::Arc::new(Self::attribution_of(&resolved));
1783 let (folded, origin) = Self::constant_steps(&resolved, &jit_steps);
1784 let alone = Self::side_channels(&resolved);
1785 let mut k = crate::compile::jit::compile_jit_raw_with(
1786 coord_count,
1787 total_slots,
1788 jit_steps,
1789 output_map,
1790 resolved.nodes,
1791 externs,
1792 scratch,
1793 volatile,
1794 alone,
1795 )
1796 .map_err(Self::refused_by_pure_native)?;
1797 k.set_slot_info(guard, types);
1798 k.set_attribution(attribution);
1799 k.fold_constants(&folded, &origin, total_slots)?;
1802 Ok(k)
1803 }
1804
1805 #[cfg(feature = "jit")]
1811 #[doc(hidden)]
1812 pub fn try_compile_tier1_simd_ordinal(
1813 self,
1814 driving_input: &str,
1815 output: &str,
1816 ) -> Result<
1817 crate::compile::simd_tier1::Tier1SimdExecutor,
1818 crate::compile::simd_tier1::Tier1SimdError,
1819 > {
1820 let resolved = self.resolve().map_err(|error| {
1821 crate::compile::simd_tier1::Tier1SimdError::VectorGraphBuild(error.to_string())
1822 })?;
1823 crate::compile::simd_tier1::compile_tier1_ordinal(resolved, driving_input, output)
1824 }
1825
1826 fn hybrid_from(
1827 resolved: ResolvedDag,
1828 ) -> Result<crate::compile::hybrid::HybridKernel, KernelError> {
1829 let _coord_names = resolved.input_names();
1830 let layout = slot_layout(&resolved);
1831
1832 let output_map = layout.named_outputs(&resolved);
1833 let input_widths: Vec<usize> = resolved
1834 .input_defs
1835 .iter()
1836 .map(|d| d.port_type.slot_width())
1837 .collect();
1838
1839 let ref_slots = layout.ref_slot_mask(&resolved);
1840 let input_types: Vec<PortType> = resolved.input_defs.iter().map(|d| d.port_type).collect();
1841 let externs = Self::externs_of(&resolved).map_err(Self::refused_by_native)?;
1842 let attribution = std::sync::Arc::new(Self::attribution_of(&resolved));
1843 let classes = PolydatProgram::classify_lifecycle(
1846 &resolved.nodes,
1847 &resolved.wiring,
1848 &resolved.input_defs,
1849 &resolved.output_map,
1850 &resolved.output_modifiers,
1851 );
1852 let constant: Vec<bool> = classes
1853 .lifecycle
1854 .iter()
1855 .map(|lc| *lc == crate::kernel::EvalLifecycle::CompileConst)
1856 .collect();
1857 let mut kernel = crate::compile::hybrid::build_hybrid(
1858 &resolved.nodes,
1859 &resolved.wiring,
1860 layout.coord_slots,
1861 layout.total_slots,
1862 &layout.port_offsets,
1863 &layout.input_starts,
1864 &input_widths,
1865 output_map,
1866 ref_slots,
1867 &input_types,
1868 externs,
1869 constant,
1870 classes.nondeterministic,
1871 attribution,
1872 )?;
1873 kernel.retain_nodes(resolved.nodes);
1874 Ok(kernel)
1875 }
1876
1877 fn log_forms(resolved: &ResolvedDag, log: &mut crate::dsl::events::CompileEventLog) {
1885 for (node_idx, node) in resolved.nodes.iter().enumerate() {
1886 let wire_types = wire_types_of(resolved, node_idx);
1887 #[cfg(feature = "jit")]
1891 let native = !matches!(
1892 crate::compile::jit::classify_node_typed(node.as_ref(), &wire_types),
1893 crate::compile::jit::JitOp::Fallback
1894 );
1895 #[cfg(not(feature = "jit"))]
1896 let native = false;
1897 let level = if native {
1898 "native"
1899 } else {
1900 match node_step_op(node.as_ref(), &wire_types) {
1901 Some((crate::compile::closures::StepOp::Copy, _)) => "slot copy",
1902 Some((crate::compile::closures::StepOp::U64(_), _)) => "compiled u64 op",
1903 Some((crate::compile::closures::StepOp::Slot(_), _)) => "slot kit",
1904 None => "interpreted",
1905 }
1906 };
1907 let name = resolved
1908 .output_map
1909 .iter()
1910 .find(|(_, (ni, _))| *ni == node_idx)
1911 .map(|(n, _)| n.clone())
1912 .unwrap_or_else(|| node.meta().name.clone());
1913 log.push(crate::dsl::events::CompileEvent::CompileLevelSelected {
1914 node: name,
1915 level: level.to_string(),
1916 });
1917 }
1918 }
1919
1920 fn log_summary(
1925 log: Option<&mut crate::dsl::events::CompileEventLog>,
1926 nodes: usize,
1927 outputs: usize,
1928 ) {
1929 if let Some(log) = log {
1930 let constants_folded = log
1931 .events()
1932 .iter()
1933 .filter(|e| matches!(e, crate::dsl::events::CompileEvent::ConstantFolded { .. }))
1934 .count();
1935 log.push(crate::dsl::events::CompileEvent::Summary {
1936 nodes,
1937 outputs,
1938 constants_folded,
1939 });
1940 }
1941 }
1942
1943 #[cfg(feature = "jit")]
1946 fn resolve(self) -> Result<ResolvedDag, AssemblyError> {
1947 self.resolve_with_log(None)
1948 }
1949
1950 fn resolve_with_log(
1951 mut self,
1952 mut log: Option<&mut crate::dsl::events::CompileEventLog>,
1953 ) -> Result<ResolvedDag, AssemblyError> {
1954 self.capture_consts()?;
1957 let open: Vec<usize> = self
1964 .input_defs
1965 .iter()
1966 .enumerate()
1967 .filter(|(_, d)| {
1968 d.kind != crate::kernel::InputKind::Coordinate
1969 && d.type_origin == crate::kernel::TypeOrigin::Inferred
1970 && d.port_type != PortType::Dyn
1971 })
1972 .map(|(i, _)| i)
1973 .collect();
1974 let variance_level = match self.input_variance {
1975 crate::dsl::compile::InputVariance::Fixed => None,
1976 crate::dsl::compile::InputVariance::Error => {
1977 if !open.is_empty() {
1978 return Err(AssemblyError::OpenInputs(
1979 open.iter()
1980 .map(|&i| {
1981 (
1982 self.input_defs[i].name.clone(),
1983 self.input_defs[i].port_type,
1984 )
1985 })
1986 .collect(),
1987 ));
1988 }
1989 None
1990 }
1991 crate::dsl::compile::InputVariance::Warn => {
1992 Some(crate::dsl::events::EventLevel::Warning)
1993 }
1994 crate::dsl::compile::InputVariance::Info => Some(crate::dsl::events::EventLevel::Info),
1995 };
1996 if variance_level.is_some() {
1997 for &i in &open {
1998 let def = &mut self.input_defs[i];
1999 def.converts_to = Some(def.port_type);
2000 def.port_type = PortType::Dyn;
2001 }
2002 }
2003 if let Some(log) = log.as_deref_mut() {
2009 let cursor_slot = |name: &str| {
2010 self.cursor_schemas
2011 .iter()
2012 .any(|s| name.starts_with(&format!("{}__cursor", s.name)))
2013 };
2014 for def in &self.input_defs {
2015 if matches!(
2016 def.kind,
2017 crate::kernel::InputKind::ExternalWrite
2018 | crate::kernel::InputKind::IterationExtern
2019 ) && def.default == crate::ast::Value::None
2020 && !cursor_slot(&def.name)
2021 {
2022 log.push(crate::dsl::events::CompileEvent::ExternWithoutDefault {
2023 name: def.name.clone(),
2024 port_type: def.port_type.to_string(),
2025 });
2026 }
2027 }
2028 }
2029 let mut name_to_idx: HashMap<String, usize> = HashMap::new();
2031 for (i, pn) in self.nodes.iter().enumerate() {
2032 if name_to_idx.contains_key(&pn.name) {
2033 return Err(AssemblyError::DuplicateNode(pn.name.clone()));
2034 }
2035 name_to_idx.insert(pn.name.clone(), i);
2036 }
2037
2038 let input_to_idx: HashMap<String, usize> = self
2040 .input_defs
2041 .iter()
2042 .enumerate()
2043 .map(|(i, d)| (d.name.clone(), i))
2044 .collect();
2045
2046 for pn in &self.nodes {
2048 let expected = pn.node.meta().wire_inputs().len();
2049 let got = pn.inputs.len();
2050 if expected != got {
2051 return Err(AssemblyError::ArityMismatch {
2052 node_name: pn.name.clone(),
2053 expected,
2054 got,
2055 });
2056 }
2057 }
2058
2059 let mut all_nodes: Vec<PendingNode> = Vec::new();
2060 let mut all_name_to_idx: HashMap<String, usize> = HashMap::new();
2061 let mut adapter_count = 0usize;
2062 let mut assertion_count = 0usize;
2063 let strict_values = self.strict_values;
2064 let strict = self.strict;
2065 let mut inserted_guards: HashMap<usize, crate::dsl::const_constraints::ConstConstraint> =
2069 HashMap::new();
2070 let volatile_nodes: std::collections::HashSet<String> = self
2073 .output_modifiers
2074 .iter()
2075 .filter(|(_, m)| m.is_volatile())
2076 .filter_map(|(name, _)| match self.outputs.get(name) {
2077 Some(WireRef::Node(node, _)) => Some(node.clone()),
2078 _ => None,
2079 })
2080 .collect();
2081
2082 for pn in self.nodes {
2083 let idx = all_nodes.len();
2084 all_name_to_idx.insert(pn.name.clone(), idx);
2085 all_nodes.push(pn);
2086 }
2087
2088 let mut resolved_wiring: Vec<Vec<WireSource>> = Vec::new();
2089 let mut converters: HashMap<(usize, PortType), usize> = HashMap::new();
2091
2092 for node_idx in 0..all_nodes.len() {
2093 let mut node_wiring = Vec::new();
2094
2095 for (port_idx, wire_ref) in all_nodes[node_idx].inputs.clone().iter().enumerate() {
2096 let port = all_nodes[node_idx].node.meta().wire_inputs()[port_idx].clone();
2097 let expected_type = port.typ;
2098
2099 let (source, source_type) = match wire_ref {
2100 WireRef::Input(name) => {
2101 let input_idx = input_to_idx
2102 .get(name)
2103 .ok_or_else(|| AssemblyError::UnknownWire(name.clone()))?;
2104 let source_type = self.input_defs[*input_idx].port_type;
2105 (WireSource::Input(*input_idx), source_type)
2106 }
2107 WireRef::Node(name, out_port) => {
2108 let src_idx = all_name_to_idx
2109 .get(name)
2110 .ok_or_else(|| AssemblyError::UnknownWire(name.clone()))?;
2111 let src_type = all_nodes[*src_idx].node.meta().outs[*out_port].typ;
2112 (WireSource::NodeOutput(*src_idx, *out_port), src_type)
2113 }
2114 };
2115
2116 if source_type == PortType::Dyn
2127 && !port.accepts_any_type
2128 && expected_type != PortType::Dyn
2129 {
2130 let WireSource::Input(input_idx) = source else {
2131 unreachable!("only an input slot is typed `Dyn`")
2132 };
2133 let conv_idx = match converters.get(&(input_idx, expected_type)) {
2134 Some(&idx) => idx,
2135 None => {
2136 let converter = crate::convert::InputConverter::new(
2137 &self.input_defs[input_idx].name,
2138 expected_type,
2139 );
2140 let conv_name = converter.meta().name.clone();
2141 let idx = all_nodes.len();
2142 all_name_to_idx.insert(conv_name.clone(), idx);
2143 while resolved_wiring.len() <= idx {
2144 resolved_wiring.push(Vec::new());
2145 }
2146 resolved_wiring[idx] = vec![source.clone()];
2147 all_nodes.push(PendingNode {
2148 name: conv_name,
2149 node: Box::new(converter),
2150 inputs: vec![],
2151 strict_values: None,
2152 });
2153 converters.insert((input_idx, expected_type), idx);
2154 idx
2155 }
2156 };
2157 node_wiring.push(WireSource::NodeOutput(conv_idx, 0));
2158 } else if port.accepts_any_type || source_type == expected_type {
2159 node_wiring.push(source);
2160 } else if let Some(adapter) = auto_adapter(source_type, expected_type) {
2161 if strict {
2162 return Err(AssemblyError::Other(format!(
2163 "strict mode: implicit type coercion {source_type} → {expected_type} \
2164 into '{}'. Use an explicit conversion function (e.g., to_f64, \
2165 to_i64, f64_to_u64).",
2166 all_nodes[node_idx].name
2167 )));
2168 }
2169 let adapter_name = format!("__adapt_{adapter_count}");
2170 adapter_count += 1;
2171 let adapter_idx = all_nodes.len();
2172
2173 if let Some(ref mut log) = log {
2174 let from_name = match wire_ref {
2175 WireRef::Input(n) => n.clone(),
2176 WireRef::Node(n, _) => n.clone(),
2177 };
2178 let to_name = all_nodes[node_idx].name.clone();
2179 log.push(if is_lossless_widening(source_type, expected_type) {
2180 crate::dsl::events::CompileEvent::TypeWidening {
2181 from: source_type.to_keyword(),
2182 to: expected_type.to_keyword(),
2183 context: format!("{from_name} → {to_name}"),
2184 }
2185 } else {
2186 crate::dsl::events::CompileEvent::TypeAdapterInserted {
2187 from_node: from_name,
2188 to_node: to_name,
2189 adapter: format!("{source_type:?}→{expected_type:?}"),
2190 }
2191 });
2192 }
2193
2194 all_name_to_idx.insert(adapter_name.clone(), adapter_idx);
2195
2196 let adapter_wiring = vec![source];
2197 while resolved_wiring.len() <= adapter_idx {
2198 resolved_wiring.push(Vec::new());
2199 }
2200 resolved_wiring[adapter_idx] = adapter_wiring;
2201
2202 let sink_mark = all_nodes[node_idx].strict_values;
2206 all_nodes.push(PendingNode {
2207 name: adapter_name,
2208 node: adapter,
2209 inputs: vec![],
2210 strict_values: sink_mark,
2211 });
2212
2213 node_wiring.push(WireSource::NodeOutput(adapter_idx, 0));
2214 } else {
2215 let from_name = match wire_ref {
2216 WireRef::Input(n) => n.clone(),
2217 WireRef::Node(n, _) => n.clone(),
2218 };
2219 return Err(AssemblyError::TypeMismatch {
2220 from_node: from_name,
2221 from_port: match wire_ref {
2222 WireRef::Input(_) => 0,
2223 WireRef::Node(_, p) => *p,
2224 },
2225 from_type: source_type,
2226 to_node: all_nodes[node_idx].name.clone(),
2227 to_port: port_idx,
2228 to_type: expected_type,
2229 });
2230 }
2231
2232 let sink_port = &all_nodes[node_idx].node.meta().wire_inputs()[port_idx];
2245 if let Some(constraint) = sink_port.constraint {
2246 let last_source = node_wiring.last().expect("wire just pushed").clone();
2247 let proof = if all_nodes[node_idx].strict_values.unwrap_or(strict_values) {
2248 constraint_proof(
2249 &all_nodes,
2250 &inserted_guards,
2251 &volatile_nodes,
2252 &last_source,
2253 &constraint,
2254 )
2255 } else {
2256 ConstraintProof::NotChecked
2257 };
2258 if let ConstraintProof::Violated { value, message } = &proof {
2259 let sink = &all_nodes[node_idx];
2260 let detail = match constraint {
2262 crate::dsl::const_constraints::ConstConstraint::StrParser(_) => {
2263 format!(" ({message})")
2264 }
2265 _ => String::new(),
2266 };
2267 return Err(AssemblyError::Other(format!(
2268 "strict_values: port '{}' of '{}' ({}) must be {}, but its \
2269 source is the constant {value}{detail}",
2270 sink_port.name,
2271 sink.name,
2272 sink.node.meta().name,
2273 crate::library::assertions::describe_constraint(&constraint),
2274 )));
2275 }
2276 if matches!(proof, ConstraintProof::Unproven) {
2277 let assert_name = format!("__assert_v_{assertion_count}");
2278 assertion_count += 1;
2279 let assert_idx = all_nodes.len();
2280
2281 if let Some(ref mut log) = log {
2282 let from_name = match wire_ref {
2283 WireRef::Input(n) => n.clone(),
2284 WireRef::Node(n, _) => n.clone(),
2285 };
2286 log.push(crate::dsl::events::CompileEvent::AssertionInserted {
2287 from_node: from_name,
2288 to_node: all_nodes[node_idx].name.clone(),
2289 kind: format!("{:?} value-assert {:?}", expected_type, constraint),
2290 });
2291 }
2292
2293 all_name_to_idx.insert(assert_name.clone(), assert_idx);
2294 let assert_wiring = vec![last_source];
2295 while resolved_wiring.len() <= assert_idx {
2296 resolved_wiring.push(Vec::new());
2297 }
2298 resolved_wiring[assert_idx] = assert_wiring;
2299
2300 all_nodes.push(PendingNode {
2301 name: assert_name,
2302 node: crate::library::assertions::assert_value_node(
2303 expected_type,
2304 constraint,
2305 ),
2306 inputs: vec![],
2307 strict_values: None,
2308 });
2309 inserted_guards.insert(assert_idx, constraint);
2310
2311 *node_wiring.last_mut().unwrap() = WireSource::NodeOutput(assert_idx, 0);
2314 } else if let Some(ref mut log) = log {
2315 let from_name = match wire_ref {
2316 WireRef::Input(n) => n.clone(),
2317 WireRef::Node(n, _) => n.clone(),
2318 };
2319 log.push(crate::dsl::events::CompileEvent::AssertionSkipped {
2320 from_node: from_name,
2321 to_node: all_nodes[node_idx].name.clone(),
2322 reason: proof.skip_reason().into(),
2323 });
2324 }
2325 }
2326 }
2327
2328 while resolved_wiring.len() <= node_idx {
2329 resolved_wiring.push(Vec::new());
2330 }
2331 resolved_wiring[node_idx] = node_wiring;
2332 }
2333
2334 while resolved_wiring.len() < all_nodes.len() {
2335 resolved_wiring.push(Vec::new());
2336 }
2337
2338 {
2343 let rules = crate::compile::fusion::default_rules();
2344 if !rules.is_empty() {
2345 let mut output_nodes: Vec<usize> = Vec::new();
2348 for wire_ref in self.outputs.values() {
2349 if let WireRef::Node(node_name, _) = wire_ref
2350 && let Some(&idx) = all_name_to_idx.get(node_name)
2351 {
2352 output_nodes.push(idx);
2353 }
2354 }
2355
2356 let marks: Vec<Option<bool>> =
2360 all_nodes.iter().map(|pn| pn.strict_values).collect();
2361 let mut opt_nodes: Vec<Option<Box<dyn PolydatNode>>> =
2362 all_nodes.into_iter().map(|pn| Some(pn.node)).collect();
2363
2364 let fused_count = crate::compile::fusion::apply_fusions(
2365 &mut opt_nodes,
2366 &mut resolved_wiring,
2367 &mut all_name_to_idx,
2368 &rules,
2369 &output_nodes,
2370 );
2371 if fused_count > 0
2372 && let Some(ref mut log) = log
2373 {
2374 log.push(crate::dsl::events::CompileEvent::FusionApplied {
2375 pattern: "subgraph".into(),
2376 nodes_replaced: fused_count,
2377 });
2378 }
2379
2380 all_nodes = opt_nodes
2383 .into_iter()
2384 .enumerate()
2385 .map(|(i, opt)| PendingNode {
2386 name: all_name_to_idx
2387 .iter()
2388 .find(|&(_, &idx)| idx == i)
2389 .map(|(n, _)| n.clone())
2390 .unwrap_or_else(|| format!("__removed_{i}")),
2391 node: opt.unwrap_or_else(|| {
2392 Box::new(crate::library::identity::Identity::new(
2393 crate::ast::PortType::U64,
2394 ))
2395 }),
2396 inputs: vec![], strict_values: marks[i],
2398 })
2399 .collect();
2400 }
2401 }
2402
2403 let node_count = all_nodes.len();
2410 let mut reachable = vec![false; node_count];
2411 {
2412 let mut worklist: Vec<usize> = Vec::new();
2413 for wire_ref in self.outputs.values() {
2415 if let WireRef::Node(node_name, _) = wire_ref
2416 && let Some(&idx) = all_name_to_idx.get(node_name)
2417 {
2418 worklist.push(idx);
2419 }
2420 }
2421 for (idx, pn) in all_nodes.iter().enumerate() {
2431 if matches!(
2432 pn.node.meta().name.as_str(),
2433 "log_debug" | "log_info" | "log_warn" | "log_error"
2434 ) {
2435 worklist.push(idx);
2436 }
2437 }
2438 while let Some(idx) = worklist.pop() {
2440 if reachable[idx] {
2441 continue;
2442 }
2443 reachable[idx] = true;
2444 for source in &resolved_wiring[idx] {
2445 if let WireSource::NodeOutput(upstream, _) = source
2446 && !reachable[*upstream]
2447 {
2448 worklist.push(*upstream);
2449 }
2450 }
2451 }
2452 }
2453 let live_count = reachable.iter().filter(|&&r| r).count();
2454
2455 if let Some(log) = log.as_deref_mut() {
2460 let mut placed: Vec<(usize, usize, PortType)> = converters
2461 .iter()
2462 .filter(|&(_, &idx)| reachable[idx])
2463 .map(|(&(input, to), &idx)| (idx, input, to))
2464 .collect();
2465 placed.sort_unstable_by_key(|&(idx, _, _)| idx);
2466 for &(idx, input, to) in &placed {
2467 let def = &self.input_defs[input];
2468 let (origin, level) = match (def.converts_to, variance_level) {
2469 (Some(_), Some(level)) => ("inferred", level),
2470 _ => ("declared dyn", crate::dsl::events::EventLevel::Info),
2471 };
2472 log.push(crate::dsl::events::CompileEvent::InputConverterInserted {
2473 input: def.name.clone(),
2474 to: to.to_keyword().to_string(),
2475 node: all_nodes[idx].name.clone(),
2476 origin: origin.to_string(),
2477 level,
2478 });
2479 }
2480 if let Some(level) = variance_level {
2481 for &input in &open {
2482 if placed.iter().any(|&(_, i, _)| i == input) {
2483 continue;
2484 }
2485 let def = &self.input_defs[input];
2486 log.push(crate::dsl::events::CompileEvent::InputConverterInserted {
2487 input: def.name.clone(),
2488 to: def
2489 .converts_to
2490 .unwrap_or(def.port_type)
2491 .to_keyword()
2492 .to_string(),
2493 node: "(none: nothing reads it)".to_string(),
2494 origin: "inferred".to_string(),
2495 level,
2496 });
2497 }
2498 }
2499 }
2500
2501 let mut in_degree = vec![0usize; node_count];
2503 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); node_count];
2504
2505 for (node_idx, wiring) in resolved_wiring.iter().enumerate() {
2506 if !reachable[node_idx] {
2507 continue;
2508 }
2509 for source in wiring {
2510 if let WireSource::NodeOutput(upstream, _) = source {
2511 in_degree[node_idx] += 1;
2512 dependents[*upstream].push(node_idx);
2513 }
2514 }
2515 }
2516
2517 let mut queue: Vec<usize> = (0..node_count)
2518 .filter(|i| reachable[*i] && in_degree[*i] == 0)
2519 .collect();
2520 let mut sorted_order: Vec<usize> = Vec::with_capacity(live_count);
2521
2522 while let Some(idx) = queue.pop() {
2523 sorted_order.push(idx);
2524 for &dep in &dependents[idx] {
2525 in_degree[dep] -= 1;
2526 if in_degree[dep] == 0 {
2527 queue.push(dep);
2528 }
2529 }
2530 }
2531
2532 if sorted_order.len() != live_count {
2533 return Err(AssemblyError::CycleDetected);
2534 }
2535
2536 let mut old_to_new = vec![0usize; node_count];
2537 for (new_idx, &old_idx) in sorted_order.iter().enumerate() {
2538 old_to_new[old_idx] = new_idx;
2539 }
2540
2541 let final_marks: Vec<Option<bool>> = sorted_order
2543 .iter()
2544 .map(|&old_idx| all_nodes[old_idx].strict_values)
2545 .collect();
2546 let mut sorted_nodes: Vec<Option<Box<dyn PolydatNode>>> =
2547 all_nodes.into_iter().map(|pn| Some(pn.node)).collect();
2548
2549 let final_nodes: Vec<Box<dyn PolydatNode>> = sorted_order
2550 .iter()
2551 .map(|&old_idx| sorted_nodes[old_idx].take().unwrap())
2552 .collect();
2553
2554 let final_wiring: Vec<Vec<WireSource>> = sorted_order
2555 .iter()
2556 .map(|&old_idx| {
2557 resolved_wiring[old_idx]
2558 .iter()
2559 .map(|source| match source {
2560 WireSource::Input(c) => WireSource::Input(*c),
2561 WireSource::NodeOutput(old_up, port) => {
2562 WireSource::NodeOutput(old_to_new[*old_up], *port)
2563 }
2564 })
2565 .collect()
2566 })
2567 .collect();
2568
2569 let mut final_output_map: HashMap<String, (usize, usize)> = HashMap::new();
2570 for (name, wire_ref) in &self.outputs {
2571 match wire_ref {
2572 WireRef::Input(coord_name) => {
2573 return Err(AssemblyError::UnknownWire(format!(
2574 "output '{name}' references coordinate '{coord_name}' directly; \
2575 wire through a node instead"
2576 )));
2577 }
2578 WireRef::Node(node_name, port) => {
2579 let old_idx = all_name_to_idx
2580 .get(node_name)
2581 .ok_or_else(|| AssemblyError::UnknownWire(node_name.clone()))?;
2582 final_output_map.insert(name.clone(), (old_to_new[*old_idx], *port));
2583 }
2584 }
2585 }
2586
2587 for (i, f) in crate::compile::roundtrip_lint::lint_type_round_trips(
2595 &final_nodes,
2596 &final_wiring,
2597 &self.input_defs,
2598 ) {
2599 if final_marks[i].unwrap_or(strict_values) {
2600 return Err(AssemblyError::Other(f.message()));
2601 }
2602 crate::library::support::audit::warn(&f.message());
2605 if let Some(ref mut log) = log {
2606 log.push(crate::dsl::events::CompileEvent::Warning {
2607 message: f.message(),
2608 });
2609 }
2610 }
2611
2612 if let Some(log) = log {
2613 let resolved_view = ResolvedDag {
2614 nodes: final_nodes,
2615 wiring: final_wiring,
2616 input_defs: self.input_defs,
2617 coord_count: self.coord_count,
2618 output_map: final_output_map,
2619 output_order: self.output_order,
2620 source: self.source,
2621 context: self.context,
2622 output_modifiers: self.output_modifiers,
2623 const_outputs: self.const_outputs,
2624 const_inits: self.const_inits,
2625 cursor_schemas: self.cursor_schemas,
2626 ledger: self.ledger,
2627 resources: self.resources,
2628 };
2629 Self::log_forms(&resolved_view, log);
2630 return Ok(resolved_view);
2631 }
2632 Ok(ResolvedDag {
2633 nodes: final_nodes,
2634 wiring: final_wiring,
2635 input_defs: self.input_defs,
2636 coord_count: self.coord_count,
2637 output_map: final_output_map,
2638 output_order: self.output_order,
2639 source: self.source,
2640 context: self.context,
2641 output_modifiers: self.output_modifiers,
2642 const_outputs: self.const_outputs,
2643 const_inits: self.const_inits,
2644 cursor_schemas: self.cursor_schemas,
2645 ledger: self.ledger,
2646 resources: self.resources,
2647 })
2648 }
2649}
2650
2651enum ConstraintProof {
2654 NotChecked,
2656 ConstantSatisfies,
2659 ConstantNone,
2662 Guarded,
2665 Violated {
2668 value: String,
2670 message: String,
2672 },
2673 Unproven,
2675}
2676
2677impl ConstraintProof {
2678 fn skip_reason(&self) -> &'static str {
2681 match self {
2682 ConstraintProof::NotChecked => "strict_values not enabled",
2683 ConstraintProof::ConstantSatisfies => "constant source satisfies the constraint",
2684 ConstraintProof::ConstantNone => "constant source is None",
2685 ConstraintProof::Guarded => "upstream assertion",
2686 ConstraintProof::Violated { .. } => "constant source fails the constraint",
2687 ConstraintProof::Unproven => "no skip rule matched",
2688 }
2689 }
2690}
2691
2692fn constraint_proof(
2706 all_nodes: &[PendingNode],
2707 inserted_guards: &HashMap<usize, crate::dsl::const_constraints::ConstConstraint>,
2708 volatile_nodes: &std::collections::HashSet<String>,
2709 src: &WireSource,
2710 constraint: &crate::dsl::const_constraints::ConstConstraint,
2711) -> ConstraintProof {
2712 let WireSource::NodeOutput(idx, port) = src else {
2713 return ConstraintProof::Unproven;
2714 };
2715 if let Some(guarded) = inserted_guards.get(idx) {
2716 return if crate::library::assertions::same_constraint(guarded, constraint) {
2717 ConstraintProof::Guarded
2718 } else {
2719 ConstraintProof::Unproven
2720 };
2721 }
2722 let pending = &all_nodes[*idx];
2723 let node = pending.node.as_ref();
2724 let nondeterministic = matches!(node.purity(), crate::ast::Purity::Nondeterministic { .. })
2725 || volatile_nodes.contains(&pending.name);
2726 if !node.meta().wire_inputs().is_empty() || nondeterministic {
2727 return ConstraintProof::Unproven;
2728 }
2729 let mut outputs = vec![crate::ast::Value::None; node.meta().outs.len()];
2732 let evaluated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2733 node.eval(&[], &mut outputs);
2734 }));
2735 if evaluated.is_err() {
2736 return ConstraintProof::Unproven;
2737 }
2738 let Some(value) = outputs.get(*port) else {
2739 return ConstraintProof::Unproven;
2740 };
2741 if matches!(value, crate::ast::Value::None) {
2742 return ConstraintProof::ConstantNone;
2743 }
2744 match crate::library::assertions::check_value(constraint, value, "the value") {
2745 Some(Ok(())) => ConstraintProof::ConstantSatisfies,
2746 Some(Err(message)) => ConstraintProof::Violated {
2747 value: value.to_display_string(),
2748 message,
2749 },
2750 None => ConstraintProof::Unproven,
2751 }
2752}
2753
2754pub(crate) fn shared_outputs_of(resolved: &ResolvedDag) -> Vec<&str> {
2757 let mut shared: Vec<&str> = resolved
2758 .output_modifiers
2759 .iter()
2760 .filter(|(_, m)| **m == crate::dsl::ast::BindingModifier::SHARED)
2761 .map(|(name, _)| name.as_str())
2762 .collect();
2763 shared.sort();
2764 shared
2765}
2766
2767fn is_lossless_widening(from: PortType, to: PortType) -> bool {
2771 use PortType as P;
2772 matches!(
2773 (from, to),
2774 (P::U64, P::F64)
2775 | (P::U32, P::U64)
2776 | (P::U32, P::I64)
2777 | (P::U32, P::F64)
2778 | (P::I32, P::I64)
2779 | (P::I32, P::F64)
2780 | (P::I64, P::F64)
2781 | (P::F32, P::F64)
2782 )
2783}
2784
2785pub(crate) fn wire_types_of(resolved: &ResolvedDag, node_idx: usize) -> Vec<PortType> {
2786 resolved.wiring[node_idx]
2787 .iter()
2788 .map(|src| match src {
2789 crate::kernel::WireSource::Input(i) => resolved.input_defs[*i].port_type,
2790 crate::kernel::WireSource::NodeOutput(j, p) => resolved.nodes[*j].meta().outs[*p].typ,
2791 })
2792 .collect()
2793}
2794
2795pub fn auto_adapter(from: PortType, to: PortType) -> Option<Box<dyn PolydatNode>> {
2799 use crate::library::convert::{
2800 BoolToStr, BoolToU64, F32ToF64, F32ToString, I32ToF64, I32ToI64, I32ToString, I64ToF64,
2801 I64ToString, U32ToF64, U32ToI64, U32ToString, U32ToU64,
2802 };
2803 use crate::library::polyfill as P;
2804 use crate::library::polyfill_128 as W;
2805 use crate::library::polyfill_complete as C;
2806 use crate::library::polyfill_narrow as N;
2807 match (from, to) {
2808 (PortType::U64, PortType::F64) => Some(Box::new(U64ToF64::new())),
2810 (PortType::U32, PortType::U64) => Some(Box::new(U32ToU64::new())),
2811 (PortType::U32, PortType::I64) => Some(Box::new(U32ToI64::new())),
2812 (PortType::U32, PortType::F64) => Some(Box::new(U32ToF64::new())),
2813 (PortType::I32, PortType::I64) => Some(Box::new(I32ToI64::new())),
2814 (PortType::I32, PortType::F64) => Some(Box::new(I32ToF64::new())),
2815 (PortType::I32, PortType::F32) => Some(Box::new(P::I32ToF32::new())),
2819 (PortType::I64, PortType::F64) => Some(Box::new(I64ToF64::new())),
2820 (PortType::F32, PortType::F64) => Some(Box::new(F32ToF64::new())),
2821
2822 (PortType::U64, PortType::Str) => Some(Box::new(U64ToString::new())),
2824 (PortType::F64, PortType::Str) => Some(Box::new(F64ToString::new())),
2825 (PortType::Bool, PortType::Str) => Some(Box::new(BoolToStr::new())),
2826 (PortType::Json, PortType::Str) => Some(Box::new(JsonToStr::new())),
2827 (PortType::U32, PortType::Str) => Some(Box::new(U32ToString::new())),
2828 (PortType::I32, PortType::Str) => Some(Box::new(I32ToString::new())),
2829 (PortType::I64, PortType::Str) => Some(Box::new(I64ToString::new())),
2830 (PortType::F32, PortType::Str) => Some(Box::new(F32ToString::new())),
2831
2832 (PortType::Bool, PortType::U64) => Some(Box::new(BoolToU64::new())),
2834 (PortType::Bool, PortType::U32) => Some(Box::new(P::BoolToU32::new())),
2835 (PortType::Bool, PortType::I64) => Some(Box::new(P::BoolToI64::new())),
2836 (PortType::Bool, PortType::I32) => Some(Box::new(P::BoolToI32::new())),
2837 (PortType::Bool, PortType::F64) => Some(Box::new(P::BoolToF64::new())),
2838 (PortType::Bool, PortType::F32) => Some(Box::new(P::BoolToF32::new())),
2839 (PortType::U64, PortType::Bool) => {
2840 Some(Box::new(crate::library::convert::U64ToBool::new()))
2841 }
2842 (PortType::U32, PortType::Bool) => Some(Box::new(P::U32ToBool::new())),
2843 (PortType::I64, PortType::Bool) => Some(Box::new(P::I64ToBool::new())),
2844 (PortType::I32, PortType::Bool) => Some(Box::new(P::I32ToBool::new())),
2845 (PortType::F64, PortType::Bool) => Some(Box::new(P::F64ToBool::new())),
2846 (PortType::F32, PortType::Bool) => Some(Box::new(P::F32ToBool::new())),
2847
2848 (PortType::U64, PortType::Bytes) => Some(Box::new(P::U64ToBytes::new())),
2850 (PortType::U32, PortType::Bytes) => Some(Box::new(P::U32ToBytes::new())),
2851 (PortType::I64, PortType::Bytes) => Some(Box::new(P::I64ToBytes::new())),
2852 (PortType::I32, PortType::Bytes) => Some(Box::new(P::I32ToBytes::new())),
2853 (PortType::F64, PortType::Bytes) => Some(Box::new(P::F64ToBytes::new())),
2854 (PortType::F32, PortType::Bytes) => Some(Box::new(P::F32ToBytes::new())),
2855 (PortType::Bool, PortType::Bytes) => Some(Box::new(P::BoolToBytes::new())),
2856 (PortType::VecF32, PortType::Bytes) => Some(Box::new(P::VecF32ToBytes::new())),
2857 (PortType::VecI32, PortType::Bytes) => Some(Box::new(P::VecI32ToBytes::new())),
2858
2859 (PortType::U64, PortType::Json) => Some(Box::new(P::U64ToJson::new())),
2863 (PortType::U32, PortType::Json) => Some(Box::new(P::U32ToJson::new())),
2864 (PortType::I64, PortType::Json) => Some(Box::new(P::I64ToJson::new())),
2865 (PortType::I32, PortType::Json) => Some(Box::new(P::I32ToJson::new())),
2866 (PortType::Bool, PortType::Json) => Some(Box::new(P::BoolToJson::new())),
2867 (PortType::VecI32, PortType::Json) => Some(Box::new(P::VecI32ToJson::new())),
2868
2869 (PortType::VecI32, PortType::VecF32) => Some(Box::new(P::VecI32ToVecF32::new())),
2871
2872 (PortType::U8, PortType::U64) => Some(Box::new(N::U8ToU64::new())),
2877 (PortType::U8, PortType::U32) => Some(Box::new(N::U8ToU32::new())),
2878 (PortType::U8, PortType::U16) => Some(Box::new(N::U8ToU16::new())),
2879 (PortType::U8, PortType::F64) => Some(Box::new(N::U8ToF64::new())),
2880 (PortType::U16, PortType::U64) => Some(Box::new(N::U16ToU64::new())),
2881 (PortType::U16, PortType::U32) => Some(Box::new(N::U16ToU32::new())),
2882 (PortType::U16, PortType::F64) => Some(Box::new(N::U16ToF64::new())),
2883 (PortType::I8, PortType::I64) => Some(Box::new(N::I8ToI64::new())),
2884 (PortType::I8, PortType::I32) => Some(Box::new(N::I8ToI32::new())),
2885 (PortType::I8, PortType::I16) => Some(Box::new(N::I8ToI16::new())),
2886 (PortType::I8, PortType::F64) => Some(Box::new(N::I8ToF64::new())),
2887 (PortType::I16, PortType::I64) => Some(Box::new(N::I16ToI64::new())),
2888 (PortType::I16, PortType::I32) => Some(Box::new(N::I16ToI32::new())),
2889 (PortType::I16, PortType::F64) => Some(Box::new(N::I16ToF64::new())),
2890 (PortType::F16, PortType::F32) => Some(Box::new(N::F16ToF32::new())),
2891 (PortType::F16, PortType::F64) => Some(Box::new(N::F16ToF64::new())),
2892 (PortType::U8, PortType::I16) => Some(Box::new(N::U8ToI16::new())),
2895 (PortType::U8, PortType::I32) => Some(Box::new(N::U8ToI32::new())),
2896 (PortType::U8, PortType::I64) => Some(Box::new(N::U8ToI64::new())),
2897 (PortType::U8, PortType::F32) => Some(Box::new(N::U8ToF32::new())),
2898 (PortType::U16, PortType::I32) => Some(Box::new(N::U16ToI32::new())),
2899 (PortType::U16, PortType::I64) => Some(Box::new(N::U16ToI64::new())),
2900 (PortType::U16, PortType::F32) => Some(Box::new(N::U16ToF32::new())),
2901 (PortType::I8, PortType::F32) => Some(Box::new(N::I8ToF32::new())),
2902 (PortType::I16, PortType::F32) => Some(Box::new(N::I16ToF32::new())),
2903 (PortType::U8, PortType::F16) => Some(Box::new(N::U8ToF16::new())),
2904 (PortType::I8, PortType::F16) => Some(Box::new(N::I8ToF16::new())),
2905 (PortType::U8, PortType::Str) => Some(Box::new(N::U8ToString::new())),
2906 (PortType::U16, PortType::Str) => Some(Box::new(N::U16ToString::new())),
2907 (PortType::I8, PortType::Str) => Some(Box::new(N::I8ToString::new())),
2908 (PortType::I16, PortType::Str) => Some(Box::new(N::I16ToString::new())),
2909 (PortType::F16, PortType::Str) => Some(Box::new(N::F16ToString::new())),
2910 (PortType::Bool, PortType::U8) => Some(Box::new(N::BoolToU8::new())),
2911 (PortType::Bool, PortType::U16) => Some(Box::new(N::BoolToU16::new())),
2912 (PortType::Bool, PortType::I8) => Some(Box::new(N::BoolToI8::new())),
2913 (PortType::Bool, PortType::I16) => Some(Box::new(N::BoolToI16::new())),
2914 (PortType::Bool, PortType::F16) => Some(Box::new(N::BoolToF16::new())),
2915 (PortType::U8, PortType::Bool) => Some(Box::new(N::U8ToBool::new())),
2916 (PortType::U16, PortType::Bool) => Some(Box::new(N::U16ToBool::new())),
2917 (PortType::I8, PortType::Bool) => Some(Box::new(N::I8ToBool::new())),
2918 (PortType::I16, PortType::Bool) => Some(Box::new(N::I16ToBool::new())),
2919 (PortType::F16, PortType::Bool) => Some(Box::new(N::F16ToBool::new())),
2920 (PortType::U8, PortType::Bytes) => Some(Box::new(N::U8ToBytes::new())),
2921 (PortType::U16, PortType::Bytes) => Some(Box::new(N::U16ToBytes::new())),
2922 (PortType::I8, PortType::Bytes) => Some(Box::new(N::I8ToBytes::new())),
2923 (PortType::I16, PortType::Bytes) => Some(Box::new(N::I16ToBytes::new())),
2924 (PortType::F16, PortType::Bytes) => Some(Box::new(N::F16ToBytes::new())),
2925 (PortType::U8, PortType::Json) => Some(Box::new(N::U8ToJson::new())),
2926 (PortType::U16, PortType::Json) => Some(Box::new(N::U16ToJson::new())),
2927 (PortType::I8, PortType::Json) => Some(Box::new(N::I8ToJson::new())),
2928 (PortType::I16, PortType::Json) => Some(Box::new(N::I16ToJson::new())),
2929
2930 (PortType::U64, PortType::U128) => Some(Box::new(W::U64ToU128::new())),
2935 (PortType::U64, PortType::I128) => Some(Box::new(W::U64ToI128::new())),
2936 (PortType::I64, PortType::I128) => Some(Box::new(W::I64ToI128::new())),
2937 (PortType::U8, PortType::U128) => Some(Box::new(W::U8ToU128::new())),
2942 (PortType::U8, PortType::I128) => Some(Box::new(W::U8ToI128::new())),
2943 (PortType::U16, PortType::U128) => Some(Box::new(W::U16ToU128::new())),
2944 (PortType::U16, PortType::I128) => Some(Box::new(W::U16ToI128::new())),
2945 (PortType::U32, PortType::U128) => Some(Box::new(W::U32ToU128::new())),
2946 (PortType::U32, PortType::I128) => Some(Box::new(W::U32ToI128::new())),
2947 (PortType::I8, PortType::I128) => Some(Box::new(W::I8ToI128::new())),
2948 (PortType::I16, PortType::I128) => Some(Box::new(W::I16ToI128::new())),
2949 (PortType::I32, PortType::I128) => Some(Box::new(W::I32ToI128::new())),
2950 (PortType::Bool, PortType::U128) => Some(Box::new(W::BoolToU128::new())),
2951 (PortType::Bool, PortType::I128) => Some(Box::new(W::BoolToI128::new())),
2952 (PortType::U128, PortType::Bool) => Some(Box::new(W::U128ToBool::new())),
2953 (PortType::I128, PortType::Bool) => Some(Box::new(W::I128ToBool::new())),
2954 (PortType::U128, PortType::F64) => Some(Box::new(W::U128ToF64::new())),
2955 (PortType::I128, PortType::F64) => Some(Box::new(W::I128ToF64::new())),
2956 (PortType::U128, PortType::Str) => Some(Box::new(W::U128ToString::new())),
2957 (PortType::I128, PortType::Str) => Some(Box::new(W::I128ToString::new())),
2958 (PortType::U128, PortType::Bytes) => Some(Box::new(W::U128ToBytes::new())),
2959 (PortType::I128, PortType::Bytes) => Some(Box::new(W::I128ToBytes::new())),
2960 (PortType::U128, PortType::Json) => Some(Box::new(W::U128ToJson::new())),
2961 (PortType::I128, PortType::Json) => Some(Box::new(W::I128ToJson::new())),
2962
2963 (from, to) if crate::library::register_view::is_reg_port(from) => {
2968 crate::library::register_view::reg_view(to)
2969 }
2970
2971 (PortType::VecI8, PortType::VecI16) => Some(Box::new(C::VecI8ToVecI16::new())),
2975 (PortType::VecI8, PortType::VecI32) => Some(Box::new(C::VecI8ToVecI32::new())),
2976 (PortType::VecI8, PortType::VecI64) => Some(Box::new(C::VecI8ToVecI64::new())),
2977 (PortType::VecI8, PortType::VecF16) => Some(Box::new(C::VecI8ToVecF16::new())),
2978 (PortType::VecI8, PortType::VecF32) => Some(Box::new(C::VecI8ToVecF32::new())),
2979 (PortType::VecI8, PortType::VecF64) => Some(Box::new(C::VecI8ToVecF64::new())),
2980 (PortType::VecI16, PortType::VecI32) => Some(Box::new(C::VecI16ToVecI32::new())),
2981 (PortType::VecI16, PortType::VecI64) => Some(Box::new(C::VecI16ToVecI64::new())),
2982 (PortType::VecI16, PortType::VecF32) => Some(Box::new(C::VecI16ToVecF32::new())),
2983 (PortType::VecI16, PortType::VecF64) => Some(Box::new(C::VecI16ToVecF64::new())),
2984 (PortType::VecI32, PortType::VecI64) => Some(Box::new(C::VecI32ToVecI64::new())),
2985 (PortType::VecI32, PortType::VecF64) => Some(Box::new(C::VecI32ToVecF64::new())),
2986 (PortType::VecI64, PortType::VecF64) => Some(Box::new(C::VecI64ToVecF64::new())),
2987 (PortType::VecF16, PortType::VecF32) => Some(Box::new(C::VecF16ToVecF32::new())),
2988 (PortType::VecF16, PortType::VecF64) => Some(Box::new(C::VecF16ToVecF64::new())),
2989 (PortType::VecF32, PortType::VecF64) => Some(Box::new(C::VecF32ToVecF64::new())),
2990 (PortType::VecF64, PortType::Bytes) => Some(Box::new(C::VecF64ToBytes::new())),
2991 (PortType::VecI64, PortType::Bytes) => Some(Box::new(C::VecI64ToBytes::new())),
2992 (PortType::VecF16, PortType::Bytes) => Some(Box::new(C::VecF16ToBytes::new())),
2993 (PortType::VecI16, PortType::Bytes) => Some(Box::new(C::VecI16ToBytes::new())),
2994 (PortType::VecI8, PortType::Bytes) => Some(Box::new(C::VecI8ToBytes::new())),
2995 (PortType::VecI64, PortType::Json) => Some(Box::new(C::VecI64ToJson::new())),
2996 (PortType::VecI16, PortType::Json) => Some(Box::new(C::VecI16ToJson::new())),
2997 (PortType::VecI8, PortType::Json) => Some(Box::new(C::VecI8ToJson::new())),
2998 (PortType::VecI32, PortType::Str) => Some(Box::new(P::VecI32ToStr::new())),
2999 (PortType::VecI64, PortType::Str) => Some(Box::new(C::VecI64ToStr::new())),
3000 (PortType::VecI16, PortType::Str) => Some(Box::new(C::VecI16ToStr::new())),
3001 (PortType::VecI8, PortType::Str) => Some(Box::new(C::VecI8ToStr::new())),
3002
3003 _ => None,
3004 }
3005}
3006
3007pub fn boundary_adapter(from: PortType, to: PortType) -> Option<Box<dyn PolydatNode>> {
3037 if let Some(adapter) = auto_adapter(from, to) {
3038 return Some(adapter);
3039 }
3040 use crate::library::convert::{StrToBool, StrToF64, StrToU64};
3041 use crate::library::polyfill as P;
3042 use crate::library::polyfill_128 as W;
3043 use crate::library::polyfill_complete as C;
3044 use crate::library::polyfill_narrow as N;
3045 match (from, to) {
3046 (PortType::U64, PortType::U32) => Some(Box::new(P::U64ToU32::new())),
3048 (PortType::U64, PortType::I64) => Some(Box::new(P::U64ToI64::new())),
3049 (PortType::U64, PortType::I32) => Some(Box::new(P::U64ToI32::new())),
3050 (PortType::U64, PortType::F32) => Some(Box::new(P::U64ToF32::new())),
3051 (PortType::U32, PortType::I32) => Some(Box::new(P::U32ToI32::new())),
3052 (PortType::U32, PortType::F32) => Some(Box::new(P::U32ToF32::new())),
3053 (PortType::I64, PortType::U64) => Some(Box::new(P::I64ToU64::new())),
3054 (PortType::I64, PortType::U32) => Some(Box::new(P::I64ToU32::new())),
3055 (PortType::I64, PortType::I32) => Some(Box::new(P::I64ToI32::new())),
3056 (PortType::I64, PortType::F32) => Some(Box::new(P::I64ToF32::new())),
3057 (PortType::I32, PortType::U64) => Some(Box::new(P::I32ToU64::new())),
3058 (PortType::I32, PortType::U32) => Some(Box::new(P::I32ToU32::new())),
3059 (PortType::I32, PortType::F32) => Some(Box::new(P::I32ToF32::new())),
3060 (PortType::F64, PortType::U64) => Some(Box::new(P::F64ToU64Checked::new())),
3061 (PortType::F64, PortType::U32) => Some(Box::new(P::F64ToU32::new())),
3062 (PortType::F64, PortType::I64) => Some(Box::new(P::F64ToI64::new())),
3063 (PortType::F64, PortType::I32) => Some(Box::new(P::F64ToI32::new())),
3064 (PortType::F64, PortType::F32) => Some(Box::new(P::F64ToF32::new())),
3065 (PortType::F32, PortType::U64) => Some(Box::new(P::F32ToU64::new())),
3066 (PortType::F32, PortType::U32) => Some(Box::new(P::F32ToU32::new())),
3067 (PortType::F32, PortType::I64) => Some(Box::new(P::F32ToI64::new())),
3068 (PortType::F32, PortType::I32) => Some(Box::new(P::F32ToI32::new())),
3069
3070 (PortType::Str, PortType::Bool) => Some(Box::new(StrToBool::new())),
3072 (PortType::Str, PortType::U64) => Some(Box::new(StrToU64::new())),
3073 (PortType::Str, PortType::F64) => Some(Box::new(StrToF64::new())),
3074 (PortType::Str, PortType::U32) => Some(Box::new(P::StrToU32::new())),
3075 (PortType::Str, PortType::I64) => Some(Box::new(P::StrToI64::new())),
3076 (PortType::Str, PortType::I32) => Some(Box::new(P::StrToI32::new())),
3077 (PortType::Str, PortType::F32) => Some(Box::new(P::StrToF32::new())),
3078 (PortType::Str, PortType::Bytes) => Some(Box::new(P::StrToBytes::new())),
3079 (PortType::Str, PortType::Json) => Some(Box::new(P::StrToJson::new())),
3080 (PortType::Str, PortType::VecF32) => Some(Box::new(P::StrToVecF32::new())),
3081 (PortType::Str, PortType::VecI32) => Some(Box::new(P::StrToVecI32::new())),
3082
3083 (PortType::Bytes, PortType::U64) => Some(Box::new(P::BytesToU64::new())),
3085 (PortType::Bytes, PortType::U32) => Some(Box::new(P::BytesToU32::new())),
3086 (PortType::Bytes, PortType::I64) => Some(Box::new(P::BytesToI64::new())),
3087 (PortType::Bytes, PortType::I32) => Some(Box::new(P::BytesToI32::new())),
3088 (PortType::Bytes, PortType::F64) => Some(Box::new(P::BytesToF64::new())),
3089 (PortType::Bytes, PortType::F32) => Some(Box::new(P::BytesToF32::new())),
3090 (PortType::Bytes, PortType::Bool) => Some(Box::new(P::BytesToBool::new())),
3091 (PortType::Bytes, PortType::Str) => Some(Box::new(P::BytesToStr::new())),
3092 (PortType::Bytes, PortType::Json) => Some(Box::new(P::BytesToJson::new())),
3093 (PortType::Bytes, PortType::VecF32) => Some(Box::new(P::BytesToVecF32::new())),
3094 (PortType::Bytes, PortType::VecI32) => Some(Box::new(P::BytesToVecI32::new())),
3095
3096 (PortType::Json, PortType::U64) => Some(Box::new(P::JsonToU64::new())),
3098 (PortType::Json, PortType::U32) => Some(Box::new(P::JsonToU32::new())),
3099 (PortType::Json, PortType::I64) => Some(Box::new(P::JsonToI64::new())),
3100 (PortType::Json, PortType::I32) => Some(Box::new(P::JsonToI32::new())),
3101 (PortType::Json, PortType::F64) => Some(Box::new(P::JsonToF64::new())),
3102 (PortType::Json, PortType::F32) => Some(Box::new(P::JsonToF32::new())),
3103 (PortType::Json, PortType::Bool) => Some(Box::new(P::JsonToBool::new())),
3104 (PortType::Json, PortType::Bytes) => Some(Box::new(P::JsonToBytes::new())),
3105 (PortType::Json, PortType::VecF32) => Some(Box::new(P::JsonToVecF32::new())),
3106 (PortType::Json, PortType::VecI32) => Some(Box::new(P::JsonToVecI32::new())),
3107
3108 (PortType::F64, PortType::Json) => Some(Box::new(P::F64ToJson::new())),
3110 (PortType::F32, PortType::Json) => Some(Box::new(P::F32ToJson::new())),
3111 (PortType::VecF32, PortType::Json) => Some(Box::new(P::VecF32ToJson::new())),
3112 (PortType::VecF32, PortType::Str) => Some(Box::new(P::VecF32ToStr::new())),
3113
3114 (PortType::VecF32, PortType::VecI32) => Some(Box::new(P::VecF32ToVecI32::new())),
3116
3117 (PortType::U64, PortType::U8) => Some(Box::new(N::U64ToU8::new())),
3121 (PortType::U32, PortType::U8) => Some(Box::new(N::U32ToU8::new())),
3122 (PortType::U16, PortType::U8) => Some(Box::new(N::U16ToU8::new())),
3123 (PortType::I64, PortType::U8) => Some(Box::new(N::I64ToU8::new())),
3124 (PortType::F64, PortType::U8) => Some(Box::new(N::F64ToU8::new())),
3125 (PortType::U64, PortType::U16) => Some(Box::new(N::U64ToU16::new())),
3126 (PortType::U32, PortType::U16) => Some(Box::new(N::U32ToU16::new())),
3127 (PortType::I64, PortType::U16) => Some(Box::new(N::I64ToU16::new())),
3128 (PortType::F64, PortType::U16) => Some(Box::new(N::F64ToU16::new())),
3129 (PortType::I64, PortType::I8) => Some(Box::new(N::I64ToI8::new())),
3130 (PortType::I32, PortType::I8) => Some(Box::new(N::I32ToI8::new())),
3131 (PortType::U64, PortType::I8) => Some(Box::new(N::U64ToI8::new())),
3132 (PortType::F64, PortType::I8) => Some(Box::new(N::F64ToI8::new())),
3133 (PortType::I64, PortType::I16) => Some(Box::new(N::I64ToI16::new())),
3134 (PortType::I32, PortType::I16) => Some(Box::new(N::I32ToI16::new())),
3135 (PortType::U64, PortType::I16) => Some(Box::new(N::U64ToI16::new())),
3136 (PortType::F64, PortType::I16) => Some(Box::new(N::F64ToI16::new())),
3137 (PortType::F64, PortType::F16) => Some(Box::new(N::F64ToF16::new())),
3138 (PortType::F32, PortType::F16) => Some(Box::new(N::F32ToF16::new())),
3139 (PortType::U64, PortType::F16) => Some(Box::new(N::U64ToF16::new())),
3140 (PortType::Str, PortType::U8) => Some(Box::new(N::StrToU8::new())),
3141 (PortType::Str, PortType::U16) => Some(Box::new(N::StrToU16::new())),
3142 (PortType::Str, PortType::I8) => Some(Box::new(N::StrToI8::new())),
3143 (PortType::Str, PortType::I16) => Some(Box::new(N::StrToI16::new())),
3144 (PortType::Str, PortType::F16) => Some(Box::new(N::StrToF16::new())),
3145 (PortType::Bytes, PortType::U8) => Some(Box::new(N::BytesToU8::new())),
3146 (PortType::Bytes, PortType::U16) => Some(Box::new(N::BytesToU16::new())),
3147 (PortType::Bytes, PortType::I8) => Some(Box::new(N::BytesToI8::new())),
3148 (PortType::Bytes, PortType::I16) => Some(Box::new(N::BytesToI16::new())),
3149 (PortType::Bytes, PortType::F16) => Some(Box::new(N::BytesToF16::new())),
3150 (PortType::Json, PortType::U8) => Some(Box::new(N::JsonToU8::new())),
3151 (PortType::Json, PortType::U16) => Some(Box::new(N::JsonToU16::new())),
3152 (PortType::Json, PortType::I8) => Some(Box::new(N::JsonToI8::new())),
3153 (PortType::Json, PortType::I16) => Some(Box::new(N::JsonToI16::new())),
3154 (PortType::Json, PortType::F16) => Some(Box::new(N::JsonToF16::new())),
3155 (PortType::F16, PortType::Json) => Some(Box::new(N::F16ToJson::new())),
3157
3158 (PortType::U128, PortType::U64) => Some(Box::new(W::U128ToU64::new())),
3160 (PortType::I128, PortType::I64) => Some(Box::new(W::I128ToI64::new())),
3161 (PortType::I64, PortType::U128) => Some(Box::new(W::I64ToU128::new())),
3162 (PortType::U128, PortType::I128) => Some(Box::new(W::U128ToI128::new())),
3163 (PortType::I128, PortType::U128) => Some(Box::new(W::I128ToU128::new())),
3164 (PortType::F64, PortType::U128) => Some(Box::new(W::F64ToU128::new())),
3165 (PortType::F64, PortType::I128) => Some(Box::new(W::F64ToI128::new())),
3166 (PortType::Str, PortType::U128) => Some(Box::new(W::StrToU128::new())),
3167 (PortType::Str, PortType::I128) => Some(Box::new(W::StrToI128::new())),
3168 (PortType::Bytes, PortType::U128) => Some(Box::new(W::BytesToU128::new())),
3169 (PortType::Bytes, PortType::I128) => Some(Box::new(W::BytesToI128::new())),
3170 (PortType::Json, PortType::U128) => Some(Box::new(W::JsonToU128::new())),
3171 (PortType::Json, PortType::I128) => Some(Box::new(W::JsonToI128::new())),
3172
3173 (PortType::U8, PortType::I8) => Some(Box::new(C::U8ToI8::new())),
3178 (PortType::I8, PortType::U8) => Some(Box::new(C::I8ToU8::new())),
3179 (PortType::I8, PortType::U16) => Some(Box::new(C::I8ToU16::new())),
3180 (PortType::I8, PortType::U32) => Some(Box::new(C::I8ToU32::new())),
3181 (PortType::I8, PortType::U64) => Some(Box::new(C::I8ToU64::new())),
3182 (PortType::I8, PortType::U128) => Some(Box::new(C::I8ToU128::new())),
3183 (PortType::U16, PortType::I8) => Some(Box::new(C::U16ToI8::new())),
3184 (PortType::U16, PortType::I16) => Some(Box::new(C::U16ToI16::new())),
3185 (PortType::U16, PortType::F16) => Some(Box::new(C::U16ToF16::new())),
3186 (PortType::I16, PortType::U8) => Some(Box::new(C::I16ToU8::new())),
3187 (PortType::I16, PortType::I8) => Some(Box::new(C::I16ToI8::new())),
3188 (PortType::I16, PortType::U16) => Some(Box::new(C::I16ToU16::new())),
3189 (PortType::I16, PortType::F16) => Some(Box::new(C::I16ToF16::new())),
3190 (PortType::I16, PortType::U32) => Some(Box::new(C::I16ToU32::new())),
3191 (PortType::I16, PortType::U64) => Some(Box::new(C::I16ToU64::new())),
3192 (PortType::I16, PortType::U128) => Some(Box::new(C::I16ToU128::new())),
3193 (PortType::U32, PortType::I8) => Some(Box::new(C::U32ToI8::new())),
3194 (PortType::U32, PortType::I16) => Some(Box::new(C::U32ToI16::new())),
3195 (PortType::U32, PortType::F16) => Some(Box::new(C::U32ToF16::new())),
3196 (PortType::I32, PortType::U8) => Some(Box::new(C::I32ToU8::new())),
3197 (PortType::I32, PortType::U16) => Some(Box::new(C::I32ToU16::new())),
3198 (PortType::I32, PortType::F16) => Some(Box::new(C::I32ToF16::new())),
3199 (PortType::I32, PortType::U128) => Some(Box::new(C::I32ToU128::new())),
3200 (PortType::F16, PortType::U8) => Some(Box::new(C::F16ToU8::new())),
3201 (PortType::F16, PortType::I8) => Some(Box::new(C::F16ToI8::new())),
3202 (PortType::F16, PortType::U16) => Some(Box::new(C::F16ToU16::new())),
3203 (PortType::F16, PortType::I16) => Some(Box::new(C::F16ToI16::new())),
3204 (PortType::F16, PortType::U32) => Some(Box::new(C::F16ToU32::new())),
3205 (PortType::F16, PortType::I32) => Some(Box::new(C::F16ToI32::new())),
3206 (PortType::F16, PortType::U64) => Some(Box::new(C::F16ToU64::new())),
3207 (PortType::F16, PortType::I64) => Some(Box::new(C::F16ToI64::new())),
3208 (PortType::F16, PortType::U128) => Some(Box::new(C::F16ToU128::new())),
3209 (PortType::F16, PortType::I128) => Some(Box::new(C::F16ToI128::new())),
3210 (PortType::F32, PortType::U8) => Some(Box::new(C::F32ToU8::new())),
3211 (PortType::F32, PortType::I8) => Some(Box::new(C::F32ToI8::new())),
3212 (PortType::F32, PortType::U16) => Some(Box::new(C::F32ToU16::new())),
3213 (PortType::F32, PortType::I16) => Some(Box::new(C::F32ToI16::new())),
3214 (PortType::F32, PortType::U128) => Some(Box::new(C::F32ToU128::new())),
3215 (PortType::F32, PortType::I128) => Some(Box::new(C::F32ToI128::new())),
3216 (PortType::I64, PortType::F16) => Some(Box::new(C::I64ToF16::new())),
3217 (PortType::U128, PortType::U8) => Some(Box::new(C::U128ToU8::new())),
3218 (PortType::U128, PortType::I8) => Some(Box::new(C::U128ToI8::new())),
3219 (PortType::U128, PortType::U16) => Some(Box::new(C::U128ToU16::new())),
3220 (PortType::U128, PortType::I16) => Some(Box::new(C::U128ToI16::new())),
3221 (PortType::U128, PortType::F16) => Some(Box::new(C::U128ToF16::new())),
3222 (PortType::U128, PortType::U32) => Some(Box::new(C::U128ToU32::new())),
3223 (PortType::U128, PortType::I32) => Some(Box::new(C::U128ToI32::new())),
3224 (PortType::U128, PortType::F32) => Some(Box::new(C::U128ToF32::new())),
3225 (PortType::U128, PortType::I64) => Some(Box::new(C::U128ToI64::new())),
3226 (PortType::I128, PortType::U8) => Some(Box::new(C::I128ToU8::new())),
3227 (PortType::I128, PortType::I8) => Some(Box::new(C::I128ToI8::new())),
3228 (PortType::I128, PortType::U16) => Some(Box::new(C::I128ToU16::new())),
3229 (PortType::I128, PortType::I16) => Some(Box::new(C::I128ToI16::new())),
3230 (PortType::I128, PortType::F16) => Some(Box::new(C::I128ToF16::new())),
3231 (PortType::I128, PortType::U32) => Some(Box::new(C::I128ToU32::new())),
3232 (PortType::I128, PortType::I32) => Some(Box::new(C::I128ToI32::new())),
3233 (PortType::I128, PortType::F32) => Some(Box::new(C::I128ToF32::new())),
3234 (PortType::I128, PortType::U64) => Some(Box::new(C::I128ToU64::new())),
3235
3236 (PortType::VecI16, PortType::VecI8) => Some(Box::new(C::VecI16ToVecI8::new())),
3240 (PortType::VecI16, PortType::VecF16) => Some(Box::new(C::VecI16ToVecF16::new())),
3241 (PortType::VecI32, PortType::VecI8) => Some(Box::new(C::VecI32ToVecI8::new())),
3242 (PortType::VecI32, PortType::VecI16) => Some(Box::new(C::VecI32ToVecI16::new())),
3243 (PortType::VecI32, PortType::VecF16) => Some(Box::new(C::VecI32ToVecF16::new())),
3244 (PortType::VecI64, PortType::VecI8) => Some(Box::new(C::VecI64ToVecI8::new())),
3245 (PortType::VecI64, PortType::VecI16) => Some(Box::new(C::VecI64ToVecI16::new())),
3246 (PortType::VecI64, PortType::VecI32) => Some(Box::new(C::VecI64ToVecI32::new())),
3247 (PortType::VecI64, PortType::VecF16) => Some(Box::new(C::VecI64ToVecF16::new())),
3248 (PortType::VecI64, PortType::VecF32) => Some(Box::new(C::VecI64ToVecF32::new())),
3249 (PortType::VecF16, PortType::VecI8) => Some(Box::new(C::VecF16ToVecI8::new())),
3250 (PortType::VecF16, PortType::VecI16) => Some(Box::new(C::VecF16ToVecI16::new())),
3251 (PortType::VecF16, PortType::VecI32) => Some(Box::new(C::VecF16ToVecI32::new())),
3252 (PortType::VecF16, PortType::VecI64) => Some(Box::new(C::VecF16ToVecI64::new())),
3253 (PortType::VecF32, PortType::VecI8) => Some(Box::new(C::VecF32ToVecI8::new())),
3254 (PortType::VecF32, PortType::VecI16) => Some(Box::new(C::VecF32ToVecI16::new())),
3255 (PortType::VecF32, PortType::VecI64) => Some(Box::new(C::VecF32ToVecI64::new())),
3256 (PortType::VecF32, PortType::VecF16) => Some(Box::new(C::VecF32ToVecF16::new())),
3257 (PortType::VecF64, PortType::VecI8) => Some(Box::new(C::VecF64ToVecI8::new())),
3258 (PortType::VecF64, PortType::VecI16) => Some(Box::new(C::VecF64ToVecI16::new())),
3259 (PortType::VecF64, PortType::VecI32) => Some(Box::new(C::VecF64ToVecI32::new())),
3260 (PortType::VecF64, PortType::VecI64) => Some(Box::new(C::VecF64ToVecI64::new())),
3261 (PortType::VecF64, PortType::VecF16) => Some(Box::new(C::VecF64ToVecF16::new())),
3262 (PortType::VecF64, PortType::VecF32) => Some(Box::new(C::VecF64ToVecF32::new())),
3263 (PortType::Bytes, PortType::VecF64) => Some(Box::new(C::BytesToVecF64::new())),
3264 (PortType::Bytes, PortType::VecI64) => Some(Box::new(C::BytesToVecI64::new())),
3265 (PortType::Bytes, PortType::VecF16) => Some(Box::new(C::BytesToVecF16::new())),
3266 (PortType::Bytes, PortType::VecI16) => Some(Box::new(C::BytesToVecI16::new())),
3267 (PortType::Bytes, PortType::VecI8) => Some(Box::new(C::BytesToVecI8::new())),
3268 (PortType::VecF64, PortType::Json) => Some(Box::new(C::VecF64ToJson::new())),
3269 (PortType::VecF16, PortType::Json) => Some(Box::new(C::VecF16ToJson::new())),
3270 (PortType::Json, PortType::VecF64) => Some(Box::new(C::JsonToVecF64::new())),
3271 (PortType::Json, PortType::VecI64) => Some(Box::new(C::JsonToVecI64::new())),
3272 (PortType::Json, PortType::VecF16) => Some(Box::new(C::JsonToVecF16::new())),
3273 (PortType::Json, PortType::VecI16) => Some(Box::new(C::JsonToVecI16::new())),
3274 (PortType::Json, PortType::VecI8) => Some(Box::new(C::JsonToVecI8::new())),
3275 (PortType::VecF64, PortType::Str) => Some(Box::new(C::VecF64ToStr::new())),
3276 (PortType::VecF16, PortType::Str) => Some(Box::new(C::VecF16ToStr::new())),
3277 (PortType::Str, PortType::VecF64) => Some(Box::new(C::StrToVecF64::new())),
3278 (PortType::Str, PortType::VecI64) => Some(Box::new(C::StrToVecI64::new())),
3279 (PortType::Str, PortType::VecF16) => Some(Box::new(C::StrToVecF16::new())),
3280 (PortType::Str, PortType::VecI16) => Some(Box::new(C::StrToVecI16::new())),
3281 (PortType::Str, PortType::VecI8) => Some(Box::new(C::StrToVecI8::new())),
3282
3283 _ => None,
3284 }
3285}
3286
3287use crate::compile::select::{Engine, KernelError, Provenance};
3290use crate::kernel::Kernel;
3291
3292fn fixed_outputs(resolved: &ResolvedDag) -> std::collections::HashSet<String> {
3295 let classes = PolydatProgram::classify_lifecycle(
3296 &resolved.nodes,
3297 &resolved.wiring,
3298 &resolved.input_defs,
3299 &resolved.output_map,
3300 &resolved.output_modifiers,
3301 );
3302 resolved
3303 .output_map
3304 .iter()
3305 .filter(|(name, (node, _))| {
3306 resolved.const_outputs.contains(*name)
3307 || classes.lifecycle[*node] == crate::kernel::EvalLifecycle::CompileConst
3308 })
3309 .map(|(name, _)| name.clone())
3310 .collect()
3311}
3312
3313impl PolydatAssembler {
3314 pub fn compile_with(self, engine: Engine) -> Result<Box<dyn Kernel>, KernelError> {
3322 self.compile_engine_with_log(engine, None)
3323 }
3324
3325 pub fn compile_kernel(self) -> Result<Box<dyn Kernel>, KernelError> {
3328 self.compile_with(Engine::default())
3329 }
3330
3331 pub fn compile_engine_with_log(
3334 self,
3335 engine: Engine,
3336 log: Option<&mut crate::dsl::events::CompileEventLog>,
3337 ) -> Result<Box<dyn Kernel>, KernelError> {
3338 match engine {
3339 Engine::Interpreter(cones) => {
3342 let mut asm = self;
3343 asm.jit_mode = Some(cones);
3344 Ok(Box::new(asm.compile_with_log(log)?))
3345 }
3346 _ => Ok(self.compile_slots_with_log(engine, log)?),
3350 }
3351 }
3352
3353 pub fn compile_slots(
3369 self,
3370 engine: Engine,
3371 ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3372 self.compile_slots_with_log(engine, None)
3373 }
3374
3375 pub fn compile_slots_with_log(
3378 self,
3379 engine: Engine,
3380 log: Option<&mut crate::dsl::events::CompileEventLog>,
3381 ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3382 let template = self.template;
3383 let mut kernel = self.build_slots_with_log(engine, log)?;
3384 if !template {
3385 crate::kernel::Kernel::init(kernel.as_mut())?;
3386 }
3387 Ok(kernel)
3388 }
3389
3390 fn build_slots_with_log(
3392 self,
3393 engine: Engine,
3394 mut log: Option<&mut crate::dsl::events::CompileEventLog>,
3395 ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3396 let refused = |reason: String| KernelError::Refused { engine, reason };
3397 let asked = |e: KernelError| match e {
3402 KernelError::Refused { reason, .. } => KernelError::Refused { engine, reason },
3403 other => other,
3404 };
3405 let strict = self.strict;
3406 match engine {
3407 Engine::Interpreter(_) => Err(refused(
3408 "the interpreter has no slot buffer: its buffers are typed `Value`s, so \
3409 there is no slot to name. Ask for `closures`, `native` or `pure-native` \
3410 for the slot surface, or compile with `compile_with` and drive the \
3411 kernel through the `Kernel` trait, which every engine answers."
3412 .into(),
3413 )),
3414 Engine::Closures(prov) => {
3415 let resolved = self.resolve_with_log(log.as_deref_mut())?;
3416 if strict {
3417 Self::refuse_strict(&resolved)?;
3418 }
3419 let folded = log.is_some().then(|| Self::constant_sites(&resolved));
3420 let (node_total, output_total) =
3421 (resolved.nodes.len(), resolved.output_order.len());
3422 let kernel = Self::closures_from(resolved, prov).map_err(asked)?;
3423 Self::log_folded(kernel.as_ref(), folded, log.as_deref_mut());
3424 Self::log_summary(log, node_total, output_total);
3425 Ok(kernel)
3426 }
3427 Engine::Native(prov) => {
3436 {
3437 let resolved = self.resolve_with_log(log.as_deref_mut())?;
3438 if strict {
3439 Self::refuse_strict(&resolved)?;
3440 }
3441 let folded = log.is_some().then(|| Self::constant_sites(&resolved));
3442 let (node_total, output_total) =
3443 (resolved.nodes.len(), resolved.output_order.len());
3444 if prov == Provenance::Push {
3450 return Err(refused(
3451 "native code has no push-only kernel: push-side invalidation \
3452 without the cone guard has no native form. Ask for `pushpull` \
3453 for both, `pull` for the guard alone, or `auto` to let the \
3454 selector choose; `push` alone is available on the closure tier."
3455 .into(),
3456 ));
3457 }
3458 let prov = Self::provenance_for(prov, &resolved);
3459 let kernel = Self::hybrid_from(resolved).map_err(asked)?;
3460 let kernel: Box<dyn crate::compile::SlotKernel> = match prov {
3461 Provenance::Raw => Box::new(kernel.into_raw()),
3462 Provenance::Pull => Box::new(kernel.into_pull()),
3463 Provenance::PushPull | Provenance::Auto => Box::new(kernel),
3469 Provenance::Push => {
3470 return Err(refused("native code has no push-only kernel".into()));
3471 }
3472 };
3473 Self::log_folded(kernel.as_ref(), folded, log.as_deref_mut());
3474 Self::log_summary(log, node_total, output_total);
3475 Ok(kernel)
3476 }
3477 }
3478 Engine::PureNative(prov) => {
3479 #[cfg(feature = "jit")]
3480 {
3481 let resolved = self.resolve_with_log(log.as_deref_mut())?;
3482 if strict {
3483 Self::refuse_strict(&resolved)?;
3484 }
3485 let folded = log.is_some().then(|| Self::constant_sites(&resolved));
3486 let (node_total, output_total) =
3487 (resolved.nodes.len(), resolved.output_order.len());
3488 let prov = match prov {
3495 Provenance::Auto => match Self::provenance_for(prov, &resolved) {
3496 Provenance::Raw => Provenance::Raw,
3497 _ => Provenance::PushPull,
3498 },
3499 named @ (Provenance::Raw | Provenance::PushPull) => named,
3500 other => {
3501 return Err(refused(format!(
3502 "pure native code has no {} kernel: the tier keeps only the \
3503 two forms the differential needs. Ask for `raw` or \
3504 `pushpull`, or `auto` to let the selector choose; every \
3505 mode is available on `native`.",
3506 format!("{other:?}").to_lowercase(),
3507 )));
3508 }
3509 };
3510 let kernel: Box<dyn crate::compile::SlotKernel> = match prov {
3511 Provenance::Raw => Box::new(Self::jit_raw_from(resolved).map_err(asked)?),
3512 _ => Box::new(Self::jit_push_pull_from(resolved).map_err(asked)?),
3513 };
3514 Self::log_folded(kernel.as_ref(), folded, log.as_deref_mut());
3515 Self::log_summary(log, node_total, output_total);
3516 Ok(kernel)
3517 }
3518 #[cfg(not(feature = "jit"))]
3519 {
3520 let _ = (prov, log);
3521 Err(refused(
3522 "this build has no native code (the `jit` feature is off)".into(),
3523 ))
3524 }
3525 }
3526 }
3527 }
3528
3529 fn constant_sites(resolved: &ResolvedDag) -> Vec<(String, usize, crate::ast::PortType)> {
3534 let classes = PolydatProgram::classify_lifecycle(
3535 &resolved.nodes,
3536 &resolved.wiring,
3537 &resolved.input_defs,
3538 &resolved.output_map,
3539 &resolved.output_modifiers,
3540 );
3541 let layout = slot_layout(resolved);
3542 resolved
3543 .nodes
3544 .iter()
3545 .enumerate()
3546 .filter(|(i, n)| {
3547 classes.lifecycle[*i] == crate::kernel::EvalLifecycle::CompileConst
3548 && n.meta().outs.len() == 1
3549 })
3550 .map(|(i, n)| {
3551 (
3552 n.meta().name.clone(),
3553 layout.port_offsets[i][0],
3554 n.meta().outs[0].typ,
3555 )
3556 })
3557 .collect()
3558 }
3559
3560 fn log_folded(
3563 kernel: &dyn Kernel,
3564 sites: Option<Vec<(String, usize, crate::ast::PortType)>>,
3565 log: Option<&mut crate::dsl::events::CompileEventLog>,
3566 ) {
3567 let (Some(sites), Some(log)) = (sites, log) else {
3568 return;
3569 };
3570 for (node, slot, ty) in sites {
3571 let value = crate::kernel::KernelInternals::slot_value(kernel, slot, ty);
3572 if !matches!(value, crate::ast::Value::None) {
3573 log.push(crate::dsl::events::CompileEvent::ConstantFolded {
3574 node,
3575 value: value.to_display_string(),
3576 });
3577 }
3578 }
3579 }
3580
3581 fn provenance_for(prov: Provenance, resolved: &ResolvedDag) -> Provenance {
3586 match prov {
3587 Provenance::Auto => {
3588 let analysis =
3589 select::analyze_graph(&resolved.nodes, &resolved.wiring, &resolved.output_map);
3590 match select::select_prov_mode(&analysis) {
3591 ProvMode::Raw => Provenance::Raw,
3592 ProvMode::Pull => Provenance::Pull,
3593 ProvMode::PushPull => Provenance::PushPull,
3594 }
3595 }
3596 p => p,
3597 }
3598 }
3599
3600 fn closures_from(
3603 resolved: ResolvedDag,
3604 prov: Provenance,
3605 ) -> Result<Box<dyn crate::compile::SlotKernel>, KernelError> {
3606 let prov = Self::provenance_for(prov, &resolved);
3607 let (coord_count, total_slots, steps, output_map, ref_slots, extras) =
3608 Self::build_p2_layout(&resolved).map_err(Self::refused_by_closures)?;
3609 let dependents = || {
3610 slot_layout(&resolved).expand_dependents(
3611 &resolved,
3612 &PolydatProgram::compute_dependents(
3613 &PolydatProgram::compute_provenance(&resolved.nodes, &resolved.wiring),
3614 resolved.input_defs.len(),
3615 ),
3616 )
3617 };
3618 Ok(match prov {
3619 Provenance::Raw => Box::new(CompiledKernelRaw::new(
3620 coord_count,
3621 total_slots,
3622 steps,
3623 output_map,
3624 ref_slots,
3625 extras,
3626 )?),
3627 Provenance::Push => Box::new(CompiledKernelPush::new(
3628 coord_count,
3629 total_slots,
3630 steps,
3631 output_map,
3632 dependents(),
3633 ref_slots,
3634 extras,
3635 )?),
3636 Provenance::Pull => Box::new(CompiledKernelPull::new(
3637 coord_count,
3638 total_slots,
3639 steps,
3640 output_map,
3641 &dependents(),
3642 ref_slots,
3643 extras,
3644 )?),
3645 Provenance::PushPull | Provenance::Auto => Box::new(CompiledKernelPushPull::new(
3646 coord_count,
3647 total_slots,
3648 steps,
3649 output_map,
3650 dependents(),
3651 ref_slots,
3652 extras,
3653 )?),
3654 })
3655 }
3656}
3657
3658#[cfg(test)]
3659mod strict_values_tests {
3660 use super::*;
3661 use crate::ast::{NodeMeta, Port, Slot, Value};
3662 use crate::dsl::const_constraints::ConstConstraint;
3663 use crate::dsl::events::{CompileEvent, CompileEventLog};
3664
3665 struct NonZeroSink {
3667 meta: NodeMeta,
3668 }
3669
3670 impl NonZeroSink {
3671 fn new() -> Self {
3672 let mut port = Port::u64("divisor");
3673 port.constraint = Some(ConstConstraint::NonZeroU64);
3674 NonZeroSink {
3675 meta: NodeMeta {
3676 name: "nonzero_sink".into(),
3677 ins: vec![Slot::Wire(port)],
3678 outs: vec![Port::u64("output")],
3679 },
3680 }
3681 }
3682 }
3683
3684 impl PolydatNode for NonZeroSink {
3685 fn meta(&self) -> &NodeMeta {
3686 &self.meta
3687 }
3688 fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
3689 outputs[0] = inputs[0].clone();
3690 }
3691 }
3692
3693 fn inserted(asm: PolydatAssembler) -> usize {
3694 let mut log = CompileEventLog::new();
3695 asm.resolve_with_log(Some(&mut log)).expect("resolve");
3696 log.events()
3697 .iter()
3698 .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
3699 .count()
3700 }
3701
3702 #[test]
3706 fn an_upstream_assertion_for_another_constraint_is_not_proof() {
3707 let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3708 asm.add_node(
3709 "ranged",
3710 crate::library::assertions::assert_value_node(
3711 PortType::U64,
3712 ConstConstraint::RangeU64 { min: 0, max: 10 },
3713 ),
3714 vec![WireRef::input("cycle")],
3715 );
3716 asm.add_node(
3717 "sink",
3718 Box::new(NonZeroSink::new()),
3719 vec![WireRef::node("ranged")],
3720 );
3721 asm.add_output("out", WireRef::node("sink"));
3722 asm.set_strict_wires(false, true);
3723 assert_eq!(inserted(asm), 1);
3724 }
3725
3726 #[test]
3729 fn a_guard_like_name_is_not_proof() {
3730 let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3731 asm.add_node(
3732 "__assert_v_0",
3733 Box::new(crate::library::identity::Identity::new(PortType::U64)),
3734 vec![WireRef::input("cycle")],
3735 );
3736 asm.add_node(
3737 "sink",
3738 Box::new(NonZeroSink::new()),
3739 vec![WireRef::node("__assert_v_0")],
3740 );
3741 asm.add_output("out", WireRef::node("sink"));
3742 asm.set_strict_wires(false, true);
3743 assert_eq!(inserted(asm), 1);
3744 }
3745
3746 #[test]
3750 fn scope_strictness_marks_only_the_nodes_added_under_it() {
3751 let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3752 let before = asm.set_scope_strict_values(Some(true));
3753 assert_eq!(before, None);
3754 asm.add_node(
3755 "inner",
3756 Box::new(NonZeroSink::new()),
3757 vec![WireRef::input("cycle")],
3758 );
3759 asm.set_scope_strict_values(before);
3760 asm.add_node(
3761 "outer",
3762 Box::new(NonZeroSink::new()),
3763 vec![WireRef::input("cycle")],
3764 );
3765 asm.add_output("a", WireRef::node("inner"));
3766 asm.add_output("b", WireRef::node("outer"));
3767 assert_eq!(inserted(asm), 1);
3768 }
3769
3770 #[test]
3774 fn a_non_strict_scope_is_unchecked_under_a_strict_program() {
3775 let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
3776 let before = asm.set_scope_strict_values(Some(false));
3777 asm.add_node(
3778 "inner",
3779 Box::new(NonZeroSink::new()),
3780 vec![WireRef::input("cycle")],
3781 );
3782 asm.set_scope_strict_values(before);
3783 asm.add_node(
3784 "outer",
3785 Box::new(NonZeroSink::new()),
3786 vec![WireRef::input("cycle")],
3787 );
3788 asm.add_output("a", WireRef::node("inner"));
3789 asm.add_output("b", WireRef::node("outer"));
3790 asm.set_strict_wires(false, true);
3791 assert_eq!(inserted(asm), 1);
3792 }
3793}