Skip to main content

hax_types/cli_options/
mod.rs

1use crate::prelude::*;
2
3use clap::{Parser, Subcommand, ValueEnum};
4use std::fmt;
5
6pub use hax_frontend_exporter_options::*;
7pub mod extension;
8use extension::Extension;
9
10#[derive_group(Serializers)]
11#[derive(JsonSchema, Debug, Clone, Eq, PartialEq)]
12pub enum DebugEngineMode {
13    File(PathOrDash),
14    Interactive,
15}
16
17impl std::convert::From<&str> for DebugEngineMode {
18    fn from(s: &str) -> Self {
19        match s {
20            "i" | "interactively" => DebugEngineMode::Interactive,
21            s => DebugEngineMode::File(s.strip_prefix("file:").unwrap_or(s).into()),
22        }
23    }
24}
25
26#[derive_group(Serializers)]
27#[derive(JsonSchema, Debug, Clone, Default)]
28pub struct ForceCargoBuild {
29    pub data: u64,
30}
31
32impl std::convert::From<&str> for ForceCargoBuild {
33    fn from(s: &str) -> Self {
34        use std::time::{SystemTime, UNIX_EPOCH};
35        if s == "false" {
36            let data = SystemTime::now()
37                .duration_since(UNIX_EPOCH)
38                .map(|r| r.as_millis())
39                .unwrap_or(0);
40            ForceCargoBuild { data: data as u64 }
41        } else {
42            ForceCargoBuild::default()
43        }
44    }
45}
46
47#[derive_group(Serializers)]
48#[derive(Debug, Clone, JsonSchema, Eq, PartialEq)]
49pub enum PathOrDash {
50    Dash,
51    Path(PathBuf),
52}
53
54impl std::convert::From<&str> for PathOrDash {
55    fn from(s: &str) -> Self {
56        match s {
57            "-" => PathOrDash::Dash,
58            _ => PathOrDash::Path(PathBuf::from(s)),
59        }
60    }
61}
62
63impl PathOrDash {
64    pub fn open_or_stdout(&self) -> Box<dyn std::io::Write> {
65        use std::io::BufWriter;
66        match self {
67            PathOrDash::Dash => Box::new(BufWriter::new(std::io::stdout())),
68            PathOrDash::Path(path) => {
69                Box::new(BufWriter::new(std::fs::File::create(&path).unwrap()))
70            }
71        }
72    }
73    pub fn map_path<F: FnOnce(&Path) -> PathBuf>(&self, f: F) -> Self {
74        match self {
75            PathOrDash::Path(path) => PathOrDash::Path(f(path)),
76            PathOrDash::Dash => PathOrDash::Dash,
77        }
78    }
79}
80
81fn absolute_path(path: impl AsRef<std::path::Path>) -> std::io::Result<std::path::PathBuf> {
82    use path_clean::PathClean;
83    let path = path.as_ref();
84
85    let absolute_path = if path.is_absolute() {
86        path.to_path_buf()
87    } else {
88        std::env::current_dir()?.join(path)
89    }
90    .clean();
91
92    Ok(absolute_path)
93}
94
95pub trait NormalizePaths {
96    fn normalize_paths(&mut self);
97}
98
99impl NormalizePaths for PathBuf {
100    fn normalize_paths(&mut self) {
101        *self = absolute_path(&self).unwrap();
102    }
103}
104impl NormalizePaths for PathOrDash {
105    fn normalize_paths(&mut self) {
106        match self {
107            PathOrDash::Path(p) => p.normalize_paths(),
108            PathOrDash::Dash => (),
109        }
110    }
111}
112
113#[derive_group(Serializers)]
114#[derive(JsonSchema, Parser, Debug, Hash, Clone, Eq, PartialEq)]
115pub struct ProVerifOptions {
116    /// Items for which hax should extract a default-valued process
117    /// macro with a corresponding type signature. This flag expects a
118    /// space-separated list of inclusion clauses. An inclusion clause
119    /// is a Rust path prefixed with `+`, `+!` or `-`. `-` means
120    /// implementation only, `+!` means interface only and `+` means
121    /// implementation and interface. Rust path chunks can be either a
122    /// concrete string, or a glob (just like bash globs, but with
123    /// Rust paths).
124    #[arg(
125        long,
126        value_parser = parse_inclusion_clause,
127        value_delimiter = ' ',
128        allow_hyphen_values(true)
129    )]
130    pub assume_items: Vec<InclusionClause>,
131
132    /// Model `Result::Err` values. By default, a `Result<T, E>` is
133    /// modelled by its `Ok` payload alone and producing an `Err` ends
134    /// the trace: error paths are pruned, which keeps the state space
135    /// small. With this flag, `Ok` and `Err` are kept as constructors,
136    /// so error paths stay reachable. The extracted model then needs
137    /// `result_errors.pvl` instead of `result.pvl`.
138    #[arg(long)]
139    pub result_errors: bool,
140
141    /// Trait items whose calls hax keeps as calls of the trait item,
142    /// rather than of the impl they dispatch to, so that a hand-written
143    /// library can model them once for every impl. This flag expects a
144    /// space-separated list of Rust paths, whose chunks can be globs
145    /// (e.g. `tls_codec::**`).
146    #[arg(long, value_delimiter = ' ')]
147    pub keep_trait_calls: Vec<String>,
148}
149
150impl ProVerifOptions {
151    /// The flag rendering of these options, as `cargo hax extract
152    /// --dry-run` prints it. Lives next to the fields so a new or renamed
153    /// option is reflected here.
154    pub fn flags(&self) -> Vec<String> {
155        let mut flags = Vec::new();
156        if !self.assume_items.is_empty() {
157            flags.push("--assume-items".to_string());
158            flags.extend(self.assume_items.iter().map(ToString::to_string));
159        }
160        if self.result_errors {
161            flags.push("--result-errors".to_string());
162        }
163        if !self.keep_trait_calls.is_empty() {
164            flags.push("--keep-trait-calls".to_string());
165            flags.extend(self.keep_trait_calls.iter().cloned());
166        }
167        flags
168    }
169}
170
171/// The defaults of the F* flags below, shared with
172/// [`FStarOptions::defaults`] so the two cannot diverge.
173const FSTAR_DEFAULT_Z3RLIMIT: u32 = 15;
174const FSTAR_DEFAULT_FUEL: u32 = 0;
175const FSTAR_DEFAULT_IFUEL: u32 = 1;
176const FSTAR_DEFAULT_LINE_WIDTH: u16 = 100;
177
178#[derive_group(Serializers)]
179#[derive(JsonSchema, Parser, Debug, Hash, Clone, Eq, PartialEq)]
180pub struct FStarOptions {
181    /// Set the Z3 per-query resource limit
182    #[arg(long, default_value_t = FSTAR_DEFAULT_Z3RLIMIT)]
183    pub z3rlimit: u32,
184    /// Number of unrolling of recursive functions to try
185    #[arg(long, default_value_t = FSTAR_DEFAULT_FUEL)]
186    pub fuel: u32,
187    /// Number of unrolling of inductive datatypes to try
188    #[arg(long, default_value_t = FSTAR_DEFAULT_IFUEL)]
189    pub ifuel: u32,
190    /// Modules for which Hax should extract interfaces (`*.fsti`
191    /// files) in supplement to implementations (`*.fst` files). By
192    /// default we extract no interface, only implementations. If a
193    /// item is signature only (see the `+:` prefix of the
194    /// `--include_namespaces` flag of the `into` subcommand), then
195    /// its namespace is extracted with an interface. This flag
196    /// expects a space-separated list of inclusion clauses. An
197    /// inclusion clause is a Rust path prefixed with `+`, `+!` or
198    /// `-`. `-` means implementation only, `+!` means interface only
199    /// and `+` means implementation and interface. Rust path chunks
200    /// can be either a concrete string, or a glob (just like bash
201    /// globs, but with Rust paths).
202    #[arg(
203        long,
204        value_parser = parse_inclusion_clause,
205        value_delimiter = ' ',
206        allow_hyphen_values(true)
207    )]
208    pub interfaces: Vec<InclusionClause>,
209
210    #[arg(long, default_value_t = FSTAR_DEFAULT_LINE_WIDTH, env = "HAX_FSTAR_LINE_WIDTH")]
211    pub line_width: u16,
212}
213
214impl FStarOptions {
215    /// The flags' defaults. Proof scenarios resolve absent keys to these;
216    /// environment-supplied flag defaults (`HAX_FSTAR_LINE_WIDTH`)
217    /// deliberately do not apply to scenario runs.
218    pub fn defaults() -> Self {
219        Self {
220            z3rlimit: FSTAR_DEFAULT_Z3RLIMIT,
221            fuel: FSTAR_DEFAULT_FUEL,
222            ifuel: FSTAR_DEFAULT_IFUEL,
223            interfaces: Vec::new(),
224            line_width: FSTAR_DEFAULT_LINE_WIDTH,
225        }
226    }
227
228    /// The flag rendering of these options, as `cargo hax extract
229    /// --dry-run` prints it. Lives next to the fields so a new or renamed
230    /// option is reflected here.
231    pub fn flags(&self) -> Vec<String> {
232        let mut flags = vec![
233            format!("--z3rlimit={}", self.z3rlimit),
234            format!("--fuel={}", self.fuel),
235            format!("--ifuel={}", self.ifuel),
236            format!("--line-width={}", self.line_width),
237        ];
238        if !self.interfaces.is_empty() {
239            flags.push("--interfaces".to_string());
240            flags.extend(self.interfaces.iter().map(ToString::to_string));
241        }
242        flags
243    }
244}
245
246/// The inputs a proof scenario resolves for the Lean backend, carried
247/// through the `__json` re-entry rather than argv: verbatim argument
248/// arrays (no shell splitting), the compiled item selection, and the
249/// package-layout overrides. Empty on flag-driven `into` invocations.
250#[derive_group(Serializers)]
251#[derive(JsonSchema, Debug, Clone, Hash, Eq, PartialEq, Default)]
252pub struct LeanScenarioOptions {
253    /// The Lean package name, overriding the crate-name derivation.
254    pub package_name: Option<String>,
255    /// The scenario's `project-files` key, overriding the top-level key.
256    pub project_files: Option<bool>,
257    /// Charon name patterns compiled to `--start-from`.
258    pub include: Vec<String>,
259    /// Charon name patterns compiled to `--exclude`.
260    pub exclude: Vec<String>,
261    /// Charon name patterns compiled to `--opaque`, the default opaque
262    /// set already merged in.
263    pub opaque: Vec<String>,
264    /// Verbatim extra charon arguments, one element per process argument.
265    pub charon_args: Vec<String>,
266    /// Verbatim extra aeneas arguments, one element per process argument.
267    pub aeneas_args: Vec<String>,
268    /// Cargo arguments (feature selection) for the cargo invocation
269    /// charon drives.
270    pub cargo_args: Vec<String>,
271}
272
273impl LeanScenarioOptions {
274    /// The charon flags compiled from the unified item-selection keys.
275    /// Both the real charon invocation and the `--dry-run` display use
276    /// this compilation, so the two cannot diverge.
277    pub fn selection_flags(&self) -> Vec<String> {
278        [
279            ("start-from", &self.include),
280            ("exclude", &self.exclude),
281            ("opaque", &self.opaque),
282        ]
283        .into_iter()
284        .flat_map(|(flag, patterns)| {
285            patterns
286                .iter()
287                .map(move |pattern| format!("--{flag}={pattern}"))
288        })
289        .collect()
290    }
291}
292
293#[derive_group(Serializers)]
294#[derive(JsonSchema, Parser, Debug, Clone, Hash, Eq, PartialEq)]
295#[command(after_help = "\
296TOOLS:
297  This backend runs `charon`, then `aeneas`, and generates a Lean proof project.
298  Tool versions are managed by hax: each tool resolves through, in order, the
299  project's `hax.toml` (member crate, then workspace root) and the built-in
300  default version this release was tested with, and is downloaded into the
301  tool cache on demand with checksum verification.
302
303  Inspect the active versions and their sources with `cargo hax tools show`;
304  pre-install them with `cargo hax tools install`.
305
306INVOCATION:
307  The tools are run with some fixed flags (to which any --charon-args/--aeneas-args
308  are appended). Pass `-v` (`cargo hax into -v lean`) to print the exact command
309  before each tool runs.
310
311  Overriding a flag that controls where output is written (aeneas's -backend,
312  -dest, -subdir, or -split-files) may break the extraction or the generated
313  proof project. Charon's --dest-file is reserved and rejected: aeneas is always
314  run on the LLBC file hax chooses. Overriding -dest or -subdir additionally disables
315  the generation and checking of the Lean package files and the clearing of stale
316  extraction files, since hax no longer knows the package layout. Committing
317  `project-files = false` in `hax.toml` disables the package files for every
318  invocation.
319
320  To use a binary you built yourself, commit a `path` entry for the tool in
321  `hax.toml` instead of a version.")]
322pub struct LeanOptions {
323    /// Extra arguments forwarded to charon. Parsed with shell-style quoting,
324    /// so values containing spaces can be single- or double-quoted.
325    /// Example: --charon-args="--opaque '{impl Serialize for _}'"
326    #[arg(long)]
327    pub charon_args: Option<String>,
328
329    /// Extra arguments forwarded to aeneas. Parsed with shell-style quoting.
330    /// Example: --aeneas-args="-split-files"
331    #[arg(long)]
332    pub aeneas_args: Option<String>,
333
334    /// The scenario-resolved inputs; not settable from the command line.
335    #[clap(skip)]
336    pub scenario: LeanScenarioOptions,
337}
338
339#[derive_group(Serializers)]
340#[derive(JsonSchema, Subcommand, Debug, Clone, Hash, Eq, PartialEq)]
341pub enum Backend {
342    /// Use the F* backend
343    Fstar(FStarOptions),
344    /// Use the legacy Lean backend (warning: experimental)
345    LegacyLean,
346    /// Use the Lean backend (charon + aeneas pipeline)
347    Lean(LeanOptions),
348    /// Use the Coq backend
349    Coq,
350    /// Use the SSProve backend
351    Ssprove,
352    /// Use the EasyCrypt backend (warning: work in progress!)
353    Easycrypt,
354    /// Use the ProVerif backend (warning: work in progress!)
355    #[clap(name = "proverif", alias = "pro-verif")]
356    ProVerif(ProVerifOptions),
357    /// Use the Rust backend (warning: work in progress!)
358    #[clap(hide = true)]
359    Rust,
360    /// Extract `DefId`s of the crate as a Rust module tree.
361    /// This is a command that regenerates code for the rust engine.
362    #[clap(hide = true)]
363    GenerateRustEngineNames,
364    /// A debugger for the Rust engine
365    Debugger {
366        #[arg(long, short)]
367        interactive: bool,
368    },
369}
370
371impl fmt::Display for Backend {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        BackendName::from(self).fmt(f)
374    }
375}
376
377#[derive_group(Serializers)]
378#[derive(JsonSchema, Debug, Hash, Clone, Eq, PartialEq)]
379pub enum DepsKind {
380    Transitive,
381    Shallow,
382    None,
383}
384
385#[derive_group(Serializers)]
386#[derive(JsonSchema, Debug, Hash, Clone, Eq, PartialEq)]
387pub enum InclusionKind {
388    /// `+query` include the items selected by `query`
389    Included(DepsKind),
390    SignatureOnly,
391    Excluded,
392}
393
394#[derive_group(Serializers)]
395#[derive(JsonSchema, Debug, Hash, Clone, Eq, PartialEq)]
396pub struct InclusionClause {
397    pub kind: InclusionKind,
398    pub namespace: Namespace,
399}
400
401const PREFIX_INCLUDED_TRANSITIVE: &str = "+";
402const PREFIX_INCLUDED_SHALLOW: &str = "+~";
403const PREFIX_INCLUDED_NONE: &str = "+!";
404const PREFIX_SIGNATURE_ONLY: &str = "+:";
405const PREFIX_EXCLUDED: &str = "-";
406
407impl ToString for InclusionClause {
408    fn to_string(&self) -> String {
409        let kind = match self.kind {
410            InclusionKind::Included(DepsKind::Transitive) => PREFIX_INCLUDED_TRANSITIVE,
411            InclusionKind::Included(DepsKind::Shallow) => PREFIX_INCLUDED_SHALLOW,
412            InclusionKind::Included(DepsKind::None) => PREFIX_INCLUDED_NONE,
413            InclusionKind::SignatureOnly => PREFIX_SIGNATURE_ONLY,
414            InclusionKind::Excluded => PREFIX_EXCLUDED,
415        };
416        format!("{kind}{}", self.namespace.to_string())
417    }
418}
419
420pub fn parse_inclusion_clause(
421    s: &str,
422) -> Result<InclusionClause, Box<dyn std::error::Error + Send + Sync + 'static>> {
423    let s = s.trim();
424    if s.is_empty() {
425        Err("Expected `-` or `+`, got an empty string")?
426    }
427    let (prefix, namespace) = {
428        let f = |&c: &char| matches!(c, '+' | '-' | '~' | '!' | ':');
429        (
430            s.chars().take_while(f).into_iter().collect::<String>(),
431            s.chars().skip_while(f).into_iter().collect::<String>(),
432        )
433    };
434    let kind = match &prefix[..] {
435        PREFIX_INCLUDED_TRANSITIVE => InclusionKind::Included(DepsKind::Transitive),
436        PREFIX_INCLUDED_SHALLOW => InclusionKind::Included(DepsKind::Shallow),
437        PREFIX_INCLUDED_NONE => InclusionKind::Included(DepsKind::None),
438        PREFIX_SIGNATURE_ONLY => InclusionKind::SignatureOnly,
439        PREFIX_EXCLUDED => InclusionKind::Excluded,
440        prefix => Err(format!(
441            "Expected `+`, `+~`, `+!`, `+:` or `-`, got an `{prefix}`"
442        ))?,
443    };
444    Ok(InclusionClause {
445        kind,
446        namespace: namespace.to_string().into(),
447    })
448}
449
450#[derive_group(Serializers)]
451#[derive(JsonSchema, Parser, Debug, Clone, Eq, PartialEq)]
452pub struct TranslationOptions {
453    /// Controls which Rust item should be extracted or not.
454    ///
455    /// This is a space-separated list of patterns prefixed with a
456    /// modifier, read from the left to the right.
457    ///
458    /// A pattern is a Rust path (say `mycrate::mymod::myfn`) where
459    /// globs are allowed: `*` matches any name
460    /// (e.g. `mycrate::mymod::myfn` is matched by
461    /// `mycrate::*::myfn`), while `**` matches any subpath, empty
462    /// included (e.g. `mycrate::mymod::myfn` is matched by
463    /// `**::myfn`).
464
465    /// By default, hax includes all items. Then, the patterns
466    /// prefixed by modifiers are processed from left to right,
467    /// excluding or including items. Each pattern selects a number of
468    /// item. The modifiers are:
469
470    /// {n}{n} - `+`: includes the selected items with their
471    /// dependencies, transitively (e.g. if function `f` calls `g`
472    /// which in turn calls `h`, then `+k::f` includes `f`, `g` and
473    /// `h`)
474
475    /// {n} - `+~`: includes the selected items with their direct
476    /// dependencies only (following the previous example, `+~k::f`
477    /// would select `f` and `g`, but not `h`)
478
479    /// {n} - `+!`: includes the selected items, without their
480    /// dependencies (`+!k::f` would only select `f`)
481
482    /// {n} - `+:`: only includes the type of the selected items (no
483    /// dependencies). This includes full struct and enums, but only
484    /// the type signature of functions and trait impls (except when
485    /// they contain associated types), dropping their bodies.
486    #[arg(
487        value_parser = parse_inclusion_clause,
488        value_delimiter = ' ',
489    )]
490    #[arg(short, allow_hyphen_values(true))]
491    pub include_namespaces: Vec<InclusionClause>,
492}
493
494#[derive_group(Serializers)]
495#[derive(JsonSchema, Parser, Debug, Clone, Eq, PartialEq)]
496pub struct BackendOptions<E: Extension> {
497    #[command(subcommand)]
498    pub backend: Backend,
499
500    /// Don't write anything on disk. Output everything as JSON to stdout
501    /// instead.
502    #[arg(long = "dry-run")]
503    pub dry_run: bool,
504
505    /// Verbose mode for the Hax engine. Set `-vv` for maximal verbosity.
506    #[arg(short, long, action = clap::ArgAction::Count)]
507    pub verbose: u8,
508
509    /// Prints statistics about how many items have been translated
510    /// successfully by the engine.
511    #[arg(long)]
512    pub stats: bool,
513
514    /// Enables profiling for the engine: for each phase of the
515    /// engine, time and memory usage are recorded and reported.
516    #[arg(long)]
517    pub profile: bool,
518
519    /// Prune Rust items that are not under the provided top-level module name.
520    /// This will effectively remove all items that don't match `*::<prune_haxmetadata>::**`.
521    /// This prunning occurs directly on the `haxmeta` file, in the frontend.
522    /// This is independent from any engine options.
523    #[arg(long)]
524    #[clap(hide = true)]
525    pub prune_haxmeta: Option<String>,
526
527    /// Enable engine debugging: dumps the AST at each phase.
528    ///
529    /// The value of `<DEBUG_ENGINE>` can be either:
530
531    /// {n}{n} - `interactive` (or `i`): enables debugging of the engine,
532    /// and visualize interactively in a webapp how a crate was
533    /// transformed by each phase, both in Rust-like syntax and
534    /// browsing directly the internal AST. By default, the webapp is
535    /// hosted on `http://localhost:8000`, the port can be override by
536    /// setting the `HAX_DEBUGGER_PORT` environment variable.
537
538    /// {n} - `<FILE>` or `file:<FILE>`: outputs the different AST as JSON
539    /// to `<FILE>`. `<FILE>` can be either [-] or a path.
540    #[arg(short, long = "debug-engine")]
541    pub debug_engine: Option<DebugEngineMode>,
542
543    /// Extract type aliases. This is disabled by default, since
544    /// extracted terms depends on expanded types rather than on type
545    /// aliases. Turning this option on is discouraged: Rust type
546    /// synonyms can ommit generic bounds, which are ususally
547    /// necessary in the hax backends, leading to typechecking
548    /// errors. For more details see
549    /// https://github.com/pereq-dev/hax/issues/708.
550    #[arg(long)]
551    pub extract_type_aliases: bool,
552
553    #[command(flatten)]
554    pub translation_options: TranslationOptions,
555
556    /// Where to put the output files resulting from the translation.
557    /// Defaults to "<crate folder>/proofs/<backend>/extraction".
558    #[arg(long)]
559    pub output_dir: Option<PathBuf>,
560
561    #[group(flatten)]
562    pub cli_extension: E::BackendOptions,
563}
564
565/// Cargo's hermeticity flags, applied to every cargo invocation a
566/// `cargo hax extract` run drives: project discovery, the frontend's
567/// `cargo check`, and the build charon drives.
568#[derive_group(Serializers)]
569#[derive(JsonSchema, Parser, Debug, Clone, Default, Eq, PartialEq)]
570pub struct CargoHermeticityOptions {
571    /// Assert that `Cargo.lock` will remain unchanged
572    #[arg(long)]
573    pub locked: bool,
574
575    /// Run without accessing the network
576    #[arg(long)]
577    pub offline: bool,
578
579    /// Equivalent to specifying both --locked and --offline
580    #[arg(long)]
581    pub frozen: bool,
582}
583
584impl CargoHermeticityOptions {
585    /// The cargo flags these options stand for, verbatim.
586    pub fn flags(&self) -> Vec<String> {
587        [
588            ("--locked", self.locked),
589            ("--offline", self.offline),
590            ("--frozen", self.frozen),
591        ]
592        .into_iter()
593        .filter(|(_, set)| *set)
594        .map(|(flag, _)| flag.to_string())
595        .collect()
596    }
597}
598
599#[derive_group(Serializers)]
600#[derive(JsonSchema, Subcommand, Debug, Clone, Eq, PartialEq)]
601pub enum Command<E: Extension> {
602    /// Translate to a backend. The translated modules will be written
603    /// under the directory `<PKG>/proofs/<BACKEND>/extraction`, where
604    /// `<PKG>` is the translated cargo package name and `<BACKEND>`
605    /// the name of the backend.
606    #[clap(name = "into")]
607    Backend(BackendOptions<E>),
608
609    /// Run the proof scenarios declared in `hax.toml` (`[scenario.<name>]`
610    /// tables): named, complete extraction configurations. Without names,
611    /// every scenario in scope runs. Scenarios run sequentially; a failing
612    /// scenario does not abort the run, failures are reported in a summary
613    /// and produce a non-zero exit code.
614    Extract {
615        /// The scenarios to run. Each name selects every scenario with
616        /// that name in scope. Absent, every scenario in scope runs.
617        names: Vec<String>,
618
619        /// Restrict the scope to the scenarios extracting the given
620        /// package. May be repeated.
621        #[arg(short = 'p', long = "package")]
622        packages: Vec<String>,
623
624        /// Print the resolved invocations, including the arguments
625        /// compiled from the scenarios, without running them.
626        #[arg(long)]
627        dry_run: bool,
628
629        /// Verbose mode, forwarded to each scenario run.
630        #[arg(short, long, action = clap::ArgAction::Count)]
631        verbose: u8,
632
633        #[command(flatten)]
634        hermeticity: CargoHermeticityOptions,
635    },
636
637    /// Export directly as a JSON file
638    JSON {
639        /// Path to the output JSON file, "-" denotes stdout.
640        #[arg(
641            short,
642            long = "output-file",
643            default_value = "hax_frontend_export.json"
644        )]
645        output_file: PathOrDash,
646        /// Whether the bodies are exported as THIR, built MIR, const
647        /// MIR, or a combination. Repeat this option to extract a
648        /// combination (e.g. `-k thir -k mir-built`). Pass `--kind`
649        /// alone with no value to disable body extraction.
650        #[arg(
651            value_enum,
652            short,
653            long = "kind",
654            num_args = 0..=3,
655            default_values_t = [ExportBodyKind::Thir]
656        )]
657        kind: Vec<ExportBodyKind>,
658
659        /// By default, `cargo hax json` outputs a JSON where every
660        /// piece of information is inlined. This however creates very
661        /// large JSON files. This flag enables the use of unique IDs
662        /// and outputs a map from IDs to actual objects.
663        #[arg(long)]
664        use_ids: bool,
665
666        /// Whether to include extra informations about `DefId`s.
667        #[arg(short = 'E', long = "include-extra", default_value = "false")]
668        include_extra: bool,
669    },
670
671    /// Serialize to a `haxmeta` file, the internal binary format used by hax to
672    /// store the ASTs produced by the hax exporter.
673    #[clap(hide = true)]
674    Serialize {
675        /// Whether the bodies are exported as THIR, built MIR, const
676        /// MIR, or a combination. Repeat this option to extract a
677        /// combination (e.g. `-k thir -k mir-built`). Pass `--kind`
678        /// alone with no value to disable body extraction.
679        #[arg(
680            value_enum,
681            short,
682            long = "kind",
683            num_args = 0..=3,
684            default_values_t = [ExportBodyKind::Thir]
685        )]
686        kind: Vec<ExportBodyKind>,
687
688        /// When extracting to a given backend, the exporter is called with different `cfg` options.
689        /// This option allows to set the same flags as `cargo hax into` would pick.
690        #[arg(short)]
691        backend: Option<BackendName>,
692    },
693
694    /// Manage the external tools hax depends on (e.g. charon and aeneas).
695    #[command(subcommand)]
696    Tools(ToolsCommand),
697
698    #[command(flatten)]
699    CliExtension(E::Command),
700}
701
702/// Subcommands of `cargo hax tools`.
703#[derive_group(Serializers)]
704#[derive(JsonSchema, Subcommand, Debug, Clone, Eq, PartialEq)]
705pub enum ToolsCommand {
706    /// Download and cache the tool versions the current project
707    /// resolves to, or a specific `<tool>@<version>`.
708    Install {
709        /// A `<tool>@<version>` specification (e.g.
710        /// `charon@nightly-2026.07.01`) to install into the
711        /// machine-wide cache. When absent, installs what the current
712        /// project's configuration resolves to.
713        spec: Option<String>,
714        /// Re-download and verify even if the version is already cached
715        /// (e.g. to verify a copy installed before its checksum shipped).
716        #[arg(long)]
717        force: bool,
718    },
719    /// List the tool versions this release of hax can install with
720    /// checksum verification.
721    List {
722        /// Restrict the listing to one tool.
723        tool: Option<String>,
724        /// Only show versions present in the local cache.
725        #[arg(long)]
726        installed: bool,
727        /// Show every version instead of only the most recent ones.
728        #[arg(long)]
729        all: bool,
730    },
731    /// Show which tool versions are active in the current project,
732    /// and where each one comes from.
733    Show,
734    /// Remove a tool version from the machine-wide cache.
735    Remove {
736        /// The `<tool>@<version>` specification (e.g.
737        /// `charon@nightly-2026.07.01`) to remove from the cache.
738        spec: String,
739    },
740    /// Delete the entire tool cache. Later runs download what they need
741    /// again.
742    Clean,
743    /// Write version pins into the project's `hax.toml`, creating the
744    /// file when missing.
745    Pin {
746        /// A `<name>@<version>` specification to write as one entry,
747        /// accepting managed tools (e.g. `charon@nightly-2026.07.01`)
748        /// and declared versions (e.g. `lean@leanprover/lean4:v4.31.0`).
749        /// When absent, pins the built-in defaults of this release.
750        spec: Option<String>,
751    },
752}
753
754impl<E: Extension> Command<E> {
755    pub fn body_kinds(&self) -> Vec<ExportBodyKind> {
756        match self {
757            Command::JSON { kind, .. } => kind.clone(),
758            Command::Serialize { kind, .. } => kind.clone(),
759            Command::Backend { .. }
760            | Command::Extract { .. }
761            | Command::Tools { .. }
762            | Command::CliExtension { .. } => {
763                vec![ExportBodyKind::Thir]
764            }
765        }
766    }
767    pub fn backend_name(&self) -> Option<BackendName> {
768        match self {
769            Command::Backend(backend_options) => Some((&backend_options.backend).into()),
770            Command::JSON { .. } => None,
771            Command::Serialize { backend, .. } => backend.clone(),
772            Command::Extract { .. } => None,
773            Command::Tools(_) => None,
774            Command::CliExtension(_) => None,
775        }
776    }
777}
778
779#[derive_group(Serializers)]
780#[derive(JsonSchema, ValueEnum, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
781pub enum ExportBodyKind {
782    Thir,
783    MirBuilt,
784}
785
786#[derive_group(Serializers)]
787#[derive(JsonSchema, Parser, Debug, Clone)]
788#[command(
789    author,
790    version = crate::HAX_VERSION,
791    long_version = concat!("\nversion=", env!("HAX_VERSION"), "\n", "commit=", env!("HAX_GIT_COMMIT_HASH")),
792    name = "hax",
793    about,
794    long_about = None
795)]
796pub struct ExtensibleOptions<E: Extension> {
797    /// Semi-colon terminated list of arguments to pass to the
798    /// `cargo build` invocation. For example, to apply this
799    /// program on a package `foo`, use `-C -p foo ;`. (make sure
800    /// to escape `;` correctly in your shell)
801    #[arg(default_values = Vec::<&str>::new(), short='C', allow_hyphen_values=true, num_args=1.., long="cargo-args", value_terminator=";")]
802    pub cargo_flags: Vec<String>,
803
804    #[command(subcommand)]
805    pub command: Command<E>,
806
807    /// `cargo` caching is enable by default, this flag disables it.
808    #[arg(long="disable-cargo-cache", action=clap::builder::ArgAction::SetFalse)]
809    pub force_cargo_build: ForceCargoBuild,
810
811    /// Apply the command to every local package of the dependency closure. By
812    /// default, the command is only applied to the primary packages (i.e. the
813    /// package(s) of the current directory, or the ones selected with cargo
814    /// options like `-C -p <PKG> ;`).
815    #[arg(long = "deps")]
816    pub deps: bool,
817
818    /// Provide a precomputed haxmeta file explicitly.
819    /// Setting this option bypasses rustc and the exporter altogether.
820    #[arg(long)]
821    #[clap(hide = true)]
822    pub haxmeta: Option<PathBuf>,
823
824    /// By default, hax uses `$CARGO_TARGET_DIR/hax` as target folder,
825    /// to avoid recompilation when working both with `cargo hax` and
826    /// `cargo build` (or, e.g. `rust-analyzer`). This option disables
827    /// this behavior.
828    #[arg(long)]
829    pub no_custom_target_directory: bool,
830
831    /// Diagnostic format. Sets `cargo`'s `--message-format` as well,
832    /// if not present.
833    #[arg(long, default_value = "human")]
834    pub message_format: MessageFormat,
835
836    /// Enables experimental FullDef format for items exported from the frontend
837    /// in the haxmeta file.
838    #[arg(long, env = "HAX_EXPERIMENTAL_FULL_DEF")]
839    pub experimental_full_def: bool,
840
841    #[group(flatten)]
842    pub extension: E::Options,
843}
844
845pub type Options = ExtensibleOptions<()>;
846
847#[derive_group(Serializers)]
848#[derive(JsonSchema, ValueEnum, Debug, Clone, Copy, Eq, PartialEq)]
849pub enum MessageFormat {
850    Human,
851    Json,
852}
853
854impl<E: Extension> NormalizePaths for Command<E> {
855    fn normalize_paths(&mut self) {
856        use Command::*;
857        match self {
858            JSON { output_file, .. } => output_file.normalize_paths(),
859            _ => (),
860        }
861    }
862}
863
864impl NormalizePaths for Options {
865    fn normalize_paths(&mut self) {
866        self.command.normalize_paths()
867    }
868}
869
870impl From<Options> for hax_frontend_exporter_options::Options {
871    fn from(_opts: Options) -> hax_frontend_exporter_options::Options {
872        hax_frontend_exporter_options::Options {
873            inline_anon_consts: true,
874            bounds_options: hax_frontend_exporter_options::BoundsOptions {
875                resolve_destruct: false,
876                prune_sized: true,
877            },
878            item_ref_use_concrete_impl: false,
879        }
880    }
881}
882
883/// The subset of `Options` the frontend is sensible to.
884#[derive_group(Serializers)]
885#[derive(JsonSchema, Debug, Clone)]
886pub struct ExporterOptions {
887    pub deps: bool,
888    pub force_cargo_build: ForceCargoBuild,
889    /// When exporting, the driver sets `--cfg hax_backend_{backkend}`, thus we need this information.
890    pub backend: Option<BackendName>,
891    pub body_kinds: Vec<ExportBodyKind>,
892    pub experimental_full_def: bool,
893}
894
895#[derive_group(Serializers)]
896#[derive(JsonSchema, ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Hash)]
897pub enum BackendName {
898    Fstar,
899    Coq,
900    Ssprove,
901    Easycrypt,
902    #[clap(alias("proverif"))]
903    ProVerif,
904    LegacyLean,
905    Lean,
906    Rust,
907    GenerateRustEngineNames,
908    Debugger,
909}
910
911impl BackendName {
912    /// The subdirectory holding the backend's extraction, below the output
913    /// directory. The engine backends keep an `extraction/` level; the Lean
914    /// backend writes its package at the top of the output directory.
915    pub fn output_subdir(self) -> Option<&'static str> {
916        match self {
917            Self::Lean => None,
918            _ => Some("extraction"),
919        }
920    }
921
922    pub fn iter() -> impl Iterator<Item = Self> {
923        [
924            Self::Fstar,
925            Self::Coq,
926            Self::Ssprove,
927            Self::Easycrypt,
928            Self::ProVerif,
929            Self::LegacyLean,
930            Self::Lean,
931            Self::Rust,
932            Self::GenerateRustEngineNames,
933        ]
934        .into_iter()
935    }
936}
937
938impl fmt::Display for BackendName {
939    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940        let name = match self {
941            BackendName::Fstar => "fstar",
942            BackendName::Coq => "coq",
943            BackendName::Ssprove => "ssprove",
944            BackendName::Easycrypt => "easycrypt",
945            BackendName::ProVerif => "proverif",
946            BackendName::LegacyLean => "legacy-lean",
947            BackendName::Lean => "lean",
948            BackendName::Rust => "rust",
949            BackendName::GenerateRustEngineNames => "generate_rust_engine_names",
950            BackendName::Debugger => "debugger",
951        };
952        write!(f, "{name}")
953    }
954}
955
956impl From<&Options> for ExporterOptions {
957    fn from(options: &Options) -> Self {
958        ExporterOptions {
959            deps: options.deps,
960            force_cargo_build: options.force_cargo_build.clone(),
961            backend: options.command.backend_name(),
962            body_kinds: options.command.body_kinds(),
963            experimental_full_def: options.experimental_full_def,
964        }
965    }
966}
967
968impl From<&Backend> for BackendName {
969    fn from(backend: &Backend) -> Self {
970        match backend {
971            Backend::Fstar { .. } => BackendName::Fstar,
972            Backend::Coq { .. } => BackendName::Coq,
973            Backend::Ssprove { .. } => BackendName::Ssprove,
974            Backend::Easycrypt { .. } => BackendName::Easycrypt,
975            Backend::ProVerif { .. } => BackendName::ProVerif,
976            Backend::LegacyLean { .. } => BackendName::LegacyLean,
977            Backend::Lean { .. } => BackendName::Lean,
978            Backend::Rust { .. } => BackendName::Rust,
979            Backend::GenerateRustEngineNames { .. } => BackendName::GenerateRustEngineNames,
980            Backend::Debugger { .. } => BackendName::Debugger,
981        }
982    }
983}
984
985pub const ENV_VAR_OPTIONS_FRONTEND: &str = "DRIVER_HAX_FRONTEND_OPTS";
986pub const ENV_VAR_OPTIONS_FULL: &str = "DRIVER_HAX_FRONTEND_FULL_OPTS";
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991
992    /// `flags()` renders the options for `extract --dry-run`. The
993    /// destructuring makes a new field a compile error here, and each field
994    /// is asserted to reach the rendering, which nothing else enforces.
995    #[test]
996    fn fstar_flags_render_every_field() {
997        let options = FStarOptions {
998            z3rlimit: 111,
999            fuel: 222,
1000            ifuel: 333,
1001            interfaces: vec![parse_inclusion_clause("+**::foo").unwrap()],
1002            line_width: 444,
1003        };
1004        let FStarOptions {
1005            z3rlimit,
1006            fuel,
1007            ifuel,
1008            interfaces,
1009            line_width,
1010        } = &options;
1011        let flags = options.flags().join(" ");
1012        assert!(flags.contains(&format!("--z3rlimit={z3rlimit}")), "{flags}");
1013        assert!(flags.contains(&format!("--fuel={fuel}")), "{flags}");
1014        assert!(flags.contains(&format!("--ifuel={ifuel}")), "{flags}");
1015        assert!(
1016            flags.contains(&format!("--line-width={line_width}")),
1017            "{flags}"
1018        );
1019        assert!(flags.contains("--interfaces"), "{flags}");
1020        for clause in interfaces {
1021            assert!(flags.contains(&clause.to_string()), "{flags}");
1022        }
1023    }
1024
1025    #[test]
1026    fn proverif_flags_render_every_field() {
1027        let options = ProVerifOptions {
1028            assume_items: vec![parse_inclusion_clause("+**::bar").unwrap()],
1029            result_errors: true,
1030            keep_trait_calls: vec!["tls_codec::**".to_string()],
1031        };
1032        let ProVerifOptions {
1033            assume_items,
1034            result_errors: _,
1035            keep_trait_calls,
1036        } = &options;
1037        let flags = options.flags().join(" ");
1038        assert!(flags.contains("--assume-items"), "{flags}");
1039        for clause in assume_items {
1040            assert!(flags.contains(&clause.to_string()), "{flags}");
1041        }
1042        assert!(flags.contains("--result-errors"), "{flags}");
1043        assert!(flags.contains("--keep-trait-calls"), "{flags}");
1044        for path in keep_trait_calls {
1045            assert!(flags.contains(path.as_str()), "{flags}");
1046        }
1047    }
1048
1049    /// The Lean backend writes its package at the top of the output
1050    /// directory; every engine backend keeps an `extraction/` level.
1051    #[test]
1052    fn only_the_lean_backend_has_no_extraction_subdir() {
1053        for backend in BackendName::iter() {
1054            let subdir = backend.output_subdir();
1055            if backend == BackendName::Lean {
1056                assert_eq!(subdir, None, "{backend}");
1057            } else {
1058                assert_eq!(subdir, Some("extraction"), "{backend}");
1059            }
1060        }
1061    }
1062}