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 Coq backend
178    Coq,
179    /// Use the SSProve backend
180    Ssprove,
181    /// Use the EasyCrypt backend (warning: work in progress!)
182    Easycrypt,
183    /// Use the ProVerif backend (warning: work in progress!)
184    ProVerif(ProVerifOptions),
185}
186
187impl fmt::Display for Backend<()> {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        match self {
190            Backend::Fstar(..) => write!(f, "fstar"),
191            Backend::Coq => write!(f, "coq"),
192            Backend::Ssprove => write!(f, "ssprove"),
193            Backend::Easycrypt => write!(f, "easycrypt"),
194            Backend::ProVerif(..) => write!(f, "proverif"),
195        }
196    }
197}
198
199#[derive_group(Serializers)]
200#[derive(JsonSchema, Debug, Clone)]
201pub enum DepsKind {
202    Transitive,
203    Shallow,
204    None,
205}
206
207#[derive_group(Serializers)]
208#[derive(JsonSchema, Debug, Clone)]
209pub enum InclusionKind {
210    /// `+query` include the items selected by `query`
211    Included(DepsKind),
212    SignatureOnly,
213    Excluded,
214}
215
216#[derive_group(Serializers)]
217#[derive(JsonSchema, Debug, Clone)]
218pub struct InclusionClause {
219    pub kind: InclusionKind,
220    pub namespace: Namespace,
221}
222
223const PREFIX_INCLUDED_TRANSITIVE: &str = "+";
224const PREFIX_INCLUDED_SHALLOW: &str = "+~";
225const PREFIX_INCLUDED_NONE: &str = "+!";
226const PREFIX_SIGNATURE_ONLY: &str = "+:";
227const PREFIX_EXCLUDED: &str = "-";
228
229impl ToString for InclusionClause {
230    fn to_string(&self) -> String {
231        let kind = match self.kind {
232            InclusionKind::Included(DepsKind::Transitive) => PREFIX_INCLUDED_TRANSITIVE,
233            InclusionKind::Included(DepsKind::Shallow) => PREFIX_INCLUDED_SHALLOW,
234            InclusionKind::Included(DepsKind::None) => PREFIX_INCLUDED_NONE,
235            InclusionKind::SignatureOnly => PREFIX_SIGNATURE_ONLY,
236            InclusionKind::Excluded => PREFIX_EXCLUDED,
237        };
238        format!("{kind}{}", self.namespace.to_string())
239    }
240}
241
242pub fn parse_inclusion_clause(
243    s: &str,
244) -> Result<InclusionClause, Box<dyn std::error::Error + Send + Sync + 'static>> {
245    let s = s.trim();
246    if s.is_empty() {
247        Err("Expected `-` or `+`, got an empty string")?
248    }
249    let (prefix, namespace) = {
250        let f = |&c: &char| matches!(c, '+' | '-' | '~' | '!' | ':');
251        (
252            s.chars().take_while(f).into_iter().collect::<String>(),
253            s.chars().skip_while(f).into_iter().collect::<String>(),
254        )
255    };
256    let kind = match &prefix[..] {
257        PREFIX_INCLUDED_TRANSITIVE => InclusionKind::Included(DepsKind::Transitive),
258        PREFIX_INCLUDED_SHALLOW => InclusionKind::Included(DepsKind::Shallow),
259        PREFIX_INCLUDED_NONE => InclusionKind::Included(DepsKind::None),
260        PREFIX_SIGNATURE_ONLY => InclusionKind::SignatureOnly,
261        PREFIX_EXCLUDED => InclusionKind::Excluded,
262        prefix => Err(format!(
263            "Expected `+`, `+~`, `+!`, `+:` or `-`, got an `{prefix}`"
264        ))?,
265    };
266    Ok(InclusionClause {
267        kind,
268        namespace: namespace.to_string().into(),
269    })
270}
271
272#[derive_group(Serializers)]
273#[derive(JsonSchema, Parser, Debug, Clone)]
274pub struct TranslationOptions {
275    /// Controls which Rust item should be extracted or not.
276    ///
277    /// This is a space-separated list of patterns prefixed with a
278    /// modifier, read from the left to the right.
279    ///
280    /// A pattern is a Rust path (say `mycrate::mymod::myfn`) where
281    /// globs are allowed: `*` matches any name
282    /// (e.g. `mycrate::mymod::myfn` is matched by
283    /// `mycrate::*::myfn`), while `**` matches any subpath, empty
284    /// included (e.g. `mycrate::mymod::myfn` is matched by
285    /// `**::myfn`).
286
287    /// By default, hax includes all items. Then, the patterns
288    /// prefixed by modifiers are processed from left to right,
289    /// excluding or including items. Each pattern selects a number of
290    /// item. The modifiers are:
291
292    /// {n}{n} - `+`: includes the selected items with their
293    /// dependencies, transitively (e.g. if function `f` calls `g`
294    /// which in turn calls `h`, then `+k::f` includes `f`, `g` and
295    /// `h`)
296
297    /// {n} - `+~`: includes the selected items with their direct
298    /// dependencies only (following the previous example, `+~k::f`
299    /// would select `f` and `g`, but not `h`)
300
301    /// {n} - `+!`: includes the selected items, without their
302    /// dependencies (`+!k::f` would only select `f`)
303
304    /// {n} - `+:`: only includes the type of the selected items (no
305    /// dependencies). This includes full struct and enums, but only
306    /// the type signature of functions and trait impls (except when
307    /// they contain associated types), dropping their bodies.
308    #[arg(
309        value_parser = parse_inclusion_clause,
310        value_delimiter = ' ',
311    )]
312    #[arg(short, allow_hyphen_values(true))]
313    pub include_namespaces: Vec<InclusionClause>,
314}
315
316#[derive_group(Serializers)]
317#[derive(JsonSchema, Parser, Debug, Clone)]
318pub struct BackendOptions<E: Extension> {
319    #[command(subcommand)]
320    pub backend: Backend<E>,
321
322    /// Don't write anything on disk. Output everything as JSON to stdout
323    /// instead.
324    #[arg(long = "dry-run")]
325    pub dry_run: bool,
326
327    /// Verbose mode for the Hax engine. Set `-vv` for maximal verbosity.
328    #[arg(short, long, action = clap::ArgAction::Count)]
329    pub verbose: u8,
330
331    /// Prints statistics about how many items have been translated
332    /// successfully by the engine.
333    #[arg(long)]
334    pub stats: bool,
335
336    /// Enables profiling for the engine: for each phase of the
337    /// engine, time and memory usage are recorded and reported.
338    #[arg(long)]
339    pub profile: bool,
340
341    /// Enable engine debugging: dumps the AST at each phase.
342    ///
343    /// The value of `<DEBUG_ENGINE>` can be either:
344
345    /// {n}{n} - `interactive` (or `i`): enables debugging of the engine,
346    /// and visualize interactively in a webapp how a crate was
347    /// transformed by each phase, both in Rust-like syntax and
348    /// browsing directly the internal AST. By default, the webapp is
349    /// hosted on `http://localhost:8000`, the port can be override by
350    /// setting the `HAX_DEBUGGER_PORT` environment variable.
351
352    /// {n} - `<FILE>` or `file:<FILE>`: outputs the different AST as JSON
353    /// to `<FILE>`. `<FILE>` can be either [-] or a path.
354    #[arg(short, long = "debug-engine")]
355    pub debug_engine: Option<DebugEngineMode>,
356
357    /// Extract type aliases. This is disabled by default, since
358    /// extracted terms depends on expanded types rather than on type
359    /// aliases. Turning this option on is discouraged: Rust type
360    /// synonyms can ommit generic bounds, which are ususally
361    /// necessary in the hax backends, leading to typechecking
362    /// errors. For more details see
363    /// https://github.com/hacspec/hax/issues/708.
364    #[arg(long)]
365    pub extract_type_aliases: bool,
366
367    #[command(flatten)]
368    pub translation_options: TranslationOptions,
369
370    /// Where to put the output files resulting from the translation.
371    /// Defaults to "<crate folder>/proofs/<backend>/extraction".
372    #[arg(long)]
373    pub output_dir: Option<PathBuf>,
374
375    #[group(flatten)]
376    pub cli_extension: E::BackendOptions,
377}
378
379#[derive_group(Serializers)]
380#[derive(JsonSchema, Subcommand, Debug, Clone)]
381pub enum Command<E: Extension> {
382    /// Translate to a backend. The translated modules will be written
383    /// under the directory `<PKG>/proofs/<BACKEND>/extraction`, where
384    /// `<PKG>` is the translated cargo package name and `<BACKEND>`
385    /// the name of the backend.
386    #[clap(name = "into")]
387    Backend(BackendOptions<E>),
388
389    /// Export directly as a JSON file
390    JSON {
391        /// Path to the output JSON file, "-" denotes stdout.
392        #[arg(
393            short,
394            long = "output-file",
395            default_value = "hax_frontend_export.json"
396        )]
397        output_file: PathOrDash,
398        /// Whether the bodies are exported as THIR, built MIR, const
399        /// MIR, or a combination. Repeat this option to extract a
400        /// combination (e.g. `-k thir -k mir-built`). Pass `--kind`
401        /// alone with no value to disable body extraction.
402        #[arg(
403            value_enum,
404            short,
405            long = "kind",
406            num_args = 0..=3,
407            default_values_t = [ExportBodyKind::Thir]
408        )]
409        kind: Vec<ExportBodyKind>,
410
411        /// By default, `cargo hax json` outputs a JSON where every
412        /// piece of information is inlined. This however creates very
413        /// large JSON files. This flag enables the use of unique IDs
414        /// and outputs a map from IDs to actual objects.
415        #[arg(long)]
416        use_ids: bool,
417
418        /// Whether to include extra informations about `DefId`s.
419        #[arg(short = 'E', long = "include-extra", default_value = "false")]
420        include_extra: bool,
421    },
422
423    #[command(flatten)]
424    CliExtension(E::Command),
425}
426
427impl<E: Extension> Command<E> {
428    pub fn body_kinds(&self) -> Vec<ExportBodyKind> {
429        match self {
430            Command::JSON { kind, .. } => kind.clone(),
431            _ => vec![ExportBodyKind::Thir],
432        }
433    }
434}
435
436#[derive_group(Serializers)]
437#[derive(JsonSchema, ValueEnum, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
438pub enum ExportBodyKind {
439    Thir,
440    MirBuilt,
441}
442
443#[derive_group(Serializers)]
444#[derive(JsonSchema, Parser, Debug, Clone)]
445#[command(
446    author,
447    version = crate::HAX_VERSION,
448    long_version = concat!("\nversion=", env!("HAX_VERSION"), "\n", "commit=", env!("HAX_GIT_COMMIT_HASH")),
449    name = "hax",
450    about,
451    long_about = None
452)]
453pub struct ExtensibleOptions<E: Extension> {
454    /// Replace the expansion of each macro matching PATTERN by their
455    /// invocation. PATTERN denotes a rust path (i.e. `A::B::c`) in
456    /// which glob patterns are allowed. The glob pattern * matches
457    /// any name, the glob pattern ** matches zero, one or more
458    /// names. For instance, `A::B::C::D::X` and `A::E::F::D::Y`
459    /// matches `A::**::D::*`.
460    #[arg(
461        short = 'i',
462        long = "inline-macro-call",
463        value_name = "PATTERN",
464        value_parser,
465        value_delimiter = ',',
466        default_values = [
467            "hacspec_lib::array::array", "hacspec_lib::array::public_bytes", "hacspec_lib::array::bytes",
468            "hacspec_lib::math_integers::public_nat_mod", "hacspec_lib::math_integers::unsigned_public_integer",
469        ],
470    )]
471    pub inline_macro_calls: Vec<Namespace>,
472
473    /// Semi-colon terminated list of arguments to pass to the
474    /// `cargo build` invocation. For example, to apply this
475    /// program on a package `foo`, use `-C -p foo ;`. (make sure
476    /// to escape `;` correctly in your shell)
477    #[arg(default_values = Vec::<&str>::new(), short='C', allow_hyphen_values=true, num_args=1.., long="cargo-args", value_terminator=";")]
478    pub cargo_flags: Vec<String>,
479
480    #[command(subcommand)]
481    pub command: Command<E>,
482
483    /// `cargo` caching is enable by default, this flag disables it.
484    #[arg(long="disable-cargo-cache", action=clap::builder::ArgAction::SetFalse)]
485    pub force_cargo_build: ForceCargoBuild,
486
487    /// Apply the command to every local package of the dependency closure. By
488    /// default, the command is only applied to the primary packages (i.e. the
489    /// package(s) of the current directory, or the ones selected with cargo
490    /// options like `-C -p <PKG> ;`).
491    #[arg(long = "deps")]
492    pub deps: bool,
493
494    /// By default, hax uses `$CARGO_TARGET_DIR/hax` as target folder,
495    /// to avoid recompilation when working both with `cargo hax` and
496    /// `cargo build` (or, e.g. `rust-analyzer`). This option disables
497    /// this behavior.
498    #[arg(long)]
499    pub no_custom_target_directory: bool,
500
501    /// Diagnostic format. Sets `cargo`'s `--message-format` as well,
502    /// if not present.
503    #[arg(long, default_value = "human")]
504    pub message_format: MessageFormat,
505
506    #[group(flatten)]
507    pub extension: E::Options,
508}
509
510pub type Options = ExtensibleOptions<()>;
511
512#[derive_group(Serializers)]
513#[derive(JsonSchema, ValueEnum, Debug, Clone, Copy, Eq, PartialEq)]
514pub enum MessageFormat {
515    Human,
516    Json,
517}
518
519impl<E: Extension> NormalizePaths for Command<E> {
520    fn normalize_paths(&mut self) {
521        use Command::*;
522        match self {
523            JSON { output_file, .. } => output_file.normalize_paths(),
524            _ => (),
525        }
526    }
527}
528
529impl NormalizePaths for Options {
530    fn normalize_paths(&mut self) {
531        self.command.normalize_paths()
532    }
533}
534
535impl From<Options> for hax_frontend_exporter_options::Options {
536    fn from(_opts: Options) -> hax_frontend_exporter_options::Options {
537        hax_frontend_exporter_options::Options {
538            inline_anon_consts: true,
539        }
540    }
541}
542
543pub const ENV_VAR_OPTIONS_FRONTEND: &str = "DRIVER_HAX_FRONTEND_OPTS";