1
//! Run the modelling pipeline without command-line arguments or global initialisation.
2

            
3
use std::cell::Cell;
4
use std::collections::BTreeMap;
5
use std::io::Write;
6
use std::path::Path;
7
use std::sync::{Arc, RwLock};
8
use std::time::Duration;
9

            
10
use anyhow::{Context as _, Result, ensure};
11

            
12
use crate::Model;
13
use crate::ast::sat_decision::{
14
    AllDifferentEncoding, AmoEncoding, CardinalityEncoding, ElementEncoding, PbEncoding,
15
    TableEncoding,
16
};
17
use crate::ast::{Literal, Name};
18
use crate::context::Context;
19
use crate::defaults::DEFAULT_RULE_SETS;
20
use crate::instantiate::{instantiate_model, validate_instantiation_conditions};
21
use crate::parse::tree_sitter::errors::ParseErrorCollection;
22
use crate::rule_engine::{get_rules, resolve_rule_sets, rewrite_model};
23
use crate::settings::{
24
    self, Channelling, Heuristic, Parser, QuantifiedExpander, Rewriter, SolverFamily,
25
};
26
use crate::solutions::{SolutionCollectionTimings, SolutionOptions, get_solutions_with_timings};
27
use crate::solver::Solver;
28
use crate::solver::adaptors::*;
29

            
30
thread_local! {
31
    static ACTIVE_PIPELINE: Cell<*const Pipeline> = const { Cell::new(std::ptr::null()) };
32
}
33

            
34
struct ActivePipelineGuard(*const Pipeline);
35

            
36
impl Drop for ActivePipelineGuard {
37
1352
    fn drop(&mut self) {
38
1352
        ACTIVE_PIPELINE.with(|active| active.set(self.0));
39
1352
    }
40
}
41

            
42
/// Modelling and solver options shared by library callers and the CLI.
43
#[derive(Clone, Debug)]
44
pub struct Config {
45
    /// Input parser; the native parser needs no external executable.
46
    pub parser: Parser,
47
    /// Rewrite engine configuration.
48
    pub rewriter: Rewriter,
49
    /// Strategy for expanding comprehensions.
50
    pub comprehension_expander: QuantifiedExpander,
51
    /// Target solver family.
52
    pub solver: SolverFamily,
53
    /// Additional registered rule sets, alongside the defaults and solver rules.
54
    pub extra_rule_sets: Vec<String>,
55
    /// Strategy for modelling decisions.
56
    pub heuristic: Heuristic,
57
    /// Random modelling seed, reset for each operation.
58
    pub seed: u64,
59
    /// Recorded 1-based interactive answers, reset for each operation.
60
    pub responses: Vec<usize>,
61
    /// Representation channelling policy.
62
    pub channelling: Channelling,
63
    /// Optional SAT encoder overrides.
64
    pub amo_encoding: Option<AmoEncoding>,
65
    /// Optional SAT cardinality encoder override.
66
    pub cardinality_encoding: Option<CardinalityEncoding>,
67
    /// Optional SAT pseudo-Boolean encoder override.
68
    pub pb_encoding: Option<PbEncoding>,
69
    /// Optional SAT element-constraint encoder override.
70
    pub element_encoding: Option<ElementEncoding>,
71
    /// Optional SAT table-constraint encoder override.
72
    pub table_encoding: Option<TableEncoding>,
73
    /// Optional SAT allDifferent encoder override.
74
    pub alldifferent_encoding: Option<AllDifferentEncoding>,
75
    /// Optional Minion discrete-domain span threshold.
76
    pub minion_discrete_threshold: Option<usize>,
77
    /// Optional Minion search orders.
78
    pub minion_varorder: Option<MinionVariableOrder>,
79
    /// Optional Minion value ordering.
80
    pub minion_valorder: Option<MinionValueOrder>,
81
    /// Compiled SAT implementation to use.
82
    #[cfg(any(
83
        feature = "sat-batsat",
84
        all(feature = "sat-cadical", not(target_family = "wasm"))
85
    ))]
86
    pub sat_backend: SatBackend,
87
    /// Backend solver seed.
88
    pub solver_seed: u32,
89
    /// Cumulative wall-clock solver timeout.
90
    pub solver_timeout: Option<Duration>,
91
    /// Trace events to emit to the caller's tracing subscriber.
92
    pub trace: TraceConfig,
