1
use std::{cell::Cell, fmt::Display, str::FromStr};
2

            
3
use schemars::JsonSchema;
4
use serde::{Deserialize, Serialize};
5
use strum_macros::{Display as StrumDisplay, EnumIter};
6

            
7
use crate::bug;
8

            
9
use crate::solver::adaptors::smt::{IntTheory, MatrixTheory, TheoryConfig};
10

            
11
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
12
pub enum Parser {
13
    #[default]
14
    TreeSitter,
15
    ViaConjure,
16
}
17

            
18
impl Display for Parser {
19
20944
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20
20944
        match self {
21
2100
            Parser::TreeSitter => write!(f, "tree-sitter"),
22
18844
            Parser::ViaConjure => write!(f, "via-conjure"),
23
        }
24
20944
    }
25
}
26

            
27
impl FromStr for Parser {
28
    type Err = String;
29

            
30
8848
    fn from_str(s: &str) -> Result<Self, Self::Err> {
31
8848
        match s.trim().to_ascii_lowercase().as_str() {
32
8848
            "tree-sitter" => Ok(Parser::TreeSitter),
33
7334
            "via-conjure" => Ok(Parser::ViaConjure),
34
            other => Err(format!(
35
                "unknown parser: {other}; expected one of: tree-sitter, via-conjure"
36
            )),
37
        }
38
8848
    }
39
}
40

            
41
thread_local! {
42
    /// Thread-local setting for which parser is currently active.
43
    ///
44
    /// Must be explicitly set before use.
45
    static CURRENT_PARSER: Cell<Option<Parser>> = const { Cell::new(None) };
46
}
47

            
48
9204
pub fn set_current_parser(parser: Parser) {
49
9204
    CURRENT_PARSER.with(|current| current.set(Some(parser)));
50
9204
}
51

            
52
pub fn current_parser() -> Parser {
53
    CURRENT_PARSER.with(|current| {
54
        current.get().unwrap_or_else(|| {
55
            // loud failure on purpose, so we don't end up using the default
56
            bug!("current parser not set for this thread; call set_current_parser first")
57
        })
58
    })
59
}
60

            
61
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
62
pub enum Rewriter {
63
    Naive,
64
    Morph,
65
}
66

            
67
thread_local! {
68
    /// Thread-local setting for which rewriter is currently active.
69
    ///
70
    /// Must be explicitly set before use.
71
    static CURRENT_REWRITER: Cell<Option<Rewriter>> = const { Cell::new(None) };
72
}
73

            
74
impl Display for Rewriter {
75
18364
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76
18364
        match self {
77
18364
            Rewriter::Naive => write!(f, "naive"),
78
            Rewriter::Morph => write!(f, "morph"),
79
        }
80
18364
    }
81
}
82

            
83
impl FromStr for Rewriter {
84
    type Err = String;
85

            
86
5808
    fn from_str(s: &str) -> Result<Self, Self::Err> {
87
5808
        match s.trim().to_ascii_lowercase().as_str() {
88
5808
            "naive" => Ok(Rewriter::Naive),
89
            "morph" => Ok(Rewriter::Morph),
90
            other => Err(format!(
91
                "unknown rewriter: {other}; expected one of: naive, morph"
92
            )),
93
        }
94
5808
    }
95
}
96

            
97
20464
pub fn set_current_rewriter(rewriter: Rewriter) {
98
20464
    CURRENT_REWRITER.with(|current| current.set(Some(rewriter)));
99
20464
}
100

            
101
2044
pub fn current_rewriter() -> Rewriter {
102
2044
    CURRENT_REWRITER.with(|current| {
103
2044
        current.get().unwrap_or_else(|| {
104
            // loud failure on purpose, so we don't end up using the default
105
            bug!("current rewriter not set for this thread; call set_current_rewriter first")
106
        })
107
2044
    })
108
2044
}
109

            
110
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111
pub enum QuantifiedExpander {
112
    Native,
113
    ViaSolver,
114
    ViaSolverAc,
115
}
116

            
117
impl Display for QuantifiedExpander {
118
18376
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119
18376
        match self {
120
1216
            QuantifiedExpander::Native => write!(f, "native"),
121
720
            QuantifiedExpander::ViaSolver => write!(f, "via-solver"),
122
16440
            QuantifiedExpander::ViaSolverAc => write!(f, "via-solver-ac"),
123
        }
124
18376
    }
