symbolica 2.2.0

A blazing fast computer algebra system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
use std::{borrow::Cow, collections::hash_map::Entry, fmt};

use ahash::{HashMap, HashSet};

use crate::{
    atom::EvaluationError,
    evaluate::EvaluatorBuilder,
    printer::{AtomPrinter, PrintOptions},
};

use super::{Atom, AtomCore, AtomType, AtomView};

/// An atom that contains opaque aliases, together with a map from the aliases to their original atoms.
/// An aliased atom may have a lower memory footprint than the original atom if it contains many repeated subexpressions.
///
/// Use [AtomCore::alias_subexpressions] to create an aliased atom, or register aliases manually.
///
///
/// # Examples
///
/// ```
/// use symbolica::prelude::*;
///
/// let a: AliasedAtom = parse!("(x+1)^2+(x+1)^3").into();
/// let b = a.add_alias(parse!("s(1)"), parse!("x+1"));
/// assert!(!b.contains_symbol(symbol!("x")));
/// assert_eq!(b.get_root(), &parse!("s(1)^2+s(1)^3"));
/// ```
#[derive(Clone)]
pub struct AliasedAtom {
    pub(crate) root: Atom,
    pub(crate) aliases: HashMap<Atom, Atom>, // TODO: Rc?
}

impl std::fmt::Display for AliasedAtom {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        AtomPrinter::new(self.get_root().as_view()).fmt(f)
    }
}

impl fmt::Debug for AliasedAtom {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let aliases = self.sorted_aliases();

        if f.alternate() {
            writeln!(f, "{{")?;
            write!(f, "    {}", AtomPrinter::new(self.root.as_view()))?;
            for (alias, original) in aliases {
                writeln!(f, ",")?;
                write!(
                    f,
                    "    {}={}",
                    AtomPrinter::new(alias.as_view()),
                    AtomPrinter::new(original.as_view())
                )?;
            }
            write!(f, "\n}}")
        } else {
            write!(f, "{{{}", AtomPrinter::new(self.root.as_view()))?;
            for (alias, original) in aliases {
                write!(
                    f,
                    ", {}={}",
                    AtomPrinter::new(alias.as_view()),
                    AtomPrinter::new(original.as_view())
                )?;
            }
            write!(f, "}}")
        }
    }
}

impl Default for AliasedAtom {
    /// Create an aliased atom that represents the number 0.
    #[inline]
    fn default() -> Self {
        AliasedAtom {
            root: Atom::Zero,
            aliases: HashMap::default(),
        }
    }
}

impl AliasedAtom {
    /// Get the root atom, which may contain aliases.
    pub fn get_root(&self) -> &Atom {
        &self.root
    }

    /// Get the map from aliases to their original atoms. These atoms may contain aliases themselves.
    pub fn get_aliases(&self) -> &HashMap<Atom, Atom> {
        &self.aliases
    }

    /// Return the number of bytes stored in the root atom and alias definitions.
    pub fn get_byte_size(&self) -> usize {
        self.root.as_view().get_byte_size()
            + self
                .aliases
                .iter()
                .map(|(alias, original)| {
                    alias.as_view().get_byte_size() + original.as_view().get_byte_size()
                })
                .sum::<usize>()
    }

