1use std::cell::Cell;
4use std::collections::BTreeMap;
5use std::path::Path;
6use std::sync::{Arc, RwLock};
7use std::time::Duration;
8
9use anyhow::{Context as _, Result, ensure};
10
11use crate::Model;
12use crate::ast::sat_decision::{
13 AllDifferentEncoding, AmoEncoding, CardinalityEncoding, ElementEncoding, PbEncoding,
14 TableEncoding,
15};
16use crate::ast::{Literal, Name};
17use crate::context::Context;
18use crate::defaults::DEFAULT_RULE_SETS;
19use crate::instantiate::{instantiate_model, validate_instantiation_conditions};
20use crate::parse::tree_sitter::errors::ParseErrorCollection;
21use crate::rule_engine::{get_rules, resolve_rule_sets, rewrite_model};
22use crate::settings::{self, Channelling, Heuristic, QuantifiedExpander, Rewriter, SolverFamily};
23use crate::solutions::{SolutionCollectionTimings, SolutionOptions, get_solutions_with_timings};
24use crate::solver::Solver;
25use crate::solver::adaptors::*;
26
27thread_local! {
28 static ACTIVE_PIPELINE: Cell<*const Pipeline> = const { Cell::new(std::ptr::null()) };
29}
30
31struct ActivePipelineGuard(*const Pipeline);
32
33impl Drop for ActivePipelineGuard {
34 fn drop(&mut self) {
35 ACTIVE_PIPELINE.with(|active| active.set(self.0));
36 }
37}
38
39#[derive(Clone, Debug)]
41pub struct Config {
42 pub rewriter: Rewriter,
44 pub comprehension_expander: QuantifiedExpander,
46 pub solver: SolverFamily,
48 pub extra_rule_sets: Vec<String>,
50 pub heuristic: Heuristic,
52 pub seed: u64,
54 pub responses: Vec<usize>,
56 pub channelling: Channelling,
58 pub amo_encoding: Option<AmoEncoding>,
60 pub cardinality_encoding: Option<CardinalityEncoding>,
62 pub pb_encoding: Option<PbEncoding>,
64 pub element_encoding: Option<ElementEncoding>,
66 pub table_encoding: Option<TableEncoding>,
68 pub alldifferent_encoding: Option<AllDifferentEncoding>,
70 pub minion_discrete_threshold: Option<usize>,
72 pub minion_varorder: Option<MinionVariableOrder>,
74 pub minion_valorder: Option<MinionValueOrder>,
76 #[cfg(any(
78 feature = "sat-batsat",
79 all(feature = "sat-cadical", not(target_family = "wasm"))
80 ))]
81 pub sat_backend: SatBackend,
82 pub solver_seed: u32,
84 pub solver_timeout: Option<Duration>,
86 pub trace: TraceConfig,
88}
89
90impl Default for Config {
91 fn default() -> Self {
92 Self {
93 rewriter: Rewriter::default(),
94 comprehension_expander: QuantifiedExpander::Auto,
95 solver: SolverFamily::Minion,
96 extra_rule_sets: Vec::new(),
97 heuristic: Heuristic::default(),
98 seed: settings::DEFAULT_HEURISTIC_SEED,
99 responses: Vec::new(),
100 channelling: Channelling::default(),
101 amo_encoding: None,
102 cardinality_encoding: None,
103 pb_encoding: None,
104 element_encoding: None,
105 table_encoding: None,
106 alldifferent_encoding: None,
107 minion_discrete_threshold: None,
108 minion_varorder: None,
109 minion_valorder: None,
110 #[cfg(any(
111 feature = "sat-batsat",
112 all(feature = "sat-cadical", not(target_family = "wasm"))
113 ))]
114 sat_backend: SatBackend::default(),
115 solver_seed: 0,
116 solver_timeout: None,
117 trace: TraceConfig::default(),
118 }
119 }
120}
121
122#[derive(Clone, Copy, Debug, Default)]
124pub struct TraceConfig {
125 pub rules: bool,
127 pub attempts: bool,
129 pub aggregates: bool,
131}
132
133impl Config {
134 fn apply(&self) {
135 settings::set_current_rewriter(self.rewriter);
136 settings::set_comprehension_expander(self.comprehension_expander);
137 settings::set_current_solver_family(self.solver);
138 settings::set_minion_discrete_threshold(self.minion_discrete_threshold);
139 settings::set_heuristic(self.heuristic);
140 settings::set_heuristic_seed(self.seed);
141 settings::set_heuristic_responses(self.responses.clone());
142 settings::begin_heuristic_all_choices(Vec::new());
143 settings::set_channelling(self.channelling);
144 settings::set_amo_encoding(self.amo_encoding);
145 settings::set_cardinality_encoding(self.cardinality_encoding);
146 settings::set_pb_encoding(self.pb_encoding);
147 settings::set_element_encoding(self.element_encoding);
148 settings::set_table_encoding(self.table_encoding);
149 settings::set_alldifferent_encoding(self.alldifferent_encoding);
150 settings::set_default_rule_trace_enabled(self.trace.rules);
151 settings::set_rule_attempt_trace_enabled(self.trace.attempts);
152 settings::set_rule_trace_aggregates_enabled(self.trace.aggregates);
153 settings::set_rule_trace_enabled(
154 self.trace.rules || self.trace.attempts || self.trace.aggregates,
155 );
156 }
157}
158
159pub struct Pipeline {
166 config: Config,
167 context: Arc<RwLock<Context<'static>>>,
168}
169
170impl Pipeline {
171 pub fn new(config: Config) -> Result<Self> {
173 #[cfg(not(any(
174 feature = "sat-batsat",
175 all(feature = "sat-cadical", not(target_family = "wasm"))
176 )))]
177 if config.solver == SolverFamily::Sat {
178 anyhow::bail!(
179 "SAT solver support was not compiled in (enable `sat-batsat` or `sat-cadical`)."
180 );
181 }
182 #[cfg(not(feature = "z3"))]
183 if config.solver == SolverFamily::Z3 {
184 anyhow::bail!("Z3 solver support was not compiled in (enable the `z3` feature).");
185 }
186 let names: Vec<&str> = DEFAULT_RULE_SETS
187 .iter()
188 .copied()
189 .chain(config.extra_rule_sets.iter().map(String::as_str))
190 .collect();
191 let rule_sets = resolve_rule_sets(config.solver, &names)
192 .context("could not resolve rule sets; link a rule provider such as conjure-cp-rules and check extra rule set names")?;
193 let rules = get_rules(&rule_sets)?.into_iter().collect();
194 tracing::info!(target: "conjure::stage", count = rule_sets.len(), "resolved rule sets");
195 let context = Context::new_ptr(
196 config.solver,
197 names.iter().map(|s| s.to_string()).collect(),
198 rules,
199 rule_sets,
200 );
201 Ok(Self { config, context })
202 }
203
204 pub fn context(&self) -> Arc<RwLock<Context<'static>>> {
206 Arc::clone(&self.context)
207 }
208
209 pub fn with_settings<T>(&self, f: impl FnOnce() -> T) -> T {
215 let pointer = std::ptr::from_ref(self);
216 if ACTIVE_PIPELINE.with(|active| active.get() == pointer) {
217 return f();
218 }
219 settings::with_saved_settings(|| {
220 let previous = ACTIVE_PIPELINE.with(|active| active.replace(pointer));
221 let _active = ActivePipelineGuard(previous);
222 self.config.apply();
223 f()
224 })
225 }
226
227 pub fn parse(&self, source: &str) -> Result<Model> {
229 self.with_settings(|| self.parse_native(source, None))
230 }
231
232 pub fn parse_file(&self, path: impl AsRef<Path>) -> Result<Model> {
234 let path = path.as_ref();
235 tracing::info!(target: "conjure::stage", path = %path.display(), "parsing input model");
236 self.with_settings(|| {
237 let source = std::fs::read_to_string(path)
238 .with_context(|| format!("could not read {}", path.display()))?;
239 self.parse_native(&source, Some(path.to_string_lossy().into_owned()))
240 })
241 }
242
243 fn parse_native(&self, source: &str, filename: Option<String>) -> Result<Model> {
244 let mut errors = Vec::new();
245 match crate::parse::tree_sitter::parse_essence_with_context(
246 source,
247 self.context(),
248 &mut errors,
249 ) {
250 Ok(Some(model)) => {
251 crate::ast::assertions::debug_assert_model_well_formed(&model, "tree-sitter");
252 Ok(model)
253 }
254 Ok(None) => {
255 Err(ParseErrorCollection::multiple(errors, Some(source.into()), filename).into())
256 }
257 Err(error) => Err(ParseErrorCollection::fatal(error).into()),
258 }
259 }
260
261 pub fn compile(&self, source: &str, parameters: Option<&str>) -> Result<Model> {
263 self.with_settings(|| {
264 let problem = self.parse(source)?;
265 let model = match parameters {
266 Some(parameters) => instantiate_model(problem, self.parse(parameters)?)?,
267 None => {
268 let mut problem = problem;
269 validate_instantiation_conditions(&mut problem)?;
270 problem
271 }
272 };
273 self.rewrite(model)
274 })
275 }
276
277 pub fn rewrite(&self, model: Model) -> Result<Model> {
279 self.check_context(&model)?;
280 for (name, declaration) in model.symbols().iter_local() {
281 ensure!(
282 declaration.as_given().is_none(),
283 "given `{name}` needs a parameter value before rewriting"
284 );
285 }
286 self.with_settings(|| {
287 tracing::debug!(model = %model, "initial model");
288 let Rewriter::Rewrite(config) = self.config.rewriter;
289 let rule_sets = self.context.read().unwrap().rule_sets.clone();
290 tracing::info!(target: "conjure::stage", %config, "rewriting model");
291 let model = rewrite_model(&model, &rule_sets, config)?;
292 tracing::debug!(model = %model, "rewritten model");
293 Ok(model)
294 })
295 }
296
297 pub fn solver(&self) -> Result<Solver> {
299 let config = &self.config;
300 Ok(match config.solver {
301 SolverFamily::Minion => Solver::new(
302 Minion::with_search_orders(config.minion_varorder, config.minion_valorder)
303 .with_solver_seed(config.solver_seed)
304 .with_timeout(config.solver_timeout),
305 ),
306 #[cfg(any(
307 feature = "sat-batsat",
308 all(feature = "sat-cadical", not(target_family = "wasm"))
309 ))]
310 SolverFamily::Sat => Solver::new(
311 Sat::new(config.sat_backend)
312 .with_solver_seed(config.solver_seed)
313 .with_timeout(config.solver_timeout),
314 ),
315 #[cfg(not(any(
316 feature = "sat-batsat",
317 all(feature = "sat-cadical", not(target_family = "wasm"))
318 )))]
319 SolverFamily::Sat => anyhow::bail!(
320 "SAT solver support was not compiled in (enable `sat-batsat` or `sat-cadical`)."
321 ),
322 #[cfg(feature = "z3")]
323 SolverFamily::Z3 => {
324 Solver::new(Smt::new(config.solver_timeout).with_solver_seed(config.solver_seed))
325 }
326 #[cfg(not(feature = "z3"))]
327 SolverFamily::Z3 => {
328 anyhow::bail!("Z3 solver support was not compiled in (enable the `z3` feature).")
329 }
330 })
331 }
332
333 pub fn solve(
335 &self,
336 model: Model,
337 options: &SolutionOptions,
338 ) -> Result<Vec<BTreeMap<Name, Literal>>> {
339 self.solve_with_timings(model, options)
340 .map(|(solutions, _)| solutions)
341 }
342
343 pub fn solve_with_timings(
345 &self,
346 model: Model,
347 options: &SolutionOptions,
348 ) -> Result<(Vec<BTreeMap<Name, Literal>>, SolutionCollectionTimings)> {
349 self.check_context(&model)?;
350 ensure!(
351 options.number_of_solutions >= 0,
352 "number of solutions must be non-negative (zero requests all)"
353 );
354 self.with_settings(|| {
355 get_solutions_with_timings(
356 self.solver()?,
357 model,
358 options.number_of_solutions,
359 options.keep_intermediate_solutions,
360 &options.solver_input_file,
361 options.rule_trace_cdp,
362 )
363 })
364 }
365
366 fn check_context(&self, model: &Model) -> Result<()> {
367 ensure!(
368 Arc::ptr_eq(&model.context, &self.context),
369 "model belongs to a different pipeline context"
370 );
371 Ok(())
372 }
373}