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)]
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)]
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, Clone)]
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
133#[derive_group(Serializers)]
134#[derive(JsonSchema, Parser, Debug, Clone)]
135pub struct FStarOptions<E: Extension> {
136    /// Set the Z3 per-query resource limit
137    #[arg(long, default_value = "15")]
138    pub z3rlimit: u32,
139    /// Number of unrolling of recursive functions to try
140    #[arg(long, default_value = "0")]
141    pub fuel: u32,
142    /// Number of unrolling of inductive datatypes to try
143    #[arg(long, default_value = "1")]
144    pub ifuel: u32,
145    /// Modules for which Hax should extract interfaces (`*.fsti`
146    /// files) in supplement to implementations (`*.fst` files). By
147    /// default we extract no interface, only implementations. If a
148    /// item is signature only (see the `+:` prefix of the
149    /// `--include_namespaces` flag of the `into` subcommand), then
150    /// its namespace is extracted with an interface. This flag
151    /// expects a space-separated list of inclusion clauses. An
152    /// inclusion clause is a Rust path prefixed with `+`, `+!` or
153    /// `-`. `-` means implementation only, `+!` means interface only
154    /// and `+` means implementation and interface. Rust path chunks
155    /// can be either a concrete string, or a glob (just like bash
156    /// globs, but with Rust paths).
157    #[arg(
158        long,
159        value_parser = parse_inclusion_clause,
160        value_delimiter = ' ',
161        allow_hyphen_values(true)
162    )]
163    pub interfaces: Vec<InclusionClause>,
164
165    #[arg(long, default_value = "100", env = "HAX_FSTAR_LINE_WIDTH")]
166    pub line_width: u16,
167
168    #[group(flatten)]
169    pub cli_extension: E::FStarOptions,
170}
171
172#[derive_group(Serializers)]
173#[derive(JsonSchema, Subcommand, Debug, Clone)]
174pub enum Backend<E: Extension> {
175    /// Use the F* backend
176    Fstar(FStarOptions<E>),
177    /// Use the Lean backend (warning: experimental)
178    Lean,
179    /// Use the Coq backend
180    Coq,
181    /// Use the SSProve backend
182    Ssprove,
183    /// Use the EasyCrypt backend (warning: work in progress!)
184    Easycrypt,
185    /// Use the ProVerif backend (warning: work in progress!)
186    ProVerif(ProVerifOptions),
187    /// Use the Rust backend (warning: work in progress!)
188    #[clap(hide = true)]
189    Rust,
190    /// Extract `DefId`s of the crate as a Rust module tree.
191    /// This is a command that regenerates code for the rust engine.
192    #[clap(hide = true)]
193    GenerateRustEngineNames,
194}
195
196impl fmt::Display for Backend<()> {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        BackendName::from(self).fmt(f)
199    }
200}
201
202#[derive_group(Serializers)]
203#[derive(JsonSchema, Debug, Clone)]
204pub enum DepsKind {
205    Transitive,
206    Shallow,
207    None,
208}
209
210#[derive_group(Serializers)]
211#[derive(JsonSchema, Debug, Clone)]
212pub enum InclusionKind {
213    /// `+query` include the items selected by `query`
214    Included(DepsKind),
215    SignatureOnly,
216    Excluded,
217}
218
219#[derive_group(Serializers)]
220#[derive(JsonSchema, Debug, Clone)]
221pub struct InclusionClause {
222    pub kind: InclusionKind,
223    pub namespace: Namespace,
224}
225
226const PREFIX_INCLUDED_TRANSITIVE: &str = "+";
227const PREFIX_INCLUDED_SHALLOW: &str = "+~";
228const PREFIX_INCLUDED_NONE: &str = "+!";
229const PREFIX_SIGNATURE_ONLY: &str = "+:";
230const PREFIX_EXCLUDED: &str = "-";
231
232impl ToString for InclusionClause {
233    fn to_string(&self) -> String {
234        let kind = match self.kind {
235            InclusionKind::Included(DepsKind::Transitive) => PREFIX_INCLUDED_TRANSITIVE,
236            InclusionKind::Included(DepsKind::Shallow) => PREFIX_INCLUDED_SHALLOW,
237            InclusionKind::Included(DepsKind::None) => PREFIX_INCLUDED_NONE,
238            InclusionKind::SignatureOnly => PREFIX_SIGNATURE_ONLY,
239            InclusionKind::Excluded => PREFIX_EXCLUDED,
240        };
241        format!("{kind}{}", self.namespace.to_string())
242    }
243}
244
245pub fn parse_inclusion_clause(
246    s: &str,
247) -> Result<InclusionClause, Box<dyn std::error::Error + Send + Sync + 'static>> {
248    let s = s.trim();
249    if s.is_empty() {
250        Err("Expected `-` or `+`, got an empty string")?
251    }
252    let (prefix, namespace) = {
253        let f = |&c: &char| matches!(c, '+' | '-' | '~' | '!' | ':');
254        (
255            s.chars().take_while(f).into_iter().collect::<String>(),
256            s.chars().skip_while(f).into_iter().collect::<String>(),
257        )
258    };
259    let kind = match &prefix[..] {
260        PREFIX_INCLUDED_TRANSITIVE => InclusionKind::Included(DepsKind::Transitive),
261        PREFIX_INCLUDED_SHALLOW => InclusionKind::Included(DepsKind::Shallow),
262        PREFIX_INCLUDED_NONE => InclusionKind::Included(DepsKind::None),
263        PREFIX_SIGNATURE_ONLY => InclusionKind::SignatureOnly,
264        PREFIX_EXCLUDED => InclusionKind::Excluded,
265        prefix => Err(format!(
266            "Expected `+`, `+~`, `+!`, `+:` or `-`, got an `{prefix}`"
267        ))?,
268    };
269    Ok(InclusionClause {
270        kind,
271        namespace: namespace.to_string().into(),
272    })
273}
274
275#[derive_group(Serializers)]
276#[derive(JsonSchema, Parser, Debug, Clone)]
277pub struct TranslationOptions {
278    /// Controls which Rust item should be extracted or not.
279    ///
280    /// This is a space-separated list of patterns prefixed with a
281    /// modifier, read from the left to the right.
282    ///
283    /// A pattern is a Rust path (say `mycrate::mymod::myfn`) where
284    /// globs are allowed: `*` matches any name
285    /// (e.g. `mycrate::mymod::myfn` is matched by
286    /// `mycrate::*::myfn`), while `**` matches any subpath, empty
287    /// included (e.g. `mycrate::mymod::myfn` is matched by
288    /// `**::myfn`).
289
290    /// By default, hax includes all items. Then, the patterns
291    /// prefixed by modifiers are processed from left to right,
292    /// excluding or including items. Each pattern selects a number of
293    /// item. The modifiers are:
294
295    /// {n}{n} - `+`: includes the selected items with their
296    /// dependencies, transitively (e.g. if function `f` calls `g`
297    /// which in turn calls `h`, then `+k::f` includes `f`, `g` and
298    /// `h`)
299
300    /// {n} - `+~`: includes the selected items with their direct
301    /// dependencies only (following the previous example, `+~k::f`
302    /// would select `f` and `g`, but not `h`)
303
304    /// {n} - `+!`: includes the selected items, without their
305    /// dependencies (`+!k::f` would only select `f`)
306
307    /// {n} - `+:`: only includes the type of the selected items (no
308    /// dependencies). This includes full struct and enums, but only
309    /// the type signature of functions and trait impls (except when
310    /// they contain associated types), dropping their bodies.
311    #[arg(
312        value_parser = parse_inclusion_clause,
313        value_delimiter = ' ',
314    )]
315    #[arg(short, allow_hyphen_values(true))]
316    pub include_namespaces: Vec<InclusionClause>,
317}
318
319#[derive_group(Serializers)]
320#[derive(JsonSchema, Parser, Debug, Clone)]
321pub struct BackendOptions<E: Extension> {
322    #[command(subcommand)]
323    pub backend: Backend<E>,
324
325    /// Don't write anything on disk. Output everything as JSON to stdout
326    /// instead.
327    #[arg(long = "dry-run")]
328    pub dry_run: bool,
329
330    /// Verbose mode for the Hax engine. Set `-vv` for maximal verbosity.
331    #[arg(short, long, action = clap::ArgAction::Count)]
332    pub verbose: u8,
333
334    /// Prints statistics about how many items have been translated
335    /// successfully by the engine.
336    #[arg(long)]
337    pub stats: bool,
338
339    /// Enables profiling for the engine: for each phase of the
340    /// engine, time and memory usage are recorded and reported.
341    #[arg(long)]
342    pub profile: bool,
343
344    /// Prune Rust items that are not under the provided top-level module name.
345    /// This will effectively remove all items that don't match `*::<prune_haxmetadata>::**`.
346    /// This prunning occurs directly on the `haxmeta` file, in the frontend.
347    /// This is independent from any engine options.
348    #[arg(long)]
349    #[clap(hide = true)]
350    pub prune_haxmeta: Option<String>,
351
352    /// Enable engine debugging: dumps the AST at each phase.
353    ///
354    /// The value of `<DEBUG_ENGINE>` can be either:
355
356    /// {n}{n} - `interactive` (or `i`): enables debugging of the engine,
357    /// and visualize interactively in a webapp how a crate was
358    /// transformed by each phase, both in Rust-like syntax and
359    /// browsing directly the internal AST. By default, the webapp is
360    /// hosted on `http://localhost:8000`, the port can be override by
361    /// setting the `HAX_DEBUGGER_PORT` environment variable.
362
363    /// {n} - `<FILE>` or `file:<FILE>`: outputs the different AST as JSON
364    /// to `<FILE>`. `<FILE>` can be either [-] or a path.
365    #[arg(short, long = "debug-engine")]
366    pub debug_engine: Option<DebugEngineMode>,
367
368    /// Extract type aliases. This is disabled by default, since
369    /// extracted terms depends on expanded types rather than on type
370    /// aliases. Turning this option on is discouraged: Rust type
371    /// synonyms can ommit generic bounds, which are ususally
372    /// necessary in the hax backends, leading to typechecking
373    /// errors. For more details see
374    /// https://github.com/hacspec/hax/issues/708.
375    #[arg(long)]
376    pub extract_type_aliases: bool,
377
378    #[command(flatten)]
379    pub translation_options: TranslationOptions,
380
381    /// Where to put the output files resulting from the translation.
382    /// Defaults to "<crate folder>/proofs/<backend>/extraction".
383    #[arg(long)]
384    pub output_dir: Option<PathBuf>,
385
386    #[group(flatten)]
387    pub cli_extension: E::BackendOptions,
388}
389
390#[derive_group(Serializers)]
391#[derive(JsonSchema, Subcommand, Debug, Clone)]
392pub enum Command<E: Extension> {
393    /// Translate to a backend. The translated modules will be written
394    /// under the directory `<PKG>/proofs/<BACKEND>/extraction`, where
395    /// `<PKG>` is the translated cargo package name and `<BACKEND>`
396    /// the name of the backend.
397    #[clap(name = "into")]
398    Backend(BackendOptions<E>),
399
400    /// Export directly as a JSON file
401    JSON {
402        /// Path to the output JSON file, "-" denotes stdout.
403        #[arg(
404            short,
405            long = "output-file",
406            default_value = "hax_frontend_export.json"
407        )]
408        output_file: PathOrDash,
409        /// Whether the bodies are exported as THIR, built MIR, const
410        /// MIR, or a combination. Repeat this option to extract a
411        /// combination (e.g. `-k thir -k mir-built`). Pass `--kind`
412        /// alone with no value to disable body extraction.
413        #[arg(
414            value_enum,
415            short,
416            long = "kind",
417            num_args = 0..=3,
418            default_values_t = [ExportBodyKind::Thir]
419        )]
420        kind: Vec<ExportBodyKind>,
421
422        /// By default, `cargo hax json` outputs a JSON where every
423        /// piece of information is inlined. This however creates very
424        /// large JSON files. This flag enables the use of unique IDs
425        /// and outputs a map from IDs to actual objects.
426        #[arg(long)]
427        use_ids: bool,
428
429        /// Whether to include extra informations about `DefId`s.
430        #[arg(short = 'E', long = "include-extra", default_value = "false")]
431        include_extra: bool,
432    },
433
434    /// Serialize to a `haxmeta` file, the internal binary format used by hax to
435    /// store the ASTs produced by the hax exporter.
436    #[clap(hide = true)]
437    Serialize {
438        /// Whether the bodies are exported as THIR, built MIR, const
439        /// MIR, or a combination. Repeat this option to extract a
440        /// combination (e.g. `-k thir -k mir-built`). Pass `--kind`
441        /// alone with no value to disable body extraction.
442        #[arg(
443            value_enum,
444            short,
445            long = "kind",
446            num_args = 0..=3,
447            default_values_t = [ExportBodyKind::Thir]
448        )]
449        kind: Vec<ExportBodyKind>,
450
451        /// When extracting to a given backend, the exporter is called with different `cfg` options.
452        /// This option allows to set the same flags as `cargo hax into` would pick.
453        #[arg(short)]
454        backend: Option<BackendName>,
455    },
456
457    #[command(flatten)]
458    CliExtension(E::Command),
459}
460
461impl<E: Extension> Command<E> {
462    pub fn body_kinds(&self) -> Vec<ExportBodyKind> {
463        match self {
464            Command::JSON { kind, .. } => kind.clone(),
465            Command::Serialize { kind, .. } => kind.clone(),
466            Command::Backend { .. } | Command::CliExtension { .. } => vec![ExportBodyKind::Thir],
467        }
468    }
469    pub fn backend_name(&self) -> Option<BackendName> {
470        match self {
471            Command::Backend(backend_options) => Some((&backend_options.backend).into()),
472            Command::JSON { .. } => None,
473            Command::Serialize { backend, .. } => backend.clone(),
474            Command::CliExtension(_) => None,
475        }
476    }
477}
478
479#[derive_group(Serializers)]
480#[derive(JsonSchema, ValueEnum, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
481pub enum ExportBodyKind {
482    Thir,
483    MirBuilt,
484}
485
486#[derive_group(Serializers)]
487#[derive(JsonSchema, Parser, Debug, Clone)]
488#[command(
489    author,
490    version = crate::HAX_VERSION,
491    long_version = concat!("\nversion=", env!("HAX_VERSION"), "\n", "commit=", env!("HAX_GIT_COMMIT_HASH")),
492    name = "hax",
493    about,
494    long_about = None
495)]
496pub struct ExtensibleOptions<E: Extension> {
497    /// Semi-colon terminated list of arguments to pass to the
498    /// `cargo build` invocation. For example, to apply this
499    /// program on a package `foo`, use `-C -p foo ;`. (make sure
500    /// to escape `;` correctly in your shell)
501    #[arg(default_values = Vec::<&str>::new(), short='C', allow_hyphen_values=true, num_args=1.., long="cargo-args", value_terminator=";")]
502    pub cargo_flags: Vec<String>,
503
504    #[command(subcommand)]
505    pub command: Command<E>,
506
507    /// `cargo` caching is enable by default, this flag disables it.
508    #[arg(long="disable-cargo-cache", action=clap::builder::ArgAction::SetFalse)]
509    pub force_cargo_build: ForceCargoBuild,
510
511    /// Apply the command to every local package of the dependency closure. By
512    /// default, the command is only applied to the primary packages (i.e. the
513    /// package(s) of the current directory, or the ones selected with cargo
514    /// options like `-C -p <PKG> ;`).
515    #[arg(long = "deps")]
516    pub deps: bool,
517
518    /// Provide a precomputed haxmeta file explicitly.
519    /// Setting this option bypasses rustc and the exporter altogether.
520    #[arg(long)]
521    #[clap(hide = true)]
522    pub haxmeta: Option<PathBuf>,
523
524    /// By default, hax uses `$CARGO_TARGET_DIR/hax` as target folder,
525    /// to avoid recompilation when working both with `cargo hax` and
526    /// `cargo build` (or, e.g. `rust-analyzer`). This option disables
527    /// this behavior.
528    #[arg(long)]
529    pub no_custom_target_directory: bool,
530
531    /// Diagnostic format. Sets `cargo`'s `--message-format` as well,
532    /// if not present.
533    #[arg(long, default_value = "human")]
534    pub message_format: MessageFormat,
535
536    #[group(flatten)]
537    pub extension: E::Options,
538}
539
540pub type Options = ExtensibleOptions<()>;
541
542#[derive_group(Serializers)]
543#[derive(JsonSchema, ValueEnum, Debug, Clone, Copy, Eq, PartialEq)]
544pub enum MessageFormat {
545    Human,
546    Json,
547}
548
549impl<E: Extension> NormalizePaths for Command<E> {
550    fn normalize_paths(&mut self) {
551        use Command::*;
552        match self {
553            JSON { output_file, .. } => output_file.normalize_paths(),
554            _ => (),
555        }
556    }
557}
558
559impl NormalizePaths for Options {
560    fn normalize_paths(&mut self) {
561        self.command.normalize_paths()
562    }
563}
564
565impl From<Options> for hax_frontend_exporter_options::Options {
566    fn from(_opts: Options) -> hax_frontend_exporter_options::Options {
567        hax_frontend_exporter_options::Options {
568            inline_anon_consts: true,
569            bounds_options: hax_frontend_exporter_options::BoundsOptions {
570                resolve_destruct: false,
571                prune_sized: true,
572            },
573            item_ref_use_concrete_impl: false,
574        }
575    }
576}
577
578/// The subset of `Options` the frontend is sensible to.
579#[derive_group(Serializers)]
580#[derive(JsonSchema, Debug, Clone)]
581pub struct ExporterOptions {
582    pub deps: bool,
583    pub force_cargo_build: ForceCargoBuild,
584    /// When exporting, the driver sets `--cfg hax_backend_{backkend}`, thus we need this information.
585    pub backend: Option<BackendName>,
586    pub body_kinds: Vec<ExportBodyKind>,
587}
588
589#[derive_group(Serializers)]
590#[derive(JsonSchema, ValueEnum, Debug, Clone, Copy)]
591pub enum BackendName {
592    Fstar,
593    Coq,
594    Ssprove,
595    Easycrypt,
596    ProVerif,
597    Lean,
598    Rust,
599    GenerateRustEngineNames,
600}
601
602impl fmt::Display for BackendName {
603    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
604        let name = match self {
605            BackendName::Fstar => "fstar",
606            BackendName::Coq => "coq",
607            BackendName::Ssprove => "ssprove",
608            BackendName::Easycrypt => "easycrypt",
609            BackendName::ProVerif => "proverif",
610            BackendName::Lean => "lean",
611            BackendName::Rust => "rust",
612            BackendName::GenerateRustEngineNames => "generate_rust_engine_names",
613        };
614        write!(f, "{name}")
615    }
616}
617
618impl From<&Options> for ExporterOptions {
619    fn from(options: &Options) -> Self {
620        ExporterOptions {
621            deps: options.deps,
622            force_cargo_build: options.force_cargo_build.clone(),
623            backend: options.command.backend_name(),
624            body_kinds: options.command.body_kinds(),
625        }
626    }
627}
628
629impl<E: Extension> From<&Backend<E>> for BackendName {
630    fn from(backend: &Backend<E>) -> Self {
631        match backend {
632            Backend::Fstar { .. } => BackendName::Fstar,
633            Backend::Coq { .. } => BackendName::Coq,
634            Backend::Ssprove { .. } => BackendName::Ssprove,
635            Backend::Easycrypt { .. } => BackendName::Easycrypt,
636            Backend::ProVerif { .. } => BackendName::ProVerif,
637            Backend::Lean { .. } => BackendName::Lean,
638            Backend::Rust { .. } => BackendName::Rust,
639            Backend::GenerateRustEngineNames { .. } => BackendName::GenerateRustEngineNames,
640        }
641    }
642}
643
644pub const ENV_VAR_OPTIONS_FRONTEND: &str = "DRIVER_HAX_FRONTEND_OPTS";
645pub const ENV_VAR_OPTIONS_FULL: &str = "DRIVER_HAX_FRONTEND_FULL_OPTS";