Skip to main content

conjure_oxide/
cli.rs

1use std::path::PathBuf;
2
3use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
4
5use clap_complete::Shell;
6use conjure_cp::settings::{
7    Channelling, DEFAULT_HEURISTIC_SEED, Heuristic, QuantifiedExpander, Rewriter, SolverFamily,
8};
9use conjure_cp::solver::adaptors::{MinionValueOrder, MinionVariableOrder, SatBackend};
10use git_version::git_version;
11
12use crate::{pretty, solve, test_solve};
13
14pub(crate) const LOGGING_HELP_HEADING: Option<&str> = Some("Logging & Output");
15pub(crate) const CONFIGURATION_HELP_HEADING: Option<&str> = Some("Configuration");
16pub(crate) const MODELLING_HELP_HEADING: Option<&str> = Some("Modelling choices");
17
18/// All subcommands of conjure-oxide
19#[derive(Clone, Debug, Subcommand)]
20pub enum Command {
21    /// Solve a model
22    Solve(solve::Args),
23    /// Tests whether the Essence model is solvable with Conjure Oxide, and whether it gets the
24    /// same solutions as Conjure.
25    ///
26    /// Return-code will be 0 if the solutions match, 1 if they don't, and >1 on crash.
27    TestSolve(test_solve::Args),
28    /// Generate a completion script for the shell provided
29    Completion(CompletionArgs),
30    Pretty(pretty::Args),
31    // Run the language server
32    ServerLSP,
33}
34
35/// Global command line arguments.
36#[derive(Clone, Debug, Parser)]
37#[command(
38    author,
39    about = "Conjure Oxide: Automated Constraints Modelling Toolkit",
40    before_help = "Full documentation can be found online at: https://conjure-cp.github.io/conjure-oxide",
41    // Free `-h` for `--heuristic`; help remains available as `--help`.
42    disable_help_flag = true,
43    version = git_version!(),
44    disable_version_flag = true,
45    display_name = "conjure-oxide",
46    // clap's derive turns this on for a required subcommand; keep the concise
47    // "requires a subcommand" error instead of dumping the full help.
48    arg_required_else_help = false
49)]
50pub struct Cli {
51    #[command(subcommand)]
52    pub subcommand: Command,
53
54    #[command(flatten)]
55    pub global_args: GlobalArgs,
56
57    /// Print version
58    // `ArgAction::Version` is handled by clap while parsing, so `--version` works on its own,
59    // without the otherwise-required subcommand.
60    #[arg(long = "version", short = 'V', action = ArgAction::Version)]
61    pub version: (),
62}
63
64#[derive(Debug, Clone, Args)]
65pub struct GlobalArgs {
66    /// Print help
67    #[arg(long, action = clap::ArgAction::Help, global = true)]
68    pub help: (),
69
70    /// Extra rule sets to enable
71    #[arg(long, value_name = "EXTRA_RULE_SETS", global = true)]
72    pub extra_rule_sets: Vec<String>,
73
74    /// Increase stderr logging detail (-v: stages, -vv: rule applications, -vvv: rule attempts).
75    ///
76    /// Rule-attempt logging can be expensive and produce a very large amount of output.
77    #[arg(
78        long,
79        short = 'v',
80        action = ArgAction::Count,
81        global = true,
82        conflicts_with = "quiet",
83        help_heading = LOGGING_HELP_HEADING
84    )]
85    pub verbose: u8,
86
87    /// Disable warning and progress logs on stderr
88    #[arg(long, short = 'q', global = true, help_heading = LOGGING_HELP_HEADING)]
89    pub quiet: bool,
90
91    /// Output file for the default rule trace.
92    #[arg(long, global = true, help_heading=LOGGING_HELP_HEADING)]
93    pub rule_trace: Option<PathBuf>,
94
95    /// Output file for aggregated rule-application counts.
96    ///
97    /// Counts are kept in memory and written when the program exits, in the format:
98    /// `total_rule_applications: N`, followed by one line per rule.
99    #[arg(long, global = true, help_heading=LOGGING_HELP_HEADING)]
100    pub rule_trace_aggregates: Option<PathBuf>,
101
102    /// Continue rule trace generation during solver-time CDP rewrites.
103    ///
104    /// This is off by default, so follow-up dominance-blocking rewrites do not contribute to the
105    /// trace.
106    #[arg(long, default_value_t = false, global = true, help_heading=LOGGING_HELP_HEADING)]
107    pub rule_trace_cdp: bool,
108
109    /// Output file for the rule-attempt trace in CSV format.
110    ///
111    /// Each row includes: elapsed_s, rule_level, rule_name, rule_set, status, expression.
112    #[arg(
113        long = "rule-attempt-trace",
114        global = true,
115        help_heading=LOGGING_HELP_HEADING
116    )]
117    pub rule_attempt_trace: Option<PathBuf>,
118
119    /// Which rewriter to use.
120    ///
121    /// Possible values: `baseline`, `optimised`, `baseline+prefilter`, or `baseline+worklist`.
122    ///
123    /// Option meanings:
124    /// - `prefilter`: skip rules whose declared expression kinds cannot match; strong win vs
125    ///   baseline and part of `optimised`.
126    /// - `worklist`: drive rewriting from persistent dirty queues instead of repeated full scans;
127    ///   strong win vs baseline and part of `optimised`.
128    #[arg(long, default_value_t = Rewriter::default(), value_parser = parse_rewriter, global = true, help_heading = CONFIGURATION_HELP_HEADING)]
129    pub rewriter: Rewriter,
130
131    /// Which strategy to use for expanding quantified variables in comprehensions.
132    ///
133    /// Possible values: `auto`, `native`, `via-solver`, `via-solver-ac`. `auto` chooses
134    /// between native and solver-backed expansion from the comprehension's estimated size and
135    /// available pruning constraints.
136    #[arg(
137        long,
138        default_value_t = QuantifiedExpander::Auto,
139        value_parser = parse_comprehension_expander,
140        global = true,
141        help_heading = MODELLING_HELP_HEADING
142    )]
143    pub comprehension_expander: QuantifiedExpander,
144
145    /// Heuristic for selecting an answer when multiple modelling choices are applicable.
146    ///
147    /// Possible values: `f` (first), `r` (random), `c` (compact), `i` (interactive). Compact
148    /// estimates structural work for supported Minion representation choices, falling back to
149    /// representation-domain size elsewhere, and minimises resulting AST depth for equally-applicable
150    /// rewrite rules. Use -v to inspect representation costs. Interactive prompts on stderr, or uses
151    /// `--responses` when provided. `x` (all) is reserved for model generation and is not
152    /// supported by the CLI yet.
153    #[arg(
154        long,
155        short = 'h',
156        default_value_t = Heuristic::Compact,
157        value_parser = parse_cli_heuristic,
158        global = true,
159        help_heading = MODELLING_HELP_HEADING
160    )]
161    pub heuristic: Heuristic,
162
163    /// Comma-separated 1-based answers for the interactive heuristic (`-h i`).
164    ///
165    /// If provided, these are used as the answers during interactive model generation instead of
166    /// prompting the user.
167    #[arg(
168        long,
169        value_name = "INTS",
170        value_delimiter = ',',
171        global = true,
172        help_heading = MODELLING_HELP_HEADING
173    )]
174    pub responses: Vec<usize>,
175
176    /// Seed used by the random heuristic.
177    #[arg(
178        long,
179        default_value_t = DEFAULT_HEURISTIC_SEED,
180        global = true,
181        help_heading = MODELLING_HELP_HEADING
182    )]
183    pub seed: u64,
184
185    /// Seed used by the backend solver's random search behaviour.
186    #[arg(
187        long,
188        default_value_t = 0,
189        global = true,
190        help_heading = CONFIGURATION_HELP_HEADING
191    )]
192    pub solver_seed: u32,
193
194    /// Whether multiple representations of the same declaration may be channelled together.
195    ///
196    /// Possible values: `no`, `yes`, `uniform`. Channelling is disabled by default.
197    /// `uniform` uses one representation kind per type family throughout the model. Enable `yes` for
198    /// different representations of the same variable at different call sites, e.g.
199    /// `1 in (x :: set (representation packed) of int) /\ 2 in (x :: set (representation occurrence) of int)`.
200    #[arg(
201        long,
202        default_value_t = Channelling::No,
203        value_parser = parse_cli_channelling,
204        global = true,
205        help_heading = MODELLING_HELP_HEADING
206    )]
207    pub channelling: Channelling,
208
209    /// Pin the SAT element composition: implication or support.
210    #[arg(long = "sat-encoding-element", global = true, help_heading = MODELLING_HELP_HEADING)]
211    pub element_encoding: Option<conjure_cp::ast::sat_decision::ElementEncoding>,
212
213    /// Pin the SAT table composition: tuple, mdd or binary-support (constant two-column relations).
214    #[arg(long = "sat-encoding-table", global = true, help_heading = MODELLING_HELP_HEADING)]
215    pub table_encoding: Option<conjure_cp::ast::sat_decision::TableEncoding>,
216
217    /// Pin allDifferent: pairwise, or value-amo (requires Direct or Boolean value indicators).
218    #[arg(long = "sat-encoding-alldifferent", global = true, help_heading = MODELLING_HELP_HEADING)]
219    pub alldifferent_encoding: Option<conjure_cp::ast::sat_decision::AllDifferentEncoding>,
220
221    /// Pin the SAT AMO encoder: pairwise, ladder, bitwise, commander, bimander, two-product,
222    /// pindakaas-pairwise, pindakaas-ladder or pindakaas-bitwise.
223    /// If omitted, compact chooses per constraint; portfolio heuristics share one family choice.
224    #[arg(long = "sat-encoding-amo", global = true, help_heading = MODELLING_HELP_HEADING)]
225    pub amo_encoding: Option<conjure_cp::ast::sat_decision::AmoEncoding>,
226
227    /// Pin the SAT cardinality encoder: rustsat-totalizer or pindakaas-sorting-network.
228    #[arg(long = "sat-encoding-cardinality", global = true, help_heading = MODELLING_HELP_HEADING)]
229    pub cardinality_encoding: Option<conjure_cp::ast::sat_decision::CardinalityEncoding>,
230
231    /// Pin the SAT weighted encoder: rustsat-generalized-totalizer, rustsat-binary-adder, pindakaas-bdd, rustsat-dynamic-poly-watchdog, or pindakaas-swc.
232    #[arg(long = "sat-encoding-pb", global = true, help_heading = MODELLING_HELP_HEADING)]
233    pub pb_encoding: Option<conjure_cp::ast::sat_decision::PbEncoding>,
234
235    /// Solver to use.
236    ///
237    /// Possible values: `minion`, `sat`, `z3`.
238    ///
239    /// How a model is expressed for the chosen solver -- which SAT encoding an integer gets, or
240    /// which Z3 theory -- is a modelling choice made per declaration, not part of the solver name.
241    /// Use `--heuristic` to steer those choices and `--channelling` to allow more than one per
242    /// declaration.
243    #[arg(
244        long,
245        value_name = "SOLVER",
246        value_parser = parse_solver_family,
247        default_value = "minion",
248        short = 's',
249        global = true,
250        help_heading = CONFIGURATION_HELP_HEADING
251    )]
252    pub solver: SolverFamily,
253
254    /// SAT backend to use with --solver sat (only compiled backends are available).
255    #[arg(long, value_enum, default_value_t = SatBackend::default(), global = true,
256        help_heading = CONFIGURATION_HELP_HEADING)]
257    pub sat_backend: SatBackend,
258
259    /// Pin the int-domain span threshold for using Minion `DISCRETE` variables.
260    ///
261    /// If maximum - minimum + 1 <= this value, emit `DISCRETE`; otherwise `BOUND`.
262    /// Constraints requiring `DISCRETE` override this choice. If omitted, the heuristic chooses
263    /// between 10, zero (all `BOUND`), and unlimited (all `DISCRETE`). Compact chooses 10.
264    #[arg(
265        long,
266        global = true,
267        help_heading = MODELLING_HELP_HEADING
268    )]
269    pub minion_discrete_threshold: Option<usize>,
270
271    /// Override Minion variable ordering.
272    ///
273    /// Possible values: `static`, `sdf`, `srf`, `ldf`, `random`, `conflict`, `wdeg`,
274    /// `domoverwdeg`.
275    #[arg(
276        long,
277        value_name = "ORDER",
278        value_parser = parse_minion_variable_order,
279        global = true,
280        help_heading = CONFIGURATION_HELP_HEADING
281    )]
282    pub minion_varorder: Option<MinionVariableOrder>,
283
284    /// Override Minion value ordering.
285    ///
286    /// Possible values: `ascend`, `descend`, `random`.
287    #[arg(
288        long,
289        value_name = "ORDER",
290        value_parser = parse_minion_value_order,
291        global = true,
292        help_heading = CONFIGURATION_HELP_HEADING
293    )]
294    pub minion_valorder: Option<MinionValueOrder>,
295
296    /// Save a solver input file to <filename>.
297    ///
298    /// This input file will be in a format compatible by the command-line
299    /// interface of the selected solver. For example, when the solver is Minion,
300    /// a valid .minion file will be output.
301    ///
302    /// This file is for informational purposes only; the results of running
303    /// this file cannot be used by Conjure Oxide in any way.
304    #[arg(long,global=true, value_names=["filename"], next_line_help=true, help_heading=LOGGING_HELP_HEADING)]
305    pub save_solver_input_file: Option<PathBuf>,
306
307    /// Stop the solver after the given cumulative wall-clock timeout.
308    ///
309    /// Minion has one-second timeout resolution, so finer durations are rounded up.
310    #[arg(long, global = true, help_heading = CONFIGURATION_HELP_HEADING)]
311    pub solver_timeout: Option<humantime::Duration>,
312
313    /// Write general logs to this file
314    #[arg(long, value_name = "PATH", global = true, help_heading = LOGGING_HELP_HEADING)]
315    pub log_file: Option<PathBuf>,
316
317    /// Format used by --log-file [default: text]
318    #[arg(long, value_enum, requires = "log_file", global = true, help_heading = LOGGING_HELP_HEADING)]
319    pub log_format: Option<LogFormat>,
320
321    /// Detail written by --log-file [default: stages]
322    #[arg(long, value_enum, requires = "log_file", global = true, help_heading = LOGGING_HELP_HEADING)]
323    pub log_detail: Option<LogDetail>,
324}
325
326impl GlobalArgs {
327    /// Convert command-line options into the library's modelling configuration.
328    pub(crate) fn library_config(&self) -> conjure_cp::pipeline::Config {
329        use conjure_cp::pipeline::{Config, TraceConfig};
330        Config {
331            rewriter: self.rewriter,
332            comprehension_expander: self.comprehension_expander,
333            solver: self.solver,
334            extra_rule_sets: self.extra_rule_sets.clone(),
335            heuristic: self.heuristic,
336            seed: self.seed,
337            responses: self.responses.clone(),
338            channelling: self.channelling,
339            amo_encoding: self.amo_encoding,
340            cardinality_encoding: self.cardinality_encoding,
341            pb_encoding: self.pb_encoding,
342            element_encoding: self.element_encoding,
343            table_encoding: self.table_encoding,
344            alldifferent_encoding: self.alldifferent_encoding,
345            minion_discrete_threshold: self.minion_discrete_threshold,
346            minion_varorder: self.minion_varorder,
347            minion_valorder: self.minion_valorder,
348            sat_backend: self.sat_backend,
349            solver_seed: self.solver_seed,
350            solver_timeout: self.solver_timeout.map(std::time::Duration::from),
351            trace: TraceConfig {
352                rules: self.rule_trace.is_some(),
353                attempts: self.rule_attempt_trace.is_some(),
354                aggregates: self.rule_trace_aggregates.is_some(),
355            },
356        }
357    }
358}
359
360#[derive(Clone, Copy, Debug, Default, ValueEnum)]
361pub enum LogFormat {
362    #[default]
363    Text,
364    Json,
365}
366
367#[derive(Clone, Copy, Debug, Default, ValueEnum)]
368pub enum LogDetail {
369    #[default]
370    Stages,
371    Applications,
372    Attempts,
373}
374
375#[derive(Debug, Clone, Args)]
376pub struct CompletionArgs {
377    /// Shell type for which to generate the completion script
378    #[arg(value_enum)]
379    pub shell: Shell,
380}
381
382#[derive(Debug, Clone, Copy, clap::ValueEnum)]
383pub enum ShellTypes {
384    Bash,
385    Zsh,
386    Fish,
387    PowerShell,
388    Elvish,
389}
390
391fn parse_comprehension_expander(input: &str) -> Result<QuantifiedExpander, String> {
392    input.parse()
393}
394
395fn parse_cli_heuristic(input: &str) -> Result<Heuristic, String> {
396    match input.parse::<Heuristic>()? {
397        Heuristic::All => {
398            Err("heuristic 'x' (all) is not supported by the command line yet".to_string())
399        }
400        heuristic => Ok(heuristic),
401    }
402}
403
404fn parse_cli_channelling(input: &str) -> Result<Channelling, String> {
405    input.parse::<Channelling>()
406}
407
408fn parse_rewriter(input: &str) -> Result<Rewriter, String> {
409    input.parse::<Rewriter>()
410}
411
412fn parse_solver_family(input: &str) -> Result<SolverFamily, String> {
413    let family = input.parse()?;
414    if family == SolverFamily::Z3 && !cfg!(feature = "z3") {
415        return Err("Z3 solver support was not compiled in (enable the `z3` feature).".into());
416    }
417    Ok(family)
418}
419
420fn parse_minion_value_order(input: &str) -> Result<MinionValueOrder, String> {
421    match input {
422        "ascend" => Ok(MinionValueOrder::Ascend),
423        "descend" => Ok(MinionValueOrder::Descend),
424        "random" => Ok(MinionValueOrder::Random),
425        other => Err(format!(
426            "unknown minion value order '{other}', expected one of: ascend, descend, random"
427        )),
428    }
429}
430
431fn parse_minion_variable_order(input: &str) -> Result<MinionVariableOrder, String> {
432    match input {
433        "static" => Ok(MinionVariableOrder::Static),
434        "sdf" => Ok(MinionVariableOrder::SmallestDomainFirst),
435        "srf" => Ok(MinionVariableOrder::SmallestRatioFirst),
436        "ldf" => Ok(MinionVariableOrder::LargestDomainFirst),
437        "random" => Ok(MinionVariableOrder::Random),
438        "conflict" => Ok(MinionVariableOrder::Conflict),
439        "wdeg" => Ok(MinionVariableOrder::WeightedDegree),
440        "domoverwdeg" => Ok(MinionVariableOrder::DomainOverWeightedDegree),
441        other => Err(format!(
442            "unknown minion variable order '{other}', expected one of: static, sdf, srf, ldf, \
443             random, conflict, wdeg, domoverwdeg"
444        )),
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451
452    #[test]
453    fn sat_backend_defaults_to_available_native_backend() {
454        let cli =
455            Cli::try_parse_from(["conjure-oxide", "solve", "model.essence", "--solver", "sat"])
456                .unwrap();
457        #[cfg(all(feature = "sat-cadical", not(target_family = "wasm")))]
458        assert_eq!(cli.global_args.sat_backend, SatBackend::Cadical);
459        #[cfg(not(all(feature = "sat-cadical", not(target_family = "wasm"))))]
460        assert_eq!(cli.global_args.sat_backend, SatBackend::Batsat);
461    }
462
463    #[test]
464    fn sat_backend_option_accepts_only_compiled_backends() {
465        for name in ["cadical", "batsat"] {
466            let result = Cli::try_parse_from([
467                "conjure-oxide",
468                "solve",
469                "model.essence",
470                "--solver",
471                "sat",
472                "--sat-backend",
473                name,
474            ]);
475            let available = SatBackend::value_variants()
476                .iter()
477                .find(|backend| backend.to_string() == name);
478            match available {
479                Some(backend) => assert_eq!(result.unwrap().global_args.sat_backend, *backend),
480                None => assert_eq!(
481                    result.unwrap_err().kind(),
482                    clap::error::ErrorKind::InvalidValue
483                ),
484            }
485        }
486    }
487
488    #[cfg(not(feature = "z3"))]
489    #[test]
490    fn selecting_z3_without_support_reports_the_missing_feature() {
491        let error =
492            Cli::try_parse_from(["conjure-oxide", "solve", "model.essence", "--solver", "z3"])
493                .unwrap_err();
494        assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
495        assert!(
496            error
497                .to_string()
498                .contains("Z3 solver support was not compiled in")
499        );
500    }
501
502    /// Regression test for #1631: `--version` used to fail as it requires a subcommand.
503    #[test]
504    fn version_flag_works_without_a_subcommand() {
505        for flag in ["--version", "-V"] {
506            let err = Cli::try_parse_from(["conjure-oxide", flag]).unwrap_err();
507            assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
508            assert!(err.to_string().starts_with("conjure-oxide "));
509        }
510    }
511
512    #[test]
513    fn compact_is_the_default_cli_heuristic() {
514        let cli = Cli::try_parse_from(["conjure-oxide", "solve", "model.essence"]).unwrap();
515        assert_eq!(cli.global_args.heuristic, Heuristic::Compact);
516    }
517
518    #[test]
519    fn auto_is_the_default_comprehension_expander() {
520        let cli = Cli::try_parse_from(["conjure-oxide", "solve", "model.essence"]).unwrap();
521        assert_eq!(
522            cli.global_args.comprehension_expander,
523            QuantifiedExpander::Auto
524        );
525    }
526
527    #[test]
528    fn solver_seed_defaults_to_zero_and_can_be_overridden() {
529        let cli = Cli::try_parse_from(["conjure-oxide", "solve", "model.essence"]).unwrap();
530        assert_eq!(cli.global_args.solver_seed, 0);
531
532        let cli = Cli::try_parse_from([
533            "conjure-oxide",
534            "solve",
535            "model.essence",
536            "--solver-seed",
537            "42",
538        ])
539        .unwrap();
540        assert_eq!(cli.global_args.solver_seed, 42);
541    }
542
543    #[test]
544    fn parses_all_minion_variable_orders() {
545        let cases = [
546            ("static", MinionVariableOrder::Static),
547            ("sdf", MinionVariableOrder::SmallestDomainFirst),
548            ("srf", MinionVariableOrder::SmallestRatioFirst),
549            ("ldf", MinionVariableOrder::LargestDomainFirst),
550            ("random", MinionVariableOrder::Random),
551            ("conflict", MinionVariableOrder::Conflict),
552            ("wdeg", MinionVariableOrder::WeightedDegree),
553            ("domoverwdeg", MinionVariableOrder::DomainOverWeightedDegree),
554        ];
555
556        for (name, expected) in cases {
557            let cli = Cli::try_parse_from([
558                "conjure-oxide",
559                "solve",
560                "model.essence",
561                "--minion-varorder",
562                name,
563            ])
564            .unwrap();
565            assert_eq!(cli.global_args.minion_varorder, Some(expected));
566        }
567    }
568}