1#![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
30pub 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#[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
84pub fn print_value(v: &Value, ctx: Ctx) -> Result<String> {
89 Ok(ppr(&to_tlc_string(v, ctx)?))
90}
91
92pub 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
128pub 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#[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
165fn 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 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
186pub(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
195pub(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#[derive(Clone, Copy)]
207struct Mode {
208 swallow: bool,
210 mark: bool,
213 converted_products: bool,
215}
216
217pub(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
245fn 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
261fn 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 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
295fn 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
326const 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 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
400thread_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
554fn 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 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}