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
use base::{
    fnv::FnvMap,
    symbol::{Symbol, SymbolRef},
};

use crate::core::{
    optimize::{walk_expr, DifferentLifetime, Visitor},
    Allocator, CExpr, Expr, Named, Pattern,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
enum Pureness {
    None,
    Load,
    Call,
}

impl Pureness {
    fn merge(&mut self, pureness: Pureness) {
        *self = (*self).min(pureness);
    }
}

#[derive(Clone, Default, Debug)]
pub struct PurityMap(FnvMap<Symbol, Pureness>);

impl PurityMap {
    pub fn pure_call(&self, k: &SymbolRef) -> bool {
        self.0.get(k).map_or(false, |p| *p == Pureness::Call)
    }

    pub fn pure_load(&self, k: &SymbolRef) -> bool {
        self.0.contains_key(k)
    }
}

pub fn purity<'a>(expr: CExpr<'a>) -> PurityMap {
    let mut pure_symbols = PurityMap(FnvMap::default());

    let mut visitor = Pure {
        is_pure: Pureness::Call,
        pure_symbols: &mut pure_symbols,
    };

    visitor.visit_expr(expr);

    pure_symbols
}

struct Pure<'b> {
    is_pure: Pureness,
    pure_symbols: &'b mut PurityMap,
}

impl Pure<'_> {
    fn is_pure(&mut self, symbol: &Symbol, expr: CExpr) -> Pureness {
        let mut visitor = Pure {
            is_pure: Pureness::Call,
            pure_symbols: self.pure_symbols,
        };
        visitor.visit_expr(expr);
        let is_pure = visitor.is_pure;
        if is_pure != Pureness::None {
            self.pure_symbols.0.insert(symbol.clone(), is_pure);
        }
        is_pure
    }

    fn mark_pure(&mut self, pat: &Pattern) {
        match pat {
            Pattern::Ident(id) => {
                self.pure_symbols.0.insert(id.name.clone(), Pureness::Load);
            }
            Pattern::Record { fields, .. } => {
                for field in fields {
                    self.pure_symbols.0.insert(
                        field.1.as_ref().unwrap_or(&field.0.name).clone(),
                        Pureness::Load,
                    );
                }
            }
            Pattern::Constructor(_, params) => {
                for param in params {
                    self.pure_symbols
                        .0
                        .insert(param.name.clone(), Pureness::Load);
                }
            }
            Pattern::Literal(_) => (),
        }
    }
}

impl<'l, 'expr> Visitor<'l, 'expr> for Pure<'_> {
    type Producer = DifferentLifetime<'l, 'expr>;

    fn visit_expr(&mut self, expr: CExpr<'expr>) -> Option<CExpr<'l>> {
        match *expr {
            Expr::Call(ref f, _) => match f {
                Expr::Ident(ref id, ..) => {
                    if self.pure_symbols.pure_call(&*id.name) || id.name.is_primitive() {
                        walk_expr(self, expr);
                    } else {
                        self.is_pure = Pureness::None;
                    }
                }
                _ => {
                    self.is_pure = Pureness::None;
                }
            },

            Expr::Ident(ref id, ..) => {
                if !self.pure_symbols.pure_load(&id.name)
                    && !id.name.is_primitive()
                    && !id.name.is_global()
                {
                    self.is_pure.merge(Pureness::Load);
                }
            }

            Expr::Let(ref bind, expr) => {
                match bind.expr {
                    // Creating a group of closures is always pure (though calling them may not be)
                    Named::Recursive(ref closures) => {
                        for closure in closures {
                            for arg in &closure.args {
                                self.pure_symbols.0.insert(arg.name.clone(), Pureness::Load);
                            }
                            self.is_pure(&closure.name.name, closure.expr);
                        }
                    }
                    Named::Expr(expr) => {
                        let is_pure = self.is_pure(&bind.name.name, expr);
                        self.is_pure.merge(is_pure);
                    }
                }
                self.visit_expr(expr);
            }

            Expr::Match(scrutinee, alts) => {
                let is_pure = self.is_pure;

                self.is_pure = Pureness::Call;
                self.visit_expr(scrutinee);
                let scrutinee_is_pure = self.is_pure;

                self.is_pure.merge(is_pure);

                if scrutinee_is_pure != Pureness::None {
                    for alt in alts {
                        self.mark_pure(&alt.pattern);
                    }
                }
                for alt in alts {
                    self.visit_expr(alt.expr);
                }
            }

            _ => {
                walk_expr(self, expr);
            }
        }
        None
    }
    fn detach_allocator(&self) -> Option<&'l Allocator<'l>> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::sync::Arc;

    use base::symbol::Symbols;

    use crate::core::interpreter::tests::parse_expr;

    #[test]
    fn pure_global() {
        let mut symbols = Symbols::new();

        let allocator = Arc::new(Allocator::new());

        let expr = parse_expr(&mut symbols, &allocator, "let x = global in x");

        assert_eq!(
            purity(expr).0,
            collect![(symbols.simple_symbol("x"), Pureness::Load)]
        );
    }
}