    /// Print the root atom and alias definitions with the given options.
    pub fn printer(&self, opts: PrintOptions) -> AliasedAtomPrinter<'_> {
        AliasedAtomPrinter {
            atom: self,
            print_opts: opts,
        }
    }

    /// Map the root atom using the given function.
    pub fn map_root(self, f: impl FnOnce(Atom) -> Atom) -> Self {
        Self {
            root: f(self.root),
            aliases: self.aliases,
        }
    }

    /// Return the root atom and the alias map.
    pub fn into_inner_with_aliases(self) -> (Atom, HashMap<Atom, Atom>) {
        (self.root, self.aliases)
    }

    /// Undo the common subexpression extraction and return the original atom.
    pub fn into_inner(mut self) -> Atom {
        // TODO: this can be a one-pass if unfolded in reverse insertion order
        loop {
            let out = self.root.replace_map(|a, _, out| {
                if let Some(replacement) = self.aliases.get::<[u8]>(a.get_data()) {
                    out.set_from_view(&replacement.as_view());
                }
            });

            if out != self.root {
                self.root = out;
            } else {
                break;
            }
        }

        self.root
    }

    /// Extract common subexpressions from the root atom and replace them with aliases, which are returned in the map.
    pub fn alias_subexpressions(
        self,
        f: impl FnMut(AtomView, usize, usize) -> Option<Atom>,
    ) -> Self {
        // FIXME: do in one pass
        self.into_inner().as_atom_view().alias_subexpressions(f)
    }

    /// Register an alias, but do not apply it to the root atom.
    pub fn register_alias(&mut self, alias: Atom, original: Atom) {
        match self.aliases.entry(alias) {
            Entry::Occupied(entry) => {
                if entry.get() != &original {
                    panic!(
                        "Redefined alias: {} -> {} vs {}",
                        entry.key(),
                        entry.get(),
                        original
                    );
                }
            }
            Entry::Vacant(entry) => {
                // TODO: check for cycles in alias definitions?
                entry.insert(original);
            }
        }
    }

    /// Create an evaluator for a multiple-alias expression.
    pub fn evaluator_multiple<'a, P: AtomCore>(
        exprs: &'a [Self],
        params: &[P],
    ) -> Result<EvaluatorBuilder<'a>, EvaluationError> {
        let roots: Vec<_> = exprs.iter().map(|x| x.root.as_atom_view()).collect();
        let mut b = EvaluatorBuilder::new_multiple_views(&roots, params);

        for aliases in exprs {
            b = b.add_aliases(aliases.aliases.iter().map(|x| (x.0.clone(), x.1.clone())))?;
        }

        Ok(b)
    }

    /// Rename an alias handle and rewrite all uses of the handle in the root and alias bodies.
    ///
    /// Returns `true` if `old` was registered as an alias and was successfully renamed.
    /// Returns an error if `new` is already registered and has a different value than `old`.
    pub fn rename_alias(&mut self, old: Atom, new: Atom) -> Result<bool, ()> {
        if old == new {
            return Ok(self.aliases.contains_key(&old));
        }

        let Some(original) = self.aliases.remove(&old) else {
            return Ok(false);
        };

        if let Some(existing) = self.aliases.get(&new) {
            if existing != &original {
                return Err(());
            }
        }

        self.root = Self::rename_alias_in_atom(&self.root, &old, &new);
        for body in self.aliases.values_mut() {
            *body = Self::rename_alias_in_atom(body, &old, &new);
        }

        self.aliases.entry(new).or_insert(original);
        Ok(true)
    }

    /// Register an alias for an atom and apply the substitution to the root.
    pub fn add_alias(mut self, alias: Atom, original: Atom) -> Self {
        let new_root = self.root.replace_map(|a, _, out| {
            if a == original.as_view() {
                out.set_from_view(&alias.as_view());
            }
        });

        self.register_alias(alias, original);

        Self {
            root: new_root,
            aliases: self.aliases,
        }
    }

    /// Apply currently registered aliases to the root atom.
    pub fn apply_aliases(&self) -> Self {
        let inv_map = self
            .aliases
            .iter()
            .map(|(a, b)| (b.as_view(), a.as_view()))
            .collect::<HashMap<_, _>>();

        let new_root = self.root.replace_map(|a, _, out| {
            if let Some(alias) = inv_map.get(&a) {
                out.set_from_view(alias);
            }
        });

        Self {
            root: new_root,
            aliases: self.aliases.clone(),
        }
    }

    /// Apply currently registered aliases to the root atom and inside the body of other aliases.
    pub fn apply_aliases_nested(&self) -> Self {
        let replacements = self.alias_replacements();
        let root = Self::apply_alias_replacements(&self.root, &replacements, None);
        let aliases = self
            .aliases
            .iter()
            .map(|(alias, body)| {
                (
                    alias.clone(),
                    Self::apply_alias_replacements(body, &replacements, Some(body)),
                )
            })
            .collect();

        Self { root, aliases }
    }

    /// Add two aliased atoms, fusing their alias maps. On conflicts, the `resolve` function is called to generate a new alias handle.
    pub fn add(mut self, rhs: &Self, resolve: impl Fn(AtomView) -> Atom) -> Self {
        let new_rhs_root = self.fuse_aliases(rhs, resolve);
        Self {
            aliases: self.aliases,
            root: &self.root + &new_rhs_root,
        }
    }

    /// Multiply two aliased atoms, fusing their alias maps.  On conflicts, the `resolve` function is called to generate a new alias handle.
    pub fn mul(mut self, rhs: &Self, resolve: impl Fn(AtomView) -> Atom) -> Self {
        let new_rhs_root = self.fuse_aliases(rhs, resolve);
        Self {
            aliases: self.aliases,
            root: &self.root * &new_rhs_root,
        }
    }

    /// Raise one aliased atom to another, fusing their alias maps. On conflicts, the `resolve` function is called to generate a new alias handle.
    pub fn pow(mut self, rhs: &Self, resolve: impl Fn(AtomView) -> Atom) -> Self {
        let new_rhs_root = self.fuse_aliases(rhs, resolve);
        Self {
            aliases: self.aliases,
            root: self.root.pow(&new_rhs_root),
        }
    }

    /// Try to add two aliased atoms, fusing their alias maps.
    ///
    /// If both atoms define the same alias handle with different bodies, the conflicting alias
    /// handle is returned.
    pub fn try_add(&self, rhs: &Self) -> Result<Self, Atom> {
        Ok(Self {
            aliases: self.try_fuse_aliases(rhs)?,
            root: &self.root + &rhs.root,
        })
    }

    /// Try to multiply two aliased atoms, fusing their alias maps.
    ///
    /// If both atoms define the same alias handle with different bodies, the conflicting alias
    /// handle is returned.
    pub fn try_mul(&self, rhs: &Self) -> Result<Self, Atom> {
        Ok(Self {
            aliases: self.try_fuse_aliases(rhs)?,
            root: &self.root * &rhs.root,
        })
    }

    /// Try to raise one aliased atom to another, fusing their alias maps.
    ///
    /// If both atoms define the same alias handle with different bodies, the conflicting alias
    /// handle is returned.
    pub fn try_pow(&self, rhs: &Self) -> Result<Self, Atom> {
        Ok(Self {
            aliases: self.try_fuse_aliases(rhs)?,
            root: self.root.pow(&rhs.root),
        })
    }

    /// Removes any aliases in the root whose body has the same symmetric operator as its use in the root.
    /// For example `x+y+s(1), s(1)=z+w` will yield `x+y+z+w`. This is important to maintain invariants in pattern matching, such
    /// as argument counts.
    pub fn flatten_operators(&mut self) {
        self.root = self.root.replace_map(|a, ctx, out| {
            if (ctx.parent_type == Some(AtomType::Add) || ctx.parent_type == Some(AtomType::Mul))
                && let Some(alias) = self.aliases.get::<[u8]>(a.get_data())
                && ctx.parent_type == Some(alias.get_atom_type())
            {
                out.set_from_view(&alias.as_atom_view());
            }
        });
    }

    /// Removes any aliases that are not used in the root or any of the aliases.
    pub fn prune(&mut self) {
        let mut to_remove = Vec::new();

        for alias in self.aliases.keys() {
            if !self.root.contains(alias) && self.aliases.values().all(|a| !a.contains(alias)) {
                to_remove.push(alias.clone());
            }
        }

        let prunable = !to_remove.is_empty();
        for alias in to_remove {
            self.aliases.remove(&alias);
        }

        if prunable {
            // recursively prune until no more aliases are removable
            self.prune();
        }
    }

    /// Removes any duplicate aliases that map to the same body, keeping the first one encountered.
    pub fn fuse_duplicate_aliases(&mut self) {
        let mut inv_map: HashMap<&Atom, &Atom> = HashMap::default();
        let mut remap: HashMap<Atom, Atom> = HashMap::default();
        for (alias, body) in &self.aliases {
            if inv_map.contains_key(body) {
                remap.insert(alias.clone(), inv_map[body].clone());
            } else {
                inv_map.insert(body, alias);
            }
        }

        for (alias, old_alias) in remap {
            self.aliases.remove(&alias);

            self.root = self.root.replace_map(|atom, _, out| {
                if atom == alias.as_view() {
                    out.set_from_view(&old_alias.as_view());
                }
            });

            for x in self.aliases.values_mut() {
                *x = x.replace_map(|atom, _, out| {
                    if atom == alias.as_view() {
                        out.set_from_view(&old_alias.as_view());
                    }
                });
            }
        }
    }

    fn sorted_aliases(&self) -> Vec<(&Atom, &Atom)> {
        let mut aliases: Vec<_> = self.aliases.iter().collect();
        aliases.sort_by_cached_key(|(alias, _)| format!("{}", AtomPrinter::new(alias.as_view())));
        aliases
    }

    /// Fuses the alias maps of two aliased atoms, resolving conflicts with the provided function, using the minimal
    /// amount of renames by analyzing the dependency graph of aliases.
    fn fuse_aliases<'a>(&mut self, rhs: &'a Self, resolve: impl Fn(AtomView) -> Atom) -> Atom {
        struct NodeInfo<'a> {
            dependencies: HashSet<AtomView<'a>>,
            rename: Option<Atom>,
            resolved: bool,
        }

        let mut dependency_graph: HashMap<&Atom, _> = HashMap::default();
        for (alias, body) in &rhs.aliases {
            let mut dependencies = HashSet::default();
            body.visitor(&mut |a| {
                if rhs.aliases.contains_key::<[u8]>(&a.get_data()) {
                    dependencies.insert(a);
                    false
                } else {
                    true
                }
            });

            dependency_graph.insert(
                alias,
                NodeInfo {
                    dependencies,
                    rename: None,
                    resolved: false,
                },
            );
        }

        fn resolve_dependencies<'a>(
            current: AtomView<'a>,
            aliases: &mut HashMap<Atom, Atom>,
            rhs_aliases: &HashMap<Atom, Atom>,
            dependency_graph: &mut HashMap<&'a Atom, NodeInfo<'a>>,
            resolve: &impl Fn(AtomView) -> Atom,
        ) {
            let node = dependency_graph.get_mut(current.get_data()).unwrap();

            if node.resolved {
                return;
            }

            let dependencies = std::mem::take(&mut node.dependencies);
            for dep in &dependencies {
                resolve_dependencies(*dep, aliases, rhs_aliases, dependency_graph, resolve);
            }

            let new_body = if dependencies
                .iter()
                .all(|d| dependency_graph[d.get_data()].rename.is_none())
            {
                Cow::Borrowed(&rhs_aliases[current.get_data()]) // original body remains unchanged
            } else {
                let body = rhs_aliases[current.get_data()].replace_map(|a, _, out| {
                    if dependencies.contains(a.get_data())
                        && let Some(new_alias) = &dependency_graph.get(a.get_data()).unwrap().rename
                    {
                        {
                            out.set_from_view(&new_alias.as_view());
                        }
                    }
                });

                Cow::Owned(body)
            };

            let node = dependency_graph.get_mut(current.get_data()).unwrap();
            node.resolved = true;

            match aliases.get(current.get_data()) {
                Some(existing) if existing == &*new_body => {}
                Some(_) => {
                    let mut new_alias = resolve(current);
                    while aliases.contains_key(&new_alias) {
                        new_alias = resolve(new_alias.as_atom_view());
                    }

                    node.rename = Some(new_alias.clone());
                    aliases.insert(new_alias, new_body.into_owned());
                }
                None => {
                    aliases.insert(current.to_owned(), new_body.into_owned());
                }
            };
        }

        for alias in rhs.aliases.keys() {
            resolve_dependencies(
                alias.as_view(),
                &mut self.aliases,
                &rhs.aliases,
                &mut dependency_graph,
                &resolve,
            );
        }

        rhs.root.replace_map(|a, _, out| {
            if let Some(new_alias) = dependency_graph
                .get(a.get_data())
                .and_then(|node| node.rename.as_ref())
            {
                out.set_from_view(&new_alias.as_atom_view());
            }
        })
    }

    fn try_fuse_aliases(&self, rhs: &Self) -> Result<HashMap<Atom, Atom>, Atom> {
        let mut aliases = self.aliases.clone();

        for (alias, original) in &rhs.aliases {
            match aliases.entry(alias.clone()) {
                Entry::Occupied(entry) => {
                    if entry.get() != original {
                        return Err(alias.clone());
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(original.clone());
                }
            }
        }

        Ok(aliases)
    }

    fn alias_replacements(&self) -> Vec<(Atom, Atom)> {
        let mut replacements: Vec<_> = self
            .aliases
            .iter()
            .map(|(alias, body)| (alias.clone(), body.clone()))
            .collect();
        replacements.sort_by(|(_, b1), (_, b2)| {
            b2.as_view()
                .get_byte_size()
                .cmp(&b1.as_view().get_byte_size())
        });
        replacements
    }

    fn apply_alias_replacements(
        atom: &Atom,
        replacements: &[(Atom, Atom)],
        skip_whole_atom: Option<&Atom>,
    ) -> Atom {
        atom.replace_map(|a, _, out| {
            for (alias, body) in replacements {
                if skip_whole_atom.is_some_and(|skip| a == skip.as_view()) && a == body.as_view() {
                    continue;
                }

                if a == body.as_view() {
                    out.set_from_view(&alias.as_view());
                    break;
                }
            }
        })
    }

    fn rename_alias_in_atom(atom: &Atom, old: &Atom, new: &Atom) -> Atom {
        atom.replace_map(|a, _, out| {
            if a == old.as_view() {
                out.set_from_view(&new.as_view());
            }
        })
    }
}

