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
#[cfg(feature = "fold")]
use crate::{Fold, FoldWith};
use serde::export::PhantomData;
use std::borrow::Cow;

pub trait CompilerPass {
    /// Name should follow hyphen-case
    ///
    /// TODO: timing
    fn name() -> Cow<'static, str>;
}

pub trait Repeated: CompilerPass {
    /// Should run again?
    fn changed(&self) -> bool;

    /// Reset.
    fn reset(&mut self);
}

pub trait RepeatedPass<At>: Repeated + CompilerPass {}

impl<T, P> RepeatedPass<T> for P where P: CompilerPass + Repeated {}

#[derive(Debug, Copy, Clone)]
pub struct Repeat<P, At>
where
    P: RepeatedPass<At>,
{
    pass: P,
    at: PhantomData<At>,
}

impl<P, At> Repeat<P, At>
where
    P: RepeatedPass<At>,
{
    pub fn new(pass: P) -> Self {
        Self {
            pass,
            at: PhantomData,
        }
    }
}

impl<P, At> CompilerPass for Repeat<P, At>
where
    P: RepeatedPass<At>,
{
    fn name() -> Cow<'static, str> {
        format!("Repeat({})", P::name()).into()
    }
}

impl<P, At> Repeated for Repeat<P, At>
where
    P: RepeatedPass<At>,
{
    fn changed(&self) -> bool {
        self.pass.changed()
    }

    fn reset(&mut self) {
        self.pass.reset()
    }
}

#[cfg(feature = "fold")]
impl<P, At> Fold<At> for Repeat<P, At>
where
    At: FoldWith<Self> + FoldWith<P>,
    P: RepeatedPass<At>,
{
    fn fold(&mut self, mut node: At) -> At {
        loop {
            self.pass.reset();
            node = node.fold_with(&mut self.pass);

            if !self.pass.changed() {
                break;
            }
        }

        node
    }
}