1
use std::{
2
    cell::{Cell, RefCell},
3
    collections::VecDeque,
4
    fmt::Display,
5
    io::{self, BufRead, Write},
6
    str::FromStr,
7
};
8

            
9
use schemars::JsonSchema;
10
use serde::{Deserialize, Serialize};
11
use strum_macros::{Display as StrumDisplay, EnumIter};
12

            
13
use crate::bug;
14
use crate::bug_assert;
15

            
16
/// Strategy used when a modelling decision has more than one applicable answer.
17
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18
pub enum Heuristic {
19
    First,
20
    Random,
21
    #[default]
22
    Compact,
23
    /// Prompt on stdin, or consume values from [`set_heuristic_responses`].
24
    Interactive,
25
    /// Enumerate every applicable choice. This is supported by the exhaustive model generator,
26
    /// but is not accepted by the command-line interface yet.
27
    All,
28
}
29

            
30
impl Display for Heuristic {
31
2652470
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32
2652470
        f.write_str(match self {
33
2356
            Self::First => "f",
34
            Self::Random => "r",
35
25127
            Self::Compact => "c",
36
            Self::Interactive => "i",
37
2624987
            Self::All => "x",
38
        })
39
2652470
    }
40
}
41

            
42
impl FromStr for Heuristic {
43
    type Err = String;
44

            
45
51507
    fn from_str(value: &str) -> Result<Self, Self::Err> {
46
51507
        match value.trim().to_ascii_lowercase().as_str() {
47
590
            "f" | "first" => Ok(Self::First),
48
1
            "r" | "random" => Ok(Self::Random),
49
8846
            "c" | "compact" => Ok(Self::Compact),
50
2
            "i" | "interactive" => Ok(Self::Interactive),
51
42068
            "x" | "all" => Ok(Self::All),
52
            other => Err(format!(
53
                "unknown heuristic '{other}'; expected one of: f, r, c, i, x"
54
            )),
55
        }
56
51507
    }
57
}
58

            
59
/// Whether a declaration may have more than one channelled representation.
60
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
61
pub enum Channelling {
62
    #[default]
63
    No,
64
    Yes,
65
    /// One representation kind per type family throughout a model, without channelling.
66
    Uniform,
67
}
68

            
69
impl Display for Channelling {
70
2681208
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71
2681208
        f.write_str(match self {
72
102255
            Self::No => "no",
73
            Self::Yes => "yes",
74
2578953
            Self::Uniform => "uniform",
75
        })
76
2681208
    }