/// A printer for aliased atoms, useful in a [format!].
///
/// # Examples
///
/// ```
/// use symbolica::prelude::*;
/// let a = parse!("(x+1)^2+(x+1)^3")
///     .alias_subexpressions(|_a, count, i| (count > 1).then(|| function!(symbol!("se"), i)));
/// println!("{}", a.printer(PrintOptions::file()));
/// ```
pub struct AliasedAtomPrinter<'a> {
    atom: &'a AliasedAtom,
    print_opts: PrintOptions,
}

impl fmt::Display for AliasedAtomPrinter<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let aliases = self.atom.sorted_aliases();

        if f.alternate() {
            writeln!(f, "{{")?;
            write!(
                f,
                "    {}",
                AtomPrinter::new_with_options(self.atom.root.as_view(), self.print_opts.clone())
            )?;
            for (alias, original) in aliases {
                writeln!(f, ",")?;
                write!(
                    f,
                    "    {}={}",
                    AtomPrinter::new_with_options(alias.as_view(), self.print_opts.clone()),
                    AtomPrinter::new_with_options(original.as_view(), self.print_opts.clone())
                )?;
            }
            write!(f, "\n}}")
        } else {
            write!(
                f,
                "{{{}",
                AtomPrinter::new_with_options(self.atom.root.as_view(), self.print_opts.clone())
            )?;
            for (alias, original) in aliases {
                write!(
                    f,
                    ", {}={}",
                    AtomPrinter::new_with_options(alias.as_view(), self.print_opts.clone()),
                    AtomPrinter::new_with_options(original.as_view(), self.print_opts.clone())
                )?;
            }
            write!(f, "}}")
        }
    }
}

