symrs/
expr.rs

1use super::*;
2use itertools::Itertools;
3use num_traits::ToPrimitive;
4
5pub mod macros;
6
7pub mod pow;
8pub use pow::*;
9
10pub mod eq;
11pub use eq::*;
12
13pub mod add;
14pub use add::*;
15
16pub mod mul;
17pub use mul::*;
18
19pub mod function;
20pub use function::*;
21
22pub mod diff;
23pub use diff::*;
24
25pub mod integral;
26pub use integral::*;
27
28pub mod symbol;
29use schemars::{JsonSchema, json_schema};
30use serde::{de, Deserialize, Serialize};
31pub use symbol::*;
32
33pub mod integer;
34pub use integer::*;
35
36pub mod rational;
37pub use rational::*;
38
39pub mod ops;
40// pub use ops::*;
41
42pub type BoxExpr = Box<dyn Expr>;
43
44use std::{
45    any::Any,
46    cmp::{Ordering, PartialEq},
47    collections::HashMap,
48    fmt::{self},
49    hash::Hash,
50    iter,
51};
52
53pub trait Arg: Any {
54    fn srepr(&self) -> String;
55
56    fn clone_arg(&self) -> Box<dyn Arg>;
57
58    fn as_expr(&self) -> Option<Box<dyn Expr>> {
59        None
60    }
61
62    fn map_expr(&self, f: &dyn (Fn(&dyn Expr) -> Box<dyn Expr>)) -> Box<dyn Arg> {
63        if let Some(expr) = self.as_expr() {
64            f(expr.get_ref())
65        } else {
66            self.clone_arg()
67        }
68    }
69}
70
71pub trait ArgOperations {}
72
73impl<A: Arg> ArgOperations for A {}
74
75pub trait AsAny {
76    fn as_any(&self) -> &dyn Any;
77}
78
79// impl<T> AsAny for Box<T>
80// where
81//     T: Any + ?Sized,
82// {
83//     fn as_any(&self) -> &dyn Any {
84//         let any = (&**self) as &dyn Any;
85//         any
86//     }
87// }
88
89// impl<T> AsAny for Box<T> where T: Any + ?Sized {
90//     fn as_any(&self) -> &dyn Any {
91//         let any = (&**self) as &dyn Any;
92//         any
93//     }
94// }
95
96impl AsAny for Box<dyn Arg> {
97    fn as_any(&self) -> &dyn Any {
98        let any = (&**self) as &dyn Any;
99        any
100    }
101}
102
103impl AsAny for Box<dyn Expr> {
104    fn as_any(&self) -> &dyn Any {
105        let any = (&**self) as &dyn Any;
106        any
107    }
108}
109
110impl fmt::Debug for Box<dyn Arg> {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "{}", self.srepr())
113    }
114}
115impl JsonSchema for dyn Expr {
116    fn schema_name() -> std::borrow::Cow<'static, str> {
117        "Expression".into()
118    }
119
120    fn schema_id() -> std::borrow::Cow<'static, str> {
121        concat!(module_path!(), "::Expression").into()
122    }
123
124    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
125        json_schema!({
126            "title": "Expression",
127            "description": "A symbolic expression.",
128            "oneOf": [
129                {
130                    "type": "string"
131                },
132                {
133                    "type": "number"
134                }
135            ]
136        })
137    }
138
139    fn inline_schema() -> bool {
140        true
141    }
142}
143
144impl Arg for isize {
145    fn srepr(&self) -> String {
146        self.to_string()
147    }
148
149    fn clone_arg(&self) -> Box<dyn Arg> {
150        Box::new(self.clone())
151    }
152}
153
154impl Arg for String {
155    fn srepr(&self) -> String {
156        self.clone()
157    }
158
159    fn clone_arg(&self) -> Box<dyn Arg> {
160        Box::new(self.clone())
161    }
162}
163
164impl<A: Arg + Clone, B: Arg + Clone> Arg for (A, B) {
165    fn srepr(&self) -> String {
166        format!("({}, {})", self.0.srepr(), self.1.srepr())
167    }
168
169    fn clone_arg(&self) -> Box<dyn Arg> {
170        Box::new((self.0.clone(), self.1.clone()))
171    }
172}
173
174impl std::fmt::Debug for &dyn Arg {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        write!(f, "{}", self.srepr())
177    }
178}
179
180impl Arg for Box<dyn Expr> {
181    fn srepr(&self) -> String {
182        (**self).srepr()
183    }
184
185    fn clone_arg(&self) -> Box<dyn Arg> {
186        self.clone_box().into()
187    }
188
189    fn as_expr(&self) -> Option<Box<dyn Expr>> {
190        Some(self.clone_box())
191    }
192}
193
194impl Arg for usize {
195    fn srepr(&self) -> String {
196        self.to_string()
197    }
198
199    fn clone_arg(&self) -> Box<dyn Arg> {
200        Box::new(self.clone())
201    }
202}
203
204impl<A: Arg + Clone> Arg for Vec<A> {
205    fn srepr(&self) -> String {
206        let args = self
207            .iter()
208            .map(|arg| arg.srepr())
209            .collect::<Vec<String>>()
210            .join(", ");
211        format!("({})", args)
212    }
213
214    fn clone_arg(&self) -> Box<dyn Arg> {
215        Box::new(self.clone())
216    }
217}
218
219// impl Arg for Vec<Box<dyn Expr>> {
220//     fn srepr(&self) -> String {
221//         let args = self
222//             .iter()
223//             .map(|arg| arg.srepr())
224//             .collect::<Vec<String>>()
225//             .join(", ");
226//         format!("({})", args)
227//     }
228//
229//     fn clone_arg(&self) -> Box<dyn Arg> {
230//         Box::new(self.clone())
231//     }
232// }
233
234impl Clone for Box<dyn Arg> {
235    fn clone(&self) -> Self {
236        self.clone_arg()
237    }
238}
239
240impl From<Box<dyn Expr>> for Box<dyn Arg> {
241    fn from(value: Box<dyn Expr>) -> Self {
242        Box::new(value.clone())
243    }
244}
245
246impl From<Box<dyn Arg>> for Box<dyn Expr> {
247    fn from(value: Box<dyn Arg>) -> Self {
248        value.as_expr().expect("This arg is not an expr")
249    }
250}
251
252impl<T> Arg for T
253where
254    T: Expr,
255{
256    fn srepr(&self) -> String {
257        let args = self
258            .args()
259            .iter()
260            .map(|arg| arg.srepr())
261            .collect::<Vec<String>>()
262            .join(", ");
263        format!("{}({})", self.name(), args)
264    }
265
266    fn clone_arg(&self) -> Box<dyn Arg> {
267        self.as_arg()
268    }
269}
270
271impl FromIterator<Box<dyn Expr>> for Vec<Box<dyn Arg>> {
272    fn from_iter<T: IntoIterator<Item = Box<dyn Expr>>>(iter: T) -> Self {
273        let mut res = Vec::new();
274        for expr in iter {
275            res.push(expr.clone_box().into())
276        }
277        res
278    }
279}
280
281impl FromIterator<Box<dyn Arg>> for Vec<Box<dyn Expr>> {
282    fn from_iter<T: IntoIterator<Item = Box<dyn Arg>>>(iter: T) -> Self {
283        let mut res = Vec::new();
284        for arg in iter {
285            // if (&arg as &dyn Any).is::<Box<dyn Expr>>() {
286            res.push(arg.clone().into())
287            // } else {
288            //
289            //     panic!("Not an Expr: {} {}", type_name_of_val(&arg),  arg.srepr())
290            // }
291        }
292        res
293    }
294}
295
296// impl Clone for &(dyn Arg + 'static) {
297//     fn clone(&self) -> Self {
298//         todo!()
299//     }
300// }
301
302pub trait Expr: Arg + Sync + Send {
303    fn as_expr(&self) -> Option<Box<dyn Expr>> {
304        Some(self.clone_box())
305    }
306    fn args(&self) -> Vec<Box<dyn Arg>> {
307        let mut res = Vec::new();
308        self.for_each_arg(&mut |a| res.push(a.clone_arg()));
309        res
310    }
311
312    fn for_each_arg(&self, f: &mut dyn FnMut(&dyn Arg) -> ());
313
314    fn args_map_exprs(&self, _f: &dyn Fn(&dyn Expr) -> Box<dyn Arg>) -> Vec<Box<dyn Arg>> {
315        todo!("Doesn't work at the moment");
316        // let mut res = Vec::new();
317        //
318        // self.for_each_arg(&mut |arg| {
319        //     if let Some(expr) = arg.as_expr() {
320        //         res.push(f(&*expr));
321        //     } else {
322        //         res.push(arg.clone_arg());
323        //     }
324        // });
325        //
326        // res
327    }
328
329    fn from_args(&self, args: Vec<Box<dyn Arg>>) -> Box<dyn Expr> {
330        panic!(
331            "from_args not implemented for {}, supplied args :\n{:#?}",
332            self.name(),
333            &args
334        )
335    }
336
337    fn as_arg(&self) -> Box<dyn Arg> {
338        self.clone_box().into()
339    }
340
341    fn as_function(&self) -> Option<&Func> {
342        None
343    }
344    fn equals(&self, other: &dyn Expr) -> bool {
345        self.srepr() == other.srepr()
346    }
347    fn clone_box(&self) -> Box<dyn Expr>;
348
349    fn as_symbol(&self) -> Option<Symbol> {
350        let res = self.clone_box();
351        match KnownExpr::from_expr_box(&res) {
352            KnownExpr::Symbol(symbol) => Some(symbol.clone()),
353            _ => None,
354        }
355    }
356
357    fn as_eq(&self) -> Option<Equation> {
358        let res = self.clone_box();
359        match KnownExpr::from_expr_box(&res) {
360            KnownExpr::Eq(eq) => Some(eq.clone()),
361            _ => None,
362        }
363    }
364
365    fn as_mul(&self) -> Option<&Mul> {
366        None
367    }
368
369    fn as_pow(&self) -> Option<&Pow> {
370        None
371    }
372
373    fn as_f64(&self) -> Option<f64> {
374        None
375    }
376
377    fn to_cpp(&self) -> String {
378        self.str()
379    }
380
381    fn simplify(&self) -> Box<dyn Expr> {
382        self.from_args(
383            self.args()
384                .iter()
385                .map(|a| a.map_expr(&|e| e.simplify()))
386                .collect(),
387        )
388    }
389
390    fn simplify_with_dimension(&self, dim: usize) -> Box<dyn Expr> {
391        let expr = self.simplify();
392        expr.from_args(
393            expr.args()
394                .iter()
395                .map(|a| a.map_expr(&|e| e.simplify_with_dimension(dim)))
396                .collect(),
397        )
398    }
399
400    fn as_int(&self) -> Option<Integer> {
401        let res = self.clone_box();
402        match KnownExpr::from_expr_box(&res) {
403            KnownExpr::Integer(i) => Some(i.clone()),
404            _ => None,
405        }
406    }
407
408    fn str(&self) -> String;
409
410    fn pow(&self, exponent: &Box<dyn Expr>) -> Box<dyn Expr> {
411        Pow::pow(self.clone_box(), exponent.clone())
412    }
413
414    fn ipow(&self, exponent: isize) -> Box<dyn Expr> {
415        Pow::pow(self.clone_box(), Integer::new_box(exponent))
416    }
417
418    fn sqrt(&self) -> Box<dyn Expr> {
419        Pow::pow(self.clone_box(), Rational::new_box(1, 2))
420    }
421
422    fn get_exponent(&self) -> (Box<dyn Expr>, Box<dyn Expr>) {
423        (self.clone_box(), Integer::one_box())
424    }
425
426    fn diff(&self, var: &str, order: usize) -> Box<dyn Expr> {
427        Box::new(Diff::idiff(self.clone_box(), Symbol::new(var), order))
428    }
429
430    fn name(&self) -> String {
431        std::any::type_name_of_val(self)
432            .to_string()
433            .split("::")
434            .last()
435            .unwrap()
436            .to_string()
437    }
438
439    fn subs(&self, substitutions: &[[Box<dyn Expr>; 2]]) -> Box<dyn Expr> {
440        ops::subs(self, substitutions)
441    }
442
443    fn has(&self, expr: &dyn Expr) -> bool {
444        if self.equals(expr) {
445            true
446        } else {
447            self.args()
448                .iter()
449                .filter_map(|a| a.as_expr())
450                .any(|e| e.has(expr))
451        }
452    }
453
454    fn has_box(&self, expr: Box<dyn Expr>) -> bool {
455        self.has(&*expr)
456    }
457
458    /// Expands an expression.
459    /// For example:
460    /// (x + y) * z -> xz + yz
461    fn expand(&self) -> Box<dyn Expr> {
462        self.from_args(
463            self.args()
464                .iter()
465                .map(|a| {
466                    if let Some(expr) = a.as_expr() {
467                        expr.expand()
468                    } else {
469                        a.clone()
470                    }
471                })
472                .collect(),
473        )
474    }
475
476    /// Factorizes an expression
477    /// For example:
478    /// factor(ax + cx + zy, [x]) -> (a + c)x + zy
479    fn factor(&self, factors: &[&dyn Expr]) -> Box<dyn Expr> {
480        ops::factor(self, factors)
481    }
482
483    fn is_one(&self) -> bool {
484        false
485    }
486    fn is_neg_one(&self) -> bool {
487        false
488    }
489
490    fn is_number(&self) -> bool {
491        false
492    }
493
494    fn is_negative_number(&self) -> bool {
495        false //Todo better
496    }
497
498    fn is_zero(&self) -> bool {
499        false
500    }
501
502    fn known_expr(&self) -> KnownExpr {
503        KnownExpr::Unknown
504    }
505
506    fn terms<'a>(&'a self) -> Box<dyn Iterator<Item = &'a dyn Expr> + 'a> {
507        Box::new(iter::once(self.get_ref()))
508    }
509
510    fn get_ref<'a>(&'a self) -> &'a dyn Expr;
511
512    fn get_coeff(&self) -> (Rational, Box<dyn Expr>) {
513        match KnownExpr::from_expr(self.get_ref()) {
514            KnownExpr::Integer(i) => i.into(),
515            KnownExpr::Pow(pow) => {
516                let (pow_coeff, pow_expr) = pow.base().get_coeff();
517
518                if pow_coeff.is_one() {
519                    return (Rational::one(), pow_expr.pow(&pow.exponent().clone_box()));
520                }
521                let coeff_box = (pow_coeff).pow(&(pow.exponent()).clone_box());
522
523                match coeff_box.known_expr() {
524                    KnownExpr::Integer(i) => return (i.into(), pow_expr),
525                    KnownExpr::Rational(r) => return (*r, pow_expr),
526                    KnownExpr::Pow(Pow {
527                        base: coeff_base,
528                        exponent: _,
529                    }) => {
530                        return (
531                            Rational::one(),
532                            Pow::pow(
533                                coeff_base.clone_box() * pow_expr,
534                                pow.exponent().clone_box(),
535                            ),
536                        );
537                    }
538                    // _ if !coeff_box.is_one() => pow_expr = ((coeff_box) * (pow_expr)),
539
540                    // _ if !coeff_box.is_one() => {
541                    //     return (Rational::one(), coeff_box * pow_expr
542                    //
543                    //     )
544                    // },
545                    // _ => {
546                    //     return (Rational::one(), pow_expr)
547                    // }
548                    _ => panic!("help: {:?}", coeff_box),
549                }
550
551                // ((
552                //     coeff,
553                //     if pow_expr.is_one() {
554                //         Integer::new_box(1)
555                //     } else {
556                //         coeff_box * pow_expr.pow(&pow.exponent)
557                //     },
558                // ))
559            }
560            // KnownExpr::Pow(_) => {
561            //     todo!("pow no matter the exponent")
562            // }
563            KnownExpr::Rational(r) => r.into(),
564            KnownExpr::Mul(Mul { operands }) => {
565                let mut coeff = Rational::one();
566                let mut expr = Integer::new_box(1);
567
568                operands
569                    .iter()
570                    .for_each(|op| match KnownExpr::from_expr_box(op) {
571                        KnownExpr::Integer(i) => coeff *= i,
572                        KnownExpr::Rational(r) => coeff *= r,
573                        KnownExpr::Pow(Pow { base, exponent }) if exponent.is_neg_one() => {
574                            let (pow_coeff, pow_expr) = base.get_coeff();
575                            coeff /= pow_coeff;
576                            expr *= (Pow {
577                                base: pow_expr,
578                                exponent: Integer::new_box(-1),
579                            })
580                            .get_ref();
581                        }
582                        _ => expr *= op,
583                    });
584
585                (coeff, expr)
586            }
587            _ => (Rational::one(), self.clone_box()),
588        }
589    }
590
591    fn compare(&self, other: &dyn Expr) -> Option<Ordering> {
592        ops::compare(self, other)
593    }
594
595    fn evaluate(&self, vars: Option<HashMap<Symbol, BoxExpr>>) -> BoxExpr {
596        let substs = if let Some(vars) = vars {
597            vars.iter()
598                .map(|(s, v)| [s.clone_box(), v.clone_box()])
599                .collect_vec()
600        } else {
601            Vec::new()
602        };
603
604        let expr = self.subs(&substs).expand().simplify();
605        expr
606    }
607}
608
609impl std::hash::Hash for dyn Expr {
610    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
611        self.srepr().hash(state);
612    }
613}
614
615impl From<&Integer> for (Rational, Box<dyn Expr>) {
616    fn from(i: &Integer) -> Self {
617        (i.into(), Integer::new_box(1))
618    }
619}
620
621impl From<&Rational> for (Rational, Box<dyn Expr>) {
622    fn from(r: &Rational) -> Self {
623        (r.clone(), Integer::new_box(1))
624    }
625}
626
627impl ToPrimitive for Integer {
628    fn to_i64(&self) -> Option<i64> {
629        Some(self.value.try_into().unwrap())
630    }
631
632    fn to_u64(&self) -> Option<u64> {
633        Some(self.value.try_into().unwrap())
634    }
635}
636
637impl ToPrimitive for &Integer {
638    fn to_i64(&self) -> Option<i64> {
639        (*self).to_i64()
640    }
641
642    fn to_u64(&self) -> Option<u64> {
643        (*self).to_u64()
644    }
645}
646impl ExprOperations for &dyn Expr {}
647
648#[cfg(test)]
649mod tests {
650    use std::collections::HashSet;
651
652    use super::*;
653
654    #[test]
655    fn check_has() {
656        let x = &Symbol::new("x");
657        let y = &Symbol::new("y");
658        let expr = Equation::new(x, (y + x).get_ref());
659        assert!(expr.has(x));
660        assert!(expr.has(y));
661        assert!(expr.has((y + x).get_ref()));
662        // For now expr.has doesn't check for commutativity
663        assert!(!expr.has((x + y).get_ref()));
664        assert!(!expr.has(&Symbol::new("z")));
665    }
666
667    #[test]
668    fn test_expand_simple() {
669        let x = &Symbol::new("x") as &dyn Expr;
670        let y = &Symbol::new("y") as &dyn Expr;
671        let z = &Symbol::new("z") as &dyn Expr;
672
673        let expr = (x + y) * z;
674        let expected = x * z + y * z;
675
676        assert!((expr.expand()).equals(&*expected))
677    }
678    #[test]
679    fn test_expand_with_first_arg_int() {
680        let x = &Symbol::new("x");
681        let y = &Symbol::new("y");
682        let z = &Symbol::new("z");
683        let i2 = &Integer::new(2);
684
685        let expr = i2 * &(x + y) * z;
686        let expected = i2 * x * z + i2 * y * z;
687
688        assert!((expr.expand()).equals(&*expected))
689    }
690    #[test]
691    /// 2(x + y)(w + z) -> 2xw + 2xz + 2yw + 2yz
692    fn test_expand_complex() {
693        let x = &Symbol::new("x");
694        let y = &Symbol::new("y");
695        let w = &Symbol::new("w");
696        let z = &Symbol::new("z");
697        let i2 = &Integer::new(2);
698
699        let expr = i2 * &(x + y) * &(w + z);
700        let expected = i2 * x * w + i2 * x * z + i2 * y * w + i2 * y * z;
701
702        assert!((expr.expand()).equals(&*(expected)))
703    }
704
705    #[test]
706    fn test_get_coeff_trivial() {
707        assert_eq!(
708            Integer::new(1).get_coeff(),
709            (Rational::one(), Integer::new_box(1))
710        );
711    }
712    #[test]
713    fn test_get_coeff_basic() {
714        let expr = Integer::new(1).get_ref() / Integer::new(2).get_ref();
715        assert_eq!(expr.get_coeff(), (Rational::new(1, 2), Integer::new_box(1)));
716    }
717    #[test]
718    fn test_get_coeff_basic_2() {
719        let num = &Integer::new(5);
720        let denom = &Integer::new(7);
721        let expr = num.get_ref() / denom.get_ref();
722
723        assert_eq!(expr.get_coeff(), (Rational::new(5, 7), Integer::new_box(1)));
724    }
725
726    #[test]
727    fn test_get_coeff_normal() {
728        let x = &Symbol::new("x");
729        let num = &Integer::new(5);
730        let denom = &Integer::new(7);
731        let expr = x * num / denom;
732
733        assert_eq!(expr.get_coeff(), (Rational::new(5, 7), x.clone_box()));
734    }
735
736    #[test]
737    fn test_check_hashing_works() {
738        let mut set = HashSet::with_capacity(2);
739        let x = &Symbol::new_box("x");
740        let x_bis = &Symbol::new_box("x");
741
742        set.insert(x);
743        set.insert(x_bis);
744
745        assert_eq!(set.len(), 1)
746    }
747
748    #[test]
749    fn test_check_sqrt() {
750        let x = &Integer::new(2).sqrt();
751
752        assert_eq!(x.srepr(), "Pow(Integer(2), Rational(1, 2))")
753    }
754
755    #[test]
756    fn test_get_sqrt_exponent() {
757        let sqrt_2 = &Integer::new(2).sqrt();
758
759        assert_eq!(
760            sqrt_2.get_exponent(),
761            (Integer::new_box(2), Rational::new_box(1, 2))
762        )
763    }
764
765    #[test]
766    fn test_check_sqrt_simplifies() {
767        let x = &Integer::new(2).sqrt();
768
769        let expr = x * x;
770
771        assert_eq!(&expr, &Integer::new_box(2))
772    }
773
774    #[test]
775    fn test_check_coeff_sqrt_2() {
776        let sqrt_2 = &Integer::new(2).sqrt();
777
778        assert_eq!(sqrt_2.get_coeff(), (Rational::one(), sqrt_2.clone_box()))
779    }
780}
781
782// pub trait E: Any + Display {
783//     fn name(&self) -> String {
784//         std::any::type_name_of_val(self)
785//             .to_string()
786//             .split("::")
787//             .last()
788//             .unwrap()
789//             .to_string()
790//     }
791//     fn args(&self) -> Vec<&dyn A>;
792//     fn from_args(&self, args: &Vec<&dyn A>);
793//     fn clone(&self) -> Box<dyn A>;
794// }
795//
796// pub trait A {}
797// impl A for &dyn E {}
798
799pub struct ExprWrapper<'a, E: Expr> {
800    expr: &'a E,
801}
802
803impl<'a, E: Expr> std::cmp::PartialEq for ExprWrapper<'a, E> {
804    fn eq(&self, other: &Self) -> bool {
805        self.expr.srepr() == other.expr.srepr()
806    }
807}
808
809impl<'a, E: Expr> std::cmp::Eq for ExprWrapper<'a, E> {}
810
811impl<'a, E: Expr> ExprWrapper<'a, E> {
812    pub fn new(expr: &'a E) -> Self {
813        ExprWrapper { expr }
814    }
815}
816impl std::cmp::PartialEq for &dyn Expr {
817    fn eq(&self, other: &Self) -> bool {
818        self.srepr() == other.srepr()
819    }
820}
821
822impl std::cmp::PartialEq<Box<dyn Expr>> for &dyn Expr {
823    fn eq(&self, other: &Box<dyn Expr>) -> bool {
824        *self == &**other
825    }
826}
827
828impl std::cmp::PartialEq<&dyn Expr> for Box<dyn Expr> {
829    fn eq(&self, other: &&dyn Expr) -> bool {
830        self.get_ref() == *other
831    }
832}
833
834impl std::cmp::PartialEq<&Box<dyn Expr>> for &dyn Expr {
835    fn eq(&self, other: &&Box<dyn Expr>) -> bool {
836        *self == other.get_ref()
837    }
838}
839
840impl fmt::Debug for &dyn Expr {
841    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842        write!(f, "{} [{}])", self.str(), self.srepr())
843    }
844}
845
846impl std::cmp::Eq for &dyn Expr {}
847
848// impl<E: Expr> Expr for ExprWrapper<'_, E> {
849//     fn args(&self) -> Vec<Box<dyn Arg>> {
850//         todo!()
851//     }
852//
853//     fn clone_box(&self) -> Box<dyn Expr> {
854//         todo!()
855//     }
856//
857//     fn str(&self) -> String {
858//         todo!()
859//     }
860// }
861
862// impl<, E: Expr> Expr for ExprWrapper<'a, E> {
863//     fn args(&self) -> Vec<Box<dyn Arg>> {
864//         self.expr.args()
865//     }
866//
867//     fn clone_box(&self) -> Box<dyn Expr> {
868//         self.expr.clone_box()
869//     }
870//
871//     fn str(&self) -> String {
872//         self.expr.str()
873//     }
874// }
875
876pub trait ExprOperations {
877    fn subs_refs<'a, Iter: IntoIterator<Item = [&'a dyn Expr; 2]>>(
878        &self,
879        substitutions: Iter,
880    ) -> Box<dyn Expr>
881    where
882        Self: Expr,
883    {
884        for [replaced, replacement] in substitutions.into_iter() {
885            if self.srepr() == replaced.srepr() {
886                return replacement.clone_box();
887            }
888        }
889        todo!()
890    }
891
892    // fn map_exprs<F>(&self, op: F) -> Vec<Box<dyn Arg>>
893    // where
894    //     Self: Expr,
895    //     F: Fn(&dyn Expr) -> Box<dyn Expr>,
896    // {
897    //     todo!()
898    // }
899
900    //     fn subs<'a, I: IntoIterator<Item = &'a [&'static dyn Expr; 2]>>(&'static self, substitutions: I) -> Box<dyn Expr>
901    //     where
902    //         Self: Expr + Sized
903    //     {
904    //         for [replaced, replacement] in substitutions.into_iter() {
905    //             // if (self as &dyn Expr) == replaced {}
906    //             // if self.clone_box() == (*replaced).clone() {
907    //             //     return (*replacement).clone();
908    //             // }
909    //         }
910    //         todo!()
911    //
912    //         // self.from_args(
913    //         //     self.args()
914    //         //         .iter()
915    //         //         .map(|arg| {
916    //         //             if let Some(expr) = arg.as_expr() {
917    //         //                 expr.subs(&substitutions).into()
918    //         //             } else {
919    //         //                 arg.clone()
920    //         //             }
921    //         //         })
922    //         //         .collect(),
923    //         // )
924    //     }
925}
926
927impl<T> ExprOperations for T where T: Expr {}
928// impl ExprOperations<&dyn Expr> for &dyn Expr {}
929
930impl fmt::Display for &dyn Expr {
931    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932        write!(f, "{}", self.str())
933    }
934}
935
936impl PartialEq for Box<dyn Expr> {
937    fn eq(&self, other: &Self) -> bool {
938        self.srepr() == other.srepr()
939    }
940}
941
942impl std::cmp::Eq for Box<dyn Expr> {}
943
944impl std::fmt::Debug for Box<dyn Expr> {
945    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
946        write!(f, "{:?}", self.get_ref())
947    }
948}
949
950impl std::fmt::Display for Box<dyn Expr> {
951    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
952        write!(f, "{}", self.str())
953    }
954}
955
956impl Clone for Box<dyn Expr> {
957    fn clone(&self) -> Self {
958        self.clone_box()
959    }
960}
961
962impl std::ops::Neg for &dyn Expr {
963    type Output = Box<dyn Expr>;
964
965    fn neg(self) -> Self::Output {
966        Integer::new_box(-1) * self
967    }
968}
969
970impl std::ops::Neg for &Box<dyn Expr> {
971    type Output = Box<dyn Expr>;
972
973    fn neg(self) -> Self::Output {
974        -&**self
975    }
976}
977
978impl std::ops::Neg for Box<dyn Expr> {
979    type Output = Box<dyn Expr>;
980
981    fn neg(self) -> Self::Output {
982        -&*self
983    }
984}
985
986impl Serialize for Box<dyn Expr> {
987    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
988    where
989        S: serde::Serializer,
990    {
991        serializer.serialize_str(&self.str())
992    }
993}
994struct ExprVisitor;
995impl<'de> de::Visitor<'de> for ExprVisitor {
996    type Value = Box<dyn Expr>;
997
998    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
999        formatter.write_str("a properly written function expression")
1000    }
1001
1002    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1003    where
1004        E: serde::de::Error,
1005    {
1006        Ok(v.parse().map_err(|e| E::custom(e))?)
1007    }
1008}
1009impl<'de> Deserialize<'de> for Box<dyn Expr> {
1010    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1011    where
1012        D: serde::Deserializer<'de>,
1013    {
1014        Ok(deserializer.deserialize_str(ExprVisitor)?)
1015    }
1016}