77
}
78

            
79
impl FromStr for Channelling {
80
    type Err = String;
81

            
82
51132
    fn from_str(value: &str) -> Result<Self, Self::Err> {
83
51132
        match value.trim().to_ascii_lowercase().as_str() {
84
15809
            "no" => Ok(Self::No),
85
7
            "yes" => Ok(Self::Yes),
86
35316
            "uniform" => Ok(Self::Uniform),
87
            other => Err(format!(
88
                "unknown channelling setting '{other}'; expected yes, no, or uniform"
89
            )),
90
        }
91
51132
    }
92
}
93

            
94
pub const DEFAULT_HEURISTIC_SEED: u64 = 0;
95

            
96
thread_local! {
97
    static ELEMENT_ENCODING: Cell<Option<crate::ast::sat_decision::ElementEncoding>> = const { Cell::new(None) };
98
    static TABLE_ENCODING: Cell<Option<crate::ast::sat_decision::TableEncoding>> = const { Cell::new(None) };
99
    static ALLDIFFERENT_ENCODING: Cell<Option<crate::ast::sat_decision::AllDifferentEncoding>> = const { Cell::new(None) };
100
    static PB_ENCODING: Cell<Option<crate::ast::sat_decision::PbEncoding>> = const { Cell::new(None) };
101
    static CARDINALITY_ENCODING: Cell<Option<crate::ast::sat_decision::CardinalityEncoding>> = const { Cell::new(None) };
102
    static AMO_ENCODING: Cell<Option<crate::ast::sat_decision::AmoEncoding>> = const { Cell::new(None) };
103
    static HEURISTIC: Cell<Heuristic> = const { Cell::new(Heuristic::Compact) };
104
    static CHANNELLING: Cell<Channelling> = const { Cell::new(Channelling::No) };
105
    static HEURISTIC_RANDOM_STATE: Cell<u64> = const { Cell::new(DEFAULT_HEURISTIC_SEED) };
106
    static HEURISTIC_ALL_CHOICES: RefCell<AllChoicesState> =
107
        const { RefCell::new(AllChoicesState::new()) };
108
    /// 1-based answers for the interactive heuristic, matching Conjure's `--responses`.
109
    static HEURISTIC_RESPONSES: RefCell<VecDeque<usize>> = const { RefCell::new(VecDeque::new()) };
110
}
111

            
112
#[derive(Clone, Debug, PartialEq, Eq)]
113
pub struct HeuristicChoice {
114
    pub selected: usize,
115
    pub options: Vec<String>,
116
}
117

            
118
#[derive(Clone, Debug, PartialEq, Eq)]
119
struct AllChoicesState {
120
    requested: Vec<usize>,
121
    decisions: Vec<HeuristicChoice>,
122
}
123

            
124
impl AllChoicesState {
125
    const fn new() -> Self {
126
        Self {
127
            requested: Vec::new(),
128
            decisions: Vec::new(),
129
        }
130
    }
131
}
132

            
133
2605508
pub fn set_heuristic(heuristic: Heuristic) {
134
2605508
    HEURISTIC.with(|current| current.set(heuristic));
135
2605508
}
136

            
137
7494382
pub fn heuristic() -> Heuristic {
138
7494382
    HEURISTIC.with(Cell::get)
139
7494382
}
140

            
141
1300552
pub fn set_channelling(channelling: Channelling) {
142
1300552
    CHANNELLING.with(|current| current.set(channelling));
143
1300552
    crate::representation::uniform::reset();
144
1300552
}
145

            
146
4296904434
pub fn channelling() -> Channelling {
147
4296904434
    CHANNELLING.with(Cell::get)
148
4296904434
}
149

            
150
1300680
pub fn set_heuristic_seed(seed: u64) {
151
1300680
    HEURISTIC_RANDOM_STATE.with(|state| state.set(seed));
152
1300680
}
153

            
154
/// Sets the 1-based answers consumed by the interactive heuristic (`i`).
155
///
156
/// When provided (e.g. via `--responses`), these are used instead of prompting on stdin.
157
/// Values must be in `1..=n` for a decision with `n` options, matching Conjure.
158
2522
pub fn set_heuristic_responses(responses: Vec<usize>) {
159
2522
    HEURISTIC_RESPONSES.with(|state| {
160
2522
        *state.borrow_mut() = VecDeque::from(responses);
161
2522
    });
162
2522
}
163

            
164
/// Clears any remaining interactive responses.
165
2
pub fn clear_heuristic_responses() {
166
2
    HEURISTIC_RESPONSES.with(|state| state.borrow_mut().clear());
167
2
}
168

            
169
/// Returns a deterministic pseudo-random index and advances the per-thread heuristic RNG.
170
652
pub fn next_heuristic_random_index(upper_bound: usize) -> usize {
171
    bug_assert!(
172
652
        upper_bound > 0,
173
        "random choice requires at least one candidate"
174
    );
175
652
    HEURISTIC_RANDOM_STATE.with(|state| {
176
        // SplitMix64: small, reproducible, and sufficient for choice ordering.
177
652
        let next = state.get().wrapping_add(0x9e37_79b9_7f4a_7c15);
178
652
        state.set(next);
179
652
        let mut mixed = next;
180
652
        mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
181
652
        mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
182
652
        mixed ^= mixed >> 31;
183
652
        (mixed as usize) % upper_bound
184
652
    })
185
652
}
186

            
187
/// Starts one replay of the `x` heuristic using the requested branch indices.
188
1293922
pub fn begin_heuristic_all_choices(requested: Vec<usize>) {
189
1293922
    HEURISTIC_ALL_CHOICES.with(|state| {
190
1293922
        *state.borrow_mut() = AllChoicesState {
191
1293922
            requested,
192
1293922
            decisions: Vec::new(),
193
1293922
        };
194
1293922
    });
195
1293922
}
196

            
197
/// Restores the previous heuristic when a scoped override ends.
198
struct HeuristicGuard(Heuristic);
199

            
200
impl Drop for HeuristicGuard {
201
6714
    fn drop(&mut self) {
202
6714
        set_heuristic(self.0);
203
6714
    }
204
}
205

            
206
/// Runs `f` with the compact heuristic in force, whatever the configured one is.
207
///
208
/// Rewriting a temporary model -- a comprehension generator submodel, say -- picks representations
209
/// too, but those are not modelling choices about the user's problem: a representation is
210
/// semantics-preserving, so whichever one a submodel gets, it enumerates the same values. Compact
211
/// takes the smallest and moves on, leaving the configured heuristic's state for the decisions that
212
/// do matter: `x` keeps enumerating combinations of the real model only, the random stream is not
213
/// advanced, and the interactive heuristic does not ask the user about throwaway variables.
214
///
215
/// A representation named on the domain itself (`set (representation packed)`) still wins -- representation
216
/// selection honours that before it consults the heuristic at all.
217
1956
pub fn with_compact_heuristic<T>(f: impl FnOnce() -> T) -> T {
218
1956
    let previous = heuristic();
219
1956
    set_heuristic(Heuristic::Compact);
220
1956
    let _guard = HeuristicGuard(previous);
221
1956
    f()
222
1956
}
223

            
224
/// Selects the requested branch at the next `x` decision and records all available options.
225
4277760
pub fn next_heuristic_all_index(options: &[&str]) -> usize {
226
    bug_assert!(
227
4277760
        !options.is_empty(),
228
        "all-choice requires at least one candidate"
229
    );
230
4277760
    HEURISTIC_ALL_CHOICES.with(|state| {
231
4277760
        let mut state = state.borrow_mut();
232
4277760
        let decision_index = state.decisions.len();
233
4277760
        let selected = state.requested.get(decision_index).copied().unwrap_or(0);
234
4277760
        assert!(
235
4277760
            selected < options.len(),
236
            "requested heuristic branch {selected} but only {} options exist",
237
            options.len()
238
        );
239
4277760
        state.decisions.push(HeuristicChoice {
240
4277760
            selected,
241
23409108
            options: options.iter().map(|option| (*option).to_string()).collect(),
242
        });
243
4277760
        selected
244
4277760
    })
245
4277760
}
246

            
247
2582924
pub fn heuristic_all_choices() -> Vec<HeuristicChoice> {
248
2582924
    HEURISTIC_ALL_CHOICES.with(|state| state.borrow().decisions.clone())
249
2582924
}
250

            
251
/// Selects an option for the interactive heuristic (`i`).
252
///
253
/// Options are printed 1-based. Prefers the next value from [`set_heuristic_responses`]; otherwise
254
/// prompts on stdin (empty input picks option 1), matching Conjure.
255
347
pub fn next_heuristic_interactive_index(options: &[&str]) -> usize {
256
    bug_assert!(
257
347
        !options.is_empty(),
258
        "interactive choice requires at least one candidate"
259
    );
260

            
261
347
    for (index, option) in options.iter().enumerate() {
262
1005
        eprintln!("{}. {}", index + 1, option);
263
    }
264

            
265
347
    let recorded = HEURISTIC_RESPONSES.with(|state| state.borrow_mut().pop_front());
266
347
    let one_based = match recorded {
267
        Some(recorded) => {
268
347
            eprintln!("Response: {recorded}");
269
347
            assert!(
270
347
                recorded >= 1 && recorded <= options.len(),
271
                "recorded response {recorded} out of range; expected a value between 1 and {}",
272
                options.len()
273
            );
274
347
            recorded
275
        }
276
        None => prompt_heuristic_interactive_choice(options.len()),
277
    };
278
347
    one_based - 1
279
347
}
280

            
281
fn prompt_heuristic_interactive_choice(option_count: usize) -> usize {
282
    let stdin = io::stdin();
283
    let mut stdout = io::stderr();
284
    loop {
285
        eprint!("Pick option: ");
286
        let _ = stdout.flush();
287
        let mut line = String::new();
288
        if stdin.lock().read_line(&mut line).is_err() {
289
            eprintln!("Failed to read interactive heuristic response; defaulting to 1");
290
            return 1;
291
        }
292
        let trimmed = line.trim();
293
        if trimmed.is_empty() {
294
            return 1;
295
        }
296
        match trimmed.parse::<usize>() {
297
            Ok(value) if value >= 1 && value <= option_count => return value,
298
            Ok(_) => {
299
                eprintln!("Enter a value between 1 and {option_count}");
300
            }
301
            Err(_) => {
302
                eprintln!("Enter an integer value.");
303
            }
304
        }
305
    }
306
}
307

            
308
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
309
pub enum Parser {
310
    #[default]
311
    TreeSitter,
312
    ViaConjure,
313
}
314

            
315
impl Display for Parser {
316
2702690
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317
2702690
        match self {
318
2696583
            Parser::TreeSitter => write!(f, "tree-sitter"),
319
6107
            Parser::ViaConjure => write!(f, "via-conjure"),
320
        }
321
2702690
    }
