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 #[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 #[arg(long, default_value = "15")]
138 pub z3rlimit: u32,
139 #[arg(long, default_value = "0")]
141 pub fuel: u32,
142 #[arg(long, default_value = "1")]
144 pub ifuel: u32,
145 #[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 Fstar(FStarOptions<E>),
177 Lean,
179 Coq,
181 Ssprove,
183 Easycrypt,
185 ProVerif(ProVerifOptions),
187 #[clap(hide = true)]
189 Rust,
190 #[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 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 #[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 #[arg(long = "dry-run")]
328 pub dry_run: bool,
329
330 #[arg(short, long, action = clap::ArgAction::Count)]
332 pub verbose: u8,
333
334 #[arg(long)]
337 pub stats: bool,
338
339 #[arg(long)]
342 pub profile: bool,
343
344 #[arg(long)]
349 #[clap(hide = true)]
350 pub prune_haxmeta: Option<String>,
351
352 #[arg(short, long = "debug-engine")]
366 pub debug_engine: Option<DebugEngineMode>,
367
368 #[arg(long)]
376 pub extract_type_aliases: bool,
377
378 #[command(flatten)]
379 pub translation_options: TranslationOptions,
380
381 #[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 #[clap(name = "into")]
398 Backend(BackendOptions<E>),
399
400 JSON {
402 #[arg(
404 short,
405 long = "output-file",
406 default_value = "hax_frontend_export.json"
407 )]
408 output_file: PathOrDash,
409 #[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 #[arg(long)]
427 use_ids: bool,
428
429 #[arg(short = 'E', long = "include-extra", default_value = "false")]
431 include_extra: bool,
432 },
433
434 #[clap(hide = true)]
437 Serialize {
438 #[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 #[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 #[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 #[arg(long="disable-cargo-cache", action=clap::builder::ArgAction::SetFalse)]
509 pub force_cargo_build: ForceCargoBuild,
510
511 #[arg(long = "deps")]
516 pub deps: bool,
517
518 #[arg(long)]
521 #[clap(hide = true)]
522 pub haxmeta: Option<PathBuf>,
523
524 #[arg(long)]
529 pub no_custom_target_directory: bool,
530
531 #[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#[derive_group(Serializers)]
580#[derive(JsonSchema, Debug, Clone)]
581pub struct ExporterOptions {
582 pub deps: bool,
583 pub force_cargo_build: ForceCargoBuild,
584 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";