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
use std::{cell::RefCell, sync::Arc};

use swc_common::Span;

use crate::Visitable;

pub trait Fold<T: Visitable> {
    fn fold(&mut self, value: T) -> T;
}

pub trait FoldWith<V: ?Sized>: Sized + Visitable {
    fn fold_with(self, visitor: &mut V) -> Self
    where
        V: Fold<Self>,
    {
        visitor.fold(self)
    }

    fn fold_children_with(self, visitor: &mut V) -> Self;
}

impl<T, V> Fold<T> for V
where
    T: Visitable + FoldWith<Self>,
    V: ?Sized,
{
    default fn fold(&mut self, val: T) -> T {
        val.fold_children_with(self)
    }
}

impl<T, V> FoldWith<V> for Box<T>
where
    T: Visitable,
    V: ?Sized + Fold<T>,
{
    fn fold_children_with(self, v: &mut V) -> Self {
        Box::new(v.fold(*self))
    }
}

impl<T, V> FoldWith<V> for RefCell<T>
where
    T: Visitable,
    V: ?Sized + Fold<T>,
{
    fn fold_children_with(self, v: &mut V) -> Self {
        RefCell::new(v.fold(self.into_inner()))
    }
}

impl<T, V> Fold<T> for &'_ mut V
where
    T: FoldWith<Self>,
    V: ?Sized + Fold<T>,
{
    fn fold(&mut self, value: T) -> T {
        (**self).fold(value)
    }
}

impl<V> FoldWith<V> for Span
where
    V: ?Sized,
{
    /// Noop
    #[inline]
    fn fold_children_with(self, _: &mut V) -> Self {
        self
    }
}

impl<T, V> FoldWith<V> for Vec<T>
where
    T: Visitable,
    V: ?Sized + Fold<T>,
{
    fn fold_children_with(self, visitor: &mut V) -> Self {
        self.into_iter().map(|node| visitor.fold(node)).collect()
    }
}

/// Noop.
impl<T, V> FoldWith<V> for Arc<T>
where
    T: Visitable,
    V: ?Sized + Fold<T>,
{
    fn fold_children_with(self, _: &mut V) -> Self {
        self
    }
}

impl<T, V> FoldWith<V> for Option<T>
where
    T: Visitable,
    V: ?Sized + Fold<T>,
{
    fn fold_children_with(self, visitor: &mut V) -> Self {
        self.map(|value| visitor.fold(value))
    }
}