impl From<Atom> for AliasedAtom {
    fn from(atom: Atom) -> Self {
        AliasedAtom {
            root: atom,
            aliases: HashMap::default(),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{atom::AtomCore, function, id::AliasedAtom, parse, symbol};

    #[test]
    fn create_alias() {
        let a: AliasedAtom = parse!("(x+1)^2+(x+1)^3").into();
        let b = a.add_alias(parse!("s(1)"), parse!("x+1"));
        let c = b + 2 + parse!("(x+1)^4");
        assert!(c.contains_symbol(symbol!("x")));
        let d = c.apply_aliases();
        assert!(!d.contains_symbol(symbol!("x")));
    }

    #[test]
    fn flatten() {
        let mut aliased: AliasedAtom = parse!("x+y+s(1)").into();
        aliased.register_alias(parse!("s(1)"), parse!("z+w"));
        aliased.flatten_operators();
        assert_eq!(aliased.get_root(), &parse!("x+y+z+w"));
    }

    fn aliased_atom() -> super::AliasedAtom {
        parse!("(x+1)^2+(x+1)^3")
            .alias_subexpressions(|_a, count, i| (count > 1).then(|| function!(symbol!("se"), i)))
    }

    #[test]
    fn byte_size_counts_root_and_aliases() {
        let aliased = aliased_atom();
        let expected = aliased.get_root().as_view().get_byte_size()
            + aliased
                .get_aliases()
                .iter()
                .map(|(alias, original)| {
                    alias.as_view().get_byte_size() + original.as_view().get_byte_size()
                })
                .sum::<usize>();

        assert_eq!(aliased.get_byte_size(), expected);
    }

    #[test]
    fn binary_ops_with_atoms_and_symbols_preserve_aliases() {
        let aliased = aliased_atom();
        let expected = parse!("(x+1)^2+(x+1)^3+y");

        let with_symbol_rhs = &aliased + symbol!("y");
        assert_eq!(with_symbol_rhs.get_aliases(), aliased.get_aliases());
        assert_eq!(with_symbol_rhs.into_inner(), expected);

        let with_atom_lhs = parse!("y") + &aliased;
        assert_eq!(with_atom_lhs.get_aliases(), aliased.get_aliases());
        assert_eq!(with_atom_lhs.into_inner(), expected);

        let with_symbol_lhs = symbol!("y") + &aliased;
        assert_eq!(with_symbol_lhs.get_aliases(), aliased.get_aliases());
        assert_eq!(with_symbol_lhs.into_inner(), expected);
    }

    #[test]
    fn rename_alias_updates_root_and_alias_bodies() {
        let mut aliased: AliasedAtom = parse!("s(1)+f(s(1))").into();
        aliased.register_alias(parse!("s(1)"), parse!("x"));
        aliased.register_alias(parse!("t(1)"), parse!("f1(s(1))"));

        assert!(
            aliased
                .rename_alias(parse!("s(1)"), parse!("u(1)"))
                .unwrap()
        );
        assert!(
            !aliased
                .rename_alias(parse!("missing(1)"), parse!("v(1)"))
                .unwrap()
        );

        assert_eq!(aliased.get_root(), &parse!("u(1)+f(u(1))"));
        assert_eq!(
            aliased.get_aliases().get(&parse!("u(1)")),
            Some(&parse!("x"))
        );
        assert_eq!(
            aliased.get_aliases().get(&parse!("t(1)")),
            Some(&parse!("f1(u(1))"))
        );
        assert!(!aliased.get_aliases().contains_key(&parse!("s(1)")));
    }

    #[test]
    fn try_ops_fuse_aliases() {
        let mut lhs: AliasedAtom = parse!("s(1)").into();
        lhs.register_alias(parse!("s(1)"), parse!("x+1"));

        let mut rhs: AliasedAtom = parse!("t(1)").into();
        rhs.register_alias(parse!("t(1)"), parse!("y+1"));

        let sum = lhs.try_add(&rhs).unwrap();
        assert_eq!(sum.get_aliases().len(), 2);
        assert_eq!(sum.into_inner(), parse!("x+y+2"));

        let product = lhs.try_mul(&rhs).unwrap();
        assert_eq!(product.get_aliases().len(), 2);
        assert_eq!(product.into_inner(), parse!("(1+x)*(1+y)"));

        let pow = lhs.try_pow(&rhs).unwrap();
        assert_eq!(pow.get_aliases().len(), 2);
        assert_eq!(pow.into_inner(), parse!("(1+x)^(1+y)"));
    }

    #[test]
    fn ops_with_resolver_fuse_independent_rhs_aliases() {
        let mut lhs: AliasedAtom = parse!("s(1)").into();
        lhs.register_alias(parse!("s(1)"), parse!("x+1"));

        let mut rhs: AliasedAtom = parse!("t(1)+z").into();
        rhs.register_alias(parse!("t(1)"), parse!("y+1"));

        let sum = lhs.add(&rhs, |_| parse!("u(1)"));

        assert_eq!(sum.get_aliases().len(), 2);
        assert_eq!(sum.into_inner(), parse!("x+y+z+2"));
    }

    #[test]
    fn ops_with_resolver_rename_rhs_alias_dependencies() {
        let mut lhs: AliasedAtom = parse!("t(1)").into();
        lhs.register_alias(parse!("t(1)"), parse!("x"));

        let mut rhs: AliasedAtom = parse!("s(1)").into();
        rhs.register_alias(parse!("s(1)"), parse!("t(1)+1"));
        rhs.register_alias(parse!("t(1)"), parse!("y"));

        let sum = lhs.add(&rhs, |_| parse!("u(1)"));

        assert_eq!(sum.get_aliases().get(&parse!("u(1)")), Some(&parse!("y")));
        assert_eq!(
            sum.get_aliases().get(&parse!("s(1)")),
            Some(&parse!("1+u(1)"))
        );
        assert_eq!(sum.into_inner(), parse!("x+y+1"));
    }

    #[test]
    fn try_ops_report_conflicting_alias_handle() {
        let mut lhs: AliasedAtom = parse!("s(1)").into();
        lhs.register_alias(parse!("s(1)"), parse!("x"));

        let mut rhs: AliasedAtom = parse!("s(1)").into();
        rhs.register_alias(parse!("s(1)"), parse!("y"));

        assert_eq!(lhs.try_add(&rhs).unwrap_err(), parse!("s(1)"));
        assert_eq!(lhs.try_mul(&rhs).unwrap_err(), parse!("s(1)"));
        assert_eq!(lhs.try_pow(&rhs).unwrap_err(), parse!("s(1)"));
    }

    #[test]
    fn apply_aliases_nested_updates_alias_bodies() {
        let mut aliased: AliasedAtom = parse!("f(x+1)+f2(f(x+1))").into();
        aliased.register_alias(parse!("s(1)"), parse!("x+1"));
        aliased.register_alias(parse!("t(1)"), parse!("f(x+1)"));

        let nested = aliased.apply_aliases_nested();

        assert_eq!(nested.get_root(), &parse!("t(1)+f2(t(1))"));
        assert_eq!(
            nested.get_aliases().get(&parse!("t(1)")),
            Some(&parse!("f(s(1))"))
        );
        assert_eq!(
            nested.get_aliases().get(&parse!("s(1)")),
            Some(&parse!("x+1"))
        );
    }
}