Skip to main content

dive_value/
print.rs

1//! TLC's value printing.
2//!
3//! [`to_tlc_string`] ports the `toString` methods of `tlc2.value.impl` (tlaplus
4//! `94d0c50`), including which lazy sets TLC expands when printing:
5//! - `SUBSET S` when `|S| < 7`;
6//! - `[S -> T]`, `[a : S]` and `S \X T` when they have fewer than 2000 elements
7//!   (`TLCGlobals.enumBound`);
8//! - filters and maps always;
9//! - intervals never (`1..3`, or `{}` when empty).
10//!
11//! [`print_value`] adds TLC's pretty-printer ([`ppr`], a port of `tlc2.pprint`), as
12//! `Print`, `PrintT`, error messages and counterexample states use it.
13
14#![allow(
15    clippy::many_single_char_names,
16    reason = "ports keep short operand names (a, b, s, t, x, y)"
17)]
18
19use std::fmt::Write as _;
20
21use crate::atom::Atom;
22use crate::ctx::Ctx;
23use crate::enumerate;
24use crate::error::Result;
25use crate::stream::elems_in;
26use crate::value::{FcnRepr, SetRepr, Value};
27
28pub use crate::pprint::{WIDTH, ppr, ppr_width};
29
30/// `Value.toStringUnchecked()`: the single-line form, with errors raised while
31/// deciding how to print a lazy set propagated (as in `Print` and `ToString`).
32///
33/// ```
34/// use dive_value::{Ctx, Interner, Value, print::to_tlc_string};
35/// let ctx = Ctx::tlc();
36/// let names = Interner::new();
37/// let v = Value::set(vec![Value::from(2), Value::from(1)], ctx)?;
38/// assert_eq!(to_tlc_string(&v, ctx)?, "{1, 2}");
39/// let s = Value::string(&names, "a\"b");
40/// assert_eq!(to_tlc_string(&s, ctx)?, r#""a\"b""#);
41/// # Ok::<(), dive_value::ValueError>(())
42/// ```
43///
44/// # Errors
45/// Normalization errors of unnormalized sets, and errors raised while sizing or
46/// enumerating a lazy set that TLC would expand.
47pub fn to_tlc_string(v: &Value, ctx: Ctx) -> Result<String> {
48    let mut out = String::new();
49    write_value(
50        v,
51        ctx,
52        Mode {
53            swallow: false,
54            mark: true,
55            converted_products: false,
56        },
57        &mut out,
58    )?;
59    Ok(out)
60}
61
62/// `Value.toString()`: like [`to_tlc_string`], but errors raised while deciding whether
63/// to expand a lazy set are swallowed (the set is printed in its lazy form), as TLC
64/// does when building error messages. Never fails; an unprintable value prints as a
65/// placeholder naming its kind.
66#[must_use]
67pub fn to_tlc_string_lenient(v: &Value, ctx: Ctx) -> String {
68    let mut out = String::new();
69    match write_value(
70        v,
71        ctx,
72        Mode {
73            swallow: true,
74            mark: true,
75            converted_products: false,
76        },
77        &mut out,
78    ) {
79        Ok(()) => out,
80        Err(_) => format!("<unprintable {}>", v.kind_name()),
81    }
82}
83
84/// What `Print`/`PrintT` print for a value: `Values.ppr(v.toStringUnchecked())`.
85///
86/// # Errors
87/// As [`to_tlc_string`].
88pub fn print_value(v: &Value, ctx: Ctx) -> Result<String> {
89    Ok(ppr(&to_tlc_string(v, ctx)?))
90}
91
92/// Fallible `Values.ppr(v.toString())` for an argument diagnostic.
93///
94/// Like TLC's checked rendering, this swallows failures while choosing a lazy
95/// expansion, then propagates failures while printing its selected or symbolic
96/// form. Concrete empty Products convert before their unused axes normalize.
97/// Existing infallible diagnostic callers retain [`to_tlc_string_lenient`].
98/// Callers retain their conversion guards for unproved Product shapes; the
99/// empty-conversion proof covers explicit storage, 32-bit intervals and nested
100/// Products, in source order. Other lazy forms keep their established renderer.
101///
102/// ```
103/// use dive_value::{Ctx, Value, print::print_error_value};
104/// let ctx = Ctx::tlc();
105/// let value = Value::product(vec![Value::nat(ctx), Value::empty_set(ctx)], ctx);
106/// assert_eq!(print_error_value(&value, ctx)?, "(Nat \\X {})");
107/// # Ok::<(), dive_value::ValueError>(())
108/// ```
109///
110/// # Errors
111/// Normalization and nested rendering errors outside TLC's expansion-selection
112/// catch. An unprintable fallback is never replaced with a placeholder.
113pub fn print_error_value(v: &Value, ctx: Ctx) -> Result<String> {
114    let mut out = String::new();
115    write_value(
116        v,
117        ctx,
118        Mode {
119            swallow: true,
120            mark: true,
121            converted_products: true,
122        },
123        &mut out,
124    )?;
125    Ok(ppr(&out))
126}
127
128/// A state as TLC prints it in a counterexample (`TLCStateMut.toString`): one
129/// `/\ x = value` line per variable, or `x = value` when there is a single variable.
130/// Each value is pretty-printed on its own, at width 80.
131///
132/// # Errors
133/// As [`to_tlc_string`].
134pub fn format_state(vars: &[(&str, &Value)], ctx: Ctx) -> Result<String> {
135    let mut out = String::new();
136    if let [(name, v)] = vars {
137        let _ = writeln!(out, "{name} = {}", ppr(&to_tlc_string(v, ctx)?));
138        return Ok(out);
139    }
140    for (name, v) in vars {
141        let _ = writeln!(out, "/\\ {name} = {}", ppr(&to_tlc_string(v, ctx)?));
142    }
143    Ok(out)
144}
145
146/// `StringValue.PrintVersion`: escapes `"`, `\`, tab, newline, form feed and carriage
147/// return.
148#[must_use]
149pub fn escape_string(s: &str) -> String {
150    let mut out = String::with_capacity(s.len() + 2);
151    for c in s.chars() {
152        match c {
153            '"' => out.push_str("\\\""),
154            '\\' => out.push_str("\\\\"),
155            '\t' => out.push_str("\\t"),
156            '\n' => out.push_str("\\n"),
157            '\u{000C}' => out.push_str("\\f"),
158            '\r' => out.push_str("\\r"),
159            c => out.push(c),
160        }
161    }
162    out
163}
164
165/// `FcnRcdValue.isName`: whether a string field prints in record syntax.
166fn is_name(s: &str) -> bool {
167    let mut has_letter = false;
168    let mut len = 0usize;
169    for u in s.encode_utf16() {
170        len += 1;
171        if u == u16::from(b'_') {
172            continue;
173        }
174        let Some(c) = char::from_u32(u32::from(u)) else {
175            // A lone surrogate is neither a letter nor a digit in Java.
176            return false;
177        };
178        if !java_is_letter_or_digit(c) {
179            return false;
180        }
181        has_letter |= java_is_letter(c);
182    }
183    has_letter && (len < 4 || !(s.starts_with("WF_") || s.starts_with("SF_")))
184}
185
186/// `Character.isLetter`, exact for ASCII; Unicode's alphabetic property otherwise.
187pub(crate) fn java_is_letter(c: char) -> bool {
188    if c.is_ascii() {
189        c.is_ascii_alphabetic()
190    } else {
191        c.is_alphabetic()
192    }
193}
194
195/// `Character.isLetterOrDigit`, exact for ASCII; Unicode's alphanumeric property
196/// otherwise.
197pub(crate) fn java_is_letter_or_digit(c: char) -> bool {
198    if c.is_ascii() {
199        c.is_ascii_alphanumeric()
200    } else {
201        c.is_alphanumeric()
202    }
203}
204
205/// How a value is being printed.
206#[derive(Clone, Copy)]
207struct Mode {
208    /// Swallow errors raised while deciding how to print a lazy set (`toString`).
209    swallow: bool,
210    /// Print as TLC does, normalizing unnormalized sets as a side effect. Off only
211    /// for `Debug`, which must not change anything observable.
212    mark: bool,
213    /// Use Product.toSetEnum demand for the fallible diagnostic boundary only.
214    converted_products: bool,
215}
216
217/// The `Debug` form: TLC's printing, without normalizing anything and without
218/// failing on what TLC would expand.
219pub(crate) fn to_debug_string(v: &Value) -> Option<String> {
220    let mut out = String::new();
221    let mode = Mode {
222        swallow: true,
223        mark: false,
224        converted_products: false,
225    };
226    write_value(v, Ctx::default(), mode, &mut out).ok()?;
227    Some(out)
228}
229
230fn write_list<'a>(
231    items: impl Iterator<Item = &'a Value>,
232    ctx: Ctx,
233    mode: Mode,
234    out: &mut String,
235) -> Result<()> {
236    for (i, v) in items.enumerate() {
237        if i > 0 {
238            out.push_str(", ");
239        }
240        write_value(v, ctx, mode, out)?;
241    }
242    Ok(())
243}
244
245/// The size estimate TLC uses to decide whether to expand `[S -> T]`.
246fn fcn_set_bound(d: &Value, r: &Value, ctx: Ctx, mode: Mode) -> Result<u128> {
247    if crate::tlc::is_empty(d, ctx)? {
248        return Ok(1);
249    }
250    let dsz = component_size(d, ctx, mode)?;
251    let rsz = u128::from(component_size(r, ctx, mode)?);
252    let mut sz: u128 = 1;
253    let mut i = 0;
254    while i < dsz && sz <= 2_147_483_647 {
255        sz *= rsz;
256        i += 1;
257    }
258    Ok(sz)
259}
260
261/// The size estimate TLC uses to decide whether to expand `[a : S]` and `S \X T`.
262fn product_bound<'a>(comps: impl Iterator<Item = &'a Value>, ctx: Ctx, mode: Mode) -> Result<u128> {
263    let mut sz: u128 = 1;
264    for c in comps {
265        let n = u128::from(component_size(c, ctx, mode)?);
266        if n == 0 {
267            return Ok(0);
268        }
269        if sz <= 2_147_483_647 {
270            sz *= n;
271        }
272    }
273    Ok(sz)
274}
275
276fn component_size(v: &Value, ctx: Ctx, mode: Mode) -> Result<u64> {
277    match v {
278        Value::Set(s)
279            if mode.converted_products
280                && matches!(s.repr(), SetRepr::Product(_))
281                && concrete_empty(v, 0) == Some(true) =>
282        {
283            // Product.size checks isEmpty before sizing any of its axes.
284            Ok(0)
285        }
286        Value::Set(s) if mode.mark => s.size(ctx),
287        Value::Set(s) => enumerate::quiet_size(s)
288            .and_then(|n| u64::try_from(n).ok())
289            .ok_or_else(|| crate::stream::not_enumerable(v, ctx)),
290        Value::Fcn(f) => Ok(f.len() as u64),
291        _ => Err(crate::stream::not_enumerable(v, ctx)),
292    }
293}
294
295/// Read-only, bounded `Value.isEmpty` on explicit, interval and Product storage.
296/// Unknown earlier operands decline before inspecting a later empty operand.
297fn concrete_empty(value: &Value, depth: u8) -> Option<bool> {
298    if depth >= 64 {
299        return None;
300    }
301    let Value::Set(set) = value else {
302        return None;
303    };
304    if let Some(values) = set.stored_elements() {
305        return Some(values.is_empty());
306    }
307    if let Some((lo, hi)) = set.as_interval() {
308        return match (lo.to_i64(), hi.to_i64()) {
309            (Some(lo), Some(hi)) if hi < lo => Some(true),
310            (Some(lo), Some(hi)) => hi
311                .checked_sub(lo)
312                .and_then(|n| n.checked_add(1))
313                .filter(|&n| n <= i64::from(i32::MAX))
314                .map(|_| false),
315            _ => None,
316        };
317    }
318    for axis in set.as_product()? {
319        if concrete_empty(axis, depth + 1)? {
320            return Some(true);
321        }
322    }
323    Some(false)
324}
325
326/// TLC's `TLCGlobals.enumBound`.
327const ENUM_BOUND: u128 = 2000;
328
329#[allow(
330    clippy::too_many_lines,
331    reason = "one arm per TLC toString method, kept together for comparison"
332)]
333fn write_value(v: &Value, ctx: Ctx, mode: Mode, out: &mut String) -> Result<()> {
334    let _guard = crate::depth::Guard::enter()?;
335    match v {
336        Value::Bool(b) => out.push_str(if *b { "TRUE" } else { "FALSE" }),
337        Value::Int(_) | Value::BigInt(_) => {
338            let _ = write!(out, "{}", v.as_int().unwrap_or(crate::Int::ZERO));
339        }
340        Value::Str(a) => {
341            out.push('"');
342            out.push_str(&escape_string(a.as_str()));
343            out.push('"');
344        }
345        Value::Model(a) => out.push_str(a.as_str()),
346        Value::Fcn(f) => write_fcn(f, ctx, mode, out)?,
347        Value::Set(s) => write_set(s, ctx, mode, out)?,
348    }
349    Ok(())
350}
351
352#[inline(never)]
353fn write_fcn(f: &crate::Fcn, ctx: Ctx, mode: Mode, out: &mut String) -> Result<()> {
354    match &f.0.repr {
355        FcnRepr::Tuple(e) => {
356            out.push_str("<<");
357            write_list(e.iter(), ctx, mode, out)?;
358            out.push_str(">>");
359        }
360        // `RecordValue.toString` always uses record syntax; a string-domain
361        // `FcnRcdValue` only when every field is a name (`isRcd`).
362        FcnRepr::Record(fs)
363            if f.is_record_literal() || fs.iter().all(|(a, _)| is_name(a.as_str())) =>
364        {
365            let mut fields: Vec<(Atom, Value)> = fs.to_vec();
366            if f.order() != ctx.order {
367                fields.sort_by(|a, b| a.0.cmp_with(&b.0, ctx.order));
368            }
369            out.push('[');
370            for (i, (a, x)) in fields.iter().enumerate() {
371                if i > 0 {
372                    out.push_str(", ");
373                }
374                out.push_str(a.as_str());
375                out.push_str(" |-> ");
376                write_value(x, ctx, mode, out)?;
377            }
378            out.push(']');
379        }
380        _ => {
381            let mut pairs: Vec<(Value, Value)> = f.iter().map(|(d, x)| (d, x.clone())).collect();
382            if f.order() != ctx.order {
383                pairs.sort_by(|a, b| a.0.cmp_with(&b.0, ctx.order));
384            }
385            out.push('(');
386            for (i, (d, x)) in pairs.iter().enumerate() {
387                if i > 0 {
388                    out.push_str(" @@ ");
389                }
390                write_value(d, ctx, mode, out)?;
391                out.push_str(" :> ");
392                write_value(x, ctx, mode, out)?;
393            }
394            out.push(')');
395        }
396    }
397    Ok(())
398}
399
400// An enumeration error can print the very set whose enumeration failed.
401// Retrying that expansion repeats the error indefinitely, even for a shallow
402// acyclic value. Keep the original error and let lenient printing use its
403// existing symbolic fallback. This does not change value nesting limits.
404thread_local! {
405    static EXPANDING: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
406}
407
408struct Expansion;
409impl Expansion {
410    fn enter(set: &crate::Set) -> Result<Self> {
411        let id = std::sync::Arc::as_ptr(&set.0) as usize;
412        let added = EXPANDING.with(|active| {
413            let mut active = active.borrow_mut();
414            if active.contains(&id) {
415                false
416            } else {
417                active.push(id);
418                true
419            }
420        });
421        if added {
422            Ok(Self)
423        } else {
424            Err(crate::error::ValueError::new(
425                crate::error::ErrorKind::NotEnumerable,
426                "Cannot expand a set again while printing its enumeration error.",
427            ))
428        }
429    }
430}
431impl Drop for Expansion {
432    fn drop(&mut self) {
433        EXPANDING.with(|active| {
434            active.borrow_mut().pop();
435        });
436    }
437}
438
439#[inline(never)]
440#[allow(
441    clippy::too_many_lines,
442    reason = "one arm per TLC toString method of a set, kept together for comparison"
443)]
444fn write_set(s: &crate::Set, ctx: Ctx, mode: Mode, out: &mut String) -> Result<()> {
445    let expand = |decide: Result<bool>| -> Result<bool> {
446        match decide {
447            Ok(b) => Ok(b),
448            Err(_) if mode.swallow => Ok(false),
449            Err(e) => Err(e),
450        }
451    };
452    let enumerated = |out: &mut String| -> Result<()> {
453        let _expansion = Expansion::enter(s)?;
454        let elems = if mode.mark {
455            elems_in(s, ctx, true)?
456        } else {
457            s.quiet_elements(ctx)?
458        };
459        out.push('{');
460        write_list(elems.iter(), ctx, mode, out)?;
461        out.push('}');
462        Ok(())
463    };
464    match s.repr() {
465        SetRepr::Enum | SetRepr::Raw(_) | SetRepr::Deferred(_) => enumerated(out)?,
466        SetRepr::Interval(lo, hi) => {
467            if lo <= hi {
468                let _ = write!(out, "{lo}..{hi}");
469            } else {
470                out.push_str("{}");
471            }
472        }
473        SetRepr::Subset(b) => {
474            if expand(component_size(b, ctx, mode).map(|n| n < 7))? {
475                enumerated(out)?;
476            } else {
477                out.push_str("SUBSET ");
478                if matches!(b, Value::Set(t) if t.as_interval().is_some()) {
479                    out.push('(');
480                    write_value(b, ctx, mode, out)?;
481                    out.push(')');
482                } else {
483                    write_value(b, ctx, mode, out)?;
484                }
485            }
486        }
487        SetRepr::FcnSet(d, r) => {
488            let small = expand(fcn_set_bound(d, r, ctx, mode).map(|n| n < ENUM_BOUND))?;
489            let printed = small && {
490                let mut tmp = String::new();
491                match enumerated(&mut tmp) {
492                    Ok(()) => {
493                        out.push_str(&tmp);
494                        true
495                    }
496                    Err(_) if mode.swallow => false,
497                    Err(e) => return Err(e),
498                }
499            };
500            if !printed {
501                out.push('[');
502                write_value(d, ctx, mode, out)?;
503                out.push_str(" -> ");
504                write_value(r, ctx, mode, out)?;
505                out.push(']');
506            }
507        }
508        SetRepr::RcdSet(fs) => {
509            if expand(product_bound(fs.iter().map(|(_, x)| x), ctx, mode).map(|n| n < ENUM_BOUND))?
510            {
511                enumerated(out)?;
512            } else {
513                out.push('[');
514                for (i, (a, x)) in fs.iter().enumerate() {
515                    if i > 0 {
516                        out.push_str(", ");
517                    }
518                    out.push_str(a.as_str());
519                    out.push_str(": ");
520                    write_value(x, ctx, mode, out)?;
521                }
522                out.push(']');
523            }
524        }
525        SetRepr::Product(fs) => {
526            if mode.converted_products {
527                return write_error_product(s, fs, ctx, mode, out);
528            }
529            if expand(product_bound(fs.iter(), ctx, mode).map(|n| n < ENUM_BOUND))? {
530                enumerated(out)?;
531            } else if !fs.is_empty() {
532                out.push('(');
533                for (i, x) in fs.iter().enumerate() {
534                    if i > 0 {
535                        out.push_str(" \\X ");
536                    }
537                    write_value(x, ctx, mode, out)?;
538                }
539                out.push(')');
540            }
541        }
542        SetRepr::Nat => out.push_str("Nat"),
543        SetRepr::Int => out.push_str("Int"),
544        SetRepr::Strings => out.push_str("STRING"),
545        SetRepr::Seq(r) => {
546            out.push_str("Seq(");
547            write_value(r, ctx, mode, out)?;
548            out.push(')');
549        }
550    }
551    Ok(())
552}
553
554/// `SetOfTuplesValue.toString` catches expansion selection, including conversion,
555/// but renders the resulting collection or original axes outside that catch.
556fn write_error_product(
557    set: &crate::Set,
558    axes: &[Value],
559    ctx: Ctx,
560    mode: Mode,
561    out: &mut String,
562) -> Result<()> {
563    let expanded: Result<_> = (|| {
564        let bound = product_bound(axes.iter(), ctx, mode)?;
565        if bound >= ENUM_BOUND {
566            return Ok(None);
567        }
568        if bound == 0 && concrete_empty(&Value::Set(set.clone()), 0) == Some(true) {
569            return Ok(Some((std::sync::Arc::from([]), None)));
570        }
571        let guard = Expansion::enter(set)?;
572        let elems = elems_in(set, ctx, true)?;
573        Ok(Some((elems, Some(guard))))
574    })();
575    match expanded {
576        Err(error)
577            if matches!(
578                error.kind(),
579                crate::ErrorKind::Interrupted { .. }
580                    | crate::ErrorKind::Unsupported
581                    | crate::ErrorKind::DeferredError { .. }
582                    | crate::ErrorKind::DiveLimit
583                    | crate::ErrorKind::Codec
584            ) =>
585        {
586            // Host control and deferred evaluator provenance are not a TLC
587            // expansion exception that this boundary can safely discard.
588            return Err(error);
589        }
590        Ok(Some((elems, _guard))) => {
591            out.push('{');
592            write_list(elems.iter(), ctx, mode, out)?;
593            out.push('}');
594        }
595        Ok(None) | Err(_) => {
596            if !axes.is_empty() {
597                out.push('(');
598                for (i, axis) in axes.iter().enumerate() {
599                    if i > 0 {
600                        out.push_str(" \\X ");
601                    }
602                    write_value(axis, ctx, mode, out)?;
603                }
604                out.push(')');
605            }
606        }
607    }
608    Ok(())
609}