1use std::cell::RefCell;
36use std::collections::HashMap;
37use std::rc::Rc;
38use std::sync::Arc;
39
40use async_recursion::async_recursion;
41
42use crate::ast::stmt::{
43 BinaryOpKind, Block, ClosureBody, CompressionCodec, ExpectedOutput, Expr, Literal, MatchArm,
44 ReadSource, Stmt, TypeExpr,
45};
46
47const TEST_ONLY_STMT_ERR: &str =
50 "test-only statement outside the test runner — run it with `largo test`";
51
52fn shrink_candidates(v: &RuntimeValue) -> Vec<RuntimeValue> {
54 match v {
55 RuntimeValue::Int(0) => vec![],
56 RuntimeValue::Int(n) => {
57 let mut out = vec![RuntimeValue::Int(0), RuntimeValue::Int(n / 2)];
58 out.push(RuntimeValue::Int(if *n > 0 { n - 1 } else { n + 1 }));
60 out.retain(|c| c != v);
61 out
62 }
63 RuntimeValue::Bool(true) => vec![RuntimeValue::Bool(false)],
64 _ => vec![],
65 }
66}
67
68fn map_obs_category(c: logicaffeine_language::ast::stmt::ObsCategory) -> crate::observe::ObsCat {
70 use logicaffeine_language::ast::stmt::ObsCategory;
71 match c {
72 ObsCategory::Note => crate::observe::ObsCat::Note,
73 ObsCategory::Warn => crate::observe::ObsCat::Warn,
74 ObsCategory::Record => crate::observe::ObsCat::Record,
75 }
76}
77
78fn format_expect_failure(
82 condition_text: &str,
83 annotations: &[(String, String)],
84 hint: Option<&str>,
85) -> String {
86 let mut s = format!("Expected that {condition_text}.");
87 for (text, value) in annotations {
88 s.push_str(&format!("\n {text} → {value}"));
89 }
90 if let Some(h) = hint {
91 s.push_str(&format!("\n Hint: {h}"));
92 }
93 s
94}
95use crate::intern::{Interner, Symbol};
96
97fn wire_compression_of(codec: CompressionCodec) -> crate::concurrency::marshal::WireCompression {
99 use crate::concurrency::marshal::WireCompression;
100 match codec {
101 CompressionCodec::Deflate => WireCompression::Deflate,
102 CompressionCodec::Lz4 => WireCompression::Lz4,
103 CompressionCodec::Zstd => WireCompression::Zstd,
104 }
105}
106use crate::analysis::{PolicyCondition, PolicyRegistry};
107
108use crate::concurrency::bridge::{BlockingRequest, Yield, YieldFuture, YieldState};
110use crate::concurrency::driver::{ErrSink, InterpreterTask};
111use crate::concurrency::marshal;
112#[cfg(not(target_arch = "wasm32"))]
113use crate::semantics::world::PageWorld;
114use logicaffeine_runtime::{ChanId, RtPayload, SelectArm, TaskId};
115use logicaffeine_system::fs::Vfs;
116
117pub type OutputCallback = Rc<RefCell<dyn FnMut(String)>>;
120
121#[derive(Debug, Clone)]
128pub struct StructValue {
129 pub type_name: String,
130 pub fields: HashMap<String, RuntimeValue>,
131}
132
133struct Place {
136 root: Symbol,
137 steps: Vec<PlaceStep>,
138}
139
140enum PlaceStep {
142 Field(String),
144 Item(RuntimeValue),
146}
147
148enum PlaceShape<'e, 'a> {
150 Field(Symbol),
151 Item(&'e Expr<'a>),
152}
153
154fn place_shape<'e, 'a>(e: &'e Expr<'a>) -> Option<(Symbol, Vec<PlaceShape<'e, 'a>>)> {
157 match e {
158 Expr::Identifier(root) => Some((*root, Vec::new())),
159 Expr::FieldAccess { object, field } => {
160 let (root, mut steps) = place_shape(object)?;
161 steps.push(PlaceShape::Field(*field));
162 Some((root, steps))
163 }
164 Expr::Index { collection, index } => {
165 let (root, mut steps) = place_shape(collection)?;
166 steps.push(PlaceShape::Item(index));
167 Some((root, steps))
168 }
169 _ => None,
170 }
171}
172
173fn own_collection(value: &mut RuntimeValue) {
177 fn shared<T>(rc: &Rc<T>) -> bool {
178 Rc::strong_count(rc) > 1 || Rc::weak_count(rc) > 0
179 }
180 match value {
181 RuntimeValue::List(rc) if shared(rc) => {
182 let own = Rc::new(RefCell::new(rc.borrow().clone()));
183 *rc = own;
184 }
185 RuntimeValue::Map(rc) if shared(rc) => {
186 let own = Rc::new(RefCell::new(rc.borrow().clone()));
187 *rc = own;
188 }
189 RuntimeValue::Set(rc) if shared(rc) => {
190 let own = Rc::new(RefCell::new(rc.borrow().clone()));
191 *rc = own;
192 }
193 _ => {}
194 }
195}
196
197fn step_into<'v>(value: &'v mut RuntimeValue, step: &PlaceStep) -> Option<&'v mut RuntimeValue> {
201 match (value, step) {
202 (RuntimeValue::Struct(s), PlaceStep::Field(name)) => s.fields.get_mut(name),
203 (RuntimeValue::Struct(s), PlaceStep::Item(RuntimeValue::Text(name))) => {
204 s.fields.get_mut(name.as_str())
205 }
206 (RuntimeValue::List(rc), PlaceStep::Item(RuntimeValue::Int(k))) => {
207 let items = Rc::get_mut(rc)?.get_mut();
208 let position = logicaffeine_data::logos_offset(*k, items.len())?;
209 items.make_boxed().get_mut(position)
210 }
211 (RuntimeValue::Map(rc), PlaceStep::Item(key)) => Rc::get_mut(rc)?.get_mut().get_mut(key),
212 _ => None,
213 }
214}
215
216pub fn default_for_declared_type(type_name: &str) -> RuntimeValue {
225 if let Some(c) = crdt_for_declared_type(type_name) {
226 return c;
227 }
228 match type_name {
229 "Int" | "Element" | "Event" | "View" | "Byte" => RuntimeValue::Int(0),
230 "Float" => RuntimeValue::Float(0.0),
231 "Bool" => RuntimeValue::Bool(false),
232 "Text" | "String" => RuntimeValue::Text(Rc::new(String::new())),
233 "Char" => RuntimeValue::Char('\0'),
234 "Seq" | "List" => RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))),
235 "Set" | "HashSet" => RuntimeValue::Set(Rc::new(RefCell::new(vec![]))),
236 "Map" | "HashMap" => RuntimeValue::Map(Rc::new(RefCell::new(MapStorage::default()))),
237 _ => RuntimeValue::Nothing,
238 }
239}
240
241pub fn crdt_for_declared_type(type_name: &str) -> Option<RuntimeValue> {
252 let kind = crate::semantics::crdt::CrdtKind::of_type_name(type_name)?;
253 Some(RuntimeValue::Crdt(Rc::new(RefCell::new(kind.fresh()))))
254}
255
256pub fn is_counter_type(type_name: &str) -> bool {
262 matches!(
263 type_name,
264 "ConvergentCount" | "GCounter" | "Tally" | "PNCounter"
265 )
266}
267
268#[derive(Debug, Clone)]
270pub struct InductiveValue {
271 pub inductive_type: String,
272 pub constructor: String,
273 pub args: Vec<RuntimeValue>,
274}
275
276pub(crate) fn option_some(inner: RuntimeValue) -> RuntimeValue {
281 RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
282 inductive_type: "Option".to_string(),
283 constructor: "Some".to_string(),
284 args: vec![inner],
285 }))
286}
287
288pub(crate) fn option_none() -> RuntimeValue {
290 RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
291 inductive_type: "Option".to_string(),
292 constructor: "None".to_string(),
293 args: Vec::new(),
294 }))
295}
296
297#[derive(Debug, Clone)]
299pub struct ClosureValue {
300 pub body_index: usize,
301 pub captured_env: HashMap<Symbol, RuntimeValue>,
302 pub param_names: Vec<Symbol>,
303 pub generated: Option<std::rc::Rc<crate::concurrency::marshal::GenExpr>>,
309}
310
311pub type MapStorage = indexmap::IndexMap<
321 RuntimeValue,
322 RuntimeValue,
323 std::hash::BuildHasherDefault<rustc_hash::FxHasher>,
324>;
325
326fn apply_capacity_hint(value: RuntimeValue, capacity: i64) -> RuntimeValue {
327 let capacity = capacity.max(0) as usize;
328 match &value {
329 RuntimeValue::List(list) => list.borrow_mut().reserve_hint(capacity),
330 RuntimeValue::Set(set) => {
331 let _ = set.borrow_mut().try_reserve(capacity);
332 }
333 RuntimeValue::Map(map) => {
334 let _ = map.borrow_mut().try_reserve(capacity);
335 }
336 _ => {}
337 }
338 match value {
339 RuntimeValue::Text(text) if text.capacity() < capacity => {
340 let mut reserved = String::with_capacity(capacity);
341 reserved.push_str(&text);
342 RuntimeValue::Text(Rc::new(reserved))
343 }
344 other => other,
345 }
346}
347
348#[derive(Debug, Clone)]
359pub enum ListRepr {
360 Boxed(Vec<RuntimeValue>),
361 Ints(Vec<i64>),
362 IntsI32(Vec<i32>),
371 Floats(Vec<f64>),
372 Bools(Vec<bool>),
373 Words32(Vec<i64>),
379 Strings {
394 data: Vec<u8>,
395 ends: Vec<u32>,
396 cache: RefCell<Vec<Option<Rc<String>>>>,
397 },
398 Structs {
410 type_name: String,
411 field_names: Vec<String>,
412 columns: Vec<ListRepr>,
413 },
414 Inductives {
426 inductive_type: String,
427 ctor_dict: Vec<String>,
428 ctors: Vec<u32>,
429 ranks: Vec<u32>,
430 arg_cols: Vec<Vec<ListRepr>>,
431 },
432 WireStructs {
442 bytes: Rc<Vec<u8>>,
443 type_name: String,
444 field_names: Vec<String>,
445 len: usize,
446 },
447 WireColumn {
454 bytes: Rc<Vec<u8>>,
455 len: usize,
456 floats: bool,
457 },
458}
459
460impl ListRepr {
461 fn reserve_hint(&mut self, capacity: usize) {
462 match self {
463 ListRepr::Boxed(v) => {
464 let _ = v.try_reserve(capacity.saturating_sub(v.len()));
465 }
466 ListRepr::Ints(v) => {
467 let _ = v.try_reserve(capacity.saturating_sub(v.len()));
468 }
469 ListRepr::IntsI32(v) => {
470 let _ = v.try_reserve(capacity.saturating_sub(v.len()));
471 }
472 ListRepr::Floats(v) => {
473 let _ = v.try_reserve(capacity.saturating_sub(v.len()));
474 }
475 ListRepr::Bools(v) => {
476 let _ = v.try_reserve(capacity.saturating_sub(v.len()));
477 }
478 ListRepr::Words32(v) => {
479 let _ = v.try_reserve(capacity.saturating_sub(v.len()));
480 }
481 ListRepr::Strings { ends, .. } => {
482 let _ = ends.try_reserve(capacity.saturating_sub(ends.len()));
483 }
484 _ => {}
485 }
486 }
487
488 pub fn from_record_list_view(bytes: Rc<Vec<u8>>) -> Option<ListRepr> {
491 let (type_name, field_names, len) = {
492 let view = crate::concurrency::marshal::view_message(&bytes)?;
493 view.structs_schema()?
494 };
495 Some(ListRepr::WireStructs {
496 bytes,
497 type_name,
498 field_names,
499 len,
500 })
501 }
502
503 pub fn from_aligned_column_view(bytes: Rc<Vec<u8>>) -> Option<ListRepr> {
507 let view = crate::concurrency::marshal::view_message(&bytes)?;
508 if let Some(s) = view.as_i64_slice() {
509 return Some(ListRepr::WireColumn {
510 len: s.len(),
511 floats: false,
512 bytes,
513 });
514 }
515 if let Some(s) = view.as_f64_slice() {
516 return Some(ListRepr::WireColumn {
517 len: s.len(),
518 floats: true,
519 bytes,
520 });
521 }
522 None
523 }
524
525 pub fn from_received_view(bytes: Rc<Vec<u8>>) -> Option<ListRepr> {
528 Self::from_record_list_view(bytes.clone()).or_else(|| Self::from_aligned_column_view(bytes))
529 }
530
531 fn wire_column_get(bytes: &[u8], floats: bool, i: usize) -> Option<RuntimeValue> {
532 let view = crate::concurrency::marshal::view_message(bytes)?;
533 if floats {
534 view.as_f64_slice()?.get(i).map(|&f| RuntimeValue::Float(f))
535 } else {
536 view.as_i64_slice()?.get(i).map(|&n| RuntimeValue::Int(n))
537 }
538 }
539
540 fn wire_column_to_values(bytes: &[u8], floats: bool) -> Vec<RuntimeValue> {
541 let Some(view) = crate::concurrency::marshal::view_message(bytes) else {
542 return Vec::new();
543 };
544 if floats {
545 view.as_f64_slice()
546 .map(|s| s.iter().map(|&f| RuntimeValue::Float(f)).collect())
547 .unwrap_or_default()
548 } else {
549 view.as_i64_slice()
550 .map(|s| s.iter().map(|&n| RuntimeValue::Int(n)).collect())
551 .unwrap_or_default()
552 }
553 }
554
555 fn wire_struct_row(
558 bytes: &[u8],
559 type_name: &str,
560 field_names: &[String],
561 len: usize,
562 i: usize,
563 ) -> Option<RuntimeValue> {
564 if i >= len {
565 return None;
566 }
567 let view = crate::concurrency::marshal::view_message(bytes)?;
568 let mut fields = HashMap::with_capacity(field_names.len());
569 for name in field_names {
570 let cell = view.structs_row_field_value(i, name)?;
571 fields.insert(name.clone(), cell);
572 }
573 Some(RuntimeValue::Struct(Box::new(StructValue {
574 type_name: type_name.to_string(),
575 fields,
576 })))
577 }
578}
579
580impl ListRepr {
581 pub fn from_values(values: Vec<RuntimeValue>) -> ListRepr {
582 if values.iter().all(|v| matches!(v, RuntimeValue::Int(_))) {
583 ListRepr::Ints(
584 values
585 .into_iter()
586 .map(|v| match v {
587 RuntimeValue::Int(n) => n,
588 _ => unreachable!(),
589 })
590 .collect(),
591 )
592 } else if values.iter().all(|v| matches!(v, RuntimeValue::Float(_))) {
593 ListRepr::Floats(
594 values
595 .into_iter()
596 .map(|v| match v {
597 RuntimeValue::Float(f) => f,
598 _ => unreachable!(),
599 })
600 .collect(),
601 )
602 } else if values.iter().all(|v| matches!(v, RuntimeValue::Bool(_))) {
603 ListRepr::Bools(
604 values
605 .into_iter()
606 .map(|v| match v {
607 RuntimeValue::Bool(b) => b,
608 _ => unreachable!(),
609 })
610 .collect(),
611 )
612 } else if !values.is_empty()
613 && values
614 .iter()
615 .all(|v| matches!(v, RuntimeValue::Word(logicaffeine_base::WordVal::W32(_))))
616 {
617 ListRepr::Words32(
620 values
621 .into_iter()
622 .map(|v| match v {
623 RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)) => w.0 as i64,
624 _ => unreachable!(),
625 })
626 .collect(),
627 )
628 } else if !values.is_empty() && values.iter().all(|v| matches!(v, RuntimeValue::Text(_))) {
629 let mut data = Vec::new();
633 let mut ends = Vec::with_capacity(values.len());
634 for v in &values {
635 if let RuntimeValue::Text(s) = v {
636 data.extend_from_slice(s.as_bytes());
637 ends.push(data.len() as u32);
638 }
639 }
640 ListRepr::strings(data, ends)
641 } else if let Some((type_name, field_names)) = Self::struct_schema(&values) {
642 let columns = field_names
645 .iter()
646 .map(|fname| {
647 ListRepr::from_values(
648 values
649 .iter()
650 .map(|v| match v {
651 RuntimeValue::Struct(sv) => sv.fields.get(fname).cloned().unwrap(),
652 _ => unreachable!("struct_schema guaranteed all-struct"),
653 })
654 .collect(),
655 )
656 })
657 .collect();
658 ListRepr::Structs {
659 type_name,
660 field_names,
661 columns,
662 }
663 } else if let Some(inductives) = Self::build_inductives(&values) {
664 inductives
665 } else {
666 ListRepr::Boxed(values)
667 }
668 }
669
670 pub(crate) fn build_inductives(values: &[RuntimeValue]) -> Option<ListRepr> {
675 let inductive_type = match values.first()? {
676 RuntimeValue::Inductive(i) => i.inductive_type.clone(),
677 _ => return None,
678 };
679 let mut ctor_dict: Vec<String> = Vec::new();
680 let mut ctors: Vec<u32> = Vec::with_capacity(values.len());
681 let mut ranks: Vec<u32> = Vec::with_capacity(values.len());
682 let mut counts: Vec<u32> = Vec::new();
683 let mut grouped: Vec<Vec<Vec<RuntimeValue>>> = Vec::new();
685 for v in values {
686 let iv = match v {
687 RuntimeValue::Inductive(i) if i.inductive_type == inductive_type => i,
688 _ => return None,
689 };
690 let c = match ctor_dict.iter().position(|n| n == &iv.constructor) {
691 Some(c) => {
692 if grouped[c].len() != iv.args.len() {
693 return None; }
695 c
696 }
697 None => {
698 ctor_dict.push(iv.constructor.clone());
699 counts.push(0);
700 grouped.push(vec![Vec::new(); iv.args.len()]);
701 ctor_dict.len() - 1
702 }
703 };
704 ctors.push(c as u32);
705 ranks.push(counts[c]);
706 counts[c] += 1;
707 for (j, a) in iv.args.iter().enumerate() {
708 grouped[c][j].push(a.clone());
709 }
710 }
711 let arg_cols: Vec<Vec<ListRepr>> = grouped
712 .into_iter()
713 .map(|cols| cols.into_iter().map(ListRepr::from_values).collect())
714 .collect();
715 Some(ListRepr::Inductives {
716 inductive_type,
717 ctor_dict,
718 ctors,
719 ranks,
720 arg_cols,
721 })
722 }
723
724 fn inductive_row(
726 inductive_type: &str,
727 ctor_dict: &[String],
728 ctors: &[u32],
729 ranks: &[u32],
730 arg_cols: &[Vec<ListRepr>],
731 i: usize,
732 ) -> Option<RuntimeValue> {
733 let c = *ctors.get(i)? as usize;
734 let r = ranks[i] as usize;
735 let mut args = Vec::with_capacity(arg_cols[c].len());
736 for col in &arg_cols[c] {
737 args.push(col.get(r)?);
738 }
739 Some(RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
740 inductive_type: inductive_type.to_string(),
741 constructor: ctor_dict[c].clone(),
742 args,
743 })))
744 }
745
746 fn struct_schema(values: &[RuntimeValue]) -> Option<(String, Vec<String>)> {
751 let first = match values.first()? {
752 RuntimeValue::Struct(s) => s,
753 _ => return None,
754 };
755 let mut names: Vec<String> = first.fields.keys().cloned().collect();
756 names.sort();
757 if names.is_empty() {
760 return None;
761 }
762 for item in values {
763 match item {
764 RuntimeValue::Struct(s)
765 if s.type_name == first.type_name
766 && s.fields.len() == names.len()
767 && names.iter().all(|n| s.fields.contains_key(n)) => {}
768 _ => return None,
769 }
770 }
771 Some((first.type_name.clone(), names))
772 }
773
774 fn struct_row(
776 type_name: &str,
777 field_names: &[String],
778 columns: &[ListRepr],
779 i: usize,
780 ) -> Option<RuntimeValue> {
781 if i >= columns.first().map_or(0, |c| c.len()) {
782 return None;
783 }
784 let mut fields = std::collections::HashMap::with_capacity(field_names.len());
785 for (j, fname) in field_names.iter().enumerate() {
786 fields.insert(fname.clone(), columns[j].get(i)?);
787 }
788 Some(RuntimeValue::Struct(Box::new(StructValue {
789 type_name: type_name.to_string(),
790 fields,
791 })))
792 }
793
794 pub fn strings(data: Vec<u8>, ends: Vec<u32>) -> ListRepr {
796 ListRepr::Strings {
797 data,
798 ends,
799 cache: RefCell::new(Vec::new()),
800 }
801 }
802
803 fn string_at(data: &[u8], ends: &[u32], i: usize) -> Option<String> {
806 let end = *ends.get(i)? as usize;
807 let start = if i == 0 { 0 } else { ends[i - 1] as usize };
808 std::str::from_utf8(data.get(start..end)?)
809 .ok()
810 .map(str::to_string)
811 }
812
813 pub fn len(&self) -> usize {
814 match self {
815 ListRepr::Boxed(v) => v.len(),
816 ListRepr::Ints(v) => v.len(),
817 ListRepr::IntsI32(v) => v.len(),
818 ListRepr::Words32(v) => v.len(),
819 ListRepr::Floats(v) => v.len(),
820 ListRepr::Bools(v) => v.len(),
821 ListRepr::Strings { ends, .. } => ends.len(),
822 ListRepr::Structs { columns, .. } => columns.first().map_or(0, |c| c.len()),
823 ListRepr::Inductives { ctors, .. } => ctors.len(),
824 ListRepr::WireStructs { len, .. } | ListRepr::WireColumn { len, .. } => *len,
825 }
826 }
827
828 pub fn is_empty(&self) -> bool {
829 self.len() == 0
830 }
831
832 pub fn storage_label(&self) -> &'static str {
837 match self {
838 ListRepr::Boxed(_) => "boxed values",
839 ListRepr::Ints(_) => "packed Vec<i64>",
840 ListRepr::IntsI32(_) => "packed Vec<i32> (narrowed)",
841 ListRepr::Words32(_) => "packed Vec<i64> (word32)",
842 ListRepr::Floats(_) => "packed Vec<f64>",
843 ListRepr::Bools(_) => "packed Vec<bool>",
844 ListRepr::Strings { .. } => "flat string buffer",
845 ListRepr::Structs { .. } => "columnar (struct-of-arrays)",
846 ListRepr::Inductives { .. } => "columnar tagged-union",
847 ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => "wire view (lazy)",
848 }
849 }
850
851 pub fn truncate(&mut self, n: usize) {
855 match self {
856 ListRepr::Boxed(v) => v.truncate(n),
857 ListRepr::Ints(v) => v.truncate(n),
858 ListRepr::IntsI32(v) => v.truncate(n),
859 ListRepr::Words32(v) => v.truncate(n),
860 ListRepr::Floats(v) => v.truncate(n),
861 ListRepr::Bools(v) => v.truncate(n),
862 ListRepr::Strings { data, ends, cache } => {
863 if n < ends.len() {
864 let cut = if n == 0 { 0 } else { ends[n - 1] as usize };
865 data.truncate(cut);
866 ends.truncate(n);
867 let mut c = cache.borrow_mut();
868 if !c.is_empty() {
869 c.truncate(n);
870 }
871 }
872 }
873 ListRepr::Structs { columns, .. } => {
874 for c in columns.iter_mut() {
875 c.truncate(n);
876 }
877 }
878 ListRepr::Inductives { .. } => {
881 if n < self.len() {
882 self.make_boxed().truncate(n);
883 }
884 }
885 ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => {
887 if n < self.len() {
888 self.make_boxed().truncate(n);
889 }
890 }
891 }
892 }
893
894 pub fn get(&self, i: usize) -> Option<RuntimeValue> {
896 match self {
897 ListRepr::Boxed(v) => v.get(i).cloned(),
898 ListRepr::Ints(v) => v.get(i).map(|&n| RuntimeValue::Int(n)),
899 ListRepr::IntsI32(v) => v.get(i).map(|&n| RuntimeValue::Int(n as i64)),
900 ListRepr::Words32(v) => v.get(i).map(|&x| {
901 RuntimeValue::Word(logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
902 x as u32,
903 )))
904 }),
905 ListRepr::Floats(v) => v.get(i).map(|&f| RuntimeValue::Float(f)),
906 ListRepr::Bools(v) => v.get(i).map(|&b| RuntimeValue::Bool(b)),
907 ListRepr::Strings { data, ends, cache } => {
908 if i >= ends.len() {
909 return None;
910 }
911 let mut c = cache.borrow_mut();
912 if c.is_empty() {
915 c.resize(ends.len(), None);
916 }
917 if c[i].is_none() {
918 c[i] = Some(Rc::new(Self::string_at(data, ends, i)?));
919 }
920 c[i].clone().map(RuntimeValue::Text)
921 }
922 ListRepr::Structs {
923 type_name,
924 field_names,
925 columns,
926 } => Self::struct_row(type_name, field_names, columns, i),
927 ListRepr::Inductives {
928 inductive_type,
929 ctor_dict,
930 ctors,
931 ranks,
932 arg_cols,
933 } => Self::inductive_row(inductive_type, ctor_dict, ctors, ranks, arg_cols, i),
934 ListRepr::WireStructs {
935 bytes,
936 type_name,
937 field_names,
938 len,
939 } => Self::wire_struct_row(bytes, type_name, field_names, *len, i),
940 ListRepr::WireColumn { bytes, floats, .. } => Self::wire_column_get(bytes, *floats, i),
941 }
942 }
943
944 pub fn get_field(&self, i: usize, name: &str) -> Option<RuntimeValue> {
949 match self {
950 ListRepr::Structs {
951 field_names,
952 columns,
953 ..
954 } => {
955 let j = field_names.iter().position(|f| f == name)?;
956 columns[j].get(i)
957 }
958 ListRepr::WireStructs { bytes, .. } => {
961 crate::concurrency::marshal::view_message(bytes)?.structs_row_field_value(i, name)
962 }
963 _ => None,
964 }
965 }
966
967 pub fn column(&self, name: &str) -> Option<&ListRepr> {
971 match self {
972 ListRepr::Structs {
973 field_names,
974 columns,
975 ..
976 } => {
977 let j = field_names.iter().position(|f| f == name)?;
978 Some(&columns[j])
979 }
980 _ => None,
981 }
982 }
983
984 fn make_boxed(&mut self) -> &mut Vec<RuntimeValue> {
986 match self {
987 ListRepr::Boxed(v) => v,
988 ListRepr::Ints(v) => {
989 let boxed = v.drain(..).map(RuntimeValue::Int).collect();
990 *self = ListRepr::Boxed(boxed);
991 match self {
992 ListRepr::Boxed(v) => v,
993 _ => unreachable!(),
994 }
995 }
996 ListRepr::Floats(v) => {
997 let boxed = v.drain(..).map(RuntimeValue::Float).collect();
998 *self = ListRepr::Boxed(boxed);
999 match self {
1000 ListRepr::Boxed(v) => v,
1001 _ => unreachable!(),
1002 }
1003 }
1004 ListRepr::IntsI32(v) => {
1005 let boxed = v.drain(..).map(|n| RuntimeValue::Int(n as i64)).collect();
1006 *self = ListRepr::Boxed(boxed);
1007 match self {
1008 ListRepr::Boxed(v) => v,
1009 _ => unreachable!(),
1010 }
1011 }
1012 ListRepr::Words32(v) => {
1013 let boxed = v
1014 .drain(..)
1015 .map(|x| {
1016 RuntimeValue::Word(logicaffeine_base::WordVal::W32(
1017 logicaffeine_base::Word32(x as u32),
1018 ))
1019 })
1020 .collect();
1021 *self = ListRepr::Boxed(boxed);
1022 match self {
1023 ListRepr::Boxed(v) => v,
1024 _ => unreachable!(),
1025 }
1026 }
1027 ListRepr::Bools(v) => {
1028 let boxed = v.drain(..).map(RuntimeValue::Bool).collect();
1029 *self = ListRepr::Boxed(boxed);
1030 match self {
1031 ListRepr::Boxed(v) => v,
1032 _ => unreachable!(),
1033 }
1034 }
1035 ListRepr::Strings { data, ends, .. } => {
1036 let boxed = (0..ends.len())
1037 .filter_map(|i| {
1038 Self::string_at(data, ends, i).map(|s| RuntimeValue::Text(Rc::new(s)))
1039 })
1040 .collect();
1041 *self = ListRepr::Boxed(boxed);
1042 match self {
1043 ListRepr::Boxed(v) => v,
1044 _ => unreachable!(),
1045 }
1046 }
1047 ListRepr::Structs {
1048 type_name,
1049 field_names,
1050 columns,
1051 } => {
1052 let n = columns.first().map_or(0, |c| c.len());
1053 debug_assert!(
1056 columns.iter().all(|c| c.len() == n),
1057 "columnar struct columns must share one length"
1058 );
1059 let boxed = (0..n)
1060 .filter_map(|i| Self::struct_row(type_name, field_names, columns, i))
1061 .collect();
1062 *self = ListRepr::Boxed(boxed);
1063 match self {
1064 ListRepr::Boxed(v) => v,
1065 _ => unreachable!(),
1066 }
1067 }
1068 ListRepr::Inductives {
1069 inductive_type,
1070 ctor_dict,
1071 ctors,
1072 ranks,
1073 arg_cols,
1074 } => {
1075 let n = ctors.len();
1076 debug_assert_eq!(ranks.len(), n, "ranks and ctors must agree");
1077 let boxed = (0..n)
1078 .filter_map(|i| {
1079 Self::inductive_row(inductive_type, ctor_dict, ctors, ranks, arg_cols, i)
1080 })
1081 .collect();
1082 *self = ListRepr::Boxed(boxed);
1083 match self {
1084 ListRepr::Boxed(v) => v,
1085 _ => unreachable!(),
1086 }
1087 }
1088 ListRepr::WireStructs {
1091 bytes,
1092 type_name,
1093 field_names,
1094 len,
1095 } => {
1096 let len = *len;
1097 let boxed: Vec<RuntimeValue> = {
1098 let view = crate::concurrency::marshal::view_message(bytes);
1099 (0..len)
1100 .filter_map(|i| {
1101 view.as_ref().and_then(|v| {
1102 let mut fields = HashMap::with_capacity(field_names.len());
1103 for name in field_names.iter() {
1104 let cell = v.structs_row_field_value(i, name)?;
1105 fields.insert(name.clone(), cell);
1106 }
1107 Some(RuntimeValue::Struct(Box::new(StructValue {
1108 type_name: type_name.clone(),
1109 fields,
1110 })))
1111 })
1112 })
1113 .collect()
1114 };
1115 *self = ListRepr::Boxed(boxed);
1116 match self {
1117 ListRepr::Boxed(v) => v,
1118 _ => unreachable!(),
1119 }
1120 }
1121 ListRepr::WireColumn { bytes, floats, .. } => {
1122 let boxed = Self::wire_column_to_values(bytes, *floats);
1123 *self = ListRepr::Boxed(boxed);
1124 match self {
1125 ListRepr::Boxed(v) => v,
1126 _ => unreachable!(),
1127 }
1128 }
1129 }
1130 }
1131
1132 fn widen_to_ints(&mut self) -> &mut Vec<i64> {
1138 match self {
1139 ListRepr::IntsI32(v) => {
1140 let wide: Vec<i64> = v.drain(..).map(|n| n as i64).collect();
1141 *self = ListRepr::Ints(wide);
1142 match self {
1143 ListRepr::Ints(v) => v,
1144 _ => unreachable!(),
1145 }
1146 }
1147 ListRepr::Ints(v) => v,
1148 _ => unreachable!("widen_to_ints called on a non-Int buffer"),
1149 }
1150 }
1151
1152 pub fn set(&mut self, i: usize, value: RuntimeValue) {
1155 match (&mut *self, &value) {
1156 (ListRepr::Ints(v), RuntimeValue::Int(n)) => v[i] = *n,
1157 (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => {
1158 if let Ok(narrow) = i32::try_from(*n) {
1159 v[i] = narrow;
1160 } else {
1161 self.widen_to_ints()[i] = *n;
1165 }
1166 }
1167 (ListRepr::Floats(v), RuntimeValue::Float(f)) => v[i] = *f,
1168 (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v[i] = *b,
1169 (ListRepr::Boxed(v), _) => v[i] = value,
1170 _ => self.make_boxed()[i] = value,
1171 }
1172 }
1173
1174 pub fn push(&mut self, value: RuntimeValue) {
1175 match (&mut *self, &value) {
1176 (ListRepr::Ints(v), RuntimeValue::Int(n)) => v.push(*n),
1177 (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => match i32::try_from(*n) {
1178 Ok(narrow) => v.push(narrow),
1179 Err(_) => self.widen_to_ints().push(*n),
1180 },
1181 (ListRepr::Floats(v), RuntimeValue::Float(f)) => v.push(*f),
1182 (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v.push(*b),
1183 (ListRepr::Words32(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w))) => {
1184 v.push(w.0 as i64)
1185 }
1186 (ListRepr::Boxed(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)))
1190 if v.is_empty() =>
1191 {
1192 let mut out = Vec::with_capacity(v.capacity().max(1));
1193 out.push(w.0 as i64);
1194 *self = ListRepr::Words32(out);
1195 }
1196 (ListRepr::Ints(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)))
1197 if v.is_empty() =>
1198 {
1199 let mut out = Vec::with_capacity(v.capacity().max(1));
1200 out.push(w.0 as i64);
1201 *self = ListRepr::Words32(out);
1202 }
1203 (ListRepr::Boxed(v), _) => v.push(value),
1204 (ListRepr::Ints(v), RuntimeValue::Float(f)) if v.is_empty() => {
1205 let mut out = Vec::with_capacity(v.capacity().max(1));
1206 out.push(*f);
1207 *self = ListRepr::Floats(out);
1208 }
1209 (ListRepr::Ints(v), RuntimeValue::Bool(b)) if v.is_empty() => {
1210 let mut out = Vec::with_capacity(v.capacity().max(1));
1211 out.push(*b);
1212 *self = ListRepr::Bools(out);
1213 }
1214 (ListRepr::Floats(v), RuntimeValue::Int(n)) if v.is_empty() => {
1215 let mut out = Vec::with_capacity(v.capacity().max(1));
1216 out.push(*n);
1217 *self = ListRepr::Ints(out);
1218 }
1219 (ListRepr::Floats(v), RuntimeValue::Bool(b)) if v.is_empty() => {
1220 let mut out = Vec::with_capacity(v.capacity().max(1));
1221 out.push(*b);
1222 *self = ListRepr::Bools(out);
1223 }
1224 (ListRepr::Bools(v), RuntimeValue::Int(n)) if v.is_empty() => {
1225 let mut out = Vec::with_capacity(v.capacity().max(1));
1226 out.push(*n);
1227 *self = ListRepr::Ints(out);
1228 }
1229 (ListRepr::Bools(v), RuntimeValue::Float(f)) if v.is_empty() => {
1230 let mut out = Vec::with_capacity(v.capacity().max(1));
1231 out.push(*f);
1232 *self = ListRepr::Floats(out);
1233 }
1234 _ => self.make_boxed().push(value),
1235 }
1236 }
1237
1238 pub fn pop(&mut self) -> Option<RuntimeValue> {
1239 match self {
1240 ListRepr::Boxed(v) => v.pop(),
1241 ListRepr::Ints(v) => v.pop().map(RuntimeValue::Int),
1242 ListRepr::IntsI32(v) => v.pop().map(|n| RuntimeValue::Int(n as i64)),
1243 ListRepr::Words32(v) => v.pop().map(|x| {
1244 RuntimeValue::Word(logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
1245 x as u32,
1246 )))
1247 }),
1248 ListRepr::Floats(v) => v.pop().map(RuntimeValue::Float),
1249 ListRepr::Bools(v) => v.pop().map(RuntimeValue::Bool),
1250 ListRepr::Strings { data, ends, cache } => {
1251 let last = ends.len().checked_sub(1)?;
1252 let s = Self::string_at(data, ends, last)?;
1253 let start = if last == 0 {
1254 0
1255 } else {
1256 ends[last - 1] as usize
1257 };
1258 data.truncate(start);
1259 ends.pop();
1260 let mut c = cache.borrow_mut();
1261 if !c.is_empty() {
1262 c.pop();
1263 }
1264 Some(RuntimeValue::Text(Rc::new(s)))
1265 }
1266 ListRepr::Structs { .. } => self.make_boxed().pop(),
1268 ListRepr::Inductives { .. } => self.make_boxed().pop(),
1269 ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => self.make_boxed().pop(),
1270 }
1271 }
1272
1273 pub fn insert(&mut self, i: usize, value: RuntimeValue) {
1274 match (&mut *self, &value) {
1275 (ListRepr::Ints(v), RuntimeValue::Int(n)) => v.insert(i, *n),
1276 (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => match i32::try_from(*n) {
1277 Ok(narrow) => v.insert(i, narrow),
1278 Err(_) => self.widen_to_ints().insert(i, *n),
1279 },
1280 (ListRepr::Floats(v), RuntimeValue::Float(f)) => v.insert(i, *f),
1281 (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v.insert(i, *b),
1282 (ListRepr::Boxed(v), _) => v.insert(i, value),
1283 _ => self.make_boxed().insert(i, value),
1284 }
1285 }
1286
1287 pub fn remove_at(&mut self, i: usize) -> RuntimeValue {
1288 match self {
1289 ListRepr::Boxed(v) => v.remove(i),
1290 ListRepr::Ints(v) => RuntimeValue::Int(v.remove(i)),
1291 ListRepr::IntsI32(v) => RuntimeValue::Int(v.remove(i) as i64),
1292 ListRepr::Words32(v) => RuntimeValue::Word(logicaffeine_base::WordVal::W32(
1293 logicaffeine_base::Word32(v.remove(i) as u32),
1294 )),
1295 ListRepr::Floats(v) => RuntimeValue::Float(v.remove(i)),
1296 ListRepr::Bools(v) => RuntimeValue::Bool(v.remove(i)),
1297 ListRepr::Strings { .. } => self.make_boxed().remove(i),
1299 ListRepr::Structs { .. } => self.make_boxed().remove(i),
1300 ListRepr::Inductives { .. } => self.make_boxed().remove(i),
1301 ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => {
1302 self.make_boxed().remove(i)
1303 }
1304 }
1305 }
1306
1307 pub fn position(&self, needle: &RuntimeValue) -> Option<usize> {
1310 match (self, needle) {
1311 (ListRepr::Ints(v), RuntimeValue::Int(n)) => v.iter().position(|x| x == n),
1312 (ListRepr::Ints(_), _) => None,
1313 (ListRepr::IntsI32(v), RuntimeValue::Int(n)) => i32::try_from(*n)
1314 .ok()
1315 .and_then(|nn| v.iter().position(|x| *x == nn)),
1316 (ListRepr::IntsI32(_), _) => None,
1317 (ListRepr::Words32(v), RuntimeValue::Word(logicaffeine_base::WordVal::W32(w))) => {
1318 v.iter().position(|x| *x == w.0 as i64)
1319 }
1320 (ListRepr::Words32(_), _) => None,
1321 (ListRepr::Floats(v), RuntimeValue::Float(f)) => {
1322 v.iter().position(|x| (x - f).abs() < f64::EPSILON)
1323 }
1324 (ListRepr::Floats(_), _) => None,
1325 (ListRepr::Bools(v), RuntimeValue::Bool(b)) => v.iter().position(|x| x == b),
1326 (ListRepr::Bools(_), _) => None,
1327 (ListRepr::Strings { data, ends, .. }, RuntimeValue::Text(t)) => (0..ends.len())
1328 .find(|&i| Self::string_at(data, ends, i).as_deref() == Some(t.as_str())),
1329 (ListRepr::Strings { .. }, _) => None,
1330 (ListRepr::Boxed(v), _) => v
1331 .iter()
1332 .position(|x| crate::semantics::compare::values_equal(x, needle)),
1333 (ListRepr::Structs { .. }, _) => (0..self.len()).find(|&i| {
1336 self.get(i)
1337 .is_some_and(|v| crate::semantics::compare::values_equal(&v, needle))
1338 }),
1339 (ListRepr::Inductives { .. }, _) => (0..self.len()).find(|&i| {
1340 self.get(i)
1341 .is_some_and(|v| crate::semantics::compare::values_equal(&v, needle))
1342 }),
1343 (ListRepr::WireStructs { .. }, _) | (ListRepr::WireColumn { .. }, _) => (0..self.len())
1345 .find(|&i| {
1346 self.get(i)
1347 .is_some_and(|v| crate::semantics::compare::values_equal(&v, needle))
1348 }),
1349 }
1350 }
1351
1352 pub fn contains(&self, needle: &RuntimeValue) -> bool {
1353 self.position(needle).is_some()
1354 }
1355
1356 pub fn to_values(&self) -> Vec<RuntimeValue> {
1358 match self {
1359 ListRepr::Boxed(v) => v.clone(),
1360 ListRepr::Ints(v) => v.iter().map(|&n| RuntimeValue::Int(n)).collect(),
1361 ListRepr::IntsI32(v) => v.iter().map(|&n| RuntimeValue::Int(n as i64)).collect(),
1362 ListRepr::Words32(v) => v
1363 .iter()
1364 .map(|&x| {
1365 RuntimeValue::Word(logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
1366 x as u32,
1367 )))
1368 })
1369 .collect(),
1370 ListRepr::Floats(v) => v.iter().map(|&f| RuntimeValue::Float(f)).collect(),
1371 ListRepr::Bools(v) => v.iter().map(|&b| RuntimeValue::Bool(b)).collect(),
1372 ListRepr::Strings { data, ends, .. } => (0..ends.len())
1373 .filter_map(|i| {
1374 Self::string_at(data, ends, i).map(|s| RuntimeValue::Text(Rc::new(s)))
1375 })
1376 .collect(),
1377 ListRepr::Structs {
1378 type_name,
1379 field_names,
1380 columns,
1381 } => {
1382 let n = columns.first().map_or(0, |c| c.len());
1383 (0..n)
1384 .filter_map(|i| Self::struct_row(type_name, field_names, columns, i))
1385 .collect()
1386 }
1387 ListRepr::Inductives {
1388 inductive_type,
1389 ctor_dict,
1390 ctors,
1391 ranks,
1392 arg_cols,
1393 } => (0..ctors.len())
1394 .filter_map(|i| {
1395 Self::inductive_row(inductive_type, ctor_dict, ctors, ranks, arg_cols, i)
1396 })
1397 .collect(),
1398 ListRepr::WireStructs {
1399 bytes,
1400 type_name,
1401 field_names,
1402 len,
1403 } => (0..*len)
1404 .filter_map(|i| Self::wire_struct_row(bytes, type_name, field_names, *len, i))
1405 .collect(),
1406 ListRepr::WireColumn { bytes, floats, .. } => {
1407 Self::wire_column_to_values(bytes, *floats)
1408 }
1409 }
1410 }
1411
1412 pub fn slice(&self, start: usize, end: usize) -> ListRepr {
1414 match self {
1415 ListRepr::Boxed(v) => ListRepr::Boxed(v[start..=end].to_vec()),
1416 ListRepr::Ints(v) => ListRepr::Ints(v[start..=end].to_vec()),
1417 ListRepr::IntsI32(v) => ListRepr::IntsI32(v[start..=end].to_vec()),
1418 ListRepr::Words32(v) => ListRepr::Words32(v[start..=end].to_vec()),
1419 ListRepr::Floats(v) => ListRepr::Floats(v[start..=end].to_vec()),
1420 ListRepr::Bools(v) => ListRepr::Bools(v[start..=end].to_vec()),
1421 ListRepr::Strings { data, ends, .. } => ListRepr::Boxed(
1422 (start..=end)
1423 .filter_map(|i| {
1424 Self::string_at(data, ends, i).map(|s| RuntimeValue::Text(Rc::new(s)))
1425 })
1426 .collect(),
1427 ),
1428 ListRepr::Structs {
1430 type_name,
1431 field_names,
1432 columns,
1433 } => ListRepr::Structs {
1434 type_name: type_name.clone(),
1435 field_names: field_names.clone(),
1436 columns: columns.iter().map(|c| c.slice(start, end)).collect(),
1437 },
1438 ListRepr::Inductives { .. } => {
1440 ListRepr::from_values((start..=end).filter_map(|i| self.get(i)).collect())
1441 }
1442 ListRepr::WireStructs { .. } | ListRepr::WireColumn { .. } => {
1444 ListRepr::from_values((start..=end).filter_map(|i| self.get(i)).collect())
1445 }
1446 }
1447 }
1448
1449 pub fn as_ints_mut(&mut self) -> Option<&mut Vec<i64>> {
1451 match self {
1452 ListRepr::Ints(v) => Some(v),
1453 _ => None,
1454 }
1455 }
1456
1457 pub fn as_floats_mut(&mut self) -> Option<&mut Vec<f64>> {
1458 match self {
1459 ListRepr::Floats(v) => Some(v),
1460 _ => None,
1461 }
1462 }
1463}
1464
1465fn empty_like(current: Option<&RuntimeValue>) -> RuntimeValue {
1475 match current {
1476 Some(RuntimeValue::Int(_)) => RuntimeValue::Int(0),
1477 Some(RuntimeValue::Float(_)) => RuntimeValue::Float(0.0),
1478 Some(RuntimeValue::Bool(_)) => RuntimeValue::Bool(false),
1479 _ => RuntimeValue::Text(Rc::new(String::new())),
1480 }
1481}
1482
1483#[derive(Debug, Clone)]
1484pub enum RuntimeValue {
1485 Int(i64),
1486 Action(Rc<ActionRef>),
1491 View(i64),
1496 BigInt(Rc<logicaffeine_base::BigInt>),
1502 Rational(Rc<logicaffeine_base::Rational>),
1508 Decimal(Rc<logicaffeine_base::Decimal>),
1515 Complex(Rc<logicaffeine_base::Complex>),
1519 ComplexF(Rc<logicaffeine_base::ComplexF>),
1524 Modular(Rc<logicaffeine_base::Modular>),
1528 Algebraic(Rc<logicaffeine_base::algebraic::Algebraic>),
1531 ExactReal(Rc<logicaffeine_base::exact_real::ExactReal>),
1534 Hyperreal(Rc<crate::semantics::exact::HyperValue>),
1537 Hypernatural(Rc<crate::semantics::exact::NaturalValue>),
1540 Ordinal(Rc<logicaffeine_base::ordinal::Ordinal>),
1542 Depends(Rc<crate::semantics::exact::DependsValue>),
1544 Converging(Rc<logicaffeine_base::limit_value::Converging<RuntimeValue>>),
1547 Float(f64),
1548 Bool(bool),
1549 Text(Rc<String>),
1550 Char(char),
1551 List(Rc<RefCell<ListRepr>>),
1552 Tuple(Rc<Vec<RuntimeValue>>),
1553 Set(Rc<RefCell<Vec<RuntimeValue>>>),
1554 Map(Rc<RefCell<MapStorage>>),
1555 Struct(Box<StructValue>),
1556 Inductive(Rc<InductiveValue>),
1559 Function(Box<ClosureValue>),
1560 Nothing,
1561 Duration(i64),
1562 Date(i32),
1563 Moment(i64),
1564 Span {
1565 months: i32,
1566 days: i32,
1567 },
1568 Time(i64),
1569 Chan(ChanId),
1571 TaskHandle(TaskId),
1573 Peer(Rc<String>),
1576 Crdt(Rc<RefCell<crate::semantics::crdt::CrdtValue>>),
1582 Word(logicaffeine_base::WordVal),
1586 Lanes(Rc<logicaffeine_base::LanesVal>),
1591 Quantity(Rc<QuantityValue>),
1597 Money(Rc<logicaffeine_base::Money>),
1601 Uuid(Rc<logicaffeine_base::Uuid>),
1605}
1606
1607#[derive(Clone, Debug)]
1612pub struct QuantityValue {
1613 pub q: logicaffeine_base::Quantity,
1614 pub unit: logicaffeine_base::Unit,
1615}
1616
1617impl QuantityValue {
1618 pub fn display(&self) -> String {
1622 let magnitude = self
1623 .q
1624 .in_unit(&self.unit)
1625 .expect("a Quantity's display unit always shares its dimension");
1626 if self.unit.symbol.is_empty() {
1627 format!("{} {}", magnitude, self.q.dimension())
1628 } else {
1629 format!("{} {}", magnitude, self.unit.symbol)
1630 }
1631 }
1632}
1633
1634impl PartialEq for RuntimeValue {
1635 fn eq(&self, other: &Self) -> bool {
1641 crate::semantics::compare::values_equal(self, other)
1642 }
1643}
1644
1645impl Eq for RuntimeValue {}
1652
1653impl std::hash::Hash for RuntimeValue {
1654 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1661 use logicaffeine_base::numeric;
1662 match self {
1663 RuntimeValue::Int(n) => state.write_u64(numeric::numeric_hash_i64(*n)),
1665 RuntimeValue::BigInt(b) => state.write_u64(numeric::numeric_hash_bigint(b)),
1666 RuntimeValue::Float(f) => state.write_u64(numeric::numeric_hash_f64(*f)),
1667 RuntimeValue::Rational(r) => state.write_u64(numeric::numeric_hash_rational(r)),
1668 other => {
1670 std::mem::discriminant(other).hash(state);
1671 match other {
1672 RuntimeValue::Int(_)
1673 | RuntimeValue::BigInt(_)
1674 | RuntimeValue::Float(_)
1675 | RuntimeValue::Rational(_) => unreachable!("handled above"),
1676 RuntimeValue::Decimal(d) => d.hash(state),
1677 RuntimeValue::Complex(c) => c.hash(state),
1678 RuntimeValue::ComplexF(c) => {
1679 state.write_u64(numeric::numeric_hash_f64(c.re()));
1680 state.write_u64(numeric::numeric_hash_f64(c.im()));
1681 }
1682 RuntimeValue::Modular(m) => m.hash(state),
1683 RuntimeValue::Algebraic(a) => a.hash(state),
1684 RuntimeValue::ExactReal(x) => x.describe().hash(state),
1685 RuntimeValue::Hyperreal(h) => h.value.hash(state),
1686 RuntimeValue::Hypernatural(n) => n.value.hash(state),
1687 RuntimeValue::Ordinal(o) => o.hash(state),
1688 RuntimeValue::Depends(_) | RuntimeValue::Converging(_) => {
1689 other.to_display_string().hash(state)
1690 }
1691 RuntimeValue::Bool(b) => b.hash(state),
1692 RuntimeValue::Text(s) => s.hash(state),
1693 RuntimeValue::Char(c) => c.hash(state),
1694 RuntimeValue::Nothing => {}
1695 RuntimeValue::Duration(d) => d.hash(state),
1696 RuntimeValue::Date(d) => d.hash(state),
1697 RuntimeValue::Moment(m) => m.hash(state),
1698 RuntimeValue::Span { months, days } => {
1699 months.hash(state);
1700 days.hash(state);
1701 }
1702 RuntimeValue::Time(t) => t.hash(state),
1703 RuntimeValue::Tuple(items) => {
1706 items.len().hash(state);
1707 for v in items.iter() {
1708 v.hash(state);
1709 }
1710 }
1711 RuntimeValue::Struct(s) => {
1715 s.type_name.hash(state);
1716 let mut fold: u64 = 0;
1717 for (k, v) in &s.fields {
1718 let mut h = rustc_hash::FxHasher::default();
1719 std::hash::Hash::hash(k, &mut h);
1720 std::hash::Hash::hash(v, &mut h);
1721 fold = fold.wrapping_add(std::hash::Hasher::finish(&h));
1722 }
1723 state.write_u64(fold);
1724 }
1725 RuntimeValue::List(items) => items.borrow().len().hash(state),
1729 RuntimeValue::Set(items) => items.borrow().len().hash(state),
1730 RuntimeValue::Map(m) => m.borrow().len().hash(state),
1731 RuntimeValue::Inductive(i) => {
1732 i.inductive_type.hash(state);
1733 i.constructor.hash(state);
1734 }
1735 RuntimeValue::Function(f) => f.body_index.hash(state),
1736 RuntimeValue::View(h) => h.hash(state),
1739 RuntimeValue::Action(a) => {
1740 a.instance.hash(state);
1741 a.name.hash(state);
1742 }
1743 RuntimeValue::Chan(c) => c.0.hash(state),
1744 RuntimeValue::TaskHandle(t) => t.0.hash(state),
1745 RuntimeValue::Peer(topic) => topic.hash(state),
1746 RuntimeValue::Crdt(c) => c.borrow().len().hash(state),
1747 RuntimeValue::Word(w) => w.hash(state),
1748 RuntimeValue::Lanes(v) => v.hash(state),
1749 RuntimeValue::Quantity(qv) => {
1752 qv.q.magnitude_si().hash(state);
1753 qv.q.dimension().hash(state);
1754 }
1755 RuntimeValue::Money(m) => m.hash(state),
1757 RuntimeValue::Uuid(u) => u.hash(state),
1758 }
1759 }
1760 }
1761 }
1762}
1763
1764impl RuntimeValue {
1765 pub fn from_bigint(b: logicaffeine_base::BigInt) -> RuntimeValue {
1771 match b.to_i64() {
1772 Some(i) => RuntimeValue::Int(i),
1773 None => RuntimeValue::BigInt(Rc::new(b)),
1774 }
1775 }
1776
1777 pub fn from_rational(r: logicaffeine_base::Rational) -> RuntimeValue {
1783 match r.to_bigint() {
1784 Some(whole) => RuntimeValue::from_bigint(whole),
1785 None => RuntimeValue::Rational(Rc::new(r)),
1786 }
1787 }
1788
1789 pub fn type_name(&self) -> &str {
1793 match self {
1794 RuntimeValue::Int(_) => "Int",
1795 RuntimeValue::BigInt(_) => "Int",
1798 RuntimeValue::Rational(_) => "Rational",
1799 RuntimeValue::Decimal(_) => "Decimal",
1800 RuntimeValue::Complex(_) => "Complex",
1801 RuntimeValue::ComplexF(_) => "ComplexF",
1802 RuntimeValue::Modular(_) => "Modular",
1803 RuntimeValue::Algebraic(_) => "Algebraic",
1804 RuntimeValue::ExactReal(_) => "ExactReal",
1805 RuntimeValue::Hyperreal(_) => "Hyperreal",
1806 RuntimeValue::Hypernatural(_) => "Hypernatural",
1807 RuntimeValue::Ordinal(_) => "Ordinal",
1808 RuntimeValue::Depends(_) => "Depends",
1809 RuntimeValue::Converging(_) => "Converging",
1810 RuntimeValue::Float(_) => "Float",
1811 RuntimeValue::Bool(_) => "Bool",
1812 RuntimeValue::Text(_) => "Text",
1813 RuntimeValue::Char(_) => "Char",
1814 RuntimeValue::List(_) => "List",
1815 RuntimeValue::Tuple(_) => "Tuple",
1816 RuntimeValue::Set(_) => "Set",
1817 RuntimeValue::Map(_) => "Map",
1818 RuntimeValue::Struct(s) => &s.type_name,
1819 RuntimeValue::Inductive(ind) => ind.inductive_type.as_str(),
1820 RuntimeValue::Function(_) => "Function",
1821 RuntimeValue::View(_) => "View",
1822 RuntimeValue::Action(_) => "Action",
1823 RuntimeValue::Nothing => "Nothing",
1824 RuntimeValue::Duration(_) => "Duration",
1825 RuntimeValue::Date(_) => "Date",
1826 RuntimeValue::Moment(_) => "Moment",
1827 RuntimeValue::Span { .. } => "Span",
1828 RuntimeValue::Time(_) => "Time",
1829 RuntimeValue::Chan(_) => "Channel",
1830 RuntimeValue::TaskHandle(_) => "Task",
1831 RuntimeValue::Peer(_) => "PeerAgent",
1832 RuntimeValue::Crdt(c) => c.borrow().kind(),
1833 RuntimeValue::Word(w) => w.type_name(),
1834 RuntimeValue::Lanes(v) => v.type_name(),
1835 RuntimeValue::Quantity(_) => "Quantity",
1836 RuntimeValue::Money(_) => "Money",
1837 RuntimeValue::Uuid(_) => "Uuid",
1838 }
1839 }
1840
1841 pub fn decided_truth(&self) -> Result<bool, String> {
1844 if let Some(why) = crate::semantics::exact::undecided_branch(self) {
1845 return Err(why);
1846 }
1847 Ok(self.is_truthy())
1848 }
1849
1850 pub fn deep_clone(&self) -> RuntimeValue {
1857 match self {
1858 RuntimeValue::List(items) => {
1859 let cloned: Vec<RuntimeValue> = items
1860 .borrow()
1861 .to_values()
1862 .iter()
1863 .map(|v| v.deep_clone())
1864 .collect();
1865 RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(cloned))))
1866 }
1867 RuntimeValue::Set(items) => {
1868 let cloned = items.borrow().iter().map(|v| v.deep_clone()).collect();
1869 RuntimeValue::Set(Rc::new(RefCell::new(cloned)))
1870 }
1871 RuntimeValue::Map(m) => {
1872 let cloned = m
1873 .borrow()
1874 .iter()
1875 .map(|(k, v)| (k.deep_clone(), v.deep_clone()))
1876 .collect();
1877 RuntimeValue::Map(Rc::new(RefCell::new(cloned)))
1878 }
1879 RuntimeValue::Tuple(items) => {
1880 let cloned = items.iter().map(|v| v.deep_clone()).collect();
1881 RuntimeValue::Tuple(Rc::new(cloned))
1882 }
1883 RuntimeValue::Struct(s) => {
1884 let cloned_fields = s
1885 .fields
1886 .iter()
1887 .map(|(k, v)| (k.clone(), v.deep_clone()))
1888 .collect();
1889 RuntimeValue::Struct(Box::new(StructValue {
1890 type_name: s.type_name.clone(),
1891 fields: cloned_fields,
1892 }))
1893 }
1894 RuntimeValue::Inductive(ind) => {
1895 let cloned_args = ind.args.iter().map(|v| v.deep_clone()).collect();
1896 RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
1897 inductive_type: ind.inductive_type.clone(),
1898 constructor: ind.constructor.clone(),
1899 args: cloned_args,
1900 }))
1901 }
1902 RuntimeValue::Function(f) => {
1903 let cloned_env = f
1904 .captured_env
1905 .iter()
1906 .map(|(k, v)| (k.clone(), v.deep_clone()))
1907 .collect();
1908 RuntimeValue::Function(Box::new(ClosureValue {
1909 body_index: f.body_index,
1910 captured_env: cloned_env,
1911 param_names: f.param_names.clone(),
1912 generated: f.generated.clone(),
1913 }))
1914 }
1915 RuntimeValue::Crdt(c) => RuntimeValue::Crdt(Rc::new(RefCell::new(c.borrow().clone()))),
1919 other => other.clone(),
1920 }
1921 }
1922
1923 pub fn is_truthy(&self) -> bool {
1927 match self {
1928 RuntimeValue::Bool(b) => *b,
1929 RuntimeValue::Int(n) => *n != 0,
1930 RuntimeValue::Float(f) => *f != 0.0,
1931 RuntimeValue::BigInt(b) => !b.is_zero(),
1932 RuntimeValue::Rational(r) => !r.is_zero(),
1933 RuntimeValue::Decimal(d) => !d.is_zero(),
1934 RuntimeValue::Complex(c) => !c.is_zero(),
1935 RuntimeValue::ComplexF(c) => !c.is_zero(),
1936 RuntimeValue::Word(w) => w.to_u64() != 0,
1937 RuntimeValue::Text(s) => !s.is_empty(),
1938 RuntimeValue::List(l) => l.borrow().len() != 0,
1939 RuntimeValue::Set(s) => !s.borrow().is_empty(),
1940 RuntimeValue::Map(m) => !m.borrow().is_empty(),
1941 RuntimeValue::Nothing => false,
1942 _ => true,
1943 }
1944 }
1945
1946 pub fn to_display_string(&self) -> String {
1952 match self {
1953 RuntimeValue::Int(n) => n.to_string(),
1954 RuntimeValue::Word(w) => w.to_string(),
1955 RuntimeValue::Lanes(v) => {
1957 let parts: Vec<String> = (0..v.lanes()).map(|i| v.lane(i).to_string()).collect();
1958 format!("[{}]", parts.join(", "))
1959 }
1960 RuntimeValue::BigInt(b) => b.to_string(),
1961 RuntimeValue::Rational(r) => r.to_string(),
1962 RuntimeValue::Decimal(d) => d.to_string(),
1963 RuntimeValue::Complex(c) => c.to_string(),
1964 RuntimeValue::ComplexF(c) => {
1965 let fmt = logicaffeine_data::fmt::fmt_f64;
1968 let (re, im) = (c.re(), c.im());
1969 if im == 0.0 {
1970 fmt(re)
1971 } else {
1972 let mag = im.abs();
1973 let icoef = if mag == 1.0 { String::new() } else { fmt(mag) };
1974 if re == 0.0 {
1975 format!("{}{}i", if im < 0.0 { "-" } else { "" }, icoef)
1976 } else {
1977 format!("{}{}{}i", fmt(re), if im < 0.0 { "-" } else { "+" }, icoef)
1978 }
1979 }
1980 }
1981 RuntimeValue::Modular(m) => m.to_string(),
1982 RuntimeValue::Algebraic(_)
1983 | RuntimeValue::ExactReal(_)
1984 | RuntimeValue::Hyperreal(_)
1985 | RuntimeValue::Hypernatural(_)
1986 | RuntimeValue::Ordinal(_)
1987 | RuntimeValue::Depends(_)
1988 | RuntimeValue::Converging(_) => {
1989 crate::semantics::exact::display(self).expect("an exact value displays")
1990 }
1991 RuntimeValue::Quantity(qv) => qv.display(),
1992 RuntimeValue::Money(m) => m.to_string(),
1993 RuntimeValue::Uuid(u) => u.to_string(),
1994 RuntimeValue::Float(f) => logicaffeine_data::fmt::fmt_f64(*f),
1995 RuntimeValue::Bool(b) => if *b { "true" } else { "false" }.to_string(),
1996 RuntimeValue::Text(s) => s.as_str().to_string(),
1997 RuntimeValue::Char(c) => c.to_string(),
1998 RuntimeValue::List(items) => {
1999 let items = items.borrow();
2000 let parts: Vec<String> = items
2001 .to_values()
2002 .iter()
2003 .map(|v| v.to_display_string())
2004 .collect();
2005 format!("[{}]", parts.join(", "))
2006 }
2007 RuntimeValue::Tuple(items) => {
2008 let parts: Vec<String> = items.iter().map(|v| v.to_display_string()).collect();
2009 format!("({})", parts.join(", "))
2010 }
2011 RuntimeValue::Set(items) => {
2012 let items = items.borrow();
2013 let parts: Vec<String> = items.iter().map(|v| v.to_display_string()).collect();
2014 format!("{{{}}}", parts.join(", "))
2015 }
2016 RuntimeValue::Map(m) => {
2017 let m = m.borrow();
2018 let pairs: Vec<String> = m
2019 .iter()
2020 .map(|(k, v)| format!("{}: {}", k.to_display_string(), v.to_display_string()))
2021 .collect();
2022 format!("{{{}}}", pairs.join(", "))
2023 }
2024 RuntimeValue::Struct(s) => {
2025 if s.fields.is_empty() {
2026 s.type_name.clone()
2027 } else {
2028 let mut field_strs: Vec<(&str, String)> = s
2032 .fields
2033 .iter()
2034 .map(|(k, v)| (k.as_str(), v.to_display_string()))
2035 .collect();
2036 field_strs.sort_by(|a, b| a.0.cmp(b.0));
2037 let joined: Vec<String> = field_strs
2038 .iter()
2039 .map(|(k, v)| format!("{k}: {v}"))
2040 .collect();
2041 format!("{} {{ {} }}", s.type_name, joined.join(", "))
2042 }
2043 }
2044 RuntimeValue::Inductive(ind) => {
2045 if ind.inductive_type == "Option" {
2055 return match ind.args.first() {
2056 Some(inner) => inner.to_display_string(),
2057 None => "nothing".to_string(),
2058 };
2059 }
2060 if ind.args.is_empty() {
2061 ind.constructor.clone()
2062 } else {
2063 let arg_strs: Vec<String> =
2064 ind.args.iter().map(|v| v.to_display_string()).collect();
2065 format!("{}({})", ind.constructor, arg_strs.join(", "))
2066 }
2067 }
2068 RuntimeValue::Function(_) => "<closure>".to_string(),
2069 RuntimeValue::View(h) => crate::semantics::dom::render_children(*h),
2072 RuntimeValue::Action(_) => "<action>".to_string(),
2075 RuntimeValue::Chan(_) => "<channel>".to_string(),
2076 RuntimeValue::TaskHandle(_) => "<task>".to_string(),
2077 RuntimeValue::Peer(topic) => format!("<peer {topic}>"),
2078 RuntimeValue::Crdt(c) => c.borrow().render(),
2079 RuntimeValue::Nothing => "nothing".to_string(),
2080 RuntimeValue::Duration(nanos) => {
2081 let abs_nanos = nanos.unsigned_abs();
2083 let sign = if *nanos < 0 { "-" } else { "" };
2084 if abs_nanos >= 3_600_000_000_000 {
2085 format!("{}{}h", sign, abs_nanos / 3_600_000_000_000)
2087 } else if abs_nanos >= 60_000_000_000 {
2088 format!("{}{}min", sign, abs_nanos / 60_000_000_000)
2090 } else if abs_nanos >= 1_000_000_000 {
2091 format!("{}{}s", sign, abs_nanos / 1_000_000_000)
2093 } else if abs_nanos >= 1_000_000 {
2094 format!("{}{}ms", sign, abs_nanos / 1_000_000)
2096 } else if abs_nanos >= 1_000 {
2097 format!("{}{}μs", sign, abs_nanos / 1_000)
2099 } else {
2100 format!("{}{}ns", sign, abs_nanos)
2102 }
2103 }
2104 RuntimeValue::Date(days) => {
2105 let z = *days as i64 + 719468; let era = if z >= 0 { z } else { z - 146096 } / 146097;
2109 let doe = z - era * 146097;
2110 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2111 let y = yoe + era * 400;
2112 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2113 let mp = (5 * doy + 2) / 153;
2114 let d = doy - (153 * mp + 2) / 5 + 1;
2115 let m = mp + if mp < 10 { 3 } else { -9 };
2116 let year = y + if m <= 2 { 1 } else { 0 };
2117 format!("{:04}-{:02}-{:02}", year, m, d)
2118 }
2119 RuntimeValue::Moment(nanos) => {
2120 let total_seconds = nanos.div_euclid(1_000_000_000);
2125 let days = total_seconds.div_euclid(86400) as i32;
2126 let day_seconds = total_seconds.rem_euclid(86400);
2127 let hours = day_seconds / 3600;
2128 let minutes = (day_seconds % 3600) / 60;
2129
2130 let z = days as i64 + 719468;
2132 let era = if z >= 0 { z } else { z - 146096 } / 146097;
2133 let doe = z - era * 146097;
2134 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2135 let y = yoe + era * 400;
2136 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2137 let mp = (5 * doy + 2) / 153;
2138 let d = doy - (153 * mp + 2) / 5 + 1;
2139 let m = mp + if mp < 10 { 3 } else { -9 };
2140 let year = y + if m <= 2 { 1 } else { 0 };
2141
2142 format!("{:04}-{:02}-{:02} {:02}:{:02}", year, m, d, hours, minutes)
2143 }
2144 RuntimeValue::Span { months, days } => {
2145 let mut parts = Vec::new();
2147
2148 let years = *months / 12;
2150 let remaining_months = *months % 12;
2151
2152 if years != 0 {
2153 parts.push(if years.abs() == 1 {
2154 format!("{} year", years)
2155 } else {
2156 format!("{} years", years)
2157 });
2158 }
2159
2160 if remaining_months != 0 {
2161 parts.push(if remaining_months.abs() == 1 {
2162 format!("{} month", remaining_months)
2163 } else {
2164 format!("{} months", remaining_months)
2165 });
2166 }
2167
2168 if *days != 0 || parts.is_empty() {
2169 parts.push(if days.abs() == 1 {
2170 format!("{} day", days)
2171 } else {
2172 format!("{} days", days)
2173 });
2174 }
2175
2176 parts.join(" and ")
2177 }
2178 RuntimeValue::Time(nanos) => {
2179 logicaffeine_base::temporal::format_time_of_day(*nanos)
2181 }
2182 }
2183 }
2184}
2185
2186pub enum ControlFlow {
2191 Continue,
2193 Return(RuntimeValue),
2195 Break,
2197}
2198
2199#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2201pub struct ActionRef {
2202 pub instance: String,
2203 pub name: Symbol,
2204}
2205
2206#[derive(Clone)]
2211pub struct FunctionDef<'a> {
2212 pub params: Vec<(Symbol, &'a TypeExpr<'a>)>,
2214 pub body: Block<'a>,
2216 pub return_type: Option<&'a TypeExpr<'a>>,
2218 pub is_native: bool,
2221 pub native_path: Option<Symbol>,
2223}
2224
2225struct Environment {
2239 globals: HashMap<Symbol, RuntimeValue>,
2241 main_block: HashMap<Symbol, RuntimeValue>,
2244 locals: HashMap<Symbol, RuntimeValue>,
2246 save_stack: Vec<Vec<(Symbol, Option<RuntimeValue>)>>,
2247 frame_stack: Vec<(
2251 HashMap<Symbol, RuntimeValue>,
2252 Vec<Vec<(Symbol, Option<RuntimeValue>)>>,
2253 )>,
2254}
2255
2256impl Environment {
2257 fn new() -> Self {
2258 Environment {
2259 globals: HashMap::new(),
2260 main_block: HashMap::new(),
2261 locals: HashMap::new(),
2262 save_stack: Vec::new(),
2263 frame_stack: Vec::new(),
2264 }
2265 }
2266
2267 fn in_function(&self) -> bool {
2268 !self.frame_stack.is_empty()
2269 }
2270
2271 fn define_map(&mut self) -> &mut HashMap<Symbol, RuntimeValue> {
2274 if !self.frame_stack.is_empty() {
2275 &mut self.locals
2276 } else if !self.save_stack.is_empty() {
2277 &mut self.main_block
2278 } else {
2279 &mut self.globals
2280 }
2281 }
2282
2283 fn push_frame(&mut self) {
2286 self.frame_stack.push((
2287 std::mem::take(&mut self.locals),
2288 std::mem::take(&mut self.save_stack),
2289 ));
2290 }
2291
2292 fn pop_frame(&mut self) {
2294 let (locals, saves) = self.frame_stack.pop().unwrap_or_default();
2295 self.locals = locals;
2296 self.save_stack = saves;
2297 }
2298
2299 fn push_scope(&mut self) {
2300 self.save_stack.push(Vec::new());
2301 }
2302
2303 fn pop_scope(&mut self) {
2304 if let Some(saves) = self.save_stack.pop() {
2305 let map = if !self.frame_stack.is_empty() {
2306 &mut self.locals
2307 } else {
2308 &mut self.main_block
2311 };
2312 for (sym, old_val) in saves.into_iter().rev() {
2313 match old_val {
2314 Some(val) => {
2315 map.insert(sym, val);
2316 }
2317 None => {
2318 map.remove(&sym);
2319 }
2320 }
2321 }
2322 }
2323 }
2324
2325 fn define(&mut self, name: Symbol, value: RuntimeValue) {
2326 let map = self.define_map();
2327 let old = map.insert(name, value);
2328 if let Some(frame) = self.save_stack.last_mut() {
2329 frame.push((name, old));
2330 }
2331 }
2332
2333 fn lookup(&self, name: Symbol) -> Option<&RuntimeValue> {
2334 if self.in_function() {
2335 self.locals.get(&name).or_else(|| self.globals.get(&name))
2336 } else {
2337 self.main_block
2338 .get(&name)
2339 .or_else(|| self.globals.get(&name))
2340 }
2341 }
2342
2343 fn lookup_mut(&mut self, name: Symbol) -> Option<&mut RuntimeValue> {
2345 let scoped = if self.in_function() {
2346 &mut self.locals
2347 } else {
2348 &mut self.main_block
2349 };
2350 if scoped.contains_key(&name) {
2351 return scoped.get_mut(&name);
2352 }
2353 self.globals.get_mut(&name)
2354 }
2355
2356 fn take_local(&mut self, name: Symbol) -> Option<RuntimeValue> {
2358 self.locals.remove(&name)
2359 }
2360
2361 fn assign(&mut self, name: Symbol, value: RuntimeValue) -> bool {
2362 if self.in_function() {
2363 if self.locals.contains_key(&name) {
2364 self.locals.insert(name, value);
2365 return true;
2366 }
2367 } else if self.main_block.contains_key(&name) {
2368 self.main_block.insert(name, value);
2369 return true;
2370 }
2371 if self.globals.contains_key(&name) {
2372 self.globals.insert(name, value);
2373 true
2374 } else {
2375 false
2376 }
2377 }
2378}
2379
2380#[derive(Clone)]
2384pub enum ClosureBodyRef<'a> {
2385 Expression(&'a Expr<'a>),
2386 Block(Block<'a>),
2387}
2388
2389const REDUNDANT_K: usize = 4;
2394const REDUNDANT_N: usize = 6;
2395
2396pub struct Interpreter<'a> {
2397 ctx: SharedCtx<'a>,
2402 task: TaskState,
2405 pub output: Vec<String>,
2407 pub current_site: Option<u32>,
2416 yield_state: Option<crate::concurrency::bridge::Yield<'a>>,
2419 err_sink: Option<ErrSink>,
2423 netbox: crate::concurrency::net_inbox::NetInbox,
2428 tcpbox: crate::concurrency::tcp_registry::TcpRegistry,
2431 test_mode: bool,
2435 test_failures: Vec<String>,
2437 test_ops: u64,
2440 test_assertions: u64,
2445 test_budget: u64,
2447 gen_rng: u64,
2450 prove_mode: bool,
2453 properties_proven: u64,
2455 fuel: Option<FuelHandles>,
2461 request_deadline: Option<std::time::Instant>,
2473 deadline_tick: u32,
2476 tiers_noop: bool,
2481 page: PageSeat<'a>,
2483 statement_observer: Option<Box<dyn FnMut(usize) + 'a>>,
2487 page_main: Option<Vec<Stmt<'a>>>,
2491 failed_call_site: Option<u32>,
2494 defined_run: Option<crate::semantics::defined::RunScope<'a>>,
2497}
2498
2499enum PageSeat<'a> {
2501 Unseated,
2503 Driven(std::rc::Rc<std::cell::RefCell<dyn crate::page_host::DrivenPage + 'a>>),
2505 Here(HostedPage),
2508}
2509
2510struct HostedPage {
2512 host: Option<crate::page_host::LoweredHost>,
2515 refused: Option<(crate::page_host::Drive, String)>,
2518}
2519
2520impl HostedPage {
2521 fn of(page: Option<String>) -> Self {
2523 HostedPage {
2524 host: Some(crate::page_host::LoweredHost::of_page(page)),
2525 refused: None,
2526 }
2527 }
2528}
2529
2530#[derive(Clone)]
2537pub struct FuelHandles {
2538 pub budget: u64,
2540 pub remaining: std::rc::Rc<std::cell::Cell<u64>>,
2542 pub exhausted: std::rc::Rc<std::cell::Cell<bool>>,
2544}
2545
2546impl FuelHandles {
2547 pub fn exhaust_message(&self) -> String {
2549 format!(
2550 "step budget of {} exhausted — the program was stopped at a deterministic op; \
2551 raise --max-steps (or the MCP step_budget) to allow more",
2552 self.budget
2553 )
2554 }
2555}
2556
2557thread_local! {
2558 static ACTIVE_FUEL: std::cell::RefCell<Option<FuelHandles>> = const { std::cell::RefCell::new(None) };
2563}
2564
2565pub fn install_fuel(budget: u64) -> FuelHandles {
2568 let handles = FuelHandles {
2569 budget,
2570 remaining: std::rc::Rc::new(std::cell::Cell::new(budget)),
2571 exhausted: std::rc::Rc::new(std::cell::Cell::new(false)),
2572 };
2573 ACTIVE_FUEL.with(|cell| *cell.borrow_mut() = Some(handles.clone()));
2574 handles
2575}
2576
2577pub fn clear_fuel() {
2579 ACTIVE_FUEL.with(|cell| *cell.borrow_mut() = None);
2580}
2581
2582pub fn active_fuel() -> Option<FuelHandles> {
2584 ACTIVE_FUEL.with(|cell| cell.borrow().clone())
2585}
2586
2587#[derive(Clone)]
2592struct SharedCtx<'a> {
2593 interner: &'a Interner,
2594 functions: HashMap<Symbol, FunctionDef<'a>>,
2595 components: HashMap<Symbol, crate::ast::component::ComponentDef<'a>>,
2599 types: Option<crate::analysis::TypeRegistry>,
2602 struct_defs: HashMap<Symbol, Vec<(Symbol, Symbol, bool)>>,
2603 enum_defs: HashMap<Symbol, Vec<Symbol>>,
2607 variant_fields: HashMap<(Symbol, Symbol), Vec<Symbol>>,
2625 vfs: Option<Arc<dyn Vfs>>,
2626 kernel_ctx: Option<Arc<crate::kernel::Context>>,
2627 policy_registry: Option<PolicyRegistry>,
2628 output_callback: Option<OutputCallback>,
2629 closure_bodies: Vec<ClosureBodyRef<'a>>,
2632 sym_show: Option<Symbol>,
2634 sym_length: Option<Symbol>,
2635 sym_format: Option<Symbol>,
2636 sym_parse_int: Option<Symbol>,
2637 sym_parse_float: Option<Symbol>,
2638 sym_abs: Option<Symbol>,
2639 sym_sqrt: Option<Symbol>,
2640 sym_min: Option<Symbol>,
2641 sym_max: Option<Symbol>,
2642 sym_floor: Option<Symbol>,
2643 sym_ceil: Option<Symbol>,
2644 sym_round: Option<Symbol>,
2645 sym_pow: Option<Symbol>,
2646 sym_copy: Option<Symbol>,
2647 sym_chr: Option<Symbol>,
2648 sym_count_ones: Option<Symbol>,
2649 sym_args: Option<Symbol>,
2650 program_args: Vec<String>,
2653}
2654
2655struct TaskState {
2660 env: Environment,
2662 call_depth: usize,
2664 tco_fn_sync: Option<Symbol>,
2670 pending_tail_call: Option<Vec<RuntimeValue>>,
2673 repeat_depth_sync: usize,
2678 tco_fn_async: Option<Symbol>,
2680 pending_tail_call_async: Option<Vec<RuntimeValue>>,
2682 repeat_depth_async: usize,
2684}
2685
2686impl TaskState {
2687 fn new() -> Self {
2688 TaskState {
2689 env: Environment::new(),
2690 call_depth: 0,
2691 tco_fn_sync: None,
2692 pending_tail_call: None,
2693 repeat_depth_sync: 0,
2694 tco_fn_async: None,
2695 pending_tail_call_async: None,
2696 repeat_depth_async: 0,
2697 }
2698 }
2699}
2700
2701pub(crate) const REQUEST_TIMED_OUT: &str = "request exceeded its time budget";
2705
2706impl<'a> Interpreter<'a> {
2707 pub fn new(interner: &'a Interner) -> Self {
2708 Interpreter {
2709 ctx: SharedCtx {
2710 interner,
2711 functions: HashMap::new(),
2712 components: HashMap::new(),
2713 types: None,
2714 struct_defs: HashMap::new(),
2715 enum_defs: HashMap::new(),
2716 variant_fields: HashMap::new(),
2717 vfs: None,
2718 kernel_ctx: None,
2719 policy_registry: None,
2720 output_callback: None,
2721 closure_bodies: Vec::new(),
2722 sym_show: interner.lookup("show"),
2723 sym_length: interner.lookup("length"),
2724 sym_format: interner.lookup("format"),
2725 sym_parse_int: interner.lookup("parseInt"),
2726 sym_parse_float: interner.lookup("parseFloat"),
2727 sym_abs: interner.lookup("abs"),
2728 sym_sqrt: interner.lookup("sqrt"),
2729 sym_min: interner.lookup("min"),
2730 sym_max: interner.lookup("max"),
2731 sym_floor: interner.lookup("floor"),
2732 sym_ceil: interner.lookup("ceil"),
2733 sym_round: interner.lookup("round"),
2734 sym_pow: interner.lookup("pow"),
2735 sym_copy: interner.lookup("copy"),
2736 sym_chr: interner.lookup("chr"),
2737 sym_count_ones: interner.lookup("count_ones"),
2738 sym_args: interner.lookup("args"),
2739 program_args: crate::semantics::argv_with_program_name(Vec::new()),
2740 },
2741 task: TaskState::new(),
2742 output: Vec::new(),
2743 current_site: None,
2744 yield_state: None,
2745 err_sink: None,
2746 netbox: crate::concurrency::net_inbox::NetInbox::new(),
2747 tcpbox: crate::concurrency::tcp_registry::TcpRegistry::new(),
2748 test_mode: false,
2749 test_failures: Vec::new(),
2750 test_ops: 0,
2751 test_assertions: 0,
2752 test_budget: u64::MAX,
2753 gen_rng: 0,
2754 prove_mode: false,
2755 properties_proven: 0,
2756 fuel: active_fuel(),
2757 request_deadline: None,
2758 deadline_tick: 0,
2759 tiers_noop: false,
2760 page: PageSeat::Here(HostedPage::of(None)),
2761 statement_observer: None,
2762 page_main: None,
2763 failed_call_site: None,
2764 defined_run: None,
2765 }
2766 }
2767
2768 pub fn enable_test_mode(&mut self, budget: u64) {
2771 self.test_mode = true;
2772 self.test_budget = budget;
2773 }
2774
2775 pub fn set_tiers_noop(&mut self, on: bool) {
2779 self.tiers_noop = on;
2780 }
2781
2782 pub fn set_gen_seed(&mut self, seed: u64) {
2785 self.gen_rng = seed;
2786 }
2787
2788 pub fn set_prove_mode(&mut self, on: bool) {
2790 self.prove_mode = on;
2791 }
2792
2793 pub fn properties_proven(&self) -> u64 {
2795 self.properties_proven
2796 }
2797
2798 fn draw_u64(&mut self) -> u64 {
2800 self.gen_rng = self.gen_rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
2801 let mut z = self.gen_rng;
2802 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2803 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
2804 z ^ (z >> 31)
2805 }
2806
2807 fn draw_domain(&mut self, domain: crate::ast::stmt::PropDomain) -> RuntimeValue {
2810 use crate::ast::stmt::PropDomain;
2811 let r = self.draw_u64();
2812 match domain {
2813 PropDomain::Integers => RuntimeValue::Int((r % 2001) as i64 - 1000),
2814 PropDomain::Naturals => RuntimeValue::Int((r % 1001) as i64),
2815 PropDomain::Booleans => RuntimeValue::Bool(r & 1 == 0),
2816 }
2817 }
2818
2819 fn run_property(
2824 &mut self,
2825 vars: &[Symbol],
2826 domain: crate::ast::stmt::PropDomain,
2827 constraint: Option<&'a Expr<'a>>,
2828 body: &[Stmt<'a>],
2829 ) -> Result<(), String> {
2830 use crate::ast::stmt::PropDomain;
2831 self.test_assertions += 1;
2834 if self.prove_mode && domain == PropDomain::Booleans && vars.len() <= 16 {
2837 let total = 1usize << vars.len();
2838 let mut counterexample: Option<Vec<RuntimeValue>> = None;
2839 for mask in 0..total {
2840 let vals: Vec<RuntimeValue> = (0..vars.len())
2841 .map(|i| RuntimeValue::Bool(mask & (1 << i) != 0))
2842 .collect();
2843 if self.property_fails(vars, constraint, body, &vals)? {
2844 counterexample = Some(vals);
2845 break;
2846 }
2847 }
2848 if let Some(vals) = counterexample {
2849 self.record_counterexample(vars, constraint, body, vals)?;
2850 } else {
2851 self.properties_proven += 1; }
2853 return Ok(());
2854 }
2855
2856 const RUNS: u32 = 256;
2857 let mut counterexample: Option<Vec<RuntimeValue>> = None;
2858 for _ in 0..RUNS {
2859 let vals: Vec<RuntimeValue> =
2860 (0..vars.len()).map(|_| self.draw_domain(domain)).collect();
2861 if self.property_fails(vars, constraint, body, &vals)? {
2862 counterexample = Some(vals);
2863 break;
2864 }
2865 }
2866 if let Some(vals) = counterexample {
2867 self.record_counterexample(vars, constraint, body, vals)?;
2868 }
2869 Ok(())
2870 }
2871
2872 fn record_counterexample(
2874 &mut self,
2875 vars: &[Symbol],
2876 constraint: Option<&'a Expr<'a>>,
2877 body: &[Stmt<'a>],
2878 vals: Vec<RuntimeValue>,
2879 ) -> Result<(), String> {
2880 let shrunk = self.shrink_property(vars, constraint, body, vals)?;
2881 let binding = vars
2882 .iter()
2883 .zip(shrunk.iter())
2884 .map(|(v, val)| {
2885 format!(
2886 "{} = {}",
2887 self.ctx.interner.resolve(*v),
2888 val.to_display_string()
2889 )
2890 })
2891 .collect::<Vec<_>>()
2892 .join(", ");
2893 self.test_failures
2894 .push(format!("Property failed. Counterexample: {binding}"));
2895 Ok(())
2896 }
2897
2898 fn property_fails(
2901 &mut self,
2902 vars: &[Symbol],
2903 constraint: Option<&'a Expr<'a>>,
2904 body: &[Stmt<'a>],
2905 vals: &[RuntimeValue],
2906 ) -> Result<bool, String> {
2907 for (v, val) in vars.iter().zip(vals.iter()) {
2908 self.define(*v, val.clone());
2909 }
2910 if let Some(c) = constraint {
2911 if !self.evaluate_expr_sync(c)?.decided_truth()? {
2912 return Ok(false); }
2914 }
2915 let before = self.test_failures.len();
2916 for s in body.iter() {
2917 self.execute_stmt_sync(s)?;
2918 }
2919 let failed = self.test_failures.len() > before;
2920 self.test_failures.truncate(before);
2921 Ok(failed)
2922 }
2923
2924 fn shrink_property(
2927 &mut self,
2928 vars: &[Symbol],
2929 constraint: Option<&'a Expr<'a>>,
2930 body: &[Stmt<'a>],
2931 mut vals: Vec<RuntimeValue>,
2932 ) -> Result<Vec<RuntimeValue>, String> {
2933 let mut improved = true;
2934 let mut guard = 0;
2935 while improved && guard < 1000 {
2936 improved = false;
2937 guard += 1;
2938 for i in 0..vals.len() {
2939 for cand in shrink_candidates(&vals[i]) {
2940 let mut trial = vals.clone();
2941 trial[i] = cand;
2942 if self.property_fails(vars, constraint, body, &trial)? {
2943 vals = trial;
2944 improved = true;
2945 break;
2946 }
2947 }
2948 }
2949 }
2950 Ok(vals)
2951 }
2952
2953 pub fn take_test_failures(&mut self) -> Vec<String> {
2955 std::mem::take(&mut self.test_failures)
2956 }
2957
2958 pub fn test_ops(&self) -> u64 {
2960 self.test_ops
2961 }
2962
2963 pub fn test_assertions(&self) -> u64 {
2966 self.test_assertions
2967 }
2968
2969 fn tick_test_budget(&mut self) -> Result<(), String> {
2974 if let Some(deadline) = self.request_deadline {
2977 self.deadline_tick = self.deadline_tick.wrapping_add(1);
2978 if self.deadline_tick % 512 == 0 && std::time::Instant::now() > deadline {
2979 return Err(REQUEST_TIMED_OUT.to_string());
2980 }
2981 }
2982 if let Some(fuel) = &self.fuel {
2983 let left = fuel.remaining.get();
2984 if left == 0 {
2985 fuel.exhausted.set(true);
2986 return Err(fuel.exhaust_message());
2987 }
2988 fuel.remaining.set(left - 1);
2989 }
2990 if !self.test_mode {
2991 return Ok(());
2992 }
2993 self.test_ops += 1;
2994 if self.test_ops > self.test_budget {
2995 return Err(format!(
2996 "op budget of {} steps exhausted — a runaway test fails at the identical op \
2997 on every run; a test that legitimately needs more declares it: \
2998 `This test may run up to {} steps.`",
2999 self.test_budget,
3000 self.test_budget.saturating_mul(10)
3001 ));
3002 }
3003 Ok(())
3004 }
3005
3006 fn expect_socratic_hint(condition: &Expr<'a>) -> Option<&'static str> {
3009 if let Expr::BinaryOp {
3010 op: BinaryOpKind::Eq,
3011 left,
3012 right,
3013 } = condition
3014 {
3015 let floaty = |e: &Expr<'a>| matches!(e, Expr::Literal(Literal::Float(_)));
3016 if floaty(left) || floaty(right) {
3017 return Some(
3018 "floats drift — did you mean `is approximately X within <eps>`? (bare `is` is IEEE bit-exact)",
3019 );
3020 }
3021 }
3022 None
3023 }
3024
3025 pub fn with_program_args(mut self, args: Vec<String>) -> Self {
3029 self.ctx.program_args = crate::semantics::argv_with_program_name(args);
3030 self
3031 }
3032
3033 pub fn with_vfs(mut self, vfs: Arc<dyn Vfs>) -> Self {
3035 self.ctx.vfs = Some(vfs);
3036 self
3037 }
3038
3039 pub fn with_kernel(mut self, ctx: Arc<crate::kernel::Context>) -> Self {
3044 self.ctx.kernel_ctx = Some(ctx);
3045 self
3046 }
3047
3048 pub fn with_policies(mut self, registry: PolicyRegistry) -> Self {
3050 self.ctx.policy_registry = Some(registry);
3051 self
3052 }
3053
3054 pub fn with_type_registry(mut self, registry: &crate::analysis::TypeRegistry) -> Self {
3058 use crate::analysis::registry::{FieldType, TypeDef};
3059 self.ctx.types = Some(registry.clone());
3060 for (name_sym, type_def) in registry.iter_types() {
3061 if let TypeDef::Struct { fields, .. } = type_def {
3062 let field_defs: Vec<(Symbol, Symbol, bool)> = fields
3063 .iter()
3064 .map(|f| {
3065 let type_sym = match &f.ty {
3066 FieldType::Primitive(s)
3067 | FieldType::Named(s)
3068 | FieldType::TypeParam(s) => *s,
3069 FieldType::Generic { base, .. } => *base,
3070 FieldType::Tuple(_) | FieldType::Record(_) => Symbol::EMPTY,
3072 };
3073 (f.name, type_sym, f.is_public)
3074 })
3075 .collect();
3076 self.ctx.struct_defs.insert(*name_sym, field_defs);
3077 } else if let TypeDef::Enum { variants, .. } = type_def {
3078 let ctors: Vec<Symbol> = variants.iter().map(|v| v.name).collect();
3081 self.ctx.enum_defs.insert(*name_sym, ctors);
3082 for v in variants {
3086 let field_names: Vec<Symbol> = v.fields.iter().map(|f| f.name).collect();
3087 self.ctx
3088 .variant_fields
3089 .insert((*name_sym, v.name), field_names);
3090 }
3091 }
3092 }
3093 self
3094 }
3095
3096 pub fn with_output_callback(mut self, callback: OutputCallback) -> Self {
3099 self.ctx.output_callback = Some(callback);
3100 self
3101 }
3102
3103 pub fn with_page(
3109 mut self,
3110 p: std::rc::Rc<std::cell::RefCell<dyn crate::page_host::DrivenPage + 'a>>,
3111 ) -> Self {
3112 self.page = PageSeat::Driven(p);
3113 self
3114 }
3115
3116 pub fn with_statement_observer(mut self, f: Box<dyn FnMut(usize) + 'a>) -> Self {
3118 self.statement_observer = Some(f);
3119 self
3120 }
3121
3122 pub fn host_lowered_page(
3130 &mut self,
3131 program: &[Stmt<'a>],
3132 auto_mounted: Option<String>,
3133 ) -> Result<(), crate::page_host::DriveError> {
3134 self.page = PageSeat::Here(HostedPage::of(auto_mounted));
3135 let ran = self.run_page_main(program);
3136 self.with_hosted_page(|host, me| host.settle(me));
3137 ran.map_err(crate::page_host::DriveError::Failed)
3138 }
3139
3140 fn with_hosted_page<R>(
3143 &mut self,
3144 f: impl FnOnce(&mut crate::page_host::LoweredHost, &mut Self) -> R,
3145 ) -> Option<R> {
3146 let PageSeat::Here(hosted) = &mut self.page else {
3147 return None;
3148 };
3149 let mut host = hosted.host.take()?;
3150 let out = f(&mut host, self);
3151 if let PageSeat::Here(hosted) = &mut self.page {
3152 hosted.host = Some(host);
3153 }
3154 Some(out)
3155 }
3156
3157 pub fn hosted_page_failure(&self) -> Option<String> {
3160 match &self.page {
3161 PageSeat::Here(HostedPage {
3162 host: Some(host), ..
3163 }) => host.unhandled_failure().map(str::to_string),
3164 _ => None,
3165 }
3166 }
3167
3168 pub fn page_failure_site(&self) -> Option<u32> {
3171 match &self.page {
3172 PageSeat::Here(HostedPage {
3173 host: Some(host), ..
3174 }) => host.unhandled_failure_site(),
3175 _ => None,
3176 }
3177 }
3178
3179 pub fn take_page_failure(&mut self) -> Option<String> {
3183 match &mut self.page {
3184 PageSeat::Unseated => None,
3185 PageSeat::Driven(page) => page.borrow().unhandled_failure(),
3186 PageSeat::Here(hosted) => hosted
3187 .host
3188 .as_mut()
3189 .and_then(|h| h.take_unhandled_failure()),
3190 }
3191 }
3192
3193 pub fn hosted_page_refusal(&self) -> Option<(&crate::page_host::Drive, &str)> {
3196 match &self.page {
3197 PageSeat::Here(HostedPage {
3198 refused: Some((d, why)),
3199 ..
3200 }) => Some((d, why.as_str())),
3201 _ => None,
3202 }
3203 }
3204
3205 pub fn run_statements(&mut self, stmts: &[Stmt<'a>]) -> Result<ControlFlow, String> {
3210 for stmt in stmts {
3211 match self.execute_stmt_sync(stmt)? {
3212 ControlFlow::Continue => {}
3213 flow => return Ok(flow),
3214 }
3215 }
3216 Ok(ControlFlow::Continue)
3217 }
3218
3219 pub async fn run_statements_async(
3221 &mut self,
3222 stmts: &[Stmt<'a>],
3223 ) -> Result<ControlFlow, String> {
3224 for stmt in stmts {
3225 match self.execute_stmt(stmt).await? {
3226 ControlFlow::Continue => {}
3227 flow => return Ok(flow),
3228 }
3229 }
3230 Ok(ControlFlow::Continue)
3231 }
3232
3233 fn drive_page(&mut self, d: crate::page_host::Drive) -> Result<ControlFlow, String> {
3237 let outcome = match &mut self.page {
3238 PageSeat::Unseated => {
3239 return Err(format!(
3240 "`{}` drives the page, and a task launched beside the test has no page to drive",
3241 d.verb()
3242 ))
3243 }
3244 PageSeat::Driven(page) => {
3245 let page = page.clone();
3246 let outcome = page.borrow_mut().drive(&d);
3247 outcome
3248 }
3249 PageSeat::Here(_) => {
3250 let Some(mut outcome) = self.with_hosted_page(|host, me| host.drive(me, &d)) else {
3251 return Err(format!(
3252 "`{}` drives the page, and the page's own code cannot drive the page it \
3253 is running in",
3254 d.verb()
3255 ));
3256 };
3257 if let (
3258 crate::page_host::Drive::Mount { component, .. },
3259 Err(crate::page_host::DriveError::Refused(why)),
3260 ) = (&d, &mut outcome)
3261 {
3262 if let Some(reason) = self.why_not_lowered(component) {
3263 *why = reason;
3264 }
3265 }
3266 if let (PageSeat::Here(hosted), Err(crate::page_host::DriveError::Refused(why))) =
3267 (&mut self.page, &outcome)
3268 {
3269 hosted
3270 .refused
3271 .get_or_insert_with(|| (d.clone(), why.clone()));
3272 }
3273 outcome
3274 }
3275 };
3276 outcome.map_err(|e| match e {
3277 crate::page_host::DriveError::Failed(m) | crate::page_host::DriveError::Refused(m) => m,
3278 })?;
3279 Ok(ControlFlow::Continue)
3280 }
3281
3282 fn why_not_lowered(&self, component: &str) -> Option<String> {
3287 let all: Vec<crate::ast::component::ComponentDef<'a>> =
3288 self.ctx.components.values().cloned().collect();
3289 let def = all
3290 .iter()
3291 .find(|d| self.ctx.interner.resolve(d.name) == component)?;
3292 logicaffeine_language::parser::lgx_lower::lowerable(
3293 def,
3294 &all,
3295 self.ctx.types.as_ref(),
3296 self.ctx.interner,
3297 )
3298 .err()
3299 .map(|why| {
3300 format!(
3301 "`Mount {component}` cannot run on this tier: {}",
3302 why.message
3303 )
3304 })
3305 }
3306
3307 fn serve_fetches_sync(&mut self) -> Result<ControlFlow, String> {
3309 self.drive_page(crate::page_host::Drive::ServeFetchesWithRoutes)
3310 }
3311
3312 fn given_fetch_sync(
3315 &mut self,
3316 method: Symbol,
3317 url: &'a Expr<'a>,
3318 status: &'a Expr<'a>,
3319 body: &'a Expr<'a>,
3320 ) -> Result<ControlFlow, String> {
3321 let u = self.evaluate_expr_sync(url)?.to_display_string();
3322 let st = match self.evaluate_expr_sync(status)? {
3323 RuntimeValue::Int(n) => n,
3324 other => {
3325 return Err(format!(
3326 "`Given that … answers …` wants a numeric status, got {}.",
3327 other.type_name()
3328 ))
3329 }
3330 };
3331 let b = self.evaluate_expr_sync(body)?.to_display_string();
3332 self.drive_page(crate::page_host::Drive::AnswerFetch {
3333 method: self.ctx.interner.resolve(method).to_string(),
3334 url: u,
3335 status: st,
3336 body: b,
3337 })
3338 }
3339
3340 fn advance_time_ms(&mut self, ms: u64) -> Result<ControlFlow, String> {
3344 self.drive_page(crate::page_host::Drive::AdvanceTime { ms })
3345 }
3346
3347 pub(crate) fn install_yield_state(
3350 &mut self,
3351 ys: crate::concurrency::bridge::Yield<'a>,
3352 err_sink: ErrSink,
3353 ) {
3354 self.yield_state = Some(ys);
3355 self.err_sink = Some(err_sink);
3356 }
3357
3358 fn emit_output(&mut self, line: String) {
3360 if let Some(ref callback) = self.ctx.output_callback {
3361 (callback.borrow_mut())(line.clone());
3362 }
3363 self.output.push(line);
3364 }
3365
3366 pub fn is_kernel_inductive(&self, name: &str) -> bool {
3368 self.ctx
3369 .kernel_ctx
3370 .as_ref()
3371 .map(|ctx| ctx.is_inductive(name))
3372 .unwrap_or(false)
3373 }
3374
3375 pub fn get_kernel_constructors(&self, name: &str) -> Vec<(String, usize)> {
3379 self.ctx
3380 .kernel_ctx
3381 .as_ref()
3382 .map(|ctx| {
3383 ctx.get_constructors(name)
3384 .iter()
3385 .map(|(ctor_name, ty)| {
3386 let arity = count_pi_args(ty);
3388 (ctor_name.to_string(), arity)
3389 })
3390 .collect()
3391 })
3392 .unwrap_or_default()
3393 }
3394
3395 fn replay_actions(&mut self, actions: &[Symbol]) -> Result<(), String> {
3405 let named = actions
3406 .iter()
3407 .map(|a| self.ctx.interner.resolve(*a).to_string())
3408 .collect();
3409 self.drive_page(crate::page_host::Drive::Replay { actions: named })
3410 .map(|_| ())
3411 }
3412
3413 fn json_of_value(value: &RuntimeValue) -> Option<serde_json::Value> {
3416 use serde_json::Value;
3417 Some(match value {
3418 RuntimeValue::Text(s) => Value::String(s.to_string()),
3419 RuntimeValue::Int(n) => serde_json::json!(n),
3420 RuntimeValue::Float(f) => serde_json::json!(f),
3421 RuntimeValue::Bool(b) => Value::Bool(*b),
3422 RuntimeValue::Char(c) => Value::String(c.to_string()),
3423 RuntimeValue::List(items) => {
3424 let elems: Option<Vec<Value>> = items
3425 .borrow()
3426 .to_values()
3427 .iter()
3428 .map(Self::json_of_value)
3429 .collect();
3430 Value::Array(elems?)
3431 }
3432 RuntimeValue::Struct(s) => {
3433 let mut map = serde_json::Map::new();
3434 for (k, v) in &s.fields {
3435 map.insert(k.clone(), Self::json_of_value(v)?);
3436 }
3437 Value::Object(map)
3438 }
3439 _ => return None,
3440 })
3441 }
3442
3443 fn value_from_json_untyped(json: &serde_json::Value) -> Option<RuntimeValue> {
3447 use serde_json::Value;
3448 match json {
3449 Value::String(s) => Some(RuntimeValue::Text(Rc::new(s.clone()))),
3450 Value::Bool(b) => Some(RuntimeValue::Bool(*b)),
3451 Value::Number(n) => match n.as_i64() {
3452 Some(i) => Some(RuntimeValue::Int(i)),
3453 None => n.as_f64().map(RuntimeValue::Float),
3454 },
3455 Value::Array(arr) => {
3456 let values: Option<Vec<RuntimeValue>> =
3457 arr.iter().map(Self::value_from_json_untyped).collect();
3458 Some(RuntimeValue::List(Rc::new(RefCell::new(
3459 ListRepr::from_values(values?),
3460 ))))
3461 }
3462 _ => None,
3463 }
3464 }
3465
3466 fn tagged_storage_text(value: &RuntimeValue) -> Option<String> {
3472 let tag = match value {
3473 RuntimeValue::Int(_) => 'i',
3474 RuntimeValue::Float(_) => 'f',
3475 RuntimeValue::Bool(_) => 'b',
3476 RuntimeValue::Text(_) | RuntimeValue::Char(_) => 't',
3477 RuntimeValue::List(_) | RuntimeValue::Struct(_) => 'j',
3478 _ => return None,
3479 };
3480 let body = if tag == 'j' {
3481 Self::json_of_value(value)?.to_string()
3482 } else {
3483 value.to_display_string()
3484 };
3485 Some(format!("{tag}:{body}"))
3486 }
3487
3488 fn value_from_tagged_storage(text: &str) -> Option<RuntimeValue> {
3492 let (tag, body) = text.split_once(':')?;
3493 Some(match tag {
3494 "i" => RuntimeValue::Int(body.parse().ok()?),
3495 "f" => RuntimeValue::Float(body.parse().ok()?),
3496 "b" => match body {
3497 "true" => RuntimeValue::Bool(true),
3498 "false" => RuntimeValue::Bool(false),
3499 _ => return None,
3500 },
3501 "t" => RuntimeValue::Text(Rc::new(body.to_string())),
3502 "j" => Self::value_from_json_untyped(&serde_json::from_str(body).ok()?)?,
3503 _ => return None,
3504 })
3505 }
3506
3507 fn evaluate_dom_query(
3510 &mut self,
3511 query: &crate::ast::stmt::DomQuery<'a>,
3512 ) -> Result<RuntimeValue, String> {
3513 use crate::ast::stmt::DomQuery;
3514 use crate::semantics::dom;
3515 let selector = match query.selector() {
3516 Some(sel) => Some(self.evaluate_expr_sync(sel)?),
3517 None => None,
3518 };
3519 if let (DomQuery::Count { .. }, Some(v)) = (query, &selector) {
3530 if !matches!(v, RuntimeValue::Text(_)) {
3531 return crate::semantics::collections::length_of(v);
3532 }
3533 }
3534 let sel = selector
3535 .as_ref()
3536 .map(|v| v.to_display_string())
3537 .unwrap_or_default();
3538 let one = |q: &str| -> Result<i64, String> {
3539 let node = dom::query_selector(&sel);
3540 if node < 0 {
3541 return Err(format!(
3542 "No element matches {sel:?}, so it has no {q}. Mount the component first, and \
3543 check the selector against the ids and classes its view renders."
3544 ));
3545 }
3546 Ok(node)
3547 };
3548 Ok(match query {
3549 DomQuery::Text { .. } => RuntimeValue::Text(Rc::new(dom::text_content(one("text")?))),
3550 DomQuery::Value { .. } => RuntimeValue::Text(Rc::new(dom::get_value(one("value")?))),
3551 DomQuery::Count { .. } => RuntimeValue::Int(dom::query_selector_all(&sel).len() as i64),
3552 DomQuery::Visible { .. } => RuntimeValue::Bool(dom::is_shown(&sel)),
3558 DomQuery::Hidden { .. } => RuntimeValue::Bool(!dom::is_shown(&sel)),
3562 DomQuery::Disabled { .. } => {
3565 let node = dom::query_selector(&sel);
3566 RuntimeValue::Bool(node >= 0 && dom::has_attribute(node, "disabled"))
3567 }
3568 DomQuery::Checked { .. } => {
3571 let node = dom::query_selector(&sel);
3572 RuntimeValue::Bool(node >= 0 && dom::get_checked(node))
3573 }
3574 DomQuery::Focused { .. } => {
3575 let node = dom::query_selector(&sel);
3576 RuntimeValue::Bool(node >= 0 && dom::focused() == node)
3577 }
3578 DomQuery::Journal => {
3581 let names: Vec<RuntimeValue> = crate::semantics::world::journal()
3582 .into_iter()
3583 .map(|e| RuntimeValue::Text(Rc::new(e.action)))
3584 .collect();
3585 RuntimeValue::List(Rc::new(RefCell::new(crate::interpreter::ListRepr::Boxed(
3586 names,
3587 ))))
3588 }
3589 DomQuery::JournalShows { first, second } => {
3593 let want_first = self.ctx.interner.resolve(*first);
3594 let want_second = self.ctx.interner.resolve(*second);
3595 let entries = crate::semantics::world::journal();
3596 let found = entries
3597 .iter()
3598 .position(|e| e.action == want_first)
3599 .is_some_and(|at| entries.iter().skip(at + 1).any(|e| e.action == want_second));
3600 RuntimeValue::Bool(found)
3601 }
3602 DomQuery::Title => RuntimeValue::Text(Rc::new(dom::title())),
3603 DomQuery::Url => RuntimeValue::Text(Rc::new(dom::route_path())),
3604 })
3605 }
3606
3607 fn require_element(&mut self, selector: &'a Expr<'a>, verb: &str) -> Result<i64, String> {
3610 let sel = self.evaluate_expr_sync(selector)?.to_display_string();
3611 let node = crate::semantics::dom::query_selector(&sel);
3612 if node < 0 {
3613 return Err(crate::semantics::drive::element_required(verb, &sel));
3614 }
3615 Ok(node)
3616 }
3617
3618 fn preregister_definitions(&mut self, stmts: &[Stmt<'a>]) {
3625 for stmt in stmts {
3626 match stmt {
3627 Stmt::FunctionDef {
3628 name,
3629 params,
3630 body,
3631 return_type,
3632 is_native,
3633 native_path,
3634 ..
3635 } => {
3636 self.ctx
3637 .functions
3638 .entry(*name)
3639 .or_insert_with(|| FunctionDef {
3640 params: params.clone(),
3641 body: *body,
3642 return_type: *return_type,
3643 is_native: *is_native,
3644 native_path: *native_path,
3645 });
3646 }
3647 Stmt::StructDef { name, fields, .. } => {
3648 self.ctx
3649 .struct_defs
3650 .entry(*name)
3651 .or_insert_with(|| fields.clone());
3652 }
3653 Stmt::ComponentDef(def) => {
3654 self.ctx
3655 .components
3656 .entry(def.name)
3657 .or_insert_with(|| (**def).clone());
3658 }
3659 _ => {}
3660 }
3661 }
3662 }
3663
3664 pub async fn run(&mut self, stmts: &[Stmt<'a>]) -> Result<(), String> {
3666 self.begin_program(stmts);
3667 for (i, stmt) in stmts.iter().enumerate() {
3668 let flow = self.execute_stmt(stmt).await?;
3669 if let Some(f) = self.statement_observer.as_mut() {
3670 f(i);
3671 }
3672 match flow {
3673 ControlFlow::Return(_) => break,
3674 ControlFlow::Break => break,
3675 ControlFlow::Continue => {}
3676 }
3677 }
3678 Ok(())
3679 }
3680
3681 #[cfg(not(target_arch = "wasm32"))]
3687 async fn activate_pnp_session(
3688 &mut self,
3689 bind: &crate::ast::SecurePad<'a>,
3690 ) -> Result<(), String> {
3691 let path = self.evaluate_expr(bind.pad).await?.to_display_string();
3692 let bytes = std::fs::read(&path)
3693 .map_err(|e| format!("one-time pad '{path}' could not be read: {e}"))?;
3694 let pool = crate::concurrency::pnp::PadPool::shared(bytes).map_err(|e| {
3695 format!("one-time pad '{path}' rejected (not truly random / too small): {e:?}")
3696 })?;
3697 let role = match bind.role {
3698 crate::ast::SecureRole::Initiator => crate::concurrency::pnp::Role::Initiator,
3699 crate::ast::SecureRole::Responder => crate::concurrency::pnp::Role::Responder,
3700 };
3701 let ledger = crate::concurrency::pnp::FileLedger::beside(std::path::Path::new(&path), role);
3704 use crate::concurrency::pnp::PadLedgerStore;
3705 ledger.update(&mut |_| false).map_err(|e| e.to_string())?;
3706 let session: std::rc::Rc<dyn crate::concurrency::channel::ActiveSession> =
3707 std::rc::Rc::new(pool.session_with_ledger(role, std::sync::Arc::new(ledger)));
3708 crate::concurrency::channel::install_session(Some(session));
3709 Ok(())
3710 }
3711
3712 #[cfg(target_arch = "wasm32")]
3715 async fn activate_pnp_session(
3716 &mut self,
3717 _bind: &crate::ast::SecurePad<'a>,
3718 ) -> Result<(), String> {
3719 Ok(())
3720 }
3721
3722 fn execute_ui(&mut self, ui: &crate::ast::stmt::UiStmt<'a>) -> Result<ControlFlow, String> {
3727 use crate::page_host::Drive;
3728 match ui {
3729 crate::ast::stmt::UiStmt::Click { selector } => {
3730 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3731 self.drive_page(Drive::Click { selector })
3732 }
3733 crate::ast::stmt::UiStmt::Submit { selector } => {
3737 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3738 self.drive_page(Drive::Submit { selector })
3739 }
3740 crate::ast::stmt::UiStmt::Press { key, selector } => {
3743 let key = self.evaluate_expr_sync(key)?.to_display_string();
3744 let selector = match selector {
3745 Some(e) => self.evaluate_expr_sync(e)?.to_display_string(),
3746 None => "body".to_string(),
3747 };
3748 self.drive_page(Drive::Press { key, selector })
3749 }
3750 crate::ast::stmt::UiStmt::Choose { value, selector } => {
3751 let value = self.evaluate_expr_sync(value)?.to_display_string();
3752 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3753 self.drive_page(Drive::Choose { value, selector })
3754 }
3755 crate::ast::stmt::UiStmt::TypeInto { text, selector } => {
3756 let text = self.evaluate_expr_sync(text)?.to_display_string();
3757 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3758 self.drive_page(Drive::Type { text, selector })
3759 }
3760 crate::ast::stmt::UiStmt::SetTitle { title } => {
3761 let t = self.evaluate_expr_sync(title)?.to_display_string();
3762 crate::semantics::dom::set_title(&t);
3763 Ok(ControlFlow::Continue)
3764 }
3765 crate::ast::stmt::UiStmt::CopyToClipboard { text } => {
3773 let t = self.evaluate_expr_sync(text)?.to_display_string();
3774 crate::semantics::dom::write_clipboard(&t);
3775 Ok(ControlFlow::Continue)
3776 }
3777 crate::ast::stmt::UiStmt::Download { bytes, name } => {
3778 let content = self.evaluate_expr_sync(bytes)?.to_display_string();
3779 let n = self.evaluate_expr_sync(name)?.to_display_string();
3780 crate::semantics::dom::offer_download(&n, &content);
3781 Ok(ControlFlow::Continue)
3782 }
3783 crate::ast::stmt::UiStmt::Notify { message, tone } => {
3784 let m = self.evaluate_expr_sync(message)?.to_display_string();
3785 let t = tone.map(|t| self.ctx.interner.resolve(t).to_string()).unwrap_or_default();
3788 crate::semantics::dom::notify(&m, &t);
3789 Ok(ControlFlow::Continue)
3790 }
3791 crate::ast::stmt::UiStmt::ScrollTo { selector } => {
3792 let node = self.require_element(selector, "Scroll to")?;
3793 crate::semantics::dom::scroll_to(node);
3794 Ok(ControlFlow::Continue)
3795 }
3796 crate::ast::stmt::UiStmt::SelectText { selector } => {
3797 let node = self.require_element(selector, "Select the text in")?;
3798 crate::semantics::dom::select_text(node);
3799 Ok(ControlFlow::Continue)
3800 }
3801 crate::ast::stmt::UiStmt::Focus { selector } => {
3802 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3803 self.drive_page(Drive::Focus { selector })
3804 }
3805 crate::ast::stmt::UiStmt::Blur { selector } => {
3806 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3807 self.drive_page(Drive::Blur { selector })
3808 }
3809 crate::ast::stmt::UiStmt::Hover { selector } => {
3810 let selector = self.evaluate_expr_sync(selector)?.to_display_string();
3811 self.drive_page(Drive::Hover { selector })
3812 }
3813 crate::ast::stmt::UiStmt::AddClass { class, selector } => {
3814 let node = self.require_element(selector, "Add class")?;
3815 let c = self.evaluate_expr_sync(class)?.to_display_string();
3816 crate::semantics::dom::add_class(node, &c);
3817 Ok(ControlFlow::Continue)
3818 }
3819 crate::ast::stmt::UiStmt::RemoveClass { class, selector } => {
3820 let node = self.require_element(selector, "Remove class")?;
3821 let c = self.evaluate_expr_sync(class)?.to_display_string();
3822 crate::semantics::dom::remove_class(node, &c);
3823 Ok(ControlFlow::Continue)
3824 }
3825 crate::ast::stmt::UiStmt::RaiseWindowEvent { event, target, value } => {
3828 let event = self.evaluate_expr_sync(event)?.to_display_string();
3829 let target = self.evaluate_expr_sync(target)?.to_display_string();
3830 let raised = self.evaluate_expr_sync(value)?;
3831 if event == "filedropped" {
3832 let file = crate::semantics::dom::DroppedFile::from_value(&raised)?;
3833 return self.drive_page(Drive::DropFile { target, file });
3834 }
3835 self.drive_page(Drive::Raise { event, target, value: raised.to_display_string() })
3836 }
3837 crate::ast::stmt::UiStmt::Publish { message, topic } => {
3842 let topic = self.evaluate_expr_sync(topic)?.to_display_string();
3843 let message = self.evaluate_expr_sync(message)?.to_display_string();
3844 crate::semantics::dom::publish(&topic, &message);
3845 if !self.page_can_be_driven() {
3846 return Ok(ControlFlow::Continue);
3847 }
3848 self.drive_page(Drive::Raise {
3849 event: format!("message:{topic}"),
3850 target: "body".to_string(),
3851 value: message,
3852 })
3853 }
3854 crate::ast::stmt::UiStmt::GoBack => {
3858 if crate::semantics::dom::go_back().is_some() {
3859 self.with_hosted_page(|host, me| host.settle(me));
3860 }
3861 Ok(ControlFlow::Continue)
3862 }
3863 crate::ast::stmt::UiStmt::Navigate { url } => {
3864 let url = self.evaluate_expr_sync(url)?.to_display_string();
3865 self.drive_page(Drive::Navigate { url })
3866 }
3867 crate::ast::stmt::UiStmt::ReplaceUrl { url } => {
3868 let u = self.evaluate_expr_sync(url)?.to_display_string();
3869 crate::semantics::dom::replace_route(&u);
3870 Ok(ControlFlow::Continue)
3871 }
3872 crate::ast::stmt::UiStmt::Toggle { field } => {
3875 let name = self.ctx.interner.resolve(*field);
3876 let current = self
3877 .lookup(*field)
3878 .map_err(|_| format!("`Toggle {name}` needs `{name}` to be a yes/no in scope."))?;
3879 let RuntimeValue::Bool(b) = current else {
3880 return Err(format!(
3881 "`Toggle {name}` flips a yes/no, but `{name}` holds {}.",
3882 current.type_name()
3883 ));
3884 };
3885 self.assign(*field, RuntimeValue::Bool(!b))?;
3886 Ok(ControlFlow::Continue)
3887 }
3888 crate::ast::stmt::UiStmt::StopTimer { name } => Err(format!(
3889 "`Stop the timer {}` runs inside a component's `Actions:`, against that component's \
3890 own timers.",
3891 self.ctx.interner.resolve(*name)
3892 )),
3893 crate::ast::stmt::UiStmt::StartTimer { name } => Err(format!(
3894 "`Start the timer {}` runs inside a component's `Actions:`, against that component's \
3895 own timers.",
3896 self.ctx.interner.resolve(*name)
3897 )),
3898 crate::ast::stmt::UiStmt::Save { value, key } => {
3901 let v = self.evaluate_expr_sync(value)?;
3902 let k = self.evaluate_expr_sync(key)?.to_display_string();
3903 let Some(tagged) = Self::tagged_storage_text(&v) else {
3904 return Err(format!(
3905 "`Save` keeps text, a number, a yes/no, a list or a record, and this value is \
3906 {} — storage holds text, and {} has none.",
3907 v.type_name(),
3908 v.type_name()
3909 ));
3910 };
3911 crate::semantics::storage::set(crate::semantics::storage::LOCAL, &k, &tagged)?;
3912 Ok(ControlFlow::Continue)
3913 }
3914 crate::ast::stmt::UiStmt::Load { key, var } => {
3915 let k = self.evaluate_expr_sync(key)?.to_display_string();
3916 let v = match crate::semantics::storage::get(crate::semantics::storage::LOCAL, &k)?
3917 .and_then(|text| Self::value_from_tagged_storage(&text))
3918 {
3919 Some(v) => v,
3920 None => empty_like(self.lookup(*var).ok()),
3921 };
3922 self.assign(*var, v)?;
3923 Ok(ControlFlow::Continue)
3924 }
3925 crate::ast::stmt::UiStmt::Forget { key } => {
3926 let k = self.evaluate_expr_sync(key)?.to_display_string();
3927 crate::semantics::storage::remove(crate::semantics::storage::LOCAL, &k)?;
3928 Ok(ControlFlow::Continue)
3929 }
3930 crate::ast::stmt::UiStmt::Reload => self.drive_page(Drive::Reload),
3931 crate::ast::stmt::UiStmt::CallStore { store, action, args } => {
3934 let store_name = self.ctx.interner.resolve(*store).to_string();
3935 let action_name = self.ctx.interner.resolve(*action).to_string();
3936 let lowered = logicaffeine_language::parser::lgx_lower::action_fn_name(&store_name, &action_name);
3937 let function = self
3938 .ctx
3939 .interner
3940 .lookup(&lowered)
3941 .filter(|f| self.ctx.functions.contains_key(f))
3942 .ok_or_else(|| {
3943 format!("`{store_name}` has no action `{action_name}` — declare it under the store's `Actions:`.")
3944 })?;
3945 let mut values = Vec::with_capacity(args.len());
3946 for arg in args.iter() {
3947 values.push(self.evaluate_expr_sync(arg)?);
3948 }
3949 self.call_function_with_values_sync(function, values)?;
3950 Ok(ControlFlow::Continue)
3951 }
3952 crate::ast::stmt::UiStmt::Mount { component, selector } => {
3953 let at = match selector {
3954 Some(e) => Some(self.evaluate_expr_sync(e)?.to_display_string()),
3955 None => None,
3956 };
3957 self.drive_page(Drive::Mount { component: self.ctx.interner.resolve(*component).to_string(), at })
3958 }
3959 }
3960 }
3961
3962 fn page_can_be_driven(&self) -> bool {
3965 match &self.page {
3966 PageSeat::Unseated => false,
3967 PageSeat::Driven(_) => true,
3968 PageSeat::Here(hosted) => hosted.host.is_some(),
3969 }
3970 }
3971
3972 #[async_recursion(?Send)]
3975 async fn execute_stmt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
3976 self.tick_test_budget()?;
3977 if self.tiers_noop
3980 && matches!(
3981 stmt,
3982 Stmt::Expect { .. }
3983 | Stmt::ExpectFail { .. }
3984 | Stmt::ExpectOutput { .. }
3985 | Stmt::AdvanceTime { .. }
3986 | Stmt::GivenFile { .. }
3987 | Stmt::ForAll { .. }
3988 )
3989 {
3990 return Ok(ControlFlow::Continue);
3991 }
3992 match stmt {
3993 Stmt::Let { var, value, .. } => {
3994 let val = self.evaluate_expr(value).await?;
3995 self.define(*var, val);
3996 Ok(ControlFlow::Continue)
3997 }
3998
3999 Stmt::Set { target, value } => {
4000 if let Some((before, operands)) = self.text_appends(*target, value) {
4001 let mut pieces = Vec::with_capacity(operands.len());
4002 for operand in operands {
4003 pieces.push(self.evaluate_expr(operand).await?.to_display_string());
4004 }
4005 self.append_text(*target, before, pieces)?;
4006 return Ok(ControlFlow::Continue);
4007 }
4008 let val = self.evaluate_expr(value).await?;
4009 self.assign(*target, val)?;
4010 Ok(ControlFlow::Continue)
4011 }
4012
4013 Stmt::Swap { a, b } => {
4014 let va = self.lookup(*a)?.clone();
4016 let vb = self.lookup(*b)?.clone();
4017 self.assign(*a, vb)?;
4018 self.assign(*b, va)?;
4019 Ok(ControlFlow::Continue)
4020 }
4021
4022 Stmt::Call { function, args } => {
4023 self.call_function(*function, args).await?;
4024 Ok(ControlFlow::Continue)
4025 }
4026
4027 Stmt::If {
4028 cond,
4029 then_block,
4030 else_block,
4031 } => {
4032 let condition = self.evaluate_expr(cond).await?;
4033 if condition.decided_truth()? {
4034 let flow = self.execute_block(then_block).await?;
4035 if !matches!(flow, ControlFlow::Continue) {
4036 return Ok(flow);
4037 }
4038 } else if let Some(else_stmts) = else_block {
4039 let flow = self.execute_block(else_stmts).await?;
4040 if !matches!(flow, ControlFlow::Continue) {
4041 return Ok(flow);
4042 }
4043 }
4044 Ok(ControlFlow::Continue)
4045 }
4046
4047 Stmt::While { cond, body, .. } => {
4048 loop {
4049 let condition = self.evaluate_expr(cond).await?;
4050 if !condition.decided_truth()? {
4051 break;
4052 }
4053 match self.execute_block(body).await? {
4054 ControlFlow::Break => break,
4055 ControlFlow::Return(v) => return Ok(ControlFlow::Return(v)),
4056 ControlFlow::Continue => {}
4057 }
4058 }
4059 Ok(ControlFlow::Continue)
4060 }
4061
4062 Stmt::Repeat {
4063 pattern,
4064 iterable,
4065 body,
4066 } => {
4067 use crate::ast::stmt::Pattern;
4068
4069 let iter_val = self.evaluate_expr(iterable).await?;
4070 let items = crate::semantics::collections::iteration_snapshot(&iter_val)?;
4071
4072 self.push_scope();
4073 self.task.repeat_depth_async += 1;
4075 for item in items {
4076 match pattern {
4078 Pattern::Identifier(sym) => {
4079 self.define(*sym, item);
4080 }
4081 Pattern::Tuple(syms) => {
4082 if let RuntimeValue::Tuple(ref tuple_vals) = item {
4083 if syms.len() != tuple_vals.len() {
4084 self.task.repeat_depth_async -= 1;
4085 return Err(format!(
4086 "Cannot bind a {}-tuple to {} names",
4087 tuple_vals.len(),
4088 syms.len()
4089 ));
4090 }
4091 for (sym, val) in syms.iter().zip(tuple_vals.iter()) {
4092 self.define(*sym, val.clone());
4093 }
4094 } else {
4095 self.task.repeat_depth_async -= 1;
4096 return Err(format!(
4097 "Expected tuple for pattern, got {}",
4098 item.type_name()
4099 ));
4100 }
4101 }
4102 }
4103
4104 match self.execute_block(body).await? {
4105 ControlFlow::Break => break,
4106 ControlFlow::Return(v) => {
4107 self.task.repeat_depth_async -= 1;
4108 self.pop_scope();
4109 return Ok(ControlFlow::Return(v));
4110 }
4111 ControlFlow::Continue => {}
4112 }
4113 }
4114 self.task.repeat_depth_async -= 1;
4115 self.pop_scope();
4116 Ok(ControlFlow::Continue)
4117 }
4118
4119 Stmt::Return { value } => {
4120 if let Some(expr) = value {
4123 if let Some(call_args) = self.self_tail_call_args_async(*expr) {
4124 let mut vals = Vec::with_capacity(call_args.len());
4125 for a in call_args {
4126 vals.push(self.evaluate_expr(a).await?);
4127 }
4128 self.task.pending_tail_call_async = Some(vals);
4129 return Ok(ControlFlow::Return(RuntimeValue::Nothing));
4130 }
4131 }
4132 let ret_val = match value {
4133 Some(expr) => self.evaluate_expr(expr).await?,
4134 None => RuntimeValue::Nothing,
4135 };
4136 Ok(ControlFlow::Return(ret_val))
4137 }
4138
4139 Stmt::Break => Ok(ControlFlow::Break),
4140
4141 Stmt::FunctionDef {
4142 name,
4143 params,
4144 body,
4145 return_type,
4146 is_native,
4147 native_path,
4148 ..
4149 } => {
4150 let func = FunctionDef {
4151 params: params.clone(),
4152 body: *body,
4153 return_type: *return_type,
4154 is_native: *is_native,
4155 native_path: *native_path,
4156 };
4157 self.ctx.functions.insert(*name, func);
4158 Ok(ControlFlow::Continue)
4159 }
4160
4161 Stmt::StructDef { name, fields, .. } => {
4162 self.ctx.struct_defs.insert(*name, fields.clone());
4163 Ok(ControlFlow::Continue)
4164 }
4165
4166 Stmt::SetField {
4167 object,
4168 field,
4169 value,
4170 } => {
4171 let new_val = self.evaluate_expr(value).await?;
4172 let place = self.place(object).await?;
4173 self.set_field_at(place, *field, new_val)?;
4174 Ok(ControlFlow::Continue)
4175 }
4176
4177 Stmt::Push { value, collection } => {
4181 let val = self.evaluate_expr(value).await?;
4182 if let Expr::FieldAccess {
4183 object: Expr::Identifier(obj_sym),
4184 field,
4185 } = collection
4186 {
4187 if let Some(place) = self.place(collection).await? {
4188 self.place_slot(&place, true);
4189 }
4190 let obj_val = self.lookup(*obj_sym)?;
4191 let field_name = self.ctx.interner.resolve(*field);
4192 crate::semantics::collections::push_to_struct_field(obj_val, field_name, val)?;
4193 } else {
4194 let coll_val = self.write_target(collection).await?;
4195 crate::semantics::collections::list_push(&coll_val, val)?;
4196 }
4197 Ok(ControlFlow::Continue)
4198 }
4199
4200 Stmt::Pop { collection, into } => {
4201 let coll_val = self.write_target(collection).await?;
4202 let popped = crate::semantics::collections::list_pop(&coll_val)?;
4203 if let Some(into_var) = into {
4204 self.define(*into_var, popped);
4205 }
4206 Ok(ControlFlow::Continue)
4207 }
4208
4209 Stmt::Add { value, collection } => {
4210 let val = self.evaluate_expr(value).await?;
4211 let coll_val = self.write_target(collection).await?;
4212 crate::semantics::collections::set_add(&coll_val, val)?;
4213 Ok(ControlFlow::Continue)
4214 }
4215
4216 Stmt::Remove { value, collection } => {
4217 let val = self.evaluate_expr(value).await?;
4218 let coll_val = self.write_target(collection).await?;
4219 crate::semantics::collections::remove_from(&coll_val, &val)?;
4220 Ok(ControlFlow::Continue)
4221 }
4222
4223 Stmt::SetIndex {
4224 collection,
4225 index,
4226 value,
4227 } => {
4228 let idx_val = self.evaluate_expr(index).await?;
4229 let new_val = self.evaluate_expr(value).await?;
4230 let target = match self.place(collection).await? {
4231 Some(place) => {
4232 match self.set_item_in_place(&place, &idx_val, new_val.clone()) {
4233 Some(done) => {
4234 done?;
4235 return Ok(ControlFlow::Continue);
4236 }
4237 None => self.read_place(&place)?,
4238 }
4239 }
4240 None => self.evaluate_expr(collection).await?,
4241 };
4242 crate::semantics::collections::index_set(&target, &idx_val, new_val)?;
4243 Ok(ControlFlow::Continue)
4244 }
4245
4246 Stmt::ComponentDef(def)
4254 if matches!(
4255 def.kind,
4256 crate::ast::component::ComponentKind::ErrorPage { .. }
4257 ) =>
4258 {
4259 {
4260 let heading = logicaffeine_language::parser::lgx_lower::construct_heading(
4264 def,
4265 self.ctx.interner,
4266 );
4267 match def.view.as_ref() {
4268 Some(v) => match logicaffeine_language::parser::lgx_lower::view_html_lowerable(
4269 &v.nodes,
4270 self.ctx.interner,
4271 ) {
4272 Ok(()) => Ok(ControlFlow::Continue),
4273 Err(why) => Err(format!(
4274 "`{heading}` cannot be rendered on this tier yet: {}.",
4275 why.message
4276 )),
4277 },
4278 None => Err(format!(
4279 "`{heading}` cannot be rendered on this tier yet: it has no `View:` to render."
4280 )),
4281 }
4282 }
4283 }
4284 Stmt::ComponentDef(_) | Stmt::DirectiveDef { .. } => Ok(ControlFlow::Continue),
4285 Stmt::Ui(ui) => self.execute_ui(ui),
4286 Stmt::RouteDef {
4292 method,
4293 path,
4294 params,
4295 return_type,
4296 body,
4297 span,
4298 } => {
4299 match logicaffeine_language::parser::lgx_lower::route_lowerable(
4300 params,
4301 *return_type,
4302 body,
4303 self.ctx.interner,
4304 &|sym| self.ctx.struct_defs.contains_key(&sym),
4305 &self.ctx.components.values().cloned().collect::<Vec<_>>(),
4309 *span,
4310 ) {
4311 Ok(()) => Ok(ControlFlow::Continue),
4312 Err(why) => Err(format!(
4313 "`{}` cannot run on this tier yet: {}.",
4314 logicaffeine_language::parser::lgx_lower::route_heading(
4315 *method,
4316 *path,
4317 self.ctx.interner
4318 ),
4319 why.message
4320 )),
4321 }
4322 }
4323 Stmt::MiddlewareDef { .. } => Ok(ControlFlow::Continue),
4327 Stmt::RedirectDef { .. } => Ok(ControlFlow::Continue),
4329 Stmt::Replay { actions } => {
4330 self.replay_actions(actions)?;
4331 Ok(ControlFlow::Continue)
4332 }
4333 Stmt::ServeFetches => self.serve_fetches_sync(),
4334 Stmt::GivenFetch {
4335 method,
4336 url,
4337 status,
4338 body,
4339 } => self.given_fetch_sync(*method, url, status, body),
4340 Stmt::Fetch { .. } => Err(
4341 "A request that answers into an action (`Get … then loaded`) is sent by a \
4342 component's own `Actions:`, whose page completes it."
4343 .to_string(),
4344 ),
4345 Stmt::Splice { body } => {
4346 for s in body.iter() {
4350 let flow = self.execute_stmt(s).await?;
4351 if !matches!(flow, ControlFlow::Continue) {
4352 return Ok(flow);
4353 }
4354 }
4355 Ok(ControlFlow::Continue)
4356 }
4357
4358 Stmt::Reversibly { body } => {
4359 for s in body.iter() {
4364 let flow = self.execute_stmt(s).await?;
4365 if !matches!(flow, ControlFlow::Continue) {
4366 return Ok(flow);
4367 }
4368 }
4369 Ok(ControlFlow::Continue)
4370 }
4371
4372 Stmt::Inspect { target, arms, .. } => {
4373 let target_val = self.evaluate_expr(target).await?;
4374 self.execute_inspect(&target_val, arms).await
4375 }
4376
4377 Stmt::Zone { name, body, .. } => {
4378 self.push_scope();
4379 self.define(*name, RuntimeValue::Nothing);
4380 let result = self.execute_block(body).await;
4381 self.pop_scope();
4382 result?;
4383 Ok(ControlFlow::Continue)
4384 }
4385
4386 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
4387 for task in tasks.iter() {
4389 self.execute_stmt(task).await?;
4390 }
4391 Ok(ControlFlow::Continue)
4392 }
4393
4394 Stmt::Assert { .. } | Stmt::Trust { .. } => Ok(ControlFlow::Continue),
4395
4396 Stmt::TestDef { .. } => Ok(ControlFlow::Continue),
4399
4400 Stmt::Expect { condition } => {
4403 if !self.test_mode {
4404 return Err(TEST_ONLY_STMT_ERR.to_string());
4405 }
4406 self.test_assertions += 1;
4407 let val = self.evaluate_expr(condition).await?;
4408 if !val.decided_truth()? {
4409 let cond_text =
4410 logicaffeine_language::printer::render_expr(condition, self.ctx.interner);
4411 let mut subs = Vec::new();
4412 logicaffeine_language::printer::subexpressions(condition, &mut subs);
4413 let mut annotations: Vec<(String, String)> = Vec::new();
4414 let mut seen = std::collections::HashSet::new();
4415 for sub in subs {
4416 let text =
4417 logicaffeine_language::printer::render_expr(sub, self.ctx.interner);
4418 if !seen.insert(text.clone()) {
4419 continue;
4420 }
4421 if let Ok(v) = self.evaluate_expr(sub).await {
4422 annotations.push((text, v.to_display_string()));
4423 }
4424 }
4425 let hint = Self::expect_socratic_hint(condition);
4426 self.test_failures
4427 .push(format_expect_failure(&cond_text, &annotations, hint));
4428 }
4429 Ok(ControlFlow::Continue)
4430 }
4431 Stmt::ExpectFail { message, body } => {
4432 if !self.test_mode {
4433 return Err(TEST_ONLY_STMT_ERR.to_string());
4434 }
4435 self.test_assertions += 1;
4436 let mut failure: Option<String> = None;
4437 for s in body.iter() {
4438 if let Err(e) = self.execute_stmt(s).await {
4439 failure = Some(e);
4440 break;
4441 }
4442 }
4443 match failure {
4444 None => self
4445 .test_failures
4446 .push("Expected this to fail — but the block succeeded.".to_string()),
4447 Some(actual) => {
4448 if let Some(expected) = message {
4449 let expected = self.ctx.interner.resolve(*expected);
4450 if actual != expected {
4451 self.test_failures.push(format!(
4452 "Expected this to fail with {expected:?} — but it failed with {actual:?}."
4453 ));
4454 }
4455 }
4456 }
4457 }
4458 Ok(ControlFlow::Continue)
4459 }
4460 Stmt::ExpectOutput { expected } => {
4461 if !self.test_mode {
4462 return Err(TEST_ONLY_STMT_ERR.to_string());
4463 }
4464 self.test_assertions += 1;
4465 match expected {
4466 ExpectedOutput::Inline(sym) => {
4467 let expected_text = self.ctx.interner.resolve(*sym).to_string();
4468 let actual = self.output.join("\n");
4469 if actual != expected_text {
4470 self.test_failures.push(format!(
4471 "Expected output {expected_text:?} — but the test printed {actual:?}."
4472 ));
4473 }
4474 }
4475 ExpectedOutput::File(path) => {
4476 self.test_failures.push(format!(
4477 "Expected output as in {:?} — golden files land with the sealed world (Wave 4).",
4478 self.ctx.interner.resolve(*path)
4479 ));
4480 }
4481 }
4482 Ok(ControlFlow::Continue)
4483 }
4484 Stmt::AdvanceTime { millis } => {
4485 if !self.test_mode {
4486 return Err(TEST_ONLY_STMT_ERR.to_string());
4487 }
4488 let ms = match self.evaluate_expr(millis).await? {
4489 RuntimeValue::Int(n) => n.max(0) as u64,
4490 RuntimeValue::Duration(ns) => (ns.max(0) / 1_000_000) as u64,
4492 other => {
4493 return Err(format!(
4494 "Advance time needs a duration in milliseconds, got {}",
4495 other.type_name()
4496 ))
4497 }
4498 };
4499 self.advance_time_ms(ms)
4500 }
4501 Stmt::GivenFile { path, content } => {
4502 if !self.test_mode {
4503 return Err(TEST_ONLY_STMT_ERR.to_string());
4504 }
4505 logicaffeine_system::testworld::seed_file(
4506 self.ctx.interner.resolve(*path).to_string(),
4507 self.ctx.interner.resolve(*content).to_string(),
4508 );
4509 Ok(ControlFlow::Continue)
4510 }
4511
4512 Stmt::Observe {
4516 category,
4517 message,
4518 payloads,
4519 sample,
4520 } => {
4521 if crate::observe::capturing() {
4522 let mut vals: Vec<(String, String)> = Vec::with_capacity(payloads.len());
4523 for (name, expr) in payloads.iter() {
4524 let v = self.evaluate_expr(expr).await?;
4525 vals.push((
4526 self.ctx.interner.resolve(*name).to_string(),
4527 v.to_display_string(),
4528 ));
4529 }
4530 crate::observe::emit(
4531 map_obs_category(*category),
4532 self.ctx.interner.resolve(*message).to_string(),
4533 vals,
4534 *sample,
4535 message.index() as u64,
4536 );
4537 }
4538 Ok(ControlFlow::Continue)
4539 }
4540 Stmt::During { label, body } => {
4541 let cap = crate::observe::capturing();
4545 let name = if cap {
4546 self.ctx.interner.resolve(*label).to_string()
4547 } else {
4548 String::new()
4549 };
4550 if cap {
4551 crate::observe::enter_span(name.clone());
4552 }
4553 let mut result: Result<ControlFlow, String> = Ok(ControlFlow::Continue);
4554 for s in body.iter() {
4555 match self.execute_stmt(s).await {
4556 Ok(ControlFlow::Continue) => {}
4557 Ok(flow) => {
4558 result = Ok(flow);
4559 break;
4560 }
4561 Err(e) => {
4562 result = Err(e);
4563 break;
4564 }
4565 }
4566 }
4567 if cap {
4568 crate::observe::exit_span(name);
4569 }
4570 result
4571 }
4572 Stmt::ForAll {
4573 vars,
4574 domain,
4575 constraint,
4576 body,
4577 } => {
4578 if !self.test_mode {
4579 return Err(TEST_ONLY_STMT_ERR.to_string());
4580 }
4581 self.run_property(vars, *domain, *constraint, body)?;
4582 Ok(ControlFlow::Continue)
4583 }
4584
4585 Stmt::RuntimeAssert {
4586 condition, reason, ..
4587 } => {
4588 let val = self.evaluate_expr(condition).await?;
4589 if !val.decided_truth()? {
4590 return Err(match reason {
4591 Some(r) => crate::semantics::builtins::contract_reason_text(
4592 self.evaluate_expr(r).await?,
4593 )?,
4594 None => "Assertion failed".to_string(),
4595 });
4596 }
4597 Ok(ControlFlow::Continue)
4598 }
4599
4600 Stmt::Fail { reason } => Err(self.evaluate_expr(reason).await?.to_display_string()),
4601
4602 Stmt::Give { object, recipient } => {
4603 let obj_val = self.evaluate_expr(object).await?;
4604 if let Expr::Identifier(sym) = recipient {
4605 self.call_function_with_values(*sym, vec![obj_val]).await?;
4606 }
4607 Ok(ControlFlow::Continue)
4608 }
4609
4610 Stmt::Show { object, recipient } => {
4611 let obj_val = self.evaluate_expr(object).await?;
4612 if let Expr::Identifier(sym) = recipient {
4613 let name = self.ctx.interner.resolve(*sym);
4614 if name == "show" {
4615 self.emit_output(obj_val.to_display_string());
4616 } else {
4617 self.call_function_with_values(*sym, vec![obj_val]).await?;
4618 }
4619 }
4620 Ok(ControlFlow::Continue)
4621 }
4622
4623 Stmt::ReadFrom { var, source } => {
4625 let content =
4626 match source {
4627 ReadSource::Console => {
4628 String::new()
4630 }
4631 ReadSource::File(path_expr) => {
4632 let path = self.evaluate_expr(path_expr).await?.to_display_string();
4633 match &self.ctx.vfs {
4634 Some(vfs) => vfs.read_to_string(&path).await.map_err(|e| {
4635 crate::semantics::builtins::vfs_read_failure(&e)
4636 })?,
4637 None => {
4638 return Err("VFS not initialized. Use Interpreter::with_vfs()"
4639 .to_string())
4640 }
4641 }
4642 }
4643 };
4644 self.define(*var, RuntimeValue::Text(Rc::new(content)));
4645 Ok(ControlFlow::Continue)
4646 }
4647
4648 Stmt::WriteFile { content, path } => {
4649 let content_val = self.evaluate_expr(content).await?.to_display_string();
4650 let path_val = self.evaluate_expr(path).await?.to_display_string();
4651 match &self.ctx.vfs {
4652 Some(vfs) => {
4653 vfs.write(&path_val, content_val.as_bytes())
4654 .await
4655 .map_err(|e| crate::semantics::builtins::vfs_write_failure(&e))?;
4656 }
4657 None => {
4658 return Err("VFS not initialized. Use Interpreter::with_vfs()".to_string())
4659 }
4660 }
4661 Ok(ControlFlow::Continue)
4662 }
4663
4664 Stmt::Spawn { name, .. } => {
4665 self.define(*name, RuntimeValue::Nothing);
4666 Ok(ControlFlow::Continue)
4667 }
4668
4669 Stmt::SendMessage {
4673 message,
4674 destination,
4675 compression,
4676 cached,
4677 unchecked,
4678 layout,
4679 shared,
4680 computed,
4681 indexed,
4682 deduped,
4683 unreliable: _,
4684 } => {
4685 use crate::concurrency::marshal::{
4686 default_integrity, message_to_wire_best, message_to_wire_cached,
4687 message_to_wire_with, with_compression_codec, with_dedup, with_integrity,
4688 with_numerics, with_struct_view, with_structure, with_type_registry, WireCodec,
4689 WireGoal, WireIntegrity, WireNumerics, WireSchemaCache, WireStructure,
4690 };
4691 use logicaffeine_language::ast::SendLayout;
4692 let dest = self.evaluate_expr(destination).await?;
4693 let topic = crate::concurrency::net_inbox::peer_topic(&dest)?;
4694 let msg = self.evaluate_expr(message).await?;
4695 let msg = if *computed {
4702 match msg {
4703 RuntimeValue::Function(c) if c.generated.is_some() => {
4704 RuntimeValue::Function(c)
4705 }
4706 RuntimeValue::Function(c) => {
4707 if c.param_names.len() != 1 {
4708 return Err(
4709 "Send computed requires a single-argument pure function"
4710 .to_string(),
4711 );
4712 }
4713 let expr =
4714 match self.ctx.closure_bodies.get(c.body_index) {
4715 Some(ClosureBodyRef::Expression(e)) => *e,
4716 _ => return Err(
4717 "Send computed requires a pure expression-bodied function"
4718 .to_string(),
4719 ),
4720 };
4721 match crate::concurrency::marshal::lower_expr_to_genexpr(expr, c.param_names[0]) {
4722 Some(gen) => RuntimeValue::Function(Box::new(ClosureValue {
4723 body_index: usize::MAX,
4724 captured_env: HashMap::default(),
4725 param_names: c.param_names.clone(),
4726 generated: Some(std::rc::Rc::new(gen)),
4727 })),
4728 None => {
4729 return Err(
4730 "Send computed: the function is not a pure arithmetic computation over its argument"
4731 .to_string(),
4732 )
4733 }
4734 }
4735 }
4736 _ => return Err("Send computed requires a function value".to_string()),
4737 }
4738 } else {
4739 msg
4740 };
4741 let from = self
4743 .netbox
4744 .inbox
4745 .as_ref()
4746 .map(|t| t.to_string())
4747 .unwrap_or_default();
4748 self.netbox.my_profile.registry_epoch = self.build_wire_type_registry().epoch();
4751 let integrity = if *unchecked {
4759 WireIntegrity::Raw
4760 } else {
4761 default_integrity()
4762 };
4763 let numerics = match layout {
4764 Some(SendLayout::Fast) => WireNumerics::Fixed,
4765 Some(SendLayout::Packed) => WireNumerics::GroupVarint,
4766 Some(SendLayout::Smallest) => WireNumerics::Varint,
4769 Some(SendLayout::Redundant) => WireNumerics::Varint,
4771 Some(SendLayout::Compact) | None => WireNumerics::Varint,
4772 };
4773 let structure = match layout {
4777 Some(SendLayout::Smallest) => WireStructure::Auto,
4778 _ => WireStructure::Off,
4779 };
4780 let registry = if *shared {
4785 self.build_wire_type_registry()
4786 } else {
4787 crate::concurrency::marshal::WireTypeRegistry::new(Vec::new())
4788 };
4789 let plain = !*computed
4799 && !*unchecked
4800 && !*shared
4801 && !*indexed
4802 && !*cached
4803 && !*deduped
4804 && compression.is_none()
4805 && matches!(layout, None | Some(SendLayout::Compact));
4806 let bytes = if plain {
4807 self.netbox.encode_negotiated(
4810 &from,
4811 &msg,
4812 &topic,
4813 self.build_wire_type_registry(),
4814 )?
4815 } else {
4816 with_dedup(*deduped, || {
4820 with_struct_view(*indexed, || {
4821 with_type_registry(registry, || -> Result<Vec<u8>, String> {
4822 if matches!(layout, Some(SendLayout::Smallest))
4831 && !*cached
4832 && !*deduped
4833 {
4834 return with_integrity(integrity, || {
4835 message_to_wire_best(&from, &msg, WireGoal::Smallest)
4836 });
4837 }
4838 if *cached {
4839 let cache = self
4840 .netbox
4841 .send_schema
4842 .entry(topic.clone())
4843 .or_insert_with(WireSchemaCache::content_addressed);
4844 let mut encode = || {
4845 message_to_wire_cached(
4846 &from,
4847 &msg,
4848 WireCodec::Native,
4849 integrity,
4850 cache,
4851 )
4852 };
4853 with_structure(structure, || {
4854 with_numerics(numerics, || match compression {
4855 Some(codec) => with_compression_codec(
4856 wire_compression_of(*codec),
4857 &mut encode,
4858 ),
4859 None => encode(),
4860 })
4861 })
4862 } else {
4863 let mut encode = || {
4864 message_to_wire_with(
4865 &from,
4866 &msg,
4867 WireCodec::Native,
4868 integrity,
4869 )
4870 };
4871 with_structure(structure, || {
4872 with_numerics(numerics, || match compression {
4873 Some(codec) => with_compression_codec(
4874 wire_compression_of(*codec),
4875 &mut encode,
4876 ),
4877 None => encode(),
4878 })
4879 })
4880 }
4881 })
4882 })
4883 })?
4884 };
4885 let bytes =
4890 crate::concurrency::channel::seal_active_checked(bytes).ok_or_else(|| {
4891 "one-time pad exhausted — message not sent (PNP fail-closed)".to_string()
4892 })?;
4893 if let Some(hs) = self.netbox.first_contact_handshake(&topic) {
4896 self.netbox.publish(
4897 &crate::concurrency::net_inbox::handshake_topic_for(&topic),
4898 hs,
4899 )?;
4900 }
4901 if matches!(layout, Some(SendLayout::Redundant)) {
4902 let msg_id = self.netbox.next_msg_id();
4906 let shards = crate::concurrency::fec::frame_redundant(
4907 msg_id,
4908 &bytes,
4909 REDUNDANT_K,
4910 REDUNDANT_N,
4911 )
4912 .ok_or_else(|| "redundant framing failed".to_string())?;
4913 for shard in shards {
4914 self.netbox.publish(&topic, shard)?;
4915 }
4916 } else {
4917 self.netbox.publish(&topic, bytes)?;
4918 }
4919 Ok(ControlFlow::Continue)
4920 }
4921
4922 Stmt::AwaitMessage {
4926 source,
4927 into,
4928 view,
4929 stream,
4930 } => {
4931 let src = self.evaluate_expr(source).await?;
4932 let want = crate::concurrency::net_inbox::peer_topic(&src)?;
4933 if self.netbox.inbox.is_none() {
4934 return Err(crate::concurrency::net_inbox::AWAIT_WITHOUT_LISTEN.to_string());
4935 }
4936 let msg = if *stream {
4940 self.await_stream_from(&want).await?
4941 } else {
4942 self.await_message_from(&want, *view).await?
4943 };
4944 self.define(*into, msg);
4945 Ok(ControlFlow::Continue)
4946 }
4947
4948 Stmt::StreamMessage {
4951 values,
4952 destination,
4953 } => {
4954 let dest = self.evaluate_expr(destination).await?;
4955 let topic = crate::concurrency::net_inbox::peer_topic(&dest)?;
4956 let list = self.evaluate_expr(values).await?;
4957 let items = match &list {
4958 RuntimeValue::List(rc) => rc.borrow().to_values(),
4959 other => vec![other.clone()],
4960 };
4961 let from = self
4962 .netbox
4963 .inbox
4964 .as_ref()
4965 .map(|t| t.to_string())
4966 .unwrap_or_default();
4967 let registry = self.build_wire_type_registry();
4968 let blob = crate::concurrency::marshal::with_type_registry(registry, || {
4969 crate::concurrency::marshal::frame_stream_message(&from, &items)
4970 })?;
4971 self.netbox.publish(&topic, blob)?;
4974 Ok(ControlFlow::Continue)
4975 }
4976
4977 Stmt::MergeCrdt { source, target } => {
4978 let source_val = self.evaluate_expr(source).await?;
4979 let source_fields = match &source_val {
4980 RuntimeValue::Struct(s) => s.fields.clone(),
4981 _ => return Err("Merge source must be a struct".to_string()),
4982 };
4983
4984 if let Expr::Identifier(target_sym) = target {
4985 let mut target_val = self.lookup(*target_sym)?.clone();
4986
4987 if let RuntimeValue::Struct(ref mut s) = target_val {
4988 for (field_name, source_field_val) in source_fields {
4989 let current = s
4990 .fields
4991 .get(&field_name)
4992 .cloned()
4993 .unwrap_or(RuntimeValue::Int(0));
4994
4995 let merged = crate::semantics::arith::crdt_merge_field(
4996 ¤t,
4997 source_field_val,
4998 );
4999 s.fields.insert(field_name, merged);
5000 }
5001 self.assign(*target_sym, target_val)?;
5002 } else {
5003 return Err("Merge target must be a struct".to_string());
5004 }
5005 } else {
5006 return Err("Merge target must be an identifier".to_string());
5007 }
5008 Ok(ControlFlow::Continue)
5009 }
5010
5011 Stmt::JoinCrdt { source, target } => {
5014 let source_val = self.evaluate_expr(source).await?;
5015 let source_fields = match &source_val {
5016 RuntimeValue::Struct(s) => s.fields.clone(),
5017 _ => return Err("Converge source must be a struct".to_string()),
5018 };
5019
5020 if let Expr::Identifier(target_sym) = target {
5021 let mut target_val = self.lookup(*target_sym)?.clone();
5022
5023 if let RuntimeValue::Struct(ref mut s) = target_val {
5024 for (field_name, source_field_val) in source_fields {
5025 let current = s
5026 .fields
5027 .get(&field_name)
5028 .cloned()
5029 .unwrap_or(RuntimeValue::Int(0));
5030
5031 let joined = crate::semantics::arith::crdt_join_field(
5032 ¤t,
5033 source_field_val,
5034 );
5035 s.fields.insert(field_name, joined);
5036 }
5037 self.assign(*target_sym, target_val)?;
5038 } else {
5039 return Err("Converge target must be a struct".to_string());
5040 }
5041 } else {
5042 return Err("Converge target must be an identifier".to_string());
5043 }
5044 Ok(ControlFlow::Continue)
5045 }
5046
5047 Stmt::IncreaseCrdt {
5048 object,
5049 field,
5050 amount,
5051 } => {
5052 let amount_val = self.evaluate_expr(amount).await?;
5053 let amount_int = match amount_val {
5054 RuntimeValue::Int(n) => n,
5055 _ => return Err("CRDT increment amount must be an integer".to_string()),
5056 };
5057
5058 if let Expr::Identifier(obj_sym) = object {
5059 let mut obj_val = self.lookup(*obj_sym)?.clone();
5060
5061 if let RuntimeValue::Struct(ref mut s) = obj_val {
5062 let field_name = self.ctx.interner.resolve(*field).to_string();
5063 let current = s
5064 .fields
5065 .get(&field_name)
5066 .cloned()
5067 .unwrap_or(RuntimeValue::Int(0));
5068
5069 let new_val = crate::semantics::arith::crdt_counter_bump(
5070 current,
5071 amount_int,
5072 &field_name,
5073 )?;
5074 s.fields.insert(field_name, new_val);
5075 self.assign(*obj_sym, obj_val)?;
5076 } else {
5077 return Err("Cannot increase field on non-struct value".to_string());
5078 }
5079 } else {
5080 return Err("IncreaseCrdt target must be an identifier".to_string());
5081 }
5082 Ok(ControlFlow::Continue)
5083 }
5084
5085 Stmt::DecreaseCrdt {
5086 object,
5087 field,
5088 amount,
5089 } => {
5090 let amount_val = self.evaluate_expr(amount).await?;
5091 let amount_int = match amount_val {
5092 RuntimeValue::Int(n) => n,
5093 _ => return Err("CRDT decrement amount must be an integer".to_string()),
5094 };
5095
5096 if let Expr::Identifier(obj_sym) = object {
5097 let mut obj_val = self.lookup(*obj_sym)?.clone();
5098
5099 if let RuntimeValue::Struct(ref mut s) = obj_val {
5100 let field_name = self.ctx.interner.resolve(*field).to_string();
5101 let current = s
5102 .fields
5103 .get(&field_name)
5104 .cloned()
5105 .unwrap_or(RuntimeValue::Int(0));
5106
5107 let new_val = crate::semantics::arith::crdt_counter_bump(
5108 current,
5109 amount_int.wrapping_neg(),
5110 &field_name,
5111 )?;
5112 s.fields.insert(field_name, new_val);
5113 self.assign(*obj_sym, obj_val)?;
5114 } else {
5115 return Err("Cannot decrease field on non-struct value".to_string());
5116 }
5117 } else {
5118 return Err("DecreaseCrdt target must be an identifier".to_string());
5119 }
5120 Ok(ControlFlow::Continue)
5121 }
5122
5123 Stmt::AppendToSequence { sequence, value } => {
5124 let val = self.evaluate_expr(value).await?;
5125 let seq_val = self.evaluate_expr(sequence).await?;
5126 match &seq_val {
5127 RuntimeValue::Crdt(rc) => rc.borrow_mut().append(&val)?,
5128 RuntimeValue::List(_) => {
5129 crate::semantics::collections::list_push(&seq_val, val)?
5130 }
5131 _ => return Err(format!("Cannot append to {}", seq_val.type_name())),
5132 }
5133 Ok(ControlFlow::Continue)
5134 }
5135
5136 Stmt::ResolveConflict {
5137 object,
5138 field,
5139 value,
5140 } => {
5141 let val = self.evaluate_expr(value).await?;
5142 let obj_val = self.evaluate_expr(object).await?;
5143 let field_name = self.ctx.interner.resolve(*field);
5144 if let RuntimeValue::Struct(s) = &obj_val {
5147 if let Some(RuntimeValue::Crdt(rc)) = s.fields.get(field_name) {
5148 rc.borrow_mut().resolve(&val)?;
5149 return Ok(ControlFlow::Continue);
5150 }
5151 }
5152 if let Expr::Identifier(obj_sym) = object {
5153 let mut owner = self.lookup(*obj_sym)?.clone();
5154 if let RuntimeValue::Struct(ref mut s) = owner {
5155 s.fields.insert(field_name.to_string(), val);
5156 self.assign(*obj_sym, owner)?;
5157 return Ok(ControlFlow::Continue);
5158 }
5159 }
5160 Err("Resolve target must be a struct field".to_string())
5161 }
5162
5163 Stmt::Check { .. } => self.exec_check(stmt),
5164
5165 Stmt::ConnectTo { address, secure } => {
5171 let raw = self.evaluate_expr(address).await?.to_display_string();
5172 let url = crate::concurrency::net_inbox::relay_url(&raw)?;
5173 if let Some(bind) = secure {
5175 self.activate_pnp_session(bind).await?;
5176 }
5177 if !crate::concurrency::net_inbox::net_is_offline() {
5182 let net = logicaffeine_system::net::Net::connect(&url)
5183 .await
5184 .map_err(|e| format!("Connect to relay '{url}' failed: {e}"))?;
5185 self.netbox.net = Some(net);
5186 }
5187 Ok(ControlFlow::Continue)
5188 }
5189 Stmt::Listen { address, secure } => {
5195 let raw = self.evaluate_expr(address).await?.to_display_string();
5196 let topic = logicaffeine_system::addr::canonical_topic(&raw);
5197 let hs_topic = crate::concurrency::net_inbox::handshake_topic_for(&topic);
5198 if let Some(bind) = secure {
5199 self.activate_pnp_session(bind).await?;
5200 }
5201 if let Some(net) = self.netbox.net.as_mut() {
5205 net.subscribe(&topic).await?;
5206 net.subscribe(&hs_topic).await?;
5208 }
5209 self.netbox.inbox = Some(Rc::new(topic));
5210 Ok(ControlFlow::Continue)
5211 }
5212 Stmt::Serve { port, handler } => {
5218 let port_num: u16 = match self.evaluate_expr(port).await? {
5219 RuntimeValue::Int(n) if (0..=65535).contains(&n) => n as u16,
5220 RuntimeValue::Int(n) => {
5221 return Err(format!("Serve: port {n} is out of range (0-65535)"))
5222 }
5223 other => {
5224 return Err(format!(
5225 "Serve: port must be an Int, got {}",
5226 other.type_name()
5227 ))
5228 }
5229 };
5230 let handler_sym = match handler {
5231 Expr::Identifier(sym) => *sym,
5232 _ => return Err("Serve: the handler must be a named function".to_string()),
5233 };
5234 self.serve_http(port_num, handler_sym).await?;
5235 Ok(ControlFlow::Continue)
5236 }
5237 Stmt::LetPeerAgent { var, address } => {
5241 let raw = self.evaluate_expr(address).await?.to_display_string();
5242 let topic = logicaffeine_system::addr::canonical_topic(&raw);
5243 self.define(*var, RuntimeValue::Peer(Rc::new(topic)));
5244 Ok(ControlFlow::Continue)
5245 }
5246 Stmt::Sleep { milliseconds } => {
5247 let val = self.evaluate_expr(milliseconds).await?;
5248 self.sleep_for(val).await?;
5249 Ok(ControlFlow::Continue)
5250 }
5251 Stmt::Sync { var, topic } => {
5256 let topic_str = self.evaluate_expr(topic).await?.to_display_string();
5257 let current = self.lookup(*var)?.clone();
5258 let is_counter = |rc: &std::rc::Rc<
5269 std::cell::RefCell<crate::semantics::crdt::CrdtValue>,
5270 >| { rc.borrow().counter_value().is_some() };
5271 let crdt_fields: Vec<(
5272 String,
5273 std::rc::Rc<std::cell::RefCell<crate::semantics::crdt::CrdtValue>>,
5274 )> = match ¤t {
5275 RuntimeValue::Crdt(rc) if !is_counter(rc) => vec![(String::new(), rc.clone())],
5276 RuntimeValue::Crdt(_) => Vec::new(),
5277 RuntimeValue::Struct(s) => s
5278 .fields
5279 .iter()
5280 .filter_map(|(k, v)| match v {
5281 RuntimeValue::Crdt(rc) if !is_counter(rc) => {
5282 Some((k.clone(), rc.clone()))
5283 }
5284 _ => None,
5285 })
5286 .collect(),
5287 _ => Vec::new(),
5288 };
5289 if !crdt_fields.is_empty() {
5290 let field_key = |name: &str| format!("{topic_str}\u{0}{name}");
5291 let mut frame: Vec<(String, Vec<u8>)> = Vec::new();
5293 for (name, rc) in &crdt_fields {
5294 let since = self
5295 .netbox
5296 .sync_versions
5297 .get(&field_key(name))
5298 .cloned()
5299 .unwrap_or_default();
5300 if let Some(d) = rc.borrow().delta_since_bytes(&since) {
5301 frame.push((name.clone(), d));
5302 }
5303 }
5304 let payload = serde_json::to_vec(&frame).unwrap_or_default();
5305 if let Some(net) = self.netbox.net.as_mut() {
5309 net.subscribe(&topic_str).await?;
5310 if !frame.is_empty() {
5311 net.publish(&topic_str, payload)?;
5312 }
5313 let incoming = net.drain();
5314 for (_t, data) in incoming {
5316 let Ok(fields) =
5317 serde_json::from_slice::<Vec<(String, Vec<u8>)>>(&data)
5318 else {
5319 continue;
5320 };
5321 for (name, delta) in fields {
5322 if let Some((_, rc)) = crdt_fields.iter().find(|(n, _)| *n == name)
5323 {
5324 rc.borrow_mut().apply_delta_bytes(&delta);
5325 }
5326 }
5327 }
5328 }
5329 for (name, rc) in &crdt_fields {
5331 let v = rc.borrow().version();
5332 self.netbox.sync_versions.insert(field_key(name), v);
5333 }
5334 return Ok(ControlFlow::Continue);
5335 }
5336 let publish_bytes = crate::semantics::arith::crdt_to_wire(¤t);
5339 let merged = if let Some(net) = self.netbox.net.as_mut() {
5345 net.subscribe(&topic_str).await?;
5346 if let Some(bytes) = publish_bytes {
5347 net.publish(&topic_str, bytes)?;
5348 }
5349 let incoming = net.drain();
5352 let mut merged = current;
5353 for (_t, data) in incoming {
5354 merged = crate::semantics::arith::crdt_merge_wire(merged, &data);
5355 }
5356 merged
5357 } else {
5358 current
5359 };
5360 self.assign(*var, merged)?;
5361 Ok(ControlFlow::Continue)
5362 }
5363 Stmt::Mount { var, path } => {
5365 let path_val = self.evaluate_expr(path).await?.to_display_string();
5366 match &self.ctx.vfs {
5367 Some(vfs) => {
5368 let content = match vfs.read_to_string(&path_val).await {
5370 Ok(s) => s,
5371 Err(_) => String::new(),
5372 };
5373 self.define(*var, RuntimeValue::Text(Rc::new(content)));
5374 }
5375 None => {
5376 return Err("VFS not initialized. Use Interpreter::with_vfs()".to_string())
5377 }
5378 }
5379 Ok(ControlFlow::Continue)
5380 }
5381
5382 Stmt::CreatePipe { var, capacity, .. } => {
5385 let cap = capacity.map(|c| c as usize);
5386 let resume = self.yield_request(BlockingRequest::NewChan(cap)).await;
5387 let ch = resume
5388 .into_chan()
5389 .ok_or_else(|| "scheduler did not create a channel".to_string())?;
5390 self.define(*var, RuntimeValue::Chan(ch));
5391 Ok(ControlFlow::Continue)
5392 }
5393 Stmt::SendPipe { value, pipe } => {
5394 let ch = self.eval_chan(pipe).await?;
5395 let val = self.evaluate_expr(value).await?;
5396 let payload = marshal::materialize(&val)
5397 .map_err(|e| format!("cannot send value through a channel: {:?}", e))?;
5398 self.yield_request(BlockingRequest::Send(ch, payload)).await;
5399 Ok(ControlFlow::Continue)
5400 }
5401 Stmt::ReceivePipe { var, pipe } => {
5402 let ch = self.eval_chan(pipe).await?;
5403 let resume = self.yield_request(BlockingRequest::Recv(ch)).await;
5404 let value = marshal::rebuild(resume.into_payload());
5405 self.define(*var, value);
5406 Ok(ControlFlow::Continue)
5407 }
5408 Stmt::LaunchTask { function, args } => {
5409 let mut arg_vals = Vec::with_capacity(args.len());
5410 for a in args.iter() {
5411 let val = self.evaluate_expr(a).await?;
5412 arg_vals.push(crossing_to_a_task(&val)?);
5413 }
5414 let child = self.spawn_child_task(*function, arg_vals);
5415 self.yield_request(BlockingRequest::Spawn(child)).await;
5416 Ok(ControlFlow::Continue)
5417 }
5418 Stmt::LaunchTaskWithHandle {
5419 handle,
5420 function,
5421 args,
5422 } => {
5423 let mut arg_vals = Vec::with_capacity(args.len());
5424 for a in args.iter() {
5425 let val = self.evaluate_expr(a).await?;
5426 arg_vals.push(crossing_to_a_task(&val)?);
5427 }
5428 let child = self.spawn_child_task(*function, arg_vals);
5429 let resume = self.yield_request(BlockingRequest::Spawn(child)).await;
5430 let tid = resume
5431 .into_task()
5432 .ok_or_else(|| "scheduler did not return a task handle".to_string())?;
5433 self.define(*handle, RuntimeValue::TaskHandle(tid));
5434 Ok(ControlFlow::Continue)
5435 }
5436 Stmt::StopTask { handle } => {
5437 let tid = self.eval_task(handle).await?;
5438 self.yield_request(BlockingRequest::Abort(tid)).await;
5439 Ok(ControlFlow::Continue)
5440 }
5441 Stmt::CloseChannel { channel } => {
5442 let ch = self.eval_chan(channel).await?;
5443 self.yield_request(BlockingRequest::Close(ch)).await;
5444 Ok(ControlFlow::Continue)
5445 }
5446 Stmt::AwaitTask { handle, result } => {
5447 let tid = self.eval_task(handle).await?;
5448 let resume = self.yield_request(BlockingRequest::Await(tid)).await;
5449 let value = marshal::rebuild(resume.into_payload());
5450 if let Some(r) = result {
5451 self.define(*r, value);
5452 }
5453 Ok(ControlFlow::Continue)
5454 }
5455 Stmt::TrySendPipe {
5456 value,
5457 pipe,
5458 result,
5459 } => {
5460 let ch = self.eval_chan(pipe).await?;
5461 let val = self.evaluate_expr(value).await?;
5462 let payload = marshal::materialize(&val)
5463 .map_err(|e| format!("cannot send value through a channel: {:?}", e))?;
5464 let resume = self
5465 .yield_request(BlockingRequest::TrySend(ch, payload))
5466 .await;
5467 let ok = matches!(resume.into_payload(), RtPayload::Bool(true));
5468 if let Some(res) = result {
5469 self.define(*res, RuntimeValue::Bool(ok));
5470 }
5471 Ok(ControlFlow::Continue)
5472 }
5473 Stmt::TryReceivePipe { var, pipe } => {
5474 let ch = self.eval_chan(pipe).await?;
5475 let resume = self.yield_request(BlockingRequest::TryRecv(ch)).await;
5476 let value = match marshal::rebuild(resume.into_payload()) {
5486 RuntimeValue::Nothing => option_none(),
5487 v => option_some(v),
5488 };
5489 self.define(*var, value);
5490 Ok(ControlFlow::Continue)
5491 }
5492 Stmt::Select { branches } => {
5493 use crate::ast::stmt::SelectBranch;
5494 let mut arms = Vec::with_capacity(branches.len());
5497 for branch in branches.iter() {
5498 match branch {
5499 SelectBranch::Receive { pipe, .. } => {
5500 let ch = self.eval_chan(pipe).await?;
5501 arms.push(SelectArm::Recv(ch));
5502 }
5503 SelectBranch::Timeout { milliseconds, .. } => {
5504 let ticks = self.eval_select_timeout_ticks(milliseconds).await?;
5505 arms.push(SelectArm::Timeout(ticks));
5506 }
5507 }
5508 }
5509 let resume = self.yield_request(BlockingRequest::Select(arms)).await;
5510 let (arm, payload) = resume
5511 .into_select()
5512 .ok_or_else(|| "scheduler did not resolve the select".to_string())?;
5513 match &branches[arm] {
5514 SelectBranch::Receive { var, body, .. } => {
5515 self.define(*var, marshal::rebuild(payload));
5516 self.execute_block(*body).await
5517 }
5518 SelectBranch::Timeout { body, .. } => self.execute_block(*body).await,
5519 }
5520 }
5521
5522 Stmt::Escape { .. } => Err(crate::semantics::escape::REFUSAL.to_string()),
5524
5525 Stmt::Require { .. } => Ok(ControlFlow::Continue),
5527
5528 Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {
5531 Ok(ControlFlow::Continue)
5532 }
5533
5534 Stmt::Site(id) => {
5538 self.current_site = Some(*id);
5539 Ok(ControlFlow::Continue)
5540 }
5541 }
5542 }
5543
5544 #[async_recursion(?Send)]
5547 async fn execute_block(&mut self, block: Block<'a>) -> Result<ControlFlow, String> {
5548 self.push_scope();
5549 for stmt in block.iter() {
5550 match self.execute_stmt(stmt).await? {
5551 ControlFlow::Continue => {}
5552 flow => {
5553 self.pop_scope();
5554 return Ok(flow);
5555 }
5556 }
5557 }
5558 self.pop_scope();
5559 Ok(ControlFlow::Continue)
5560 }
5561
5562 fn inspect_unhandled(&self, target: &RuntimeValue) -> String {
5571 let variant = match target {
5572 RuntimeValue::Inductive(i) => i.constructor.as_str(),
5573 _ => "the value",
5574 };
5575 crate::semantics::builtins::inspect_unhandled_message(target.type_name(), variant)
5576 }
5577
5578 #[async_recursion(?Send)]
5582 async fn execute_inspect(
5583 &mut self,
5584 target: &RuntimeValue,
5585 arms: &[MatchArm<'a>],
5586 ) -> Result<ControlFlow, String> {
5587 for arm in arms {
5588 if arm.variant.is_none() {
5590 let flow = self.execute_block(arm.body).await?;
5591 return Ok(flow);
5592 }
5593
5594 match target {
5595 RuntimeValue::Struct(s) => {
5596 if let Some(variant) = arm.variant {
5597 let variant_name = self.ctx.interner.resolve(variant);
5598 if s.type_name == variant_name {
5599 self.push_scope();
5600 for (field_name, binding_name) in &arm.bindings {
5601 let field_str = self.ctx.interner.resolve(*field_name);
5602 if let Some(val) = s.fields.get(field_str) {
5603 self.define(*binding_name, val.clone());
5604 }
5605 }
5606 let result = self.execute_block(arm.body).await;
5607 self.pop_scope();
5608 let flow = result?;
5609 return Ok(flow);
5610 }
5611 }
5627 }
5628
5629 RuntimeValue::Inductive(ind) => {
5630 if let Some(variant) = arm.variant {
5631 let variant_name = self.ctx.interner.resolve(variant);
5632 if ind.constructor == variant_name {
5633 self.push_scope();
5634 for (i, (_, binding_name)) in arm.bindings.iter().enumerate() {
5635 if i < ind.args.len() {
5636 self.define(*binding_name, ind.args[i].clone());
5637 }
5638 }
5639 let result = self.execute_block(arm.body).await;
5640 self.pop_scope();
5641 let flow = result?;
5642 return Ok(flow);
5643 }
5644 }
5645 }
5646
5647 RuntimeValue::Nothing => {
5652 if let Some(variant) = arm.variant {
5653 if self.ctx.interner.resolve(variant) == "None" {
5654 let flow = self.execute_block(arm.body).await?;
5655 return Ok(flow);
5656 }
5657 }
5658 }
5659
5660 _ => {}
5665 }
5666 }
5667 Err(self.inspect_unhandled(target))
5668 }
5669
5670 fn build_wire_type_registry(&self) -> crate::concurrency::marshal::WireTypeRegistry {
5679 let is_builtin = |name_sym: &Symbol| {
5680 self.ctx
5681 .types
5682 .as_ref()
5683 .is_some_and(|t| t.is_builtin_struct(*name_sym))
5684 };
5685 let schemas: Vec<(String, Vec<String>)> = self
5686 .ctx
5687 .struct_defs
5688 .iter()
5689 .filter(|(name_sym, _)| !is_builtin(name_sym))
5690 .map(|(name_sym, fields)| {
5691 let type_name = self.ctx.interner.resolve(*name_sym).to_string();
5692 let field_names = fields
5693 .iter()
5694 .map(|(fname, _ty, _public)| self.ctx.interner.resolve(*fname).to_string())
5695 .collect();
5696 (type_name, field_names)
5697 })
5698 .collect();
5699 let enums: Vec<(String, Vec<String>)> = self
5700 .ctx
5701 .enum_defs
5702 .iter()
5703 .map(|(name_sym, ctors)| {
5704 let type_name = self.ctx.interner.resolve(*name_sym).to_string();
5705 let ctor_names = ctors
5706 .iter()
5707 .map(|c| self.ctx.interner.resolve(*c).to_string())
5708 .collect();
5709 (type_name, ctor_names)
5710 })
5711 .collect();
5712 crate::concurrency::marshal::WireTypeRegistry::new(schemas).with_enums(enums)
5713 }
5714
5715 async fn await_message_from(&mut self, want: &str, view: bool) -> Result<RuntimeValue, String> {
5720 loop {
5721 if let Some(v) = self.netbox.try_take_message(want, view) {
5722 return Ok(v);
5723 }
5724 let registry = self.build_wire_type_registry();
5725 self.netbox.drain(registry);
5726 if let Some(v) = self.netbox.try_take_message(want, view) {
5727 return Ok(v);
5728 }
5729 Self::poll_tick().await;
5730 }
5731 }
5732
5733 async fn await_stream_from(&mut self, want: &str) -> Result<RuntimeValue, String> {
5736 loop {
5737 if let Some(v) = self.netbox.try_take_stream(want) {
5738 return Ok(v);
5739 }
5740 let registry = self.build_wire_type_registry();
5741 self.netbox.drain(registry);
5742 if let Some(v) = self.netbox.try_take_stream(want) {
5743 return Ok(v);
5744 }
5745 Self::poll_tick().await;
5746 }
5747 }
5748
5749 async fn poll_tick() {
5752 #[cfg(not(target_arch = "wasm32"))]
5753 logicaffeine_system::tokio::time::sleep(std::time::Duration::from_millis(2)).await;
5754 #[cfg(target_arch = "wasm32")]
5755 gloo_timers::future::TimeoutFuture::new(2).await;
5756 }
5757
5758 #[async_recursion(?Send)]
5761 async fn evaluate_expr(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
5762 match expr {
5763 Expr::View(_) => Err(
5764 "A view is drawn by the component it belongs to — place it in that component's `View:`."
5765 .to_string(),
5766 ),
5767 Expr::Dom(q) => self.evaluate_dom_query(q),
5768 Expr::Literal(lit) => self.evaluate_literal(lit),
5769
5770 Expr::Identifier(sym) => {
5771 let name = self.ctx.interner.resolve(*sym);
5772 match name {
5774 "today" => {
5775 return Ok(crate::semantics::temporal::today());
5776 }
5777 "now" => {
5778 return Ok(crate::semantics::temporal::now());
5779 }
5780 _ => {}
5781 }
5782 self.lookup(*sym).cloned()
5783 }
5784
5785 Expr::BinaryOp { op, left, right } => {
5786 match op {
5787 BinaryOpKind::And => {
5788 let left_val = self.evaluate_expr(left).await?;
5789 if !left_val.decided_truth()? {
5790 return Ok(RuntimeValue::Bool(false));
5791 }
5792 let right_val = self.evaluate_expr(right).await?;
5793 Ok(RuntimeValue::Bool(right_val.decided_truth()?))
5794 }
5795 BinaryOpKind::Or => {
5796 let left_val = self.evaluate_expr(left).await?;
5797 if left_val.decided_truth()? {
5798 return Ok(RuntimeValue::Bool(true));
5799 }
5800 let right_val = self.evaluate_expr(right).await?;
5801 Ok(RuntimeValue::Bool(right_val.decided_truth()?))
5802 }
5803 _ => {
5804 let left_val = self.evaluate_expr(left).await?;
5805 let right_val = self.evaluate_expr(right).await?;
5806 self.apply_binary_op(*op, left_val, right_val)
5807 }
5808 }
5809 }
5810
5811 Expr::Call { function, args } => {
5812 self.call_function(*function, args).await
5813 }
5814
5815 Expr::Index { collection, index } => {
5816 let coll_val = self.evaluate_expr(collection).await?;
5817 let idx_val = self.evaluate_expr(index).await?;
5818 crate::semantics::collections::index_get(&coll_val, &idx_val)
5819 }
5820
5821 Expr::Slice { collection, start, end } => {
5822 let coll_val = self.evaluate_expr(collection).await?;
5823 let start_val = self.evaluate_expr(start).await?;
5824 let end_val = self.evaluate_expr(end).await?;
5825 crate::semantics::collections::slice(&coll_val, &start_val, &end_val)
5826 }
5827
5828 Expr::Copy { expr: inner } => {
5829 let val = self.evaluate_expr(inner).await?;
5830 Ok(val.deep_clone())
5831 }
5832
5833 Expr::Give { value } => {
5834 self.evaluate_expr(value).await
5836 }
5837
5838 Expr::Length { collection } => {
5839 let coll_val = self.evaluate_expr(collection).await?;
5840 crate::semantics::collections::length_of(&coll_val)
5841 }
5842
5843 Expr::Contains { collection, value } => {
5844 let coll_val = self.evaluate_expr(collection).await?;
5845 let val = self.evaluate_expr(value).await?;
5846 crate::semantics::collections::contains(&coll_val, &val)
5847 }
5848
5849 Expr::Union { left, right } => {
5850 let left_val = self.evaluate_expr(left).await?;
5851 let right_val = self.evaluate_expr(right).await?;
5852 crate::semantics::collections::union(&left_val, &right_val)
5853 }
5854
5855 Expr::Intersection { left, right } => {
5856 let left_val = self.evaluate_expr(left).await?;
5857 let right_val = self.evaluate_expr(right).await?;
5858 crate::semantics::collections::intersection(&left_val, &right_val)
5859 }
5860
5861 Expr::List(items) => {
5862 let mut values = Vec::with_capacity(items.len());
5863 for e in items.iter() {
5864 values.push(self.evaluate_expr(e).await?);
5865 }
5866 Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(values)))))
5867 }
5868
5869 Expr::Tuple(items) => {
5870 let mut values = Vec::with_capacity(items.len());
5871 for e in items.iter() {
5872 values.push(self.evaluate_expr(e).await?);
5873 }
5874 Ok(RuntimeValue::Tuple(Rc::new(values)))
5875 }
5876
5877 Expr::Range { start, end } => {
5878 let start_val = self.evaluate_expr(start).await?;
5879 let end_val = self.evaluate_expr(end).await?;
5880 crate::semantics::collections::range(&start_val, &end_val)
5881 }
5882
5883 Expr::FieldAccess { object, field } => {
5884 let obj_val = self.evaluate_expr(object).await?;
5885 match &obj_val {
5886 RuntimeValue::Struct(s) => {
5887 let field_name = self.ctx.interner.resolve(*field);
5888 s.fields.get(field_name).cloned()
5889 .ok_or_else(|| format!("Field '{}' not found", field_name))
5890 }
5891 _ => Err(format!("Cannot access field on {}", obj_val.type_name())),
5892 }
5893 }
5894
5895 Expr::New { type_name, init_fields, .. } => {
5896 let name = self.ctx.interner.resolve(*type_name).to_string();
5897
5898 if name == "Seq" || name == "List" {
5899 return Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))));
5900 }
5901
5902 if name == "Set" || name == "HashSet" {
5903 return Ok(RuntimeValue::Set(Rc::new(RefCell::new(vec![]))));
5904 }
5905
5906 if name == "Map" || name == "HashMap" {
5907 return Ok(RuntimeValue::Map(Rc::new(RefCell::new(MapStorage::default()))));
5908 }
5909
5910 let mut fields = HashMap::new();
5911 for (field_sym, field_expr) in init_fields {
5912 let field_name = self.ctx.interner.resolve(*field_sym).to_string();
5913 let field_val = self.evaluate_expr(field_expr).await?;
5914 fields.insert(field_name, field_val);
5915 }
5916
5917 if let Some(def) = self.ctx.struct_defs.get(type_name) {
5918 for (field_sym, type_sym, _) in def {
5919 let field_name = self.ctx.interner.resolve(*field_sym).to_string();
5920 if !fields.contains_key(&field_name) {
5921 let type_name_str = self.ctx.interner.resolve(*type_sym).to_string();
5922 let default = default_for_declared_type(type_name_str.as_str());
5923 fields.insert(field_name, default);
5924 }
5925 }
5926 }
5927
5928 Ok(RuntimeValue::Struct(Box::new(StructValue { type_name: name, fields })))
5929 }
5930
5931 Expr::NewVariant { enum_name, variant, fields } => {
5934 let inductive_type = self.ctx.interner.resolve(*enum_name).to_string();
5935 let constructor = self.ctx.interner.resolve(*variant).to_string();
5936
5937 let declared = self.ctx.variant_fields.get(&(*enum_name, *variant)).cloned();
5949 let args = match &declared {
5950 Some(names) => {
5951 let mut slots: Vec<Option<RuntimeValue>> = (0..names.len()).map(|_| None).collect();
5952 for (field_name, field_expr) in fields {
5953 let field_val = self.evaluate_expr(field_expr).await?;
5954 if let Some(pos) = names.iter().position(|n| n == field_name) {
5955 slots[pos] = Some(field_val);
5956 }
5957 }
5958 slots.into_iter().map(|v| v.unwrap_or(RuntimeValue::Nothing)).collect()
5959 }
5960 None => {
5961 let mut args = Vec::with_capacity(fields.len());
5962 for (_, field_expr) in fields {
5963 args.push(self.evaluate_expr(field_expr).await?);
5964 }
5965 args
5966 }
5967 };
5968
5969 Ok(RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
5970 inductive_type,
5971 constructor,
5972 args,
5973 })))
5974 }
5975
5976 Expr::ManifestOf { .. } => {
5977 Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))))
5978 }
5979
5980 Expr::ChunkAt { .. } => {
5981 Ok(RuntimeValue::Nothing)
5982 }
5983
5984 Expr::WithCapacity { value, capacity } => {
5985 let capacity = match self.evaluate_expr(capacity).await? {
5986 RuntimeValue::Int(capacity) => capacity,
5987 _ => return Err("Capacity requires an Int".to_string()),
5988 };
5989 let value = self.evaluate_expr(value).await?;
5990 Ok(apply_capacity_hint(value, capacity))
5991 }
5992
5993 Expr::OptionSome { value } => {
6002 let inner = self.evaluate_expr(value).await?;
6003 Ok(option_some(inner))
6004 }
6005
6006 Expr::OptionNone => Ok(option_none()),
6007
6008 Expr::Not { operand } => {
6009 let val = self.evaluate_expr(operand).await?;
6010 crate::semantics::arith::not_value(val)
6011 }
6012
6013 Expr::InterpolatedString(parts) => {
6014 let mut result = String::new();
6015 for part in parts {
6016 match part {
6017 crate::ast::stmt::StringPart::Literal(sym) => {
6018 result.push_str(self.ctx.interner.resolve(*sym));
6019 }
6020 crate::ast::stmt::StringPart::Expr { value, format_spec, debug } => {
6021 let val = self.evaluate_expr(value).await?;
6022 if *debug {
6023 let prefix = match value {
6024 Expr::Identifier(sym) => self.ctx.interner.resolve(*sym).to_string(),
6025 _ => "expr".to_string(),
6026 };
6027 result.push_str(&prefix);
6028 result.push('=');
6029 }
6030 if let Some(spec_sym) = format_spec {
6031 let spec = self.ctx.interner.resolve(*spec_sym);
6032 result.push_str(&apply_format_spec(&val, spec));
6033 } else {
6034 result.push_str(&val.to_display_string());
6035 }
6036 }
6037 }
6038 }
6039 Ok(RuntimeValue::Text(Rc::new(result)))
6040 }
6041
6042 Expr::Escape { .. } => {
6043 Err(crate::semantics::escape::REFUSAL.to_string())
6044 }
6045
6046 Expr::Closure { params, body, .. } => {
6047 let free_vars = self.collect_free_vars_in_closure(params, body);
6048 let mut captured_env = HashMap::new();
6049 for sym in &free_vars {
6050 if let Some(val) = self.task.env.lookup(*sym) {
6051 captured_env.insert(*sym, val.deep_clone());
6052 }
6053 }
6054
6055 let body_index = self.ctx.closure_bodies.len();
6056 match body {
6057 ClosureBody::Expression(expr) => {
6058 self.ctx.closure_bodies.push(ClosureBodyRef::Expression(expr));
6059 }
6060 ClosureBody::Block(block) => {
6061 self.ctx.closure_bodies.push(ClosureBodyRef::Block(block));
6062 }
6063 }
6064
6065 let param_names: Vec<Symbol> = params.iter().map(|(name, _)| *name).collect();
6066
6067 Ok(RuntimeValue::Function(Box::new(ClosureValue {
6068 body_index,
6069 captured_env,
6070 param_names,
6071 generated: None,
6072 })))
6073 }
6074
6075 Expr::CallExpr { callee, args } => {
6076 let callee_val = self.evaluate_expr(callee).await?;
6077 if let RuntimeValue::Function(closure) = callee_val {
6078 let mut arg_values = Vec::with_capacity(args.len());
6079 for arg in args.iter() {
6080 arg_values.push(self.evaluate_expr(arg).await?);
6081 }
6082 self.call_closure_value(&closure, arg_values).await
6083 } else {
6084 Err(format!("Cannot call value of type {}", callee_val.type_name()))
6085 }
6086 }
6087 }
6088 }
6089
6090 fn evaluate_literal(&self, lit: &Literal) -> Result<RuntimeValue, String> {
6092 match lit {
6093 Literal::Number(n) => Ok(RuntimeValue::Int(*n)),
6094 Literal::Float(f) => Ok(RuntimeValue::Float(*f)),
6095 Literal::Text(sym) => Ok(RuntimeValue::Text(Rc::new(
6096 self.ctx.interner.resolve(*sym).to_string(),
6097 ))),
6098 Literal::Boolean(b) => Ok(RuntimeValue::Bool(*b)),
6099 Literal::Nothing => Ok(RuntimeValue::Nothing),
6100 Literal::Char(c) => Ok(RuntimeValue::Char(*c)),
6101 Literal::Duration(nanos) => Ok(RuntimeValue::Duration(*nanos)),
6102 Literal::Date(days) => Ok(RuntimeValue::Date(*days)),
6103 Literal::Moment(nanos) => Ok(RuntimeValue::Moment(*nanos)),
6104 Literal::Span { months, days } => Ok(RuntimeValue::Span {
6105 months: *months,
6106 days: *days,
6107 }),
6108 Literal::Time(nanos) => Ok(RuntimeValue::Time(*nanos)),
6109 }
6110 }
6111
6112 fn apply_binary_op(
6114 &self,
6115 op: BinaryOpKind,
6116 left: RuntimeValue,
6117 right: RuntimeValue,
6118 ) -> Result<RuntimeValue, String> {
6119 crate::semantics::arith::binary_op(op, left, right)
6120 }
6121
6122 pub fn values_equal_pub(&self, left: &RuntimeValue, right: &RuntimeValue) -> bool {
6123 self.values_equal(left, right)
6124 }
6125
6126 fn values_equal(&self, left: &RuntimeValue, right: &RuntimeValue) -> bool {
6127 crate::semantics::compare::values_equal(left, right)
6128 }
6129
6130 fn coerce_record_return(&self, val: RuntimeValue, function: Symbol) -> RuntimeValue {
6135 let rt = match self
6136 .ctx
6137 .functions
6138 .get(&function)
6139 .and_then(|f| f.return_type)
6140 {
6141 Some(rt) => rt,
6142 None => return val,
6143 };
6144 if let crate::ast::stmt::TypeExpr::Record { field_names, .. } = rt {
6145 if let RuntimeValue::Tuple(elems) = &val {
6146 if elems.len() == field_names.len() {
6147 let mut fields = HashMap::with_capacity(field_names.len());
6148 for (n, v) in field_names.iter().zip(elems.iter()) {
6149 fields.insert(self.ctx.interner.resolve(*n).to_string(), v.clone());
6150 }
6151 return RuntimeValue::Struct(Box::new(StructValue {
6152 type_name: "Record".to_string(),
6153 fields,
6154 }));
6155 }
6156 }
6157 }
6158 val
6159 }
6160
6161 #[async_recursion(?Send)]
6163 async fn call_function(
6164 &mut self,
6165 function: Symbol,
6166 args: &[&'async_recursion Expr<'a>],
6167 ) -> Result<RuntimeValue, String> {
6168 let func_sym = Some(function);
6170 if self.declares(function) {
6171 } else if func_sym == self.ctx.sym_show {
6173 for arg in args {
6174 let val = self.evaluate_expr(arg).await?;
6175 self.emit_output(val.to_display_string());
6176 }
6177 return Ok(RuntimeValue::Nothing);
6178 } else if func_sym == self.ctx.sym_args {
6179 let items: Vec<RuntimeValue> = self
6183 .ctx
6184 .program_args
6185 .iter()
6186 .map(|s| RuntimeValue::Text(Rc::new(s.clone())))
6187 .collect();
6188 return Ok(RuntimeValue::List(Rc::new(RefCell::new(
6189 ListRepr::from_values(items),
6190 ))));
6191 } else if self.pbkdf2_accel(function, args.len()) {
6192 let pw = self.evaluate_expr(&args[0]).await?;
6199 let salt = self.evaluate_expr(&args[1]).await?;
6200 let iters = self.evaluate_expr(&args[2]).await?;
6201 let (pw, salt, iters) = crate::semantics::builtins::pbkdf2_arguments(&pw, &salt, &iters)?;
6202 let dk = crate::crypto_accel::pbkdf2_sha256(&pw, &salt, iters);
6203 return Ok(crate::semantics::builtins::bytes_to_seq(&dk));
6204 } else if let Some(kernel) = self.native_kernel(function, args.len()) {
6205 let mut vals = Vec::with_capacity(args.len());
6209 for arg in args {
6210 vals.push(self.evaluate_expr(arg).await?);
6211 }
6212 return kernel.call(&vals);
6213 } else if let Some(id) = self.system_native_id(function, args.len()) {
6214 let mut vals = Vec::with_capacity(args.len());
6220 for arg in args {
6221 vals.push(self.evaluate_expr(arg).await?);
6222 }
6223 return crate::semantics::builtins::call_builtin(id, vals);
6224 } else if self.sleep_native(function, args.len()) {
6225 let val = self.evaluate_expr(&args[0]).await?;
6227 self.sleep_for(val).await?;
6228 return Ok(RuntimeValue::Nothing);
6229 } else if let Some(op) = self.tcp_native_op(function, args.len()) {
6230 let mut vals = Vec::with_capacity(args.len());
6235 for arg in args {
6236 vals.push(self.evaluate_expr(arg).await?);
6237 }
6238 return self.tcpbox.exec_values(op, vals).await;
6239 } else if let Some(id) = self.builtin_id(function) {
6240 crate::semantics::builtins::check_arity(id, args.len())?;
6242 let vals = if id == crate::semantics::builtins::BuiltinId::Format {
6244 match args.first() {
6245 Some(a) => vec![self.evaluate_expr(a).await?],
6246 None => Vec::new(),
6247 }
6248 } else {
6249 let mut v = Vec::with_capacity(args.len());
6250 for arg in args {
6251 v.push(self.evaluate_expr(arg).await?);
6252 }
6253 v
6254 };
6255 if id == crate::semantics::builtins::BuiltinId::DefinedReal {
6256 return self.open_defined_run().define(vals);
6257 }
6258 return crate::semantics::builtins::call_builtin(id, vals);
6259 }
6260
6261 if let Some(refusal) = self.native_refusal(function) {
6262 return Err(refusal);
6263 }
6264
6265 if let Some(func) = self.ctx.functions.get(&function) {
6267 let param_count = func.params.len();
6268 let body = func.body;
6269
6270 if args.len() != param_count {
6271 return Err(format!(
6272 "Function {} expects {} arguments, got {}",
6273 self.ctx.interner.resolve(function),
6274 param_count,
6275 args.len()
6276 ));
6277 }
6278
6279 let mut arg_values = Vec::with_capacity(param_count);
6281 let mut lent: Vec<(usize, Place)> = Vec::new();
6282 for (i, arg) in args.iter().enumerate() {
6283 if matches!(
6284 self.ctx.functions[&function].params[i].1,
6285 TypeExpr::Mutable { .. }
6286 ) {
6287 let place = match self.place(arg).await {
6288 Ok(place) => place,
6289 Err(e) => {
6290 let values = self.values_to_give_back(&lent, &mut arg_values);
6291 self.give_back(lent, values);
6292 return Err(e);
6293 }
6294 };
6295 if let Some(value) = place.as_ref().and_then(|place| self.lend(place)) {
6296 arg_values.push(value);
6297 lent.push((i, place.expect("a lent argument names a place")));
6298 continue;
6299 }
6300 }
6301 match self.evaluate_expr(arg).await {
6302 Ok(v) => arg_values.push(v),
6303 Err(e) => {
6304 let values = self.values_to_give_back(&lent, &mut arg_values);
6305 self.give_back(lent, values);
6306 return Err(e);
6307 }
6308 }
6309 }
6310
6311 if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
6314 let values = self.values_to_give_back(&lent, &mut arg_values);
6315 self.give_back(lent, values);
6316 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
6317 }
6318 self.task.call_depth += 1;
6319 self.task.env.push_frame();
6320 for i in 0..param_count {
6321 let param_name = self.ctx.functions[&function].params[i].0;
6322 self.task.env.define(
6323 param_name,
6324 std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
6325 );
6326 }
6327
6328 let prev_tco = self.task.tco_fn_async.replace(function);
6332 let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_async, 0);
6333 let mut return_value = RuntimeValue::Nothing;
6334 let mut body_err = None;
6335 'tco: loop {
6336 self.task.pending_tail_call_async = None;
6337 let mut idx = 0;
6338 while idx < body.len() {
6339 if idx + 1 < body.len() {
6340 if let Some(call_args) = crate::tail_call::tail_pair_args(
6341 &body[idx],
6342 &body[idx + 1],
6343 function,
6344 param_count,
6345 ) {
6346 let mut vals = Vec::with_capacity(call_args.len());
6347 let mut perr = None;
6348 for a in call_args {
6349 match self.evaluate_expr(a).await {
6350 Ok(v) => vals.push(v),
6351 Err(e) => {
6352 perr = Some(e);
6353 break;
6354 }
6355 }
6356 }
6357 match perr {
6358 Some(e) => body_err = Some(e),
6359 None => self.task.pending_tail_call_async = Some(vals),
6360 }
6361 break;
6362 }
6363 }
6364 match self.execute_stmt(&body[idx]).await {
6365 Ok(ControlFlow::Return(val)) => {
6366 return_value = val;
6367 break;
6368 }
6369 Ok(ControlFlow::Break) => break,
6370 Ok(ControlFlow::Continue) => {}
6371 Err(e) => {
6372 body_err = Some(e);
6373 break;
6374 }
6375 }
6376 idx += 1;
6377 }
6378 if body_err.is_some() {
6379 break 'tco;
6380 }
6381 match self.task.pending_tail_call_async.take() {
6382 Some(new_args) => {
6383 self.task.env.pop_frame();
6384 self.task.env.push_frame();
6385 for (i, v) in new_args.into_iter().enumerate() {
6386 let param_name = self.ctx.functions[&function].params[i].0;
6387 self.task.env.define(param_name, v);
6388 }
6389 continue 'tco;
6390 }
6391 None => break 'tco,
6392 }
6393 }
6394 self.task.repeat_depth_async = prev_repeat;
6395 self.task.tco_fn_async = prev_tco;
6396
6397 let returned = self.lent_values(function, &lent);
6398 self.task.env.pop_frame();
6399 self.give_back(lent, returned);
6400 self.task.call_depth -= 1;
6401 match body_err {
6402 Some(e) => Err(e),
6403 None => Ok(self.coerce_record_return(return_value, function)),
6404 }
6405 } else {
6406 let maybe_closure = self.task.env.lookup(function).and_then(|v| {
6408 if let RuntimeValue::Function(c) = v {
6409 Some((**c).clone())
6410 } else {
6411 None
6412 }
6413 });
6414
6415 if let Some(closure) = maybe_closure {
6416 let mut arg_values = Vec::with_capacity(args.len());
6417 for arg in args {
6418 arg_values.push(self.evaluate_expr(arg).await?);
6419 }
6420 self.call_closure_value(&closure, arg_values).await
6421 } else {
6422 Err(format!(
6423 "Unknown function: {}",
6424 self.ctx.interner.resolve(function)
6425 ))
6426 }
6427 }
6428 }
6429
6430 fn yield_request(&self, req: BlockingRequest<'a>) -> YieldFuture<'a> {
6435 let ys = self
6436 .yield_state
6437 .clone()
6438 .expect("concurrency op executed outside a scheduler context");
6439 ys.borrow_mut().request = Some(req);
6440 YieldFuture::new(ys)
6441 }
6442
6443 async fn eval_chan(&mut self, expr: &Expr<'a>) -> Result<ChanId, String> {
6445 match self.evaluate_expr(expr).await? {
6446 RuntimeValue::Chan(id) => Ok(id),
6447 other => Err(format!("expected a channel, found {}", other.type_name())),
6448 }
6449 }
6450
6451 async fn eval_task(&mut self, expr: &Expr<'a>) -> Result<TaskId, String> {
6453 match self.evaluate_expr(expr).await? {
6454 RuntimeValue::TaskHandle(id) => Ok(id),
6455 other => Err(format!(
6456 "expected a task handle, found {}",
6457 other.type_name()
6458 )),
6459 }
6460 }
6461
6462 async fn eval_select_timeout_ticks(&mut self, expr: &Expr<'a>) -> Result<u64, String> {
6467 let ticks = match self.evaluate_expr(expr).await? {
6468 RuntimeValue::Int(n) => n.max(0) as u64,
6469 RuntimeValue::Duration(d) => d.max(0) as u64,
6470 RuntimeValue::Span { months, days } => {
6471 (((months as i64) * 30 + days as i64) * 86_400).max(0) as u64
6472 }
6473 other => {
6474 return Err(format!(
6475 "select timeout must be a number or duration, found {}",
6476 other.type_name()
6477 ))
6478 }
6479 };
6480 Ok(ticks)
6481 }
6482
6483 fn spawn_child_task(
6486 &self,
6487 function: Symbol,
6488 args: Vec<RuntimeValue>,
6489 ) -> Box<dyn logicaffeine_runtime::Task<'a> + 'a> {
6490 let ys: Yield<'a> = Rc::new(RefCell::new(YieldState::new()));
6491 let mut child = Interpreter {
6492 ctx: self.ctx.clone(),
6493 task: TaskState::new(),
6494 output: Vec::new(),
6495 current_site: None,
6496 yield_state: Some(ys.clone()),
6497 err_sink: self.err_sink.clone(),
6498 netbox: crate::concurrency::net_inbox::NetInbox::new(),
6499 tcpbox: crate::concurrency::tcp_registry::TcpRegistry::new(),
6500 test_mode: false,
6505 test_failures: Vec::new(),
6506 test_ops: 0,
6507 test_assertions: 0,
6508 request_deadline: None,
6509 deadline_tick: 0,
6510 test_budget: u64::MAX,
6511 gen_rng: 0,
6512 prove_mode: false,
6513 properties_proven: 0,
6514 fuel: self.fuel.clone(),
6516 tiers_noop: false,
6517 page: PageSeat::Unseated,
6520 statement_observer: None,
6521 page_main: None,
6522 failed_call_site: None,
6523 defined_run: None,
6524 };
6525 let fut = Box::pin(async move {
6526 child
6527 .call_function_with_values(function, args)
6528 .await
6529 .map(|_| ())
6530 });
6531 Box::new(InterpreterTask::new(fut, ys, self.err_sink.clone()))
6532 }
6533
6534 #[async_recursion(?Send)]
6535 async fn call_function_with_values(
6536 &mut self,
6537 function: Symbol,
6538 mut args: Vec<RuntimeValue>,
6539 ) -> Result<RuntimeValue, String> {
6540 if Some(function) == self.ctx.sym_show {
6542 for val in args {
6543 self.emit_output(val.to_display_string());
6544 }
6545 return Ok(RuntimeValue::Nothing);
6546 }
6547 if let Some(id) = self.system_native_id(function, args.len()) {
6548 return crate::semantics::builtins::call_builtin(id, args);
6549 }
6550 if let Some(kernel) = self.native_kernel(function, args.len()) {
6551 return kernel.call(&args);
6552 }
6553 if self.sleep_native(function, args.len()) {
6554 self.sleep_for(args.remove(0)).await?;
6555 return Ok(RuntimeValue::Nothing);
6556 }
6557 if let Some(refusal) = self.native_refusal(function) {
6558 return Err(refusal);
6559 }
6560
6561 if let Some(func) = self.ctx.functions.get(&function) {
6562 let param_count = func.params.len();
6563 let body = func.body;
6564
6565 if args.len() != param_count {
6566 return Err(format!(
6567 "Function {} expects {} arguments, got {}",
6568 self.ctx.interner.resolve(function),
6569 param_count,
6570 args.len()
6571 ));
6572 }
6573
6574 if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
6575 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
6576 }
6577 self.task.call_depth += 1;
6578 self.task.env.push_frame();
6579 for i in 0..param_count {
6580 let param_name = self.ctx.functions[&function].params[i].0;
6581 self.task.env.define(
6582 param_name,
6583 std::mem::replace(&mut args[i], RuntimeValue::Nothing),
6584 );
6585 }
6586
6587 let prev_tco = self.task.tco_fn_async.replace(function);
6590 let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_async, 0);
6591 let mut return_value = RuntimeValue::Nothing;
6592 let mut body_err = None;
6593 'tco: loop {
6594 self.task.pending_tail_call_async = None;
6595 let mut idx = 0;
6596 while idx < body.len() {
6597 if idx + 1 < body.len() {
6598 if let Some(call_args) = crate::tail_call::tail_pair_args(
6599 &body[idx],
6600 &body[idx + 1],
6601 function,
6602 param_count,
6603 ) {
6604 let mut vals = Vec::with_capacity(call_args.len());
6605 let mut perr = None;
6606 for a in call_args {
6607 match self.evaluate_expr(a).await {
6608 Ok(v) => vals.push(v),
6609 Err(e) => {
6610 perr = Some(e);
6611 break;
6612 }
6613 }
6614 }
6615 match perr {
6616 Some(e) => body_err = Some(e),
6617 None => self.task.pending_tail_call_async = Some(vals),
6618 }
6619 break;
6620 }
6621 }
6622 match self.execute_stmt(&body[idx]).await {
6623 Ok(ControlFlow::Return(val)) => {
6624 return_value = val;
6625 break;
6626 }
6627 Ok(ControlFlow::Break) => break,
6628 Ok(ControlFlow::Continue) => {}
6629 Err(e) => {
6630 body_err = Some(e);
6631 break;
6632 }
6633 }
6634 idx += 1;
6635 }
6636 if body_err.is_some() {
6637 break 'tco;
6638 }
6639 match self.task.pending_tail_call_async.take() {
6640 Some(new_args) => {
6641 self.task.env.pop_frame();
6642 self.task.env.push_frame();
6643 for (i, v) in new_args.into_iter().enumerate() {
6644 let param_name = self.ctx.functions[&function].params[i].0;
6645 self.task.env.define(param_name, v);
6646 }
6647 continue 'tco;
6648 }
6649 None => break 'tco,
6650 }
6651 }
6652 self.task.repeat_depth_async = prev_repeat;
6653 self.task.tco_fn_async = prev_tco;
6654
6655 self.task.env.pop_frame();
6656 self.task.call_depth -= 1;
6657 match body_err {
6658 Some(e) => Err(e),
6659 None => Ok(self.coerce_record_return(return_value, function)),
6660 }
6661 } else {
6662 let maybe_closure = self.task.env.lookup(function).and_then(|v| {
6663 if let RuntimeValue::Function(c) = v {
6664 Some((**c).clone())
6665 } else {
6666 None
6667 }
6668 });
6669
6670 if let Some(closure) = maybe_closure {
6671 self.call_closure_value(&closure, args).await
6672 } else {
6673 Err(format!(
6674 "Unknown function: {}",
6675 self.ctx.interner.resolve(function)
6676 ))
6677 }
6678 }
6679 }
6680
6681 fn system_native_id(
6687 &self,
6688 f: Symbol,
6689 argc: usize,
6690 ) -> Option<crate::semantics::builtins::BuiltinId> {
6691 let id = crate::semantics::builtins::system_native(self.ctx.interner.resolve(f), argc)?;
6692 self.ctx
6693 .functions
6694 .get(&f)
6695 .is_some_and(|fd| fd.is_native)
6696 .then_some(id)
6697 }
6698
6699 fn sleep_native(&self, f: Symbol, argc: usize) -> bool {
6702 argc == 1
6703 && self.ctx.interner.resolve(f) == "sleep"
6704 && self.ctx.functions.get(&f).is_some_and(|fd| fd.is_native)
6705 }
6706
6707 async fn sleep_for(&mut self, val: RuntimeValue) -> Result<(), String> {
6715 if self.yield_state.is_some() {
6716 let ticks = sleep_ticks(&val)?;
6717 if ticks > 0 {
6718 self.yield_request(BlockingRequest::Sleep(ticks)).await;
6719 }
6720 return Ok(());
6721 }
6722 let nanos = sleep_nanos(&val)?;
6723 if nanos > 0 {
6724 #[cfg(not(target_arch = "wasm32"))]
6725 {
6726 let dur = std::time::Duration::from_nanos(nanos as u64);
6727 match logicaffeine_system::tokio::runtime::Handle::try_current() {
6728 Ok(_) => logicaffeine_system::tokio::time::sleep(dur).await,
6729 Err(_) => std::thread::sleep(dur),
6730 }
6731 }
6732 #[cfg(target_arch = "wasm32")]
6733 {
6734 let millis = (nanos / 1_000_000) as u32;
6735 if millis > 0 {
6736 gloo_timers::future::TimeoutFuture::new(millis).await;
6737 }
6738 }
6739 }
6740 Ok(())
6741 }
6742
6743 fn sleep_for_sync(&mut self, val: RuntimeValue) -> Result<(), String> {
6747 let nanos = sleep_nanos(&val)?;
6748 #[cfg(not(target_arch = "wasm32"))]
6749 if nanos > 0 {
6750 std::thread::sleep(std::time::Duration::from_nanos(nanos as u64));
6751 }
6752 #[cfg(target_arch = "wasm32")]
6753 let _ = nanos;
6754 Ok(())
6755 }
6756
6757 fn native_refusal(&self, f: Symbol) -> Option<String> {
6760 let fd = self.ctx.functions.get(&f)?;
6761 fd.is_native.then(|| {
6762 crate::semantics::builtins::unimplemented_native(
6763 self.ctx.interner.resolve(f),
6764 fd.native_path.map(|p| self.ctx.interner.resolve(p)),
6765 )
6766 })
6767 }
6768
6769 fn pbkdf2_accel(&self, f: Symbol, argc: usize) -> bool {
6778 argc == 3
6779 && self.ctx.interner.resolve(f) == "pbkdf2Sha256"
6780 && crate::loader::is_library_function("pbkdf2Sha256")
6781 }
6782
6783 fn declares(&self, f: Symbol) -> bool {
6787 self.ctx
6788 .functions
6789 .get(&f)
6790 .is_some_and(|d| !d.is_native)
6791 && !self.pbkdf2_accel(f, 3)
6792 }
6793
6794 fn native_kernel(
6797 &self,
6798 f: Symbol,
6799 argc: usize,
6800 ) -> Option<crate::semantics::native_kernels::NativeKernel> {
6801 let kernel = crate::semantics::native_kernels::NativeKernel::from_name(
6802 self.ctx.interner.resolve(f),
6803 )?;
6804 (kernel.arity() == argc
6805 && self
6806 .ctx
6807 .functions
6808 .get(&f)
6809 .is_some_and(|fd| fd.is_native))
6810 .then_some(kernel)
6811 }
6812
6813 fn tcp_native_op(
6816 &self,
6817 f: Symbol,
6818 argc: usize,
6819 ) -> Option<crate::concurrency::tcp_registry::TcpOp> {
6820 let op =
6821 crate::concurrency::tcp_registry::TcpOp::from_name(self.ctx.interner.resolve(f), argc)?;
6822 self.ctx
6823 .functions
6824 .get(&f)
6825 .is_some_and(|fd| fd.is_native)
6826 .then_some(op)
6827 }
6828
6829 fn builtin_id(&self, f: Symbol) -> Option<crate::semantics::builtins::BuiltinId> {
6830 use crate::semantics::builtins::BuiltinId as B;
6831 let s = Some(f);
6832 if s == self.ctx.sym_length {
6833 Some(B::Length)
6834 } else if s == self.ctx.sym_format {
6835 Some(B::Format)
6836 } else if s == self.ctx.sym_parse_int {
6837 Some(B::ParseInt)
6838 } else if s == self.ctx.sym_parse_float {
6839 Some(B::ParseFloat)
6840 } else if s == self.ctx.sym_chr {
6841 Some(B::Chr)
6842 } else if s == self.ctx.sym_abs {
6843 Some(B::Abs)
6844 } else if s == self.ctx.sym_sqrt {
6845 Some(B::Sqrt)
6846 } else if s == self.ctx.sym_min {
6847 Some(B::Min)
6848 } else if s == self.ctx.sym_max {
6849 Some(B::Max)
6850 } else if s == self.ctx.sym_floor {
6851 Some(B::Floor)
6852 } else if s == self.ctx.sym_ceil {
6853 Some(B::Ceil)
6854 } else if s == self.ctx.sym_round {
6855 Some(B::Round)
6856 } else if s == self.ctx.sym_pow {
6857 Some(B::Pow)
6858 } else if s == self.ctx.sym_copy {
6859 Some(B::Copy)
6860 } else if s == self.ctx.sym_count_ones {
6861 Some(B::CountOnes)
6862 } else {
6863 crate::semantics::builtins::builtin_from_name(self.ctx.interner.resolve(f))
6868 }
6869 }
6870
6871 fn push_scope(&mut self) {
6874 self.task.env.push_scope();
6875 }
6876
6877 fn pop_scope(&mut self) {
6878 self.task.env.pop_scope();
6879 }
6880
6881 fn define(&mut self, name: Symbol, value: RuntimeValue) {
6882 self.task.env.define(name, value);
6883 }
6884
6885 fn assign(&mut self, name: Symbol, value: RuntimeValue) -> Result<(), String> {
6886 if self.task.env.assign(name, value) {
6887 Ok(())
6888 } else {
6889 Err(format!(
6890 "Undefined variable: {}",
6891 self.ctx.interner.resolve(name)
6892 ))
6893 }
6894 }
6895
6896 fn lookup(&self, name: Symbol) -> Result<&RuntimeValue, String> {
6897 self.task
6898 .env
6899 .lookup(name)
6900 .ok_or_else(|| format!("Undefined variable: {}", self.ctx.interner.resolve(name)))
6901 }
6902
6903 fn place_sync(&mut self, e: &Expr<'a>) -> Result<Option<Place>, String> {
6905 let Some((root, shape)) = place_shape(e) else {
6906 return Ok(None);
6907 };
6908 let mut steps = Vec::with_capacity(shape.len());
6909 for step in shape {
6910 steps.push(match step {
6911 PlaceShape::Field(f) => PlaceStep::Field(self.ctx.interner.resolve(f).to_string()),
6912 PlaceShape::Item(k) => PlaceStep::Item(self.evaluate_expr_sync(k)?),
6913 });
6914 }
6915 Ok(Some(Place { root, steps }))
6916 }
6917
6918 #[async_recursion(?Send)]
6920 async fn place(&mut self, e: &Expr<'a>) -> Result<Option<Place>, String> {
6921 let Some((root, shape)) = place_shape(e) else {
6922 return Ok(None);
6923 };
6924 let mut steps = Vec::with_capacity(shape.len());
6925 for step in shape {
6926 steps.push(match step {
6927 PlaceShape::Field(f) => PlaceStep::Field(self.ctx.interner.resolve(f).to_string()),
6928 PlaceShape::Item(k) => PlaceStep::Item(self.evaluate_expr(k).await?),
6929 });
6930 }
6931 Ok(Some(Place { root, steps }))
6932 }
6933
6934 fn place_slot(&mut self, place: &Place, own_target: bool) -> Option<&mut RuntimeValue> {
6941 let cow = crate::semantics::collections::value_semantics_enabled();
6942 let mut here = self.task.env.lookup_mut(place.root)?;
6943 for step in &place.steps {
6944 if cow {
6945 own_collection(here);
6946 }
6947 here = step_into(here, step)?;
6948 }
6949 if cow && own_target {
6950 own_collection(here);
6951 }
6952 Some(here)
6953 }
6954
6955 fn read_place(&self, place: &Place) -> Result<RuntimeValue, String> {
6958 let mut here = self.lookup(place.root)?.clone();
6959 for step in &place.steps {
6960 here = match (step, &here) {
6961 (PlaceStep::Field(name), RuntimeValue::Struct(s)) => s
6962 .fields
6963 .get(name)
6964 .cloned()
6965 .ok_or_else(|| format!("Field '{name}' not found"))?,
6966 (PlaceStep::Field(_), other) => {
6967 return Err(format!("Cannot access field on {}", other.type_name()))
6968 }
6969 (PlaceStep::Item(key), value) => {
6970 crate::semantics::collections::index_get(value, key)?
6971 }
6972 };
6973 }
6974 Ok(here)
6975 }
6976
6977 fn write_target_sync(&mut self, target: &Expr<'a>) -> Result<RuntimeValue, String> {
6982 match self.place_sync(target)? {
6983 Some(place) => match self.place_slot(&place, true) {
6984 Some(slot) => Ok(slot.clone()),
6985 None => self.read_place(&place),
6986 },
6987 None => self.evaluate_expr_sync(target),
6988 }
6989 }
6990
6991 #[async_recursion(?Send)]
6993 async fn write_target(&mut self, target: &Expr<'a>) -> Result<RuntimeValue, String> {
6994 match self.place(target).await? {
6995 Some(place) => match self.place_slot(&place, true) {
6996 Some(slot) => Ok(slot.clone()),
6997 None => self.read_place(&place),
6998 },
6999 None => self.evaluate_expr(target).await,
7000 }
7001 }
7002
7003 fn set_field_at(
7006 &mut self,
7007 place: Option<Place>,
7008 field: Symbol,
7009 value: RuntimeValue,
7010 ) -> Result<(), String> {
7011 let Some(place) = place else {
7012 return Err("SetField target must be a variable, a field or an item".to_string());
7013 };
7014 self.lookup(place.root)?;
7015 let name = self.ctx.interner.resolve(field).to_string();
7016 match self.place_slot(&place, true) {
7017 Some(RuntimeValue::Struct(s)) => {
7018 s.fields.insert(name, value);
7019 Ok(())
7020 }
7021 _ => Err("Cannot set field on non-struct value".to_string()),
7022 }
7023 }
7024
7025 fn set_item_in_place(
7032 &mut self,
7033 place: &Place,
7034 key: &RuntimeValue,
7035 value: RuntimeValue,
7036 ) -> Option<Result<(), String>> {
7037 let slot = self.place_slot(place, true)?;
7038 Some(match (slot, key) {
7039 (RuntimeValue::Struct(s), RuntimeValue::Text(field)) => {
7040 s.fields.insert(field.to_string(), value);
7041 Ok(())
7042 }
7043 (slot, _) => {
7044 let target = slot.clone();
7045 crate::semantics::collections::index_set(&target, key, value)
7046 }
7047 })
7048 }
7049
7050 fn text_appends<'e>(
7055 &self,
7056 target: Symbol,
7057 value: &'e Expr<'a>,
7058 ) -> Option<(Rc<String>, Vec<&'e Expr<'a>>)> {
7059 let Some(RuntimeValue::Text(before)) = self.task.env.lookup(target) else {
7060 return None;
7061 };
7062 let mut operands = Vec::new();
7063 let mut here = value;
7064 loop {
7065 match here {
7066 Expr::BinaryOp {
7067 op: BinaryOpKind::Add | BinaryOpKind::Concat,
7068 left,
7069 right,
7070 } => {
7071 operands.push(*right);
7072 here = left;
7073 }
7074 Expr::Identifier(sym) if *sym == target && !operands.is_empty() => break,
7075 _ => return None,
7076 }
7077 }
7078 operands.reverse();
7079 Some((before.clone(), operands))
7080 }
7081
7082 fn append_text(
7089 &mut self,
7090 target: Symbol,
7091 before: Rc<String>,
7092 pieces: Vec<String>,
7093 ) -> Result<(), String> {
7094 let slot =
7095 self.task.env.lookup_mut(target).ok_or_else(|| {
7096 format!("Undefined variable: {}", self.ctx.interner.resolve(target))
7097 })?;
7098 if let RuntimeValue::Text(held) = slot {
7099 if Rc::ptr_eq(held, &before) {
7100 drop(before);
7101 let text = Rc::make_mut(held);
7102 for piece in &pieces {
7103 text.push_str(piece);
7104 }
7105 return Ok(());
7106 }
7107 }
7108 let mut text =
7109 String::with_capacity(before.len() + pieces.iter().map(String::len).sum::<usize>());
7110 text.push_str(&before);
7111 for piece in &pieces {
7112 text.push_str(piece);
7113 }
7114 *slot = RuntimeValue::Text(Rc::new(text));
7115 Ok(())
7116 }
7117
7118 fn lend(&mut self, place: &Place) -> Option<RuntimeValue> {
7124 self.place_slot(place, false)
7125 .map(|slot| std::mem::replace(slot, RuntimeValue::Nothing))
7126 }
7127
7128 fn lent_values(
7131 &mut self,
7132 function: Symbol,
7133 lent: &[(usize, Place)],
7134 ) -> Vec<Option<RuntimeValue>> {
7135 lent.iter()
7136 .map(|(i, _)| {
7137 let param = self.ctx.functions[&function].params[*i].0;
7138 self.task.env.take_local(param)
7139 })
7140 .collect()
7141 }
7142
7143 fn values_to_give_back(
7146 &self,
7147 lent: &[(usize, Place)],
7148 arg_values: &mut [RuntimeValue],
7149 ) -> Vec<Option<RuntimeValue>> {
7150 lent.iter()
7151 .map(|(i, _)| {
7152 Some(std::mem::replace(
7153 &mut arg_values[*i],
7154 RuntimeValue::Nothing,
7155 ))
7156 })
7157 .collect()
7158 }
7159
7160 fn give_back(&mut self, lent: Vec<(usize, Place)>, values: Vec<Option<RuntimeValue>>) {
7163 for ((_, place), value) in lent.into_iter().zip(values) {
7164 if let (Some(value), Some(slot)) = (value, self.place_slot(&place, false)) {
7165 *slot = value;
7166 }
7167 }
7168 }
7169
7170 fn evaluate_policy_condition(
7172 &self,
7173 condition: &PolicyCondition,
7174 subject: &RuntimeValue,
7175 object: Option<&RuntimeValue>,
7176 ) -> bool {
7177 crate::semantics::policy::evaluate_policy_condition(
7178 self.ctx.policy_registry.as_ref(),
7179 self.ctx.interner,
7180 condition,
7181 subject,
7182 object,
7183 )
7184 }
7185
7186 pub fn global_bindings(&self) -> Vec<(String, String, String)> {
7190 let mut rows: Vec<(String, String, String)> = self
7191 .task
7192 .env
7193 .globals
7194 .iter()
7195 .map(|(sym, value)| {
7196 (
7197 self.ctx.interner.resolve(*sym).to_string(),
7198 value.type_name().to_string(),
7199 value.to_display_string(),
7200 )
7201 })
7202 .collect();
7203 rows.sort();
7204 rows
7205 }
7206
7207 pub fn run_sync(&mut self, stmts: &[Stmt<'a>]) -> Result<(), String> {
7214 self.begin_program(stmts);
7215 self.run_top_level_sync(stmts, true)
7216 }
7217
7218 fn begin_program(&mut self, stmts: &[Stmt<'a>]) {
7221 crate::semantics::world::begin_run();
7222 self.begin_engine(stmts);
7223 }
7224
7225 fn begin_engine(&mut self, stmts: &[Stmt<'a>]) {
7230 logicaffeine_base::money::clear_ambient_rates();
7231 crate::semantics::dom::retire_stream();
7232 self.preregister_definitions(stmts);
7233 self.seat_page_of(stmts);
7234 }
7235
7236 fn seat_page_of(&mut self, stmts: &[Stmt<'a>]) {
7243 if self.page_main.is_some() || !matches!(self.page, PageSeat::Here(_)) {
7244 return;
7245 }
7246 let interner = self.ctx.interner;
7247 let main = crate::page_host::page_main_len(stmts, interner);
7248 self.page_main = Some(stmts[..main].to_vec());
7249 self.page = PageSeat::Here(HostedPage::of(
7250 crate::page_host::auto_mounted_page_component(stmts, interner),
7251 ));
7252 }
7253
7254 fn run_top_level_sync(&mut self, stmts: &[Stmt<'a>], observed: bool) -> Result<(), String> {
7257 for (i, stmt) in stmts.iter().enumerate() {
7258 let flow = self.execute_stmt_sync(stmt)?;
7259 if observed {
7260 if let Some(f) = self.statement_observer.as_mut() {
7261 f(i);
7262 }
7263 }
7264 match flow {
7265 ControlFlow::Return(_) => break,
7266 ControlFlow::Break => break,
7267 ControlFlow::Continue => {}
7268 }
7269 }
7270 Ok(())
7271 }
7272
7273 pub fn run_page_main(&mut self, program: &[Stmt<'a>]) -> Result<(), String> {
7282 if self.page_main.is_some() {
7283 return Err(
7284 "tree-walker: the page's main has already run, and running it again would \
7285 re-initialize every global the page is using"
7286 .to_string(),
7287 );
7288 }
7289 self.page_main = Some(program.to_vec());
7290 self.begin_engine(program);
7291 self.run_top_level_sync(program, false)
7292 }
7293
7294 fn require_page_main(&self, what: &str) -> Result<(), String> {
7296 if self.page_main.is_some() {
7297 Ok(())
7298 } else {
7299 Err(format!(
7300 "tree-walker: cannot call {what} before the page's main has run — main registers \
7301 every function and initializes the globals every function reads"
7302 ))
7303 }
7304 }
7305
7306 fn host_call<R>(
7310 &mut self,
7311 call: impl FnOnce(&mut Self) -> Result<R, String>,
7312 ) -> Result<R, String> {
7313 let site = self.current_site;
7314 let outcome = call(self);
7315 if outcome.is_err() {
7316 self.failed_call_site = self.current_site;
7317 }
7318 self.current_site = site;
7319 outcome
7320 }
7321
7322 fn at_top_level<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
7327 let env = &mut self.task.env;
7328 let frames = std::mem::take(&mut env.frame_stack);
7329 let locals = std::mem::take(&mut env.locals);
7330 let saves = std::mem::take(&mut env.save_stack);
7331 let block = std::mem::take(&mut env.main_block);
7332 let tco = self.task.tco_fn_sync.take();
7333 let repeat = std::mem::replace(&mut self.task.repeat_depth_sync, 0);
7334 let outcome = f(self);
7335 let env = &mut self.task.env;
7336 env.frame_stack = frames;
7337 env.locals = locals;
7338 env.save_stack = saves;
7339 env.main_block = block;
7340 self.task.tco_fn_sync = tco;
7341 self.task.repeat_depth_sync = repeat;
7342 outcome
7343 }
7344
7345 fn execute_stmt_sync(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7346 self.tick_test_budget()?;
7347 if self.tiers_noop
7350 && matches!(
7351 stmt,
7352 Stmt::Expect { .. }
7353 | Stmt::ExpectFail { .. }
7354 | Stmt::ExpectOutput { .. }
7355 | Stmt::AdvanceTime { .. }
7356 | Stmt::GivenFile { .. }
7357 | Stmt::ForAll { .. }
7358 )
7359 {
7360 return Ok(ControlFlow::Continue);
7361 }
7362 match stmt {
7363 Stmt::Let { var, value, .. } => {
7364 let val = self.evaluate_expr_sync(value)?;
7365 self.define(*var, val);
7366 Ok(ControlFlow::Continue)
7367 }
7368
7369 Stmt::Set { target, value } => {
7370 if let Some((before, operands)) = self.text_appends(*target, value) {
7371 let mut pieces = Vec::with_capacity(operands.len());
7372 for operand in operands {
7373 pieces.push(self.evaluate_expr_sync(operand)?.to_display_string());
7374 }
7375 self.append_text(*target, before, pieces)?;
7376 return Ok(ControlFlow::Continue);
7377 }
7378 let val = self.evaluate_expr_sync(value)?;
7379 self.assign(*target, val)?;
7380 Ok(ControlFlow::Continue)
7381 }
7382
7383 Stmt::Swap { a, b } => {
7384 let va = self.lookup(*a)?.clone();
7386 let vb = self.lookup(*b)?.clone();
7387 self.assign(*a, vb)?;
7388 self.assign(*b, va)?;
7389 Ok(ControlFlow::Continue)
7390 }
7391
7392 Stmt::Call { function, args } => {
7393 self.call_function_sync(*function, args)?;
7394 Ok(ControlFlow::Continue)
7395 }
7396
7397 Stmt::If {
7398 cond,
7399 then_block,
7400 else_block,
7401 } => {
7402 let condition = self.evaluate_expr_sync(cond)?;
7403 if condition.decided_truth()? {
7404 let flow = self.execute_block_sync(then_block)?;
7405 if !matches!(flow, ControlFlow::Continue) {
7406 return Ok(flow);
7407 }
7408 } else if let Some(else_stmts) = else_block {
7409 let flow = self.execute_block_sync(else_stmts)?;
7410 if !matches!(flow, ControlFlow::Continue) {
7411 return Ok(flow);
7412 }
7413 }
7414 Ok(ControlFlow::Continue)
7415 }
7416
7417 Stmt::While { cond, body, .. } => {
7418 loop {
7419 let condition = self.evaluate_expr_sync(cond)?;
7420 if !condition.decided_truth()? {
7421 break;
7422 }
7423 match self.execute_block_sync(body)? {
7424 ControlFlow::Break => break,
7425 ControlFlow::Return(v) => return Ok(ControlFlow::Return(v)),
7426 ControlFlow::Continue => {}
7427 }
7428 }
7429 Ok(ControlFlow::Continue)
7430 }
7431
7432 Stmt::Repeat {
7433 pattern,
7434 iterable,
7435 body,
7436 } => self.exec_repeat(stmt),
7437
7438 Stmt::Return { value } => self.exec_return(stmt),
7439
7440 Stmt::Break => Ok(ControlFlow::Break),
7441
7442 Stmt::FunctionDef {
7443 name,
7444 params,
7445 body,
7446 return_type,
7447 is_native,
7448 native_path,
7449 ..
7450 } => {
7451 let func = FunctionDef {
7452 params: params.clone(),
7453 body: *body,
7454 return_type: *return_type,
7455 is_native: *is_native,
7456 native_path: *native_path,
7457 };
7458 self.ctx.functions.insert(*name, func);
7459 Ok(ControlFlow::Continue)
7460 }
7461
7462 Stmt::StructDef { name, fields, .. } => {
7463 self.ctx.struct_defs.insert(*name, fields.clone());
7464 Ok(ControlFlow::Continue)
7465 }
7466
7467 Stmt::SetField {
7468 object,
7469 field,
7470 value,
7471 } => {
7472 let new_val = self.evaluate_expr_sync(value)?;
7473 let place = self.place_sync(object)?;
7474 self.set_field_at(place, *field, new_val)?;
7475 Ok(ControlFlow::Continue)
7476 }
7477
7478 Stmt::Push { value, collection } => self.exec_push(stmt),
7479
7480 Stmt::Pop { collection, into } => {
7481 let coll_val = self.write_target_sync(collection)?;
7482 let popped = crate::semantics::collections::list_pop(&coll_val)?;
7483 if let Some(into_var) = into {
7484 self.define(*into_var, popped);
7485 }
7486 Ok(ControlFlow::Continue)
7487 }
7488
7489 Stmt::Add { value, collection } => {
7492 let val = self.evaluate_expr_sync(value)?;
7493 let coll_val = self.write_target_sync(collection)?;
7494 crate::semantics::collections::set_add(&coll_val, val)?;
7495 Ok(ControlFlow::Continue)
7496 }
7497
7498 Stmt::Remove { value, collection } => {
7499 let val = self.evaluate_expr_sync(value)?;
7500 let coll_val = self.write_target_sync(collection)?;
7501 crate::semantics::collections::remove_from(&coll_val, &val)?;
7502 Ok(ControlFlow::Continue)
7503 }
7504
7505 Stmt::SetIndex {
7506 collection,
7507 index,
7508 value,
7509 } => self.exec_set_index(stmt),
7510
7511 Stmt::ComponentDef(def)
7519 if matches!(
7520 def.kind,
7521 crate::ast::component::ComponentKind::ErrorPage { .. }
7522 ) =>
7523 {
7524 {
7525 let heading = logicaffeine_language::parser::lgx_lower::construct_heading(
7529 def,
7530 self.ctx.interner,
7531 );
7532 match def.view.as_ref() {
7533 Some(v) => match logicaffeine_language::parser::lgx_lower::view_html_lowerable(
7534 &v.nodes,
7535 self.ctx.interner,
7536 ) {
7537 Ok(()) => Ok(ControlFlow::Continue),
7538 Err(why) => Err(format!(
7539 "`{heading}` cannot be rendered on this tier yet: {}.",
7540 why.message
7541 )),
7542 },
7543 None => Err(format!(
7544 "`{heading}` cannot be rendered on this tier yet: it has no `View:` to render."
7545 )),
7546 }
7547 }
7548 }
7549 Stmt::ComponentDef(_) | Stmt::DirectiveDef { .. } => Ok(ControlFlow::Continue),
7550 Stmt::Ui(ui) => self.execute_ui(ui),
7551 Stmt::RouteDef {
7557 method,
7558 path,
7559 params,
7560 return_type,
7561 body,
7562 span,
7563 } => {
7564 match logicaffeine_language::parser::lgx_lower::route_lowerable(
7565 params,
7566 *return_type,
7567 body,
7568 self.ctx.interner,
7569 &|sym| self.ctx.struct_defs.contains_key(&sym),
7570 &self.ctx.components.values().cloned().collect::<Vec<_>>(),
7574 *span,
7575 ) {
7576 Ok(()) => Ok(ControlFlow::Continue),
7577 Err(why) => Err(format!(
7578 "`{}` cannot run on this tier yet: {}.",
7579 logicaffeine_language::parser::lgx_lower::route_heading(
7580 *method,
7581 *path,
7582 self.ctx.interner
7583 ),
7584 why.message
7585 )),
7586 }
7587 }
7588 Stmt::MiddlewareDef { .. } => Ok(ControlFlow::Continue),
7592 Stmt::RedirectDef { .. } => Ok(ControlFlow::Continue),
7594 Stmt::Replay { actions } => {
7595 self.replay_actions(actions)?;
7596 Ok(ControlFlow::Continue)
7597 }
7598 Stmt::ServeFetches => self.serve_fetches_sync(),
7599 Stmt::GivenFetch {
7600 method,
7601 url,
7602 status,
7603 body,
7604 } => self.given_fetch_sync(*method, url, status, body),
7605 Stmt::Fetch { .. } => Err(
7606 "A request that answers into an action (`Get … then loaded`) is sent by a \
7607 component's own `Actions:`, whose page completes it."
7608 .to_string(),
7609 ),
7610 Stmt::Splice { body } => {
7611 for s in body.iter() {
7613 let flow = self.execute_stmt_sync(s)?;
7614 if !matches!(flow, ControlFlow::Continue) {
7615 return Ok(flow);
7616 }
7617 }
7618 Ok(ControlFlow::Continue)
7619 }
7620
7621 Stmt::Reversibly { body } => {
7622 for s in body.iter() {
7624 let flow = self.execute_stmt_sync(s)?;
7625 if !matches!(flow, ControlFlow::Continue) {
7626 return Ok(flow);
7627 }
7628 }
7629 Ok(ControlFlow::Continue)
7630 }
7631
7632 Stmt::Inspect { target, arms, .. } => {
7633 let target_val = self.evaluate_expr_sync(target)?;
7634 self.execute_inspect_sync(&target_val, arms)
7635 }
7636
7637 Stmt::Zone { name, body, .. } => {
7638 self.push_scope();
7639 self.define(*name, RuntimeValue::Nothing);
7640 let result = self.execute_block_sync(body);
7641 self.pop_scope();
7642 result?;
7643 Ok(ControlFlow::Continue)
7644 }
7645
7646 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
7647 for task in tasks.iter() {
7648 self.execute_stmt_sync(task)?;
7649 }
7650 Ok(ControlFlow::Continue)
7651 }
7652
7653 Stmt::Assert { .. } | Stmt::Trust { .. } => Ok(ControlFlow::Continue),
7654
7655 Stmt::TestDef { .. } => Ok(ControlFlow::Continue),
7658
7659 Stmt::Expect { condition } => self.exec_expect(stmt),
7662 Stmt::ExpectFail { message, body } => self.exec_expect_fail(stmt),
7663 Stmt::ExpectOutput { expected } => self.exec_expect_output(stmt),
7664 Stmt::AdvanceTime { millis } => {
7665 if !self.test_mode {
7666 return Err(TEST_ONLY_STMT_ERR.to_string());
7667 }
7668 let ms = match self.evaluate_expr_sync(millis)? {
7669 RuntimeValue::Int(n) => n.max(0) as u64,
7670 RuntimeValue::Duration(ns) => (ns.max(0) / 1_000_000) as u64,
7672 other => {
7673 return Err(format!(
7674 "Advance time needs a duration in milliseconds, got {}",
7675 other.type_name()
7676 ))
7677 }
7678 };
7679 self.advance_time_ms(ms)
7680 }
7681 Stmt::GivenFile { path, content } => {
7682 if !self.test_mode {
7683 return Err(TEST_ONLY_STMT_ERR.to_string());
7684 }
7685 logicaffeine_system::testworld::seed_file(
7686 self.ctx.interner.resolve(*path).to_string(),
7687 self.ctx.interner.resolve(*content).to_string(),
7688 );
7689 Ok(ControlFlow::Continue)
7690 }
7691
7692 Stmt::Observe {
7695 category,
7696 message,
7697 payloads,
7698 sample,
7699 } => self.exec_observe(stmt),
7700 Stmt::During { label, body } => self.exec_during(stmt),
7701 Stmt::ForAll {
7702 vars,
7703 domain,
7704 constraint,
7705 body,
7706 } => {
7707 if !self.test_mode {
7708 return Err(TEST_ONLY_STMT_ERR.to_string());
7709 }
7710 self.run_property(vars, *domain, *constraint, body)?;
7711 Ok(ControlFlow::Continue)
7712 }
7713
7714 Stmt::RuntimeAssert {
7715 condition, reason, ..
7716 } => {
7717 let val = self.evaluate_expr_sync(condition)?;
7718 if !val.decided_truth()? {
7719 return Err(match reason {
7720 Some(r) => crate::semantics::builtins::contract_reason_text(
7721 self.evaluate_expr_sync(r)?,
7722 )?,
7723 None => "Assertion failed".to_string(),
7724 });
7725 }
7726 Ok(ControlFlow::Continue)
7727 }
7728
7729 Stmt::Fail { reason } => Err(self.evaluate_expr_sync(reason)?.to_display_string()),
7730
7731 Stmt::Give { object, recipient } => {
7732 let obj_val = self.evaluate_expr_sync(object)?;
7733 if let Expr::Identifier(sym) = recipient {
7734 self.call_function_with_values_sync(*sym, vec![obj_val])?;
7735 }
7736 Ok(ControlFlow::Continue)
7737 }
7738
7739 Stmt::Show { object, recipient } => {
7740 let obj_val = self.evaluate_expr_sync(object)?;
7741 if let Expr::Identifier(sym) = recipient {
7742 let name = self.ctx.interner.resolve(*sym);
7743 if name == "show" {
7744 self.emit_output(obj_val.to_display_string());
7745 } else {
7746 self.call_function_with_values_sync(*sym, vec![obj_val])?;
7747 }
7748 }
7749 Ok(ControlFlow::Continue)
7750 }
7751
7752 Stmt::ReadFrom { var, source } => match source {
7754 ReadSource::Console => {
7755 self.define(*var, RuntimeValue::Text(Rc::new(String::new())));
7756 Ok(ControlFlow::Continue)
7757 }
7758 ReadSource::File(_) => Err("File read requires async execution path".to_string()),
7759 },
7760
7761 Stmt::WriteFile { .. } => Err("File write requires async execution path".to_string()),
7762
7763 Stmt::Spawn { name, .. } => {
7764 self.define(*name, RuntimeValue::Nothing);
7765 Ok(ControlFlow::Continue)
7766 }
7767
7768 Stmt::SendMessage { .. } => {
7769 Err("Send (peer messaging) requires the async execution path".to_string())
7770 }
7771 Stmt::StreamMessage { .. } => {
7772 Err("Stream (batch peer messaging) requires the async execution path".to_string())
7773 }
7774
7775 Stmt::AwaitMessage { .. } => {
7776 Err("Await (peer messaging) requires the async execution path".to_string())
7777 }
7778
7779 Stmt::MergeCrdt { source, target } => self.exec_merge_crdt(stmt),
7780
7781 Stmt::JoinCrdt { source, target } => self.exec_join_crdt(stmt),
7784
7785 Stmt::IncreaseCrdt {
7786 object,
7787 field,
7788 amount,
7789 } => self.exec_increase_crdt(stmt),
7790
7791 Stmt::DecreaseCrdt {
7792 object,
7793 field,
7794 amount,
7795 } => self.exec_decrease_crdt(stmt),
7796
7797 Stmt::AppendToSequence { sequence, value } => {
7798 let val = self.evaluate_expr_sync(value)?;
7799 let seq_val = self.evaluate_expr_sync(sequence)?;
7800 match &seq_val {
7801 RuntimeValue::Crdt(rc) => rc.borrow_mut().append(&val)?,
7802 RuntimeValue::List(_) => {
7803 crate::semantics::collections::list_push(&seq_val, val)?
7804 }
7805 _ => return Err(format!("Cannot append to {}", seq_val.type_name())),
7806 }
7807 Ok(ControlFlow::Continue)
7808 }
7809
7810 Stmt::ResolveConflict {
7811 object,
7812 field,
7813 value,
7814 } => self.exec_resolve_conflict(stmt),
7815
7816 Stmt::Check { .. } => self.exec_check(stmt),
7817
7818 Stmt::Listen { .. } | Stmt::ConnectTo { .. } => {
7819 Err("Networking (Connect/Listen) requires the async execution path".to_string())
7820 }
7821 Stmt::Serve { .. } => {
7822 Err("`Serve` (HTTP server) requires the async execution path".to_string())
7823 }
7824 Stmt::LetPeerAgent { var, address } => {
7827 let raw = self.evaluate_expr_sync(address)?.to_display_string();
7828 let topic = logicaffeine_system::addr::canonical_topic(&raw);
7829 self.define(*var, RuntimeValue::Peer(Rc::new(topic)));
7830 Ok(ControlFlow::Continue)
7831 }
7832 Stmt::Sleep { .. } => Err("Sleep requires async execution path".to_string()),
7833 Stmt::Sync { .. } => Err("Sync requires the async execution path".to_string()),
7834 Stmt::Mount { .. } => Err("Mount requires async execution path".to_string()),
7835
7836 Stmt::LaunchTask { .. }
7837 | Stmt::LaunchTaskWithHandle { .. }
7838 | Stmt::CreatePipe { .. }
7839 | Stmt::SendPipe { .. }
7840 | Stmt::ReceivePipe { .. }
7841 | Stmt::TrySendPipe { .. }
7842 | Stmt::TryReceivePipe { .. }
7843 | Stmt::StopTask { .. }
7844 | Stmt::CloseChannel { .. }
7845 | Stmt::AwaitTask { .. }
7846 | Stmt::Select { .. } => Err(
7847 "Go-like concurrency (Launch, Pipe, Select) is only supported in compiled mode"
7848 .to_string(),
7849 ),
7850
7851 Stmt::Escape { .. } => Err(crate::semantics::escape::REFUSAL.to_string()),
7852
7853 Stmt::Require { .. } => Ok(ControlFlow::Continue),
7854
7855 Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {
7856 Ok(ControlFlow::Continue)
7857 }
7858
7859 Stmt::Site(id) => {
7862 self.current_site = Some(*id);
7863 Ok(ControlFlow::Continue)
7864 }
7865 }
7866 }
7867
7868 #[inline(never)]
7872 fn exec_check(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7873 let Stmt::Check {
7874 subject,
7875 predicate,
7876 is_capability,
7877 object,
7878 source_text,
7879 ..
7880 } = stmt
7881 else {
7882 unreachable!()
7883 };
7884 let registry = match &self.ctx.policy_registry {
7885 Some(r) => r,
7886 None => return Err(crate::semantics::policy::NO_POLICIES.to_string()),
7887 };
7888
7889 let subj_val = self.lookup(*subject)?.clone();
7890 let obj_val = if *is_capability {
7893 match object {
7894 Some(obj_sym) => Some(self.lookup(*obj_sym)?.clone()),
7895 None => None,
7896 }
7897 } else {
7898 None
7899 };
7900 crate::semantics::policy::check_policy(
7901 registry,
7902 self.ctx.interner,
7903 &subj_val,
7904 *predicate,
7905 *is_capability,
7906 obj_val.as_ref(),
7907 source_text,
7908 )?;
7909 Ok(ControlFlow::Continue)
7910 }
7911
7912 #[inline(never)]
7916 fn exec_resolve_conflict(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7917 let Stmt::ResolveConflict {
7918 object,
7919 field,
7920 value,
7921 } = stmt
7922 else {
7923 unreachable!()
7924 };
7925 let val = self.evaluate_expr_sync(value)?;
7926 let obj_val = self.evaluate_expr_sync(object)?;
7927 let field_name = self.ctx.interner.resolve(*field);
7928 if let RuntimeValue::Struct(s) = &obj_val {
7929 if let Some(RuntimeValue::Crdt(rc)) = s.fields.get(field_name) {
7930 rc.borrow_mut().resolve(&val)?;
7931 return Ok(ControlFlow::Continue);
7932 }
7933 }
7934 if let Expr::Identifier(obj_sym) = object {
7935 let mut owner = self.lookup(*obj_sym)?.clone();
7936 if let RuntimeValue::Struct(ref mut s) = owner {
7937 s.fields.insert(field_name.to_string(), val);
7938 self.assign(*obj_sym, owner)?;
7939 return Ok(ControlFlow::Continue);
7940 }
7941 }
7942 Err("Resolve target must be a struct field".to_string())
7943 }
7944
7945 #[inline(never)]
7949 fn exec_decrease_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7950 let Stmt::DecreaseCrdt {
7951 object,
7952 field,
7953 amount,
7954 } = stmt
7955 else {
7956 unreachable!()
7957 };
7958 let amount_val = self.evaluate_expr_sync(amount)?;
7959 let amount_int = match amount_val {
7960 RuntimeValue::Int(n) => n,
7961 _ => return Err("CRDT decrement amount must be an integer".to_string()),
7962 };
7963
7964 if let Expr::Identifier(obj_sym) = object {
7965 let mut obj_val = self.lookup(*obj_sym)?.clone();
7966
7967 if let RuntimeValue::Struct(ref mut s) = obj_val {
7968 let field_name = self.ctx.interner.resolve(*field).to_string();
7969 let current = s
7970 .fields
7971 .get(&field_name)
7972 .cloned()
7973 .unwrap_or(RuntimeValue::Int(0));
7974
7975 let new_val = crate::semantics::arith::crdt_counter_bump(
7976 current,
7977 amount_int.wrapping_neg(),
7978 &field_name,
7979 )?;
7980 s.fields.insert(field_name, new_val);
7981 self.assign(*obj_sym, obj_val)?;
7982 } else {
7983 return Err("Cannot decrease field on non-struct value".to_string());
7984 }
7985 } else {
7986 return Err("DecreaseCrdt target must be an identifier".to_string());
7987 }
7988 Ok(ControlFlow::Continue)
7989 }
7990
7991 #[inline(never)]
7995 fn exec_increase_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
7996 let Stmt::IncreaseCrdt {
7997 object,
7998 field,
7999 amount,
8000 } = stmt
8001 else {
8002 unreachable!()
8003 };
8004 let amount_val = self.evaluate_expr_sync(amount)?;
8005 let amount_int = match amount_val {
8006 RuntimeValue::Int(n) => n,
8007 _ => return Err("CRDT increment amount must be an integer".to_string()),
8008 };
8009
8010 if let Expr::Identifier(obj_sym) = object {
8011 let mut obj_val = self.lookup(*obj_sym)?.clone();
8012
8013 if let RuntimeValue::Struct(ref mut s) = obj_val {
8014 let field_name = self.ctx.interner.resolve(*field).to_string();
8015 let current = s
8016 .fields
8017 .get(&field_name)
8018 .cloned()
8019 .unwrap_or(RuntimeValue::Int(0));
8020
8021 let new_val =
8022 crate::semantics::arith::crdt_counter_bump(current, amount_int, &field_name)?;
8023 s.fields.insert(field_name, new_val);
8024 self.assign(*obj_sym, obj_val)?;
8025 } else {
8026 return Err("Cannot increase field on non-struct value".to_string());
8027 }
8028 } else {
8029 return Err("IncreaseCrdt target must be an identifier".to_string());
8030 }
8031 Ok(ControlFlow::Continue)
8032 }
8033
8034 #[inline(never)]
8038 fn exec_join_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8039 let Stmt::JoinCrdt { source, target } = stmt else {
8040 unreachable!()
8041 };
8042 let source_val = self.evaluate_expr_sync(source)?;
8043 let source_fields = match &source_val {
8044 RuntimeValue::Struct(s) => s.fields.clone(),
8045 _ => return Err("Converge source must be a struct".to_string()),
8046 };
8047
8048 if let Expr::Identifier(target_sym) = target {
8049 let mut target_val = self.lookup(*target_sym)?.clone();
8050
8051 if let RuntimeValue::Struct(ref mut s) = target_val {
8052 for (field_name, source_field_val) in source_fields {
8053 let current = s
8054 .fields
8055 .get(&field_name)
8056 .cloned()
8057 .unwrap_or(RuntimeValue::Int(0));
8058
8059 let joined =
8060 crate::semantics::arith::crdt_join_field(¤t, source_field_val);
8061 s.fields.insert(field_name, joined);
8062 }
8063 self.assign(*target_sym, target_val)?;
8064 } else {
8065 return Err("Converge target must be a struct".to_string());
8066 }
8067 } else {
8068 return Err("Converge target must be an identifier".to_string());
8069 }
8070 Ok(ControlFlow::Continue)
8071 }
8072
8073 #[inline(never)]
8077 fn exec_merge_crdt(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8078 let Stmt::MergeCrdt { source, target } = stmt else {
8079 unreachable!()
8080 };
8081 let source_val = self.evaluate_expr_sync(source)?;
8082 let source_fields = match &source_val {
8083 RuntimeValue::Struct(s) => s.fields.clone(),
8084 _ => return Err("Merge source must be a struct".to_string()),
8085 };
8086
8087 if let Expr::Identifier(target_sym) = target {
8088 let mut target_val = self.lookup(*target_sym)?.clone();
8089
8090 if let RuntimeValue::Struct(ref mut s) = target_val {
8091 for (field_name, source_field_val) in source_fields {
8092 let current = s
8093 .fields
8094 .get(&field_name)
8095 .cloned()
8096 .unwrap_or(RuntimeValue::Int(0));
8097
8098 let merged =
8099 crate::semantics::arith::crdt_merge_field(¤t, source_field_val);
8100 s.fields.insert(field_name, merged);
8101 }
8102 self.assign(*target_sym, target_val)?;
8103 } else {
8104 return Err("Merge target must be a struct".to_string());
8105 }
8106 } else {
8107 return Err("Merge target must be an identifier".to_string());
8108 }
8109 Ok(ControlFlow::Continue)
8110 }
8111
8112 #[inline(never)]
8116 fn exec_during(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8117 let Stmt::During { label, body } = stmt else {
8118 unreachable!()
8119 };
8120 let cap = crate::observe::capturing();
8122 let name = if cap {
8123 self.ctx.interner.resolve(*label).to_string()
8124 } else {
8125 String::new()
8126 };
8127 if cap {
8128 crate::observe::enter_span(name.clone());
8129 }
8130 let mut result: Result<ControlFlow, String> = Ok(ControlFlow::Continue);
8131 for s in body.iter() {
8132 match self.execute_stmt_sync(s) {
8133 Ok(ControlFlow::Continue) => {}
8134 Ok(flow) => {
8135 result = Ok(flow);
8136 break;
8137 }
8138 Err(e) => {
8139 result = Err(e);
8140 break;
8141 }
8142 }
8143 }
8144 if cap {
8145 crate::observe::exit_span(name);
8146 }
8147 result
8148 }
8149
8150 #[inline(never)]
8154 fn exec_observe(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8155 let Stmt::Observe {
8156 category,
8157 message,
8158 payloads,
8159 sample,
8160 } = stmt
8161 else {
8162 unreachable!()
8163 };
8164 if crate::observe::capturing() {
8165 let mut vals: Vec<(String, String)> = Vec::with_capacity(payloads.len());
8166 for (name, expr) in payloads.iter() {
8167 let v = self.evaluate_expr_sync(expr)?;
8168 vals.push((
8169 self.ctx.interner.resolve(*name).to_string(),
8170 v.to_display_string(),
8171 ));
8172 }
8173 crate::observe::emit(
8174 map_obs_category(*category),
8175 self.ctx.interner.resolve(*message).to_string(),
8176 vals,
8177 *sample,
8178 message.index() as u64,
8179 );
8180 }
8181 Ok(ControlFlow::Continue)
8182 }
8183
8184 #[inline(never)]
8188 fn exec_expect_output(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8189 let Stmt::ExpectOutput { expected } = stmt else {
8190 unreachable!()
8191 };
8192 if !self.test_mode {
8193 return Err(TEST_ONLY_STMT_ERR.to_string());
8194 }
8195 self.test_assertions += 1;
8196 match expected {
8197 ExpectedOutput::Inline(sym) => {
8198 let expected_text = self.ctx.interner.resolve(*sym).to_string();
8199 let actual = self.output.join("\n");
8200 if actual != expected_text {
8201 self.test_failures.push(format!(
8202 "Expected output {expected_text:?} — but the test printed {actual:?}."
8203 ));
8204 }
8205 }
8206 ExpectedOutput::File(path) => {
8207 self.test_failures.push(format!(
8208 "Expected output as in {:?} — golden files land with the sealed world (Wave 4).",
8209 self.ctx.interner.resolve(*path)
8210 ));
8211 }
8212 }
8213 Ok(ControlFlow::Continue)
8214 }
8215
8216 #[inline(never)]
8220 fn exec_expect_fail(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8221 let Stmt::ExpectFail { message, body } = stmt else {
8222 unreachable!()
8223 };
8224 if !self.test_mode {
8225 return Err(TEST_ONLY_STMT_ERR.to_string());
8226 }
8227 self.test_assertions += 1;
8228 let mut failure: Option<String> = None;
8229 for s in body.iter() {
8230 if let Err(e) = self.execute_stmt_sync(s) {
8231 failure = Some(e);
8232 break;
8233 }
8234 }
8235 match failure {
8236 None => self
8237 .test_failures
8238 .push("Expected this to fail — but the block succeeded.".to_string()),
8239 Some(actual) => {
8240 if let Some(expected) = message {
8241 let expected = self.ctx.interner.resolve(*expected);
8242 if actual != expected {
8243 self.test_failures.push(format!(
8244 "Expected this to fail with {expected:?} — but it failed with {actual:?}."
8245 ));
8246 }
8247 }
8248 }
8249 }
8250 Ok(ControlFlow::Continue)
8251 }
8252
8253 #[inline(never)]
8257 fn exec_expect(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8258 let Stmt::Expect { condition } = stmt else {
8259 unreachable!()
8260 };
8261 if !self.test_mode {
8262 return Err(TEST_ONLY_STMT_ERR.to_string());
8263 }
8264 self.test_assertions += 1;
8265 let val = self.evaluate_expr_sync(condition)?;
8266 if !val.decided_truth()? {
8267 let cond_text =
8268 logicaffeine_language::printer::render_expr(condition, self.ctx.interner);
8269 let mut subs = Vec::new();
8270 logicaffeine_language::printer::subexpressions(condition, &mut subs);
8271 let mut annotations: Vec<(String, String)> = Vec::new();
8272 let mut seen = std::collections::HashSet::new();
8273 for sub in subs {
8274 let text = logicaffeine_language::printer::render_expr(sub, self.ctx.interner);
8275 if !seen.insert(text.clone()) {
8276 continue;
8277 }
8278 if let Ok(v) = self.evaluate_expr_sync(sub) {
8279 annotations.push((text, v.to_display_string()));
8280 }
8281 }
8282 let hint = Self::expect_socratic_hint(condition);
8283 self.test_failures
8284 .push(format_expect_failure(&cond_text, &annotations, hint));
8285 }
8286 Ok(ControlFlow::Continue)
8287 }
8288
8289 #[inline(never)]
8293 fn exec_set_index(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8294 let Stmt::SetIndex {
8295 collection,
8296 index,
8297 value,
8298 } = stmt
8299 else {
8300 unreachable!()
8301 };
8302 let idx_val = self.evaluate_expr_sync(index)?;
8303 let new_val = self.evaluate_expr_sync(value)?;
8304 let target = match self.place_sync(collection)? {
8305 Some(place) => match self.set_item_in_place(&place, &idx_val, new_val.clone()) {
8306 Some(done) => {
8307 done?;
8308 return Ok(ControlFlow::Continue);
8309 }
8310 None => self.read_place(&place)?,
8311 },
8312 None => self.evaluate_expr_sync(collection)?,
8313 };
8314 crate::semantics::collections::index_set(&target, &idx_val, new_val)?;
8315 Ok(ControlFlow::Continue)
8316 }
8317
8318 #[inline(never)]
8322 fn exec_push(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8323 let Stmt::Push { value, collection } = stmt else {
8324 unreachable!()
8325 };
8326 let val = self.evaluate_expr_sync(value)?;
8327 if let Expr::FieldAccess {
8328 object: Expr::Identifier(obj_sym),
8329 field,
8330 } = collection
8331 {
8332 if let Some(place) = self.place_sync(collection)? {
8333 self.place_slot(&place, true);
8334 }
8335 let obj_val = self.lookup(*obj_sym)?;
8336 let field_name = self.ctx.interner.resolve(*field);
8337 crate::semantics::collections::push_to_struct_field(obj_val, field_name, val)?;
8338 } else {
8339 let coll_val = self.write_target_sync(collection)?;
8340 crate::semantics::collections::list_push(&coll_val, val)?;
8341 }
8342 Ok(ControlFlow::Continue)
8343 }
8344
8345 #[inline(never)]
8349 fn exec_return(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8350 let Stmt::Return { value } = stmt else {
8351 unreachable!()
8352 };
8353 if let Some(expr) = value {
8359 if let Some(call_args) = self.self_tail_call_args_sync(*expr) {
8360 let mut vals = Vec::with_capacity(call_args.len());
8361 for a in call_args {
8362 vals.push(self.evaluate_expr_sync(a)?);
8363 }
8364 self.task.pending_tail_call = Some(vals);
8365 return Ok(ControlFlow::Return(RuntimeValue::Nothing));
8366 }
8367 }
8368 let ret_val = match value {
8369 Some(expr) => self.evaluate_expr_sync(expr)?,
8370 None => RuntimeValue::Nothing,
8371 };
8372 Ok(ControlFlow::Return(ret_val))
8373 }
8374
8375 #[inline(never)]
8379 fn exec_repeat(&mut self, stmt: &Stmt<'a>) -> Result<ControlFlow, String> {
8380 let Stmt::Repeat {
8381 pattern,
8382 iterable,
8383 body,
8384 } = stmt
8385 else {
8386 unreachable!()
8387 };
8388 use crate::ast::stmt::Pattern;
8389
8390 let iter_val = self.evaluate_expr_sync(iterable)?;
8391 let items = crate::semantics::collections::iteration_snapshot(&iter_val)?;
8392
8393 self.push_scope();
8394 self.task.repeat_depth_sync += 1;
8398 for item in items {
8399 match pattern {
8400 Pattern::Identifier(sym) => {
8401 self.define(*sym, item);
8402 }
8403 Pattern::Tuple(syms) => {
8404 if let RuntimeValue::Tuple(ref tuple_vals) = item {
8405 if syms.len() != tuple_vals.len() {
8406 self.task.repeat_depth_sync -= 1;
8407 return Err(format!(
8408 "Cannot bind a {}-tuple to {} names",
8409 tuple_vals.len(),
8410 syms.len()
8411 ));
8412 }
8413 for (sym, val) in syms.iter().zip(tuple_vals.iter()) {
8414 self.define(*sym, val.clone());
8415 }
8416 } else {
8417 self.task.repeat_depth_sync -= 1;
8418 return Err(format!(
8419 "Expected tuple for pattern, got {}",
8420 item.type_name()
8421 ));
8422 }
8423 }
8424 }
8425
8426 match self.execute_block_sync(body)? {
8427 ControlFlow::Break => break,
8428 ControlFlow::Return(v) => {
8429 self.task.repeat_depth_sync -= 1;
8430 self.pop_scope();
8431 return Ok(ControlFlow::Return(v));
8432 }
8433 ControlFlow::Continue => {}
8434 }
8435 }
8436 self.task.repeat_depth_sync -= 1;
8437 self.pop_scope();
8438 Ok(ControlFlow::Continue)
8439 }
8440
8441 fn execute_block_sync(&mut self, block: Block<'a>) -> Result<ControlFlow, String> {
8442 self.push_scope();
8443 for stmt in block.iter() {
8444 match self.execute_stmt_sync(stmt)? {
8445 ControlFlow::Continue => {}
8446 flow => {
8447 self.pop_scope();
8448 return Ok(flow);
8449 }
8450 }
8451 }
8452 self.pop_scope();
8453 Ok(ControlFlow::Continue)
8454 }
8455
8456 fn execute_inspect_sync(
8457 &mut self,
8458 target: &RuntimeValue,
8459 arms: &[MatchArm<'a>],
8460 ) -> Result<ControlFlow, String> {
8461 for arm in arms {
8462 if arm.variant.is_none() {
8463 let flow = self.execute_block_sync(arm.body)?;
8464 return Ok(flow);
8465 }
8466
8467 match target {
8468 RuntimeValue::Struct(s) => {
8469 if let Some(variant) = arm.variant {
8470 let variant_name = self.ctx.interner.resolve(variant);
8471 if s.type_name == variant_name {
8472 self.push_scope();
8473 for (field_name, binding_name) in &arm.bindings {
8474 let field_str = self.ctx.interner.resolve(*field_name);
8475 if let Some(val) = s.fields.get(field_str) {
8476 self.define(*binding_name, val.clone());
8477 }
8478 }
8479 let result = self.execute_block_sync(arm.body);
8480 self.pop_scope();
8481 let flow = result?;
8482 return Ok(flow);
8483 }
8484 }
8500 }
8501
8502 RuntimeValue::Inductive(ind) => {
8503 if let Some(variant) = arm.variant {
8504 let variant_name = self.ctx.interner.resolve(variant);
8505 if ind.constructor == variant_name {
8506 self.push_scope();
8507 for (i, (_, binding_name)) in arm.bindings.iter().enumerate() {
8508 if i < ind.args.len() {
8509 self.define(*binding_name, ind.args[i].clone());
8510 }
8511 }
8512 let result = self.execute_block_sync(arm.body);
8513 self.pop_scope();
8514 let flow = result?;
8515 return Ok(flow);
8516 }
8517 }
8518 }
8519
8520 RuntimeValue::Nothing => {
8525 if let Some(variant) = arm.variant {
8526 if self.ctx.interner.resolve(variant) == "None" {
8527 let flow = self.execute_block_sync(arm.body)?;
8528 return Ok(flow);
8529 }
8530 }
8531 }
8532
8533 _ => {}
8535 }
8536 }
8537 Err(self.inspect_unhandled(target))
8538 }
8539
8540 fn evaluate_expr_sync(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8541 match expr {
8542 Expr::View(_) => Err(
8543 "A view is drawn by the component it belongs to — place it in that component's `View:`."
8544 .to_string(),
8545 ),
8546 Expr::Dom(q) => self.evaluate_dom_query(q),
8547 Expr::Literal(lit) => self.evaluate_literal(lit),
8548
8549 Expr::Identifier(sym) => {
8550 let name = self.ctx.interner.resolve(*sym);
8551 match name {
8553 "today" => {
8554 return Ok(crate::semantics::temporal::today());
8555 }
8556 "now" => {
8557 return Ok(crate::semantics::temporal::now());
8558 }
8559 _ => {}
8560 }
8561 self.lookup(*sym).cloned()
8562 }
8563
8564 Expr::BinaryOp { op, left, right } => self.eval_binary_op(expr),
8565
8566 Expr::Call { function, args } => {
8567 self.call_function_sync(*function, args)
8568 }
8569
8570 Expr::Index { collection, index } => {
8571 let coll_val = self.evaluate_expr_sync(collection)?;
8572 let idx_val = self.evaluate_expr_sync(index)?;
8573 crate::semantics::collections::index_get(&coll_val, &idx_val)
8574 }
8575
8576 Expr::Slice { collection, start, end } => {
8577 let coll_val = self.evaluate_expr_sync(collection)?;
8578 let start_val = self.evaluate_expr_sync(start)?;
8579 let end_val = self.evaluate_expr_sync(end)?;
8580 crate::semantics::collections::slice(&coll_val, &start_val, &end_val)
8581 }
8582
8583 Expr::Copy { expr: inner } => {
8584 let val = self.evaluate_expr_sync(inner)?;
8585 Ok(val.deep_clone())
8586 }
8587
8588 Expr::Give { value } => {
8589 self.evaluate_expr_sync(value)
8590 }
8591
8592 Expr::Length { collection } => {
8593 let coll_val = self.evaluate_expr_sync(collection)?;
8594 crate::semantics::collections::length_of(&coll_val)
8595 }
8596
8597 Expr::Contains { collection, value } => {
8598 let coll_val = self.evaluate_expr_sync(collection)?;
8599 let val = self.evaluate_expr_sync(value)?;
8600 crate::semantics::collections::contains(&coll_val, &val)
8601 }
8602
8603 Expr::Union { left, right } => {
8604 let left_val = self.evaluate_expr_sync(left)?;
8605 let right_val = self.evaluate_expr_sync(right)?;
8606 crate::semantics::collections::union(&left_val, &right_val)
8607 }
8608
8609 Expr::Intersection { left, right } => {
8610 let left_val = self.evaluate_expr_sync(left)?;
8611 let right_val = self.evaluate_expr_sync(right)?;
8612 crate::semantics::collections::intersection(&left_val, &right_val)
8613 }
8614
8615 Expr::List(items) => {
8616 let mut values = Vec::with_capacity(items.len());
8617 for e in items.iter() {
8618 values.push(self.evaluate_expr_sync(e)?);
8619 }
8620 Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(values)))))
8621 }
8622
8623 Expr::Tuple(items) => {
8624 let mut values = Vec::with_capacity(items.len());
8625 for e in items.iter() {
8626 values.push(self.evaluate_expr_sync(e)?);
8627 }
8628 Ok(RuntimeValue::Tuple(Rc::new(values)))
8629 }
8630
8631 Expr::Range { start, end } => {
8632 let start_val = self.evaluate_expr_sync(start)?;
8633 let end_val = self.evaluate_expr_sync(end)?;
8634 crate::semantics::collections::range(&start_val, &end_val)
8635 }
8636
8637 Expr::FieldAccess { object, field } => {
8638 let obj_val = self.evaluate_expr_sync(object)?;
8639 match &obj_val {
8640 RuntimeValue::Struct(s) => {
8641 let field_name = self.ctx.interner.resolve(*field);
8642 s.fields.get(field_name).cloned()
8643 .ok_or_else(|| format!("Field '{}' not found", field_name))
8644 }
8645 _ => Err(format!("Cannot access field on {}", obj_val.type_name())),
8646 }
8647 }
8648
8649 Expr::New { type_name, init_fields, .. } => self.eval_new(expr),
8650
8651 Expr::NewVariant { enum_name, variant, fields } => self.eval_new_variant(expr),
8652
8653 Expr::ManifestOf { .. } => {
8654 Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(Vec::new())))))
8655 }
8656
8657 Expr::ChunkAt { .. } => {
8658 Ok(RuntimeValue::Nothing)
8659 }
8660
8661 Expr::WithCapacity { value, capacity } => {
8662 let capacity = match self.evaluate_expr_sync(capacity)? {
8663 RuntimeValue::Int(capacity) => capacity,
8664 _ => return Err("Capacity requires an Int".to_string()),
8665 };
8666 let value = self.evaluate_expr_sync(value)?;
8667 Ok(apply_capacity_hint(value, capacity))
8668 }
8669
8670 Expr::OptionSome { value } => {
8672 let inner = self.evaluate_expr_sync(value)?;
8673 Ok(option_some(inner))
8674 }
8675
8676 Expr::OptionNone => Ok(option_none()),
8677
8678 Expr::Not { operand } => {
8679 let val = self.evaluate_expr_sync(operand)?;
8680 crate::semantics::arith::not_value(val)
8681 }
8682
8683 Expr::InterpolatedString(parts) => self.eval_interpolated_string(expr),
8684
8685 Expr::Escape { .. } => {
8686 Err(crate::semantics::escape::REFUSAL.to_string())
8687 }
8688
8689 Expr::Closure { params, body, .. } => self.eval_closure(expr),
8690
8691 Expr::CallExpr { callee, args } => {
8692 let callee_val = self.evaluate_expr_sync(callee)?;
8693 if let RuntimeValue::Function(closure) = callee_val {
8694 let mut arg_values = Vec::with_capacity(args.len());
8695 for arg in args.iter() {
8696 arg_values.push(self.evaluate_expr_sync(arg)?);
8697 }
8698 self.call_closure_value_sync(&closure, arg_values)
8699 } else {
8700 Err(format!("Cannot call value of type {}", callee_val.type_name()))
8701 }
8702 }
8703 }
8704 }
8705
8706 #[inline(never)]
8710 fn eval_closure(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8711 let Expr::Closure { params, body, .. } = expr else {
8712 unreachable!()
8713 };
8714 let free_vars = self.collect_free_vars_in_closure(params, body);
8715 let mut captured_env = HashMap::new();
8716 for sym in &free_vars {
8717 if let Some(val) = self.task.env.lookup(*sym) {
8718 captured_env.insert(*sym, val.deep_clone());
8719 }
8720 }
8721
8722 let body_index = self.ctx.closure_bodies.len();
8723 match body {
8724 ClosureBody::Expression(expr) => {
8725 self.ctx
8726 .closure_bodies
8727 .push(ClosureBodyRef::Expression(expr));
8728 }
8729 ClosureBody::Block(block) => {
8730 self.ctx.closure_bodies.push(ClosureBodyRef::Block(block));
8731 }
8732 }
8733
8734 let param_names: Vec<Symbol> = params.iter().map(|(name, _)| *name).collect();
8735
8736 Ok(RuntimeValue::Function(Box::new(ClosureValue {
8737 body_index,
8738 captured_env,
8739 param_names,
8740 generated: None,
8741 })))
8742 }
8743
8744 #[inline(never)]
8748 fn eval_interpolated_string(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8749 let Expr::InterpolatedString(parts) = expr else {
8750 unreachable!()
8751 };
8752 let mut result = String::new();
8753 for part in parts {
8754 match part {
8755 crate::ast::stmt::StringPart::Literal(sym) => {
8756 result.push_str(self.ctx.interner.resolve(*sym));
8757 }
8758 crate::ast::stmt::StringPart::Expr {
8759 value,
8760 format_spec,
8761 debug,
8762 } => {
8763 let val = self.evaluate_expr_sync(value)?;
8764 if *debug {
8765 let prefix = match value {
8766 Expr::Identifier(sym) => self.ctx.interner.resolve(*sym).to_string(),
8767 _ => "expr".to_string(),
8768 };
8769 result.push_str(&prefix);
8770 result.push('=');
8771 }
8772 if let Some(spec_sym) = format_spec {
8773 let spec = self.ctx.interner.resolve(*spec_sym);
8774 result.push_str(&apply_format_spec(&val, spec));
8775 } else {
8776 result.push_str(&val.to_display_string());
8777 }
8778 }
8779 }
8780 }
8781 Ok(RuntimeValue::Text(Rc::new(result)))
8782 }
8783
8784 #[inline(never)]
8788 fn eval_new_variant(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8789 let Expr::NewVariant {
8790 enum_name,
8791 variant,
8792 fields,
8793 } = expr
8794 else {
8795 unreachable!()
8796 };
8797 let inductive_type = self.ctx.interner.resolve(*enum_name).to_string();
8798 let constructor = self.ctx.interner.resolve(*variant).to_string();
8799
8800 let declared = self
8806 .ctx
8807 .variant_fields
8808 .get(&(*enum_name, *variant))
8809 .cloned();
8810 let args = match &declared {
8811 Some(names) => {
8812 let mut slots: Vec<Option<RuntimeValue>> = (0..names.len()).map(|_| None).collect();
8813 for (field_name, field_expr) in fields {
8814 let field_val = self.evaluate_expr_sync(field_expr)?;
8815 if let Some(pos) = names.iter().position(|n| n == field_name) {
8816 slots[pos] = Some(field_val);
8817 }
8818 }
8819 slots
8820 .into_iter()
8821 .map(|v| v.unwrap_or(RuntimeValue::Nothing))
8822 .collect()
8823 }
8824 None => {
8825 let mut args = Vec::with_capacity(fields.len());
8826 for (_, field_expr) in fields {
8827 args.push(self.evaluate_expr_sync(field_expr)?);
8828 }
8829 args
8830 }
8831 };
8832
8833 Ok(RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
8834 inductive_type,
8835 constructor,
8836 args,
8837 })))
8838 }
8839
8840 #[inline(never)]
8844 fn eval_new(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8845 let Expr::New {
8846 type_name,
8847 init_fields,
8848 ..
8849 } = expr
8850 else {
8851 unreachable!()
8852 };
8853 let name = self.ctx.interner.resolve(*type_name).to_string();
8854
8855 if name == "Seq" || name == "List" {
8856 return Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(
8857 Vec::new(),
8858 )))));
8859 }
8860
8861 if name == "Set" || name == "HashSet" {
8862 return Ok(RuntimeValue::Set(Rc::new(RefCell::new(vec![]))));
8863 }
8864
8865 if name == "Map" || name == "HashMap" {
8866 return Ok(RuntimeValue::Map(Rc::new(RefCell::new(
8867 MapStorage::default(),
8868 ))));
8869 }
8870
8871 let mut fields = HashMap::new();
8872 for (field_sym, field_expr) in init_fields {
8873 let field_name = self.ctx.interner.resolve(*field_sym).to_string();
8874 let field_val = self.evaluate_expr_sync(field_expr)?;
8875 fields.insert(field_name, field_val);
8876 }
8877
8878 if let Some(def) = self.ctx.struct_defs.get(type_name) {
8879 for (field_sym, type_sym, _) in def {
8880 let field_name = self.ctx.interner.resolve(*field_sym).to_string();
8881 if !fields.contains_key(&field_name) {
8882 let type_name_str = self.ctx.interner.resolve(*type_sym).to_string();
8883 let default = default_for_declared_type(type_name_str.as_str());
8884 fields.insert(field_name, default);
8885 }
8886 }
8887 }
8888
8889 Ok(RuntimeValue::Struct(Box::new(StructValue {
8890 type_name: name,
8891 fields,
8892 })))
8893 }
8894
8895 #[inline(never)]
8899 fn eval_binary_op(&mut self, expr: &Expr<'a>) -> Result<RuntimeValue, String> {
8900 let Expr::BinaryOp { op, left, right } = expr else {
8901 unreachable!()
8902 };
8903 match op {
8904 BinaryOpKind::And => {
8905 let left_val = self.evaluate_expr_sync(left)?;
8906 if !left_val.decided_truth()? {
8907 return Ok(RuntimeValue::Bool(false));
8908 }
8909 let right_val = self.evaluate_expr_sync(right)?;
8910 Ok(RuntimeValue::Bool(right_val.decided_truth()?))
8911 }
8912 BinaryOpKind::Or => {
8913 let left_val = self.evaluate_expr_sync(left)?;
8914 if left_val.decided_truth()? {
8915 return Ok(RuntimeValue::Bool(true));
8916 }
8917 let right_val = self.evaluate_expr_sync(right)?;
8918 Ok(RuntimeValue::Bool(right_val.decided_truth()?))
8919 }
8920 _ => {
8921 let left_val = self.evaluate_expr_sync(left)?;
8922 let right_val = self.evaluate_expr_sync(right)?;
8923 self.apply_binary_op(*op, left_val, right_val)
8924 }
8925 }
8926 }
8927
8928 fn self_tail_call_args_sync(&self, expr: &'a Expr<'a>) -> Option<&'a [&'a Expr<'a>]> {
8933 if self.task.repeat_depth_sync != 0 {
8934 return None;
8935 }
8936 let cur = self.task.tco_fn_sync?;
8937 let param_count = self.ctx.functions.get(&cur)?.params.len();
8938 crate::tail_call::direct_self_tail_args(expr, cur, param_count)
8939 }
8940
8941 fn self_tail_call_args_async(&self, expr: &'a Expr<'a>) -> Option<&'a [&'a Expr<'a>]> {
8943 if self.task.repeat_depth_async != 0 {
8944 return None;
8945 }
8946 let cur = self.task.tco_fn_async?;
8947 let param_count = self.ctx.functions.get(&cur)?.params.len();
8948 crate::tail_call::direct_self_tail_args(expr, cur, param_count)
8949 }
8950
8951 fn call_function_sync(
8952 &mut self,
8953 function: Symbol,
8954 args: &[&Expr<'a>],
8955 ) -> Result<RuntimeValue, String> {
8956 let func_sym = Some(function);
8958 if self.declares(function) {
8959 } else if func_sym == self.ctx.sym_show {
8961 for arg in args {
8962 let val = self.evaluate_expr_sync(arg)?;
8963 self.emit_output(val.to_display_string());
8964 }
8965 return Ok(RuntimeValue::Nothing);
8966 } else if func_sym == self.ctx.sym_args {
8967 let items: Vec<RuntimeValue> = self
8971 .ctx
8972 .program_args
8973 .iter()
8974 .map(|s| RuntimeValue::Text(Rc::new(s.clone())))
8975 .collect();
8976 return Ok(RuntimeValue::List(Rc::new(RefCell::new(
8977 ListRepr::from_values(items),
8978 ))));
8979 } else if self.pbkdf2_accel(function, args.len()) {
8980 let pw = self.evaluate_expr_sync(&args[0])?;
8984 let salt = self.evaluate_expr_sync(&args[1])?;
8985 let iters = self.evaluate_expr_sync(&args[2])?;
8986 let (pw, salt, iters) = crate::semantics::builtins::pbkdf2_arguments(&pw, &salt, &iters)?;
8987 let dk = crate::crypto_accel::pbkdf2_sha256(&pw, &salt, iters);
8988 return Ok(crate::semantics::builtins::bytes_to_seq(&dk));
8989 } else if let Some(kernel) = self.native_kernel(function, args.len()) {
8990 let mut vals = Vec::with_capacity(args.len());
8992 for arg in args {
8993 vals.push(self.evaluate_expr_sync(arg)?);
8994 }
8995 return kernel.call(&vals);
8996 } else if let Some(id) = self.system_native_id(function, args.len()) {
8997 let mut vals = Vec::with_capacity(args.len());
9000 for arg in args {
9001 vals.push(self.evaluate_expr_sync(arg)?);
9002 }
9003 return crate::semantics::builtins::call_builtin(id, vals);
9004 } else if self.sleep_native(function, args.len()) {
9005 let val = self.evaluate_expr_sync(&args[0])?;
9006 self.sleep_for_sync(val)?;
9007 return Ok(RuntimeValue::Nothing);
9008 } else if self.tcp_native_op(function, args.len()).is_some() {
9009 return Err(format!(
9012 "{} (tcp) requires the async interpreter path",
9013 self.ctx.interner.resolve(function)
9014 ));
9015 } else if let Some(id) = self.builtin_id(function) {
9016 crate::semantics::builtins::check_arity(id, args.len())?;
9018 let vals = if id == crate::semantics::builtins::BuiltinId::Format {
9020 match args.first() {
9021 Some(a) => vec![self.evaluate_expr_sync(a)?],
9022 None => Vec::new(),
9023 }
9024 } else {
9025 let mut v = Vec::with_capacity(args.len());
9026 for arg in args {
9027 v.push(self.evaluate_expr_sync(arg)?);
9028 }
9029 v
9030 };
9031 if id == crate::semantics::builtins::BuiltinId::DefinedReal {
9032 return self.open_defined_run().define(vals);
9033 }
9034 return crate::semantics::builtins::call_builtin(id, vals);
9035 }
9036
9037 if let Some(refusal) = self.native_refusal(function) {
9038 return Err(refusal);
9039 }
9040
9041 if let Some(func) = self.ctx.functions.get(&function) {
9043 let param_count = func.params.len();
9044 let body = func.body;
9045
9046 if args.len() != param_count {
9047 return Err(format!(
9048 "Function {} expects {} arguments, got {}",
9049 self.ctx.interner.resolve(function),
9050 param_count,
9051 args.len()
9052 ));
9053 }
9054
9055 let mut arg_values = Vec::with_capacity(param_count);
9056 let mut lent: Vec<(usize, Place)> = Vec::new();
9057 for (i, arg) in args.iter().enumerate() {
9058 if matches!(
9059 self.ctx.functions[&function].params[i].1,
9060 TypeExpr::Mutable { .. }
9061 ) {
9062 let place = match self.place_sync(arg) {
9063 Ok(place) => place,
9064 Err(e) => {
9065 let values = self.values_to_give_back(&lent, &mut arg_values);
9066 self.give_back(lent, values);
9067 return Err(e);
9068 }
9069 };
9070 if let Some(value) = place.as_ref().and_then(|place| self.lend(place)) {
9071 arg_values.push(value);
9072 lent.push((i, place.expect("a lent argument names a place")));
9073 continue;
9074 }
9075 }
9076 match self.evaluate_expr_sync(arg) {
9077 Ok(v) => arg_values.push(v),
9078 Err(e) => {
9079 let values = self.values_to_give_back(&lent, &mut arg_values);
9080 self.give_back(lent, values);
9081 return Err(e);
9082 }
9083 }
9084 }
9085
9086 if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
9087 let values = self.values_to_give_back(&lent, &mut arg_values);
9088 self.give_back(lent, values);
9089 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
9090 }
9091 self.task.call_depth += 1;
9092 self.task.env.push_frame();
9093 for i in 0..param_count {
9094 let param_name = self.ctx.functions[&function].params[i].0;
9095 self.task.env.define(
9096 param_name,
9097 std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
9098 );
9099 }
9100
9101 let prev_tco = self.task.tco_fn_sync.replace(function);
9106 let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_sync, 0);
9107 let mut return_value = RuntimeValue::Nothing;
9108 let mut body_err = None;
9109 'tco: loop {
9110 self.task.pending_tail_call = None;
9111 let mut idx = 0;
9112 while idx < body.len() {
9113 if idx + 1 < body.len() {
9117 if let Some(call_args) = crate::tail_call::tail_pair_args(
9118 &body[idx],
9119 &body[idx + 1],
9120 function,
9121 param_count,
9122 ) {
9123 let mut vals = Vec::with_capacity(call_args.len());
9124 let mut perr = None;
9125 for a in call_args {
9126 match self.evaluate_expr_sync(a) {
9127 Ok(v) => vals.push(v),
9128 Err(e) => {
9129 perr = Some(e);
9130 break;
9131 }
9132 }
9133 }
9134 match perr {
9135 Some(e) => body_err = Some(e),
9136 None => self.task.pending_tail_call = Some(vals),
9137 }
9138 break;
9139 }
9140 }
9141 match self.execute_stmt_sync(&body[idx]) {
9142 Ok(ControlFlow::Return(val)) => {
9143 return_value = val;
9144 break;
9145 }
9146 Ok(ControlFlow::Break) => break,
9147 Ok(ControlFlow::Continue) => {}
9148 Err(e) => {
9149 body_err = Some(e);
9150 break;
9151 }
9152 }
9153 idx += 1;
9154 }
9155 if body_err.is_some() {
9156 break 'tco;
9157 }
9158 match self.task.pending_tail_call.take() {
9159 Some(new_args) => {
9160 self.task.env.pop_frame();
9163 self.task.env.push_frame();
9164 for (i, v) in new_args.into_iter().enumerate() {
9165 let param_name = self.ctx.functions[&function].params[i].0;
9166 self.task.env.define(param_name, v);
9167 }
9168 continue 'tco;
9169 }
9170 None => break 'tco,
9171 }
9172 }
9173 self.task.repeat_depth_sync = prev_repeat;
9174 self.task.tco_fn_sync = prev_tco;
9175
9176 let returned = self.lent_values(function, &lent);
9177 self.task.env.pop_frame();
9178 self.give_back(lent, returned);
9179 self.task.call_depth -= 1;
9180 match body_err {
9181 Some(e) => Err(e),
9182 None => Ok(self.coerce_record_return(return_value, function)),
9183 }
9184 } else {
9185 let maybe_closure = self.task.env.lookup(function).and_then(|v| {
9187 if let RuntimeValue::Function(c) = v {
9188 Some((**c).clone())
9189 } else {
9190 None
9191 }
9192 });
9193
9194 if let Some(closure) = maybe_closure {
9195 let mut arg_values = Vec::with_capacity(args.len());
9196 for arg in args {
9197 arg_values.push(self.evaluate_expr_sync(arg)?);
9198 }
9199 self.call_closure_value_sync(&closure, arg_values)
9200 } else {
9201 Err(format!(
9202 "Unknown function: {}",
9203 self.ctx.interner.resolve(function)
9204 ))
9205 }
9206 }
9207 }
9208
9209 fn call_function_with_values_sync(
9210 &mut self,
9211 function: Symbol,
9212 mut args: Vec<RuntimeValue>,
9213 ) -> Result<RuntimeValue, String> {
9214 if Some(function) == self.ctx.sym_show {
9216 for val in args {
9217 self.emit_output(val.to_display_string());
9218 }
9219 return Ok(RuntimeValue::Nothing);
9220 }
9221 if let Some(id) = self.system_native_id(function, args.len()) {
9222 return crate::semantics::builtins::call_builtin(id, args);
9223 }
9224 if let Some(kernel) = self.native_kernel(function, args.len()) {
9225 return kernel.call(&args);
9226 }
9227 if self.sleep_native(function, args.len()) {
9228 self.sleep_for_sync(args.remove(0))?;
9229 return Ok(RuntimeValue::Nothing);
9230 }
9231 if let Some(refusal) = self.native_refusal(function) {
9232 return Err(refusal);
9233 }
9234
9235 if let Some(func) = self.ctx.functions.get(&function) {
9236 let param_count = func.params.len();
9237 let body = func.body;
9238
9239 if args.len() != param_count {
9240 return Err(format!(
9241 "Function {} expects {} arguments, got {}",
9242 self.ctx.interner.resolve(function),
9243 param_count,
9244 args.len()
9245 ));
9246 }
9247
9248 if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
9249 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
9250 }
9251 self.task.call_depth += 1;
9252 self.task.env.push_frame();
9253 for i in 0..param_count {
9254 let param_name = self.ctx.functions[&function].params[i].0;
9255 self.task.env.define(
9256 param_name,
9257 std::mem::replace(&mut args[i], RuntimeValue::Nothing),
9258 );
9259 }
9260
9261 let prev_tco = self.task.tco_fn_sync.replace(function);
9266 let prev_repeat = std::mem::replace(&mut self.task.repeat_depth_sync, 0);
9267 let mut return_value = RuntimeValue::Nothing;
9268 let mut body_err = None;
9269 'tco: loop {
9270 self.task.pending_tail_call = None;
9271 let mut idx = 0;
9272 while idx < body.len() {
9273 if idx + 1 < body.len() {
9277 if let Some(call_args) = crate::tail_call::tail_pair_args(
9278 &body[idx],
9279 &body[idx + 1],
9280 function,
9281 param_count,
9282 ) {
9283 let mut vals = Vec::with_capacity(call_args.len());
9284 let mut perr = None;
9285 for a in call_args {
9286 match self.evaluate_expr_sync(a) {
9287 Ok(v) => vals.push(v),
9288 Err(e) => {
9289 perr = Some(e);
9290 break;
9291 }
9292 }
9293 }
9294 match perr {
9295 Some(e) => body_err = Some(e),
9296 None => self.task.pending_tail_call = Some(vals),
9297 }
9298 break;
9299 }
9300 }
9301 match self.execute_stmt_sync(&body[idx]) {
9302 Ok(ControlFlow::Return(val)) => {
9303 return_value = val;
9304 break;
9305 }
9306 Ok(ControlFlow::Break) => break,
9307 Ok(ControlFlow::Continue) => {}
9308 Err(e) => {
9309 body_err = Some(e);
9310 break;
9311 }
9312 }
9313 idx += 1;
9314 }
9315 if body_err.is_some() {
9316 break 'tco;
9317 }
9318 match self.task.pending_tail_call.take() {
9319 Some(new_args) => {
9320 self.task.env.pop_frame();
9323 self.task.env.push_frame();
9324 for (i, v) in new_args.into_iter().enumerate() {
9325 let param_name = self.ctx.functions[&function].params[i].0;
9326 self.task.env.define(param_name, v);
9327 }
9328 continue 'tco;
9329 }
9330 None => break 'tco,
9331 }
9332 }
9333 self.task.repeat_depth_sync = prev_repeat;
9334 self.task.tco_fn_sync = prev_tco;
9335
9336 self.task.env.pop_frame();
9337 self.task.call_depth -= 1;
9338 match body_err {
9339 Some(e) => Err(e),
9340 None => Ok(self.coerce_record_return(return_value, function)),
9341 }
9342 } else {
9343 let maybe_closure = self.task.env.lookup(function).and_then(|v| {
9344 if let RuntimeValue::Function(c) = v {
9345 Some((**c).clone())
9346 } else {
9347 None
9348 }
9349 });
9350
9351 if let Some(closure) = maybe_closure {
9352 self.call_closure_value_sync(&closure, args)
9353 } else {
9354 Err(format!(
9355 "Unknown function: {}",
9356 self.ctx.interner.resolve(function)
9357 ))
9358 }
9359 }
9360 }
9361
9362 pub(crate) fn collect_free_vars_in_closure(
9371 &self,
9372 params: &[(Symbol, &TypeExpr<'a>)],
9373 body: &ClosureBody<'a>,
9374 ) -> Vec<Symbol> {
9375 Self::free_vars_in_closure(params, body)
9376 }
9377
9378 pub(crate) fn free_vars_in_closure(
9381 params: &[(Symbol, &TypeExpr<'a>)],
9382 body: &ClosureBody<'a>,
9383 ) -> Vec<Symbol> {
9384 let param_set: std::collections::HashSet<Symbol> = params.iter().map(|(s, _)| *s).collect();
9385 let mut out = Vec::new();
9386 let mut seen = std::collections::HashSet::new();
9387
9388 match body {
9389 ClosureBody::Expression(expr) => {
9390 Self::collect_symbols_from_expr(expr, ¶m_set, &mut out, &mut seen);
9391 }
9392 ClosureBody::Block(block) => {
9393 Self::collect_symbols_from_block(block, ¶m_set, &mut out, &mut seen);
9394 }
9395 }
9396
9397 out
9398 }
9399
9400 fn collect_symbols_from_expr(
9401 expr: &Expr<'a>,
9402 exclude: &std::collections::HashSet<Symbol>,
9403 out: &mut Vec<Symbol>,
9404 seen: &mut std::collections::HashSet<Symbol>,
9405 ) {
9406 match expr {
9407 Expr::Dom(q) => {
9408 if let Some(sel) = q.selector() {
9409 Self::collect_symbols_from_expr(sel, exclude, out, seen);
9410 }
9411 }
9412 Expr::View(v) => {
9413 let (view_exprs, view_blocks) = v.exprs_and_blocks();
9414 for e in view_exprs {
9415 Self::collect_symbols_from_expr(e, exclude, out, seen);
9416 }
9417 let _ = &view_blocks;
9418 }
9419 Expr::Identifier(sym) => {
9420 if !exclude.contains(sym) && seen.insert(*sym) {
9421 out.push(*sym);
9422 }
9423 }
9424 Expr::Literal(_) | Expr::OptionNone | Expr::Escape { .. } => {}
9425 Expr::BinaryOp { left, right, .. } => {
9426 Self::collect_symbols_from_expr(left, exclude, out, seen);
9427 Self::collect_symbols_from_expr(right, exclude, out, seen);
9428 }
9429 Expr::Call { function, args } => {
9430 if !exclude.contains(function) && seen.insert(*function) {
9431 out.push(*function);
9432 }
9433 for arg in args {
9434 Self::collect_symbols_from_expr(arg, exclude, out, seen);
9435 }
9436 }
9437 Expr::FieldAccess { object, .. } => {
9438 Self::collect_symbols_from_expr(object, exclude, out, seen);
9439 }
9440 Expr::Index { collection, index } => {
9441 Self::collect_symbols_from_expr(collection, exclude, out, seen);
9442 Self::collect_symbols_from_expr(index, exclude, out, seen);
9443 }
9444 Expr::Slice {
9445 collection,
9446 start,
9447 end,
9448 } => {
9449 Self::collect_symbols_from_expr(collection, exclude, out, seen);
9450 Self::collect_symbols_from_expr(start, exclude, out, seen);
9451 Self::collect_symbols_from_expr(end, exclude, out, seen);
9452 }
9453 Expr::Copy { expr: e }
9454 | Expr::Give { value: e }
9455 | Expr::Length { collection: e }
9456 | Expr::Not { operand: e } => {
9457 Self::collect_symbols_from_expr(e, exclude, out, seen);
9458 }
9459 Expr::List(items) | Expr::Tuple(items) => {
9460 for item in items {
9461 Self::collect_symbols_from_expr(item, exclude, out, seen);
9462 }
9463 }
9464 Expr::Range { start, end } => {
9465 Self::collect_symbols_from_expr(start, exclude, out, seen);
9466 Self::collect_symbols_from_expr(end, exclude, out, seen);
9467 }
9468 Expr::New { init_fields, .. } => {
9469 for (_, e) in init_fields {
9470 Self::collect_symbols_from_expr(e, exclude, out, seen);
9471 }
9472 }
9473 Expr::NewVariant { fields, .. } => {
9474 for (_, e) in fields {
9475 Self::collect_symbols_from_expr(e, exclude, out, seen);
9476 }
9477 }
9478 Expr::Contains { collection, value }
9479 | Expr::Union {
9480 left: collection,
9481 right: value,
9482 }
9483 | Expr::Intersection {
9484 left: collection,
9485 right: value,
9486 } => {
9487 Self::collect_symbols_from_expr(collection, exclude, out, seen);
9488 Self::collect_symbols_from_expr(value, exclude, out, seen);
9489 }
9490 Expr::ManifestOf { zone } | Expr::OptionSome { value: zone } => {
9491 Self::collect_symbols_from_expr(zone, exclude, out, seen);
9492 }
9493 Expr::ChunkAt { index, zone }
9494 | Expr::WithCapacity {
9495 value: index,
9496 capacity: zone,
9497 } => {
9498 Self::collect_symbols_from_expr(index, exclude, out, seen);
9499 Self::collect_symbols_from_expr(zone, exclude, out, seen);
9500 }
9501 Expr::Closure {
9502 params: inner_params,
9503 body: inner_body,
9504 ..
9505 } => {
9506 let mut inner_exclude = exclude.clone();
9508 for (s, _) in inner_params {
9509 inner_exclude.insert(*s);
9510 }
9511 match inner_body {
9512 ClosureBody::Expression(e) => {
9513 Self::collect_symbols_from_expr(e, &inner_exclude, out, seen);
9514 }
9515 ClosureBody::Block(b) => {
9516 Self::collect_symbols_from_block(b, &inner_exclude, out, seen);
9517 }
9518 }
9519 }
9520 Expr::CallExpr { callee, args } => {
9521 Self::collect_symbols_from_expr(callee, exclude, out, seen);
9522 for arg in args {
9523 Self::collect_symbols_from_expr(arg, exclude, out, seen);
9524 }
9525 }
9526 Expr::InterpolatedString(parts) => {
9527 for part in parts {
9528 if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
9529 Self::collect_symbols_from_expr(value, exclude, out, seen);
9530 }
9531 }
9532 }
9533 }
9534 }
9535
9536 fn collect_symbols_from_block(
9537 stmts: &[Stmt<'a>],
9538 exclude: &std::collections::HashSet<Symbol>,
9539 out: &mut Vec<Symbol>,
9540 seen: &mut std::collections::HashSet<Symbol>,
9541 ) {
9542 use crate::ast::stmt::Pattern;
9543 let mut bound = exclude.clone();
9551 for stmt in stmts {
9552 match stmt {
9553 Stmt::Let { var, value, .. } => {
9554 Self::collect_symbols_from_expr(value, &bound, out, seen);
9555 bound.insert(*var);
9556 }
9557 Stmt::Set { target, value } => {
9558 Self::collect_symbols_from_expr(value, &bound, out, seen);
9559 if !bound.contains(target) && seen.insert(*target) {
9566 out.push(*target);
9567 }
9568 }
9569 Stmt::Call { function, args } => {
9570 if !bound.contains(function) && seen.insert(*function) {
9571 out.push(*function);
9572 }
9573 for arg in args {
9574 Self::collect_symbols_from_expr(arg, &bound, out, seen);
9575 }
9576 }
9577 Stmt::Return { value: Some(e) } => {
9578 Self::collect_symbols_from_expr(e, &bound, out, seen);
9579 }
9580 Stmt::If {
9581 cond,
9582 then_block,
9583 else_block,
9584 } => {
9585 Self::collect_symbols_from_expr(cond, &bound, out, seen);
9586 Self::collect_symbols_from_block(then_block, &bound, out, seen);
9587 if let Some(eb) = else_block {
9588 Self::collect_symbols_from_block(eb, &bound, out, seen);
9589 }
9590 }
9591 Stmt::While { cond, body, .. } => {
9592 Self::collect_symbols_from_expr(cond, &bound, out, seen);
9593 Self::collect_symbols_from_block(body, &bound, out, seen);
9594 }
9595 Stmt::Repeat {
9596 pattern,
9597 iterable,
9598 body,
9599 } => {
9600 Self::collect_symbols_from_expr(iterable, &bound, out, seen);
9601 let mut body_bound = bound.clone();
9602 match pattern {
9603 Pattern::Identifier(s) => {
9604 body_bound.insert(*s);
9605 }
9606 Pattern::Tuple(syms) => {
9607 for s in syms {
9608 body_bound.insert(*s);
9609 }
9610 }
9611 }
9612 Self::collect_symbols_from_block(body, &body_bound, out, seen);
9613 }
9614 Stmt::Show { object, .. } | Stmt::Give { object, .. } => {
9615 Self::collect_symbols_from_expr(object, &bound, out, seen);
9616 }
9617 Stmt::Push { value, collection }
9618 | Stmt::Add { value, collection }
9619 | Stmt::Remove { value, collection } => {
9620 Self::collect_symbols_from_expr(value, &bound, out, seen);
9621 Self::collect_symbols_from_expr(collection, &bound, out, seen);
9622 }
9623 Stmt::SetIndex {
9624 collection,
9625 index,
9626 value,
9627 } => {
9628 Self::collect_symbols_from_expr(collection, &bound, out, seen);
9629 Self::collect_symbols_from_expr(index, &bound, out, seen);
9630 Self::collect_symbols_from_expr(value, &bound, out, seen);
9631 }
9632 Stmt::SetField { object, value, .. } => {
9633 Self::collect_symbols_from_expr(object, &bound, out, seen);
9634 Self::collect_symbols_from_expr(value, &bound, out, seen);
9635 }
9636 Stmt::RuntimeAssert {
9637 condition, reason, ..
9638 } => {
9639 Self::collect_symbols_from_expr(condition, &bound, out, seen);
9640 if let Some(r) = reason {
9641 Self::collect_symbols_from_expr(r, &bound, out, seen);
9642 }
9643 }
9644 Stmt::Fail { reason } => {
9645 Self::collect_symbols_from_expr(reason, &bound, out, seen);
9646 }
9647 Stmt::Zone { body, .. } => {
9648 Self::collect_symbols_from_block(body, &bound, out, seen);
9649 }
9650 Stmt::Inspect { target, arms, .. } => {
9651 Self::collect_symbols_from_expr(target, &bound, out, seen);
9652 for arm in arms {
9653 Self::collect_symbols_from_block(arm.body, &bound, out, seen);
9654 }
9655 }
9656 Stmt::Pop { collection, .. } => {
9657 Self::collect_symbols_from_expr(collection, &bound, out, seen);
9658 }
9659 _ => {}
9660 }
9661 }
9662 }
9663
9664 #[cfg(not(target_arch = "wasm32"))]
9674 async fn serve_http(&mut self, port: u16, handler: Symbol) -> Result<(), String> {
9675 let port = logicaffeine_system::http::server::env_port_override(port);
9679 if logicaffeine_system::tokio::runtime::Handle::try_current().is_ok() {
9680 return self.serve_http_concurrent(port, handler).await;
9681 }
9682 let rt = logicaffeine_system::tokio::runtime::Builder::new_current_thread()
9683 .enable_all()
9684 .build()
9685 .map_err(|e| format!("Serve: cannot start async runtime: {e}"))?;
9686 rt.block_on(self.serve_http_concurrent(port, handler))
9687 }
9688
9689 #[cfg(not(target_arch = "wasm32"))]
9705 async fn serve_http_concurrent(&mut self, port: u16, handler: Symbol) -> Result<(), String> {
9706 use futures::stream::{FuturesUnordered, StreamExt};
9707 use logicaffeine_system::http::server::{
9708 internal_error, read_error_response, try_upgrade, Conn, Listener, ReadError,
9709 UpgradeHandler,
9710 };
9711 use logicaffeine_system::http::wire::{
9712 request_wants_keep_alive, HttpRequest, HttpResponse,
9713 };
9714 use logicaffeine_system::http::{
9715 service_unavailable, shutdown_requested, Admission, Lifecycle, LifecycleConfig,
9716 };
9717 use std::time::Duration;
9718
9719 enum Step {
9722 Request(Conn, Result<HttpRequest, ReadError>),
9725 Closed,
9728 }
9729 type StepFut = std::pin::Pin<Box<dyn std::future::Future<Output = Step>>>;
9730
9731 async fn read_bounded(
9738 conn: &mut Conn,
9739 max_body: usize,
9740 deadline: Duration,
9741 ) -> Option<Result<HttpRequest, ReadError>> {
9742 match logicaffeine_system::tokio::time::timeout(
9743 deadline,
9744 conn.read_request_capped(max_body),
9745 )
9746 .await
9747 {
9748 Ok(read) => Some(read),
9749 Err(_) => None,
9750 }
9751 }
9752
9753 fn read_step(mut conn: Conn, max_body: usize, deadline: Duration) -> StepFut {
9755 Box::pin(async move {
9756 match read_bounded(&mut conn, max_body, deadline).await {
9757 Some(read) => Step::Request(conn, read),
9758 None => Step::Closed,
9759 }
9760 })
9761 }
9762
9763 fn write_step(
9766 mut conn: Conn,
9767 resp: HttpResponse,
9768 keep_alive: bool,
9769 max_body: usize,
9770 deadline: Duration,
9771 ) -> StepFut {
9772 Box::pin(async move {
9773 if conn.write_response_conn(&resp, keep_alive).await.is_err() || !keep_alive {
9774 return Step::Closed;
9775 }
9776 match read_bounded(&mut conn, max_body, deadline).await {
9777 Some(read) => Step::Request(conn, read),
9778 None => Step::Closed,
9779 }
9780 })
9781 }
9782
9783 let lifecycle = Lifecycle::new(LifecycleConfig::from_env());
9787 lifecycle.set_ready(true);
9788 let cfg = lifecycle.config();
9789 let (max_body, read_deadline, max_inflight) =
9790 (cfg.max_body, cfg.read_deadline, cfg.max_inflight);
9791 let (drain_timeout, request_timeout) = (cfg.drain_timeout, cfg.request_timeout);
9792
9793 let addr = logicaffeine_system::http::server::env_bind_address(port);
9798 let listener = Listener::bind(&addr)
9799 .await
9800 .map_err(|e| format!("Serve: cannot bind {addr}: {e}"))?;
9801 let bound = listener.local_addr().map_err(|e| format!("Serve: {e}"))?;
9802 logicaffeine_system::http::server::announce_serving(bound);
9806
9807 let upgrades: std::collections::BTreeMap<String, UpgradeHandler> = if self
9810 .ctx
9811 .components
9812 .values()
9813 .any(crate::analysis::relay::component_uses_the_relay)
9814 {
9815 logicaffeine_system::relay::RelayHub::new()
9816 .upgrades()
9817 .into_iter()
9818 .map(|(path, handler)| (path.to_string(), handler))
9819 .collect()
9820 } else {
9821 std::collections::BTreeMap::new()
9822 };
9823
9824 let shutdown = shutdown_requested();
9825 futures::pin_mut!(shutdown);
9826 let mut draining = false;
9827 let mut inflight: FuturesUnordered<StepFut> = FuturesUnordered::new();
9828 loop {
9829 if draining && inflight.is_empty() {
9833 return Ok(());
9834 }
9835 logicaffeine_system::tokio::select! {
9836 accepted = listener.accept(), if !draining && inflight.len() < max_inflight => {
9837 if let Ok(conn) = accepted {
9838 inflight.push(read_step(conn, max_body, read_deadline));
9839 }
9840 }
9841 _ = &mut shutdown, if !draining => {
9844 lifecycle.set_ready(false);
9845 draining = true;
9846 let _ = logicaffeine_system::tokio::time::timeout(
9847 drain_timeout,
9848 std::future::pending::<()>(),
9849 );
9850 }
9851 Some(step) = inflight.next() => {
9852 match step {
9853 Step::Request(conn, Ok(req)) => {
9854 match try_upgrade(&req, &upgrades) {
9857 Some(Ok((response, handler))) => {
9858 inflight.push(Box::pin(async move {
9859 conn.upgrade(response, handler).await;
9860 Step::Closed
9861 }));
9862 continue;
9863 }
9864 Some(Err(())) => continue,
9865 None => {}
9866 }
9867 let keep_alive = request_wants_keep_alive(&req);
9868 if let Some(resp) = lifecycle.probe_response(&req.path) {
9871 inflight.push(write_step(conn, resp, keep_alive, max_body, read_deadline));
9872 continue;
9873 }
9874 let guard = match lifecycle.admit() {
9878 Admission::Admit(g) => g,
9879 Admission::NotReady | Admission::Overloaded => {
9880 inflight.push(write_step(conn, service_unavailable(), false, max_body, read_deadline));
9881 continue;
9882 }
9883 };
9884 let request_value = Self::http_request_to_value(&req);
9885 self.request_deadline = Some(std::time::Instant::now() + request_timeout);
9889 let outcome =
9890 self.call_function_with_values(handler, vec![request_value]).await;
9891 self.request_deadline = None;
9892 let resp = match outcome {
9893 Ok(value) => match Self::value_to_http_response(&value) {
9894 Ok(resp) => resp,
9895 Err(e) => {
9896 eprintln!("Serve: handler error: {e}");
9897 internal_error()
9898 }
9899 },
9900 Err(e) if e == crate::interpreter::REQUEST_TIMED_OUT => {
9904 eprintln!("Serve: {e}");
9905 service_unavailable()
9906 }
9907 Err(e) => {
9908 eprintln!("Serve: handler error: {e}");
9909 internal_error()
9910 }
9911 };
9912 drop(guard);
9913 lifecycle.notify_slot_freed();
9914 inflight.push(write_step(conn, resp, keep_alive, max_body, read_deadline));
9915 }
9916 Step::Request(conn, Err(ReadError::Parse(ref e))) => {
9917 inflight.push(write_step(conn, read_error_response(e), false, max_body, read_deadline));
9920 }
9921 Step::Request(_, Err(_)) | Step::Closed => {}
9924 }
9925 }
9926 }
9927 }
9928 }
9929
9930 #[cfg(target_arch = "wasm32")]
9931 async fn serve_http(&mut self, _port: u16, _handler: Symbol) -> Result<(), String> {
9932 Err("`Serve` (HTTP server) is not available in the browser".to_string())
9933 }
9934
9935 #[cfg(not(target_arch = "wasm32"))]
9940 pub(crate) fn http_request_to_value(
9941 req: &logicaffeine_system::http::wire::HttpRequest,
9942 ) -> RuntimeValue {
9943 let text_map = |src: &std::collections::BTreeMap<String, String>| {
9944 let mut m = MapStorage::default();
9945 for (k, v) in src {
9946 m.insert(
9947 RuntimeValue::Text(Rc::new(k.clone())),
9948 RuntimeValue::Text(Rc::new(v.clone())),
9949 );
9950 }
9951 RuntimeValue::Map(Rc::new(RefCell::new(m)))
9952 };
9953 let mut fields = HashMap::new();
9954 fields.insert(
9955 "method".to_string(),
9956 RuntimeValue::Text(Rc::new(req.method.clone())),
9957 );
9958 fields.insert(
9959 "path".to_string(),
9960 RuntimeValue::Text(Rc::new(req.path.clone())),
9961 );
9962 fields.insert(
9963 "body".to_string(),
9964 RuntimeValue::Text(Rc::new(String::from_utf8_lossy(&req.body).into_owned())),
9965 );
9966 fields.insert("headers".to_string(), text_map(&req.headers));
9967 fields.insert("query".to_string(), text_map(&req.query));
9968 RuntimeValue::Struct(Box::new(StructValue {
9969 type_name: "Request".to_string(),
9970 fields,
9971 }))
9972 }
9973
9974 #[cfg(not(target_arch = "wasm32"))]
9976 pub(crate) fn value_to_http_response(
9977 value: &RuntimeValue,
9978 ) -> Result<logicaffeine_system::http::wire::HttpResponse, String> {
9979 use logicaffeine_system::http::wire::HttpResponse;
9980 use std::collections::BTreeMap;
9981
9982 let s = match value {
9983 RuntimeValue::Struct(s) => s,
9984 other => {
9985 return Err(format!(
9986 "Serve: handler must return a Response, got {}",
9987 other.type_name()
9988 ))
9989 }
9990 };
9991 let status = match s.fields.get("status") {
9992 Some(RuntimeValue::Int(n)) if (100..=599).contains(n) => *n as u16,
9993 Some(RuntimeValue::Int(n)) => {
9994 return Err(format!(
9995 "Serve: response status {n} is out of range (100-599)"
9996 ))
9997 }
9998 _ => 200,
9999 };
10000 let content_type = match s.fields.get("contentType") {
10004 Some(RuntimeValue::Text(t)) => {
10005 logicaffeine_system::http::wire::safe_content_type(t).to_string()
10006 }
10007 _ => "text/plain".to_string(),
10008 };
10009 let bytes_body = match s.fields.get("bytes") {
10012 Some(RuntimeValue::List(list)) => {
10013 let l = list.borrow();
10014 (l.len() > 0).then(|| {
10015 (0..l.len())
10016 .filter_map(|i| l.get(i))
10017 .map(|v| match v {
10018 RuntimeValue::Int(n) => n as u8,
10019 _ => 0,
10020 })
10021 .collect::<Vec<u8>>()
10022 })
10023 }
10024 _ => None,
10025 };
10026 let body = bytes_body.unwrap_or_else(|| match s.fields.get("body") {
10027 Some(RuntimeValue::Text(t)) => t.as_bytes().to_vec(),
10028 Some(other) => other.to_display_string().into_bytes(),
10029 None => Vec::new(),
10030 });
10031 let mut headers = BTreeMap::new();
10035 if let Some(RuntimeValue::Map(m)) = s.fields.get("headers") {
10036 for (k, v) in m.borrow().iter() {
10037 if let (RuntimeValue::Text(name), RuntimeValue::Text(value)) = (k, v) {
10038 if logicaffeine_system::http::wire::response_header_allowed(name, value) {
10039 headers.insert(name.to_string(), value.to_string());
10040 }
10041 }
10042 }
10043 }
10044 headers.insert("Content-Type".to_string(), content_type);
10045 Ok(HttpResponse {
10046 status,
10047 headers,
10048 body,
10049 })
10050 }
10051
10052 #[async_recursion(?Send)]
10054 async fn call_closure_value(
10055 &mut self,
10056 closure: &ClosureValue,
10057 mut arg_values: Vec<RuntimeValue>,
10058 ) -> Result<RuntimeValue, String> {
10059 if arg_values.len() != closure.param_names.len() {
10060 return Err(format!(
10061 "Closure expects {} arguments, got {}",
10062 closure.param_names.len(),
10063 arg_values.len()
10064 ));
10065 }
10066
10067 if let Some(expr) = &closure.generated {
10071 let i = match arg_values.first() {
10072 Some(RuntimeValue::Int(n)) => *n,
10073 _ => 0,
10074 };
10075 return Ok(RuntimeValue::Int(crate::concurrency::marshal::gen_eval(
10076 expr, i,
10077 )));
10078 }
10079
10080 let body_index = closure.body_index;
10082 let is_block = matches!(
10083 self.ctx.closure_bodies.get(body_index),
10084 Some(ClosureBodyRef::Block(_))
10085 );
10086
10087 if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
10090 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
10091 }
10092 self.task.call_depth += 1;
10093 self.task.env.push_frame();
10094
10095 for (sym, val) in &closure.captured_env {
10097 self.task.env.define(*sym, val.deep_clone());
10098 }
10099
10100 for (i, param_sym) in closure.param_names.iter().enumerate() {
10102 self.task.env.define(
10103 *param_sym,
10104 std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
10105 );
10106 }
10107
10108 let result = if is_block {
10109 let block = match &self.ctx.closure_bodies[body_index] {
10110 ClosureBodyRef::Block(b) => *b,
10111 _ => unreachable!(),
10112 };
10113 let mut outcome = Ok(RuntimeValue::Nothing);
10114 for stmt in block.iter() {
10115 match self.execute_stmt(stmt).await {
10116 Ok(ControlFlow::Return(val)) => {
10117 outcome = Ok(val);
10118 break;
10119 }
10120 Ok(ControlFlow::Break) => break,
10121 Ok(ControlFlow::Continue) => {}
10122 Err(e) => {
10123 outcome = Err(e);
10124 break;
10125 }
10126 }
10127 }
10128 outcome
10129 } else {
10130 let expr = match &self.ctx.closure_bodies[body_index] {
10131 ClosureBodyRef::Expression(e) => *e,
10132 _ => unreachable!(),
10133 };
10134 self.evaluate_expr(expr).await
10135 };
10136
10137 self.task.env.pop_frame();
10138 self.task.call_depth -= 1;
10139 result
10140 }
10141
10142 fn open_defined_run(&mut self) -> &crate::semantics::defined::RunScope<'a> {
10149 let child = RefCell::new(Interpreter::evaluation_child(self.ctx.clone(), self.fuel.clone()));
10150 let (ctx, fuel) = (self.ctx.clone(), self.fuel.clone());
10151 let evaluator: crate::semantics::defined::Evaluator<'a> = Rc::new(move |closure, n| {
10152 let RuntimeValue::Function(c) = closure else {
10153 return Err(format!("a real number is defined by a function, got {}", closure.type_name()));
10154 };
10155 let args = vec![RuntimeValue::Int(n)];
10156 match child.try_borrow_mut() {
10157 Ok(mut child) => child.call_closure_value_sync(c, args),
10158 Err(_) => Interpreter::evaluation_child(ctx.clone(), fuel.clone()).call_closure_value_sync(c, args),
10159 }
10160 });
10161 match &self.defined_run {
10162 Some(run) => run.renew(evaluator),
10163 None => self.defined_run = Some(crate::semantics::defined::open_run(evaluator)),
10164 }
10165 self.defined_run.as_ref().expect("the run is open")
10166 }
10167
10168 fn evaluation_child(ctx: SharedCtx<'a>, fuel: Option<FuelHandles>) -> Interpreter<'a> {
10171 Interpreter {
10172 ctx,
10173 task: TaskState::new(),
10174 output: Vec::new(),
10175 current_site: None,
10176 yield_state: None,
10177 err_sink: None,
10178 netbox: crate::concurrency::net_inbox::NetInbox::new(),
10179 tcpbox: crate::concurrency::tcp_registry::TcpRegistry::new(),
10180 test_mode: false,
10181 test_failures: Vec::new(),
10182 test_ops: 0,
10183 test_assertions: 0,
10184 test_budget: u64::MAX,
10185 gen_rng: 0,
10186 prove_mode: false,
10187 properties_proven: 0,
10188 fuel,
10189 request_deadline: None,
10190 deadline_tick: 0,
10191 tiers_noop: false,
10192 page: PageSeat::Unseated,
10193 statement_observer: None,
10194 page_main: None,
10195 failed_call_site: None,
10196 defined_run: None,
10197 }
10198 }
10199
10200 fn call_closure_value_sync(
10202 &mut self,
10203 closure: &ClosureValue,
10204 mut arg_values: Vec<RuntimeValue>,
10205 ) -> Result<RuntimeValue, String> {
10206 if arg_values.len() != closure.param_names.len() {
10207 return Err(format!(
10208 "Closure expects {} arguments, got {}",
10209 closure.param_names.len(),
10210 arg_values.len()
10211 ));
10212 }
10213
10214 if let Some(expr) = &closure.generated {
10216 let i = match arg_values.first() {
10217 Some(RuntimeValue::Int(n)) => *n,
10218 _ => 0,
10219 };
10220 return Ok(RuntimeValue::Int(crate::concurrency::marshal::gen_eval(
10221 expr, i,
10222 )));
10223 }
10224
10225 let body_index = closure.body_index;
10226 let is_block = matches!(
10227 self.ctx.closure_bodies.get(body_index),
10228 Some(ClosureBodyRef::Block(_))
10229 );
10230
10231 if self.task.call_depth >= crate::semantics::MAX_CALL_DEPTH {
10233 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
10234 }
10235 self.task.call_depth += 1;
10236 self.task.env.push_frame();
10237
10238 for (sym, val) in &closure.captured_env {
10239 self.task.env.define(*sym, val.deep_clone());
10240 }
10241
10242 for (i, param_sym) in closure.param_names.iter().enumerate() {
10243 self.task.env.define(
10244 *param_sym,
10245 std::mem::replace(&mut arg_values[i], RuntimeValue::Nothing),
10246 );
10247 }
10248
10249 let result = if is_block {
10250 let block = match &self.ctx.closure_bodies[body_index] {
10251 ClosureBodyRef::Block(b) => *b,
10252 _ => unreachable!(),
10253 };
10254 let mut outcome = Ok(RuntimeValue::Nothing);
10255 for stmt in block.iter() {
10256 match self.execute_stmt_sync(stmt) {
10257 Ok(ControlFlow::Return(val)) => {
10258 outcome = Ok(val);
10259 break;
10260 }
10261 Ok(ControlFlow::Break) => break,
10262 Ok(ControlFlow::Continue) => {}
10263 Err(e) => {
10264 outcome = Err(e);
10265 break;
10266 }
10267 }
10268 }
10269 outcome
10270 } else {
10271 let expr = match &self.ctx.closure_bodies[body_index] {
10272 ClosureBodyRef::Expression(e) => *e,
10273 _ => unreachable!(),
10274 };
10275 self.evaluate_expr_sync(expr)
10276 };
10277
10278 self.task.env.pop_frame();
10279 self.task.call_depth -= 1;
10280 result
10281 }
10282}
10283
10284impl<'a> crate::page_host::LoweredCalls for Interpreter<'a> {
10290 fn call(&mut self, name: &str, args: Vec<RuntimeValue>) -> Result<RuntimeValue, String> {
10291 self.require_page_main(&format!("`{name}`"))?;
10292 let function = self
10293 .ctx
10294 .interner
10295 .lookup(name)
10296 .filter(|f| self.ctx.functions.contains_key(f))
10297 .ok_or_else(|| format!("tree-walker: this program has no function `{name}`"))?;
10298 let expected = self.ctx.functions[&function].params.len();
10299 if args.len() != expected {
10300 return Err(format!(
10301 "`{name}` expects {expected} arguments, got {}",
10302 args.len()
10303 ));
10304 }
10305 self.host_call(|me| me.call_function_with_values_sync(function, args))
10306 }
10307
10308 fn call_value(
10309 &mut self,
10310 callee: &RuntimeValue,
10311 args: Vec<RuntimeValue>,
10312 ) -> Result<RuntimeValue, String> {
10313 self.require_page_main("a closure")?;
10314 match callee {
10315 RuntimeValue::Function(closure) => {
10316 self.host_call(|me| me.call_closure_value_sync(closure, args))
10317 }
10318 other => Err(format!("Cannot call value of type {}", other.type_name())),
10319 }
10320 }
10321
10322 fn has(&self, name: &str) -> bool {
10323 self.ctx
10324 .interner
10325 .lookup(name)
10326 .is_some_and(|f| self.ctx.functions.contains_key(&f))
10327 }
10328
10329 fn reload(&mut self) -> Result<(), String> {
10333 self.require_page_main("a reload")?;
10334 let program = self.page_main.clone().unwrap_or_default();
10335 self.at_top_level(|me| me.host_call(|me| me.run_top_level_sync(&program, false)))
10336 }
10337
10338 fn lines(&self) -> &[String] {
10339 &self.output
10340 }
10341
10342 fn failure_site(&self) -> Option<u32> {
10343 self.failed_call_site
10344 }
10345}
10346
10347pub const SESSION_STACK_BYTES: usize = 256 * 1024 * 1024;
10355
10356thread_local! {
10357 static ON_SESSION_STACK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
10359}
10360
10361#[cfg(not(target_arch = "wasm32"))]
10363struct WorldHandoff(PageWorld);
10364
10365#[cfg(not(target_arch = "wasm32"))]
10366impl WorldHandoff {
10367 fn arrive(self) {
10369 self.0.restore();
10370 }
10371}
10372
10373#[cfg(not(target_arch = "wasm32"))]
10383unsafe impl Send for WorldHandoff {}
10384
10385pub fn on_session_stack<R: Send>(session: impl FnOnce() -> R + Send) -> R {
10395 #[cfg(not(target_arch = "wasm32"))]
10396 {
10397 if ON_SESSION_STACK.with(|on| on.get()) {
10398 return session();
10399 }
10400 let world = WorldHandoff(PageWorld::take());
10401 let (ran, world) = std::thread::scope(|scope| {
10402 let worker = std::thread::Builder::new()
10403 .name("logos-session".to_string())
10404 .stack_size(SESSION_STACK_BYTES)
10405 .spawn_scoped(scope, move || {
10406 ON_SESSION_STACK.with(|on| on.set(true));
10407 world.arrive();
10408 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(session));
10409 (ran, WorldHandoff(PageWorld::take()))
10410 })
10411 .expect("spawn the tree-walker session thread");
10412 worker
10413 .join()
10414 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
10415 });
10416 world.arrive();
10417 ran.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
10418 }
10419 #[cfg(target_arch = "wasm32")]
10420 {
10421 session()
10422 }
10423}
10424
10425fn apply_format_spec(val: &RuntimeValue, spec: &str) -> String {
10430 crate::semantics::format::apply_format_spec(val, spec)
10431}
10432
10433fn crossing_to_a_task(val: &RuntimeValue) -> Result<RuntimeValue, String> {
10437 let payload =
10438 marshal::materialize(val).map_err(|e| format!("cannot send value through a channel: {:?}", e))?;
10439 Ok(marshal::rebuild(payload))
10440}
10441
10442fn sleep_ticks(val: &RuntimeValue) -> Result<u64, String> {
10444 match val {
10445 RuntimeValue::Int(n) => Ok((*n).max(0) as u64),
10446 RuntimeValue::Duration(d) => Ok((*d).max(0) as u64),
10447 _ => Err(format!(
10448 "Sleep requires Duration or Int, got {}",
10449 val.type_name()
10450 )),
10451 }
10452}
10453
10454fn sleep_nanos(val: &RuntimeValue) -> Result<i64, String> {
10456 match val {
10457 RuntimeValue::Duration(nanos) => Ok(*nanos),
10458 RuntimeValue::Int(ms) => Ok(ms.wrapping_mul(1_000_000)),
10459 _ => Err(format!(
10460 "Sleep requires Duration or Int, got {}",
10461 val.type_name()
10462 )),
10463 }
10464}
10465
10466pub fn needs_async(stmts: &[Stmt], interner: &Interner) -> bool {
10467 stmts.iter().any(|s| stmt_needs_async(s, interner))
10468}
10469
10470fn stmt_needs_async(stmt: &Stmt, interner: &Interner) -> bool {
10471 match stmt {
10472 Stmt::ReadFrom { source, .. } => {
10473 matches!(source, ReadSource::File(_))
10474 }
10475 Stmt::WriteFile { .. } | Stmt::Sleep { .. } | Stmt::Mount { .. } => true,
10476 Stmt::Sync { .. } | Stmt::Listen { .. } | Stmt::ConnectTo { .. } => true,
10478 Stmt::Serve { .. } => true,
10480 Stmt::SendMessage { .. } | Stmt::AwaitMessage { .. } | Stmt::StreamMessage { .. } => true,
10482 Stmt::FunctionDef {
10486 name,
10487 is_native: true,
10488 ..
10489 } if matches!(
10490 interner.resolve(*name),
10491 "tcpConnect"
10492 | "tcpSend"
10493 | "tcpRecv"
10494 | "tcpRecvExact"
10495 | "tcpClose"
10496 | "tcpSetTimeout"
10497 | "tcpListen"
10498 | "tcpAccept"
10499 | "tcpListenerPort"
10500 | "tcpShutdownWrite"
10501 | "tcpConnectTls"
10502 | "tcpUpgradeTls"
10503 ) =>
10504 {
10505 true
10506 }
10507 Stmt::If {
10508 then_block,
10509 else_block,
10510 ..
10511 } => {
10512 needs_async(then_block, interner)
10513 || else_block
10514 .as_ref()
10515 .map_or(false, |b| needs_async(b, interner))
10516 }
10517 Stmt::While { body, .. } | Stmt::Repeat { body, .. } => needs_async(body, interner),
10518 Stmt::FunctionDef { body, .. } => needs_async(body, interner),
10519 Stmt::Zone { body, .. } => needs_async(body, interner),
10520 Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => needs_async(tasks, interner),
10521 Stmt::Inspect { arms, .. } => arms.iter().any(|arm| needs_async(arm.body, interner)),
10522 _ => false,
10523 }
10524}
10525
10526fn count_pi_args(term: &crate::kernel::Term) -> usize {
10530 use crate::kernel::Term;
10531 match term {
10532 Term::Pi { body_type, .. } => 1 + count_pi_args(body_type),
10533 _ => 0,
10534 }
10535}
10536
10537pub fn interp_nanos<'a>(stmts: &[Stmt<'a>], interner: &'a Interner, iters: usize) -> Option<u128> {
10545 {
10546 let mut it = Interpreter::new(interner);
10547 let _ = it.run_sync(stmts); }
10549 let mut best = u128::MAX;
10550 for _ in 0..iters {
10551 let mut it = Interpreter::new(interner);
10552 let t = std::time::Instant::now();
10553 let _ = it.run_sync(stmts);
10554 best = best.min(t.elapsed().as_nanos());
10555 }
10556 Some(best)
10557}
10558
10559#[derive(Debug, Clone)]
10565pub struct InterpreterResult {
10566 pub lines: Vec<String>,
10568 pub error: Option<String>,
10570}
10571
10572#[cfg(test)]
10573#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/ints_i32_repr_tests.rs"]
10574mod ints_i32_repr_tests;
10575
10576#[cfg(test)]
10577#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/structs_repr_tests.rs"]
10578mod structs_repr_tests;
10579
10580#[cfg(test)]
10581#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/enums_repr_tests.rs"]
10582mod enums_repr_tests;
10583
10584#[cfg(test)]
10585#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/float_comparison_tests.rs"]
10586mod float_comparison_tests;
10587
10588#[cfg(test)]
10589#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/page_seam_tests.rs"]
10590mod page_seam_tests;
10591
10592#[cfg(test)]
10593#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/interpreter/lowered_calls_tests.rs"]
10594mod lowered_calls_tests;