322
}
323

            
324
impl FromStr for Parser {
325
    type Err = String;
326

            
327
29460
    fn from_str(s: &str) -> Result<Self, Self::Err> {
328
29460
        match s.trim().to_ascii_lowercase().as_str() {
329
23981
            "tree-sitter" => Ok(Parser::TreeSitter),
330
5479
            "via-conjure" => Ok(Parser::ViaConjure),
331
            other => Err(format!(
332
                "unknown parser: {other}; expected one of: tree-sitter, via-conjure"
333
            )),
334
        }
335
29460
    }
336
}
337

            
338
thread_local! {
339
    /// Thread-local setting for which parser is currently active.
340
    ///
341
    /// Must be explicitly set before use.
342
    static CURRENT_PARSER: Cell<Option<Parser>> = const { Cell::new(None) };
343
}
344

            
345
1300552
pub fn set_current_parser(parser: Parser) {
346
1300552
    CURRENT_PARSER.with(|current| current.set(Some(parser)));
347
1300552
}
348

            
349
186
pub fn current_parser() -> Parser {
350
186
    CURRENT_PARSER.with(|current| {
351
186
        current.get().unwrap_or_else(|| {
352
            // loud failure on purpose, so we don't end up using the default
353
            bug!("current parser not set for this thread; call set_current_parser first")
354
        })
355
186
    })
356
186
}
357

            
358
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
359
pub struct RewriteConfig {
360
    /// Skip rules whose declared expression discriminants cannot match.
361
    pub prefilter: bool,
362
    /// Drive rewriting from persistent dirty node queues instead of repeated full scans.
363
    pub worklist: bool,
364
}
365

            
366
impl RewriteConfig {
367
133
    pub const fn baseline() -> Self {
368
133
        Self {
369
133
            prefilter: false,
370
133
            worklist: false,
371
133
        }
372
133
    }
373

            
374
23250
    pub const fn optimised() -> Self {
375
23250
        Self {
376
23250
            prefilter: true,
377
23250
            worklist: true,
378
23250
        }
379
23250
    }
380

            
381
1447049
    pub const fn is_baseline(self) -> bool {
382
1447049
        !self.prefilter && !self.worklist
383
1447049
    }
384

            
385
2645921
    pub const fn is_optimised(self) -> bool {
386
2645921
        self.prefilter && self.worklist
387
2645921
    }
388
}
389

            
390
impl Default for RewriteConfig {
391
    fn default() -> Self {
392
        Self::optimised()
393
    }
394
}
395

            
396
impl Display for RewriteConfig {
397
2645921
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398
2645921
        if self.is_optimised() {
399
2645918
            write!(f, "optimised")
400
3
        } else if self.is_baseline() {
401
1
            write!(f, "baseline")
402
        } else {
403
2
            let mut options = vec!["baseline"];
404
2
            if self.prefilter {
405
1
                options.push("prefilter");
406
1
            }
407
2
            if self.worklist {
408
1
                options.push("worklist");
409
1
            }
410
2
            write!(f, "{}", options.join("+"))
411
        }
412
2645921
    }
413
}
414

            
415
impl FromStr for RewriteConfig {
416
    type Err = String;
417

            
418
21265
    fn from_str(s: &str) -> Result<Self, Self::Err> {
419
21265
        let trimmed = s.trim().to_ascii_lowercase();
420
21265
        match trimmed.as_str() {
421
19
            "baseline" => return Ok(Self::baseline()),
422
21228
            "optimised" => return Ok(Self::optimised()),
423
18
            _ => {}
424
        }
425

            
426
18
        if !trimmed.starts_with("baseline+") {
427
2
            return Err(format!(
428
2
                "unknown rewrite config: {trimmed}; expected baseline, optimised, or baseline plus '+' separated prefilter/worklist options"
429
2
            ));
430
16
        }
431

            
432
16
        let mut config = Self::baseline();
433
16
        let mut baseline_seen = false;
434
16
        let mut prefilter_seen = false;
435
16
        let mut worklist_seen = false;
436
16
        let mut option_seen = false;
437

            
438
16
        for token in trimmed.split('+') {
439
35
            match token {
440
                "" => {}
441
                "baseline" => {
442
16
                    if baseline_seen {
443
                        return Err("duplicate rewrite option 'baseline'".to_string());
444
16
                    }
445
16
                    baseline_seen = true;
446
                }
447
                "prefilter" => {
448
5
                    if prefilter_seen {
449
                        return Err("duplicate rewrite option 'prefilter'".to_string());
450
5
                    }
451
5
                    config.prefilter = true;
452
5
                    prefilter_seen = true;
453
5
                    option_seen = true;
454
                }
455
                "worklist" => {
456
4
                    if worklist_seen {
457
                        return Err("duplicate rewrite option 'worklist'".to_string());
458
4
                    }
459
4
                    config.worklist = true;
460
4
                    worklist_seen = true;
461
4
                    option_seen = true;
462
                }
463
                other => {
464
10
                    return Err(format!(
465
10
                        "unknown rewrite option '{other}'; expected baseline, optimised, or a '+' separated combination of: prefilter, worklist"
466
10
                    ));
467
                }
468
            }
469
        }
470

            
471
6
        if !option_seen {
472
            return Err(
473
                "rewrite config 'baseline+' must include at least one of: prefilter, worklist"
474
                    .to_string(),
475
            );
476
6
        }
477

            
478
6
        Ok(config)
479
21265
    }
480
}
481

            
482
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
483
pub enum Rewriter {
484
    Rewrite(RewriteConfig),
485
}
486

            
487
impl Default for Rewriter {
488
1940
    fn default() -> Self {
489
1940
        Self::Rewrite(RewriteConfig::optimised())
490
1940
    }
491
}
492

            
493
thread_local! {
494
    /// Thread-local setting for which rewriter is currently active.
495
    ///
496
    /// Must be explicitly set before use.
497
    static CURRENT_REWRITER: Cell<Option<Rewriter>> = const { Cell::new(None) };
498
}
499

            
500
impl Display for Rewriter {
501
2645898
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502
2645898
        match self {
503
2645898
            Rewriter::Rewrite(config) => write!(f, "{config}"),
504
2645898
        }
505
2645898
    }