125
}
126

            
127
impl FromStr for QuantifiedExpander {
128
    type Err = String;
129

            
130
6368
    fn from_str(s: &str) -> Result<Self, Self::Err> {
131
6368
        match s.trim().to_ascii_lowercase().as_str() {
132
6368
            "native" => Ok(QuantifiedExpander::Native),
133
5764
            "via-solver" => Ok(QuantifiedExpander::ViaSolver),
134
5404
            "via-solver-ac" => Ok(QuantifiedExpander::ViaSolverAc),
135
            _ => Err(format!(
136
                "unknown comprehension expander: {s}; expected one of: \
137
                 native, via-solver, via-solver-ac"
138
            )),
139
        }
140
6368
    }
141
}
142

            
143
thread_local! {
144
    /// Thread-local setting for which comprehension expansion strategy is currently active.
145
    ///
146
    /// Must be explicitly set before use.
147
    static COMPREHENSION_EXPANDER: Cell<Option<QuantifiedExpander>> = const { Cell::new(None) };
148
}
149

            
150
9242
pub fn set_comprehension_expander(expander: QuantifiedExpander) {
151
9242
    COMPREHENSION_EXPANDER.with(|current| current.set(Some(expander)));
152
9242
}
153

            
154
889630
pub fn comprehension_expander() -> QuantifiedExpander {
155
889630
    COMPREHENSION_EXPANDER.with(|current| {
156
889630
        current.get().unwrap_or_else(|| {
157
            // loud failure on purpose, so we don't end up using the default
158
            bug!(
159
                "comprehension expander not set for this thread; call set_comprehension_expander first"
160
            )
161
        })
162
889630
    })
163
889630
}
164

            
165
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize, JsonSchema)]
166
pub enum SatEncoding {
167
    #[default]
168
    Log,
169
    Direct,
170
    Order,
171
}
172

            
173
impl SatEncoding {
174
15820
    pub const fn as_str(self) -> &'static str {
175
15820
        match self {
176
5460
            SatEncoding::Log => "log",
177
6580
            SatEncoding::Direct => "direct",
178
3780
            SatEncoding::Order => "order",
179
        }
180
15820
    }
181

            
182
2260
    pub const fn as_rule_set(self) -> &'static str {
183
2260
        match self {
184
780
            SatEncoding::Log => "SAT_Log",
185
940
            SatEncoding::Direct => "SAT_Direct",
186
540
            SatEncoding::Order => "SAT_Order",
187
        }
188
2260
    }
189
}
190

            
191
impl Display for SatEncoding {
192
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193
        match self {
194
            SatEncoding::Log => write!(f, "log"),
195
            SatEncoding::Direct => write!(f, "direct"),
196
            SatEncoding::Order => write!(f, "order"),
197
        }
198
    }
199
}
200

            
201
impl FromStr for SatEncoding {
202
    type Err = String;
203

            
204
    fn from_str(s: &str) -> Result<Self, Self::Err> {
205
        match s.trim().to_ascii_lowercase().as_str() {
206
            "log" => Ok(SatEncoding::Log),
207
            "direct" => Ok(SatEncoding::Direct),
208
            "order" => Ok(SatEncoding::Order),
209
            other => Err(format!(
210
                "unknown sat-encoding: {other}; expected one of: log, direct, order"
211
            )),
212
        }
213
    }
214
}
215

            
216
#[derive(
217
    Debug,
218
    EnumIter,
219
    StrumDisplay,
220
    PartialEq,
221
    Eq,
222
    Hash,
223
    Clone,
224
    Copy,
225
    Serialize,
226
    Deserialize,
227
    JsonSchema,
