1use std::sync::Arc;
18
19use dive_value::{Ctx, Interner, Value};
20
21use crate::Error;
22use crate::handle::Handle;
23use crate::heap::Heap;
24use crate::node::{Kind, flags};
25
26#[derive(Clone)]
29pub struct Printer {
30 pub names: Arc<Interner>,
33 pub ctx: Ctx,
35}
36
37impl std::fmt::Debug for Printer {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.debug_struct("Printer").finish_non_exhaustive()
40 }
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum Conversion {
46 Report,
49 Graph,
56 Print,
59 Draw,
62}
63
64pub fn to_value(
70 heap: &mut Heap,
71 names: &Interner,
72 h: Handle,
73 ctx: Ctx,
74 conv: Conversion,
75) -> Result<Value, String> {
76 if let Some(b) = h.as_bool() {
77 return Ok(Value::Bool(b));
78 }
79 if let Some(i) = h.as_int() {
80 return Ok(Value::Int(i));
81 }
82 if let Some(id) = h.as_str_id() {
83 let text = heap
84 .store()
85 .strings()
86 .text(id)
87 .ok_or_else(|| format!("unknown string {id}"))?;
88 return Ok(Value::Str(names.intern(&text)));
89 }
90 if let Some(id) = h.as_model_id() {
91 let text = heap
92 .store()
93 .strings()
94 .text(id)
95 .ok_or_else(|| format!("unknown model value {id}"))?;
96 return Ok(Value::Model(names.intern(&text)));
97 }
98 if !h.is_compound() {
99 return Err("a value the core cannot report".into());
100 }
101 if heap.view(h).is_lazy() {
102 return Err("printing a function or set the core keeps lazy (M1 core)".into());
103 }
104 let kind = heap.view(h).kind;
105 if conv == Conversion::Graph && kind.is_symbolic() {
106 return Err(format!(
107 "an unmaterialized symbolic {kind:?} in core graph conversion"
108 ));
109 }
110 if kind == Kind::BigInt {
111 let b = heap.big(h).ok_or("a malformed integer")?;
112 return Ok(Value::int(dive_value::Int::from_big(b)));
113 }
114 let keep = conv != Conversion::Report
117 && matches!(
118 kind,
119 Kind::Interval | Kind::Subset | Kind::FcnSet | Kind::RecSet | Kind::Product
120 );
121 if keep || !heap.is_finite(h) {
122 return symbolic_value(heap, names, h, ctx, conv);
123 }
124 if kind.is_symbolic() {
125 let m = heap.materialize(h).map_err(|e| e.message().to_owned())?;
126 return to_value(heap, names, m, ctx, conv);
127 }
128 if conv == Conversion::Print
129 && let Some(why) = ambiguous(heap, h)
130 {
131 return Err(why);
132 }
133 let v = heap.view(h);
134 let (lo, view_flags, keys, vals) = (v.lo, v.flags, v.keys().to_vec(), v.values().to_vec());
135 match kind {
136 Kind::Set | Kind::SetEnum => {
137 let mut elems = Vec::with_capacity(vals.len());
138 for e in vals {
139 elems.push(to_value(heap, names, e, ctx, conv)?);
140 }
141 Value::set_canonical(elems, ctx).map_err(|error| error.to_string())
142 }
143 Kind::IntFcn => {
144 let mut elems = Vec::with_capacity(vals.len());
145 for e in vals {
146 elems.push(to_value(heap, names, e, ctx, conv)?);
147 }
148 if lo == 1 {
149 return Ok(
150 if conv == Conversion::Graph && view_flags & flags::TUPLE == 0 {
151 Value::tuple_fcn(elems)
152 } else {
153 Value::tuple(elems)
154 },
155 );
156 }
157 let pairs = elems
158 .into_iter()
159 .zip(lo..)
160 .map(|(v, k)| (Value::Int(k), v))
161 .collect();
162 Value::fcn(pairs, ctx).map_err(|e| e.to_string())
163 }
164 _ => {
165 let mut pairs = Vec::with_capacity(keys.len());
166 for (k, x) in keys.into_iter().zip(vals) {
167 pairs.push((
168 to_value(heap, names, k, ctx, conv)?,
169 to_value(heap, names, x, ctx, conv)?,
170 ));
171 }
172 function_value(pairs, ctx, conv, view_flags)
173 }
174 }
175}
176
177fn function_value(
178 pairs: Vec<(Value, Value)>,
179 ctx: Ctx,
180 conv: Conversion,
181 view_flags: u8,
182) -> Result<Value, String> {
183 let strings = pairs.iter().all(|(k, _)| matches!(k, Value::Str(_)));
184 let literal = conv == Conversion::Graph && view_flags & flags::RECORD != 0;
185 if literal && !strings {
186 return Err("a core graph record literal with non-string fields".into());
187 }
188 if strings && (conv == Conversion::Report || literal) {
191 let fields = pairs
192 .into_iter()
193 .filter_map(|(k, x)| match k {
194 Value::Str(a) => Some((a, x)),
195 _ => None,
196 })
197 .collect();
198 Value::record(fields, ctx).map_err(|e| e.to_string())
199 } else {
200 Value::fcn(pairs, ctx).map_err(|e| e.to_string())
201 }
202}
203
204#[cfg(test)]
205#[path = "print_tests.rs"]
206mod tests;
207#[derive(Debug)]
209pub enum ConversionError {
210 Unsupported(String),
212 Construction(dive_value::ConstructionError),
214}
215
216impl From<dive_value::ConstructionError> for ConversionError {
217 fn from(error: dive_value::ConstructionError) -> Self {
218 Self::Construction(error)
219 }
220}
221
222impl std::fmt::Display for ConversionError {
223 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224 match self {
225 Self::Unsupported(reason) => f.write_str(reason),
226 Self::Construction(error) => error.fmt(f),
227 }
228 }
229}
230impl std::error::Error for ConversionError {}
231
232#[allow(
243 clippy::too_many_lines,
244 reason = "preserve conversion and name encounter order in one value-class match"
245)]
246pub fn to_value_controlled(
247 heap: &mut Heap,
248 names: &Interner,
249 h: Handle,
250 ctx: Ctx,
251 conv: Conversion,
252 proceed: &mut dyn FnMut() -> bool,
253) -> Result<Value, ConversionError> {
254 fn check(proceed: &mut dyn FnMut() -> bool) -> Result<(), ConversionError> {
255 if proceed() {
256 Ok(())
257 } else {
258 Err(dive_value::ConstructionError::Interrupted.into())
259 }
260 }
261 fn storage<T>(
262 len: usize,
263 proceed: &mut dyn FnMut() -> bool,
264 ) -> Result<Vec<T>, ConversionError> {
265 check(proceed)?;
266 let mut out = Vec::new();
267 out.try_reserve_exact(len).map_err(|_| {
268 ConversionError::Construction(dive_value::ConstructionError::Allocation)
269 })?;
270 Ok(out)
271 }
272 check(proceed)?;
273 if !h.is_compound()
274 || heap.view(h).is_lazy()
275 || heap.view(h).kind.is_symbolic()
276 || heap.view(h).kind == Kind::BigInt
277 {
278 let value = to_value(heap, names, h, ctx, conv).map_err(ConversionError::Unsupported)?;
279 check(proceed)?;
280 return Ok(value);
281 }
282 if conv == Conversion::Print
283 && let Some(reason) = ambiguous(heap, h)
284 {
285 return Err(ConversionError::Unsupported(reason));
286 }
287 let view = heap.view(h);
288 let (kind, lo, view_flags) = (view.kind, view.lo, view.flags);
289 let mut keys = storage(view.keys().len(), proceed)?;
290 for &key in view.keys() {
291 check(proceed)?;
292 keys.push(key);
293 }
294 let mut handles = storage(view.values().len(), proceed)?;
295 for &value in view.values() {
296 check(proceed)?;
297 handles.push(value);
298 }
299 match kind {
300 Kind::Set | Kind::SetEnum => {
301 let mut elements = storage(handles.len(), proceed)?;
302 for value in handles {
303 elements.push(to_value_controlled(heap, names, value, ctx, conv, proceed)?);
304 }
305 Value::set_controlled(elements, ctx, proceed).map_err(Into::into)
306 }
307 Kind::IntFcn => {
308 let mut elements = storage(handles.len(), proceed)?;
309 for value in handles {
310 elements.push(to_value_controlled(heap, names, value, ctx, conv, proceed)?);
311 }
312 check(proceed)?;
313 if lo == 1 {
314 return Ok(
315 if conv == Conversion::Graph && view_flags & flags::TUPLE == 0 {
316 Value::tuple_fcn(elements)
317 } else {
318 Value::tuple(elements)
319 },
320 );
321 }
322 let mut pairs = storage(elements.len(), proceed)?;
323 for (value, key) in elements.into_iter().zip(lo..) {
324 check(proceed)?;
325 pairs.push((Value::Int(key), value));
326 }
327 Value::fcn_controlled(pairs, ctx, proceed).map_err(Into::into)
328 }
329 _ => {
330 let mut pairs = storage(keys.len(), proceed)?;
331 for (key, value) in keys.into_iter().zip(handles) {
332 pairs.push((
333 to_value_controlled(heap, names, key, ctx, conv, proceed)?,
334 to_value_controlled(heap, names, value, ctx, conv, proceed)?,
335 ));
336 }
337 let mut strings = true;
338 for (key, _) in &pairs {
339 check(proceed)?;
340 strings &= matches!(key, Value::Str(_));
341 }
342 let literal = conv == Conversion::Graph && view_flags & flags::RECORD != 0;
343 if literal && !strings {
344 return Err(ConversionError::Unsupported(
345 "a core graph record literal with non-string fields".into(),
346 ));
347 }
348 if strings && (conv == Conversion::Report || literal) {
349 let mut fields = storage(pairs.len(), proceed)?;
350 for (key, value) in pairs {
351 check(proceed)?;
352 if let Value::Str(name) = key {
353 fields.push((name, value));
354 }
355 }
356 Value::record_controlled(fields, ctx, proceed).map_err(Into::into)
357 } else {
358 Value::fcn_controlled(pairs, ctx, proceed).map_err(Into::into)
359 }
360 }
361 }
362}
363
364const LAZY_PRINT_MIN: usize = 128;
367
368fn ambiguous(heap: &Heap, h: Handle) -> Option<String> {
374 if !heap.store().lazy_sets() {
375 return None;
376 }
377 let v = heap.view(h);
378 if !v.kind.is_set() {
379 return None;
380 }
381 let elems = v.values();
382 if elems.len() >= LAZY_PRINT_MIN {
383 return Some(format!(
384 "printing a set of {} elements, which TLC may hold as a lazy set and print in its lazy form (M1 core)",
385 elems.len()
386 ));
387 }
388 let ints: Option<Vec<i64>> = elems.iter().map(|e| e.as_int()).collect();
389 if let Some(ints) = ints
390 && !ints.is_empty()
391 && ints.windows(2).all(|w| w[1] == w[0] + 1)
392 {
393 return Some(
394 "printing a set of consecutive integers, which TLC may hold as an interval and print as `a..b` (M1 core)".into(),
395 );
396 }
397 None
398}
399
400fn symbolic_value(
402 heap: &mut Heap,
403 names: &Interner,
404 h: Handle,
405 ctx: Ctx,
406 conv: Conversion,
407) -> Result<Value, String> {
408 let v = heap.view(h);
409 let (kind, lo, data) = (v.kind, v.lo, v.data.to_vec());
410 if kind == Kind::Interval {
411 let hi = data
412 .first()
413 .and_then(|h| h.as_int())
414 .ok_or("an interval without its bound")?;
415 return Ok(Value::interval(
416 dive_value::Int::from(lo),
417 dive_value::Int::from(hi),
418 ctx,
419 ));
420 }
421 let mut parts = Vec::with_capacity(data.len());
422 let n = if kind == Kind::RecSet {
423 data.len() / 2
424 } else {
425 0
426 };
427 for (i, &d) in data.iter().enumerate() {
428 parts.push(to_value(heap, names, d, ctx, conv).map_err(|e| {
430 if i < n {
431 format!("a record set's field name: {e}")
432 } else {
433 e
434 }
435 })?);
436 }
437 let one = |parts: &mut Vec<Value>| parts.pop().ok_or("a set without its parts");
438 match kind {
439 Kind::Nat => Ok(Value::nat(ctx)),
440 Kind::Int => Ok(Value::int_set(ctx)),
441 Kind::SeqSet => Ok(Value::seq_set(one(&mut parts)?, ctx)),
442 Kind::Subset => Ok(Value::subset(one(&mut parts)?, ctx)),
443 Kind::FcnSet if parts.len() == 2 => {
444 let range = one(&mut parts)?;
445 Ok(Value::fcn_set(one(&mut parts)?, range, ctx))
446 }
447 Kind::Product => Ok(Value::product(parts, ctx)),
448 Kind::RecSet => {
449 let sets = parts.split_off(n);
450 let fields = parts
451 .into_iter()
452 .zip(sets)
453 .map(|(k, x)| match k {
454 Value::Str(a) => Ok((a, x)),
455 _ => Err("a record set's field name that is not a string".to_owned()),
456 })
457 .collect::<Result<_, _>>()?;
458 Value::record_set(fields, ctx).map_err(|e| e.to_string())
459 }
460 _ => Err(format!("an infinite {kind:?} the core cannot report")),
461 }
462}
463
464pub fn tlc_string(heap: &mut Heap, h: Handle) -> Result<String, Error> {
471 print_with(heap, h, dive_value::print::to_tlc_string)
472}
473
474pub fn pretty(heap: &mut Heap, h: Handle) -> Result<String, Error> {
480 print_with(heap, h, dive_value::print::print_value)
481}
482
483fn print_with(
484 heap: &mut Heap,
485 h: Handle,
486 f: fn(&Value, Ctx) -> dive_value::Result<String>,
487) -> Result<String, Error> {
488 let Some(p) = heap.store().printer().cloned() else {
489 return Err(Error::unsupported(
490 "printing without the model's names (M1 core)",
491 ));
492 };
493 let v = to_value(heap, &p.names, h, p.ctx, Conversion::Print).map_err(Error::unsupported)?;
494 f(&v, p.ctx)
495 .map_err(|e| Error::unsupported(format!("an error while printing a value (M1 core): {e}")))
496}
497
498#[cfg(test)]
499#[allow(clippy::expect_used, reason = "conversion fixtures")]
500mod controlled_tests {
501 use super::*;
502 use crate::Store;
503
504 #[test]
505 fn materialized_conversion_keeps_results_and_name_interning_order() {
506 for ctx in [Ctx::tlc(), Ctx::default()] {
507 let source_names = Interner::new();
508 let input = Value::tuple(vec![
509 Value::string(&source_names, "z"),
510 Value::set(vec![Value::Int(2), Value::Int(1)], ctx).expect("set"),
511 Value::record(
512 vec![(source_names.intern("a"), Value::model(&source_names, "M_x"))],
513 ctx,
514 )
515 .expect("record"),
516 ]);
517 let mut heap = Heap::new(Arc::new(Store::default()), false, false);
518 let handle = crate::convert::from_value(&mut heap, &input, ctx).expect("import");
519 let baseline_names = Interner::new();
520 let controlled_names = Interner::new();
521 let expected = to_value(&mut heap, &baseline_names, handle, ctx, Conversion::Report)
522 .expect("baseline");
523 let mut checks = 0;
524 let actual = to_value_controlled(
525 &mut heap,
526 &controlled_names,
527 handle,
528 ctx,
529 Conversion::Report,
530 &mut || {
531 checks += 1;
532 true
533 },
534 )
535 .expect("controlled");
536 assert_eq!(expected, actual);
537 for at in 0..baseline_names.len() {
538 let at = u32::try_from(at).expect("small names");
539 assert_eq!(
540 baseline_names
541 .resolve(at)
542 .map(|name| name.as_str().to_owned()),
543 controlled_names
544 .resolve(at)
545 .map(|name| name.as_str().to_owned())
546 );
547 }
548 assert!(checks > 20);
549 for stop in 0..checks {
550 let mut visited = 0;
551 let result = to_value_controlled(
552 &mut heap,
553 &Interner::new(),
554 handle,
555 ctx,
556 Conversion::Report,
557 &mut || {
558 let proceed = visited != stop;
559 visited += 1;
560 proceed
561 },
562 );
563 assert!(
564 matches!(
565 result,
566 Err(ConversionError::Construction(
567 dive_value::ConstructionError::Interrupted
568 ))
569 ),
570 "{stop}: {result:?}"
571 );
572 }
573 }
574 }
575
576 #[test]
577 fn symbolic_report_conversion_keeps_explicit_legacy_fallback() {
578 let mut heap = Heap::new(Arc::new(Store::default()), false, false);
579 let interval = heap.interval(1, 3);
580 let names = Interner::new();
581 let expected = to_value(&mut heap, &names, interval, Ctx::tlc(), Conversion::Report)
582 .expect("baseline");
583 let actual = to_value_controlled(
584 &mut heap,
585 &names,
586 interval,
587 Ctx::tlc(),
588 Conversion::Report,
589 &mut || true,
590 )
591 .expect("controlled");
592 assert_eq!(expected, actual);
593 }
594
595 #[test]
596 fn controlled_graph_conversion_keeps_literal_classes_and_symbolic_refusals() {
597 for ctx in [Ctx::dive(), Ctx::tlc()] {
598 let mut heap = Heap::new(Arc::new(Store::default()), true, false);
599 let names = Interner::new();
600 let key = heap.string("a").expect("field");
601 let zero = Handle::int(0).expect("integer");
602 let functions = [
603 heap.fcn_sorted(&[key], &[zero]),
604 heap.record(&[key], &[zero]),
605 heap.tuple(&[zero]),
606 heap.tuple_literal(&[zero]),
607 ];
608 for handle in functions {
609 let original =
610 to_value(&mut heap, &names, handle, ctx, Conversion::Graph).expect("baseline");
611 let converted = to_value_controlled(
612 &mut heap,
613 &names,
614 handle,
615 ctx,
616 Conversion::Graph,
617 &mut || true,
618 )
619 .expect("controlled");
620 let (original, converted) = (
621 original.as_fcn().expect("function"),
622 converted.as_fcn().expect("function"),
623 );
624 assert_eq!(original.kind(), converted.kind());
625 assert_eq!(original.is_record_literal(), converted.is_record_literal());
626 assert_eq!(original.is_tuple_literal(), converted.is_tuple_literal());
627 }
628 for handle in [heap.set_enum(&[zero]), heap.interval(0, 1)] {
629 let expected = to_value(&mut heap, &names, handle, ctx, Conversion::Graph)
630 .expect_err("unknown history");
631 let actual = to_value_controlled(
632 &mut heap,
633 &names,
634 handle,
635 ctx,
636 Conversion::Graph,
637 &mut || true,
638 )
639 .expect_err("controlled unknown history");
640 assert_eq!(expected, actual.to_string());
641 }
642 }
643 }
644}