506
}
507

            
508
impl FromStr for Rewriter {
509
    type Err = String;
510

            
511
21250
    fn from_str(s: &str) -> Result<Self, Self::Err> {
512
21250
        let trimmed = s.trim().to_ascii_lowercase();
513
21250
        match trimmed.as_str() {
514
21245
            "baseline" | "optimised" => Ok(Rewriter::Rewrite(trimmed.parse()?)),
515
            other => {
516
5
                if other.contains('+') {
517
4
                    return Ok(Rewriter::Rewrite(other.parse()?));
518
1
                }
519

            
520
1
                Err(format!(
521
1
                    "unknown rewriter: {other}; expected baseline, optimised, or baseline plus '+' separated prefilter/worklist options"
522
1
                ))
523
            }
524
        }
525
21250
    }
526
}
527

            
528
2747568
pub fn set_current_rewriter(rewriter: Rewriter) {
529
2747568
    CURRENT_REWRITER.with(|current| current.set(Some(rewriter)));
530
2747568
}
531

            
532
147827
pub fn current_rewriter() -> Rewriter {
533
147827
    CURRENT_REWRITER.with(|current| {
534
147827
        current.get().unwrap_or_else(|| {
535
            // loud failure on purpose, so we don't end up using the default
536
            bug!("current rewriter not set for this thread; call set_current_rewriter first")
537
        })
538
147827
    })
539
147827
}
540

            
541
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
542
pub enum QuantifiedExpander {
543
    Auto,
544
    Native,
545
    ViaSolver,
546
    ViaSolverAc,
547
}
548

            
549
impl Display for QuantifiedExpander {
550
2694538
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
551
2694538
        match self {
552
2694538
            QuantifiedExpander::Auto => write!(f, "auto"),
553
            QuantifiedExpander::Native => write!(f, "native"),
554
            QuantifiedExpander::ViaSolver => write!(f, "via-solver"),
555
            QuantifiedExpander::ViaSolverAc => write!(f, "via-solver-ac"),
556
        }
557
2694538
    }
558
}
559

            
560
impl FromStr for QuantifiedExpander {
561
    type Err = String;
562

            
563
21246
    fn from_str(s: &str) -> Result<Self, Self::Err> {
564
21246
        match s.trim().to_ascii_lowercase().as_str() {
565
21228
            "auto" => Ok(QuantifiedExpander::Auto),
566
            "native" => Ok(QuantifiedExpander::Native),
567
            "via-solver" => Ok(QuantifiedExpander::ViaSolver),
568
18
            "via-solver-ac" => Ok(QuantifiedExpander::ViaSolverAc),
569
            _ => Err(format!(
570
                "unknown comprehension expander: {s}; expected one of: \
571
                 auto, native, via-solver, via-solver-ac"
572
            )),
573
        }
574
21246
    }
575
}
576

            
577
thread_local! {
578
    /// Thread-local setting for which comprehension expansion strategy is currently active.
579
    ///
580
    /// Must be explicitly set before use.
581
    static COMPREHENSION_EXPANDER: Cell<Option<QuantifiedExpander>> = const { Cell::new(None) };
582
}
583

            
584
1300583
pub fn set_comprehension_expander(expander: QuantifiedExpander) {
585
1300583
    COMPREHENSION_EXPANDER.with(|current| current.set(Some(expander)));
586
1300583
}
587

            
588
992838
pub fn comprehension_expander() -> QuantifiedExpander {
589
992838
    COMPREHENSION_EXPANDER.with(|current| {
590
992838
        current.get().unwrap_or_else(|| {
591
            // loud failure on purpose, so we don't end up using the default
592
            bug!(
593
                "comprehension expander not set for this thread; call set_comprehension_expander first"
594
            )
595
        })
596
992838
    })
597
992838
}
598

            
599
#[derive(
600
    Debug,
601
    EnumIter,
602
    StrumDisplay,
603
    PartialEq,
604
    Eq,
605
    Hash,
606
    Clone,
607
    Copy,
608
    Serialize,
609
    Deserialize,
610
    JsonSchema,
