1use std::collections::{BTreeSet, HashMap};
17
18use serde::Serialize;
19
20use crate::vm::{disassemble, CompiledProgram, DebugVmState, DisasmLine, Vm, VmStep};
21
22const STEP_LIMIT: usize = 5_000_000;
25
26#[derive(Clone, Serialize)]
29pub struct DebugReg {
30 pub index: u16,
31 pub name: Option<String>,
32 pub kind: String,
34 pub value: String,
35 pub changed: bool,
37}
38
39#[derive(Clone, Serialize)]
42pub struct DebugFrame {
43 pub function: Option<String>,
44 pub base: usize,
45 pub registers: Vec<DebugReg>,
46}
47
48#[derive(Clone, Serialize, Debug)]
53pub struct HeapObject {
54 pub id: String,
56 pub kind: String,
57 pub summary: String,
58 pub storage: String,
61 pub rc: usize,
63 pub referenced_by: Vec<String>,
64 pub shared: bool,
66}
67
68#[derive(Clone, Serialize)]
70pub struct DebugSnapshot {
71 pub pc: usize,
73 pub op_text: String,
75 pub narration: String,
78 pub fol: String,
82 pub socratic: String,
87 pub op_reads: Vec<u16>,
89 pub op_writes: Option<u16>,
90 pub state: String,
92 pub error: Option<String>,
93 pub step: usize,
95 pub total_steps: usize,
97 pub total_ops: usize,
99 pub frames: Vec<DebugFrame>,
101 pub heap: Vec<HeapObject>,
103 pub globals: Vec<(String, String)>,
105 pub output: Vec<String>,
107 pub at_breakpoint: bool,
109}
110
111#[derive(Clone, Serialize)]
115pub struct VarTrace {
116 pub reg: u16,
118 pub name: String,
119 pub kind: String,
121 pub points: Vec<TimelinePoint>,
122}
123
124#[derive(Clone, Serialize)]
127pub struct TimelinePoint {
128 pub value: String,
129 pub present: bool,
132 pub changed: bool,
134}
135
136#[derive(Clone, Serialize)]
140pub struct VarTimeline {
141 pub start: usize,
143 pub steps: usize,
145 pub cursor: usize,
147 pub truncated: bool,
149 pub vars: Vec<VarTrace>,
150}
151
152#[derive(Clone, Serialize)]
156pub struct VarInsight {
157 pub name: String,
158 pub kind: String,
159 pub facts: Vec<String>,
160}
161
162#[derive(Clone, Serialize, Default)]
167pub struct ProvenFacts {
168 pub scalar: Option<String>,
169 pub int_range: Option<(i64, i64)>,
170 pub nonneg: bool,
171}
172
173impl From<crate::optimize::VarProvenFacts> for ProvenFacts {
174 fn from(v: crate::optimize::VarProvenFacts) -> Self {
175 ProvenFacts {
176 scalar: v.scalar.map(|s| format!("{s:?}")),
177 int_range: v.int_range,
178 nonneg: v.nonneg,
179 }
180 }
181}
182
183impl ProvenFacts {
184 fn labels(&self) -> Vec<String> {
187 let mut out = Vec::new();
188 match self.int_range {
189 Some((lo, hi)) => out.push(format!("\u{2208} [{lo}, {hi}]")),
190 None if self.nonneg => out.push("\u{2265} 0".to_string()),
191 None => {}
192 }
193 if let Some(s) = &self.scalar {
194 out.push(format!("type {s}"));
195 }
196 out
197 }
198}
199
200#[derive(Clone, Serialize)]
202pub struct ProvenInsight {
203 pub name: String,
204 pub facts: Vec<String>,
205}
206
207#[derive(Clone, Serialize, PartialEq, Debug)]
211pub enum ProofVerdict {
212 ProvenTrue,
213 ProvenFalse,
214 Unknown,
215}
216
217#[derive(Clone, Serialize)]
223pub struct AssertionResult {
224 pub query: String,
225 pub parsed: bool,
227 pub now: Option<bool>,
229 pub now_detail: String,
230 pub verdict: ProofVerdict,
232 pub verdict_detail: String,
233}
234
235enum Operand {
237 Var(String),
238 Int(i64),
239}
240
241#[derive(Clone, Copy)]
242enum Cmp {
243 Lt,
244 Le,
245 Gt,
246 Ge,
247 Eq,
248 Ne,
249}
250
251#[derive(Clone, Serialize)]
256pub struct CausalNode {
257 pub step: usize,
259 pub pc: usize,
261 pub op_text: String,
262 pub narration: String,
263 pub reg: u16,
265 pub name: Option<String>,
266 pub kind: String,
267 pub value: String,
268 pub inputs: Vec<CausalNode>,
270}
271
272const TIMELINE_MAX_STEPS: usize = 512;
275
276const PROVENANCE_MAX_DEPTH: usize = 24;
279const PROVENANCE_MAX_NODES: usize = 96;
280
281#[derive(Clone)]
285enum Outcome {
286 Running,
287 Done,
288 Blocked,
289 Error(String),
290}
291
292struct Frame {
294 state: DebugVmState,
295 outcome: Outcome,
296}
297
298pub struct Debugger {
306 program: CompiledProgram,
307 disasm: Vec<DisasmLine>,
308 history: Vec<Frame>,
309 cursor: usize,
310 breakpoints: BTreeSet<usize>,
311 proven: HashMap<String, ProvenFacts>,
315}
316
317impl Debugger {
318 pub fn from_source(src: &str) -> Result<Debugger, String> {
322 let (program, proven) = compile_source(src)?;
323 let disasm = disassemble(&program);
324 let initial = Vm::new(&program).save_debug_state();
325 Ok(Debugger {
326 program,
327 disasm,
328 history: vec![Frame {
329 state: initial,
330 outcome: Outcome::Running,
331 }],
332 cursor: 0,
333 breakpoints: BTreeSet::new(),
334 proven,
335 })
336 }
337
338 pub fn step(&mut self) {
340 self.run_one();
341 }
342
343 pub fn step_over(&mut self) {
345 let start = self.current_depth();
346 if !self.run_one() {
347 return;
348 }
349 let mut budget = STEP_LIMIT;
350 while self.is_paused() && self.current_depth() > start {
351 if self.at_breakpoint() {
352 break;
353 }
354 if !self.run_one() {
355 break;
356 }
357 budget -= 1;
358 if budget == 0 {
359 break;
360 }
361 }
362 }
363
364 pub fn step_out(&mut self) {
366 let start = self.current_depth();
367 let mut budget = STEP_LIMIT;
368 loop {
369 if !self.is_paused() || self.current_depth() < start {
370 break;
371 }
372 if !self.run_one() {
373 break;
374 }
375 if self.at_breakpoint() {
376 break;
377 }
378 budget -= 1;
379 if budget == 0 {
380 break;
381 }
382 }
383 }
384
385 pub fn resume(&mut self) {
387 let mut budget = STEP_LIMIT;
388 loop {
389 if !self.is_paused() {
390 break;
391 }
392 if !self.run_one() {
393 break;
394 }
395 if self.at_breakpoint() {
396 break;
397 }
398 budget -= 1;
399 if budget == 0 {
400 break;
401 }
402 }
403 }
404
405 pub fn reverse_resume(&mut self) {
409 while self.cursor > 0 {
410 self.cursor -= 1;
411 if self.breakpoints.contains(&self.current().pc()) {
412 break;
413 }
414 }
415 }
416
417 pub fn step_back(&mut self) {
419 self.cursor = self.cursor.saturating_sub(1);
420 }
421
422 pub fn seek(&mut self, step: usize) {
424 self.cursor = step.min(self.history.len().saturating_sub(1));
425 }
426
427 pub fn restart(&mut self) {
430 self.cursor = 0;
431 }
432
433 pub fn toggle_breakpoint(&mut self, pc: usize) {
435 if !self.breakpoints.remove(&pc) {
436 self.breakpoints.insert(pc);
437 }
438 }
439
440 pub fn set_breakpoint(&mut self, pc: usize) {
441 self.breakpoints.insert(pc);
442 }
443
444 pub fn clear_breakpoint(&mut self, pc: usize) {
445 self.breakpoints.remove(&pc);
446 }
447
448 pub fn breakpoints(&self) -> Vec<usize> {
449 self.breakpoints.iter().copied().collect()
450 }
451
452 pub fn disassembly(&self) -> &[DisasmLine] {
454 &self.disasm
455 }
456
457 pub fn is_running(&self) -> bool {
460 self.is_paused()
461 }
462
463 pub fn output(&self) -> &[String] {
466 self.current().lines()
467 }
468
469 pub fn error(&self) -> Option<&str> {
471 match &self.cur().outcome {
472 Outcome::Error(message) => Some(message),
473 _ => None,
474 }
475 }
476
477 pub fn snapshot(&self) -> DebugSnapshot {
479 let (view, heap_raw) = self.view_and_heap(self.current());
480 let prev_inner: HashMap<u16, String> = if self.cursor >= 1 {
485 let pv = self.view_of(&self.history[self.cursor - 1].state);
486 if pv.frames.len() == view.frames.len() {
487 pv.frames
488 .last()
489 .map(|f| {
490 f.registers
491 .iter()
492 .map(|(idx, _kind, val)| (*idx, val.clone()))
493 .collect()
494 })
495 .unwrap_or_default()
496 } else {
497 HashMap::new()
498 }
499 } else {
500 HashMap::new()
501 };
502 let frame_names = |func: Option<u16>| -> HashMap<u16, String> {
505 match func {
506 None => self.program.reg_names.iter().cloned().collect(),
507 Some(i) => self
508 .program
509 .fn_debug
510 .get(i as usize)
511 .map(|f| f.reg_names.iter().cloned().collect())
512 .unwrap_or_default(),
513 }
514 };
515 let function_name = |i: u16| {
516 self.program
517 .fn_debug
518 .get(i as usize)
519 .map(|f| f.name.clone())
520 .filter(|n| !n.is_empty())
521 .unwrap_or_else(|| format!("fn#{i}"))
522 };
523 let n = view.frames.len();
524 let frames: Vec<DebugFrame> = view
525 .frames
526 .iter()
527 .enumerate()
528 .map(|(fi, f)| {
529 let inner = fi + 1 == n;
530 let names = frame_names(f.func);
531 DebugFrame {
532 function: f.func.map(function_name),
533 base: f.base,
534 registers: f
535 .registers
536 .iter()
537 .map(|(idx, kind, val)| DebugReg {
538 index: *idx,
539 name: names.get(idx).cloned(),
540 kind: kind.clone(),
541 value: val.clone(),
542 changed: inner
543 && prev_inner.get(idx).map(|p| p != val).unwrap_or(false),
544 })
545 .collect(),
546 }
547 })
548 .collect();
549 let (state, error) = match &self.cur().outcome {
550 Outcome::Running => ("paused", None),
551 Outcome::Done => ("done", None),
552 Outcome::Blocked => ("blocked", None),
553 Outcome::Error(e) => ("error", Some(e.clone())),
554 };
555 let op_text = self
556 .disasm
557 .get(view.pc)
558 .map(|d| d.text.clone())
559 .unwrap_or_default();
560 let inner_regs: HashMap<u16, (Option<String>, String)> = frames
562 .last()
563 .map(|f: &DebugFrame| {
564 f.registers
565 .iter()
566 .map(|r| (r.index, (r.name.clone(), r.value.clone())))
567 .collect()
568 })
569 .unwrap_or_default();
570 let cur_op = self.program.code.get(view.pc).copied();
571 let (narration, op_reads, op_writes) = match (&self.cur().outcome, cur_op) {
572 (Outcome::Error(e), _) => (format!("error: {e}"), Vec::new(), None),
573 (Outcome::Done, _) => ("the program has finished".to_string(), Vec::new(), None),
574 (Outcome::Blocked, _) => (
575 "waiting on a concurrency operation".to_string(),
576 Vec::new(),
577 None,
578 ),
579 (Outcome::Running, Some(op)) => {
580 let io = crate::vm::op_io(&op);
581 (
582 narrate(&op, &inner_regs, &self.program),
583 io.reads,
584 io.writes,
585 )
586 }
587 _ => (String::new(), Vec::new(), None),
588 };
589 let fol = match (&self.cur().outcome, cur_op) {
590 (Outcome::Running, Some(op)) => fol_of_op(&op, &inner_regs, &self.program),
591 _ => String::new(),
592 };
593 let socratic = match (&self.cur().outcome, cur_op) {
594 (Outcome::Running, Some(op)) => socratic_of_op(&op, &inner_regs),
595 (Outcome::Done, _) => {
596 "The program has finished — did the result match what you expected?".to_string()
597 }
598 _ => String::new(),
599 };
600 let heap: Vec<HeapObject> = heap_raw
601 .iter()
602 .enumerate()
603 .map(|(i, o)| HeapObject {
604 id: format!("#{}", i + 1),
605 kind: o.kind.clone(),
606 summary: o.summary.clone(),
607 storage: o.storage.clone(),
608 rc: o.rc,
609 referenced_by: o.referenced_by.clone(),
610 shared: o.referenced_by.len() > 1,
611 })
612 .collect();
613 DebugSnapshot {
614 pc: view.pc,
615 op_text,
616 narration,
617 fol,
618 socratic,
619 op_reads,
620 op_writes,
621 state: state.to_string(),
622 error,
623 step: self.cursor,
624 total_steps: self.history.len().saturating_sub(1),
625 total_ops: self.disasm.len(),
626 frames,
627 heap,
628 globals: view.globals.clone(),
629 output: view.output.clone(),
630 at_breakpoint: self.at_breakpoint(),
631 }
632 }
633
634 pub fn variable_timeline(&self) -> VarTimeline {
639 let names = self.main_names();
640 let total = self.history.len();
641 let start = total.saturating_sub(TIMELINE_MAX_STEPS);
642 let truncated = start > 0;
643 let window = &self.history[start..];
644 let n = window.len();
645
646 let mut order: Vec<u16> = names.keys().copied().collect();
647 order.sort_unstable();
648 let mut series: HashMap<u16, Vec<Option<(String, String)>>> =
650 order.iter().map(|r| (*r, vec![None; n])).collect();
651 for (col, frame) in window.iter().enumerate() {
652 let view = self.view_of(&frame.state);
653 if let Some(main) = view.frames.iter().find(|f| f.func.is_none()) {
654 for (idx, kind, val) in &main.registers {
655 if let Some(slot) = series.get_mut(idx) {
656 slot[col] = Some((kind.clone(), val.clone()));
657 }
658 }
659 }
660 }
661
662 let vars = order
663 .iter()
664 .map(|reg| {
665 let name = names.get(reg).cloned().unwrap_or_else(|| format!("R{reg}"));
666 let raw = &series[reg];
667 let mut kind = String::new();
668 let mut points = Vec::with_capacity(n);
669 let mut prev: Option<String> = None;
670 for cell in raw {
671 match cell {
672 Some((k, v)) => {
673 if k != "Nothing" || kind.is_empty() {
676 kind = k.clone();
677 }
678 let changed = matches!(&prev, Some(p) if p != v);
681 points.push(TimelinePoint {
682 value: v.clone(),
683 present: true,
684 changed,
685 });
686 prev = Some(v.clone());
687 }
688 None => {
689 points.push(TimelinePoint {
690 value: String::new(),
691 present: false,
692 changed: false,
693 });
694 prev = None;
695 }
696 }
697 }
698 VarTrace {
699 reg: *reg,
700 name,
701 kind,
702 points,
703 }
704 })
705 .filter(|t| t.points.iter().any(|p| p.present))
707 .collect();
708
709 VarTimeline {
710 start,
711 steps: n,
712 cursor: self.cursor,
713 truncated,
714 vars,
715 }
716 }
717
718 pub fn observed_invariants(&self) -> Vec<VarInsight> {
723 let tl = self.variable_timeline();
724 tl.vars
725 .iter()
726 .filter_map(|v| {
727 let first = v.points.iter().position(|p| p.present && p.changed)?;
730 let vals: Vec<&str> = v.points[first..]
731 .iter()
732 .filter(|p| p.present)
733 .map(|p| p.value.as_str())
734 .collect();
735 if vals.is_empty() {
736 return None;
737 }
738 let distinct: BTreeSet<&str> = vals.iter().copied().collect();
739 let nums: Option<Vec<f64>> = vals.iter().map(|s| s.parse::<f64>().ok()).collect();
740 let mut facts = Vec::new();
741 if distinct.len() == 1 {
742 facts.push(format!("constant {}", vals[0]));
743 } else {
744 if let Some(ns) = &nums {
745 let min = ns.iter().cloned().fold(f64::INFINITY, f64::min);
746 let max = ns.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
747 facts.push(format!("range [{}, {}]", fmt_num(min), fmt_num(max)));
748 if ns.windows(2).all(|w| w[1] >= w[0]) {
749 facts.push("only increases".to_string());
750 } else if ns.windows(2).all(|w| w[1] <= w[0]) {
751 facts.push("only decreases".to_string());
752 }
753 }
754 facts.push(format!("{} distinct values", distinct.len()));
755 }
756 Some(VarInsight {
757 name: v.name.clone(),
758 kind: v.kind.clone(),
759 facts,
760 })
761 })
762 .collect()
763 }
764
765 pub fn proven_invariants(&self) -> Vec<ProvenInsight> {
770 let mut out: Vec<ProvenInsight> = self
771 .proven
772 .iter()
773 .filter_map(|(name, pf)| {
774 let facts = pf.labels();
775 if facts.is_empty() {
776 None
777 } else {
778 Some(ProvenInsight {
779 name: name.clone(),
780 facts,
781 })
782 }
783 })
784 .collect();
785 out.sort_by(|a, b| a.name.cmp(&b.name));
786 out
787 }
788
789 pub fn assert_at_cursor(&self, predicate: &str) -> AssertionResult {
796 let query = predicate.trim().to_string();
797 let Some((lhs, cmp, rhs)) = parse_comparison(&query) else {
798 return AssertionResult {
799 query,
800 parsed: false,
801 now: None,
802 now_detail: "couldn't parse \u{2014} try a comparison like `x < y` or `x >= 0`"
803 .to_string(),
804 verdict: ProofVerdict::Unknown,
805 verdict_detail: String::new(),
806 };
807 };
808
809 let frame = self.snapshot();
811 let live = |o: &Operand| -> Option<i64> {
812 match o {
813 Operand::Int(c) => Some(*c),
814 Operand::Var(name) => frame
815 .frames
816 .last()
817 .and_then(|f| {
818 f.registers
819 .iter()
820 .find(|r| r.name.as_deref() == Some(name.as_str()))
821 })
822 .and_then(|r| r.value.parse::<i64>().ok()),
823 }
824 };
825 let now = match (live(&lhs), live(&rhs)) {
826 (Some(a), Some(b)) => Some(apply_cmp(a, cmp, b)),
827 _ => None,
828 };
829 let now_detail = {
830 let mut parts = Vec::new();
831 for o in [&lhs, &rhs] {
832 if let Operand::Var(name) = o {
833 match live(o) {
834 Some(v) => parts.push(format!("{name} = {v}")),
835 None => parts.push(format!("{name} = ?")),
836 }
837 }
838 }
839 parts.join(", ")
840 };
841
842 let prange = |o: &Operand| -> Option<(i64, i64)> {
844 match o {
845 Operand::Int(c) => Some((*c, *c)),
846 Operand::Var(name) => self.proven.get(name).and_then(|pf| pf.int_range),
847 }
848 };
849 let (verdict, verdict_detail) = match (prange(&lhs), prange(&rhs)) {
850 (Some(a), Some(b)) => {
851 let v = entail(a, cmp, b);
852 let mut srcs = Vec::new();
853 if let Operand::Var(n) = &lhs {
854 srcs.push(format!("{n} \u{2208} [{}, {}]", a.0, a.1));
855 }
856 if let Operand::Var(n) = &rhs {
857 srcs.push(format!("{n} \u{2208} [{}, {}]", b.0, b.1));
858 }
859 let detail = match v {
860 ProofVerdict::Unknown => "the proven ranges don't decide it".to_string(),
861 _ => format!("from {}", srcs.join(", ")),
862 };
863 (v, detail)
864 }
865 _ => (
866 ProofVerdict::Unknown,
867 "no proven range for one of the terms".to_string(),
868 ),
869 };
870
871 AssertionResult {
872 query,
873 parsed: true,
874 now,
875 now_detail,
876 verdict,
877 verdict_detail,
878 }
879 }
880
881 pub fn provenance(&self, reg: u16) -> Option<CausalNode> {
886 let mut budget = PROVENANCE_MAX_NODES;
887 self.trace_value(reg, self.cursor, PROVENANCE_MAX_DEPTH, &mut budget)
888 }
889
890 fn trace_value(
894 &self,
895 reg: u16,
896 at_step: usize,
897 depth: usize,
898 budget: &mut usize,
899 ) -> Option<CausalNode> {
900 let (name, kind, value) = self.reg_value_at(at_step, reg)?;
901 if *budget == 0 || depth == 0 {
902 return Some(CausalNode {
903 step: 0,
904 pc: 0,
905 op_text: String::new(),
906 narration: String::new(),
907 reg,
908 name,
909 kind,
910 value,
911 inputs: Vec::new(),
912 });
913 }
914 *budget -= 1;
915
916 for i in (1..=at_step).rev() {
919 let producer_pc = self.history[i - 1].state.pc();
920 let Some(op) = self.program.code.get(producer_pc).copied() else {
921 continue;
922 };
923 let io = crate::vm::op_io(&op);
924 if io.writes != Some(reg) {
925 continue;
926 }
927 if let crate::vm::Op::Move { src, .. } = op {
932 if let Some(mut child) = self.trace_value(src, i - 1, depth, budget) {
933 if let Some((nm, k, v)) = self.reg_value_at(i, reg) {
934 child.reg = reg;
935 child.name = nm;
936 child.kind = k;
937 child.value = v;
938 }
939 return Some(child);
940 }
941 }
942 let (pname, pkind, pvalue) = self
945 .reg_value_at(i, reg)
946 .unwrap_or_else(|| (name.clone(), kind.clone(), value.clone()));
947 let inner = self.input_regs(i - 1);
948 let narration = narrate(&op, &inner, &self.program);
949 let op_text = self
950 .disasm
951 .get(producer_pc)
952 .map(|d| d.text.clone())
953 .unwrap_or_default();
954 let inputs = io
955 .reads
956 .iter()
957 .filter_map(|r| self.trace_value(*r, i - 1, depth - 1, budget))
958 .collect();
959 return Some(CausalNode {
960 step: i,
961 pc: producer_pc,
962 op_text,
963 narration,
964 reg,
965 name: pname,
966 kind: pkind,
967 value: pvalue,
968 inputs,
969 });
970 }
971
972 Some(CausalNode {
974 step: 0,
975 pc: 0,
976 op_text: String::new(),
977 narration: String::new(),
978 reg,
979 name,
980 kind,
981 value,
982 inputs: Vec::new(),
983 })
984 }
985
986 fn main_names(&self) -> HashMap<u16, String> {
990 self.program.reg_names.iter().cloned().collect()
991 }
992
993 fn reg_value_at(&self, step: usize, reg: u16) -> Option<(Option<String>, String, String)> {
996 let frame = self.history.get(step)?;
997 let view = self.view_of(&frame.state);
998 let f = view.frames.last()?;
999 let is_main = f.func.is_none();
1000 f.registers
1001 .iter()
1002 .find(|(idx, _, _)| *idx == reg)
1003 .map(|(idx, kind, val)| {
1004 let name = if is_main {
1005 self.main_names().get(idx).cloned()
1006 } else {
1007 None
1008 };
1009 (name, kind.clone(), val.clone())
1010 })
1011 }
1012
1013 fn input_regs(&self, step: usize) -> HashMap<u16, (Option<String>, String)> {
1016 let names = self.main_names();
1017 let Some(frame) = self.history.get(step) else {
1018 return HashMap::new();
1019 };
1020 let view = self.view_of(&frame.state);
1021 let Some(f) = view.frames.last() else {
1022 return HashMap::new();
1023 };
1024 let is_main = f.func.is_none();
1025 f.registers
1026 .iter()
1027 .map(|(idx, _, val)| {
1028 let name = if is_main {
1029 names.get(idx).cloned()
1030 } else {
1031 None
1032 };
1033 (*idx, (name, val.clone()))
1034 })
1035 .collect()
1036 }
1037
1038 fn cur(&self) -> &Frame {
1039 &self.history[self.cursor]
1040 }
1041
1042 fn current(&self) -> &DebugVmState {
1043 &self.cur().state
1044 }
1045
1046 fn is_paused(&self) -> bool {
1047 matches!(self.cur().outcome, Outcome::Running)
1048 }
1049
1050 fn current_depth(&self) -> usize {
1051 self.current().call_depth()
1052 }
1053
1054 fn at_breakpoint(&self) -> bool {
1055 self.is_paused() && self.breakpoints.contains(&self.current().pc())
1056 }
1057
1058 fn view_of(&self, st: &DebugVmState) -> crate::vm::DebugView {
1060 let mut vm = Vm::new(&self.program);
1061 vm.restore_debug_state(st.clone());
1062 vm.debug_view()
1063 }
1064
1065 fn view_and_heap(
1068 &self,
1069 st: &DebugVmState,
1070 ) -> (crate::vm::DebugView, Vec<crate::vm::HeapObjView>) {
1071 let mut vm = Vm::new(&self.program);
1072 vm.restore_debug_state(st.clone());
1073 (vm.debug_view(), vm.debug_heap())
1074 }
1075
1076 fn run_one(&mut self) -> bool {
1081 if !self.is_paused() {
1082 return false;
1083 }
1084 if self.cursor + 1 < self.history.len() {
1085 self.cursor += 1;
1086 return self.is_paused();
1087 }
1088 let cur_state = self.current().clone();
1089 let mut vm = Vm::new(&self.program);
1090 vm.restore_debug_state(cur_state.clone());
1091 let frame = match vm.run_steps(1) {
1092 Ok(VmStep::Paused) => Frame {
1093 state: vm.save_debug_state(),
1094 outcome: Outcome::Running,
1095 },
1096 Ok(VmStep::Done(_)) => Frame {
1097 state: vm.save_debug_state(),
1098 outcome: Outcome::Done,
1099 },
1100 Ok(VmStep::Blocked) => Frame {
1101 state: vm.save_debug_state(),
1102 outcome: Outcome::Blocked,
1103 },
1104 Err(e) => Frame {
1106 state: cur_state,
1107 outcome: Outcome::Error(e),
1108 },
1109 };
1110 self.history.push(frame);
1111 self.cursor += 1;
1112 self.is_paused()
1113 }
1114}
1115
1116fn narrate(
1120 op: &crate::vm::Op,
1121 regs: &HashMap<u16, (Option<String>, String)>,
1122 prog: &CompiledProgram,
1123) -> String {
1124 use crate::vm::Op;
1125 let name = |r: u16| {
1126 regs.get(&r)
1127 .and_then(|(n, _)| n.clone())
1128 .unwrap_or_else(|| format!("R{r}"))
1129 };
1130 let operand = |r: u16| match regs.get(&r) {
1131 Some((_, v)) if !v.is_empty() => format!("{}({})", name(r), v),
1132 _ => name(r),
1133 };
1134 match *op {
1135 Op::LoadConst { dst, idx } => {
1136 format!(
1137 "load {} into {}",
1138 crate::vm::format_constant(prog, idx),
1139 name(dst)
1140 )
1141 }
1142 Op::Move { dst, src } => format!("copy {} into {}", operand(src), name(dst)),
1143 Op::Add { dst, lhs, rhs } => format!(
1144 "add {} + {} \u{2192} {}",
1145 operand(lhs),
1146 operand(rhs),
1147 name(dst)
1148 ),
1149 Op::Sub { dst, lhs, rhs } => format!(
1150 "subtract {} - {} \u{2192} {}",
1151 operand(lhs),
1152 operand(rhs),
1153 name(dst)
1154 ),
1155 Op::Mul { dst, lhs, rhs } => format!(
1156 "multiply {} \u{00d7} {} \u{2192} {}",
1157 operand(lhs),
1158 operand(rhs),
1159 name(dst)
1160 ),
1161 Op::Div { dst, lhs, rhs } | Op::ExactDiv { dst, lhs, rhs } => {
1162 format!(
1163 "divide {} \u{00f7} {} \u{2192} {}",
1164 operand(lhs),
1165 operand(rhs),
1166 name(dst)
1167 )
1168 }
1169 Op::Mod { dst, lhs, rhs } => format!(
1170 "{} mod {} \u{2192} {}",
1171 operand(lhs),
1172 operand(rhs),
1173 name(dst)
1174 ),
1175 Op::Lt { dst, lhs, rhs } => format!(
1176 "is {} < {}? \u{2192} {}",
1177 operand(lhs),
1178 operand(rhs),
1179 name(dst)
1180 ),
1181 Op::Gt { dst, lhs, rhs } => format!(
1182 "is {} > {}? \u{2192} {}",
1183 operand(lhs),
1184 operand(rhs),
1185 name(dst)
1186 ),
1187 Op::LtEq { dst, lhs, rhs } => format!(
1188 "is {} <= {}? \u{2192} {}",
1189 operand(lhs),
1190 operand(rhs),
1191 name(dst)
1192 ),
1193 Op::GtEq { dst, lhs, rhs } => format!(
1194 "is {} >= {}? \u{2192} {}",
1195 operand(lhs),
1196 operand(rhs),
1197 name(dst)
1198 ),
1199 Op::Eq { dst, lhs, rhs } => format!(
1200 "is {} == {}? \u{2192} {}",
1201 operand(lhs),
1202 operand(rhs),
1203 name(dst)
1204 ),
1205 Op::NotEq { dst, lhs, rhs } => format!(
1206 "is {} != {}? \u{2192} {}",
1207 operand(lhs),
1208 operand(rhs),
1209 name(dst)
1210 ),
1211 Op::AddAssign { dst, src } => format!("append {} onto {}", operand(src), name(dst)),
1212 Op::Not { dst, src } => format!("negate {} \u{2192} {}", operand(src), name(dst)),
1213 Op::Show { src } => format!("print {}", operand(src)),
1214 Op::Return { src } => format!("return {}", operand(src)),
1215 Op::ReturnNothing => "return".to_string(),
1216 Op::Jump { target } => format!("jump to step {target}"),
1217 Op::JumpIfFalse { cond, target } => {
1218 format!("if {} is false, jump to {target}", operand(cond))
1219 }
1220 Op::JumpIfTrue { cond, target } => {
1221 format!("if {} is true, jump to {target}", operand(cond))
1222 }
1223 Op::Index {
1224 dst,
1225 collection,
1226 index,
1227 }
1228 | Op::IndexUnchecked {
1229 dst,
1230 collection,
1231 index,
1232 } => {
1233 format!(
1234 "read {}[{}] \u{2192} {}",
1235 name(collection),
1236 operand(index),
1237 name(dst)
1238 )
1239 }
1240 Op::SetIndex {
1241 collection,
1242 index,
1243 value,
1244 }
1245 | Op::SetIndexUnchecked {
1246 collection,
1247 index,
1248 value,
1249 } => {
1250 format!(
1251 "set {}[{}] = {}",
1252 name(collection),
1253 operand(index),
1254 operand(value)
1255 )
1256 }
1257 Op::Length { dst, collection } => {
1258 format!("count {} \u{2192} {}", name(collection), name(dst))
1259 }
1260 Op::ListPush { list, value } => format!("push {} onto {}", operand(value), name(list)),
1261 Op::NewEmptyList { dst } | Op::NewEmptyListI32 { dst } => {
1262 format!("make an empty list \u{2192} {}", name(dst))
1263 }
1264 Op::NewEmptyListFixed { dst, capacity } => {
1265 format!(
1266 "make an empty list with capacity {capacity} \u{2192} {}",
1267 name(dst)
1268 )
1269 }
1270 Op::NewEmptyListWithCapacity { dst, capacity } => {
1271 format!(
1272 "make an empty list with capacity {} \u{2192} {}",
1273 operand(capacity),
1274 name(dst)
1275 )
1276 }
1277 Op::NewEmptyMapWithCapacity { dst, capacity } => {
1278 format!(
1279 "make an empty map with capacity {} \u{2192} {}",
1280 operand(capacity),
1281 name(dst)
1282 )
1283 }
1284 Op::Call { .. } => "call a function".to_string(),
1285 Op::Halt => "halt \u{2014} the program is done".to_string(),
1286 _ => String::new(),
1287 }
1288}
1289
1290fn fol_of_op(
1296 op: &crate::vm::Op,
1297 regs: &HashMap<u16, (Option<String>, String)>,
1298 prog: &CompiledProgram,
1299) -> String {
1300 use crate::vm::Op;
1301 let name = |r: u16| {
1302 regs.get(&r)
1303 .and_then(|(n, _)| n.clone())
1304 .unwrap_or_else(|| format!("R{r}"))
1305 };
1306 match *op {
1307 Op::LoadConst { dst, idx } => {
1308 format!("{} = {}", name(dst), crate::vm::format_constant(prog, idx))
1309 }
1310 Op::Move { dst, src } => format!("{} = {}", name(dst), name(src)),
1311 Op::Add { dst, lhs, rhs } => format!("{} = {} + {}", name(dst), name(lhs), name(rhs)),
1312 Op::Sub { dst, lhs, rhs } => {
1313 format!("{} = {} \u{2212} {}", name(dst), name(lhs), name(rhs))
1314 }
1315 Op::Mul { dst, lhs, rhs } => {
1316 format!("{} = {} \u{00d7} {}", name(dst), name(lhs), name(rhs))
1317 }
1318 Op::Div { dst, lhs, rhs } | Op::ExactDiv { dst, lhs, rhs } => {
1319 format!("{} = {} \u{00f7} {}", name(dst), name(lhs), name(rhs))
1320 }
1321 Op::Mod { dst, lhs, rhs } => format!("{} = {} mod {}", name(dst), name(lhs), name(rhs)),
1322 Op::Lt { dst, lhs, rhs } => {
1323 format!("{} \u{27fa} ({} < {})", name(dst), name(lhs), name(rhs))
1324 }
1325 Op::Gt { dst, lhs, rhs } => {
1326 format!("{} \u{27fa} ({} > {})", name(dst), name(lhs), name(rhs))
1327 }
1328 Op::LtEq { dst, lhs, rhs } => format!(
1329 "{} \u{27fa} ({} \u{2264} {})",
1330 name(dst),
1331 name(lhs),
1332 name(rhs)
1333 ),
1334 Op::GtEq { dst, lhs, rhs } => format!(
1335 "{} \u{27fa} ({} \u{2265} {})",
1336 name(dst),
1337 name(lhs),
1338 name(rhs)
1339 ),
1340 Op::Eq { dst, lhs, rhs } => {
1341 format!("{} \u{27fa} ({} = {})", name(dst), name(lhs), name(rhs))
1342 }
1343 Op::NotEq { dst, lhs, rhs } => format!(
1344 "{} \u{27fa} ({} \u{2260} {})",
1345 name(dst),
1346 name(lhs),
1347 name(rhs)
1348 ),
1349 Op::Not { dst, src } => format!("{} \u{27fa} \u{00ac}{}", name(dst), name(src)),
1350 Op::AddAssign { dst, src } => format!(
1351 "{} \u{2254} {} \u{29fa} {}",
1352 name(dst),
1353 name(dst),
1354 name(src)
1355 ),
1356 Op::Index {
1357 dst,
1358 collection,
1359 index,
1360 }
1361 | Op::IndexUnchecked {
1362 dst,
1363 collection,
1364 index,
1365 } => {
1366 format!("{} = {}[{}]", name(dst), name(collection), name(index))
1367 }
1368 Op::SetIndex {
1369 collection,
1370 index,
1371 value,
1372 }
1373 | Op::SetIndexUnchecked {
1374 collection,
1375 index,
1376 value,
1377 } => {
1378 format!(
1379 "{}[{}] \u{2254} {}",
1380 name(collection),
1381 name(index),
1382 name(value)
1383 )
1384 }
1385 Op::Length { dst, collection } => format!("{} = |{}|", name(dst), name(collection)),
1386 Op::ListPush { list, value } => format!(
1387 "{} \u{2254} {} \u{2295} {}",
1388 name(list),
1389 name(list),
1390 name(value)
1391 ),
1392 Op::NewEmptyList { dst }
1393 | Op::NewEmptyListI32 { dst }
1394 | Op::NewEmptyListFixed { dst, .. }
1395 | Op::NewEmptyListWithCapacity { dst, .. } => format!("{} = \u{2205}", name(dst)),
1396 Op::NewEmptyMapWithCapacity { dst, .. } => format!("{} = \u{2205}", name(dst)),
1397 Op::Return { src } => format!("result = {}", name(src)),
1398 Op::Jump { target } => format!("goto {target}"),
1399 Op::JumpIfFalse { cond, target } => {
1400 format!("\u{00ac}{} \u{2192} goto {target}", name(cond))
1401 }
1402 Op::JumpIfTrue { cond, target } => format!("{} \u{2192} goto {target}", name(cond)),
1403 _ => String::new(),
1404 }
1405}
1406
1407fn socratic_of_op(op: &crate::vm::Op, regs: &HashMap<u16, (Option<String>, String)>) -> String {
1413 use crate::vm::Op;
1414 let name = |r: u16| {
1415 regs.get(&r)
1416 .and_then(|(n, _)| n.clone())
1417 .unwrap_or_else(|| format!("R{r}"))
1418 };
1419 let nv = |r: u16| match regs.get(&r) {
1421 Some((_, v)) if !v.is_empty() => format!("{} ({})", name(r), v),
1422 _ => name(r),
1423 };
1424 match *op {
1425 Op::Add { lhs, rhs, .. } => {
1426 format!("{} and {} \u{2014} what is their sum?", nv(lhs), nv(rhs))
1427 }
1428 Op::Sub { lhs, rhs, .. } => format!("{} minus {} \u{2014} what's left?", nv(lhs), nv(rhs)),
1429 Op::Mul { lhs, rhs, .. } => {
1430 format!("{} times {} \u{2014} what do you get?", nv(lhs), nv(rhs))
1431 }
1432 Op::Div { lhs, rhs, .. } | Op::ExactDiv { lhs, rhs, .. } => {
1433 format!(
1434 "{} divided by {} \u{2014} what is the quotient?",
1435 nv(lhs),
1436 nv(rhs)
1437 )
1438 }
1439 Op::Mod { lhs, rhs, .. } => {
1440 format!("What remains when {} is divided by {}?", nv(lhs), nv(rhs))
1441 }
1442 Op::Lt { lhs, rhs, .. } => format!("Is {} less than {}?", nv(lhs), nv(rhs)),
1443 Op::Gt { lhs, rhs, .. } => format!("Is {} greater than {}?", nv(lhs), nv(rhs)),
1444 Op::LtEq { lhs, rhs, .. } => format!("Is {} at most {}?", nv(lhs), nv(rhs)),
1445 Op::GtEq { lhs, rhs, .. } => format!("Is {} at least {}?", nv(lhs), nv(rhs)),
1446 Op::Eq { lhs, rhs, .. } => format!("Does {} equal {}?", nv(lhs), nv(rhs)),
1447 Op::NotEq { lhs, rhs, .. } => format!("Are {} and {} different?", nv(lhs), nv(rhs)),
1448 Op::Not { src, .. } => format!("{} \u{2014} what is its negation?", nv(src)),
1449 Op::JumpIfFalse { cond, .. } => {
1450 format!(
1451 "{} \u{2014} will the program take this branch, or fall through?",
1452 nv(cond)
1453 )
1454 }
1455 Op::JumpIfTrue { cond, .. } => {
1456 format!(
1457 "{} \u{2014} is the condition met, so the program jumps?",
1458 nv(cond)
1459 )
1460 }
1461 Op::Index {
1462 collection, index, ..
1463 }
1464 | Op::IndexUnchecked {
1465 collection, index, ..
1466 } => {
1467 format!(
1468 "What sits at position {} of {}?",
1469 nv(index),
1470 name(collection)
1471 )
1472 }
1473 Op::Length { collection, .. } => format!("How many items does {} hold?", name(collection)),
1474 Op::Return { src } => {
1475 format!(
1476 "The result is about to be {} \u{2014} is that what you predicted?",
1477 nv(src)
1478 )
1479 }
1480 _ => String::new(),
1481 }
1482}
1483
1484fn parse_comparison(s: &str) -> Option<(Operand, Cmp, Operand)> {
1488 for (sym, cmp) in [
1489 ("<=", Cmp::Le),
1490 (">=", Cmp::Ge),
1491 ("==", Cmp::Eq),
1492 ("!=", Cmp::Ne),
1493 ] {
1494 if let Some(i) = s.find(sym) {
1495 return build_cmp(&s[..i], &s[i + sym.len()..], cmp);
1496 }
1497 }
1498 for (sym, cmp) in [('<', Cmp::Lt), ('>', Cmp::Gt), ('=', Cmp::Eq)] {
1499 if let Some(i) = s.find(sym) {
1500 return build_cmp(&s[..i], &s[i + 1..], cmp);
1501 }
1502 }
1503 None
1504}
1505
1506fn build_cmp(l: &str, r: &str, cmp: Cmp) -> Option<(Operand, Cmp, Operand)> {
1507 Some((operand_of(l)?, cmp, operand_of(r)?))
1508}
1509
1510fn operand_of(s: &str) -> Option<Operand> {
1511 let t = s.trim();
1512 if t.is_empty() {
1513 return None;
1514 }
1515 Some(match t.parse::<i64>() {
1516 Ok(n) => Operand::Int(n),
1517 Err(_) => Operand::Var(t.to_string()),
1518 })
1519}
1520
1521fn apply_cmp(a: i64, cmp: Cmp, b: i64) -> bool {
1522 match cmp {
1523 Cmp::Lt => a < b,
1524 Cmp::Le => a <= b,
1525 Cmp::Gt => a > b,
1526 Cmp::Ge => a >= b,
1527 Cmp::Eq => a == b,
1528 Cmp::Ne => a != b,
1529 }
1530}
1531
1532fn entail((al, ah): (i64, i64), cmp: Cmp, (bl, bh): (i64, i64)) -> ProofVerdict {
1536 use ProofVerdict::{ProvenFalse, ProvenTrue, Unknown};
1537 let singleton_eq = al == ah && bl == bh && al == bl;
1538 let disjoint = ah < bl || bh < al;
1539 match cmp {
1540 Cmp::Lt => {
1541 if ah < bl {
1542 ProvenTrue
1543 } else if al >= bh {
1544 ProvenFalse
1545 } else {
1546 Unknown
1547 }
1548 }
1549 Cmp::Le => {
1550 if ah <= bl {
1551 ProvenTrue
1552 } else if al > bh {
1553 ProvenFalse
1554 } else {
1555 Unknown
1556 }
1557 }
1558 Cmp::Gt => {
1559 if al > bh {
1560 ProvenTrue
1561 } else if ah <= bl {
1562 ProvenFalse
1563 } else {
1564 Unknown
1565 }
1566 }
1567 Cmp::Ge => {
1568 if al >= bh {
1569 ProvenTrue
1570 } else if ah < bl {
1571 ProvenFalse
1572 } else {
1573 Unknown
1574 }
1575 }
1576 Cmp::Eq => {
1577 if singleton_eq {
1578 ProvenTrue
1579 } else if disjoint {
1580 ProvenFalse
1581 } else {
1582 Unknown
1583 }
1584 }
1585 Cmp::Ne => {
1586 if disjoint {
1587 ProvenTrue
1588 } else if singleton_eq {
1589 ProvenFalse
1590 } else {
1591 Unknown
1592 }
1593 }
1594 }
1595}
1596
1597fn fmt_num(n: f64) -> String {
1600 if n.fract() == 0.0 && n.abs() < 9.007e15 {
1601 format!("{}", n as i64)
1602 } else {
1603 format!("{n}")
1604 }
1605}
1606
1607fn compile_source(src: &str) -> Result<(CompiledProgram, HashMap<String, ProvenFacts>), String> {
1618 crate::ui_bridge::with_parsed_program(src, |parsed, interner| {
1619 let (stmts, types, _policies) = parsed?;
1620 let program = crate::vm::Compiler::compile_for_debug(stmts, interner, Some(types))?;
1621 let facts = crate::optimize::oracle_analyze_with(stmts, interner);
1622 let proven = facts
1623 .summarize_variables(stmts)
1624 .into_iter()
1625 .map(|(sym, vf)| (interner.resolve(sym).to_string(), ProvenFacts::from(vf)))
1626 .collect();
1627 Ok((program, proven))
1628 })
1629}
1630
1631#[cfg(test)]
1632#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/debug/tests.rs"]
1633mod tests;