oxilean_codegen/prolog_backend/
prologterm_traits.rs1use super::functions::fmt_dcg_seq;
12use super::types::PrologTerm;
13use std::fmt;
14
15impl fmt::Display for PrologTerm {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 match self {
18 PrologTerm::Atom(s) => write!(f, "{}", Self::fmt_atom(s)),
19 PrologTerm::Integer(n) => write!(f, "{}", n),
20 PrologTerm::Float(x) => {
21 let s = format!("{}", x);
22 if s.contains('.') {
23 write!(f, "{}", s)
24 } else {
25 write!(f, "{}.0", s)
26 }
27 }
28 PrologTerm::Variable(v) => write!(f, "{}", v),
29 PrologTerm::Anon => write!(f, "_"),
30 PrologTerm::Cut => write!(f, "!"),
31 PrologTerm::Nil => write!(f, "[]"),
32 PrologTerm::Compound(functor, args) => {
33 write!(f, "{}", Self::fmt_atom(functor))?;
34 write!(f, "(")?;
35 for (i, arg) in args.iter().enumerate() {
36 if i > 0 {
37 write!(f, ", ")?;
38 }
39 if arg.needs_parens_as_arg() {
40 write!(f, "({})", arg)?;
41 } else {
42 write!(f, "{}", arg)?;
43 }
44 }
45 write!(f, ")")
46 }
47 PrologTerm::List(elems, tail) => {
48 write!(f, "[")?;
49 for (i, e) in elems.iter().enumerate() {
50 if i > 0 {
51 write!(f, ", ")?;
52 }
53 write!(f, "{}", e)?;
54 }
55 if let Some(t) = tail {
56 if !elems.is_empty() {
57 write!(f, "|")?;
58 }
59 write!(f, "{}", t)?;
60 }
61 write!(f, "]")
62 }
63 PrologTerm::Op(op, lhs, rhs) => {
64 let lhs_s = if lhs.needs_parens_as_arg() {
65 format!("({})", lhs)
66 } else {
67 format!("{}", lhs)
68 };
69 let rhs_s = if rhs.needs_parens_as_arg() {
70 format!("({})", rhs)
71 } else {
72 format!("{}", rhs)
73 };
74 write!(f, "{} {} {}", lhs_s, op, rhs_s)
75 }
76 PrologTerm::PrefixOp(op, arg) => write!(f, "{}({})", op, arg),
77 PrologTerm::DcgPhrase(rule, list) => write!(f, "phrase({}, {})", rule, list),
78 }
79 }
80}