Skip to main content

litex/obj/
obj.rs

1use super::standard_set::StandardSet;
2use crate::prelude::*;
3use std::fmt;
4
5#[derive(Clone)]
6pub enum Obj {
7    Identifier(Identifier),
8    IdentifierWithMod(IdentifierWithMod),
9    FieldAccess(FieldAccess),
10    FieldAccessWithMod(FieldAccessWithMod),
11    FnObj(FnObj),
12    Number(Number),
13    Add(Add),
14    Sub(Sub),
15    Mul(Mul),
16    Div(Div),
17    Mod(Mod),
18    Pow(Pow),
19    Abs(Abs),
20    Log(Log),
21    Max(Max),
22    Min(Min),
23    Union(Union),
24    Intersect(Intersect),
25    SetMinus(SetMinus),
26    SetDiff(SetDiff),
27    Cup(Cup),
28    Cap(Cap),
29    PowerSet(PowerSet),
30    ListSet(ListSet),
31    SetBuilder(SetBuilder),
32    FnSet(FnSet),
33    Cart(Cart),
34    CartDim(CartDim),
35    Proj(Proj),
36    TupleDim(TupleDim),
37    Tuple(Tuple),
38    Count(Count),
39    Range(Range),
40    ClosedRange(ClosedRange),
41    FiniteSeqSet(FiniteSeqSet),
42    SeqSet(SeqSet),
43    FiniteSeqListObj(FiniteSeqListObj),
44    Choose(Choose),
45    ObjAtIndex(ObjAtIndex),
46    StandardSet(StandardSet),
47    FamilyObj(FamilyObj),
48    StructObj(StructObj),
49    MatrixSet(MatrixSet),
50    MatrixListObj(MatrixListObj),
51    MatrixAdd(MatrixAdd),
52    MatrixSub(MatrixSub),
53    MatrixMul(MatrixMul),
54    MatrixScalarMul(MatrixScalarMul),
55    MatrixPow(MatrixPow),
56}
57
58#[derive(Clone)]
59pub struct MatrixAdd {
60    pub left: Box<Obj>,
61    pub right: Box<Obj>,
62}
63
64#[derive(Clone)]
65pub struct MatrixSub {
66    pub left: Box<Obj>,
67    pub right: Box<Obj>,
68}
69
70#[derive(Clone)]
71pub struct MatrixMul {
72    pub left: Box<Obj>,
73    pub right: Box<Obj>,
74}
75
76#[derive(Clone)]
77pub struct MatrixScalarMul {
78    pub scalar: Box<Obj>,
79    pub matrix: Box<Obj>,
80}
81
82#[derive(Clone)]
83pub struct MatrixPow {
84    pub base: Box<Obj>,
85    pub exponent: Box<Obj>,
86}
87
88#[derive(Clone)]
89pub struct MatrixSet {
90    pub set: Box<Obj>,
91    pub row_len: Box<Obj>,
92    pub col_len: Box<Obj>,
93}
94
95#[derive(Clone)]
96pub struct MatrixListObj {
97    pub rows: Vec<Vec<Box<Obj>>>,
98}
99
100#[derive(Clone)]
101pub struct FamilyObj {
102    pub name: IdentifierOrIdentifierWithMod,
103    pub params: Vec<Obj>,
104}
105
106/// Instantiated struct type: `struct` name followed by argument objects (field types / indices).
107#[derive(Clone)]
108pub struct StructObj {
109    pub name: IdentifierOrIdentifierWithMod,
110    pub args: Vec<Obj>,
111}
112
113impl StructObj {
114    pub fn new(name: IdentifierOrIdentifierWithMod, args: Vec<Obj>) -> Self {
115        StructObj { name, args }
116    }
117}
118
119impl fmt::Display for FamilyObj {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        write!(
122            f,
123            "{} {}({})",
124            FAMILY,
125            self.name,
126            vec_to_string_join_by_comma(&self.params)
127        )
128    }
129}
130
131impl fmt::Display for StructObj {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        write!(
134            f,
135            "{} {}({})",
136            STRUCT,
137            self.name,
138            vec_to_string_join_by_comma(&self.args)
139        )
140    }
141}
142
143#[derive(Clone)]
144pub struct ObjAtIndex {
145    pub obj: Box<Obj>,
146    pub index: Box<Obj>,
147}
148
149#[derive(Clone)]
150pub struct Choose {
151    pub set: Box<Obj>,
152}
153
154#[derive(Clone)]
155pub struct PowerSet {
156    pub set: Box<Obj>,
157}
158
159#[derive(Clone)]
160pub struct Range {
161    pub start: Box<Obj>,
162    pub end: Box<Obj>,
163}
164
165#[derive(Clone)]
166pub struct ClosedRange {
167    pub start: Box<Obj>,
168    pub end: Box<Obj>,
169}
170
171/// Set of functions `fn(x N_pos: x <= n) s` (Lit surface syntax: keyword `finite_seq(s, n)`).
172#[derive(Clone)]
173pub struct FiniteSeqSet {
174    pub set: Box<Obj>,
175    pub n: Box<Obj>,
176}
177
178/// `seq(s)` — functions `fn(x N_pos) s` (no length bound; surface: keyword `seq(s)`).
179#[derive(Clone)]
180pub struct SeqSet {
181    pub set: Box<Obj>,
182}
183
184/// Literal `[a, b, ...]` as a finite sequence value (for membership in `finite_seq(s, n)`).
185#[derive(Clone)]
186pub struct FiniteSeqListObj {
187    pub objs: Vec<Box<Obj>>,
188}
189
190#[derive(Clone)]
191pub struct Count {
192    pub set: Box<Obj>,
193}
194
195#[derive(Clone)]
196pub struct Tuple {
197    pub args: Vec<Box<Obj>>,
198}
199
200#[derive(Clone)]
201pub struct TupleDim {
202    pub arg: Box<Obj>,
203}
204
205#[derive(Clone)]
206pub struct CartDim {
207    pub set: Box<Obj>,
208}
209
210#[derive(Clone)]
211pub struct Proj {
212    pub set: Box<Obj>,
213    pub dim: Box<Obj>,
214}
215
216#[derive(Clone)]
217pub struct FnObj {
218    pub head: Box<Atom>,
219    pub body: Vec<Vec<Box<Obj>>>,
220}
221
222#[derive(Clone)]
223pub struct Number {
224    pub normalized_value: String,
225}
226
227#[derive(Clone)]
228pub struct Add {
229    pub left: Box<Obj>,
230    pub right: Box<Obj>,
231}
232
233#[derive(Clone)]
234pub struct Sub {
235    pub left: Box<Obj>,
236    pub right: Box<Obj>,
237}
238
239#[derive(Clone)]
240pub struct Mul {
241    pub left: Box<Obj>,
242    pub right: Box<Obj>,
243}
244
245#[derive(Clone)]
246pub struct Div {
247    pub left: Box<Obj>,
248    pub right: Box<Obj>,
249}
250
251#[derive(Clone)]
252pub struct Mod {
253    pub left: Box<Obj>,
254    pub right: Box<Obj>,
255}
256
257#[derive(Clone)]
258pub struct Pow {
259    pub base: Box<Obj>,
260    pub exponent: Box<Obj>,
261}
262
263#[derive(Clone)]
264pub struct Abs {
265    pub arg: Box<Obj>,
266}
267
268/// Real logarithm `log(base, x)` with `base > 0`, `base != 1`, `x > 0`.
269#[derive(Clone)]
270pub struct Log {
271    pub base: Box<Obj>,
272    pub arg: Box<Obj>,
273}
274
275#[derive(Clone)]
276pub struct Max {
277    pub left: Box<Obj>,
278    pub right: Box<Obj>,
279}
280
281#[derive(Clone)]
282pub struct Min {
283    pub left: Box<Obj>,
284    pub right: Box<Obj>,
285}
286
287#[derive(Clone)]
288pub struct Union {
289    pub left: Box<Obj>,
290    pub right: Box<Obj>,
291}
292
293#[derive(Clone)]
294pub struct Intersect {
295    pub left: Box<Obj>,
296    pub right: Box<Obj>,
297}
298
299#[derive(Clone)]
300pub struct SetMinus {
301    pub left: Box<Obj>,
302    pub right: Box<Obj>,
303}
304
305#[derive(Clone)]
306pub struct SetDiff {
307    pub left: Box<Obj>,
308    pub right: Box<Obj>,
309}
310
311#[derive(Clone)]
312pub struct Cup {
313    pub left: Box<Obj>,
314}
315
316#[derive(Clone)]
317pub struct Cap {
318    pub left: Box<Obj>,
319}
320
321#[derive(Clone)]
322pub struct ListSet {
323    pub list: Vec<Box<Obj>>,
324}
325
326#[derive(Clone)]
327pub struct SetBuilder {
328    pub param: String,
329    pub param_set: Box<Obj>,
330    pub facts: Vec<OrAndChainAtomicFact>,
331}
332
333#[derive(Clone)]
334pub struct FnSet {
335    pub params_def_with_set: Vec<ParamGroupWithSet>,
336    pub dom_facts: Vec<OrAndChainAtomicFact>,
337    pub ret_set: Box<Obj>,
338}
339
340#[derive(Clone)]
341pub struct Cart {
342    pub args: Vec<Box<Obj>>,
343}
344
345impl ObjAtIndex {
346    pub fn new(obj: Obj, index: Obj) -> Self {
347        ObjAtIndex {
348            obj: Box::new(obj),
349            index: Box::new(index),
350        }
351    }
352}
353
354impl FnObj {
355    pub fn new(head: Atom, body: Vec<Vec<Box<Obj>>>) -> Self {
356        FnObj {
357            head: Box::new(head),
358            body,
359        }
360    }
361}
362
363impl Number {
364    pub fn new(value: String) -> Self {
365        Number {
366            normalized_value: normalize_decimal_number_string(&value),
367        }
368    }
369}
370
371impl Add {
372    pub fn new(left: Obj, right: Obj) -> Self {
373        Add {
374            left: Box::new(left),
375            right: Box::new(right),
376        }
377    }
378}
379
380impl Sub {
381    pub fn new(left: Obj, right: Obj) -> Self {
382        Sub {
383            left: Box::new(left),
384            right: Box::new(right),
385        }
386    }
387}
388
389impl Mul {
390    pub fn new(left: Obj, right: Obj) -> Self {
391        Mul {
392            left: Box::new(left),
393            right: Box::new(right),
394        }
395    }
396}
397
398impl Div {
399    pub fn new(left: Obj, right: Obj) -> Self {
400        Div {
401            left: Box::new(left),
402            right: Box::new(right),
403        }
404    }
405}
406
407impl Mod {
408    pub fn new(left: Obj, right: Obj) -> Self {
409        Mod {
410            left: Box::new(left),
411            right: Box::new(right),
412        }
413    }
414}
415
416impl Pow {
417    pub fn new(base: Obj, exponent: Obj) -> Self {
418        Pow {
419            base: Box::new(base),
420            exponent: Box::new(exponent),
421        }
422    }
423}
424
425impl Abs {
426    pub fn new(arg: Obj) -> Self {
427        Abs { arg: Box::new(arg) }
428    }
429}
430
431impl Log {
432    pub fn new(base: Obj, arg: Obj) -> Self {
433        Log {
434            base: Box::new(base),
435            arg: Box::new(arg),
436        }
437    }
438}
439
440impl Max {
441    pub fn new(left: Obj, right: Obj) -> Self {
442        Max {
443            left: Box::new(left),
444            right: Box::new(right),
445        }
446    }
447}
448
449impl Min {
450    pub fn new(left: Obj, right: Obj) -> Self {
451        Min {
452            left: Box::new(left),
453            right: Box::new(right),
454        }
455    }
456}
457
458impl Union {
459    pub fn new(left: Obj, right: Obj) -> Self {
460        Union {
461            left: Box::new(left),
462            right: Box::new(right),
463        }
464    }
465}
466
467impl Intersect {
468    pub fn new(left: Obj, right: Obj) -> Self {
469        Intersect {
470            left: Box::new(left),
471            right: Box::new(right),
472        }
473    }
474}
475
476impl SetMinus {
477    pub fn new(left: Obj, right: Obj) -> Self {
478        SetMinus {
479            left: Box::new(left),
480            right: Box::new(right),
481        }
482    }
483}
484
485impl SetDiff {
486    pub fn new(left: Obj, right: Obj) -> Self {
487        SetDiff {
488            left: Box::new(left),
489            right: Box::new(right),
490        }
491    }
492}
493
494impl Cup {
495    pub fn new(left: Obj) -> Self {
496        Cup {
497            left: Box::new(left),
498        }
499    }
500}
501
502impl Cap {
503    pub fn new(left: Obj) -> Self {
504        Cap {
505            left: Box::new(left),
506        }
507    }
508}
509
510impl ListSet {
511    pub fn new(list: Vec<Obj>) -> Self {
512        ListSet {
513            list: list.into_iter().map(Box::new).collect(),
514        }
515    }
516}
517
518impl SetBuilder {
519    pub fn new(param: String, param_set: Obj, facts: Vec<OrAndChainAtomicFact>) -> Self {
520        SetBuilder {
521            param: param,
522            param_set: Box::new(param_set),
523            facts,
524        }
525    }
526
527    // Same storage shape as parsing `{user cart(...): ...}`: bound name is `__` + user (facts rewritten).
528    pub fn new_with_mangled_name(
529        user_param: String,
530        param_set: Obj,
531        facts: Vec<OrAndChainAtomicFact>,
532    ) -> Self {
533        let mangled = format!("{}{}", DEFAULT_MANGLED_FN_PARAM_PREFIX, user_param);
534        let param_set = Obj::replace_bound_identifier(param_set, &user_param, &mangled);
535        let facts = facts
536            .into_iter()
537            .map(|f| f.replace_bound_identifier(&user_param, &mangled))
538            .collect();
539        Self::new(mangled, param_set, facts)
540    }
541}
542
543impl FnSet {
544    pub fn new(
545        params_and_their_sets: Vec<ParamGroupWithSet>,
546        dom_facts: Vec<OrAndChainAtomicFact>,
547        ret_set: Obj,
548    ) -> Self {
549        FnSet {
550            params_def_with_set: params_and_their_sets,
551            dom_facts,
552            ret_set: Box::new(ret_set),
553        }
554    }
555
556    pub fn get_params(&self) -> Vec<String> {
557        let mut ret = Vec::with_capacity(ParamGroupWithSet::number_of_params(
558            &self.params_def_with_set,
559        ));
560        for param_def_with_set in &self.params_def_with_set {
561            ret.extend(param_def_with_set.params.iter().cloned());
562        }
563        ret
564    }
565}
566
567impl PowerSet {
568    pub fn new(set: Obj) -> Self {
569        PowerSet { set: Box::new(set) }
570    }
571}
572
573impl Choose {
574    pub fn new(set: Obj) -> Self {
575        Choose { set: Box::new(set) }
576    }
577}
578
579impl CartDim {
580    pub fn new(set: Obj) -> Self {
581        CartDim { set: Box::new(set) }
582    }
583}
584
585impl Proj {
586    pub fn new(set: Obj, dim: Obj) -> Self {
587        Proj {
588            set: Box::new(set),
589            dim: Box::new(dim),
590        }
591    }
592}
593
594impl TupleDim {
595    pub fn new(dim: Obj) -> Self {
596        TupleDim { arg: Box::new(dim) }
597    }
598}
599
600impl Cart {
601    pub fn new(args: Vec<Obj>) -> Self {
602        let n = args.len();
603        if n < 2 {
604            panic!("Cart::new: expected at least 2 factors, got {n}");
605        }
606        Cart {
607            args: args.into_iter().map(Box::new).collect(),
608        }
609    }
610}
611
612impl Tuple {
613    pub fn new(elements: Vec<Obj>) -> Self {
614        let n = elements.len();
615        if n < 2 {
616            panic!("Tuple::new: expected at least 2 elements, got {n}");
617        }
618        Tuple {
619            args: elements.into_iter().map(Box::new).collect(),
620        }
621    }
622}
623
624impl Count {
625    pub fn new(set: Obj) -> Self {
626        Count { set: Box::new(set) }
627    }
628}
629
630impl Range {
631    pub fn new(start: Obj, end: Obj) -> Self {
632        Range {
633            start: Box::new(start),
634            end: Box::new(end),
635        }
636    }
637}
638
639impl ClosedRange {
640    pub fn new(start: Obj, end: Obj) -> Self {
641        ClosedRange {
642            start: Box::new(start),
643            end: Box::new(end),
644        }
645    }
646}
647
648impl FiniteSeqSet {
649    pub fn new(set: Obj, n: Obj) -> Self {
650        FiniteSeqSet {
651            set: Box::new(set),
652            n: Box::new(n),
653        }
654    }
655}
656
657impl SeqSet {
658    pub fn new(set: Obj) -> Self {
659        SeqSet {
660            set: Box::new(set),
661        }
662    }
663}
664
665impl FiniteSeqListObj {
666    pub fn new(objs: Vec<Obj>) -> Self {
667        FiniteSeqListObj {
668            objs: objs.into_iter().map(Box::new).collect(),
669        }
670    }
671}
672
673impl MatrixSet {
674    pub fn new(set: Obj, row_len: Obj, col_len: Obj) -> Self {
675        MatrixSet {
676            set: Box::new(set),
677            row_len: Box::new(row_len),
678            col_len: Box::new(col_len),
679        }
680    }
681}
682
683impl MatrixListObj {
684    pub fn new(rows: Vec<Vec<Obj>>) -> Self {
685        MatrixListObj {
686            rows: rows
687                .into_iter()
688                .map(|row| row.into_iter().map(Box::new).collect())
689                .collect(),
690        }
691    }
692}
693
694impl MatrixAdd {
695    pub fn new(left: Obj, right: Obj) -> Self {
696        MatrixAdd {
697            left: Box::new(left),
698            right: Box::new(right),
699        }
700    }
701}
702
703impl MatrixSub {
704    pub fn new(left: Obj, right: Obj) -> Self {
705        MatrixSub {
706            left: Box::new(left),
707            right: Box::new(right),
708        }
709    }
710}
711
712impl MatrixMul {
713    pub fn new(left: Obj, right: Obj) -> Self {
714        MatrixMul {
715            left: Box::new(left),
716            right: Box::new(right),
717        }
718    }
719}
720
721impl MatrixScalarMul {
722    pub fn new(scalar: Obj, matrix: Obj) -> Self {
723        MatrixScalarMul {
724            scalar: Box::new(scalar),
725            matrix: Box::new(matrix),
726        }
727    }
728}
729
730impl MatrixPow {
731    pub fn new(base: Obj, exponent: Obj) -> Self {
732        MatrixPow {
733            base: Box::new(base),
734            exponent: Box::new(exponent),
735        }
736    }
737}
738
739/// 算术运算符优先级:数值越小绑定越紧。^ / matrix ops =1, * / % / *. =2, + -=3;非算术=0 不参与括号。
740fn precedence(o: &Obj) -> u8 {
741    match o {
742        Obj::Add(_) | Obj::Sub(_) => 3,
743        Obj::Mul(_)
744        | Obj::Div(_)
745        | Obj::Mod(_)
746        | Obj::Max(_)
747        | Obj::Min(_)
748        | Obj::MatrixScalarMul(_) => 2,
749        Obj::Pow(_)
750        | Obj::Abs(_)
751        | Obj::Log(_)
752        | Obj::MatrixAdd(_)
753        | Obj::MatrixSub(_)
754        | Obj::MatrixMul(_)
755        | Obj::MatrixPow(_) => 1,
756        _ => 0,
757    }
758}
759
760impl fmt::Display for Obj {
761    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762        self.fmt_with_precedence(f, 0)
763    }
764}
765
766impl Obj {
767    /// 按优先级输出:当子表达式优先级低于父节点时自动加括号,例如 ^ 下出现 + 则写成 (a + b)。
768    pub fn fmt_with_precedence(
769        &self,
770        f: &mut fmt::Formatter<'_>,
771        parent_precedent: u8,
772    ) -> fmt::Result {
773        let precedent = precedence(self);
774        let need_parens = parent_precedent != 0 && precedent != 0 && precedent > parent_precedent;
775        if need_parens {
776            write!(f, "{}", LEFT_BRACE)?;
777        }
778        match self {
779            Obj::Add(a) => {
780                a.left.fmt_with_precedence(f, 3)?;
781                write!(f, " {} ", ADD)?;
782                a.right.fmt_with_precedence(f, 3)?;
783            }
784            Obj::Sub(s) => {
785                s.left.fmt_with_precedence(f, 3)?;
786                write!(f, " {} ", SUB)?;
787                s.right.fmt_with_precedence(f, 3)?;
788            }
789            Obj::Mul(m) => {
790                m.left.fmt_with_precedence(f, 2)?;
791                write!(f, " {} ", MUL)?;
792                m.right.fmt_with_precedence(f, 2)?;
793            }
794            Obj::Div(d) => {
795                d.left.fmt_with_precedence(f, 2)?;
796                write!(f, " {} ", DIV)?;
797                d.right.fmt_with_precedence(f, 2)?;
798            }
799            Obj::Mod(m) => {
800                m.left.fmt_with_precedence(f, 2)?;
801                write!(f, " {} ", MOD)?;
802                m.right.fmt_with_precedence(f, 2)?;
803            }
804            Obj::Pow(p) => {
805                p.base.fmt_with_precedence(f, 1)?;
806                write!(f, " {} ", POW)?;
807                p.exponent.fmt_with_precedence(f, 1)?;
808            }
809            Obj::MatrixAdd(m) => {
810                m.left.fmt_with_precedence(f, 1)?;
811                write!(f, " {} ", MATRIX_ADD)?;
812                m.right.fmt_with_precedence(f, 1)?;
813            }
814            Obj::MatrixSub(m) => {
815                m.left.fmt_with_precedence(f, 1)?;
816                write!(f, " {} ", MATRIX_SUB)?;
817                m.right.fmt_with_precedence(f, 1)?;
818            }
819            Obj::MatrixMul(m) => {
820                m.left.fmt_with_precedence(f, 1)?;
821                write!(f, " {} ", MATRIX_MUL)?;
822                m.right.fmt_with_precedence(f, 1)?;
823            }
824            Obj::MatrixPow(m) => {
825                m.base.fmt_with_precedence(f, 1)?;
826                write!(f, " {} ", MATRIX_POW)?;
827                m.exponent.fmt_with_precedence(f, 1)?;
828            }
829            Obj::MatrixScalarMul(m) => {
830                m.scalar.fmt_with_precedence(f, 2)?;
831                write!(f, " {} ", MATRIX_SCALAR_MUL)?;
832                m.matrix.fmt_with_precedence(f, 2)?;
833            }
834            Obj::Abs(a) => {
835                write!(f, "{} {}", ABS, LEFT_BRACE)?;
836                a.arg.fmt_with_precedence(f, 0)?;
837                write!(f, "{}", RIGHT_BRACE)?;
838            }
839            Obj::Log(l) => {
840                write!(f, "{} {}", LOG, LEFT_BRACE)?;
841                l.base.fmt_with_precedence(f, 0)?;
842                write!(f, "{} ", COMMA)?;
843                l.arg.fmt_with_precedence(f, 0)?;
844                write!(f, "{}", RIGHT_BRACE)?;
845            }
846            Obj::Max(m) => {
847                write!(f, "{} {}", MAX, LEFT_BRACE)?;
848                m.left.fmt_with_precedence(f, 0)?;
849                write!(f, "{} ", COMMA)?;
850                m.right.fmt_with_precedence(f, 0)?;
851                write!(f, "{}", RIGHT_BRACE)?;
852            }
853            Obj::Min(m) => {
854                write!(f, "{} {}", MIN, LEFT_BRACE)?;
855                m.left.fmt_with_precedence(f, 0)?;
856                write!(f, "{} ", COMMA)?;
857                m.right.fmt_with_precedence(f, 0)?;
858                write!(f, "{}", RIGHT_BRACE)?;
859            }
860            Obj::Union(x) => write!(f, "{}", x)?,
861            Obj::Intersect(x) => write!(f, "{}", x)?,
862            Obj::SetMinus(x) => write!(f, "{}", x)?,
863            Obj::SetDiff(x) => write!(f, "{}", x)?,
864            Obj::Cup(x) => write!(f, "{}", x)?,
865            Obj::Cap(x) => write!(f, "{}", x)?,
866            Obj::Identifier(x) => write!(f, "{}", x)?,
867            Obj::IdentifierWithMod(x) => write!(f, "{}", x)?,
868            Obj::FieldAccess(x) => write!(f, "{}", x)?,
869            Obj::FieldAccessWithMod(x) => write!(f, "{}", x)?,
870            Obj::FnObj(x) => write!(f, "{}", x)?,
871            Obj::Number(x) => write!(f, "{}", x)?,
872            Obj::ListSet(x) => write!(f, "{}", x)?,
873            Obj::SetBuilder(x) => write!(f, "{}", x)?,
874            Obj::FnSet(x) => write!(f, "{}", x)?,
875            Obj::StandardSet(standard_set) => write!(f, "{}", standard_set)?,
876            Obj::Cart(x) => write!(f, "{}", x)?,
877            Obj::CartDim(x) => write!(f, "{}", x)?,
878            Obj::Proj(x) => write!(f, "{}", x)?,
879            Obj::TupleDim(x) => write!(f, "{}", x)?,
880            Obj::Tuple(x) => write!(f, "{}", x)?,
881            Obj::Count(x) => write!(f, "{}", x)?,
882            Obj::Range(x) => write!(f, "{}", x)?,
883            Obj::ClosedRange(x) => write!(f, "{}", x)?,
884            Obj::FiniteSeqSet(x) => write!(f, "{}", x)?,
885            Obj::SeqSet(x) => write!(f, "{}", x)?,
886            Obj::FiniteSeqListObj(x) => write!(f, "{}", x)?,
887            Obj::MatrixSet(x) => write!(f, "{}", x)?,
888            Obj::MatrixListObj(x) => write!(f, "{}", x)?,
889            Obj::PowerSet(x) => write!(f, "{}", x)?,
890            Obj::Choose(x) => write!(f, "{}", x)?,
891            Obj::ObjAtIndex(x) => write!(f, "{}", x)?,
892            Obj::FamilyObj(x) => write!(f, "{}", x)?,
893            Obj::StructObj(x) => write!(f, "{}", x)?,
894        }
895        if need_parens {
896            write!(f, "{}", RIGHT_BRACE)?;
897        }
898        Ok(())
899    }
900
901    pub fn replace_bound_identifier(self, from: &str, to: &str) -> Obj {
902        if from == to {
903            return self;
904        }
905        match self {
906            Obj::Identifier(i) => {
907                if i.name == from {
908                    to.to_string().into()
909                } else {
910                    i.into()
911                }
912            }
913            Obj::IdentifierWithMod(m) => {
914                let name = if m.name == from {
915                    to.to_string()
916                } else {
917                    m.name
918                };
919                IdentifierWithMod::new(m.mod_name, name).into()
920            }
921            Obj::FieldAccess(f) => {
922                let name = if f.name == from {
923                    to.to_string()
924                } else {
925                    f.name
926                };
927                FieldAccess::new(name, f.field).into()
928            }
929            Obj::FieldAccessWithMod(f) => {
930                let name = if f.name == from {
931                    to.to_string()
932                } else {
933                    f.name
934                };
935                FieldAccessWithMod::new(f.mod_name, name, f.field).into()
936            }
937            Obj::FnObj(inner) => {
938                let head = replace_bound_identifier_in_atom(*inner.head, from, to);
939                let body = inner
940                    .body
941                    .into_iter()
942                    .map(|group| {
943                        group
944                            .into_iter()
945                            .map(|b| Box::new(Obj::replace_bound_identifier(*b, from, to)))
946                            .collect()
947                    })
948                    .collect();
949                FnObj::new(head, body).into()
950            }
951            Obj::Number(n) => n.into(),
952            Obj::Add(x) => Add::new(
953                Obj::replace_bound_identifier(*x.left, from, to),
954                Obj::replace_bound_identifier(*x.right, from, to),
955            )
956            .into(),
957            Obj::Sub(x) => Sub::new(
958                Obj::replace_bound_identifier(*x.left, from, to),
959                Obj::replace_bound_identifier(*x.right, from, to),
960            )
961            .into(),
962            Obj::Mul(x) => Mul::new(
963                Obj::replace_bound_identifier(*x.left, from, to),
964                Obj::replace_bound_identifier(*x.right, from, to),
965            )
966            .into(),
967            Obj::Div(x) => Div::new(
968                Obj::replace_bound_identifier(*x.left, from, to),
969                Obj::replace_bound_identifier(*x.right, from, to),
970            )
971            .into(),
972            Obj::Mod(x) => Mod::new(
973                Obj::replace_bound_identifier(*x.left, from, to),
974                Obj::replace_bound_identifier(*x.right, from, to),
975            )
976            .into(),
977            Obj::Pow(x) => Pow::new(
978                Obj::replace_bound_identifier(*x.base, from, to),
979                Obj::replace_bound_identifier(*x.exponent, from, to),
980            )
981            .into(),
982            Obj::Abs(x) => Abs::new(Obj::replace_bound_identifier(*x.arg, from, to)).into(),
983            Obj::Log(x) => Log::new(
984                Obj::replace_bound_identifier(*x.base, from, to),
985                Obj::replace_bound_identifier(*x.arg, from, to),
986            )
987            .into(),
988            Obj::Max(x) => Max::new(
989                Obj::replace_bound_identifier(*x.left, from, to),
990                Obj::replace_bound_identifier(*x.right, from, to),
991            )
992            .into(),
993            Obj::Min(x) => Min::new(
994                Obj::replace_bound_identifier(*x.left, from, to),
995                Obj::replace_bound_identifier(*x.right, from, to),
996            )
997            .into(),
998            Obj::Union(x) => Union::new(
999                Obj::replace_bound_identifier(*x.left, from, to),
1000                Obj::replace_bound_identifier(*x.right, from, to),
1001            )
1002            .into(),
1003            Obj::Intersect(x) => Intersect::new(
1004                Obj::replace_bound_identifier(*x.left, from, to),
1005                Obj::replace_bound_identifier(*x.right, from, to),
1006            )
1007            .into(),
1008            Obj::SetMinus(x) => SetMinus::new(
1009                Obj::replace_bound_identifier(*x.left, from, to),
1010                Obj::replace_bound_identifier(*x.right, from, to),
1011            )
1012            .into(),
1013            Obj::SetDiff(x) => SetDiff::new(
1014                Obj::replace_bound_identifier(*x.left, from, to),
1015                Obj::replace_bound_identifier(*x.right, from, to),
1016            )
1017            .into(),
1018            Obj::Cup(x) => Cup::new(Obj::replace_bound_identifier(*x.left, from, to)).into(),
1019            Obj::Cap(x) => Cap::new(Obj::replace_bound_identifier(*x.left, from, to)).into(),
1020            Obj::PowerSet(x) => {
1021                PowerSet::new(Obj::replace_bound_identifier(*x.set, from, to)).into()
1022            }
1023            Obj::ListSet(x) => ListSet::new(
1024                x.list
1025                    .into_iter()
1026                    .map(|b| Obj::replace_bound_identifier(*b, from, to))
1027                    .collect(),
1028            )
1029            .into(),
1030            Obj::SetBuilder(sb) => {
1031                let param = if sb.param == from {
1032                    to.to_string()
1033                } else {
1034                    sb.param
1035                };
1036                let param_set = Box::new(Obj::replace_bound_identifier(*sb.param_set, from, to));
1037                let facts = sb
1038                    .facts
1039                    .into_iter()
1040                    .map(|f| f.replace_bound_identifier(from, to))
1041                    .collect();
1042                Obj::SetBuilder(SetBuilder {
1043                    param,
1044                    param_set,
1045                    facts,
1046                })
1047            }
1048            Obj::FnSet(fs) => {
1049                let params_def_with_set = fs
1050                    .params_def_with_set
1051                    .into_iter()
1052                    .map(|pg| ParamGroupWithSet {
1053                        params: pg
1054                            .params
1055                            .into_iter()
1056                            .map(|p| if p == from { to.to_string() } else { p })
1057                            .collect(),
1058                        set: Obj::replace_bound_identifier(pg.set, from, to),
1059                    })
1060                    .collect();
1061                let dom_facts = fs
1062                    .dom_facts
1063                    .into_iter()
1064                    .map(|f| f.replace_bound_identifier(from, to))
1065                    .collect();
1066                let ret_set = Obj::replace_bound_identifier(*fs.ret_set, from, to);
1067                FnSet::new(params_def_with_set, dom_facts, ret_set).into()
1068            }
1069            Obj::Cart(c) => Cart::new(
1070                c.args
1071                    .into_iter()
1072                    .map(|b| Obj::replace_bound_identifier(*b, from, to))
1073                    .collect(),
1074            )
1075            .into(),
1076            Obj::CartDim(x) => CartDim::new(Obj::replace_bound_identifier(*x.set, from, to)).into(),
1077            Obj::Proj(x) => Proj::new(
1078                Obj::replace_bound_identifier(*x.set, from, to),
1079                Obj::replace_bound_identifier(*x.dim, from, to),
1080            )
1081            .into(),
1082            Obj::TupleDim(x) => {
1083                TupleDim::new(Obj::replace_bound_identifier(*x.arg, from, to)).into()
1084            }
1085            Obj::Tuple(t) => Tuple::new(
1086                t.args
1087                    .into_iter()
1088                    .map(|b| Obj::replace_bound_identifier(*b, from, to))
1089                    .collect(),
1090            )
1091            .into(),
1092            Obj::Count(x) => Count::new(Obj::replace_bound_identifier(*x.set, from, to)).into(),
1093            Obj::Range(x) => Range::new(
1094                Obj::replace_bound_identifier(*x.start, from, to),
1095                Obj::replace_bound_identifier(*x.end, from, to),
1096            )
1097            .into(),
1098            Obj::ClosedRange(x) => ClosedRange::new(
1099                Obj::replace_bound_identifier(*x.start, from, to),
1100                Obj::replace_bound_identifier(*x.end, from, to),
1101            )
1102            .into(),
1103            Obj::FiniteSeqSet(x) => FiniteSeqSet::new(
1104                Obj::replace_bound_identifier(*x.set, from, to),
1105                Obj::replace_bound_identifier(*x.n, from, to),
1106            )
1107            .into(),
1108            Obj::SeqSet(x) => {
1109                SeqSet::new(Obj::replace_bound_identifier(*x.set, from, to)).into()
1110            }
1111            Obj::FiniteSeqListObj(x) => FiniteSeqListObj::new(
1112                x.objs
1113                    .into_iter()
1114                    .map(|b| Obj::replace_bound_identifier(*b, from, to))
1115                    .collect(),
1116            )
1117            .into(),
1118            Obj::MatrixSet(x) => MatrixSet::new(
1119                Obj::replace_bound_identifier(*x.set, from, to),
1120                Obj::replace_bound_identifier(*x.row_len, from, to),
1121                Obj::replace_bound_identifier(*x.col_len, from, to),
1122            )
1123            .into(),
1124            Obj::MatrixListObj(x) => MatrixListObj::new(
1125                x.rows
1126                    .into_iter()
1127                    .map(|row| {
1128                        row.into_iter()
1129                            .map(|b| Obj::replace_bound_identifier(*b, from, to))
1130                            .collect()
1131                    })
1132                    .collect(),
1133            )
1134            .into(),
1135            Obj::MatrixAdd(x) => MatrixAdd::new(
1136                Obj::replace_bound_identifier(*x.left, from, to),
1137                Obj::replace_bound_identifier(*x.right, from, to),
1138            )
1139            .into(),
1140            Obj::MatrixSub(x) => MatrixSub::new(
1141                Obj::replace_bound_identifier(*x.left, from, to),
1142                Obj::replace_bound_identifier(*x.right, from, to),
1143            )
1144            .into(),
1145            Obj::MatrixMul(x) => MatrixMul::new(
1146                Obj::replace_bound_identifier(*x.left, from, to),
1147                Obj::replace_bound_identifier(*x.right, from, to),
1148            )
1149            .into(),
1150            Obj::MatrixScalarMul(x) => MatrixScalarMul::new(
1151                Obj::replace_bound_identifier(*x.scalar, from, to),
1152                Obj::replace_bound_identifier(*x.matrix, from, to),
1153            )
1154            .into(),
1155            Obj::MatrixPow(x) => MatrixPow::new(
1156                Obj::replace_bound_identifier(*x.base, from, to),
1157                Obj::replace_bound_identifier(*x.exponent, from, to),
1158            )
1159            .into(),
1160            Obj::Choose(x) => Choose::new(Obj::replace_bound_identifier(*x.set, from, to)).into(),
1161            Obj::ObjAtIndex(x) => ObjAtIndex::new(
1162                Obj::replace_bound_identifier(*x.obj, from, to),
1163                Obj::replace_bound_identifier(*x.index, from, to),
1164            )
1165            .into(),
1166            Obj::StandardSet(s) => s.into(),
1167            Obj::FamilyObj(f) => FamilyObj {
1168                name: f.name,
1169                params: f
1170                    .params
1171                    .into_iter()
1172                    .map(|o| Obj::replace_bound_identifier(o, from, to))
1173                    .collect(),
1174            }
1175            .into(),
1176            Obj::StructObj(s) => StructObj::new(
1177                s.name,
1178                s.args
1179                    .into_iter()
1180                    .map(|o| Obj::replace_bound_identifier(o, from, to))
1181                    .collect(),
1182            )
1183            .into(),
1184        }
1185    }
1186}
1187
1188fn replace_bound_identifier_in_atom(atom: Atom, from: &str, to: &str) -> Atom {
1189    if from == to {
1190        return atom;
1191    }
1192    match atom {
1193        Atom::Identifier(i) => {
1194            if i.name == from {
1195                Identifier::new(to.to_string()).into()
1196            } else {
1197                i.into()
1198            }
1199        }
1200        Atom::IdentifierWithMod(m) => {
1201            let name = if m.name == from {
1202                to.to_string()
1203            } else {
1204                m.name
1205            };
1206            IdentifierWithMod::new(m.mod_name, name).into()
1207        }
1208        Atom::FieldAccess(f) => {
1209            let name = if f.name == from {
1210                to.to_string()
1211            } else {
1212                f.name
1213            };
1214            FieldAccess::new(name, f.field).into()
1215        }
1216        Atom::FieldAccessWithMod(f) => {
1217            let name = if f.name == from {
1218                to.to_string()
1219            } else {
1220                f.name
1221            };
1222            FieldAccessWithMod::new(f.mod_name, name, f.field).into()
1223        }
1224    }
1225}
1226
1227impl fmt::Display for ObjAtIndex {
1228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1229        write!(
1230            f,
1231            "{}{}{}{}",
1232            self.obj, LEFT_BRACKET, self.index, RIGHT_BRACKET
1233        )
1234    }
1235}
1236
1237impl fmt::Display for Choose {
1238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1239        write!(
1240            f,
1241            "{}{}",
1242            CHOOSE,
1243            braced_vec_to_string(&vec![self.set.as_ref()])
1244        )
1245    }
1246}
1247
1248impl fmt::Display for Range {
1249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250        write!(
1251            f,
1252            "{}{}",
1253            RANGE,
1254            braced_vec_to_string(&vec![self.start.as_ref(), self.end.as_ref()])
1255        )
1256    }
1257}
1258
1259impl fmt::Display for ClosedRange {
1260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261        write!(
1262            f,
1263            "{}{}",
1264            CLOSED_RANGE,
1265            braced_vec_to_string(&vec![self.start.as_ref(), self.end.as_ref()])
1266        )
1267    }
1268}
1269
1270impl fmt::Display for FiniteSeqSet {
1271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1272        write!(
1273            f,
1274            "{}{}",
1275            FINITE_SEQ,
1276            braced_vec_to_string(&vec![self.set.as_ref(), self.n.as_ref()])
1277        )
1278    }
1279}
1280
1281impl fmt::Display for SeqSet {
1282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1283        write!(
1284            f,
1285            "{}{}",
1286            SEQ,
1287            braced_vec_to_string(&vec![self.set.as_ref()])
1288        )
1289    }
1290}
1291
1292impl fmt::Display for FiniteSeqListObj {
1293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1294        write!(f, "{}", LEFT_BRACKET)?;
1295        for (i, o) in self.objs.iter().enumerate() {
1296            if i > 0 {
1297                write!(f, "{} ", COMMA)?;
1298            }
1299            write!(f, "{}", o)?;
1300        }
1301        write!(f, "{}", RIGHT_BRACKET)
1302    }
1303}
1304
1305impl fmt::Display for MatrixSet {
1306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307        write!(
1308            f,
1309            "{}{}",
1310            MATRIX,
1311            braced_vec_to_string(&vec![
1312                self.set.as_ref(),
1313                self.row_len.as_ref(),
1314                self.col_len.as_ref(),
1315            ])
1316        )
1317    }
1318}
1319
1320impl fmt::Display for MatrixListObj {
1321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1322        write!(f, "{}", LEFT_BRACKET)?;
1323        for (ri, row) in self.rows.iter().enumerate() {
1324            if ri > 0 {
1325                write!(f, "{} ", COMMA)?;
1326            }
1327            write!(f, "{}", LEFT_BRACKET)?;
1328            for (ci, o) in row.iter().enumerate() {
1329                if ci > 0 {
1330                    write!(f, "{} ", COMMA)?;
1331                }
1332                write!(f, "{}", o)?;
1333            }
1334            write!(f, "{}", RIGHT_BRACKET)?;
1335        }
1336        write!(f, "{}", RIGHT_BRACKET)
1337    }
1338}
1339
1340impl fmt::Display for Count {
1341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342        write!(
1343            f,
1344            "{}{}",
1345            COUNT,
1346            braced_vec_to_string(&vec![self.set.as_ref()])
1347        )
1348    }
1349}
1350
1351impl fmt::Display for Tuple {
1352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1353        write!(f, "{}", braced_vec_to_string(&self.args))
1354    }
1355}
1356
1357impl fmt::Display for CartDim {
1358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1359        write!(
1360            f,
1361            "{}{}",
1362            CART_DIM,
1363            braced_vec_to_string(&vec![self.set.as_ref()])
1364        )
1365    }
1366}
1367
1368impl fmt::Display for Proj {
1369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1370        write!(
1371            f,
1372            "{}{}",
1373            PROJ,
1374            braced_vec_to_string(&vec![self.set.as_ref(), self.dim.as_ref()])
1375        )
1376    }
1377}
1378
1379impl fmt::Display for TupleDim {
1380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1381        write!(
1382            f,
1383            "{}{}",
1384            TUPLE_DIM,
1385            braced_vec_to_string(&vec![self.arg.as_ref()])
1386        )
1387    }
1388}
1389
1390impl fmt::Display for Identifier {
1391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1392        write!(f, "{}", self.name)
1393    }
1394}
1395
1396impl fmt::Display for FnObj {
1397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1398        write!(f, "{}", fn_obj_to_string(self.head.as_ref(), &self.body))
1399    }
1400}
1401
1402pub fn fn_obj_to_string(head: &Atom, body: &Vec<Vec<Box<Obj>>>) -> String {
1403    let mut fn_obj_string = head.to_string();
1404    for group in body.iter() {
1405        fn_obj_string = format!("{}{}", fn_obj_string, braced_vec_to_string(group));
1406    }
1407    fn_obj_string
1408}
1409
1410impl fmt::Display for Number {
1411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1412        write!(f, "{}", self.normalized_value)
1413    }
1414}
1415
1416impl fmt::Display for Add {
1417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1418        write!(f, "{} {} {}", self.left, ADD, self.right)
1419    }
1420}
1421
1422impl fmt::Display for Sub {
1423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1424        write!(f, "{} {} {}", self.left, SUB, self.right)
1425    }
1426}
1427
1428impl fmt::Display for Mul {
1429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1430        write!(f, "{} {} {}", self.left, MUL, self.right)
1431    }
1432}
1433
1434impl fmt::Display for Div {
1435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1436        write!(f, "{} {} {}", self.left, DIV, self.right)
1437    }
1438}
1439
1440impl fmt::Display for Mod {
1441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1442        write!(f, "{} {} {}", self.left, MOD, self.right)
1443    }
1444}
1445
1446impl fmt::Display for Pow {
1447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1448        write!(f, "{} {} {}", self.base, POW, self.exponent)
1449    }
1450}
1451
1452impl fmt::Display for MatrixAdd {
1453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454        write!(f, "{} {} {}", self.left, MATRIX_ADD, self.right)
1455    }
1456}
1457
1458impl fmt::Display for MatrixSub {
1459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1460        write!(f, "{} {} {}", self.left, MATRIX_SUB, self.right)
1461    }
1462}
1463
1464impl fmt::Display for MatrixMul {
1465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466        write!(f, "{} {} {}", self.left, MATRIX_MUL, self.right)
1467    }
1468}
1469
1470impl fmt::Display for MatrixScalarMul {
1471    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1472        write!(f, "{} {} {}", self.scalar, MATRIX_SCALAR_MUL, self.matrix)
1473    }
1474}
1475
1476impl fmt::Display for MatrixPow {
1477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1478        write!(f, "{} {} {}", self.base, MATRIX_POW, self.exponent)
1479    }
1480}
1481
1482impl fmt::Display for Abs {
1483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1484        write!(f, "{} {}{}{}", ABS, LEFT_BRACE, self.arg, RIGHT_BRACE)
1485    }
1486}
1487
1488impl fmt::Display for Log {
1489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1490        write!(
1491            f,
1492            "{} {}{}{}{}{}",
1493            LOG, LEFT_BRACE, self.base, COMMA, self.arg, RIGHT_BRACE
1494        )
1495    }
1496}
1497
1498impl fmt::Display for Max {
1499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1500        write!(
1501            f,
1502            "{} {}{}{}{}{}",
1503            MAX, LEFT_BRACE, self.left, COMMA, self.right, RIGHT_BRACE
1504        )
1505    }
1506}
1507
1508impl fmt::Display for Min {
1509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1510        write!(
1511            f,
1512            "{} {}{}{}{}{}",
1513            MIN, LEFT_BRACE, self.left, COMMA, self.right, RIGHT_BRACE
1514        )
1515    }
1516}
1517
1518impl fmt::Display for Union {
1519    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1520        write!(
1521            f,
1522            "{}{}",
1523            UNION,
1524            braced_vec_to_string(&vec![self.left.as_ref(), self.right.as_ref()])
1525        )
1526    }
1527}
1528
1529impl fmt::Display for Intersect {
1530    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531        write!(
1532            f,
1533            "{}{}",
1534            INTERSECT,
1535            braced_vec_to_string(&vec![self.left.as_ref(), self.right.as_ref()])
1536        )
1537    }
1538}
1539
1540impl fmt::Display for SetMinus {
1541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1542        write!(
1543            f,
1544            "{}{}",
1545            SET_MINUS,
1546            braced_vec_to_string(&vec![self.left.as_ref(), self.right.as_ref()])
1547        )
1548    }
1549}
1550
1551impl fmt::Display for SetDiff {
1552    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1553        write!(
1554            f,
1555            "{}{}",
1556            SET_DIFF,
1557            braced_vec_to_string(&vec![self.left.as_ref(), self.right.as_ref()])
1558        )
1559    }
1560}
1561
1562impl fmt::Display for Cup {
1563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1564        write!(
1565            f,
1566            "{}{}",
1567            CUP,
1568            braced_vec_to_string(&vec![self.left.as_ref()])
1569        )
1570    }
1571}
1572
1573impl fmt::Display for Cap {
1574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1575        write!(
1576            f,
1577            "{}{}",
1578            CAP,
1579            braced_vec_to_string(&vec![self.left.as_ref()])
1580        )
1581    }
1582}
1583
1584impl fmt::Display for IdentifierWithMod {
1585    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1586        write!(f, "{}{}{}", self.mod_name, MOD_SIGN, self.name)
1587    }
1588}
1589
1590impl fmt::Display for ListSet {
1591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592        write!(f, "{}", curly_braced_vec_to_string(&self.list))
1593    }
1594}
1595
1596impl fmt::Display for SetBuilder {
1597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1598        write!(
1599            f,
1600            "{}{} {}{} {}{}",
1601            LEFT_CURLY_BRACE,
1602            self.param,
1603            self.param_set,
1604            COLON,
1605            vec_to_string_join_by_comma(&self.facts),
1606            RIGHT_CURLY_BRACE
1607        )
1608    }
1609}
1610
1611impl fmt::Display for FnSet {
1612    /// 与 AST 一致:形参表、dom 均使用**存储名**(`fn` 形参为 `__` + 用户符面)。  
1613    /// 区别于单独 [`ParamGroupWithSet`] 的 `Display`(会隐去 `__` 以便其它上下文)。
1614    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1615        let params_with_sets_display: Vec<String> = self
1616            .params_def_with_set
1617            .iter()
1618            .map(|g| format!("{} {}", vec_to_string_join_by_comma(&g.params), g.set))
1619            .collect();
1620        write!(
1621            f,
1622            "{} {} {}",
1623            FN_LOWER_CASE,
1624            brace_vec_colon_vec_to_string(&params_with_sets_display, &self.dom_facts),
1625            self.ret_set
1626        )
1627    }
1628}
1629
1630impl fmt::Display for Cart {
1631    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1632        write!(f, "{}{}", CART, braced_vec_to_string(&self.args))
1633    }
1634}
1635
1636impl fmt::Display for PowerSet {
1637    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1638        write!(
1639            f,
1640            "{}{}",
1641            POWER_SET,
1642            braced_vec_to_string(&vec![self.set.as_ref()])
1643        )
1644    }
1645}
1646
1647impl From<Atom> for Obj {
1648    fn from(atom: Atom) -> Self {
1649        match atom {
1650            Atom::Identifier(a) => a.into(),
1651            Atom::IdentifierWithMod(a) => a.into(),
1652            Atom::FieldAccess(a) => a.into(),
1653            Atom::FieldAccessWithMod(a) => a.into(),
1654        }
1655    }
1656}
1657
1658impl From<Identifier> for Obj {
1659    fn from(id: Identifier) -> Self {
1660        Obj::Identifier(id)
1661    }
1662}
1663
1664impl From<String> for Obj {
1665    fn from(name: String) -> Self {
1666        Identifier::new(name).into()
1667    }
1668}
1669
1670impl From<&str> for Obj {
1671    fn from(name: &str) -> Self {
1672        Identifier::new(name.to_string()).into()
1673    }
1674}
1675
1676impl From<usize> for Obj {
1677    fn from(n: usize) -> Self {
1678        Number::new(n.to_string()).into()
1679    }
1680}
1681
1682impl From<Number> for Obj {
1683    fn from(n: Number) -> Self {
1684        Obj::Number(n)
1685    }
1686}
1687
1688impl From<Add> for Obj {
1689    fn from(a: Add) -> Self {
1690        Obj::Add(a)
1691    }
1692}
1693
1694impl From<MatrixAdd> for Obj {
1695    fn from(m: MatrixAdd) -> Self {
1696        Obj::MatrixAdd(m)
1697    }
1698}
1699
1700impl From<MatrixSub> for Obj {
1701    fn from(m: MatrixSub) -> Self {
1702        Obj::MatrixSub(m)
1703    }
1704}
1705
1706impl From<MatrixMul> for Obj {
1707    fn from(m: MatrixMul) -> Self {
1708        Obj::MatrixMul(m)
1709    }
1710}
1711
1712impl From<MatrixScalarMul> for Obj {
1713    fn from(m: MatrixScalarMul) -> Self {
1714        Obj::MatrixScalarMul(m)
1715    }
1716}
1717
1718impl From<MatrixPow> for Obj {
1719    fn from(m: MatrixPow) -> Self {
1720        Obj::MatrixPow(m)
1721    }
1722}
1723
1724impl From<Sub> for Obj {
1725    fn from(s: Sub) -> Self {
1726        Obj::Sub(s)
1727    }
1728}
1729
1730impl From<FnObj> for Obj {
1731    fn from(f: FnObj) -> Self {
1732        Obj::FnObj(f)
1733    }
1734}
1735
1736impl From<Mul> for Obj {
1737    fn from(m: Mul) -> Self {
1738        Obj::Mul(m)
1739    }
1740}
1741
1742impl From<Div> for Obj {
1743    fn from(d: Div) -> Self {
1744        Obj::Div(d)
1745    }
1746}
1747
1748impl From<Mod> for Obj {
1749    fn from(m: Mod) -> Self {
1750        Obj::Mod(m)
1751    }
1752}
1753
1754impl From<Pow> for Obj {
1755    fn from(p: Pow) -> Self {
1756        Obj::Pow(p)
1757    }
1758}
1759
1760impl From<Abs> for Obj {
1761    fn from(a: Abs) -> Self {
1762        Obj::Abs(a)
1763    }
1764}
1765
1766impl From<Log> for Obj {
1767    fn from(l: Log) -> Self {
1768        Obj::Log(l)
1769    }
1770}
1771
1772impl From<Max> for Obj {
1773    fn from(m: Max) -> Self {
1774        Obj::Max(m)
1775    }
1776}
1777
1778impl From<Min> for Obj {
1779    fn from(m: Min) -> Self {
1780        Obj::Min(m)
1781    }
1782}
1783
1784impl From<Union> for Obj {
1785    fn from(u: Union) -> Self {
1786        Obj::Union(u)
1787    }
1788}
1789
1790impl From<Intersect> for Obj {
1791    fn from(i: Intersect) -> Self {
1792        Obj::Intersect(i)
1793    }
1794}
1795
1796impl From<SetMinus> for Obj {
1797    fn from(s: SetMinus) -> Self {
1798        Obj::SetMinus(s)
1799    }
1800}
1801
1802impl From<SetDiff> for Obj {
1803    fn from(s: SetDiff) -> Self {
1804        Obj::SetDiff(s)
1805    }
1806}
1807
1808impl From<Cup> for Obj {
1809    fn from(c: Cup) -> Self {
1810        Obj::Cup(c)
1811    }
1812}
1813
1814impl From<Cap> for Obj {
1815    fn from(c: Cap) -> Self {
1816        Obj::Cap(c)
1817    }
1818}
1819
1820impl From<PowerSet> for Obj {
1821    fn from(p: PowerSet) -> Self {
1822        Obj::PowerSet(p)
1823    }
1824}
1825
1826impl From<ListSet> for Obj {
1827    fn from(l: ListSet) -> Self {
1828        Obj::ListSet(l)
1829    }
1830}
1831
1832impl From<SetBuilder> for Obj {
1833    fn from(s: SetBuilder) -> Self {
1834        Obj::SetBuilder(s)
1835    }
1836}
1837
1838impl From<FnSet> for Obj {
1839    fn from(f: FnSet) -> Self {
1840        Obj::FnSet(f)
1841    }
1842}
1843
1844impl From<Cart> for Obj {
1845    fn from(c: Cart) -> Self {
1846        Obj::Cart(c)
1847    }
1848}
1849
1850impl From<CartDim> for Obj {
1851    fn from(c: CartDim) -> Self {
1852        Obj::CartDim(c)
1853    }
1854}
1855
1856impl From<Proj> for Obj {
1857    fn from(p: Proj) -> Self {
1858        Obj::Proj(p)
1859    }
1860}
1861
1862impl From<TupleDim> for Obj {
1863    fn from(t: TupleDim) -> Self {
1864        Obj::TupleDim(t)
1865    }
1866}
1867
1868impl From<Tuple> for Obj {
1869    fn from(t: Tuple) -> Self {
1870        Obj::Tuple(t)
1871    }
1872}
1873
1874impl From<Count> for Obj {
1875    fn from(c: Count) -> Self {
1876        Obj::Count(c)
1877    }
1878}
1879
1880impl From<Range> for Obj {
1881    fn from(r: Range) -> Self {
1882        Obj::Range(r)
1883    }
1884}
1885
1886impl From<ClosedRange> for Obj {
1887    fn from(r: ClosedRange) -> Self {
1888        Obj::ClosedRange(r)
1889    }
1890}
1891
1892impl From<FiniteSeqSet> for Obj {
1893    fn from(v: FiniteSeqSet) -> Self {
1894        Obj::FiniteSeqSet(v)
1895    }
1896}
1897
1898impl From<SeqSet> for Obj {
1899    fn from(v: SeqSet) -> Self {
1900        Obj::SeqSet(v)
1901    }
1902}
1903
1904impl From<FiniteSeqListObj> for Obj {
1905    fn from(v: FiniteSeqListObj) -> Self {
1906        Obj::FiniteSeqListObj(v)
1907    }
1908}
1909
1910impl From<MatrixSet> for Obj {
1911    fn from(v: MatrixSet) -> Self {
1912        Obj::MatrixSet(v)
1913    }
1914}
1915
1916impl From<MatrixListObj> for Obj {
1917    fn from(v: MatrixListObj) -> Self {
1918        Obj::MatrixListObj(v)
1919    }
1920}
1921
1922impl From<Choose> for Obj {
1923    fn from(c: Choose) -> Self {
1924        Obj::Choose(c)
1925    }
1926}
1927
1928impl From<ObjAtIndex> for Obj {
1929    fn from(o: ObjAtIndex) -> Self {
1930        Obj::ObjAtIndex(o)
1931    }
1932}
1933
1934impl From<FieldAccess> for Obj {
1935    fn from(f: FieldAccess) -> Self {
1936        Obj::FieldAccess(f)
1937    }
1938}
1939
1940impl From<FieldAccessWithMod> for Obj {
1941    fn from(f: FieldAccessWithMod) -> Self {
1942        Obj::FieldAccessWithMod(f)
1943    }
1944}
1945
1946impl From<IdentifierWithMod> for Obj {
1947    fn from(m: IdentifierWithMod) -> Self {
1948        Obj::IdentifierWithMod(m)
1949    }
1950}
1951
1952impl From<StructObj> for Obj {
1953    fn from(s: StructObj) -> Self {
1954        Obj::StructObj(s)
1955    }
1956}
1957
1958impl From<FamilyObj> for Obj {
1959    fn from(f: FamilyObj) -> Self {
1960        Obj::FamilyObj(f)
1961    }
1962}
1963
1964impl From<StandardSet> for Obj {
1965    fn from(s: StandardSet) -> Self {
1966        Obj::StandardSet(s)
1967    }
1968}
1969
1970impl Identifier {
1971    /// Build an Obj::Identifier from a name. Parameter is String (not &str).
1972    pub fn mk(name: String) -> Obj {
1973        Identifier::new(name).into()
1974    }
1975}