1
//! Model-scoped representation choices for `--channelling uniform`.
2
//!
3
//! Choices concern the outer type family, ignoring domain bounds and element types. Integer
4
//! encoding is separate from matrix layout. State is scoped to a rewrite, including nested
5
//! rewrites, so enumerated models and subsequent solves never inherit another model's choices.
6
use super::{ReprInitError, ReprRulePtr};
7
use crate::ast::{DomainPtr, ReturnType, Typeable};
8
use crate::settings::{Channelling, channelling};
9
use std::cell::RefCell;
10
use std::collections::HashMap;
11
use std::mem::{Discriminant, discriminant};
12

            
13
pub(crate) type Choices = HashMap<Discriminant<ReturnType>, ReprRulePtr>;
14
thread_local! {
15
    static CHOICES: RefCell<Choices> = RefCell::new(HashMap::new());
16
}
17

            
18
264495897
fn family(dom: &DomainPtr, rule: ReprRulePtr) -> Discriminant<ReturnType> {
19
264495897
    discriminant(&if rule.is_integer_encoding() {
20
55793987
        ReturnType::Int
21
    } else {
22
208701910
        dom.return_type()
23
    })
24
264495897
}
25

            
26
/// Return the uniform representation selected for this type in the current model.
27
688105827
pub fn selected(dom: &DomainPtr, integer_encoding: bool) -> Option<ReprRulePtr> {
28
688105827
    if channelling() != Channelling::Uniform {
29
        return None;
30
688105827
    }
31
688105827
    let key = discriminant(&if integer_encoding {
32
4133707
        ReturnType::Int
33
    } else {
34
683972120
        dom.return_type()
35
    });
36
688105827
    CHOICES.with(|choices| choices.borrow().get(&key).copied())
37
688105827
}
38

            
39
262168302
pub(crate) fn check_choice(dom: &DomainPtr, rule: ReprRulePtr) -> Result<(), ReprInitError> {
40
262168302
    if channelling() == Channelling::Uniform
41
        && let Some(existing) =
42
250689044
            CHOICES.with(|choices| choices.borrow().get(&family(dom, rule)).copied())
43
111712926
        && existing.id() != rule.id()
44
    {
45
103153467
        return Err(ReprInitError::UniformConflict {
46
103153467
            domain: dom.clone(),
47
103153467
            existing: existing.name(),
48
103153467
            requested: rule.name(),
49
103153467
        });
50
159014835
    }
51
159014835
    Ok(())
52
262168302
}
53

            
54
1300552
pub(crate) fn reset() {
55
1300552
    CHOICES.with(|choices| choices.borrow_mut().clear());
56
1300552
}
57

            
58
14420637
pub(crate) fn record_choice(dom: &DomainPtr, rule: ReprRulePtr) {
59
14420637
    if channelling() == Channelling::Uniform {
60
13806853
        CHOICES.with(|choices| {
61
13806853
            choices.borrow_mut().insert(family(dom, rule), rule);
62
13806853
        });
63
613784
    }
64
14420637
}
65

            
66
/// Restore the enclosing rewrite's choices even on early return or panic.
67
pub(crate) struct Scope(Choices);
68
impl Scope {
69
1447046
    pub(crate) fn new() -> Self {
70
1447046
        Self(CHOICES.with(|choices| std::mem::take(&mut *choices.borrow_mut())))
71
1447046
    }
72

            
73
67753183
    pub(crate) fn save() -> Self {
74
67753183
        Self(CHOICES.with(|choices| choices.borrow().clone()))
75
67753183
    }
76
}
77
impl Drop for Scope {
78
2610895622
    fn drop(&mut self) {
79
2610895622
        CHOICES.with(|choices| *choices.borrow_mut() = std::mem::take(&mut self.0));
80
2610895622
    }
81
}
82

            
83
/// Representation probes instantiate a detached declaration. They must not select a family.
84
22103639
pub(crate) fn probe<T>(f: impl FnOnce() -> T) -> T {
85
22103639
    if channelling() != Channelling::Uniform {
86
2434056
        return f();
87
19669583
    }
88
19669583
    let _restore = Scope::save();
89
19669583
    f()
90
22103639
}
91

            
92
/// Rule applicability is speculative. Commit choices only for the selected effect.
93
2892019977
pub(crate) fn attempt(
94
2892019977
    f: impl FnOnce() -> crate::rule_engine::ApplicationResult,
95
2892019977
) -> crate::rule_engine::ApplicationResult {
96
2892019977
    if channelling() != Channelling::Uniform {
97
350324566
        return f();
98
2541695411
    }
99
2541695411
    let previous = CHOICES.with(|choices| choices.borrow().clone());
100
2541695411
    let restore = Scope(previous.clone());
101
2541695411
    let result = f().map(|mut effect| {
102
61999495
        effect.uniform_choices = CHOICES.with(|choices| {
103
61999495
            choices
104
61999495
                .borrow()
105
61999495
                .iter()
106
131833102
                .filter(|(key, _)| !previous.contains_key(*key))
107
2170161
                .map(|(key, rule)| (*key, *rule))
108
                .collect()
109
61999495
        });
110
61999495
        effect
111
61999495
    });
112
2541695411
    drop(restore);
113
2541695411
    result
114
2892019977
}
115

            
116
69513388
pub(crate) fn commit(choices: Choices) {
117
69513388
    if channelling() == Channelling::Uniform {
118
62006067
        CHOICES.with(|current| current.borrow_mut().extend(choices));
119
7507321
    }
120
69513388
}