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 Coq,
179 Ssprove,
181 Easycrypt,
183 ProVerif(ProVerifOptions),
185 #[clap(hide = true)]
187 Lean,
188 #[clap(hide = true)]
191 GenerateRustEngineNames,
192}
193
194impl fmt::Display for Backend<()> {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 match self {
197 Backend::Fstar { .. } => write!(f, "fstar"),
198 Backend::Coq { .. } => write!(f, "coq"),
199 Backend::Ssprove { .. } => write!(f, "ssprove"),
200 Backend::Easycrypt { .. } => write!(f, "easycrypt"),
201 Backend::ProVerif { .. } => write!(f, "proverif"),
202 Backend::Lean { .. } => write!(f, "lean"),
203 Backend::GenerateRustEngineNames { .. } => write!(f, "generate_rust_engine_names"),
204 }
205 }
206}
207
208#[derive_group(Serializers)]
209#[derive(JsonSchema, Debug, Clone)]
210pub enum DepsKind {
211 Transitive,
212 Shallow,
213 None,
214}
215
216#[derive_group(Serializers)]
217#[derive(JsonSchema, Debug, Clone)]
218pub enum InclusionKind {
219 Included(DepsKind),
221 SignatureOnly,
222 Excluded,
223}
224
225#[derive_group(Serializers)]
226#[derive(JsonSchema, Debug, Clone)]
227pub struct InclusionClause {
228 pub kind: InclusionKind,
229 pub namespace: Namespace,
230}
231
232const PREFIX_INCLUDED_TRANSITIVE: &str = "+";
233const PREFIX_INCLUDED_SHALLOW: &str = "+~";
234const PREFIX_INCLUDED_NONE: &str = "+!";
235const PREFIX_SIGNATURE_ONLY: &str = "+:";
236const PREFIX_EXCLUDED: &str = "-";
237
238impl ToString for InclusionClause {
239 fn to_string(&self) -> String {
240 let kind = match self.kind {
241 InclusionKind::Included(DepsKind::Transitive) => PREFIX_INCLUDED_TRANSITIVE,
242 InclusionKind::Included(DepsKind::Shallow) => PREFIX_INCLUDED_SHALLOW,
243 InclusionKind::Included(DepsKind::None) => PREFIX_INCLUDED_NONE,
244 InclusionKind::SignatureOnly => PREFIX_SIGNATURE_ONLY,
245 InclusionKind::Excluded => PREFIX_EXCLUDED,
246 };
247 format!("{kind}{}", self.namespace.to_string())
248 }
249}
250
251pub fn parse_inclusion_clause(
252 s: &str,
253) -> Result<InclusionClause, Box<dyn std::error::Error + Send + Sync + 'static>> {
254 let s = s.trim();
255 if s.is_empty() {
256 Err("Expected `-` or `+`, got an empty string")?
257 }
258 let (prefix, namespace) = {
259 let f = |&c: &char| matches!(c, '+' | '-' | '~' | '!' | ':');
260 (
261 s.chars().take_while(f).into_iter().collect::<String>(),
262 s.chars().skip_while(f).into_iter().collect::<String>(),
263 )
264 };
265 let kind = match &prefix[..] {
266 PREFIX_INCLUDED_TRANSITIVE => InclusionKind::Included(DepsKind::Transitive),
267 PREFIX_INCLUDED_SHALLOW => InclusionKind::Included(DepsKind::Shallow),
268 PREFIX_INCLUDED_NONE => InclusionKind::Included(DepsKind::None),
269 PREFIX_SIGNATURE_ONLY => InclusionKind::SignatureOnly,
270 PREFIX_EXCLUDED => InclusionKind::Excluded,
271 prefix => Err(format!(
272 "Expected `+`, `+~`, `+!`, `+:` or `-`, got an `{prefix}`"
273 ))?,
274 };
275 Ok(InclusionClause {
276 kind,
277 namespace: namespace.to_string().into(),
278 })
279}
280
281#[derive_group(Serializers)]
282#[derive(JsonSchema, Parser, Debug, Clone)]
283pub struct TranslationOptions {
284 #[arg(
318 value_parser = parse_inclusion_clause,
319 value_delimiter = ' ',
320 )]
321 #[arg(short, allow_hyphen_values(true))]
322 pub include_namespaces: Vec<InclusionClause>,
323}
324
325#[derive_group(Serializers)]
326#[derive(JsonSchema, Parser, Debug, Clone)]
327pub struct BackendOptions<E: Extension> {
328 #[command(subcommand)]
329 pub backend: Backend<E>,
330
331 #[arg(long = "dry-run")]
334 pub dry_run: bool,
335
336 #[arg(short, long, action = clap::ArgAction::Count)]
338 pub verbose: u8,
339
340 #[arg(long)]
343 pub stats: bool,
344
345 #[arg(long)]
348 pub profile: bool,
349
350 #[arg(short, long = "debug-engine")]
364 pub debug_engine: Option<DebugEngineMode>,
365
366 #[arg(long)]
374 pub extract_type_aliases: bool,
375
376 #[command(flatten)]
377 pub translation_options: TranslationOptions,
378
379 #[arg(long)]
382 pub output_dir: Option<PathBuf>,
383
384 #[group(flatten)]
385 pub cli_extension: E::BackendOptions,
386}
387
388#[derive_group(Serializers)]
389#[derive(JsonSchema, Subcommand, Debug, Clone)]
390pub enum Command<E: Extension> {
391 #[clap(name = "into")]
396 Backend(BackendOptions<E>),
397
398 JSON {
400 #[arg(
402 short,
403 long = "output-file",
404 default_value = "hax_frontend_export.json"
405 )]
406 output_file: PathOrDash,
407 #[arg(
412 value_enum,
413 short,
414 long = "kind",
415 num_args = 0..=3,
416 default_values_t = [ExportBodyKind::Thir]
417 )]
418 kind: Vec<ExportBodyKind>,
419
420 #[arg(long)]
425 use_ids: bool,
426
427 #[arg(short = 'E', long = "include-extra", default_value = "false")]
429 include_extra: bool,
430 },
431
432 #[command(flatten)]
433 CliExtension(E::Command),
434}
435
436impl<E: Extension> Command<E> {
437 pub fn body_kinds(&self) -> Vec<ExportBodyKind> {
438 match self {
439 Command::JSON { kind, .. } => kind.clone(),
440 _ => vec![ExportBodyKind::Thir],
441 }
442 }
443}
444
445#[derive_group(Serializers)]
446#[derive(JsonSchema, ValueEnum, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
447pub enum ExportBodyKind {
448 Thir,
449 MirBuilt,
450}
451
452#[derive_group(Serializers)]
453#[derive(JsonSchema, Parser, Debug, Clone)]
454#[command(
455 author,
456 version = crate::HAX_VERSION,
457 long_version = concat!("\nversion=", env!("HAX_VERSION"), "\n", "commit=", env!("HAX_GIT_COMMIT_HASH")),
458 name = "hax",
459 about,
460 long_about = None
461)]
462pub struct ExtensibleOptions<E: Extension> {
463 #[arg(
470 short = 'i',
471 long = "inline-macro-call",
472 value_name = "PATTERN",
473 value_parser,
474 value_delimiter = ',',
475 default_values = [
476 "hacspec_lib::array::array", "hacspec_lib::array::public_bytes", "hacspec_lib::array::bytes",
477 "hacspec_lib::math_integers::public_nat_mod", "hacspec_lib::math_integers::unsigned_public_integer",
478 ],
479 )]
480 pub inline_macro_calls: Vec<Namespace>,
481
482 #[arg(default_values = Vec::<&str>::new(), short='C', allow_hyphen_values=true, num_args=1.., long="cargo-args", value_terminator=";")]
487 pub cargo_flags: Vec<String>,
488
489 #[command(subcommand)]
490 pub command: Command<E>,
491
492 #[arg(long="disable-cargo-cache", action=clap::builder::ArgAction::SetFalse)]
494 pub force_cargo_build: ForceCargoBuild,
495
496 #[arg(long = "deps")]
501 pub deps: bool,
502
503 #[arg(long)]
508 pub no_custom_target_directory: bool,
509
510 #[arg(long, default_value = "human")]
513 pub message_format: MessageFormat,
514
515 #[group(flatten)]
516 pub extension: E::Options,
517}
518
519pub type Options = ExtensibleOptions<()>;
520
521#[derive_group(Serializers)]
522#[derive(JsonSchema, ValueEnum, Debug, Clone, Copy, Eq, PartialEq)]
523pub enum MessageFormat {
524 Human,
525 Json,
526}
527
528impl<E: Extension> NormalizePaths for Command<E> {
529 fn normalize_paths(&mut self) {
530 use Command::*;
531 match self {
532 JSON { output_file, .. } => output_file.normalize_paths(),
533 _ => (),
534 }
535 }
536}
537
538impl NormalizePaths for Options {
539 fn normalize_paths(&mut self) {
540 self.command.normalize_paths()
541 }
542}
543
544impl From<Options> for hax_frontend_exporter_options::Options {
545 fn from(_opts: Options) -> hax_frontend_exporter_options::Options {
546 hax_frontend_exporter_options::Options {
547 inline_anon_consts: true,
548 bounds_options: hax_frontend_exporter_options::BoundsOptions {
549 resolve_drop: false,
550 prune_sized: true,
551 },
552 }
553 }
554}
555
556pub const ENV_VAR_OPTIONS_FRONTEND: &str = "DRIVER_HAX_FRONTEND_OPTS";