93
}
94

            
95
impl Default for Config {
96
360
    fn default() -> Self {
97
360
        Self {
98
360
            parser: Parser::default(),
99
360
            rewriter: Rewriter::default(),
100
360
            comprehension_expander: QuantifiedExpander::Auto,
101
360
            solver: SolverFamily::Minion,
102
360
            extra_rule_sets: Vec::new(),
103
360
            heuristic: Heuristic::default(),
104
360
            seed: settings::DEFAULT_HEURISTIC_SEED,
105
360
            responses: Vec::new(),
106
360
            channelling: Channelling::default(),
107
360
            amo_encoding: None,
108
360
            cardinality_encoding: None,
109
360
            pb_encoding: None,
110
360
            element_encoding: None,
111
360
            table_encoding: None,
112
360
            alldifferent_encoding: None,
113
360
            minion_discrete_threshold: None,
114
360
            minion_varorder: None,
115
360
            minion_valorder: None,
116
360
            #[cfg(any(
117
360
                feature = "sat-batsat",
118
360
                all(feature = "sat-cadical", not(target_family = "wasm"))
119
360
            ))]
120
360
            sat_backend: SatBackend::default(),
121
360
            solver_seed: 0,
122
360
            solver_timeout: None,
123
360
            trace: TraceConfig::default(),
124
360
        }
125
360
    }
126
}
127

            
128
/// Rule trace events enabled for a pipeline; subscribers and output belong to the caller.
129
#[derive(Clone, Copy, Debug, Default)]
130
pub struct TraceConfig {
131
    /// Emit the default rule trace.
132
    pub rules: bool,
133
    /// Emit rule-attempt events.
134
    pub attempts: bool,
135
    /// Emit aggregate rule-application events.
136
    pub aggregates: bool,
137
}
138

            
139
impl Config {
140
1364
    fn apply(&self) {
141
1364
        settings::set_current_parser(self.parser);
142
1364
        settings::set_current_rewriter(self.rewriter);
143
1364
        settings::set_comprehension_expander(self.comprehension_expander);
144
1364
        settings::set_current_solver_family(self.solver);
145
1364
        settings::set_minion_discrete_threshold(self.minion_discrete_threshold);
146
1364
        settings::set_heuristic(self.heuristic);
147
1364
        settings::set_heuristic_seed(self.seed);
148
1364
        settings::set_heuristic_responses(self.responses.clone());
149
1364
        settings::begin_heuristic_all_choices(Vec::new());
150
1364
        settings::set_channelling(self.channelling);
151
1364
        settings::set_amo_encoding(self.amo_encoding);
152
1364
        settings::set_cardinality_encoding(self.cardinality_encoding);
153
1364
        settings::set_pb_encoding(self.pb_encoding);
154
1364
        settings::set_element_encoding(self.element_encoding);
155
1364
        settings::set_table_encoding(self.table_encoding);
156
1364
        settings::set_alldifferent_encoding(self.alldifferent_encoding);
157
1364
        settings::set_default_rule_trace_enabled(self.trace.rules);
158
1364
        settings::set_rule_attempt_trace_enabled(self.trace.attempts);
159
1364
        settings::set_rule_trace_aggregates_enabled(self.trace.aggregates);
160
1364
        settings::set_rule_trace_enabled(
161
1364
            self.trace.rules || self.trace.attempts || self.trace.aggregates,
162
        );
163
1364
    }
164
}
165

            
166
/// A configured pipeline with a shared model context and accumulated statistics.
167
///
168
/// Link a rule provider (for example `use conjure_cp_rules as _;`) before constructing one.
169
/// Each operation installs its settings on the current thread and restores the caller's settings,
170
/// including on panic. A pipeline can be reused for successive fuzzer inputs; construct a new one
171
/// when each run needs separate statistics.
172
pub struct Pipeline {
173
    config: Config,
174
    context: Arc<RwLock<Context<'static>>>,
175
}
176

            
177
impl Pipeline {
178
    /// Resolve registered rules and create a context, returning configuration errors to the caller.
179
1004
    pub fn new(config: Config) -> Result<Self> {
180
        #[cfg(not(any(
181
            feature = "sat-batsat",
182
            all(feature = "sat-cadical", not(target_family = "wasm"))
183
        )))]
184
        if config.solver == SolverFamily::Sat {
185
            anyhow::bail!(
186
                "SAT solver support was not compiled in (enable `sat-batsat` or `sat-cadical`)."
187
            );
188
        }
189
        #[cfg(not(feature = "z3"))]
190
        if config.solver == SolverFamily::Z3 {
191
            anyhow::bail!("Z3 solver support was not compiled in (enable the `z3` feature).");
192
        }
193
1004
        let names: Vec<&str> = DEFAULT_RULE_SETS
194
1004
            .iter()
195
1004
            .copied()
196
1004
            .chain(config.extra_rule_sets.iter().map(String::as_str))
197
1004
            .collect();
198
1004
        let rule_sets = resolve_rule_sets(config.solver, &names)
199
1004
            .context("could not resolve rule sets; link a rule provider such as conjure-cp-rules and check extra rule set names")?;
