Skip to main content

conjure_cp_core/
settings.rs

1use std::{
2    cell::{Cell, RefCell},
3    collections::VecDeque,
4    fmt::Display,
5    io::{self, BufRead, Write},
6    str::FromStr,
7};
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use strum_macros::{Display as StrumDisplay, EnumIter};
12
13use crate::bug;
14use 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)]
18pub 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
30impl Display for Heuristic {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.write_str(match self {
33            Self::First => "f",
34            Self::Random => "r",
35            Self::Compact => "c",
36            Self::Interactive => "i",
37            Self::All => "x",
38        })
39    }
40}
41
42impl FromStr for Heuristic {
43    type Err = String;
44
45    fn from_str(value: &str) -> Result<Self, Self::Err> {
46        match value.trim().to_ascii_lowercase().as_str() {
47            "f" | "first" => Ok(Self::First),
48            "r" | "random" => Ok(Self::Random),
49            "c" | "compact" => Ok(Self::Compact),
50            "i" | "interactive" => Ok(Self::Interactive),
51            "x" | "all" => Ok(Self::All),
52            other => Err(format!(
53                "unknown heuristic '{other}'; expected one of: f, r, c, i, x"
54            )),
55        }
56    }
57}
58
59/// Whether a declaration may have more than one channelled representation.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
61pub enum Channelling {
62    #[default]
63    No,
64    Yes,
65    /// One representation kind per type family throughout a model, without channelling.
66    Uniform,
67}
68
69impl Display for Channelling {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.write_str(match self {
72            Self::No => "no",
73            Self::Yes => "yes",
74            Self::Uniform => "uniform",
75        })
76    }
77}
78
79impl FromStr for Channelling {
80    type Err = String;
81
82    fn from_str(value: &str) -> Result<Self, Self::Err> {
83        match value.trim().to_ascii_lowercase().as_str() {
84            "no" => Ok(Self::No),
85            "yes" => Ok(Self::Yes),
86            "uniform" => Ok(Self::Uniform),
87            other => Err(format!(
88                "unknown channelling setting '{other}'; expected yes, no, or uniform"
89            )),
90        }
91    }
92}
93
94pub const DEFAULT_HEURISTIC_SEED: u64 = 0;
95
96thread_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)]
113pub struct HeuristicChoice {
114    pub selected: usize,
115    pub options: Vec<String>,
116}
117
118#[derive(Clone, Debug, PartialEq, Eq)]
119struct AllChoicesState {
120    requested: Vec<usize>,
121    decisions: Vec<HeuristicChoice>,
122}
123
124impl AllChoicesState {
125    const fn new() -> Self {
126        Self {
127            requested: Vec::new(),
128            decisions: Vec::new(),
129        }
130    }
131}
132
133pub fn set_heuristic(heuristic: Heuristic) {
134    HEURISTIC.with(|current| current.set(heuristic));
135}
136
137pub fn heuristic() -> Heuristic {
138    HEURISTIC.with(Cell::get)
139}
140
141pub fn set_channelling(channelling: Channelling) {
142    CHANNELLING.with(|current| current.set(channelling));
143    crate::representation::uniform::reset();
144}
145
146pub fn channelling() -> Channelling {
147    CHANNELLING.with(Cell::get)
148}
149
150pub fn set_heuristic_seed(seed: u64) {
151    HEURISTIC_RANDOM_STATE.with(|state| state.set(seed));
152}
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.
158pub fn set_heuristic_responses(responses: Vec<usize>) {
159    HEURISTIC_RESPONSES.with(|state| {
160        *state.borrow_mut() = VecDeque::from(responses);
161    });
162}
163
164/// Clears any remaining interactive responses.
165pub fn clear_heuristic_responses() {
166    HEURISTIC_RESPONSES.with(|state| state.borrow_mut().clear());
167}
168
169/// Returns a deterministic pseudo-random index and advances the per-thread heuristic RNG.
170pub fn next_heuristic_random_index(upper_bound: usize) -> usize {
171    bug_assert!(
172        upper_bound > 0,
173        "random choice requires at least one candidate"
174    );
175    HEURISTIC_RANDOM_STATE.with(|state| {
176        // SplitMix64: small, reproducible, and sufficient for choice ordering.
177        let next = state.get().wrapping_add(0x9e37_79b9_7f4a_7c15);
178        state.set(next);
179        let mut mixed = next;
180        mixed = (mixed ^ (mixed >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
181        mixed = (mixed ^ (mixed >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
182        mixed ^= mixed >> 31;
183        (mixed as usize) % upper_bound
184    })
185}
186
187/// Starts one replay of the `x` heuristic using the requested branch indices.
188pub fn begin_heuristic_all_choices(requested: Vec<usize>) {
189    HEURISTIC_ALL_CHOICES.with(|state| {
190        *state.borrow_mut() = AllChoicesState {
191            requested,
192            decisions: Vec::new(),
193        };
194    });
195}
196
197/// Restores the previous heuristic when a scoped override ends.
198struct HeuristicGuard(Heuristic);
199
200impl Drop for HeuristicGuard {
201    fn drop(&mut self) {
202        set_heuristic(self.0);
203    }
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.
217pub fn with_compact_heuristic<T>(f: impl FnOnce() -> T) -> T {
218    let previous = heuristic();
219    set_heuristic(Heuristic::Compact);
220    let _guard = HeuristicGuard(previous);
221    f()
222}
223
224/// Selects the requested branch at the next `x` decision and records all available options.
225pub fn next_heuristic_all_index(options: &[&str]) -> usize {
226    bug_assert!(
227        !options.is_empty(),
228        "all-choice requires at least one candidate"
229    );
230    HEURISTIC_ALL_CHOICES.with(|state| {
231        let mut state = state.borrow_mut();
232        let decision_index = state.decisions.len();
233        let selected = state.requested.get(decision_index).copied().unwrap_or(0);
234        assert!(
235            selected < options.len(),
236            "requested heuristic branch {selected} but only {} options exist",
237            options.len()
238        );
239        state.decisions.push(HeuristicChoice {
240            selected,
241            options: options.iter().map(|option| (*option).to_string()).collect(),
242        });
243        selected
244    })
245}
246
247pub fn heuristic_all_choices() -> Vec<HeuristicChoice> {
248    HEURISTIC_ALL_CHOICES.with(|state| state.borrow().decisions.clone())
249}
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.
255pub fn next_heuristic_interactive_index(options: &[&str]) -> usize {
256    bug_assert!(
257        !options.is_empty(),
258        "interactive choice requires at least one candidate"
259    );
260
261    for (index, option) in options.iter().enumerate() {
262        eprintln!("{}. {}", index + 1, option);
263    }
264
265    let recorded = HEURISTIC_RESPONSES.with(|state| state.borrow_mut().pop_front());
266    let one_based = match recorded {
267        Some(recorded) => {
268            eprintln!("Response: {recorded}");
269            assert!(
270                recorded >= 1 && recorded <= options.len(),
271                "recorded response {recorded} out of range; expected a value between 1 and {}",
272                options.len()
273            );
274            recorded
275        }
276        None => prompt_heuristic_interactive_choice(options.len()),
277    };
278    one_based - 1
279}
280
281fn 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)]
309pub struct RewriteConfig {
310    /// Skip rules whose declared expression discriminants cannot match.
311    pub prefilter: bool,
312    /// Drive rewriting from persistent dirty node queues instead of repeated full scans.
313    pub worklist: bool,
314}
315
316impl RewriteConfig {
317    pub const fn baseline() -> Self {
318        Self {
319            prefilter: false,
320            worklist: false,
321        }
322    }
323
324    pub const fn optimised() -> Self {
325        Self {
326            prefilter: true,
327            worklist: true,
328        }
329    }
330
331    pub const fn is_baseline(self) -> bool {
332        !self.prefilter && !self.worklist
333    }
334
335    pub const fn is_optimised(self) -> bool {
336        self.prefilter && self.worklist
337    }
338}
339
340impl Default for RewriteConfig {
341    fn default() -> Self {
342        Self::optimised()
343    }
344}
345
346impl Display for RewriteConfig {
347    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348        if self.is_optimised() {
349            write!(f, "optimised")
350        } else if self.is_baseline() {
351            write!(f, "baseline")
352        } else {
353            let mut options = vec!["baseline"];
354            if self.prefilter {
355                options.push("prefilter");
356            }
357            if self.worklist {
358                options.push("worklist");
359            }
360            write!(f, "{}", options.join("+"))
361        }
362    }
363}
364
365impl FromStr for RewriteConfig {
366    type Err = String;
367
368    fn from_str(s: &str) -> Result<Self, Self::Err> {
369        let trimmed = s.trim().to_ascii_lowercase();
370        match trimmed.as_str() {
371            "baseline" => return Ok(Self::baseline()),
372            "optimised" => return Ok(Self::optimised()),
373            _ => {}
374        }
375
376        if !trimmed.starts_with("baseline+") {
377            return Err(format!(
378                "unknown rewrite config: {trimmed}; expected baseline, optimised, or baseline plus '+' separated prefilter/worklist options"
379            ));
380        }
381
382        let mut config = Self::baseline();
383        let mut baseline_seen = false;
384        let mut prefilter_seen = false;
385        let mut worklist_seen = false;
386        let mut option_seen = false;
387
388        for token in trimmed.split('+') {
389            match token {
390                "" => {}
391                "baseline" => {
392                    if baseline_seen {
393                        return Err("duplicate rewrite option 'baseline'".to_string());
394                    }
395                    baseline_seen = true;
396                }
397                "prefilter" => {
398                    if prefilter_seen {
399                        return Err("duplicate rewrite option 'prefilter'".to_string());
400                    }
401                    config.prefilter = true;
402                    prefilter_seen = true;
403                    option_seen = true;
404                }
405                "worklist" => {
406                    if worklist_seen {
407                        return Err("duplicate rewrite option 'worklist'".to_string());
408                    }
409                    config.worklist = true;
410                    worklist_seen = true;
411                    option_seen = true;
412                }
413                other => {
414                    return Err(format!(
415                        "unknown rewrite option '{other}'; expected baseline, optimised, or a '+' separated combination of: prefilter, worklist"
416                    ));
417                }
418            }
419        }
420
421        if !option_seen {
422            return Err(
423                "rewrite config 'baseline+' must include at least one of: prefilter, worklist"
424                    .to_string(),
425            );
426        }
427
428        Ok(config)
429    }
430}
431
432#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
433pub enum Rewriter {
434    Rewrite(RewriteConfig),
435}
436
437impl Default for Rewriter {
438    fn default() -> Self {
439        Self::Rewrite(RewriteConfig::optimised())
440    }
441}
442
443thread_local! {
444    /// Thread-local setting for which rewriter is currently active.
445    ///
446    /// Must be explicitly set before use.
447    static CURRENT_REWRITER: Cell<Option<Rewriter>> = const { Cell::new(None) };
448}
449
450impl Display for Rewriter {
451    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452        match self {
453            Rewriter::Rewrite(config) => write!(f, "{config}"),
454        }
455    }
456}
457
458impl FromStr for Rewriter {
459    type Err = String;
460
461    fn from_str(s: &str) -> Result<Self, Self::Err> {
462        let trimmed = s.trim().to_ascii_lowercase();
463        match trimmed.as_str() {
464            "baseline" | "optimised" => Ok(Rewriter::Rewrite(trimmed.parse()?)),
465            other => {
466                if other.contains('+') {
467                    return Ok(Rewriter::Rewrite(other.parse()?));
468                }
469
470                Err(format!(
471                    "unknown rewriter: {other}; expected baseline, optimised, or baseline plus '+' separated prefilter/worklist options"
472                ))
473            }
474        }
475    }
476}
477
478pub fn set_current_rewriter(rewriter: Rewriter) {
479    CURRENT_REWRITER.with(|current| current.set(Some(rewriter)));
480}
481
482pub fn current_rewriter() -> Rewriter {
483    CURRENT_REWRITER.with(|current| {
484        current.get().unwrap_or_else(|| {
485            // loud failure on purpose, so we don't end up using the default
486            bug!("current rewriter not set for this thread; call set_current_rewriter first")
487        })
488    })
489}
490
491#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
492pub enum QuantifiedExpander {
493    Auto,
494    Native,
495    ViaSolver,
496    ViaSolverAc,
497}
498
499impl Display for QuantifiedExpander {
500    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501        match self {
502            QuantifiedExpander::Auto => write!(f, "auto"),
503            QuantifiedExpander::Native => write!(f, "native"),
504            QuantifiedExpander::ViaSolver => write!(f, "via-solver"),
505            QuantifiedExpander::ViaSolverAc => write!(f, "via-solver-ac"),
506        }
507    }
508}
509
510impl FromStr for QuantifiedExpander {
511    type Err = String;
512
513    fn from_str(s: &str) -> Result<Self, Self::Err> {
514        match s.trim().to_ascii_lowercase().as_str() {
515            "auto" => Ok(QuantifiedExpander::Auto),
516            "native" => Ok(QuantifiedExpander::Native),
517            "via-solver" => Ok(QuantifiedExpander::ViaSolver),
518            "via-solver-ac" => Ok(QuantifiedExpander::ViaSolverAc),
519            _ => Err(format!(
520                "unknown comprehension expander: {s}; expected one of: \
521                 auto, native, via-solver, via-solver-ac"
522            )),
523        }
524    }
525}
526
527thread_local! {
528    /// Thread-local setting for which comprehension expansion strategy is currently active.
529    ///
530    /// Must be explicitly set before use.
531    static COMPREHENSION_EXPANDER: Cell<Option<QuantifiedExpander>> = const { Cell::new(None) };
532}
533
534pub fn set_comprehension_expander(expander: QuantifiedExpander) {
535    COMPREHENSION_EXPANDER.with(|current| current.set(Some(expander)));
536}
537
538pub fn comprehension_expander() -> QuantifiedExpander {
539    COMPREHENSION_EXPANDER.with(|current| {
540        current.get().unwrap_or_else(|| {
541            // loud failure on purpose, so we don't end up using the default
542            bug!(
543                "comprehension expander not set for this thread; call set_comprehension_expander first"
544            )
545        })
546    })
547}
548
549#[derive(
550    Debug,
551    EnumIter,
552    StrumDisplay,
553    PartialEq,
554    Eq,
555    Hash,
556    Clone,
557    Copy,
558    Serialize,
559    Deserialize,
560    JsonSchema,
561)]
562pub enum SolverFamily {
563    Minion,
564    Sat,
565    Z3,
566}
567
568thread_local! {
569    /// Thread-local setting for which solver family is currently active.
570    ///
571    /// Must be explicitly set before use.
572    static CURRENT_SOLVER_FAMILY: Cell<Option<SolverFamily>> = const { Cell::new(None) };
573}
574
575pub const DEFAULT_MINION_DISCRETE_THRESHOLD: usize = 10;
576
577thread_local! {
578    /// Thread-local setting controlling when Minion int domains are emitted as `DISCRETE`.
579    ///
580    /// If an int domain size is <= this threshold, the Minion adaptor uses `DISCRETE`; otherwise
581    /// it uses `BOUND`, unless another constraint requires `DISCRETE`.
582    static MINION_DISCRETE_THRESHOLD: Cell<Option<usize>> = const { Cell::new(None) };
583
584    /// Thread-local setting controlling whether rule-trace outputs are active in this phase.
585    ///
586    /// This is intentionally off by default and can be disabled before solver-time rewrites so
587    /// follow-up dominance-blocking rewrites do not pollute the initial rewrite trace.
588    static RULE_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
589
590    /// Thread-local setting controlling whether default rule traces are configured.
591    static DEFAULT_RULE_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
592
593    /// Thread-local setting controlling whether verbose rule-attempt traces are configured.
594    static RULE_ATTEMPT_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
595
596    /// Thread-local setting controlling whether aggregate rule-application traces are configured.
597    static RULE_TRACE_AGGREGATES_ENABLED: Cell<bool> = const { Cell::new(false) };
598}
599
600pub fn set_current_solver_family(solver_family: SolverFamily) {
601    CURRENT_SOLVER_FAMILY.with(|current| current.set(Some(solver_family)));
602}
603
604/// Restores the previous solver family when a scoped override ends.
605struct SolverFamilyGuard(Option<SolverFamily>);
606
607impl Drop for SolverFamilyGuard {
608    fn drop(&mut self) {
609        CURRENT_SOLVER_FAMILY.with(|current| current.set(self.0));
610    }
611}
612
613/// Runs `f` as a rewrite for `solver_family`, then restores the surrounding solver context.
614///
615/// Some rewrites build and solve a temporary model with a different backend from the outer model.
616/// Representation applicability must follow the backend that will actually consume that temporary
617/// model, not the user's outer solver setting.
618pub fn with_solver_family<T>(solver_family: SolverFamily, f: impl FnOnce() -> T) -> T {
619    let previous = CURRENT_SOLVER_FAMILY.with(|current| current.replace(Some(solver_family)));
620    let _guard = SolverFamilyGuard(previous);
621    f()
622}
623
624/// The active solver family, or `None` if this thread has not set one.
625///
626/// Unlike [`current_solver_family`] this does not panic. Solver-family gating asks with this so
627/// that unit tests exercising a single component do not have to stand up a solver context.
628pub fn try_current_solver_family() -> Option<SolverFamily> {
629    CURRENT_SOLVER_FAMILY.with(|current| current.get())
630}
631
632pub fn current_solver_family() -> SolverFamily {
633    CURRENT_SOLVER_FAMILY.with(|current| {
634        current.get().unwrap_or_else(|| {
635            // loud failure on purpose, so we don't end up using the default
636            bug!(
637                "current solver family not set for this thread; call set_current_solver_family first"
638            )
639        })
640    })
641}
642
643/// Whether integers carry a representation choice for the solver being targeted.
644///
645/// SAT has no integers at all: an int variable is encoded as a vector of Booleans, and which
646/// encoding it gets is a representation choice like any other. The SMT backend does have integers,
647/// but has two ways to express them -- linear arithmetic and bit-vectors -- so the choice is a
648/// representation there too. Minion has one native integer and needs none of this. With no solver
649/// family set -- a unit test exercising one component, say -- integers stay concrete.
650pub fn ints_need_representation() -> bool {
651    matches!(
652        try_current_solver_family(),
653        Some(SolverFamily::Sat | SolverFamily::Z3)
654    )
655}
656
657/// Pins Minion's domain threshold, or leaves it to the modelling heuristic.
658pub fn set_minion_discrete_threshold(threshold: Option<usize>) {
659    MINION_DISCRETE_THRESHOLD.with(|current| current.set(threshold));
660}
661
662/// Selects one threshold for a Minion model: the default, all bound, or all discrete.
663/// Constraints requiring discrete variables still override the threshold.
664pub fn select_minion_discrete_threshold() -> usize {
665    if let Some(threshold) = MINION_DISCRETE_THRESHOLD.with(Cell::get) {
666        return threshold;
667    }
668    let thresholds = [DEFAULT_MINION_DISCRETE_THRESHOLD, 0, usize::MAX];
669    let labels = [
670        "minion-discrete-threshold=10",
671        "minion-discrete-threshold=0",
672        "minion-discrete-threshold=unlimited",
673    ];
674    let index = match heuristic() {
675        Heuristic::First | Heuristic::Compact => 0,
676        Heuristic::Random => next_heuristic_random_index(thresholds.len()),
677        Heuristic::Interactive => next_heuristic_interactive_index(&labels),
678        Heuristic::All => next_heuristic_all_index(&labels),
679    };
680    thresholds[index]
681}
682
683pub fn set_rule_trace_enabled(enabled: bool) {
684    RULE_TRACE_ENABLED.with(|current| current.set(enabled));
685}
686
687pub fn rule_trace_enabled() -> bool {
688    RULE_TRACE_ENABLED.with(|current| current.get())
689}
690
691pub fn set_default_rule_trace_enabled(enabled: bool) {
692    DEFAULT_RULE_TRACE_ENABLED.with(|current| current.set(enabled));
693}
694
695pub fn default_rule_trace_enabled() -> bool {
696    DEFAULT_RULE_TRACE_ENABLED.with(|current| current.get())
697}
698
699pub fn set_rule_attempt_trace_enabled(enabled: bool) {
700    RULE_ATTEMPT_TRACE_ENABLED.with(|current| current.set(enabled));
701}
702
703pub fn rule_attempt_trace_enabled() -> bool {
704    RULE_ATTEMPT_TRACE_ENABLED.with(|current| current.get())
705}
706
707pub fn set_rule_trace_aggregates_enabled(enabled: bool) {
708    RULE_TRACE_AGGREGATES_ENABLED.with(|current| current.set(enabled));
709}
710
711pub fn rule_trace_aggregates_enabled() -> bool {
712    RULE_TRACE_AGGREGATES_ENABLED.with(|current| current.get())
713}
714
715pub fn configured_rule_trace_enabled() -> bool {
716    default_rule_trace_enabled() || rule_attempt_trace_enabled() || rule_trace_aggregates_enabled()
717}
718
719impl FromStr for SolverFamily {
720    type Err = String;
721
722    fn from_str(s: &str) -> Result<Self, Self::Err> {
723        match s.trim().to_ascii_lowercase().as_str() {
724            "minion" => Ok(SolverFamily::Minion),
725            "sat" => Ok(SolverFamily::Sat),
726            "z3" => Ok(SolverFamily::Z3),
727            other => Err(format!(
728                "unknown solver '{other}', expected one of: minion, sat, z3"
729            )),
730        }
731    }
732}
733
734impl SolverFamily {
735    pub fn as_str(&self) -> String {
736        match self {
737            SolverFamily::Minion => "minion".to_owned(),
738            SolverFamily::Sat => "sat".to_owned(),
739            SolverFamily::Z3 => "z3".to_owned(),
740        }
741    }
742}
743
744#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
745pub struct SolverArgs {
746    pub timeout_ms: Option<u64>,
747}
748
749#[derive(Clone, Debug, PartialEq, Eq)]
750struct SavedSettings {
751    rewriter: Option<Rewriter>,
752    expander: Option<QuantifiedExpander>,
753    solver_family: Option<SolverFamily>,
754    heuristic: Heuristic,
755    channelling: Channelling,
756    random_state: u64,
757    all_choices: AllChoicesState,
758    responses: VecDeque<usize>,
759    minion_discrete_threshold: Option<usize>,
760    element_encoding: Option<crate::ast::sat_decision::ElementEncoding>,
761    table_encoding: Option<crate::ast::sat_decision::TableEncoding>,
762    alldifferent_encoding: Option<crate::ast::sat_decision::AllDifferentEncoding>,
763    pb_encoding: Option<crate::ast::sat_decision::PbEncoding>,
764    cardinality_encoding: Option<crate::ast::sat_decision::CardinalityEncoding>,
765    amo_encoding: Option<crate::ast::sat_decision::AmoEncoding>,
766    rule_trace: bool,
767    default_rule_trace: bool,
768    rule_attempt_trace: bool,
769    rule_trace_aggregates: bool,
770}
771
772impl SavedSettings {
773    fn capture() -> Self {
774        Self {
775            rewriter: CURRENT_REWRITER.with(Cell::get),
776            expander: COMPREHENSION_EXPANDER.with(Cell::get),
777            solver_family: CURRENT_SOLVER_FAMILY.with(Cell::get),
778            heuristic: HEURISTIC.with(Cell::get),
779            channelling: CHANNELLING.with(Cell::get),
780            random_state: HEURISTIC_RANDOM_STATE.with(Cell::get),
781            all_choices: HEURISTIC_ALL_CHOICES.with(|state| state.borrow().clone()),
782            responses: HEURISTIC_RESPONSES.with(|state| state.borrow().clone()),
783            minion_discrete_threshold: MINION_DISCRETE_THRESHOLD.with(Cell::get),
784            element_encoding: ELEMENT_ENCODING.with(Cell::get),
785            table_encoding: TABLE_ENCODING.with(Cell::get),
786            alldifferent_encoding: ALLDIFFERENT_ENCODING.with(Cell::get),
787            pb_encoding: PB_ENCODING.with(Cell::get),
788            cardinality_encoding: CARDINALITY_ENCODING.with(Cell::get),
789            amo_encoding: AMO_ENCODING.with(Cell::get),
790            rule_trace: RULE_TRACE_ENABLED.with(Cell::get),
791            default_rule_trace: DEFAULT_RULE_TRACE_ENABLED.with(Cell::get),
792            rule_attempt_trace: RULE_ATTEMPT_TRACE_ENABLED.with(Cell::get),
793            rule_trace_aggregates: RULE_TRACE_AGGREGATES_ENABLED.with(Cell::get),
794        }
795    }
796
797    fn restore(self) {
798        CURRENT_REWRITER.with(|current| current.set(self.rewriter));
799        COMPREHENSION_EXPANDER.with(|current| current.set(self.expander));
800        CURRENT_SOLVER_FAMILY.with(|current| current.set(self.solver_family));
801        HEURISTIC.with(|current| current.set(self.heuristic));
802        CHANNELLING.with(|current| current.set(self.channelling));
803        HEURISTIC_RANDOM_STATE.with(|current| current.set(self.random_state));
804        HEURISTIC_ALL_CHOICES.with(|current| *current.borrow_mut() = self.all_choices);
805        HEURISTIC_RESPONSES.with(|current| *current.borrow_mut() = self.responses);
806        MINION_DISCRETE_THRESHOLD.with(|current| current.set(self.minion_discrete_threshold));
807        ELEMENT_ENCODING.with(|current| current.set(self.element_encoding));
808        TABLE_ENCODING.with(|current| current.set(self.table_encoding));
809        ALLDIFFERENT_ENCODING.with(|current| current.set(self.alldifferent_encoding));
810        PB_ENCODING.with(|current| current.set(self.pb_encoding));
811        CARDINALITY_ENCODING.with(|current| current.set(self.cardinality_encoding));
812        AMO_ENCODING.with(|current| current.set(self.amo_encoding));
813        RULE_TRACE_ENABLED.with(|current| current.set(self.rule_trace));
814        DEFAULT_RULE_TRACE_ENABLED.with(|current| current.set(self.default_rule_trace));
815        RULE_ATTEMPT_TRACE_ENABLED.with(|current| current.set(self.rule_attempt_trace));
816        RULE_TRACE_AGGREGATES_ENABLED.with(|current| current.set(self.rule_trace_aggregates));
817    }
818}
819
820struct SettingsGuard(Option<SavedSettings>);
821
822impl Drop for SettingsGuard {
823    fn drop(&mut self) {
824        if let Some(settings) = self.0.take() {
825            settings.restore();
826        }
827    }
828}
829
830/// Runs `f`, restoring the calling thread's settings afterwards, including on panic.
831///
832/// Changes inside the closure stay local to the scope. Random state, pending heuristic answers,
833/// recorded choices and uniform representations are restored along with configuration values.
834pub fn with_saved_settings<T>(f: impl FnOnce() -> T) -> T {
835    let _uniform = crate::representation::uniform::Scope::save();
836    let _settings = SettingsGuard(Some(SavedSettings::capture()));
837    f()
838}
839
840#[cfg(test)]
841mod tests {
842    use super::{
843        Channelling, Heuristic, QuantifiedExpander, RewriteConfig, Rewriter, SolverFamily,
844        begin_heuristic_all_choices, clear_heuristic_responses, heuristic_all_choices,
845        next_heuristic_all_index, next_heuristic_interactive_index, next_heuristic_random_index,
846        set_current_solver_family, set_heuristic_responses, set_heuristic_seed,
847        try_current_solver_family, with_solver_family,
848    };
849    use std::str::FromStr;
850
851    #[test]
852    fn compact_is_the_default_heuristic() {
853        assert_eq!(Heuristic::default(), Heuristic::Compact);
854    }
855
856    #[test]
857    fn scoped_solver_family_restores_the_outer_solver() {
858        set_current_solver_family(SolverFamily::Z3);
859
860        with_solver_family(SolverFamily::Minion, || {
861            assert_eq!(try_current_solver_family(), Some(SolverFamily::Minion));
862        });
863
864        assert_eq!(try_current_solver_family(), Some(SolverFamily::Z3));
865    }
866
867    #[test]
868    fn parses_answer_heuristics_and_channelling() {
869        assert_eq!(Heuristic::from_str("f"), Ok(Heuristic::First));
870        assert_eq!(Heuristic::from_str("random"), Ok(Heuristic::Random));
871        assert_eq!(Heuristic::from_str("c"), Ok(Heuristic::Compact));
872        assert_eq!(Heuristic::from_str("i"), Ok(Heuristic::Interactive));
873        assert_eq!(
874            Heuristic::from_str("interactive"),
875            Ok(Heuristic::Interactive)
876        );
877        assert_eq!(Heuristic::from_str("x"), Ok(Heuristic::All));
878        assert_eq!(Channelling::from_str("no"), Ok(Channelling::No));
879        assert_eq!(Channelling::from_str("yes"), Ok(Channelling::Yes));
880        assert_eq!(Channelling::from_str("uniform"), Ok(Channelling::Uniform));
881        assert_eq!(Channelling::Uniform.to_string(), "uniform");
882    }
883
884    #[test]
885    fn parses_auto_comprehension_expander() {
886        assert_eq!(
887            QuantifiedExpander::from_str("auto"),
888            Ok(QuantifiedExpander::Auto)
889        );
890        assert_eq!(QuantifiedExpander::Auto.to_string(), "auto");
891    }
892
893    #[test]
894    fn interactive_heuristic_consumes_one_based_responses() {
895        set_heuristic_responses(vec![2, 1]);
896        assert_eq!(next_heuristic_interactive_index(&["left", "right"]), 1);
897        assert_eq!(next_heuristic_interactive_index(&["a", "b", "c"]), 0);
898        clear_heuristic_responses();
899    }
900
901    #[test]
902    fn random_heuristic_is_reproducible_from_seed() {
903        set_heuristic_seed(42);
904        let first: Vec<_> = (0..8).map(|_| next_heuristic_random_index(7)).collect();
905        set_heuristic_seed(42);
906        let second: Vec<_> = (0..8).map(|_| next_heuristic_random_index(7)).collect();
907        assert_eq!(first, second);
908    }
909
910    #[test]
911    fn all_heuristic_replays_and_records_choices() {
912        begin_heuristic_all_choices(vec![1]);
913        assert_eq!(next_heuristic_all_index(&["left", "right"]), 1);
914        assert_eq!(
915            heuristic_all_choices()[0].options,
916            vec!["left".to_string(), "right".to_string()]
917        );
918    }
919
920    #[test]
921    fn parses_rewrite_option_combinations() {
922        assert_eq!(
923            RewriteConfig::from_str("baseline").unwrap(),
924            RewriteConfig {
925                prefilter: false,
926                worklist: false,
927            }
928        );
929        assert_eq!(
930            RewriteConfig::from_str("baseline+prefilter").unwrap(),
931            RewriteConfig {
932                prefilter: true,
933                worklist: false,
934            }
935        );
936        assert_eq!(
937            RewriteConfig::from_str("baseline+worklist").unwrap(),
938            RewriteConfig {
939                prefilter: false,
940                worklist: true,
941            }
942        );
943        assert_eq!(
944            RewriteConfig::from_str("baseline+prefilter+worklist").unwrap(),
945            RewriteConfig::optimised()
946        );
947        assert!(RewriteConfig::from_str("+dirty").is_err());
948        assert!(RewriteConfig::from_str("baseline+dirty").is_err());
949        assert!(RewriteConfig::from_str("baseline+cache").is_err());
950        assert!(RewriteConfig::from_str("baseline+rulememo").is_err());
951        assert!(RewriteConfig::from_str("baseline+candidateindex").is_err());
952        assert!(RewriteConfig::from_str("baseline+dirtyqueues").is_err());
953        assert!(RewriteConfig::from_str("baseline+rule-memo").is_err());
954        assert!(RewriteConfig::from_str("baseline+candidate-index").is_err());
955        assert!(RewriteConfig::from_str("baseline+candidate-node-index").is_err());
956        assert!(RewriteConfig::from_str("baseline+dirty-node-queues").is_err());
957    }
958
959    #[test]
960    fn optimised_rewrite_config_enables_fast_default_options() {
961        assert_eq!(
962            RewriteConfig::from_str("optimised").unwrap(),
963            RewriteConfig {
964                prefilter: true,
965                worklist: true,
966            }
967        );
968    }
969
970    #[test]
971    fn displays_rewrite_option_combinations() {
972        assert_eq!(RewriteConfig::baseline().to_string(), "baseline");
973        assert_eq!(
974            RewriteConfig {
975                prefilter: true,
976                worklist: false,
977            }
978            .to_string(),
979            "baseline+prefilter"
980        );
981        assert_eq!(
982            RewriteConfig {
983                prefilter: false,
984                worklist: true,
985            }
986            .to_string(),
987            "baseline+worklist"
988        );
989        assert_eq!(RewriteConfig::optimised().to_string(), "optimised");
990        assert_eq!(
991            RewriteConfig::from_str("baseline+prefilter+worklist")
992                .unwrap()
993                .to_string(),
994            "optimised"
995        );
996    }
997
998    #[test]
999    fn parses_rewriter_option_combinations() {
1000        assert_eq!(
1001            Rewriter::from_str("baseline+prefilter").unwrap(),
1002            Rewriter::Rewrite(RewriteConfig {
1003                prefilter: true,
1004                worklist: false,
1005            })
1006        );
1007        assert_eq!(
1008            Rewriter::from_str("baseline+prefilter+worklist").unwrap(),
1009            Rewriter::Rewrite(RewriteConfig::optimised())
1010        );
1011        assert!(Rewriter::from_str("+dirty").is_err());
1012        assert!(Rewriter::from_str("dirty").is_err());
1013        assert!(Rewriter::from_str("baseline+dirty").is_err());
1014    }
1015}
1016
1017/// Pin the AMO algorithm, or allow the modelling heuristic to choose.
1018pub fn set_amo_encoding(encoding: Option<crate::ast::sat_decision::AmoEncoding>) {
1019    AMO_ENCODING.with(|current| current.set(encoding));
1020}
1021/// Explicit AMO algorithm override for this compilation thread.
1022pub fn amo_encoding() -> Option<crate::ast::sat_decision::AmoEncoding> {
1023    AMO_ENCODING.with(Cell::get)
1024}
1025
1026/// Pin a cardinality provider/algorithm, or let the heuristic select it.
1027pub fn set_cardinality_encoding(encoding: Option<crate::ast::sat_decision::CardinalityEncoding>) {
1028    CARDINALITY_ENCODING.with(|current| current.set(encoding));
1029}
1030/// Explicit cardinality encoder override for this compilation thread.
1031pub fn cardinality_encoding() -> Option<crate::ast::sat_decision::CardinalityEncoding> {
1032    CARDINALITY_ENCODING.with(Cell::get)
1033}
1034
1035/// Pin a pseudo-Boolean provider/algorithm, or let the heuristic select it.
1036pub fn set_pb_encoding(encoding: Option<crate::ast::sat_decision::PbEncoding>) {
1037    PB_ENCODING.with(|current| current.set(encoding));
1038}
1039/// Explicit pseudo-Boolean encoder override for this compilation thread.
1040pub fn pb_encoding() -> Option<crate::ast::sat_decision::PbEncoding> {
1041    PB_ENCODING.with(Cell::get)
1042}
1043
1044/// Pin the allDifferent strategy, or let the heuristic choose an applicable composition.
1045pub fn set_alldifferent_encoding(encoding: Option<crate::ast::sat_decision::AllDifferentEncoding>) {
1046    ALLDIFFERENT_ENCODING.with(|current| current.set(encoding));
1047}
1048/// Explicit allDifferent strategy override for this compilation thread.
1049pub fn alldifferent_encoding() -> Option<crate::ast::sat_decision::AllDifferentEncoding> {
1050    ALLDIFFERENT_ENCODING.with(Cell::get)
1051}
1052
1053/// Pin the table composition, or let the modelling heuristic select it.
1054pub fn set_table_encoding(encoding: Option<crate::ast::sat_decision::TableEncoding>) {
1055    TABLE_ENCODING.with(|current| current.set(encoding));
1056}
1057/// Explicit table strategy override for this compilation thread.
1058pub fn table_encoding() -> Option<crate::ast::sat_decision::TableEncoding> {
1059    TABLE_ENCODING.with(Cell::get)
1060}
1061
1062/// Pin the element composition, or let the modelling heuristic select it.
1063pub fn set_element_encoding(encoding: Option<crate::ast::sat_decision::ElementEncoding>) {
1064    ELEMENT_ENCODING.with(|current| current.set(encoding));
1065}
1066/// Explicit element strategy override for this compilation thread.
1067pub fn element_encoding() -> Option<crate::ast::sat_decision::ElementEncoding> {
1068    ELEMENT_ENCODING.with(Cell::get)
1069}
1070
1071#[cfg(test)]
1072mod saved_settings_tests {
1073    use super::*;
1074    use crate::ast::sat_decision::{
1075        AllDifferentEncoding, AmoEncoding, CardinalityEncoding, ElementEncoding, PbEncoding,
1076        TableEncoding,
1077    };
1078
1079    fn configure_settings() {
1080        set_current_rewriter(Rewriter::Rewrite(RewriteConfig::baseline()));
1081        set_comprehension_expander(QuantifiedExpander::ViaSolver);
1082        set_current_solver_family(SolverFamily::Sat);
1083        set_heuristic(Heuristic::Random);
1084        set_channelling(Channelling::Uniform);
1085        set_heuristic_seed(42);
1086        set_heuristic_responses(vec![2, 1]);
1087        begin_heuristic_all_choices(vec![1, 0]);
1088        next_heuristic_all_index(&["left", "right"]);
1089        set_minion_discrete_threshold(Some(123));
1090        set_element_encoding(Some(ElementEncoding::Support));
1091        set_table_encoding(Some(TableEncoding::Mdd));
1092        set_alldifferent_encoding(Some(AllDifferentEncoding::ValueAmo));
1093        set_pb_encoding(Some(PbEncoding::PindakaasBdd));
1094        set_cardinality_encoding(Some(CardinalityEncoding::PindakaasSortingNetwork));
1095        set_amo_encoding(Some(AmoEncoding::Ladder));
1096        set_rule_trace_enabled(true);
1097        set_default_rule_trace_enabled(true);
1098        set_rule_attempt_trace_enabled(true);
1099        set_rule_trace_aggregates_enabled(true);
1100    }
1101
1102    #[test]
1103    fn saved_settings_restore_nested_configuration() {
1104        with_saved_settings(|| {
1105            configure_settings();
1106            let outer = SavedSettings::capture();
1107
1108            let result = with_saved_settings(|| {
1109                set_current_rewriter(Rewriter::default());
1110                set_comprehension_expander(QuantifiedExpander::Native);
1111                set_current_solver_family(SolverFamily::Minion);
1112                set_heuristic(Heuristic::Compact);
1113                set_channelling(Channelling::No);
1114                set_heuristic_seed(99);
1115                clear_heuristic_responses();
1116                begin_heuristic_all_choices(vec![]);
1117                set_minion_discrete_threshold(None);
1118                set_element_encoding(None);
1119                set_table_encoding(None);
1120                set_alldifferent_encoding(None);
1121                set_pb_encoding(None);
1122                set_cardinality_encoding(None);
1123                set_amo_encoding(None);
1124                set_rule_trace_enabled(false);
1125                set_default_rule_trace_enabled(false);
1126                set_rule_attempt_trace_enabled(false);
1127                set_rule_trace_aggregates_enabled(false);
1128                let inner = SavedSettings::capture();
1129
1130                with_saved_settings(configure_settings);
1131
1132                assert_eq!(SavedSettings::capture(), inner);
1133                7
1134            });
1135
1136            assert_eq!(result, 7);
1137            assert_eq!(SavedSettings::capture(), outer);
1138        });
1139    }
1140
1141    #[test]
1142    fn saved_settings_restore_unset_configuration_after_panic() {
1143        std::thread::spawn(|| {
1144            let before = SavedSettings::capture();
1145            assert_eq!(try_current_solver_family(), None);
1146
1147            let result = std::panic::catch_unwind(|| {
1148                with_saved_settings(|| {
1149                    configure_settings();
1150                    panic!("interrupted library run");
1151                });
1152            });
1153
1154            assert!(result.is_err());
1155            assert_eq!(SavedSettings::capture(), before);
1156        })
1157        .join()
1158        .unwrap();
1159    }
1160
1161    #[test]
1162    fn saved_settings_preserve_heuristic_progress() {
1163        with_saved_settings(|| {
1164            set_heuristic_seed(42);
1165            let expected: Vec<_> = (0..3).map(|_| next_heuristic_random_index(997)).collect();
1166            set_heuristic_seed(42);
1167            assert_eq!(next_heuristic_random_index(997), expected[0]);
1168            set_heuristic_responses(vec![2, 1]);
1169            assert_eq!(next_heuristic_interactive_index(&["left", "right"]), 1);
1170            begin_heuristic_all_choices(vec![1, 1]);
1171            assert_eq!(next_heuristic_all_index(&["left", "right"]), 1);
1172
1173            with_saved_settings(|| {
1174                for _ in 0..10 {
1175                    next_heuristic_random_index(997);
1176                }
1177                assert_eq!(next_heuristic_interactive_index(&["a", "b"]), 0);
1178                begin_heuristic_all_choices(vec![]);
1179                assert_eq!(next_heuristic_all_index(&["a", "b"]), 0);
1180            });
1181
1182            assert_eq!(next_heuristic_random_index(997), expected[1]);
1183            assert_eq!(next_heuristic_random_index(997), expected[2]);
1184            assert_eq!(next_heuristic_interactive_index(&["left", "right"]), 0);
1185            assert_eq!(heuristic_all_choices().len(), 1);
1186            assert_eq!(next_heuristic_all_index(&["a", "b"]), 1);
1187            assert_eq!(heuristic_all_choices()[0].options, ["left", "right"]);
1188        });
1189    }
1190}