228
)]
229
pub enum SolverFamily {
230
    Minion,
231
    Sat(SatEncoding),
232
    Smt(TheoryConfig),
233
}
234

            
235
thread_local! {
236
    /// Thread-local setting for which solver family is currently active.
237
    ///
238
    /// Must be explicitly set before use.
239
    static CURRENT_SOLVER_FAMILY: Cell<Option<SolverFamily>> = const { Cell::new(None) };
240
}
241

            
242
pub const DEFAULT_MINION_DISCRETE_THRESHOLD: usize = 10;
243

            
244
thread_local! {
245
    /// Thread-local setting controlling when Minion int domains are emitted as `DISCRETE`.
246
    ///
247
    /// If an int domain size is <= this threshold, the Minion adaptor uses `DISCRETE`; otherwise
248
    /// it uses `BOUND`, unless another constraint requires `DISCRETE`.
249
    static MINION_DISCRETE_THRESHOLD: Cell<usize> =
250
        const { Cell::new(DEFAULT_MINION_DISCRETE_THRESHOLD) };
251
}
252

            
253
9204
pub fn set_current_solver_family(solver_family: SolverFamily) {
254
9204
    CURRENT_SOLVER_FAMILY.with(|current| current.set(Some(solver_family)));
255
9204
}
256

            
257
pub fn current_solver_family() -> SolverFamily {
258
    CURRENT_SOLVER_FAMILY.with(|current| {
259
        current.get().unwrap_or_else(|| {
260
            // loud failure on purpose, so we don't end up using the default
261
            bug!(
262
                "current solver family not set for this thread; call set_current_solver_family first"
263
            )
264
        })
265
    })
266
}
267

            
268
9204
pub fn set_minion_discrete_threshold(threshold: usize) {
269
9204
    MINION_DISCRETE_THRESHOLD.with(|current| current.set(threshold));
270
9204
}
271

            
272
79090
pub fn minion_discrete_threshold() -> usize {
273
79090
    MINION_DISCRETE_THRESHOLD.with(|current| current.get())
274
79090
}
275

            
276
impl FromStr for SolverFamily {
277
    type Err = String;
278

            
279
8228
    fn from_str(s: &str) -> Result<Self, Self::Err> {
280
8228
        let s = s.trim().to_ascii_lowercase();
281

            
282
8228
        match s.as_str() {
283
8228
            "minion" => Ok(SolverFamily::Minion),
284
3320
            "sat" | "sat-log" => Ok(SolverFamily::Sat(SatEncoding::Log)),
285
2540
            "sat-direct" => Ok(SolverFamily::Sat(SatEncoding::Direct)),
286
1600
            "sat-order" => Ok(SolverFamily::Sat(SatEncoding::Order)),
287
1060
            "smt" => Ok(SolverFamily::Smt(TheoryConfig::default())),
288
1060
            other => {
289
                // allow forms like `smt-bv-atomic` or `smt-lia-arrays`
290
1060
                if other.starts_with("smt-") {
291
1060
                    let parts = other.split('-').skip(1);
292
1060
                    let mut ints = IntTheory::default();
293
1060
                    let mut matrices = MatrixTheory::default();
294
1060
                    let mut unwrap_alldiff = false;
295

            
296
2200
                    for token in parts {
297
2200
                        match token {
298
2200
                            "" => {}
299
2200
                            "lia" => ints = IntTheory::Lia,
300
1220
                            "bv" => ints = IntTheory::Bv,
301
1140
                            "arrays" => matrices = MatrixTheory::Arrays,
302
160
                            "atomic" => matrices = MatrixTheory::Atomic,
303
80
                            "nodiscrete" => unwrap_alldiff = true,
304
                            other_token => {
305
                                return Err(format!(
306
                                    "unknown SMT theory option '{other_token}', must be one of bv|lia|arrays|atomic|nodiscrete"
307
                                ));
308
                            }
309
                        }
310
                    }
311

            
312
1060
                    return Ok(SolverFamily::Smt(TheoryConfig {
313
1060
                        ints,
314
1060
                        matrices,
315
1060
                        unwrap_alldiff,
316
1060
                    }));
317
                }
318
                Err(format!(
319
                    "unknown solver family '{other}', expected one of: minion, sat-log, sat-direct, sat-order, smt[(bv|lia)-(arrays|atomic)][-nodiscrete]"
320
                ))
321
            }
322
        }
323
8228
    }
324
}
325

            
326
impl SolverFamily {
327
64120
    pub fn as_str(&self) -> String {
328
64120
        match self {
329
40880
            SolverFamily::Minion => "minion".to_owned(),
330
15820
            SolverFamily::Sat(encoding) => format!("sat-{}", encoding.as_str()),
331
7420
            SolverFamily::Smt(theory_config) => format!("smt-{}", theory_config.as_str()),
332
        }
333
64120
    }
334
}
335

            
336
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
337
pub struct SolverArgs {
338
    pub timeout_ms: Option<u64>,
339
}