200
989
        let rules = get_rules(&rule_sets)?.into_iter().collect();
201
989
        tracing::info!(target: "conjure::stage", count = rule_sets.len(), "resolved rule sets");
202
989
        let context = Context::new_ptr(
203
989
            config.solver,
204
1978
            names.iter().map(|s| s.to_string()).collect(),
205
989
            rules,
206
989
            rule_sets,
207
        );
208
989
        Ok(Self { config, context })
209
1004
    }
210

            
211
    /// Access source metadata, enabled rules and accumulated statistics.
212
1780
    pub fn context(&self) -> Arc<RwLock<Context<'static>>> {
213
1780
        Arc::clone(&self.context)
214
1780
    }
215

            
216
    /// Run lower-level library operations with this pipeline's settings in scope.
217
    ///
218
    /// Use this when loading or running a [`Solver`] directly, including solver-time rewrites.
219
    /// Nested operations on this pipeline share the current random stream and interactive answers.
220
    /// Keep the closure synchronous; settings are local to its current thread.
221
2687
    pub fn with_settings<T>(&self, f: impl FnOnce() -> T) -> T {
222
2687
        let pointer = std::ptr::from_ref(self);
223
2687
        if ACTIVE_PIPELINE.with(|active| active.get() == pointer) {
224
1757
            return f();
225
930
        }
226
930
        settings::with_saved_settings(|| {
227
930
            let previous = ACTIVE_PIPELINE.with(|active| active.replace(pointer));
228
930
            let _active = ActivePipelineGuard(previous);
229
930
            self.config.apply();
230
930
            f()
231
930
        })
232
2687
    }
233

            
234
    /// Parse Essence source in memory using the configured parser.
235
405
    pub fn parse(&self, source: &str) -> Result<Model> {
236
405
        self.with_settings(|| match self.config.parser {
237
405
            Parser::TreeSitter => self.parse_native(source, None),
238
            Parser::ViaConjure => {
239
                let mut file = tempfile::Builder::new().suffix(".essence").tempfile()?;
240
                file.write_all(source.as_bytes())?;
241
                self.parse_via_conjure(file.path())
242
            }
243
405
        })
244
405
    }
245

            
246
    /// Parse a file using the configured parser without requiring a UTF-8 path.
247
363
    pub fn parse_file(&self, path: impl AsRef<Path>) -> Result<Model> {
248
363
        let path = path.as_ref();
249
363
        tracing::info!(target: "conjure::stage", path = %path.display(), "parsing input model");
250
363
        self.with_settings(|| match self.config.parser {
251
            Parser::TreeSitter => {
252
195
                let source = std::fs::read_to_string(path)
253
4
                    .with_context(|| format!("could not read {}", path.display()))?;
254
191
                self.parse_native(&source, Some(path.to_string_lossy().into_owned()))
255
            }
256
168
            Parser::ViaConjure => self.parse_via_conjure(path),
257
363
        })
258
363
    }
259

            
260
800
    fn parse_native(&self, source: &str, filename: Option<String>) -> Result<Model> {
261
800
        let mut errors = Vec::new();
262
800
        match crate::parse::tree_sitter::parse_essence_with_context(
263
800
            source,
264
800
            self.context(),
265
800
            &mut errors,
266
800
        ) {
267
            Ok(Some(model)) => {
268
733
                crate::ast::assertions::debug_assert_model_well_formed(&model, "tree-sitter");
269
733
                Ok(model)
270
            }
271
            Ok(None) => {
272
67
                Err(ParseErrorCollection::multiple(errors, Some(source.into()), filename).into())
273
            }
274
            Err(error) => Err(ParseErrorCollection::fatal(error).into()),
275
        }
276
800
    }
277

            
278
336
    fn parse_via_conjure(&self, path: &Path) -> Result<Model> {
279
336
        crate::find_conjure::conjure_executable()
280
336
            .context("Could not find correct conjure executable")?;
281
336
        let output = std::process::Command::new("conjure")
282
336
            .args(["pretty", "--output-format=astjson"])
283
336
            .arg(path)
284
336
            .output()?;
285
336
        ensure!(
286
336
            output.status.success(),
287
            "Parsing error: {}",
288
            String::from_utf8_lossy(&output.stderr)
289
        );
290
336
        let astjson = String::from_utf8(output.stdout)?;
291
336
        crate::parse::conjure_json::model_from_json(&astjson, self.context()).map_err(Into::into)
292
336
    }
293

            
294
    /// Parse, instantiate optional Essence parameters, and rewrite an in-memory problem.
