1use std::collections::{BTreeSet, HashMap, VecDeque};
7
8use crate::program::{Program, StopInfo, StopKind};
9use crate::registry::Registry;
10use crate::value::{Ty, Value};
11use crate::vm::{
12 DEFAULT_SEED, Input, Snapshot, StateKey, Vm, VmConfig, VmError, VmErrorKind, Yield,
13};
14
15pub const DEFAULT_MAX_STATES: usize = 100_000;
17
18#[non_exhaustive]
20#[derive(Debug, Clone)]
21pub struct ExploreConfig {
22 pub vm: VmConfig,
25 pub seeds: Vec<u64>,
27 pub max_states: usize,
29}
30
31impl Default for ExploreConfig {
32 fn default() -> Self {
33 Self {
34 vm: VmConfig::default(),
35 seeds: vec![DEFAULT_SEED],
36 max_states: DEFAULT_MAX_STATES,
37 }
38 }
39}
40
41#[non_exhaustive]
43#[derive(Debug, Clone, PartialEq)]
44pub struct ExploreStep {
45 pub stop: String,
47 pub command: String,
49 pub kind: StopKind,
51 pub answer: Value,
53 pub option_id: Option<String>,
55}
56
57#[non_exhaustive]
59#[derive(Debug, Clone, PartialEq)]
60pub struct TestPath {
61 pub name: String,
63 pub seed: u64,
65 pub steps: Vec<ExploreStep>,
67}
68
69#[non_exhaustive]
71#[derive(Debug, Clone, PartialEq)]
72pub struct ErrorPath {
73 pub seed: u64,
75 pub steps: Vec<ExploreStep>,
77 pub error: VmError,
79}
80
81#[non_exhaustive]
83#[derive(Debug, Clone, PartialEq)]
84pub struct StuckPath {
85 pub seed: u64,
87 pub steps: Vec<ExploreStep>,
89 pub stop: String,
91 pub command: String,
93}
94
95#[non_exhaustive]
97#[derive(Debug, Clone, Default)]
98pub struct ExploreReport {
99 pub paths: Vec<TestPath>,
101 pub errors: Vec<ErrorPath>,
103 pub unanswered: Vec<StuckPath>,
105 pub unreached_stops: Vec<String>,
107 pub unchosen_options: Vec<String>,
109 pub unreached_labels: Vec<String>,
111 pub states: usize,
113 pub truncated: bool,
115}
116
117pub fn explore(
126 program: &Program,
127 registry: &Registry,
128 config: &ExploreConfig,
129 answers: &mut dyn FnMut(&Yield) -> Option<Vec<Value>>,
130) -> Result<ExploreReport, VmError> {
131 let mut ex = Explorer::new(program, registry, config, answers);
132 let default_seeds = [DEFAULT_SEED];
133 let seeds: &[u64] = if config.seeds.is_empty() {
134 &default_seeds
135 } else {
136 &config.seeds
137 };
138 for &seed in seeds {
139 if ex.truncated {
140 break;
141 }
142 ex.explore_seed(seed, seeds.len() > 1)?;
143 }
144 Ok(ex.finish())
145}
146
147const END: usize = 0;
149
150struct Edge {
151 from: usize,
152 to: usize,
153 step: ExploreStep,
154 name_part: Option<String>,
156}
157
158#[derive(Default)]
159struct Node {
160 parent: Option<usize>,
162 next: Option<usize>,
164}
165
166struct Frame {
167 node: usize,
168 snap: Snapshot,
169 persistent: Vec<u8>,
170 label: usize,
171 ordinal: u32,
172 name: String,
173 command: String,
174 kind: StopKind,
175 candidates: Vec<Value>,
176 origins: Vec<u32>,
178}
179
180struct Explorer<'p, 'f> {
181 program: &'p Program,
182 registry: &'p Registry,
183 config: &'p ExploreConfig,
184 answers: &'f mut dyn FnMut(&Yield) -> Option<Vec<Value>>,
185 states: usize,
186 truncated: bool,
187 reached: BTreeSet<(usize, u32)>,
188 chosen: BTreeSet<(usize, u32, usize)>,
189 visited: BTreeSet<u32>,
190 paths: Vec<TestPath>,
191 errors: Vec<ErrorPath>,
192 unanswered: Vec<StuckPath>,
193 error_keys: BTreeSet<(String, &'static str)>,
194 stuck_keys: BTreeSet<String>,
195 path_names: HashMap<String, usize>,
196}
197
198#[derive(Default)]
200struct ChoicePart {
201 name: Option<String>,
203 option: Option<usize>,
205 id: Option<String>,
207}
208
209enum Arrival {
211 End,
212 Error(VmError),
213 Stop(Box<StateKey>),
214}
215
216impl<'p, 'f> Explorer<'p, 'f> {
217 fn new(
218 program: &'p Program,
219 registry: &'p Registry,
220 config: &'p ExploreConfig,
221 answers: &'f mut dyn FnMut(&Yield) -> Option<Vec<Value>>,
222 ) -> Self {
223 Self {
224 program,
225 registry,
226 config,
227 answers,
228 states: 0,
229 truncated: false,
230 reached: BTreeSet::new(),
231 chosen: BTreeSet::new(),
232 visited: BTreeSet::new(),
233 paths: Vec::new(),
234 errors: Vec::new(),
235 unanswered: Vec::new(),
236 error_keys: BTreeSet::new(),
237 stuck_keys: BTreeSet::new(),
238 path_names: HashMap::new(),
239 }
240 }
241
242 fn vm_config(&self, seed: u64) -> VmConfig {
243 let mut cfg = self.config.vm.clone();
244 cfg.seed = seed;
245 cfg.persistent = None;
246 cfg.seen_points = Vec::new();
247 cfg.history_limit = 0;
248 cfg
249 }
250
251 fn explore_seed(&mut self, seed: u64, multi: bool) -> Result<(), VmError> {
252 let mut vm = Vm::new(self.program, self.registry, self.vm_config(seed))?;
253 let first = vm.run();
254 self.visited.extend(vm.visited_indices().iter().copied());
255 let key = match first {
256 Err(e) => {
257 self.report_error(seed, Vec::new(), e)?;
258 return Ok(());
259 }
260 Ok(Yield::End) => {
261 let name = self.unique_name(path_name(&[], seed, multi));
262 self.paths.push(TestPath {
263 name,
264 seed,
265 steps: Vec::new(),
266 });
267 return Ok(());
268 }
269 Ok(_) => vm.state_key()?,
270 };
271
272 let mut edges: Vec<Edge> = Vec::new();
273 let mut nodes: Vec<Node> = vec![Node::default()];
275 let mut index: HashMap<u128, usize> = HashMap::new();
276 let mut queue: VecDeque<Frame> = VecDeque::new();
277 let mut applied = Some(key.persistent.clone());
279
280 let start = self.new_node(&mut nodes, &mut index, &key, None);
281 if let Some(frame) = self.open_frame(&vm, start, key.persistent, &nodes, &edges, seed)? {
282 queue.push_back(frame);
283 }
284
285 'search: while let Some(frame) = queue.pop_front() {
286 for (k, candidate) in frame.candidates.iter().enumerate() {
287 vm.restore(&frame.snap)?;
288 if applied.as_deref() != Some(&frame.persistent[..])
289 && vm.load_persistent(&frame.persistent).is_err()
290 {
291 return Err(vm_error(VmErrorKind::SnapshotMismatch));
292 }
293 let node = frame.node;
294 let ChoicePart {
295 name: name_part,
296 option,
297 id: option_id,
298 } = self.choice_part(&frame, k);
299 let step = ExploreStep {
300 stop: frame.name.clone(),
301 command: frame.command.clone(),
302 kind: frame.kind,
303 answer: candidate.clone(),
304 option_id,
305 };
306 if let Some(opt) = option {
307 self.chosen.insert((frame.label, frame.ordinal, opt));
308 }
309 let arrival = match vm.resume(Input::Return(candidate.clone())) {
310 Err(e) => Arrival::Error(e),
311 Ok(()) => {
312 let r = vm.run();
313 self.visited.extend(vm.visited_indices().iter().copied());
314 match r {
315 Err(e) => Arrival::Error(e),
316 Ok(Yield::End) => Arrival::End,
317 Ok(_) => Arrival::Stop(Box::new(vm.state_key()?)),
318 }
319 }
320 };
321 match arrival {
322 Arrival::Error(e) => {
323 applied = None;
324 let mut steps = prefix_steps(&nodes, &edges, node);
325 steps.push(step);
326 self.report_error(seed, steps, e)?;
327 }
328 Arrival::End => {
329 applied = None;
330 edges.push(Edge {
331 from: node,
332 to: END,
333 step,
334 name_part,
335 });
336 }
337 Arrival::Stop(key) => {
338 applied = Some(key.persistent.clone());
339 if let Some(&t) = index.get(&hash_key(&key)) {
340 edges.push(Edge {
341 from: node,
342 to: t,
343 step,
344 name_part,
345 });
346 continue;
347 }
348 if self.states >= self.config.max_states {
349 self.truncated = true;
350 break 'search;
351 }
352 let e = edges.len();
353 edges.push(Edge {
354 from: node,
355 to: usize::MAX,
356 step,
357 name_part,
358 });
359 let t = self.new_node(&mut nodes, &mut index, &key, Some(e));
360 edges[e].to = t;
361 if let Some(f) =
362 self.open_frame(&vm, t, key.persistent, &nodes, &edges, seed)?
363 {
364 queue.push_back(f);
365 }
366 }
367 }
368 }
369 }
370
371 link_to_end(&mut nodes, &edges);
372 self.collect_paths(&nodes, &edges, seed, multi);
373 Ok(())
374 }
375
376 fn new_node(
377 &mut self,
378 nodes: &mut Vec<Node>,
379 index: &mut HashMap<u128, usize>,
380 key: &StateKey,
381 parent: Option<usize>,
382 ) -> usize {
383 self.states += 1;
384 let id = nodes.len();
385 nodes.push(Node { parent, next: None });
386 index.insert(hash_key(key), id);
387 id
388 }
389
390 fn open_frame(
392 &mut self,
393 vm: &Vm<'_>,
394 node: usize,
395 persistent: Vec<u8>,
396 nodes: &[Node],
397 edges: &[Edge],
398 seed: u64,
399 ) -> Result<Option<Frame>, VmError> {
400 let (label, ordinal) = vm
401 .stop_position()
402 .expect("the VM is stopped at a stop point");
403 let Some(Yield::Stop { command, .. }) = vm.current().cloned() else {
404 return Ok(None);
405 };
406 let stop = &self.program.labels[label].stops[ordinal as usize];
407 let name = stop_name(self.program, label, stop);
408 let command_name = self.registry.command(command).name.clone();
409 self.reached.insert((label, ordinal));
410 let current = vm.current().cloned().expect("stopped");
411 let candidates = if stop.choice.is_some() {
412 (0..vm.choice_origins().len() as i64)
413 .map(Value::Int)
414 .collect()
415 } else if self.registry.command(command).ret == Ty::Unit {
416 vec![Value::Unit]
417 } else {
418 let mut list: Vec<Value> = Vec::new();
419 for v in (self.answers)(¤t).unwrap_or_default() {
420 if !list.contains(&v) {
421 list.push(v);
422 }
423 }
424 list
425 };
426 if candidates.is_empty() {
427 if self.stuck_keys.insert(name.clone()) {
428 self.unanswered.push(StuckPath {
429 seed,
430 steps: prefix_steps(nodes, edges, node),
431 stop: name,
432 command: command_name,
433 });
434 }
435 return Ok(None);
436 }
437 Ok(Some(Frame {
438 node,
439 snap: vm.snapshot()?,
440 persistent,
441 label,
442 ordinal,
443 name,
444 command: command_name,
445 kind: stop.kind,
446 candidates,
447 origins: vm.choice_origins().to_vec(),
448 }))
449 }
450
451 fn choice_part(&self, frame: &Frame, k: usize) -> ChoicePart {
453 let stop = &self.program.labels[frame.label].stops[frame.ordinal as usize];
454 let Some(info) = &stop.choice else {
455 return ChoicePart::default();
456 };
457 let orig = frame.origins.get(k).copied().unwrap_or(k as u32) as usize;
458 let id = info.options.get(orig).and_then(|o| o.id.clone());
459 let name = match &id {
460 Some(id) => sanitize(id),
461 None => format!("c{}", k + 1),
462 };
463 ChoicePart {
464 name: Some(name),
465 option: Some(orig),
466 id,
467 }
468 }
469
470 fn report_error(
471 &mut self,
472 seed: u64,
473 steps: Vec<ExploreStep>,
474 error: VmError,
475 ) -> Result<(), VmError> {
476 if matches!(error.kind, VmErrorKind::Interrupted) {
477 return Err(error);
478 }
479 let from = steps
480 .last()
481 .map(|s| s.stop.clone())
482 .unwrap_or_else(|| "(start)".to_string());
483 if self.error_keys.insert((from, error.kind.code())) {
484 self.errors.push(ErrorPath { seed, steps, error });
485 }
486 Ok(())
487 }
488
489 fn collect_paths(&mut self, nodes: &[Node], edges: &[Edge], seed: u64, multi: bool) {
490 let mut covered = vec![false; edges.len()];
492 let mut chosen: Vec<Vec<usize>> = Vec::new();
493 for e in (0..edges.len()).rev() {
494 if covered[e] || !completes(nodes, edges[e].to) {
495 continue;
496 }
497 let mut ids: Vec<usize> = prefix_edges(nodes, edges, edges[e].from);
498 ids.push(e);
499 let mut at = edges[e].to;
500 while at != END {
501 let n = nodes[at].next.expect("a node that completes has an edge");
502 ids.push(n);
503 at = edges[n].to;
504 }
505 for &i in &ids {
506 covered[i] = true;
507 }
508 chosen.push(ids);
509 }
510 for ids in chosen.into_iter().rev() {
512 let parts: Vec<&str> = ids
513 .iter()
514 .filter_map(|&i| edges[i].name_part.as_deref())
515 .collect();
516 let name = self.unique_name(path_name(&parts, seed, multi));
517 self.paths.push(TestPath {
518 name,
519 seed,
520 steps: ids.iter().map(|&i| edges[i].step.clone()).collect(),
521 });
522 }
523 }
524
525 fn unique_name(&mut self, name: String) -> String {
526 let count = self.path_names.entry(name.clone()).or_insert(0);
527 *count += 1;
528 if *count == 1 {
529 name
530 } else {
531 format!("{name}~{count}")
532 }
533 }
534
535 fn finish(self) -> ExploreReport {
536 let program = self.program;
537 let mut unreached_stops = Vec::new();
538 let mut unchosen_options = Vec::new();
539 let mut unreached_labels = Vec::new();
540 for (l, label) in program.labels.iter().enumerate() {
541 if !self.visited.contains(&(l as u32)) {
542 unreached_labels.push(format!(
543 "{}.{}",
544 program.modules[label.module as usize], label.name
545 ));
546 }
547 for (o, stop) in label.stops.iter().enumerate() {
548 if !self.reached.contains(&(l, o as u32)) {
549 unreached_stops.push(stop_name(program, l, stop));
550 }
551 if let Some(info) = &stop.choice {
552 for (i, opt) in info.options.iter().enumerate() {
553 if !self.chosen.contains(&(l, o as u32, i)) {
554 unchosen_options.push(option_name(
555 program,
556 l,
557 opt.id.as_deref(),
558 opt.line,
559 ));
560 }
561 }
562 }
563 }
564 }
565 ExploreReport {
566 paths: self.paths,
567 errors: self.errors,
568 unanswered: self.unanswered,
569 unreached_stops,
570 unchosen_options,
571 unreached_labels,
572 states: self.states,
573 truncated: self.truncated,
574 }
575 }
576}
577
578fn vm_error(kind: VmErrorKind) -> VmError {
579 VmError {
580 kind,
581 module: None,
582 label: None,
583 line: None,
584 }
585}
586
587fn completes(nodes: &[Node], node: usize) -> bool {
588 node == END || nodes[node].next.is_some()
589}
590
591fn link_to_end(nodes: &mut [Node], edges: &[Edge]) {
594 let mut incoming: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
595 for (e, edge) in edges.iter().enumerate() {
596 incoming[edge.to].push(e);
597 }
598 let mut dist: Vec<Option<usize>> = vec![None; nodes.len()];
599 dist[END] = Some(0);
600 let mut queue = VecDeque::from([END]);
601 while let Some(t) = queue.pop_front() {
602 let d = dist[t].expect("queued nodes have a distance");
603 for &e in &incoming[t] {
604 let f = edges[e].from;
605 if dist[f].is_none() {
606 dist[f] = Some(d + 1);
607 queue.push_back(f);
608 }
609 }
610 }
611 for (e, edge) in edges.iter().enumerate() {
612 if nodes[edge.from].next.is_none()
613 && let (Some(df), Some(dt)) = (dist[edge.from], dist[edge.to])
614 && df == dt + 1
615 {
616 nodes[edge.from].next = Some(e);
617 }
618 }
619}
620
621fn prefix_edges(nodes: &[Node], edges: &[Edge], node: usize) -> Vec<usize> {
623 let mut ids = Vec::new();
624 let mut at = node;
625 while let Some(e) = nodes[at].parent {
626 ids.push(e);
627 at = edges[e].from;
628 }
629 ids.reverse();
630 ids
631}
632
633fn prefix_steps(nodes: &[Node], edges: &[Edge], node: usize) -> Vec<ExploreStep> {
634 prefix_edges(nodes, edges, node)
635 .into_iter()
636 .map(|e| edges[e].step.clone())
637 .collect()
638}
639
640fn hash_key(key: &StateKey) -> u128 {
641 let mut a: u64 = 0xcbf2_9ce4_8422_2325;
642 let mut b: u64 = 0x8422_2325_cbf2_9ce4 ^ 0x9e37_79b9_7f4a_7c15;
643 for chunk in [&key.save, &key.persistent] {
644 for &byte in chunk.iter() {
645 a = (a ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
646 b = (b.rotate_left(5) ^ u64::from(byte)).wrapping_mul(0x9e37_79b9_7f4a_7c15);
647 }
648 a = (a ^ 0xff).wrapping_mul(0x0000_0100_0000_01b3);
650 b = (b.rotate_left(5) ^ 0xff).wrapping_mul(0x9e37_79b9_7f4a_7c15);
651 a ^= chunk.len() as u64;
652 b ^= (chunk.len() as u64).rotate_left(32);
653 }
654 (u128::from(a) << 64) | u128::from(b)
655}
656
657fn stop_name(program: &Program, label: usize, stop: &StopInfo) -> String {
659 option_name(program, label, stop.id.as_deref(), stop.line)
660}
661
662fn option_name(program: &Program, label: usize, id: Option<&str>, line: u32) -> String {
663 let code = &program.labels[label];
664 let base = format!("{}.{}", program.modules[code.module as usize], code.name);
665 match id {
666 Some(id) => format!("{base}#{id}"),
667 None => format!("{base}:{line}"),
668 }
669}
670
671fn sanitize(text: &str) -> String {
673 text.chars()
674 .map(|c| {
675 if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-' {
676 c
677 } else {
678 '_'
679 }
680 })
681 .collect()
682}
683
684fn fnv1a64(text: &str) -> u64 {
685 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
686 for b in text.bytes() {
687 h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
688 }
689 h
690}
691
692fn path_name(parts: &[&str], seed: u64, multi: bool) -> String {
694 let mut name = if parts.is_empty() {
695 "main".to_string()
696 } else {
697 parts.join("-")
698 };
699 if multi {
700 name = format!("s{seed}-{name}");
701 }
702 if name.chars().count() > 200 {
703 let head: String = name.chars().take(180).collect();
704 name = format!("{head}~{:016x}", fnv1a64(&name));
705 }
706 name
707}