1
//! Settles the homes of a unit's stored globals, struct fields and assigned
2
//! binders (plan 0014 stages GJ and F2a): a home's type is the join of its init
3
//! and every store into it, and a store's type exists only where it compiles.
4
//! The unit compiles again, from the table as it was, until the homes it
5
//! allocates are the join of its stores.
6

            
7
use crate::error::{Error, Result};
8
use crate::runtime::SymbolTable;
9

            
10
/// Runs `attempt` until no home it allocated is narrower than the join of the
11
/// stores it compiled. A unit whose homes are right the first time compiles
12
/// once; a unit that never settles is an `Error::Resource`, so the loop is
13
/// bounded by the homes the unit can widen (three steps each, plus the first
14
/// attempt). A unit that does not compile ran nothing, so it leaves the table
15
/// as it was.
16
2262245
pub(super) fn settle_homes<T>(
17
2262245
    symbols: &mut SymbolTable,
18
2262245
    mut attempt: impl FnMut(&mut SymbolTable) -> Result<T>,
19
2262245
) -> Result<T> {
20
2262245
    let pristine = symbols.clone();
21
2262245
    symbols.begin_home_attempt(Default::default());
22
2262245
    let mut attempts = 1;
23
    loop {
24
2352290
        let result = attempt(symbols)
25
211149
            .map_err(|err| symbols.explain_expired(err))
26
211149
            .map_err(|err| symbols.name_structs(err));
27
2352290
        let Some(hints) = symbols.widened_homes() else {
28
2262242
            symbols.end_home_attempt();
29
2262242
            if result.is_err() {
30
187703
                *symbols = pristine;
31
2074539
            }
32
2262242
            return result;
33
        };
34
90048
        if attempts > 3 * (symbols.unit_home_count() + symbols.site_home_count()) {
35
3
            let unsettled = symbols
36
3
                .unsettled_home()
37
3
                .map_or_else(|| "a global home".to_string(), |key| key.to_string());
38
3
            let err = symbols.name_structs(Error::Resource(format!(
39
3
                "the type of {unsettled} did not settle"
40
3
            )));
41
3
            *symbols = pristine;
42
3
            return Err(err);
43
90045
        }
44
90045
        let closures = symbols.closure_shapes();
45
90045
        let forced = symbols.forced_cells();
46
90045
        let refused = symbols.refused_seeds();
47
90045
        *symbols = pristine.clone();
48
90045
        symbols.begin_home_attempt(hints);
49
90045
        symbols.hint_closures(closures);
50
90045
        symbols.force_cells(forced);
51
90045
        symbols.unseed_cells(refused);
52
90045
        attempts += 1;
53
    }
54
2262245
}
55

            
56
#[cfg(test)]
57
#[path = "settle_tests.rs"]
58
mod tests;