611
)]
612
pub enum SolverFamily {
613
    Minion,
614
    Sat,
615
    Z3,
616
}
617

            
618
thread_local! {
619
    /// Thread-local setting for which solver family is currently active.
620
    ///
621
    /// Must be explicitly set before use.
622
    static CURRENT_SOLVER_FAMILY: Cell<Option<SolverFamily>> = const { Cell::new(None) };
623
}
624

            
625
pub const DEFAULT_MINION_DISCRETE_THRESHOLD: usize = 10;
626

            
627
thread_local! {
628
    /// Thread-local setting controlling when Minion int domains are emitted as `DISCRETE`.
629
    ///
630
    /// If an int domain size is <= this threshold, the Minion adaptor uses `DISCRETE`; otherwise
631
    /// it uses `BOUND`, unless another constraint requires `DISCRETE`.
632
    static MINION_DISCRETE_THRESHOLD: Cell<Option<usize>> = const { Cell::new(None) };
633

            
634
    /// Thread-local setting controlling whether rule-trace outputs are active in this phase.
635
    ///
636
    /// This is intentionally off by default and can be disabled before solver-time rewrites so
637
    /// follow-up dominance-blocking rewrites do not pollute the initial rewrite trace.
638
    static RULE_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
639

            
640
    /// Thread-local setting controlling whether default rule traces are configured.
641
    static DEFAULT_RULE_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
642

            
643
    /// Thread-local setting controlling whether verbose rule-attempt traces are configured.
644
    static RULE_ATTEMPT_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
645

            
646
    /// Thread-local setting controlling whether aggregate rule-application traces are configured.
647
    static RULE_TRACE_AGGREGATES_ENABLED: Cell<bool> = const { Cell::new(false) };
648
}
649

            
650
1300553
pub fn set_current_solver_family(solver_family: SolverFamily) {
651
1300553
    CURRENT_SOLVER_FAMILY.with(|current| current.set(Some(solver_family)));
652
1300553
}
653

            
654
/// Restores the previous solver family when a scoped override ends.
655
struct SolverFamilyGuard(Option<SolverFamily>);
656

            
657
impl Drop for SolverFamilyGuard {
658
6715
    fn drop(&mut self) {
659
6715
        CURRENT_SOLVER_FAMILY.with(|current| current.set(self.0));
660
6715
    }
661
}
662

            
663
/// Runs `f` as a rewrite for `solver_family`, then restores the surrounding solver context.
664
///
665
/// Some rewrites build and solve a temporary model with a different backend from the outer model.
666
/// Representation applicability must follow the backend that will actually consume that temporary
667
/// model, not the user's outer solver setting.
668
1957
pub fn with_solver_family<T>(solver_family: SolverFamily, f: impl FnOnce() -> T) -> T {
669
1957
    let previous = CURRENT_SOLVER_FAMILY.with(|current| current.replace(Some(solver_family)));
670
1957
    let _guard = SolverFamilyGuard(previous);
671
1957
    f()
672
1957
}
673

            
674
/// The active solver family, or `None` if this thread has not set one.
675
///
676
/// Unlike [`current_solver_family`] this does not panic. Solver-family gating asks with this so
677
/// that unit tests exercising a single component do not have to stand up a solver context.
678
348766624
pub fn try_current_solver_family() -> Option<SolverFamily> {
679
348766624
    CURRENT_SOLVER_FAMILY.with(|current| current.get())
680
348766624
}
681

            
682
62
pub fn current_solver_family() -> SolverFamily {
683
62
    CURRENT_SOLVER_FAMILY.with(|current| {
684
62
        current.get().unwrap_or_else(|| {
685
            // loud failure on purpose, so we don't end up using the default
686
            bug!(
687
                "current solver family not set for this thread; call set_current_solver_family first"
688
            )
689
        })
690
62
    })
691
62
}
692

            
693
/// Whether integers carry a representation choice for the solver being targeted.
694
///
695
/// SAT has no integers at all: an int variable is encoded as a vector of Booleans, and which
696
/// encoding it gets is a representation choice like any other. The SMT backend does have integers,
697
/// but has two ways to express them -- linear arithmetic and bit-vectors -- so the choice is a
698
/// representation there too. Minion has one native integer and needs none of this. With no solver
699
/// family set -- a unit test exercising one component, say -- integers stay concrete.
700
63386883
pub fn ints_need_representation() -> bool {
701
63386883
    matches!(
702
63386883
        try_current_solver_family(),
703
        Some(SolverFamily::Sat | SolverFamily::Z3)
704
    )
705
63386883
}
706

            
707
/// Pins Minion's domain threshold, or leaves it to the modelling heuristic.
708
1300490
pub fn set_minion_discrete_threshold(threshold: Option<usize>) {
709
1300490
    MINION_DISCRETE_THRESHOLD.with(|current| current.set(threshold));
710
1300490
}
711

            
712
/// Selects one threshold for a Minion model: the default, all bound, or all discrete.
713
/// Constraints requiring discrete variables still override the threshold.
714
31133
pub fn select_minion_discrete_threshold() -> usize {
715
31133
    if let Some(threshold) = MINION_DISCRETE_THRESHOLD.with(Cell::get) {
716
30721
        return threshold;
717
412
    }
718
412
    let thresholds = [DEFAULT_MINION_DISCRETE_THRESHOLD, 0, usize::MAX];
719
412
    let labels = [
720
412
        "minion-discrete-threshold=10",
721
412
        "minion-discrete-threshold=0",
722
412
        "minion-discrete-threshold=unlimited",
723
412
    ];
724
412
    let index = match heuristic() {
725
319
        Heuristic::First | Heuristic::Compact => 0,
726
62
        Heuristic::Random => next_heuristic_random_index(thresholds.len()),
727
31
        Heuristic::Interactive => next_heuristic_interactive_index(&labels),
728
        Heuristic::All => next_heuristic_all_index(&labels),
729
    };
730
412
    thresholds[index]
731
31133
}
732

            
733
3898110
pub fn set_rule_trace_enabled(enabled: bool) {
734
3898110
    RULE_TRACE_ENABLED.with(|current| current.set(enabled));
735
3898110
}
736

            
737
161493975
pub fn rule_trace_enabled() -> bool {
738
161493975
    RULE_TRACE_ENABLED.with(|current| current.get())
739
161493975
}
740

            
741
1300494
pub fn set_default_rule_trace_enabled(enabled: bool) {
742
1300494
    DEFAULT_RULE_TRACE_ENABLED.with(|current| current.set(enabled));
743
1300494
}
744

            
745
77319439
pub fn default_rule_trace_enabled() -> bool {
746
77319439
    DEFAULT_RULE_TRACE_ENABLED.with(|current| current.get())
747
77319439
}
748

            
749
1300490
pub fn set_rule_attempt_trace_enabled(enabled: bool) {
750
1300490
    RULE_ATTEMPT_TRACE_ENABLED.with(|current| current.set(enabled));
751
1300490
}
752

            
753
2586048
pub fn rule_attempt_trace_enabled() -> bool {
754
2586048
    RULE_ATTEMPT_TRACE_ENABLED.with(|current| current.get())
755
2586048
}
756

            
757
1300490
pub fn set_rule_trace_aggregates_enabled(enabled: bool) {
758
1300490
    RULE_TRACE_AGGREGATES_ENABLED.with(|current| current.set(enabled));
759
1300490
}
760

            
761
59776776
pub fn rule_trace_aggregates_enabled() -> bool {
762
59776776
    RULE_TRACE_AGGREGATES_ENABLED.with(|current| current.get())
763
59776776
}
764

            
765
pub fn configured_rule_trace_enabled() -> bool {
766
    default_rule_trace_enabled() || rule_attempt_trace_enabled() || rule_trace_aggregates_enabled()
767
}
768

            
769
impl FromStr for SolverFamily {
770
    type Err = String;
771

            
772
69202
    fn from_str(s: &str) -> Result<Self, Self::Err> {
773
69202
        match s.trim().to_ascii_lowercase().as_str() {
774
20513
            "minion" => Ok(SolverFamily::Minion),
775
36458
            "sat" => Ok(SolverFamily::Sat),
776
12231
            "z3" => Ok(SolverFamily::Z3),
777
            other => Err(format!(
778
                "unknown solver '{other}', expected one of: minion, sat, z3"
779
            )),
780
        }
781
69202
    }
782
}
783

            
784
impl SolverFamily {
785
9410949
    pub fn as_str(&self) -> String {
786
9410949
        match self {
787
331638
            SolverFamily::Minion => "minion".to_owned(),
788
8767761
            SolverFamily::Sat => "sat".to_owned(),
789
311550
            SolverFamily::Z3 => "z3".to_owned(),
790
        }
791
9410949
    }
792
}
793

            
794
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
795
pub struct SolverArgs {
796
    pub timeout_ms: Option<u64>,
797
}
798

            
799
#[derive(Clone, Debug, PartialEq, Eq)]
800
struct SavedSettings {
801
    parser: Option<Parser>,
802
    rewriter: Option<Rewriter>,
803
    expander: Option<QuantifiedExpander>,
804
    solver_family: Option<SolverFamily>,
805
    heuristic: Heuristic,
806
    channelling: Channelling,
807
    random_state: u64,
808
    all_choices: AllChoicesState,
809
    responses: VecDeque<usize>,
810
    minion_discrete_threshold: Option<usize>,
811
    element_encoding: Option<crate::ast::sat_decision::ElementEncoding>,
812
    table_encoding: Option<crate::ast::sat_decision::TableEncoding>,
813
    alldifferent_encoding: Option<crate::ast::sat_decision::AllDifferentEncoding>,
814
    pb_encoding: Option<crate::ast::sat_decision::PbEncoding>,
815
    cardinality_encoding: Option<crate::ast::sat_decision::CardinalityEncoding>,
816
    amo_encoding: Option<crate::ast::sat_decision::AmoEncoding>,
817
    rule_trace: bool,
818
    default_rule_trace: bool,
819
    rule_attempt_trace: bool,
820
    rule_trace_aggregates: bool,
821
}
822

            
823
impl SavedSettings {
824
2652
    fn capture() -> Self {
825
        Self {
826
2652
            parser: CURRENT_PARSER.with(Cell::get),
827
2652
            rewriter: CURRENT_REWRITER.with(Cell::get),
828
2652
            expander: COMPREHENSION_EXPANDER.with(Cell::get),
829
2652
            solver_family: CURRENT_SOLVER_FAMILY.with(Cell::get),
830
2652
            heuristic: HEURISTIC.with(Cell::get),
831
2652
            channelling: CHANNELLING.with(Cell::get),
832
2652
            random_state: HEURISTIC_RANDOM_STATE.with(Cell::get),
833
2652
            all_choices: HEURISTIC_ALL_CHOICES.with(|state| state.borrow().clone()),
834
2652
            responses: HEURISTIC_RESPONSES.with(|state| state.borrow().clone()),
835
2652
            minion_discrete_threshold: MINION_DISCRETE_THRESHOLD.with(Cell::get),
836
2652
            element_encoding: ELEMENT_ENCODING.with(Cell::get),
837
2652
            table_encoding: TABLE_ENCODING.with(Cell::get),
838
2652
            alldifferent_encoding: ALLDIFFERENT_ENCODING.with(Cell::get),
839
2652
            pb_encoding: PB_ENCODING.with(Cell::get),
840
2652
            cardinality_encoding: CARDINALITY_ENCODING.with(Cell::get),
841
2652
            amo_encoding: AMO_ENCODING.with(Cell::get),
842
2652
            rule_trace: RULE_TRACE_ENABLED.with(Cell::get),
843
2652
            default_rule_trace: DEFAULT_RULE_TRACE_ENABLED.with(Cell::get),
844
2652
            rule_attempt_trace: RULE_ATTEMPT_TRACE_ENABLED.with(Cell::get),
845
2652
            rule_trace_aggregates: RULE_TRACE_AGGREGATES_ENABLED.with(Cell::get),
846
        }
847
2652
    }
848

            
849
2628
    fn restore(self) {
850
2628
        CURRENT_PARSER.with(|current| current.set(self.parser));
851
2628
        CURRENT_REWRITER.with(|current| current.set(self.rewriter));
852
2628
        COMPREHENSION_EXPANDER.with(|current| current.set(self.expander));
853
2628
        CURRENT_SOLVER_FAMILY.with(|current| current.set(self.solver_family));
854
2628
        HEURISTIC.with(|current| current.set(self.heuristic));
855
2628
        CHANNELLING.with(|current| current.set(self.channelling));
856
2628
        HEURISTIC_RANDOM_STATE.with(|current| current.set(self.random_state));
857
2628
        HEURISTIC_ALL_CHOICES.with(|current| *current.borrow_mut() = self.all_choices);
858
2628
        HEURISTIC_RESPONSES.with(|current| *current.borrow_mut() = self.responses);
859
2628
        MINION_DISCRETE_THRESHOLD.with(|current| current.set(self.minion_discrete_threshold));
860
2628
        ELEMENT_ENCODING.with(|current| current.set(self.element_encoding));
861
2628
        TABLE_ENCODING.with(|current| current.set(self.table_encoding));
862
2628
        ALLDIFFERENT_ENCODING.with(|current| current.set(self.alldifferent_encoding));
863
2628
        PB_ENCODING.with(|current| current.set(self.pb_encoding));
864
2628
        CARDINALITY_ENCODING.with(|current| current.set(self.cardinality_encoding));
865
2628
        AMO_ENCODING.with(|current| current.set(self.amo_encoding));
866
2628
        RULE_TRACE_ENABLED.with(|current| current.set(self.rule_trace));
867
2628
        DEFAULT_RULE_TRACE_ENABLED.with(|current| current.set(self.default_rule_trace));
868
2628
        RULE_ATTEMPT_TRACE_ENABLED.with(|current| current.set(self.rule_attempt_trace));
869
2628
        RULE_TRACE_AGGREGATES_ENABLED.with(|current| current.set(self.rule_trace_aggregates));
870
2628
    }
871
}
872

            
873
struct SettingsGuard(Option<SavedSettings>);
874

            
875
impl Drop for SettingsGuard {
876
2628
    fn drop(&mut self) {
877
2628
        if let Some(settings) = self.0.take() {
878
2628
            settings.restore();
879
        }
880
2628
    }
881
}
882

            
883
/// Runs `f`, restoring the calling thread's settings afterwards, including on panic.
884
///
885
/// Changes inside the closure stay local to the scope. Random state, pending heuristic answers,
886
/// recorded choices and uniform representations are restored along with configuration values.
887
942
pub fn with_saved_settings<T>(f: impl FnOnce() -> T) -> T {
888
942
    let _uniform = crate::representation::uniform::Scope::save();
889
942
    let _settings = SettingsGuard(Some(SavedSettings::capture()));
890
942
    f()
891
942
}
892

            
893
#[cfg(test)]
894
mod tests {
895
    use super::{
896
        Channelling, Heuristic, QuantifiedExpander, RewriteConfig, Rewriter, SolverFamily,
897
        begin_heuristic_all_choices, clear_heuristic_responses, heuristic_all_choices,
898
        next_heuristic_all_index, next_heuristic_interactive_index, next_heuristic_random_index,
899
        set_current_solver_family, set_heuristic_responses, set_heuristic_seed,
900
        try_current_solver_family, with_solver_family,
901
    };
902
    use std::str::FromStr;
903

            
904
    #[test]
905
1
    fn compact_is_the_default_heuristic() {
906
1
        assert_eq!(Heuristic::default(), Heuristic::Compact);
907
1
    }
908

            
909
    #[test]
910
1
    fn scoped_solver_family_restores_the_outer_solver() {
911
1
        set_current_solver_family(SolverFamily::Z3);
912

            
913
1
        with_solver_family(SolverFamily::Minion, || {
914
1
            assert_eq!(try_current_solver_family(), Some(SolverFamily::Minion));
915
1
        });
916

            
917
1
        assert_eq!(try_current_solver_family(), Some(SolverFamily::Z3));
918
1
    }
919

            
920
    #[test]
921
1
    fn parses_answer_heuristics_and_channelling() {
922
1
        assert_eq!(Heuristic::from_str("f"), Ok(Heuristic::First));
923
1
        assert_eq!(Heuristic::from_str("random"), Ok(Heuristic::Random));
924
1
        assert_eq!(Heuristic::from_str("c"), Ok(Heuristic::Compact));
925
1
        assert_eq!(Heuristic::from_str("i"), Ok(Heuristic::Interactive));
926
1
        assert_eq!(
927
1
            Heuristic::from_str("interactive"),
928
1
            Ok(Heuristic::Interactive)
929
        );
930
1
        assert_eq!(Heuristic::from_str("x"), Ok(Heuristic::All));
931
1
        assert_eq!(Channelling::from_str("no"), Ok(Channelling::No));
932
1
        assert_eq!(Channelling::from_str("yes"), Ok(Channelling::Yes));
933
1
        assert_eq!(Channelling::from_str("uniform"), Ok(Channelling::Uniform));
934
1
        assert_eq!(Channelling::Uniform.to_string(), "uniform");
935
1
    }
936

            
937
    #[test]
938
1
    fn parses_auto_comprehension_expander() {
939
1
        assert_eq!(
940
1
            QuantifiedExpander::from_str("auto"),
941
1
            Ok(QuantifiedExpander::Auto)
942
        );
943
1
        assert_eq!(QuantifiedExpander::Auto.to_string(), "auto");
944
1
    }
945

            
946
    #[test]
947
1
    fn interactive_heuristic_consumes_one_based_responses() {
948
1
        set_heuristic_responses(vec![2, 1]);
949
1
        assert_eq!(next_heuristic_interactive_index(&["left", "right"]), 1);
950
1
        assert_eq!(next_heuristic_interactive_index(&["a", "b", "c"]), 0);
951
1
        clear_heuristic_responses();
952
1
    }
953

            
954
    #[test]
955
1
    fn random_heuristic_is_reproducible_from_seed() {
956
1
        set_heuristic_seed(42);
957
8
        let first: Vec<_> = (0..8).map(|_| next_heuristic_random_index(7)).collect();
958
1
        set_heuristic_seed(42);
959
8
        let second: Vec<_> = (0..8).map(|_| next_heuristic_random_index(7)).collect();
960
1
        assert_eq!(first, second);
961
1
    }
962

            
963
    #[test]
964
1
    fn all_heuristic_replays_and_records_choices() {
965
1
        begin_heuristic_all_choices(vec![1]);
966
1
        assert_eq!(next_heuristic_all_index(&["left", "right"]), 1);
967
1
        assert_eq!(
968
1
            heuristic_all_choices()[0].options,
969
1
            vec!["left".to_string(), "right".to_string()]
970
        );
971
1
    }
972

            
973
    #[test]
974
1
    fn parses_rewrite_option_combinations() {
975
1
        assert_eq!(
976
1
            RewriteConfig::from_str("baseline").unwrap(),
977
1
            RewriteConfig {
978
1
                prefilter: false,
979
1
                worklist: false,
980
1
            }
981
        );
982
1
        assert_eq!(
983
1
            RewriteConfig::from_str("baseline+prefilter").unwrap(),
984
1
            RewriteConfig {
985
1
                prefilter: true,
986
1
                worklist: false,
987
1
            }
988
        );
989
1
        assert_eq!(
990
1
            RewriteConfig::from_str("baseline+worklist").unwrap(),
991
1
            RewriteConfig {
992
1
                prefilter: false,
993
1
                worklist: true,
994
1
            }
995
        );
996
1
        assert_eq!(
997
1
            RewriteConfig::from_str("baseline+prefilter+worklist").unwrap(),
998
1
            RewriteConfig::optimised()
999
        );
1
        assert!(RewriteConfig::from_str("+dirty").is_err());
1
        assert!(RewriteConfig::from_str("baseline+dirty").is_err());
1
        assert!(RewriteConfig::from_str("baseline+cache").is_err());
1
        assert!(RewriteConfig::from_str("baseline+rulememo").is_err());
1
        assert!(RewriteConfig::from_str("baseline+candidateindex").is_err());
1
        assert!(RewriteConfig::from_str("baseline+dirtyqueues").is_err());
1
        assert!(RewriteConfig::from_str("baseline+rule-memo").is_err());
1
        assert!(RewriteConfig::from_str("baseline+candidate-index").is_err());
1
        assert!(RewriteConfig::from_str("baseline+candidate-node-index").is_err());
1
        assert!(RewriteConfig::from_str("baseline+dirty-node-queues").is_err());
1
    }
    #[test]
1
    fn optimised_rewrite_config_enables_fast_default_options() {
1
        assert_eq!(
1
            RewriteConfig::from_str("optimised").unwrap(),
1
            RewriteConfig {
1
                prefilter: true,
1
                worklist: true,
1
            }
        );
1
    }
    #[test]
1
    fn displays_rewrite_option_combinations() {
1
        assert_eq!(RewriteConfig::baseline().to_string(), "baseline");
1
        assert_eq!(
1
            RewriteConfig {
1
                prefilter: true,
1
                worklist: false,
1
            }
1
            .to_string(),
1
            "baseline+prefilter"
        );
1
        assert_eq!(
1
            RewriteConfig {
1
                prefilter: false,
1
                worklist: true,
1
            }
1
            .to_string(),
1
            "baseline+worklist"
        );
1
        assert_eq!(RewriteConfig::optimised().to_string(), "optimised");
1
        assert_eq!(
1
            RewriteConfig::from_str("baseline+prefilter+worklist")
1
                .unwrap()
1
                .to_string(),
1
            "optimised"
        );
1
    }
    #[test]
1
    fn parses_rewriter_option_combinations() {
1
        assert_eq!(
1
            Rewriter::from_str("baseline+prefilter").unwrap(),
1
            Rewriter::Rewrite(RewriteConfig {
1
                prefilter: true,
1
                worklist: false,
1
            })
        );
1
        assert_eq!(
1
            Rewriter::from_str("baseline+prefilter+worklist").unwrap(),
1
            Rewriter::Rewrite(RewriteConfig::optimised())
        );
1
        assert!(Rewriter::from_str("+dirty").is_err());
1
        assert!(Rewriter::from_str("dirty").is_err());
1
        assert!(Rewriter::from_str("baseline+dirty").is_err());
1
    }
}
/// Pin the AMO algorithm, or allow the modelling heuristic to choose.
2489
pub fn set_amo_encoding(encoding: Option<crate::ast::sat_decision::AmoEncoding>) {
2489
    AMO_ENCODING.with(|current| current.set(encoding));
2489
}
/// Explicit AMO algorithm override for this compilation thread.
2318177
pub fn amo_encoding() -> Option<crate::ast::sat_decision::AmoEncoding> {
2318177
    AMO_ENCODING.with(Cell::get)
2318177
}
/// Pin a cardinality provider/algorithm, or let the heuristic select it.
2458
pub fn set_cardinality_encoding(encoding: Option<crate::ast::sat_decision::CardinalityEncoding>) {
2458
    CARDINALITY_ENCODING.with(|current| current.set(encoding));
2458
}
/// Explicit cardinality encoder override for this compilation thread.
231136
pub fn cardinality_encoding() -> Option<crate::ast::sat_decision::CardinalityEncoding> {
231136
    CARDINALITY_ENCODING.with(Cell::get)
231136
}
/// Pin a pseudo-Boolean provider/algorithm, or let the heuristic select it.
2458
pub fn set_pb_encoding(encoding: Option<crate::ast::sat_decision::PbEncoding>) {
2458
    PB_ENCODING.with(|current| current.set(encoding));
2458
}
/// Explicit pseudo-Boolean encoder override for this compilation thread.
1291586
pub fn pb_encoding() -> Option<crate::ast::sat_decision::PbEncoding> {
1291586
    PB_ENCODING.with(Cell::get)
1291586
}
/// Pin the allDifferent strategy, or let the heuristic choose an applicable composition.
2458
pub fn set_alldifferent_encoding(encoding: Option<crate::ast::sat_decision::AllDifferentEncoding>) {
2458
    ALLDIFFERENT_ENCODING.with(|current| current.set(encoding));
2458
}
/// Explicit allDifferent strategy override for this compilation thread.
67766
pub fn alldifferent_encoding() -> Option<crate::ast::sat_decision::AllDifferentEncoding> {
67766
    ALLDIFFERENT_ENCODING.with(Cell::get)
67766
}
/// Pin the table composition, or let the modelling heuristic select it.
2458
pub fn set_table_encoding(encoding: Option<crate::ast::sat_decision::TableEncoding>) {
2458
    TABLE_ENCODING.with(|current| current.set(encoding));
2458
}
/// Explicit table strategy override for this compilation thread.
1533846
pub fn table_encoding() -> Option<crate::ast::sat_decision::TableEncoding> {
1533846
    TABLE_ENCODING.with(Cell::get)
1533846
}
/// Pin the element composition, or let the modelling heuristic select it.
2458
pub fn set_element_encoding(encoding: Option<crate::ast::sat_decision::ElementEncoding>) {
2458
    ELEMENT_ENCODING.with(|current| current.set(encoding));
2458
}
/// Explicit element strategy override for this compilation thread.
153078
pub fn element_encoding() -> Option<crate::ast::sat_decision::ElementEncoding> {
153078
    ELEMENT_ENCODING.with(Cell::get)
153078
}
#[cfg(test)]
mod saved_settings_tests {
    use super::*;
    use crate::ast::sat_decision::{
        AllDifferentEncoding, AmoEncoding, CardinalityEncoding, ElementEncoding, PbEncoding,
        TableEncoding,
    };
3
    fn configure_settings() {
3
        set_current_parser(Parser::ViaConjure);
3
        set_current_rewriter(Rewriter::Rewrite(RewriteConfig::baseline()));
3
        set_comprehension_expander(QuantifiedExpander::ViaSolver);
3
        set_current_solver_family(SolverFamily::Sat);
3
        set_heuristic(Heuristic::Random);
3
        set_channelling(Channelling::Uniform);
3
        set_heuristic_seed(42);
3
        set_heuristic_responses(vec![2, 1]);
3
        begin_heuristic_all_choices(vec![1, 0]);
3
        next_heuristic_all_index(&["left", "right"]);
3
        set_minion_discrete_threshold(Some(123));
3
        set_element_encoding(Some(ElementEncoding::Support));
3
        set_table_encoding(Some(TableEncoding::Mdd));
3
        set_alldifferent_encoding(Some(AllDifferentEncoding::ValueAmo));
3
        set_pb_encoding(Some(PbEncoding::PindakaasBdd));
3
        set_cardinality_encoding(Some(CardinalityEncoding::PindakaasSortingNetwork));
3
        set_amo_encoding(Some(AmoEncoding::Ladder));
3
        set_rule_trace_enabled(true);
3
        set_default_rule_trace_enabled(true);
3
        set_rule_attempt_trace_enabled(true);
3
        set_rule_trace_aggregates_enabled(true);
3
    }
    #[test]
1
    fn saved_settings_restore_nested_configuration() {
1
        with_saved_settings(|| {
1
            configure_settings();
1
            let outer = SavedSettings::capture();
1
            let result = with_saved_settings(|| {
1
                set_current_parser(Parser::TreeSitter);
1
                set_current_rewriter(Rewriter::default());
1
                set_comprehension_expander(QuantifiedExpander::Native);
1
                set_current_solver_family(SolverFamily::Minion);
1
                set_heuristic(Heuristic::Compact);
1
                set_channelling(Channelling::No);
1
                set_heuristic_seed(99);
1
                clear_heuristic_responses();
1
                begin_heuristic_all_choices(vec![]);
1
                set_minion_discrete_threshold(None);
1
                set_element_encoding(None);
1
                set_table_encoding(None);
1
                set_alldifferent_encoding(None);
1
                set_pb_encoding(None);
1
                set_cardinality_encoding(None);
1
                set_amo_encoding(None);
1
                set_rule_trace_enabled(false);
1
                set_default_rule_trace_enabled(false);
1
                set_rule_attempt_trace_enabled(false);
1
                set_rule_trace_aggregates_enabled(false);
1
                let inner = SavedSettings::capture();
1
                with_saved_settings(configure_settings);
1
                assert_eq!(SavedSettings::capture(), inner);
1
                7
1
            });
1
            assert_eq!(result, 7);
1
            assert_eq!(SavedSettings::capture(), outer);
1
        });
1
    }
    #[test]
1
    fn saved_settings_restore_unset_configuration_after_panic() {
1
        std::thread::spawn(|| {
1
            let before = SavedSettings::capture();
1
            assert_eq!(try_current_solver_family(), None);
1
            let result = std::panic::catch_unwind(|| {
1
                with_saved_settings(|| {
1
                    configure_settings();
1
                    panic!("interrupted library run");
                });
            });
1
            assert!(result.is_err());
1
            assert_eq!(SavedSettings::capture(), before);
1
        })
        .join()
        .unwrap();
1
    }
    #[test]
1
    fn saved_settings_preserve_heuristic_progress() {
1
        with_saved_settings(|| {
1
            set_heuristic_seed(42);
3
            let expected: Vec<_> = (0..3).map(|_| next_heuristic_random_index(997)).collect();
1
            set_heuristic_seed(42);
1
            assert_eq!(next_heuristic_random_index(997), expected[0]);
1
            set_heuristic_responses(vec![2, 1]);
1
            assert_eq!(next_heuristic_interactive_index(&["left", "right"]), 1);
1
            begin_heuristic_all_choices(vec![1, 1]);
1
            assert_eq!(next_heuristic_all_index(&["left", "right"]), 1);
1
            with_saved_settings(|| {
1
                for _ in 0..10 {
10
                    next_heuristic_random_index(997);
                }
1
                assert_eq!(next_heuristic_interactive_index(&["a", "b"]), 0);
1
                begin_heuristic_all_choices(vec![]);
1
                assert_eq!(next_heuristic_all_index(&["a", "b"]), 0);
1
            });
1
            assert_eq!(next_heuristic_random_index(997), expected[1]);
1
            assert_eq!(next_heuristic_random_index(997), expected[2]);
1
            assert_eq!(next_heuristic_interactive_index(&["left", "right"]), 0);
1
            assert_eq!(heuristic_all_choices().len(), 1);
1
            assert_eq!(next_heuristic_all_index(&["a", "b"]), 1);
1
            assert_eq!(heuristic_all_choices()[0].options, ["left", "right"]);
1
        });
1
    }
}