1
//! The session's struct instances (rstruct S5): a global that holds a struct
2
//! carries an [`Expr::Instance`] leaf, and the instance's field constants live
3
//! here, so aliasing, mutation through an unwritten global and cycles survive
4
//! from one unit to the next.
5

            
6
use std::cell::RefCell;
7
use std::collections::{BTreeMap, BTreeSet};
8

            
9
use crate::ast::{Expr, StructId};
10

            
11
use super::carry::Carried;
12
use super::table::SymbolTable;
13

            
14
/// A live instance: its layout and the constant of each field.
15
#[derive(Clone, Debug, PartialEq)]
16
pub struct StructInstance {
17
    pub layout: StructId,
18
    pub fields: Vec<Expr>,
19
}
20

            
21
#[derive(Clone, Debug, Default, PartialEq)]
22
pub(crate) struct InstanceHeap {
23
    instances: BTreeMap<u32, StructInstance>,
24
    next_serial: u32,
25
}
26

            
27
/// What a host read of one instance after a unit: its fields, or `None` when
28
/// it holds a value no constant holds (a closure, an entity, compound money).
29
pub type Found = BTreeMap<u32, Option<StructInstance>>;
30

            
31
/// The serials of the instances `expr` mentions.
32
24159483
fn mentioned(expr: &Expr) -> Vec<u32> {
33
24159483
    let found = RefCell::new(Vec::new());
34
781108129
    expr.any_form(|form| {
35
781108129
        if let Expr::Instance(serial, _) = form {
36
7285064
            found.borrow_mut().push(*serial);
37
773823065
        }
38
781108129
        false
39
781108129
    });
40
24159483
    found.into_inner()
41
24159483
}
42

            
43
impl SymbolTable {
44
    /// The serial the next unit's first new instance takes.
45
    #[must_use]
46
2342440
    pub fn next_serial(&self) -> u32 {
47
2342440
        self.instances.next_serial
48
2342440
    }
49

            
50
    /// The live instances, by serial.
51
3783468
    pub fn instances(&self) -> impl Iterator<Item = (u32, &StructInstance)> {
52
3783468
        self.instances
53
3783468
            .instances
54
3783468
            .iter()
55
1981227
            .map(|(serial, instance)| (*serial, instance))
56
3783468
    }
57

            
58
    /// Replaces the heap with what a host read after a unit. An instance that
59
    /// is opaque, or reaches one or one never read, is dropped and so is every
60
    /// global that reaches it, loud when a later unit reads it; an instance no
61
    /// global or carried closure reaches is swept. The serial counter never
62
    /// goes back.
63
506709
    pub fn settle_instances(&mut self, found: Found, next_serial: u32) {
64
506709
        let usable = usable(found);
65
506709
        self.demote_unreachable(&usable);
66
506709
        self.instances.instances = self.swept(usable);
67
506709
        self.instances.next_serial = self.instances.next_serial.max(next_serial);
68
506709
    }
69

            
70
1013418
    fn global_values(&self) -> impl Iterator<Item = (&String, &Expr)> {
71
1013418
        self.symbols
72
1013418
            .iter()
73
536870622
            .filter_map(|(name, symbol)| symbol.value().map(|value| (name, value)))
74
1013418
    }
75

            
76
506709
    fn demote_unreachable(&mut self, usable: &BTreeMap<u32, StructInstance>) {
77
506709
        let lost: Vec<(String, &'static str)> = self
78
506709
            .global_values()
79
8468001
            .filter(|(_, value)| {
80
8468001
                mentioned(value)
81
8468001
                    .iter()
82
3521890
                    .any(|serial| !usable.contains_key(serial))
83
8468001
            })
84
837
            .map(|(name, value)| match value {
85
1
                Expr::Lambda(..) => (name.clone(), "closure"),
86
836
                _ => (name.clone(), "struct"),
87
837
            })
88
            .collect();
89
506709
        for (name, type_name) in lost {
90
837
            self.carry(&name, Carried::Opaque(type_name.to_string()));
91
        }
92
506709
    }
93

            
94
506709
    fn swept(&self, mut usable: BTreeMap<u32, StructInstance>) -> BTreeMap<u32, StructInstance> {
95
506709
        let mut marked = BTreeSet::new();
96
506709
        let mut pending: Vec<u32> = self
97
506709
            .global_values()
98
8467164
            .flat_map(|(_, value)| mentioned(value))
99
            .collect();
100
4148821
        while let Some(serial) = pending.pop() {
101
3642112
            if marked.insert(serial)
102
3609871
                && let Some(instance) = usable.get(&serial)
103
            {
104
3609871
                pending.extend(instance.fields.iter().flat_map(mentioned));
105
32241
            }
106
        }
107
3610706
        usable.retain(|serial, _| marked.contains(serial));
108
506709
        usable
109
506709
    }
110
}
111

            
112
/// The instances every field of which is a constant of live instances.
113
506709
fn usable(found: Found) -> BTreeMap<u32, StructInstance> {
114
506709
    let mut usable: BTreeMap<u32, StructInstance> = found
115
506709
        .into_iter()
116
3611541
        .filter_map(|(serial, instance)| instance.map(|instance| (serial, instance)))
117
        .collect();
118
    loop {
119
506710
        let dangling: Vec<u32> = usable
120
506710
            .iter()
121
3610707
            .filter(|(_, instance)| {
122
3610707
                instance
123
3610707
                    .fields
124
3610707
                    .iter()
125
3610707
                    .flat_map(mentioned)
126
121062
                    .any(|serial| !usable.contains_key(&serial))
127
3610707
            })
128
1
            .map(|(serial, _)| *serial)
129
            .collect();
130
506710
        if dangling.is_empty() {
131
506709
            return usable;
132
1
        }
133
1
        for serial in dangling {
134
1
            usable.remove(&serial);
135
        }
136
    }
137
506709
}
138

            
139
#[cfg(test)]
140
#[path = "instances_tests.rs"]
141
mod tests;