295
330
    pub fn compile(&self, source: &str, parameters: Option<&str>) -> Result<Model> {
296
330
        self.with_settings(|| {
297
330
            let problem = self.parse(source)?;
298
330
            let model = match parameters {
299
45
                Some(parameters) => instantiate_model(problem, self.parse(parameters)?)?,
300
                None => {
301
285
                    let mut problem = problem;
302
285
                    validate_instantiation_conditions(&mut problem)?;
303
285
                    problem
304
                }
305
            };
306
330
            self.rewrite(model)
307
330
        })
308
330
    }
309

            
310
    /// Rewrite a model parsed with this pipeline, resetting modelling choices for the operation.
311
676
    pub fn rewrite(&self, model: Model) -> Result<Model> {
312
676
        self.check_context(&model)?;
313
661
        for (name, declaration) in model.symbols().iter_local() {
314
9298
            ensure!(
315
9298
                declaration.as_given().is_none(),
316
15
                "given `{name}` needs a parameter value before rewriting"
317
            );
318
        }
319
646
        self.with_settings(|| {
320
            tracing::debug!(model = %model, "initial model");
321
646
            let Rewriter::Rewrite(config) = self.config.rewriter;
322
646
            let rule_sets = self.context.read().unwrap().rule_sets.clone();
323
646
            tracing::info!(target: "conjure::stage", %config, "rewriting model");
324
646
            let model = rewrite_model(&model, &rule_sets, config)?;
325
            tracing::debug!(model = %model, "rewritten model");
326
646
            Ok(model)
327
646
        })
328
676
    }
329

            
330
    /// Create a configured solver; use [`Self::with_settings`] when running it directly.
331
543
    pub fn solver(&self) -> Result<Solver> {
332
543
        let config = &self.config;
333
543
        Ok(match config.solver {
334
387
            SolverFamily::Minion => Solver::new(
335
387
                Minion::with_search_orders(config.minion_varorder, config.minion_valorder)
336
387
                    .with_solver_seed(config.solver_seed)
337
387
                    .with_timeout(config.solver_timeout),
338
387
            ),
339
            #[cfg(any(
340
                feature = "sat-batsat",
341
                all(feature = "sat-cadical", not(target_family = "wasm"))
342
            ))]
343
144
            SolverFamily::Sat => Solver::new(
344
144
                Sat::new(config.sat_backend)
345
144
                    .with_solver_seed(config.solver_seed)
346
144
                    .with_timeout(config.solver_timeout),
347
144
            ),
348
            #[cfg(not(any(
349
                feature = "sat-batsat",
350
                all(feature = "sat-cadical", not(target_family = "wasm"))
351
            )))]
352
            SolverFamily::Sat => anyhow::bail!(
353
                "SAT solver support was not compiled in (enable `sat-batsat` or `sat-cadical`)."
354
            ),
355
            #[cfg(feature = "z3")]
356
            SolverFamily::Z3 => {
357
12
                Solver::new(Smt::new(config.solver_timeout).with_solver_seed(config.solver_seed))
358
            }
359
            #[cfg(not(feature = "z3"))]
360
            SolverFamily::Z3 => {
361
                anyhow::bail!("Z3 solver support was not compiled in (enable the `z3` feature).")
362
            }
363
        })
364
543
    }
365

            
366
    /// Solve a rewritten model and reconstruct its high-level Essence values.
367
342
    pub fn solve(
368
342
        &self,
369
342
        model: Model,
370
342
        options: &SolutionOptions,
371
342
    ) -> Result<Vec<BTreeMap<Name, Literal>>> {
372
342
        self.solve_with_timings(model, options)
373
            .map(|(solutions, _)| solutions)
374
342
    }
375

            
376
    /// Collect reconstructed solutions and backend, search and reconstruction timings.
377
558
    pub fn solve_with_timings(
378
558
        &self,
379
558
        model: Model,
380
558
        options: &SolutionOptions,
381
558
    ) -> Result<(Vec<BTreeMap<Name, Literal>>, SolutionCollectionTimings)> {
382
558
        self.check_context(&model)?;
383
543
        ensure!(
384
543
            options.number_of_solutions >= 0,
385
            "number of solutions must be non-negative (zero requests all)"
386
        );
387
543
        self.with_settings(|| {
388
543
            get_solutions_with_timings(
389
543
                self.solver()?,
390
543
                model,
391
543
                options.number_of_solutions,
392
543
                options.keep_intermediate_solutions,
393
543
                &options.solver_input_file,
394
543
                options.rule_trace_cdp,
395
            )
396
543
        })
397
558
    }
398

            
399
1234
    fn check_context(&self, model: &Model) -> Result<()> {
400
1234
        ensure!(
401
1234
            Arc::ptr_eq(&model.context, &self.context),
402
30
            "model belongs to a different pipeline context"
403
        );
404
1204
        Ok(())
405
1234
    }
406
}